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 | def planetoplot (namefiles,\ |
---|
13 | level=0,\ |
---|
14 | vertmode=0,\ |
---|
15 | proj=None,\ |
---|
16 | back=None,\ |
---|
17 | target=None, |
---|
18 | stride=3,\ |
---|
19 | var=None,\ |
---|
20 | colorb="def",\ |
---|
21 | winds=False,\ |
---|
22 | addchar=None,\ |
---|
23 | interv=[0,1],\ |
---|
24 | vmin=None,\ |
---|
25 | vmax=None,\ |
---|
26 | tile=False,\ |
---|
27 | zoom=None,\ |
---|
28 | display=True,\ |
---|
29 | hole=False,\ |
---|
30 | save="gui",\ |
---|
31 | anomaly=False,\ |
---|
32 | var2=None,\ |
---|
33 | ndiv=10,\ |
---|
34 | mult=1.,\ |
---|
35 | zetitle="fill",\ |
---|
36 | slon=None,\ |
---|
37 | slat=None,\ |
---|
38 | svert=None,\ |
---|
39 | stime=None,\ |
---|
40 | outputname=None,\ |
---|
41 | resolution=200,\ |
---|
42 | ope=None,\ |
---|
43 | fileref=None,\ |
---|
44 | minop=0.,\ |
---|
45 | maxop=0.,\ |
---|
46 | titleref="fill",\ |
---|
47 | invert_y=False,\ |
---|
48 | xaxis=[None,None],\ |
---|
49 | yaxis=[None,None],\ |
---|
50 | ylog=False,\ |
---|
51 | yintegral=False,\ |
---|
52 | blat=None,\ |
---|
53 | blon=None,\ |
---|
54 | tsat=False,\ |
---|
55 | flagnolow=False,\ |
---|
56 | mrate=None,\ |
---|
57 | mquality=False,\ |
---|
58 | trans=1,\ |
---|
59 | zarea=None,\ |
---|
60 | axtime=None,\ |
---|
61 | redope=None,\ |
---|
62 | seevar=False,\ |
---|
63 | xlab=None,\ |
---|
64 | ylab=None): |
---|
65 | |
---|
66 | #################################################################################################################### |
---|
67 | ### Colorbars http://www.scipy.org/Cookbook/Matplotlib/Show_colormaps?action=AttachFile&do=get&target=colormaps3.png |
---|
68 | |
---|
69 | ################################# |
---|
70 | ### Load librairies and functions |
---|
71 | from netCDF4 import Dataset |
---|
72 | from myplot import getcoord2d,define_proj,makeplotres,simplinterv,vectorfield,ptitle,latinterv,getproj,wrfinterv,dumpbdy,\ |
---|
73 | fmtvar,definecolorvec,defcolorb,getprefix,putpoints,calculate_bounds,errormess,definesubplot,\ |
---|
74 | zoomset,getcoorddef,getwinddef,whatkindfile,reducefield,bounds,getstralt,getfield,smooth,nolow,\ |
---|
75 | getname,localtime,polarinterv,getsindex,define_axis,determineplot,readslices,bidimfind,getlschar,hole_bounds |
---|
76 | from mymath import deg,max,min,mean,get_tsat,writeascii,fig2data,fig2img |
---|
77 | import matplotlib as mpl |
---|
78 | from matplotlib.pyplot import contour,contourf, subplot, figure, rcParams, savefig, colorbar, pcolor, show, plot, clabel, title, close, legend, xlabel, axis, ylabel, subplots_adjust, axes |
---|
79 | from matplotlib.cm import get_cmap |
---|
80 | #from mpl_toolkits.basemap import cm |
---|
81 | import numpy as np |
---|
82 | from numpy.core.defchararray import find |
---|
83 | from videosink import VideoSink |
---|
84 | import subprocess |
---|
85 | #from singlet import singlet |
---|
86 | |
---|
87 | ################################ |
---|
88 | ### Preliminary stuff |
---|
89 | ################################ |
---|
90 | print "********************************************" |
---|
91 | print "********** WELCOME TO PLANETOPLOT **********" |
---|
92 | print "********************************************" |
---|
93 | if not isinstance(namefiles, np.ndarray): namefiles = [namefiles] |
---|
94 | if not isinstance(var, np.ndarray): var = [var] |
---|
95 | initime=-1 |
---|
96 | |
---|
97 | ################################ |
---|
98 | ### Which plot needs to be done? |
---|
99 | ################################ |
---|
100 | nlon, nlat, nvert, ntime, mapmode, nslices = determineplot(slon, slat, svert, stime) |
---|
101 | if mrate is not None and len(var) > 1: errormess("multivar not allowed in movies. should be fixed soon!") |
---|
102 | zelen = len(namefiles)*len(var) |
---|
103 | numplot = zelen*nslices |
---|
104 | print "********** FILES, SLICES, VARS, TOTAL PLOTS: ", len(namefiles), nslices, len(var), numplot |
---|
105 | if ope is not None: |
---|
106 | if fileref is not None: zelen = zelen + 2 |
---|
107 | elif "var" in ope: zelen = zelen + 1 |
---|
108 | all_var = [[]]*zelen ; all_var2 = [[]]*zelen ; all_title = [[]]*zelen ; all_varname = [[]]*zelen ; all_namefile = [[]]*zelen ; all_time = [[]]*zelen ; all_windu = [[]]*zelen ; all_windv = [[]]*zelen |
---|
109 | |
---|
110 | ################################################################################################# |
---|
111 | ### Loop over the files + vars initially separated by commas to be plotted on the same figure ### |
---|
112 | ################################################################################################# |
---|
113 | k = 0 ; firstfile = True ; count = 0 |
---|
114 | for nnn in range(len(namefiles)): |
---|
115 | for vvv in range(len(var)): |
---|
116 | |
---|
117 | ###################### |
---|
118 | ### Load NETCDF object |
---|
119 | namefile = namefiles[nnn] |
---|
120 | nc = Dataset(namefile) |
---|
121 | varinfile = nc.variables.keys() |
---|
122 | if seevar: print varinfile ; exit() |
---|
123 | |
---|
124 | ################################## |
---|
125 | ### Initial checks and definitions |
---|
126 | ### ... TYPEFILE |
---|
127 | typefile = whatkindfile(nc) |
---|
128 | if typefile in ['mesoideal']: mapmode=0 |
---|
129 | elif typefile in ['gcm'] and len(nc.variables["longitude"][:]) is 1 and len(nc.variables["latitude"][:]) is 1: mapmode=0 |
---|
130 | elif typefile in ['earthgcm'] and len(nc.variables["lon"][:]) is 1 and len(nc.variables["lat"][:]) is 1: mapmode=0 |
---|
131 | if mapmode == 0: winds=False |
---|
132 | elif mapmode == 1 and redope is None: |
---|
133 | if svert is None: svert = readslices(str(level)) ; nvert=1 |
---|
134 | if stime is None and mrate is None: |
---|
135 | stime = readslices(str(0)) ; ntime=1 ## this is a default choice |
---|
136 | print "WELL... nothing about time axis. I took default: first time reference stored in file." |
---|
137 | |
---|
138 | if firstfile: print "********** MAPMODE: ", mapmode |
---|
139 | if firstfile: typefile0 = typefile |
---|
140 | elif typefile != typefile0: errormess("Not the same kind of files !", [typefile0, typefile]) |
---|
141 | ### ... VAR |
---|
142 | varname=var[vvv] |
---|
143 | if varname not in nc.variables: |
---|
144 | if len(varinfile) == 1: varname = varinfile[0] |
---|
145 | else: varname = False |
---|
146 | ### ... WINDS |
---|
147 | if winds: |
---|
148 | [uchar,vchar,metwind] = getwinddef(nc) |
---|
149 | if uchar == 'not found': winds = False |
---|
150 | if not varname and not winds: errormess("please set at least winds or var",printvar=nc.variables) |
---|
151 | ### ... COORDINATES, could be moved below |
---|
152 | [lon2d,lat2d] = getcoorddef(nc) |
---|
153 | ### ... PROJECTION |
---|
154 | if ((proj == None) and (typefile not in ['mesoideal'])): proj = getproj(nc) |
---|
155 | |
---|
156 | if firstfile: |
---|
157 | ########################## |
---|
158 | ### Define plot boundaries |
---|
159 | ### todo: possible areas in latinterv in argument (ex: "Far_South_Pole") |
---|
160 | if proj in ["npstere","spstere"]: [wlon,wlat] = polarinterv(lon2d,lat2d) |
---|
161 | elif proj in ["lcc","laea"]: [wlon,wlat] = wrfinterv(lon2d,lat2d) |
---|
162 | else: [wlon,wlat] = simplinterv(lon2d,lat2d) |
---|
163 | if zoom: [wlon,wlat] = zoomset(wlon,wlat,zoom) |
---|
164 | elif zarea is not None: [wlon,wlat] = latinterv(area=zarea) |
---|
165 | |
---|
166 | ########################################################## |
---|
167 | ############ LOAD 4D DIMENSIONS : x, y, z, t ############# |
---|
168 | ########################################################## |
---|
169 | if typefile in ["gcm","earthgcm"]: |
---|
170 | ### SPACE |
---|
171 | if typefile == "gcm": lat = nc.variables["latitude"][:] ; lon = nc.variables["longitude"][:] ; vert = nc.variables["altitude"][:] |
---|
172 | elif typefile == "earthgcm": lat = nc.variables["lat"][:] ; lon = nc.variables["lon"][:] ; vert = nc.variables["Alt"][:] |
---|
173 | if "aire" in nc.variables: area = nc.variables["aire"][:,:] #JL to weight means with the area |
---|
174 | else: area = None |
---|
175 | ### TIME |
---|
176 | if "Time" in nc.variables: time = nc.variables["Time"][:] |
---|
177 | elif "time" in nc.variables: time = nc.variables["time"][:] |
---|
178 | elif "time_counter" in nc.variables: time = nc.variables["time_counter"][:]/86400. #### time counter cinverstion from s-> days |
---|
179 | else: errormess("no time axis found.") |
---|
180 | if axtime in ["ls","sol"]: errormess("not supported. should not be too difficult though.") |
---|
181 | # for 1D plots (no need for longitude computation): |
---|
182 | if axtime in ["lt"]: |
---|
183 | if initime == -1: initime=input("Please type initial local time:") |
---|
184 | time = (initime+time*24)%24 |
---|
185 | print "LOCAL TIMES.... ", time |
---|
186 | elif typefile in ['meso','mesoapi','geo','mesoideal']: |
---|
187 | area = None ## not active for the moment |
---|
188 | ###### STUFF TO GET THE CORRECT LAT/LON FROM MESOSCALE FILES WITH 2D LAT/LON ARRAYS |
---|
189 | ###### principle: calculate correct indices then repopulate slon and slat |
---|
190 | if slon is not None or slat is not None: |
---|
191 | if firstfile and save == 'png' and typefile == 'meso': iwantawhereplot = nc #show a topo map with a cross on the chosen point |
---|
192 | else: iwantawhereplot = None #do not show anything, just select indices |
---|
193 | numlon = 1 ; numlat = 1 |
---|
194 | if slon is not None: numlon = slon.shape[0] |
---|
195 | if slat is not None: numlat = slat.shape[0] |
---|
196 | indices = np.ones([numlon,numlat,2]) ; vlon = None ; vlat = None |
---|
197 | for iii in range(numlon): |
---|
198 | for jjj in range(numlat): |
---|
199 | if slon is not None: vlon = slon[iii][0] ### note: slon[:][0] does not work |
---|
200 | if slat is not None: vlat = slat[jjj][0] ### note: slon[:][0] does not work |
---|
201 | indices[iii,jjj,:] = bidimfind(lon2d,lat2d,vlon,vlat,file=iwantawhereplot) |
---|
202 | lonp,latp = ( lon2d[indices[iii,jjj,0],indices[iii,jjj,1]] , lat2d[indices[iii,jjj,0],indices[iii,jjj,1]] ) |
---|
203 | #print vlon, lonp, vlat, latp |
---|
204 | for iii in range(numlon): |
---|
205 | for jjj in range(numlat): |
---|
206 | if slon is not None: slon[iii][0] = indices[iii,0,1] ; slon[iii][1] = indices[iii,0,1] #...this is idx |
---|
207 | if slat is not None: slat[jjj][0] = indices[0,jjj,0] ; slat[jjj][1] = indices[0,jjj,0] #...this is idy |
---|
208 | lonp,latp = ( lon2d[indices[0,0,0],indices[0,0,1]] , lat2d[indices[0,0,0],indices[0,0,1]] ) |
---|
209 | ###### |
---|
210 | if typefile in ['mesoapi','meso'] and mapmode == 1: lon2d = dumpbdy(lon2d,6) ; lat2d = dumpbdy(lat2d,6) ### important to do that now and not before |
---|
211 | ###### |
---|
212 | if varname in ['PHTOT','W']: vertdim='BOTTOM-TOP_PATCH_END_STAG' |
---|
213 | else: vertdim='BOTTOM-TOP_PATCH_END_UNSTAG' |
---|
214 | if (var2 is not None and var2 not in ['PHTOT','W']): dumped_vert_stag=True ; vertdim='BOTTOM-TOP_PATCH_END_UNSTAG' |
---|
215 | else: dumped_vert_stag=False |
---|
216 | if varname in ['V']: latdim='SOUTH-NORTH_PATCH_END_STAG' |
---|
217 | else: latdim='SOUTH-NORTH_PATCH_END_UNSTAG' |
---|
218 | if varname in ['U']: londim='WEST-EAST_PATCH_END_STAG' |
---|
219 | else: londim='WEST-EAST_PATCH_END_UNSTAG' |
---|
220 | lon = np.arange(0,getattr(nc,londim),1) ; lat = np.arange(0,getattr(nc,latdim),1) |
---|
221 | ### |
---|
222 | if axtime in ["ls","sol"]: |
---|
223 | lstab, soltab, lttab = getlschar ( namefile, getaxis = True ) |
---|
224 | if axtime == "ls": time = lstab |
---|
225 | elif axtime == "sol": time = soltab |
---|
226 | else: |
---|
227 | if "Times" in nc.variables: time = count + np.arange(0,len(nc.variables["Times"]),1) |
---|
228 | elif "Time" in nc.variables: time = count + np.arange(0,len(nc.variables["Time"]),1) |
---|
229 | else: time = count + np.arange(0,1,1) |
---|
230 | if nnn > 0: count = time[-1] + 1 ## so that a cat is possible with simple subscripts |
---|
231 | else: count = 0 |
---|
232 | if axtime in ["lt"]: |
---|
233 | for i in range(len(time)): time[i] = localtime ( interv[0]+time[i]*interv[1], 0.5*(wlon[0]+wlon[1]) ) |
---|
234 | print "LOCAL TIMES.... ", time |
---|
235 | ### |
---|
236 | if typefile in ['geo']: vert = [0.] ; stime = readslices(str(0)) |
---|
237 | else: |
---|
238 | if vertmode is None: vertmode=0 |
---|
239 | if vertmode == 0: vert = np.arange(0,getattr(nc,vertdim),1) |
---|
240 | else: vert = nc.variables["vert"][:] |
---|
241 | #if firstfile: |
---|
242 | # lat0 = lat |
---|
243 | #elif len(lat0) != len(lat): |
---|
244 | # errormess("Not the same latitude lengths !", [len(lat0), len(lat)]) |
---|
245 | #elif sum((lat == lat0) == False) != 0: |
---|
246 | # errormess("Not the same latitudes !", [lat,lat0]) |
---|
247 | ## Faire d'autre checks sur les compatibilites entre fichiers!! |
---|
248 | ########################################################## |
---|
249 | ########################################################## |
---|
250 | ########################################################## |
---|
251 | |
---|
252 | all_varname[k] = varname |
---|
253 | all_namefile[k] = namefile |
---|
254 | all_time[k] = time |
---|
255 | if var2: all_var2[k] = getfield(nc,var2) |
---|
256 | if winds: all_windu[k] = getfield(nc,uchar) ; all_windv[k] = getfield(nc,vchar) |
---|
257 | ##### SPECIFIC |
---|
258 | if varname in ["temp","t","T_nadir_nit","T_nadir_day","temp_day","temp_night"] and tsat: |
---|
259 | tt=getfield(nc,varname) ; print "computing Tsat-T, I ASSUME Z-AXIS IS PRESSURE" |
---|
260 | if type(tt).__name__=='MaskedArray': tt.set_fill_value([np.NaN]) ; tinput=tt.filled() |
---|
261 | else: tinput=tt |
---|
262 | all_var[k]=get_tsat(vert,tinput,zlon=lon,zlat=lat,zalt=vert,ztime=time) |
---|
263 | else: |
---|
264 | ##### GENERAL STUFF HERE |
---|
265 | all_var[k] = getfield(nc,varname) |
---|
266 | |
---|
267 | print "**** GOT SUBDATA:",k," NAMEFILE:",namefile," VAR:",varname, var2 ; k += 1 ; firstfile = False |
---|
268 | #### End of for namefile in namefiles |
---|
269 | |
---|
270 | ################################## |
---|
271 | ### Operation on files |
---|
272 | if ope is not None: |
---|
273 | print "********** OPERATION: ",ope |
---|
274 | if "var" not in ope: |
---|
275 | if len(var) > 1: errormess("for this operation... please set only one var !") |
---|
276 | if ope in ["-","+","-%"]: |
---|
277 | if fileref is not None: all_var[k] = getfield(Dataset(fileref),all_varname[k-1]) ; all_varname[k] = all_varname[k-1] ; all_time[k] = all_time[k-1] ; all_namefile[k] = all_namefile[k-1] |
---|
278 | else: errormess("fileref is missing!") |
---|
279 | if ope == "-": all_var[k+1]= all_var[k-1] - all_var[k] |
---|
280 | elif ope == "+": all_var[k+1]= all_var[k-1] + all_var[k] |
---|
281 | elif ope == "-%": |
---|
282 | masked = np.ma.masked_where(all_var[k] == 0,all_var[k]) |
---|
283 | masked.set_fill_value([np.NaN]) |
---|
284 | all_var[k+1]= 100.*(all_var[k-1] - masked)/masked |
---|
285 | all_varname[k+1] = all_varname[k] ; all_time[k+1] = all_time[k] ; all_namefile[k+1] = all_namefile[k] ; numplot = numplot+2 |
---|
286 | elif ope in ["cat"]: |
---|
287 | tabtime = all_time[0];tab = all_var[0];k = 1 |
---|
288 | if var2: tab2 = all_var2[0] |
---|
289 | while k != len(namefiles) and len(all_time[k]) != 0: |
---|
290 | if var2: tab2 = np.append(tab2,all_var2[k],axis=0) |
---|
291 | tabtime = np.append(tabtime,all_time[k]) ; tab = np.append(tab,all_var[k],axis=0) ; k += 1 |
---|
292 | all_time[0] = np.array(tabtime) ; all_var[0] = np.array(tab) ; numplot = 1 |
---|
293 | if var2: all_var2[0] = np.array(tab2) |
---|
294 | else: errormess(ope+" : non-implemented operation. Check pp.py --help") |
---|
295 | else: |
---|
296 | if len(namefiles) > 1: errormess("for this operation... please set only one file !") |
---|
297 | if len(var) > 2: errormess("not sure this works for more than 2 vars... please check.") |
---|
298 | if ope in ["div_var"]: all_var[k] = all_var[k-2] / all_var[k-1] ; insert = '_div_' |
---|
299 | elif ope in ["mul_var"]: all_var[k] = all_var[k-2] * all_var[k-1] ; insert = '_mul_' |
---|
300 | elif ope in ["add_var"]: all_var[k] = all_var[k-2] + all_var[k-1] ; insert = '_add_' |
---|
301 | elif ope in ["sub_var"]: all_var[k] = all_var[k-2] - all_var[k-1] ; insert = '_sub_' |
---|
302 | else: errormess(ope+" : non-implemented operation. Check pp.py --help") |
---|
303 | numplot = numplot + 1 ; all_time[k] = all_time[k-1] ; all_namefile[k] = all_namefile[k-1] |
---|
304 | all_varname[k] = all_varname[k-2] + insert + all_varname[k-1] |
---|
305 | ################################## |
---|
306 | ### Open a figure and set subplots |
---|
307 | fig = figure() |
---|
308 | subv,subh = definesubplot( numplot, fig ) |
---|
309 | if ope in ['-','-%']: subv,subh = 2,2 |
---|
310 | |
---|
311 | ################################# |
---|
312 | ### Time loop for plotting device |
---|
313 | nplot = 1 ; error = False |
---|
314 | print "********************************************" |
---|
315 | while error is False: |
---|
316 | |
---|
317 | print "********** NPLOT", nplot |
---|
318 | if nplot > numplot: break |
---|
319 | |
---|
320 | #################################################################### |
---|
321 | ## get all indexes to be taken into account for this subplot and then reduce field |
---|
322 | ## 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 |
---|
323 | indexlon = getsindex(slon,(nplot-1)%nlon,lon) |
---|
324 | indexlat = getsindex(slat,((nplot-1)//nlon)%nlat,lat) |
---|
325 | indexvert = getsindex(svert,((nplot-1)//(nlon*nlat))%nvert,vert) |
---|
326 | if ope is not None: |
---|
327 | 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 |
---|
328 | elif "var" in ope: index_f = ((nplot-1)//(nlon*nlat*nvert*ntime))%(len(var)+1) ## OK only 1 file, see test in the beginning |
---|
329 | elif "cat" in ope: index_f = 0 |
---|
330 | else: yeah = len(namefiles)*len(var) ; index_f = ((nplot-1)//(nlon*nlat*nvert*ntime))%yeah |
---|
331 | time = all_time[index_f] |
---|
332 | if mrate is not None: indextime = None |
---|
333 | else: indextime = getsindex(stime,((nplot-1)//(nlon*nlat*nvert))%ntime,time) |
---|
334 | ltst = None |
---|
335 | if typefile in ['mesoapi','meso'] and indextime is not None: ltst = localtime ( interv[0]+indextime*interv[1], 0.5*(wlon[0]+wlon[1]) ) |
---|
336 | print "********** INDEX LON:",indexlon," LAT:",indexlat," VERT:",indexvert," TIME:",indextime |
---|
337 | ##var = nc.variables["phisinit"][:,:] |
---|
338 | ##contourf(np.transpose(var),30,cmap = get_cmap(name="Greys_r") ) ; axis('off') ; plot(indexlat,indexlon,'mx',mew=4.0,ms=20.0) |
---|
339 | ##show() |
---|
340 | ##exit() |
---|
341 | #truc = True |
---|
342 | #truc = False |
---|
343 | #if truc: indexvert = None |
---|
344 | #################################################################### |
---|
345 | ########## REDUCE FIELDS |
---|
346 | #################################################################### |
---|
347 | error = False |
---|
348 | varname = all_varname[index_f] |
---|
349 | if varname: ### what is shaded. |
---|
350 | what_I_plot, error = reducefield( all_var[index_f], d4=indextime, d1=indexlon, d2=indexlat, d3=indexvert, \ |
---|
351 | yint=yintegral, alt=vert, anomaly=anomaly, redope=redope, mesharea=area ) |
---|
352 | if mult != 2718.: what_I_plot = what_I_plot*mult |
---|
353 | else: what_I_plot = np.log10(what_I_plot) ; print "log plot" |
---|
354 | if var2: ### what is contoured. |
---|
355 | what_I_plot_contour, error = reducefield( all_var2[index_f], d4=indextime, d1=indexlon, d2=indexlat , d3=indexvert, \ |
---|
356 | yint=yintegral, alt=vert ) |
---|
357 | if winds: ### what is plot as vectors. |
---|
358 | vecx, error = reducefield( all_windu[index_f], d4=indextime, d3=indexvert, yint=yintegral, alt=vert) |
---|
359 | vecy, error = reducefield( all_windv[index_f], d4=indextime, d3=indexvert, yint=yintegral, alt=vert) |
---|
360 | if varname in [uchar,vchar]: what_I_plot = np.sqrt( np.square(vecx) + np.square(vecy) ) ; varname = "wind" |
---|
361 | |
---|
362 | ##################################################################### |
---|
363 | #if truc: |
---|
364 | # nx = what_I_plot.shape[2] ; ny = what_I_plot.shape[1] ; nz = what_I_plot.shape[0] |
---|
365 | # for k in range(nz): print k,' over ',nz ; what_I_plot[k,:,:] = what_I_plot[k,:,:] / smooth(what_I_plot[k,:,:],12) |
---|
366 | # for iii in range(nx): |
---|
367 | # for jjj in range(ny): |
---|
368 | # deviation = what_I_plot[:,jjj,iii] ; mx = max(deviation) ; mn = min(deviation) |
---|
369 | # 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 |
---|
370 | # else: what_I_plot[0,jjj,iii] = 0. |
---|
371 | # if np.abs(what_I_plot[0,jjj,iii]) > 1.5: |
---|
372 | # print iii,jjj,what_I_plot[0,jjj,iii],int(abs(1.-mx)*100.),int(abs(1.-mn)*100.) |
---|
373 | # plot(rel) |
---|
374 | # show() |
---|
375 | # anomaly = True ### pour avoir les bons reglages plots |
---|
376 | # what_I_plot = what_I_plot[0,:,:] |
---|
377 | ##################################################################### |
---|
378 | |
---|
379 | #################################################################### |
---|
380 | ### General plot settings |
---|
381 | changesubplot = (numplot > 1) and (len(what_I_plot.shape) != 1) ## default for 1D plots: superimposed. to be reworked for better flexibility. |
---|
382 | if changesubplot: subplot(subv,subh,nplot) #; subplots_adjust(wspace=0,hspace=0) |
---|
383 | #################################################################### |
---|
384 | if error: |
---|
385 | errormess("There is an error in reducing field !") |
---|
386 | else: |
---|
387 | ticks = ndiv + 1 |
---|
388 | fvar = varname |
---|
389 | if anomaly: fvar = 'anomaly' |
---|
390 | ### |
---|
391 | if mapmode == 0: ### could this be moved inside imov loop ? |
---|
392 | itime=indextime |
---|
393 | if len(what_I_plot.shape) is 3:itime=[0] |
---|
394 | m = None ; x = None ; y = None |
---|
395 | what_I_plot, x, y = define_axis(lon,lat,vert,time,indexlon,indexlat,indexvert,\ |
---|
396 | itime,what_I_plot, len(all_var[index_f].shape),vertmode) |
---|
397 | ### |
---|
398 | if (fileref is not None) and (index_f == numplot-1): zevmin, zevmax = calculate_bounds(what_I_plot,vmin=minop,vmax=maxop) |
---|
399 | else: zevmin, zevmax = calculate_bounds(what_I_plot,vmin=vmin,vmax=vmax) |
---|
400 | if (fileref is not None) and (index_f == numplot-1): colorb = "RdBu_r" |
---|
401 | if colorb in ["def","nobar","onebar"]: palette = get_cmap(name=defcolorb(fvar.upper())) |
---|
402 | else: palette = get_cmap(name=colorb) |
---|
403 | #palette = cm.GMT_split |
---|
404 | ##### 1. ELIMINATE 0D or >3D CASES |
---|
405 | if len(what_I_plot.shape) == 0: |
---|
406 | print "VALUE VALUE VALUE VALUE ::: ",what_I_plot |
---|
407 | save = 'donothing' |
---|
408 | elif len(what_I_plot.shape) >= 4: |
---|
409 | print "WARNING!!! ",len(what_I_plot.shape),"-D PLOT NOT SUPPORTED !!! dimensions: ",what_I_plot.shape |
---|
410 | errormess("Are you sure you did not forget to prescribe a dimension ?") |
---|
411 | ##### 2. HANDLE simple 1D/2D field and movies of 1D/2D fields |
---|
412 | else: |
---|
413 | if mrate is not None: iend=len(time)-1 |
---|
414 | else: iend=0 |
---|
415 | imov = 0 |
---|
416 | if len(what_I_plot.shape) == 3: |
---|
417 | if var2: which = "contour" ## have to start with contours rather than shading |
---|
418 | else: which = "regular" |
---|
419 | if mrate is None: errormess("3D field. Use --rate RATE for movie or specify --time TIME. Exit.") |
---|
420 | elif len(what_I_plot.shape) == 2: |
---|
421 | if var2: which = "contour" ## have to start with contours rather than shading |
---|
422 | else: which = "regular" |
---|
423 | if mrate is not None: which = "unidim" |
---|
424 | elif len(what_I_plot.shape) == 1: |
---|
425 | which = "unidim" |
---|
426 | ##### IMOV LOOP #### IMOV LOOP |
---|
427 | while imov <= iend: |
---|
428 | print "-> frame ",imov+1, which |
---|
429 | if which == "regular": |
---|
430 | if mrate is None: what_I_plot_frame = what_I_plot |
---|
431 | else: what_I_plot_frame = what_I_plot[imov,:,:] |
---|
432 | if winds: |
---|
433 | if mrate is None: vecx_frame = vecx ; vecy_frame = vecy |
---|
434 | else: vecx_frame = vecx[imov,:,:] ; vecy_frame = vecy[imov,:,:] |
---|
435 | elif which == "contour": |
---|
436 | if mrate is None or what_I_plot_contour.ndim < 3: what_I_plot_frame = what_I_plot_contour |
---|
437 | else: what_I_plot_frame = what_I_plot_contour[imov,:,:] |
---|
438 | elif which == "unidim": |
---|
439 | if mrate is None: what_I_plot_frame = what_I_plot |
---|
440 | else: what_I_plot_frame = what_I_plot[:,imov] ## because swapaxes |
---|
441 | #if mrate is not None: |
---|
442 | if mapmode == 1: |
---|
443 | m = define_proj(proj,wlon,wlat,back=back,blat=blat,blon=blon) ## this is dirty, defined above but out of imov loop |
---|
444 | x, y = m(lon2d, lat2d) ## this is dirty, defined above but out of imov loop |
---|
445 | if typefile in ['mesoapi','meso'] and mapmode == 1: what_I_plot_frame = dumpbdy(what_I_plot_frame,6,condition=True) |
---|
446 | # if typefile in ['mesoideal']: what_I_plot_frame = dumpbdy(what_I_plot_frame,0,stag='W',condition=dumped_vert_stag) |
---|
447 | |
---|
448 | if which == "unidim": |
---|
449 | lbl = "" |
---|
450 | if indexlat is not None: lbl = lbl + " ix" + str(indexlat[0]) |
---|
451 | if indexlon is not None: lbl = lbl + " iy" + str(indexlon[0]) |
---|
452 | if indexvert is not None: lbl = lbl + " iz" + str(indexvert[0]) |
---|
453 | if indextime is not None: lbl = lbl + " it" + str(indextime[0]) |
---|
454 | if lbl == "": lbl = namefiles[index_f] |
---|
455 | if mrate is not None: x = y ## because swapaxes... |
---|
456 | #what_I_plot_frame = np.diff(what_I_plot_frame, n=1) ; x = x[1:] |
---|
457 | |
---|
458 | if not tile: zeline='-' |
---|
459 | else: zeline=',' |
---|
460 | if indexvert is not None or indextime is None: plot(x,what_I_plot_frame,zeline,label=lbl) ## regular plot |
---|
461 | else: plot(what_I_plot_frame,x,zeline,label=lbl) ## vertical profile |
---|
462 | if nplot > 1: legend(loc='best') |
---|
463 | if indextime is None and axtime is not None and xlab is None: xlabel(axtime.upper()) ## define the right label |
---|
464 | if save == 'txt': writeascii(np.transpose(what_I_plot),'profile'+str(nplot*1000+imov)+'.txt') |
---|
465 | |
---|
466 | elif which == "regular": |
---|
467 | if hole: what_I_plot_frame = hole_bounds(what_I_plot_frame,zevmin,zevmax) |
---|
468 | else: what_I_plot_frame = bounds(what_I_plot_frame,zevmin,zevmax) |
---|
469 | if flagnolow: what_I_plot_frame = nolow(what_I_plot_frame) |
---|
470 | if not tile: |
---|
471 | #zelevels = np.linspace(zevmin*(1. + 1.e-7),zevmax*(1. - 1.e-7)) #,num=20) |
---|
472 | zelevels = np.linspace(zevmin,zevmax,num=ticks) |
---|
473 | if mapmode == 1: m.contourf( x, y, what_I_plot_frame, zelevels, cmap = palette, alpha=trans) |
---|
474 | elif mapmode == 0: contourf( x, y, what_I_plot_frame, zelevels, cmap = palette, alpha=trans) |
---|
475 | else: |
---|
476 | if mapmode == 1: m.pcolor( x, y, what_I_plot_frame, cmap = palette, vmin=zevmin, vmax=zevmax, alpha=trans) |
---|
477 | elif mapmode == 0: pcolor( x, y, what_I_plot_frame, cmap = palette, vmin=zevmin, vmax=zevmax, alpha=trans) |
---|
478 | |
---|
479 | if colorb not in ['nobar','onebar']: |
---|
480 | if (fileref is not None) and (index_f == numplot-1): daformat = "%.3f" |
---|
481 | elif mult != 1: daformat = "%.1f" |
---|
482 | else: daformat = fmtvar(fvar.upper()) |
---|
483 | if proj in ['moll']: zeorientation="horizontal" |
---|
484 | else: zeorientation="vertical" |
---|
485 | zecb = colorbar( fraction=0.05,pad=0.03,format=daformat,orientation=zeorientation,\ |
---|
486 | ticks=np.linspace(zevmin,zevmax,num=min([ticks/2+1,21])),extend='neither',spacing='proportional' ) |
---|
487 | if zeorientation == "horizontal" and zetitle != "fill": zecb.ax.set_xlabel(zetitle) ; zetitle="" |
---|
488 | if winds: |
---|
489 | if typefile in ['mesoapi','meso']: |
---|
490 | [vecx_frame,vecy_frame] = [dumpbdy(vecx_frame,6,stag=uchar,condition=True), dumpbdy(vecy_frame,6,stag=vchar,condition=True)] |
---|
491 | key = True |
---|
492 | elif typefile in ['gcm']: |
---|
493 | key = False |
---|
494 | if metwind: [vecx_frame,vecy_frame] = m.rotate_vector(vecx_frame, vecy_frame, lon2d, lat2d) |
---|
495 | if var: colorvec = definecolorvec(back) |
---|
496 | else: colorvec = definecolorvec(colorb) |
---|
497 | vectorfield(vecx_frame, vecy_frame, x, y, stride=stride, csmooth=2,\ |
---|
498 | #scale=15., factor=300., color=colorvec, key=key) |
---|
499 | scale=20., factor=250., color=colorvec, key=key) |
---|
500 | #200. ## or csmooth=stride |
---|
501 | elif which == "contour": |
---|
502 | zevminc, zevmaxc = calculate_bounds(what_I_plot_frame) |
---|
503 | zelevels = np.linspace(zevminc,zevmaxc,ticks/2) #20) |
---|
504 | if var2 == 'HGT': zelevels = np.arange(-10000.,30000.,2000.) |
---|
505 | if mapmode == 0: |
---|
506 | what_I_plot_frame, x, y = define_axis( lon,lat,vert,time,indexlon,indexlat,indexvert,\ |
---|
507 | itime,what_I_plot_frame, len(all_var2[index_f].shape),vertmode ) |
---|
508 | cs = contour( x,y,what_I_plot_frame, zelevels, colors='k', linewidths = 1 ) #0.33 colors='w' )# , alpha=0.5) |
---|
509 | elif mapmode == 1: cs = m.contour( x,y,what_I_plot_frame, zelevels, colors='k', linewidths = 1 ) #0.33 colors='w' )# , alpha=0.5) |
---|
510 | |
---|
511 | if which in ["regular","unidim"]: |
---|
512 | |
---|
513 | if nplot > 1 and which == "unidim": |
---|
514 | pass ## because we superimpose nplot instances |
---|
515 | else: |
---|
516 | # Axis directives for movie frames [including the first one). |
---|
517 | zxmin, zxmax = xaxis ; zymin, zymax = yaxis |
---|
518 | if zxmin is not None: mpl.pyplot.xlim(xmin=zxmin) |
---|
519 | if zxmax is not None: mpl.pyplot.xlim(xmax=zxmax) |
---|
520 | if zymin is not None: mpl.pyplot.ylim(ymin=zymin) |
---|
521 | if zymax is not None: mpl.pyplot.ylim(ymax=zymax) |
---|
522 | if ylog: mpl.pyplot.semilogy() |
---|
523 | if invert_y: ax = mpl.pyplot.gca() ; ax.set_ylim(ax.get_ylim()[::-1]) |
---|
524 | if xlab is not None: xlabel(xlab) |
---|
525 | if ylab is not None: ylabel(ylab) |
---|
526 | |
---|
527 | if mrate is not None: |
---|
528 | ### THIS IS A MENCODER MOVIE |
---|
529 | if mrate > 0: |
---|
530 | figframe=mpl.pyplot.gcf() |
---|
531 | if mquality: figframe.set_dpi(600.) |
---|
532 | else: figframe.set_dpi(200.) |
---|
533 | mframe=fig2img(figframe) |
---|
534 | if imov == 0: |
---|
535 | moviename='movie' ;W,H = figframe.canvas.get_width_height() |
---|
536 | video = VideoSink((H,W), moviename, rate=mrate, byteorder="rgba") |
---|
537 | video.run(mframe) ; close() |
---|
538 | if imov == iend: video.close() |
---|
539 | ### THIS IS A WEBPAGE MOVIE |
---|
540 | else: |
---|
541 | nameframe = "image"+str(1000+imov) |
---|
542 | makeplotres(nameframe,res=100.,disp=False) ; close() |
---|
543 | if imov == 0: myfile = open("zepics", 'w') |
---|
544 | myfile.write("modImages["+str(imov)+"] = '"+nameframe+"_100.png';"+ '\n') |
---|
545 | if imov == iend: |
---|
546 | myfile.write("first_image = 0;"+ '\n') |
---|
547 | myfile.write("last_image = "+str(iend)+";"+ '\n') |
---|
548 | myfile.close() |
---|
549 | if var2 and which == "regular": which = "contour" |
---|
550 | imov = imov+1 |
---|
551 | elif which == "contour": |
---|
552 | which = "regular" |
---|
553 | |
---|
554 | ### Next subplot |
---|
555 | zevarname = varname |
---|
556 | if redope is not None: zevarname = zevarname + "_" + redope |
---|
557 | basename = getname(var=zevarname,var2=var2,winds=winds,anomaly=anomaly) |
---|
558 | if len(what_I_plot.shape) > 3: |
---|
559 | basename = basename + getstralt(nc,level) |
---|
560 | if mrate is not None: basename = "movie_" + basename |
---|
561 | if typefile in ['mesoapi','meso']: |
---|
562 | if slon is not None: basename = basename + "_lon_" + str(int(round(lonp))) |
---|
563 | if slat is not None: basename = basename + "_lat_" + str(int(round(latp))) |
---|
564 | plottitle = basename |
---|
565 | ### dans le nouveau systeme time=ls,sol,lt cette ligne pourrait ne servir a rien (ou deplacer au dessus) |
---|
566 | if addchar and indextime is not None: [addchar,gogol,gogol2] = getlschar ( all_namefile[index_f] ) ; plottitle = plottitle + addchar |
---|
567 | ### en fait redope is None doit etre remplace par : n'est ni maxt ni mint |
---|
568 | if redope is None and ltst is not None and ( (mapmode == 0) or (proj in ["lcc","laea","merc","nsper"]) ): plottitle = plottitle + "_LT" + str(ltst) |
---|
569 | else: |
---|
570 | if fileref is not None: |
---|
571 | if index_f is numplot-1: plottitle = basename+' '+"fig(1) "+ope+" fig(2)" |
---|
572 | elif index_f is numplot-2: plottitle = basename+' '+fileref |
---|
573 | else: plottitle = basename+' '+namefiles[0]#index_f] |
---|
574 | else: plottitle = basename+' '+namefiles[0]#index_f] |
---|
575 | if mult != 1: plottitle = '{:.0e}'.format(mult) + "*" + plottitle |
---|
576 | if zetitle != "fill": |
---|
577 | plottitle = zetitle |
---|
578 | if titleref is "fill": titleref=zetitle |
---|
579 | if fileref is not None: |
---|
580 | if index_f is numplot-2: plottitle = titleref |
---|
581 | if index_f is numplot-1: plottitle = "fig(1) "+ope+" fig(2)" |
---|
582 | # if indexlon is not None: plottitle = plottitle + " lon: " + str(min(lon[indexlon])) +" "+ str(max(lon[indexlon])) |
---|
583 | # if indexlat is not None: plottitle = plottitle + " lat: " + str(min(lat[indexlat])) +" "+ str(max(lat[indexlat])) |
---|
584 | # if indexvert is not None: plottitle = plottitle + " vert: " + str(min(vert[indexvert])) +" "+ str(max(vert[indexvert])) |
---|
585 | # if indextime is not None: plottitle = plottitle + " time: " + str(min(time[indextime])) +" "+ str(max(time[indextime])) |
---|
586 | if colorb != "onebar": title( plottitle ) |
---|
587 | if nplot >= numplot: error = True |
---|
588 | nplot += 1 |
---|
589 | |
---|
590 | if colorb == "onebar": |
---|
591 | cax = axes([0.1, 0.2, 0.8, 0.03]) # a ameliorer |
---|
592 | zecb = colorbar(cax=cax, orientation="horizontal", format=fmtvar(fvar.upper()),\ |
---|
593 | ticks=np.linspace(zevmin,zevmax,num=min([ticks/2+1,21])),extend='neither',spacing='proportional') |
---|
594 | if zetitle != "fill": zecb.ax.set_xlabel(zetitle) ; zetitle="" |
---|
595 | |
---|
596 | |
---|
597 | ########################################################################## |
---|
598 | ### Save the figure in a file in the data folder or an user-defined folder |
---|
599 | if outputname is None: |
---|
600 | if typefile in ['meso','mesoapi']: prefix = getprefix(nc) |
---|
601 | elif typefile in ['gcm']: prefix = 'LMD_GCM_' |
---|
602 | else: prefix = '' |
---|
603 | ### |
---|
604 | zeplot = prefix + basename |
---|
605 | if addchar: zeplot = zeplot + addchar |
---|
606 | if numplot <= 0: zeplot = zeplot + "_LT"+str(abs(numplot)) |
---|
607 | ### |
---|
608 | if not target: zeplot = namefile[0:find(namefile,'wrfout')] + zeplot |
---|
609 | else: zeplot = target + "/" + zeplot |
---|
610 | ### |
---|
611 | else: |
---|
612 | zeplot=outputname |
---|
613 | |
---|
614 | if mrate is None: |
---|
615 | pad_inches_value = 0.35 |
---|
616 | print "********** SAVE ", save |
---|
617 | if save == 'png': |
---|
618 | if display: makeplotres(zeplot,res=100.,pad_inches_value=pad_inches_value) #,erase=True) ## a miniature |
---|
619 | makeplotres(zeplot,res=resolution,pad_inches_value=pad_inches_value,disp=False) |
---|
620 | elif save in ['eps','svg','pdf']: makeplotres(zeplot,pad_inches_value=pad_inches_value,disp=False,ext=save) |
---|
621 | elif save == 'gui': show() |
---|
622 | elif save == 'donothing': pass |
---|
623 | elif save == 'txt': print "Saved results in txt file." |
---|
624 | else: |
---|
625 | print "INFO: save mode not supported. using gui instead." |
---|
626 | show() |
---|
627 | |
---|
628 | ################################### |
---|
629 | #### Getting more out of this video -- PROBLEMS WITH CREATED VIDEOS |
---|
630 | # |
---|
631 | #if mrate is not None: |
---|
632 | # print "Re-encoding movie.. first pass" |
---|
633 | # video.first_pass(filename=moviename,quality=mquality,rate=mrate) |
---|
634 | # print "Re-encoding movie.. second pass" |
---|
635 | # video.second_pass(filename=moviename,quality=mquality,rate=mrate) |
---|
636 | |
---|
637 | ############### |
---|
638 | ### Now the end |
---|
639 | return zeplot |
---|