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

Last change on this file since 821 was 817, checked in by aslmd, 13 years ago

UTIL PYTHON : improved projections. improved local time ticks. small bug fix with vertical coordinates. added a keyword nocolorb.

  • Property svn:executable set to *
File size: 60.7 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
13### T. Navarro   -- LMD --    04/2012 -- Added capabilities (e.g. histograms for difference maps)
14### A. Colaitis  -- LMD -- 05~06/2012 -- Added capabilities for analysis of mesoscale files (wind speed, etc...)
15### A. Spiga     -- LMD -- 04~07/2012 -- Added larger support of files + planets. Corrected a few bugs. Cleaning and improved comments
16### A. Colaitis  -- LMD --    08/2012 -- Added functionalities for further analysis: spectra, hodographs, etc... plus improved flexibility (e.g. grid)
17
18def planetoplot (namefiles,\
19           level=0,\
20           vertmode=0,\
21           proj=None,\
22           back=None,\
23           target=None,
24           stride=3,\
25           var=None,\
26           clb=None,\
27           winds=False,\
28           addchar=None,\
29           vmin=None,\
30           vmax=None,\
31           tile=False,\
32           zoom=None,\
33           display=True,\
34           hole=False,\
35           save="gui",\
36           anomaly=False,\
37           var2=None,\
38           ndiv=10,\
39           mult=1.,\
40           zetitle=["fill"],\
41           slon=None,\
42           slat=None,\
43           svert=None,\
44           stime=None,\
45           outputname=None,\
46           resolution=200,\
47           ope=None,\
48           fileref=None,\
49           minop=0.,\
50           maxop=0.,\
51           titleref="fill",\
52           invert_y=False,\
53           xaxis=[None,None],\
54           yaxis=[None,None],\
55           ylog=False,\
56           xlog=False,\
57           yintegral=False,\
58           blat=None,\
59           blon=None,\
60           tsat=False,\
61           flagnolow=False,\
62           mrate=None,\
63           mquality=False,\
64           trans=1,\
65           zarea=None,\
66           axtime=None,\
67           redope=None,\
68           seevar=False,\
69           xlab=None,\
70           ylab=None,\
71           lbls=None,\
72           lstyle=None,\
73           cross=None,\
74           markdevil=False,\
75           facwind=1.,\
76           trycol=False,\
77           streamflag=False,\
78           nocolorb=False,\
79           analysis=None):
80
81    ####################################################################################################################
82    ### Colorbars http://www.scipy.org/Cookbook/Matplotlib/Show_colormaps?action=AttachFile&do=get&target=colormaps3.png
83
84    #################################
85    ### Load librairies and functions
86    from netCDF4 import Dataset
87    from myplot import getcoord2d,define_proj,makeplotres,simplinterv,vectorfield,ptitle,latinterv,getproj,wrfinterv,dumpbdy,\
88                       fmtvar,definecolorvec,defcolorb,getprefix,putpoints,calculate_bounds,errormess,definesubplot,\
89                       zoomset,getcoorddef,getwinddef,whatkindfile,reducefield,bounds,getstralt,getfield,smooth,nolow,\
90                       getname,localtime,check_localtime,polarinterv,getsindex,define_axis,determineplot,readslices,bidimfind,getlschar,hole_bounds,\
91                       getdimfromvar,select_getfield,find_devil
92    from mymath import deg,max,min,mean,writeascii,fig2data,fig2img
93    import matplotlib as mpl
94    from matplotlib.pyplot import contour,contourf,hist, text,subplot, figure, rcParams, savefig, colorbar, \
95                                  pcolor, show, plot, clabel, title, close, legend, xlabel, axis, ylabel, \
96                                  subplots_adjust, axes, clabel
97    from matplotlib.cm import get_cmap
98    #from mpl_toolkits.basemap import cm
99    import numpy as np
100    from numpy.core.defchararray import find
101    from scipy.stats import gaussian_kde,describe
102    from videosink import VideoSink
103    from times import sol2ls
104    import subprocess
105    #from singlet import singlet
106    from itertools import cycle
107    import os
108
109#########################
110### PRELIMINARY STUFF ###
111#########################
112### we say hello
113    print "********************************************"
114    print "********** WELCOME TO PLANETOPLOT **********"
115    print "********************************************"
116### we ensure namefiles and var are arrays
117    if not isinstance(namefiles, np.ndarray): namefiles = [namefiles]
118    if not isinstance(var, np.ndarray):       var = [var]
119### we initialize a few variables
120    initime=-1 ; sslon = None ; sslat = None
121    k = 0 ; firstfile = True ; count = 0
122### we perform sanity checks and correct for insufficient information
123    if slon is not None: sslon = np.zeros([1,2])
124    if slat is not None: sslat = np.zeros([1,2])
125    if clb is None:            clb = ["def"]*len(var)
126    elif len(clb) < len(var):  clb = [clb[0]]*len(var) ; print "WARNING: less color than vars! setting all to 1st value."
127### we set option trycol i.e. the user wants to try a set of colorbars
128    if trycol: clb = ["Greys","Blues","YlOrRd","jet","spectral","hot","RdBu","RdYlBu","Paired"] ; zetitle = clb ; var = [var[0]]*9
129### we avoid specific cases not yet implemented
130    if mrate is not None and len(var) > 1: errormess("multivar not allowed in movies. should be fixed soon!")
131### we prepare number of plot fields [zelen] and number of plot instances [numplot] according to user choices
132### --> we support multifile and multivar plots : files + vars separated by commas are on the same figure
133    nlon, nlat, nvert, ntime, mapmode, nslices = determineplot(slon, slat, svert, stime, redope)
134    zelen = len(namefiles)*len(var)
135### we correct number of plot fields for possible operation (substract, etc...)
136    if ope is not None:
137        if fileref is not None:       zelen = 3*len(var)*len(namefiles)
138        elif "var" in ope:            zelen = zelen + 1
139    numplot = zelen*nslices
140    print "********** FILES, SLICES, VARS, TOTAL PLOTS: ", len(namefiles), nslices, len(var), numplot
141    print "********** MAPMODE: ", mapmode
142### we define the arrays for plot fields -- which will be placed within multiplot loops
143    all_var  = [[]]*zelen ; all_var2  = [[]]*zelen
144    all_title = [[]]*zelen ; all_varname = [[]]*zelen ; all_namefile = [[]]*zelen ; all_colorb = [[]]*zelen
145    all_time = [[]]*zelen ; all_vert = [[]]*zelen ; all_lat = [[]]*zelen ; all_lon = [[]]*zelen
146    all_windu = [[]]*zelen ; all_windv = [[]]*zelen
147    plot_x = [[]]*zelen ; plot_y = [[]]*zelen ; multiplot = [[]]*zelen
148### tool (should be move to mymath)
149    getVar = lambda searchList, ind: [searchList[i] for i in ind]
150#############################
151### LOOP OVER PLOT FIELDS ###
152#############################
153   
154    for nnn in range(len(namefiles)):
155     for vvv in range(len(var)): 
156
157    ### we load each NETCDF objects in namefiles
158      namefile = namefiles[nnn] 
159      nc  = Dataset(namefile)
160    ### we explore the variables in the file
161      varinfile = nc.variables.keys()
162      if seevar: print varinfile ; exit() 
163    ### we define the type of file we have (gcm, meso, etc...)
164      typefile = whatkindfile(nc)
165      if firstfile:                 typefile0 = typefile
166      elif typefile != typefile0:   errormess("Not the same kind of files !", [typefile0, typefile])
167    ### we care for input file being 1D simulations
168      is1d=999 
169      if "longitude" in nc.dimensions and "latitude" in nc.dimensions: is1d = len(nc.variables["longitude"][:])*len(nc.variables["latitude"][:])
170      elif "lon" in nc.dimensions and "lat" in nc.dimensions: is1d = len(nc.variables["lon"][:])*len(nc.variables["lat"][:])
171      if typefile in ['gcm','earthgcm'] and is1d == 1:       mapmode=0 ; winds=False
172    ### we create default vert and time prescriptions if not here in case mapping mode is on (lat/lon maps)
173      if redope is None and mapmode == 1:
174          if svert is None:  svert = readslices(str(level)) ; nvert=1
175          if stime is None and mrate is None:
176             stime = readslices(str(0)) ; ntime=1 ## this is a default choice
177             print "WELL... nothing about time axis. I took default: first time reference stored in file."
178    ### we get the names of variables to be read. in case only one available, we choose this one.
179    ### (we take out of the test specific names e.g. UV is not in the file but used to ask a wind speed computation)
180      varname = select_getfield(zvarname=var[vvv],znc=nc,ztypefile=typefile,mode='check')
181    ### we get the names of wind variables to be read (if any)
182      if winds:                                                   
183         [uchar,vchar,metwind] = getwinddef(nc)             
184         if uchar == 'not found': winds = False
185    ### we tell the user that either no var or no wind is not acceptable
186      if not varname and not winds: errormess("please set at least winds or var",printvar=nc.variables)
187    ### we get the coordinates lat/lon to be used
188      [lon2d,lat2d] = getcoorddef(nc)
189    ### we get an adapted map projection if none is provided by the user
190      if proj == None:   proj = getproj(nc)                 
191    ### we define plot boundaries given projection or user choices
192      if firstfile:
193         if proj in ["npstere","spstere"]: [wlon,wlat] = polarinterv(lon2d,lat2d)
194         elif proj in ["lcc","laea"]:      [wlon,wlat] = wrfinterv(lon2d,lat2d)
195         else:                             [wlon,wlat] = simplinterv(lon2d,lat2d)
196         if zoom:                          [wlon,wlat] = zoomset(wlon,wlat,zoom)
197         elif zarea is not None:           [wlon,wlat] = latinterv(area=zarea)
198
199#############################################################
200############ WE LOAD 4D DIMENSIONS : x, y, z, t #############
201#############################################################
202
203      ###should be available for GCM or simple files ?
204      ##if ope in ["cat"] and nnn > 0:    count = time[-1] + 1  ## so that a cat is possible with simple subscripts
205
206    ### TYPE 1 : GCM files or simple files
207      if typefile in ["gcm","earthgcm","ecmwf"]:
208      ### this is needed for continuity
209          if slon is not None: sslon = slon 
210          if slat is not None: sslat = slat 
211      ### we define lat/lon vectors. we get what was done in getcoorddef.
212          lat = lat2d[:,0] ; lon = lon2d[0,:]
213      ### we define areas. this is needed for calculate means and weight with area. this is not compulsory (see reduce_field).
214          if "aire" in nc.variables:      area = nc.variables["aire"][:,:]
215          ### --> add a line here if your reference is not present
216          else:                           area = None
217      ### we define altitude vector. either it is referenced or it is guessed based on last variable's dimensions.
218          if "altitude" in nc.variables:   vert = nc.variables["altitude"][:]
219          elif "Alt" in nc.variables:      vert = nc.variables["Alt"][:]
220          elif "lev" in nc.variables:      vert = nc.variables["lev"][:]
221          elif "presnivs" in nc.variables: vert = nc.variables["presnivs"][:]
222          ### --> add a line here if your reference is not present
223          else: 
224              print "No altitude found. Try to build a simple axis." ; dadim = getdimfromvar(nc) 
225              if   len(dadim) == 4:  print "-- 4D field. Assume z is dim 2." ; vert = np.arange(dadim[-3])
226              elif len(dadim) == 3:  print "-- 3D field. Assume z is dim 1." ; vert = [0.]
227              else:                  vert = [0.]
228      ### we define time vector. either it is referenced or it is guessed based on last variable's dimensions.
229          if "Time" in nc.variables:            time = nc.variables["Time"][:]
230          elif "time_counter" in nc.variables:  time = nc.variables["time_counter"][:]/86400. #### convert from s to days
231          elif "time" in nc.variables:          time = nc.variables["time"][:]
232          ### --> add a line here if your reference is not present
233          else: 
234              print "No time found. Try to build a simple axis. Assume t is dim 1." 
235              dadim = getdimfromvar(nc)
236              if   len(dadim) == 4:  time = np.arange(dadim[-4])
237              elif len(dadim) == 3:  time = np.arange(dadim[-3])
238              else:                  time = [0.] #errormess("no time axis found.")
239          ### (SPECIFIC. convert to Ls for Martian GCM files.)
240          if axtime in ["ls"]:
241              print "converting to Ls ..."
242              for iii in range(len(time)):
243                time[iii] = sol2ls(time[iii])
244                if iii > 0:
245                  while abs(time[iii]-time[iii-1]) > 300: time[iii] = time[iii]+360
246          ### (a case where the user would like to set local times. e.g. : 1D plot with no longitude reference)
247          if axtime in ["lt"]:
248              if initime == -1: initime=input("Please type initial local time:")
249              time = (initime+time*24)%24 ; print "LOCAL TIMES.... ", time
250
251    ### TYPE 2 : MESOSCALE FILES
252      elif typefile in ['meso','geo']:
253          ### area not active with mesoscale files
254          area = None 
255          ### HACK TO GET THE CORRECT LAT/LON FROM MESOSCALE FILES WITH 2D LAT/LON ARRAYS
256          ### principle: calculate correct indices then repopulate slon and slat
257          if slon is not None or slat is not None:
258              show_topo_map_user = ((save == 'png') and (typefile == 'meso') and ("HGT" in varinfile) and display)
259              if firstfile and show_topo_map_user:  iwantawhereplot = nc     #show a topo map with a cross on the chosen point
260              else:                                 iwantawhereplot = None   #do not show anything, just select indices
261              numlon = 1 ; numlat = 1 
262              if slon is not None:   numlon = slon.shape[1]   
263              if slat is not None:   numlat = slat.shape[1]
264              indices = np.ones([numlon,numlat,2]) ; vlon = None ; vlat = None
265              for iii in range(numlon): 
266               for jjj in range(numlat):
267                 if slon is not None:  vlon = slon[0][iii]  ### note: slon[:][0] does not work
268                 if slat is not None:  vlat = slat[0][jjj]  ### note: slon[:][0] does not work
269                 indices[iii,jjj,:] = bidimfind(lon2d,lat2d,vlon,vlat,file=iwantawhereplot) 
270                 lonp,latp = ( lon2d[indices[iii,jjj,0],indices[iii,jjj,1]] , lat2d[indices[iii,jjj,0],indices[iii,jjj,1]] )
271              ### possible bug here if several --lat
272              for iii in range(numlon):
273               for jjj in range(numlat):
274                 if slon is not None: sslon[0][iii] = indices[iii,0,1] #...this is idx
275                 if slat is not None: sslat[0][jjj] = indices[0,jjj,0] #...this is idy
276              lonp,latp = ( lon2d[indices[0,0,0],indices[0,0,1]] , lat2d[indices[0,0,0],indices[0,0,1]] )
277          ### we get rid of boundary relaxation zone for plots. important to do that now and not before.
278          if typefile in ['meso'] and mapmode == 1:
279             if '9999' not in getattr(nc,'START_DATE'): lon2d = dumpbdy(lon2d,6) ; lat2d = dumpbdy(lat2d,6) 
280          ### we read the keyword for vertical dimension. we take care for vertical staggering.
281          if varname in ['PHTOT','W']:    vertdim='BOTTOM-TOP_PATCH_END_STAG'
282          else:                           vertdim='BOTTOM-TOP_PATCH_END_UNSTAG'
283          if (var2 is not None and var2 not in ['PHTOT','W']): dumped_vert_stag=True ; vertdim='BOTTOM-TOP_PATCH_END_UNSTAG'
284          else:                                                dumped_vert_stag=False
285          ### we read the keyword for horizontal dimensions. we take care for horizontal staggering.
286          if varname in ['V']:  latdim='SOUTH-NORTH_PATCH_END_STAG'
287          else:                 latdim='SOUTH-NORTH_PATCH_END_UNSTAG'
288          if varname in ['U']:  londim='WEST-EAST_PATCH_END_STAG'
289          else:                 londim='WEST-EAST_PATCH_END_UNSTAG'
290          lon = np.arange(0,getattr(nc,londim),1) ; lat = np.arange(0,getattr(nc,latdim),1)
291          ### we define the time axis and take care of various specificities (lt, ls, sol) or issues (concatenation)
292          if axtime in ["ls","sol"]:
293              lstab, soltab, lttab = getlschar ( namefile, getaxis = True )
294              if axtime == "ls":      time = lstab
295              elif axtime == "sol":   time = soltab
296          else:
297              if ope in ["cat"] and nnn > 0:    count = time[-1] + 1  ## so that a cat is possible with simple subscripts
298              else:                             count = 0
299              if "Times" in nc.dimensions:   time = count + np.arange(0,len(nc.dimensions["Times"]),1)
300              elif "Time" in nc.dimensions:  time = count + np.arange(0,len(nc.dimensions["Time"]),1)
301              else:                          time = count + np.arange(0,1,1)
302          if axtime in ["lt"]:
303              ftime = np.zeros(len(time))
304              for i in range(len(time)): ftime[i] = localtime ( time[i], slon , namefile )
305              time=ftime ; time=check_localtime(time)
306              print "LOCAL TIMES.... ", time
307          ### we define the vertical axis (or lack thereof) and cover possibilities for it to be altitude, pressure, geopotential. quite SPECIFIC.
308          if typefile in ['geo']:   vert = [0.] ; stime = readslices(str(0))
309          else:
310              if vertmode is None:  vertmode=0
311              if vertmode == 0:     
312                  if "vert" in nc.variables: vert = nc.variables["vert"][:]/1000. ; vertmode = 1
313                  else:                      vert = np.arange(0,getattr(nc,vertdim),1)
314              elif vertmode == -1:  vert = nc.variables["PHTOT"][0,:,0,0]/3.72 ; vert = np.array(vert[0:len(vert)-1]) #; print vert
315              elif vertmode == 1 or vertmode == 2:  vert = nc.variables["vert"][:]        ## pressure in Pa
316              else:                                 vert = nc.variables["vert"][:]/1000.  ## altitude in km
317####################################################################
318############ END of WE LOAD 4D DIMENSIONS : x, y, z, t #############
319####################################################################
320
321    ### we fill the arrays of varname, namefile, time, colorbar at the current step considered (NB: why use both k and nnn ?)
322      all_varname[k] = varname
323      all_namefile[k] = namefile
324      all_time[k] = time
325      all_vert[k] = vert
326      all_lat[k] = lat
327      all_lon[k] =  lon
328      all_colorb[k] = clb[vvv]
329      if var2:  all_var2[k], plot_x[k], plot_y[k] = select_getfield(zvarname=var2,znc=nc,ztypefile=typefile,mode='getvar',ztsat=tsat,ylon=all_lon[k],ylat=all_lat[k],yalt=all_vert[k],ytime=all_time[k],analysis=analysis)
330      if winds: all_windu[k] = getfield(nc,uchar) ; all_windv[k] = getfield(nc,vchar)
331    ### we fill the arrays of fields to be plotted at the current step considered
332      all_var[k], plot_x[k], plot_y[k] = select_getfield(zvarname=all_varname[k],znc=nc,ztypefile=typefile,mode='getvar',ztsat=tsat,ylon=all_lon[k],ylat=all_lat[k],yalt=all_vert[k],ytime=all_time[k],analysis=analysis)
333
334      # last line of for namefile in namefiles
335      print "**** GOT SUBDATA:",k," NAMEFILE:",namefile," VAR:",varname, var2 ; k += 1 ; firstfile = False
336
337    ### note to self : stopped comment rewriting here.
338
339    ##################################
340    ### Operation on files (I) with _var
341    if ope is not None and "var" in ope:
342         print "********** OPERATION: ",ope
343         if len(namefiles) > 1: errormess("for this operation... please set only one file !")
344         if len(var) > 2:       errormess("not sure this works for more than 2 vars... please check.")
345         if   "div_var" in ope: all_var[k] = all_var[k-2] / all_var[k-1] ; insert = '_div_'
346         elif "mul_var" in ope: all_var[k] = all_var[k-2] * all_var[k-1] ; insert = '_mul_'
347         elif "add_var" in ope: all_var[k] = all_var[k-2] + all_var[k-1] ; insert = '_add_'
348         elif "sub_var" in ope: all_var[k] = all_var[k-2] - all_var[k-1] ; insert = '_sub_'
349         else:                    errormess(ope+" : non-implemented operation. Check pp.py --help")
350         plot_x[k] = None ; plot_y[k] = None
351         all_time[k] = all_time[k-1] ; all_vert[k] = all_vert[k-1] ; all_lat[k] = all_lat[k-1] ; all_lon[k] = all_lon[k-1] ; all_namefile[k] = all_namefile[k-1]
352         all_varname[k] = all_varname[k-2] + insert + all_varname[k-1]
353         if len(clb) >= zelen: all_colorb[k] = clb[-1]   # last additional user-defined color is for operation plot
354         else:                 all_colorb[k] = all_colorb[k-1]  # if no additional user-defined color... set same as var
355         ### only the operation plot. do not mention colorb so that it is user-defined?
356         if "only" in ope:
357             numplot = 1 ; all_var[0] = all_var[k]
358             all_time[0] = all_time[k] ; all_vert[0] = all_vert[k] ; all_lat[0] = all_lat[k] ; all_lon[0] = all_lon[k] ; all_namefile[0] = all_namefile[k]
359             all_varname[0] = all_varname[k-2] + insert + all_varname[k-1]
360
361
362    ##################################
363    ### Operation on files (II) without _var
364    # we re-iterate on the plots to set operation subplots to make it compatible with multifile (using the same ref file)
365    # (k+1)%3==0 is the index of operation plots
366    # (k+2)%3==0 is the index of reference plots
367    # (k+3)%3==0 is the index of first plots
368    opefirstpass=True
369    if ope is not None and "var" not in ope:
370       print "********** OPERATION: ",ope
371       for k in np.arange(zelen):
372               if len(var) > 1: errormess("for this operation... please set only one var !")
373               if ope in ["-","+","-%","-_only","+_only","-%_only","-_histo"]:
374                  if fileref is None: errormess("fileref is missing!")
375                  else:ncref = Dataset(fileref)
376
377                  if opefirstpass: ## first plots
378                     for ll in np.arange(len(namefiles)):
379                        print "SETTING FIRST PLOT"
380                        all_varname[3*ll] = all_varname[ll] ; all_time[3*ll] = all_time[ll] ; all_vert[3*ll] = all_vert[ll] ; all_lat[3*ll] = all_lat[ll] ; all_lon[3*ll] = all_lon[ll] ; all_namefile[3*ll] = all_namefile[ll] ; all_var2[3*ll] = all_var2[ll] ; all_colorb[3*ll] = all_colorb[ll] ; all_var[3*ll] = all_var[ll]
381                        if plot_y[ll] is not None: plot_y[3*ll] = plot_y[ll] ; plot_x[3*ll] = plot_x[ll]
382                        else: plot_y[3*ll] = None ; plot_x[3*ll] = None
383                        opefirstpass=False
384
385                  if (k+2)%3==0: ## reference plots
386                        print "SETTING REFERENCE PLOT"
387                        all_varname[k] = all_varname[k-1] ; all_time[k] = all_time[k-1] ; all_vert[k] = all_vert[k-1] ; all_lat[k] = all_lat[k-1] ; all_lon[k] = all_lon[k-1] ; all_namefile[k] = all_namefile[k-1] ; all_var2[k] = all_var2[k-1] ; all_colorb[k] = all_colorb[k-1]
388                        all_var[k], plot_x[k], plot_y[k] = select_getfield(zvarname=all_varname[k-1],znc=ncref,ztypefile=typefile,mode='getvar',ztsat=tsat,ylon=all_lon[k],ylat=all_lat[k],yalt=all_vert[k],ytime=all_time[k],analysis=analysis)
389                        if winds: all_windu[k] = getfield(ncref,uchar) ; all_windv[k] = getfield(ncref,vchar)
390
391                  if (k+1)%3==0: ## operation plots
392                     print "SETTING OPERATION PLOT"
393                     all_varname[k] = all_varname[k-1] ; all_time[k] = all_time[k-1] ; all_vert[k] = all_vert[k-1] ; all_lat[k] = all_lat[k-1] ; all_lon[k] = all_lon[k-1] ; all_namefile[k] = all_namefile[k-1] ; all_var2[k] = all_var2[k-1]
394                     if ope in ["-","-_only","-_histo"]:
395                         all_var[k]= all_var[k-2] - all_var[k-1]
396                         if plot_y[k-1] is not None and plot_y[k-2] is not None: plot_y[k] = plot_y[k-2] - plot_y[k-1]
397                         if plot_y[k-2] is None: plot_y[k] = None; plot_x[k] = None
398                     elif ope in ["+","+_only"]:   
399                         all_var[k]= all_var[k-2] + all_var[k-1]
400                         if plot_y[k-1] is not None and plot_y[k-2] is not None: plot_y[k] = plot_y[k-2] + plot_y[k-1]
401                         if plot_y[k-2] is None: plot_y[k] = None; plot_x[k] = None
402                     elif ope in ["-%","-%_only"]:
403                         masked = np.ma.masked_where(all_var[k-1] == 0,all_var[k-1])
404                         masked.set_fill_value([np.NaN])
405                         all_var[k]= 100.*(all_var[k-2] - masked)/masked
406                         if plot_y[k-1] is not None and plot_y[k-2] is not None: 
407                            masked = np.ma.masked_where(plot_y[k-1] == 0,plot_y[k-1])
408                            masked.set_fill_value([np.NaN])
409                            plot_y[k]= 100.*(plot_y[k-2] - masked)/masked
410                         if plot_y[k-2] is None: plot_y[k] = None; plot_x[k] = None
411                     if len(clb) >= zelen: all_colorb[k] = clb[-1]
412                     else: all_colorb[k] = "RdBu_r" # if no additional user-defined color... set a good default one
413                     if winds: all_windu[k] = all_windu[k-2]-all_windu[k-1] ; all_windv[k] = all_windv[k-2] - all_windv[k-1]
414
415               elif ope in ["cat"]:
416                  tabtime = all_time[0];tab = all_var[0];k = 1
417                  if var2: tab2 = all_var2[0]
418                  while k != len(namefiles) and len(all_time[k]) != 0:
419                      if var2: tab2 = np.append(tab2,all_var2[k],axis=0) 
420                      tabtime = np.append(tabtime,all_time[k]) ; tab = np.append(tab,all_var[k],axis=0) ; k += 1
421                  all_time[0] = np.array(tabtime) ; all_var[0] = np.array(tab) ; numplot = 1
422                  if var2: all_var2[0] = np.array(tab2)
423               else: errormess(ope+" : non-implemented operation. Check pp.py --help")
424       if "only" in ope:
425           numplot = 1 ; all_var[0] = all_var[k]
426           all_time[0] = all_time[k] ; all_vert[0] = all_vert[k] ; all_lat[0] = all_lat[k] ; all_lon[0] = all_lon[k] ; all_namefile[0] = all_namefile[k] ; plot_x[0]=plot_x[k] ; plot_y[0]=plot_y[k]
427           all_varname[0] = all_varname[k]
428
429    ##################################
430    ### Open a figure and set subplots
431    fig = figure()
432    subv,subh = definesubplot( numplot, fig, ipreferline = (mapmode == 1) ) 
433    if ope in ['-','-%','-_histo'] and len(namefiles) ==1 : subv,subh = 2,2
434    elif ope in ['-','-%'] and len(namefiles)>1 : subv, subh = len(namefiles), 3
435 
436    #################################
437    ### Time loop for plotting device
438    nplot = 1 ; error = False ; firstpass = True 
439    if lstyle is not None: linecycler = cycle(lstyle)
440    else: linecycler = cycle(["-","--","-.",":"])
441    print "********************************************"
442    while error is False:
443     
444       print "********** PLOT", nplot, " OF ",numplot
445       if nplot > numplot: break
446
447       ####################################################################
448       ## get all indexes to be taken into account for this subplot and then reduce field
449       ## 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
450       if ope is not None:
451           if fileref is not None:      index_f = ((nplot-1)//(nlon*nlat*nvert*ntime))%(3*len(namefiles))  ## OK only 1 var,  see test in the beginning
452           elif "var" in ope:           index_f = ((nplot-1)//(nlon*nlat*nvert*ntime))%(len(var)+1)        ## OK only 1 file, see test in the beginning
453           elif "cat" in ope:           index_f = 0
454       elif not firstpass:
455          if len(namefiles) > 1 and len(var) == 1 and which == "unidim": pass
456          else: yeah = len(namefiles)*len(var) ; index_f = ((nplot-1)//(nlon*nlat*nvert*ntime))%yeah
457       else: yeah = len(namefiles)*len(var) ; index_f = ((nplot-1)//(nlon*nlat*nvert*ntime))%yeah
458       time = all_time[index_f] ; vert = all_vert[index_f] ; lat = all_lat[index_f] ; lon = all_lon[index_f]
459       indexlon  = getsindex(sslon,(nplot-1)%nlon,lon)
460       indexlat  = getsindex(sslat,((nplot-1)//nlon)%nlat,lat)
461       indexvert = getsindex(svert,((nplot-1)//(nlon*nlat))%nvert,vert)
462       plotx=plot_x[index_f] ; ploty=plot_y[index_f]
463       if mrate is not None:                 indextime = None 
464       else:                                 indextime = getsindex(stime,((nplot-1)//(nlon*nlat*nvert))%ntime,time)
465       ltst = None 
466       if typefile in ['meso'] and indextime is not None and len(indextime) < 2: ltst = localtime ( indextime, slon , all_namefile[index_f])
467
468
469       #if mapmode == 0:
470       # if xlab is None:
471       #  if indexlon is None:  xlab = "Longitude"
472       #  elif indexlat is None: xlab = "Latitude"
473       # if ylab is None:
474       #  if indexvert is None: ylab = "Altitude"
475
476
477       print "********** INDEX LON:",indexlon," LAT:",indexlat," VERT:",indexvert," TIME:",indextime
478       ##var = nc.variables["phisinit"][:,:]
479       ##contourf(np.transpose(var),30,cmap = get_cmap(name="Greys_r") ) ; axis('off') ; plot(indexlat,indexlon,'mx',mew=4.0,ms=20.0)
480       ##show()
481       ##exit()
482       #truc = True
483       #truc = False
484       #if truc: indexvert = None
485       ####################################################################
486       ########## REDUCE FIELDS
487       ####################################################################
488       error = False
489       varname = all_varname[index_f]
490       which=''
491       if varname:   ### what is shaded.
492           what_I_plot, error = reducefield( all_var[index_f], d4=indextime, d1=indexlon, d2=indexlat, d3=indexvert, \
493                                             yint=yintegral, alt=vert, anomaly=anomaly, redope=redope, mesharea=area, unidim=is1d)
494           if mult != 2718.:  what_I_plot = what_I_plot*mult
495           else:              what_I_plot = np.log10(what_I_plot) ; print "log plot"
496                 
497       if var2:      ### what is contoured.
498           what_I_plot_contour, error = reducefield( all_var2[index_f], d4=indextime, d1=indexlon, d2=indexlat , d3=indexvert, \
499                                                     yint=yintegral, alt=vert )
500       if winds:     ### what is plot as vectors.
501           vecx, error = reducefield( all_windu[index_f], d4=indextime, d3=indexvert, yint=yintegral, alt=vert)
502           vecy, error = reducefield( all_windv[index_f], d4=indextime, d3=indexvert, yint=yintegral, alt=vert)
503           if varname in [uchar,vchar]: what_I_plot = np.sqrt( np.square(vecx) + np.square(vecy) ) ; varname = "wind"
504 
505       if plotx is not None:
506          plotx, error = reducefield( plotx, d4=indextime, d1=indexlon, d2=indexlat, d3=indexvert, \
507                                             yint=yintegral, alt=vert, anomaly=anomaly, redope=redope, mesharea=area, unidim=is1d)
508          ploty, error = reducefield( ploty, d4=indextime, d1=indexlon, d2=indexlat, d3=indexvert, \
509                                             yint=yintegral, alt=vert, anomaly=anomaly, redope=redope, mesharea=area, unidim=is1d)
510          which='xy'
511       #####################################################################
512       #if truc:
513       #   nx = what_I_plot.shape[2] ; ny = what_I_plot.shape[1] ; nz = what_I_plot.shape[0]
514       #   for k in range(nz): print k,' over ',nz ; what_I_plot[k,:,:] = what_I_plot[k,:,:] / smooth(what_I_plot[k,:,:],12)
515       #   for iii in range(nx):
516       #    for jjj in range(ny):
517       #     deviation = what_I_plot[:,jjj,iii] ; mx = max(deviation) ; mn = min(deviation)
518       #     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
519       #     else:                                                   what_I_plot[0,jjj,iii]     = 0.
520       #     if np.abs(what_I_plot[0,jjj,iii]) > 1.5:
521       #         print iii,jjj,what_I_plot[0,jjj,iii],int(abs(1.-mx)*100.),int(abs(1.-mn)*100.)
522       #         plot(rel)
523       #   show()
524       #   anomaly = True ### pour avoir les bons reglages plots
525       #   what_I_plot = what_I_plot[0,:,:] 
526       #####################################################################
527
528       ####################################################################
529       ### General plot settings
530       changesubplot = (numplot > 1) and (len(what_I_plot.shape) != 1) and (which != "xy")  ## default for 1D plots: superimposed. to be reworked for better flexibility.
531       if changesubplot: subplot(subv,subh,nplot) #; subplots_adjust(wspace=0,hspace=0)
532       colorb = all_colorb[index_f]
533       ####################################################################
534       if error:
535               errormess("There is an error in reducing field !")
536       else:
537               ticks = ndiv + 1 
538               fvar = varname
539               if anomaly: fvar = 'anomaly'
540               ###
541               if mapmode == 0:    ### could this be moved inside imov loop ?
542                   itime=indextime
543                   if len(what_I_plot.shape) == 3: itime=[0]
544                   m = None ; x = None ; y = None
545                   latyeah = lat ; lonyeah = lon
546                   if typefile in ['meso']:
547                       # now that the section is determined we can set the real lat
548                       # ... or for now, a temptative one.
549                       if slon is not None: latyeah = lat2d[:,0]
550                       if slat is not None: lonyeah = lon2d[0,:]
551                   what_I_plot, x, y = define_axis(lonyeah,latyeah,vert,time,indexlon,indexlat,indexvert,\
552                         itime,what_I_plot, len(all_var[index_f].shape),vertmode,redope)
553               ###
554               if (fileref is not None) and ((index_f+1)%3 == 0):    zevmin, zevmax = calculate_bounds(what_I_plot,vmin=minop,vmax=maxop)
555               else:                                                   zevmin, zevmax = calculate_bounds(what_I_plot,vmin=vmin,vmax=vmax)
556               #if (fileref is not None) and (index_f == numplot-1):    colorb = "RdBu_r"
557               if colorb in ["def","nobar","onebar"]:                  palette = get_cmap(name=defcolorb(fvar.upper()))
558               else:                                                   palette = get_cmap(name=colorb)
559               #palette = cm.GMT_split
560               #palette = cm.GMT_globe
561               ##### 1. ELIMINATE 0D or >3D CASES
562               if len(what_I_plot.shape) == 0:   
563                 print "VALUE VALUE VALUE VALUE ::: ",what_I_plot
564                 save = 'donothing'
565               elif len(what_I_plot.shape) >= 4:
566                 print "WARNING!!! ",len(what_I_plot.shape),"-D PLOT NOT SUPPORTED !!! dimensions: ",what_I_plot.shape
567                 errormess("Are you sure you did not forget to prescribe a dimension ?")
568               ##### 2. HANDLE simple 1D/2D field and movies of 1D/2D fields
569               else:
570                 if mrate is not None: iend=len(time)-1
571                 else:                 iend=0
572                 imov = 0
573                 if analysis in ['density','histo','fft','histodensity']: which="xy"
574                 elif len(what_I_plot.shape) == 3:
575                    if var2 and which == '':               which = "contour" ## have to start with contours rather than shading
576                    elif which == '':                      which = "regular"
577                    if mrate is None:      errormess("3D field. Use --rate RATE for movie or specify --time TIME. Exit.")
578                 elif len(what_I_plot.shape) == 2:
579                    if var2 and which == '':               which = "contour" ## have to start with contours rather than shading
580                    elif which == '':                      which = "regular"
581                    if mrate is not None and which == '':  which = "unidim"
582                 elif len(what_I_plot.shape) == 1 and which == '' :
583                    which = "unidim"
584                    if what_I_plot.shape[-1] == 1:      print "VALUE VALUE VALUE VALUE ::: ", what_I_plot[0] ; save = 'donothing'
585##                 if which == "unidim" and len(namefiles) > 1: numplot = 1 # this case is similar to several vars from one file
586                 ##### IMOV LOOP #### IMOV LOOP
587                 while imov <= iend:
588                    print "-> frame ",imov+1, which
589                    if which == "regular":   
590                        if mrate is None:                                   what_I_plot_frame = what_I_plot
591                        else:                                               what_I_plot_frame = what_I_plot[imov,:,:]
592                        if winds:
593                            if mrate is None:                                   vecx_frame = vecx ; vecy_frame = vecy
594                            else:                                               vecx_frame = vecx[imov,:,:] ; vecy_frame = vecy[imov,:,:]
595                    elif which == "contour": 
596                        if mrate is None or what_I_plot_contour.ndim < 3:   what_I_plot_frame = what_I_plot_contour
597                        else:                                               what_I_plot_frame = what_I_plot_contour[imov,:,:]
598                    elif which == "unidim":
599                        if mrate is None:                                   what_I_plot_frame = what_I_plot
600                        else:                                               what_I_plot_frame = what_I_plot[:,imov]  ## because swapaxes
601                    #if mrate is not None:     
602                    if mapmode == 1: 
603                        m = define_proj(proj,wlon,wlat,back=back,blat=blat,blon=blon)  ## this is dirty, defined above but out of imov loop
604                        x, y = m(lon2d, lat2d)                                         ## this is dirty, defined above but out of imov loop
605                    if typefile in ['meso'] and mapmode == 1: 
606                       if '9999' not in getattr(nc,'START_DATE'): what_I_plot_frame = dumpbdy(what_I_plot_frame,6,condition=True)
607#                   if typefile in ['mesoideal']:    what_I_plot_frame = dumpbdy(what_I_plot_frame,0,stag='W',condition=dumped_vert_stag)
608
609                    if which == "unidim":
610#                        if lbls is not None: lbl=lbls[nplot-1]
611                        if lbls is not None: lbl=lbls[index_f]
612                        else:
613                           lbl = ""
614                           if indexlat is not None:  lbl = lbl + " ix" + str(indexlat[0])
615                           if indexlon is not None:  lbl = lbl + " iy" + str(indexlon[0])
616                           if indexvert is not None: lbl = lbl + " iz" + str(indexvert[0])
617                           if indextime is not None: lbl = lbl + " it" + str(indextime[0])
618                           if lbl == "": lbl = all_namefile[index_f]
619
620                        if mrate is not None: x = y  ## because swapaxes...
621                        #what_I_plot_frame = np.diff(what_I_plot_frame, n=1) ; x = x[1:]
622                     
623                        zeline = next(linecycler) ## "-" for simple lines
624                        if tile:      zemarker = 'x'
625                        else:         zemarker = None 
626                        this_is_a_regular_plot = (indexvert is not None) or (indextime is None) or (indexlat is None) or (indexlon is None)
627                        if this_is_a_regular_plot:   plot(x,what_I_plot_frame,zeline,label=lbl,marker=zemarker)  ## vertical profile
628                        else:                        plot(what_I_plot_frame,x,zeline,label=lbl,marker=zemarker)  ## regular plot
629                        if nplot > 1: legend(loc='best')
630                        if indextime is None and axtime is not None and xlab is None:    xlabel(axtime.upper()) ## define the right label
631                        if save == 'txt':  writeascii(np.transpose([x,np.transpose(what_I_plot)]),'profile'+str(nplot*1000+imov)+'.txt')
632                        if axtime == "lt":
633                            ax = mpl.pyplot.gca()
634                            # set ticks where your images will be
635                            ax.get_xaxis().set_ticks(np.arange(0,48,2))
636                            # rename tick labels
637                            ax.get_xaxis().set_ticklabels(["0","2","4","6","8","10","12","14","16","18","20","22",\
638                                                       "0","2","4","6","8","10","12","14","16","18","20","22"])
639                            ## rebound everyone
640                            ax.set_xbound(lower=min(x), upper=max(x))
641                    elif which == "xy":
642                        if lbls is not None: lbl=lbls[index_f]
643                        else: lbl=None
644                        if analysis is not None:
645                           if analysis == 'histo': 
646                               if zelen == 1:
647                                  mpl.pyplot.hist(ploty.flatten(),bins=ndiv,normed=True, alpha=0.67, facecolor = 'green', label = lbls)
648                                  mpl.pyplot.legend()
649                                  mpl.pyplot.grid(True)
650                                  mpl.pyplot.title(zetitle)
651                               else:
652                                  multiplot[index_f]=ploty.flatten()
653                                  if index_f == zelen-1: 
654                                     if ope is not None: multiplot = getVar(multiplot,3*np.arange((index_f+1)/3)+2) ## we only compute histograms for the operation plots
655                                     mpl.pyplot.hist(multiplot,bins=ndiv,normed=True, alpha=0.75, label = lbls) 
656                                     mpl.pyplot.legend()
657                                     mpl.pyplot.grid(True)
658                                     mpl.pyplot.title(zetitle)
659                           elif analysis in ['density','histodensity']:
660                                  if ope is not None and (index_f+1)%3 !=0: pass
661                                  else:
662                                     plotx = np.linspace(min(ploty.flatten()),max(ploty.flatten()),1000)
663                                     density = gaussian_kde(ploty.flatten())
664   #                                  density.covariance_factor = lambda : .25  # adjust the covariance factor to change the bandwidth if needed
665   #                                  density._compute_covariance()
666                                        # display the mean and variance of the kde:
667                                     sample = density.resample(size=20000)
668                                     n, (smin, smax), sm, sv, ss, sk = describe(sample[0])
669                                     mpl.pyplot.plot(plotx,density(plotx), label = lbl+'\nmean: '+str(sm)[0:5]+'   std: '+str(np.sqrt(sv))[0:5]+'\nskewness: '+str(ss)[0:5]+'   kurtosis: '+str(sk)[0:5])
670                                     if analysis == 'histodensity':  # plot both histo and density (to assess the rightness of the kernel density estimate for exemple) and display the estimated variance
671                                        mpl.pyplot.hist(ploty.flatten(),bins=ndiv,normed=True, alpha=0.30, label = lbl)
672                                     if index_f == zelen-1: mpl.pyplot.legend() ; mpl.pyplot.title(zetitle)
673                           else:
674                              plot(plotx,ploty,label = lbl)
675                              if index_f == zelen-1: mpl.pyplot.legend() ; mpl.pyplot.title(zetitle)
676                              mpl.pyplot.grid(True)
677                        else:
678                           plot(plotx,ploty,label = lbl)
679                           if index_f == zelen-1: mpl.pyplot.legend() ; mpl.pyplot.title(zetitle)
680                        if varname == 'hodograph':
681                            a=0
682                            for ii in np.arange(len(time)): 
683                               if a%6 == 0: mpl.pyplot.text(plotx[ii],ploty[ii],time[ii]) 
684                               a=a+1
685                            mpl.pyplot.grid(True)
686
687                    elif which == "regular":
688                   
689                        # plot stream lines if there is a stream file and a vert/lat slice. Might not work with movies ??
690                        if streamflag and sslat is None and svert is None:
691                             streamfile = all_namefile[index_f].replace('.nc','_stream.nc')
692                             teststream = os.path.exists(streamfile)
693                             if teststream:
694                                print 'INFO: Using stream file',streamfile, 'for stream lines'
695                                ncstream = Dataset(streamfile)
696                                psi = getfield(ncstream,'psi')
697                                psi = psi[0,:,:,0] # time and longitude are dummy dimensions
698                                if psi.shape[1] != len(x) or psi.shape[0] != len(y):
699                                    errormess('stream file does not fit! Dimensions: '+str(psi.shape)+' '+str(x.shape)+' '+str(y.shape))
700                                zelevels = np.arange(-1.e10,1.e10,1.e9)
701                                zemin = np.min(abs(zelevels))
702                                zemax = np.max(abs(zelevels))
703                                zewidth  =  (abs(zelevels)-zemin)*(5.- 0.5)/(zemax - zemin) + 0.5 # linewidth ranges from 5 to 0.5
704                                cs = contour( x,y,psi, zelevels, colors='k', linewidths = zewidth)
705                                clabel(cs, inline=True, fontsize = 4.*rcParams['font.size']/5., fmt="%1.1e")
706                             else:
707                                print 'WARNING: STREAM FILE',streamfile, 'DOES NOT EXIST !'
708                             
709                        if hole:         what_I_plot_frame = hole_bounds(what_I_plot_frame,zevmin,zevmax)
710                        else:            what_I_plot_frame = bounds(what_I_plot_frame,zevmin,zevmax)
711                        if flagnolow:    what_I_plot_frame = nolow(what_I_plot_frame)
712                        if not tile:
713                            #zelevels = np.linspace(zevmin*(1. + 1.e-7),zevmax*(1. - 1.e-7)) #,num=20)
714                            zelevels = np.linspace(zevmin,zevmax,num=ticks)
715                            #what_I_plot_frame = smooth(what_I_plot_frame,100)
716                            if mapmode == 1:       m.contourf( x, y, what_I_plot_frame, zelevels, cmap = palette, alpha=trans)
717                            elif mapmode == 0:     contourf( x, y, what_I_plot_frame, zelevels, cmap = palette, alpha=trans)
718                        else:
719                            if mapmode == 1:       m.pcolor( x, y, what_I_plot_frame, cmap = palette, vmin=zevmin, vmax=zevmax, alpha=trans)
720                            elif mapmode == 0:     pcolor( x, y, what_I_plot_frame, cmap = palette, vmin=zevmin, vmax=zevmax, alpha=trans)
721
722                        if (cross is not None or markdevil) and mapmode == 1:
723                            if cross is not None: idx,idy=m(cross[0][0],cross[0][1])
724                            elif markdevil:
725                                idx,idy=find_devil(nc,indextime)
726                                idx,idy=x[idx,idy],y[idx,idy]
727                            mpl.pyplot.plot([idx],[idy],'+k',mew=0.5,ms=18)
728
729                        if not nocolorb:
730                          if colorb not in ['nobar','onebar']:
731                            if (fileref is not None) and ((index_f+1)%3 == 0):   daformat = "%.3f" 
732                            elif mult != 1:                                        daformat = "%.1f"
733                            else:                                                  daformat = fmtvar(fvar.upper())
734                            #if proj in ['moll','cyl']:  zeorientation="horizontal" ; zepad = 0.05
735                            if proj in ['moll']:        zeorientation="horizontal" ; zepad = 0.05
736                            else:                       zeorientation="vertical" ; zepad = 0.03
737                            zecb = colorbar( fraction=0.05,pad=zepad,format=daformat,orientation=zeorientation,\
738                                      ticks=np.linspace(zevmin,zevmax,num=min([ticks/2+1,21])),extend='neither',spacing='proportional' ) 
739                            if zeorientation == "horizontal" and zetitle[0] != "fill": zecb.ax.set_xlabel(zetitle[index_f]) ; zetitle[index_f]=""
740                        if winds:
741                            if typefile in ['meso']:
742                                if '9999' not in getattr(nc,'START_DATE') : [vecx_frame,vecy_frame] = [dumpbdy(vecx_frame,6,stag=uchar,condition=True), dumpbdy(vecy_frame,6,stag=vchar,condition=True)]
743                                key = True
744                                if fvar in ['UV','uv','uvmet']: key = False
745                            elif typefile in ['gcm']:
746                                key = False
747                            if metwind and mapmode == 1:   [vecx_frame,vecy_frame] = m.rotate_vector(vecx_frame, vecy_frame, lon2d, lat2d)
748                            if trans != 0.0:   colorvec = definecolorvec(colorb) 
749                            else:              colorvec = definecolorvec(back) 
750                            vectorfield(vecx_frame, vecy_frame, x, y, stride=stride, csmooth=2,\
751                                             #scale=15., factor=300., color=colorvec, key=key)
752                                             scale=20., factor=250./facwind, color=colorvec, key=key)
753                                                              #200.         ## or csmooth=stride
754                        ### THIS IS A QUITE SPECIFIC PIECE (does not work for mesoscale files)
755                        if ope == '-_histo' and nplot == numplot: # this should work as long as ope is '-' guarantees 3 plots for 4 panels without contour
756                            subplot(subv,subh,nplot+1)
757                            rcParams["legend.fontsize"] = 'xx-large'
758                            if indexlat is None:
759                                latmin = -50.; latmax = 50. # latitude range for histogram of difference
760                                zeindexlat = (lat<latmax)*(lat>latmin)
761                                if typefile in ['meso']: zeindexlat = 10
762                                # this follows the define_axis logic in myplot.py:
763                                if indextime is None or indexlon is None: what_I_plot_frame = what_I_plot_frame[zeindexlat,:]
764                                else: what_I_plot_frame = what_I_plot_frame[:,zeindexlat]
765                            toplot = np.ravel(what_I_plot_frame[np.isnan(what_I_plot_frame)==False])
766                            zebins = np.linspace(zevmin,zevmax,num=30)
767                            hist(toplot,bins=zebins,histtype='step',linewidth=2,color='k',normed=True)
768                            zestd = np.std(toplot);zemean = np.mean(toplot)
769                            zebins = np.linspace(zevmin,zevmax,num=300)
770                            zegauss = (1./(zestd * np.sqrt(2 * np.pi)) * np.exp( - (zebins - zemean)**2 / (2 * zestd**2) ) )
771                            plot(zebins, zegauss, linewidth=1, color='r',label="mean: "+str(zemean)[0:5]+"\nstd: "+str(zestd)[0:5])
772                            legend(loc=0,frameon=False)
773                            subplot(subv,subh,nplot) # go back to last plot for title of contour difference
774                        if ope is not None and "only" not in ope: title("fig(1) "+ope+" fig(2)")
775                        elif ope is not None and "only" in ope: title("fig(1) "+ope[0]+" fig(2)")
776                           
777                    elif which == "contour":
778                        zevminc, zevmaxc = calculate_bounds(what_I_plot_frame, vmin=min(what_I_plot_frame), vmax=max(what_I_plot_frame))
779                        zelevels = np.linspace(zevminc,zevmaxc,ticks/2) #20)
780                        ### another dirty specific stuff in the wall
781                        if var2 == 'HGT':        zelevels = np.arange(-10000.,30000.,500.) #1000.)
782                        elif var2 == 'tpot':     zelevels = np.arange(270,370,5)
783                        elif var2 == 'tk':       zelevels = np.arange(150,250,5)
784                        elif var2 == 'wstar':    zelevels = np.arange(0,10,1.0)
785                        elif var2 == 'zmax_th':  zelevels = np.arange(0,10,2.0) ; what_I_plot_frame = what_I_plot_frame / 1000.
786                        ###
787                        if mapmode == 0:   
788                            what_I_plot_frame, x, y = define_axis( lonyeah,latyeah,vert,time,indexlon,indexlat,indexvert,\
789                                                              itime,what_I_plot_frame, len(all_var2[index_f].shape),vertmode,redope)
790                            ## is this needed? only if len(all_var2[index_f].shape) != len(all_var[index_f].shape)
791                            cs = contour( x,y,what_I_plot_frame, zelevels, colors='k', linewidths = 0.33)#, alpha=0.5, linestyles='solid')
792                            #cs = contour( x,y,what_I_plot_frame, zelevels, colors='w', linewidths = 0.5)#, alpha=0.5, linestyles='solid')
793                            clabel(cs, inline=1, fontsize = 4.*rcParams['font.size']/5., fmt=fmtvar(var2.upper()))
794                        elif mapmode == 1: 
795                            cs = m.contour( x,y,what_I_plot_frame, zelevels, colors='k', linewidths = 0.33)#, alpha=0.5, linestyles='solid')
796                            #clabel(cs, inline=0, fontsize = rcParams['font.size'], fmt="%.0f") #fmtvar(var2.upper()))
797                    if which in ["regular","unidim","xy"]:
798
799                        if nplot > 1 and which in ["unidim","xy"]:
800                           pass  ## because we superimpose nplot instances
801                        else:
802                           # Axis directives for movie frames [including the first one).
803                           zxmin, zxmax = xaxis ; zymin, zymax = yaxis
804                           if zxmin is not None: mpl.pyplot.xlim(xmin=zxmin)
805                           if zxmax is not None: mpl.pyplot.xlim(xmax=zxmax)
806                           if zymin is not None: mpl.pyplot.ylim(ymin=zymin)
807                           if zymax is not None: mpl.pyplot.ylim(ymax=zymax)
808                           if ylog and not xlog:      mpl.pyplot.semilogy()
809                           if xlog and not ylog:      mpl.pyplot.semilogx()
810                           if xlog and ylog: 
811                                mpl.pyplot.xscale('log') 
812                                mpl.pyplot.yscale('log')
813                           if invert_y:  ax = mpl.pyplot.gca() ; ax.set_ylim(ax.get_ylim()[::-1])
814                           if xlab is not None: xlabel(xlab)
815                           if ylab is not None: ylabel(ylab)
816
817                        if mrate is not None:
818                           ### THIS IS A MENCODER MOVIE
819                           if mrate > 0:
820                             figframe=mpl.pyplot.gcf()
821                             if mquality:   figframe.set_dpi(600.)
822                             else:          figframe.set_dpi(200.)
823                             mframe=fig2img(figframe)
824                             if imov == 0:
825                                moviename='movie' ;W,H = figframe.canvas.get_width_height()
826                                video = VideoSink((H,W), moviename, rate=mrate, byteorder="rgba")
827                             video.run(mframe) ; close()
828                             if imov == iend: video.close()                           
829                           ### THIS IS A WEBPAGE MOVIE
830                           else:
831                             nameframe = "image"+str(1000+imov)
832                             makeplotres(nameframe,res=100.,disp=False) ; close()
833                             if imov == 0: myfile = open("zepics", 'w')
834                             myfile.write("modImages["+str(imov)+"] = '"+nameframe+"_100.png';"+ '\n')
835                             if imov == iend:
836                                 myfile.write("first_image = 0;"+ '\n')
837                                 myfile.write("last_image = "+str(iend)+";"+ '\n')
838                                 myfile.close()
839                        if var2 and which == "regular":  which = "contour"
840                        imov = imov+1
841                    elif which == "contour":
842                        which = "regular"
843
844       ### Next subplot
845       zevarname = varname
846       if redope is not None: zevarname = zevarname + "_" + redope
847       basename = getname(var=zevarname,var2=var2,winds=winds,anomaly=anomaly)
848       if len(what_I_plot.shape) > 3:
849           basename = basename + getstralt(nc,level) 
850       if mrate is not None: basename = "movie_" + basename
851       if typefile in ['meso']:
852            if sslon is not None: basename = basename + "_lon_" + str(int(round(lonp)))
853            if sslat is not None: basename = basename + "_lat_" + str(int(round(latp)))
854            plottitle = basename
855            ### dans le nouveau systeme time=ls,sol,lt cette ligne pourrait ne servir a rien (ou deplacer au dessus)
856            if addchar and indextime is not None:   [addchar,gogol,gogol2] = getlschar ( all_namefile[index_f] )  ;  plottitle = plottitle + addchar
857            ### en fait redope is None doit etre remplace par : n'est ni maxt ni mint
858            if redope is None and ltst is not None and ( (mapmode == 0) or (proj in ["lcc","laea","merc","nsper"]) ):  plottitle = plottitle + "_LT" + str(ltst)
859       else:
860            if fileref is not None:
861               if (index_f+1)%3 == 0:     plottitle = basename+' '+"fig(1) "+ope+" fig(2)"
862               elif (index_f+2)%3 == 0:   plottitle = basename+' '+fileref
863               else:                        plottitle = basename+' '+all_namefile[index_f]
864            else:                            plottitle = basename+' '+all_namefile[index_f]
865       if mult != 1:                         plottitle = '{:.0e}'.format(mult) + "*" + plottitle
866       if zetitle[0] != "fill":                 
867          if index_f < len(zetitle): plottitle = zetitle[index_f]
868          else: plottitle = zetitle[0]
869          if titleref is "fill":             titleref=zetitle[index_f]
870          if fileref is not None and which != "xy":
871             if (index_f+2)%3 == 0:        plottitle = titleref
872             if (index_f+1)%3 == 0:        plottitle = "fig(1) "+ope+" fig(2)"
873#       if indexlon is not None:      plottitle = plottitle + " lon: " + str(min(lon[indexlon])) +" "+ str(max(lon[indexlon]))
874#       if indexlat is not None:      plottitle = plottitle + " lat: " + str(min(lat[indexlat])) +" "+ str(max(lat[indexlat]))
875#       if indexvert is not None:     plottitle = plottitle + " vert: " + str(min(vert[indexvert])) +" "+ str(max(vert[indexvert]))
876#       if indextime is not None:     plottitle = plottitle + " time: " + str(min(time[indextime])) +" "+ str(max(time[indextime]))
877       if colorb != "onebar": title( plottitle )
878       if nplot >= numplot: error = True
879       nplot += 1
880
881       if len(namefiles) > 1 and len(var) == 1 and which == "unidim": index_f=index_f+1
882       firstpass=False
883
884    if colorb == "onebar":
885        cax = axes([0.1, 0.2, 0.8, 0.03]) # a ameliorer
886        zecb = colorbar(cax=cax, orientation="horizontal", format=fmtvar(fvar.upper()),\
887                 ticks=np.linspace(zevmin,zevmax,num=min([ticks/2+1,21])),extend='neither',spacing='proportional')
888        if zetitle[0] != "fill": zecb.ax.set_xlabel(zetitle[index_f]) ; zetitle[index_f]=""
889
890
891    ##########################################################################
892    ### Save the figure in a file in the data folder or an user-defined folder
893    if outputname is None:
894       if typefile in ['meso']:   prefix = getprefix(nc)
895       elif typefile in ['gcm']:            prefix = 'LMD_GCM_'
896       else:                                prefix = ''
897    ###
898       zeplot = prefix + basename
899       if zoom:            zeplot = zeplot + "zoom"+str(abs(zoom))
900       if addchar:         zeplot = zeplot + addchar
901       if numplot <= 0:    zeplot = zeplot + "_LT"+str(abs(numplot))
902    ###
903       if not target:      zeplot = namefile[0:find(namefile,'wrfout')] + zeplot
904       else:               zeplot = target + "/" + zeplot 
905    ###
906    else:
907       zeplot=outputname
908
909    if mrate is None:
910        pad_inches_value = 0.35
911        if wlon[1]-wlon[0] < 2.: pad_inches_value = 0.5  # LOCAL MODE (small values)
912        print "********** SAVE ", save
913        if save == 'png': 
914            if display: makeplotres(zeplot,res=100.,pad_inches_value=pad_inches_value) #,erase=True)  ## a miniature
915            makeplotres(zeplot,res=resolution,pad_inches_value=pad_inches_value,disp=False)
916        elif save in ['eps','svg','pdf']:     makeplotres(zeplot,pad_inches_value=pad_inches_value,disp=False,ext=save)
917        elif save == 'gui':                   show()
918        elif save == 'donothing':             pass
919        elif save == 'txt':                   print "Saved results in txt file." 
920        else: 
921            print "INFO: save mode not supported. using gui instead."
922            show()
923
924    ###################################
925    #### Getting more out of this video -- PROBLEMS WITH CREATED VIDEOS
926    #
927    #if mrate is not None:
928    #    print "Re-encoding movie.. first pass"
929    #    video.first_pass(filename=moviename,quality=mquality,rate=mrate)
930    #    print "Re-encoding movie.. second pass"
931    #    video.second_pass(filename=moviename,quality=mquality,rate=mrate)   
932
933    ###############
934    ### Now the end
935    return zeplot
Note: See TracBrowser for help on using the repository browser.