1 | #!/usr/bin/env python |
---|
2 | |
---|
3 | ### A. Spiga -- LMD -- 30/06/2011 to 10/07/2011 |
---|
4 | ### Thanks to A. Colaitis for the parser trick |
---|
5 | |
---|
6 | |
---|
7 | #################################### |
---|
8 | #################################### |
---|
9 | ### The main program to plot vectors |
---|
10 | def winds (namefile,\ |
---|
11 | nvert,\ |
---|
12 | proj=None,\ |
---|
13 | back=None,\ |
---|
14 | target=None, |
---|
15 | stride=3,\ |
---|
16 | numplot=4,\ |
---|
17 | var=None,\ |
---|
18 | colorb=True,\ |
---|
19 | winds=True,\ |
---|
20 | addchar=None,\ |
---|
21 | interv=[0,1],\ |
---|
22 | vmin=None,\ |
---|
23 | vmax=None,\ |
---|
24 | tile=False,\ |
---|
25 | zoom=None): |
---|
26 | |
---|
27 | #################################################################################################################### |
---|
28 | ### Colorbars http://www.scipy.org/Cookbook/Matplotlib/Show_colormaps?action=AttachFile&do=get&target=colormaps3.png |
---|
29 | |
---|
30 | ################################# |
---|
31 | ### Load librairies and functions |
---|
32 | from netCDF4 import Dataset |
---|
33 | from myplot import getcoord2d,define_proj,makeplotpng,simplinterv,vectorfield,ptitle,latinterv,getproj,wrfinterv,dumpbdy,\ |
---|
34 | fmtvar,definecolorvec,getwinds,defcolorb,getprefix |
---|
35 | from mymath import deg,max,min,mean |
---|
36 | from matplotlib.pyplot import contour,contourf, subplot, figure, rcParams, savefig, colorbar, pcolor |
---|
37 | from matplotlib.cm import get_cmap |
---|
38 | import numpy as np |
---|
39 | from numpy.core.defchararray import find |
---|
40 | |
---|
41 | ### |
---|
42 | #rcParams['text.usetex'] = True |
---|
43 | #rcParams['cairo.format'] = 'svg' |
---|
44 | |
---|
45 | ###################### |
---|
46 | ### Load NETCDF object |
---|
47 | nc = Dataset(namefile) |
---|
48 | |
---|
49 | ################################### |
---|
50 | ### Recognize predefined file types |
---|
51 | if 'controle' in nc.variables: typefile = 'gcm' |
---|
52 | elif 'vert' in nc.variables: typefile = 'mesoapi' |
---|
53 | elif 'U' in nc.variables: typefile = 'meso' |
---|
54 | else: |
---|
55 | print "typefile not supported." |
---|
56 | print nc.variables |
---|
57 | exit() |
---|
58 | |
---|
59 | ############################################################## |
---|
60 | ### Try to guess the projection from wrfout if not set by user |
---|
61 | if typefile in ['mesoapi','meso']: |
---|
62 | if proj == None: proj = getproj(nc) |
---|
63 | ### (il faudrait passer CEN_LON dans la projection ?) |
---|
64 | elif typefile in ['gcm']: |
---|
65 | if proj == None: proj = "cyl" |
---|
66 | ## pb avec les autres (de trace derriere la sphere ?) |
---|
67 | |
---|
68 | ############################################ |
---|
69 | #### Choose underlying topography by default |
---|
70 | if not back: |
---|
71 | if not var: back = "mola" ## if no var: draw mola |
---|
72 | elif typefile in ['mesoapi','meso'] \ |
---|
73 | and proj not in ['merc','lcc']: back = "molabw" ## if var but meso: draw molabw |
---|
74 | else: pass ## else: draw None |
---|
75 | |
---|
76 | #################################################### |
---|
77 | ### Get geographical coordinates and plot boundaries |
---|
78 | if typefile in ['mesoapi','meso']: |
---|
79 | [lon2d,lat2d] = getcoord2d(nc) |
---|
80 | lon2d = dumpbdy(lon2d) |
---|
81 | lat2d = dumpbdy(lat2d) |
---|
82 | elif typefile in ['gcm']: |
---|
83 | [lon2d,lat2d] = getcoord2d(nc,nlat="latitude",nlon="longitude",is1d=True) |
---|
84 | if proj == "npstere": [wlon,wlat] = latinterv("North_Pole") |
---|
85 | elif proj == "lcc": [wlon,wlat] = wrfinterv(lon2d,lat2d) |
---|
86 | else: [wlon,wlat] = simplinterv(lon2d,lat2d) |
---|
87 | if zoom: |
---|
88 | dlon = abs(wlon[1]-wlon[0])/2. |
---|
89 | dlat = abs(wlat[1]-wlat[0])/2. |
---|
90 | [wlon,wlat] = [ [wlon[0]+zoom*dlon/100.,wlon[1]-zoom*dlon/100.],\ |
---|
91 | [wlat[0]+zoom*dlat/100.,wlat[1]-zoom*dlat/100.] ] |
---|
92 | print "zoom %",zoom,wlon,wlat |
---|
93 | |
---|
94 | ############################################################################## |
---|
95 | ### Get winds and know if those are meteorological winds (ie. zon, mer) or not |
---|
96 | if winds: |
---|
97 | if typefile is 'mesoapi': |
---|
98 | [u,v] = getwinds(nc) |
---|
99 | metwind = True ## meteorological (zon/mer) |
---|
100 | elif typefile is 'gcm': |
---|
101 | [u,v] = getwinds(nc,charu='u',charv='v') |
---|
102 | metwind = True ## meteorological (zon/mer) |
---|
103 | elif typefile is 'meso': |
---|
104 | [u,v] = getwinds(nc,charu='U',charv='V') |
---|
105 | metwind = False ## geometrical (wrt grid) |
---|
106 | print "Beware ! Not using meteorological winds. You trust numerical grid as being (x,y)." |
---|
107 | |
---|
108 | ##################################################### |
---|
109 | ### Load the chosen variables, whether it is 2D or 3D |
---|
110 | if var: |
---|
111 | if var not in nc.variables: |
---|
112 | print "not found in file:",var |
---|
113 | exit() |
---|
114 | else: |
---|
115 | dimension = np.array(nc.variables[var]).ndim |
---|
116 | if dimension == 2: field = nc.variables[var][:,:] |
---|
117 | elif dimension == 3: field = nc.variables[var][:,:,:] |
---|
118 | elif dimension == 4: field = nc.variables[var][:,nvert,:,:] |
---|
119 | dev = np.std(field)*3.0 |
---|
120 | if vmin is None: zevmin = mean(field) - dev |
---|
121 | else: zevmin = vmin |
---|
122 | if vmax is None: zevmax = mean(field) + dev |
---|
123 | else: zevmax = vmax |
---|
124 | print "bounds ", zevmin, zevmax |
---|
125 | ### some already defined colormaps |
---|
126 | if colorb is True: colorb = defcolorb(var) |
---|
127 | |
---|
128 | ########################### |
---|
129 | ### Get length of time axis |
---|
130 | if winds: nt = len(u[:,0,0,0]) |
---|
131 | elif var: |
---|
132 | if dimension == 2: nt = 1 |
---|
133 | else : nt = len(field[:,0,0]) |
---|
134 | |
---|
135 | ######################################### |
---|
136 | ### Name for title and graphics save file |
---|
137 | if winds: basename = "UV_" |
---|
138 | else: basename = "" |
---|
139 | if var: basename = basename + var |
---|
140 | ### |
---|
141 | if typefile is 'meso': stralt = "_lvl" + str(nvert) |
---|
142 | elif typefile is 'mesoapi': |
---|
143 | zelevel = int(nc.variables['vert'][nvert]) |
---|
144 | if 'altitude' in nc.dimensions: stralt = "_"+str(zelevel)+"m-AMR" |
---|
145 | elif 'altitude_abg' in nc.dimensions: stralt = "_"+str(zelevel)+"m-ALS" |
---|
146 | elif 'bottom_top' in nc.dimensions: stralt = "_"+str(zelevel)+"m" |
---|
147 | elif 'pressure' in nc.dimensions: stralt = "_"+str(zelevel)+"Pa" |
---|
148 | else: stralt = "" |
---|
149 | ### |
---|
150 | basename = basename + stralt |
---|
151 | |
---|
152 | ################################## |
---|
153 | ### Open a figure and set subplots |
---|
154 | fig = figure() |
---|
155 | if numplot > 0: |
---|
156 | if numplot == 4: |
---|
157 | sub = 221 |
---|
158 | fig.subplots_adjust(wspace = 0.3, hspace = 0.3) |
---|
159 | rcParams['font.size'] = int( rcParams['font.size'] * 2. / 3. ) |
---|
160 | elif numplot == 2: |
---|
161 | sub = 121 |
---|
162 | fig.subplots_adjust(wspace = 0.3) |
---|
163 | rcParams['font.size'] = int( rcParams['font.size'] * 3. / 4. ) |
---|
164 | elif numplot == 3: |
---|
165 | sub = 131 |
---|
166 | fig.subplots_adjust(wspace = 0.5) |
---|
167 | rcParams['font.size'] = int( rcParams['font.size'] * 1. / 2. ) |
---|
168 | elif numplot == 6: |
---|
169 | sub = 231 |
---|
170 | fig.subplots_adjust(wspace = 0.4, hspace = 0.0) |
---|
171 | rcParams['font.size'] = int( rcParams['font.size'] * 1. / 2. ) |
---|
172 | elif numplot == 8: |
---|
173 | sub = 331 #241 |
---|
174 | fig.subplots_adjust(wspace = 0.3, hspace = 0.3) |
---|
175 | rcParams['font.size'] = int( rcParams['font.size'] * 1. / 2. ) |
---|
176 | elif numplot == 9: |
---|
177 | sub = 331 |
---|
178 | fig.subplots_adjust(wspace = 0.3, hspace = 0.3) |
---|
179 | rcParams['font.size'] = int( rcParams['font.size'] * 1. / 2. ) |
---|
180 | elif numplot == 1: |
---|
181 | sub = 99999 |
---|
182 | else: |
---|
183 | print "supported: 1,2,3,4,6,8" |
---|
184 | exit() |
---|
185 | ### Prepare time loop |
---|
186 | if nt <= numplot or numplot == 1: |
---|
187 | tabrange = [0] |
---|
188 | numplot = 1 |
---|
189 | else: |
---|
190 | tabrange = range(0,nt,int(nt/numplot)) #nt-1 |
---|
191 | tabrange = tabrange[0:numplot] |
---|
192 | else: |
---|
193 | tabrange = range(0,nt,1) |
---|
194 | sub = 99999 |
---|
195 | print tabrange |
---|
196 | |
---|
197 | ################################# |
---|
198 | ### Time loop for plotting device |
---|
199 | found_lct = False |
---|
200 | for i in tabrange: |
---|
201 | |
---|
202 | ### Which local time ? |
---|
203 | ltst = ( interv[0] + 0.5*(wlon[0]+wlon[1])/15.) + i*interv[1] |
---|
204 | ltst = int (ltst * 10) / 10. |
---|
205 | ltst = ltst % 24 |
---|
206 | |
---|
207 | ### General plot settings |
---|
208 | if numplot > 1: |
---|
209 | subplot(sub) |
---|
210 | found_lct = True |
---|
211 | elif numplot == 1: |
---|
212 | found_lct = True |
---|
213 | ### If only one local time is requested (numplot < 0) |
---|
214 | elif numplot <= 0: |
---|
215 | if int(ltst) + numplot != 0: continue |
---|
216 | else: found_lct = True |
---|
217 | |
---|
218 | ### Map projection |
---|
219 | m = define_proj(proj,wlon,wlat,back=back) |
---|
220 | x, y = m(lon2d, lat2d) |
---|
221 | |
---|
222 | #### Contour plot |
---|
223 | if var: |
---|
224 | if typefile in ['mesoapi','meso']: what_I_plot = dumpbdy(field[i,:,:]) |
---|
225 | elif typefile in ['gcm']: |
---|
226 | if dimension == 2: what_I_plot = field[:,:] |
---|
227 | elif dimension == 3: what_I_plot = field[i,:,:] |
---|
228 | palette = get_cmap(name=colorb) |
---|
229 | #palette.set_over('b', 1.0) |
---|
230 | if not tile: |
---|
231 | zelevels = np.linspace(zevmin,zevmax) |
---|
232 | contourf( x, y, what_I_plot, 10, cmap = palette, levels = zelevels ) |
---|
233 | else: |
---|
234 | pcolor( x, y, what_I_plot, cmap = palette, vmin=zevmin, vmax=zevmax ) |
---|
235 | if var in ['HGT']: pass |
---|
236 | elif colorb: |
---|
237 | ndiv = 10 |
---|
238 | colorbar(fraction=0.05,pad=0.1,format=fmtvar(var),\ |
---|
239 | ticks=np.linspace(zevmin,zevmax,ndiv+1),\ |
---|
240 | extend='max',spacing='proportional') |
---|
241 | # both min max neither |
---|
242 | ### Vector plot |
---|
243 | if winds: |
---|
244 | if typefile in ['mesoapi','meso']: |
---|
245 | [vecx,vecy] = [dumpbdy(u[i,nvert,:,:]), dumpbdy(v[i,nvert,:,:])] |
---|
246 | key = True |
---|
247 | elif typefile in ['gcm']: |
---|
248 | [vecx,vecy] = [ u[i,nvert,:,:] , v[i,nvert,:,:] ] |
---|
249 | key = False |
---|
250 | if metwind: [vecx,vecy] = m.rotate_vector(vecx, vecy, lon2d, lat2d) |
---|
251 | if var == None: colorvec = definecolorvec(back) |
---|
252 | else: colorvec = definecolorvec(colorb) |
---|
253 | vectorfield(vecx, vecy,\ |
---|
254 | x, y, stride=stride, csmooth=stride,\ |
---|
255 | scale=15., factor=300., color=colorvec, key=key) |
---|
256 | #200. ## or csmooth=2 |
---|
257 | |
---|
258 | ### Next subplot |
---|
259 | plottitle = basename |
---|
260 | if addchar: plottitle = plottitle + addchar + "_LT"+str(ltst) |
---|
261 | else: plottitle = plottitle + "_LT"+str(ltst) |
---|
262 | ptitle( plottitle ) |
---|
263 | sub += 1 |
---|
264 | |
---|
265 | ########################################################################## |
---|
266 | ### Save the figure in a file in the data folder or an user-defined folder |
---|
267 | if typefile in ['meso','mesoapi']: prefix = getprefix(nc) |
---|
268 | elif typefile in ['gcm']: prefix = 'LMD_GCM_' |
---|
269 | else: prefix = '' |
---|
270 | ### |
---|
271 | zeplot = prefix + basename |
---|
272 | if addchar: zeplot = zeplot + addchar |
---|
273 | if numplot <= 0: zeplot = zeplot + "_LT"+str(abs(numplot)) |
---|
274 | ### |
---|
275 | if not target: zeplot = namefile[0:find(namefile,'wrfout')] + zeplot |
---|
276 | else: zeplot = target + "/" + zeplot |
---|
277 | ### |
---|
278 | if found_lct: makeplotpng(zeplot,pad_inches_value=0.35) |
---|
279 | else: print "Local time not found" |
---|
280 | |
---|
281 | ############### |
---|
282 | ### Now the end |
---|
283 | return zeplot |
---|
284 | |
---|
285 | ########################################################################################### |
---|
286 | ########################################################################################### |
---|
287 | ### What is below relate to running the file as a command line executable (very convenient) |
---|
288 | if __name__ == "__main__": |
---|
289 | import sys |
---|
290 | from optparse import OptionParser ### to be replaced by argparse |
---|
291 | from api_wrapper import api_onelevel |
---|
292 | from netCDF4 import Dataset |
---|
293 | from myplot import getlschar |
---|
294 | |
---|
295 | ############################# |
---|
296 | ### Get options and variables |
---|
297 | parser = OptionParser() |
---|
298 | parser.add_option('-f', action='store', dest='namefile', type="string", default=None, help='[NEEDED] name of WRF file') |
---|
299 | parser.add_option('-l', action='store', dest='nvert', type="float", default=0, help='vertical level (def=0)(-i 2: p,mbar)(-i 3,4: z,km)') |
---|
300 | parser.add_option('-p', action='store', dest='proj', type="string", default=None, help='projection') |
---|
301 | parser.add_option('-b', action='store', dest='back', type="string", default=None, help='background') |
---|
302 | parser.add_option('-t', action='store', dest='target', type="string", default=None, help='destination folder') |
---|
303 | parser.add_option('-s', action='store', dest='stride', type="int", default=3, help='stride vectors (def=3)') |
---|
304 | parser.add_option('-v', action='store', dest='var', type="string", default=None, help='variable contoured') |
---|
305 | parser.add_option('-n', action='store', dest='numplot', type="int", default=4, help='number of plots (def=1)(<0: 1 plot of LT -*numplot*)') |
---|
306 | parser.add_option('-i', action='store', dest='interp', type="int", default=None, help='interpolation method (2: press, 3: z-amr, 4:z-als)') |
---|
307 | parser.add_option('-c', action='store', dest='colorb', type="string", default=True, help='change colormap') |
---|
308 | parser.add_option('-x', action='store_false', dest='winds', default=True, help='flag: no wind vectors') |
---|
309 | parser.add_option('-m', action='store', dest='vmin', type="float", default=None, help='bounding minimum value for color plot') |
---|
310 | parser.add_option('-M', action='store', dest='vmax', type="float", default=None, help='bounding maximum value for color plot') |
---|
311 | parser.add_option('-T', action='store_true', dest='tile', default=False, help='draw a tiled plot (no blank zone)') |
---|
312 | parser.add_option('-z', action='store', dest='zoom', type="float", default=None, help='zoom factor in %') |
---|
313 | #parser.add_option('-V', action='store', dest='comb', type="float", default=None, help='a defined combination of variables') |
---|
314 | (opt,args) = parser.parse_args() |
---|
315 | if opt.namefile is None: |
---|
316 | print "I want to eat one file at least ! Use winds.py -f name_of_my_file. Or type winds.py -h" |
---|
317 | exit() |
---|
318 | print "Options:", opt |
---|
319 | zefile = opt.namefile |
---|
320 | zelevel = opt.nvert |
---|
321 | stralt = None |
---|
322 | [lschar,zehour,zehourin] = getlschar ( zefile ) ## getlschar from wrfout (or simply return "" if another file) |
---|
323 | |
---|
324 | ##################################################### |
---|
325 | ### Call Fortran routines for vertical interpolations |
---|
326 | if opt.interp is not None: |
---|
327 | if opt.nvert is 0 and opt.interp is 4: zelevel = 0.010 |
---|
328 | ### winds or no winds |
---|
329 | if opt.winds : zefields = 'uvmet' |
---|
330 | else : zefields = '' |
---|
331 | ### var or no var |
---|
332 | if opt.var is None : pass |
---|
333 | elif zefields == '' : zefields = opt.var |
---|
334 | else : zefields = zefields + "," + opt.var |
---|
335 | print zefields |
---|
336 | zefile = api_onelevel ( path_to_input = '', \ |
---|
337 | input_name = zefile, \ |
---|
338 | path_to_output = opt.target, \ |
---|
339 | fields = zefields, \ |
---|
340 | interp_method = opt.interp, \ |
---|
341 | onelevel = zelevel ) |
---|
342 | zelevel = 0 ## so that zelevel could play again the role of nvert |
---|
343 | |
---|
344 | ############# |
---|
345 | ### Main call |
---|
346 | name = winds (zefile,int(zelevel),\ |
---|
347 | proj=opt.proj,back=opt.back,target=opt.target,stride=opt.stride,var=opt.var,numplot=opt.numplot,colorb=opt.colorb,winds=opt.winds,\ |
---|
348 | addchar=lschar,interv=[zehour,zehourin],vmin=opt.vmin,vmax=opt.vmax,tile=opt.tile,zoom=opt.zoom) |
---|
349 | print 'Done: '+name |
---|
350 | |
---|
351 | ######################################################### |
---|
352 | ### Generate a .sh file with the used command saved in it |
---|
353 | command = "" |
---|
354 | for arg in sys.argv: command = command + arg + ' ' |
---|
355 | f = open(name+'.sh', 'w') |
---|
356 | f.write(command) |
---|