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

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

PYTHON: quite a lot of modifs and tests. extended multivar subplot capabilities + cosmetic changes + general cleaning. corrected some stuff that were not working with mesoscale. and there is now a common script for meso and gcm svn status -uq! it is named pp.py [stands for: planetoplot]. put some examples in README file. testing is probably a bit necessary for most complex options.

  • Property svn:executable set to *
File size: 22.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/2011 -- Extended multivar subplot capabilities + cosmetic changes + general cleaning and tests
9
10def planetoplot (namefiles,\
11           level=0,\
12           vertmode=0,\
13           proj=None,\
14           back=None,\
15           target=None,
16           stride=3,\
17           numplot=None,\
18           var=None,\
19           colorb="def",\
20           winds=True,\
21           addchar=None,\
22           interv=[0,1],\
23           vmin=None,\
24           vmax=None,\
25           tile=False,\
26           zoom=None,\
27           display=True,\
28           itstep=None,\
29           hole=False,\
30           save="gui",\
31           anomaly=False,\
32           var2=None,\
33           ndiv=10,\
34           first=1,\
35           mult=1.,\
36           zetitle="fill",\
37           slon=None,\
38           slat=None,\
39           svert=None,\
40           stime=None,\
41           outputname=None,\
42           resolution=200,\
43           ope=None,\
44           fileref=None,\
45           minop=0.,\
46           maxop=0.,\
47           titleref="fill",\
48           invert_y=False,\
49           xaxis=[None,None],\
50           yaxis=[None,None],\
51           ylog=False,\
52           yintegral=False,\
53           blat=None,\
54           tsat=False):
55
56
57    ####################################################################################################################
58    ### Colorbars http://www.scipy.org/Cookbook/Matplotlib/Show_colormaps?action=AttachFile&do=get&target=colormaps3.png
59
60    #################################
61    ### Load librairies and functions
62    from netCDF4 import Dataset
63    from myplot import getcoord2d,define_proj,makeplotres,simplinterv,vectorfield,ptitle,latinterv,getproj,wrfinterv,dumpbdy,\
64                       fmtvar,definecolorvec,defcolorb,getprefix,putpoints,calculate_bounds,errormess,definesubplot,\
65                       zoomset,getcoorddef,getwinddef,whatkindfile,reducefield,bounds,getstralt,getfield,smooth,nolow,\
66                       getname,localtime,polarinterv,getsindex,define_axis,determineplot,readslices
67    from mymath import deg,max,min,mean,get_tsat
68    import matplotlib as mpl
69    from matplotlib.pyplot import contour,contourf, subplot, figure, rcParams, savefig, colorbar, pcolor, show, plot, clabel, title
70    from matplotlib.cm import get_cmap
71    import numpy as np
72    from numpy.core.defchararray import find
73
74    ################################
75    ### Preliminary stuff
76    ################################
77    print "********************************************"
78    print "********** WELCOME TO PLANETOPLOT **********"
79    print "********************************************"
80    if not isinstance(namefiles, np.ndarray): namefiles = [namefiles]
81    if not isinstance(var, np.ndarray):       var = [var]
82    if ope is not None and len(var) > 1:      errormess("you are using an operation... please set only one var !")
83
84    ################################
85    ### Which plot needs to be done?
86    ################################
87    nlon, nlat, nvert, ntime, mapmode, nslices = determineplot(slon, slat, svert, stime)
88    if mapmode == 0:       winds=False
89    elif mapmode == 1:     
90        if svert is None:  svert = readslices(str(level)) ; nvert=1
91    zelen = len(namefiles)*len(var)
92    if numplot is None:  numplot = zelen*nslices
93    print "********** FILES, SLICES, VARS, TOTAL PLOTS: ", len(namefiles), nslices, len(var), numplot
94    print "********** MAPMODE: ", mapmode
95    if fileref is not None:       all_var  = [[]]*(zelen+2) ;  all_varname = [[]]*(zelen+2)
96    else:                         all_var  = [[]]*zelen     ;  all_var2  = [[]]*zelen ;  all_title = [[]]*zelen ;  all_varname = [[]]*zelen
97 
98    #################################################################################################
99    ### Loop over the files + vars initially separated by commas to be plotted on the same figure ###
100    #################################################################################################
101    k = 0
102    firstfile = True
103    for nnn in range(len(namefiles)):
104     for vvv in range(len(var)): 
105
106      print "********** LOOP..... THIS IS SUBPLOT NUMBER.....",k
107
108      ######################
109      ### Load NETCDF object
110      namefile = namefiles[nnn] ; print "********** THE NAMEFILE IS....", namefile
111      nc  = Dataset(namefile)
112
113      ##################################
114      ### Initial checks and definitions
115      ### ... TYPEFILE
116      typefile = whatkindfile(nc)                                 
117      if firstfile:                 typefile0 = typefile
118      elif typefile != typefile0:   errormess("Not the same kind of files !", [typefile0, typefile])
119      ### ... VAR
120      varname=var[vvv]
121      print "********** THE VAR IS....",varname, var2
122      if varname not in nc.variables: varname = False
123      ### ... WINDS
124      if winds:                                                   
125         [uchar,vchar,metwind] = getwinddef(nc)             
126         if uchar == 'not found': winds = False
127      if not varname and not winds: errormess("please set at least winds or var",printvar=nc.variables)
128      ### ... COORDINATES, could be moved below
129      [lon2d,lat2d] = getcoorddef(nc)                       
130      ### ... PROJECTION
131      if proj == None:   proj = getproj(nc)                 
132
133##########################################################
134      if typefile == "gcm":
135          lat = nc.variables["latitude"][:] 
136          lon = nc.variables["longitude"][:]
137          if "Time" in nc.variables:
138             time = nc.variables["Time"][:]
139          elif "time" in nc.variables:
140             time = nc.variables["time"][:]
141          else:
142             print "no time axis found."
143             exit()
144          vert = nc.variables["altitude"][:]
145      elif typefile in ['meso','mesoapi']:
146          if mapmode == 0:
147              if varname in ['PHTOT','W']:    vertdim='BOTTOM-TOP_PATCH_END_STAG'
148              else:                           vertdim='BOTTOM-TOP_PATCH_END_UNSTAG'
149              if varname in ['V']:  latdim='SOUTH-NORTH_PATCH_END_STAG'
150              else:                 latdim='SOUTH-NORTH_PATCH_END_UNSTAG'
151              if varname in ['U']:  londim='WEST-EAST_PATCH_END_STAG'
152              else:                 londim='WEST-EAST_PATCH_END_UNSTAG'
153              lon = np.arange(0,getattr(nc,londim),1)
154              lat = np.arange(0,getattr(nc,latdim),1)
155              if vertmode is None:  vertmode=0
156              if vertmode == 0:     vert = np.arange(0,getattr(nc,vertdim),1)
157              else:                 vert = nc.variables["vert"][:]
158              time = np.arange(0,len(nc.variables["Times"]),1)
159          else: 
160              lon=None ; lat=None ; vert=None ; time=None
161       #if firstfile:
162       #   lat0 = lat
163       #elif len(lat0) != len(lat):
164       #   errormess("Not the same latitude lengths !", [len(lat0), len(lat)])
165       #elif sum((lat == lat0) == False) != 0:
166       #   errormess("Not the same latitudes !", [lat,lat0])
167       ## Faire d'autre checks sur les compatibilites entre fichiers!!
168##########################################################
169
170      if firstfile:
171         ##########################
172         ### Define plot boundaries
173         ### todo: possible areas in latinterv in argument (ex: "Far_South_Pole")
174         if proj in ["npstere","spstere"]: [wlon,wlat] = polarinterv(lon2d,lat2d)
175         elif proj in ["lcc","laea"]:      [wlon,wlat] = wrfinterv(lon2d,lat2d)
176         else:                             [wlon,wlat] = simplinterv(lon2d,lat2d)
177         if zoom:                          [wlon,wlat] = zoomset(wlon,wlat,zoom) 
178         ### ... NAME FOR TITLE and FILE (have to do something for multiple vars...)
179         basename = getname(var=varname,winds=winds,anomaly=anomaly)
180         basename = basename + getstralt(nc,level)  ## can be moved elsewhere for a more generic routine
181
182      ##### SPECIFIC
183      if varname in ["temp","t","T_nadir_nit","T_nadir_day"] and tsat:
184          tt=getfield(nc,varname) ; print "computing Tsat-T, I ASSUME Z-AXIS IS PRESSURE"
185          if type(tt).__name__=='MaskedArray':  tt.set_fill_value([np.NaN]) ; tinput=tt.filled()
186          else:                                 tinput=tt
187          all_var[k]=get_tsat(vert,tinput,zlon=lon,zlat=lat,zalt=vert,ztime=time)
188      else:
189      ##### GENERAL STUFF HERE
190          all_var[k] = getfield(nc,varname)
191          all_varname[k] = varname
192      if var2: all_var2[k] = getfield(nc,var2)
193     
194      print "********** all_var[k].shape", all_var[k].shape
195      k += 1
196      firstfile = False
197      #### End of for namefile in namefiles
198
199    ##################################
200    ### Operation on files
201    ### ... for the moment only OK when 1 var only
202    if ope is not None:
203             print ope
204             if ope in ["-","+"]:
205                if fileref is not None:   all_var[k] = getfield(Dataset(fileref),all_varname[k-1]) ; all_varname[k] = all_varname[k-1]
206                else:                     errormess("fileref is missing!") 
207                if ope == "-":     all_var[k+1]= all_var[k-1] - all_var[k]
208                elif ope == "+":   all_var[k+1]= all_var[k-1] + all_var[k]
209                all_varname[k+1] = all_varname[k]
210                numplot = numplot+2
211             elif ope in ["cat"]:
212                tab = all_var[0];k = 0
213                while k != len(namefiles)-1: 
214                    tab = np.append(tab,all_var[k],axis=0)
215                    k += 1
216                time = np.arange(0,len(tab),1) ### AS: time reference is simple, should be better
217                all_var[0] = np.array(tab);numplot = 1
218             elif ope is not None:
219                errormess(ope+" : non-implemented operation. Available op. are + and -.")
220
221    ##################################
222    ### Open a figure and set subplots
223    fig = figure()
224    subv,subh = definesubplot( numplot, fig ) 
225 
226    #################################
227    ### Time loop for plotting device
228    found_lct = False;nplot = 1;itime = first;error = False
229    if itstep is None and numplot > 0: itstep = int(24./numplot)
230    elif numplot <= 0:                 itstep = 1 
231   
232    print "********************************************"
233    while error is False:
234       print "********** nplot", nplot, "itime",itime,"error",error
235       
236       ### Which local time ?
237       ltst = localtime ( interv[0]+itime*interv[1], 0.5*(wlon[0]+wlon[1]) )
238
239       ### General plot settings
240       #print itime, int(ltst), numplot, nplot
241       if numplot >= 1: 
242           if nplot > numplot: break
243           if numplot > 1:     
244               if typefile not in ['geo']:  subplot(subv,subh,nplot)
245           found_lct = True
246       ### If only one local time is requested (numplot < 0)
247       elif numplot <= 0: 
248           if int(ltst) + numplot != 0: 
249                 itime += 1 
250                 if found_lct is True: break     ## because it means LT was found at previous iteration
251                 else:                 continue  ## continue to iterate to find the correct LT
252           else: 
253                 found_lct = True
254
255       ### Map projection                   
256       if mapmode == 1:
257           m = define_proj(proj,wlon,wlat,back=back,blat=blat)
258           x, y = m(lon2d, lat2d)
259
260####################################################################
261       ## get all indexes to be taken into account for this subplot and then reduce field
262       ## 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
263       indexlon  = getsindex(slon,(nplot-1)%nlon,lon)
264       indexlat  = getsindex(slat,((nplot-1)//nlon)%nlat,lat)
265       indexvert = getsindex(svert,((nplot-1)//(nlon*nlat))%nvert,vert) 
266       if mapmode == 1 and stime is None: 
267           indextime = itime
268           if len(var) != 1 or len(namefiles) != 1: indextime = first
269       else:
270           indextime = getsindex(stime,((nplot-1)//(nlon*nlat*nvert))%ntime,time) 
271
272       if fileref is not None:
273           index_f = ((nplot-1)//(nlon*nlat*nvert*ntime))%(len(namefiles)+2)  ## OK only 1 var, see test in the beginning
274       else:
275           yeah = len(namefiles)*len(var)
276           index_f = ((nplot-1)//(nlon*nlat*nvert*ntime))%yeah
277       #print nlon, nlat, nvert, ntime 
278       #print slon, slat, svert, stime       
279       #print index_f
280       #print "index lon,lat,vert,time", max(indexlon), max(indexlat), max(indexvert), max(indextime)
281       #if varname != all_varname[index_f]:  indextime = first
282####################################################################
283
284       ticks = ndiv + 1
285
286       #### Contour plot
287       if var2:
288           what_I_plot, error = reducefield(all_var2[index_f], d4=indextime, d1=indexlon, d2=indexlat , d3=indexvert, yint=yintegral, alt=vert)
289           #what_I_plot = what_I_plot*mult
290           if not error:
291              if mapmode == 1:
292                  if typefile in ['mesoapi','meso']:    what_I_plot = dumpbdy(what_I_plot,6)
293              zevmin, zevmax = calculate_bounds(what_I_plot)
294              zelevels = np.linspace(zevmin,zevmax,ticks) #20)
295              if var2 == 'HGT':  zelevels = np.arange(-10000.,30000.,2000.)
296              if mapmode == 0:
297                  x, y = define_axis(lon,lat,vert,time,indexlon,indexlat,indexvert,\
298                        indextime,what_I_plot.shape, len(all_var2[index_f].shape),vertmode)
299              ### If we plot a 2-D field
300              if len(what_I_plot.shape) is 2:
301                  cs = contour(x,y,what_I_plot, zelevels, colors='k', linewidths = 1 ) #0.33 colors='w' )# , alpha=0.5)
302                  #if typefile in ['gcm']: clabel(cs,fmt = '%1.2e')
303              ### If we plot a 1-D field
304              elif len(what_I_plot.shape) is 1:
305                  plot(what_I_plot,x) 
306           else:
307              errormess("There is an error in reducing field !")
308
309       #### Shaded plot
310       varname = all_varname[index_f]
311       if varname:
312           what_I_plot, error = reducefield(all_var[index_f], d4=indextime, d1=indexlon, d2=indexlat , d3=indexvert , yint=yintegral, alt=vert)
313           what_I_plot = what_I_plot*mult
314           if not error: 
315               fvar = varname
316               ###
317               if anomaly:
318                   what_I_plot = 100. * ((what_I_plot / smooth(what_I_plot,12)) - 1.)
319                   fvar = 'anomaly'
320               #if mult != 1:     
321               #    fvar = str(mult) + "*" + var
322               ###
323               if mapmode == 1:
324                   if typefile in ['mesoapi','meso']:    what_I_plot = dumpbdy(what_I_plot,6)
325               elif mapmode == 0:
326                   what_I_plot, x, y = define_axis(lon,lat,vert,time,indexlon,indexlat,indexvert,\
327                         indextime,what_I_plot, len(all_var[index_f].shape),vertmode)
328               if (fileref is not None) and (index_f is numplot-1):
329                  zevmin, zevmax = calculate_bounds(what_I_plot,vmin=minop,vmax=maxop)
330               else:
331                  zevmin, zevmax = calculate_bounds(what_I_plot,vmin=vmin,vmax=vmax)
332               if colorb in ["def","nobar"]:   palette = get_cmap(name=defcolorb(fvar.upper()))
333               else:                           palette = get_cmap(name=colorb)
334               ##### 2D field
335               if len(what_I_plot.shape) is 2:
336                 if not tile:
337                     if not hole: what_I_plot = bounds(what_I_plot,zevmin,zevmax)
338                     #zelevels = np.linspace(zevmin*(1. + 1.e-7),zevmax*(1. - 1.e-7)) #,num=20)
339                     zelevels = np.linspace(zevmin,zevmax,num=ticks)
340                     #contourf(what_I_plot, zelevels, cmap = palette )
341
342                     if mapmode == 1:
343                       m.contourf( x, y, what_I_plot, zelevels, cmap = palette)
344                     elif mapmode == 0:
345                       contourf( x, y, what_I_plot, zelevels, cmap = palette)
346
347                     zxmin, zxmax = xaxis
348                     zymin, zymax = yaxis
349                     if zxmin is not None: mpl.pyplot.xlim(xmin=zxmin)
350                     if zxmax is not None: mpl.pyplot.xlim(xmax=zxmax)
351                     if zymin is not None: mpl.pyplot.ylim(ymin=zymin)
352                     if zymax is not None: mpl.pyplot.ylim(ymax=zymax)
353                     if invert_y:     lima,limb = mpl.pyplot.ylim() ; mpl.pyplot.ylim(limb,lima)
354                     if ylog:         mpl.pyplot.semilogy()
355
356                 else:
357                     if hole:  what_I_plot = nolow(what_I_plot)
358                     pcolor( x, y, what_I_plot, cmap = palette, vmin=zevmin, vmax=zevmax )
359                 if colorb != 'nobar' and varname != 'HGT' :       
360                     if (fileref is not None) and (index_f is numplot-1):
361                        colorbar(fraction=0.05,pad=0.03,format="%.2f",\
362                                           ticks=np.linspace(zevmin,zevmax,num=min([ticks/2+1,20])),\
363                                           extend='neither',spacing='proportional')
364                     else:
365                        colorbar(fraction=0.05,pad=0.03,format=fmtvar(fvar.upper()),\
366                                           ticks=np.linspace(zevmin,zevmax,num=min([ticks/2+1,20])),\
367                                           extend='neither',spacing='proportional')
368
369                                           # both min max neither
370               ##### 1D field
371               elif len(what_I_plot.shape) is 1:
372                 plot(x,what_I_plot)
373               #### Other cases: (maybe plot 3-D field one day or movie ??)
374               else:
375                 print "WARNING!!! ",len(what_I_plot.shape),"-D PLOT NOT SUPPORTED !!!"
376                 print "field dimensions: ", what_I_plot.shape
377                 exit()
378               
379           else:
380               errormess("There is an error in reducing field !")
381
382       ### Vector plot --- a adapter
383       if winds:
384           vecx, error = reducefield( getfield(nc,uchar), d4=indextime, d3=indexvert , yint=yintegral , alt=vert)
385           vecy, error = reducefield( getfield(nc,vchar), d4=indextime, d3=indexvert , yint=yintegral , alt=vert)
386           #what_I_plot, error = reducefield(all_var[index_f], d4=indextime, d1=indexlon, d2=indexlat , d3=indexvert )
387           if not error:
388               if typefile in ['mesoapi','meso']:   
389                   [vecx,vecy] = [dumpbdy(vecx,6,stag=uchar), dumpbdy(vecy,6,stag=vchar)]
390                   key = True
391               elif typefile in ['gcm']:           
392                   key = False
393               if metwind:  [vecx,vecy] = m.rotate_vector(vecx, vecy, lon2d, lat2d)
394               if varname == False:       colorvec = definecolorvec(back)
395               else:                  colorvec = definecolorvec(colorb)
396               vectorfield(vecx, vecy,\
397                          x, y, stride=stride, csmooth=2,\
398                          #scale=15., factor=300., color=colorvec, key=key)
399                          scale=20., factor=250., color=colorvec, key=key)
400                                            #200.         ## or csmooth=stride
401   
402       ### Next subplot
403       basename = getname(var=varname,winds=winds,anomaly=anomaly)
404       if typefile in ['mesoapi','meso']:
405            plottitle = basename
406            if addchar:  plottitle = plottitle + addchar + "_LT"+str(ltst)
407            else:        plottitle = plottitle + "_LT"+str(ltst)
408       else:
409            if fileref is not None:
410                if index_f is numplot-1:
411                   plottitle = basename+' '+"fig(1) "+ope+" fig(2)"
412                elif index_f is numplot-2:
413                   plottitle = basename+' '+fileref
414                else:
415                   plottitle = basename+' '+namefiles[0]#index_f]
416            else:
417                plottitle = basename+' '+namefiles[0]#index_f]
418       if mult != 1:           plottitle = str(mult) + "*" + plottitle
419       if zetitle != "fill":   
420          plottitle = zetitle
421          if titleref is "fill":
422             titleref=zetitle
423          if fileref is not None:
424             if index_f is numplot-2:
425                plottitle = titleref
426             if index_f is numplot-1:
427                plottitle = "fig(1) "+ope+" fig(2)"
428#       if indexlon is not None:
429#         plottitle = plottitle + " lon: " + str(min(lon[indexlon])) +" "+ str(max(lon[indexlon]))
430#       if indexlat is not None:
431#         plottitle = plottitle + " lat: " + str(min(lat[indexlat])) +" "+ str(max(lat[indexlat]))
432#       if indexvert is not None:
433#         plottitle = plottitle + " vert: " + str(min(vert[indexvert])) +" "+ str(max(vert[indexvert]))
434#       if indextime is not None:
435#         plottitle = plottitle + " time: " + str(min(time[indextime])) +" "+ str(max(time[indextime]))
436       title( plottitle )
437       itime += itstep
438       if nplot >= numplot:
439          error = True
440       nplot += 1
441
442 
443
444
445
446
447
448     
449    ##########################################################################
450    ### Save the figure in a file in the data folder or an user-defined folder
451    if outputname is None:
452       if typefile in ['meso','mesoapi']:   prefix = getprefix(nc)
453       elif typefile in ['gcm']:            prefix = 'LMD_GCM_'
454       else:                                prefix = ''
455    ###
456       zeplot = prefix + basename
457       if addchar:         zeplot = zeplot + addchar
458       if numplot <= 0:    zeplot = zeplot + "_LT"+str(abs(numplot))
459    ###
460       if not target:      zeplot = namefile[0:find(namefile,'wrfout')] + zeplot
461       else:               zeplot = target + "/" + zeplot 
462    ###
463    else:
464       zeplot=outputname
465
466    if found_lct:     
467        pad_inches_value = 0.35
468        print "********** SAVE ", save
469        if save == 'png': 
470            if display: makeplotres(zeplot,res=100.,pad_inches_value=pad_inches_value) #,erase=True)  ## a miniature
471            makeplotres(zeplot,res=resolution,pad_inches_value=pad_inches_value,disp=False)
472        elif save in ['eps','svg','pdf']:
473            makeplotres(zeplot,         pad_inches_value=pad_inches_value,disp=False,ext=save)
474        elif save == 'gui':
475            show()
476        else: 
477            print "INFO: save mode not supported. using gui instead."
478            show()
479    else:   print "!!! Local time not found"
480
481    ###############
482    ### Now the end
483    return zeplot
Note: See TracBrowser for help on using the repository browser.