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

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

UTIL PYTHON : improved comments. otherwise purely cosmetic changes to improve lisibility.

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