source: trunk/UTIL/PYTHON/planetoplot.py @ 513

Last change on this file since 513 was 507, checked in by aslmd, 14 years ago

UTIL PYTHON: added an option --seevar to see the list of variables in file. also if there is only one variable and the name is not right the script figure it out.

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