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