source: trunk/MESOSCALE/PLOT/PYTHON/scripts/winds.py @ 191

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

MESOSCALE: python graphics. added the nowind case plus corrected a few minor things.

  • Property svn:executable set to *
File size: 12.6 KB
Line 
1#!/usr/bin/env python
2
3### A. Spiga -- LMD -- 30/06/2011 to 04/07/2011
4### Thanks to A. Colaitis for the parser trick
5
6
7####################################
8####################################
9### The main program to plot vectors
10def winds (namefile,\
11           nvert,\
12           proj=None,\
13           back=None,\
14           target=None,
15           stride=3,\
16           numplot=4,\
17           var=None,\
18           colorb=None,\
19           winds=True):
20
21    #################################
22    ### Load librairies and functions
23    from netCDF4 import Dataset
24    from myplot import getcoord2d,define_proj,makeplotpng,simplinterv,vectorfield,ptitle,latinterv,getproj,wrfinterv,dumpbdy
25    from matplotlib.pyplot import contourf, subplot, figure, rcParams, savefig, colorbar
26    import numpy as np
27
28    ######################
29    ### Load NETCDF object
30    nc  = Dataset(namefile)
31
32    ###################################
33    ### Recognize predefined file types
34    if 'controle' in nc.variables:   typefile = 'gcm'
35    elif 'vert' in nc.variables:     typefile = 'mesoapi'
36    elif 'U' in nc.variables:        typefile = 'meso'
37    else:                           
38        print "typefile not supported."
39        print nc.variables
40        exit()
41
42    ##############################################################
43    ### Try to guess the projection from wrfout if not set by user
44    if typefile in ['mesoapi','meso']:
45        if proj == None:       proj = getproj(nc)
46                                    ### (il faudrait passer CEN_LON dans la projection ?)
47    elif typefile in ['gcm']:
48        if proj == None:       proj = "cyl"   
49                                    ## pb avec les autres (de trace derriere la sphere ?)
50
51    ############################################
52    #### Choose underlying topography by default
53    if not back:
54        if not var:                                        back = "mola"    ## if no var:         draw mola
55        elif typefile in ['mesoapi','meso'] \
56             and proj not in ['merc','lcc']:               back = "molabw"  ## if var but meso:   draw molabw
57        else:                                              pass             ## else:              draw None
58
59    ####################################################
60    ### Get geographical coordinates and plot boundaries
61    if typefile in ['mesoapi','meso']:
62        [lon2d,lat2d] = getcoord2d(nc)
63        lon2d = dumpbdy(lon2d)
64        lat2d = dumpbdy(lat2d)
65    elif typefile in ['gcm']:
66        [lon2d,lat2d] = getcoord2d(nc,nlat="latitude",nlon="longitude",is1d=True)
67    if proj == "npstere":    [wlon,wlat] = latinterv("North_Pole")
68    elif proj == "lcc":      [wlon,wlat] = wrfinterv(lon2d,lat2d)
69    else:                    [wlon,wlat] = simplinterv(lon2d,lat2d)
70
71    ##################
72    ### Get local time
73    if typefile in ['mesoapi','meso']:  ltst = int(getattr(nc, 'GMT') + 0.5*(wlon[0]+wlon[1])/15.)
74    elif typefile in ['gcm']:           ltst = 0
75
76    ##############################################################################
77    ### Get winds and know if those are meteorological winds (ie. zon, mer) or not
78    if winds:
79        if typefile is 'mesoapi': 
80            [u,v] = getwinds(nc)
81            metwind = True  ## meteorological (zon/mer)
82        elif typefile is 'gcm':
83            [u,v] = getwinds(nc,charu='u',charv='v')
84            metwind = True  ## meteorological (zon/mer)
85        elif typefile is 'meso':
86            [u,v] = getwinds(nc,charu='U',charv='V')
87            metwind = False ## geometrical (wrt grid)
88            print "Beware ! Not using meteorological winds. You trust numerical grid as being (x,y)."
89
90    #####################################################
91    ### Load the chosen variables, whether it is 2D or 3D
92    if var:
93        if var not in nc.variables: 
94            print "not found in file:",var
95            exit()
96        else:   
97            dimension = np.array(nc.variables[var]).ndim
98            if dimension == 2:     field = nc.variables[var][:,:]
99            elif dimension == 3:   field = nc.variables[var][:,:,:]
100            elif dimension == 4:   field = nc.variables[var][:,nvert,:,:] 
101
102    ###########################
103    ### Get length of time axis
104    if winds:               nt = len(u[:,0,0,0])
105    elif var: 
106        if dimension == 2:  nt = 1
107        else             :  nt = len(field[:,0,0])
108
109    #########################################
110    ### Name for title and graphics save file
111    if winds:   basename = "WINDS_"
112    else:       basename = ""
113    if var:
114        basename = basename + var
115    if   typefile is 'meso':                    stralt = "_lvl" + str(nvert)
116    elif typefile is 'mesoapi': 
117        zelevel = int(nc.variables['vert'][nvert])
118        if 'altitude_abg'   in nc.dimensions:   stralt = "_"+str(zelevel)+"m-ALS"
119        elif 'bottom_top'   in nc.dimensions:   stralt = "_"+str(zelevel)+"m-AMR"
120        elif 'pressure'     in nc.dimensions:   stralt = "_"+str(zelevel)+"Pa" 
121    else:                                       stralt = ""         
122    basename = basename + stralt
123
124    ##################################
125    ### Open a figure and set subplots
126    fig = figure()
127    if   numplot > 0:   
128        if   numplot == 4: 
129            sub = 221
130            fig.subplots_adjust(wspace = 0.1, hspace = 0.3)
131            rcParams['font.size'] = int( rcParams['font.size'] * 2. / 3. )
132        elif numplot == 2: 
133            sub = 121
134            fig.subplots_adjust(wspace = 0.3)
135            rcParams['font.size'] = int( rcParams['font.size'] * 3. / 4. )
136        elif numplot == 3: 
137            sub = 131
138            fig.subplots_adjust(wspace = 0.3)
139            rcParams['font.size'] = int( rcParams['font.size'] * 2. / 3. )
140        elif numplot == 6: 
141            sub = 231
142            fig.subplots_adjust(wspace = 0.4, hspace = 0.0)
143            rcParams['font.size'] = int( rcParams['font.size'] * 2. / 3. )
144        elif numplot == 8: 
145            sub = 331 #241
146            fig.subplots_adjust(wspace = 0.1, hspace = 0.3)
147            rcParams['font.size'] = int( rcParams['font.size'] * 1. / 2. )
148        elif numplot == 9:
149            sub = 331 
150            fig.subplots_adjust(wspace = 0.1, hspace = 0.3)
151            rcParams['font.size'] = int( rcParams['font.size'] * 1. / 2. )
152        elif numplot == 1:
153            sub = 99999
154        else:
155            print "supported: 1,2,3,4,6,8"
156            exit()
157        ### Prepare time loop
158        if nt <= numplot or numplot == 1: 
159            tabrange = [0]
160            numplot = 1
161        else:                         
162            tabrange = range(0,nt,int(nt/numplot))  #nt-1
163            tabrange = tabrange[0:numplot]
164    else: 
165        tabrange = range(0,nt,1)
166        sub = 99999
167    print tabrange
168
169    #################################
170    ### Time loop for plotting device
171    found_lct = False
172    for i in tabrange:
173
174       ### General plot settings
175       if numplot > 1: 
176           subplot(sub)
177           found_lct = True
178       elif numplot == 1:
179           found_lct = True 
180            ### If only one local time is requested (numplot < 0)
181       elif numplot <= 0: 
182           if (ltst+i)%24 + numplot != 0:   continue
183           else:                            found_lct = True
184
185       ### Map projection
186       m = define_proj(proj,wlon,wlat,back=back)
187       x, y = m(lon2d, lat2d)
188
189       #### Contour plot
190       if var:
191           if typefile in ['mesoapi','meso']:    what_I_plot = dumpbdy(field[i,:,:])
192           elif typefile in ['gcm']:             
193               if dimension == 2:                what_I_plot = field[:,:]
194               elif dimension == 3:              what_I_plot = field[i,:,:]
195           contourf(x, y, what_I_plot, 30)
196           if colorb:     colorbar(fraction=0.05,pad=0.1)
197
198       ### Vector plot
199       if winds:
200           if   typefile in ['mesoapi','meso']:   
201               [vecx,vecy] = [dumpbdy(u[i,nvert,:,:]), dumpbdy(v[i,nvert,:,:])]
202               key = True
203           elif typefile in ['gcm']:               
204               [vecx,vecy] = [        u[i,nvert,:,:] ,         v[i,nvert,:,:] ]
205               key = False
206           if metwind:  [vecx,vecy] = m.rotate_vector(vecx, vecy, lon2d, lat2d)
207           if var == None and back == "vishires":  colorvec = 'w'
208           else:                                   colorvec = 'k'
209           vectorfield(vecx, vecy,\
210                      x, y, stride=stride, csmooth=stride,\
211                      scale=15., factor=300., color=colorvec, key=key)
212                                        #200.         ## or csmooth=2
213       
214       ### Next subplot
215       ptitle( basename + "_LT"+str((ltst+i)%24) )
216       sub += 1
217
218    ##########################################################################
219    ### Save the figure in a file in the data folder or an user-defined folder
220    if not target:    zeplot = namefile+"_"+basename
221    else:             zeplot = target+"/"+basename
222    if numplot <= 0:  zeplot = zeplot + "_LT"+str(abs(numplot))
223    if found_lct:     makeplotpng(zeplot,pad_inches_value=0.35)   
224    else:             print "Local time not found"
225
226
227
228####################################################
229####################################################
230### A simple program to get wind vectors' components
231def getwinds (nc,charu='Um',charv='Vm'):
232    import numpy as np
233    u = nc.variables[charu]
234    v = nc.variables[charv]
235    if charu == 'U': u = u[:, :, :, 0:len(u[0,0,0,:])-1]
236    if charv == 'V': v = v[:, :, 0:len(v[0,0,:,0])-1, :]
237                     ### ou alors prendre les coordonnees speciales
238    return u,v
239
240
241
242###########################################################################################
243###########################################################################################
244### What is below relate to running the file as a command line executable (very convenient)
245if __name__ == "__main__":
246    import sys
247    from optparse import OptionParser    ### to be replaced by argparse
248    from api_wrapper import api_onelevel
249    parser = OptionParser()
250    parser.add_option('-f', action='store', dest='namefile',    type="string",  default=None,  help='[NEEDED] name of WRF file')
251    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)')
252    parser.add_option('-p', action='store', dest='proj',        type="string",  default=None,  help='projection')
253    parser.add_option('-b', action='store', dest='back',        type="string",  default=None,  help='background')
254    parser.add_option('-t', action='store', dest='target',      type="string",  default=None,  help='destination folder')
255    parser.add_option('-s', action='store', dest='stride',      type="int",     default=3,     help='stride vectors (def=3)')
256    parser.add_option('-v', action='store', dest='var',         type="string",  default=None,  help='variable contoured')
257    parser.add_option('-n', action='store', dest='numplot',     type="int",     default=4,     help='number of plots (def=1)(<0: 1 plot of LT -*numplot*)')
258    parser.add_option('-i', action='store', dest='interp',      type="int",     default=None,  help='interpolation method (2: press, 3: z-amr, 4:z-als)')
259    parser.add_option('-c', action='store', dest='colorb',      type="string",  default=None,  help='colorbar')
260    parser.add_option('-x', action='store_false', dest='winds',                 default=True,  help='flag: no wind vectors')
261    (opt,args) = parser.parse_args()
262    if opt.namefile is None: 
263        print "I want to eat one file at least ! Use winds.py -f name_of_my_file. Or type winds.py -h"
264        exit()
265    print "Options:", opt
266
267    zefile = opt.namefile   
268    zelevel = opt.nvert   
269    stralt = None
270    if opt.interp is not None:
271        if opt.nvert is 0 and opt.interp is 4:  zelevel = 0.010
272        ### winds or no winds
273        if opt.winds            :  zefields = 'uvmet'
274        else                    :  zefields = ''
275        ### var or no var
276        if opt.var is None      :  pass
277        elif zefields == ''     :  zefields = opt.var
278        else                    :  zefields = zefields + "," + opt.var
279        print zefields
280        zefile = api_onelevel (  path_to_input   = '', \
281                                 input_name      = zefile, \
282                                 path_to_output  = opt.target, \
283                                 fields          = zefields, \
284                                 interp_method   = opt.interp, \
285                                 onelevel        = zelevel )
286        zelevel = 0 ## so that zelevel could play again the role of nvert
287
288    winds (zefile,int(zelevel),\
289           proj=opt.proj,back=opt.back,target=opt.target,stride=opt.stride,var=opt.var,numplot=opt.numplot,colorb=opt.colorb,winds=opt.winds)
Note: See TracBrowser for help on using the repository browser.