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

Last change on this file since 540 was 540, checked in by lfita, 10 years ago

Working version of the `draw_barbs'

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