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

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

Adding 'draw_line_time': script to draw lines with times

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