1 | ####################### |
---|
2 | ##### PLANETOPLOT ##### |
---|
3 | ####################### |
---|
4 | |
---|
5 | ### A. Spiga -- LMD -- 06~09/2011 -- General building and mapping capabilities |
---|
6 | ### T. Navarro -- LMD -- 10~11/2011 -- Improved use for GCM and added sections + 1Dplot capabilities |
---|
7 | ### A. Colaitis -- LMD -- 11/2011 -- Mostly minor improvements and inter-plot operation capabilities + zrecast interpolation for gcm |
---|
8 | ### A. Spiga -- LMD -- 11~12/2011 -- Extended multivar subplot capabilities + cosmetic changes + general cleaning and tests |
---|
9 | ### A. Colaitis -- LMD -- 12/2011 -- Added movie capability [mencoder must be installed] |
---|
10 | ### A. Spiga -- LMD -- 12/2011 -- Added HTML animated page capability + general tests of consistency [winds, etc...] + consistent generic movie loop |
---|
11 | ### J. Leconte -- LMD -- 02/2012 -- Added area weighted averaging. Compatibility with terrestrial gcm. |
---|
12 | ### A. Spiga -- LMD -- 03/2012 -- Cleaning and improved comments |
---|
13 | ### T. Navarro -- LMD -- 04/2012 -- Added capabilities (e.g. histograms for difference maps) |
---|
14 | ### A. Colaitis -- LMD -- 05~06/2012 -- Added capabilities for analysis of mesoscale files (wind speed, etc...) |
---|
15 | ### A. Spiga -- LMD -- 04~07/2012 -- Added larger support of files + planets. Corrected a few bugs. Cleaning and improved comments |
---|
16 | |
---|
17 | def planetoplot (namefiles,\ |
---|
18 | level=0,\ |
---|
19 | vertmode=0,\ |
---|
20 | proj=None,\ |
---|
21 | back=None,\ |
---|
22 | target=None, |
---|
23 | stride=3,\ |
---|
24 | var=None,\ |
---|
25 | colorb="def",\ |
---|
26 | winds=False,\ |
---|
27 | addchar=None,\ |
---|
28 | interv=[0,1],\ |
---|
29 | vmin=None,\ |
---|
30 | vmax=None,\ |
---|
31 | tile=False,\ |
---|
32 | zoom=None,\ |
---|
33 | display=True,\ |
---|
34 | hole=False,\ |
---|
35 | save="gui",\ |
---|
36 | anomaly=False,\ |
---|
37 | var2=None,\ |
---|
38 | ndiv=10,\ |
---|
39 | mult=1.,\ |
---|
40 | zetitle=["fill"],\ |
---|
41 | slon=None,\ |
---|
42 | slat=None,\ |
---|
43 | svert=None,\ |
---|
44 | stime=None,\ |
---|
45 | outputname=None,\ |
---|
46 | resolution=200,\ |
---|
47 | ope=None,\ |
---|
48 | fileref=None,\ |
---|
49 | minop=0.,\ |
---|
50 | maxop=0.,\ |
---|
51 | titleref="fill",\ |
---|
52 | invert_y=False,\ |
---|
53 | xaxis=[None,None],\ |
---|
54 | yaxis=[None,None],\ |
---|
55 | ylog=False,\ |
---|
56 | yintegral=False,\ |
---|
57 | blat=None,\ |
---|
58 | blon=None,\ |
---|
59 | tsat=False,\ |
---|
60 | flagnolow=False,\ |
---|
61 | mrate=None,\ |
---|
62 | mquality=False,\ |
---|
63 | trans=1,\ |
---|
64 | zarea=None,\ |
---|
65 | axtime=None,\ |
---|
66 | redope=None,\ |
---|
67 | seevar=False,\ |
---|
68 | xlab=None,\ |
---|
69 | ylab=None,\ |
---|
70 | lbls=None,\ |
---|
71 | lstyle=None,\ |
---|
72 | cross=None,\ |
---|
73 | facwind=1.,\ |
---|
74 | streamflag=False): |
---|
75 | |
---|
76 | #################################################################################################################### |
---|
77 | ### Colorbars http://www.scipy.org/Cookbook/Matplotlib/Show_colormaps?action=AttachFile&do=get&target=colormaps3.png |
---|
78 | |
---|
79 | ################################# |
---|
80 | ### Load librairies and functions |
---|
81 | from netCDF4 import Dataset |
---|
82 | from myplot import getcoord2d,define_proj,makeplotres,simplinterv,vectorfield,ptitle,latinterv,getproj,wrfinterv,dumpbdy,\ |
---|
83 | fmtvar,definecolorvec,defcolorb,getprefix,putpoints,calculate_bounds,errormess,definesubplot,\ |
---|
84 | zoomset,getcoorddef,getwinddef,whatkindfile,reducefield,bounds,getstralt,getfield,smooth,nolow,\ |
---|
85 | getname,localtime,check_localtime,polarinterv,getsindex,define_axis,determineplot,readslices,bidimfind,getlschar,hole_bounds,\ |
---|
86 | windamplitude,slopeamplitude,deltat0t1,enrichment_factor,getdimfromvar |
---|
87 | from mymath import deg,max,min,mean,get_tsat,writeascii,fig2data,fig2img |
---|
88 | import matplotlib as mpl |
---|
89 | from matplotlib.pyplot import contour,contourf,hist, text,subplot, figure, rcParams, savefig, colorbar, \ |
---|
90 | pcolor, show, plot, clabel, title, close, legend, xlabel, axis, ylabel, \ |
---|
91 | subplots_adjust, axes, clabel |
---|
92 | from matplotlib.cm import get_cmap |
---|
93 | #from mpl_toolkits.basemap import cm |
---|
94 | import numpy as np |
---|
95 | from numpy.core.defchararray import find |
---|
96 | from videosink import VideoSink |
---|
97 | from times import sol2ls |
---|
98 | import subprocess |
---|
99 | #from singlet import singlet |
---|
100 | from itertools import cycle |
---|
101 | import os |
---|
102 | |
---|
103 | ######################### |
---|
104 | ### PRELIMINARY STUFF ### |
---|
105 | ######################### |
---|
106 | ### we say hello |
---|
107 | print "********************************************" |
---|
108 | print "********** WELCOME TO PLANETOPLOT **********" |
---|
109 | print "********************************************" |
---|
110 | ### we ensure namefiles and var are arrays |
---|
111 | if not isinstance(namefiles, np.ndarray): namefiles = [namefiles] |
---|
112 | if not isinstance(var, np.ndarray): var = [var] |
---|
113 | ### we initialize a few variables |
---|
114 | initime=-1 ; sslon = None ; sslat = None |
---|
115 | if slon is not None: sslon = np.zeros([1,2]) |
---|
116 | if slat is not None: sslat = np.zeros([1,2]) |
---|
117 | k = 0 ; firstfile = True ; count = 0 |
---|
118 | ### we avoid specific cases not yet implemented |
---|
119 | if mrate is not None and len(var) > 1: errormess("multivar not allowed in movies. should be fixed soon!") |
---|
120 | ### we prepare number of plot fields [zelen] and plot instances [numplot] according to user choices |
---|
121 | ### --> we support multifile and multivar plots : files + vars separated by commas are on the same figure |
---|
122 | nlon, nlat, nvert, ntime, mapmode, nslices = determineplot(slon, slat, svert, stime) |
---|
123 | zelen = len(namefiles)*len(var) |
---|
124 | numplot = zelen*nslices |
---|
125 | print "********** FILES, SLICES, VARS, TOTAL PLOTS: ", len(namefiles), nslices, len(var), numplot |
---|
126 | print "********** MAPMODE: ", mapmode |
---|
127 | ### we correct number of plot fields for possible operation (substract, etc...) |
---|
128 | if ope is not None: |
---|
129 | if fileref is not None: zelen = zelen + 2 |
---|
130 | elif "var" in ope: zelen = zelen + 1 |
---|
131 | ### we define the arrays for plot fields -- which will be placed within multiplot loops |
---|
132 | all_var = [[]]*zelen ; all_var2 = [[]]*zelen |
---|
133 | all_title = [[]]*zelen ; all_varname = [[]]*zelen ; all_namefile = [[]]*zelen ; all_time = [[]]*zelen |
---|
134 | all_windu = [[]]*zelen ; all_windv = [[]]*zelen |
---|
135 | |
---|
136 | ############################# |
---|
137 | ### LOOP OVER PLOT FIELDS ### |
---|
138 | ############################# |
---|
139 | for nnn in range(len(namefiles)): |
---|
140 | for vvv in range(len(var)): |
---|
141 | |
---|
142 | ### we load each NETCDF objects in namefiles |
---|
143 | namefile = namefiles[nnn] |
---|
144 | nc = Dataset(namefile) |
---|
145 | ### we explore the variables in the file |
---|
146 | varinfile = nc.variables.keys() |
---|
147 | if seevar: print varinfile ; exit() |
---|
148 | ### we define the type of file we have (gcm, meso, etc...) |
---|
149 | typefile = whatkindfile(nc) |
---|
150 | if firstfile: typefile0 = typefile |
---|
151 | elif typefile != typefile0: errormess("Not the same kind of files !", [typefile0, typefile]) |
---|
152 | ### we care for input file being 1D simulations |
---|
153 | is1d=999 |
---|
154 | if "longitude" in nc.dimensions and "latitude" in nc.dimensions: is1d = len(nc.variables["longitude"][:])*len(nc.variables["latitude"][:]) |
---|
155 | elif "lon" in nc.dimensions and "lat" in nc.dimensions: is1d = len(nc.variables["lon"][:])*len(nc.variables["lat"][:]) |
---|
156 | if typefile in ['gcm','earthgcm'] and is1d == 1: mapmode=0 ; winds=False |
---|
157 | ### we create default vert and time prescriptions if not here in case mapping mode is on (lat/lon maps) |
---|
158 | if redope is None and mapmode == 1: |
---|
159 | if svert is None: svert = readslices(str(level)) ; nvert=1 |
---|
160 | if stime is None and mrate is None: |
---|
161 | stime = readslices(str(0)) ; ntime=1 ## this is a default choice |
---|
162 | print "WELL... nothing about time axis. I took default: first time reference stored in file." |
---|
163 | ### we get the names of variables to be read. in case only one available, we choose this one. |
---|
164 | ### (we take out of the test specific names e.g. UV is not in the file but used to ask a wind speed computation) |
---|
165 | varname=var[vvv] |
---|
166 | logical_novarname = varname not in nc.variables |
---|
167 | specificname_meso = ['UV','uv','uvmet','slopexy','SLOPEXY','deltat','DELTAT'] |
---|
168 | logical_nospecificname_meso = not ((typefile in ['meso']) and (varname in specificname_meso)) |
---|
169 | specificname_gcm = ['enfact'] |
---|
170 | logical_nospecificname_gcm = not ((typefile in ['gcm']) and (varname in specificname_gcm)) |
---|
171 | if ( logical_novarname and logical_nospecificname_meso and logical_nospecificname_gcm ): |
---|
172 | if len(varinfile) == 1: varname = varinfile[0] |
---|
173 | else: varname = False |
---|
174 | ### we get the names of wind variables to be read (if any) |
---|
175 | if winds: |
---|
176 | [uchar,vchar,metwind] = getwinddef(nc) |
---|
177 | if uchar == 'not found': winds = False |
---|
178 | ### we tell the user that either no var or no wind is not acceptable |
---|
179 | if not varname and not winds: errormess("please set at least winds or var",printvar=nc.variables) |
---|
180 | ### we get the coordinates lat/lon to be used |
---|
181 | [lon2d,lat2d] = getcoorddef(nc) |
---|
182 | ### we get an adapted map projection if none is provided by the user |
---|
183 | if proj == None: proj = getproj(nc) |
---|
184 | ### we define plot boundaries given projection or user choices |
---|
185 | if firstfile: |
---|
186 | if proj in ["npstere","spstere"]: [wlon,wlat] = polarinterv(lon2d,lat2d) |
---|
187 | elif proj in ["lcc","laea"]: [wlon,wlat] = wrfinterv(lon2d,lat2d) |
---|
188 | else: [wlon,wlat] = simplinterv(lon2d,lat2d) |
---|
189 | if zoom: [wlon,wlat] = zoomset(wlon,wlat,zoom) |
---|
190 | elif zarea is not None: [wlon,wlat] = latinterv(area=zarea) |
---|
191 | |
---|
192 | ############################################################# |
---|
193 | ############ WE LOAD 4D DIMENSIONS : x, y, z, t ############# |
---|
194 | ############################################################# |
---|
195 | |
---|
196 | ### TYPE 1 : GCM files or simple files |
---|
197 | if typefile in ["gcm","earthgcm","ecmwf"]: |
---|
198 | ### this is needed for continuity |
---|
199 | if slon is not None: sslon = slon |
---|
200 | if slat is not None: sslat = slat |
---|
201 | ### we define lat/lon vectors. we get what was done in getcoorddef. |
---|
202 | lat = lat2d[:,0] ; lon = lon2d[0,:] |
---|
203 | ### we define areas. this is needed for calculate means and weight with area. this is not compulsory (see reduce_field). |
---|
204 | if "aire" in nc.variables: area = nc.variables["aire"][:,:] |
---|
205 | ### --> add a line here if your reference is not present |
---|
206 | else: area = None |
---|
207 | ### we define altitude vector. either it is referenced or it is guessed based on last variable's dimensions. |
---|
208 | if "altitude" in nc.variables: vert = nc.variables["altitude"][:] |
---|
209 | elif "Alt" in nc.variables: vert = nc.variables["Alt"][:] |
---|
210 | elif "lev" in nc.variables: vert = nc.variables["lev"][:] |
---|
211 | elif "presnivs" in nc.variables: vert = nc.variables["presnivs"][:] |
---|
212 | ### --> add a line here if your reference is not present |
---|
213 | else: |
---|
214 | print "No altitude found. Try to build a simple axis." ; dadim = getdimfromvar(nc) |
---|
215 | if len(dadim) == 4: print "-- 4D field. Assume z is dim 2." ; vert = np.arange(dadim[-3]) |
---|
216 | elif len(dadim) == 3: print "-- 3D field. Assume z is dim 1." ; vert = [0.] |
---|
217 | else: vert = [0.] |
---|
218 | ### we define time vector. either it is referenced or it is guessed based on last variable's dimensions. |
---|
219 | if "Time" in nc.variables: time = nc.variables["Time"][:] |
---|
220 | elif "time_counter" in nc.variables: time = nc.variables["time_counter"][:]/86400. #### convert from s to days |
---|
221 | elif "time" in nc.variables: time = nc.variables["time"][:] |
---|
222 | ### --> add a line here if your reference is not present |
---|
223 | else: |
---|
224 | print "No time found. Try to build a simple axis. Assume t is dim 1." |
---|
225 | dadim = getdimfromvar(nc) |
---|
226 | if len(dadim) == 4: time = np.arange(dadim[-4]) |
---|
227 | elif len(dadim) == 3: time = np.arange(dadim[-3]) |
---|
228 | else: time = [0.] #errormess("no time axis found.") |
---|
229 | ### (SPECIFIC. convert to Ls for Martian GCM files.) |
---|
230 | if axtime in ["ls"]: |
---|
231 | print "converting to Ls ..." |
---|
232 | for iii in range(len(time)): |
---|
233 | time[iii] = sol2ls(time[iii]) |
---|
234 | if iii > 0: |
---|
235 | while abs(time[iii]-time[iii-1]) > 300: time[iii] = time[iii]+360 |
---|
236 | ### (a case where the user would like to set local times. e.g. : 1D plot with no longitude reference) |
---|
237 | if axtime in ["lt"]: |
---|
238 | if initime == -1: initime=input("Please type initial local time:") |
---|
239 | time = (initime+time*24)%24 ; print "LOCAL TIMES.... ", time |
---|
240 | |
---|
241 | ### TYPE 2 : MESOSCALE FILES |
---|
242 | elif typefile in ['meso','geo']: |
---|
243 | ### area not active with mesoscale files |
---|
244 | area = None |
---|
245 | ### HACK TO GET THE CORRECT LAT/LON FROM MESOSCALE FILES WITH 2D LAT/LON ARRAYS |
---|
246 | ### principle: calculate correct indices then repopulate slon and slat |
---|
247 | if slon is not None or slat is not None: |
---|
248 | show_topo_map_user = ((save == 'png') and (typefile == 'meso') and ("HGT" in varinfile) and display) |
---|
249 | if firstfile and show_topo_map_user: iwantawhereplot = nc #show a topo map with a cross on the chosen point |
---|
250 | else: iwantawhereplot = None #do not show anything, just select indices |
---|
251 | numlon = 1 ; numlat = 1 |
---|
252 | if slon is not None: numlon = slon.shape[1] |
---|
253 | if slat is not None: numlat = slat.shape[1] |
---|
254 | indices = np.ones([numlon,numlat,2]) ; vlon = None ; vlat = None |
---|
255 | for iii in range(numlon): |
---|
256 | for jjj in range(numlat): |
---|
257 | if slon is not None: vlon = slon[0][iii] ### note: slon[:][0] does not work |
---|
258 | if slat is not None: vlat = slat[0][jjj] ### note: slon[:][0] does not work |
---|
259 | indices[iii,jjj,:] = bidimfind(lon2d,lat2d,vlon,vlat,file=iwantawhereplot) |
---|
260 | lonp,latp = ( lon2d[indices[iii,jjj,0],indices[iii,jjj,1]] , lat2d[indices[iii,jjj,0],indices[iii,jjj,1]] ) |
---|
261 | ### possible bug here if several --lat |
---|
262 | for iii in range(numlon): |
---|
263 | for jjj in range(numlat): |
---|
264 | if slon is not None: sslon[0][iii] = indices[iii,0,1] #...this is idx |
---|
265 | if slat is not None: sslat[0][jjj] = indices[0,jjj,0] #...this is idy |
---|
266 | lonp,latp = ( lon2d[indices[0,0,0],indices[0,0,1]] , lat2d[indices[0,0,0],indices[0,0,1]] ) |
---|
267 | ### we get rid of boundary relaxation zone for plots. important to do that now and not before. |
---|
268 | if typefile in ['meso'] and mapmode == 1: lon2d = dumpbdy(lon2d,6) ; lat2d = dumpbdy(lat2d,6) |
---|
269 | ### we read the keyword for vertical dimension. we take care for vertical staggering. |
---|
270 | if varname in ['PHTOT','W']: vertdim='BOTTOM-TOP_PATCH_END_STAG' |
---|
271 | else: vertdim='BOTTOM-TOP_PATCH_END_UNSTAG' |
---|
272 | if (var2 is not None and var2 not in ['PHTOT','W']): dumped_vert_stag=True ; vertdim='BOTTOM-TOP_PATCH_END_UNSTAG' |
---|
273 | else: dumped_vert_stag=False |
---|
274 | ### we read the keyword for horizontal dimensions. we take care for horizontal staggering. |
---|
275 | if varname in ['V']: latdim='SOUTH-NORTH_PATCH_END_STAG' |
---|
276 | else: latdim='SOUTH-NORTH_PATCH_END_UNSTAG' |
---|
277 | if varname in ['U']: londim='WEST-EAST_PATCH_END_STAG' |
---|
278 | else: londim='WEST-EAST_PATCH_END_UNSTAG' |
---|
279 | lon = np.arange(0,getattr(nc,londim),1) ; lat = np.arange(0,getattr(nc,latdim),1) |
---|
280 | ### we define the time axis and take care of various specificities (lt, ls, sol) or issues (concatenation) |
---|
281 | if axtime in ["ls","sol"]: |
---|
282 | lstab, soltab, lttab = getlschar ( namefile, getaxis = True ) |
---|
283 | if axtime == "ls": time = lstab |
---|
284 | elif axtime == "sol": time = soltab |
---|
285 | else: |
---|
286 | if ope in ["cat"] and nnn > 0: count = time[-1] + 1 ## so that a cat is possible with simple subscripts |
---|
287 | else: count = 0 |
---|
288 | if "Times" in nc.dimensions: time = count + np.arange(0,len(nc.dimensions["Times"]),1) |
---|
289 | elif "Time" in nc.dimensions: time = count + np.arange(0,len(nc.dimensions["Time"]),1) |
---|
290 | else: time = count + np.arange(0,1,1) |
---|
291 | if axtime in ["lt"]: |
---|
292 | ftime = np.zeros(len(time)) |
---|
293 | for i in range(len(time)): |
---|
294 | ftime[i] = localtime ( interv[0]+time[i]*interv[1], 0.5*(wlon[0]+wlon[1]) ) |
---|
295 | time=ftime |
---|
296 | time=check_localtime(time) |
---|
297 | print "LOCAL TIMES.... ", time |
---|
298 | ### we define the vertical axis (or lack thereof) and cover possibilities for it to be altitude, pressure, geopotential. quite SPECIFIC. |
---|
299 | if typefile in ['geo']: vert = [0.] ; stime = readslices(str(0)) |
---|
300 | else: |
---|
301 | if vertmode is None: vertmode=0 |
---|
302 | if vertmode == 0: |
---|
303 | if "vert" in nc.variables: vert = nc.variables["vert"][:]/1000. ; vertmode = 1 |
---|
304 | else: vert = np.arange(0,getattr(nc,vertdim),1) |
---|
305 | elif vertmode == -1: vert = nc.variables["PHTOT"][0,:,0,0]/3.72 ; vert = np.array(vert[0:len(vert)-1]) #; print vert |
---|
306 | elif vertmode == 1 or vertmode == 2: vert = nc.variables["vert"][:] ## pressure in Pa |
---|
307 | else: vert = nc.variables["vert"][:]/1000. ## altitude in km |
---|
308 | #################################################################### |
---|
309 | ############ END of WE LOAD 4D DIMENSIONS : x, y, z, t ############# |
---|
310 | #################################################################### |
---|
311 | |
---|
312 | ### we fill the arrays of varname, namefile, time at the current step considered (NB: why use both k and nnn ?) |
---|
313 | all_varname[k] = varname |
---|
314 | all_namefile[k] = namefile |
---|
315 | all_time[k] = time |
---|
316 | if var2: |
---|
317 | all_var2[k] = getfield(nc,var2) |
---|
318 | ### v--- too SPECIFIC (see below) |
---|
319 | if ((var2 in ['slopexy','SLOPEXY']) and (typefile in ['meso']) and (var2 not in nc.variables)): all_var2[k] = slopeamplitude(nc) |
---|
320 | if winds: all_windu[k] = getfield(nc,uchar) ; all_windv[k] = getfield(nc,vchar) |
---|
321 | ### we fill the arrays of fields to be plotted at the current step considered |
---|
322 | ### ----------- SPECIFIC CASES. NOT HAPPY WITH THIS. note : we could probably call those via a "toolbox" in myplot. |
---|
323 | ### ----------- 1. saturation temperature |
---|
324 | if varname in ["temp","t","T_nadir_nit","T_nadir_day","temp_day","temp_night"] and tsat: |
---|
325 | tt=getfield(nc,varname) ; print "computing Tsat-T, I ASSUME Z-AXIS IS PRESSURE" |
---|
326 | if type(tt).__name__=='MaskedArray': tt.set_fill_value([np.NaN]) ; tinput=tt.filled() |
---|
327 | else: tinput=tt |
---|
328 | all_var[k]=get_tsat(vert,tinput,zlon=lon,zlat=lat,zalt=vert,ztime=time) |
---|
329 | ### ----------- 2. wind amplitude |
---|
330 | elif ((varname in ['UV','uv','uvmet']) and (typefile in ['meso']) and (varname not in nc.variables)): |
---|
331 | all_var[k]=windamplitude(nc) |
---|
332 | elif ((varname in ['slopexy','SLOPEXY']) and (typefile in ['meso']) and (varname not in nc.variables)): |
---|
333 | all_var[k]=slopeamplitude(nc) |
---|
334 | ### ------------ 3. Near surface instability |
---|
335 | elif ((varname in ['DELTAT','deltat']) and (typefile in ['meso']) and (varname not in nc.variables)): |
---|
336 | all_var[k]=deltat0t1(nc) |
---|
337 | ### ------------ 4. Enrichment factor |
---|
338 | elif ((typefile in ['gcm']) and (varname in ['enfact'])): |
---|
339 | all_var[k]=enrichment_factor(nc,lon,lat,time) |
---|
340 | else: |
---|
341 | ### ideally only this line should be here |
---|
342 | all_var[k] = getfield(nc,varname) |
---|
343 | ### we inform the user about the loop then increment the loop. this is the last line of "for namefile in namefiles" |
---|
344 | print "**** GOT SUBDATA:",k," NAMEFILE:",namefile," VAR:",varname, var2 ; k += 1 ; firstfile = False |
---|
345 | |
---|
346 | ### note to self : stopped comment rewriting here. |
---|
347 | |
---|
348 | ################################## |
---|
349 | ### Operation on files |
---|
350 | if ope is not None: |
---|
351 | print "********** OPERATION: ",ope |
---|
352 | if "var" not in ope: |
---|
353 | if len(var) > 1: errormess("for this operation... please set only one var !") |
---|
354 | if ope in ["-","+","-%"]: |
---|
355 | if fileref is not None: |
---|
356 | ncref = Dataset(fileref) |
---|
357 | if ((all_varname[k-1] in ['UV','uv','uvmet']) and (typefile in ['meso']) and (all_varname[k-1] not in ncref.variables)): |
---|
358 | all_var[k] = windamplitude(ncref) |
---|
359 | elif ((all_varname[k-1] in ['slopexy','SLOPEXY']) and (typefile in ['meso']) and (all_varname[k-1] not in ncref.variables)): |
---|
360 | all_var[k] = slopeamplitude(ncref) |
---|
361 | elif ((all_varname[k-1] in ['DELTAT','deltat']) and (typefile in ['meso']) and (all_varname[k-1] not in ncref.variables)): |
---|
362 | all_var[k]=deltat0t1(ncref) |
---|
363 | else: |
---|
364 | all_var[k] = getfield(ncref,all_varname[k-1]) |
---|
365 | all_varname[k] = all_varname[k-1] ; all_time[k] = all_time[k-1] ; all_namefile[k] = all_namefile[k-1] ; all_var2[k] = all_var2[k-1] |
---|
366 | if winds: all_windu[k] = getfield(ncref,uchar) ; all_windv[k] = getfield(ncref,vchar) |
---|
367 | else: errormess("fileref is missing!") |
---|
368 | if ope == "-": all_var[k+1]= all_var[k-1] - all_var[k] |
---|
369 | elif ope == "+": all_var[k+1]= all_var[k-1] + all_var[k] |
---|
370 | elif ope == "-%": |
---|
371 | masked = np.ma.masked_where(all_var[k] == 0,all_var[k]) |
---|
372 | masked.set_fill_value([np.NaN]) |
---|
373 | all_var[k+1]= 100.*(all_var[k-1] - masked)/masked |
---|
374 | all_varname[k+1] = all_varname[k] ; all_time[k+1] = all_time[k] ; all_namefile[k+1] = all_namefile[k] ; all_var2[k+1] = all_var2[k] ; numplot = numplot+2 |
---|
375 | if winds: all_windu[k+1] = all_windu[k-1]-all_windu[k] ; all_windv[k+1] = all_windv[k-1] - all_windv[k] |
---|
376 | elif ope in ["cat"]: |
---|
377 | tabtime = all_time[0];tab = all_var[0];k = 1 |
---|
378 | if var2: tab2 = all_var2[0] |
---|
379 | while k != len(namefiles) and len(all_time[k]) != 0: |
---|
380 | if var2: tab2 = np.append(tab2,all_var2[k],axis=0) |
---|
381 | tabtime = np.append(tabtime,all_time[k]) ; tab = np.append(tab,all_var[k],axis=0) ; k += 1 |
---|
382 | all_time[0] = np.array(tabtime) ; all_var[0] = np.array(tab) ; numplot = 1 |
---|
383 | if var2: all_var2[0] = np.array(tab2) |
---|
384 | else: errormess(ope+" : non-implemented operation. Check pp.py --help") |
---|
385 | else: |
---|
386 | if len(namefiles) > 1: errormess("for this operation... please set only one file !") |
---|
387 | if len(var) > 2: errormess("not sure this works for more than 2 vars... please check.") |
---|
388 | if "div_var" in ope: all_var[k] = all_var[k-2] / all_var[k-1] ; insert = '_div_' |
---|
389 | elif "mul_var" in ope: all_var[k] = all_var[k-2] * all_var[k-1] ; insert = '_mul_' |
---|
390 | elif "add_var" in ope: all_var[k] = all_var[k-2] + all_var[k-1] ; insert = '_add_' |
---|
391 | elif "sub_var" in ope: all_var[k] = all_var[k-2] - all_var[k-1] ; insert = '_sub_' |
---|
392 | else: errormess(ope+" : non-implemented operation. Check pp.py --help") |
---|
393 | numplot = numplot + 1 ; all_time[k] = all_time[k-1] ; all_namefile[k] = all_namefile[k-1] |
---|
394 | all_varname[k] = all_varname[k-2] + insert + all_varname[k-1] |
---|
395 | ### only the operation plot |
---|
396 | if "only" in ope: |
---|
397 | numplot = 1 ; all_var[0] = all_var[k] |
---|
398 | all_time[0] = all_time[k] ; all_namefile[0] = all_namefile[k] |
---|
399 | all_varname[0] = all_varname[k-2] + insert + all_varname[k-1] |
---|
400 | |
---|
401 | |
---|
402 | ################################## |
---|
403 | ### Open a figure and set subplots |
---|
404 | fig = figure() |
---|
405 | subv,subh = definesubplot( numplot, fig ) |
---|
406 | if ope in ['-','-%']: subv,subh = 2,2 |
---|
407 | |
---|
408 | ################################# |
---|
409 | ### Time loop for plotting device |
---|
410 | nplot = 1 ; error = False |
---|
411 | if lstyle is not None: linecycler = cycle(lstyle) |
---|
412 | else: linecycler = cycle(["-","--","-.",":"]) |
---|
413 | print "********************************************" |
---|
414 | while error is False: |
---|
415 | |
---|
416 | print "********** NPLOT", nplot |
---|
417 | if nplot > numplot: break |
---|
418 | |
---|
419 | #################################################################### |
---|
420 | ## get all indexes to be taken into account for this subplot and then reduce field |
---|
421 | ## We plot 1) all lon slices 2) all lat slices 3) all vert slices 4) all time slices and then go to the next slice |
---|
422 | indexlon = getsindex(sslon,(nplot-1)%nlon,lon) |
---|
423 | indexlat = getsindex(sslat,((nplot-1)//nlon)%nlat,lat) |
---|
424 | indexvert = getsindex(svert,((nplot-1)//(nlon*nlat))%nvert,vert) |
---|
425 | if ope is not None: |
---|
426 | if fileref is not None: index_f = ((nplot-1)//(nlon*nlat*nvert*ntime))%(len(namefiles)+2) ## OK only 1 var, see test in the beginning |
---|
427 | elif "var" in ope: index_f = ((nplot-1)//(nlon*nlat*nvert*ntime))%(len(var)+1) ## OK only 1 file, see test in the beginning |
---|
428 | elif "cat" in ope: index_f = 0 |
---|
429 | else: yeah = len(namefiles)*len(var) ; index_f = ((nplot-1)//(nlon*nlat*nvert*ntime))%yeah |
---|
430 | time = all_time[index_f] |
---|
431 | if mrate is not None: indextime = None |
---|
432 | else: indextime = getsindex(stime,((nplot-1)//(nlon*nlat*nvert))%ntime,time) |
---|
433 | ltst = None |
---|
434 | if typefile in ['meso'] and indextime is not None: ltst = localtime ( interv[0]+indextime*interv[1], 0.5*(wlon[0]+wlon[1]) ) |
---|
435 | print "********** INDEX LON:",indexlon," LAT:",indexlat," VERT:",indexvert," TIME:",indextime |
---|
436 | ##var = nc.variables["phisinit"][:,:] |
---|
437 | ##contourf(np.transpose(var),30,cmap = get_cmap(name="Greys_r") ) ; axis('off') ; plot(indexlat,indexlon,'mx',mew=4.0,ms=20.0) |
---|
438 | ##show() |
---|
439 | ##exit() |
---|
440 | #truc = True |
---|
441 | #truc = False |
---|
442 | #if truc: indexvert = None |
---|
443 | #################################################################### |
---|
444 | ########## REDUCE FIELDS |
---|
445 | #################################################################### |
---|
446 | error = False |
---|
447 | varname = all_varname[index_f] |
---|
448 | if varname: ### what is shaded. |
---|
449 | what_I_plot, error = reducefield( all_var[index_f], d4=indextime, d1=indexlon, d2=indexlat, d3=indexvert, \ |
---|
450 | yint=yintegral, alt=vert, anomaly=anomaly, redope=redope, mesharea=area, unidim=is1d) |
---|
451 | if mult != 2718.: what_I_plot = what_I_plot*mult |
---|
452 | else: what_I_plot = np.log10(what_I_plot) ; print "log plot" |
---|
453 | |
---|
454 | if var2: ### what is contoured. |
---|
455 | what_I_plot_contour, error = reducefield( all_var2[index_f], d4=indextime, d1=indexlon, d2=indexlat , d3=indexvert, \ |
---|
456 | yint=yintegral, alt=vert ) |
---|
457 | if winds: ### what is plot as vectors. |
---|
458 | vecx, error = reducefield( all_windu[index_f], d4=indextime, d3=indexvert, yint=yintegral, alt=vert) |
---|
459 | vecy, error = reducefield( all_windv[index_f], d4=indextime, d3=indexvert, yint=yintegral, alt=vert) |
---|
460 | if varname in [uchar,vchar]: what_I_plot = np.sqrt( np.square(vecx) + np.square(vecy) ) ; varname = "wind" |
---|
461 | |
---|
462 | ##################################################################### |
---|
463 | #if truc: |
---|
464 | # nx = what_I_plot.shape[2] ; ny = what_I_plot.shape[1] ; nz = what_I_plot.shape[0] |
---|
465 | # for k in range(nz): print k,' over ',nz ; what_I_plot[k,:,:] = what_I_plot[k,:,:] / smooth(what_I_plot[k,:,:],12) |
---|
466 | # for iii in range(nx): |
---|
467 | # for jjj in range(ny): |
---|
468 | # deviation = what_I_plot[:,jjj,iii] ; mx = max(deviation) ; mn = min(deviation) |
---|
469 | # if iii > 6 and iii < nx-6 and jjj > 6 and jjj < ny-6: what_I_plot[0,jjj,iii],rel = singlet(deviation,vert/1000.) ### z must be in km |
---|
470 | # else: what_I_plot[0,jjj,iii] = 0. |
---|
471 | # if np.abs(what_I_plot[0,jjj,iii]) > 1.5: |
---|
472 | # print iii,jjj,what_I_plot[0,jjj,iii],int(abs(1.-mx)*100.),int(abs(1.-mn)*100.) |
---|
473 | # plot(rel) |
---|
474 | # show() |
---|
475 | # anomaly = True ### pour avoir les bons reglages plots |
---|
476 | # what_I_plot = what_I_plot[0,:,:] |
---|
477 | ##################################################################### |
---|
478 | |
---|
479 | #################################################################### |
---|
480 | ### General plot settings |
---|
481 | changesubplot = (numplot > 1) and (len(what_I_plot.shape) != 1) ## default for 1D plots: superimposed. to be reworked for better flexibility. |
---|
482 | if changesubplot: subplot(subv,subh,nplot) #; subplots_adjust(wspace=0,hspace=0) |
---|
483 | #################################################################### |
---|
484 | if error: |
---|
485 | errormess("There is an error in reducing field !") |
---|
486 | else: |
---|
487 | ticks = ndiv + 1 |
---|
488 | fvar = varname |
---|
489 | if anomaly: fvar = 'anomaly' |
---|
490 | ### |
---|
491 | if mapmode == 0: ### could this be moved inside imov loop ? |
---|
492 | itime=indextime |
---|
493 | if len(what_I_plot.shape) == 3: itime=[0] |
---|
494 | m = None ; x = None ; y = None |
---|
495 | latyeah = lat ; lonyeah = lon |
---|
496 | if typefile in ['meso']: |
---|
497 | # now that the section is determined we can set the real lat |
---|
498 | # ... or for now, a temptative one. |
---|
499 | if slon is not None: latyeah = lat2d[:,0] |
---|
500 | if slat is not None: lonyeah = lon2d[0,:] |
---|
501 | what_I_plot, x, y = define_axis(lonyeah,latyeah,vert,time,indexlon,indexlat,indexvert,\ |
---|
502 | itime,what_I_plot, len(all_var[index_f].shape),vertmode) |
---|
503 | ### |
---|
504 | if (fileref is not None) and (index_f == numplot-1): zevmin, zevmax = calculate_bounds(what_I_plot,vmin=minop,vmax=maxop) |
---|
505 | else: zevmin, zevmax = calculate_bounds(what_I_plot,vmin=vmin,vmax=vmax) |
---|
506 | if (fileref is not None) and (index_f == numplot-1): colorb = "RdBu_r" |
---|
507 | if colorb in ["def","nobar","onebar"]: palette = get_cmap(name=defcolorb(fvar.upper())) |
---|
508 | else: palette = get_cmap(name=colorb) |
---|
509 | #palette = cm.GMT_split |
---|
510 | ##### 1. ELIMINATE 0D or >3D CASES |
---|
511 | if len(what_I_plot.shape) == 0: |
---|
512 | print "VALUE VALUE VALUE VALUE ::: ",what_I_plot |
---|
513 | save = 'donothing' |
---|
514 | elif len(what_I_plot.shape) >= 4: |
---|
515 | print "WARNING!!! ",len(what_I_plot.shape),"-D PLOT NOT SUPPORTED !!! dimensions: ",what_I_plot.shape |
---|
516 | errormess("Are you sure you did not forget to prescribe a dimension ?") |
---|
517 | ##### 2. HANDLE simple 1D/2D field and movies of 1D/2D fields |
---|
518 | else: |
---|
519 | if mrate is not None: iend=len(time)-1 |
---|
520 | else: iend=0 |
---|
521 | imov = 0 |
---|
522 | if len(what_I_plot.shape) == 3: |
---|
523 | if var2: which = "contour" ## have to start with contours rather than shading |
---|
524 | else: which = "regular" |
---|
525 | if mrate is None: errormess("3D field. Use --rate RATE for movie or specify --time TIME. Exit.") |
---|
526 | elif len(what_I_plot.shape) == 2: |
---|
527 | if var2: which = "contour" ## have to start with contours rather than shading |
---|
528 | else: which = "regular" |
---|
529 | if mrate is not None: which = "unidim" |
---|
530 | elif len(what_I_plot.shape) == 1: |
---|
531 | which = "unidim" |
---|
532 | if what_I_plot.shape[-1] == 1: print "VALUE VALUE VALUE VALUE ::: ", what_I_plot[0] ; save = 'donothing' |
---|
533 | ##### IMOV LOOP #### IMOV LOOP |
---|
534 | while imov <= iend: |
---|
535 | print "-> frame ",imov+1, which |
---|
536 | if which == "regular": |
---|
537 | if mrate is None: what_I_plot_frame = what_I_plot |
---|
538 | else: what_I_plot_frame = what_I_plot[imov,:,:] |
---|
539 | if winds: |
---|
540 | if mrate is None: vecx_frame = vecx ; vecy_frame = vecy |
---|
541 | else: vecx_frame = vecx[imov,:,:] ; vecy_frame = vecy[imov,:,:] |
---|
542 | elif which == "contour": |
---|
543 | if mrate is None or what_I_plot_contour.ndim < 3: what_I_plot_frame = what_I_plot_contour |
---|
544 | else: what_I_plot_frame = what_I_plot_contour[imov,:,:] |
---|
545 | elif which == "unidim": |
---|
546 | if mrate is None: what_I_plot_frame = what_I_plot |
---|
547 | else: what_I_plot_frame = what_I_plot[:,imov] ## because swapaxes |
---|
548 | #if mrate is not None: |
---|
549 | if mapmode == 1: |
---|
550 | m = define_proj(proj,wlon,wlat,back=back,blat=blat,blon=blon) ## this is dirty, defined above but out of imov loop |
---|
551 | x, y = m(lon2d, lat2d) ## this is dirty, defined above but out of imov loop |
---|
552 | if typefile in ['meso'] and mapmode == 1: what_I_plot_frame = dumpbdy(what_I_plot_frame,6,condition=True) |
---|
553 | # if typefile in ['mesoideal']: what_I_plot_frame = dumpbdy(what_I_plot_frame,0,stag='W',condition=dumped_vert_stag) |
---|
554 | |
---|
555 | if which == "unidim": |
---|
556 | if lbls is not None: lbl=lbls[nplot-1] |
---|
557 | else: |
---|
558 | lbl = "" |
---|
559 | if indexlat is not None: lbl = lbl + " ix" + str(indexlat[0]) |
---|
560 | if indexlon is not None: lbl = lbl + " iy" + str(indexlon[0]) |
---|
561 | if indexvert is not None: lbl = lbl + " iz" + str(indexvert[0]) |
---|
562 | if indextime is not None: lbl = lbl + " it" + str(indextime[0]) |
---|
563 | if lbl == "": lbl = all_namefile[index_f] |
---|
564 | |
---|
565 | if mrate is not None: x = y ## because swapaxes... |
---|
566 | #what_I_plot_frame = np.diff(what_I_plot_frame, n=1) ; x = x[1:] |
---|
567 | |
---|
568 | zeline = next(linecycler) ## "-" for simple lines |
---|
569 | if tile: zemarker = 'x' |
---|
570 | else: zemarker = None |
---|
571 | this_is_a_regular_plot = (indexvert is not None) or (indextime is None) or (indexlat is None) or (indexlon is None) |
---|
572 | if this_is_a_regular_plot: plot(x,what_I_plot_frame,zeline,label=lbl,marker=zemarker) ## vertical profile |
---|
573 | else: plot(what_I_plot_frame,x,zeline,label=lbl,marker=zemarker) ## regular plot |
---|
574 | if nplot > 1: legend(loc='best') |
---|
575 | if indextime is None and axtime is not None and xlab is None: xlabel(axtime.upper()) ## define the right label |
---|
576 | if save == 'txt': writeascii(np.transpose([x,np.transpose(what_I_plot)]),'profile'+str(nplot*1000+imov)+'.txt') |
---|
577 | |
---|
578 | elif which == "regular": |
---|
579 | |
---|
580 | # plot stream lines if there is a stream file and a vert/lat slice. Might not work with movies ?? |
---|
581 | if streamflag and sslat is None and svert is None: |
---|
582 | streamfile = all_namefile[index_f].replace('.nc','_stream.nc') |
---|
583 | teststream = os.path.exists(streamfile) |
---|
584 | if teststream: |
---|
585 | print 'INFO: Using stream file',streamfile, 'for stream lines' |
---|
586 | ncstream = Dataset(streamfile) |
---|
587 | psi = getfield(ncstream,'psi') |
---|
588 | psi = psi[0,:,:,0] # time and longitude are dummy dimensions |
---|
589 | if psi.shape[1] != len(x) or psi.shape[0] != len(y): |
---|
590 | errormess('stream file does not fit! Dimensions: '+str(psi.shape)+' '+str(x.shape)+' '+str(y.shape)) |
---|
591 | zelevels = np.arange(-1.e10,1.e10,1.e9) |
---|
592 | zemin = np.min(abs(zelevels)) |
---|
593 | zemax = np.max(abs(zelevels)) |
---|
594 | zewidth = (abs(zelevels)-zemin)*(5.- 0.5)/(zemax - zemin) + 0.5 # linewidth ranges from 5 to 0.5 |
---|
595 | cs = contour( x,y,psi, zelevels, colors='k', linewidths = zewidth) |
---|
596 | clabel(cs, inline=True, fontsize = 4.*rcParams['font.size']/5., fmt="%1.1e") |
---|
597 | else: |
---|
598 | print 'WARNING: STREAM FILE',streamfile, 'DOES NOT EXIST !' |
---|
599 | |
---|
600 | if hole: what_I_plot_frame = hole_bounds(what_I_plot_frame,zevmin,zevmax) |
---|
601 | else: what_I_plot_frame = bounds(what_I_plot_frame,zevmin,zevmax) |
---|
602 | if flagnolow: what_I_plot_frame = nolow(what_I_plot_frame) |
---|
603 | if not tile: |
---|
604 | #zelevels = np.linspace(zevmin*(1. + 1.e-7),zevmax*(1. - 1.e-7)) #,num=20) |
---|
605 | zelevels = np.linspace(zevmin,zevmax,num=ticks) |
---|
606 | #what_I_plot_frame = smooth(what_I_plot_frame,100) |
---|
607 | if mapmode == 1: m.contourf( x, y, what_I_plot_frame, zelevels, cmap = palette, alpha=trans) |
---|
608 | elif mapmode == 0: contourf( x, y, what_I_plot_frame, zelevels, cmap = palette, alpha=trans) |
---|
609 | if cross is not None and mapmode == 1: |
---|
610 | idx,idy=m(cross[0][0],cross[0][1]) |
---|
611 | mpl.pyplot.plot([idx],[idy],'+k',mew=0.5,ms=18) |
---|
612 | else: |
---|
613 | if mapmode == 1: m.pcolor( x, y, what_I_plot_frame, cmap = palette, vmin=zevmin, vmax=zevmax, alpha=trans) |
---|
614 | elif mapmode == 0: pcolor( x, y, what_I_plot_frame, cmap = palette, vmin=zevmin, vmax=zevmax, alpha=trans) |
---|
615 | |
---|
616 | |
---|
617 | if colorb not in ['nobar','onebar']: |
---|
618 | if (fileref is not None) and (index_f == numplot-1): daformat = "%.3f" |
---|
619 | elif mult != 1: daformat = "%.1f" |
---|
620 | else: daformat = fmtvar(fvar.upper()) |
---|
621 | #if proj in ['moll','cyl']: zeorientation="horizontal" ; zepad = 0.05 |
---|
622 | if proj in ['moll']: zeorientation="horizontal" ; zepad = 0.05 |
---|
623 | else: zeorientation="vertical" ; zepad = 0.03 |
---|
624 | zecb = colorbar( fraction=0.05,pad=zepad,format=daformat,orientation=zeorientation,\ |
---|
625 | ticks=np.linspace(zevmin,zevmax,num=min([ticks/2+1,21])),extend='neither',spacing='proportional' ) |
---|
626 | if zeorientation == "horizontal" and zetitle[0] != "fill": zecb.ax.set_xlabel(zetitle[index_f]) ; zetitle[index_f]="" |
---|
627 | if winds: |
---|
628 | if typefile in ['meso']: |
---|
629 | [vecx_frame,vecy_frame] = [dumpbdy(vecx_frame,6,stag=uchar,condition=True), dumpbdy(vecy_frame,6,stag=vchar,condition=True)] |
---|
630 | key = True |
---|
631 | if fvar in ['UV','uv','uvmet']: key = False |
---|
632 | elif typefile in ['gcm']: |
---|
633 | key = False |
---|
634 | if metwind and mapmode == 1: [vecx_frame,vecy_frame] = m.rotate_vector(vecx_frame, vecy_frame, lon2d, lat2d) |
---|
635 | if trans != 0.0: colorvec = definecolorvec(colorb) |
---|
636 | else: colorvec = definecolorvec(back) |
---|
637 | vectorfield(vecx_frame, vecy_frame, x, y, stride=stride, csmooth=2,\ |
---|
638 | #scale=15., factor=300., color=colorvec, key=key) |
---|
639 | scale=20., factor=250./facwind, color=colorvec, key=key) |
---|
640 | #200. ## or csmooth=stride |
---|
641 | ### THIS IS A QUITE SPECIFIC PIECE (does not work for mesoscale files) |
---|
642 | if ope == '-' and nplot == numplot: # this should work as long as ope is '-' guarantees 3 plots for 4 panels without contour |
---|
643 | subplot(subv,subh,nplot+1) |
---|
644 | rcParams["legend.fontsize"] = 'xx-large' |
---|
645 | if indexlat is None: |
---|
646 | latmin = -50.; latmax = 50. # latitude range for histogram of difference |
---|
647 | zeindexlat = (lat<latmax)*(lat>latmin) |
---|
648 | if typefile in ['meso']: zeindexlat = 10 |
---|
649 | # this follows the define_axis logic in myplot.py: |
---|
650 | if indextime is None or indexlon is None: what_I_plot_frame = what_I_plot_frame[zeindexlat,:] |
---|
651 | else: what_I_plot_frame = what_I_plot_frame[:,zeindexlat] |
---|
652 | toplot = np.ravel(what_I_plot_frame[np.isnan(what_I_plot_frame)==False]) |
---|
653 | zebins = np.linspace(zevmin,zevmax,num=30) |
---|
654 | hist(toplot,bins=zebins,histtype='step',linewidth=2,color='k',normed=True) |
---|
655 | zestd = np.std(toplot);zemean = np.mean(toplot) |
---|
656 | zebins = np.linspace(zevmin,zevmax,num=300) |
---|
657 | zegauss = (1./(zestd * np.sqrt(2 * np.pi)) * np.exp( - (zebins - zemean)**2 / (2 * zestd**2) ) ) |
---|
658 | plot(zebins, zegauss, linewidth=1, color='r',label="mean: "+str(zemean)[0:5]+"\nstd: "+str(zestd)[0:5]) |
---|
659 | legend(loc=0,frameon=False) |
---|
660 | title("Histogram fig(1) "+ope+" fig(2)") |
---|
661 | subplot(subv,subh,nplot) # go back to last plot for title of contour difference |
---|
662 | |
---|
663 | elif which == "contour": |
---|
664 | zevminc, zevmaxc = calculate_bounds(what_I_plot_frame, vmin=min(what_I_plot_frame), vmax=max(what_I_plot_frame)) |
---|
665 | zelevels = np.linspace(zevminc,zevmaxc,ticks/2) #20) |
---|
666 | ### another dirty specific stuff in the wall |
---|
667 | if var2 == 'HGT': zelevels = np.arange(-10000.,30000.,500.) #1000.) |
---|
668 | elif var2 == 'tpot': zelevels = np.arange(270,370,5) |
---|
669 | elif var2 == 'tk': zelevels = np.arange(150,250,5) |
---|
670 | elif var2 == 'wstar': zelevels = np.arange(0,10,1.0) |
---|
671 | elif var2 == 'zmax_th': zelevels = np.arange(0,10,2.0) ; what_I_plot_frame = what_I_plot_frame / 1000. |
---|
672 | ### |
---|
673 | if mapmode == 0: |
---|
674 | what_I_plot_frame, x, y = define_axis( lonyeah,latyeah,vert,time,indexlon,indexlat,indexvert,\ |
---|
675 | itime,what_I_plot_frame, len(all_var2[index_f].shape),vertmode ) |
---|
676 | ## is this needed? only if len(all_var2[index_f].shape) != len(all_var[index_f].shape) |
---|
677 | cs = contour( x,y,what_I_plot_frame, zelevels, colors='k', linewidths = 0.33)#, alpha=0.5, linestyles='solid') |
---|
678 | #cs = contour( x,y,what_I_plot_frame, zelevels, colors='w', linewidths = 0.5)#, alpha=0.5, linestyles='solid') |
---|
679 | clabel(cs, inline=1, fontsize = 4.*rcParams['font.size']/5., fmt=fmtvar(var2.upper())) |
---|
680 | elif mapmode == 1: |
---|
681 | cs = m.contour( x,y,what_I_plot_frame, zelevels, colors='k', linewidths = 0.33)#, alpha=0.5, linestyles='solid') |
---|
682 | #clabel(cs, inline=0, fontsize = rcParams['font.size'], fmt="%.0f") #fmtvar(var2.upper())) |
---|
683 | if which in ["regular","unidim"]: |
---|
684 | |
---|
685 | if nplot > 1 and which == "unidim": |
---|
686 | pass ## because we superimpose nplot instances |
---|
687 | else: |
---|
688 | # Axis directives for movie frames [including the first one). |
---|
689 | zxmin, zxmax = xaxis ; zymin, zymax = yaxis |
---|
690 | if zxmin is not None: mpl.pyplot.xlim(xmin=zxmin) |
---|
691 | if zxmax is not None: mpl.pyplot.xlim(xmax=zxmax) |
---|
692 | if zymin is not None: mpl.pyplot.ylim(ymin=zymin) |
---|
693 | if zymax is not None: mpl.pyplot.ylim(ymax=zymax) |
---|
694 | if ylog: mpl.pyplot.semilogy() |
---|
695 | if invert_y: ax = mpl.pyplot.gca() ; ax.set_ylim(ax.get_ylim()[::-1]) |
---|
696 | if xlab is not None: xlabel(xlab) |
---|
697 | if ylab is not None: ylabel(ylab) |
---|
698 | |
---|
699 | if mrate is not None: |
---|
700 | ### THIS IS A MENCODER MOVIE |
---|
701 | if mrate > 0: |
---|
702 | figframe=mpl.pyplot.gcf() |
---|
703 | if mquality: figframe.set_dpi(600.) |
---|
704 | else: figframe.set_dpi(200.) |
---|
705 | mframe=fig2img(figframe) |
---|
706 | if imov == 0: |
---|
707 | moviename='movie' ;W,H = figframe.canvas.get_width_height() |
---|
708 | video = VideoSink((H,W), moviename, rate=mrate, byteorder="rgba") |
---|
709 | video.run(mframe) ; close() |
---|
710 | if imov == iend: video.close() |
---|
711 | ### THIS IS A WEBPAGE MOVIE |
---|
712 | else: |
---|
713 | nameframe = "image"+str(1000+imov) |
---|
714 | makeplotres(nameframe,res=100.,disp=False) ; close() |
---|
715 | if imov == 0: myfile = open("zepics", 'w') |
---|
716 | myfile.write("modImages["+str(imov)+"] = '"+nameframe+"_100.png';"+ '\n') |
---|
717 | if imov == iend: |
---|
718 | myfile.write("first_image = 0;"+ '\n') |
---|
719 | myfile.write("last_image = "+str(iend)+";"+ '\n') |
---|
720 | myfile.close() |
---|
721 | if var2 and which == "regular": which = "contour" |
---|
722 | imov = imov+1 |
---|
723 | elif which == "contour": |
---|
724 | which = "regular" |
---|
725 | |
---|
726 | ### Next subplot |
---|
727 | zevarname = varname |
---|
728 | if redope is not None: zevarname = zevarname + "_" + redope |
---|
729 | basename = getname(var=zevarname,var2=var2,winds=winds,anomaly=anomaly) |
---|
730 | if len(what_I_plot.shape) > 3: |
---|
731 | basename = basename + getstralt(nc,level) |
---|
732 | if mrate is not None: basename = "movie_" + basename |
---|
733 | if typefile in ['meso']: |
---|
734 | if sslon is not None: basename = basename + "_lon_" + str(int(round(lonp))) |
---|
735 | if sslat is not None: basename = basename + "_lat_" + str(int(round(latp))) |
---|
736 | plottitle = basename |
---|
737 | ### dans le nouveau systeme time=ls,sol,lt cette ligne pourrait ne servir a rien (ou deplacer au dessus) |
---|
738 | if addchar and indextime is not None: [addchar,gogol,gogol2] = getlschar ( all_namefile[index_f] ) ; plottitle = plottitle + addchar |
---|
739 | ### en fait redope is None doit etre remplace par : n'est ni maxt ni mint |
---|
740 | if redope is None and ltst is not None and ( (mapmode == 0) or (proj in ["lcc","laea","merc","nsper"]) ): plottitle = plottitle + "_LT" + str(ltst) |
---|
741 | else: |
---|
742 | if fileref is not None: |
---|
743 | if index_f is numplot-1: plottitle = basename+' '+"fig(1) "+ope+" fig(2)" |
---|
744 | elif index_f is numplot-2: plottitle = basename+' '+fileref |
---|
745 | else: plottitle = basename+' '+all_namefile[index_f] |
---|
746 | else: plottitle = basename+' '+all_namefile[index_f] |
---|
747 | if mult != 1: plottitle = '{:.0e}'.format(mult) + "*" + plottitle |
---|
748 | if zetitle[0] != "fill": |
---|
749 | if index_f < len(zetitle): plottitle = zetitle[index_f] |
---|
750 | else: plottitle = zetitle[0] |
---|
751 | if titleref is "fill": titleref=zetitle[index_f] |
---|
752 | if fileref is not None: |
---|
753 | if index_f is numplot-2: plottitle = titleref |
---|
754 | if index_f is numplot-1: plottitle = "fig(1) "+ope+" fig(2)" |
---|
755 | # if indexlon is not None: plottitle = plottitle + " lon: " + str(min(lon[indexlon])) +" "+ str(max(lon[indexlon])) |
---|
756 | # if indexlat is not None: plottitle = plottitle + " lat: " + str(min(lat[indexlat])) +" "+ str(max(lat[indexlat])) |
---|
757 | # if indexvert is not None: plottitle = plottitle + " vert: " + str(min(vert[indexvert])) +" "+ str(max(vert[indexvert])) |
---|
758 | # if indextime is not None: plottitle = plottitle + " time: " + str(min(time[indextime])) +" "+ str(max(time[indextime])) |
---|
759 | if colorb != "onebar": title( plottitle ) |
---|
760 | if nplot >= numplot: error = True |
---|
761 | nplot += 1 |
---|
762 | |
---|
763 | if colorb == "onebar": |
---|
764 | cax = axes([0.1, 0.2, 0.8, 0.03]) # a ameliorer |
---|
765 | zecb = colorbar(cax=cax, orientation="horizontal", format=fmtvar(fvar.upper()),\ |
---|
766 | ticks=np.linspace(zevmin,zevmax,num=min([ticks/2+1,21])),extend='neither',spacing='proportional') |
---|
767 | if zetitle[0] != "fill": zecb.ax.set_xlabel(zetitle[index_f]) ; zetitle[index_f]="" |
---|
768 | |
---|
769 | |
---|
770 | ########################################################################## |
---|
771 | ### Save the figure in a file in the data folder or an user-defined folder |
---|
772 | if outputname is None: |
---|
773 | if typefile in ['meso']: prefix = getprefix(nc) |
---|
774 | elif typefile in ['gcm']: prefix = 'LMD_GCM_' |
---|
775 | else: prefix = '' |
---|
776 | ### |
---|
777 | zeplot = prefix + basename |
---|
778 | if zoom: zeplot = zeplot + "zoom"+str(abs(zoom)) |
---|
779 | if addchar: zeplot = zeplot + addchar |
---|
780 | if numplot <= 0: zeplot = zeplot + "_LT"+str(abs(numplot)) |
---|
781 | ### |
---|
782 | if not target: zeplot = namefile[0:find(namefile,'wrfout')] + zeplot |
---|
783 | else: zeplot = target + "/" + zeplot |
---|
784 | ### |
---|
785 | else: |
---|
786 | zeplot=outputname |
---|
787 | |
---|
788 | if mrate is None: |
---|
789 | pad_inches_value = 0.35 |
---|
790 | print "********** SAVE ", save |
---|
791 | if save == 'png': |
---|
792 | if display: makeplotres(zeplot,res=100.,pad_inches_value=pad_inches_value) #,erase=True) ## a miniature |
---|
793 | makeplotres(zeplot,res=resolution,pad_inches_value=pad_inches_value,disp=False) |
---|
794 | elif save in ['eps','svg','pdf']: makeplotres(zeplot,pad_inches_value=pad_inches_value,disp=False,ext=save) |
---|
795 | elif save == 'gui': show() |
---|
796 | elif save == 'donothing': pass |
---|
797 | elif save == 'txt': print "Saved results in txt file." |
---|
798 | else: |
---|
799 | print "INFO: save mode not supported. using gui instead." |
---|
800 | show() |
---|
801 | |
---|
802 | ################################### |
---|
803 | #### Getting more out of this video -- PROBLEMS WITH CREATED VIDEOS |
---|
804 | # |
---|
805 | #if mrate is not None: |
---|
806 | # print "Re-encoding movie.. first pass" |
---|
807 | # video.first_pass(filename=moviename,quality=mquality,rate=mrate) |
---|
808 | # print "Re-encoding movie.. second pass" |
---|
809 | # video.second_pass(filename=moviename,quality=mquality,rate=mrate) |
---|
810 | |
---|
811 | ############### |
---|
812 | ### Now the end |
---|
813 | return zeplot |
---|