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

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

Fixing a for without a 'range'

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