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

Last change on this file since 469 was 468, checked in by aslmd, 14 years ago

UTIL:PYTHON: added support for Ls and sol indexing through option --axtime (mesoscale model files). also a bit of cleaning, especially with info to user, now more compact.

  • Property svn:executable set to *
File size: 31.7 KB
Line 
1#######################
2##### PLANETOPLOT #####
3#######################
4
5### A. Spiga     -- LMD -- 06~09/2011 -- General building and mapping capabilities
6### T. Navarro   -- LMD -- 10~11/2011 -- Improved use for GCM and added sections + 1Dplot capabilities
7### A. Colaitis  -- LMD --    11/2011 -- Mostly minor improvements and inter-plot operation capabilities + zrecast interpolation for gcm
8### A. Spiga     -- LMD -- 11~12/2011 -- Extended multivar subplot capabilities + cosmetic changes + general cleaning and tests
9### A. Colaitis  -- LMD --    12/2011 -- Added movie capability [mencoder must be installed]
10### A. Spiga     -- LMD --    12/2011 -- Added HTML animated page capability + general tests of consistency [winds, etc...]
11
12def planetoplot (namefiles,\
13           level=0,\
14           vertmode=0,\
15           proj=None,\
16           back=None,\
17           target=None,
18           stride=3,\
19           var=None,\
20           colorb="def",\
21           winds=False,\
22           addchar=None,\
23           interv=[0,1],\
24           vmin=None,\
25           vmax=None,\
26           tile=False,\
27           zoom=None,\
28           display=True,\
29           hole=False,\
30           save="gui",\
31           anomaly=False,\
32           var2=None,\
33           ndiv=10,\
34           mult=1.,\
35           zetitle="fill",\
36           slon=None,\
37           slat=None,\
38           svert=None,\
39           stime=None,\
40           outputname=None,\
41           resolution=200,\
42           ope=None,\
43           fileref=None,\
44           minop=0.,\
45           maxop=0.,\
46           titleref="fill",\
47           invert_y=False,\
48           xaxis=[None,None],\
49           yaxis=[None,None],\
50           ylog=False,\
51           yintegral=False,\
52           blat=None,\
53           blon=None,\
54           tsat=False,\
55           flagnolow=False,\
56           mrate=None,\
57           mquality=False,\
58           trans=1,\
59           zarea=None,\
60           axtime=None):
61
62
63    ####################################################################################################################
64    ### Colorbars http://www.scipy.org/Cookbook/Matplotlib/Show_colormaps?action=AttachFile&do=get&target=colormaps3.png
65
66    #################################
67    ### Load librairies and functions
68    from netCDF4 import Dataset
69    from myplot import getcoord2d,define_proj,makeplotres,simplinterv,vectorfield,ptitle,latinterv,getproj,wrfinterv,dumpbdy,\
70                       fmtvar,definecolorvec,defcolorb,getprefix,putpoints,calculate_bounds,errormess,definesubplot,\
71                       zoomset,getcoorddef,getwinddef,whatkindfile,reducefield,bounds,getstralt,getfield,smooth,nolow,\
72                       getname,localtime,polarinterv,getsindex,define_axis,determineplot,readslices,bidimfind,getlschar,hole_bounds
73    from mymath import deg,max,min,mean,get_tsat,writeascii,fig2data,fig2img
74    import matplotlib as mpl
75    from matplotlib.pyplot import contour,contourf, subplot, figure, rcParams, savefig, colorbar, pcolor, show, plot, clabel, title, close, legend, xlabel
76    from matplotlib.cm import get_cmap
77    import numpy as np
78    from numpy.core.defchararray import find
79    from videosink import VideoSink
80    import subprocess
81
82    ################################
83    ### Preliminary stuff
84    ################################
85    print "********************************************"
86    print "********** WELCOME TO PLANETOPLOT **********"
87    print "********************************************"
88    if not isinstance(namefiles, np.ndarray): namefiles = [namefiles]
89    if not isinstance(var, np.ndarray):       var = [var]
90
91    ################################
92    ### Which plot needs to be done?
93    ################################
94    nlon, nlat, nvert, ntime, mapmode, nslices = determineplot(slon, slat, svert, stime)
95    vlon = None ; vlat = None
96    if slon is not None: vlon = slon[0][0]
97    if slat is not None: vlat = slat[0][0]
98    if mapmode == 0:       winds=False
99    elif mapmode == 1:     
100        if svert is None:  svert = readslices(str(level)) ; nvert=1
101        if stime is None and mrate is None:
102           stime = readslices(str(0)) ; ntime=1 ## this is a default choice
103           print "WELL... nothing about time axis. I took default: first time reference stored in file."
104    if mrate is not None and len(var) > 1: errormess("multivar not allowed in movies. should be fixed soon!")
105    zelen = len(namefiles)*len(var)
106    numplot = zelen*nslices
107    print "********** FILES, SLICES, VARS, TOTAL PLOTS: ", len(namefiles), nslices, len(var), numplot
108    if ope is not None:
109        if fileref is not None:       zelen = zelen + 2
110        elif "var" in ope:            zelen = zelen + 1
111    all_var  = [[]]*zelen ; all_var2  = [[]]*zelen ; all_title = [[]]*zelen ; all_varname = [[]]*zelen ; all_namefile = [[]]*zelen ; all_time = [[]]*zelen ; all_windu = [[]]*zelen ; all_windv = [[]]*zelen
112 
113    #################################################################################################
114    ### Loop over the files + vars initially separated by commas to be plotted on the same figure ###
115    #################################################################################################
116    k = 0 ; firstfile = True ; count = 0
117    for nnn in range(len(namefiles)):
118     for vvv in range(len(var)): 
119
120      ######################
121      ### Load NETCDF object
122      namefile = namefiles[nnn] 
123      nc  = Dataset(namefile)
124
125      ##################################
126      ### Initial checks and definitions
127      ### ... TYPEFILE
128      typefile = whatkindfile(nc)                                 
129      if typefile in ['mesoideal']:   mapmode=0;winds=False
130      if firstfile: print "********** MAPMODE: ", mapmode
131      if firstfile:                 typefile0 = typefile
132      elif typefile != typefile0:   errormess("Not the same kind of files !", [typefile0, typefile])
133      ### ... VAR
134      varname=var[vvv]
135      if varname not in nc.variables: varname = False
136      ### ... WINDS
137      if winds:                                                   
138         [uchar,vchar,metwind] = getwinddef(nc)             
139         if uchar == 'not found': winds = False
140      if not varname and not winds: errormess("please set at least winds or var",printvar=nc.variables)
141      ### ... COORDINATES, could be moved below
142      [lon2d,lat2d] = getcoorddef(nc)
143      ### ... PROJECTION
144      if ((proj == None) and (typefile not in ['mesoideal'])):   proj = getproj(nc)                 
145
146##########################################################
147      if typefile == "gcm":
148          lat = nc.variables["latitude"][:] ; lon = nc.variables["longitude"][:]
149          if "Time" in nc.variables:      time = nc.variables["Time"][:]
150          elif "time" in nc.variables:    time = nc.variables["time"][:]
151          else:                           errormess("no time axis found.")
152          vert = nc.variables["altitude"][:]
153          if axtime in ["ls","sol"]:   errormess("not supported. should not be too difficult though.")
154      elif typefile in ['meso','mesoapi','geo','mesoideal']:
155          ### the following lines are kind of dirty... not possible to ask for several lats and lons
156          if vlon is not None or vlat is not None:   indices = bidimfind(lon2d,lat2d,vlon,vlat) 
157          if slon is not None: slon[0][0] = indices[0] ; slon[0][1] = indices[0]
158          if slat is not None: slat[0][0] = indices[1] ; slat[0][1] = indices[1]
159          if varname in ['PHTOT','W']:    vertdim='BOTTOM-TOP_PATCH_END_STAG'
160          else:                           vertdim='BOTTOM-TOP_PATCH_END_UNSTAG'
161          if (var2 is not None and var2 not in ['PHTOT','W']):
162               vertdim='BOTTOM-TOP_PATCH_END_UNSTAG'
163               dumped_vert_stag=True
164          else: dumped_vert_stag=False
165          if varname in ['V']:  latdim='SOUTH-NORTH_PATCH_END_STAG'
166          else:                 latdim='SOUTH-NORTH_PATCH_END_UNSTAG'
167          if varname in ['U']:  londim='WEST-EAST_PATCH_END_STAG'
168          else:                 londim='WEST-EAST_PATCH_END_UNSTAG'
169          lon = np.arange(0,getattr(nc,londim),1) ; lat = np.arange(0,getattr(nc,latdim),1)
170          ###
171          if axtime in ["ls","sol"]:
172              lstab, soltab, lttab = getlschar ( namefile, getaxis = True )
173              if axtime == "ls":      time = lstab
174              elif axtime == "sol":   time = soltab
175          else:
176              if "Times" in nc.variables:   time = count + np.arange(0,len(nc.variables["Times"]),1)
177              elif "Time" in nc.variables:  time = count + np.arange(0,len(nc.variables["Time"]),1)
178              count = time[-1] + 1  ## so that a cat is possible with simple subscripts
179          ###
180          if typefile in ['geo']:   vert = [0.] ; stime = readslices(str(0))
181          else:
182              if vertmode is None:  vertmode=0
183              if vertmode == 0:     vert = np.arange(0,getattr(nc,vertdim),1)
184              else:                 vert = nc.variables["vert"][:]
185       #if firstfile:
186       #   lat0 = lat
187       #elif len(lat0) != len(lat):
188       #   errormess("Not the same latitude lengths !", [len(lat0), len(lat)])
189       #elif sum((lat == lat0) == False) != 0:
190       #   errormess("Not the same latitudes !", [lat,lat0])
191       ## Faire d'autre checks sur les compatibilites entre fichiers!!
192##########################################################
193
194      if firstfile:
195         ##########################
196         ### Define plot boundaries
197         ### todo: possible areas in latinterv in argument (ex: "Far_South_Pole")
198         if proj in ["npstere","spstere"]: [wlon,wlat] = polarinterv(lon2d,lat2d)
199         elif proj in ["lcc","laea"]:      [wlon,wlat] = wrfinterv(lon2d,lat2d)
200         else:                             [wlon,wlat] = simplinterv(lon2d,lat2d)
201         if zoom:                          [wlon,wlat] = zoomset(wlon,wlat,zoom)
202         elif zarea is not None: [wlon,wlat] = latinterv(area=zarea) 
203
204      all_varname[k] = varname
205      all_namefile[k] = namefile
206      all_time[k] = time
207      if var2: all_var2[k] = getfield(nc,var2)
208      if winds: all_windu[k] = getfield(nc,uchar) ; all_windv[k] = getfield(nc,vchar)
209      ##### SPECIFIC
210      if varname in ["temp","t","T_nadir_nit","T_nadir_day","temp_day","temp_night"] and tsat:
211          tt=getfield(nc,varname) ; print "computing Tsat-T, I ASSUME Z-AXIS IS PRESSURE"
212          if type(tt).__name__=='MaskedArray':  tt.set_fill_value([np.NaN]) ; tinput=tt.filled()
213          else:                                 tinput=tt
214          all_var[k]=get_tsat(vert,tinput,zlon=lon,zlat=lat,zalt=vert,ztime=time)
215      else:
216      ##### GENERAL STUFF HERE
217          all_var[k] = getfield(nc,varname)
218     
219      print "**** GOT SUBDATA:",k," NAMEFILE:",namefile," VAR:",varname, var2 ; k += 1 ; firstfile = False
220      #### End of for namefile in namefiles
221
222    ##################################
223    ### Operation on files
224    if ope is not None:
225        print "********** OPERATION: ",ope
226        if "var" not in ope:
227             if len(var) > 1: errormess("for this operation... please set only one var !")
228             if ope in ["-","+","-%"]:
229                if fileref is not None:   all_var[k] = getfield(Dataset(fileref),all_varname[k-1]) ; all_varname[k] = all_varname[k-1] ; all_time[k] = all_time[k-1] ; all_namefile[k] = all_namefile[k-1]
230                else:                     errormess("fileref is missing!") 
231                if ope == "-":     all_var[k+1]= all_var[k-1] - all_var[k]
232                elif ope == "+":   all_var[k+1]= all_var[k-1] + all_var[k]
233                elif ope == "-%":  all_var[k+1]= 100.*(all_var[k-1] + all_var[k])/all_var[k]
234                all_varname[k+1] = all_varname[k] ; all_time[k+1] = all_time[k] ; all_namefile[k+1] = all_namefile[k] ; numplot = numplot+2
235             elif ope in ["cat"]:
236                tabtime = all_time[0];tab = all_var[0];k = 1
237                if var2: tab2 = all_var2[0]
238                while k != len(namefiles):
239                    if var2: tab2 = np.append(tab2,all_var2[k],axis=0) 
240                    tabtime = np.append(tabtime,all_time[k]) ; tab = np.append(tab,all_var[k],axis=0) ; k += 1
241                #all_time[0] = np.arange(0,len(tab),1) ### AS: time reference is too simplistic, should be better
242                all_time[0] = np.array(tabtime) ; all_var[0] = np.array(tab) ; numplot = 1
243                if var2: all_var2[0] = np.array(tab2)
244             else: errormess(ope+" : non-implemented operation. Check pp.py --help")
245        else:
246             if len(namefiles) > 1: errormess("for this operation... please set only one file !") 
247             if len(var) > 2:       errormess("not sure this works for more than 2 vars... please check.")
248             if   ope in ["div_var"]: all_var[k] = all_var[k-2] / all_var[k-1] ; insert = '_div_'
249             elif ope in ["mul_var"]: all_var[k] = all_var[k-2] * all_var[k-1] ; insert = '_mul_'
250             elif ope in ["add_var"]: all_var[k] = all_var[k-2] + all_var[k-1] ; insert = '_add_'
251             elif ope in ["sub_var"]: all_var[k] = all_var[k-2] - all_var[k-1] ; insert = '_sub_'
252             else:                    errormess(ope+" : non-implemented operation. Check pp.py --help")
253             numplot = numplot + 1 ; all_time[k] = all_time[k-1] ; all_namefile[k] = all_namefile[k-1]
254             all_varname[k] = all_varname[k-2] + insert + all_varname[k-1] 
255    ##################################
256    ### Open a figure and set subplots
257    fig = figure()
258    subv,subh = definesubplot( numplot, fig ) 
259    if ope in ['-','-%']: subv,subh = 2,2
260 
261    #################################
262    ### Time loop for plotting device
263    nplot = 1 ; error = False 
264    print "********************************************"
265    while error is False:
266     
267       print "********** NPLOT", nplot
268       if nplot > numplot: break
269
270       ####################################################################
271       ## get all indexes to be taken into account for this subplot and then reduce field
272       ## 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
273       indexlon  = getsindex(slon,(nplot-1)%nlon,lon)
274       indexlat  = getsindex(slat,((nplot-1)//nlon)%nlat,lat)
275       indexvert = getsindex(svert,((nplot-1)//(nlon*nlat))%nvert,vert) 
276       if ope is not None:
277           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
278           elif "var" in ope:           index_f = ((nplot-1)//(nlon*nlat*nvert*ntime))%(len(var)+1)        ## OK only 1 file, see test in the beginning
279           elif "cat" in ope:           index_f = 0
280       else:                            yeah = len(namefiles)*len(var) ; index_f = ((nplot-1)//(nlon*nlat*nvert*ntime))%yeah
281       time = all_time[index_f]
282       if stime is not None:
283           if stime[0][0] < 0:
284               if typefile in ['mesoapi','meso']:
285                   for i in range(len(time)):  time[i] = localtime ( interv[0]+time[i]*interv[1], 0.5*(wlon[0]+wlon[1]) )
286                   print "OK... WORKING WITH LOCAL TIMES"
287               else: errormess("local times not supported. not too hard to modify the code though.")
288       if mrate is not None:                 indextime = None 
289       else:                                 indextime = getsindex(stime,((nplot-1)//(nlon*nlat*nvert))%ntime,time)
290       ltst = None 
291       if typefile in ['mesoapi','meso'] and indextime is not None:  ltst = localtime ( interv[0]+indextime*interv[1], 0.5*(wlon[0]+wlon[1]) ) 
292       print "********** INDEX LON:",indexlon," LAT:",indexlat," VERT:",indexvert," TIME:",indextime
293       ####################################################################
294       error = False
295       varname = all_varname[index_f]
296       if varname:   ### what is shaded.
297           what_I_plot, error = reducefield( all_var[index_f], d4=indextime, d1=indexlon, d2=indexlat, d3=indexvert, \
298                                             yint=yintegral, alt=vert, anomaly=anomaly )
299           what_I_plot = what_I_plot*mult
300       if var2:      ### what is contoured.
301           what_I_plot_contour, error = reducefield( all_var2[index_f], d4=indextime, d1=indexlon, d2=indexlat , d3=indexvert, \
302                                             yint=yintegral, alt=vert )
303       if winds:     ### what is plot as vectors.
304           vecx, error = reducefield( all_windu[index_f], d4=indextime, d3=indexvert, yint=yintegral, alt=vert)
305           vecy, error = reducefield( all_windv[index_f], d4=indextime, d3=indexvert, yint=yintegral, alt=vert)
306       ####################################################################
307       ### General plot settings
308       changesubplot = (numplot > 1) and (len(what_I_plot.shape) != 1)  ## default for 1D plots: superimposed. to be reworked for better flexibility.
309       if changesubplot: subplot(subv,subh,nplot)
310       ### Map projection                   
311       if mapmode == 1:     m = define_proj(proj,wlon,wlat,back=back,blat=blat,blon=blon) ; x, y = m(lon2d, lat2d)
312       elif mapmode ==0:    m = None ; x = None ; y = None
313       ####################################################################
314
315       if not error:
316               ticks = ndiv + 1 
317               fvar = varname
318               if anomaly: fvar = 'anomaly'
319               if mapmode == 0:
320                   itime=indextime
321                   if len(what_I_plot.shape) is 3:itime=[0]
322                   what_I_plot, x, y = define_axis(lon,lat,vert,time,indexlon,indexlat,indexvert,\
323                         itime,what_I_plot, len(all_var[index_f].shape),vertmode)
324                   zxmin, zxmax = xaxis ; zymin, zymax = yaxis
325                   if zxmin is not None: mpl.pyplot.xlim(xmin=zxmin)
326                   if zxmax is not None: mpl.pyplot.xlim(xmax=zxmax)
327                   if zymin is not None: mpl.pyplot.ylim(ymin=zymin)
328                   if zymax is not None: mpl.pyplot.ylim(ymax=zymax)
329                   if invert_y:     lima,limb = mpl.pyplot.ylim() ; mpl.pyplot.ylim(limb,lima)
330                   if ylog:         mpl.pyplot.semilogy()
331
332               if (fileref is not None) and (index_f is numplot-1):    zevmin, zevmax = calculate_bounds(what_I_plot,vmin=minop,vmax=maxop)
333               else:                                                   zevmin, zevmax = calculate_bounds(what_I_plot,vmin=vmin,vmax=vmax)
334               if colorb in ["def","nobar"]:                           palette = get_cmap(name=defcolorb(fvar.upper()))
335               elif (fileref is not None) and (index_f is numplot-1):  palette = get_cmap(name="RdBu_r")
336               else:                                                   palette = get_cmap(name=colorb)
337
338               ##### simple 2D field and movies of 2D fields
339               if len(what_I_plot.shape) >= 2:
340                 if (len(what_I_plot.shape) is 3 and mrate is None):  errormess("3D field. Use --rate RATE for movie or specify --time TIME. Exit.")
341                 if mrate is not None: iend=len(time)-1
342                 else:                 iend=0
343                 imov = 0 
344                 if var2:  which = "contour" ## have to start with contours rather than shading
345                 else:     which = "regular"
346                 while imov <= iend:
347                    print "-> frame ",imov+1, which
348                    if which == "regular":   
349                        if mrate is None:                                   what_I_plot_frame = what_I_plot
350                        else:                                               what_I_plot_frame = what_I_plot[imov,:,:]
351                        if winds:
352                            if mrate is None:                                   vecx_frame = vecx ; vecy_frame = vecy
353                            else:                                               vecx_frame = vecx[imov,:,:] ; vecy_frame = vecy[imov,:,:]
354                    elif which == "contour": 
355                        if mrate is None or what_I_plot_contour.ndim < 3:   what_I_plot_frame = what_I_plot_contour
356                        else:                                               what_I_plot_frame = what_I_plot_contour[imov,:,:]
357                    if mrate is not None:     
358                        if mapmode == 1: 
359                            m = define_proj(proj,wlon,wlat,back=back,blat=blat,blon=blon)  ## this is dirty, defined above but out of imov loop
360                            x, y = m(lon2d, lat2d)                                         ## this is dirty, defined above but out of imov loop
361                    if typefile in ['mesoapi','meso'] and mapmode == 1:   what_I_plot_frame = dumpbdy(what_I_plot_frame,6,condition=True)
362#                   if typefile in ['mesoideal']:    what_I_plot_frame = dumpbdy(what_I_plot_frame,0,stag='W',condition=dumped_vert_stag)
363
364                    if imov >= 0:
365                        # Renew axis directives for movie frames which are not the first one.
366                        zxmin, zxmax = xaxis ; zymin, zymax = yaxis
367                        if zxmin is not None: mpl.pyplot.xlim(xmin=zxmin)
368                        if zxmax is not None: mpl.pyplot.xlim(xmax=zxmax)
369                        if zymin is not None: mpl.pyplot.ylim(ymin=zymin)
370                        if zymax is not None: mpl.pyplot.ylim(ymax=zymax)
371                        if invert_y:     lima,limb = mpl.pyplot.ylim() ; mpl.pyplot.ylim(limb,lima)
372                        if ylog:         mpl.pyplot.semilogy()
373                   
374                    if which == "regular": 
375                        if hole:         what_I_plot_frame = hole_bounds(what_I_plot_frame,zevmin,zevmax)
376                        else:            what_I_plot_frame = bounds(what_I_plot_frame,zevmin,zevmax)
377                        if flagnolow:    what_I_plot_frame = nolow(what_I_plot_frame)
378                        if not tile:
379                            #zelevels = np.linspace(zevmin*(1. + 1.e-7),zevmax*(1. - 1.e-7)) #,num=20)
380                            zelevels = np.linspace(zevmin,zevmax,num=ticks)
381                            if mapmode == 1:       m.contourf( x, y, what_I_plot_frame, zelevels, cmap = palette, alpha=trans)
382                            elif mapmode == 0:     contourf( x, y, what_I_plot_frame, zelevels, cmap = palette, alpha=trans)
383                        else:
384                            if mapmode == 1:       m.pcolor( x, y, what_I_plot_frame, cmap = palette, vmin=zevmin, vmax=zevmax, alpha=trans)
385                            elif mapmode == 0:     pcolor( x, y, what_I_plot_frame, cmap = palette, vmin=zevmin, vmax=zevmax, alpha=trans)
386                        if colorb != 'nobar':       
387                            if (fileref is not None) and (index_f is numplot-1):   daformat = "%.3f"
388                            elif mult != 1:                                        daformat = "%.1f"
389                            else:                                                  daformat = fmtvar(fvar.upper())
390                            colorbar( fraction=0.05,pad=0.03,format=daformat,\
391                                      ticks=np.linspace(zevmin,zevmax,num=min([ticks/2+1,21])),extend='neither',spacing='proportional' ) 
392                        if winds:
393                            if typefile in ['mesoapi','meso']:
394                                [vecx_frame,vecy_frame] = [dumpbdy(vecx_frame,6,stag=uchar,condition=True), dumpbdy(vecy_frame,6,stag=vchar,condition=True)]
395                                key = True
396                            elif typefile in ['gcm']:
397                                key = False
398                            if metwind:  [vecx_frame,vecy_frame] = m.rotate_vector(vecx_frame, vecy_frame, lon2d, lat2d)
399                            if var:       colorvec = definecolorvec(back)
400                            else:         colorvec = definecolorvec(colorb)
401                            vectorfield(vecx_frame, vecy_frame, x, y, stride=stride, csmooth=2,\
402                                             #scale=15., factor=300., color=colorvec, key=key)
403                                             scale=20., factor=250., color=colorvec, key=key)
404                                                              #200.         ## or csmooth=stride
405                    elif which == "contour":
406                        zevminc, zevmaxc = calculate_bounds(what_I_plot_frame)
407                        zelevels = np.linspace(zevminc,zevmaxc,ticks/2) #20)
408                        if var2 == 'HGT': zelevels = np.arange(-10000.,30000.,2000.)
409                        if mapmode == 0:   
410                            what_I_plot_frame, x, y = define_axis( lon,lat,vert,time,indexlon,indexlat,indexvert,\
411                                                              itime,what_I_plot_frame, len(all_var2[index_f].shape),vertmode )
412                            cs = contour( x,y,what_I_plot_frame, zelevels, colors='k', linewidths = 1 ) #0.33 colors='w' )# , alpha=0.5)
413                        elif mapmode == 1:  cs = m.contour( x,y,what_I_plot_frame, zelevels, colors='k', linewidths = 1 ) #0.33 colors='w' )# , alpha=0.5)
414
415
416                    if which == "regular":
417                        if mrate is not None:
418                           ### THIS IS A MENCODER MOVIE
419                           if mrate > 0:
420                             figframe=mpl.pyplot.gcf()
421                             if mquality:   figframe.set_dpi(600.)
422                             else:          figframe.set_dpi(200.)
423                             mframe=fig2img(figframe)
424                             if imov == 0:
425                                moviename='movie' ;W,H = figframe.canvas.get_width_height()
426                                video = VideoSink((H,W), moviename, rate=mrate, byteorder="rgba")
427                             video.run(mframe) ; close()
428                             if imov == iend: video.close()                           
429                           ### THIS IS A WEBPAGE MOVIE
430                           else:
431                             nameframe = "image"+str(1000+imov)
432                             makeplotres(nameframe,res=100.,disp=False) ; close()
433                             if imov == 0: myfile = open("zepics", 'w')
434                             myfile.write("modImages["+str(imov)+"] = '"+nameframe+"_100.png';"+ '\n')
435                             if imov == iend:
436                                 myfile.write("first_image = 0;"+ '\n')
437                                 myfile.write("last_image = "+str(iend)+";"+ '\n')
438                                 myfile.close()
439                        if var2:  which = "contour"
440                        imov = imov+1
441                    elif which == "contour":
442                        which = "regular"
443
444               ##### 1D field
445               elif len(what_I_plot.shape) is 1:
446                 lbl = ""
447                 if indexlat is not None:  lbl = lbl + " ix" + str(indexlat)
448                 if indexlon is not None:  lbl = lbl + " iy" + str(indexlon)
449                 if indexvert is not None: lbl = lbl + " iz" + str(indexvert)
450                 if indextime is not None: lbl = lbl + " it" + str(indextime)
451
452                 if indexvert is not None or indextime is None:    plot(x,what_I_plot,label=lbl)  ## regular plot
453                 else:                                             plot(what_I_plot,x,label=lbl)  ## vertical profile
454                 if nplot > 1: legend(loc='best')
455                 if indextime is None and axtime is not None:      xlabel(axtime.upper()) ## define the right label
456                 if save == 'txt':  writeascii(np.transpose(what_I_plot),'profile'+str(nplot)+'.txt')
457
458               #### Other cases: (maybe plot 3-D field one day ??)
459               else:
460                 print "WARNING!!! ",len(what_I_plot.shape),"-D PLOT NOT SUPPORTED !!! dimensions: ",what_I_plot.shape
461                 errormess("Are you sure you did not forget to prescribe a dimension ?")
462       else:
463               errormess("There is an error in reducing field !")
464
465       ### Next subplot
466       basename = getname(var=varname,var2=var2,winds=winds,anomaly=anomaly)
467       if len(what_I_plot.shape) > 3:
468           basename = basename + getstralt(nc,level) 
469       if mrate is not None: basename = "movie_" + basename
470       if typefile in ['mesoapi','meso']:
471            if slon is not None: basename = basename + "_lon_" + str(int(lon2d[indices[1],indices[0]]))
472            if slat is not None: basename = basename + "_lat_" + str(int(lat2d[indices[1],indices[0]]))
473            plottitle = basename
474            ### dans le nouveau systeme time=ls,sol,lt cette ligne pourrait ne servir a rien (ou deplacer au dessus)
475            if addchar and indextime is not None:   [addchar,gogol,gogol2] = getlschar ( all_namefile[index_f] )  ;  plottitle = plottitle + addchar
476            if ltst is not None and ( (mapmode == 0) or (proj in ["lcc","laea","merc","nsper"]) ):  plottitle = plottitle + "_LT" + str(ltst)
477       else:
478            if fileref is not None:
479                if index_f is numplot-1:     plottitle = basename+' '+"fig(1) "+ope+" fig(2)"
480                elif index_f is numplot-2:   plottitle = basename+' '+fileref
481                else:                        plottitle = basename+' '+namefiles[0]#index_f]
482            else:                            plottitle = basename+' '+namefiles[0]#index_f]
483       if mult != 1:                         plottitle = '{:.0e}'.format(mult) + "*" + plottitle
484       if zetitle != "fill":                 
485          plottitle = zetitle
486          if titleref is "fill":             titleref=zetitle
487          if fileref is not None:
488             if index_f is numplot-2:        plottitle = titleref
489             if index_f is numplot-1:        plottitle = "fig(1) "+ope+" fig(2)"
490#       if indexlon is not None:      plottitle = plottitle + " lon: " + str(min(lon[indexlon])) +" "+ str(max(lon[indexlon]))
491#       if indexlat is not None:      plottitle = plottitle + " lat: " + str(min(lat[indexlat])) +" "+ str(max(lat[indexlat]))
492#       if indexvert is not None:     plottitle = plottitle + " vert: " + str(min(vert[indexvert])) +" "+ str(max(vert[indexvert]))
493#       if indextime is not None:     plottitle = plottitle + " time: " + str(min(time[indextime])) +" "+ str(max(time[indextime]))
494       title( plottitle )
495       if nplot >= numplot: error = True
496       nplot += 1
497
498 
499
500
501
502
503
504     
505    ##########################################################################
506    ### Save the figure in a file in the data folder or an user-defined folder
507    if outputname is None:
508       if typefile in ['meso','mesoapi']:   prefix = getprefix(nc)
509       elif typefile in ['gcm']:            prefix = 'LMD_GCM_'
510       else:                                prefix = ''
511    ###
512       zeplot = prefix + basename
513       if addchar:         zeplot = zeplot + addchar
514       if numplot <= 0:    zeplot = zeplot + "_LT"+str(abs(numplot))
515    ###
516       if not target:      zeplot = namefile[0:find(namefile,'wrfout')] + zeplot
517       else:               zeplot = target + "/" + zeplot 
518    ###
519    else:
520       zeplot=outputname
521
522    if mrate is None:
523        pad_inches_value = 0.35
524        print "********** SAVE ", save
525        if save == 'png': 
526            if display: makeplotres(zeplot,res=100.,pad_inches_value=pad_inches_value) #,erase=True)  ## a miniature
527            makeplotres(zeplot,res=resolution,pad_inches_value=pad_inches_value,disp=False)
528        elif save in ['eps','svg','pdf']:     makeplotres(zeplot,pad_inches_value=pad_inches_value,disp=False,ext=save)
529        elif save == 'gui':                   show()
530        elif save == 'txt':                   print "Saved results in txt file." 
531        else: 
532            print "INFO: save mode not supported. using gui instead."
533            show()
534
535    ###################################
536    #### Getting more out of this video -- PROBLEMS WITH CREATED VIDEOS
537    #
538    #if mrate is not None:
539    #    print "Re-encoding movie.. first pass"
540    #    video.first_pass(filename=moviename,quality=mquality,rate=mrate)
541    #    print "Re-encoding movie.. second pass"
542    #    video.second_pass(filename=moviename,quality=mquality,rate=mrate)   
543
544    ###############
545    ### Now the end
546    return zeplot
Note: See TracBrowser for help on using the repository browser.