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

Last change on this file since 378 was 372, checked in by acolaitis, 14 years ago

PYTHON: small commit to add possibility to do semilog plot along the y axis of 2D contour plots.

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