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

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

Fixing a lot of errors on `draw_TimeSeires'

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