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

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

UTIL PYTHON : a few stupid tricks added. if you ask --mult 2718 you'll have a log(field). if you ask moll projection the colorbar will be horizontal and title under the colorbar. if you use -T (tile) with a 1D plot you will have individual points instead of a line.

  • Property svn:executable set to *
File size: 37.4 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           if mult != 2718.:  what_I_plot = what_I_plot*mult
345           else:              what_I_plot = np.log10(what_I_plot) ; print "log plot"
346       if var2:      ### what is contoured.
347           what_I_plot_contour, error = reducefield( all_var2[index_f], d4=indextime, d1=indexlon, d2=indexlat , d3=indexvert, \
348                                             yint=yintegral, alt=vert )
349       if winds:     ### what is plot as vectors.
350           vecx, error = reducefield( all_windu[index_f], d4=indextime, d3=indexvert, yint=yintegral, alt=vert)
351           vecy, error = reducefield( all_windv[index_f], d4=indextime, d3=indexvert, yint=yintegral, alt=vert)
352           if varname in [uchar,vchar]: what_I_plot = np.sqrt( np.square(vecx) + np.square(vecy) ) ; varname = "wind"
353
354       #####################################################################
355       #if truc:
356       #   nx = what_I_plot.shape[2] ; ny = what_I_plot.shape[1] ; nz = what_I_plot.shape[0]
357       #   for k in range(nz): print k,' over ',nz ; what_I_plot[k,:,:] = what_I_plot[k,:,:] / smooth(what_I_plot[k,:,:],12)
358       #   for iii in range(nx):
359       #    for jjj in range(ny):
360       #     deviation = what_I_plot[:,jjj,iii] ; mx = max(deviation) ; mn = min(deviation)
361       #     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
362       #     else:                                                   what_I_plot[0,jjj,iii]     = 0.
363       #     if np.abs(what_I_plot[0,jjj,iii]) > 1.5:
364       #         print iii,jjj,what_I_plot[0,jjj,iii],int(abs(1.-mx)*100.),int(abs(1.-mn)*100.)
365       #         plot(rel)
366       #   show()
367       #   anomaly = True ### pour avoir les bons reglages plots
368       #   what_I_plot = what_I_plot[0,:,:] 
369       #####################################################################
370
371       ####################################################################
372       ### General plot settings
373       changesubplot = (numplot > 1) and (len(what_I_plot.shape) != 1)  ## default for 1D plots: superimposed. to be reworked for better flexibility.
374       if changesubplot: subplot(subv,subh,nplot)
375       ####################################################################
376       if error:
377               errormess("There is an error in reducing field !")
378       else:
379               ticks = ndiv + 1 
380               fvar = varname
381               if anomaly: fvar = 'anomaly'
382               ###
383               if mapmode == 0:    ### could this be moved inside imov loop ?
384                   itime=indextime
385                   if len(what_I_plot.shape) is 3:itime=[0]
386                   m = None ; x = None ; y = None
387                   what_I_plot, x, y = define_axis(lon,lat,vert,time,indexlon,indexlat,indexvert,\
388                         itime,what_I_plot, len(all_var[index_f].shape),vertmode)
389               ###
390               if (fileref is not None) and (index_f == numplot-1):    zevmin, zevmax = calculate_bounds(what_I_plot,vmin=minop,vmax=maxop)
391               else:                                                   zevmin, zevmax = calculate_bounds(what_I_plot,vmin=vmin,vmax=vmax)
392               if (fileref is not None) and (index_f == numplot-1):    colorb = "RdBu_r"
393               if colorb in ["def","nobar"]:                           palette = get_cmap(name=defcolorb(fvar.upper()))
394               else:                                                   palette = get_cmap(name=colorb)
395               #palette = cm.GMT_split
396               ##### 1. ELIMINATE 0D or >3D CASES
397               if len(what_I_plot.shape) == 0:   
398                 print "VALUE VALUE VALUE VALUE ::: ",what_I_plot
399                 save = 'donothing'
400               elif len(what_I_plot.shape) >= 4:
401                 print "WARNING!!! ",len(what_I_plot.shape),"-D PLOT NOT SUPPORTED !!! dimensions: ",what_I_plot.shape
402                 errormess("Are you sure you did not forget to prescribe a dimension ?")
403               ##### 2. HANDLE simple 1D/2D field and movies of 1D/2D fields
404               else:
405                 if mrate is not None: iend=len(time)-1
406                 else:                 iend=0
407                 imov = 0 
408                 if len(what_I_plot.shape) == 3:
409                    if var2:               which = "contour" ## have to start with contours rather than shading
410                    else:                  which = "regular"
411                    if mrate is None:      errormess("3D field. Use --rate RATE for movie or specify --time TIME. Exit.")
412                 elif len(what_I_plot.shape) == 2:
413                    if var2:               which = "contour" ## have to start with contours rather than shading
414                    else:                  which = "regular"
415                    if mrate is not None:  which = "unidim"
416                 elif len(what_I_plot.shape) == 1:
417                    which = "unidim"
418                 ##### IMOV LOOP #### IMOV LOOP
419                 while imov <= iend:
420                    print "-> frame ",imov+1, which
421                    if which == "regular":   
422                        if mrate is None:                                   what_I_plot_frame = what_I_plot
423                        else:                                               what_I_plot_frame = what_I_plot[imov,:,:]
424                        if winds:
425                            if mrate is None:                                   vecx_frame = vecx ; vecy_frame = vecy
426                            else:                                               vecx_frame = vecx[imov,:,:] ; vecy_frame = vecy[imov,:,:]
427                    elif which == "contour": 
428                        if mrate is None or what_I_plot_contour.ndim < 3:   what_I_plot_frame = what_I_plot_contour
429                        else:                                               what_I_plot_frame = what_I_plot_contour[imov,:,:]
430                    elif which == "unidim":
431                        if mrate is None:                                   what_I_plot_frame = what_I_plot
432                        else:                                               what_I_plot_frame = what_I_plot[:,imov]  ## because swapaxes
433                    #if mrate is not None:     
434                    if mapmode == 1: 
435                            m = define_proj(proj,wlon,wlat,back=back,blat=blat,blon=blon)  ## this is dirty, defined above but out of imov loop
436                            x, y = m(lon2d, lat2d)                                         ## this is dirty, defined above but out of imov loop
437                    if typefile in ['mesoapi','meso'] and mapmode == 1:   what_I_plot_frame = dumpbdy(what_I_plot_frame,6,condition=True)
438#                   if typefile in ['mesoideal']:    what_I_plot_frame = dumpbdy(what_I_plot_frame,0,stag='W',condition=dumped_vert_stag)
439
440                    if which == "unidim":
441                        lbl = ""
442                        if indexlat is not None:  lbl = lbl + " ix" + str(indexlat[0])
443                        if indexlon is not None:  lbl = lbl + " iy" + str(indexlon[0])
444                        if indexvert is not None: lbl = lbl + " iz" + str(indexvert[0])
445                        if indextime is not None: lbl = lbl + " it" + str(indextime[0])
446                        if lbl == "": lbl = namefiles[index_f]
447                        if mrate is not None: x = y  ## because swapaxes...
448                        #what_I_plot_frame = np.diff(what_I_plot_frame, n=1) ; x = x[1:]
449                       
450                        if not tile:  zeline='-'
451                        else:         zeline=','
452                        if indexvert is not None or indextime is None:    plot(x,what_I_plot_frame,zeline,label=lbl)  ## regular plot
453                        else:                                             plot(what_I_plot_frame,x,zeline,label=lbl)  ## vertical profile
454                        if nplot > 1: legend(loc='best')
455                        if indextime is None and axtime is not None and xlab is None:    xlabel(axtime.upper()) ## define the right label
456                        if save == 'txt':  writeascii(np.transpose(what_I_plot),'profile'+str(nplot*1000+imov)+'.txt')
457
458                    elif which == "regular": 
459                        if hole:         what_I_plot_frame = hole_bounds(what_I_plot_frame,zevmin,zevmax)
460                        else:            what_I_plot_frame = bounds(what_I_plot_frame,zevmin,zevmax)
461                        if flagnolow:    what_I_plot_frame = nolow(what_I_plot_frame)
462                        if not tile:
463                            #zelevels = np.linspace(zevmin*(1. + 1.e-7),zevmax*(1. - 1.e-7)) #,num=20)
464                            zelevels = np.linspace(zevmin,zevmax,num=ticks)
465                            if mapmode == 1:       m.contourf( x, y, what_I_plot_frame, zelevels, cmap = palette, alpha=trans)
466                            elif mapmode == 0:     contourf( x, y, what_I_plot_frame, zelevels, cmap = palette, alpha=trans)
467                        else:
468                            if mapmode == 1:       m.pcolor( x, y, what_I_plot_frame, cmap = palette, vmin=zevmin, vmax=zevmax, alpha=trans)
469                            elif mapmode == 0:     pcolor( x, y, what_I_plot_frame, cmap = palette, vmin=zevmin, vmax=zevmax, alpha=trans)
470
471                        if colorb != 'nobar':       
472                            if (fileref is not None) and (index_f == numplot-1):   daformat = "%.3f" 
473                            elif mult != 1:                                        daformat = "%.1f"
474                            else:                                                  daformat = fmtvar(fvar.upper())
475                            if proj in ['moll']:  zeorientation="horizontal"
476                            else:                 zeorientation="vertical"
477                            zecb = colorbar( fraction=0.05,pad=0.03,format=daformat,orientation=zeorientation,\
478                                      ticks=np.linspace(zevmin,zevmax,num=min([ticks/2+1,21])),extend='neither',spacing='proportional' ) 
479                            if zeorientation == "horizontal":
480                                zecb.ax.set_xlabel(zetitle)
481                                zetitle=""
482                        if winds:
483                            if typefile in ['mesoapi','meso']:
484                                [vecx_frame,vecy_frame] = [dumpbdy(vecx_frame,6,stag=uchar,condition=True), dumpbdy(vecy_frame,6,stag=vchar,condition=True)]
485                                key = True
486                            elif typefile in ['gcm']:
487                                key = False
488                            if metwind:  [vecx_frame,vecy_frame] = m.rotate_vector(vecx_frame, vecy_frame, lon2d, lat2d)
489                            if var:       colorvec = definecolorvec(back)
490                            else:         colorvec = definecolorvec(colorb)
491                            vectorfield(vecx_frame, vecy_frame, x, y, stride=stride, csmooth=2,\
492                                             #scale=15., factor=300., color=colorvec, key=key)
493                                             scale=20., factor=250., color=colorvec, key=key)
494                                                              #200.         ## or csmooth=stride
495                    elif which == "contour":
496                        zevminc, zevmaxc = calculate_bounds(what_I_plot_frame)
497                        zelevels = np.linspace(zevminc,zevmaxc,ticks/2) #20)
498                        if var2 == 'HGT': zelevels = np.arange(-10000.,30000.,2000.)
499                        if mapmode == 0:   
500                            what_I_plot_frame, x, y = define_axis( lon,lat,vert,time,indexlon,indexlat,indexvert,\
501                                                              itime,what_I_plot_frame, len(all_var2[index_f].shape),vertmode )
502                            cs = contour( x,y,what_I_plot_frame, zelevels, colors='k', linewidths = 1 ) #0.33 colors='w' )# , alpha=0.5)
503                        elif mapmode == 1:  cs = m.contour( x,y,what_I_plot_frame, zelevels, colors='k', linewidths = 1 ) #0.33 colors='w' )# , alpha=0.5)
504
505                    if which in ["regular","unidim"]:
506
507                        if nplot > 1 and which == "unidim":
508                           pass  ## because we superimpose nplot instances
509                        else:
510                           # Axis directives for movie frames [including the first one).
511                           zxmin, zxmax = xaxis ; zymin, zymax = yaxis
512                           if zxmin is not None: mpl.pyplot.xlim(xmin=zxmin)
513                           if zxmax is not None: mpl.pyplot.xlim(xmax=zxmax)
514                           if zymin is not None: mpl.pyplot.ylim(ymin=zymin)
515                           if zymax is not None: mpl.pyplot.ylim(ymax=zymax)
516                           if ylog:      mpl.pyplot.semilogy()
517                           if invert_y:  ax = mpl.pyplot.gca() ; ax.set_ylim(ax.get_ylim()[::-1])
518                           if xlab is not None: xlabel(xlab)
519                           if ylab is not None: ylabel(ylab)
520
521                        if mrate is not None:
522                           ### THIS IS A MENCODER MOVIE
523                           if mrate > 0:
524                             figframe=mpl.pyplot.gcf()
525                             if mquality:   figframe.set_dpi(600.)
526                             else:          figframe.set_dpi(200.)
527                             mframe=fig2img(figframe)
528                             if imov == 0:
529                                moviename='movie' ;W,H = figframe.canvas.get_width_height()
530                                video = VideoSink((H,W), moviename, rate=mrate, byteorder="rgba")
531                             video.run(mframe) ; close()
532                             if imov == iend: video.close()                           
533                           ### THIS IS A WEBPAGE MOVIE
534                           else:
535                             nameframe = "image"+str(1000+imov)
536                             makeplotres(nameframe,res=100.,disp=False) ; close()
537                             if imov == 0: myfile = open("zepics", 'w')
538                             myfile.write("modImages["+str(imov)+"] = '"+nameframe+"_100.png';"+ '\n')
539                             if imov == iend:
540                                 myfile.write("first_image = 0;"+ '\n')
541                                 myfile.write("last_image = "+str(iend)+";"+ '\n')
542                                 myfile.close()
543                        if var2 and which == "regular":  which = "contour"
544                        imov = imov+1
545                    elif which == "contour":
546                        which = "regular"
547
548       ### Next subplot
549       zevarname = varname
550       if redope is not None: zevarname = zevarname + "_" + redope
551       basename = getname(var=zevarname,var2=var2,winds=winds,anomaly=anomaly)
552       if len(what_I_plot.shape) > 3:
553           basename = basename + getstralt(nc,level) 
554       if mrate is not None: basename = "movie_" + basename
555       if typefile in ['mesoapi','meso']:
556            if slon is not None: basename = basename + "_lon_" + str(int(round(lonp)))
557            if slat is not None: basename = basename + "_lat_" + str(int(round(latp)))
558            plottitle = basename
559            ### dans le nouveau systeme time=ls,sol,lt cette ligne pourrait ne servir a rien (ou deplacer au dessus)
560            if addchar and indextime is not None:   [addchar,gogol,gogol2] = getlschar ( all_namefile[index_f] )  ;  plottitle = plottitle + addchar
561            ### en fait redope is None doit etre remplace par : n'est ni maxt ni mint
562            if redope is None and ltst is not None and ( (mapmode == 0) or (proj in ["lcc","laea","merc","nsper"]) ):  plottitle = plottitle + "_LT" + str(ltst)
563       else:
564            if fileref is not None:
565                if index_f is numplot-1:     plottitle = basename+' '+"fig(1) "+ope+" fig(2)"
566                elif index_f is numplot-2:   plottitle = basename+' '+fileref
567                else:                        plottitle = basename+' '+namefiles[0]#index_f]
568            else:                            plottitle = basename+' '+namefiles[0]#index_f]
569       if mult != 1:                         plottitle = '{:.0e}'.format(mult) + "*" + plottitle
570       if zetitle != "fill":                 
571          plottitle = zetitle
572          if titleref is "fill":             titleref=zetitle
573          if fileref is not None:
574             if index_f is numplot-2:        plottitle = titleref
575             if index_f is numplot-1:        plottitle = "fig(1) "+ope+" fig(2)"
576#       if indexlon is not None:      plottitle = plottitle + " lon: " + str(min(lon[indexlon])) +" "+ str(max(lon[indexlon]))
577#       if indexlat is not None:      plottitle = plottitle + " lat: " + str(min(lat[indexlat])) +" "+ str(max(lat[indexlat]))
578#       if indexvert is not None:     plottitle = plottitle + " vert: " + str(min(vert[indexvert])) +" "+ str(max(vert[indexvert]))
579#       if indextime is not None:     plottitle = plottitle + " time: " + str(min(time[indextime])) +" "+ str(max(time[indextime]))
580       title( plottitle )
581       if nplot >= numplot: error = True
582       nplot += 1
583
584 
585
586
587
588
589
590     
591    ##########################################################################
592    ### Save the figure in a file in the data folder or an user-defined folder
593    if outputname is None:
594       if typefile in ['meso','mesoapi']:   prefix = getprefix(nc)
595       elif typefile in ['gcm']:            prefix = 'LMD_GCM_'
596       else:                                prefix = ''
597    ###
598       zeplot = prefix + basename
599       if addchar:         zeplot = zeplot + addchar
600       if numplot <= 0:    zeplot = zeplot + "_LT"+str(abs(numplot))
601    ###
602       if not target:      zeplot = namefile[0:find(namefile,'wrfout')] + zeplot
603       else:               zeplot = target + "/" + zeplot 
604    ###
605    else:
606       zeplot=outputname
607
608    if mrate is None:
609        pad_inches_value = 0.35
610        print "********** SAVE ", save
611        if save == 'png': 
612            if display: makeplotres(zeplot,res=100.,pad_inches_value=pad_inches_value) #,erase=True)  ## a miniature
613            makeplotres(zeplot,res=resolution,pad_inches_value=pad_inches_value,disp=False)
614        elif save in ['eps','svg','pdf']:     makeplotres(zeplot,pad_inches_value=pad_inches_value,disp=False,ext=save)
615        elif save == 'gui':                   show()
616        elif save == 'donothing':             pass
617        elif save == 'txt':                   print "Saved results in txt file." 
618        else: 
619            print "INFO: save mode not supported. using gui instead."
620            show()
621
622    ###################################
623    #### Getting more out of this video -- PROBLEMS WITH CREATED VIDEOS
624    #
625    #if mrate is not None:
626    #    print "Re-encoding movie.. first pass"
627    #    video.first_pass(filename=moviename,quality=mquality,rate=mrate)
628    #    print "Re-encoding movie.. second pass"
629    #    video.second_pass(filename=moviename,quality=mquality,rate=mrate)   
630
631    ###############
632    ### Now the end
633    return zeplot
Note: See TracBrowser for help on using the repository browser.