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

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

Python. Simplified planetoplot.py: all specific cases are now under the hood, in myplot. (see select_case). The user can add new specific cases to select_case routine without planetoplot.py getting dirtier.

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