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

Last change on this file since 572 was 571, checked in by aslmd, 13 years ago

UTIL PYTHON: moved windamplitude stuff into a so-called function.

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