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

Last change on this file since 553 was 548, checked in by aslmd, 13 years ago

UTIL PYTHON: no more meso,mesoapi,mesoideal types -- only meso. fixed wind plotting for idealized file. also more flexible possibilities for naming wind fields in getwinddef

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