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

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

Fixing 'slice_variable' for that dimensions which are not given a value to slice

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