source: lmdz_wrf/trunk/tools/drawing.py @ 773

Last change on this file since 773 was 773, checked in by lfita, 9 years ago

Adding draw_vertical_levels' and plot_vertical_lev', plotting vertical levels distribution

File size: 146.4 KB
Line 
1import numpy as np
2import os
3from netCDF4 import Dataset as NetCDFFile
4import drawing_tools as drw
5import generic_tools as gen
6from optparse import OptionParser
7import sys
8from cStringIO import StringIO
9
10## e.g. # drawing.py -f /media/data2/etudes/WRF_LMDZ/WL_HyMeX/IIphase/medic950116/wlmdza/wrfout/wrfout_d01_1995-01-13_00:00:00 -o create_movie -S 'draw_2D_shad#Time@WRFTimes@10@95@191@1#tas:East_West|-1,North_South|-1,Time|2:longitude:latitude:Summer:270.,300.:tas|at|t=0:pdf:None:None' -v T2
11## e.g. # drawing.py -f wrfout_d01_1980-03-01_00\:00\:00_Time_B0-E48-I1.nc -o draw_2D_shad -S 'tas:East_West|-1,North_South|-1,Time|2:longitude:latitude:Summer:270.,300.:tas|at|t=0:pdf:None:cyl,i' -v T2
12## e.g. # drawing.py -f ~/etudes/domains/MEDCORDEX/geo_em.d01.nc -o draw_2D_shad_cont -S 'landmask,height:Time|0:Time|0:XLONG_M:XLAT_M:rainbow:fixc,k:%.2f:0,1:0.,3000.,10:landmask & height:pdf:False:lcc,i' -v LANDMASK,HGT_M
13## e.g. # drawing.py -f ~/etudes/domains/MEDCORDEX/geo_em.d01.nc -o draw_2D_shad_cont -S 'height,landmask:Time|0:Time|0:XLONG_M:XLAT_M:terrain:fixc,k:None:0.,3000.:0,1,10:MEDCORDEX height & landmask:pdf:False:lcc,i' -v HGT_M,LANDMASK
14## e.g. # drawing.py -o draw_2D_shad_line -f 'mean_dtcon-pluc-pres_lat.nc,mean_dtcon-pluc-pres_lat.nc' -S 'dtcon,prc:bottom_top|-1,south_north|-1:latmean:presmean:seismic,k:-5.,5.:monthly|dtcon|&|prc:pdf:flip@y:None:True' -v 'dtconmean,prcmean'
15## e.g. # drawing.py -f 'geo_em.d02.nc' -o draw_topo_geogrid -S '0.,3000.:None:FF_3dom d02:png:cyl,i'
16## e.g. # drawing.py -o draw_topo_geogrid_boxes -S '0.,3000.:None:FF domains:pdf:lcc,i:d01,d02,d03:0' -f geo_em.d01.nc,geo_em.d02.nc,geo_em.d03.nc
17## e.g. # drawing.py -o draw_trajectories -f 'WRF/control/trajectory.dat@-1@/home/lluis/etudes/domains/WL_HyMeX_HighRes_C/geo_em.d03.nc#XLONG_M#XLAT_M,WRF_LMDZ/wlmdza/trajectory.dat@-1@/home/lluis/etudes/domains/WL_HyMeX_C/geo_em.d01.nc#XLONG_M#XLAT_M,WRF_LMDZ/wlmdzb/trajectory.dat@-1@/home/lluis/etudes/domains/WL_HyMeX_C/geo_em.d01.nc#XLONG_M#XLAT_M,WRF_LMDZ/wlmdzb_ii/trajectory.dat@-1@/home/lluis/etudes/domains/WL_HyMeX_C/geo_em.d01.nc#XLONG_M#XLAT_M' -S '$WRF_{CRM}$,$LMDZ_{AR4.0}$,$LMDZ_{NPv3.1}$,$LMDZ_{NPv3.1b}$|None|medicane trajectories|pdf|cyl,i' -v obs/trajectory.dat,satellite,-1
18## e.g. # drawing.py -o draw_vals_trajectories -f WRF_LMDZ/wlmdza/tevolboxtraj_T2.nc,WRF_LMDZ/wlmdzb/tevolboxtraj_T2.nc,WRF/control/tevolboxtraj_T2.nc -S 'mean:-1:$WRF_{CRM}$,$LMDZ_{AR4.0}$,$LMDZ_{NPv3.1}$@4:tas:time|($[DD]^[HH]$):exct,6,h:$%d^{%H}$:trajectory|following|mean:pdf' -v T2
19## e.g. # drawing.py -o draw_2D_shad_time -f 'netcdf_concatenated.nc' -S 'dtcon:Time|-1,bottom_top|-1:presmean:time:seismic:-3.e-6,3.e-6:monthly|dtcon:pdf:transpose:time|hours!since!1949-12-01|exct,2,d|%d|date!([DD])|x:True' -v 'dtconmean'
20## e.g. # drawing.py -o variable_values -S PSFC
21## e.g. # drawing.py -o draw_timeSeries -f wrfout_d01_1979-12-01_00:00:00_bottom_top_B6-E6-I1_south_north_B3-E3-I1_west_east_B26-E26-I1.nc -S 'dt_con:time|($[DD]^{[HH]}$):exct,12,h:$%d^{%H}$:time|evolution|at|-1|6|3|26:1:pdf' -v 'LDQCON,time'
22## e.g. # drawing.py -f wrfout_d01_1979-12-01_00:00:00 -o draw_Neighbourghood_evol -S 'q:Time|-1|Times,bottom_top|6|ZNU,south_north|3|XLAT,west_east|26|XLONG:south_north,west_east:5:auto:time|($[DD]^{[HH]}$),time|($[DD]^{[HH]}$):exct,2,h|exct,1,d:$%d^{%H}$,$%d^{%H}$:5|pts|neighbourghood|temporal|evolution:0.0,0.004:BuPu:pdf:True' -v QVAPOR
23## e.g. # drawing.py -o draw_lines_time -f wrfout_d01_1980-03-01_00:00:00_Time_B0-E48-I1_south_north_B15-E15-I1_west_east_B15-E15-I1.nc -S 'time;y;time ([DD]${[HH]}$);file1;tas;evolution;time|hours!since!1949-12-01_00:00:00|exct,12,h|%d$^{%H}$;pdf' -v T2
24## e.g. # drawing.py -o draw_barbs -f ERAI_pl199501_131-132.nc -S 'X|lon|lon|-1,Y|lat|lat|-1,Z|lev|lev|4,T|time|time|0:auto,auto,auto:wind,ms-1:cyl,c:ERA-Interim|winds|at|1000|hPa|on|1996|January|1st|at|00|UTC:pdf:ERAI_pl199501_131-132' -v var131,var132
25## e.g. # ~/etudes/WRF_LMDZ/svn/LMDZ_WRF/tools/drawing.py -o draw_points -S 'tslist.dat,#,3,2,1:SuperStorm|sfc|stations:cyl,i:legend:auto:None:0:png:stations_loc' -f $HOME'/etudes/domains/WRFdynamicoSENS_SuperStorm/geo_em.d02.nc,XLONG_M,XLAT_M,HGT_M,Time|0,height,0.,3000.,terrain,m'
26## e.g. # drawing.py -o draw_points -S 'tslist.dat,#,3,2,1:SuperStorm|sfc|stations:cyl,i:labelled,8,black:auto:None:0:png:stations_loc' -f $HOME'/etudes/domains/WRFdynamicoSENS_SuperStorm/geo_em_west_east_B25-E180-I1_south_north_B160-E262-I1.nc,XLONG_M,XLAT_M,HGT_M,Time|0,height,0.,1500.,terrain,m'
27## e.g. # drawing.py -o draw_ptZvals -f geo_v2_2012102123_RR1.nc -S 'pracc:lon,lat:o:80:2,42,7,47,:values!of!values:Blues:cyl,l:pdf' -v pr
28## e.g. # drawing.py -f carteveg5km.nc -o draw_points_lonlat -S 'longitude:latitude:pdf:points!veget|type:green:.:0.5:None:0:legend'
29## e.g. # drawing.py -o draw_vectors -f wrfout_d01_2001-11-11_00:00:00 -S 'T|Time|Times|2,Y|south_north|XLAT|-1,X|west_east|XLONG|-1:3@3,wind@rainbow,9:10m wind,ms-1:cyl,l:WRF 10 m winds:pdf:winds' -v U10,V10
30## e.g. # drawing.py -o draw_basins -f routing.py -S 'Y|y|nav_lat|-1,X|x|nav_lon|-1:1@1,rainbow,9:basins,-:cyl,l:ORCDHIEE river-basins:pdf:basins_named' -v nav_lon,nav_lat,trip,basins
31## e.g. # drawing.py -o draw_river_desc -f diver_desc.nc -S 'Y|lat|lat|-1,X|lon|lon|-1:red,green:Blues:cyl,l:ORCDHIEE rivers:pdf:0:or_rivers -v Amazon
32
33main = 'drawing.py'
34
35errormsg = 'ERROR -- error -- ERROR -- error'
36warnmsg = 'WARNING -- waring -- WARNING -- warning'
37fillValue=1.e20
38
39namegraphics = ['create_movie', 'draw_2D_shad', 'draw_2D_shad_time',                 \
40  'draw_2D_shad_cont', 'draw_2D_shad_cont_time', 'draw_2D_shad_line',                \
41  'draw_2D_shad_line_time', 'draw_barbs', 'draw_basins',                             \
42  'draw_lines', 'draw_lines_time', 'draw_Neighbourghood_evol',                       \
43  'draw_points', 'draw_points_lonlat',                                               \
44  'draw_ptZvals', 'draw_river_desc', 'draw_timeSeries',                              \
45  'draw_topo_geogrid',                                                               \
46  'draw_topo_geogrid_boxes', 'draw_trajectories', 'draw_vals_trajectories',          \
47  'draw_vectors',  'draw_vertical_levels', 'list_graphics', 'variable_values']
48
49def draw_2D_shad(ncfile, values, varn):
50    """ plotting a fields with shading
51    draw_2D_shad(ncfile, values, varn)
52      ncfile= file to use
53      values=[vnamefs]:[dimvals]:[dimxvn]:[dimyvn]:[colorbar]:[sminv],[smaxv]:[figt]:
54       [kindfig]:[reverse]:[mapv]:[close]
55        [vnamefs]: Name in the figure of the variable to be shaded
56        [dimvals]: ',' list of [dimname]|[value] telling at which dimension of the
57          variable a given value is required (-1, all the length)
58        [dimx/yvn]: name of the variables with the values of the final dimensions (x,y)
59        [colorbar]: name of the color bar
60        [smin/axv]: minimum and maximum value for the shading or:
61          'Srange': for full range
62          'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean)
63          'Saroundminmax@val': for min*val,max*val
64          'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val),
65            percentile_(100-val)-median)
66          'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean)
67          'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median)
68          'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val),
69             percentile_(100-val)-median)
70        [figt]: title of the figure ('|' for spaces)
71        [kindfig]: kind of figure
72        [reverse]: Transformation of the values
73          * 'transpose': reverse the axes (x-->y, y-->x)
74          * 'flip'@[x/y]: flip the axis x or y
75        [mapv]: map characteristics: [proj],[res]
76          see full documentation: http://matplotlib.org/basemap/
77          [proj]: projection
78            * 'cyl', cilindric
79            * 'lcc', lamvbert conformal
80          [res]: resolution:
81            * 'c', crude
82            * 'l', low
83            * 'i', intermediate
84            * 'h', high
85            * 'f', full
86      valules= 'rh:z|-1,x|-1:z|-1,x|-1:lat:pressure:BuPu:0.,100.:rh:pdf:flip@y:None'
87      varn= [varsn] name of the variable to plot with shading
88    """
89
90    fname = 'draw_2D_shad'
91    if values == 'h':
92        print fname + '_____________________________________________________________'
93        print draw_2D_shad.__doc__
94        quit()
95
96    expectargs = '[vnamefs]:[dimvals]:[dimxvn]:[dimyvn]:[colorbar]:[sminv],[smaxv]'+\
97      ':[figt]:[kindfig]:[reverse]:[mapv]:[close]'
98 
99    drw.check_arguments(fname,values,expectargs,':')
100
101    vnamesfig = values.split(':')[0]
102    dimvals= values.split(':')[1].replace('|',':')
103    vdimxn = values.split(':')[2]
104    vdimyn = values.split(':')[3]
105    colbarn = values.split(':')[4]
106    shadminmax = values.split(':')[5]
107    figtitle = values.split(':')[6].replace('|',' ')
108    figkind = values.split(':')[7]
109    revals = values.split(':')[8]
110    mapvalue = values.split(':')[9]
111#    varn = values.split(':')[10]
112
113    ncfiles = ncfile
114   
115    if not os.path.isfile(ncfiles):
116        print errormsg
117        print '  ' + fname + ': shading file "' + ncfiles + '" does not exist !!'
118        quit(-1)   
119
120    objsf = NetCDFFile(ncfiles, 'r')
121   
122    varns = varn.split(',')[0]
123
124    if  not objsf.variables.has_key(varns):
125        print errormsg
126        print '  ' + fname + ': shading file "' + ncfiles +                          \
127          '" does not have variable "' +  varns + '" !!'
128        quit(-1)
129
130# Variables' values
131    objvars = objsf.variables[varns]
132
133    valshad, dimsshad = drw.slice_variable(objvars, dimvals.replace(',','|'))
134
135# Dimensions names
136##    print fname + ' obj dimnames: ', objvars.dimensions, dimvals, len(dimvals.split(','))
137##    dimnamesv = []
138##    for idd in range(len(objvars.dimensions)):
139##        cutdim = False
140##        for idc in range(len(dimvals.split(','))):
141##            dimcutn = dimvals.split(',')[idc].split(':')[0]
142##            print objvars.dimensions[idd], dimcutn
143##            if objvars.dimensions[idd] == dimcutn:
144##                cutdim = True
145##                break
146##        if not cutdim: dimnamesv.append(objvars.dimensions[idd])
147    dimnamesv = [vdimyn, vdimxn]
148
149    if drw.searchInlist(objvars.ncattrs(),'units'):
150        varunits = objvars.getncattr('units')
151    else:
152        print warnmsg
153        print '  ' + fname + ": variable '" + varn + "' without units!!"
154        varunits = '-'
155
156    if  not objsf.variables.has_key(vdimxn):
157        print errormsg
158        print '  ' + fname + ': shading file "' + ncfiles +                          \
159          '" does not have dimension variable "' +  vdimxn + '" !!'
160        quit(-1)
161    if  not objsf.variables.has_key(vdimyn):
162        print errormsg
163        print '  ' + fname + ': shading file "' + ncfiles +                          \
164          '" does not have dimension variable "' +  vdimyn + '" !!'
165        quit(-1)
166
167    objdimx = objsf.variables[vdimxn]
168    objdimy = objsf.variables[vdimyn]
169    if drw.searchInlist(objdimx.ncattrs(),'units'):
170        odimxu = objdimx.getncattr('units')
171    else:
172        print warnmsg
173        print '  ' + fname + ": variable dimension '" + vdimxn + "' without units!!"
174        odimxu = '-'
175
176    if drw.searchInlist(objdimy.ncattrs(),'units'):
177        odimyu = objdimy.getncattr('units')
178    else:
179        print warnmsg
180        print '  ' + fname + ": variable dimension '" + vdimyn + "' without units!!"
181        odimyu = '-'
182
183    odimxv, odimyv = drw.dxdy_lonlatDIMS(objdimx[:], objdimy[:], objdimx.dimensions,     \
184      objdimy.dimensions, dimvals.replace(':','|').split(','))
185
186
187#    if len(objdimx.shape) <= 2:
188##        odimxv = objdimx[valshad.shape]
189##        odimyv = objdimy[valshad.shape]
190#        odimxv = objdimx[:]
191#        odimyv = objdimy[:]
192
193#    elif len(objdimx.shape) == 3:
194##        dimcut = [0, slice(0,valshad.shape[0]), slice(0,valshad.shape[1])]
195##        odimxv = objdimx[tuple(dimcut)]
196##        odimyv = objdimy[tuple(dimcut)]
197#        odimxv = objdimx[0,:]
198#        odimyv = objdimy[0,:]
199#    else:
200#        print errormsg
201#        print '  ' + fname + ': shape of dimension variable:', objdimx.shape,        \
202#          ' not ready!!'
203#        quit(-1)
204
205    shading_nx = []
206    if shadminmax.split(',')[0][0:1] != 'S':
207            shading_nx.append(np.float(shadminmax.split(',')[0]))
208    else:
209        shading_nx.append(shadminmax.split(',')[0])
210
211    if shadminmax.split(',')[1][0:1] != 'S':
212        shading_nx.append(np.float(shadminmax.split(',')[1]))
213    else:
214        shading_nx.append(shadminmax.split(',')[1])
215
216    if mapvalue == 'None': mapvalue = None
217
218    drw.plot_2D_shadow(valshad, vnamesfig, odimxv, odimyv, odimxu, odimyu, dimnamesv,\
219      colbarn, shading_nx, varunits, figtitle, figkind, revals, mapvalue, True)
220
221    return
222
223def draw_2D_shad_time(ncfile, values, varn):
224    """ plotting a fields with shading with time values
225    draw_2D_shad(ncfile, values, varn)
226      ncfile= file to use
227      values=[vnamefs]~[dimvals]~[dimxvn]~[dimyvn]~[colorbar]~[sminv],[smaxv]~[figt]~
228       [kindfig]~[reverse]~[timevals]~[close]
229        [vnamefs]: Name in the figure of the variable to be shaded
230        [dimvals]: ',' list of [dimname]|[value] telling at which dimension of the
231          variable a given value is required (-1, all the length, [beg]@[end] for an interval)
232        [dimx/yvn]: name of the variables with the values of the final dimensions (x,y)
233        [colorbar]: name of the color bar
234        [smin/axv]: minimum and maximum value for the shading or:
235          'Srange': for full range
236          'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean)
237          'Saroundminmax@val': for min*val,max*val
238          'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val),
239            percentile_(100-val)-median)
240          'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean)
241          'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median)
242          'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val),
243             percentile_(100-val)-median)
244        [figt]: title of the figure ('|' for spaces)
245        [kindfig]: kind of figure
246        [reverse]: Transformation of the values
247          * 'transpose': reverse the axes (x-->y, y-->x)
248          * 'flip'@[x/y]: flip the axis x or y
249        [timevals]: [timen]|[units]|[kind]|[tfmt]|[label]|[timeaxis] time labels characteristics
250           [timen]; name of the time variable
251           [units]; units string according to CF conventions ([tunits] since
252             [YYYY]-[MM]-[DD] [[HH]:[MI]:[SS]], '!' for spaces)
253           [kind]; kind of output
254             'Nval': according to a given number of values as 'Nval',[Nval]
255             'exct': according to an exact time unit as 'exct',[tunit];
256               tunit= [Nunits],[tu]; [tu]= 'c': centuries, 'y': year, 'm': month,
257                'w': week, 'd': day, 'h': hour, 'i': minute, 's': second,
258                'l': milisecond
259           [tfmt]; desired format
260           [label]; label at the graph ('!' for spaces)
261        [close]: should figure be closed (finished)
262      values='dtcon~Time|-1,bottom_top|-1~presmean~time~seismic~-3.e-6,3.e-6~monthly|'
263        'dtcon~pdf~transpose~time|hours!since!1949-12-01|exct,2,d|%d|date!([DD])~True
264      varn= [varsn] name of the variable to plot with shading
265    """
266    fname = 'draw_2D_shad_time'
267
268    if values == 'h':
269        print fname + '_____________________________________________________________'
270        print draw_2D_shad_time.__doc__
271        quit()
272
273    farguments = '[vnamefs]~[dimvals]~[dimxvn]~[dimyvn]~[colorbar]~[sminv],[smaxv]~'+\
274      '[figt]~[kindfig]~[reverse]~[timevals]~[close]'
275    drw.check_arguments(fname,values,farguments,'~')
276
277    vnamesfig = values.split('~')[0]
278    dimvals= values.split('~')[1].replace('|',':')
279    vdimxn = values.split('~')[2]
280    vdimyn = values.split('~')[3]
281    colbarn = values.split('~')[4]
282    shadminmax = values.split('~')[5]
283    figtitle = values.split('~')[6].replace('|',' ')
284    figkind = values.split('~')[7]
285    revals = values.split('~')[8]
286    timevals = values.split('~')[9]
287    close = values.split('~')[10]
288
289    ncfiles = ncfile
290   
291    if not os.path.isfile(ncfiles):
292        print errormsg
293        print '  ' + fname + ': shading file "' + ncfiles + '" does not exist !!'
294        quit(-1)   
295
296    objsf = NetCDFFile(ncfiles, 'r')
297   
298    varns = varn.split(',')[0]
299
300    if  not objsf.variables.has_key(varns):
301        print errormsg
302        print '  ' + fname + ': shading file "' + ncfiles +                          \
303          '" does not have variable "' +  varns + '" !!'
304        quit(-1)
305
306# Variables' values
307    objvars = objsf.variables[varns]
308
309    valshad, dimsshad = drw.slice_variable(objvars, dimvals.replace(',','|'))
310
311    dimnamesv = [vdimyn, vdimxn]
312
313    varunits = objvars.getncattr('units')
314
315    if  not objsf.variables.has_key(vdimxn):
316        print errormsg
317        print '  ' + fname + ': shading file "' + ncfiles +                          \
318          '" does not have dimension variable "' +  vdimxn + '" !!'
319        quit(-1)
320    if  not objsf.variables.has_key(vdimyn):
321        print errormsg
322        print '  ' + fname + ': shading file "' + ncfiles +                          \
323          '" does not have dimensino variable "' +  vdimyn + '" !!'
324        quit(-1)
325
326    objdimx = objsf.variables[vdimxn]
327    objdimy = objsf.variables[vdimyn]
328    odimxu = objdimx.getncattr('units')
329    odimyu = objdimy.getncattr('units')
330
331    if len(objdimx.shape) <= 2:
332        odimxv0 = objdimx[:]
333        odimyv0 = objdimy[:]
334
335    elif len(objdimx.shape) == 3:
336        odimxv0 = objdimx[0,:]
337        odimyv0 = objdimy[0,:]
338    else:
339        print errormsg
340        print '  ' + fname + ': shape of dimension variable:', objdimx.shape,        \
341          ' not ready!!'
342        quit(-1)
343
344    timename = timevals.split('|')[0]
345    timeunit = timevals.split('|')[1].replace('!',' ')
346    timekind = timevals.split('|')[2]
347    timefmt = timevals.split('|')[3]
348    timelabel = timevals.split('|')[4].replace('!',' ')
349
350# Dimensional values
351    odxv, dimsdxv = drw.slice_variable(objsf.variables[vdimxn], dimvals.replace(',','|'))
352    odyv, dimsdyv = drw.slice_variable(objsf.variables[vdimyn], dimvals.replace(',','|'))
353
354    if vdimxn == timename:
355        odimxv = objsf.variables[vdimxn][:]
356        odimxu = timelabel
357        timeaxis = 'x'
358        odimyv = objsf.variables[vdimyn]
359        odimyu = odimyv.getncattr('units')
360        timepos, timelabels = drw.CFtimes_plot(odxv, timeunit, timekind, timefmt)
361    elif vdimyn == timename:
362        odimyv = objsf.variables[vdimyn]
363        odimyu = timelabel
364        timeaxis = 'y'
365        odimxv = objsf.variables[vdimxn]
366        odimxu = odimxv.getncattr('units')
367        timepos, timelabels = drw.CFtimes_plot(odyv, timeunit, timekind, timefmt)
368    else:
369        print errormsg
370        print '  ' + fname + ": time variable '" + timename + "' not found!!"
371        quit(-1)
372
373    shading_nx = []
374    if shadminmax.split(',')[0][0:1] != 'S':
375        shading_nx.append(np.float(shadminmax.split(',')[0]))
376    else:
377        shading_nx.append(shadminmax.split(',')[0])
378
379    if shadminmax.split(',')[1][0:1] != 'S':
380        shading_nx.append(np.float(shadminmax.split(',')[1]))
381    else:
382        shading_nx.append(shadminmax.split(',')[1])
383
384    closeval = drw.Str_Bool(close)
385
386    drw.plot_2D_shadow_time(valshad, vnamesfig, odxv, odyv, odimxu, odimyu,          \
387      dimnamesv, colbarn, shading_nx, varunits, figtitle, figkind, revals, timeaxis, \
388      timepos, timelabels, closeval)
389
390    return
391
392def draw_2D_shad_cont(ncfile, values, varn):
393    """ plotting two fields, one with shading and the other with contour lines
394    draw_2D_shad_cont(ncfile, values, varn)
395      ncfile= [ncfilevars],[ncfilevarc] files to use (one value, same file)
396      values=[vnamefs]:[dimvals]:[dimvalc]:[dimxvn]:[dimyvn]:[colorbar]:[ckind]:[clabfmt]:[sminv],[smaxv]:[sminc],[smaxv],[Nlev]:[figt]:[kindfig]:[reverse]:[mapv]
397        [vnamefs],[vnamefc]: Name in the figure of the shaded and the contour variables
398        [dimvals/c]: list of [dimname]|[value] telling at which dimension of the
399          variable a given value is required (no dimension name, all the length)
400        [dimx/yvn]: names of the variables with the values of the dimensions for the plot
401        [colorbar]: name of the color bar
402        [ckind]: kind of contours
403          'cmap': as it gets from colorbar
404          'fixc,[colname]': fixed color [colname], all stright lines
405          'fixsigc,[colname]': fixed color [colname], >0 stright, <0 dashed  line
406        [clabfmt]: format of the labels in the contour (None, also possible)
407        [smin/axv]: minimum and maximum value for the shading
408        [sminc]:[smaxv]:[Nlev]: minimum, maximum and number of values for the contour
409        [figt]: title of the figure ('|' for spaces)
410        [kindfig]: kind of figure
411        [reverse]: does the values be transposed? 'True/False',
412        [mapv]: map characteristics: [proj],[res]
413          see full documentation: http://matplotlib.org/basemap/
414          [proj]: projection
415            * 'cyl', cilindric
416            * 'lcc', lamvbert conformal
417          [res]: resolution:
418            * 'c', crude
419            * 'l', low
420            * 'i', intermediate
421            * 'h', high
422            * 'f', full
423      valules= 'rh,ta:z|-1,x|-1:z|-1,x|-1:lat:pressure:BuPu:fixsigc,black:%d:0.,100.:195.,305.,7:Meridonal|average|of|rh|&|ta:pdf:flip@y:None'
424      varn= [varsn],[varcn] name of the variable to plot with shading variable with contour
425    """
426
427    fname = 'draw_2D_shad_cont'
428    if values == 'h':
429        print fname + '_____________________________________________________________'
430        print draw_2D_shad_cont.__doc__
431        quit()
432
433    expectargs = '[vnamefs]:[dimvals]:[dimvalc]:[dimxvn]:[dimyvn]:[colorbar]:'
434    expectargs = expectargs + '[ckind]:[clabfmt]:[sminv],[smaxv]:[sminc],[smaxv],'
435    expectargs = expectargs + '[Nlev]:[figt]:[kindfig]:[reverse]:[mapv]'
436 
437    drw.check_arguments(fname,values,expectargs,':')
438
439    vnamesfig = values.split(':')[0].split(',')
440    dimvals= values.split(':')[1].replace('|',':')
441    dimvalc= values.split(':')[2].replace('|',':')
442    vdimxn = values.split(':')[3]
443    vdimyn = values.split(':')[4]
444    colbarn = values.split(':')[5]
445    countkind = values.split(':')[6]
446    countlabelfmt = values.split(':')[7]
447    shadminmax = values.split(':')[8]
448    contlevels = values.split(':')[9]
449    figtitle = values.split(':')[10].replace('|',' ')
450    figkind = values.split(':')[11]
451    revals = values.split(':')[12]
452    mapvalue = values.split(':')[13]
453
454    if2filenames = ncfile.find(',')
455
456    if if2filenames != -1:
457        ncfiles = ncfile.split(',')[0]
458        ncfilec = ncfile.split(',')[1]
459    else:
460        ncfiles = ncfile
461        ncfilec = ncfile
462
463    if not os.path.isfile(ncfiles):
464        print errormsg
465        print '  ' + fname + ': shading file "' + ncfiles + '" does not exist !!'
466        quit(-1)   
467
468    if not os.path.isfile(ncfilec):
469        print errormsg
470        print '  ' + fname + ': contour file "' + ncfilec + '" does not exist !!'
471        quit(-1)   
472
473    objsf = NetCDFFile(ncfiles, 'r')
474    objcf = NetCDFFile(ncfilec, 'r')
475   
476    varns = varn.split(',')[0]
477    varnc = varn.split(',')[1]
478
479    if  not objsf.variables.has_key(varns):
480        print errormsg
481        print '  ' + fname + ': shading file "' + ncfiles +                          \
482          '" does not have variable "' +  varns + '" !!'
483        quit(-1)
484
485    if  not objcf.variables.has_key(varnc):
486        print errormsg
487        print '  ' + fname + ': contour file "' + ncfilec +                          \
488          '" does not have variable "' +  varnc + '" !!'
489        quit(-1)
490
491# Variables' values
492    objvars = objsf.variables[varns]
493    objvarc = objcf.variables[varnc]
494
495    if len(objvars.shape) != len(objvarc.shape):
496        print errormsg
497        print '  ' + fname + ': shading variable "' + varns + '" has a shape: ',     \
498          objvars.shape,  'different than contour variable "' +  varnc + '": ',      \
499          objvarc.shape,' !!!'
500        quit(-1)
501
502    for idim in range(len(objvars.shape)):
503        if objvars.shape[idim] != objvarc.shape[idim]:
504            print errormsg
505            print '  ' + fname + ': shading variable "' + varns + '" has a shape: ', \
506              objvars.shape,  'different than contour variable "' +  varnc + '": ',  \
507              objvarc.shape,' !!!'
508            quit(-1)
509
510    valshad, dimsshad = drw.slice_variable(objvars, dimvals.replace(',','|'))
511    valcont, dimscont = drw.slice_variable(objvarc, dimvalc.replace(',','|'))
512
513# Dimensions names
514##    print fname + ' obj dimnames: ', objvars.dimensions, dimvals, len(dimvals.split(','))
515##    dimnamesv = []
516##    for idd in range(len(objvars.dimensions)):
517##        cutdim = False
518##        for idc in range(len(dimvals.split(','))):
519##            dimcutn = dimvals.split(',')[idc].split(':')[0]
520##            print objvars.dimensions[idd], dimcutn
521##            if objvars.dimensions[idd] == dimcutn:
522##                cutdim = True
523##                break
524##        if not cutdim: dimnamesv.append(objvars.dimensions[idd])
525    dimnamesv = [vdimyn, vdimxn]
526
527    varunits = []
528    varunits.append(objvars.getncattr('units'))
529    varunits.append(objvarc.getncattr('units'))
530
531    if  not objsf.variables.has_key(vdimxn):
532        print errormsg
533        print '  ' + fname + ': shading file "' + ncfiles +                          \
534          '" does not have dimension variable "' +  vdimxn + '" !!'
535        quit(-1)
536    if  not objsf.variables.has_key(vdimyn):
537        print errormsg
538        print '  ' + fname + ': shading file "' + ncfiles +                          \
539          '" does not have dimensino variable "' +  vdimyn + '" !!'
540        quit(-1)
541
542    objdimx = objsf.variables[vdimxn]
543    objdimy = objsf.variables[vdimyn]
544    odimxu = objdimx.getncattr('units')
545    odimyu = objdimy.getncattr('units')
546
547# Getting only that dimensions with coincident names
548    odimxv, odimyv = drw.dxdy_lonlatDIMS(objdimx[:], objdimy[:], objdimx.dimensions,     \
549      objdimy.dimensions, dimvals.replace(':','|').split(','))
550
551#    dimnvx = objdimx.dimensions
552#    cutslice = []
553#    for idimn in objdimx.dimensions:
554#        found = False
555#        for dimsn in dimsshad:
556#            if idimn == dimsn:
557#                cutslice.append(slice(0,len(objsf.dimensions[idimn])))
558#                found = True
559#        if not found: cutslice.append(0)
560#
561#    odimxv = objdimx[tuple(cutslice)]
562#
563#    dimnvy = objdimy.dimensions
564#    cutslice = []
565#    for idimn in objdimy.dimensions:
566#        found = False
567#        for dimsn in dimsshad:
568#            if idimn == dimsn:
569#                cutslice.append(slice(0,len(objsf.dimensions[idimn])))
570#                found = True
571#        if not found: cutslice.append(0)
572#
573#    odimyv = objdimy[tuple(cutslice)]
574
575#    if len(objdimx.shape) <= 2:
576#        odimxv = objdimx[:]
577#        odimyv = objdimy[:]
578#    elif len(objdimx.shape) == 3:
579#        odimxv = objdimx[0,:]
580#        odimyv = objdimy[0,:]
581#    else:
582#        print errormsg
583#        print '  ' + fname + ': shape of dimension variable:', objdimx.shape,        \
584#          ' not ready!!'
585#        quit(-1)
586
587    if countlabelfmt == 'None': 
588        countlfmt = None
589    else:
590        countlfmt = countlabelfmt
591
592    shading_nx = np.zeros((2), dtype=np.float)
593    shading_nx[0] = np.float(shadminmax.split(',')[0])
594    shading_nx[1] = np.float(shadminmax.split(',')[1])
595
596    clevmin = np.float(contlevels.split(',')[0])
597    clevmax = np.float(contlevels.split(',')[1])
598    Nclevels = int(contlevels.split(',')[2])
599
600    levels_cont = drw.pretty_int(clevmin, clevmax, Nclevels)
601
602    if len(levels_cont) <= 1: 
603        print warnmsg
604        print '  ' + fname + ': wrong contour levels:', levels_cont,' !!'
605        del(levels_cont)
606        levels_cont = np.zeros((Nclevels), dtype=np.float)
607        levels_cont = np.arange(7)*(clevmax - clevmin)/(Nclevels-1)
608        print '    generating default ones: ',levels_cont
609
610    if mapvalue == 'None': mapvalue = None
611
612    drw.plot_2D_shadow_contour(valshad, valcont, vnamesfig, odimxv, odimyv, odimxu,  \
613      odimyu, dimnamesv, colbarn, countkind, countlfmt, shading_nx, levels_cont,     \
614      varunits, figtitle, figkind, revals, mapvalue)
615
616    return
617
618def draw_2D_shad_cont_time(ncfile, values, varn):
619    """ plotting two fields, one with shading and the other with contour lines being
620    one of the dimensions of time characteristics
621    draw_2D_shad_cont(ncfile, values, varn)
622      ncfile= [ncfilevars],[ncfilevarc] files to use (one value, same file)
623      values=[vnamefs]:[dimvals]:[dimvalc]:[dimxvn]:[dimyvn]:[colorbar]:[ckind]:[clabfmt]:[sminv],[smaxv]:[sminc],[smaxv],[Nlev]:[figt]:[kindfig]:[reverse]:[timevals]:[mapv]
624        [vnamefs],[vnamefc]: Name in the figure of the shaded and the contour variables
625        [dimvals/c]: list of [dimname]|[value] telling at which dimension of the
626          variable a given value is required (no dimension name, all the length)
627        [dimx/yvn]: ',' list with the name of the variables with the values of the dimensions
628        [colorbar]: name of the color bar
629        [ckind]: kind of contours
630          'cmap': as it gets from colorbar
631          'fixc,[colname]': fixed color [colname], all stright lines
632          'fixsigc,[colname]': fixed color [colname], >0 stright, <0 dashed  line
633        [clabfmt]: format of the labels in the contour (None, also possible)
634        [smin/axv]: minimum and maximum value for the shading
635        [sminc]:[smaxv]:[Nlev]: minimum, maximum and number of values for the contour
636        [figt]: title of the figure ('|' for spaces)
637        [kindfig]: kind of figure
638        [reverse]: modification to the dimensions:
639          'transposed': transpose matrices
640          'flip',[x/y]: flip only the dimension [x] or [y]
641        [timevals]: [timen]|[units]|[kind]|[tfmt]|[label] time labels characteristics
642           [timen]; name of the time variable
643           [units]; units string according to CF conventions ([tunits] since
644             [YYYY]-[MM]-[DD] [[HH]:[MI]:[SS]], '!' for spaces)
645           [kind]; kind of output
646             'Nval': according to a given number of values as 'Nval',[Nval]
647             'exct': according to an exact time unit as 'exct',[tunit];
648               tunit= [Nunits],[tu]; [tu]= 'c': centuries, 'y': year, 'm': month,
649                'w': week, 'd': day, 'h': hour, 'i': minute, 's': second,
650                'l': milisecond
651           [tfmt]; desired format
652           [label]; label at the graph ('!' for spaces)
653        [mapv]: map characteristics: [proj],[res]
654          see full documentation: http://matplotlib.org/basemap/
655          [proj]: projection
656            * 'cyl', cilindric
657            * 'lcc', lamvbert conformal
658          [res]: resolution:
659            * 'c', crude
660            * 'l', low
661            * 'i', intermediate
662            * 'h', high
663            * 'f', full
664      valules= 'rh,ta:z|-1,x|-1:z|-1,x|-1:lat:pressure:BuPu:fixsigc,black:%d:0.,100.:195.,305.,7:Meridonal|average|of|rh|&|ta:pdf:flip@y:time!hours!since!1949/12/01|exct,5d|%d|date!([DD]):None'
665      varn= [varsn],[varcn] name of the variable to plot with shading variable with contour
666    """
667
668    fname = 'draw_2D_shad_cont_time'
669    if values == 'h':
670        print fname + '_____________________________________________________________'
671        print draw_2D_shad_cont_time.__doc__
672        quit()
673
674    expectargs = '[vnamefs]:[dimvals]:[dimvalc]:[dimxvn]:[dimyvn]:[colorbar]:' +     \
675      '[ckind]:[clabfmt]:[sminv],[smaxv]:[sminc],[smaxv],[Nlev]:[figt]:[kindfig]:' + \
676      '[reverse]:[timevals]:[mapv]'
677 
678    drw.check_arguments(fname,values,expectargs,':')
679
680    vnamesfig = values.split(':')[0].split(',')
681    dimvals= values.split(':')[1].replace('|',':')
682    dimvalc= values.split(':')[2].replace('|',':')
683    vdimxn = values.split(':')[3]
684    vdimyn = values.split(':')[4]
685    colbarn = values.split(':')[5]
686    countkind = values.split(':')[6]
687    countlabelfmt = values.split(':')[7]
688    shadminmax = values.split(':')[8]
689    contlevels = values.split(':')[9]
690    figtitle = values.split(':')[10].replace('|',' ')
691    figkind = values.split(':')[11]
692    revals = values.split(':')[12]
693    timevals = values.split(':')[13]
694    mapvalue = values.split(':')[14]
695
696    if2filenames = ncfile.find(',')
697
698    if if2filenames != -1:
699        ncfiles = ncfile.split(',')[0]
700        ncfilec = ncfile.split(',')[1]
701    else:
702        ncfiles = ncfile
703        ncfilec = ncfile
704
705    if not os.path.isfile(ncfiles):
706        print errormsg
707        print '  ' + fname + ': shading file "' + ncfiles + '" does not exist !!'
708        quit(-1)   
709
710    if not os.path.isfile(ncfilec):
711        print errormsg
712        print '  ' + fname + ': contour file "' + ncfilec + '" does not exist !!'
713        quit(-1)   
714
715    objsf = NetCDFFile(ncfiles, 'r')
716    objcf = NetCDFFile(ncfilec, 'r')
717   
718    varns = varn.split(',')[0]
719    varnc = varn.split(',')[1]
720
721    if  not objsf.variables.has_key(varns):
722        print errormsg
723        print '  ' + fname + ': shading file "' + ncfiles +                          \
724          '" does not have variable "' +  varns + '" !!'
725        quit(-1)
726
727    if  not objcf.variables.has_key(varnc):
728        print errormsg
729        print '  ' + fname + ': contour file "' + ncfilec +                          \
730          '" does not have variable "' +  varnc + '" !!'
731        quit(-1)
732
733# Variables' values
734    objvars = objsf.variables[varns]
735    objvarc = objcf.variables[varnc]
736
737    if len(objvars.shape) != len(objvarc.shape):
738        print errormsg
739        print '  ' + fname + ': shading variable "' + varns + '" has a shape: ',     \
740          objvars.shape,  'different than contour variable "' +  varnc + '": ',      \
741          objvarc.shape,' !!!'
742        quit(-1)
743
744    for idim in range(len(objvars.shape)):
745        if objvars.shape[idim] != objvarc.shape[idim]:
746            print errormsg
747            print '  ' + fname + ': shading variable "' + varns + '" has a shape: ', \
748              objvars.shape,  'different than contour variable "' +  varnc + '": ',  \
749              objvarc.shape,' !!!'
750            quit(-1)
751
752    valshad, dimsshad = drw.slice_variable(objvars, dimvals.replace(',','|'))
753    valcont, dimscont = drw.slice_variable(objvarc, dimvalc.replace(',','|'))
754
755# Dimensions names
756##    print fname + ' obj dimnames: ', objvars.dimensions, dimvals, len(dimvals.split(','))
757##    dimnamesv = []
758##    for idd in range(len(objvars.dimensions)):
759##        cutdim = False
760##        for idc in range(len(dimvals.split(','))):
761##            dimcutn = dimvals.split(',')[idc].split(':')[0]
762##            print objvars.dimensions[idd], dimcutn
763##            if objvars.dimensions[idd] == dimcutn:
764##                cutdim = True
765##                break
766##        if not cutdim: dimnamesv.append(objvars.dimensions[idd])
767    dimnamesv = [vdimyn, vdimxn]
768
769    varunits = []
770    varunits.append(objvars.getncattr('units'))
771    varunits.append(objvarc.getncattr('units'))
772
773    if  not objsf.variables.has_key(vdimxn):
774        print errormsg
775        print '  ' + fname + ': shading file "' + ncfiles +                          \
776          '" does not have dimension variable "' +  vdimxn + '" !!'
777        quit(-1)
778    if  not objsf.variables.has_key(vdimyn):
779        print errormsg
780        print '  ' + fname + ': shading file "' + ncfiles +                          \
781          '" does not have dimension variable "' +  vdimyn + '" !!'
782        quit(-1)
783
784    timename = timevals.split('|')[0]
785    timeunit = timevals.split('|')[1].replace('!',' ')
786    timekind = timevals.split('|')[2]
787    timefmt = timevals.split('|')[3]
788    timelabel = timevals.split('|')[4].replace('!',' ')
789
790    if vdimxn == timename:
791        timevals = objsf.variables[vdimxn][:]
792        timedims = objsf.variables[vdimxn].dimensions
793        dimt = 'x'
794        ovalaxis = objsf.variables[vdimyn]
795        ovalu = ovalaxis.getncattr('units')
796    elif vdimyn == timename:
797        timevals = objsf.variables[vdimyn][:]
798        timedims = objsf.variables[vdimyn].dimensions
799        dimt = 'y'
800        ovalaxis = objsf.variables[vdimxn]
801        ovalu = ovalaxis.getncattr('units')
802    else:
803        print errormsg
804        print '  ' + fname + ": time variable '" + timename + "' not found!!"
805        quit(-1)
806
807    timepos, timelabels = drw.CFtimes_plot(timevals, timeunit, timekind, timefmt)
808
809# Getting only that dimensions with coincident names
810    dimnvx = ovalaxis.dimensions
811
812    cutslice = []
813    for idimn in dimsshad:
814        found = False
815        for dimsn in dimnvx:
816            if idimn == dimsn:
817                cutslice.append(slice(0,len(objsf.dimensions[idimn])))
818                found = True
819        if not found: cutslice.append(0)
820
821    ovalaxisv = ovalaxis[tuple(cutslice)]
822
823##    if len(ovalaxis.shape) <= 2:
824##        ovalaxisv = ovalaxis[:]
825
826##    elif len(ovalaxis.shape) == 3:
827##        ovalaxisv = ovalaxis[0,:]
828##    else:
829##        print errormsg
830##        print '  ' + fname + ': shape of dimension variable:', ovalaxis.shape,       \
831##          ' not ready!!'
832##        quit(-1)
833
834    if countlabelfmt == 'None': 
835        countlfmt = None
836    else:
837        countlfmt = countlabelfmt
838
839    shading_nx = np.zeros((2), dtype=np.float)
840    shading_nx[0] = np.float(shadminmax.split(',')[0])
841    shading_nx[1] = np.float(shadminmax.split(',')[1])
842
843    clevmin = np.float(contlevels.split(',')[0])
844    clevmax = np.float(contlevels.split(',')[1])
845    Nclevels = int(contlevels.split(',')[2])
846
847    levels_cont = drw.pretty_int(clevmin, clevmax, Nclevels)
848
849    if len(levels_cont) <= 1: 
850        print warnmsg
851        print '  ' + fname + ': wrong contour levels:', levels_cont,' !!'
852        del(levels_cont)
853        levels_cont = np.zeros((Nclevels), dtype=np.float)
854        levels_cont = np.arange(7)*(clevmax - clevmin)/(Nclevels-1)
855        print '    generating default ones: ',levels_cont
856
857    if mapvalue == 'None': mapvalue = None
858
859    drw.plot_2D_shadow_contour_time(valshad, valcont, vnamesfig, ovalaxisv,         \
860      timevals, timepos, timelabels, ovalu, timelabel, dimt, dimnamesv, colbarn,    \
861      countkind, countlfmt, shading_nx, levels_cont, varunits, figtitle, figkind,   \
862      revals, mapvalue)
863
864    return
865
866def draw_2D_shad_line(ncfile, values, varn):
867    """ plotting a fields with shading and another with line
868    draw_2D_shad_line(ncfile, values, varn)
869      ncfile= [ncfiles],[ncfilel] file to use for the shading and for the line
870      values=[vnamefs],[vnamefl]:[dimvals]:[dimxvn]:[dimyvn]:[colorbar],[colline]:[sminv],[smaxv]:[figt]:
871       [kindfig]:[reverse]:[mapv]:[close]
872        [vnamefs]: Name in the figure of the variable to be shaded
873        [vnamefl]: Name in the figure of the variable to be lined
874        [dimvals]: ',' list of [dimname]|[value] telling at which dimension of the
875          variable a given value is required (-1, all the length)
876        [dimx/yvn]: name of the variables with the values of the final dimensions (x,y)
877        [colorbar]: name of the color bar
878        [colline]: name of the color for the line
879        [smin/axv]: minimum and maximum value for the shading
880        [figt]: title of the figure ('|' for spaces)
881        [kindfig]: kind of figure
882        [reverse]: Transformation of the values
883          * 'transpose': reverse the axes (x-->y, y-->x)
884          * 'flip'@[x/y]: flip the axis x or y
885        [mapv]: map characteristics: [proj],[res]
886          see full documentation: http://matplotlib.org/basemap/
887          [proj]: projection
888            * 'cyl', cilindric
889            * 'lcc', lamvbert conformal
890          [res]: resolution:
891            * 'c', crude
892            * 'l', low
893            * 'i', intermediate
894            * 'h', high
895            * 'f', full
896      valules= 'rh:z|-1,x|-1:z|-1,x|-1:lat:pressure:BuPu:0.,100.:rh:pdf:flip@y:None'
897      varn= [varsn],[varnl] name of the variable to plot with shading and with line
898    """
899
900    fname = 'draw_2D_shad_line'
901    if values == 'h':
902        print fname + '_____________________________________________________________'
903        print draw_2D_shad_line.__doc__
904        quit()
905
906    farguments = '[vnamefs],[vnamefl]:[dimvals]:[dimxvn]:[dimyvn]:' +                \
907      '[colorbar],[colline]:[sminv],[smaxv]:[figt]:[kindfig]:[reverse]:' +           \
908      '[mapv]:[close]'
909    drw.check_arguments(fname,values,farguments,':')
910
911    vnamesfig = values.split(':')[0].split(',')[0]
912    dimvals= values.split(':')[1].replace('|',':')
913    vdimxn = values.split(':')[2]
914    vdimyn = values.split(':')[3]
915    colbarn = values.split(':')[4].split(',')[0]
916    shadminmax = values.split(':')[5]
917    figtitle = values.split(':')[6].replace('|',' ')
918    figkind = values.split(':')[7]
919    revals = values.split(':')[8]
920    mapvalue = values.split(':')[9]
921#    varn = values.split(':')[10]
922
923    ncfiles = ncfile.split(',')[0]
924   
925    if not os.path.isfile(ncfiles):
926        print errormsg
927        print '  ' + fname + ': shading file "' + ncfiles + '" does not exist !!'
928        quit(-1)   
929
930    objsf = NetCDFFile(ncfiles, 'r')
931   
932    varns = varn.split(',')[0]
933
934    if  not objsf.variables.has_key(varns):
935        print errormsg
936        print '  ' + fname + ': shading file "' + ncfiles +                          \
937          '" does not have variable "' +  varns + '" !!'
938        quit(-1)
939
940# Variables' values
941    objvars = objsf.variables[varns]
942
943    valshad, dimsshad = drw.slice_variable(objvars, dimvals.replace(',','|'))
944
945# Dimensions names
946##    print fname + ' obj dimnames: ', objvars.dimensions, dimvals, len(dimvals.split(','))
947##    dimnamesv = []
948##    for idd in range(len(objvars.dimensions)):
949##        cutdim = False
950##        for idc in range(len(dimvals.split(','))):
951##            dimcutn = dimvals.split(',')[idc].split(':')[0]
952##            print objvars.dimensions[idd], dimcutn
953##            if objvars.dimensions[idd] == dimcutn:
954##                cutdim = True
955##                break
956##        if not cutdim: dimnamesv.append(objvars.dimensions[idd])
957    dimnamesv = [vdimyn, vdimxn]
958
959    varunits = objvars.getncattr('units')
960
961    if  not objsf.variables.has_key(vdimxn):
962        print errormsg
963        print '  ' + fname + ': shading file "' + ncfiles +                          \
964          '" does not have dimension variable "' +  vdimxn + '" !!'
965        quit(-1)
966    if  not objsf.variables.has_key(vdimyn):
967        print errormsg
968        print '  ' + fname + ': shading file "' + ncfiles +                          \
969          '" does not have dimensino variable "' +  vdimyn + '" !!'
970        quit(-1)
971
972    objdimx = objsf.variables[vdimxn]
973    objdimy = objsf.variables[vdimyn]
974    odimxu = objdimx.getncattr('units')
975    odimyu = objdimy.getncattr('units')
976
977    if len(objdimx.shape) <= 2:
978#        odimxv = objdimx[valshad.shape]
979#        odimyv = objdimy[valshad.shape]
980        odimxv = objdimx[:]
981        odimyv = objdimy[:]
982
983    elif len(objdimx.shape) == 3:
984#        dimcut = [0, slice(0,valshad.shape[0]), slice(0,valshad.shape[1])]
985#        odimxv = objdimx[tuple(dimcut)]
986#        odimyv = objdimy[tuple(dimcut)]
987        odimxv = objdimx[0,:]
988        odimyv = objdimy[0,:]
989    else:
990        print errormsg
991        print '  ' + fname + ': shape of dimension variable:', objdimx.shape,        \
992          ' not ready!!'
993        quit(-1)
994
995    shading_nx = np.zeros((2), dtype=np.float)
996    shading_nx[0] = np.float(shadminmax.split(',')[0])
997    shading_nx[1] = np.float(shadminmax.split(',')[1])
998
999    if mapvalue == 'None': mapvalue = None
1000
1001# line plot
1002##
1003    ncfilel = ncfile.split(',')[1]
1004    vnamelfig = values.split(':')[0].split(',')[1]
1005    varnl = varn.split(',')[1]
1006    colline = values.split(':')[4].split(',')[1]
1007
1008    objlf = NetCDFFile(ncfilel,'r')
1009    objlvar = objlf.variables[varnl]
1010
1011    linevals = objlvar[:]
1012    varlunits = objlvar.units
1013
1014    drw.plot_2D_shadow_line(valshad, linevals, vnamesfig, vnamelfig, odimxv, odimyv, \
1015      odimxu, odimyu, dimnamesv, colbarn, colline, shading_nx, varunits, varlunits,  \
1016      figtitle, figkind, revals, mapvalue, True)
1017
1018    objsf.close()
1019    objlf.close()
1020
1021    return
1022
1023def draw_2D_shad_line_time(ncfile, values, varn):
1024    """ plotting a fields with shading and a line with time values
1025    draw_2D_shad_line(ncfile, values, varn)
1026      ncfile= [ncfiles],[ncfilel] files to use to draw with shading and the line
1027      values= [vnamefs],[vanemefl]:[dimvals]:[dimxvn]:[dimyvn]:[colorbar]:[sminv],[smaxv]:[figt]:
1028       [kindfig]:[reverse]:[timevals]:[close]
1029        [vnamefs]: Name in the figure of the variable to be shaded
1030        [vnamefl]: Name in the figure of the variable to be lined
1031        [dimvals]: ',' list of [dimname]|[value] telling at which dimension of the
1032          variable a given value is required (-1, all the length)
1033        [dimx/yvn]: name of the variables with the values of the final dimensions (x,y)
1034        [colorbar]: name of the color bar
1035        [smin/axv]: minimum and maximum value for the shading
1036        [figt]: title of the figure ('|' for spaces)
1037        [kindfig]: kind of figure
1038        [reverse]: Transformation of the values
1039          * 'transpose': reverse the axes (x-->y, y-->x)
1040          * 'flip'@[x/y]: flip the axis x or y
1041        [timevals]: [timen]|[units]|[kind]|[tfmt]|[label]|[timeaxis] time labels characteristics
1042           [timen]; name of the time variable
1043           [units]; units string according to CF conventions ([tunits] since
1044             [YYYY]-[MM]-[DD] [[HH]:[MI]:[SS]], '!' for spaces)
1045           [kind]; kind of output
1046             'Nval': according to a given number of values as 'Nval',[Nval]
1047             'exct': according to an exact time unit as 'exct',[tunit];
1048               tunit= [Nunits],[tu]; [tu]= 'c': centuries, 'y': year, 'm': month,
1049                'w': week, 'd': day, 'h': hour, 'i': minute, 's': second,
1050                'l': milisecond
1051           [tfmt]; desired format
1052           [label]; label at the graph ('!' for spaces)
1053        [close]: should figure be closed (finished)
1054      values='dtcon,prc:Time|-1,bottom_top|-1:presmean:time:seismic:-3.e-6,3.e-6:monthly|'
1055        'dtcon:pdf:transpose:time|hours!since!1949-12-01|exct,2,d|%d|date!([DD])|x:True
1056      varn= [varsn].[varln] name of the variable to plot with shading and to plot with line
1057    """
1058    fname = 'draw_2D_shad_line_time'
1059    if values == 'h':
1060        print fname + '_____________________________________________________________'
1061        print draw_2D_shad__line_time.__doc__
1062        quit()
1063
1064    farguments = '[vnamefs],[vanemefl]:[dimvals]:[dimxvn]:[dimyvn]:' +               \
1065      '[colorbar]:[sminv],[smaxv]:[figt]:[kindfig]:[reverse]:[timevals]:[close]'
1066    drw.check_arguments(fname,values,farguments,':')
1067
1068    vnamesfig = values.split(':')[0].split(',')[0]
1069    dimvals= values.split(':')[1].replace('|',':')
1070    vdimxn = values.split(':')[2]
1071    vdimyn = values.split(':')[3]
1072    colbarn = values.split(':')[4]
1073    shadminmax = values.split(':')[5]
1074    figtitle = values.split(':')[6].replace('|',' ')
1075    figkind = values.split(':')[7]
1076    revals = values.split(':')[8]
1077    timevals = values.split(':')[9]
1078    close = values.split(':')[10]
1079
1080    ncfiles = ncfile.split(',')[0]
1081   
1082    if not os.path.isfile(ncfiles):
1083        print errormsg
1084        print '  ' + fname + ': shading file "' + ncfiles + '" does not exist !!'
1085        quit(-1)   
1086
1087    objsf = NetCDFFile(ncfiles, 'r')
1088   
1089    varns = varn.split(',')[0]
1090
1091    if  not objsf.variables.has_key(varns):
1092        print errormsg
1093        print '  ' + fname + ': shading file "' + ncfiles +                          \
1094          '" does not have variable "' +  varns + '" !!'
1095        quit(-1)
1096
1097# Variables' values
1098    objvars = objsf.variables[varns]
1099
1100    valshad, dimsshad = drw.slice_variable(objvars, dimvals.replace(',','|'))
1101
1102    dimnamesv = [vdimyn, vdimxn]
1103
1104    varunits = objvars.getncattr('units')
1105
1106    if  not objsf.variables.has_key(vdimxn):
1107        print errormsg
1108        print '  ' + fname + ': shading file "' + ncfiles +                          \
1109          '" does not have dimension variable "' +  vdimxn + '" !!'
1110        quit(-1)
1111    if  not objsf.variables.has_key(vdimyn):
1112        print errormsg
1113        print '  ' + fname + ': shading file "' + ncfiles +                          \
1114          '" does not have dimensino variable "' +  vdimyn + '" !!'
1115        quit(-1)
1116
1117    objdimx = objsf.variables[vdimxn]
1118    objdimy = objsf.variables[vdimyn]
1119    odimxu = objdimx.getncattr('units')
1120    odimyu = objdimy.getncattr('units')
1121
1122    if len(objdimx.shape) <= 2:
1123        odimxv = objdimx[:]
1124        odimyv = objdimy[:]
1125
1126    elif len(objdimx.shape) == 3:
1127        odimxv = objdimx[0,:]
1128        odimyv = objdimy[0,:]
1129    else:
1130        print errormsg
1131        print '  ' + fname + ': shape of dimension variable:', objdimx.shape,        \
1132          ' not ready!!'
1133        quit(-1)
1134
1135    timename = timevals.split('|')[0]
1136    timeunit = timevals.split('|')[1].replace('!',' ')
1137    timekind = timevals.split('|')[2]
1138    timefmt = timevals.split('|')[3]
1139    timelabel = timevals.split('|')[4].replace('!',' ')
1140
1141    if vdimxn == timename:
1142        odimxv = objsf.variables[vdimxn][:]
1143        odimxu = timelabel
1144        timeaxis = 'x'
1145        odimyv = objsf.variables[vdimyn]
1146        odimyu = odimyv.getncattr('units')
1147        timepos, timelabels = drw.CFtimes_plot(odimxv, timeunit, timekind, timefmt)
1148    elif vdimyn == timename:
1149        odimyv = objsf.variables[vdimyn][:]
1150        odimyu = timelabel
1151        timeaxis = 'y'
1152        odimxv = objsf.variables[vdimxn]
1153        odimxu = odimxv.getncattr('units')
1154        timepos, timelabels = drw.CFtimes_plot(odimyv, timeunit, timekind, timefmt)
1155    else:
1156        print errormsg
1157        print '  ' + fname + ": time variable '" + timename + "' not found!!"
1158        quit(-1)
1159
1160    shading_nx = np.zeros((2), dtype=np.float)
1161    shading_nx[0] = np.float(shadminmax.split(',')[0])
1162    shading_nx[1] = np.float(shadminmax.split(',')[1])
1163
1164    closeval = drw.Str_Bool(close)
1165
1166    drw.plot_2D_shadow_time(valshad, vnamesfig, odimxv, odimyv, odimxu, odimyu,      \
1167      dimnamesv, colbarn, shading_nx, varunits, figtitle, figkind, revals, timeaxis, \
1168      timepos, timelabels, False)
1169
1170# Line values
1171##
1172    ncfilel = ncfile.split(',')[1]
1173
1174    vnamelfig = values.split(':')[0].split(',')[1]
1175    varnl = varn.split(',')[1]
1176
1177    objlf = NetCDFFile(ncfilel,'r')
1178    objlvar = objlf.variables[varnl]
1179
1180    linevals = objlvar[:]
1181    if reva0 == 'tranpose':
1182        plt.plot (linevals, odimxv, '-', color='k')
1183    else:
1184        plt.plot (odimxv, linevals, '-', color='k')
1185
1186    objsf.close()
1187    objsl.close()
1188
1189    return
1190
1191def draw_barbs(ncfile, values, varns):
1192    """ Function to plot wind barbs
1193      values= [dimname]|[vardimname]|[value]:[vecvals]:[windlabs]:[mapvalues]:
1194        [gtit]:[kindfig]:[figuren]
1195        'X/Y/Z/T'|[dimname]|[vardimname]|[value]: ',', list for each basic dimension '|' separated of:
1196          [dimname]: name of the dimension in the file
1197          [vardimname]: name of the variable with the values for the dimension in the file
1198          [value]: which value of the given dimension (-1, all; [ibeg]@[iend], i-range beginning, end)
1199          No value takes all the range of the dimension
1200        [vecvals]= [frequency],[color],[length]
1201          [frequency]: [xfreq]@[yfreq] frequency of values allong each axis ('None', all grid points;
1202            'auto', computed automatically to have 20 vectors along each axis)
1203          [color]: color of the vectors ('auto', for 'red')
1204          [length]: length of the wind barbs ('auto', for 9)
1205        [windlabs]= [windname],[windunits]
1206          [windname]: name of the wind variable in the graph
1207          [windunits]: units of the wind variable in the graph ('None', for the value in the file)
1208        [mapvalues]= map characteristics: [proj],[res]
1209          see full documentation: http://matplotlib.org/basemap/
1210          [proj]: projection
1211            * 'cyl', cilindric
1212            * 'lcc', lambert conformal
1213          [res]: resolution:
1214            * 'c', crude
1215            * 'l', low
1216            * 'i', intermediate
1217            * 'h', high
1218            * 'f', full
1219        gtit= title of the graph ('|', for spaces)
1220        kindfig= kind of figure
1221        figuren= name of the figure
1222      ncfile= file to use
1223      varns= [uwind],[ywind] ',' list of the name of the variables with the u-wind,y-wind component
1224    """
1225    fname = 'draw_barbs'
1226
1227    if values == 'h':
1228        print fname + '_____________________________________________________________'
1229        print draw_barbs.__doc__
1230        quit()
1231
1232    expectargs = '[X/Y/Z/T]|[dimname]|[vardimname]|[value]:[vecvals]:[windlabs]:' +  \
1233      '[mapvalues]:[gtit]:[kindfig]:[figuren]'
1234 
1235    drw.check_arguments(fname,values,expectargs,':')
1236
1237    dimvals = values.split(':')[0]
1238    vecvals = values.split(':')[1]
1239    windlabels = values.split(':')[2]
1240    mapvalues = values.split(':')[3]
1241    gtit = values.split(':')[4]
1242    kindfig = values.split(':')[5]
1243    figuren = values.split(':')[6]
1244
1245    of = NetCDFFile(ncfile,'r')
1246
1247    dims = {}
1248    for dimv in dimvals.split(','):
1249        dns = dimv.split('|')
1250        dims[dns[0]] = [dns[1], dns[2], dns[3]]
1251
1252    varNs = []
1253    for dn in dims.keys():
1254        if dn == 'X':
1255            varNs.append(dims[dn][1])
1256            dimx = len(of.dimensions[dims[dn][0]])
1257        elif dn == 'Y':
1258            varNs.append(dims[dn][1])
1259            dimy = len(of.dimensions[dims[dn][0]])
1260
1261    ivar = 0
1262    for wvar in varns.split(','):
1263        if not drw.searchInlist(of.variables.keys(), wvar):
1264            print errormsg
1265            print '  ' + fname + ": file does not have variable '" + wvar + "' !!"
1266            quit(-1)
1267        if ivar == 0:
1268            varNs.append(wvar)
1269        else:
1270            varNs.append(wvar)
1271
1272    ivar = 0
1273    for varN in varNs:
1274        varslice = []
1275
1276        ovarN = of.variables[varN]
1277        vard = ovarN.dimensions
1278        for vdn in vard:
1279            found = False
1280            for dd in dims.keys():
1281                if dims[dd][0] == vdn:
1282                    if dims[dd][2].find('@') != -1:
1283                        rvals = dims[dd][2].split('@')
1284                        varslice.append(slice(int(rvals[0]), int(rvals[1])))
1285                    elif dims[dd][2] == '-1':
1286                        varslice.append(slice(0,len(of.dimensions[dims[dd][0]])))
1287                    else:
1288                        varslice.append(int(dims[dd][2]))
1289
1290                    found = True
1291                    break
1292            if not found:
1293                varslice.append(slice(0,len(of.dimensions[dims[dd][0]])))
1294
1295        if varN == dims['X'][1]:
1296            lonvals0 = np.squeeze(ovarN[tuple(varslice)])
1297        elif varN == dims['Y'][1]:
1298            latvals0 = np.squeeze(ovarN[tuple(varslice)])
1299        elif ivar == 2:
1300            uwvals = np.squeeze(np.array(ovarN[tuple(varslice)]))
1301        elif ivar == 3:
1302            vwvals = np.squeeze(ovarN[tuple(varslice)])           
1303
1304        ivar = ivar + 1
1305
1306#    print 'Final shapes:',lonvals0.shape,':',latvals0.shape,':',uwvals.shape,':',
1307#      vwvals.shape
1308
1309    if len(uwvals.shape) != 2 or len(vwvals.shape) != 2:
1310        print errormsg
1311        print '  ' + fname + ': wrong size of the wind fields! they must be ' +      \
1312          '2-dimensional!'
1313        print '    u-winds shape:',uwvals.shape,'dims:',of.variables[varNs[2]]
1314        print '    v-winds shape:',vwvals.shape,'dims:',of.variables[varNs[3]]
1315        print '      provide more values for their dimensions!!'
1316        quit(-1)
1317
1318    if len(lonvals0.shape) == 1:
1319        lonvals, latvals = np.meshgrid(lonvals0, latvals0)
1320    else:
1321        lonvals = lonvals0
1322        latvals = latvals0
1323
1324# Vecor values
1325    if vecvals.split(',')[0] == 'None':
1326        freqv = None
1327    else:
1328        freqv = vecvals.split(',')[0] 
1329    colorv = vecvals.split(',')[1]
1330    lengthv = vecvals.split(',')[2]
1331
1332# Vector labels
1333    windname = windlabels.split(',')[0]
1334    windunits = windlabels.split(',')[1]
1335
1336    drw.plot_barbs(lonvals, latvals, uwvals, vwvals, freqv, colorv, lengthv, 
1337      windname, windunits, mapvalues, gtit, kindfig, figuren)
1338
1339    return
1340 
1341def draw_topo_geogrid(ncfile, values):
1342    """ plotting geo_em.d[nn].nc topography from WPS files
1343    draw_topo_geogrid(ncfile, values)
1344      ncfile= geo_em.d[nn].nc file to use
1345      values= [minTopo],[maxTopo]:[lonlatL]:[title]:[graphic_kind]:[mapvalues]
1346        [min/max]Topo: minimum and maximum values of topography to draw
1347        lonlatL: limits of longitudes and latitudes [lonmin, latmin, lonmax, latmax] or None
1348        title: title of the graph ('!' for spaces)
1349        graphic_kind: kind of figure (jpg, pdf, png)
1350        mapvalues: map characteristics [proj],[res]
1351          see full documentation: http://matplotlib.org/basemap/
1352          [proj]: projection
1353            * 'cyl', cilindric
1354            * 'lcc', lambert conformal
1355          [res]: resolution:
1356            * 'c', crude
1357            * 'l', low
1358            * 'i', intermediate
1359            * 'h', high
1360            * 'f', full
1361    """
1362    fname = 'draw_topo_geogrid'
1363
1364    if values == 'h':
1365        print fname + '_____________________________________________________________'
1366        print draw_topo_geogrid.__doc__
1367        quit()
1368
1369    expectargs = '[minTopo],[maxTopo]:[lonlatL]:[title]:[graphic_kind]:[mapvalues]'
1370 
1371    drw.check_arguments(fname,values,expectargs,':')
1372
1373    mintopo = np.float(values.split(':')[0].split(',')[0])
1374    maxtopo = np.float(values.split(':')[0].split(',')[1])
1375
1376    lonlatLS = values.split(':')[1]
1377    lonlatLv = lonlatLS.split(',')[0]
1378
1379    if lonlatLv == 'None':
1380        lonlatL = None
1381    else:
1382        lonlatL = np.zeros((4), dtype=np.float)
1383        lonlatL[0] = np.float(lonlatLS.split(',')[0])
1384        lonlatL[1] = np.float(lonlatLS.split(',')[1])
1385        lonlatL[2] = np.float(lonlatLS.split(',')[2])
1386        lonlatL[3] = np.float(lonlatLS.split(',')[3])
1387
1388    grtit = values.split(':')[2].replace('!',' ')
1389    kindfig = values.split(':')[3]
1390    mapvalues = values.split(':')[4]
1391
1392    if not os.path.isfile(ncfile):
1393        print errormsg
1394        print '  ' + fname + ': domain file "' + ncfile + '" does not exist !!'
1395        quit(-1)   
1396
1397    objdomf = NetCDFFile(ncfile, 'r')
1398   
1399    objhgt = objdomf.variables['HGT_M']
1400    objlon = objdomf.variables['XLONG_M']
1401    objlat = objdomf.variables['XLAT_M']
1402
1403    topography = objhgt[0,:,:]
1404
1405    drw.plot_topo_geogrid(topography, objlon, objlat, mintopo, maxtopo, lonlatL,     \
1406      grtit, kindfig, mapvalues, True)
1407
1408    objdomf.close()
1409
1410    return
1411
1412def draw_topo_geogrid_boxes(ncfiles, values):
1413    """ plotting different geo_em.d[nn].nc topography from WPS files
1414    draw_topo_geogrid_boxes(ncfile, values)
1415      ncfiles= ',' list of geo_em.d[nn].nc files to use (fisrt as topographyc reference)
1416      values= [minTopo],[maxTopo]:[lonlatL]:[title]:[graphic_kind]:[mapvalues]:[labels]:[legloc]
1417        [min/max]Topo: minimum and maximum values of topography to draw
1418        lonlatL: limits of longitudes and latitudes [lonmin, latmin, lonmax, latmax] or None
1419        title: title of the graph ('!' for spaces)
1420        graphic_kind: kind of figure (jpg, pdf, png)
1421        mapvalues: map characteristics [proj],[res]
1422          see full documentation: http://matplotlib.org/basemap/
1423          [proj]: projection
1424            * 'cyl', cilindric
1425            * 'lcc', lambert conformal
1426          [res]: resolution:
1427            * 'c', crude
1428            * 'l', low
1429            * 'i', intermediate
1430            * 'h', high
1431            * 'f', full
1432        legloc= location of the legend (0, autmoatic)
1433          1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
1434          5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
1435          9: 'upper center', 10: 'center'
1436        labels= labels to write in the graph
1437    """
1438#    import matplotlib as mpl
1439#    mpl.use('Agg')
1440    import matplotlib.pyplot as plt
1441
1442    fname = 'draw_topo_geogrid_boxes'
1443
1444    if values == 'h':
1445        print fname + '_____________________________________________________________'
1446        print draw_topo_geogrid_boxes.__doc__
1447        quit()
1448
1449    mintopo = np.float(values.split(':')[0].split(',')[0])
1450    maxtopo = np.float(values.split(':')[0].split(',')[1])
1451
1452    lonlatLS = values.split(':')[1]
1453    lonlatLv = lonlatLS.split(',')[0]
1454
1455    if lonlatLv == 'None':
1456        lonlatL = None
1457    else:
1458        lonlatL = np.zeros((4), dtype=np.float)
1459        lonlatL[0] = np.float(lonlatLS.split(',')[0])
1460        lonlatL[1] = np.float(lonlatLS.split(',')[1])
1461        lonlatL[2] = np.float(lonlatLS.split(',')[2])
1462        lonlatL[3] = np.float(lonlatLS.split(',')[3])
1463
1464    grtit = values.split(':')[2].replace('!', ' ')
1465    kindfig = values.split(':')[3]
1466    mapvalues = values.split(':')[4]
1467    labels = values.split(':')[5]
1468    legloc = int(values.split(':')[6])
1469
1470    ncfile = ncfiles.split(',')[0]
1471    if not os.path.isfile(ncfile):
1472        print errormsg
1473        print '  ' + fname + ': domain file "' + ncfile + '" does not exist !!'
1474        quit(-1)   
1475
1476    objdomf = NetCDFFile(ncfile, 'r')
1477   
1478    objhgt = objdomf.variables['HGT_M']
1479    objlon0 = objdomf.variables['XLONG_M']
1480    objlat0 = objdomf.variables['XLAT_M']
1481
1482    topography = objhgt[0,:,:]
1483
1484    Nfiles = len(ncfiles.split(','))
1485    boxlabels = labels.split(',')
1486
1487    Xboxlines = []
1488    Yboxlines = []
1489
1490    for ifile in range(Nfiles):
1491        ncfile = ncfiles.split(',')[ifile]
1492#        print ifile, ncfile
1493        if not os.path.isfile(ncfile):
1494            print errormsg
1495            print '  ' + fname + ': domain file "' + ncfile + '" does not exist !!'
1496            quit(-1)   
1497
1498        objdomfi = NetCDFFile(ncfile, 'r')
1499   
1500        objlon = objdomfi.variables['XLONG_M']
1501        objlat = objdomfi.variables['XLAT_M']
1502
1503        dx = objlon.shape[2]
1504        dy = objlon.shape[1]
1505
1506        Xboxlines.append(objlon[0,0,:])
1507        Yboxlines.append(objlat[0,0,:])
1508        Xboxlines.append(objlon[0,dy-1,:])
1509        Yboxlines.append(objlat[0,dy-1,:])
1510        Xboxlines.append(objlon[0,:,0])
1511        Yboxlines.append(objlat[0,:,0])
1512        Xboxlines.append(objlon[0,:,dx-1])
1513        Yboxlines.append(objlat[0,:,dx-1])
1514
1515        objdomfi.close()
1516
1517    drw.plot_topo_geogrid_boxes(topography, Xboxlines, Yboxlines, boxlabels,         \
1518      objlon0, objlat0, mintopo, maxtopo, lonlatL, grtit, kindfig, mapvalues, legloc,\
1519      True)
1520
1521    objdomf.close()
1522
1523    return
1524
1525def movievalslice(origslice, dimmovien, framenum):
1526    """ Function to provide variable slice according to a geneation of a movie
1527    movievals(origslice, dimmovien, framenum)
1528      [origslice]= slice original as [dimname1]|[val1],[...,[dimnameN]|[valN]]
1529        ([val] = -1, full length)
1530      [dimmovien]= name of the dimension to produce the movie
1531      [framenum]= value of the frame to substitue in [origslice] as
1532        [dimmovien]|[framenum]
1533    >>> movievalslice('East_West|-1,North_South|-1,Time|2','Time',0)
1534    East_West|-1,North_South|-1,Time|0
1535    """
1536
1537    fname = 'movievalslice'
1538
1539    if origslice == 'h':
1540        print fname + '_____________________________________________________________'
1541        print movievalslice.__doc__
1542        quit()
1543   
1544    dims = origslice.split(',')
1545
1546    movieslice = ''
1547    idim = 0
1548
1549    for dimn in dims:
1550        dn = dimn.split('|')[0]
1551        if dn == dimmovien:
1552            movieslice = movieslice + dn + '|' + str(framenum)
1553        else:
1554            movieslice = movieslice + dimn
1555        if idim < len(dims)-1: movieslice = movieslice + ','
1556
1557        idim = idim + 1
1558
1559    return movieslice
1560
1561class Capturing(list):
1562    """ Class to capture function output as a list
1563    from: http://stackoverflow.com/questions/16571150/how-to-capture-stdout-output-from-a-python-function-call
1564    """
1565#    from cStringIO import StringIO
1566
1567    def __enter__(self):
1568        self._stdout = sys.stdout
1569        sys.stdout = self._stringio = StringIO()
1570        return self
1571    def __exit__(self, *args):
1572        self.extend(self._stringio.getvalue().splitlines())
1573        sys.stdout = self._stdout
1574
1575def create_movie(netcdfile, values, variable):
1576    """ Function to create a movie assuming ImageMagick installed!
1577      values= [graph]#[movie_dimension]#[graph_values]
1578        [graph]: which graphic
1579        [movie_dimension]: [dimnmovie]@[dimvmovie]@[moviedelay]@[interval]
1580          [dimnmovie]; name of the dimension from which make the movie
1581          [dimvmovie]; name of the variable with the values of the dimension
1582          [moviedelay]; delay between frames
1583          [interval]; [beg]@[end]@[freq] or -1 (all)
1584        [graph_values]: values to generate the graphic
1585      netcdfile= netCDF file
1586      variable= variable to use (when applicable)
1587    """ 
1588    fname = 'create_movie'
1589
1590    if values == 'h':
1591        print fname + '_____________________________________________________________'
1592        print create_movie.__doc__
1593        quit()
1594
1595    graph = values.split('#')[0]
1596    movie_dim = values.split('#')[1]
1597    graph_vals = values.split('#')[2]
1598
1599    ncobj = NetCDFFile(netcdfile, 'r')
1600
1601# Movie dimension
1602##
1603    dimnmovie = movie_dim.split('@')[0]
1604    dimvmovie = movie_dim.split('@')[1]
1605    moviedelay = movie_dim.split('@')[2]
1606    moviebeg = int(movie_dim.split('@')[3])
1607
1608    if not drw.searchInlist(ncobj.dimensions.keys(),dimnmovie):
1609        print errormsg
1610        print '  ' + fname + ": file '" + netcdfile + "' has not dimension '" +      \
1611          dimnmovie + "' !!!"
1612        quit(-1)
1613
1614    objdmovie = ncobj.dimensions[dimnmovie]
1615    dmovie = len(objdmovie)
1616    if moviebeg != -1:
1617        moviend = int(movie_dim.split('@')[4])
1618        moviefreq = int(movie_dim.split('@')[5])
1619    else:
1620        moviebeg = 0
1621        moviend = dmovie
1622        moviefreq = 1
1623
1624    if dimvmovie == 'WRFTimes':
1625        objvdmovie = ncobj.variables['Times']
1626        vdmovieunits = ''
1627        valsdmovie = []
1628        for it in range(objvdmovie.shape[0]):
1629            valsdmovie.append(drw.datetimeStr_conversion(objvdmovie[it,:],           \
1630              'WRFdatetime', 'Y/m/d H-M-S'))
1631    elif dimvmovie == 'CFtime':
1632        objvdmovie = ncobj.variables['time']
1633        vdmovieunits = ''
1634        print objvdmovie.units
1635        valsdmovie0 = drw.netCDFdatetime_realdatetime(objvdmovie.units, 'standard',  \
1636          objvdmovie[:])
1637        valsdmovie = []
1638        for it in range(objvdmovie.shape[0]):
1639            valsdmovie.append(drw.datetimeStr_conversion(valsdmovie0[it,:],          \
1640              'matYmdHMS', 'Y/m/d H-M-S'))
1641    else:
1642        if  not drw.searchInlist(ncobj.variables.keys(),dimvmovie):
1643            print errormsg
1644            print '  ' + fname + ": file '" + netcdfile + "' has not variable '" +   \
1645              dimvmovie + "' !!!"
1646            quit(-1)
1647        vdmovieunits = objvdmovie.getncattr('units')
1648        objvdmovie = ncobj.variables[dimvmovie]
1649        if len(objvdmovie.shape) == 1:
1650            vasldmovie = objvdmovie[:]
1651        else:
1652            print errormsg
1653            print '  ' + fname + ': shape', objvdmovie.shape, 'of variable with ' +  \
1654              'dimension movie values not ready!!!'
1655            quit(-1)
1656
1657    ncobj.close()
1658    os.system('rm frame_*.png > /dev/null')
1659
1660# graphic
1661##
1662    if graph == 'draw_2D_shad':
1663        graphvals = graph_vals.split(':')
1664
1665        for iframe in range(moviebeg,moviend,moviefreq):
1666            iframeS = str(iframe).zfill(4)
1667
1668            drw.percendone((iframe-moviebeg)/moviefreq,(moviend-moviebeg)/moviefreq, \
1669              5, 'frames')
1670            titgraph = dimnmovie + '|=|' + str(valsdmovie[iframe]) + '|' +           \
1671              vdmovieunits
1672
1673            graphvals[1] = movievalslice(graphvals[1],dimnmovie,iframe)
1674            graphvals[6] = titgraph
1675            graphvals[7] = 'png'
1676
1677            graphv = drw.numVector_String(graphvals, ":")
1678
1679            with Capturing() as output:
1680                draw_2D_shad(netcdfile, graphv, variable)
1681
1682            os.system('mv 2Dfields_shadow.png frame_' + iframeS + '.png')
1683    else:
1684        print errormsg
1685        print '  ' + fname + ": graphic '" +  graph + "' not defined !!!"
1686        quit(-1)
1687
1688    os.system('convert -delay ' + moviedelay + ' -loop 0 frame_*.png create_movie.gif')
1689
1690    print "Succesfuly creation of movie file 'create_movie.gif' !!!"
1691
1692    return
1693
1694def draw_lines(ncfilens, values, varname):
1695    """ Function to draw different lines at the same time from different files
1696    draw_lines(ncfilens, values, varname):
1697      ncfilens= [filen] ',' separated list of netCDF files
1698      values= [dimvname]:[valuesaxis]:[dimtit]:[leglabels]:[vtit]:[title]:[locleg]:[graphk]
1699        [dimvname]: ',' list of names of the variable with he values of the common dimension
1700        [valuesaxis]: which axis will be used for the values ('x', or 'y')
1701        [dimtit]: title for the common dimension
1702        [leglabels]: ',' separated list of names for the legend
1703        [vartit]: name of the variable in the graph
1704        [title]: title of the plot ('|' for spaces)
1705        [locleg]: location of the legend (0, autmoatic)
1706          1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
1707          5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
1708          9: 'upper center', 10: 'center'
1709        [graphk]: kind of the graphic
1710      varname= variable to plot
1711      values= 'XLAT:x:latitude:32x32:$wss^{*}$:wss Taylor's turbulence term:pdf'
1712    """
1713
1714    fname = 'draw_lines'
1715
1716    if values == 'h':
1717        print fname + '_____________________________________________________________'
1718        print draw_lines.__doc__
1719        quit()
1720
1721    expectargs = '[dimvname]:[valuesaxis]:[dimtit]:[leglabels]:[vtit]:[title]:[locleg]:[graphk]'
1722    drw.check_arguments(fname,values,expectargs,':')
1723
1724    ncfiles = ncfilens.split(',')
1725    dimvnames = values.split(':')[0]
1726    valuesaxis = values.split(':')[1]
1727    dimtit = values.split(':')[2]
1728    leglabels = values.split(':')[3].replace('_','\_')
1729    vartit = values.split(':')[4]
1730    title = values.split(':')[5].replace('|',' ')
1731    locleg = values.split(':')[6]
1732    graphk = values.split(':')[7]
1733
1734    Nfiles = len(ncfiles)
1735
1736# Getting trajectotries
1737##
1738
1739    varvalues = []
1740    dimvalues = []
1741
1742    print '  ' + fname
1743    ifn = 0
1744    for ifile in ncfiles:
1745        filen = ifile.split('@')[0]
1746
1747        print '    filen:',filen
1748
1749        if not os.path.isfile(filen):
1750            print errormsg
1751            print '  ' + fname + ": netCDF file '" + filen + "' does not exist !!"
1752            quit(-1)
1753
1754        objfile = NetCDFFile(filen, 'r')
1755
1756        if dimvnames.find(',') != -1:
1757            dimvname = dimvnames.split(',')
1758        else:
1759            dimvname = [dimvnames]
1760   
1761        found = False
1762        for dvn in dimvname:
1763            if objfile.variables.has_key(dvn):
1764                found = True
1765                break
1766   
1767        if not found:
1768            print errormsg
1769            print '  ' + fname + ": netCDF file '" + filen +                         \
1770              "' does not have variables '" + dimvnames + "' !!"
1771            quit(-1)
1772
1773        if not objfile.variables.has_key(varname):
1774            print errormsg
1775            print '  ' + fname + ": netCDF file '" + filen +                         \
1776              "' does not have variable '" + varname + "' !!"
1777            quit(-1)
1778
1779        vvobj = objfile.variables[varname]
1780        if len(vvobj.shape) != 1:
1781            print errormsg
1782            print '  ' + fname + ': wrong shape:',vvobj.shape," of variable '" +     \
1783              varname +  "' !!"
1784            quit(-1)
1785
1786        for dimvn in dimvname:
1787            if drw.searchInlist(objfile.variables, dimvn):
1788                vdobj = objfile.variables[dimvn]
1789                if len(vdobj.shape) != 1:
1790                    print errormsg
1791                    print '  ' + fname + ': wrong shape:',vdobj.shape,               \
1792                      " of variable '" + dimvn +  "' !!"
1793                    quit(-1)
1794                break
1795
1796        varvalues.append(vvobj[:])
1797        dimvalues.append(vdobj[:])
1798
1799        if ifn == 0:
1800            varunits = vvobj.units
1801
1802        objfile.close()
1803
1804        ifn = ifn + 1
1805
1806    drw.plot_lines(dimvalues, varvalues, valuesaxis, dimtit, leglabels.split(','),   \
1807      vartit, varunits, title, locleg, graphk)
1808
1809    return
1810
1811def draw_lines_time(ncfilens, values, varname0):
1812    """ Function to draw different lines at the same time from different files with times
1813    draw_lines_time(ncfilens, values, varname):
1814      ncfilens= [filen] ',' separated list of netCDF files
1815      values= [dimvname];[valuesaxis];[dimtit];[leglabels];[vtit];[title];[timevals];[locleg];
1816        [graphk];[collines];[points];[linewidths];[pointsizes];[pointfreq];[period]
1817        [dimvname]: ',' list of names of the variables with he values of the common dimension
1818        [valuesaxis]: which axis will be used for the values ('x', or 'y')
1819        [dimtit]: title for the common dimension ('|' for spaces)
1820        [leglabels]: ',' separated list of names for the legend ('None', no legend)
1821        [vartit]: name of the variable in the graph
1822        [title]: title of the plot ('|' for spaces)
1823        [timevals]: [timen]|[units]|[kind]|[tfmt] time labels characteristics
1824           [timen]; name of the time variable
1825           [units]; units string according to CF conventions ([tunits] since
1826             [YYYY]-[MM]-[DD] [[HH]:[MI]:[SS]], '!' for spaces)
1827           [kind]; kind of output
1828             'Nval': according to a given number of values as 'Nval',[Nval]
1829             'exct': according to an exact time unit as 'exct',[tunit];
1830               tunit= [Nunits],[tu]; [tu]= 'c': centuries, 'y': year, 'm': month,
1831                'w': week, 'd': day, 'h': hour, 'i': minute, 's': second,
1832                'l': milisecond
1833           [tfmt]; desired format
1834        [locleg]: location of the legend (0, autmoatic)
1835          1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
1836          5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
1837          9: 'upper center', 10: 'center'
1838        [graphk]: kind of the graphic
1839        [lines]: ',' list of type of lines, None for automatic, single value all the same
1840        [collines]: ',' list of colors for the lines, None for automatic, single
1841          value all the same
1842        [points]: ',' list of type of points for the lines, None for automatic, single
1843          value all the same
1844        [linewidths]: ',' list of widths for the lines, None for automatic, single
1845          value all the same
1846        [pointsizes]: ',' list of widths for the lines, None for automatic, single
1847          value all the same
1848        [pointfreq]: frequency of point plotting, 'all' for all time steps
1849        [period]: which period to plot
1850          '-1': all period
1851          [beg],[end]: beginning and end of the period in reference time-units of first file
1852      varname0= ',' list of variable names to plot (assuming only 1 variable per file)
1853      values= 'time;y;time ([DD]${[HH]}$);32x32;$wss^{*}$;wss Taylor's turbulence term;time|hours!since!1949-12-01_00:00:00;exct,12,h|%d$^{%H}$;2;pdf'
1854    """
1855
1856    fname = 'draw_lines_time'
1857
1858    if values == 'h':
1859        print fname + '_____________________________________________________________'
1860        print draw_lines_time.__doc__
1861        quit()
1862
1863    expectargs = '[dimvname];[valuesaxis];[dimtit];[leglabels];[vtit];[title];'
1864    expectargs = expectargs + '[timevals];[locleg];[graphk];[lines];[collines];[points];'
1865    expectargs = expectargs + '[linewidths];[pointsizes];[pointfreq];[period]'
1866    drw.check_arguments(fname,values,expectargs,';')
1867
1868    ncfiles = ncfilens.split(',')
1869    dimvname0 = values.split(';')[0]
1870    valuesaxis = values.split(';')[1]
1871    dimtit = values.split(';')[2].replace('|',' ')
1872    leglabels = values.split(';')[3].replace('_','\_')
1873    vartit = values.split(';')[4]
1874    title = values.split(';')[5].replace('|',' ')
1875    timevals = values.split(';')[6]
1876    locleg = int(values.split(';')[7])
1877    graphk = values.split(';')[8]
1878    lines0 = values.split(';')[9]
1879    collines0 = values.split(';')[10]
1880    points0 = values.split(';')[11]
1881    linewidths0 = values.split(';')[12]
1882    pointsizes0 = values.split(';')[13]
1883    pointfreq0 = values.split(';')[14]
1884    period = values.split(';')[15]
1885
1886    Nfiles = len(ncfiles)
1887
1888# Multiple variable-dimension names?
1889    if dimvname0.find(',') != -1:
1890        dimvname = dimvname0.split(',')
1891    else:
1892        dimvname = [dimvname0]
1893
1894# Multiple variables?
1895    if varname0.find(',') != -1:
1896        varname = varname0.split(',')
1897    else:
1898        varname = [varname0]
1899
1900# Multiple lines types?
1901    if lines0.find(',') != -1:
1902        lines = lines0.split(',')
1903    elif lines0 == 'None':
1904        lines = None
1905    else:
1906        lines = []
1907        for il in range(Nfiles):
1908            lines.append(lines0)
1909
1910# Multiple color names?
1911    if collines0.find(',') != -1:
1912        collines = collines0.split(',')
1913    elif collines0 == 'None':
1914        collines = None
1915    else:
1916        collines = []
1917        for ip in range(Nfiles):
1918            collines.append(collines0)
1919
1920# Multiple point types?
1921    if points0.find(',') != -1:
1922        points = points0.split(',')
1923    elif points0 == 'None':
1924        points = None
1925    else:
1926        points = []
1927        for ip in range(Nfiles):
1928            points.append(points0)
1929
1930# Multiple line sizes?
1931    if linewidths0.find(',') != -1:
1932        linewidths = []
1933        Nlines = len(linewidths0.split(','))
1934        for il in Nlines:
1935          linewidths.append(np.float(linewidths0.split(',')[il]))
1936    elif linewidths0 == 'None':
1937        linewidths = None
1938    else:
1939        linewidths = [np.float(linewidths0)]
1940
1941# Multiple point sizes?
1942    if pointsizes0.find(',') != -1:
1943        pointsizes = []
1944        Npts = len(pointsizes0.split(','))
1945        for ip in Npts:
1946          pointsizes.append(np.float(pointsizes0.split(',')[ip]))
1947    elif pointsizes0 == 'None':
1948        pointsizes = None
1949    else:
1950        pointsizes = [np.float(pointsizes0)]
1951
1952# Getting values
1953##
1954    varvalues = []
1955    dimvalues = []
1956    timvalues = []
1957    timvals0 = timvalues
1958
1959    print '  ' + fname
1960    ifn = 0
1961    mintval = 1.e20
1962    maxtval = -1.e20
1963
1964    for ifile in ncfiles:
1965        filen = ifile.split('@')[0]
1966
1967        print '    filen:',filen
1968
1969        if not os.path.isfile(filen):
1970            print errormsg
1971            print '  ' + fname + ": netCDF file '" + filen + "' does not exist !!"
1972            quit(-1)
1973
1974        objfile = NetCDFFile(filen, 'r')
1975
1976        founddvar = False
1977        for dvar in dimvname:
1978            if objfile.variables.has_key(dvar):
1979                founddvar = True
1980                vdobj = objfile.variables[dvar]
1981                if len(vdobj.shape) != 1:
1982                    print errormsg
1983                    print '  ' + fname + ': wrong shape:',vdobj.shape," of " +       \
1984                      "variable '" + dvar +  "' !!"
1985                    quit(-1)
1986                break
1987        if not founddvar:
1988            print errormsg
1989            print '  ' + fname + ": netCDF file '" + filen +                         \
1990            "' has any variable '", dimvname, "' !!"
1991            quit(-1)
1992
1993        foundvar = False
1994        for var in varname:
1995            if objfile.variables.has_key(var):
1996                foundvar = True
1997                vvobj = objfile.variables[var]
1998                if len(vvobj.shape) != 1:
1999                    print errormsg
2000                    print '  ' + fname + ': wrong shape:',vvobj.shape," of " +       \
2001                      "variable '" + var +  "' !!"
2002                    quit(-1)
2003
2004                break
2005        if not foundvar:
2006            print errormsg
2007            print '  ' + fname + ": netCDF file '" + filen +                         \
2008              "' has any variable '", varname, "' !!"
2009            quit(-1)
2010
2011
2012# Getting period
2013        dimt = len(vdobj[:])
2014
2015        if period == '-1':
2016            varvalues.append(vvobj[:])
2017            dimvalues.append(vdobj[:])
2018            mindvals = np.min(vdobj[:])
2019            maxdvals = np.max(vdobj[:])
2020        else:
2021            ibeg=-1
2022            iend=-1
2023            tbeg = np.float(period.split(',')[0])
2024            tend = np.float(period.split(',')[1])
2025
2026            for it in range(dimt-1):
2027                if vdobj[it] <= tbeg and vdobj[it+1] > tbeg : ibeg = it
2028                if vdobj[it] <= tend and vdobj[it+1] > tend: iend = it + 1
2029                if ibeg != -1 and iend != -1: break
2030
2031            if ibeg == -1 and iend == -1:
2032                print errormsg
2033                print '  ' + fname + ': Period:',tbeg,',',tend,'not found!!'
2034                print '    ibeg:',ibeg,'iend:',iend
2035                print '    period in file:',np.min(vdobj[:]), np.max(vdobj[:])
2036                quit(-1)
2037            elif iend == -1:
2038                iend = dimt
2039                print warnmsg
2040                print '  ' + fname + ': end of Period:',tbeg,',',tend,'not found!!'
2041                print '    getting last available time instead'
2042                print '    ibeg:',ibeg,'iend:',iend
2043                print '    period in file:',np.min(vdobj[:]), np.max(vdobj[:])
2044            elif ibeg == -1:
2045                ibeg = 0
2046                print warnmsg
2047                print '  ' + fname + ': beginning of Period:',tbeg,',',tend,         \
2048                  'not found!!'
2049                print '    getting first available time instead'
2050                print '    ibeg:',ibeg,'iend:',iend
2051                print '    period in file:',np.min(vdobj[:]), np.max(vdobj[:])
2052
2053            varvalues.append(vvobj[ibeg:iend])
2054            dimvalues.append(vdobj[ibeg:iend])
2055            mindvals = np.min(vdobj[ibeg:iend])
2056            maxdvals = np.max(vdobj[ibeg:iend])
2057
2058            dimt = iend - ibeg
2059
2060        if mindvals < mintval: mintval = mindvals
2061        if maxdvals > maxtval: maxtval = maxdvals
2062
2063        if ifn == 0:
2064            varunits = drw.units_lunits(vvobj.units)
2065
2066        objfile.close()
2067
2068        ifn = ifn + 1
2069
2070# Times
2071    timename = timevals.split('|')[0]
2072    timeunit = timevals.split('|')[1].replace('!',' ')
2073    timekind = timevals.split('|')[2]
2074    timefmt = timevals.split('|')[3]
2075
2076    dtvals = (maxtval - mintval)/dimt
2077    tvals = np.arange(mintval, maxtval, dtvals/2.)
2078
2079    timepos, timelabels = drw.CFtimes_plot(tvals, timeunit, timekind, timefmt)
2080
2081    if leglabels != 'None':
2082        legvals = leglabels.split(',')
2083    else:
2084        legvals = None
2085
2086    if pointfreq0 == 'all':
2087        pointfreq = None
2088    else:
2089        pointfreq = int(pointfreq0)
2090
2091    drw.plot_lines_time(dimvalues, varvalues, valuesaxis, dimtit, legvals, vartit,   \
2092      varunits, timepos, timelabels, title, locleg, graphk, lines, collines, points, \
2093      linewidths, pointsizes, pointfreq)
2094
2095    return
2096
2097def draw_Neighbourghood_evol(filen, values, variable):
2098    """ Function to draw the temporal evolution of a neighbourghood around a point
2099    draw_Neighbourghood_evol(filen, values, variable)
2100      filen= netCDF file name
2101      values= [gvarname]:[dimsval]:[neigdims]:[Nneig]:[Ncol]:[timetits]:[tkinds]:
2102       [timefmts]:[gtitle]:[shadxtrms]:[cbar]:[gkind]:[ofile]
2103        [dimsval]: [dimn1]|[val1]|[dimv1],...,[dimnN]|[valN]|[dimvN] dimension names, values to get
2104          (-1, for all; no name/value pair given full length) and variable with values of the dimension
2105          NOTE: when dimsval[X,Y] == neigdims[X,Y], valX,valY --> valX,valY-Nneig/2, valX,valY+Nneig/2
2106        [neigdims]: [dimnX],[dimnY] dimensions mnames along which the neigbourghood should be defined
2107        [Nneig]: Number of grid points of the full side of the box (odd value)
2108        [Ncol]: Number of columns ('auto': square final plot)
2109        [gvarname]: name of the variable to appear in the graph
2110        [timetits]: [titX],[titY] titles of the axes ('|' for spaces)
2111        [tkinds]: [tkindX]|[tkindY] kinds of time to appear in the graph
2112          'Nval': according to a given number of values as 'Nval',[Nval]
2113          'exct': according to an exact time unit as 'exct',[tunit];
2114            tunit= [Nunits],[tu]; [tu]= 'c': centuries, 'y': year, 'm': month,
2115              'w': week, 'd': day, 'h': hour, 'i': minute, 's': second,
2116              'l': milisecond
2117        [timefmts]: [tfmtX],[tfmtY] format of the time labels
2118        [gtitle]: title of the graphic ('|' for spaces)
2119        [shadxtrms]: Extremes for the shading
2120        [cbar]: colorbar to use
2121        [gkind]: kind of graphical output
2122        [ofile]: True/False whether the netcdf with data should be created or not
2123      variable= name of the variable
2124      values = 'q:Time|-1|Times,bottom_top|6|ZNU,south_north|3|XLAT,west_east|26|XLONG:south_north,west_east:5:auto:time|($[DD]^{[HH]}$),time|($[DD]^{[HH]}$):exct,2,h|exct,1,d:$%d^{%H}$,$%d^{%H}$:5|pts|neighbourghood|temporal|evolution:0.0,0.004:BuPu:pdf:True'
2125    """ 
2126
2127    fname = 'draw_Neighbourghood_evol'
2128
2129    if values == 'h':
2130        print fname + '_____________________________________________________________'
2131        print draw_Neighbourghood_evol.__doc__
2132        quit()
2133
2134    expectargs = '[gvarname]:[dimsval]:[neigdims]:[Nneig]:[Ncol]:' +                 \
2135      '[timetits]:[tkinds]:[timefmts]:[gtitle]:[shadxtrms]:[cbar]:[gkind]:[ofile]'
2136 
2137    drw.check_arguments(fname,values,expectargs,':')
2138
2139    gvarname = values.split(':')[0]
2140    dimsval = values.split(':')[1].split(',')
2141    neigdims = values.split(':')[2].split(',')
2142    Nneig = int(values.split(':')[3])
2143    Ncol0 = values.split(':')[4]
2144    timetits = values.split(':')[5].split(',')
2145    timekinds = values.split(':')[6].split('|')
2146    timefmts = values.split(':')[7].split(',')
2147    gtitle = values.split(':')[8].replace('|',' ')
2148    shadxtrms = values.split(':')[9].split(',')
2149    cbar = values.split(':')[10]
2150    gkind = values.split(':')[11]
2151    ofile = values.split(':')[12]
2152
2153    if Ncol0 != 'auto': 
2154        Ncol = int(Ncol0)
2155    else:
2156        Ncol = Ncol0
2157
2158    timetits[0] = timetits[0].replace('|',' ')
2159    timetits[1] = timetits[1].replace('|',' ')
2160
2161    if np.mod(Nneig,2) == 0:
2162        print errormsg
2163        print '  ' + fname + ": an odd value for 'Nneig':",Nneig,'is required !!!'
2164        quit(-1)
2165
2166    Nneig2 = int(Nneig/2)
2167
2168# Values to slice the variable
2169    dimvslice = {}
2170    dimvvalues = {}
2171    for dimvs in dimsval:
2172        dimn = dimvs.split('|')[0]
2173        dimv = int(dimvs.split('|')[1])
2174        dimnv = dimvs.split('|')[2]
2175
2176        dimvvalues[dimn] = dimnv
2177        dimvslice[dimn] = dimv
2178
2179    ncobj = NetCDFFile(filen, 'r')
2180
2181    varobj = ncobj.variables[variable]
2182
2183    slicevar = []
2184    newdimn = []
2185    newdimsvar = {}
2186
2187    for dimn in varobj.dimensions:
2188        if not drw.searchInlist(dimvslice.keys(), dimn):
2189            dimsize = len(ncobj.dimensions[dimn])
2190            slicevar.append(slice(0, dimsize+1))
2191            newdimn.append(dimn)
2192            newdimsvar[dimn] = dimseize
2193
2194        for dimslicen in dimvslice.keys():
2195            if dimn == dimslicen:
2196                if dimvslice[dimn] != -1:
2197                    if drw.searchInlist(neigdims, dimn):
2198                        slicevar.append(slice(dimvslice[dimn]-Nneig2,                \
2199                          dimvslice[dimn]+Nneig2+1))
2200                        newdimn.append(dimn)
2201                        newdimsvar[dimn] = Nneig
2202                        break
2203                    else:
2204                        slicevar.append(slice(dimvslice[dimn], dimvslice[dimn]+1))
2205                        break
2206                else:
2207                    dimsize = len(ncobj.dimensions[dimn])
2208                    slicevar.append(slice(0, dimsize+1))
2209                    newdimn.append(dimn)
2210                    newdimsvar[dimn] = dimsize
2211                    break
2212 
2213    varv = varobj[tuple(slicevar)]
2214
2215    if len(newdimn) != 3:
2216        print errormsg
2217        print '  ' + fname + ': sliced variable with shape=', varv.shape,            \
2218          ' must have three dimensions',len(varv.shape),'given !!'
2219        quit(-1)
2220
2221    newdims = []
2222    for nwdims in newdimn:
2223        newdims.append(newdimsvar[nwdims])
2224
2225# The dimension which is not in the neighbourhood dimensions must be time!
2226    for dim1 in newdimn:
2227        if not drw.searchInlist(neigdims, dim1):
2228            dimt = newdimsvar[dim1]
2229            dimtime = dim1
2230
2231    if Ncol == 'auto':
2232        dimtsqx = int(np.sqrt(dimt)) + 1
2233        dimtsqy = int(np.sqrt(dimt)) + 1
2234    else:
2235        dimtsqx = int(Ncol)
2236        dimtsqy = dimt/dimtsqx + 1
2237
2238    neighbourghood = np.ones((dimtsqy*Nneig,dimtsqx*Nneig), dtype=np.float)*fillValue
2239
2240    for it in range(dimt):
2241        ity = int(it/dimtsqx)
2242        itx = it-ity*dimtsqx
2243
2244        itty = (dimtsqy - ity - 1)*Nneig + Nneig2
2245        ittx = itx*Nneig + Nneig2
2246
2247        neighbourghood[itty-Nneig2:itty+Nneig2+1,ittx-Nneig2:ittx+Nneig2+1]=         \
2248          varv[it,::-1,:]
2249
2250    variablevals = drw.variables_values(variable)
2251    if drw.searchInlist(varobj.ncattrs(), 'units'):
2252        vunits = varobj.units
2253    else:
2254        vunits = variablevals[5]
2255
2256# Time values at the X/Y axes
2257    if ncobj.variables[dimvvalues[dimtime]].dtype == '|S1':
2258        print '    ' + fname + ': WRF time variable!'
2259        refdate = '19491201000000'
2260        tunitsval = 'hours'
2261        dimtvalues = np.zeros((dimt), dtype=np.float)
2262        tvals = ncobj.variables[dimvvalues[dimtime]]
2263        yrref=refdate[0:4]
2264        monref=refdate[4:6]
2265        dayref=refdate[6:8]
2266        horref=refdate[8:10]
2267        minref=refdate[10:12]
2268        secref=refdate[12:14]
2269
2270        refdateS = yrref + '/' + monref + '/' + dayref + '_' + horref + ':' +        \
2271          minref + ':' + secref
2272        tunits = tunitsval + ' since ' + refdateS
2273        for it in range(dimt):
2274            wrfdates = drw.datetimeStr_conversion(tvals[it,:],'WRFdatetime', 'matYmdHMS')
2275            dimtvalues[it] = drw.realdatetime1_CFcompilant(wrfdates, refdate, tunitsval)
2276    else:
2277        dimtvalues = ncobj.variables[dimvvalues[dimtime]][:]
2278        tunits = ncobj.variables[newdimsvar[dimtime]].units
2279
2280    dimxv = dimtvalues[0:dimtsqx]
2281    dimyv = dimtvalues[0:dimt:dimtsqx]
2282
2283    dimn = ['time','time']
2284
2285    if ofile == 'True':
2286        ofilen = 'Neighbourghood_evol.nc'
2287        newnc = NetCDFFile(ofilen, 'w')
2288# Dimensions
2289        newdim = newnc.createDimension('time',None)
2290        newdim = newnc.createDimension('y',dimtsqy*Nneig)
2291        newdim = newnc.createDimension('x',dimtsqx*Nneig)
2292# Dimension values
2293        newvar = newnc.createVariable('time','f8',('time'))
2294        newvar[:] = np.arange(dimt)
2295        newattr = drw.basicvardef(newvar, 'time','time',tunits)
2296# Neighbourhghood variable
2297        newvar = newnc.createVariable(variable + 'neigevol', 'f4', ('y','x'),        \
2298          fill_value=fillValue)
2299        newvar[:] = neighbourghood
2300
2301        newnc.sync()
2302        newnc.close()
2303        print fname + ": Successfull generation of file '" + ofilen + "' !!"
2304
2305# Time ticks
2306    timeposX, timelabelsX = drw.CFtimes_plot(dimxv, tunits, timekinds[0], timefmts[0])
2307    timeposY, timelabelsY = drw.CFtimes_plot(dimyv, tunits, timekinds[1], timefmts[1])
2308
2309    timepos = [timeposX[0:len(timeposX)], timeposY[len(timeposY):0:-1]]
2310    timelabels = [timelabelsX[0:len(timeposX)], timelabelsY[0:len(timeposY)]]
2311
2312    for i in range(2):
2313        if shadxtrms[i][0:1] != 'S':
2314            shadxtrms[i] = np.float(shadxtrms[i])
2315
2316    drw.plot_Neighbourghood_evol(neighbourghood, dimxv, dimyv, gvarname, timetits,   \
2317      timepos, timelabels, cbar, Nneig, shadxtrms, vunits, gtitle, gkind, True)
2318
2319def draw_points(filen, values):
2320    """ Function to plot a series of points
2321      [values]= [ptasciifile]:[gtit]:[mapvalues]:[kindfigure]:[pointcolor]:[pointlabels]:
2322        [locleg]:[figureko]:[figuren]
2323        [ptasciifile]:[file],[comchar],[collon],[collat],[lab]
2324          [file]: column ASCII file with the location of the points
2325          [comchar]: '|' list of characters for commentaries
2326          [collon]: number of column with the longitude of the points
2327          [collat]: number of column with the latitude of the points
2328          [collab]: number of column with the labels of the points ('None', and will get
2329            the values from the [pointlabels] variable
2330        [gtit]: title of the figure ('|' for spaces)
2331        [mapvalues]: drawing coastaline ([proj],[res]) or None
2332          [proj]: projection
2333             * 'cyl', cilindric
2334             * 'lcc', lambert conformal
2335          [res]: resolution:
2336             * 'c', crude
2337             * 'l', low
2338             * 'i', intermediate
2339             * 'h', high
2340             * 'f', full
2341        [kindfigure]: kind of figure
2342          'legend': only points in the map with the legend with the names
2343          'labelled',[txtsize],[txtcol]: points with the names and size, color of text
2344        [pointcolor]: color for the points ('auto' for "red")
2345        [pointlabels]: ',' of labels [only used if [collab]='None'] ('None' for no labels)
2346        [locleg]: location of the legend (0, autmoatic)
2347          1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
2348          5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
2349          9: 'upper center', 10: 'center'
2350        [figureko]: kind of the output file (pdf, png, ...)
2351        [figuren]: name of the figure
2352      [filen]= [ncfile],[lonvarn],[latvarn][,[varn],[dimvals],[vargn],[min],[max],[cbar],[varu]]
2353        [ncfile]: netCDF to use to geolocalize the points
2354        [lonvarn]: name of the variable with the longitudes
2355        [latvarn]: name of the variable with the latitudes
2356        [varn]: optional variable to add staff into the graph
2357        [dimval]: '@' list of [dimn]|[dimval] to get the values for [varn]
2358          [dimn]: name of the dimension
2359          [dimval]: value of the dimension (no value all range)
2360        [vargn]: name of the variable in the graph
2361        [min]: minimum value for the extra variable
2362        [max]: maximum value for the extra variable
2363        [cbar]: color bar
2364        [varu]: units of the variable
2365    """
2366    fname = 'draw_points'
2367
2368    if values == 'h':
2369        print fname + '_____________________________________________________________'
2370        print draw_points.__doc__
2371        quit()
2372
2373    expectargs = '[ptasciifile]:[gtit]:[mapvalues]:[kindfigure]:[pointcolor]:' +     \
2374      '[pointlabels]:[locleg]:[figurek]:[figuren]'
2375 
2376    drw.check_arguments(fname,values,expectargs,':')
2377
2378    ptasciifile = values.split(':')[0]
2379    gtit = values.split(':')[1]
2380    mapvalues = values.split(':')[2]
2381    kindfigure = values.split(':')[3]
2382    pointcolor = values.split(':')[4]
2383    pointlabels = values.split(':')[5]
2384    locleg = int(values.split(':')[6])
2385    figureko = values.split(':')[7]
2386    figuren = values.split(':')[8]
2387
2388# Getting station locations
2389##
2390    filev = ptasciifile.split(',')[0]
2391    comchar = ptasciifile.split(',')[1].split('|')
2392    collon = int(ptasciifile.split(',')[2])
2393    collat = int(ptasciifile.split(',')[3])
2394    collab = ptasciifile.split(',')[4]
2395
2396    if not os.path.isfile(filev):
2397        print errormsg
2398        print '  ' + fname + ": file '" + filev + "' does not exist!!"
2399        quit(-1)
2400
2401# Getting points position and labels
2402    oascii = open(filev, 'r')
2403    xptval = []
2404    yptval = []
2405    if collab != 'None':
2406        ptlabels = []
2407        for line in oascii:
2408            if not drw.searchInlist(comchar, line[0:1]):
2409                linevals = drw.reduce_spaces(line)
2410                xptval.append(np.float(linevals[collon].replace('\n','')))
2411                yptval.append(np.float(linevals[collat].replace('\n','')))
2412                ptlabels.append(linevals[int(collab)].replace('\n',''))
2413    else:
2414        ptlabels = None
2415        for line in oascii:
2416            if  not drw.searchInlist(comchar, line[0:1]):
2417                linevals = drw.reduce_spaces(line)
2418                xptval.append(np.float(linevals[collon].replace('\n','')))
2419                yptval.append(np.float(linevals[collat].replace('\n','')))
2420
2421    oascii.close()
2422
2423    if pointlabels != 'None' and collab == 'None':
2424        ptlabels = pointlabels.split(',')
2425
2426# Getting localization of the points
2427##
2428    filev = filen.split(',')
2429    Nvals = len(filev)
2430
2431    ncfile = filev[0]
2432    lonvarn = filev[1]
2433    latvarn = filev[2]
2434    varn = None
2435    varextrav = None
2436    if Nvals == 10:
2437        varn = filev[3]
2438        dimvals = filev[4]
2439        varextrav = [filev[5], np.float(filev[6]), np.float(filev[7]), filev[8],     \
2440          filev[9]]
2441   
2442    if not os.path.isfile(ncfile):
2443        print errormsg
2444        print '  ' + fname + ": file '" + ncfile + "' does not exist!!"
2445        quit(-1)
2446
2447    onc = NetCDFFile(ncfile, 'r')
2448   
2449    lonv, latv = drw.lonlat2D(onc.variables[lonvarn], onc.variables[latvarn])
2450
2451    if varn is not None:
2452        objextra = onc.variables[varn]
2453        vard = objextra.dimensions
2454        dd = {}
2455        for dn in dimvals.split('@'):
2456            ddn = dn.split('|')[0]
2457            ddv = dn.split('|')[1]
2458            dd[ddn] = ddv
2459        slicevar = []
2460        for dv in vard:
2461            found= False
2462            for dn in dd.keys():
2463                if dn == dv:
2464                    slicevar.append(int(dd[dn]))
2465                    found = True
2466                    break
2467            if not found:
2468                slicevar.append(slice(0,len(onc.dimensions[dv])))
2469
2470        varextra = np.squeeze(objextra[tuple(slicevar)])
2471
2472    if mapvalues == 'None':
2473        mapV = None
2474    else:
2475        mapV = mapvalues
2476
2477    drw.plot_points(xptval, yptval, lonv, latv, varextra, varextrav, gtit, mapV,     \
2478      kindfigure, pointcolor, ptlabels, locleg, figureko, figuren)
2479
2480    onc.close()
2481
2482    return
2483
2484def draw_points_lonlat(filen, values):
2485    """ Function to plot a series of lon/lat points
2486     filen= name of the file
2487     values= [lonvarname]:[latvarname]:[gkind]:[gtit]:[ptcolor]:[pttype]:[ptsize]:[labels]:[locleg]:[figureK]
2488       [lonvarname]: name of the variable longitude
2489       [latvarname]: name of the variable latitude
2490       [gkind]: kind of graphical output
2491       [gtit]: graphic title '!' for spaces
2492       [ptcolor]: color of the points ('auto', for "red")
2493       [pttype]: type of point
2494       [ptsize]: size of point
2495       [labels]: ',' list of labels to use
2496       [locleg]: location of the legend (0, automatic)
2497         1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
2498         5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
2499         9: 'upper center', 10: 'center'
2500       [figureK]= kind of figure
2501         'legend': only points in the map with the legend with the names
2502         'labelled',[txtsize],[txtcol]: points with the names and size, color of text
2503    """
2504    fname = 'draw_points_lonlat'
2505
2506    if values == 'h':
2507        print fname + '_____________________________________________________________'
2508        print draw_points_lonlat.__doc__
2509        quit()
2510
2511    expectargs = '[lonvarname]:[latvarname]:[gkind]:[gtit]:[ptcolor]:[pttype]:' +    \
2512      '[ptsize]:[labels]:[locleg]:[figureK]'
2513 
2514    drw.check_arguments(fname,values,expectargs,':')
2515
2516    lonname = values.split(':')[0]
2517    latname = values.split(':')[1]
2518    kindfigure = values.split(':')[2]
2519    gtit = values.split(':')[3].replace('!',' ')
2520    pointcolor = values.split(':')[4]
2521    pointtype = values.split(':')[5]
2522    pointsize = np.float(values.split(':')[6])
2523    labelsv = values.split(':')[7]
2524    loclegend = values.split(':')[8]
2525    figureK = values.split(':')[9]
2526
2527    fname = 'points_lonlat'
2528
2529    onc = NetCDFFile(filen, 'r')
2530    if not onc.variables.has_key(lonname):
2531        print errormsg
2532        print fname + ": file '" + filen + "' does not have longitudes '" + lonname +\
2533          "' !!"
2534        quit(-1)
2535    if not onc.variables.has_key(lonname):
2536        print errormsg
2537        print fname + ": file '" + filen + "' does not have longitudes '" + lonname +\
2538          "' !!"
2539        quit(-1)
2540   
2541    olon = onc.variables[lonname]
2542    olat = onc.variables[latname]
2543
2544    Ndimlon = len(olon.shape)
2545    if Ndimlon == 1:
2546        dx = olon.shape[0]
2547        dy = olat.shape[0]
2548        if dx == dy: 
2549            lonvals = olon[:]
2550            latvals = olat[:]
2551        else: 
2552            lonvals0 = np.zeros((dy,dx), dtype=np.float)
2553            latvals0 = np.zeros((dy,dx), dtype=np.float)
2554            for iL in range(dy):
2555                lonvals0[iL,:] = olon[:]
2556            for il in range(dx):
2557                latvals0[:,il] = olat[:]
2558            lonvals = lonvals0.flatten()
2559            latvals = latvals0.flatten()
2560
2561    elif Ndimlon == 2:
2562        lonvals = olon[:].flatten()
2563        latvals = olat[:].flatten()
2564    elif Ndimlon == 3:
2565        lonvals = olon[1,:,:].flatten()
2566        latvals = olat[1,:,:].flatten()
2567# Playing for Anna
2568#        lonvals = olon[:].flatten()
2569#        latvals = olat[:].flatten()
2570    elif Ndimlon == 4:
2571        lonvals = olon[1,0,:,:].flatten()
2572        latvals = olat[1,0,:,:].flatten()
2573    else:
2574        print errormsg
2575        print '  ' + fname + ': longitude size:',len(olon),' not ready!!'
2576        quit(-1)
2577
2578    if labelsv == 'None':
2579        labels = None
2580    else:
2581        labels = labelsv.split(',')
2582
2583    drw.plot_list_points(lonvals, latvals, lonname, latname, gtit, figureK, pointcolor, pointtype,    \
2584      pointsize, labels, loclegend, kindfigure, fname)
2585
2586    onc.close()
2587
2588    return
2589
2590def draw_timeSeries(filen, values, variables):
2591    """ Function to draw a time-series
2592    draw_timeSeries(filen, values, variable):
2593      filen= name of the file
2594      values= [gvarname]:[timetit]:[tkind]:[timefmt]:[title]:[locleg]:[gkind]:[colorlines]:[pointtype]:[pointfreq]
2595      [gvarname]: name of the variable to appear in the graph
2596      [timetit]: title of the time axis (assumed x-axis, '|' for spaces)
2597      [tkind]: kind of time to appear in the graph (assumed x-axis)
2598        'Nval': according to a given number of values as 'Nval',[Nval]
2599        'exct': according to an exact time unit as 'exct',[tunit];
2600          tunit= [Nunits],[tu]; [tu]= 'c': centuries, 'y': year, 'm': month,
2601            'w': week, 'd': day, 'h': hour, 'i': minute, 's': second,
2602            'l': milisecond
2603      [timefmt]: format of the time labels
2604      [title]: title of the graphic ('|' for spaces)
2605      [locleg]: location of the legend (0, automatic)
2606        1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
2607        5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
2608        9: 'upper center', 10: 'center'
2609      [gkind]: kind of graphical output
2610      [colorlines]: ',' list of colors for the lines, None for automatic, single
2611          value all the same
2612      [pointtype]: ',' list of type of points for the lines, None for automatic, single
2613          value all the same
2614      [pointfreq]: frequency of point plotting, 'all' for all time steps
2615      variables= [varname],[timename] names of variable and variable with times
2616      draw_timeSeries('wrfout_d01_1979-12-01_00:00:00_bottom_top_B6-E6-I1_south_north_B3-E3-I1_west_east_B26-E26-I1.nc', 'dt_con:time|($[DD]^{[HH]}$):exct,12,h:$%d^{%H}$:time|evolution|at|-1|6|3|26:1:pdf', 'LDQCON,time')
2617    """
2618
2619    fname = 'draw_timeSeries'
2620
2621    if values == 'h':
2622        print fname + '_____________________________________________________________'
2623        print draw_timeSeries.__doc__
2624        quit()
2625
2626    expectargs = '[gvarname]:[timetit]:[tkind]:[timefmt]:[title]:' +                 \
2627      '[locleg]:[gkind]:[colorlines]:[pointtype]:[pointfreq]'
2628 
2629    drw.check_arguments(fname,values,expectargs,':')
2630
2631    gvarname = values.split(':')[0]
2632    timetit = values.split(':')[1].replace('|',' ')
2633    tkind = values.split(':')[2]
2634    timefmt = values.split(':')[3]
2635    title = values.split(':')[4].replace('|',' ')
2636    locleg = int(values.split(':')[5])
2637    gkind = values.split(':')[6]
2638    colorlines = values.split(':')[7]
2639    pointtype = values.split(':')[8]
2640    pointfreq0 = values.split(':')[9]
2641   
2642    ncobj = NetCDFFile(filen, 'r')
2643
2644    variable = variables.split(',')[0]
2645    timevar = variables.split(',')[1]
2646
2647    if not ncobj.variables.has_key(variable):
2648        print errormsg
2649        print '  ' + fname + ": file '" +  filen + "' does not have variable '" +    \
2650          variable + "' !!"
2651        quit(-1)
2652
2653    if not ncobj.variables.has_key(timevar):
2654        print errormsg
2655        print '  ' + fname + ": file '" +  filen + "' does not have variable time '" \
2656          + timevar + "' !!"
2657        quit(-1)
2658
2659    varobj = ncobj.variables[variable]
2660    timeobj = ncobj.variables[timevar]
2661
2662    dimt = len(timeobj[:])
2663    varvals = np.zeros((2,dimt), dtype=np.float)
2664
2665    gunits = varobj.getncattr('units')
2666    tunits = timeobj.getncattr('units')
2667
2668    varvals[0,:], valpot, newgunits, Spot = drw.pot_values(varobj[:].flatten(), gunits)
2669    varvals[1,:] = timeobj[:]
2670
2671    tseriesvals = []
2672    tseriesvals.append(varvals)
2673
2674    if colorlines == 'None': 
2675        collines = None
2676    else:
2677        collines = colorlines.split(',')
2678    if pointtype == 'None': 
2679        pttype = None
2680    else:
2681        pttype = pointtype.split(',')
2682
2683    if pointfreq0 == 'all':
2684        pointfreq = None
2685    else:
2686        pointfreq = int(pointfreq0)
2687
2688    drw.plot_TimeSeries(tseriesvals, Spot + drw.units_lunits(gunits), tunits,        \
2689      'TimeSeries', gvarname, timetit, tkind, timefmt, title,                        \
2690      gvarname.replace('_','\_'), locleg, gkind, collines, pttype, pointfreq)
2691
2692    return
2693
2694#draw_timeSeries('wrfout_d01_1979-12-01_00:00:00_bottom_top_B6-E6-I1_south_north_B3-E3-I1_west_east_B26-E26-I1.nc', 'dt_con:time|($[DD]^{[HH]}$):exct,12,h:$%d^{%H}$:time|evolution|at|-1|6|3|26:1:pdf:None:None', 'LDQCON,time')
2695
2696def draw_trajectories(trjfilens, values, observations):
2697    """ Function to draw different trajectories at the same time
2698    draw_trajectories(trjfilens, values, observations):
2699      trjfilens= [filen]@[Tint]@[map] ',' separated list of files with trajectories,
2700         time intervals and reference maps (first one will be used to plot)
2701        [filen]: name of the file to use (lines with '#', not readed) as:
2702          [t-step] [x] [y]
2703        [Tint]: interval of time as [Tbeg]@[Tend] or -1 for all the interval
2704        [map]: [file]#[lonname]#[latname]
2705          [file]; with the [lon],[lat] matrices
2706          [lonname],[latname]; names of the longitudes and latitudes variables
2707      values=[leglabels]|[lonlatlims]|[title]|[graphk]|[mapkind]
2708        [leglabels]: ',' separated list of names for the legend
2709        [lonlatlims]: ',' list of limits of the map [lonmin, latmin, lonmax, latmax] or None
2710        [title]: title of the plot ('!' for spaces)
2711        [graphk]: kind of the graphic
2712        [mapkind]: drawing coastaline ([proj],[res]) or None
2713          [proj]: projection
2714             * 'cyl', cilindric
2715             * 'lcc', lambert conformal
2716          [res]: resolution:
2717             * 'c', crude
2718             * 'l', low
2719             * 'i', intermediate
2720             * 'h', high
2721             * 'f', full
2722      obsevations= [obsfile],[obsname],[Tint],[null]
2723        [obsfile]: name fo the File with the observations as [t-step] [lat] [lon]
2724        [obsname]: name of the observations in the graph
2725        [Tint]: interval of time as [Tbeg]@[Tend] or -1 for all the interval
2726        [null]: null value for the observed trajectory
2727    """
2728
2729    fname = 'draw_trajectories'
2730
2731    if values == 'h':
2732        print fname + '_____________________________________________________________'
2733        print draw_trajectories.__doc__
2734        quit()
2735
2736    expectargs = '[leglabels]|[lonlatlims]|[title]|[graphk]|[mapkind]'
2737 
2738    drw.check_arguments(fname,values,expectargs,'|')
2739
2740    trjfiles = trjfilens.split(',')
2741    leglabels = values.split('|')[0]
2742    lonlatlims = values.split('|')[1]
2743    title = values.split('|')[2].replace('!',' ')
2744    graphk = values.split('|')[3]
2745    mapkind = values.split('|')[4]
2746
2747    Nfiles = len(trjfiles)
2748
2749# Getting trajectotries
2750##
2751
2752    lontrjvalues = []
2753    lattrjvalues = []
2754
2755    print '  ' + fname
2756    ifn = 0
2757    for ifile in trjfiles:
2758        filen = ifile.split('@')[0]
2759        Tint = ifile.split('@')[1]
2760
2761        print '    trajectory:',filen
2762
2763        if Tint != '-1':
2764            Tbeg = Tint
2765            Tend = ifile.split('@')[2]
2766            mapv = ifile.split('@')[3]
2767        else:
2768            mapv = ifile.split('@')[2]
2769
2770        if not os.path.isfile(filen):
2771            print errormsg
2772            print '  ' + fname + ": trajectory file '" + filen + "' does not exist !!"
2773            quit(-1)
2774
2775# Charging longitude and latitude values
2776##
2777        lonvals, latvals = drw.lonlat_values(mapv.split('#')[0], mapv.split('#')[1], \
2778          mapv.split('#')[2])
2779
2780        if ifn == 0: mapref = mapv
2781        ifn = ifn + 1
2782
2783        objfile = open(filen, 'r')
2784        trjtimev = []
2785        trjxv = []
2786        trjyv = []
2787
2788        for line in objfile:
2789            if line[0:1] != '#':
2790                trjtimev.append(int(line.split(' ')[0]))
2791                trjxv.append(int(line.split(' ')[1]))
2792                trjyv.append(int(line.split(' ')[2]))
2793
2794        objfile.close()
2795
2796        if Tint != '-1':
2797            lontrjvalues.append(lonvals[trjyv[Tint:Tend+1], trjxv[Tint:Tend+1]])
2798            lattrjvalues.append(latvals[trjyv[Tint:Tend+1], trjxv[Tint:Tend+1]])
2799        else:
2800            lontrjvalues.append(lonvals[trjyv[:], trjxv[:]])
2801            lattrjvalues.append(latvals[trjyv[:], trjxv[:]])
2802
2803# lonlatlimits
2804##
2805
2806    if lonlatlims == 'None':
2807        lonlatlimsv = None
2808    else:
2809        lonlatlimsv = np.zeros((4), dtype=np.float)
2810        lonlatlimsv[0] = np.float(lonlatlims.split(',')[0])
2811        lonlatlimsv[1] = np.float(lonlatlims.split(',')[1])
2812        lonlatlimsv[2] = np.float(lonlatlims.split(',')[2])
2813        lonlatlimsv[3] = np.float(lonlatlims.split(',')[3])
2814
2815# lon/lat objects
2816##
2817    objnc = NetCDFFile(mapref.split('#')[0])
2818    lonobj = objnc.variables[mapref.split('#')[1]]
2819    latobj = objnc.variables[mapref.split('#')[2]]
2820
2821# map
2822##
2823    if mapkind == 'None':
2824        mapkindv = None
2825    else:
2826        mapkindv = mapkind
2827
2828    if observations is None:
2829        obsname = None
2830    else:
2831        obsfile = observations.split(',')[0]
2832        obsname = observations.split(',')[1]
2833        Tint = observations.split(',')[2]
2834        null = np.float(observations.split(',')[3])
2835        print '    observational trajectory:',obsfile
2836
2837        if not os.path.isfile(obsfile):
2838            print errormsg
2839            print '  ' + fname + ": observations trajectory file '" + obsfile +      \
2840              "' does not exist !!"
2841            quit(-1)
2842
2843        objfile = open(obsfile, 'r')
2844        obstrjtimev = []
2845        obstrjxv = []
2846        obstrjyv = []
2847
2848        for line in objfile:
2849            if line[0:1] != '#':
2850                lon = np.float(line.split(' ')[2])
2851                lat = np.float(line.split(' ')[1])
2852                if not lon == null and not lat == null:
2853                    obstrjtimev.append(int(line.split(' ')[0]))
2854                    obstrjxv.append(lon)
2855                    obstrjyv.append(lat)
2856                else:
2857                    obstrjtimev.append(int(line.split(' ')[0]))
2858                    obstrjxv.append(None)
2859                    obstrjyv.append(None)
2860
2861        objfile.close()
2862
2863        if Tint != '-1':
2864            Tint = int(observations.split(',')[2].split('@')[0])
2865            Tend = int(observations.split(',')[2].split('@')[1])
2866            lontrjvalues.append(obstrjxv[Tint:Tend+1])
2867            lattrjvalues.append(obstrjyv[Tint:Tend+1])
2868        else:
2869            lontrjvalues.append(obstrjxv[:])
2870            lattrjvalues.append(obstrjyv[:])
2871
2872    drw.plot_Trajectories(lontrjvalues, lattrjvalues, leglabels.split(','),          \
2873      lonobj, latobj, lonlatlimsv, title, graphk, mapkindv, obsname)
2874
2875    objnc.close()
2876
2877    return
2878
2879def draw_vals_trajectories(ncfile, values, variable):
2880    """ Function to draw values from the outputs from 'compute_tevolboxtraj'
2881    draw_vals_trajectories(ncfile, values, variable)
2882    ncfile= [ncfile] ',' list of files to use
2883    values= [statisticskind]:[Tint]:[labels]@[locleg]:[gvarname]:[timetit]:[tkind]:[timefmt]:[title]:[gkind]
2884      [statisticskind]=[statistics][kind]
2885        [statistics]: which statistics to use, from: 'center', 'min', 'max', 'mean',
2886        'mean2', 'stdev'
2887        [kind]: 'box', 'circle' statistics taking the values from a box or a circle
2888        'trj': value following the trajectory
2889      [Tint]: [Tbeg]@[Tend] or None, interval of time to plot or -1 for all the times
2890      [labels]: ',' separated list of labels for the legend
2891      [locleg]: location of the legend (0, automatic)
2892        1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
2893        5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
2894        9: 'upper center', 10: 'center'
2895      [gvarname]: name of the variable to appear in the graph
2896      [timetit]: title of the time axis (assumed x-axis, '|' for spaces)
2897      [tkind]: kind of time to appear in the graph (assumed x-axis)
2898        'Nval': according to a given number of values as 'Nval',[Nval]
2899        'exct': according to an exact time unit as 'exct',[tunit];
2900          tunit= [Nunits],[tu]; [tu]= 'c': centuries, 'y': year, 'm': month,
2901            'w': week, 'd': day, 'h': hour, 'i': minute, 's': second,
2902            'l': milisecond
2903      [timefmt]: format of the time labels
2904      [title]: title of the graphic ('|' for spaces)
2905      [gkind]: kind of graphical output
2906    variable= variable to use
2907    """
2908
2909    fname = 'draw_vals_trajectories'
2910
2911    if values == 'h':
2912        print fname + '_____________________________________________________________'
2913        print draw_vals_trajectories.__doc__
2914        quit()
2915
2916    sims = ncfile.split(',')
2917
2918    if len(values.split(':')) != 9:
2919        print errormsg
2920        print '  ' + fname  + ': wrong number of values!', len(values.split(':')),   \
2921          'given 9 needed!!'
2922        print '    ',values.split(':')
2923        quit(-1)
2924
2925    statisticskind = values.split(':')[0]
2926    Tint = values.split(':')[1]
2927    labels = values.split(':')[2]
2928    gvarname = values.split(':')[3]
2929    timetit = values.split(':')[4].replace('|',' ')
2930    tkind = values.split(':')[5]
2931    timefmt = values.split(':')[6]
2932    title = values.split(':')[7].replace('|',' ')
2933    gkind = values.split(':')[8]
2934
2935    leglabels = labels.split('@')[0].split(',')
2936    locleg = int(labels.split('@')[1])
2937
2938    Nsims = len(sims)
2939
2940    if Tint != '-1':
2941        tini = np.float(Tint.split('@')[0])
2942        tend = np.float(Tint.split('@')[1])
2943    else:
2944        tini = -1.
2945        tend = -1.
2946
2947    vartimetrjv = []
2948
2949    print '  ' + fname
2950    for trjfile in sims:
2951        print '    ' + trjfile + ' ...'
2952        if not os.path.isfile(trjfile):
2953            print errormsg
2954            print '  ' + fname + ": trajectory file: '" + trjfile +                  \
2955              "' does not exist !!"
2956            quit(-1)
2957
2958        trjobj = NetCDFFile(trjfile, 'r')
2959        otim = trjobj.variables['time']
2960        if not trjobj.variables.has_key(statisticskind + '_' + variable):
2961            print errormsg
2962            print '  ' + fname + ": file '" + trjfile + "' does not have variable '"+\
2963              statisticskind + '_' + variable + "' !!"
2964            quit(-1)
2965        ovar = trjobj.variables[statisticskind + '_' + variable]
2966        dimt = otim.shape[0]
2967
2968        if trjfile == sims[0]:
2969            gunits = ovar.getncattr('units')
2970            lname = ovar.getncattr('long_name')
2971            tunits = otim.getncattr('units')
2972
2973        if tini != -1:
2974            tiniid = -1
2975            tendid = -1       
2976            for itv in range(dimt):
2977                if otim[itv] <= tini and otim[itv+1] >= tini: tiniid = itv
2978                if otim[itv] <= tend and otim[itv+1] >= tend: tendid = itv
2979
2980            if tiniid == -1 or tendid == -1:
2981                print errormsg
2982                print '  ' + main + ' time interval ', tini,',',tend,' not found: ',     \
2983                  tendid, ',', tiniid, ' !!'
2984                print '    data interval [',otim[0], otim[dimt-1],']'
2985                quit(-1)
2986            dimt = tendid - tiniid + 1
2987
2988        else:
2989            dimt = otim.shape[0]
2990
2991        valsv = np.zeros((2,dimt), dtype=np.float)
2992# Checking for time consistency
2993        if otim.getncattr('units') != tunits:
2994            print warnmsg
2995            print '  ' + fname + ': different time units in the plot!!'
2996            newtimes = drw.coincident_CFtimes(otim[:], tunits, otim.getncattr('units'))
2997        else:
2998            newtimes = otim[:]
2999
3000        if tini == -1:
3001            valsv[1,:] = newtimes[:]
3002            valsv[0,:] = ovar[:]
3003        else:
3004            valsv[1,:] = newtimes[tiniid:tendid+1]
3005            valsv[0,:] = ovar[tiniid:tendid+1]
3006
3007        vartimetrjv.append(valsv)
3008        trjobj.close()
3009
3010    drw.plot_TimeSeries(vartimetrjv, drw.units_lunits(gunits), tunits,               \
3011      'val_trajectories_' + statisticskind, gvarname, timetit, tkind, timefmt, title,\
3012      leglabels, locleg, gkind)
3013
3014def variable_values(values):
3015    """ Function to give back values for a given variable
3016      values= [varname] name of the variable
3017    """
3018
3019    fname = 'variable_values'
3020
3021    values = drw.variables_values(values)
3022
3023    print fname,'values:',values
3024    print fname,'variable_name:',values[0]
3025    print fname,'standard_name:',values[1]
3026    print fname,'min,max:',str(values[2]) + ',' + str(values[3])
3027    print fname,'long_name:',values[4]
3028    print fname,'units:',values[5]
3029    print fname,'shad_colors:',values[6]
3030    print fname,'all_values:',drw.numVector_String(values,',')
3031
3032    return
3033
3034def draw_ptZvals(ncfile, values, variable):
3035    """ Function to plot a given list of points and values
3036      ncfile= netCDF file to use
3037      values= [fvname]:[XYvar]:[pointype]:[pointsize]:[graphlimits]:[nxtype]:
3038        [figuretitle]:[colorbar]:[mapvalue]:[kindfig]
3039        fvname: name of the variable in the graph
3040        XYvar: [lon],[lat] variable names
3041        ptype: type of the point
3042        ptsize: size of the point
3043        graphlimits: minLON,minLAT,maxLON,maxLAT limits of the graph 'None' for the full size
3044        nxtype: minimum and maximum type
3045          'auto': values taken from the extrems of the data
3046          [min],[max]: given minimum and maximum values
3047        figtitle: title of the figure
3048        cbar: color bar
3049        mapv: map characteristics: [proj],[res]
3050          see full documentation: http://matplotlib.org/basemap/
3051          [proj]: projection
3052            * 'cyl', cilindric
3053            * 'lcc', lambert-conformal
3054          [res]: resolution:
3055            * 'c', crude
3056            * 'l', low
3057            * 'i', intermediate
3058            * 'h', high
3059            * 'f', full
3060        kfig: kind of figure
3061      variable= name of the variable to plot
3062    """
3063    fname = 'draw_ptZvals'
3064    import numpy.ma as ma
3065
3066    if values == 'h':
3067        print fname + '_____________________________________________________________'
3068        print draw_ptZvals.__doc__
3069        quit()
3070
3071    expectargs = '[fvname]:[XYvar]:[pointype]:[pointsize]:[graphlmits]:[nxtype]:' +  \
3072      '[figuretit]:[colorbar]:[mapvalue]:[kindfig]'
3073 
3074    drw.check_arguments(fname,values,expectargs,':')
3075
3076    fvname = values.split(':')[0]
3077    XYvar = values.split(':')[1]
3078    pointype = values.split(':')[2]
3079    pointsize = int(values.split(':')[3])
3080    graphlimits = values.split(':')[4]
3081    nxtype = values.split(':')[5]
3082    figuretitle = values.split(':')[6].replace('!',' ')
3083    colorbar = values.split(':')[7]
3084    mapvalue = values.split(':')[8]
3085    kindfig = values.split(':')[9]
3086
3087    onc = NetCDFFile(ncfile, 'r')
3088   
3089    if not onc.variables.has_key(variable):
3090        print errormsg
3091        print '  ' + fname + ": file '" + ncfile + "' does not have variable '" +    \
3092          variable + "' !!"
3093        quit(-1)
3094
3095# points
3096    lonvarn = XYvar.split(',')[0]
3097    latvarn = XYvar.split(',')[1]
3098
3099    if not onc.variables.has_key(lonvarn):
3100        print errormsg
3101        print '  ' + fname + ": file '" + ncfile + "' does not have longitude " +    \
3102          "variable '" + lonvarn + "' !!"
3103        quit(-1)
3104   
3105    if not onc.variables.has_key(latvarn):
3106        print errormsg
3107        print '  ' + fname + ": file '" + ncfile + "' does not have latitude " +    \
3108          "variable '" + latvarn + "' !!"
3109        quit(-1)
3110
3111    olonvar = onc.variables[lonvarn]
3112    olatvar = onc.variables[latvarn]
3113    ovarvar = onc.variables[variable]
3114
3115    Lpts = len(olonvar[:].flatten())
3116
3117    pointvalues = ma.masked_array(np.zeros((Lpts,3), dtype=np.float))
3118    pointvalues[:,0] = olonvar[:]
3119    pointvalues[:,1] = olatvar[:]
3120    pointvalues[:,2] = ovarvar[:]
3121
3122    varattrs = ovarvar.ncattrs()
3123    if drw.searchInlist(varattrs, 'units'):
3124        fvunits = ovarvar.getncattr('units')
3125    else:
3126        fvunits = drw.variables_values(variable)[5]
3127
3128# map value
3129    if mapvalue == 'None': mapvalue = None
3130
3131# Graph limits
3132    if graphlimits != 'None':
3133        graphlts = np.zeros((4), dtype=np.float)
3134        for il in range(4): graphlts[il] = np.float(graphlimits.split(',')[il])
3135        pointvalues[:,0] = ma.masked_outside(pointvalues[:,0], graphlts[0],          \
3136          graphlts[2])
3137        pointvalues[:,1] = ma.masked_outside(pointvalues[:,1], graphlts[3],          \
3138          graphlts[2])
3139
3140#        for ip in range(Lpts): 
3141#            if pointvalues[ip,0] < graphlts[0] or pointvalues[ip,0] > graphlts[2]    \
3142#              or pointvalues[ip,1] < graphlts[1] or pointvalues[ip,1] > graphlts[3]:
3143#                print ip,pointvalues[ip,0:2], graphlts
3144#                pointvalues[ip,2] = None
3145    else:
3146        graphlts = None
3147
3148    drw.plot_ptZvals(fvname,fvunits,pointvalues,pointype,pointsize,graphlts, nxtype, \
3149      figuretitle,colorbar,mapvalue,kindfig)
3150
3151    return
3152
3153#draw_ptZvals('OBSnetcdf.nc', 'pracc:lon,lat:o:80:2,42,7,47,:values!of!values:Blues:cyl,l:pdf', 'pr')
3154
3155def draw_vectors(ncfile, values, varns):
3156    """ Function to plot wind vectors
3157      values= [dimname]|[vardimname]|[value]:[vecvals]:[windlabs]:[mapvalues]:
3158        [gtit]:[kindfig]:[figuren]
3159        'X/Y/Z/T'|[dimname]|[vardimname]|[value]: ',', list for each basic dimension '|' separated of:
3160          [dimname]: name of the dimension in the file
3161          [vardimname]: name of the variable with the values for the dimension in the file
3162          [value]: which value of the given dimension (-1, all; [ibeg]@[iend], i-range beginning, end)
3163          No value takes all the range of the dimension
3164        [vecvals]= [frequency],[color],[length]
3165          [frequency]: [xfreq]@[yfreq] frequency of values allong each axis ('None', all grid points;
3166            'auto', computed automatically to have 20 vectors along each axis)
3167          [color]: color of the vectors
3168            'singlecol'@[colorn]: all the vectors same color ('auto': for 'red')
3169            'wind'@[colorbar]: color of the vectors according to wind speed sqrt(u^2+v^2) and given [colorbar]
3170              all vectors the same length
3171            '3rdvar'@[colorbar]@[varn]@[units]: color of the vectors according to a 3rd variable (to be added at -v) and given [colorbar]
3172              all vectors the same length
3173          [length]: length of the wind vectors ('auto', for 9)
3174        [windlabs]= [windname],[windunits]
3175          [windname]: name of the wind variable in the graph
3176          [windunits]: units of the wind variable in the graph ('None', for the value in the file)
3177        [mapvalues]= map characteristics: [proj],[res]
3178          see full documentation: http://matplotlib.org/basemap/
3179          [proj]: projection
3180            * 'cyl', cilindric
3181            * 'lcc', lambert conformal
3182          [res]: resolution:
3183            * 'c', crude
3184            * 'l', low
3185            * 'i', intermediate
3186            * 'h', high
3187            * 'f', full
3188        gtit= title of the graph ('|', for spaces)
3189        kindfig= kind of figure
3190        figuren= name of the figure
3191      ncfile= file to use
3192      varns= [uwind],[ywind] ',' list of the name of the variables with the u-wind,y-wind component
3193    """
3194    fname = 'draw_vectors'
3195
3196    if values == 'h':
3197        print fname + '_____________________________________________________________'
3198        print draw_vectors.__doc__
3199        quit()
3200
3201    expectargs = '[X/Y/Z/T]|[dimname]|[vardimname]|[value]:[vecvals]:[windlabs]:' +  \
3202      '[mapvalues]:[gtit]:[kindfig]:[figuren]'
3203 
3204    drw.check_arguments(fname,values,expectargs,':')
3205
3206    dimvals = values.split(':')[0]
3207    vecvals = values.split(':')[1]
3208    windlabels = values.split(':')[2]
3209    mapvalues = values.split(':')[3]
3210    gtit = values.split(':')[4]
3211    kindfig = values.split(':')[5]
3212    figuren = values.split(':')[6]
3213
3214    of = NetCDFFile(ncfile,'r')
3215
3216    dims = {}
3217    for dimv in dimvals.split(','):
3218        dns = dimv.split('|')
3219        dims[dns[0]] = [dns[1], dns[2], dns[3]]
3220
3221    varNs = []
3222    for dn in dims.keys():
3223        if dn == 'X':
3224            varNs.append(dims[dn][1])
3225            dimx = len(of.dimensions[dims[dn][0]])
3226        elif dn == 'Y':
3227            varNs.append(dims[dn][1])
3228            dimy = len(of.dimensions[dims[dn][0]])
3229
3230    ivar = 0
3231    for wvar in varns.split(','):
3232        if not drw.searchInlist(of.variables.keys(), wvar):
3233            print errormsg
3234            print '  ' + fname + ": file does not have variable '" + wvar + "' !!"
3235            quit(-1)
3236        if ivar == 0:
3237            varNs.append(wvar)
3238        else:
3239            varNs.append(wvar)
3240
3241    ivar = 0
3242    for varN in varNs:
3243        varslice = []
3244
3245        ovarN = of.variables[varN]
3246        vard = ovarN.dimensions
3247        for vdn in vard:
3248            found = False
3249            for dd in dims.keys():
3250                if dims[dd][0] == vdn:
3251                    if dims[dd][2].find('@') != -1:
3252                        rvals = dims[dd][2].split('@')
3253                        varslice.append(slice(int(rvals[0]), int(rvals[1])))
3254                    elif dims[dd][2] == '-1':
3255                        varslice.append(slice(0,len(of.dimensions[dims[dd][0]])))
3256                    else:
3257                        varslice.append(int(dims[dd][2]))
3258
3259                    found = True
3260                    break
3261            if not found:
3262                varslice.append(slice(0,len(of.dimensions[dims[dd][0]])))
3263
3264        if varN == dims['X'][1]:
3265            lonvals0 = np.squeeze(ovarN[tuple(varslice)])
3266        elif varN == dims['Y'][1]:
3267            latvals0 = np.squeeze(ovarN[tuple(varslice)])
3268        elif ivar == 2:
3269            uwvals = np.squeeze(np.array(ovarN[tuple(varslice)]))
3270        elif ivar == 3:
3271            vwvals = np.squeeze(ovarN[tuple(varslice)])
3272
3273        ivar = ivar + 1
3274
3275#    print 'Final shapes:',lonvals0.shape,':',latvals0.shape,':',uwvals.shape,':',
3276#      vwvals.shape
3277
3278    if len(uwvals.shape) != 2 or len(vwvals.shape) != 2:
3279        print errormsg
3280        print '  ' + fname + ': wrong size of the wind fields! they must be ' +      \
3281          '2-dimensional!'
3282        print '    u-winds shape:',uwvals.shape,'dims:',of.variables[varNs[2]]
3283        print '    v-winds shape:',vwvals.shape,'dims:',of.variables[varNs[3]]
3284        print '      provide more values for their dimensions!!'
3285        quit(-1)
3286
3287    if len(lonvals0.shape) == 1:
3288        lonvals, latvals = np.meshgrid(lonvals0, latvals0)
3289    else:
3290        lonvals = lonvals0
3291        latvals = latvals0
3292
3293# Vector values
3294    if vecvals.split(',')[0] == 'None':
3295        freqv = None
3296    else:
3297        freqv = vecvals.split(',')[0] 
3298    colorvals = vecvals.split(',')[1]
3299    coln = colorvals.split('@')[0]
3300    colv = colorvals.split('@')[1]
3301    if coln == 'singlecol':
3302        colorv = colv
3303    elif coln == 'wind':
3304        colorv = np.sqrt(uwvals**2 + vwvals**2)
3305    elif coln == '3rdvar':
3306        if len(varn.split(',')) != 3:
3307            print errormsg
3308            print '  ' + fname + ": color of vectors should be according to '" +     \
3309              coln + "' but a third varibale is not provided !!"
3310            quit(-1)
3311        ocolvec = of.variables[varNs[4]]
3312        colorv = ocolvec[:]
3313        stdvn, lonvn, unitsvn = drw.var_3desc(ocolvec)
3314        colorvals = colorvals + '@' + stdvn + '@' + unitsvn
3315    else:
3316        print errormsg
3317        print '  ' + fname + ": color type '" + coln + "' not ready !!"
3318        quit(-1)
3319
3320    lengthv = vecvals.split(',')[2]
3321
3322# Vector labels
3323    windname = windlabels.split(',')[0]
3324    windunits = windlabels.split(',')[1]
3325
3326    drw.plot_vector(lonvals, latvals, uwvals, vwvals, freqv, colorvals, colorv,      \
3327      lengthv, windname, windunits, mapvalues, gtit, kindfig, figuren)
3328
3329    of.close()
3330
3331    return
3332
3333def draw_basins(ncfile, values, varns):
3334    """ Function to plot wind basins
3335      values= [dimname]|[vardimname]|[value]:[vecvals]:[windlabs]:[mapvalues]:
3336        [gtit]:[kindfig]:[figuren]
3337        'X/Y/Z/T'|[dimname]|[vardimname]|[value]: ',', list for each basic dimension '|' separated of:
3338          [dimname]: name of the dimension in the file
3339          [vardimname]: name of the variable with the values for the dimension in the file
3340          [value]: which value of the given dimension (-1, all; [ibeg]@[iend], i-range beginning, end)
3341          No value takes all the range of the dimension
3342        [vecvals]= [frequency],[color],[length]
3343          [frequency]: [xfreq]@[yfreq] frequency of values allong each axis ('None', all grid points;
3344            'auto', computed automatically to have 20 vectors along each axis)
3345          [color]: [colorbar]@[varn]@[units]: color of the vectors according to a 3rd variable (to be added at -v) and given [colorbar]
3346              all vectors the same length
3347          [length]: length of the wind vectors ('auto', for 9)
3348        [windlabs]= [windname],[windunits]
3349          [windname]: name of the wind variable in the graph
3350          [windunits]: units of the wind variable in the graph ('None', for the value in the file)
3351        [mapvalues]= map characteristics: [proj],[res]
3352          see full documentation: http://matplotlib.org/basemap/
3353          [proj]: projection
3354            * 'cyl', cilindric
3355            * 'lcc', lambert conformal
3356          [res]: resolution:
3357            * 'c', crude
3358            * 'l', low
3359            * 'i', intermediate
3360            * 'h', high
3361            * 'f', full
3362        gtit= title of the graph ('|', for spaces)
3363        kindfig= kind of figure
3364        figuren= name of the figure
3365      ncfile= file to use
3366      varns= [lon],[lat],[outflow],[basinID] ',' list of the name of the variables with the lon,lat, the outflow and the basin ID
3367    """
3368    fname = 'draw_basins'
3369
3370    if values == 'h':
3371        print fname + '_____________________________________________________________'
3372        print draw_vectors.__doc__
3373        quit()
3374
3375    expectargs = '[X/Y/Z/T]|[dimname]|[vardimname]|[value]:[vecvals]:[windlabs]:' +  \
3376      '[mapvalues]:[gtit]:[kindfig]:[figuren]'
3377 
3378    drw.check_arguments(fname,values,expectargs,':')
3379
3380    dimvals = values.split(':')[0]
3381    vecvals = values.split(':')[1]
3382    windlabels = values.split(':')[2]
3383    mapvalues = values.split(':')[3]
3384    gtit = values.split(':')[4]
3385    kindfig = values.split(':')[5]
3386    figuren = values.split(':')[6]
3387
3388    of = NetCDFFile(ncfile,'r')
3389
3390    dims = {}
3391    for dimv in dimvals.split(','):
3392        dns = dimv.split('|')
3393        dims[dns[0]] = [dns[1], dns[2], dns[3]]
3394
3395    varNs = []
3396    for dn in dims.keys():
3397        if dn == 'X':
3398            varNs.append(dims[dn][1])
3399            dimx = len(of.dimensions[dims[dn][0]])
3400        elif dn == 'Y':
3401            varNs.append(dims[dn][1])
3402            dimy = len(of.dimensions[dims[dn][0]])
3403
3404    ivar = 0
3405    for wvar in varns.split(','):
3406        if not drw.searchInlist(of.variables.keys(), wvar):
3407            print errormsg
3408            print '  ' + fname + ": file does not have variable '" + wvar + "' !!"
3409            quit(-1)
3410        if ivar == 0:
3411            varNs.append(wvar)
3412        else:
3413            varNs.append(wvar)
3414
3415    ivar = 0
3416    for varN in varNs:
3417        varslice = []
3418
3419        ovarN = of.variables[varN]
3420        vard = ovarN.dimensions
3421        for vdn in vard:
3422            found = False
3423            for dd in dims.keys():
3424                if dims[dd][0] == vdn:
3425                    if dims[dd][2].find('@') != -1:
3426                        rvals = dims[dd][2].split('@')
3427                        varslice.append(slice(int(rvals[0]), int(rvals[1])))
3428                    elif dims[dd][2] == '-1':
3429                        varslice.append(slice(0,len(of.dimensions[dims[dd][0]])))
3430                    else:
3431                        varslice.append(int(dims[dd][2]))
3432
3433                    found = True
3434                    break
3435            if not found:
3436                varslice.append(slice(0,len(of.dimensions[dims[dd][0]])))
3437
3438        if varN == dims['X'][1]:
3439            lonvals0 = np.squeeze(ovarN[tuple(varslice)])
3440        elif varN == dims['Y'][1]:
3441            latvals0 = np.squeeze(ovarN[tuple(varslice)])
3442
3443        ivar = ivar + 1
3444
3445    if len(lonvals0.shape) == 1:
3446        lonvals, latvals = np.meshgrid(lonvals0, latvals0)
3447    else:
3448        lonvals = lonvals0
3449        latvals = latvals0
3450
3451# Vector values
3452    if vecvals.split(',')[0] == 'None':
3453        freqv = None
3454    else:
3455        freqv = vecvals.split(',')[0] 
3456
3457    colorvals = vecvals.split(',')[1]
3458    if len(varn.split(',')) != 3:
3459        print errormsg
3460        print '  ' + fname + ": color of vectors should be according to '" +         \
3461          coln + "' but a third varibale is not provided !!"
3462        quit(-1)
3463
3464    ocolvec = of.variables[varNs[3]]
3465    colorv = ocolvec[:]
3466    stdvn, lonvn, unitsvn = drw.var_3desc(ocolvec)
3467    colorvals = colorvals + '@' + stdvn + '@' + unitsvn
3468
3469    lengthv = vecvals.split(',')[2]
3470
3471# Vector labels
3472    windname = windlabels.split(',')[0]
3473    windunits = windlabels.split(',')[1]
3474
3475# Vector angles
3476    oflow = ofile.variables[varNs[2]]
3477    angle = (oflow[:] - 1)*np.pi/4
3478    xflow = np.where(oflow[:] < 9, np.float(lengthv)*np.sin(angle), 0.)
3479    yflow = np.where(oflow[:] < 9, np.float(lengthv)*np.cos(angle), 0.)
3480
3481    drw.plot_basins(lonvals, latvals, xflow, yflow, freqv, colorvals, colorv,      \
3482      lengthv, windname, windunits, mapvalues, gtit, kindfig, figuren)
3483
3484    of.close()
3485
3486    return
3487
3488def draw_river_desc(ncfile, values, riverns):
3489    """ Function to plot rivers' description from ORCHIDEE's routing scheme
3490      values= [dimname]|[vardimname]|[value]:[basinvals]:[upstreamvals]:[mapvalues]:
3491        [gtit]:[kindfig]:[legloc]:[figuren]
3492        'X/Y'|[dimname]|[vardimname]|[value]: ',', list for each basic dimension '|' separated of:
3493          [dimname]: name of the dimension in the file
3494          [vardimname]: name of the variable with the values for the dimension in the file
3495          [value]: which value of the given dimension (-1, all; [ibeg]@[iend], i-range beginning, end)
3496          No value takes all the range of the dimension
3497        [basinsvals]= [colorline]
3498          [basincolor]: ',' list of colors of the line to use to mark the basins contours (single value also possible)
3499        [upstreamvals]= [upstreamvarn],[colorbar]
3500          [upstreamcolor]: colorbar to use to plot the basins upstream values
3501        [mapvalues]= map characteristics: [proj],[res]
3502          see full documentation: http://matplotlib.org/basemap/
3503          [proj]: projection
3504            * 'cyl', cilindric
3505            * 'lcc', lambert conformal
3506          [res]: resolution:
3507            * 'c', crude
3508            * 'l', low
3509            * 'i', intermediate
3510            * 'h', high
3511            * 'f', full
3512        gtit= title of the graph ('|', for spaces)
3513        kindfig= kind of figure
3514        legloc= location of the legend (0, automatic)
3515          1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
3516          5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
3517          9: 'upper center', 10: 'center'      kfig= kind of figure
3518        figuren= name of the figure
3519      ncfile= file to use
3520      riverns= ',' list of the name of the rivers to plot
3521    """
3522    import numpy.ma as ma
3523    fname = 'draw_river_desc'
3524
3525    if values == 'h':
3526        print fname + '_____________________________________________________________'
3527        print draw_river_desc.__doc__
3528        quit()
3529
3530    expectargs = '[X/Y/Z/T]|[dimname]|[vardimname]|[value]:[basinvals]:' +           \
3531      '[upstreamvals]:[mapvalues]:[gtit]:[kindfig]:[legloc]:[figuren]'
3532 
3533    drw.check_arguments(fname,values,expectargs,':')
3534
3535    dimvals = values.split(':')[0]
3536    basinvals = values.split(':')[1]
3537    upstreamvals = values.split(':')[2]
3538    mapvals = values.split(':')[3]
3539    gtit = values.split(':')[4]
3540    kindfig = values.split(':')[5]
3541    legloc = int(values.split(':')[6])
3542    figuren = values.split(':')[7]
3543
3544    basincol = basinvals
3545    if basincol.find(',') != 1:
3546        basincolor = basincol.split(',')
3547    else:
3548        basincolor = [basincol]
3549
3550    upstreamcolor = upstreamvals
3551
3552    of = NetCDFFile(ncfile,'r')
3553
3554    dims = {}
3555    for dimv in dimvals.split(','):
3556        dns = dimv.split('|')
3557        dims[dns[0]] = [dns[1], dns[2], dns[3]]
3558
3559    varNs = []
3560    for dn in dims.keys():
3561        if dn == 'X':
3562            varNs.append(dims[dn][1])
3563            dimx = len(of.dimensions[dims[dn][0]])
3564        elif dn == 'Y':
3565            varNs.append(dims[dn][1])
3566            dimy = len(of.dimensions[dims[dn][0]])
3567
3568    if riverns.find(',') != -1:
3569        riverns = riverns.split(',')
3570    else:
3571        riverns = [riverns]
3572
3573    rivers = []
3574    riversubbasins = {}
3575    riversupstream = {}
3576    riversoutflow = {}
3577    for rivern in riverns:
3578        print rivern
3579
3580# subBasins
3581        basinvar = rivern + '_coding'
3582        if not drw.searchInlist(of.variables.keys(), basinvar):
3583            print errormsg
3584            print '  ' + fname + ": file does not have variable '" + basinvar + "' !!"
3585            quit(-1)
3586        rivers.append(rivern)
3587        obasin = of.variables[basinvar]
3588        riversubbasins[rivern] = obasin[:]
3589        if rivern == riverns[0]:
3590            finalmask = obasin[:].mask
3591        else:
3592            finalmask = finalmask * obasin[:].mask
3593
3594# upstream
3595        upstreamvar = rivern + '_upstream'
3596        if not drw.searchInlist(of.variables.keys(), upstreamvar):
3597            print errormsg
3598            print '  ' + fname + ": file does not have variable '" + upstreamvar + "' !!"
3599            quit(-1)
3600        oupstream = of.variables[upstreamvar]
3601        riversupstream[rivern] = oupstream[:]
3602        if rivern == riverns[0]:
3603            uunits = oupstream.getncattr('units')
3604
3605# River metadata
3606        fracvar = rivern + '_frac'
3607        if not drw.searchInlist(of.variables.keys(), fracvar):
3608            print errormsg
3609            print '  ' + fname + ": file does not have variable '" + fracvar + "' !!"
3610            quit(-1)
3611        ofrac = of.variables[fracvar]
3612        riversoutflow[rivern] = [ofrac.getncattr('Longitude_of_outflow_point'),      \
3613          ofrac.getncattr('Latitude_of_outflow_point')]
3614
3615    ivar = 0
3616    for varN in varNs:
3617        varslice = []
3618
3619        ovarN = of.variables[varN]
3620        vard = ovarN.dimensions
3621        for vdn in vard:
3622            found = False
3623            for dd in dims.keys():
3624                if dims[dd][0] == vdn:
3625                    if dims[dd][2].find('@') != -1:
3626                        rvals = dims[dd][2].split('@')
3627                        varslice.append(slice(int(rvals[0]), int(rvals[1])))
3628                    elif dims[dd][2] == '-1':
3629                        varslice.append(slice(0,len(of.dimensions[dims[dd][0]])))
3630                    else:
3631                        varslice.append(int(dims[dd][2]))
3632
3633                    found = True
3634                    break
3635            if not found:
3636                varslice.append(slice(0,len(of.dimensions[dims[dd][0]])))
3637
3638        if varN == dims['X'][1]:
3639            lonvals0 = np.squeeze(ovarN[tuple(varslice)])
3640        elif varN == dims['Y'][1]:
3641            latvals0 = np.squeeze(ovarN[tuple(varslice)])
3642
3643        ivar = ivar + 1
3644
3645    if len(lonvals0.shape) == 1:
3646        lonvals, latvals = np.meshgrid(lonvals0, latvals0)
3647    else:
3648        lonvals = lonvals0
3649        latvals = latvals0
3650
3651# Masking only the lon,lat with rivers
3652    malonvals = ma.masked_array(lonvals, mask=finalmask)
3653    malatvals = ma.masked_array(latvals, mask=finalmask)
3654
3655    if mapvals == 'None':
3656        mapvalues = None
3657    else:
3658        mapvalues = mapvals
3659
3660    drw.plot_river_desc(malonvals, malatvals, rivers, riversubbasins, riversupstream, riversoutflow,  \
3661      basincolor, upstreamcolor, uunits, mapvalues, gtit, kindfig, legloc, figuren)
3662
3663    of.close()
3664
3665def draw_vertical_levels(ncfile, values, varn):
3666    """ plotting vertical levels distribution
3667    draw_topo_geogrid(ncfile, values, varn)
3668      ncfile= file to use
3669      values= [zlog]:[dzlog]:[title]:[graphic_kind]:[legloc]
3670        zlog: to use logarithmic scale on the height axis ('true/false')
3671        dzlog: to use logarithmic scale on the difference of height between levels axis ('true/false')
3672        title: title of the graph ('!' for spaces)
3673        graphic_kind: kind of figure (jpg, pdf, png)
3674        legloc= location of the legend (0, automatic)
3675          1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
3676          5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
3677          9: 'upper center', 10: 'center'      kfig= kind of figure
3678      varn= name of the variable with the vertical levels
3679        'WRFz': for WRF z-levels (computed as (PH + PHB)/g, from a PHB(0,i,j) = 0)
3680    """
3681    fname = 'draw_vertical_levels'
3682
3683    if values == 'h':
3684        print fname + '_____________________________________________________________'
3685        print draw_vertical_levels.__doc__
3686        quit()
3687
3688    expectargs = '[zlog]:[dzlog]:[title]:[graphic_kind]:[legloc]'
3689 
3690    drw.check_arguments(fname,values,expectargs,':')
3691
3692    zlog = values.split(':')[0]
3693    dzlog = values.split(':')[1]
3694    title = values.split(':')[2].replace('!',' ')
3695    kindfig = values.split(':')[3]
3696    legloc = int(values.split(':')[4])
3697
3698    if not os.path.isfile(ncfile):
3699        print errormsg
3700        print '  ' + fname + ': file "' + ncfile + '" does not exist !!'
3701        quit(-1)   
3702
3703    objf = NetCDFFile(ncfile, 'r')
3704
3705    if varn == 'WRFz': 
3706        if not gen.searchInlist(objf.variables,'PH'):
3707            print errormsg
3708            print '  ' + fname + ": WRF file '" + ncfile + "' does not have " +      \
3709              "variable 'PH' !!"
3710            quit(-1)
3711        if not gen.searchInlist(objf.variables,'PHB'):
3712            print errormsg
3713            print '  ' + fname + ": WRF file '" + ncfile + "' does not have " +      \
3714              "variable 'PHB' !!"
3715            quit(-1)
3716
3717        objph = objf.variables['PH']
3718        objphb = objf.variables['PHB']
3719        geop = objph[:] + objphb[:]
3720
3721        ijz0 = gen.index_mat(geop[0,], 0.)
3722        zvals = geop[0, :, ijz0[0], ijz0[1]] / 9.8
3723    else:
3724        if not objf.has_variable(varn):
3725            print errormsg
3726            print '  ' + fname + ": file '" + ncfile + "' does not have variable '" +\
3727              varn + "' !!"
3728            quit(-1)
3729        objvar = objf.variables[varn]
3730        if len(objvar.shape) == 4:
3731            print warnmsg
3732            print '  ' + fname + ": assuming that variable '" + varn + "' with " +   \
3733              "shape: dt,dz,dy,dx. Tacking first time-step"
3734
3735            ijz0 = gen.index_mat(objvar[0,0,], 0.)
3736            zvals = objvar[0, :, ijz0[0], ijz0[1]]
3737        elif len(objvar.shape) == 3:
3738            print warnmsg
3739            print '  ' + fname + ": assuming that variable '" + varn + "' with " +   \
3740              "shape: dz,dy,dx"
3741
3742            ijz0 = gen.index_mat(objvar[0,], 0.)
3743            zvals = objvar[:, ijz0[0], ijz0[1]]
3744       
3745        elif len(objvar.shape) == 2:
3746            print warnmsg
3747            print '  ' + fname + ": assuming that variable '" + varn + "' with " +   \
3748              "shape: dz,dyx"
3749
3750            ijz0 = gen.index_mat(objvar[0,], 0.)
3751            zvals = objvar[:, ijz0[0]]
3752        else:
3753            zvals = objvar[:]
3754
3755    if zlog == 'true':
3756        zlogv = True
3757    elif zlog == 'false':
3758        zlogv = False
3759    else:
3760        print errormsg
3761        print '  ' + fname + ": wrong value for zlog: '" + zlog + "' !!"
3762        print "    must be either: 'true' or 'false'"
3763        quit(-1)
3764    if dzlog == 'true':
3765        dzlogv = True
3766    elif dzlog == 'false':
3767        dzlogv = False
3768    else:
3769        print errormsg
3770        print '  ' + fname + ": wrong value for dzlog: '" + dzlog + "' !!"
3771        print "    must be either: 'true' or 'false'"
3772        quit(-1)
3773
3774    drw.plot_vertical_lev(zvals, zlogv, dzlogv, title, kindfig, legloc)
3775
3776    objf.close()
3777
3778    return
3779
3780#quit()
3781
3782####### ###### ##### #### ### ## #
3783
3784ngraphics = "'" + drw.numVector_String(namegraphics, "', '") + "'"
3785 
3786### Options
3787##string_operation="operation to make: " + '\n' + " out, output values -S inidim1,[inidim2,...]:enddim1,[enddim2,...]"
3788string_operation="""operation to make:
3789  draw_topo_geogrid, draws topography from a WPS geo_em.d[nn].nc: -S [minTopo],[maxTopo]:[SW_lon],[SW_lat],[NE_lon],[NE_lat]:[title]:[graphic_kind]:[projection],[res_coastline]
3790  draw_2D_shad_cont, draws two 2D fields, first with shading second with contour lines: -v [varns],[varnc] -S [vnamefs],[vnamefc],[dimxvn],[dimyvn],[colorbar],[ckind],[clabfmt],[sminv]:[smaxv],[sminc]:[smaxv]:[Nlev],[figt],[kindfig],[reverse]
3791    [ckind]:
3792      'cmap': as it gets from colorbar
3793      'fixc,[colname]': fixed color [colname], all stright lines
3794      'fixsignc,[colname]': fixed color [colname], >0 stright, <0 dashed  line
3795"""
3796
3797#print string_operation
3798
3799parser = OptionParser()
3800parser.add_option("-f", "--netCDF_file", dest="ncfile", 
3801                  help="file to use", metavar="FILE")
3802parser.add_option("-o", "--operation", type='choice', dest="operation", 
3803       choices=namegraphics, 
3804                  help="operation to make: " + ngraphics, metavar="OPER")
3805parser.add_option("-S", "--valueS", dest="values", 
3806                  help="[WHEN APPLICABLE] values to use according to the operation", metavar="VALUES")
3807parser.add_option("-v", "--variable", dest="varname",
3808                  help="[WHEN APPLICABLE] variable to check", metavar="VAR")
3809
3810(opts, args) = parser.parse_args()
3811
3812#######    #######
3813## MAIN
3814    #######
3815
3816# Not checking file operation
3817Notcheckingfile = ['draw_2D_shad_cont', 'draw_2D_shad_cont_time',                    \
3818  'draw_2D_shad_line', 'draw_2D_shad_line_time', 'draw_lines', 'draw_lines_time',    \
3819  'draw_points', 'draw_topo_geogrid_boxes', 'draw_trajectories',                     \
3820  'draw_vals_trajectories', 'variable_values']
3821
3822####### ###### ##### #### ### ## #
3823errormsg='ERROR -- error -- ERROR -- error'
3824
3825varn=opts.varname
3826oper=opts.operation
3827
3828if opts.ncfile is not None and not os.path.isfile(opts.ncfile) and                   \
3829  not drw.searchInlist(Notcheckingfile, oper):
3830    print errormsg
3831    print '  ' + main + ': File ' + opts.ncfile + ' does not exist !!'
3832    quit(-1)
3833
3834if oper == 'create_movie':
3835    create_movie(opts.ncfile, opts.values, opts.varname)
3836elif oper == 'draw_2D_shad':
3837    draw_2D_shad(opts.ncfile, opts.values, opts.varname)
3838elif oper == 'draw_2D_shad_time':
3839    draw_2D_shad_time(opts.ncfile, opts.values, opts.varname)
3840elif oper == 'draw_2D_shad_cont':
3841    draw_2D_shad_cont(opts.ncfile, opts.values, opts.varname)
3842elif oper == 'draw_2D_shad_cont_time':
3843    draw_2D_shad_cont_time(opts.ncfile, opts.values, opts.varname)
3844elif oper == 'draw_2D_shad_line':
3845    draw_2D_shad_line(opts.ncfile, opts.values, opts.varname)
3846elif oper == 'draw_2D_shad_line_time':
3847    draw_2D_shad_line_time(opts.ncfile, opts.values, opts.varname)
3848elif oper == 'draw_barbs':
3849    draw_barbs(opts.ncfile, opts.values, opts.varname)
3850elif oper == 'draw_basins':
3851    draw_basins(opts.ncfile, opts.values, opts.varname)
3852elif oper == 'draw_Neighbourghood_evol':
3853    draw_Neighbourghood_evol(opts.ncfile, opts.values, opts.varname)
3854elif oper == 'draw_lines':
3855    draw_lines(opts.ncfile, opts.values, opts.varname)
3856elif oper == 'draw_lines_time':
3857    draw_lines_time(opts.ncfile, opts.values, opts.varname)
3858elif oper == 'draw_points':
3859    draw_points(opts.ncfile, opts.values)
3860elif oper == 'draw_points_lonlat':
3861    draw_points_lonlat(opts.ncfile, opts.values)
3862elif oper == 'draw_ptZvals':
3863    draw_ptZvals(opts.ncfile, opts.values, opts.varname)
3864elif oper == 'draw_river_desc':
3865    draw_river_desc(opts.ncfile, opts.values, opts.varname)
3866elif oper == 'draw_timeSeries':
3867    draw_timeSeries(opts.ncfile, opts.values, opts.varname)
3868elif oper == 'draw_topo_geogrid':
3869    draw_topo_geogrid(opts.ncfile, opts.values)
3870elif oper == 'draw_topo_geogrid_boxes':
3871    draw_topo_geogrid_boxes(opts.ncfile, opts.values)
3872elif oper == 'draw_trajectories':
3873    draw_trajectories(opts.ncfile, opts.values, opts.varname)
3874elif oper == 'draw_vals_trajectories':
3875    draw_vals_trajectories(opts.ncfile, opts.values, opts.varname)
3876elif oper == 'draw_vectors':
3877    draw_vectors(opts.ncfile, opts.values, opts.varname)
3878elif oper == 'draw_vertical_levels':
3879    draw_vertical_levels(opts.ncfile, opts.values, opts.varname)
3880elif oper == 'list_graphics':
3881# From: http://www.diveintopython.net/power_of_introspection/all_together.html
3882    import drawing as myself
3883    object = myself
3884    for opern in namegraphics:
3885        if  opern != 'list_graphics': 
3886            print opern + '_______ ______ _____ ____ ___ __ _'
3887            print getattr(object, opern).__doc__
3888elif oper == 'variable_values':
3889    variable_values(opts.values)
3890else:
3891    print errormsg
3892    print '  ' + main + ": the graphic '" + oper + "' is not ready !!"
3893    print errormsg
3894    quit()
Note: See TracBrowser for help on using the repository browser.