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

Last change on this file since 416 was 407, checked in by acolaitis, 14 years ago

Corrected small bug related to all_time

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