source: trunk/MESOSCALE/LMD_MM_MARS/SRC/PYTHON/planetoplot.py @ 350

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

PYTHON: improvements on handling 1D 2D slices for gcm and meso. a few minor corrections added for the scripts to work better. it might be possible at some point to merge meso.py and gcm.py, wait and see.

  • Property svn:executable set to *
File size: 16.1 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           nvert=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              vert = np.arange(0,getattr(nc,vertdim),1)
115              time = np.arange(0,len(nc.variables["Times"]),1)
116       #if firstfile:
117       #   lat0 = lat
118       #elif len(lat0) != len(lat):
119       #   errormess("Not the same latitude lengths !", [len(lat0), len(lat)])
120       #elif sum((lat == lat0) == False) != 0:
121       #   errormess("Not the same latitudes !", [lat,lat0])
122       ## Faire d'autre checks sur les compatibilites entre fichiers!!
123##########################################################
124
125      if firstfile:
126         ##########################
127         ### Define plot boundaries
128         ### todo: possible areas in latinterv in argument (ex: "Far_South_Pole")
129         if proj in ["npstere","spstere"]: [wlon,wlat] = polarinterv(lon2d,lat2d)
130         elif proj in ["lcc","laea"]:      [wlon,wlat] = wrfinterv(lon2d,lat2d)
131         else:                             [wlon,wlat] = simplinterv(lon2d,lat2d)
132         if zoom:                          [wlon,wlat] = zoomset(wlon,wlat,zoom) 
133
134         #########################################
135         ### Name for title and graphics save file
136         basename = getname(var=var,winds=winds,anomaly=anomaly)
137         basename = basename + getstralt(nc,nvert)  ## can be moved elsewhere for a more generic routine
138     
139      print "var, var2: ", var, var2
140      if var: all_var[k] = getfield(nc,var)
141      if var2: all_var2[k] = getfield(nc,var2)
142     
143      print "k", k
144      print "all_var[k].shape", all_var[k].shape
145      k += 1
146      firstfile = False
147      #### End of for namefile in namefiles
148
149
150    ##################################
151    ### Open a figure and set subplots
152    fig = figure()
153    subv,subh = definesubplot( numplot, fig ) 
154 
155    #################################
156    ### Time loop for plotting device
157    found_lct = False
158    nplot = 1
159    itime = first
160    error = False
161    if itstep is None and numplot > 0: itstep = int(24./numplot)
162    elif numplot <= 0:                 itstep = 1 
163   
164    #for nplot in range(numplot):
165    while error is False:
166       print "nplot", nplot
167       print error
168       
169       ### Which local time ?
170       ltst = localtime ( interv[0]+itime*interv[1], 0.5*(wlon[0]+wlon[1]) )
171
172       ### General plot settings
173       #print itime, int(ltst), numplot, nplot
174       if numplot >= 1: 
175           if nplot > numplot: break
176           if numplot > 1:     
177               if typefile not in ['geo']:  subplot(subv,subh,nplot)
178           found_lct = True
179       ### If only one local time is requested (numplot < 0)
180       elif numplot <= 0: 
181           if int(ltst) + numplot != 0: 
182                 itime += 1 
183                 if found_lct is True: break     ## because it means LT was found at previous iteration
184                 else:                 continue  ## continue to iterate to find the correct LT
185           else: 
186                 found_lct = True
187
188       ### Map projection                   
189       if mapmode == 1:
190           m = define_proj(proj,wlon,wlat,back=back)
191           x, y = m(lon2d, lat2d)
192
193####################################################################
194       if typefile in ['meso','mesoapi'] and mapmode == 1: 
195               indextime = itime
196               indexlon = None
197               indexlat = None
198               indexvert = nvert  ## ou svert ???
199               nlon = 1
200               nlat = 1
201               nvert = 1
202               ntime = 1 
203       else:
204           ## get all indexes to be taken into account for this subplot and then reduce field
205           ## 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
206           indexlon  = getsindex(slon,(nplot-1)%nlon,lon)
207           indexlat  = getsindex(slat,((nplot-1)//nlon)%nlat,lat)
208           indexvert = getsindex(svert,((nplot-1)//(nlon*nlat))%nvert,vert) 
209           indextime = getsindex(stime,((nplot-1)//(nlon*nlat*nvert))%ntime,time) 
210       index_f = ((nplot-1)//(nlon*nlat*nvert*ntime))%len(namefiles)
211       print nlon, nlat, nvert, ntime 
212       print slon, slat, svert, stime       
213       print index_f
214       print "index lon,lat,vert,time", max(indexlon), max(indexlat), max(indexvert), max(indextime)
215####################################################################
216
217       #### Contour plot
218       if var2:
219           what_I_plot, error = reducefield(all_var2[index_f], d4=indextime, d1=indexlon, d2=indexlat , d3=indexvert )
220           #what_I_plot = what_I_plot*mult
221           if not error:
222              if mapmode == 1:
223                  if typefile in ['mesoapi','meso']:    what_I_plot = dumpbdy(what_I_plot,6)
224              zevmin, zevmax = calculate_bounds(what_I_plot)
225              zelevels = np.linspace(zevmin,zevmax,num=ndiv+1) #20)
226              if var2 == 'HGT':  zelevels = np.arange(-10000.,30000.,2000.)
227              if mapmode == 0:
228                  x, y = define_axis(lon,lat,vert,time,indexlon,indexlat,indexvert,\
229                        indextime,what_I_plot.shape, len(all_var2[index_f].shape),vertmode)
230              ### If we plot a 2-D field
231              if len(what_I_plot.shape) is 2:
232                  cs = contour(x,y,what_I_plot, zelevels, colors='k', linewidths = 1 ) #0.33 colors='w' )# , alpha=0.5)
233                  if typefile in ['gcm']: clabel(cs,fmt = '%1.2e')
234              ### If we plot a 1-D field
235              elif len(what_I_plot.shape) is 1:
236                  plot(what_I_plot,x) 
237           else:
238              errormess("There is an error in reducing field !")
239
240       #### Shaded plot
241       if var:
242           what_I_plot, error = reducefield(all_var[index_f], d4=indextime, d1=indexlon, d2=indexlat , d3=indexvert )
243           what_I_plot = what_I_plot*mult
244           
245           if not error: 
246               fvar = var
247               ###
248               if anomaly:
249                   what_I_plot = 100. * ((what_I_plot / smooth(what_I_plot,12)) - 1.)
250                   fvar = 'anomaly'
251               #if mult != 1:     
252               #    fvar = str(mult) + "*" + var
253               ###
254               if mapmode == 1:
255                   if typefile in ['mesoapi','meso']:    what_I_plot = dumpbdy(what_I_plot,6)
256               elif mapmode == 0:
257                   what_I_plot, x, y = define_axis(lon,lat,vert,time,indexlon,indexlat,indexvert,\
258                         indextime,what_I_plot, len(all_var[index_f].shape),vertmode)
259               zevmin, zevmax = calculate_bounds(what_I_plot,vmin=vmin,vmax=vmax)
260               if colorb in ["def","nobar"]:   palette = get_cmap(name=defcolorb(fvar.upper()))
261               else:                           palette = get_cmap(name=colorb)
262               ##### 2D field
263               if len(what_I_plot.shape) is 2:
264                 if not tile:
265                     if not hole: what_I_plot = bounds(what_I_plot,zevmin,zevmax)
266                     #zelevels = np.linspace(zevmin*(1. + 1.e-7),zevmax*(1. - 1.e-7)) #,num=20)
267                     zelevels = np.linspace(zevmin,zevmax)#,num=ndiv+1)
268                     #contourf(what_I_plot, zelevels, cmap = palette )
269                     contourf( x, y, what_I_plot, zelevels, cmap = palette )
270                 else:
271                     if hole:  what_I_plot = nolow(what_I_plot)
272                     pcolor( x, y, what_I_plot, cmap = palette, vmin=zevmin, vmax=zevmax )
273                 if colorb != 'nobar' and var != 'HGT' :       
274                         colorbar(fraction=0.05,pad=0.03,format=fmtvar(fvar.upper()),\
275                                           ticks=np.linspace(zevmin,zevmax,min([ndiv+1,20])),\
276                                           extend='neither',spacing='proportional')
277                                           # both min max neither
278               ##### 1D field
279               elif len(what_I_plot.shape) is 1:
280                 plot(x,what_I_plot)
281               #### Other cases: (maybe plot 3-D field one day or movie ??)
282               else:
283                 print "WARNING!!! ",len(what_I_plot.shape),"-D PLOT NOT SUPPORTED !!!"
284                 print "field dimensions: ", what_I_plot.shape
285                 exit()
286               
287           else:
288               errormess("There is an error in reducing field !")
289
290       ### Vector plot --- a adapter
291       if winds:
292           vecx, error = reducefield( getfield(nc,uchar), d4=indextime, d3=indexvert )
293           vecy, error = reducefield( getfield(nc,vchar), d4=indextime, d3=indexvert )
294           #what_I_plot, error = reducefield(all_var[index_f], d4=indextime, d1=indexlon, d2=indexlat , d3=indexvert )
295           if not error:
296               if typefile in ['mesoapi','meso']:   
297                   [vecx,vecy] = [dumpbdy(vecx,6,stag=uchar), dumpbdy(vecy,6,stag=vchar)]
298                   key = True
299               elif typefile in ['gcm']:           
300                   key = False
301               if metwind:  [vecx,vecy] = m.rotate_vector(vecx, vecy, lon2d, lat2d)
302               if var == False:       colorvec = definecolorvec(back)
303               else:                  colorvec = definecolorvec(colorb)
304               vectorfield(vecx, vecy,\
305                          x, y, stride=stride, csmooth=2,\
306                          #scale=15., factor=300., color=colorvec, key=key)
307                          scale=20., factor=250., color=colorvec, key=key)
308                                            #200.         ## or csmooth=stride
309   
310       ### Next subplot
311       if typefile in ['mesoapi','meso']:
312            plottitle = basename
313            if addchar:  plottitle = plottitle + addchar + "_LT"+str(ltst)
314            else:        plottitle = plottitle + "_LT"+str(ltst)
315       else:
316            plottitle = basename+' '+namefiles[index_f]
317       if mult != 1:           plottitle = str(mult) + "*" + plottitle
318       if zetitle != "fill":   plottitle = zetitle
319#       if indexlon is not None:
320#         plottitle = plottitle + " lon: " + str(min(lon[indexlon])) +" "+ str(max(lon[indexlon]))
321#       if indexlat is not None:
322#         plottitle = plottitle + " lat: " + str(min(lat[indexlat])) +" "+ str(max(lat[indexlat]))
323#       if indexvert is not None:
324#         plottitle = plottitle + " vert: " + str(min(vert[indexvert])) +" "+ str(max(vert[indexvert]))
325#       if indextime is not None:
326#         plottitle = plottitle + " time: " + str(min(time[indextime])) +" "+ str(max(time[indextime]))
327       ptitle( plottitle )
328       itime += itstep
329       if nplot >= numplot:
330          error = True
331       nplot += 1
332
333 
334
335
336
337
338
339     
340    ##########################################################################
341    ### Save the figure in a file in the data folder or an user-defined folder
342    if typefile in ['meso','mesoapi']:   prefix = getprefix(nc)
343    elif typefile in ['gcm']:            prefix = 'LMD_GCM_'
344    else:                                prefix = ''
345    ###
346    zeplot = prefix + basename
347    if addchar:         zeplot = zeplot + addchar
348    if numplot <= 0:    zeplot = zeplot + "_LT"+str(abs(numplot))
349    ###
350    if not target:      zeplot = namefile[0:find(namefile,'wrfout')] + zeplot
351    else:               zeplot = target + "/" + zeplot 
352    ###
353    if found_lct:     
354        pad_inches_value = 0.35
355        print "save", save
356        if save == 'png': 
357            if display: makeplotres(zeplot,res=100.,pad_inches_value=pad_inches_value) #,erase=True)  ## a miniature
358            makeplotres(zeplot,res=200.,pad_inches_value=pad_inches_value,disp=False)
359        elif save in ['eps','svg','pdf']:
360            makeplotres(zeplot,         pad_inches_value=pad_inches_value,disp=False,ext=save)
361        elif save == 'gui':
362            show()
363        else: 
364            print "save mode not supported. using gui instead."
365            show()
366    else:   print "Local time not found"
367
368    ###############
369    ### Now the end
370    return zeplot
Note: See TracBrowser for help on using the repository browser.