-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflo_utils.py
315 lines (255 loc) · 8.55 KB
/
flo_utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
from __future__ import print_function
import subprocess as sp
import shlex
import sys
import getopt
import os
import glob
import shutil
import re
import numpy as np
import netCDF4 as nc
import collections
from os.path import expanduser
home = expanduser("~")
debug = False
def cerr(*objs):
print( *objs, file=sys.stderr)
def debug_cerr(*objs):
if debug:
print( *objs, file=sys.stderr)
def check_dict(keys, dictionary):
found_all = True
missing = []
dc = dictionary.keys()
for key in keys:
if(not key in dc):
found_all = False
missing.append(key)
return (found_all, missing)
def year_to_num(year, cal):
if cal:
return nc.date2num(datetime (int(year),6,30), units="days since 0001-01-01 00:00:00", calendar=cal)
else:
return year
def gen_names(start, end):
nums=[int(start)] + range(int(start)+ 50 - (int(start)%50),int(end)+2,50)
names= ["%s-%s"%(nums[x],nums[x+1]-1) for x in range (len(nums)-1)]
debug_cerr(names)
return names
def save_cpt(p, name):
of = open(home+"/.NCL/colormaps/%s.rgb"%name, 'w')
of.write( "n_colors=%d\n"%len(p))
of.write( "# r g b \n")
of.write("\n".join([ " ".join([str (y) for y in x ]) for x in p ]))
of.close()
def get_tornado_dir(floname):
return my_tornado_run_dir + "/%s"%(floname)
def get_mpism_dir (floname):
return work+"/mpism/" +floname
def set_debug(state):
global debug
debug = state
def get_my_bin():
return my_bin
def query (question, stdin_string=False, env={}):
if type(question) is str:
question=shlex.split(question)
debug_cerr("FU: trying " + " ".join(question))
debug_cerr("FU: env is ")
debug_cerr(env)
if env:
a = sp.Popen(question, stdin = sp.PIPE, stdout = sp.PIPE, stderr = sp.PIPE, env=env)
else:
a = sp.Popen(question, stdin = sp.PIPE, stdout = sp.PIPE, stderr = sp.PIPE)
if stdin_string:
(so, se) = a.communicate(stdin_string)
else:
(so, se) = a.communicate()
if debug:
cerr( "returned " + str( a.returncode) )
if a.returncode:
cerr( "FU: attempting " + str(question) + " in " + os.getcwd())
cerr( "FU: returned " + str( a.returncode) )
cerr( "FU: program stdout:")
for o in so.decode('UTF-8').split("\n"):
cerr( o)
cerr( "FU: program stderr:")
for e in se.decode('UTF-8').split("\n"):
cerr( e)
exit (a.returncode)
return (so,se)
def qo(question, stdin_string=False, env={}):
a = query(question, stdin_string, env)[0]
return a
def check_call_ncl(arguments):
if (debug):
cerr( "trying ncl " " ".join(arguments))
return sp.check_call(["/sw/lenny-x64/ncl-5.2.1-gccsys/bin/ncl"] + arguments, env= {"NCARG_ROOT" : "/sw/lenny-x64/ncl-5.2.1-gccsys", "PATH" : os.environ["PATH"]})
def rm_if_exist(files):
if type (files) is str:
files = [files]
for filename in files:
debug_cerr( "FU: removing %s if exists"%(filename))
if ( os.access(filename,os.R_OK) ) :
debug_cerr( "FU: %s exists. Removing it"%(filename))
os.remove(filename)
def guess_name_from_dir():
currdir=os.getcwd()
if currdir[-8:-4] == '/flo':
try:
num=int(currdir[-4:])
except:
cerr( "FU: Could not guess run from directory name %s"%(currdir))
exit(2)
flo_name = currdir[-7:]
debug_cerr( "using flo_name %s"%flo_name)
if currdir[-4:-2] == '/F':
try:
num=int(currdir[-2:])
except:
cerr( "FU: Could not guess run from directory name %s"%(currdir))
exit(2)
flo_name = "flo00" + currdir[-2:]
debug_cerr( "FU: using flo_name %s"%flo_name)
return flo_name
def goto_dir(directory):
if os.path.isdir(directory):
debug_cerr( "FU: directory %s exists. Entering it."%(directory))
else:
sys.exit("FU: no data found\n" + directory + "\ndoes not exist")
os.chdir(directory)
def check_files(filenames, fatal = True):
ok = True
if type(filenames) is str:
filenames=filenames.split("\n")
for filename in filenames:
ok = ok and os.access(filename,os.R_OK)
if not os.access(filename,os.R_OK):
if fatal:
sys.exit("FU: file '" + os.path.abspath(filename) + "' does not exist! Exiting!")
else:
cerr("FU: checked file '" + os.path.abspath(filename) + "' -- It does not exist. Continuing anyway since not considered fatal.")
return ok
def get_script_dir (floname):
return my_script_dir + "/%s/scripts" % (floname)
def get_dir(floname):
oke = "/work/mh0020/m300019/cosmos_work/experiments/"
ke = work + "/cosmos_work/experiments/"
se = scratch + "/cosmos_work/experiments/"
for x in [ke, oke, se]:
if os.path.isdir(x+floname):
debug_cerr( "FU: directory %s exists. using it"%(x+floname))
return x+floname
sys.exit("FU: no directory found for " + floname + "! Exiting!")
def get_tmp_name(floname, param):
return scratch + "/tmp/" + floname + "/" + param
def get_meanplot_dir(floname):
return work + "/means/" + floname
def mkdir(target):
if not os.path.isdir(target):
debug_cerr( "FU: creating directory " + target)
os.makedirs(target)
return target
def mktmp(floname, param):
target = get_tmp_name (floname, param)
return mkdir(target)
def make_p2e_dir(floname):
target = get_dir(floname) + "/pism2echam"
return mkdir(target)
def copy_files(files,target):
debug_cerr( "copying \n%s\nto %s"%("\n".join(files), target))
for x in files:
shutil.copy2(x,target)
def get_uwe_name(flo_name):
return flo_name[0].upper()+flo_name[-2:]
cache_dirs=[]
def pushd(directory = False):
global cache_dirs
if (not directory):
directory = os.getcwd()
debug_cerr( "FU: pushing directory %s"%directory)
cache_dirs.append (directory)
def popd():
global cache_dirs
directory = (cache_dirs[-1])
cache_dirs = cache_dirs[:-1]
debug_cerr( "FU: popping directory %s"%directory)
return directory
def parse_years (arg):
years=[]
single_year = re.compile('-?[0-9]*')
year_range = re.compile('(-?[0-9]*):(-?[0-9]*)')
year_stride = re.compile('(-?[0-9]*):(-?[0-9]*):(-?[0-9]*)')
sy = single_year.match(arg)
my = year_range.match (arg)
mys = year_stride.match (arg)
if sy and sy.group() == arg :
years.append(arg)
elif my and my.group() == arg:
(start,stop) = my.groups()
start=int(start)
stop=int(stop)
if start <= stop:
years = years + [str(x) for x in xrange (start,stop)]
else:
cerr( "trouble parsing year argument " + arg)
cerr( "start year must be <= end year for ranges")
exit(2)
elif mys and mys.group() == arg:
(start,stop,stride) = mys.groups()
start=int(start)
stop=int(stop)
stride=int(stride)
if (stop - start) * stride > 0 :
years = years + [str(x) for x in xrange (start,stop,stride)]
else:
cerr( "trouble parsing year argument " + arg)
cerr( "start year must be <= end year for ranges with positive stride and the other way around for neg strides")
exit(2)
else:
cerr( "can't parse year argument " + arg)
usage()
sys.exit(2)
return years
def spread_out(a, width=5):
b=np.zeros(a.shape)
for x in np.arange (width):
if x:
b[x:] =b[x:] +a[:-x]
b[:-x]=b[:-x]+a[x:]
else :
b = b + a
for y in np.arange(width-x):
if y and x :
b[x: , y: ] = b[x: , y: ] + a[ :-x, :-y]
b[x: , :-y] = b[x: , :-y] + a[ :-x, y: ]
b[ :-x, :-y] = b[ :-x, :-y] + a[x: , y: ]
b[ :-x, y: ] = b[ :-x, y: ] + a[x: , :-y]
else :
if y:
b[:,y:] =b[:,y:] +a[:,:-y]
b[:,:-y]=b[:,:-y]+a[:,y:]
return b
def get_data(filename, variable):
infile=nc.Dataset(filename, "r")
data=infile.variables[variable][:]
dimensions=collections.OrderedDict([ [x,infile.variables[x][:]] for x in infile.variables[variable].dimensions])
infile.close()
return (data, dimensions)
def corr(fields_file, fields_var, ts_file, ts_var, opts={}):
if "cdo_opts" in opts.keys():
cdo_opts = opts["cdo_opts"]
else:
cdo_opts = ""
qo("cdo -f ext -b 64 copy %s -selvar,%s %s fort.50"%(cdo_opts, fields_var, fields_file))
qo("cdo -f ext -b 64 copy %s -selvar,%s %s fort.51"%(cdo_opts, ts_var, ts_file))
if ("max_lag" in opts.keys()) and ( "increment" in opts.keys() ):
qo("%s/lagreg_uwe"%(my_bin), "%s %s"%(opts["max_lag"], opts["increment"]))
else:
qo("%s/lagreg_-200_1_200"%(my_bin))
rm_if_exist("results.nc")
command = "cdo -f nc -merge -setgrid,%s -setname,regression fort.60 -setname,correlation -setgrid,%s fort.61 results.nc"%(fields_file, fields_file)
qo(command)
label= "%s from %s as function of %s from_%s, options = %s"%(fields_var, fields_file,ts_var,ts_file, str(opts))
qo(["ncatted", "-a" , "generated_by,global,o,c,"+label , "results.nc"])