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

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

Adding legend position in 'draw_lines_time'

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