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

Last change on this file since 580 was 580, checked in by acolaitis, 13 years ago

Python. Minor bug correction

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