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

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

PYTHON GRAPHICS: for mesoscale files section with vertically interpolated fields with alitude or pressure (through api wrapper) is now supported. the same thing might be useful to be done with zrecast for GCM.

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