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=2,\ |
---|
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 | |
---|
35 | #################################################################################################################### |
---|
36 | ### Colorbars http://www.scipy.org/Cookbook/Matplotlib/Show_colormaps?action=AttachFile&do=get&target=colormaps3.png |
---|
37 | |
---|
38 | ################################# |
---|
39 | ### Load librairies and functions |
---|
40 | from netCDF4 import Dataset |
---|
41 | from myplot import getcoord2d,define_proj,makeplotres,simplinterv,vectorfield,ptitle,latinterv,getproj,wrfinterv,dumpbdy,\ |
---|
42 | fmtvar,definecolorvec,defcolorb,getprefix,putpoints,calculate_bounds,errormess,definesubplot,\ |
---|
43 | zoomset,getcoorddef,getwinddef,whatkindfile,reducefield,bounds,getstralt,getfield,smooth,nolow,\ |
---|
44 | getname,localtime,polarinterv |
---|
45 | from mymath import deg,max,min,mean |
---|
46 | from matplotlib.pyplot import contour,contourf, subplot, figure, rcParams, savefig, colorbar, pcolor, show |
---|
47 | from matplotlib.cm import get_cmap |
---|
48 | import numpy as np |
---|
49 | from numpy.core.defchararray import find |
---|
50 | |
---|
51 | #if save == 'eps': rcParams['backend'] = 'PS' |
---|
52 | |
---|
53 | ###################### |
---|
54 | ### Load NETCDF object |
---|
55 | nc = Dataset(namefile) |
---|
56 | |
---|
57 | ################################## |
---|
58 | ### Initial checks and definitions |
---|
59 | typefile = whatkindfile(nc) ## TYPEFILE |
---|
60 | if var not in nc.variables: var = False ## VAR |
---|
61 | if winds: ## WINDS |
---|
62 | [uchar,vchar,metwind] = getwinddef(nc) |
---|
63 | if uchar == 'not found': winds = False |
---|
64 | if not var and not winds: errormess("please set at least winds or var",printvar=nc.variables) |
---|
65 | [lon2d,lat2d] = getcoorddef(nc) ## COORDINATES, could be moved below |
---|
66 | if proj == None: proj = getproj(nc) ## PROJECTION |
---|
67 | |
---|
68 | ########################## |
---|
69 | ### Define plot boundaries |
---|
70 | ### todo: possible areas in latinterv in argument (ex: "Far_South_Pole") |
---|
71 | if proj in ["npstere","spstere"]: [wlon,wlat] = polarinterv(lon2d,lat2d) |
---|
72 | elif proj in ["lcc","laea"]: [wlon,wlat] = wrfinterv(lon2d,lat2d) |
---|
73 | else: [wlon,wlat] = simplinterv(lon2d,lat2d) |
---|
74 | if zoom: [wlon,wlat] = zoomset(wlon,wlat,zoom) |
---|
75 | |
---|
76 | ######################################### |
---|
77 | ### Name for title and graphics save file |
---|
78 | basename = getname(var=var,winds=winds,anomaly=anomaly) |
---|
79 | basename = basename + getstralt(nc,nvert) ## can be moved elsewhere for a more generic routine |
---|
80 | |
---|
81 | ################################## |
---|
82 | ### Open a figure and set subplots |
---|
83 | fig = figure() |
---|
84 | sub = definesubplot( numplot, fig ) |
---|
85 | |
---|
86 | ################################# |
---|
87 | ### Time loop for plotting device |
---|
88 | found_lct = False |
---|
89 | itime = first |
---|
90 | nplot = 1 |
---|
91 | error = False |
---|
92 | if itstep is None and numplot > 0: itstep = int(24./numplot) |
---|
93 | elif numplot <= 0: itstep = 1 |
---|
94 | while error is False: |
---|
95 | |
---|
96 | ### Which local time ? |
---|
97 | ltst = localtime ( interv[0]+itime*interv[1], 0.5*(wlon[0]+wlon[1]) ) |
---|
98 | |
---|
99 | ### General plot settings |
---|
100 | #print itime, int(ltst), numplot, nplot |
---|
101 | if numplot >= 1: |
---|
102 | if nplot > numplot: break |
---|
103 | if numplot > 1: |
---|
104 | if typefile not in ['geo']: subplot(sub+nplot-1) |
---|
105 | found_lct = True |
---|
106 | ### If only one local time is requested (numplot < 0) |
---|
107 | elif numplot <= 0: |
---|
108 | if int(ltst) + numplot != 0: |
---|
109 | itime += 1 |
---|
110 | if found_lct is True: break ## because it means LT was found at previous iteration |
---|
111 | else: continue ## continue to iterate to find the correct LT |
---|
112 | else: |
---|
113 | found_lct = True |
---|
114 | |
---|
115 | ### Map projection |
---|
116 | m = define_proj(proj,wlon,wlat,back=back) |
---|
117 | x, y = m(lon2d, lat2d) |
---|
118 | |
---|
119 | #### Contour plot |
---|
120 | if var2: |
---|
121 | what_I_contour, error = reducefield( getfield(nc,var2), d4=itime, d3=nvert ) |
---|
122 | if not error: |
---|
123 | if typefile in ['mesoapi','meso']: what_I_contour = dumpbdy(what_I_contour,6) |
---|
124 | zevmin, zevmax = calculate_bounds(what_I_contour) |
---|
125 | zelevels = np.linspace(zevmin,zevmax,num=20) |
---|
126 | if var2 == 'HGT': zelevels = np.arange(-10000.,30000.,2000.) |
---|
127 | contour( x, y, what_I_contour, zelevels, colors='k', linewidths = 0.33 ) #colors='w' )# , alpha=0.5) |
---|
128 | |
---|
129 | #### Shaded plot |
---|
130 | if var: |
---|
131 | what_I_plot, error = reducefield( getfield(nc,var), d4=itime, d3=nvert ) |
---|
132 | if not error: |
---|
133 | fvar = var |
---|
134 | ### |
---|
135 | if anomaly: |
---|
136 | what_I_plot = 100. * ((what_I_plot / smooth(what_I_plot,12)) - 1.) |
---|
137 | fvar = 'anomaly' |
---|
138 | ### |
---|
139 | if typefile in ['mesoapi','meso']: what_I_plot = dumpbdy(what_I_plot,6) |
---|
140 | zevmin, zevmax = calculate_bounds(what_I_plot,vmin=vmin,vmax=vmax) |
---|
141 | if colorb in ["def","nobar"]: palette = get_cmap(name=defcolorb(fvar)) |
---|
142 | else: palette = get_cmap(name=colorb) |
---|
143 | if not tile: |
---|
144 | if not hole: what_I_plot = bounds(what_I_plot,zevmin,zevmax) |
---|
145 | zelevels = np.linspace(zevmin*(1. + 1.e-7),zevmax*(1. - 1.e-7)) #,num=20) |
---|
146 | contourf( x, y, what_I_plot, zelevels, cmap = palette ) |
---|
147 | else: |
---|
148 | if hole: what_I_plot = nolow(what_I_plot) |
---|
149 | pcolor( x, y, what_I_plot, cmap = palette, \ |
---|
150 | vmin=zevmin, vmax=zevmax ) |
---|
151 | if colorb != 'nobar' and var != 'HGT': |
---|
152 | colorbar(fraction=0.05,pad=0.03,format=fmtvar(fvar),\ |
---|
153 | ticks=np.linspace(zevmin,zevmax,ndiv+1),\ |
---|
154 | extend='neither',spacing='proportional') |
---|
155 | # both min max neither |
---|
156 | |
---|
157 | ### Vector plot |
---|
158 | if winds: |
---|
159 | vecx, error = reducefield( getfield(nc,uchar), d4=itime, d3=nvert ) |
---|
160 | vecy, error = reducefield( getfield(nc,vchar), d4=itime, d3=nvert ) |
---|
161 | if not error: |
---|
162 | if typefile in ['mesoapi','meso']: |
---|
163 | [vecx,vecy] = [dumpbdy(vecx,6,stag=uchar), dumpbdy(vecy,6,stag=vchar)] |
---|
164 | key = True |
---|
165 | elif typefile in ['gcm']: |
---|
166 | key = False |
---|
167 | if metwind: [vecx,vecy] = m.rotate_vector(vecx, vecy, lon2d, lat2d) |
---|
168 | if var == False: colorvec = definecolorvec(back) |
---|
169 | else: colorvec = definecolorvec(colorb) |
---|
170 | vectorfield(vecx, vecy,\ |
---|
171 | x, y, stride=stride, csmooth=2,\ |
---|
172 | #scale=15., factor=300., color=colorvec, key=key) |
---|
173 | scale=20., factor=250., color=colorvec, key=key) |
---|
174 | #200. ## or csmooth=stride |
---|
175 | |
---|
176 | ### Next subplot |
---|
177 | plottitle = basename |
---|
178 | if typefile in ['mesoapi','meso']: |
---|
179 | if addchar: plottitle = plottitle + addchar + "_LT"+str(ltst) |
---|
180 | else: plottitle = plottitle + "_LT"+str(ltst) |
---|
181 | ptitle( plottitle ) |
---|
182 | itime += itstep |
---|
183 | nplot += 1 |
---|
184 | |
---|
185 | ########################################################################## |
---|
186 | ### Save the figure in a file in the data folder or an user-defined folder |
---|
187 | if typefile in ['meso','mesoapi']: prefix = getprefix(nc) |
---|
188 | elif typefile in ['gcm','gcmex']: prefix = 'LMD_GCM_' |
---|
189 | else: prefix = '' |
---|
190 | ### |
---|
191 | zeplot = prefix + basename |
---|
192 | if addchar: zeplot = zeplot + addchar |
---|
193 | if numplot <= 0: zeplot = zeplot + "_LT"+str(abs(numplot)) |
---|
194 | ### |
---|
195 | if not target: zeplot = namefile[0:find(namefile,'wrfout')] + zeplot |
---|
196 | else: zeplot = target + "/" + zeplot |
---|
197 | ### |
---|
198 | if found_lct: |
---|
199 | pad_inches_value = 0.35 |
---|
200 | if save == 'png': |
---|
201 | makeplotres(zeplot,res=100.,pad_inches_value=pad_inches_value) #,erase=True) ## a miniature |
---|
202 | makeplotres(zeplot,res=200.,pad_inches_value=pad_inches_value,disp=False) |
---|
203 | elif save in ['eps','svg','pdf']: |
---|
204 | makeplotres(zeplot, pad_inches_value=pad_inches_value,disp=False,ext=save) |
---|
205 | elif save == 'gui': |
---|
206 | show() |
---|
207 | else: |
---|
208 | print "save mode not supported. using gui instead." |
---|
209 | show() |
---|
210 | else: print "Local time not found" |
---|
211 | |
---|
212 | ############### |
---|
213 | ### Now the end |
---|
214 | return zeplot |
---|
215 | |
---|
216 | ############################## |
---|
217 | ### A specific stuff for below |
---|
218 | def adjust_length (tab, zelen): |
---|
219 | from numpy import ones |
---|
220 | if tab is None: |
---|
221 | outtab = ones(zelen) * -999999 |
---|
222 | else: |
---|
223 | if zelen != len(tab): |
---|
224 | print "not enough or too much values... setting same values all variables" |
---|
225 | outtab = ones(zelen) * tab[0] |
---|
226 | else: |
---|
227 | outtab = tab |
---|
228 | return outtab |
---|
229 | |
---|
230 | ########################################################################################### |
---|
231 | ########################################################################################### |
---|
232 | ### What is below relate to running the file as a command line executable (very convenient) |
---|
233 | if __name__ == "__main__": |
---|
234 | import sys |
---|
235 | from optparse import OptionParser ### to be replaced by argparse |
---|
236 | from api_wrapper import api_onelevel |
---|
237 | from netCDF4 import Dataset |
---|
238 | from myplot import getlschar |
---|
239 | from os import system |
---|
240 | |
---|
241 | ############################# |
---|
242 | ### Get options and variables |
---|
243 | parser = OptionParser() |
---|
244 | parser.add_option('-f', '--file', action='append',dest='namefile', type="string", default=None, help='[NEEDED] name of WRF file (append)') |
---|
245 | parser.add_option('-l', '--level', action='store',dest='nvert', type="float", default=0, help='level (def=0)(-i 2: p,mbar)(-i 3,4: z,km)') |
---|
246 | parser.add_option('-p', '--proj', action='store',dest='proj', type="string", default=None, help='projection') |
---|
247 | parser.add_option('-b', '--back', action='store',dest='back', type="string", default=None, help='background image (def: None)') |
---|
248 | parser.add_option('-t', '--target', action='store',dest='target', type="string", default=None, help='destination folder') |
---|
249 | parser.add_option('-s', '--stride', action='store',dest='stride', type="int", default=3, help='stride vectors (def=3)') |
---|
250 | parser.add_option('-v', '--var', action='append',dest='var', type="string", default=None, help='variable color-shaded (append)') |
---|
251 | parser.add_option('-n', '--num', action='store',dest='numplot', type="int", default=2, help='plot number (def=2)(<0: plot LT -*numplot*)') |
---|
252 | parser.add_option('-i', '--interp', action='store',dest='interp', type="int", default=None, help='interpolation (2: p, 3: z-amr, 4:z-als)') |
---|
253 | parser.add_option('-c', '--color', action='store',dest='colorb', type="string", default="def", help='change colormap (nobar: no colorbar)') |
---|
254 | parser.add_option('-x', '--no-vect',action='store_false',dest='winds', default=True, help='no wind vectors') |
---|
255 | parser.add_option('-m', '--min', action='append',dest='vmin', type="float", default=None, help='bounding minimum value (append)') |
---|
256 | parser.add_option('-M', '--max', action='append',dest='vmax', type="float", default=None, help='bounding maximum value (append)') |
---|
257 | parser.add_option('-T', '--tiled', action='store_true',dest='tile', default=False, help='draw a tiled plot (no blank zone)') |
---|
258 | parser.add_option('-z', '--zoom', action='store',dest='zoom', type="float", default=None, help='zoom factor in %') |
---|
259 | parser.add_option('-N', '--no-api', action='store_true',dest='nocall', default=False, help='do not recreate api file') |
---|
260 | parser.add_option('-d', '--display',action='store_false',dest='display', default=True, help='do not pop up created images') |
---|
261 | parser.add_option('-e', '--itstep', action='store',dest='itstep', type="int", default=None, help='stride time (def=4)') |
---|
262 | parser.add_option('-H', '--hole', action='store_true',dest='hole', default=False, help='holes above max and below min') |
---|
263 | parser.add_option('-S', '--save', action='store',dest='save', type="string", default="gui", help='save mode (png,eps,svg,pdf or gui)(def=gui)') |
---|
264 | parser.add_option('-a', '--anomaly',action='store_true',dest='anomaly', default=False, help='compute and plot relative anomaly in %') |
---|
265 | parser.add_option('-w', '--with', action='store',dest='var2', type="string", default=None, help='variable contoured') |
---|
266 | parser.add_option('--div', action='store',dest='ndiv', type="int", default=10, help='number of divisions in colorbar (def: 10)') |
---|
267 | parser.add_option('-F', '--first', action='store',dest='first', type="int", default=1, help='first subscript to plot (def: 1)') |
---|
268 | #parser.add_option('-V', action='store', dest='comb', type="float", default=None, help='a defined combination of variables') |
---|
269 | (opt,args) = parser.parse_args() |
---|
270 | if opt.namefile is None: |
---|
271 | print "I want to eat one file at least ! Use winds.py -f name_of_my_file. Or type winds.py -h" |
---|
272 | exit() |
---|
273 | if opt.var is None and opt.anomaly is True: |
---|
274 | print "Cannot ask to compute anomaly if no variable is set" |
---|
275 | exit() |
---|
276 | print "Options:", opt |
---|
277 | |
---|
278 | listvar = '' |
---|
279 | if opt.var is None: |
---|
280 | zerange = [-999999] |
---|
281 | else: |
---|
282 | zelen = len(opt.var) |
---|
283 | zerange = range(zelen) |
---|
284 | #if zelen == 1: listvar = opt.var[0] + ',' |
---|
285 | #else : |
---|
286 | for jjj in zerange: listvar += opt.var[jjj] + ',' |
---|
287 | listvar = listvar[0:len(listvar)-1] |
---|
288 | vmintab = adjust_length (opt.vmin, zelen) |
---|
289 | vmaxtab = adjust_length (opt.vmax, zelen) |
---|
290 | |
---|
291 | for i in range(len(opt.namefile)): |
---|
292 | |
---|
293 | zefile = opt.namefile[i] |
---|
294 | print zefile |
---|
295 | zelevel = opt.nvert |
---|
296 | stralt = None |
---|
297 | [lschar,zehour,zehourin] = getlschar ( zefile ) ## getlschar from wrfout (or simply return "" if another file) |
---|
298 | |
---|
299 | ##################################################### |
---|
300 | ### Call Fortran routines for vertical interpolations |
---|
301 | if opt.interp is not None: |
---|
302 | if opt.nvert is 0 and opt.interp is 4: zelevel = 0.010 |
---|
303 | ### winds or no winds |
---|
304 | if opt.winds : zefields = 'uvmet' |
---|
305 | else : zefields = '' |
---|
306 | ### var or no var |
---|
307 | #if opt.var is None : pass |
---|
308 | if zefields == '' : zefields = listvar |
---|
309 | else : zefields = zefields + "," + listvar |
---|
310 | if opt.var2 is not None : zefields = zefields + "," + opt.var2 |
---|
311 | print zefields |
---|
312 | zefile = api_onelevel ( path_to_input = '', \ |
---|
313 | input_name = zefile, \ |
---|
314 | fields = zefields, \ |
---|
315 | interp_method = opt.interp, \ |
---|
316 | onelevel = zelevel, \ |
---|
317 | nocall = opt.nocall ) |
---|
318 | print zefile |
---|
319 | zelevel = 0 ## so that zelevel could play again the role of nvert |
---|
320 | |
---|
321 | if opt.var is None: zerange = [-999999] |
---|
322 | else: zerange = range(zelen) |
---|
323 | for jjj in zerange: |
---|
324 | if jjj == -999999: |
---|
325 | argvar = None |
---|
326 | argvmin = None |
---|
327 | argvmax = None |
---|
328 | else: |
---|
329 | argvar = opt.var[jjj] |
---|
330 | if vmintab[jjj] != -999999: argvmin = vmintab[jjj] |
---|
331 | else: argvmin = None |
---|
332 | if vmaxtab[jjj] != -999999: argvmax = vmaxtab[jjj] |
---|
333 | else: argvmax = None |
---|
334 | ############# |
---|
335 | ### Main call |
---|
336 | name = winds (zefile,int(zelevel),\ |
---|
337 | proj=opt.proj,back=opt.back,target=opt.target,stride=opt.stride,var=argvar,\ |
---|
338 | numplot=opt.numplot,colorb=opt.colorb,winds=opt.winds,\ |
---|
339 | addchar=lschar,interv=[zehour,zehourin],vmin=argvmin,vmax=argvmax,\ |
---|
340 | tile=opt.tile,zoom=opt.zoom,display=opt.display,\ |
---|
341 | itstep=opt.itstep,hole=opt.hole,save=opt.save,\ |
---|
342 | anomaly=opt.anomaly,var2=opt.var2,ndiv=opt.ndiv,first=opt.first) |
---|
343 | print 'Done: '+name |
---|
344 | system("rm -f to_be_erased") |
---|
345 | |
---|
346 | ######################################################### |
---|
347 | ### Generate a .sh file with the used command saved in it |
---|
348 | command = "" |
---|
349 | for arg in sys.argv: command = command + arg + ' ' |
---|
350 | f = open(name+'.sh', 'w') |
---|
351 | f.write(command) |
---|