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