1 | ## Author: AS |
---|
2 | def errormess(text,printvar=None): |
---|
3 | print text |
---|
4 | if printvar is not None: print printvar |
---|
5 | exit() |
---|
6 | return |
---|
7 | |
---|
8 | ## Author: AS |
---|
9 | def adjust_length (tab, zelen): |
---|
10 | from numpy import ones |
---|
11 | if tab is None: |
---|
12 | outtab = ones(zelen) * -999999 |
---|
13 | else: |
---|
14 | if zelen != len(tab): |
---|
15 | print "not enough or too much values... setting same values all variables" |
---|
16 | outtab = ones(zelen) * tab[0] |
---|
17 | else: |
---|
18 | outtab = tab |
---|
19 | return outtab |
---|
20 | |
---|
21 | ## Author: AS |
---|
22 | def getname(var=False,winds=False,anomaly=False): |
---|
23 | if var and winds: basename = var + '_UV' |
---|
24 | elif var: basename = var |
---|
25 | elif winds: basename = 'UV' |
---|
26 | else: errormess("please set at least winds or var",printvar=nc.variables) |
---|
27 | if anomaly: basename = 'd' + basename |
---|
28 | return basename |
---|
29 | |
---|
30 | ## Author: AS |
---|
31 | def localtime(utc,lon): |
---|
32 | ltst = utc + lon / 15. |
---|
33 | ltst = int (ltst * 10) / 10. |
---|
34 | ltst = ltst % 24 |
---|
35 | return ltst |
---|
36 | |
---|
37 | ## Author: AS |
---|
38 | def whatkindfile (nc): |
---|
39 | if 'controle' in nc.variables: typefile = 'gcm' |
---|
40 | elif 'phisinit' in nc.variables: typefile = 'gcm' |
---|
41 | elif 'vert' in nc.variables: typefile = 'mesoapi' |
---|
42 | elif 'U' in nc.variables: typefile = 'meso' |
---|
43 | elif 'HGT_M' in nc.variables: typefile = 'geo' |
---|
44 | #else: errormess("whatkindfile: typefile not supported.") |
---|
45 | else: typefile = 'gcm' # for lslin-ed files from gcm |
---|
46 | return typefile |
---|
47 | |
---|
48 | ## Author: AS |
---|
49 | def getfield (nc,var): |
---|
50 | ## this allows to get much faster (than simply referring to nc.variables[var]) |
---|
51 | import numpy as np |
---|
52 | dimension = len(nc.variables[var].dimensions) |
---|
53 | #print " Opening variable with", dimension, "dimensions ..." |
---|
54 | if dimension == 2: field = nc.variables[var][:,:] |
---|
55 | elif dimension == 3: field = nc.variables[var][:,:,:] |
---|
56 | elif dimension == 4: field = nc.variables[var][:,:,:,:] |
---|
57 | # if there are NaNs in the ncdf, they should be loaded as a masked array which will be |
---|
58 | # recasted as a regular array later in reducefield |
---|
59 | if (np.isnan(np.sum(field)) and (type(field).__name__ not in 'MaskedArray')): |
---|
60 | print "Warning: netcdf as nan values but is not loaded as a Masked Array." |
---|
61 | print "recasting array type" |
---|
62 | out=np.ma.masked_invalid(field) |
---|
63 | out.set_fill_value([np.NaN]) |
---|
64 | else: |
---|
65 | out=field |
---|
66 | return out |
---|
67 | |
---|
68 | ## Author: AS + TN + AC |
---|
69 | def reducefield (input,d4=None,d3=None,d2=None,d1=None,yint=False,alt=None): |
---|
70 | ### we do it the reverse way to be compliant with netcdf "t z y x" or "t y x" or "y x" |
---|
71 | ### it would be actually better to name d4 d3 d2 d1 as t z y x |
---|
72 | import numpy as np |
---|
73 | from mymath import max,mean |
---|
74 | dimension = np.array(input).ndim |
---|
75 | shape = np.array(input).shape |
---|
76 | #print 'd1,d2,d3,d4: ',d1,d2,d3,d4 |
---|
77 | print 'IN REDUCEFIELD dim,shape: ',dimension,shape |
---|
78 | output = input |
---|
79 | error = False |
---|
80 | #### this is needed to cope the case where d4,d3,d2,d1 are single integers and not arrays |
---|
81 | if d4 is not None and not isinstance(d4, np.ndarray): d4=[d4] |
---|
82 | if d3 is not None and not isinstance(d3, np.ndarray): d3=[d3] |
---|
83 | if d2 is not None and not isinstance(d2, np.ndarray): d2=[d2] |
---|
84 | if d1 is not None and not isinstance(d1, np.ndarray): d1=[d1] |
---|
85 | ### now the main part |
---|
86 | if dimension == 2: |
---|
87 | if d2 >= shape[0]: error = True |
---|
88 | elif d1 >= shape[1]: error = True |
---|
89 | elif d1 is not None and d2 is not None: output = mean(input[d2,:],axis=0); output = mean(output[d1],axis=0) |
---|
90 | elif d1 is not None: output = mean(input[:,d1],axis=1) |
---|
91 | elif d2 is not None: output = mean(input[d2,:],axis=0) |
---|
92 | elif dimension == 3: |
---|
93 | if max(d4) >= shape[0]: error = True |
---|
94 | elif max(d2) >= shape[1]: error = True |
---|
95 | elif max(d1) >= shape[2]: error = True |
---|
96 | elif d4 is not None and d2 is not None and d1 is not None: |
---|
97 | output = mean(input[d4,:,:],axis=0); output = mean(output[d2,:],axis=0); output = mean(output[d1],axis=0) |
---|
98 | elif d4 is not None and d2 is not None: output = mean(input[d4,:,:],axis=0); output=mean(output[d2,:],axis=0) |
---|
99 | elif d4 is not None and d1 is not None: output = mean(input[d4,:,:],axis=0); output=mean(output[:,d1],axis=1) |
---|
100 | elif d2 is not None and d1 is not None: output = mean(input[:,d2,:],axis=1); output=mean(output[:,d1],axis=1) |
---|
101 | elif d1 is not None: output = mean(input[:,:,d1],axis=2) |
---|
102 | elif d2 is not None: output = mean(input[:,d2,:],axis=1) |
---|
103 | elif d4 is not None: output = mean(input[d4,:,:],axis=0) |
---|
104 | elif dimension == 4: |
---|
105 | if max(d4) >= shape[0]: error = True |
---|
106 | elif max(d3) >= shape[1]: error = True |
---|
107 | elif max(d2) >= shape[2]: error = True |
---|
108 | elif max(d1) >= shape[3]: error = True |
---|
109 | elif d4 is not None and d3 is not None and d2 is not None and d1 is not None: |
---|
110 | output = mean(input[d4,:,:,:],axis=0) |
---|
111 | output = reduce_zaxis(output[d3,:,:],ax=0,yint=yint,vert=alt,indice=d3) |
---|
112 | output = mean(output[d2,:],axis=0) |
---|
113 | output = mean(output[d1],axis=0) |
---|
114 | elif d4 is not None and d3 is not None and d2 is not None: |
---|
115 | output = mean(input[d4,:,:,:],axis=0) |
---|
116 | output = reduce_zaxis(output[d3,:,:],ax=0,yint=yint,vert=alt,indice=d3) |
---|
117 | output = mean(output[d2,:],axis=0) |
---|
118 | elif d4 is not None and d3 is not None and d1 is not None: |
---|
119 | output = mean(input[d4,:,:,:],axis=0) |
---|
120 | output = reduce_zaxis(output[d3,:,:],ax=0,yint=yint,vert=alt,indice=d3) |
---|
121 | output = mean(output[:,d1],axis=1) |
---|
122 | elif d4 is not None and d2 is not None and d1 is not None: |
---|
123 | output = mean(input[d4,:,:,:],axis=0) |
---|
124 | output = mean(output[:,d2,:],axis=1) |
---|
125 | output = mean(output[:,d1],axis=1) |
---|
126 | elif d3 is not None and d2 is not None and d1 is not None: |
---|
127 | output = reduce_zaxis(input[:,d3,:,:],ax=1,yint=yint,vert=alt,indice=d3) |
---|
128 | output = mean(output[:,d2,:],axis=1) |
---|
129 | output = mean(output[:,d1],axis=1) |
---|
130 | elif d4 is not None and d3 is not None: |
---|
131 | output = mean(input[d4,:,:,:],axis=0) |
---|
132 | output = reduce_zaxis(output[d3,:,:],ax=0,yint=yint,vert=alt,indice=d3) |
---|
133 | elif d4 is not None and d2 is not None: |
---|
134 | output = mean(input[d4,:,:,:],axis=0) |
---|
135 | output = mean(output[:,d2,:],axis=1) |
---|
136 | elif d4 is not None and d1 is not None: |
---|
137 | output = mean(input[d4,:,:,:],axis=0) |
---|
138 | output = mean(output[:,:,d1],axis=2) |
---|
139 | elif d3 is not None and d2 is not None: |
---|
140 | output = reduce_zaxis(input[:,d3,:,:],ax=1,yint=yint,vert=alt,indice=d3) |
---|
141 | output = mean(output[:,d2,:],axis=1) |
---|
142 | elif d3 is not None and d1 is not None: |
---|
143 | output = reduce_zaxis(input[:,d3,:,:],ax=1,yint=yint,vert=alt,indice=d3) |
---|
144 | output = mean(output[:,:,d1],axis=0) |
---|
145 | elif d2 is not None and d1 is not None: |
---|
146 | output = mean(input[:,:,d2,:],axis=2) |
---|
147 | output = mean(output[:,:,d1],axis=2) |
---|
148 | elif d1 is not None: output = mean(input[:,:,:,d1],axis=3) |
---|
149 | elif d2 is not None: output = mean(input[:,:,d2,:],axis=2) |
---|
150 | elif d3 is not None: output = reduce_zaxis(input[:,d3,:,:],ax=0,yint=yint,vert=alt,indice=d3) |
---|
151 | elif d4 is not None: output = mean(input[d4,:,:,:],axis=0) |
---|
152 | dimension = np.array(output).ndim |
---|
153 | shape = np.array(output).shape |
---|
154 | print 'OUT REDUCEFIELD dim,shape: ',dimension,shape |
---|
155 | return output, error |
---|
156 | |
---|
157 | ## Author: AC + AS |
---|
158 | def reduce_zaxis (input,ax=None,yint=False,vert=None,indice=None): |
---|
159 | from mymath import max,mean |
---|
160 | from scipy import integrate |
---|
161 | if yint and vert is not None and indice is not None: |
---|
162 | if type(input).__name__=='MaskedArray': |
---|
163 | input.set_fill_value([np.NaN]) |
---|
164 | output = integrate.trapz(input.filled(),x=vert[indice],axis=ax) |
---|
165 | else: |
---|
166 | output = integrate.trapz(input,x=vert[indice],axis=ax) |
---|
167 | else: |
---|
168 | output = mean(input,axis=ax) |
---|
169 | return output |
---|
170 | |
---|
171 | ## Author: AS + TN |
---|
172 | def definesubplot ( numplot, fig ): |
---|
173 | from matplotlib.pyplot import rcParams |
---|
174 | rcParams['font.size'] = 12. ## default (important for multiple calls) |
---|
175 | if numplot <= 0: |
---|
176 | subv = 99999 |
---|
177 | subh = 99999 |
---|
178 | elif numplot == 1: |
---|
179 | subv = 99999 |
---|
180 | subh = 99999 |
---|
181 | elif numplot == 2: |
---|
182 | subv = 1 |
---|
183 | subh = 2 |
---|
184 | fig.subplots_adjust(wspace = 0.35) |
---|
185 | rcParams['font.size'] = int( rcParams['font.size'] * 3. / 4. ) |
---|
186 | elif numplot == 3: |
---|
187 | subv = 2 |
---|
188 | subh = 2 |
---|
189 | fig.subplots_adjust(wspace = 0.5) |
---|
190 | rcParams['font.size'] = int( rcParams['font.size'] * 1. / 2. ) |
---|
191 | elif numplot == 4: |
---|
192 | subv = 2 |
---|
193 | subh = 2 |
---|
194 | fig.subplots_adjust(wspace = 0.3, hspace = 0.3) |
---|
195 | rcParams['font.size'] = int( rcParams['font.size'] * 2. / 3. ) |
---|
196 | elif numplot <= 6: |
---|
197 | subv = 2 |
---|
198 | subh = 3 |
---|
199 | fig.subplots_adjust(wspace = 0.4, hspace = 0.0) |
---|
200 | rcParams['font.size'] = int( rcParams['font.size'] * 1. / 2. ) |
---|
201 | elif numplot <= 8: |
---|
202 | subv = 2 |
---|
203 | subh = 4 |
---|
204 | fig.subplots_adjust(wspace = 0.3, hspace = 0.3) |
---|
205 | rcParams['font.size'] = int( rcParams['font.size'] * 1. / 2. ) |
---|
206 | elif numplot <= 9: |
---|
207 | subv = 3 |
---|
208 | subh = 3 |
---|
209 | fig.subplots_adjust(wspace = 0.3, hspace = 0.3) |
---|
210 | rcParams['font.size'] = int( rcParams['font.size'] * 1. / 2. ) |
---|
211 | elif numplot <= 12: |
---|
212 | subv = 3 |
---|
213 | subh = 4 |
---|
214 | fig.subplots_adjust(wspace = 0.1, hspace = 0.1) |
---|
215 | rcParams['font.size'] = int( rcParams['font.size'] * 1. / 2. ) |
---|
216 | elif numplot <= 16: |
---|
217 | subv = 4 |
---|
218 | subh = 4 |
---|
219 | fig.subplots_adjust(wspace = 0.3, hspace = 0.3) |
---|
220 | rcParams['font.size'] = int( rcParams['font.size'] * 1. / 2. ) |
---|
221 | else: |
---|
222 | print "number of plot supported: 1 to 16" |
---|
223 | exit() |
---|
224 | return subv,subh |
---|
225 | |
---|
226 | ## Author: AS |
---|
227 | def getstralt(nc,nvert): |
---|
228 | typefile = whatkindfile(nc) |
---|
229 | if typefile is 'meso': |
---|
230 | stralt = "_lvl" + str(nvert) |
---|
231 | elif typefile is 'mesoapi': |
---|
232 | zelevel = int(nc.variables['vert'][nvert]) |
---|
233 | if abs(zelevel) < 10000.: strheight=str(zelevel)+"m" |
---|
234 | else: strheight=str(int(zelevel/1000.))+"km" |
---|
235 | if 'altitude' in nc.dimensions: stralt = "_"+strheight+"-AMR" |
---|
236 | elif 'altitude_abg' in nc.dimensions: stralt = "_"+strheight+"-ALS" |
---|
237 | elif 'bottom_top' in nc.dimensions: stralt = "_"+strheight |
---|
238 | elif 'pressure' in nc.dimensions: stralt = "_"+str(zelevel)+"Pa" |
---|
239 | else: stralt = "" |
---|
240 | else: |
---|
241 | stralt = "" |
---|
242 | return stralt |
---|
243 | |
---|
244 | ## Author: AS |
---|
245 | def getlschar ( namefile ): |
---|
246 | from netCDF4 import Dataset |
---|
247 | from timestuff import sol2ls |
---|
248 | from numpy import array |
---|
249 | nc = Dataset(namefile) |
---|
250 | zetime = None |
---|
251 | if 'Times' in nc.variables: |
---|
252 | zetime = nc.variables['Times'][0] |
---|
253 | shape = array(nc.variables['Times']).shape |
---|
254 | if shape[0] < 2: zetime = None |
---|
255 | if zetime is not None \ |
---|
256 | and 'vert' not in nc.variables: |
---|
257 | #### strangely enough this does not work for api or ncrcat results! |
---|
258 | zetimestart = getattr(nc, 'START_DATE') |
---|
259 | zeday = int(zetime[8]+zetime[9]) - int(zetimestart[8]+zetimestart[9]) |
---|
260 | if zeday < 0: lschar="" ## might have crossed a month... fix soon |
---|
261 | else: lschar="_Ls"+str( int( 10. * sol2ls ( getattr( nc, 'JULDAY' ) + zeday ) ) / 10. ) |
---|
262 | ### |
---|
263 | zetime2 = nc.variables['Times'][1] |
---|
264 | one = int(zetime[11]+zetime[12]) + int(zetime[14]+zetime[15])/37. |
---|
265 | next = int(zetime2[11]+zetime2[12]) + int(zetime2[14]+zetime2[15])/37. |
---|
266 | zehour = one |
---|
267 | zehourin = abs ( next - one ) |
---|
268 | else: |
---|
269 | lschar="" |
---|
270 | zehour = 0 |
---|
271 | zehourin = 1 |
---|
272 | return lschar, zehour, zehourin |
---|
273 | |
---|
274 | ## Author: AS |
---|
275 | def getprefix (nc): |
---|
276 | prefix = 'LMD_MMM_' |
---|
277 | prefix = prefix + 'd'+str(getattr(nc,'GRID_ID'))+'_' |
---|
278 | prefix = prefix + str(int(getattr(nc,'DX')/1000.))+'km_' |
---|
279 | return prefix |
---|
280 | |
---|
281 | ## Author: AS |
---|
282 | def getproj (nc): |
---|
283 | typefile = whatkindfile(nc) |
---|
284 | if typefile in ['mesoapi','meso','geo']: |
---|
285 | ### (il faudrait passer CEN_LON dans la projection ?) |
---|
286 | map_proj = getattr(nc, 'MAP_PROJ') |
---|
287 | cen_lat = getattr(nc, 'CEN_LAT') |
---|
288 | if map_proj == 2: |
---|
289 | if cen_lat > 10.: |
---|
290 | proj="npstere" |
---|
291 | #print "NP stereographic polar domain" |
---|
292 | else: |
---|
293 | proj="spstere" |
---|
294 | #print "SP stereographic polar domain" |
---|
295 | elif map_proj == 1: |
---|
296 | #print "lambert projection domain" |
---|
297 | proj="lcc" |
---|
298 | elif map_proj == 3: |
---|
299 | #print "mercator projection" |
---|
300 | proj="merc" |
---|
301 | else: |
---|
302 | proj="merc" |
---|
303 | elif typefile in ['gcm']: proj="cyl" ## pb avec les autres (de trace derriere la sphere ?) |
---|
304 | else: proj="ortho" |
---|
305 | return proj |
---|
306 | |
---|
307 | ## Author: AS |
---|
308 | def ptitle (name): |
---|
309 | from matplotlib.pyplot import title |
---|
310 | title(name) |
---|
311 | print name |
---|
312 | |
---|
313 | ## Author: AS |
---|
314 | def polarinterv (lon2d,lat2d): |
---|
315 | import numpy as np |
---|
316 | wlon = [np.min(lon2d),np.max(lon2d)] |
---|
317 | ind = np.array(lat2d).shape[0] / 2 ## to get a good boundlat and to get the pole |
---|
318 | wlat = [np.min(lat2d[ind,:]),np.max(lat2d[ind,:])] |
---|
319 | return [wlon,wlat] |
---|
320 | |
---|
321 | ## Author: AS |
---|
322 | def simplinterv (lon2d,lat2d): |
---|
323 | import numpy as np |
---|
324 | return [[np.min(lon2d),np.max(lon2d)],[np.min(lat2d),np.max(lat2d)]] |
---|
325 | |
---|
326 | ## Author: AS |
---|
327 | def wrfinterv (lon2d,lat2d): |
---|
328 | nx = len(lon2d[0,:])-1 |
---|
329 | ny = len(lon2d[:,0])-1 |
---|
330 | lon1 = lon2d[0,0] |
---|
331 | lon2 = lon2d[nx,ny] |
---|
332 | lat1 = lat2d[0,0] |
---|
333 | lat2 = lat2d[nx,ny] |
---|
334 | if abs(0.5*(lat1+lat2)) > 60.: wider = 0.5 * (abs(lon1)+abs(lon2)) * 0.1 |
---|
335 | else: wider = 0. |
---|
336 | if lon1 < lon2: wlon = [lon1, lon2 + wider] |
---|
337 | else: wlon = [lon2, lon1 + wider] |
---|
338 | if lat1 < lat2: wlat = [lat1, lat2] |
---|
339 | else: wlat = [lat2, lat1] |
---|
340 | return [wlon,wlat] |
---|
341 | |
---|
342 | ## Author: AS |
---|
343 | def makeplotres (filename,res=None,pad_inches_value=0.25,folder='',disp=True,ext='png',erase=False): |
---|
344 | import matplotlib.pyplot as plt |
---|
345 | from os import system |
---|
346 | addstr = "" |
---|
347 | if res is not None: |
---|
348 | res = int(res) |
---|
349 | addstr = "_"+str(res) |
---|
350 | name = filename+addstr+"."+ext |
---|
351 | if folder != '': name = folder+'/'+name |
---|
352 | plt.savefig(name,dpi=res,bbox_inches='tight',pad_inches=pad_inches_value) |
---|
353 | if disp: display(name) |
---|
354 | if ext in ['eps','ps','svg']: system("tar czvf "+name+".tar.gz "+name+" ; rm -f "+name) |
---|
355 | if erase: system("mv "+name+" to_be_erased") |
---|
356 | return |
---|
357 | |
---|
358 | ## Author: AS |
---|
359 | def dumpbdy (field,n,stag=None): |
---|
360 | nx = len(field[0,:])-1 |
---|
361 | ny = len(field[:,0])-1 |
---|
362 | if stag == 'U': nx = nx-1 |
---|
363 | if stag == 'V': ny = ny-1 |
---|
364 | return field[n:ny-n,n:nx-n] |
---|
365 | |
---|
366 | ## Author: AS |
---|
367 | def getcoorddef ( nc ): |
---|
368 | import numpy as np |
---|
369 | ## getcoord2d for predefined types |
---|
370 | typefile = whatkindfile(nc) |
---|
371 | if typefile in ['mesoapi','meso']: |
---|
372 | [lon2d,lat2d] = getcoord2d(nc) |
---|
373 | lon2d = dumpbdy(lon2d,6) |
---|
374 | lat2d = dumpbdy(lat2d,6) |
---|
375 | elif typefile in ['gcm']: |
---|
376 | [lon2d,lat2d] = getcoord2d(nc,nlat="latitude",nlon="longitude",is1d=True) |
---|
377 | elif typefile in ['geo']: |
---|
378 | [lon2d,lat2d] = getcoord2d(nc,nlat='XLAT_M',nlon='XLONG_M') |
---|
379 | return lon2d,lat2d |
---|
380 | |
---|
381 | ## Author: AS |
---|
382 | def getcoord2d (nc,nlat='XLAT',nlon='XLONG',is1d=False): |
---|
383 | import numpy as np |
---|
384 | if is1d: |
---|
385 | lat = nc.variables[nlat][:] |
---|
386 | lon = nc.variables[nlon][:] |
---|
387 | [lon2d,lat2d] = np.meshgrid(lon,lat) |
---|
388 | else: |
---|
389 | lat = nc.variables[nlat][0,:,:] |
---|
390 | lon = nc.variables[nlon][0,:,:] |
---|
391 | [lon2d,lat2d] = [lon,lat] |
---|
392 | return lon2d,lat2d |
---|
393 | |
---|
394 | ## Author: AS |
---|
395 | def smooth (field, coeff): |
---|
396 | ## actually blur_image could work with different coeff on x and y |
---|
397 | if coeff > 1: result = blur_image(field,int(coeff)) |
---|
398 | else: result = field |
---|
399 | return result |
---|
400 | |
---|
401 | ## FROM COOKBOOK http://www.scipy.org/Cookbook/SignalSmooth |
---|
402 | def gauss_kern(size, sizey=None): |
---|
403 | import numpy as np |
---|
404 | # Returns a normalized 2D gauss kernel array for convolutions |
---|
405 | size = int(size) |
---|
406 | if not sizey: |
---|
407 | sizey = size |
---|
408 | else: |
---|
409 | sizey = int(sizey) |
---|
410 | x, y = np.mgrid[-size:size+1, -sizey:sizey+1] |
---|
411 | g = np.exp(-(x**2/float(size)+y**2/float(sizey))) |
---|
412 | return g / g.sum() |
---|
413 | |
---|
414 | ## FROM COOKBOOK http://www.scipy.org/Cookbook/SignalSmooth |
---|
415 | def blur_image(im, n, ny=None) : |
---|
416 | from scipy.signal import convolve |
---|
417 | # blurs the image by convolving with a gaussian kernel of typical size n. |
---|
418 | # The optional keyword argument ny allows for a different size in the y direction. |
---|
419 | g = gauss_kern(n, sizey=ny) |
---|
420 | improc = convolve(im, g, mode='same') |
---|
421 | return improc |
---|
422 | |
---|
423 | ## Author: AS |
---|
424 | def getwinddef (nc): |
---|
425 | ## getwinds for predefined types |
---|
426 | typefile = whatkindfile(nc) |
---|
427 | ### |
---|
428 | if typefile is 'mesoapi': [uchar,vchar] = ['Um','Vm'] |
---|
429 | elif typefile is 'gcm': [uchar,vchar] = ['u','v'] |
---|
430 | elif typefile is 'meso': [uchar,vchar] = ['U','V'] |
---|
431 | else: [uchar,vchar] = ['not found','not found'] |
---|
432 | ### |
---|
433 | if typefile in ['meso']: metwind = False ## geometrical (wrt grid) |
---|
434 | else: metwind = True ## meteorological (zon/mer) |
---|
435 | if metwind is False: print "Not using meteorological winds. You trust numerical grid as being (x,y)" |
---|
436 | ### |
---|
437 | return uchar,vchar,metwind |
---|
438 | |
---|
439 | ## Author: AS |
---|
440 | def vectorfield (u, v, x, y, stride=3, scale=15., factor=250., color='black', csmooth=1, key=True): |
---|
441 | ## scale regle la reference du vecteur |
---|
442 | ## factor regle toutes les longueurs (dont la reference). l'AUGMENTER pour raccourcir les vecteurs. |
---|
443 | import matplotlib.pyplot as plt |
---|
444 | import numpy as np |
---|
445 | posx = np.min(x) - np.std(x) / 10. |
---|
446 | posy = np.min(y) - np.std(y) / 10. |
---|
447 | u = smooth(u,csmooth) |
---|
448 | v = smooth(v,csmooth) |
---|
449 | widthvec = 0.003 #0.005 #0.003 |
---|
450 | q = plt.quiver( x[::stride,::stride],\ |
---|
451 | y[::stride,::stride],\ |
---|
452 | u[::stride,::stride],\ |
---|
453 | v[::stride,::stride],\ |
---|
454 | angles='xy',color=color,pivot='middle',\ |
---|
455 | scale=factor,width=widthvec ) |
---|
456 | if color in ['white','yellow']: kcolor='black' |
---|
457 | else: kcolor=color |
---|
458 | if key: p = plt.quiverkey(q,posx,posy,scale,\ |
---|
459 | str(int(scale)),coordinates='data',color=kcolor,labelpos='S',labelsep = 0.03) |
---|
460 | return |
---|
461 | |
---|
462 | ## Author: AS |
---|
463 | def display (name): |
---|
464 | from os import system |
---|
465 | system("display "+name+" > /dev/null 2> /dev/null &") |
---|
466 | return name |
---|
467 | |
---|
468 | ## Author: AS |
---|
469 | def findstep (wlon): |
---|
470 | steplon = int((wlon[1]-wlon[0])/4.) #3 |
---|
471 | step = 120. |
---|
472 | while step > steplon and step > 15. : step = step / 2. |
---|
473 | if step <= 15.: |
---|
474 | while step > steplon and step > 5. : step = step - 5. |
---|
475 | if step <= 5.: |
---|
476 | while step > steplon and step > 1. : step = step - 1. |
---|
477 | if step <= 1.: |
---|
478 | step = 1. |
---|
479 | return step |
---|
480 | |
---|
481 | ## Author: AS |
---|
482 | def define_proj (char,wlon,wlat,back=None,blat=None): |
---|
483 | from mpl_toolkits.basemap import Basemap |
---|
484 | import numpy as np |
---|
485 | import matplotlib as mpl |
---|
486 | from mymath import max |
---|
487 | meanlon = 0.5*(wlon[0]+wlon[1]) |
---|
488 | meanlat = 0.5*(wlat[0]+wlat[1]) |
---|
489 | if blat is None: |
---|
490 | ortholat=meanlat |
---|
491 | if wlat[0] >= 80.: blat = 40. |
---|
492 | elif wlat[1] <= -80.: blat = -40. |
---|
493 | elif wlat[1] >= 0.: blat = wlat[0] |
---|
494 | elif wlat[0] <= 0.: blat = wlat[1] |
---|
495 | else: ortholat=blat |
---|
496 | #print "blat ", blat |
---|
497 | h = 50. ## en km |
---|
498 | radius = 3397200. |
---|
499 | if char == "cyl": m = Basemap(rsphere=radius,projection='cyl',\ |
---|
500 | llcrnrlat=wlat[0],urcrnrlat=wlat[1],llcrnrlon=wlon[0],urcrnrlon=wlon[1]) |
---|
501 | elif char == "moll": m = Basemap(rsphere=radius,projection='moll',lon_0=meanlon) |
---|
502 | elif char == "ortho": m = Basemap(rsphere=radius,projection='ortho',lon_0=meanlon,lat_0=ortholat) |
---|
503 | elif char == "lcc": m = Basemap(rsphere=radius,projection='lcc',lat_1=meanlat,lat_0=meanlat,lon_0=meanlon,\ |
---|
504 | llcrnrlat=wlat[0],urcrnrlat=wlat[1],llcrnrlon=wlon[0],urcrnrlon=wlon[1]) |
---|
505 | elif char == "npstere": m = Basemap(rsphere=radius,projection='npstere', boundinglat=blat, lon_0=0.) |
---|
506 | elif char == "spstere": m = Basemap(rsphere=radius,projection='spstere', boundinglat=blat, lon_0=180.) |
---|
507 | elif char == "nplaea": m = Basemap(rsphere=radius,projection='nplaea', boundinglat=wlat[0], lon_0=meanlon) |
---|
508 | elif char == "laea": m = Basemap(rsphere=radius,projection='laea',lon_0=meanlon,lat_0=meanlat,lat_ts=meanlat,\ |
---|
509 | llcrnrlat=wlat[0],urcrnrlat=wlat[1],llcrnrlon=wlon[0],urcrnrlon=wlon[1]) |
---|
510 | elif char == "nsper": m = Basemap(rsphere=radius,projection='nsper',lon_0=meanlon,lat_0=meanlat,satellite_height=h*1000.) |
---|
511 | elif char == "merc": m = Basemap(rsphere=radius,projection='merc',lat_ts=0.,\ |
---|
512 | llcrnrlat=wlat[0],urcrnrlat=wlat[1],llcrnrlon=wlon[0],urcrnrlon=wlon[1]) |
---|
513 | fontsizemer = int(mpl.rcParams['font.size']*3./4.) |
---|
514 | if char in ["cyl","lcc","merc","nsper","laea"]: step = findstep(wlon) |
---|
515 | else: step = 10. |
---|
516 | steplon = step*2. |
---|
517 | #if back in ["geolocal"]: |
---|
518 | # step = np.min([5.,step]) |
---|
519 | # steplon = step |
---|
520 | m.drawmeridians(np.r_[-180.:180.:steplon], labels=[0,0,0,1], color='grey', fontsize=fontsizemer) |
---|
521 | m.drawparallels(np.r_[-90.:90.:step], labels=[1,0,0,0], color='grey', fontsize=fontsizemer) |
---|
522 | if back: m.warpimage(marsmap(back),scale=0.75) |
---|
523 | #if not back: |
---|
524 | # if not var: back = "mola" ## if no var: draw mola |
---|
525 | # elif typefile in ['mesoapi','meso','geo'] \ |
---|
526 | # and proj not in ['merc','lcc','nsper','laea']: back = "molabw" ## if var but meso: draw molabw |
---|
527 | # else: pass ## else: draw None |
---|
528 | return m |
---|
529 | |
---|
530 | ## Author: AS |
---|
531 | #### test temporaire |
---|
532 | def putpoints (map,plot): |
---|
533 | #### from http://www.scipy.org/Cookbook/Matplotlib/Maps |
---|
534 | # lat/lon coordinates of five cities. |
---|
535 | lats = [18.4] |
---|
536 | lons = [-134.0] |
---|
537 | points=['Olympus Mons'] |
---|
538 | # compute the native map projection coordinates for cities. |
---|
539 | x,y = map(lons,lats) |
---|
540 | # plot filled circles at the locations of the cities. |
---|
541 | map.plot(x,y,'bo') |
---|
542 | # plot the names of those five cities. |
---|
543 | wherept = 0 #1000 #50000 |
---|
544 | for name,xpt,ypt in zip(points,x,y): |
---|
545 | plot.text(xpt+wherept,ypt+wherept,name) |
---|
546 | ## le nom ne s'affiche pas... |
---|
547 | return |
---|
548 | |
---|
549 | ## Author: AS |
---|
550 | def calculate_bounds(field,vmin=None,vmax=None): |
---|
551 | import numpy as np |
---|
552 | from mymath import max,min,mean |
---|
553 | ind = np.where(field < 9e+35) |
---|
554 | fieldcalc = field[ ind ] # la syntaxe compacte ne marche si field est un tuple |
---|
555 | ### |
---|
556 | dev = np.std(fieldcalc)*3.0 |
---|
557 | ### |
---|
558 | if vmin is None: |
---|
559 | zevmin = mean(fieldcalc) - dev |
---|
560 | else: zevmin = vmin |
---|
561 | ### |
---|
562 | if vmax is None: zevmax = mean(fieldcalc) + dev |
---|
563 | else: zevmax = vmax |
---|
564 | if vmin == vmax: |
---|
565 | zevmin = mean(fieldcalc) - dev ### for continuity |
---|
566 | zevmax = mean(fieldcalc) + dev ### for continuity |
---|
567 | ### |
---|
568 | if zevmin < 0. and min(fieldcalc) > 0.: zevmin = 0. |
---|
569 | print "BOUNDS field ", min(fieldcalc), max(fieldcalc) |
---|
570 | print "BOUNDS adopted ", zevmin, zevmax |
---|
571 | return zevmin, zevmax |
---|
572 | |
---|
573 | ## Author: AS |
---|
574 | def bounds(what_I_plot,zevmin,zevmax): |
---|
575 | from mymath import max,min,mean |
---|
576 | ### might be convenient to add the missing value in arguments |
---|
577 | #what_I_plot[ what_I_plot < zevmin ] = zevmin#*(1. + 1.e-7) |
---|
578 | if zevmin < 0: what_I_plot[ what_I_plot < zevmin*(1. - 1.e-7) ] = zevmin*(1. - 1.e-7) |
---|
579 | else: what_I_plot[ what_I_plot < zevmin*(1. + 1.e-7) ] = zevmin*(1. + 1.e-7) |
---|
580 | print "NEW MIN ", min(what_I_plot) |
---|
581 | what_I_plot[ what_I_plot > 9e+35 ] = -9e+35 |
---|
582 | what_I_plot[ what_I_plot > zevmax ] = zevmax |
---|
583 | print "NEW MAX ", max(what_I_plot) |
---|
584 | return what_I_plot |
---|
585 | |
---|
586 | ## Author: AS |
---|
587 | def nolow(what_I_plot): |
---|
588 | from mymath import max,min |
---|
589 | lim = 0.15*0.5*(abs(max(what_I_plot))+abs(min(what_I_plot))) |
---|
590 | print "NO PLOT BELOW VALUE ", lim |
---|
591 | what_I_plot [ abs(what_I_plot) < lim ] = 1.e40 |
---|
592 | return what_I_plot |
---|
593 | |
---|
594 | ## Author: AS |
---|
595 | def zoomset (wlon,wlat,zoom): |
---|
596 | dlon = abs(wlon[1]-wlon[0])/2. |
---|
597 | dlat = abs(wlat[1]-wlat[0])/2. |
---|
598 | [wlon,wlat] = [ [wlon[0]+zoom*dlon/100.,wlon[1]-zoom*dlon/100.],\ |
---|
599 | [wlat[0]+zoom*dlat/100.,wlat[1]-zoom*dlat/100.] ] |
---|
600 | print "ZOOM %",zoom,wlon,wlat |
---|
601 | return wlon,wlat |
---|
602 | |
---|
603 | ## Author: AS |
---|
604 | def fmtvar (whichvar="def"): |
---|
605 | fmtvar = { \ |
---|
606 | "tk": "%.0f",\ |
---|
607 | "T_NADIR_DAY": "%.0f",\ |
---|
608 | "T_NADIR_NIT": "%.0f",\ |
---|
609 | "TEMP_DAY": "%.0f",\ |
---|
610 | "TEMP_NIGHT": "%.0f",\ |
---|
611 | "tpot": "%.0f",\ |
---|
612 | "TSURF": "%.0f",\ |
---|
613 | "def": "%.1e",\ |
---|
614 | "PTOT": "%.0f",\ |
---|
615 | "HGT": "%.1e",\ |
---|
616 | "USTM": "%.2f",\ |
---|
617 | "HFX": "%.0f",\ |
---|
618 | "ICETOT": "%.1e",\ |
---|
619 | "TAU_ICE": "%.2f",\ |
---|
620 | "VMR_ICE": "%.1e",\ |
---|
621 | "MTOT": "%.1f",\ |
---|
622 | "anomaly": "%.1f",\ |
---|
623 | "W": "%.1f",\ |
---|
624 | "WMAX_TH": "%.1f",\ |
---|
625 | "QSURFICE": "%.0f",\ |
---|
626 | "Um": "%.0f",\ |
---|
627 | "ALBBARE": "%.2f",\ |
---|
628 | "TAU": "%.1f",\ |
---|
629 | "CO2": "%.2f",\ |
---|
630 | #### T.N. |
---|
631 | "TEMP": "%.0f",\ |
---|
632 | "VMR_H2OICE": "%.0f",\ |
---|
633 | "VMR_H2OVAP": "%.0f",\ |
---|
634 | "TAUTES": "%.2f",\ |
---|
635 | "TAUTESAP": "%.2f",\ |
---|
636 | |
---|
637 | } |
---|
638 | if whichvar not in fmtvar: |
---|
639 | whichvar = "def" |
---|
640 | return fmtvar[whichvar] |
---|
641 | |
---|
642 | ## Author: AS |
---|
643 | #################################################################################################################### |
---|
644 | ### Colorbars http://www.scipy.org/Cookbook/Matplotlib/Show_colormaps?action=AttachFile&do=get&target=colormaps3.png |
---|
645 | def defcolorb (whichone="def"): |
---|
646 | whichcolorb = { \ |
---|
647 | "def": "spectral",\ |
---|
648 | "HGT": "spectral",\ |
---|
649 | "tk": "gist_heat",\ |
---|
650 | "TSURF": "RdBu_r",\ |
---|
651 | "QH2O": "PuBu",\ |
---|
652 | "USTM": "YlOrRd",\ |
---|
653 | #"T_nadir_nit": "RdBu_r",\ |
---|
654 | #"T_nadir_day": "RdBu_r",\ |
---|
655 | "HFX": "RdYlBu",\ |
---|
656 | "ICETOT": "YlGnBu_r",\ |
---|
657 | #"MTOT": "PuBu",\ |
---|
658 | "CCNQ": "YlOrBr",\ |
---|
659 | "CCNN": "YlOrBr",\ |
---|
660 | "TEMP": "Jet",\ |
---|
661 | "TAU_ICE": "Blues",\ |
---|
662 | "VMR_ICE": "Blues",\ |
---|
663 | "W": "jet",\ |
---|
664 | "WMAX_TH": "spectral",\ |
---|
665 | "anomaly": "RdBu_r",\ |
---|
666 | "QSURFICE": "hot_r",\ |
---|
667 | "ALBBARE": "spectral",\ |
---|
668 | "TAU": "YlOrBr_r",\ |
---|
669 | "CO2": "YlOrBr_r",\ |
---|
670 | #### T.N. |
---|
671 | "MTOT": "Jet",\ |
---|
672 | "H2O_ICE_S": "RdBu",\ |
---|
673 | "VMR_H2OICE": "PuBu",\ |
---|
674 | "VMR_H2OVAP": "PuBu",\ |
---|
675 | } |
---|
676 | #W --> spectral ou jet |
---|
677 | #spectral BrBG RdBu_r |
---|
678 | #print "predefined colorbars" |
---|
679 | if whichone not in whichcolorb: |
---|
680 | whichone = "def" |
---|
681 | return whichcolorb[whichone] |
---|
682 | |
---|
683 | ## Author: AS |
---|
684 | def definecolorvec (whichone="def"): |
---|
685 | whichcolor = { \ |
---|
686 | "def": "black",\ |
---|
687 | "vis": "yellow",\ |
---|
688 | "vishires": "yellow",\ |
---|
689 | "molabw": "yellow",\ |
---|
690 | "mola": "black",\ |
---|
691 | "gist_heat": "white",\ |
---|
692 | "hot": "tk",\ |
---|
693 | "gist_rainbow": "black",\ |
---|
694 | "spectral": "black",\ |
---|
695 | "gray": "red",\ |
---|
696 | "PuBu": "black",\ |
---|
697 | } |
---|
698 | if whichone not in whichcolor: |
---|
699 | whichone = "def" |
---|
700 | return whichcolor[whichone] |
---|
701 | |
---|
702 | ## Author: AS |
---|
703 | def marsmap (whichone="vishires"): |
---|
704 | from os import uname |
---|
705 | mymachine = uname()[1] |
---|
706 | ### not sure about speed-up with this method... looks the same |
---|
707 | if "lmd.jussieu.fr" in mymachine: domain = "/u/aslmd/WWW/maps/" |
---|
708 | else: domain = "http://www.lmd.jussieu.fr/~aslmd/maps/" |
---|
709 | whichlink = { \ |
---|
710 | #"vis": "http://maps.jpl.nasa.gov/pix/mar0kuu2.jpg",\ |
---|
711 | #"vishires": "http://www.lmd.jussieu.fr/~aslmd/maps/MarsMap_2500x1250.jpg",\ |
---|
712 | #"geolocal": "http://dl.dropbox.com/u/11078310/geolocal.jpg",\ |
---|
713 | #"mola": "http://www.lns.cornell.edu/~seb/celestia/mars-mola-2k.jpg",\ |
---|
714 | #"molabw": "http://dl.dropbox.com/u/11078310/MarsElevation_2500x1250.jpg",\ |
---|
715 | "vis": domain+"mar0kuu2.jpg",\ |
---|
716 | "vishires": domain+"MarsMap_2500x1250.jpg",\ |
---|
717 | "geolocal": domain+"geolocal.jpg",\ |
---|
718 | "mola": domain+"mars-mola-2k.jpg",\ |
---|
719 | "molabw": domain+"MarsElevation_2500x1250.jpg",\ |
---|
720 | "clouds": "http://www.johnstonsarchive.net/spaceart/marswcloudmap.jpg",\ |
---|
721 | "jupiter": "http://www.mmedia.is/~bjj/data/jupiter_css/jupiter_css.jpg",\ |
---|
722 | "jupiter_voy": "http://www.mmedia.is/~bjj/data/jupiter/jupiter_vgr2.jpg",\ |
---|
723 | "bw": "http://users.info.unicaen.fr/~karczma/TEACH/InfoGeo/Images/Planets/EarthElevation_2500x1250.jpg",\ |
---|
724 | "contrast": "http://users.info.unicaen.fr/~karczma/TEACH/InfoGeo/Images/Planets/EarthMapAtmos_2500x1250.jpg",\ |
---|
725 | "nice": "http://users.info.unicaen.fr/~karczma/TEACH/InfoGeo/Images/Planets/earthmap1k.jpg",\ |
---|
726 | "blue": "http://eoimages.gsfc.nasa.gov/ve/2430/land_ocean_ice_2048.jpg",\ |
---|
727 | "blueclouds": "http://eoimages.gsfc.nasa.gov/ve/2431/land_ocean_ice_cloud_2048.jpg",\ |
---|
728 | "justclouds": "http://eoimages.gsfc.nasa.gov/ve/2432/cloud_combined_2048.jpg",\ |
---|
729 | } |
---|
730 | ### see http://www.mmedia.is/~bjj/planetary_maps.html |
---|
731 | if whichone not in whichlink: |
---|
732 | print "marsmap: choice not defined... you'll get the default one... " |
---|
733 | whichone = "vishires" |
---|
734 | return whichlink[whichone] |
---|
735 | |
---|
736 | #def earthmap (whichone): |
---|
737 | # if whichone == "contrast": whichlink="http://users.info.unicaen.fr/~karczma/TEACH/InfoGeo/Images/Planets/EarthMapAtmos_2500x1250.jpg" |
---|
738 | # elif whichone == "bw": whichlink="http://users.info.unicaen.fr/~karczma/TEACH/InfoGeo/Images/Planets/EarthElevation_2500x1250.jpg" |
---|
739 | # elif whichone == "nice": whichlink="http://users.info.unicaen.fr/~karczma/TEACH/InfoGeo/Images/Planets/earthmap1k.jpg" |
---|
740 | # return whichlink |
---|
741 | |
---|
742 | ## Author: AS |
---|
743 | def latinterv (area="Whole"): |
---|
744 | list = { \ |
---|
745 | "Europe": [[ 20., 80.],[- 50., 50.]],\ |
---|
746 | "Central_America": [[-10., 40.],[ 230., 300.]],\ |
---|
747 | "Africa": [[-20., 50.],[- 50., 50.]],\ |
---|
748 | "Whole": [[-90., 90.],[-180., 180.]],\ |
---|
749 | "Southern_Hemisphere": [[-90., 60.],[-180., 180.]],\ |
---|
750 | "Northern_Hemisphere": [[-60., 90.],[-180., 180.]],\ |
---|
751 | "Tharsis": [[-30., 60.],[-170.,- 10.]],\ |
---|
752 | "Whole_No_High": [[-60., 60.],[-180., 180.]],\ |
---|
753 | "Chryse": [[-60., 60.],[- 60., 60.]],\ |
---|
754 | "North_Pole": [[ 50., 90.],[-180., 180.]],\ |
---|
755 | "Close_North_Pole": [[ 75., 90.],[-180., 180.]],\ |
---|
756 | "Far_South_Pole": [[-90.,-40.],[-180., 180.]],\ |
---|
757 | "South_Pole": [[-90.,-50.],[-180., 180.]],\ |
---|
758 | "Close_South_Pole": [[-90.,-75.],[-180., 180.]],\ |
---|
759 | } |
---|
760 | if area not in list: area = "Whole" |
---|
761 | [olat,olon] = list[area] |
---|
762 | return olon,olat |
---|
763 | |
---|
764 | ## Author: TN |
---|
765 | def separatenames (name): |
---|
766 | from numpy import concatenate |
---|
767 | # look for comas in the input name to separate different names (files, variables,etc ..) |
---|
768 | if name is None: |
---|
769 | names = None |
---|
770 | else: |
---|
771 | names = [] |
---|
772 | stop = 0 |
---|
773 | currentname = name |
---|
774 | while stop == 0: |
---|
775 | indexvir = currentname.find(',') |
---|
776 | if indexvir == -1: |
---|
777 | stop = 1 |
---|
778 | name1 = currentname |
---|
779 | else: |
---|
780 | name1 = currentname[0:indexvir] |
---|
781 | names = concatenate((names,[name1])) |
---|
782 | currentname = currentname[indexvir+1:len(currentname)] |
---|
783 | return names |
---|
784 | |
---|
785 | ## Author: TN [old] |
---|
786 | def getopmatrix (kind,n): |
---|
787 | import numpy as np |
---|
788 | # compute matrix of operations between files |
---|
789 | # the matrix is 'number of files'-square |
---|
790 | # 1: difference (row minus column), 2: add |
---|
791 | # not 0 in diag : just plot |
---|
792 | if n == 1: |
---|
793 | opm = np.eye(1) |
---|
794 | elif kind == 'basic': |
---|
795 | opm = np.eye(n) |
---|
796 | elif kind == 'difference1': # show differences with 1st file |
---|
797 | opm = np.zeros((n,n)) |
---|
798 | opm[0,:] = 1 |
---|
799 | opm[0,0] = 0 |
---|
800 | elif kind == 'difference2': # show differences with 1st file AND show 1st file |
---|
801 | opm = np.zeros((n,n)) |
---|
802 | opm[0,:] = 1 |
---|
803 | else: |
---|
804 | opm = np.eye(n) |
---|
805 | return opm |
---|
806 | |
---|
807 | ## Author: TN [old] |
---|
808 | def checkcoherence (nfiles,nlat,nlon,ntime): |
---|
809 | if (nfiles > 1): |
---|
810 | if (nlat > 1): |
---|
811 | errormess("what you asked is not possible !") |
---|
812 | return 1 |
---|
813 | |
---|
814 | ## Author: TN |
---|
815 | def readslices(saxis): |
---|
816 | from numpy import empty |
---|
817 | if saxis == None: |
---|
818 | zesaxis = None |
---|
819 | else: |
---|
820 | zesaxis = empty((len(saxis),2)) |
---|
821 | for i in range(len(saxis)): |
---|
822 | a = separatenames(saxis[i]) |
---|
823 | if len(a) == 1: |
---|
824 | zesaxis[i,:] = float(a[0]) |
---|
825 | else: |
---|
826 | zesaxis[i,0] = float(a[0]) |
---|
827 | zesaxis[i,1] = float(a[1]) |
---|
828 | |
---|
829 | return zesaxis |
---|
830 | |
---|
831 | ## Author: AS |
---|
832 | def bidimfind(lon2d,lat2d,vlon,vlat): |
---|
833 | import numpy as np |
---|
834 | if vlat is None: array = (lon2d - vlon)**2 |
---|
835 | elif vlon is None: array = (lat2d - vlat)**2 |
---|
836 | else: array = (lon2d - vlon)**2 + (lat2d - vlat)**2 |
---|
837 | idy,idx = np.unravel_index( np.argmin(array), lon2d.shape ) |
---|
838 | if vlon is not None: |
---|
839 | #print lon2d[idy,idx],vlon |
---|
840 | if (np.abs(lon2d[idy,idx]-vlon)) > 5: errormess("longitude not found ",printvar=lon2d) |
---|
841 | if vlat is not None: |
---|
842 | #print lat2d[idy,idx],vlat |
---|
843 | if (np.abs(lat2d[idy,idx]-vlat)) > 5: errormess("latitude not found ",printvar=lat2d) |
---|
844 | return idx,idy |
---|
845 | |
---|
846 | ## Author: TN |
---|
847 | def getsindex(saxis,index,axis): |
---|
848 | # input : all the desired slices and the good index |
---|
849 | # output : all indexes to be taken into account for reducing field |
---|
850 | import numpy as np |
---|
851 | if ( np.array(axis).ndim == 2): |
---|
852 | axis = axis[:,0] |
---|
853 | if saxis is None: |
---|
854 | zeindex = None |
---|
855 | else: |
---|
856 | aaa = int(np.argmin(abs(saxis[index,0] - axis))) |
---|
857 | bbb = int(np.argmin(abs(saxis[index,1] - axis))) |
---|
858 | [imin,imax] = np.sort(np.array([aaa,bbb])) |
---|
859 | zeindex = np.array(range(imax-imin+1))+imin |
---|
860 | # because -180 and 180 are the same point in longitude, |
---|
861 | # we get rid of one for averaging purposes. |
---|
862 | if axis[imin] == -180 and axis[imax] == 180: |
---|
863 | zeindex = zeindex[0:len(zeindex)-1] |
---|
864 | print "INFO: whole longitude averaging asked, so last point is not taken into account." |
---|
865 | return zeindex |
---|
866 | |
---|
867 | ## Author: TN |
---|
868 | def define_axis(lon,lat,vert,time,indexlon,indexlat,indexvert,indextime,what_I_plot,dim0,vertmode): |
---|
869 | # Purpose of define_axis is to find x and y axis scales in a smart way |
---|
870 | # x axis priority: 1/time 2/lon 3/lat 4/vertical |
---|
871 | # To be improved !!!... |
---|
872 | from numpy import array,swapaxes |
---|
873 | x = None |
---|
874 | y = None |
---|
875 | count = 0 |
---|
876 | what_I_plot = array(what_I_plot) |
---|
877 | shape = what_I_plot.shape |
---|
878 | if indextime is None: |
---|
879 | print "AXIS is time" |
---|
880 | x = time |
---|
881 | count = count+1 |
---|
882 | if indexlon is None: |
---|
883 | print "AXIS is lon" |
---|
884 | if count == 0: x = lon |
---|
885 | else: y = lon |
---|
886 | count = count+1 |
---|
887 | if indexlat is None: |
---|
888 | print "AXIS is lat" |
---|
889 | if count == 0: x = lat |
---|
890 | else: y = lat |
---|
891 | count = count+1 |
---|
892 | if indexvert is None and dim0 is 4: |
---|
893 | print "AXIS is vert" |
---|
894 | if vertmode == 0: # vertical axis is as is (GCM grid) |
---|
895 | if count == 0: x=range(len(vert)) |
---|
896 | else: y=range(len(vert)) |
---|
897 | count = count+1 |
---|
898 | else: # vertical axis is in kms |
---|
899 | if count == 0: x = vert |
---|
900 | else: y = vert |
---|
901 | count = count+1 |
---|
902 | x = array(x) |
---|
903 | y = array(y) |
---|
904 | print "CHECK: what_I_plot.shape", what_I_plot.shape |
---|
905 | print "CHECK: x.shape, y.shape", x.shape, y.shape |
---|
906 | if len(shape) == 1: |
---|
907 | if shape[0] != len(x): |
---|
908 | print "WARNING HERE !!!" |
---|
909 | x = y |
---|
910 | elif len(shape) == 2: |
---|
911 | if shape[1] == len(y) and shape[0] == len(x) and shape[0] != shape[1]: |
---|
912 | what_I_plot = swapaxes(what_I_plot,0,1) |
---|
913 | print "INFO: swapaxes", what_I_plot.shape, shape |
---|
914 | return what_I_plot,x,y |
---|
915 | |
---|
916 | # Author: TN + AS |
---|
917 | def determineplot(slon, slat, svert, stime): |
---|
918 | nlon = 1 # number of longitudinal slices -- 1 is None |
---|
919 | nlat = 1 |
---|
920 | nvert = 1 |
---|
921 | ntime = 1 |
---|
922 | nslices = 1 |
---|
923 | if slon is not None: |
---|
924 | nslices = nslices*len(slon) |
---|
925 | nlon = len(slon) |
---|
926 | if slat is not None: |
---|
927 | nslices = nslices*len(slat) |
---|
928 | nlat = len(slat) |
---|
929 | if svert is not None: |
---|
930 | nslices = nslices*len(svert) |
---|
931 | nvert = len(svert) |
---|
932 | if stime is not None: |
---|
933 | nslices = nslices*len(stime) |
---|
934 | ntime = len(stime) |
---|
935 | #else: |
---|
936 | # nslices = 2 |
---|
937 | |
---|
938 | mapmode = 0 |
---|
939 | if slon is None and slat is None: |
---|
940 | mapmode = 1 # in this case we plot a map, with the given projection |
---|
941 | |
---|
942 | return nlon, nlat, nvert, ntime, mapmode, nslices |
---|