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

Last change on this file since 1446 was 1438, checked in by lfita, 8 years ago

adding: plot_WindRose: Function to plot a wind rose (from where the dinw blows)

File size: 228.3 KB
Line 
1# Python to manage plot data in netCDF files.
2# From L. Fita work in different places: LMD (France)
3# More information at: http://www.xn--llusfb-5va.cat/python/PyNCplot
4#
5# pyNCplot and its component drawing.py comes with ABSOLUTELY NO WARRANTY.
6# This work is licendes under a Creative Commons
7#   Attribution-ShareAlike 4.0 International License (http://creativecommons.org/licenses/by-sa/4.0)
8#
9import numpy as np
10import os
11from netCDF4 import Dataset as NetCDFFile
12import nc_var_tools as ncvar
13import drawing_tools as drw
14import generic_tools as gen
15from optparse import OptionParser
16import sys
17from cStringIO import StringIO
18
19## e.g. # drawing.py -f /media/data2/etudes/WRF_LMDZ/WL_HyMeX/IIphase/medic950116/wlmdza/wrfout/wrfout_d01_1995-01-13_00:00:00 -o create_movie -S 'draw_2D_shad#Time@WRFTimes@10@95@191@1#tas:East_West|-1,North_South|-1,Time|2:longitude:latitude:Summer:270.,300.:tas|at|t=0:pdf:None:None' -v T2
20## e.g. # drawing.py -o draw_2D_shad -f wrfout_d01_2001-11-11_00:00:00 -S 'tas:west_east|-1,south_north|-1,Time|2:XLONG:XLAT:auto:rainbow,auto,auto:Srange,Srange:tas|at|2001-11-11|02|UTC:png:None:cyl,l:True' -v T2
21## e.g. # drawing.py -o draw_2D_shad_time -f wrfout_d01_2001-11-11_00:00:00 -S 'hurs~west_east|-1,south_north|27,Time|-1~XLONG~WRFtime~auto~Blues,auto,auto~Srange,Srange~tas|evolution|at|south_north=27~png~None~WRFtime|hours!since!1949-12-01|exct,1,h|$%d^{%H}$|date!($[DD]^{[HH]}$)~True' -v Q2
22## e.g. # drawing.py -o draw_2D_shad_cont -f wrfout_d01_2001-11-11_00:00:00 -S 'huss,tas:west_east|-1,south_north|-1,Time|2:Time|2:XLONG:XLAT:auto:Blues,auto,auto:fixc,r:%3g:Srange,Srange:260,300,9:huss|&|tas|at|2001-11-11|02|UTC:png:None:cyl,c:True' -v Q2,T2
23## e.g. # drawing.py -o draw_2D_shad_cont_time -f wrfout_d01_2001-11-11_00:00:00 -S 'hfls,tas;west_east|-1,south_north|27,Time|-1;south_north|27;XLONG;WRFtime;auto;BuPu,auto,auto;fixc,y;%3g;Srange,Srange;260,300,9;huss|&|tas|evolution|at|south_north=27;png;None;WRFtime|hours!since!1949-12-01|exct,1,h|$%d^{%H}$|date!($[DD]^{[HH]}$);True' -v LH,T2
24## e.g. # drawing.py -o draw_2D_shad_line -f wrfout_d01_2001-11-11_00:00:00,wrfout_d01_2001-11-11_00:00:00 -S 'hus,hgt:west_east|-1,south_north|96,Time|2,bottom_top|-1:XLONG:ZNU:auto:rainbow,auto,horizontal:Srange,Srange:k,0.,4000.,auto,auto,auto,45.:vert.|sec.|hus|at|y=96|on|2001-11-11|02|UTC:png:flip@y:None:True' -v QVAPOR,HGT
25## e.g. # drawing.py -o draw_barbs -f wrfout_d01_2001-11-11_00:00:00 -S 'west_east|XLONG|-1,west_east_stag|XLONG|0@239@1,south_north|XLAT|15,bottom_top|ZNU|-1,bottom_top_stag|ZNW|0@39@1,Time|WRFtime|3:10@2,colormap@rainbow,7.:uw,ms-1:XLONG:ZNW:None:auto:flip@y:vertical|cross|section|wind|speed|at|y=15|on|2001-11-10|03|UTC:png:wind_barbs_2001111003_uw:True' -v U,W
26## e.g. # drawing.py -f geo_em.d02.nc -o draw_topo_geogrid -S '0.,1500.:None:2km!domain!centered!at!SIRTA:png:cyl,i:True'
27## e.g. # python ../drawing.py -f ~/etudes/domains/SIRTA/geo_em.d01.nc,/home/lluis/etudes/domains/SIRTA/geo_em.d02.nc -o draw_topo_geogrid_boxes -S '0.,1500.:None:WRF!domain!centered!at!SIRTA:png:cyl,i:d01$_{15k}$,d02$_{3k}$:0|10:True'
28## e.g. # drawing.py -f ~/etudes/domains/MEDCORDEX/geo_em.d01.nc -o draw_2D_shad_cont -S 'height,landmask:Time|0:Time|0:XLONG_M:XLAT_M:terrain:fixc,k:None:0.,3000.:0,1,10:MEDCORDEX height & landmask:pdf:False:lcc,i' -v HGT_M,LANDMASK
29## e.g. # $ drawing.py -f WRF/current/hurs_wrfout_tturb_xmean_last.nc,WRF/micro1/hurs_wrfout_tturb_xmean_last.nc,WRF/micro2/hurs_wrfout_tturb_xmean_last.nc,WRF_LMDZ/AR40/hurs_wrfout_tturb_xmean_last.nc,WRF_LMDZ/NPv31/hurs_wrfout_tturb_xmean_last.nc,LMDZ/AR40/hurs_reproj-histins_tturb_xmean_last.nc,LMDZ/NPv31/hurs_reproj-histins_tturb_xmean_last.nc -o draw_lines -S 'lat:x:lat ($degrees\ North$):auto:wcurr,wmp1,wmp2,wlmdza,wlmdzb,lmdza,lmdzb:hurs:all model-experiments meridional hurs$_{[tturb\ xmean\ last]}$:0|auto:None:-:,:2.:2.:all:Nlines_hurs_wrfout_tturb-xmean-last:png:True' -v hursturbmean
30## e.g. # drawing.py -o draw_lines_time -f wrfout_d01_2001-11-11_00:00:00_west_east_B20-E20-I1_south_north_B20-E20-I1.nc,wrfout_d01_2001-11-11_00:00:00_west_east_B25-E25-I1_south_north_B25-E25-I1.nc,wrfout_d01_2001-11-11_00:00:00_west_east_B35-E35-I1_south_north_B35-E35-I1.nc -S 'WRFtime;y;time ([DD]${[HH]}$);auto;we=20$\times$sn=20,we=25$\times$sn=25,we=35$\times$sn=35;tas;tas|evolution|at|3|different|grid|points;None;time|hours!since!1949-12-01_00:00:00|exct,3,h|%d$^{%H}$;0|12;pdf;-;r,g,b;.;2.;2.;all;-1;True' -v T2
31## e.g. # drawing.py -o draw_Neighbourghood_evol -S 'vas:Time|-1|WRFtime,south_north|44|XLAT,west_east|88|XLONG:south_north,west_east:5:auto:time|($[DD]^{[HH]}$),time|($[DD]^{[HH]}$):exct,1,h|exct,3,h:$%d^{%H}$,$%d^{%H}$:5|pts|neighbourghood|temporal|evolution|on|2001|Nov.|at|x=88,|y=44:0.0,20.:rainbow,auto,auto:auto:png:vas_Neigh_evol:True' -f ~/PY/wrfout_d01_2001-11-11_00:00:00 -v V10
32## e.g. # drawing.py -o draw_points -S 'SuperStorm/tslist.dat,#,3,2,1:SuperStorm|sfc|stations:auto:cyl,i:labelled,10,r:auto:None:0:png:stations_loc:True' -f 'geo_em.d02.nc,XLONG_M,XLAT_M,HGT_M,Time|0@west_east|30;180;1@south_north|175;255;1,height,0.,1500.,terrain,auto,auto,m'
33
34## e.g. # drawing.py -o draw_trajectories -f 'WRF/control/trajectory.dat@-1@/home/lluis/etudes/domains/WL_HyMeX_HighRes_C/geo_em.d03.nc#XLONG_M#XLAT_M,WRF_LMDZ/wlmdza/trajectory.dat@-1@/home/lluis/etudes/domains/WL_HyMeX_C/geo_em.d01.nc#XLONG_M#XLAT_M,WRF_LMDZ/wlmdzb/trajectory.dat@-1@/home/lluis/etudes/domains/WL_HyMeX_C/geo_em.d01.nc#XLONG_M#XLAT_M,WRF_LMDZ/wlmdzb_ii/trajectory.dat@-1@/home/lluis/etudes/domains/WL_HyMeX_C/geo_em.d01.nc#XLONG_M#XLAT_M' -S '$WRF_{CRM}$,$LMDZ_{AR4.0}$,$LMDZ_{NPv3.1}$,$LMDZ_{NPv3.1b}$|None|medicane trajectories|pdf|cyl,i' -v obs/trajectory.dat,satellite,-1
35## e.g. # drawing.py -o draw_vals_trajectories -f WRF_LMDZ/wlmdza/tevolboxtraj_T2.nc,WRF_LMDZ/wlmdzb/tevolboxtraj_T2.nc,WRF/control/tevolboxtraj_T2.nc -S 'mean:-1:$WRF_{CRM}$,$LMDZ_{AR4.0}$,$LMDZ_{NPv3.1}$@4:tas:time|($[DD]^[HH]$):exct,6,h:$%d^{%H}$:trajectory|following|mean:pdf' -v T2
36## e.g. # drawing.py -o draw_2D_shad_time -f 'netcdf_concatenated.nc' -S 'dtcon:Time|-1,bottom_top|-1:presmean:time:seismic:-3.e-6,3.e-6:monthly|dtcon:pdf:transpose:time|hours!since!1949-12-01|exct,2,d|%d|date!([DD])|x:True' -v 'dtconmean'
37## e.g. # drawing.py -o variable_values -S PSFC
38## e.g. # drawing.py -o draw_timeSeries -f wrfout_d01_1979-12-01_00:00:00_bottom_top_B6-E6-I1_south_north_B3-E3-I1_west_east_B26-E26-I1.nc -S 'dt_con:time|($[DD]^{[HH]}$):exct,12,h:$%d^{%H}$:time|evolution|at|-1|6|3|26:1:pdf' -v 'LDQCON,time'
39## e.g. # drawing.py -f wrfout_d01_1979-12-01_00:00:00 -o draw_Neighbourghood_evol -S 'q:Time|-1|Times,bottom_top|6|ZNU,south_north|3|XLAT,west_east|26|XLONG:south_north,west_east:5:auto:time|($[DD]^{[HH]}$),time|($[DD]^{[HH]}$):exct,2,h|exct,1,d:$%d^{%H}$,$%d^{%H}$:5|pts|neighbourghood|temporal|evolution:0.0,0.004:BuPu:pdf:True' -v QVAPOR
40## e.g. # drawing.py -o draw_lines_time -f wrfout_d01_1980-03-01_00:00:00_Time_B0-E48-I1_south_north_B15-E15-I1_west_east_B15-E15-I1.nc -S 'time;y;time ([DD]${[HH]}$);file1;tas;evolution;time|hours!since!1949-12-01_00:00:00|exct,12,h|%d$^{%H}$;pdf' -v T2
41## e.g. # drawing.py -o draw_barbs -f ERAI_pl199501_131-132.nc -S 'X|lon|lon|-1,Y|lat|lat|-1,Z|lev|lev|4,T|time|time|0:auto,auto,auto:wind,ms-1:cyl,c:ERA-Interim|winds|at|1000|hPa|on|1996|January|1st|at|00|UTC:pdf:ERAI_pl199501_131-132' -v var131,var132
42## e.g. # ~/etudes/WRF_LMDZ/svn/LMDZ_WRF/tools/drawing.py -o draw_points -S 'tslist.dat,#,3,2,1:SuperStorm|sfc|stations:cyl,i:legend:auto:None:0:png:stations_loc' -f $HOME'/etudes/domains/WRFdynamicoSENS_SuperStorm/geo_em.d02.nc,XLONG_M,XLAT_M,HGT_M,Time|0,height,0.,3000.,terrain,m'
43## e.g. # drawing.py -o draw_points -S 'tslist.dat,#,3,2,1:SuperStorm|sfc|stations:cyl,i:labelled,8,black:auto:None:0:png:stations_loc' -f $HOME'/etudes/domains/WRFdynamicoSENS_SuperStorm/geo_em_west_east_B25-E180-I1_south_north_B160-E262-I1.nc,XLONG_M,XLAT_M,HGT_M,Time|0,height,0.,1500.,terrain,m'
44## e.g. # drawing.py -o draw_ptZvals -f geo_v2_2012102123_RR1.nc -S 'pracc:lon,lat:o:80:2,42,7,47,:values!of!values:Blues:cyl,l:pdf' -v pr
45## e.g. # drawing.py -f carteveg5km.nc -o draw_points_lonlat -S 'longitude:latitude:pdf:points!veget|type:green:.:0.5:None:0:legend'
46## e.g. # drawing.py -o draw_vectors -f wrfout_d01_2001-11-11_00:00:00 -S 'T|Time|Times|2,Y|south_north|XLAT|-1,X|west_east|XLONG|-1:3@3,wind@rainbow,9:10m wind,ms-1:cyl,l:WRF 10 m winds:pdf:winds' -v U10,V10
47## e.g. # drawing.py -o draw_basins -f routing.py -S 'Y|y|nav_lat|-1,X|x|nav_lon|-1:1@1,rainbow,9:basins,-:cyl,l:ORCDHIEE river-basins:pdf:basins_named' -v nav_lon,nav_lat,trip,basins
48## e.g. # drawing.py -o draw_river_desc -f diver_desc.nc -S 'Y|lat|lat|-1,X|lon|lon|-1:red,green:Blues:cyl,l:ORCDHIEE rivers:pdf:0:or_rivers -v Amazon
49## e.g. # drawing.py -o draw_vertical_levels -f wrfout_d01_2001-11-11_00:00:00 -S 'true:false:wrfout!vertical!levels!(standard!40):png:4' -v WRFz
50## e.g. # drawing.py -o draw_subbasin -f Caceres_subbasin.nc -S 'Caceres:None:cyl,l:2,True:Caceres:pdf:0:Caceres_subbasin'
51## e.g. # drawing.py -o draw_2lines -f /home/lluis/etudes/WRF_LMDZ/WaquaL_highres/tests/model_graphics/WRF/current/wss_wrfout_tvar_xmean.nc,/home/lluis/etudes/WRF_LMDZ/WaquaL_highres/tests/model_graphics/WRF/current/tas_wrfout_tvar_xmean.nc -v wssvarmean,tasvarmean -S 'lat:0.,20.:0.,4.:-90.,90.:y:wss,tas:red,blue:2.,2.:-:2.,2.:,:wss!tas!mean!meridional!tvar:lon:0:wss_tas_wrfout_tvar_xmean:pdf'
52## e.g. # drawing.py -o draw_2lines_time -f /home/lluis/etudes/WRF_LMDZ/WaquaL_highres/tests/model_graphics/WRF/current/wss_wrfout_xvar_ymean.nc,/home/lluis/etudes/WRF_LMDZ/WaquaL_highres/tests/model_graphics/WRF/current/tas_wrfout_xvar_ymean.nc -v wssvarmean,tasvarmean -S 'time:0.,20.:0.,4.:exct,1,d;%d:x:wss,tas:red,blue:2.,2.:-:2.,2.:,:wss!tas!mean!longitudinal!xvar:time!($[DD]$):0:wss_tas_wrfout_xvar_ymean:pdf'
53
54#######
55# create_movie: Function to create a movie assuming ImageMagick installed!
56# draw_2D_shad: plotting a fields with shading
57# draw_2D_shad_cont: plotting two fields, one with shading and the other with contour lines
58# draw_2D_shad_cont_time: plotting two fields, one with shading and the other with contour lines being
59#   one of the dimensions of time characteristics
60# draw_2D_shad_line: plotting a fields with shading and another with line
61# draw_2D_shad_line_time: plotting a fields with shading and a line with time values
62# draw_2D_shad_time: plotting a fields with shading with time values
63# draw_2lines: Fucntion to plot two lines in different axes (x/x2 or y/y2)
64# draw_2lines_time: Function to plot two time-lines in different axes (x/x2 or y/y2)
65# draw_barbs: Function to plot wind barbs
66# draw_basins: Function to plot river basins with their discharge vector and basins id (from 'routing.nc')
67# draw_lines: Function to draw different lines at the same time from different files
68# draw_lines_time: Function to draw different lines at the same time from different files with times
69# draw_Neighbourghood_evol: Function to draw the temporal evolution of a neighbourghood around a point
70# draw_points: Function to plot a series of points
71# draw_points_lonlat: Function to plot a series of lon/lat points
72# draw_ptZvals: Function to plot a given list of points and values
73# draw_timeSeries: Function to draw a time-series
74# draw_topo_geogrid: plotting geo_em.d[nn].nc topography from WPS files
75# draw_topo_geogrid_boxes: plotting different geo_em.d[nn].nc topography from WPS files
76# draw_trajectories: Function to draw different trajectories at the same time
77# draw_vals_trajectories: Function to draw values from the outputs from 'compute_tevolboxtraj'
78# draw_vectors: Function to plot wind vectors
79# movievalslice: Function to provide variable slice according to a geneation of a movie
80# variable_values: Function to give back values for a given variable
81# draw_river_desc: Function to plot rivers' description from ORCHIDEE's routing scheme
82# draw_subbasin: Function to plot subbasin from 'routnig.nc' ORCDHIEE
83# draw_vertical_levels: plotting vertical levels distribution
84# plot_WindRose: Function to plot a wind rose (from where the dinw blows)
85
86mainn = 'drawing.py'
87
88errormsg = 'ERROR -- error -- ERROR -- error'
89warnmsg = 'WARNING -- waring -- WARNING -- warning'
90fillValue=1.e20
91
92namegraphics = ['create_movie', 'draw_2D_shad', 'draw_2D_shad_time',                 \
93  'draw_2D_shad_cont', 'draw_2D_shad_cont_time', 'draw_2D_shad_line',                \
94  'draw_2D_shad_line_time', 'draw_barbs', 'draw_basins',                             \
95  'draw_2lines', 'draw_2lines_time', 'draw_lines', 'draw_lines_time',                \
96  'draw_Neighbourghood_evol',                                                        \
97  'draw_points', 'draw_points_lonlat',                                               \
98  'draw_ptZvals', 'draw_river_desc', 'draw_subbasin', 'draw_timeSeries',             \
99  'draw_topo_geogrid',                                                               \
100  'draw_topo_geogrid_boxes', 'draw_trajectories', 'draw_vals_trajectories',          \
101  'draw_vectors',  'draw_vertical_levels', 'list_graphics', 'draw_WindRose',         \
102  'variable_values']
103
104def draw_2D_shad(ncfile, values, varn, axfig=None, fig=None):
105    """ plotting a fields with shading
106    draw_2D_shad(ncfile, values, varn)
107      ncfile= file to use
108      values=[vnamefs]:[dimvals]:[dimxvn]:[dimyvn]:[dimxyfmt]:[colorbarvals]:[sminv],[smaxv]:[figt]:
109       [kindfig]:[reverse]:[mapv]:[close]
110        [vnamefs]: Name in the figure of the variable to be shaded
111        [dimvals]: ',' list of [dimname]|[value] telling at which dimension of the
112          variable a given value is required:
113            * [integer]: which value of the dimension
114            * -1: all along the dimension
115            * -9: last value of the dimension
116            * [beg]@[end]@[inc] slice from [beg] to [end] every [inc]
117            * NOTE, no dim name all the dimension size
118        [dimx/yvn]: name of the variables with the values of the final dimensions (x,y)
119        [dimxyfmt]=[dxs],[dxf],[Ndx],[ordx],[dys],[dyf],[Ndy],[ordx]: format of the values at each axis (or 'auto')
120          [dxs]: style of x-axis ('auto' for 'pretty')
121            'Nfix', values computed at even 'Ndx'
122            'Vfix', values computed at even 'Ndx' increments
123            'pretty', values computed following aprox. 'Ndx' at 'pretty' intervals (2.,2.5,4,5,10)
124          [dxf]: format of the labels at the x-axis ('auto' for '%5g')
125          [Ndx]: Number of ticks at the x-axis ('auto' for 5)
126          [ordx]: angle of orientation of ticks at the x-axis ('auto' for horizontal)
127          [dys]: style of y-axis ('auto' for 'pretty')
128          [dyf]: format of the labels at the y-axis ('auto' for '%5g')
129          [Ndy]: Number of ticks at the y-axis ('auto' for 5)
130          [ordy]: angle of orientation of ticks at the y-axis ('auto' for horizontal)
131        [colorbarvals]=[colbarn],[fmtcolorbar],[orientation]
132          [colorbarn]: name of the color bar
133          [fmtcolorbar]: format of the numbers in the color bar 'C'-like ('auto' for %6g)
134          [orientation]: orientation of the colorbar ('vertical' (default, by 'auto'), 'horizontal')
135        [smin/axv]: minimum and maximum value for the shading or:
136          'Srange': for full range
137          'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean)
138          'Saroundminmax@val': for min*val,max*val
139          'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val),
140            percentile_(100-val)-median)
141          'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean)
142          'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median)
143          'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val),
144             percentile_(100-val)-median)
145        [figt]: title of the figure ('|' for spaces)
146        [kindfig]: kind of figure
147        [reverse]: Transformation of the values
148          * 'transpose': reverse the axes (x-->y, y-->x)
149          * 'flip'@[x/y]: flip the axis x or y
150        [mapv]: map characteristics: [proj],[res]
151          see full documentation: http://matplotlib.org/basemap/
152          [proj]: projection
153            * 'cyl', cilindric
154            * 'lcc', lambert conformal
155          [res]: resolution:
156            * 'c', crude
157            * 'l', low
158            * 'i', intermediate
159            * 'h', high
160            * 'f', full
161        [close]: Whether figure should be finished or not
162      valules= 'rh:z|-1,x|-1:z|-1,x|-1:lat:pressure:BuPu:0.,100.:rh:pdf:flip@y:None'
163      varn= [varsn] name of the variable to plot with shading
164    """
165
166    fname = 'draw_2D_shad'
167    if values == 'h':
168        print fname + '_____________________________________________________________'
169        print draw_2D_shad.__doc__
170        quit()
171
172    expectargs = '[vnamefs]:[dimvals]:[dimxvn]:[dimyvn]:[dimxyf]:[colbarvals]:' +    \
173      '[sminv],[smaxv]:[figt]:[kindfig]:[reverse]:[mapv]:[close]'
174 
175    drw.check_arguments(fname,values,expectargs,':')
176
177    vnamesfig = values.split(':')[0]
178    dimvals= values.split(':')[1].replace('|',':')
179    vdimxn = values.split(':')[2]
180    vdimyn = values.split(':')[3]
181    dimxyf = values.split(':')[4]
182    colorbarvals = values.split(':')[5]
183    shadminmax = values.split(':')[6]
184    figtitle = values.split(':')[7].replace('|',' ')
185    figkind = values.split(':')[8]
186    revals = values.split(':')[9]
187    mapvalue = values.split(':')[10]
188    close = gen.Str_Bool(values.split(':')[11])
189
190    ncfiles = ncfile
191   
192    if not os.path.isfile(ncfiles):
193        print errormsg
194        print '  ' + fname + ': shading file "' + ncfiles + '" does not exist !!'
195        quit(-1)   
196
197    objsf = NetCDFFile(ncfiles, 'r')
198   
199    varns = varn.split(',')[0]
200
201    if  not objsf.variables.has_key(varns):
202        print errormsg
203        print '  ' + fname + ': shading file "' + ncfiles +                          \
204          '" does not have variable "' +  varns + '" !!'
205        quit(-1)
206
207# Variables' values
208    objvars = objsf.variables[varns]
209
210    valshad, dimsshad = drw.slice_variable(objvars, dimvals.replace(',','|'))
211
212# Dimensions names
213##    print fname + ' obj dimnames: ', objvars.dimensions, dimvals, len(dimvals.split(','))
214##    dimnamesv = []
215##    for idd in range(len(objvars.dimensions)):
216##        cutdim = False
217##        for idc in range(len(dimvals.split(','))):
218##            dimcutn = dimvals.split(',')[idc].split(':')[0]
219##            print objvars.dimensions[idd], dimcutn
220##            if objvars.dimensions[idd] == dimcutn:
221##                cutdim = True
222##                break
223##        if not cutdim: dimnamesv.append(objvars.dimensions[idd])
224    dimnamesv = [vdimxn, vdimyn]
225
226    if drw.searchInlist(objvars.ncattrs(),'units'):
227        varunits = objvars.getncattr('units')
228    else:
229        print warnmsg
230        print '  ' + fname + ": variable '" + varn + "' without units!!"
231        varunits = '-'
232
233    if  not objsf.variables.has_key(vdimxn):
234        print errormsg
235        print '  ' + fname + ': shading file "' + ncfiles +                          \
236          '" does not have dimension variable "' +  vdimxn + '" !!'
237        quit(-1)
238    if  not objsf.variables.has_key(vdimyn):
239        print errormsg
240        print '  ' + fname + ': shading file "' + ncfiles +                          \
241          '" does not have dimension variable "' +  vdimyn + '" !!'
242        quit(-1)
243
244    objdimx = objsf.variables[vdimxn]
245    objdimy = objsf.variables[vdimyn]
246    if drw.searchInlist(objdimx.ncattrs(),'units'):
247        odimxu = objdimx.getncattr('units')
248    else:
249        print warnmsg
250        print '  ' + fname + ": variable dimension '" + vdimxn + "' without units!!"
251        odimxu = '-'
252
253    if drw.searchInlist(objdimy.ncattrs(),'units'):
254        odimyu = objdimy.getncattr('units')
255    else:
256        print warnmsg
257        print '  ' + fname + ": variable dimension '" + vdimyn + "' without units!!"
258        odimyu = '-'
259
260    odimxv, odimyv = drw.dxdy_lonlatDIMS(objdimx[:], objdimy[:], objdimx.dimensions,     \
261      objdimy.dimensions, dimvals.replace(':','|').split(','))
262
263    shading_nx = []
264    if shadminmax.split(',')[0][0:1] != 'S':
265            shading_nx.append(np.float(shadminmax.split(',')[0]))
266    else:
267        shading_nx.append(shadminmax.split(',')[0])
268
269    if shadminmax.split(',')[1][0:1] != 'S':
270        shading_nx.append(np.float(shadminmax.split(',')[1]))
271    else:
272        shading_nx.append(shadminmax.split(',')[1])
273
274    if mapvalue == 'None': mapvalue = None
275
276    colbarn, fmtcolbar, colbaror = drw.colorbar_vals(colorbarvals,',')
277    colormapv = [colbarn, fmtcolbar, colbaror]
278
279    xstyl, xaxf, Nxax, xaxor, ystyl, yaxf, Nyax, yaxor = drw.format_axes(dimxyf,',')
280    xaxis = [xstyl, xaxf, Nxax, xaxor]
281    yaxis = [ystyl, yaxf, Nyax, yaxor]
282
283    if revals == 'None':
284        revals = None
285
286    drw.plot_2D_shadow(valshad, vnamesfig, odimxv, odimyv, odimxu, odimyu, xaxis,    \
287      yaxis, dimnamesv, colormapv, shading_nx, varunits, figtitle, figkind, revals,  \
288      mapvalue, close)
289
290    return
291
292def draw_2D_shad_time(ncfile, values, varn):
293    """ plotting a fields with shading with time values
294    draw_2D_shad_time(ncfile, values, varn)
295      ncfile= file to use
296      values=[vnamefs]~[dimvals]~[dimxvn]~[dimyvn]~[dimvfmt]~[colorbarvals]~[sminv],[smaxv]~[figt]~
297       [kindfig]~[reverse]~[timevals]~[close]
298        [vnamefs]: Name in the figure of the variable to be shaded
299        [dimvals]: ',' list of [dimname]|[value] telling at which dimension of the
300          variable a given value is required:
301            * [integer]: which value of the dimension
302            * -1: all along the dimension
303            * -9: last value of the dimension
304            * [beg]@[end]@[inc] slice from [beg] to [end] every [inc]
305            * NOTE, no dim name all the dimension size
306        [dimx/yvn]: name of the variables with the values of the final dimensions (x,y)  ('WRFtime' for WRF times)
307        [dimvfmt]=[dvs],[dvf],[Ndv],[ordv]: format of the values for the non-temporal axis (or 'auto')
308          [dvs]: style of non-temporal axis ('auto' for 'pretty')
309            'Nfix', values computed at even 'Ndx'
310            'Vfix', values computed at even 'Ndx' increments
311            'pretty', values computed following aprox. 'Ndx' at 'pretty' intervals (2.,2.5,4,5,10)
312          [dvf]: format of the labels at the x-axis ('auto' for '%5g')
313          [Ndv]: Number of ticks at the x-axis ('auto' for 5)
314          [ordv]: angle of orientation of ticks at the x-axis ('auto' for horizontal)
315        [colorbarvals]=[colbarn],[fmtcolorbar],[orientation]
316          [colorbarn]: name of the color bar
317          [fmtcolorbar]: format of the numbers in the color bar 'C'-like ('auto' for %6g)
318          [orientation]: orientation of the colorbar ('vertical' (default, by 'auto'), 'horizontal')
319        [smin/axv]: minimum and maximum value for the shading or:
320          'Srange': for full range
321          'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean)
322          'Saroundminmax@val': for min*val,max*val
323          'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val),
324            percentile_(100-val)-median)
325          'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean)
326          'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median)
327          'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val),
328             percentile_(100-val)-median)
329        [figt]: title of the figure ('|' for spaces)
330        [kindfig]: kind of figure
331        [reverse]: Transformation of the values
332          * 'transpose': reverse the axes (x-->y, y-->x)
333          * 'flip'@[x/y]: flip the axis x or y
334        [timevals]: [timen]|[units]|[kind]|[tfmt]|[label]|[timeaxis] time labels characteristics
335           [timen]; name of the time variable ('WRFtime' for WRF times)
336           [units]; units string according to CF conventions ([tunits] since
337             [YYYY]-[MM]-[DD] [[HH]:[MI]:[SS]], '!' for spaces)
338           [kind]; kind of output
339             'Nval': according to a given number of values as 'Nval',[Nval]
340             'exct': according to an exact time unit as 'exct',[tunit];
341               tunit= [Nunits],[tu]; [tu]= 'c': centuries, 'y': year, 'm': month,
342                'w': week, 'd': day, 'h': hour, 'i': minute, 's': second,
343                'l': milisecond
344           [tfmt]; desired format
345           [label]; label at the graph ('!' for spaces)
346        [close]: should figure be closed (finished)
347      values='dtcon~Time|-1,bottom_top|-1~presmean~time~auto~seismic,auto,auto~-3.e-6,3.e-6~monthly|'
348        'dtcon~pdf~transpose~time|hours!since!1949-12-01|exct,2,d|%d|date!([DD])~True
349      varn= [varsn] name of the variable to plot with shading
350    """
351    fname = 'draw_2D_shad_time'
352
353    if values == 'h':
354        print fname + '_____________________________________________________________'
355        print draw_2D_shad_time.__doc__
356        quit()
357
358    farguments = '[vnamefs]~[dimvals]~[dimxvn]~[dimyvn]~[dimvfmt]~[colorbarvals]~' + \
359      '[sminv],[smaxv]~[figt]~[kindfig]~[reverse]~[timevals]~[close]'
360    drw.check_arguments(fname,values,farguments,'~')
361
362    vnamesfig = values.split('~')[0]
363    dimvals= values.split('~')[1].replace('|',':')
364    vdimxn = values.split('~')[2]
365    vdimyn = values.split('~')[3]
366    dimvfmt = values.split('~')[4]   
367    colorbarvals = values.split('~')[5]
368    shadminmax = values.split('~')[6]
369    figtitle = values.split('~')[7].replace('|',' ')
370    figkind = values.split('~')[8]
371    revals = values.split('~')[9]
372    timevals = values.split('~')[10]
373    close = gen.Str_Bool(values.split('~')[11])
374
375    ncfiles = ncfile
376   
377    if not os.path.isfile(ncfiles):
378        print errormsg
379        print '  ' + fname + ': shading file "' + ncfiles + '" does not exist !!'
380        quit(-1)   
381
382    objsf = NetCDFFile(ncfiles, 'r')
383   
384    varns = varn.split(',')[0]
385
386    if  not objsf.variables.has_key(varns):
387        print errormsg
388        print '  ' + fname + ': shading file "' + ncfiles +                          \
389          '" does not have variable "' +  varns + '" !!'
390        quit(-1)
391
392# Variables' values
393    objvars = objsf.variables[varns]
394
395    valshad, dimsshad = drw.slice_variable(objvars, dimvals.replace(',','|'))
396
397    dimnamesv = [vdimxn, vdimyn]
398
399    varunits = objvars.getncattr('units')
400
401    if vdimxn != 'WRFtime' and not objsf.variables.has_key(vdimxn):
402        print errormsg
403        print '  ' + fname + ": shading file '" + ncfiles +                          \
404          "' does not have dimension variable '" +  vdimxn + "' !!"
405        quit(-1)
406    if vdimyn != 'WRFtime' and not objsf.variables.has_key(vdimyn):
407        print errormsg
408        print '  ' + fname + ": shading file '" + ncfiles +                          \
409          "' does not have dimension variable '" +  vdimyn + " !!'"
410        quit(-1)
411
412    timename = timevals.split('|')[0]
413    timeunit = timevals.split('|')[1].replace('!',' ')
414    timekind = timevals.split('|')[2]
415    timefmt = timevals.split('|')[3]
416    timelabel = timevals.split('|')[4].replace('!',' ')
417
418    if vdimxn == 'WRFtime' or vdimyn == 'WRFtime':
419        tunitsec = timeunit.split(' ')
420        if len(tunitsec) == 4:
421            refdate = tunitsec[2][0:4]+tunitsec[2][5:7]+tunitsec[2][8:10] +          \
422              tunitsec[3][0:2] + tunitsec[3][3:5] + tunitsec[3][6:8]
423        else:
424            refdate = tunitsec[2][0:4]+tunitsec[2][5:7]+tunitsec[2][8:10]+ '000000'
425        tunitsval = tunitsec[0]
426           
427        timewrfv = objsf.variables['Times']
428        dt = timewrfv.shape[0]
429        cftimes = np.zeros((dt), dtype=np.float)
430
431        for it in range(dt):
432            wrfdates = gen.datetimeStr_conversion(timewrfv[it,:],'WRFdatetime',      \
433              'matYmdHMS')
434            cftimes[it] = gen.realdatetime1_CFcompilant(wrfdates, refdate, tunitsval)
435
436    if vdimxn != 'WRFtime':
437        objdimx = objsf.variables[vdimxn]
438        objdimxv = objdimx[:]
439        odimxu = objdimx.getncattr('units')
440    else:
441        objdimxv = cftimes
442        odimxu = timeunit
443
444    if vdimyn != 'WRFtime':
445        objdimy = objsf.variables[vdimyn]
446        objdimyv = objdimy[:]
447        odimyu = objdimy.getncattr('units')
448    else:
449        objdimyv = cftimes
450        odimyu = timeunit
451
452    if len(objdimxv.shape) <= 2:
453        odimxv0 = objdimxv[:]
454    elif len(objdimxv.shape) == 3:
455        odimxv0 = objdimxv[0,:]
456    else:
457        print errormsg
458        print '  ' + fname + ': shape of dimension variable:', objdimxv.shape,       \
459          ' not ready!!'
460        quit(-1)
461    if len(objdimyv.shape) <= 2:
462        odimyv0 = objdimyv[:]
463    elif len(objdimyv.shape) == 3:
464        odimyv0 = objdimyv[0,:]
465    else:
466        print errormsg
467        print '  ' + fname + ': shape of dimension variable:', objdimyv.shape,       \
468          ' not ready!!'
469        quit(-1)
470
471# Dimensional values
472    if vdimxn != 'WRFtime':
473        odxv, dimsdxv = drw.slice_variable(objsf.variables[vdimxn], dimvals.replace(',','|'))
474    else:
475        odxv = cftimes
476        dimsdxv = ['Time']
477
478    if vdimyn != 'WRFtime':
479        odyv, dimsdyv = drw.slice_variable(objsf.variables[vdimyn], dimvals.replace(',','|'))
480    else:
481        odyv = cftimes
482        dimsdyv = ['Time']
483
484    if vdimxn == timename:
485        odimxv = odxv
486        odimxu = timelabel
487        timeaxis = 'x'
488        odimyv = odyv
489        odimyu = objdimy.getncattr('units')
490        timepos, timelabels = drw.CFtimes_plot(odxv, timeunit, timekind, timefmt)
491    elif vdimyn == timename:
492        odimyv = odyv
493        odimyu = timelabel
494        timeaxis = 'y'
495        odimxv = odxv
496        odimxu = objdimx.getncattr('units')
497        timepos, timelabels = drw.CFtimes_plot(odyv, timeunit, timekind, timefmt)
498    else:
499        print errormsg
500        print '  ' + fname + ": time variable '" + timename + "' not found!!"
501        quit(-1)
502
503    shading_nx = []
504    if shadminmax.split(',')[0][0:1] != 'S':
505        shading_nx.append(np.float(shadminmax.split(',')[0]))
506    else:
507        shading_nx.append(shadminmax.split(',')[0])
508
509    if shadminmax.split(',')[1][0:1] != 'S':
510        shading_nx.append(np.float(shadminmax.split(',')[1]))
511    else:
512        shading_nx.append(shadminmax.split(',')[1])
513
514    colbarn, fmtcolbar, colbaror = drw.colorbar_vals(colorbarvals,',')
515    colormapv = [colbarn, fmtcolbar, colbaror]
516
517    if dimvfmt != 'auto': dimvfmt = dimvfmt + 'auto,auto,auto,auto'
518    xstyl, xaxf, Nxax, xaxor, ystyl, yaxf, Nyax, yaxor = drw.format_axes(dimvfmt,',')
519    vaxis = [xstyl, xaxf, Nxax, xaxor]
520
521    if revals == 'None':
522        revals = None
523
524    drw.plot_2D_shadow_time(valshad, vnamesfig, odxv, odyv, odimxu, odimyu,          \
525      dimnamesv, vaxis, colormapv, shading_nx, varunits, figtitle, figkind, revals,  \
526      timeaxis, timepos, timelabels, close)
527
528    return
529
530def draw_2D_shad_cont(ncfile, values, varn):
531    """ plotting two fields, one with shading and the other with contour lines
532    draw_2D_shad_cont(ncfile, values, varn)
533      ncfile= [ncfilevars],[ncfilevarc] files to use (one value, same file)
534      values=[vnamefs]:[dimvals]:[dimvalc]:[dimxvn]:[dimyvn]:[dimxyfmt]:[colorbarvals]:[ckind]:[clabfmt]:[sminv],[smaxv]:[sminc],[smaxv],[Nlev]:[figt]:[kindfig]:[reverse]:[mapv]:[close]
535        [vnamefs],[vnamefc]: Name in the figure of the shaded and the contour variables
536        [dimvals/c]: list of [dimname]|[value] telling at which dimension of the
537          variable a given value is required:
538            * [integer]: which value of the dimension
539            * -1: all along the dimension
540            * -9: last value of the dimension
541            * [beg]@[end]@[inc] slice from [beg] to [end] every [inc]
542            * NOTE, no dim name all the dimension size
543        [dimx/yvn]: names of the variables with the values of the dimensions for the plot
544        [dimxyfmt]=[dxf],[Ndx],[dyf],[Ndy]: format of the values at each axis
545          [dxs]: style of x-axis ('auto' for 'pretty')
546            'Nfix', values computed at even 'Ndx'
547            'Vfix', values computed at even 'Ndx' increments
548            'pretty', values computed following aprox. 'Ndx' at 'pretty' intervals (2.,2.5,4,5,10)
549          [dxf]: format of the labels at the x-axis
550          [Ndx]: Number of ticks at the x-axis
551          [ordx]: angle of orientation of ticks at the x-axis ('auto' for horizontal)
552          [dys]: style of y-axis ('auto' for 'pretty')
553          [dyf]: format of the labels at the y-axis
554          [Ndy]: Number of ticks at the y-axis
555          [ordy]: angle of orientation of ticks at the y-axis ('auto' for horizontal)
556        [colorbarvals]=[colbarn],[fmtcolorbar],[orientation]
557          [colorbarn]: name of the color bar
558          [fmtcolorbar]: format of the numbers in the color bar 'C'-like ('auto' for %6g)
559          [orientation]: orientation of the colorbar ('vertical' (default, by 'auto'), 'horizontal')
560        [ckind]: kind of contours
561          'cmap': as it gets from colorbar
562          'fixc,[colname]': fixed color [colname], all stright lines
563          'fixsigc,[colname]': fixed color [colname], >0 stright, <0 dashed  line
564        [clabfmt]: format of the labels in the contour (None, also possible)
565        [smin/axv]: minimum and maximum value for the shading or
566          'Srange': for full range
567          'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean)
568          'Saroundminmax@val': for min*val,max*val
569          'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val),
570            percentile_(100-val)-median)
571          'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean)
572          'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median)
573          'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val),
574             percentile_(100-val)-median)
575        [sminc]:[smaxv]:[Nlev]: minimum, maximum and number of values for the contour
576        [figt]: title of the figure ('|' for spaces)
577        [kindfig]: kind of figure
578        [reverse]: does the values be transposed? 'True/False',
579        [mapv]: map characteristics: [proj],[res]
580          see full documentation: http://matplotlib.org/basemap/
581          [proj]: projection
582            * 'cyl', cilindric
583            * 'lcc', lamvbert conformal
584          [res]: resolution:
585            * 'c', crude
586            * 'l', low
587            * 'i', intermediate
588            * 'h', high
589            * 'f', full
590        [close]: Whether figure should be finished or not
591      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'
592      varn= [varsn],[varcn] name of the variable to plot with shading variable with contour
593    """
594
595    fname = 'draw_2D_shad_cont'
596    if values == 'h':
597        print fname + '_____________________________________________________________'
598        print draw_2D_shad_cont.__doc__
599        quit()
600
601    expectargs = '[vnamefs]:[dimvals]:[dimvalc]:[dimxvn]:[dimyvn]:[dimxyf]:' +       \
602      '[colorbarvals]:[ckind]:[clabfmt]:[sminv],[smaxv]:[sminc],[smaxv],[Nlev]:' +   \
603      '[figt]:[kindfig]:[reverse]:[mapv]:[close]'
604 
605    drw.check_arguments(fname,values,expectargs,':')
606
607    vnamesfig = values.split(':')[0].split(',')
608    dimvals= values.split(':')[1].replace('|',':')
609    dimvalc= values.split(':')[2].replace('|',':')
610    vdimxn = values.split(':')[3]
611    vdimyn = values.split(':')[4]
612    dimxyf = values.split(':')[5]
613    colorbarvals = values.split(':')[6]
614    countkind = values.split(':')[7]
615    countlabelfmt = values.split(':')[8]
616    shadminmax = values.split(':')[9].split(',')
617    contlevels = values.split(':')[10]
618    figtitle = values.split(':')[11].replace('|',' ')
619    figkind = values.split(':')[12]
620    revals = values.split(':')[13]
621    mapvalue = values.split(':')[14]
622    close = gen.Str_Bool(values.split(':')[15])
623
624    if2filenames = ncfile.find(',')
625
626    if if2filenames != -1:
627        ncfiles = ncfile.split(',')[0]
628        ncfilec = ncfile.split(',')[1]
629    else:
630        ncfiles = ncfile
631        ncfilec = ncfile
632
633    if not os.path.isfile(ncfiles):
634        print errormsg
635        print '  ' + fname + ': shading file "' + ncfiles + '" does not exist !!'
636        quit(-1)   
637
638    if not os.path.isfile(ncfilec):
639        print errormsg
640        print '  ' + fname + ': contour file "' + ncfilec + '" does not exist !!'
641        quit(-1)   
642
643    objsf = NetCDFFile(ncfiles, 'r')
644    objcf = NetCDFFile(ncfilec, 'r')
645   
646    varns = varn.split(',')[0]
647    varnc = varn.split(',')[1]
648
649    if  not objsf.variables.has_key(varns):
650        print errormsg
651        print '  ' + fname + ': shading file "' + ncfiles +                          \
652          '" does not have variable "' +  varns + '" !!'
653        quit(-1)
654
655    if  not objcf.variables.has_key(varnc):
656        print errormsg
657        print '  ' + fname + ': contour file "' + ncfilec +                          \
658          '" does not have variable "' +  varnc + '" !!'
659        quit(-1)
660
661# Variables' values
662    objvars = objsf.variables[varns]
663    objvarc = objcf.variables[varnc]
664
665    if len(objvars.shape) != len(objvarc.shape):
666        print errormsg
667        print '  ' + fname + ': shading variable "' + varns + '" has a shape: ',     \
668          objvars.shape,  'different than contour variable "' +  varnc + '": ',      \
669          objvarc.shape,' !!!'
670        quit(-1)
671
672    for idim in range(len(objvars.shape)):
673        if objvars.shape[idim] != objvarc.shape[idim]:
674            print errormsg
675            print '  ' + fname + ': shading variable "' + varns + '" has a shape: ', \
676              objvars.shape,  'different than contour variable "' +  varnc + '": ',  \
677              objvarc.shape,' !!!'
678            quit(-1)
679
680    valshad, dimsshad = drw.slice_variable(objvars, dimvals.replace(',','|'))
681    valcont, dimscont = drw.slice_variable(objvarc, dimvalc.replace(',','|'))
682
683# Dimensions names
684##    print fname + ' obj dimnames: ', objvars.dimensions, dimvals, len(dimvals.split(','))
685##    dimnamesv = []
686##    for idd in range(len(objvars.dimensions)):
687##        cutdim = False
688##        for idc in range(len(dimvals.split(','))):
689##            dimcutn = dimvals.split(',')[idc].split(':')[0]
690##            print objvars.dimensions[idd], dimcutn
691##            if objvars.dimensions[idd] == dimcutn:
692##                cutdim = True
693##                break
694##        if not cutdim: dimnamesv.append(objvars.dimensions[idd])
695    dimnamesv = [vdimxn, vdimyn]
696
697    varunits = []
698    varunits.append(objvars.getncattr('units'))
699    varunits.append(objvarc.getncattr('units'))
700
701    if  not objsf.variables.has_key(vdimxn):
702        print errormsg
703        print '  ' + fname + ': shading file "' + ncfiles +                          \
704          '" does not have dimension variable "' +  vdimxn + '" !!'
705        quit(-1)
706    if  not objsf.variables.has_key(vdimyn):
707        print errormsg
708        print '  ' + fname + ': shading file "' + ncfiles +                          \
709          '" does not have dimension variable "' +  vdimyn + '" !!'
710        quit(-1)
711
712    objdimx = objsf.variables[vdimxn]
713    objdimy = objsf.variables[vdimyn]
714    odimxu = objdimx.getncattr('units')
715    odimyu = objdimy.getncattr('units')
716
717# Getting only that dimensions with coincident names
718    odimxv, odimyv = drw.dxdy_lonlatDIMS(objdimx[:], objdimy[:], objdimx.dimensions,     \
719      objdimy.dimensions, dimvals.replace(':','|').split(','))
720
721#    dimnvx = objdimx.dimensions
722#    cutslice = []
723#    for idimn in objdimx.dimensions:
724#        found = False
725#        for dimsn in dimsshad:
726#            if idimn == dimsn:
727#                cutslice.append(slice(0,len(objsf.dimensions[idimn])))
728#                found = True
729#        if not found: cutslice.append(0)
730#
731#    odimxv = objdimx[tuple(cutslice)]
732#
733#    dimnvy = objdimy.dimensions
734#    cutslice = []
735#    for idimn in objdimy.dimensions:
736#        found = False
737#        for dimsn in dimsshad:
738#            if idimn == dimsn:
739#                cutslice.append(slice(0,len(objsf.dimensions[idimn])))
740#                found = True
741#        if not found: cutslice.append(0)
742#
743#    odimyv = objdimy[tuple(cutslice)]
744
745#    if len(objdimx.shape) <= 2:
746#        odimxv = objdimx[:]
747#        odimyv = objdimy[:]
748#    elif len(objdimx.shape) == 3:
749#        odimxv = objdimx[0,:]
750#        odimyv = objdimy[0,:]
751#    else:
752#        print errormsg
753#        print '  ' + fname + ': shape of dimension variable:', objdimx.shape,        \
754#          ' not ready!!'
755#        quit(-1)
756
757    if countlabelfmt == 'None': 
758        countlfmt = None
759    else:
760        countlfmt = countlabelfmt
761
762    # Shading limits
763    shading_nx = drw.graphic_range(shadminmax,valshad)
764
765    # Contour limits
766    clevmin = np.float(contlevels.split(',')[0])
767    clevmax = np.float(contlevels.split(',')[1])
768    Nclevels = int(contlevels.split(',')[2])
769
770    levels_cont = gen.pretty_int(clevmin, clevmax, Nclevels)
771
772    if len(levels_cont) <= 1: 
773        print warnmsg
774        print '  ' + fname + ': wrong contour levels:', levels_cont,' !!'
775        del(levels_cont)
776        levels_cont = np.zeros((Nclevels), dtype=np.float)
777        levels_cont = np.arange(7)*(clevmax - clevmin)/(Nclevels-1)
778        print '    generating default ones: ',levels_cont
779
780    if mapvalue == 'None': mapvalue = None
781
782    colbarn, fmtcolbar, colbaror = drw.colorbar_vals(colorbarvals,',')
783
784    xstyl, xaxf, Nxax, xaxor, ystyl, yaxf, Nyax, yaxor = drw.format_axes(dimxyf,',')
785    xaxis = [xstyl, xaxf, Nxax, xaxor]
786    yaxis = [ystyl, yaxf, Nyax, yaxor]
787
788    if revals == 'None': revals = None
789
790    drw.plot_2D_shadow_contour(valshad, valcont, vnamesfig, odimxv, odimyv, odimxu,  \
791      odimyu, xaxis, yaxis, dimnamesv, [colbarn, fmtcolbar, colbaror], countkind,    \
792      countlfmt, shading_nx, levels_cont, varunits, figtitle, figkind, revals,       \
793      mapvalue, close)
794
795    return
796
797def draw_2D_shad_cont_time(ncfile, values, varn):
798    """ plotting two fields, one with shading and the other with contour lines being
799    one of the dimensions of time characteristics
800    draw_2D_shad_cont_time(ncfile, values, varn)
801      ncfile= [ncfilevars],[ncfilevarc] files to use (one value, same file)
802      values=[vnamefs];[dimvals];[dimvalc];[dimxvn];[dimyvn];[dimxyf];[colorbarvals];[ckind];[clabfmt];[sminv],[smaxv];[sminc],[smaxv],[Nlev];[figt];[kindfig];[reverse];[timevals];[close]
803        [vnamefs],[vnamefc]: Name in the figure of the shaded and the contour variables
804        [dimvals/c]: list of [dimname]|[value] telling at which dimension of the
805          variable a given value is required:
806            * [integer]: which value of the dimension
807            * -1: all along the dimension
808            * -9: last value of the dimension
809            * [beg]@[end]@[inc] slice from [beg] to [end] every [inc]
810            * NOTE, no dim name all the dimension size
811        [dimxvn]: name of the variables with the values of the dimension of the x-axis ('WRFtime' for WRF times)
812        [dimyvn]: name of the variables with the values of the dimension of the y-axis ('WRFtime' for WRF times)
813        [dimxyf]=[dxf],[Ndx],[dyf],[Ndy]: format of the values at each axis
814          [dxs]: style of x-axis ('auto' for 'pretty')
815            'Nfix', values computed at even 'Ndx' (unique map plotted with constant pixel size)
816            'Vfix', values computed at even 'Ndx' increments
817            'pretty', values computed following aprox. 'Ndx' at 'pretty' intervals (2.,2.5,4,5,10)
818          [dxf]: format of the labels at the x-axis
819          [Ndx]: Number of ticks at the x-axis
820          [ordx]: angle of orientation of ticks at the x-axis ('auto' for horizontal)
821          [dys]: style of y-axis ('auto' for 'pretty')
822          [dyf]: format of the labels at the y-axis
823          [Ndy]: Number of ticks at the y-axis
824          [ordy]: angle of orientation of ticks at the y-axis ('auto' for horizontal)
825        [colorbarvals]=[colbarn],[fmtcolorbar],[orientation]
826          [colorbarn]: name of the color bar
827          [fmtcolorbar]: format of the numbers in the color bar 'C'-like ('auto' for %6g)
828          [orientation]: orientation of the colorbar ('vertical' (default, by 'auto'), 'horizontal')
829        [ckind]: kind of contours
830          'cmap': as it gets from colorbar
831          'fixc,[colname]': fixed color [colname], all stright lines
832          'fixsigc,[colname]': fixed color [colname], >0 stright, <0 dashed  line
833        [clabfmt]: format of the labels in the contour (None, also possible)
834        [smin/axv]: minimum and maximum value for the shading or:
835          'Srange': for full range
836          'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean)
837          'Saroundminmax@val': for min*val,max*val
838          'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val),
839            percentile_(100-val)-median)
840          'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean)
841          'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median)
842          'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val),
843             percentile_(100-val)-median)
844        [sminc]:[smaxv]:[Nlev]: minimum, maximum and number of values for the contour
845        [figt]: title of the figure ('|' for spaces)
846        [kindfig]: kind of figure
847        [reverse]: modification to the dimensions:
848          'transposed': transpose matrices
849          'flip',[x/y]: flip only the dimension [x] or [y]
850        [timevals]: [timen]|[units]|[kind]|[tfmt]|[label] time labels characteristics
851          [timen]; name of the time variable ('WRFtime' for WRF times)
852          [units]; units string according to CF conventions ([tunits] since
853            [YYYY]-[MM]-[DD] [[HH]:[MI]:[SS]], '!' for spaces)
854          [kind]; kind of output
855            'Nval': according to a given number of values as 'Nval',[Nval]
856            'exct': according to an exact time unit as 'exct',[tunit];
857              tunit= [Nunits],[tu]; [tu]= 'c': centuries, 'y': year, 'm': month,
858               'w': week, 'd': day, 'h': hour, 'i': minute, 's': second,
859               'l': milisecond
860          [tfmt]; desired format
861          [label]; label at the graph ('!' for spaces)
862        [close]: Whether figure should be finished or not
863      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])'
864      varn= [varsn],[varcn] name of the variable to plot with shading variable with contour
865    """
866
867    fname = 'draw_2D_shad_cont_time'
868    if values == 'h':
869        print fname + '_____________________________________________________________'
870        print draw_2D_shad_cont_time.__doc__
871        quit()
872
873    expectargs = '[vnamefs];[dimvals];[dimvalc];[dimxvn];[dimyvn];[dimxyf];' +       \
874      '[colorbarvals];[ckind];[clabfmt];[sminv],[smaxv];[sminc],[smaxv],[Nlev];' +   \
875      '[figt];[kindfig];[reverse];[timevals];[close]'
876 
877    drw.check_arguments(fname,values,expectargs,';')
878
879    vnamesfig = values.split(';')[0].split(',')
880    dimvals= values.split(';')[1].replace('|',':')
881    dimvalc= values.split(';')[2].replace('|',':')
882    vdimxn = values.split(';')[3]
883    vdimyn = values.split(';')[4]
884    dimxyf = values.split(';')[5]
885    colorbarvals = values.split(';')[6]
886    countkind = values.split(';')[7]
887    countlabelfmt = values.split(';')[8]
888    shadminmax = values.split(';')[9]
889    contlevels = values.split(';')[10]
890    figtitle = values.split(';')[11].replace('|',' ')
891    figkind = values.split(';')[12]
892    revals = values.split(';')[13]
893    timevals = values.split(';')[14]
894    close = gen.Str_Bool(values.split(';')[15])
895
896    if2filenames = ncfile.find(',')
897
898    if if2filenames != -1:
899        ncfiles = ncfile.split(',')[0]
900        ncfilec = ncfile.split(',')[1]
901    else:
902        ncfiles = ncfile
903        ncfilec = ncfile
904
905    if not os.path.isfile(ncfiles):
906        print errormsg
907        print '  ' + fname + ': shading file "' + ncfiles + '" does not exist !!'
908        quit(-1)   
909
910    if not os.path.isfile(ncfilec):
911        print errormsg
912        print '  ' + fname + ': contour file "' + ncfilec + '" does not exist !!'
913        quit(-1)   
914
915    objsf = NetCDFFile(ncfiles, 'r')
916    objcf = NetCDFFile(ncfilec, 'r')
917   
918    varns = varn.split(',')[0]
919    varnc = varn.split(',')[1]
920
921    if  not objsf.variables.has_key(varns):
922        print errormsg
923        print '  ' + fname + ': shading file "' + ncfiles +                          \
924          '" does not have variable "' +  varns + '" !!'
925        quit(-1)
926
927    if  not objcf.variables.has_key(varnc):
928        print errormsg
929        print '  ' + fname + ': contour file "' + ncfilec +                          \
930          '" does not have variable "' +  varnc + '" !!'
931        quit(-1)
932
933# Variables' values
934    objvars = objsf.variables[varns]
935    objvarc = objcf.variables[varnc]
936
937    if len(objvars.shape) != len(objvarc.shape):
938        print errormsg
939        print '  ' + fname + ': shading variable "' + varns + '" has a shape: ',     \
940          objvars.shape,  'different than contour variable "' +  varnc + '": ',      \
941          objvarc.shape,' !!!'
942        quit(-1)
943
944    for idim in range(len(objvars.shape)):
945        if objvars.shape[idim] != objvarc.shape[idim]:
946            print errormsg
947            print '  ' + fname + ': shading variable "' + varns + '" has a shape: ', \
948              objvars.shape,  'different than contour variable "' +  varnc + '": ',  \
949              objvarc.shape,' !!!'
950            quit(-1)
951
952    valshad, dimsshad = drw.slice_variable(objvars, dimvals.replace(',','|'))
953    valcont, dimscont = drw.slice_variable(objvarc, dimvalc.replace(',','|'))
954
955    dimnamesv = [vdimxn, vdimyn]
956
957    varunits = []
958    varunits.append(objvars.getncattr('units'))
959    varunits.append(objvarc.getncattr('units'))
960
961    if vdimxn != 'WRFtime' and not objsf.variables.has_key(vdimxn):
962        print errormsg
963        print '  ' + fname + ': shading file "' + ncfiles +                          \
964          '" does not have dimension variable "' +  vdimxn + '" !!'
965        quit(-1)
966    if vdimyn != 'WRFtime' and not objsf.variables.has_key(vdimyn):
967        print errormsg
968        print '  ' + fname + ': shading file "' + ncfiles +                          \
969          '" does not have dimension variable "' +  vdimyn + '" !!'
970        quit(-1)
971
972    timename = timevals.split('|')[0]
973    timeunit = timevals.split('|')[1].replace('!',' ')
974    timekind = timevals.split('|')[2]
975    timefmt = timevals.split('|')[3]
976    timelabel = timevals.split('|')[4].replace('!',' ')
977
978    if vdimxn == 'WRFtime' or vdimyn == 'WRFtime':
979        tunitsec = timeunit.split(' ')
980        if len(tunitsec) == 4:
981            refdate = tunitsec[2][0:4]+tunitsec[2][5:7]+tunitsec[2][8:10] +          \
982              tunitsec[3][0:2] + tunitsec[3][3:5] + tunitsec[3][6:8]
983        else:
984            refdate = tunitsec[2][0:4]+tunitsec[2][5:7]+tunitsec[2][8:10]+ '000000'
985        tunitsval = tunitsec[0]
986
987        timewrfv = objsf.variables['Times']
988        dt = timewrfv.shape[0]
989        cftimes = np.zeros((dt), dtype=np.float)
990
991        for it in range(dt):
992            wrfdates = gen.datetimeStr_conversion(timewrfv[it,:],'WRFdatetime',      \
993              'matYmdHMS')
994            cftimes[it] = gen.realdatetime1_CFcompilant(wrfdates, refdate, tunitsval)
995
996    if vdimxn == timename:
997        if vdimxn == 'WRFtime':
998            timevals = cftimes
999            timedims = ['Time']
1000        else:
1001            timevals = objsf.variables[vdimxn][:]
1002            timedims = objsf.variables[vdimxn].dimensions
1003        dimt = 'x'
1004        ovalaxis = objsf.variables[vdimyn]
1005        ovalu = ovalaxis.getncattr('units')
1006    elif vdimyn == timename:
1007        if vdimyn == 'WRFtime':
1008            timevals = cftimes
1009            timedims = ['Time']
1010        else:
1011            timevals = objsf.variables[vdimyn][:]
1012            timedims = objsf.variables[vdimyn].dimensions
1013        dimt = 'y'
1014        ovalaxis = objsf.variables[vdimxn]
1015        ovalu = ovalaxis.getncattr('units')
1016    else:
1017        print errormsg
1018        print '  ' + fname + ": time variable '" + timename + "' not found!!"
1019        quit(-1)
1020
1021    timepos, timelabels = drw.CFtimes_plot(timevals, timeunit, timekind, timefmt)
1022
1023# Getting only that dimensions with coincident names
1024    dimnvx = ovalaxis.dimensions
1025    dimsliceaxis = []
1026    for dimv in dimvals.split(','):
1027        adimvn = dimv.split(':')[0]
1028        adimval = dimv.split(':')[1]
1029        found = False
1030        for dimtn in timedims:
1031            if adimvn == dimtn:
1032                dimsliceaxis.append(adimvn + ':0')
1033                found = True
1034                break
1035        if not found:
1036            dimsliceaxis.append(dimv)
1037
1038    dimsliceaxisS = '|'.join(dimsliceaxis)
1039
1040    ovalaxisv, odimaxisv = drw.slice_variable(ovalaxis,dimsliceaxisS)
1041
1042    if countlabelfmt == 'None': 
1043        countlfmt = None
1044    else:
1045        countlfmt = countlabelfmt
1046
1047    shading_nx = []
1048    if shadminmax.split(',')[0][0:1] != 'S':
1049            shading_nx.append(np.float(shadminmax.split(',')[0]))
1050    else:
1051        shading_nx.append(shadminmax.split(',')[0])
1052
1053    if shadminmax.split(',')[1][0:1] != 'S':
1054        shading_nx.append(np.float(shadminmax.split(',')[1]))
1055    else:
1056        shading_nx.append(shadminmax.split(',')[1])
1057
1058    clevmin = np.float(contlevels.split(',')[0])
1059    clevmax = np.float(contlevels.split(',')[1])
1060    Nclevels = int(contlevels.split(',')[2])
1061
1062    levels_cont = gen.pretty_int(clevmin, clevmax, Nclevels)
1063
1064    if len(levels_cont) <= 1: 
1065        print warnmsg
1066        print '  ' + fname + ': wrong contour levels:', levels_cont,' !!'
1067        del(levels_cont)
1068        levels_cont = np.zeros((Nclevels), dtype=np.float)
1069        levels_cont = np.arange(7)*(clevmax - clevmin)/(Nclevels-1)
1070        print '    generating default ones: ',levels_cont
1071
1072    colbarn, fmtcolbar, colbaror = drw.colorbar_vals(colorbarvals,',')
1073
1074    xstyl, xaxf, Nxax, xaxor, ystyl, yaxf, Nyax, yaxor = drw.format_axes(dimxyf,',')
1075    xaxis = [xstyl, xaxf, Nxax, xaxor]
1076    yaxis = [ystyl, yaxf, Nyax, yaxor]
1077
1078    if revals == 'None': revals = None
1079
1080    drw.plot_2D_shadow_contour_time(valshad, valcont, vnamesfig, ovalaxisv,         \
1081      timevals, timepos, timelabels, ovalu, timelabel, dimt, xaxis, yaxis,          \
1082      dimnamesv, [colbarn, fmtcolbar, colbaror], countkind, countlfmt, shading_nx,  \
1083      levels_cont, varunits, figtitle, figkind, revals, close)
1084
1085    return
1086
1087def draw_2D_shad_line(ncfile, values, varn):
1088    """ plotting a fields with shading and another with line
1089    draw_2D_shad_line(ncfile, values, varn)
1090      ncfile= [ncfiles],[ncfilel] file to use for the shading and for the line
1091      values=[vnamefs],[vnamefl]:[dimvals]:[dimxvn]:[dimyvn]:[dimxyfmt]:[colorbarvals]:[smin/axv]:[linevalues]:[figt]:
1092       [kindfig]:[reverse]:[mapv]:[close]
1093        [vnamefs]: Name in the figure of the variable to be shaded
1094        [vnamefl]: Name in the figure of the variable to be lined
1095        [dimvals]: ',' list of [dimname]|[value] telling at which dimension of the
1096          variable a given value is required:
1097            * [integer]: which value of the dimension
1098            * -1: all along the dimension
1099            * -9: last value of the dimension
1100            * [beg]@[end]@[inc] slice from [beg] to [end] every [inc]
1101            * NOTE, no dim name all the dimension size
1102        [dimx/yvn]: name of the variables with the values of the final dimensions (x,y)
1103        [dimxyfmt]=[dxs],[dxf],[Ndx],[ordx],[dys],[dyf],[Ndy],[ordx]: format of the values at each axis (or 'auto')
1104          [dxs]: style of x-axis ('auto' for 'pretty')
1105            'Nfix', values computed at even 'Ndx'
1106            'Vfix', values computed at even 'Ndx' increments
1107            'pretty', values computed following aprox. 'Ndx' at 'pretty' intervals (2.,2.5,4,5,10)
1108          [dxf]: format of the labels at the x-axis ('auto' for '%5g')
1109          [Ndx]: Number of ticks at the x-axis ('auto' for 5)
1110          [ordx]: angle of orientation of ticks at the x-axis ('auto' for horizontal)
1111          [dys]: style of y-axis ('auto' for 'pretty')
1112          [dyf]: format of the labels at the y-axis ('auto' for '%5g')
1113          [Ndy]: Number of ticks at the y-axis ('auto' for 5)
1114          [ordy]: angle of orientation of ticks at the y-axis ('auto' for horizontal)
1115        [colorbarvals]=[colbarn],[fmtcolorbar],[orientation]
1116          [colorbarn]: name of the color bar
1117          [fmtcolorbar]: format of the numbers in the color bar 'C'-like ('auto' for %6g)
1118          [orientation]: orientation of the colorbar ('vertical' (default, by 'auto'), 'horizontal')
1119        [smin/axv]: minimum and maximum value for the shading or:
1120          'Srange': for full range
1121          'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean)
1122          'Saroundminmax@val': for min*val,max*val
1123          'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val),
1124            percentile_(100-val)-median)
1125          'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean)
1126          'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median)
1127          'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val),
1128             percentile_(100-val)-median)
1129        [linevalues]=[colline],[sminl],[smaxl],[dls],[dlf],[Ndl],[ordl]
1130          [colline]: name of the color for the line
1131          [smin/axv]: minimum and maximum value for the line or:
1132            'Srange': for full range
1133             'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean)
1134            'Saroundminmax@val': for min*val,max*val
1135            'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val),
1136              percentile_(100-val)-median)
1137            'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean)
1138            'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median)
1139            'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val),
1140               percentile_(100-val)-median)
1141          [dls]: style of line-axis ('auto' for 'pretty')
1142          [dlf]: format of the labels at the line-axis ('auto' for '%5g')
1143          [Ndl]: Number of ticks at the line-axis ('auto' for 5)
1144          [ordl]: angle of orientation of ticks at the line-axis ('auto' for horizontal)
1145        [figt]: title of the figure ('|' for spaces)
1146        [kindfig]: kind of figure
1147        [reverse]: Transformation of the values
1148          * 'transpose': reverse the axes (x-->y, y-->x)
1149          * 'flip'@[x/y]: flip the axis x or y
1150        [mapv]: map characteristics: [proj],[res]
1151          see full documentation: http://matplotlib.org/basemap/
1152          [proj]: projection
1153            * 'cyl', cilindric
1154            * 'lcc', lamvbert conformal
1155          [res]: resolution:
1156            * 'c', crude
1157            * 'l', low
1158            * 'i', intermediate
1159            * 'h', high
1160            * 'f', full
1161        [close]: Whether figure should be finished or not
1162      valules= 'rh:z|-1,x|-1:z|-1,x|-1:lat:pressure:BuPu:0.,100.:rh:pdf:flip@y:None'
1163      varn= [varsn],[varnl] name of the variable to plot with shading and with line
1164    """
1165
1166    fname = 'draw_2D_shad_line'
1167    if values == 'h':
1168        print fname + '_____________________________________________________________'
1169        print draw_2D_shad_line.__doc__
1170        quit()
1171
1172    farguments = '[vnamefs],[vnamefl]:[dimvals]:[dimxvn]:[dimyvn]:' +                \
1173      '[dimxyfmt]:[colorbarvals]:[smin/axv]:[linevalues]:[figt]:[kindfig]:' +        \
1174      '[reverse]:[mapv]:[close]'
1175    drw.check_arguments(fname,values,farguments,':')
1176
1177    vnamesfig = values.split(':')[0].split(',')[0]
1178    dimvals= values.split(':')[1].replace('|',':')
1179    vdimxn = values.split(':')[2]
1180    vdimyn = values.split(':')[3]
1181    dimxyf = values.split(':')[4]
1182    colorbarvals = values.split(':')[5]
1183    shadminmax = values.split(':')[6]
1184    linevalues = values.split(':')[7]
1185    figtitle = values.split(':')[8].replace('|',' ')
1186    figkind = values.split(':')[9]
1187    revals = values.split(':')[10]
1188    mapvalue = values.split(':')[11]
1189    close = gen.Str_Bool(values.split(':')[12])
1190
1191    ncfiles = ncfile.split(',')[0]
1192   
1193    if not os.path.isfile(ncfiles):
1194        print errormsg
1195        print '  ' + fname + ': shading file "' + ncfiles + '" does not exist !!'
1196        quit(-1)   
1197
1198    objsf = NetCDFFile(ncfiles, 'r')
1199   
1200    varns = varn.split(',')[0]
1201
1202    if  not objsf.variables.has_key(varns):
1203        print errormsg
1204        print '  ' + fname + ': shading file "' + ncfiles +                          \
1205          '" does not have variable "' +  varns + '" !!'
1206        quit(-1)
1207
1208# Variables' values
1209    objvars = objsf.variables[varns]
1210
1211    valshad, dimsshad = drw.slice_variable(objvars, dimvals.replace(',','|'))
1212
1213# Dimensions names
1214    dimnamesv = [vdimxn, vdimyn]
1215
1216    varunits = objvars.getncattr('units')
1217
1218    if  not objsf.variables.has_key(vdimxn):
1219        print errormsg
1220        print '  ' + fname + ': shading file "' + ncfiles +                          \
1221          '" does not have dimension variable "' +  vdimxn + '" !!'
1222        quit(-1)
1223    if  not objsf.variables.has_key(vdimyn):
1224        print errormsg
1225        print '  ' + fname + ': shading file "' + ncfiles +                          \
1226          '" does not have dimension variable "' +  vdimyn + '" !!'
1227        quit(-1)
1228
1229    objdimx = objsf.variables[vdimxn]
1230    objdimy = objsf.variables[vdimyn]
1231    if drw.searchInlist(objdimx.ncattrs(),'units'):
1232        odimxu = objdimx.getncattr('units')
1233    else:
1234        print warnmsg
1235        print '  ' + fname + ": variable dimension '" + vdimxn + "' without units!!"
1236        odimxu = '-'
1237
1238    if drw.searchInlist(objdimy.ncattrs(),'units'):
1239        odimyu = objdimy.getncattr('units')
1240    else:
1241        print warnmsg
1242        print '  ' + fname + ": variable dimension '" + vdimyn + "' without units!!"
1243        odimyu = '-'
1244
1245    odimxv, odimyv = drw.dxdy_lonlatDIMS(objdimx[:], objdimy[:], objdimx.dimensions,     \
1246      objdimy.dimensions, dimvals.replace(':','|').split(','))
1247
1248    shading_nx = []
1249    if shadminmax.split(',')[0][0:1] != 'S':
1250            shading_nx.append(np.float(shadminmax.split(',')[0]))
1251    else:
1252        shading_nx.append(shadminmax.split(',')[0])
1253
1254    if shadminmax.split(',')[1][0:1] != 'S':
1255        shading_nx.append(np.float(shadminmax.split(',')[1]))
1256    else:
1257        shading_nx.append(shadminmax.split(',')[1])
1258
1259# line plot
1260##
1261    linearg = linevalues.split(',')
1262    if linevalues.split(',')[1][0:1] != 'S':
1263        linearg[1] = np.float(linevalues.split(',')[1])
1264    if linevalues.split(',')[2][0:1] != 'S':
1265        linearg[2] = np.float(linevalues.split(',')[2])
1266    if linearg[3] == 'auto': linearg[3] = 'pretty'
1267    if linearg[4] == 'auto': linearg[4] = '5g'
1268    if linearg[5] == 'auto': linearg[5] = 5
1269    if linearg[6] == 'auto': linearg[6] = 0.
1270
1271    ncfilel = ncfile.split(',')[1]
1272    vnamelfig = values.split(':')[0].split(',')[1]
1273    varnl = varn.split(',')[1]
1274
1275    if not os.path.isfile(ncfilel):
1276        print errormsg
1277        print '  ' + fname + ': file for line "' + ncfilel + '" does not exist !!'
1278        quit(-1)
1279    objlf = NetCDFFile(ncfilel,'r')
1280
1281    if  not objlf.variables.has_key(varnl):
1282        print errormsg
1283        print '  ' + fname + ': line file "' + ncfilel +                            \
1284          '" does not have variable "' +  varnl + '" !!'
1285        quit(-1)
1286    objlvar = objlf.variables[varnl]
1287    linevals, dimsline = drw.slice_variable(objlvar, dimvals.replace(',','|'))
1288    varlunits = objlvar.units
1289
1290    if mapvalue == 'None': mapvalue = None
1291
1292    colbarn, fmtcolbar, colbaror = drw.colorbar_vals(colorbarvals,',')
1293    colormapv = [colbarn, fmtcolbar, colbaror]
1294
1295    xstyl, xaxf, Nxax, xaxor, ystyl, yaxf, Nyax, yaxor = drw.format_axes(dimxyf,',')
1296    xaxis = [xstyl, xaxf, Nxax, xaxor]
1297    yaxis = [ystyl, yaxf, Nyax, yaxor]
1298
1299    if revals == 'None':
1300        revals = None
1301
1302    drw.plot_2D_shadow_line(valshad, linevals, vnamesfig, vnamelfig, odimxv, odimyv, \
1303      odimxu, odimyu, dimnamesv, xaxis, yaxis, colormapv, linearg, shading_nx,       \
1304      varunits, varlunits, figtitle, figkind, revals, mapvalue, close)
1305
1306    objsf.close()
1307    objlf.close()
1308
1309    return
1310
1311def draw_2D_shad_line_time(ncfile, values, varn):
1312    """ plotting a fields with shading and a line with time values
1313    draw_2D_shad_line(ncfile, values, varn)
1314      ncfile= [ncfiles],[ncfilel] files to use to draw with shading and the line
1315      values= [vnamefs],[vanemefl];[dimvals];[dimxvn];[dimyvn];[dimxyfmt];[colorbarvals];[sminv],[smaxv];
1316        [figt];[kindfig];[reverse];[timevals];[close]
1317        [vnamefs]: Name in the figure of the variable to be shaded
1318        [vnamefl]: Name in the figure of the variable to be lined
1319        [dimvals]: ',' list of [dimname]|[value] telling at which dimension of the
1320          variable a given value is required:
1321            * [integer]: which value of the dimension
1322            * -1: all along the dimension
1323            * -9: last value of the dimension
1324            * [beg]@[end]@[inc] slice from [beg] to [end] every [inc]
1325            * NOTE, no dim name all the dimension size
1326        [dimx/yvn]: name of the variables with the values of the final dimensions (x,y)
1327        [dimxyfmt]=[dxs],[dxf],[Ndx],[ordx],[dys],[dyf],[Ndy],[ordx]: format of the values at each axis (or 'auto')
1328          [dxs]: style of x-axis ('auto' for 'pretty')
1329            'Nfix', values computed at even 'Ndx'
1330            'Vfix', values computed at even 'Ndx' increments
1331            'pretty', values computed following aprox. 'Ndx' at 'pretty' intervals (2.,2.5,4,5,10)
1332          [dxf]: format of the labels at the x-axis ('auto' for '%5g')
1333          [Ndx]: Number of ticks at the x-axis ('auto' for 5)
1334          [ordx]: angle of orientation of ticks at the x-axis ('auto' for horizontal)
1335          [dys]: style of y-axis ('auto' for 'pretty')
1336          [dyf]: format of the labels at the y-axis ('auto' for '%5g')
1337          [Ndy]: Number of ticks at the y-axis ('auto' for 5)
1338          [ordy]: angle of orientation of ticks at the y-axis ('auto' for horizontal)
1339        [colorbarvals]=[colbarn],[fmtcolorbar],[orientation]
1340          [colorbarn]: name of the color bar
1341          [fmtcolorbar]: format of the numbers in the color bar 'C'-like ('auto' for %6g)
1342          [orientation]: orientation of the colorbar ('vertical' (default, by 'auto'), 'horizontal')
1343        [smin/axv]: minimum and maximum value for the shading or:
1344          'Srange': for full range
1345          'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean)
1346          'Saroundminmax@val': for min*val,max*val
1347          'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val),
1348            percentile_(100-val)-median)
1349          'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean)
1350          'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median)
1351          'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val),
1352             percentile_(100-val)-median)
1353        [linevalues]=[colline],[sminl],[smaxl],[dls],[dlf],[Ndl],[ordl]
1354          [colline]: name of the color for the line
1355          [smin/axv]: minimum and maximum value for the line or:
1356            'Srange': for full range
1357             'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean)
1358            'Saroundminmax@val': for min*val,max*val
1359            'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val),
1360              percentile_(100-val)-median)
1361            'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean)
1362            'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median)
1363            'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val),
1364               percentile_(100-val)-median)
1365          [dls]: style of line-axis ('auto' for 'pretty')
1366          [dlf]: format of the labels at the line-axis ('auto' for '%5g')
1367          [Ndl]: Number of ticks at the line-axis ('auto' for 5)
1368          [ordl]: angle of orientation of ticks at the line-axis ('auto' for horizontal)
1369        [figt]: title of the figure ('|' for spaces)
1370        [kindfig]: kind of figure
1371        [reverse]: Transformation of the values
1372          * 'transpose': reverse the axes (x-->y, y-->x)
1373          * 'flip'@[x/y]: flip the axis x or y
1374        [timevals]: [timen]|[units]|[kind]|[tfmt]|[label]|[timeaxis] time labels characteristics
1375           [timen]; name of the time variable
1376           [units]; units string according to CF conventions ([tunits] since
1377             [YYYY]-[MM]-[DD] [[HH]:[MI]:[SS]], '!' for spaces)
1378           [kind]; kind of output
1379             'Nval': according to a given number of values as 'Nval',[Nval]
1380             'exct': according to an exact time unit as 'exct',[tunit];
1381               tunit= [Nunits],[tu]; [tu]= 'c': centuries, 'y': year, 'm': month,
1382                'w': week, 'd': day, 'h': hour, 'i': minute, 's': second,
1383                'l': milisecond
1384           [tfmt]; desired format
1385           [label]; label at the graph ('!' for spaces)
1386        [close]: should figure be closed (finished)
1387      values='dtcon,prc:Time|-1,bottom_top|-1:presmean:time:seismic:-3.e-6,3.e-6:monthly|'
1388        'dtcon:pdf:transpose:time|hours!since!1949-12-01|exct,2,d|%d|date!([DD])|x:True
1389      varn= [varsn].[varln] name of the variable to plot with shading and to plot with line
1390    """
1391    fname = 'draw_2D_shad_line_time'
1392    if values == 'h':
1393        print fname + '_____________________________________________________________'
1394        print draw_2D_shad__line_time.__doc__
1395        quit()
1396
1397    farguments = '[vnamefs],[vanemefl];[dimvals];[dimxvn];[dimyvn];[dimxyfmt];' +    \
1398      '[colorbarvals];[sminv],[smaxv];[linevalues];[figt];[kindfig];[reverse];[timevals];[close]'
1399    drw.check_arguments(fname,values,farguments,';')
1400
1401    vnamesfig = values.split(';')[0]
1402    dimvals= values.split(';')[1].replace('|',':')
1403    vdimxn = values.split(';')[2]
1404    vdimyn = values.split(';')[3]
1405    dimxyfmt = values.split(';')[4]
1406    colorbarvals = values.split(';')[5]
1407    shadminmax = values.split(';')[6]
1408    linevalues = values.split(';')[7]
1409    figtitle = values.split(';')[8].replace('|',' ')
1410    figkind = values.split(';')[9]
1411    revals = values.split(';')[10]
1412    timevals = values.split(';')[11]
1413    close = gen.Str_Bool(values.split(';')[12])
1414
1415    ncfiles = ncfile.split(',')[0]
1416    ncfilel = ncfile.split(',')[1]
1417
1418    vshadn = vnamesfig.split(',')[0]
1419    vlinen = vnamesfig.split(',')[1]
1420   
1421    if not os.path.isfile(ncfiles):
1422        print errormsg
1423        print '  ' + fname + ': shading file "' + ncfiles + '" does not exist !!'
1424        quit(-1)   
1425    if not os.path.isfile(ncfilel):
1426        print errormsg
1427        print '  ' + fname + ': line file "' + ncfilel + '" does not exist !!'
1428        quit(-1)   
1429
1430    objsf = NetCDFFile(ncfiles, 'r')
1431   
1432    varns = varn.split(',')[0]
1433
1434    if  not objsf.variables.has_key(varns):
1435        print errormsg
1436        print '  ' + fname + ': shading file "' + ncfiles +                          \
1437          '" does not have variable "' +  varns + '" !!'
1438        quit(-1)
1439
1440# Variables' values
1441    objvars = objsf.variables[varns]
1442
1443    valshad, dimsshad = drw.slice_variable(objvars, dimvals.replace(',','|'))
1444
1445    dimnamesv = [vdimxn, vdimyn]
1446
1447    varunits = objvars.getncattr('units')
1448
1449    if vdimxn != 'WRFtime' and not objsf.variables.has_key(vdimxn):
1450        print errormsg
1451        print '  ' + fname + ': shading file "' + ncfiles +                          \
1452          '" does not have dimension variable "' +  vdimxn + '" !!'
1453        quit(-1)
1454    if vdimyn != 'WRFtime' and not objsf.variables.has_key(vdimyn):
1455        print errormsg
1456        print '  ' + fname + ': shading file "' + ncfiles +                          \
1457          '" does not have dimension variable "' +  vdimyn + '" !!'
1458        quit(-1)
1459
1460    timename = timevals.split('|')[0]
1461    timeunit = timevals.split('|')[1].replace('!',' ')
1462    timekind = timevals.split('|')[2]
1463    timefmt = timevals.split('|')[3]
1464    timelabel = timevals.split('|')[4].replace('!',' ')
1465
1466    # Getting time as WRF Times
1467    if timename == 'WRFtime':
1468        dictslice = {}
1469        for dnv in dimvals.split(','):
1470            dimn = dnv.split(':')[0]
1471            dimv = dnv.split(':')[1]
1472            if dimv.find(',') != -1: 
1473                dictslice[dimn] = list(np.array(dimv.split(','), dtype=int))
1474            else:
1475                dictslice[dimn] = int(dimv)
1476
1477        wrft = objsf.variables['Times']
1478        slicewrft, dwrfd = ncvar.SliceVarDict(wrft, dictslice)
1479        timewrfv = wrft[tuple(slicewrft)]
1480        if len(timeunit.split(' ')) > 3:
1481            refdateS = timeunit.split(' ')[2] + ' ' + timeunit.split(' ')[3]
1482        else:
1483            refdateS = timeunit.split(' ')[2] + ' 00:00:00'
1484        tunitsval = timeunit.split(' ')[0]
1485
1486        yrref=refdateS[0:4]
1487        monref=refdateS[5:7]
1488        dayref=refdateS[8:10]
1489        horref=refdateS[11:13]
1490        minref=refdateS[14:16]
1491        secref=refdateS[17:19]
1492
1493        refdate = yrref + monref + dayref + horref + minref + secref
1494
1495        dt = timewrfv.shape[0]
1496        cftimes = np.zeros((dt), dtype=np.float)
1497        for it in range(dt):
1498            wrfdates = gen.datetimeStr_conversion(timewrfv[it,:],        \
1499              'WRFdatetime', 'matYmdHMS')
1500            cftimes[it] = gen.realdatetime1_CFcompilant(wrfdates,        \
1501              refdate, tunitsval)
1502        tunits = tunitsval + ' since ' + refdateS
1503
1504    if vdimxn == timename:
1505        if timename != 'WRFtime':
1506            odimxv = objsf.variables[vdimxn][:]
1507        else:
1508            odimxv = cftimes
1509        odimxu = timelabel
1510        timeaxis = 'x'
1511        objdimyv = objsf.variables[vdimyn]
1512        odimyv = objdimyv[:]
1513        odimyu = objdimyv.getncattr('units')
1514        timepos, timelabels = drw.CFtimes_plot(odimxv, timeunit, timekind, timefmt)
1515    elif vdimyn == timename:
1516        if timename != 'WRFtime':
1517            odimyv = objsf.variables[vdimxn][:]
1518        else:
1519            odimyv = cftimes
1520        odimyu = timelabel
1521        timeaxis = 'y'
1522        objdimxv = objsf.variables[vdimxn]
1523        odimxv = objdimxv[:]
1524        odimxu = objdimxv.getncattr('units')
1525        timepos, timelabels = drw.CFtimes_plot(odimyv, timeunit, timekind, timefmt)
1526    else:
1527        print errormsg
1528        print '  ' + fname + ": time variable '" + timename + "' not found!!"
1529        quit(-1)
1530
1531    shading_nx = shadminmax.split(',')
1532
1533# Line values
1534##
1535    linearg = linevalues.split(',')
1536    if linevalues.split(',')[1][0:1] != 'S':
1537        linearg[1] = np.float(linevalues.split(',')[1])
1538    if linevalues.split(',')[2][0:1] != 'S':
1539        linearg[2] = np.float(linevalues.split(',')[2])
1540    if linearg[3] == 'auto': linearg[3] = 'pretty'
1541    if linearg[4] == 'auto': linearg[4] = '5g'
1542    if linearg[5] == 'auto': linearg[5] = 5
1543    if linearg[6] == 'auto': linearg[6] = 0.
1544
1545    vnamelfig = values.split(':')[0].split(',')[1]
1546    varnl = varn.split(',')[1]
1547
1548    objlf = NetCDFFile(ncfilel,'r')
1549    objlvar = objlf.variables[varnl]
1550
1551    linevals, dimsline = drw.slice_variable(objlvar, dimvals.replace(',','|'))
1552    varlunits = objlvar.units
1553
1554    colbarn, fmtcolbar, colbaror = drw.colorbar_vals(colorbarvals,',')
1555    colormapv = [colbarn, fmtcolbar, colbaror]
1556
1557    xstyl, xaxf, Nxax, xaxor, ystyl, yaxf, Nyax, yaxor = drw.format_axes(dimxyfmt,',')
1558    xaxis = [xstyl, xaxf, Nxax, xaxor]
1559    yaxis = [ystyl, yaxf, Nyax, yaxor]
1560
1561    if revals == 'None':
1562        revals = None
1563
1564    drw.plot_2D_shadow_line_time(valshad, linevals, vshadn, vlinen, odimxv, odimyv,  \
1565      odimxu, odimyu, dimnamesv, xaxis, yaxis, colormapv, linearg, shading_nx,       \
1566      varunits, varlunits, figtitle, figkind, revals, timeaxis, timepos, timelabels, \
1567      close)
1568
1569    objsf.close()
1570    objlf.close()
1571
1572    return
1573
1574def draw_barbs(ncfile, values, varns):
1575    """ Function to plot wind barbs
1576      draw_barbs(ncfile, values, varns)
1577      values= [dimname]|[vardimname]|[value]:[vecvals]:[windlabs]:[dimxv]:[dimyv]:[mapvalues]:[dimxyfmt]:
1578        [transform]:[gtit]:[kindfig]:[figuren]:[close]
1579        [dimname]|[vardimname]|[value]: ',', list for each basic dimension '|' separated of:
1580          [dimname]: name of the dimension in the file
1581          [vardimname]: name of the variable with the values for the dimension in the file
1582          [value]: which value of the given dimension (-1, all; [ibeg]@[iend], i-range beginning, end)
1583          No value takes all the range of the dimension
1584        [vecvals]= [frequency],[color],[length]
1585          [frequency]: [xfreq]@[yfreq] frequency of values allong each axis ('None', all grid points;
1586            'auto', computed automatically to have 20 vectors along each axis)
1587          [color]: color of the vectors ('auto', for 'red') two options:
1588            [colorname]: name of the color fixed for all vectors
1589            'colormap'@[colormapname]: use colormap to provide the colors tacking wind speed as reference
1590          [length]: length of the wind barbs ('auto', for 9)
1591        [windlabs]= [windname],[windunits]
1592          [windname]: name of the wind variable in the graph
1593          [windunits]: units of the wind variable in the graph ('None', for the value in the file)
1594        [dimxvn]: Variables with the final values for the x dimension
1595        [dimyvn]: Variables with the final values for the y dimension
1596        [mapvalues]= map characteristics: [proj],[res]
1597          see full documentation: http://matplotlib.org/basemap/
1598          [proj]: projection
1599            * 'cyl', cilindric
1600            * 'lcc', lambert conformal
1601          [res]: resolution:
1602            * 'c', crude
1603            * 'l', low
1604            * 'i', intermediate
1605            * 'h', high
1606            * 'f', full
1607        [dimxyfmt]=[dxs],[dxf],[Ndx],[ordx],[dys],[dyf],[Ndy],[ordx]: format of the values at each axis (or 'auto')
1608          [dxs]: style of x-axis ('auto' for 'pretty')
1609            'Nfix', values computed at even 'Ndx'
1610            'Vfix', values computed at even 'Ndx' increments
1611            'pretty', values computed following aprox. 'Ndx' at 'pretty' intervals (2.,2.5,4,5,10)
1612          [dxf]: format of the labels at the x-axis ('auto' for '%5g')
1613          [Ndx]: Number of ticks at the x-axis ('auto' for 5)
1614          [ordx]: angle of orientation of ticks at the x-axis ('auto' for horizontal)
1615          [dys]: style of y-axis ('auto' for 'pretty')
1616          [dyf]: format of the labels at the y-axis ('auto' for '%5g')
1617          [Ndy]: Number of ticks at the y-axis ('auto' for 5)
1618          [ordy]: angle of orientation of ticks at the y-axis ('auto' for horizontal)
1619        [transform]: Transformation of the values
1620          * 'transpose': reverse the axes (x-->y, y-->x)
1621          * 'flip'@[x/y]: flip the axis x or y
1622        [gtit]= title of the graph ('|', for spaces)
1623        [kindfig]= kind of figure
1624        [figuren]= name of the figure
1625        [close]= whether figure should be finished or not
1626      ncfile= file to use
1627      varns= [uwind],[ywind] ',' list of the name of the variables with the u-wind,y-wind component
1628    """
1629    fname = 'draw_barbs'
1630
1631    if values == 'h':
1632        print fname + '_____________________________________________________________'
1633        print draw_barbs.__doc__
1634        quit()
1635
1636    expectargs = '[dimname]|[vardimname]|[value]:[vecvals]:[windlabs]:[dimxv]:' +   \
1637      '[dimyv]:[mapvalues]:[dimxyfmt]:[transform]:[gtit]:[kindfig]:[figuren]:[close]'
1638 
1639    drw.check_arguments(fname,values,expectargs,':')
1640
1641    dimvals = values.split(':')[0]
1642    vecvals = values.split(':')[1]
1643    windlabels = values.split(':')[2]
1644    dimxvn = values.split(':')[3]
1645    dimyvn = values.split(':')[4]
1646    mapvalues = values.split(':')[5]
1647    dimxyfmt = values.split(':')[6]
1648    reverse = values.split(':')[7]
1649    gtit = values.split(':')[8]
1650    kindfig = values.split(':')[9]
1651    figuren = values.split(':')[10]
1652    close = gen.Str_Bool(values.split(':')[11])
1653
1654    of = NetCDFFile(ncfile,'r')
1655
1656    # Dictionary with the dimension name and its associated variable and slice
1657    dims = {}
1658    for dimv in dimvals.split(','):
1659        dns = dimv.split('|')
1660        dims[dns[0]] = [dns[1], dns[2]]
1661
1662    varNs = [dimxvn, dimyvn]
1663    for dn in dims.keys():
1664        vdn = dims[dn]
1665        if vdn == dimxvn:
1666            dimx = len(of.dimensions[dn])
1667        elif vdn == dimyvn:
1668            dimy = len(of.dimensions[dn])
1669
1670    # x-y variable-dimensions' names
1671    xydimns = [dimxvn, dimyvn]
1672    # x-y variable-dimensions' units
1673    xydimus = []
1674    odimx = of.variables[xydimns[0]]
1675    odimax = odimx.ncattrs()
1676    if gen.searchInlist(odimax,'units'):
1677        xydimus.append(odimx.getncattr('units'))
1678        odimy = of.variables[xydimns[1]]
1679        xydimus.append(odimy.getncattr('units'))
1680    else:
1681        xydimus= [gen.variable_values(xydimns[0])[4],gen.variable_values(xydimns[1])[4]]
1682
1683    ivar = 0
1684    for wvar in varns.split(','):
1685        if not drw.searchInlist(of.variables.keys(), wvar):
1686            print errormsg
1687            print '  ' + fname + ": file does not have variable '" + wvar + "' !!"
1688            quit(-1)
1689        if ivar == 0:
1690            varNs.append(wvar)
1691        else:
1692            varNs.append(wvar)
1693
1694    ivar = 0
1695    for varN in varNs:
1696        varslice = []
1697
1698        ovarN = of.variables[varN]
1699        vard = ovarN.dimensions
1700        for vdn in vard:
1701            found = False
1702            for dd in dims.keys():
1703                if dd == vdn:
1704                    if dims[dd][1].find('@') != -1:
1705                        rvals = dims[dd][1].split('@')
1706                        varslice.append(slice(int(rvals[0]), int(rvals[1])))
1707                    elif dims[dd][1] == '-1':
1708                        varslice.append(slice(0,len(of.dimensions[dd])))
1709                    else:
1710                        varslice.append(int(dims[dd][1]))
1711
1712                    found = True
1713                    break
1714            if not found:
1715                varslice.append(slice(0,len(of.dimensions[vdn])))
1716
1717        if ivar == 0:
1718            lonvals0 = np.squeeze(ovarN[tuple(varslice)])
1719        elif ivar == 1:
1720            latvals0 = np.squeeze(ovarN[tuple(varslice)])
1721        elif ivar == 2:
1722            uwvals = np.squeeze(np.array(ovarN[tuple(varslice)]))
1723        elif ivar == 3:
1724            vwvals = np.squeeze(ovarN[tuple(varslice)])           
1725
1726        ivar = ivar + 1
1727
1728#    print 'Final shapes:',lonvals0.shape,':',latvals0.shape,':',uwvals.shape,':',
1729#      vwvals.shape
1730
1731    if len(uwvals.shape) != 2 or len(vwvals.shape) != 2:
1732        print errormsg
1733        print '  ' + fname + ': wrong size of the wind fields! they must be ' +      \
1734          '2-dimensional!'
1735        print '    u-winds shape:',uwvals.shape,'dims:',of.variables[varNs[2]]
1736        print '    v-winds shape:',vwvals.shape,'dims:',of.variables[varNs[3]]
1737        print '      provide more values for their dimensions!!'
1738        quit(-1)
1739
1740    if len(lonvals0.shape) == 1:
1741        lonvals, latvals = np.meshgrid(lonvals0, latvals0)
1742    else:
1743        lonvals = lonvals0
1744        latvals = latvals0
1745
1746# Vecor values
1747    if vecvals.split(',')[0] == 'None':
1748        freqv = None
1749    else:
1750        freqv = vecvals.split(',')[0] 
1751    colorv = vecvals.split(',')[1]
1752    lengthv = vecvals.split(',')[2]
1753
1754# Vector labels
1755    windname = windlabels.split(',')[0]
1756    windunits = windlabels.split(',')[1]
1757
1758    xstyl, xaxf, Nxax, xaxor, ystyl, yaxf, Nyax, yaxor = drw.format_axes(dimxyfmt,',')
1759    xaxis = [xstyl, xaxf, Nxax, xaxor]
1760    yaxis = [ystyl, yaxf, Nyax, yaxor]
1761
1762    if mapvalues == 'None':
1763        mapvs = None
1764    else:
1765        mapvs = mapvalues
1766
1767    if reverse == 'None':
1768        revs = None
1769    else:
1770        revs = reverse
1771
1772    drw.plot_barbs(lonvals, latvals, uwvals, vwvals, freqv, colorv, lengthv,         \
1773      windname, windunits, xaxis, yaxis, xydimns, xydimus, mapvs, revs, gtit,        \
1774      kindfig, figuren, close)
1775
1776    return
1777 
1778def draw_topo_geogrid(ncfile, values):
1779    """ plotting geo_em.d[nn].nc topography from WPS files
1780    draw_topo_geogrid(ncfile, values)
1781      ncfile= geo_em.d[nn].nc file to use
1782      values= [minTopo],[maxTopo]:[lonlatL]:[title]:[graphic_kind]:[mapvalues]
1783        [min/max]Topo: minimum and maximum values of topography to draw
1784        lonlatL: limits of longitudes and latitudes [lonmin, latmin, lonmax, latmax] or None
1785        title: title of the graph ('!' for spaces)
1786        graphic_kind: kind of figure (jpg, pdf, png)
1787        mapvalues: map characteristics [proj],[res]
1788          see full documentation: http://matplotlib.org/basemap/
1789          [proj]: projection
1790            * 'cyl', cilindric
1791            * 'lcc', lambert conformal
1792          [res]: resolution:
1793            * 'c', crude
1794            * 'l', low
1795            * 'i', intermediate
1796            * 'h', high
1797            * 'f', full
1798        close: Whether figure should be finished or not
1799    """
1800    fname = 'draw_topo_geogrid'
1801
1802    if values == 'h':
1803        print fname + '_____________________________________________________________'
1804        print draw_topo_geogrid.__doc__
1805        quit()
1806
1807    expectargs= '[minTopo],[maxTopo]:[lonlatL]:[title]:[graphic_kind]:[mapvalues]:'+ \
1808      '[close]'
1809 
1810    drw.check_arguments(fname,values,expectargs,':')
1811
1812    mintopo = np.float(values.split(':')[0].split(',')[0])
1813    maxtopo = np.float(values.split(':')[0].split(',')[1])
1814
1815    lonlatLS = values.split(':')[1]
1816    lonlatLv = lonlatLS.split(',')[0]
1817
1818    if lonlatLv == 'None':
1819        lonlatL = None
1820    else:
1821        lonlatL = np.zeros((4), dtype=np.float)
1822        lonlatL[0] = np.float(lonlatLS.split(',')[0])
1823        lonlatL[1] = np.float(lonlatLS.split(',')[1])
1824        lonlatL[2] = np.float(lonlatLS.split(',')[2])
1825        lonlatL[3] = np.float(lonlatLS.split(',')[3])
1826
1827    grtit = values.split(':')[2].replace('!',' ')
1828    kindfig = values.split(':')[3]
1829    mapvalues = values.split(':')[4]
1830    close = gen.Str_Bool(values.split(':')[5])
1831
1832    if not os.path.isfile(ncfile):
1833        print errormsg
1834        print '  ' + fname + ': domain file "' + ncfile + '" does not exist !!'
1835        quit(-1)   
1836
1837    objdomf = NetCDFFile(ncfile, 'r')
1838   
1839    objhgt = objdomf.variables['HGT_M']
1840    objlon = objdomf.variables['XLONG_M']
1841    objlat = objdomf.variables['XLAT_M']
1842
1843    topography = objhgt[0,:,:]
1844
1845    drw.plot_topo_geogrid(topography, objlon, objlat, mintopo, maxtopo, lonlatL,     \
1846      grtit, kindfig, mapvalues, close)
1847
1848    objdomf.close()
1849
1850    return
1851
1852def draw_topo_geogrid_boxes(ncfiles, values):
1853    """ plotting different geo_em.d[nn].nc topography from WPS files
1854    draw_topo_geogrid_boxes(ncfiles, values)
1855      ncfiles= ',' list of geo_em.d[nn].nc files to use (fisrt as topographyc reference)
1856      values= [minTopo],[maxTopo]:[lonlatL]:[title]:[graphic_kind]:[mapvalues]:[labels]:[legvals]:[close]
1857        [min/max]Topo: minimum and maximum values of topography to draw
1858        lonlatL: limits of longitudes and latitudes [lonmin, latmin, lonmax, latmax] or None
1859        title: title of the graph ('!' for spaces)
1860        graphic_kind: kind of figure (jpg, pdf, png)
1861        mapvalues: map characteristics [proj],[res]
1862          see full documentation: http://matplotlib.org/basemap/
1863          [proj]: projection
1864            * 'cyl', cilindric
1865            * 'lcc', lambert conformal
1866          [res]: resolution:
1867            * 'c', crude
1868            * 'l', low
1869            * 'i', intermediate
1870            * 'h', high
1871            * 'f', full
1872        legvals: [locleg]|[fontsize]:
1873          [locleg]: location of the legend (0, autmoatic)
1874            1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
1875            5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
1876            9: 'upper center', 10: 'center'
1877          [fontsize]: font size for the legend (auto for 12)
1878        labels: labels to write in the graph ('!' for spaces)
1879        close: Whether figure should be finished or not
1880    """
1881#    import matplotlib as mpl
1882#    mpl.use('Agg')
1883    import matplotlib.pyplot as plt
1884
1885    fname = 'draw_topo_geogrid_boxes'
1886
1887    if values == 'h':
1888        print fname + '_____________________________________________________________'
1889        print draw_topo_geogrid_boxes.__doc__
1890        quit()
1891
1892    expectargs = '[minTopo],[maxTopo]:[lonlatL]:[title]:[graphic_kind]:[mapvalues]:'+\
1893       '[labels]:[legvals]:[close]'
1894    drw.check_arguments(fname,values,expectargs,':')
1895
1896    mintopo = np.float(values.split(':')[0].split(',')[0])
1897    maxtopo = np.float(values.split(':')[0].split(',')[1])
1898
1899    lonlatLS = values.split(':')[1]
1900    lonlatLv = lonlatLS.split(',')[0]
1901
1902    if lonlatLv == 'None':
1903        lonlatL = None
1904    else:
1905        lonlatL = np.zeros((4), dtype=np.float)
1906        lonlatL[0] = np.float(lonlatLS.split(',')[0])
1907        lonlatL[1] = np.float(lonlatLS.split(',')[1])
1908        lonlatL[2] = np.float(lonlatLS.split(',')[2])
1909        lonlatL[3] = np.float(lonlatLS.split(',')[3])
1910
1911    grtit = values.split(':')[2].replace('!', ' ')
1912    kindfig = values.split(':')[3]
1913    mapvalues = values.split(':')[4]
1914    labels = values.split(':')[5]
1915    legvals = values.split(':')[6]
1916    close = gen.Str_Bool(values.split(':')[7])
1917
1918    ncfile = ncfiles.split(',')[0]
1919    if not os.path.isfile(ncfile):
1920        print errormsg
1921        print '  ' + fname + ': domain file "' + ncfile + '" does not exist !!'
1922        quit(-1)   
1923
1924    objdomf = NetCDFFile(ncfile, 'r')
1925   
1926    objhgt = objdomf.variables['HGT_M']
1927    objlon0 = objdomf.variables['XLONG_M']
1928    objlat0 = objdomf.variables['XLAT_M']
1929
1930    topography = objhgt[0,:,:]
1931
1932    Nfiles = len(ncfiles.split(','))
1933    boxlabels = labels.split(',')
1934
1935    Xboxlines = []
1936    Yboxlines = []
1937
1938    for ifile in range(Nfiles):
1939        ncfile = ncfiles.split(',')[ifile]
1940#        print ifile, ncfile
1941        if not os.path.isfile(ncfile):
1942            print errormsg
1943            print '  ' + fname + ': domain file "' + ncfile + '" does not exist !!'
1944            quit(-1)   
1945
1946        objdomfi = NetCDFFile(ncfile, 'r')
1947   
1948        objlon = objdomfi.variables['XLONG_M']
1949        objlat = objdomfi.variables['XLAT_M']
1950
1951        dx = objlon.shape[2]
1952        dy = objlon.shape[1]
1953
1954        Xboxlines.append(objlon[0,0,:])
1955        Yboxlines.append(objlat[0,0,:])
1956        Xboxlines.append(objlon[0,dy-1,:])
1957        Yboxlines.append(objlat[0,dy-1,:])
1958        Xboxlines.append(objlon[0,:,0])
1959        Yboxlines.append(objlat[0,:,0])
1960        Xboxlines.append(objlon[0,:,dx-1])
1961        Yboxlines.append(objlat[0,:,dx-1])
1962
1963        objdomfi.close()
1964
1965    # Legend
1966    locleg, legfontsize = drw.legend_values(legvals,'|')
1967
1968    drw.plot_topo_geogrid_boxes(topography, Xboxlines, Yboxlines, boxlabels,         \
1969      objlon0, objlat0, mintopo, maxtopo, lonlatL, grtit, kindfig, mapvalues, locleg,\
1970      legfontsize, close)
1971
1972    objdomf.close()
1973
1974    return
1975
1976def movievalslice(origslice, dimmovien, framenum):
1977    """ Function to provide variable slice according to a geneation of a movie
1978    movievals(origslice, dimmovien, framenum)
1979      [origslice]= slice original as [dimname1]|[val1],[...,[dimnameN]|[valN]]
1980        ([val] = -1, full length)
1981      [dimmovien]= name of the dimension to produce the movie
1982      [framenum]= value of the frame to substitue in [origslice] as
1983        [dimmovien]|[framenum]
1984    >>> movievalslice('East_West|-1,North_South|-1,Time|2','Time',0)
1985    East_West|-1,North_South|-1,Time|0
1986    """
1987
1988    fname = 'movievalslice'
1989
1990    if origslice == 'h':
1991        print fname + '_____________________________________________________________'
1992        print movievalslice.__doc__
1993        quit()
1994   
1995    dims = origslice.split(',')
1996
1997    movieslice = ''
1998    idim = 0
1999
2000    for dimn in dims:
2001        dn = dimn.split('|')[0]
2002        if dn == dimmovien:
2003            movieslice = movieslice + dn + '|' + str(framenum)
2004        else:
2005            movieslice = movieslice + dimn
2006        if idim < len(dims)-1: movieslice = movieslice + ','
2007
2008        idim = idim + 1
2009
2010    return movieslice
2011
2012class Capturing(list):
2013    """ Class to capture function output as a list
2014    from: http://stackoverflow.com/questions/16571150/how-to-capture-stdout-output-from-a-python-function-call
2015    """
2016#    from cStringIO import StringIO
2017
2018    def __enter__(self):
2019        self._stdout = sys.stdout
2020        sys.stdout = self._stringio = StringIO()
2021        return self
2022    def __exit__(self, *args):
2023        self.extend(self._stringio.getvalue().splitlines())
2024        sys.stdout = self._stdout
2025
2026def create_movie(netcdfile, values, variable):
2027    """ Function to create a movie assuming ImageMagick installed!
2028      values= [graph]#[movie_dimension]#[graph_values]
2029        [graph]: which graphic
2030        [movie_dimension]: [dimnmovie]@[dimvmovie]@[moviedelay]@[interval]
2031          [dimnmovie]; name of the dimension from which make the movie
2032          [dimvmovie]; name of the variable with the values of the dimension
2033          [moviedelay]; delay between frames
2034          [interval]; [beg]@[end]@[freq] or -1 (all)
2035        [graph_values]: values to generate the graphic
2036      netcdfile= netCDF file
2037      variable= variable to use (when applicable)
2038    """ 
2039    fname = 'create_movie'
2040
2041    if values == 'h':
2042        print fname + '_____________________________________________________________'
2043        print create_movie.__doc__
2044        quit()
2045
2046    graph = values.split('#')[0]
2047    movie_dim = values.split('#')[1]
2048    graph_vals = values.split('#')[2]
2049
2050    ncobj = NetCDFFile(netcdfile, 'r')
2051
2052# Movie dimension
2053##
2054    dimnmovie = movie_dim.split('@')[0]
2055    dimvmovie = movie_dim.split('@')[1]
2056    moviedelay = movie_dim.split('@')[2]
2057    moviebeg = int(movie_dim.split('@')[3])
2058
2059    if not drw.searchInlist(ncobj.dimensions.keys(),dimnmovie):
2060        print errormsg
2061        print '  ' + fname + ": file '" + netcdfile + "' has not dimension '" +      \
2062          dimnmovie + "' !!!"
2063        quit(-1)
2064
2065    objdmovie = ncobj.dimensions[dimnmovie]
2066    dmovie = len(objdmovie)
2067    if moviebeg != -1:
2068        moviend = int(movie_dim.split('@')[4])
2069        moviefreq = int(movie_dim.split('@')[5])
2070    else:
2071        moviebeg = 0
2072        moviend = dmovie
2073        moviefreq = 1
2074
2075    if dimvmovie == 'WRFTimes':
2076        objvdmovie = ncobj.variables['Times']
2077        vdmovieunits = ''
2078        valsdmovie = []
2079        for it in range(objvdmovie.shape[0]):
2080            valsdmovie.append(drw.datetimeStr_conversion(objvdmovie[it,:],           \
2081              'WRFdatetime', 'Y/m/d H-M-S'))
2082    elif dimvmovie == 'CFtime':
2083        objvdmovie = ncobj.variables['time']
2084        vdmovieunits = ''
2085        print objvdmovie.units
2086        valsdmovie0 = drw.netCDFdatetime_realdatetime(objvdmovie.units, 'standard',  \
2087          objvdmovie[:])
2088        valsdmovie = []
2089        for it in range(objvdmovie.shape[0]):
2090            valsdmovie.append(drw.datetimeStr_conversion(valsdmovie0[it,:],          \
2091              'matYmdHMS', 'Y/m/d H-M-S'))
2092    else:
2093        if  not drw.searchInlist(ncobj.variables.keys(),dimvmovie):
2094            print errormsg
2095            print '  ' + fname + ": file '" + netcdfile + "' has not variable '" +   \
2096              dimvmovie + "' !!!"
2097            quit(-1)
2098        vdmovieunits = objvdmovie.getncattr('units')
2099        objvdmovie = ncobj.variables[dimvmovie]
2100        if len(objvdmovie.shape) == 1:
2101            vasldmovie = objvdmovie[:]
2102        else:
2103            print errormsg
2104            print '  ' + fname + ': shape', objvdmovie.shape, 'of variable with ' +  \
2105              'dimension movie values not ready!!!'
2106            quit(-1)
2107
2108    ncobj.close()
2109    os.system('rm frame_*.png > /dev/null')
2110
2111# graphic
2112##
2113    if graph == 'draw_2D_shad':
2114        graphvals = graph_vals.split(':')
2115
2116        for iframe in range(moviebeg,moviend,moviefreq):
2117            iframeS = str(iframe).zfill(4)
2118
2119            drw.percendone((iframe-moviebeg)/moviefreq,(moviend-moviebeg)/moviefreq, \
2120              5, 'frames')
2121            titgraph = dimnmovie + '|=|' + str(valsdmovie[iframe]) + '|' +           \
2122              vdmovieunits
2123
2124            graphvals[1] = movievalslice(graphvals[1],dimnmovie,iframe)
2125            graphvals[6] = titgraph
2126            graphvals[7] = 'png'
2127
2128            graphv = drw.numVector_String(graphvals, ":")
2129
2130            with Capturing() as output:
2131                draw_2D_shad(netcdfile, graphv, variable)
2132
2133            os.system('mv 2Dfields_shadow.png frame_' + iframeS + '.png')
2134    else:
2135        print errormsg
2136        print '  ' + fname + ": graphic '" +  graph + "' not defined !!!"
2137        quit(-1)
2138
2139    os.system('convert -delay ' + moviedelay + ' -loop 0 frame_*.png create_movie.gif')
2140
2141    print "Succesfuly creation of movie file 'create_movie.gif' !!!"
2142
2143    return
2144
2145def draw_lines(ncfilens, values, varname):
2146    """ Function to draw different lines at the same time from different files
2147    draw_lines(ncfilens, values, varname):
2148      ncfilens= [filen] ',' separated list of netCDF files
2149      values= [dimvname]:[valuesaxis]:[dimtit]:[dimxyfmt]:[leglabels]:[vtit]:[title]:[legvals]:[colns]:[lines]
2150       [points]:[lwdths]:[psizes]:[freqv]:[figname]:[graphk]:[close]
2151        [dimvname]: ',' list of names of the variable with he values of the common dimension
2152        [valuesaxis]: which axis will be used for the values ('x', or 'y')
2153        [dimtit]: title for the common dimension
2154        [dimxyfmt]=[dxs],[dxf],[Ndx],[ordx],[dys],[dyf],[Ndy],[ordx]: format of the values at each axis (or 'auto')
2155          [dxs]: style of x-axis ('auto' for 'pretty')
2156            'Nfix', values computed at even 'Ndx'
2157            'Vfix', values computed at even 'Ndx' increments
2158            'pretty', values computed following aprox. 'Ndx' at 'pretty' intervals (2.,2.5,4,5,10)
2159          [dxf]: format of the labels at the x-axis ('auto' for '%5g')
2160          [Ndx]: Number of ticks at the x-axis ('auto' for 5)
2161          [ordx]: angle of orientation of ticks at the x-axis ('auto' for horizontal)
2162          [dys]: style of y-axis ('auto' for 'pretty')
2163          [dyf]: format of the labels at the y-axis ('auto' for '%5g')
2164          [Ndy]: Number of ticks at the y-axis ('auto' for 5)
2165          [ordy]: angle of orientation of ticks at the y-axis ('auto' for horizontal)
2166        [leglabels]: ',' separated list of names for the legend ('!' for spaces)
2167        [vartit]: name of the variable in the graph
2168        [title]: title of the plot ('|' for spaces)
2169        [legvals]=[locleg]|[fontsize]:
2170          [locleg]: location of the legend (0, autmoatic)
2171            1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
2172            5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
2173            9: 'upper center', 10: 'center'
2174          [fontsize]: font size for the legend (auto for 12)
2175        [colns]= ',' list of color names ('None' for automatic, single value for all the same)
2176        [lines]= ',' list of style of lines ('None' for automatic, single value for all the same)
2177        [points]= '@' list of style of points ('None' for automatic, single value for all the same)
2178        [lwdths]= ',' list of withs of lines ('None' for automatic, single value for all the same)
2179        [psizes]= ',' list of size of points ('None' for automatic, single value for all the same)
2180        [freqv]= frequency of values ('all' for all values)
2181        [figname]= name of the figure
2182        [graphk]: kind of the graphic
2183        [close]: should figure be closed (finished)
2184      varname= variable to plot
2185      values= 'XLAT:x:latitude:32x32:$wss^{*}$:wss Taylor's turbulence term:pdf'
2186    """
2187
2188    fname = 'draw_lines'
2189
2190    if values == 'h':
2191        print fname + '_____________________________________________________________'
2192        print draw_lines.__doc__
2193        quit()
2194
2195    expectargs = '[dimvname]:[valuesaxis]:[dimtit]:[dimxyfmt]:[leglabels]:[vtit]:' + \
2196      '[title]:[legvals]:[colns]:[lines]:[points]:[lwdths]:[psizes]:[freqv]:' +      \
2197      '[figname]:[graphk]:[close]'
2198    drw.check_arguments(fname,values,expectargs,':')
2199
2200    ncfiles = ncfilens.split(',')
2201    dimvnames = values.split(':')[0]
2202    valuesaxis = values.split(':')[1]
2203    dimtit = values.split(':')[2]
2204    dimxyfmt = values.split(':')[3]
2205    leglabels = gen.latex_text(values.split(':')[4].replace('!',' '))
2206    vartit = values.split(':')[5]
2207    title = values.split(':')[6].replace('|',' ')
2208    legvals = values.split(':')[7]
2209    colns = gen.str_list(values.split(':')[8], ',')
2210    lines = gen.str_list(values.split(':')[9], ',')
2211    points = gen.str_list(values.split(':')[10], '@')
2212    lwdths = gen.str_list_k(values.split(':')[11], ',', 'R')
2213    psizes = gen.str_list_k(values.split(':')[12], ',', 'R')
2214    freqv0 = values.split(':')[13]
2215    figname = values.split(':')[14]
2216    graphk = values.split(':')[15]
2217    close = gen.Str_Bool(values.split(':')[16])
2218
2219    Nfiles = len(ncfiles)
2220
2221# Getting trajectotries
2222##
2223
2224    varvalues = []
2225    dimvalues = []
2226
2227    print '  ' + fname
2228    ifn = 0
2229    for ifile in ncfiles:
2230        filen = ifile.split('@')[0]
2231
2232        print '    filen:',filen
2233
2234        if not os.path.isfile(filen):
2235            print errormsg
2236            print '  ' + fname + ": netCDF file '" + filen + "' does not exist !!"
2237            quit(-1)
2238
2239        objfile = NetCDFFile(filen, 'r')
2240
2241        if dimvnames.find(',') != -1:
2242            dimvname = dimvnames.split(',')
2243        else:
2244            dimvname = [dimvnames]
2245   
2246        found = False
2247        for dvn in dimvname:
2248            if objfile.variables.has_key(dvn):
2249                found = True
2250                break
2251   
2252        if not found:
2253            print errormsg
2254            print '  ' + fname + ": netCDF file '" + filen +                         \
2255              "' does not have variables '" + dimvnames + "' !!"
2256            quit(-1)
2257
2258        if not objfile.variables.has_key(varname):
2259            print errormsg
2260            print '  ' + fname + ": netCDF file '" + filen +                         \
2261              "' does not have variable '" + varname + "' !!"
2262            quit(-1)
2263
2264        vvobj = objfile.variables[varname]
2265        if len(vvobj.shape) != 1:
2266            print errormsg
2267            print '  ' + fname + ': wrong shape:',vvobj.shape," of variable '" +     \
2268              varname +  "' !!"
2269            quit(-1)
2270
2271        for dimvn in dimvname:
2272            if drw.searchInlist(objfile.variables, dimvn):
2273                vdobj = objfile.variables[dimvn]
2274                if len(vdobj.shape) != 1:
2275                    print errormsg
2276                    print '  ' + fname + ': wrong shape:',vdobj.shape,               \
2277                      " of variable '" + dimvn +  "' !!"
2278                    quit(-1)
2279                break
2280
2281        varvalues.append(vvobj[:])
2282        dimvalues.append(vdobj[:])
2283
2284        if ifn == 0:
2285            varunits = vvobj.units
2286
2287        objfile.close()
2288
2289        ifn = ifn + 1
2290
2291    if freqv0 == 'all':
2292        freqv = None
2293    else:
2294        freqv = int(freqv0)
2295
2296    # Legend
2297    locleg, legfontsize = drw.legend_values(legvals,'|')
2298
2299    # axis
2300    xstyl, xaxf, Nxax, xaxor, ystyl, yaxf, Nyax, yaxor = drw.format_axes(dimxyfmt,',')
2301    xaxis = [xstyl, xaxf, Nxax, xaxor]
2302    yaxis = [ystyl, yaxf, Nyax, yaxor]
2303
2304    drw.plot_lines(dimvalues, varvalues, valuesaxis, dimtit, xaxis, yaxis,           \
2305      leglabels.split(','), vartit, varunits, title, locleg, legfontsize, colns,     \
2306      lines, points, lwdths, psizes, freqv, figname, graphk, close)
2307
2308    return
2309
2310def draw_lines_time(ncfilens, values, varnames):
2311    """ Function to draw different lines at the same time from different files with times
2312    draw_lines_time(ncfilens, values, varname):
2313      ncfilens= [filen] ',' separated list of netCDF files
2314      values= [dimvname];[valuesaxis];[dimtit];[dimxyfmt];[leglabels];[vtit];[title];[rangevals];[timevals];
2315        [legvals];[graphk];[collines];[points];[linewidths];[pointsizes];[pointfreq];[period];[close]
2316        [dimvname]: ',' list of names of the variables with he values of the common dimension ('WRFtime' for WRF Times variable)
2317        [valuesaxis]: which axis will be used for the values ('x', or 'y')
2318        [dimtit]: title for the common dimension ('|' for spaces)
2319        [dimxyfmt]=[dxs],[dxf],[Ndx],[ordx],[dys],[dyf],[Ndy],[ordx]: format of the values at each axis (or 'auto')
2320          [dxs]: style of x-axis ('auto' for 'pretty')
2321            'Nfix', values computed at even 'Ndx'
2322            'Vfix', values computed at even 'Ndx' increments
2323            'pretty', values computed following aprox. 'Ndx' at 'pretty' intervals (2.,2.5,4,5,10)
2324          [dxf]: format of the labels at the x-axis ('auto' for '%5g')
2325          [Ndx]: Number of ticks at the x-axis ('auto' for 5)
2326          [ordx]: angle of orientation of ticks at the x-axis ('auto' for horizontal)
2327          [dys]: style of y-axis ('auto' for 'pretty')
2328          [dyf]: format of the labels at the y-axis ('auto' for '%5g')
2329          [Ndy]: Number of ticks at the y-axis ('auto' for 5)
2330          [ordy]: angle of orientation of ticks at the y-axis ('auto' for horizontal)
2331        [leglabels]: ',' separated list of names for the legend ('None', no legend '!' for spaces)
2332        [vartit]: name of the variable in the graph
2333        [title]: title of the plot ('|' for spaces)
2334        [rangevals]: Range of the axis with the values ('None' for 'auto','auto')
2335          [vmin],[vmax]: minimum and maximum values where [vmNN] can also be:
2336            'auto': the computed minimumm or maximum of the values 
2337        [timevals]: [timen]|[units]|[kind]|[tfmt] time labels characteristics
2338           [timen]; name of the time variable
2339           [units]; units string according to CF conventions ([tunits] since
2340             [YYYY]-[MM]-[DD] [[HH]:[MI]:[SS]], '!' for spaces)
2341           [kind]; kind of output
2342             'Nval': according to a given number of values as 'Nval',[Nval]
2343             'exct': according to an exact time unit as 'exct',[tunit];
2344               tunit= [Nunits],[tu]; [tu]= 'c': centuries, 'y': year, 'm': month,
2345                'w': week, 'd': day, 'h': hour, 'i': minute, 's': second,
2346                'l': milisecond
2347           [tfmt]; desired format
2348        [legvals]=[locleg]|[fontsize]:
2349          [locleg]: location of the legend (0, autmoatic)
2350            1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
2351            5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
2352            9: 'upper center', 10: 'center'
2353          [fontsize]: font size for the legend (auto for 12)
2354        [graphk]: kind of the graphic
2355        [lines]: ',' list of type of lines, None for automatic, single value all the same
2356        [collines]: ',' list of colors for the lines, None for automatic, single
2357          value all the same
2358        [points]: '@' list of type of points for the lines, None for automatic, single
2359          value all the same
2360        [linewidths]: ',' list of widths for the lines, None for automatic, single
2361          value all the same
2362        [pointsizes]: ',' list of widths for the lines, None for automatic, single
2363          value all the same
2364        [pointfreq]: frequency of point plotting, 'all' for all time steps
2365        [period]: which period to plot
2366          '-1': all period
2367          [beg],[end]: beginning and end of the period in reference time-units of first file
2368        [close]: Whether figure should be finished or not
2369      varnames= ',' list of variable names to plot (assuming only 1 variable per file)
2370      values= 'time;y;time ([DD]${[HH]}$);32x32;$wss^{*}$;wss Taylor's turbulence term;time|hours!since!1949-12-01_00:00:00;exct,12,h|%d$^{%H}$;2;pdf'
2371    """
2372
2373    fname = 'draw_lines_time'
2374
2375    if values == 'h':
2376        print fname + '_____________________________________________________________'
2377        print draw_lines_time.__doc__
2378        quit()
2379
2380    expectargs = '[dimvname];[valuesaxis];[dimtit];[dimxyfmt];[leglabels];[vtit];' + \
2381      '[title];[rangevals];[timevals];[legvals];[graphk];[lines];[collines];' +      \
2382      '[points];[linewidths];[pointsizes];[pointfreq];[period];[close]'
2383    drw.check_arguments(fname,values,expectargs,';')
2384
2385    ncfiles = ncfilens.split(',')
2386    dimvname0 = values.split(';')[0]
2387    valuesaxis = values.split(';')[1]
2388    dimtit = values.split(';')[2].replace('|',' ')
2389    dimxyfmt = values.split(';')[3]
2390    leglabels = gen.latex_text(values.split(';')[4]).replace('!',' ')
2391    vartit = values.split(';')[5]
2392    title = values.split(';')[6].replace('|',' ')
2393    rangevals = values.split(';')[7]
2394    timevals = values.split(';')[8]
2395    legvals = values.split(';')[9]
2396    graphk = values.split(';')[10]
2397    lines0 = values.split(';')[11]
2398    collines0 = values.split(';')[12]
2399    points0 = values.split(';')[13]
2400    linewidths0 = values.split(';')[14]
2401    pointsizes0 = values.split(';')[15]
2402    pointfreq0 = values.split(';')[16]
2403    period = values.split(';')[17]
2404    close = gen.Str_Bool(values.split(';')[18])
2405
2406    Nfiles = len(ncfiles)
2407
2408# Multiple variable-dimension names?
2409    if dimvname0.find(',') != -1:
2410        dimvname = dimvname0.split(',')
2411    else:
2412        dimvname = [dimvname0]
2413
2414# Multiple variables?
2415    if varname0.find(',') != -1:
2416        varname = varname0.split(',')
2417    else:
2418        varname = [varname0]
2419
2420# Multiple lines types?
2421    if lines0.find(',') != -1:
2422        lines = lines0.split(',')
2423    elif lines0 == 'None':
2424        lines = None
2425    else:
2426        lines = []
2427        for il in range(Nfiles):
2428            lines.append(lines0)
2429
2430# Multiple color names?
2431    if collines0.find(',') != -1:
2432        collines = collines0.split(',')
2433    elif collines0 == 'None':
2434        collines = None
2435    else:
2436        collines = []
2437        for ip in range(Nfiles):
2438            collines.append(collines0)
2439
2440# Multiple point types?
2441    if points0.find(',') != -1:
2442        if len(points0) == 1:
2443            points = []
2444            for ip in range(Nfiles):
2445                points.append(points0)
2446        else:
2447            points = points0.split('@')
2448    elif points0 == 'None':
2449        points = None
2450    else:
2451        points = []
2452        for ip in range(Nfiles):
2453            points.append(points0)
2454
2455# Multiple line sizes?
2456    if linewidths0.find(',') != -1:
2457        linewidths = []
2458        Nlines = len(linewidths0.split(','))
2459        for il in range(Nlines):
2460          linewidths.append(np.float(linewidths0.split(',')[il]))
2461    elif linewidths0 == 'None':
2462        linewidths = None
2463    else:
2464        linewidths = [np.float(linewidths0)]
2465
2466# Multiple point sizes?
2467    if pointsizes0.find(',') != -1:
2468        pointsizes = []
2469        Npts = len(pointsizes0.split(','))
2470        for ip in Npts:
2471          pointsizes.append(np.float(pointsizes0.split(',')[ip]))
2472    elif pointsizes0 == 'None':
2473        pointsizes = None
2474    else:
2475        pointsizes = [np.float(pointsizes0)]
2476
2477    timename = timevals.split('|')[0]
2478    timeunit = timevals.split('|')[1].replace('!',' ')
2479    timekind = timevals.split('|')[2]
2480    timefmt = timevals.split('|')[3]
2481
2482    if rangevals == 'None':
2483        valmin = 'auto'
2484        valmax = 'auto'
2485    else:
2486        valmin = rangevals.split(',')[0]
2487        valmax = rangevals.split(',')[1]
2488        if valmin != 'auto': valmin = np.float(valmin)
2489        if valmax != 'auto': valmax = np.float(valmax)
2490
2491    # Legend
2492    locleg, legfontsize = drw.legend_values(legvals,'|')
2493
2494# Getting values
2495##
2496    varvalues = []
2497    dimvalues = []
2498    timvalues = []
2499    timvals0 = timvalues
2500
2501    print '  ' + fname
2502    ifn = 0
2503    mintval = 1.e20
2504    maxtval = -1.e20
2505
2506    for ifile in ncfiles:
2507        filen = ifile.split('@')[0]
2508
2509        print '    filen:',filen
2510
2511        if not os.path.isfile(filen):
2512            print errormsg
2513            print '  ' + fname + ": netCDF file '" + filen + "' does not exist !!"
2514            quit(-1)
2515
2516        objfile = NetCDFFile(filen, 'r')
2517
2518        founddvar = False
2519        for dvar in dimvname:
2520            if dvar != 'WRFtime' and objfile.variables.has_key(dvar):
2521                founddvar = True
2522                vdobj = objfile.variables[dvar]
2523                uvd = str(vdobj.units)
2524                if len(vdobj.shape) != 1:
2525                    print errormsg
2526                    print '  ' + fname + ': wrong shape:',vdobj.shape," of " +       \
2527                      "variable '" + dvar +  "' !!"
2528                    quit(-1)
2529                vdvals = vdobj[:]
2530                break
2531            elif dvar == 'WRFtime' and objfile.variables.has_key('Times'):
2532                founddvar = True
2533                uvd = timeunit
2534                tunitsec = timeunit.split(' ')
2535                if len(tunitsec) == 4:
2536                    refdate = tunitsec[2][0:4]+tunitsec[2][5:7]+tunitsec[2][8:10] +  \
2537                      tunitsec[3][0:2] + tunitsec[3][3:5] + tunitsec[3][6:8]
2538                else:
2539                    refdate = tunitsec[2][0:4]+tunitsec[2][5:7]+tunitsec[2][8:10] +  \
2540                      '000000'
2541                tunitsval = tunitsec[0]
2542
2543                timewrfv = objfile.variables['Times']
2544                dt = timewrfv.shape[0]
2545                vdvals = np.zeros((dt), dtype=np.float)
2546
2547                for it in range(dt):
2548                    wrfdates = gen.datetimeStr_conversion(timewrfv[it,:],            \
2549                      'WRFdatetime', 'matYmdHMS')
2550                    vdvals[it] = gen.realdatetime1_CFcompilant(wrfdates, refdate,    \
2551                      tunitsval)
2552
2553        if not founddvar:
2554            print errormsg
2555            print '  ' + fname + ": netCDF file '" + filen +                         \
2556            "' has any variable '", dimvname, "' !!"
2557            quit(-1)
2558
2559        foundvar = False
2560        for var in varname:
2561            if objfile.variables.has_key(var):
2562                foundvar = True
2563                vvobj = objfile.variables[var]
2564                if len(vvobj.shape) != 1:
2565                    print errormsg
2566                    print '  ' + fname + ': wrong shape:',vvobj.shape," of " +       \
2567                      "variable '" + var +  "' !!"
2568                    quit(-1)
2569
2570                break
2571        if not foundvar:
2572            print errormsg
2573            print '  ' + fname + ": netCDF file '" + filen +                         \
2574              "' has any variable '", varname, "' !!"
2575            quit(-1)
2576        if uvd.find('month') != -1:
2577            print warnmsg
2578            print '  ' + fname + ": transforming time units from 'months' to 'days'!!"
2579            timevals0, tunits0 = gen.CFmonthU_daysU(vdvals[:], vdobj.units) 
2580        else:
2581            timevals0 = vdvals[:]
2582            tunits0 = uvd
2583
2584# Getting period
2585        if ifn > 0: 
2586# Referring all times to the same reference time!
2587            reftvals = gen.coincident_CFtimes(timevals0, timeunit, tunits0)
2588        else:
2589            reftvals = timevals0
2590
2591        dimt = len(vdvals[:])
2592
2593        if period == '-1':
2594            varvalues.append(vvobj[:])
2595            dimvalues.append(reftvals)
2596            mindvals = np.min(reftvals)
2597            maxdvals = np.max(reftvals)
2598        else:
2599            ibeg=-1
2600            iend=-1
2601            tbeg = np.float(period.split(',')[0])
2602            tend = np.float(period.split(',')[1])
2603
2604            for it in range(dimt-1):
2605                if reftvals[it] <= tbeg and reftvals[it+1] > tbeg: ibeg = it
2606                if reftvals[it] <= tend and reftvals[it+1] > tend: iend = it + 1
2607                if ibeg != -1 and iend != -1: break
2608
2609            if ibeg == -1 and iend == -1:
2610                print warnmsg
2611                print '  ' + fname + ': Period:',tbeg,',',tend,'not found!!'
2612                print '    ibeg:',ibeg,'iend:',iend
2613                print '    period in file:',np.min(reftvals), np.max(reftvals)
2614                print '    getting all the period in file !!!'
2615                ibeg = 0
2616                iend = dimt
2617            elif iend == -1:
2618                iend = dimt
2619                print warnmsg
2620                print '  ' + fname + ': end of Period:',tbeg,',',tend,'not found!!'
2621                print '    getting last available time instead'
2622                print '    ibeg:',ibeg,'iend:',iend
2623                print '    period in file:',np.min(reftvals), np.max(reftvals)
2624            elif ibeg == -1:
2625                ibeg = 0
2626                print warnmsg
2627                print '  ' + fname + ': beginning of Period:',tbeg,',',tend,         \
2628                  'not found!!'
2629                print '    getting first available time instead'
2630                print '    ibeg:',ibeg,'iend:',iend
2631                print '    period in file:',np.min(reftvals), np.max(reftvals)
2632
2633            varvalues.append(vvobj[ibeg:iend])
2634            dimvalues.append(reftvals[ibeg:iend])
2635            mindvals = np.min(reftvals[ibeg:iend])
2636            maxdvals = np.max(reftvals[ibeg:iend])
2637
2638            dimt = iend - ibeg
2639
2640        if mindvals < mintval: mintval = mindvals
2641        if maxdvals > maxtval: maxtval = maxdvals
2642        print '  ' + fname + ": file '" + filen + "' period:", mindvals, '->', maxdvals
2643
2644        if ifn == 0:
2645            varunits = drw.units_lunits(vvobj.units)
2646
2647        objfile.close()
2648
2649        ifn = ifn + 1
2650
2651# Times
2652
2653    dtvals = (maxtval - mintval)/dimt
2654#    dti = mintval-dtvals/2.
2655#    dte = maxtval+dtvals/2.
2656    dti = mintval
2657    dte = maxtval
2658    tvals = np.arange(dti, dte, dtvals)
2659
2660    dtiS = drw.datetimeStr_conversion(str(dti) + ',' + timeunit, 'cfTime',           \
2661      'Y/m/d H-M-S')
2662    dteS = drw.datetimeStr_conversion(str(dte) + ',' + timeunit, 'cfTime',           \
2663      'Y/m/d H-M-S')
2664
2665    print '  ' + fname + ': plotting from: ' + dtiS + ' to ' + dteS
2666
2667    timepos, timelabels = drw.CFtimes_plot(tvals, timeunit, timekind, timefmt)
2668
2669#    print 'Lluis min/max tval +/- dtval/2:', mintval-dtvals/2., maxtval+dtvals/2.,'dt:', len(tvals)
2670#    for it in range(len(timepos)):
2671#        print timepos[it], timelabels[it]
2672
2673    if leglabels != 'None':
2674        legvals = leglabels.split(',')
2675    else:
2676        legvals = None
2677
2678    if pointfreq0 == 'all':
2679        pointfreq = None
2680    else:
2681        pointfreq = int(pointfreq0)
2682
2683    # axis
2684    xstyl, xaxf, Nxax, xaxor, ystyl, yaxf, Nyax, yaxor = drw.format_axes(dimxyfmt,',')
2685    xaxis = [xstyl, xaxf, Nxax, xaxor]
2686    yaxis = [ystyl, yaxf, Nyax, yaxor]
2687
2688    drw.plot_lines_time(dimvalues, varvalues, valuesaxis, xaxis, yaxis, dimtit,      \
2689      legvals, vartit, varunits, timepos, timelabels, title, locleg, legfontsize,    \
2690      graphk, valmin, valmax, lines, collines, points, linewidths, pointsizes,       \
2691      pointfreq, close)
2692
2693    return
2694
2695def draw_Neighbourghood_evol(filen, values, variable):
2696    """ Function to draw the temporal evolution of a neighbourghood around a point
2697    draw_Neighbourghood_evol(filen, values, variable)
2698      filen= netCDF file name
2699      values= [gvarname]:[dimsval]:[neigdims]:[Nneig]:[Ncol]:[timetits]:[tkinds]:
2700       [timefmts]:[gtitle]:[shadxtrms]:[colobarvals]:[neighlinevals]:[gkind]:[ofile]:[close]
2701        [gvarname]: ':' list of names of the variables in the plot
2702        [dimsval]: [dimn1]|[val1]|[dimv1],...,[dimnN]|[valN]|[dimvN] dimension names, values to get:
2703          * [integer]: which value of the dimension
2704          * -1: all along the dimension
2705          * NOTE, no dim name all the dimension size
2706          'WRFtime' for WRF times
2707          NOTE: when dimsval[X,Y] == neigdims[X,Y], valX,valY --> valX,valY-Nneig/2, valX,valY+Nneig/2
2708        [neigdims]: [dimnX],[dimnY] dimensions mnames along which the neigbourghood should be defined
2709        [Nneig]: Number of grid points of the full side of the box (odd value)
2710        [Ncol]: Number of columns ('auto': square final plot)
2711        [gvarname]: name of the variable to appear in the graph
2712        [timetits]: [titX],[titY] titles of the axes ('|' for spaces)
2713        [tkinds]: [tkindX]|[tkindY] kinds of time to appear in the graph
2714          'Nval': according to a given number of values as 'Nval',[Nval]
2715          'exct': according to an exact time unit as 'exct',[tunit];
2716            tunit= [Nunits],[tu]; [tu]= 'c': centuries, 'y': year, 'm': month,
2717              'w': week, 'd': day, 'h': hour, 'i': minute, 's': second,
2718              'l': milisecond
2719        [timefmts]: [tfmtX],[tfmtY] format of the time labels
2720        [gtitle]: title of the graphic ('|' for spaces)
2721        [shadxtrms]: minimum and maximum value for the shading or:
2722          'Srange': for full range
2723          'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean)
2724          'Saroundminmax@val': for min*val,max*val
2725          'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val),
2726            percentile_(100-val)-median)
2727          'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean)
2728          'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median)
2729          'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val),
2730             percentile_(100-val)-median)
2731        [colorbarvals]=[colbarn],[fmtcolorbar],[orientation] characteristics of the colormap and colorbar
2732          [colorbarn]: name of the color bar
2733          [fmtcolorbar]: format of the numbers in the color bar 'C'-like ('auto' for %6g)
2734          [orientation]: orientation of the colorbar ('vertical' (default, by 'auto'), 'horizontal')
2735        [neighlinevals]=[linecol],[linestyle],[linewidth] characterisitcs of the lines to mark the limits of the neighborhood
2736          ('auto' for: ['#646464', '-', 2.])
2737          [linecol]: color of the line
2738          [linestyle]: style of the line
2739          [linewidth]: width of the line
2740        [gkind]: kind of graphical output
2741        [ofile]: True/False whether the netcdf with data should be created or not
2742        [close]: Whether figure should be finished or not
2743      variable= name of the variable
2744      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'
2745    """ 
2746
2747    fname = 'draw_Neighbourghood_evol'
2748
2749    if values == 'h':
2750        print fname + '_____________________________________________________________'
2751        print draw_Neighbourghood_evol.__doc__
2752        quit()
2753
2754    expectargs = '[gvarname]:[dimsval]:[neigdims]:[Nneig]:[Ncol]:' +                 \
2755      '[timetits]:[tkinds]:[timefmts]:[gtitle]:[shadxtrms]:[colorbarvals]:' +        \
2756      '[neighlinevals]:[gkind]:[ofile]:[close]'
2757 
2758    drw.check_arguments(fname,values,expectargs,':')
2759
2760    gvarname = values.split(':')[0]
2761    dimsval = values.split(':')[1].split(',')
2762    neigdims = values.split(':')[2].split(',')
2763    Nneig = int(values.split(':')[3])
2764    Ncol0 = values.split(':')[4]
2765    timetits = values.split(':')[5].split(',')
2766    timekinds = values.split(':')[6].split('|')
2767    timefmts = values.split(':')[7].split(',')
2768    gtitle = values.split(':')[8].replace('|',' ')
2769    shadxtrms = values.split(':')[9].split(',')
2770    colorbarvals = values.split(':')[10]
2771    neighlinevals = values.split(':')[11]
2772    gkind = values.split(':')[12]
2773    ofile = values.split(':')[13]
2774    close = gen.Str_Bool(values.split(':')[14])
2775
2776    if Ncol0 != 'auto': 
2777        Ncol = int(Ncol0)
2778    else:
2779        Ncol = Ncol0
2780
2781    timetits[0] = timetits[0].replace('|',' ')
2782    timetits[1] = timetits[1].replace('|',' ')
2783
2784    if np.mod(Nneig,2) == 0:
2785        print errormsg
2786        print '  ' + fname + ": an odd value for 'Nneig':", Nneig, 'is required !!!'
2787        quit(-1)
2788
2789    Nneig2 = int(Nneig/2)
2790
2791# Values to slice the variable
2792    dimvslice = {}
2793    dimvvalues = {}
2794    for dimvs in dimsval:
2795        dimn = dimvs.split('|')[0]
2796        dimv = int(dimvs.split('|')[1])
2797        dimnv = dimvs.split('|')[2]
2798
2799        dimvvalues[dimn] = dimnv
2800        dimvslice[dimn] = dimv
2801
2802    ncobj = NetCDFFile(filen, 'r')
2803
2804    varobj = ncobj.variables[variable]
2805
2806    slicevar = []
2807    newdimn = []
2808    newdimsvar = {}
2809
2810    for dimn in varobj.dimensions:
2811        if not drw.searchInlist(dimvslice.keys(), dimn):
2812            dimsize = len(ncobj.dimensions[dimn])
2813            slicevar.append(slice(0, dimsize+1))
2814            newdimn.append(dimn)
2815            newdimsvar[dimn] = dimsize
2816
2817        for dimslicen in dimvslice.keys():
2818            if dimn == dimslicen:
2819                if dimvslice[dimn] != -1:
2820                    if drw.searchInlist(neigdims, dimn):
2821                        slicevar.append(slice(dimvslice[dimn]-Nneig2,                \
2822                          dimvslice[dimn]+Nneig2+1))
2823                        newdimn.append(dimn)
2824                        newdimsvar[dimn] = Nneig
2825                        break
2826                    else:
2827                        slicevar.append(slice(dimvslice[dimn], dimvslice[dimn]+1))
2828                        break
2829                else:
2830                    dimsize = len(ncobj.dimensions[dimn])
2831                    slicevar.append(slice(0, dimsize+1))
2832                    newdimn.append(dimn)
2833                    newdimsvar[dimn] = dimsize
2834                    break
2835 
2836    varv = varobj[tuple(slicevar)]
2837
2838    if len(newdimn) != 3:
2839        print errormsg
2840        print '  ' + fname + ': sliced variable with shape=', varv.shape,            \
2841          ' must have three dimensions',len(varv.shape),'given !!'
2842        quit(-1)
2843
2844    newdims = []
2845    for nwdims in newdimn:
2846        newdims.append(newdimsvar[nwdims])
2847
2848# The dimension which is not in the neighbourhood dimensions must be time!
2849    for dim1 in newdimn:
2850        if not drw.searchInlist(neigdims, dim1):
2851            dimt = newdimsvar[dim1]
2852            dimtime = dim1
2853
2854    # Number of columns and rows
2855    if Ncol == 'auto':
2856        dimtsqx = int(np.sqrt(dimt))
2857    else:
2858        dimtsqx = int(Ncol)
2859
2860    dimtsqy = dimt/dimtsqx + 1
2861    print '  ' + fname + '; plotting ', dimtsqx, 'x', dimtsqy, 'time-windows of:',   \
2862      Nneig, 'x', Nneig, 'grid-points'
2863
2864    neighbourghood = np.ones((dimtsqy*Nneig,dimtsqx*Nneig), dtype=np.float)*fillValue
2865
2866    for it in range(dimt):
2867        ity = int(it/dimtsqx)
2868        itx = it-ity*dimtsqx
2869
2870        itty = (dimtsqy - ity - 1)*Nneig + Nneig2
2871        ittx = itx*Nneig + Nneig2
2872
2873        neighbourghood[itty-Nneig2:itty+Nneig2+1,ittx-Nneig2:ittx+Nneig2+1]=         \
2874          varv[it,::-1,:]
2875
2876    variablevals = drw.variables_values(variable)
2877    if drw.searchInlist(varobj.ncattrs(), 'units'):
2878        vunits = varobj.units
2879    else:
2880        vunits = variablevals[5]
2881
2882# Time values at the X/Y axes
2883    if dimvvalues[dimtime] == 'WRFtime':
2884        print '    ' + fname + ": WRF time variable!: 'Times'"
2885        refdate = '19491201000000'
2886        tunitsval = 'hours'
2887        dimtvalues = np.zeros((dimt), dtype=np.float)
2888        tvals = ncobj.variables['Times']
2889        yrref=refdate[0:4]
2890        monref=refdate[4:6]
2891        dayref=refdate[6:8]
2892        horref=refdate[8:10]
2893        minref=refdate[10:12]
2894        secref=refdate[12:14]
2895
2896        refdateS = yrref + '/' + monref + '/' + dayref + '_' + horref + ':' +        \
2897          minref + ':' + secref
2898        tunits = tunitsval + ' since ' + refdateS
2899        for it in range(dimt):
2900            wrfdates = drw.datetimeStr_conversion(tvals[it,:],'WRFdatetime', 'matYmdHMS')
2901            dimtvalues[it] = drw.realdatetime1_CFcompilant(wrfdates, refdate, tunitsval)
2902    else:
2903        dimtvalues = ncobj.variables[dimvvalues[dimtime]][:]
2904        tunits = ncobj.variables[newdimsvar[dimtime]].units
2905
2906    dimxv = dimtvalues[0:dimtsqx]
2907    dimyv = dimtvalues[0:dimt:dimtsqx]
2908
2909    dimn = ['time','time']
2910
2911    if ofile == 'True':
2912        ofilen = 'Neighbourghood_evol.nc'
2913        newnc = NetCDFFile(ofilen, 'w')
2914# Dimensions
2915        newdim = newnc.createDimension('time',None)
2916        newdim = newnc.createDimension('y',dimtsqy*Nneig)
2917        newdim = newnc.createDimension('x',dimtsqx*Nneig)
2918# Dimension values
2919        newvar = newnc.createVariable('time','f8',('time'))
2920        newvar[:] = np.arange(dimt)
2921        newattr = drw.basicvardef(newvar, 'time','time',tunits)
2922# Neighbourhghood variable
2923        newvar = newnc.createVariable(variable + 'neigevol', 'f4', ('y','x'),        \
2924          fill_value=fillValue)
2925        newvar[:] = neighbourghood
2926
2927        newnc.sync()
2928        newnc.close()
2929        print fname + ": Successfull generation of file '" + ofilen + "' !!"
2930# Colorbar values
2931    colbarn, fmtcolbar, colbaror = drw.colorbar_vals(colorbarvals,',')
2932    colormapv = [colbarn, fmtcolbar, colbaror]
2933
2934# Neighborhood line values
2935    if neighlinevals == 'auto':
2936        neiglinev = ['#646464', '-', 2.]
2937    else:
2938        neiglinev = neighlinevals.split(',')
2939
2940# Time ticks
2941    timeposX, timelabelsX = drw.CFtimes_plot(dimxv, tunits, timekinds[0], timefmts[0])
2942    timeposY, timelabelsY = drw.CFtimes_plot(dimyv, tunits, timekinds[1], timefmts[1])
2943
2944    timepos = [timeposX[0:len(timeposX)], timeposY[len(timeposY):0:-1]]
2945    timelabels = [timelabelsX[0:len(timeposX)], timelabelsY[0:len(timeposY)]]
2946
2947    for i in range(2):
2948        if shadxtrms[i][0:1] != 'S':
2949            shadxtrms[i] = np.float(shadxtrms[i])
2950
2951    drw.plot_Neighbourghood_evol(neighbourghood, dimxv, dimyv, gvarname, timetits,   \
2952      timepos, timelabels, colormapv, neiglinev, Nneig, shadxtrms, vunits, gtitle,   \
2953      gkind, close)
2954
2955def draw_points(filen, values):
2956    """ Function to plot a series of points read from an ASCII file with lon, lat, label
2957      draw_points(filen, values)
2958      [values]= [ptasciifile]:[gtit]:[dimxyfmt]:[mapvalues]:[kindfigure]:[pointcolor]:[pointlabels]:
2959        [legvals]:[figureko]:[figuren]:[close]
2960        [ptasciifile]:[file],[comchar],[collon],[collat],[lab]
2961          [file]: column ASCII file with the location of the points
2962          [comchar]: '|' list of characters for commentaries
2963          [collon]: number of column with the longitude of the points
2964          [collat]: number of column with the latitude of the points
2965          [collab]: number of column with the labels of the points ('None', and will get
2966            the values from the [pointlabels] variable
2967        [gtit]: title of the figure ('|' for spaces)
2968        [dimxyfmt]: [dxs],[dxf],[Ndx],[ordx],[dys],[dyf],[Ndy],[ordx]: format of the values at each axis (or 'auto')
2969          [dxs]: style of x-axis ('auto' for 'pretty')
2970            'Nfix', values computed at even 'Ndx'
2971            'Vfix', values computed at even 'Ndx' increments
2972            'pretty', values computed following aprox. 'Ndx' at 'pretty' intervals (2.,2.5,4,5,10)
2973          [dxf]: format of the labels at the x-axis ('auto' for '%5g')
2974          [Ndx]: Number of ticks at the x-axis ('auto' for 5)
2975          [ordx]: angle of orientation of ticks at the x-axis ('auto' for horizontal)
2976          [dys]: style of y-axis ('auto' for 'pretty')
2977          [dyf]: format of the labels at the y-axis ('auto' for '%5g')
2978          [Ndy]: Number of ticks at the y-axis ('auto' for 5)
2979          [ordy]: angle of orientation of ticks at the y-axis ('auto' for horizontal)
2980        [mapvalues]: drawing coastaline ([proj],[res]) or None
2981          [proj]: projection
2982             * 'cyl', cilindric
2983             * 'lcc', lambert conformal
2984          [res]: resolution:
2985             * 'c', crude
2986             * 'l', low
2987             * 'i', intermediate
2988             * 'h', high
2989             * 'f', full
2990        [kindfigure]: kind of figure
2991          'legend': only points in the map with the legend with the names
2992          'labelled',[txtsize],[txtcol]: points with the names and size, color of text
2993        [pointcolor]: color for the points ('auto' for "red")
2994        [pointlabels]: ',' of labels [only used if [collab]='None'] ('None' for no labels, '!' for spaces)
2995        [legvals]=[locleg]|[fontsize]:
2996          [locleg]: location of the legend (0, autmoatic)
2997            1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
2998            5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
2999            9: 'upper center', 10: 'center'
3000          [fontsize]: font size for the legend (auto for 12)
3001        [figureko]: kind of the output file (pdf, png, ...)
3002        [figuren]: name of the figure
3003        [close]: Whether figure should be finished or not
3004      [filen]= [ncfile],[lonvarn],[latvarn][,[varn],[dimvals],[vargn],[min],[max],[colbarn],[fmtcolorbar],[orientation],[varu]]
3005        [ncfile]: netCDF to use to geolocalize the points
3006        [lonvarn]: name of the variable with the longitudes
3007        [latvarn]: name of the variable with the latitudes
3008        Optional values:
3009          [varn]: optional variable to add staff into the graph
3010          [dimval]: '@' list of [dimn]|[dimval] to get the values for [varn]
3011            [dimn]: name of the dimension
3012            [dimval]: value of the dimension variable a given value is required:
3013              * [integer]: which value of the dimension
3014              * -1: all along the dimension
3015              * -9: last value of the dimension
3016              * [beg];[end];[inc] slice from [beg] to [end] every [inc]
3017              * NOTE, no dim name all the dimension size
3018          [vargn]: name of the variable in the graph
3019          [min]: minimum value for the extra variable
3020          [max]: maximum value for the extra variable
3021          [colbarn]: name of the color bar
3022          [fmtcolorbar]: format of the numbers in the color bar 'C'-like ('auto' for %6g)
3023          [orientation]: orientation of the colorbar ('vertical' (default, by 'auto'), 'horizontal')
3024          [varu]: units of the variable
3025    """
3026    fname = 'draw_points'
3027
3028    if values == 'h':
3029        print fname + '_____________________________________________________________'
3030        print draw_points.__doc__
3031        quit()
3032
3033    expectargs = '[ptasciifile]:[gtit]:[dimxyfmt]:[mapvalues]:[kindfigure]:' +       \
3034      '[pointcolor]:[pointlabels]:[locleg]:[figurek]:[figuren]:[close]'
3035 
3036    drw.check_arguments(fname,values,expectargs,':')
3037
3038    ptasciifile = values.split(':')[0]
3039    gtit = values.split(':')[1]
3040    dimxyfmt = values.split(':')[2]
3041    mapvalues = values.split(':')[3]
3042    kindfigure = values.split(':')[4]
3043    pointcolor = values.split(':')[5]
3044    pointlabels = values.split(':')[6].replace('!',' ')
3045    locleg = int(values.split(':')[7])
3046    figureko = values.split(':')[8]
3047    figuren = values.split(':')[9]
3048    close = gen.Str_Bool(values.split(':')[10])
3049
3050# Getting station locations
3051##
3052    filev = ptasciifile.split(',')[0]
3053    comchar = ptasciifile.split(',')[1].split('|')
3054    collon = int(ptasciifile.split(',')[2])
3055    collat = int(ptasciifile.split(',')[3])
3056    collab = ptasciifile.split(',')[4]
3057
3058    if not os.path.isfile(filev):
3059        print errormsg
3060        print '  ' + fname + ": file '" + filev + "' does not exist!!"
3061        quit(-1)
3062
3063# Getting points position and labels
3064    oascii = open(filev, 'r')
3065    xptval = []
3066    yptval = []
3067    if collab != 'None':
3068        ptlabels = []
3069        for line in oascii:
3070            if not drw.searchInlist(comchar, line[0:1]):
3071                linevals = drw.reduce_spaces(line)
3072                xptval.append(np.float(linevals[collon].replace('\n','')))
3073                yptval.append(np.float(linevals[collat].replace('\n','')))
3074                ptlabels.append(linevals[int(collab)].replace('\n',''))
3075    else:
3076        ptlabels = None
3077        for line in oascii:
3078            if  not drw.searchInlist(comchar, line[0:1]):
3079                linevals = drw.reduce_spaces(line)
3080                xptval.append(np.float(linevals[collon].replace('\n','')))
3081                yptval.append(np.float(linevals[collat].replace('\n','')))
3082
3083    oascii.close()
3084
3085    if pointlabels != 'None' and collab == 'None':
3086        ptlabels = pointlabels.split(',')
3087
3088# Getting localization of the points
3089##
3090    filev = filen.split(',')
3091    Nvals = len(filev)
3092
3093    ncfile = filev[0]
3094    lonvarn = filev[1]
3095    latvarn = filev[2]
3096    varn = None
3097    varextrav = None
3098    if Nvals == 12:
3099        varn = filev[3]
3100        dimvals = filev[4]
3101        varextrav = [filev[5], np.float(filev[6]), np.float(filev[7]), filev[8],     \
3102          filev[9], filev[10], filev[11]]
3103        if filev[9] == 'auto': varextrav[4] = '%6g'
3104        if filev[10] == 'auto': varextrav[5] = 'vertical'
3105   
3106    if not os.path.isfile(ncfile):
3107        print errormsg
3108        print '  ' + fname + ": file '" + ncfile + "' does not exist!!"
3109        quit(-1)
3110
3111    onc = NetCDFFile(ncfile, 'r')
3112   
3113    # Slicing lon,lats
3114    dd = {}
3115    for dn in dimvals.split('@'):
3116        ddn = dn.split('|')[0]
3117        ddv = dn.split('|')[1]
3118        dd[ddn] = ddv
3119
3120    objlon = onc.variables[lonvarn]
3121    vard = objlon.dimensions
3122    slicevar = []
3123    for dv in vard:
3124        found= False
3125        for dn in dd.keys():
3126            if dn == dv:
3127                if dd[dn].find(';') == -1:
3128                    if dd[dn] == '-1':
3129                        slicevar.append(slice(0,len(onc.dimensions[dv])))
3130                    elif dd[dn] == '-9':
3131                        slicevar.append(len(onc.dimensions[dv]))
3132                    else:
3133                        slicevar.append(int(dd[dn]))
3134                else:
3135                    islc = int(dd[dn].split(';')[0])
3136                    eslc = int(dd[dn].split(';')[1])
3137                    tslc = int(dd[dn].split(';')[2])
3138                    slicevar.append(slice(islc,eslc,tslc))
3139                found = True
3140                break
3141        if not found:
3142            slicevar.append(slice(0,len(onc.dimensions[dv])))
3143    lonvals = np.squeeze(objlon[tuple(slicevar)])
3144
3145    objlat = onc.variables[latvarn]
3146    vard = objlat.dimensions
3147    slicevar = []
3148    for dv in vard:
3149        found= False
3150        for dn in dd.keys():
3151            if dn == dv:
3152                if dd[dn].find(';') == -1:
3153                    if dd[dn] == '-1':
3154                        slicevar.append(slice(0,len(onc.dimensions[dv])))
3155                    elif dd[dn] == '-9':
3156                        slicevar.append(len(onc.dimensions[dv]))
3157                    else:
3158                        slicevar.append(int(dd[dn]))
3159                else:
3160                    islc = int(dd[dn].split(';')[0])
3161                    eslc = int(dd[dn].split(';')[1])
3162                    tslc = int(dd[dn].split(';')[2])
3163                    slicevar.append(slice(islc,eslc,tslc))
3164                found = True
3165                break
3166        if not found:
3167            slicevar.append(slice(0,len(onc.dimensions[dv])))
3168    latvals = np.squeeze(objlat[tuple(slicevar)])
3169
3170    lonv, latv = drw.lonlat2D(lonvals, latvals)
3171
3172    if varn is not None:
3173        objextra = onc.variables[varn]
3174        vard = objextra.dimensions
3175        slicevar = []
3176        for dv in vard:
3177            found= False
3178            for dn in dd.keys():
3179                if dn == dv:
3180                    if dd[dn].find(';') == -1:
3181                        if dd[dn] == '-1':
3182                            slicevar.append(slice(0,len(onc.dimensions[dv])))
3183                        elif dd[dn] == '-9':
3184                            slicevar.append(len(onc.dimensions[dv]))
3185                        else:
3186                            slicevar.append(int(dd[dn]))
3187                    else:
3188                        islc = int(dd[dn].split(';')[0])
3189                        eslc = int(dd[dn].split(';')[1])
3190                        tslc = int(dd[dn].split(';')[2])
3191                        slicevar.append(slice(islc,eslc,tslc))
3192                    found = True
3193                    break
3194            if not found:
3195                slicevar.append(slice(0,len(onc.dimensions[dv])))
3196
3197        varextra = np.squeeze(objextra[tuple(slicevar)])
3198
3199    # Axis values
3200    xstyl, xaxf, Nxax, xaxor, ystyl, yaxf, Nyax, yaxor = drw.format_axes(dimxyfmt,',')
3201    xaxis = [xstyl, xaxf, Nxax, xaxor]
3202    yaxis = [ystyl, yaxf, Nyax, yaxor]
3203
3204    if mapvalues == 'None':
3205        mapV = None
3206    else:
3207        mapV = mapvalues
3208
3209    drw.plot_points(xptval, yptval, lonv, latv, varextra, varextrav, gtit, xaxis,    \
3210      yaxis, mapV, kindfigure, pointcolor, ptlabels, locleg, figureko, figuren, close)
3211
3212    onc.close()
3213
3214    return
3215
3216def draw_points_lonlat(filen, values):
3217    """ Function to plot a series of lon/lat points
3218      filen= name of the file
3219      values= [lonvarname]:[latvarname]:[gkind]:[gtit]:[ptcolor]:[pttype]:[ptsize]:[labels]:[legvals]:[figureK]
3220        [lonvarname]: name of the variable longitude
3221        [latvarname]: name of the variable latitude
3222        [gkind]: kind of graphical output
3223        [gtit]: graphic title '!' for spaces
3224        [ptcolor]: color of the points ('auto', for "red")
3225        [pttype]: type of point
3226        [ptsize]: size of point
3227        [labels]: ',' list of labels to use
3228        [legvals]=[locleg]|[fontsize]:
3229          [locleg]: location of the legend (0, autmoatic)
3230            1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
3231            5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
3232            9: 'upper center', 10: 'center'
3233          [fontsize]: font size for the legend (auto for 12)
3234        [figureK]= kind of figure
3235          'legend': only points in the map with the legend with the names
3236          'labelled',[txtsize],[txtcol]: points with the names and size, color of text
3237    """
3238    fname = 'draw_points_lonlat'
3239
3240    if values == 'h':
3241        print fname + '_____________________________________________________________'
3242        print draw_points_lonlat.__doc__
3243        quit()
3244
3245    expectargs = '[lonvarname]:[latvarname]:[gkind]:[gtit]:[ptcolor]:[pttype]:' +    \
3246      '[ptsize]:[labels]:[locleg]:[figureK]'
3247 
3248    drw.check_arguments(fname,values,expectargs,':')
3249
3250    lonname = values.split(':')[0]
3251    latname = values.split(':')[1]
3252    kindfigure = values.split(':')[2]
3253    gtit = values.split(':')[3].replace('!',' ')
3254    pointcolor = values.split(':')[4]
3255    pointtype = values.split(':')[5]
3256    pointsize = np.float(values.split(':')[6])
3257    labelsv = values.split(':')[7]
3258    loclegend = values.split(':')[8]
3259    figureK = values.split(':')[9]
3260
3261    fname = 'points_lonlat'
3262
3263    onc = NetCDFFile(filen, 'r')
3264    if not onc.variables.has_key(lonname):
3265        print errormsg
3266        print fname + ": file '" + filen + "' does not have longitudes '" + lonname +\
3267          "' !!"
3268        quit(-1)
3269    if not onc.variables.has_key(lonname):
3270        print errormsg
3271        print fname + ": file '" + filen + "' does not have longitudes '" + lonname +\
3272          "' !!"
3273        quit(-1)
3274   
3275    olon = onc.variables[lonname]
3276    olat = onc.variables[latname]
3277
3278    Ndimlon = len(olon.shape)
3279    if Ndimlon == 1:
3280        dx = olon.shape[0]
3281        dy = olat.shape[0]
3282        if dx == dy: 
3283            lonvals = olon[:]
3284            latvals = olat[:]
3285        else: 
3286            lonvals0 = np.zeros((dy,dx), dtype=np.float)
3287            latvals0 = np.zeros((dy,dx), dtype=np.float)
3288            for iL in range(dy):
3289                lonvals0[iL,:] = olon[:]
3290            for il in range(dx):
3291                latvals0[:,il] = olat[:]
3292            lonvals = lonvals0.flatten()
3293            latvals = latvals0.flatten()
3294
3295    elif Ndimlon == 2:
3296        lonvals = olon[:].flatten()
3297        latvals = olat[:].flatten()
3298    elif Ndimlon == 3:
3299        lonvals = olon[1,:,:].flatten()
3300        latvals = olat[1,:,:].flatten()
3301# Playing for Anna
3302#        lonvals = olon[:].flatten()
3303#        latvals = olat[:].flatten()
3304    elif Ndimlon == 4:
3305        lonvals = olon[1,0,:,:].flatten()
3306        latvals = olat[1,0,:,:].flatten()
3307    else:
3308        print errormsg
3309        print '  ' + fname + ': longitude size:',len(olon),' not ready!!'
3310        quit(-1)
3311
3312    if labelsv == 'None':
3313        labels = None
3314    else:
3315        labels = labelsv.split(',')
3316
3317    drw.plot_list_points(lonvals, latvals, lonname, latname, gtit, figureK, pointcolor, pointtype,    \
3318      pointsize, labels, loclegend, kindfigure, fname)
3319
3320    onc.close()
3321
3322    return
3323
3324def draw_timeSeries(filen, values, variables):
3325    """ Function to draw a time-series
3326      draw_timeSeries(filen, values, variable):
3327        filen= name of the file
3328        values= [gvarname]:[timetit]:[tkind]:[timefmt]:[title]:[legvals]:[gkind]:[colorlines]:[pointtype]:[pointfreq]
3329        [gvarname]: name of the variable to appear in the graph
3330        [timetit]: title of the time axis (assumed x-axis, '|' for spaces)
3331        [tkind]: kind of time to appear in the graph (assumed x-axis)
3332          'Nval': according to a given number of values as 'Nval',[Nval]
3333          'exct': according to an exact time unit as 'exct',[tunit];
3334            tunit= [Nunits],[tu]; [tu]= 'c': centuries, 'y': year, 'm': month,
3335              'w': week, 'd': day, 'h': hour, 'i': minute, 's': second,
3336              'l': milisecond
3337        [timefmt]: format of the time labels
3338        [title]: title of the graphic ('|' for spaces)
3339        [legvals]=[locleg]|[fontsize]:
3340          [locleg]: location of the legend (0, autmoatic)
3341            1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
3342            5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
3343            9: 'upper center', 10: 'center'
3344          [fontsize]: font size for the legend (auto for 12)
3345        [gkind]: kind of graphical output
3346        [colorlines]: ',' list of colors for the lines, None for automatic, single
3347          value all the same
3348        [pointtype]: ',' list of type of points for the lines, None for automatic, single
3349          value all the same
3350        [pointfreq]: frequency of point plotting, 'all' for all time steps
3351      variables= [varname],[timename] names of variable and variable with times
3352      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')
3353    """
3354
3355    fname = 'draw_timeSeries'
3356
3357    if values == 'h':
3358        print fname + '_____________________________________________________________'
3359        print draw_timeSeries.__doc__
3360        quit()
3361
3362    expectargs = '[gvarname]:[timetit]:[tkind]:[timefmt]:[title]:' +                 \
3363      '[locleg]:[gkind]:[colorlines]:[pointtype]:[pointfreq]'
3364 
3365    drw.check_arguments(fname,values,expectargs,':')
3366
3367    gvarname = values.split(':')[0]
3368    timetit = values.split(':')[1].replace('|',' ')
3369    tkind = values.split(':')[2]
3370    timefmt = values.split(':')[3]
3371    title = values.split(':')[4].replace('|',' ')
3372    locleg = int(values.split(':')[5])
3373    gkind = values.split(':')[6]
3374    colorlines = values.split(':')[7]
3375    pointtype = values.split(':')[8]
3376    pointfreq0 = values.split(':')[9]
3377   
3378    ncobj = NetCDFFile(filen, 'r')
3379
3380    variable = variables.split(',')[0]
3381    timevar = variables.split(',')[1]
3382
3383    if not ncobj.variables.has_key(variable):
3384        print errormsg
3385        print '  ' + fname + ": file '" +  filen + "' does not have variable '" +    \
3386          variable + "' !!"
3387        quit(-1)
3388
3389    if not ncobj.variables.has_key(timevar):
3390        print errormsg
3391        print '  ' + fname + ": file '" +  filen + "' does not have variable time '" \
3392          + timevar + "' !!"
3393        quit(-1)
3394
3395    varobj = ncobj.variables[variable]
3396    timeobj = ncobj.variables[timevar]
3397
3398    dimt = len(timeobj[:])
3399    varvals = np.zeros((2,dimt), dtype=np.float)
3400
3401    gunits = varobj.getncattr('units')
3402    tunits = timeobj.getncattr('units')
3403
3404    varvals[0,:], valpot, newgunits, Spot = drw.pot_values(varobj[:].flatten(), gunits)
3405    varvals[1,:] = timeobj[:]
3406
3407    tseriesvals = []
3408    tseriesvals.append(varvals)
3409
3410    if colorlines == 'None': 
3411        collines = None
3412    else:
3413        collines = colorlines.split(',')
3414    if pointtype == 'None': 
3415        pttype = None
3416    else:
3417        pttype = pointtype.split(',')
3418
3419    if pointfreq0 == 'all':
3420        pointfreq = None
3421    else:
3422        pointfreq = int(pointfreq0)
3423
3424    drw.plot_TimeSeries(tseriesvals, Spot + drw.units_lunits(gunits), tunits,        \
3425      'TimeSeries', gvarname, timetit, tkind, timefmt, title,                        \
3426      gvarname.replace('_','\_'), locleg, gkind, collines, pttype, pointfreq)
3427
3428    return
3429
3430#draw_timeSeries('wrfout_d01_1979-12-01_00:00:00_bottom_top_B6-E6-I1_south_north_B3-E3-I1_west_east_B26-E26-I1.nc', 'dt_con:time|($[DD]^{[HH]}$):exct,12,h:$%d^{%H}$:time|evolution|at|-1|6|3|26:1:pdf:None:None', 'LDQCON,time')
3431
3432def draw_trajectories(trjfilens, values, observations):
3433    """ Function to draw different trajectories at the same time
3434    draw_trajectories(trjfilens, values, observations):
3435      trjfilens= [filen]@[Tint]@[map] ',' separated list of files with trajectories,
3436         time intervals and reference maps (first one will be used to plot)
3437        [filen]: name of the file to use (lines with '#', not readed) as:
3438          [t-step] [x] [y]
3439        [Tint]: interval of time as [Tbeg]@[Tend] or -1 for all the interval
3440        [map]: [file]#[lonname]#[latname]
3441          [file]; with the [lon],[lat] matrices
3442          [lonname],[latname]; names of the longitudes and latitudes variables
3443      values=[leglabels]|[lonlatlims]|[title]|[graphk]|[mapkind]
3444        [leglabels]: ',' separated list of names for the legend
3445        [lonlatlims]: ',' list of limits of the map [lonmin, latmin, lonmax, latmax] or None
3446        [title]: title of the plot ('!' for spaces)
3447        [graphk]: kind of the graphic
3448        [mapkind]: drawing coastaline ([proj],[res]) or None
3449          [proj]: projection
3450             * 'cyl', cilindric
3451             * 'lcc', lambert conformal
3452          [res]: resolution:
3453             * 'c', crude
3454             * 'l', low
3455             * 'i', intermediate
3456             * 'h', high
3457             * 'f', full
3458      obsevations= [obsfile],[obsname],[Tint],[null]
3459        [obsfile]: name fo the File with the observations as [t-step] [lat] [lon]
3460        [obsname]: name of the observations in the graph
3461        [Tint]: interval of time as [Tbeg]@[Tend] or -1 for all the interval
3462        [null]: null value for the observed trajectory
3463    """
3464
3465    fname = 'draw_trajectories'
3466
3467    if values == 'h':
3468        print fname + '_____________________________________________________________'
3469        print draw_trajectories.__doc__
3470        quit()
3471
3472    expectargs = '[leglabels]|[lonlatlims]|[title]|[graphk]|[mapkind]'
3473 
3474    drw.check_arguments(fname,values,expectargs,'|')
3475
3476    trjfiles = trjfilens.split(',')
3477    leglabels = values.split('|')[0]
3478    lonlatlims = values.split('|')[1]
3479    title = values.split('|')[2].replace('!',' ')
3480    graphk = values.split('|')[3]
3481    mapkind = values.split('|')[4]
3482
3483    Nfiles = len(trjfiles)
3484
3485# Getting trajectotries
3486##
3487
3488    lontrjvalues = []
3489    lattrjvalues = []
3490
3491    print '  ' + fname
3492    ifn = 0
3493    for ifile in trjfiles:
3494        filen = ifile.split('@')[0]
3495        Tint = ifile.split('@')[1]
3496
3497        print '    trajectory:',filen
3498
3499        if Tint != '-1':
3500            Tbeg = Tint
3501            Tend = ifile.split('@')[2]
3502            mapv = ifile.split('@')[3]
3503        else:
3504            mapv = ifile.split('@')[2]
3505
3506        if not os.path.isfile(filen):
3507            print errormsg
3508            print '  ' + fname + ": trajectory file '" + filen + "' does not exist !!"
3509            quit(-1)
3510
3511# Charging longitude and latitude values
3512##
3513        lonvals, latvals = drw.lonlat_values(mapv.split('#')[0], mapv.split('#')[1], \
3514          mapv.split('#')[2])
3515
3516        if ifn == 0: mapref = mapv
3517        ifn = ifn + 1
3518
3519        objfile = open(filen, 'r')
3520        trjtimev = []
3521        trjxv = []
3522        trjyv = []
3523
3524        for line in objfile:
3525            if line[0:1] != '#':
3526                trjtimev.append(int(line.split(' ')[0]))
3527                trjxv.append(int(line.split(' ')[1]))
3528                trjyv.append(int(line.split(' ')[2]))
3529
3530        objfile.close()
3531
3532        if Tint != '-1':
3533            lontrjvalues.append(lonvals[trjyv[Tint:Tend+1], trjxv[Tint:Tend+1]])
3534            lattrjvalues.append(latvals[trjyv[Tint:Tend+1], trjxv[Tint:Tend+1]])
3535        else:
3536            lontrjvalues.append(lonvals[trjyv[:], trjxv[:]])
3537            lattrjvalues.append(latvals[trjyv[:], trjxv[:]])
3538
3539# lonlatlimits
3540##
3541
3542    if lonlatlims == 'None':
3543        lonlatlimsv = None
3544    else:
3545        lonlatlimsv = np.zeros((4), dtype=np.float)
3546        lonlatlimsv[0] = np.float(lonlatlims.split(',')[0])
3547        lonlatlimsv[1] = np.float(lonlatlims.split(',')[1])
3548        lonlatlimsv[2] = np.float(lonlatlims.split(',')[2])
3549        lonlatlimsv[3] = np.float(lonlatlims.split(',')[3])
3550
3551# lon/lat objects
3552##
3553    objnc = NetCDFFile(mapref.split('#')[0])
3554    lonobj = objnc.variables[mapref.split('#')[1]]
3555    latobj = objnc.variables[mapref.split('#')[2]]
3556
3557# map
3558##
3559    if mapkind == 'None':
3560        mapkindv = None
3561    else:
3562        mapkindv = mapkind
3563
3564    if observations is None:
3565        obsname = None
3566    else:
3567        obsfile = observations.split(',')[0]
3568        obsname = observations.split(',')[1]
3569        Tint = observations.split(',')[2]
3570        null = np.float(observations.split(',')[3])
3571        print '    observational trajectory:',obsfile
3572
3573        if not os.path.isfile(obsfile):
3574            print errormsg
3575            print '  ' + fname + ": observations trajectory file '" + obsfile +      \
3576              "' does not exist !!"
3577            quit(-1)
3578
3579        objfile = open(obsfile, 'r')
3580        obstrjtimev = []
3581        obstrjxv = []
3582        obstrjyv = []
3583
3584        for line in objfile:
3585            if line[0:1] != '#':
3586                lon = np.float(line.split(' ')[2])
3587                lat = np.float(line.split(' ')[1])
3588                if not lon == null and not lat == null:
3589                    obstrjtimev.append(int(line.split(' ')[0]))
3590                    obstrjxv.append(lon)
3591                    obstrjyv.append(lat)
3592                else:
3593                    obstrjtimev.append(int(line.split(' ')[0]))
3594                    obstrjxv.append(None)
3595                    obstrjyv.append(None)
3596
3597        objfile.close()
3598
3599        if Tint != '-1':
3600            Tint = int(observations.split(',')[2].split('@')[0])
3601            Tend = int(observations.split(',')[2].split('@')[1])
3602            lontrjvalues.append(obstrjxv[Tint:Tend+1])
3603            lattrjvalues.append(obstrjyv[Tint:Tend+1])
3604        else:
3605            lontrjvalues.append(obstrjxv[:])
3606            lattrjvalues.append(obstrjyv[:])
3607
3608    drw.plot_Trajectories(lontrjvalues, lattrjvalues, leglabels.split(','),          \
3609      lonobj, latobj, lonlatlimsv, title, graphk, mapkindv, obsname)
3610
3611    objnc.close()
3612
3613    return
3614
3615def draw_vals_trajectories(ncfile, values, variable):
3616    """ Function to draw values from the outputs from 'compute_tevolboxtraj'
3617      draw_vals_trajectories(ncfile, values, variable)
3618      ncfile= [ncfile] ',' list of files to use
3619      values= [statisticskind]:[Tint]:[labels]@[legvals]:[gvarname]:[timetit]:[tkind]:[timefmt]:[title]:[gkind]
3620        [statisticskind]=[statistics][kind]
3621          [statistics]: which statistics to use, from: 'center', 'min', 'max', 'mean',
3622            'mean2', 'stdev'
3623          [kind]: 'box', 'circle' statistics taking the values from a box or a circle
3624            'trj': value following the trajectory
3625        [Tint]: [Tbeg]@[Tend] or None, interval of time to plot or -1 for all the times
3626        [labels]: ',' separated list of labels for the legend
3627        [legvals]=[locleg]|[fontsize]:
3628          [locleg]: location of the legend (0, autmoatic)
3629            1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
3630            5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
3631            9: 'upper center', 10: 'center'
3632          [fontsize]: font size for the legend (auto for 12)
3633        [gvarname]: name of the variable to appear in the graph
3634        [timetit]: title of the time axis (assumed x-axis, '|' for spaces)
3635        [tkind]: kind of time to appear in the graph (assumed x-axis)
3636          'Nval': according to a given number of values as 'Nval',[Nval]
3637          'exct': according to an exact time unit as 'exct',[tunit];
3638            tunit= [Nunits],[tu]; [tu]= 'c': centuries, 'y': year, 'm': month,
3639              'w': week, 'd': day, 'h': hour, 'i': minute, 's': second,
3640                'l': milisecond
3641        [timefmt]: format of the time labels
3642        [title]: title of the graphic ('|' for spaces)
3643        [gkind]: kind of graphical output
3644      variable= variable to use
3645    """
3646    fname = 'draw_vals_trajectories'
3647
3648    if values == 'h':
3649        print fname + '_____________________________________________________________'
3650        print draw_vals_trajectories.__doc__
3651        quit()
3652
3653    sims = ncfile.split(',')
3654
3655    if len(values.split(':')) != 9:
3656        print errormsg
3657        print '  ' + fname  + ': wrong number of values!', len(values.split(':')),   \
3658          'given 9 needed!!'
3659        print '    ',values.split(':')
3660        quit(-1)
3661
3662    statisticskind = values.split(':')[0]
3663    Tint = values.split(':')[1]
3664    labels = values.split(':')[2]
3665    gvarname = values.split(':')[3]
3666    timetit = values.split(':')[4].replace('|',' ')
3667    tkind = values.split(':')[5]
3668    timefmt = values.split(':')[6]
3669    title = values.split(':')[7].replace('|',' ')
3670    gkind = values.split(':')[8]
3671
3672    leglabels = labels.split('@')[0].split(',')
3673    locleg = int(labels.split('@')[1])
3674
3675    Nsims = len(sims)
3676
3677    if Tint != '-1':
3678        tini = np.float(Tint.split('@')[0])
3679        tend = np.float(Tint.split('@')[1])
3680    else:
3681        tini = -1.
3682        tend = -1.
3683
3684    vartimetrjv = []
3685
3686    print '  ' + fname
3687    for trjfile in sims:
3688        print '    ' + trjfile + ' ...'
3689        if not os.path.isfile(trjfile):
3690            print errormsg
3691            print '  ' + fname + ": trajectory file: '" + trjfile +                  \
3692              "' does not exist !!"
3693            quit(-1)
3694
3695        trjobj = NetCDFFile(trjfile, 'r')
3696        otim = trjobj.variables['time']
3697        if not trjobj.variables.has_key(statisticskind + '_' + variable):
3698            print errormsg
3699            print '  ' + fname + ": file '" + trjfile + "' does not have variable '"+\
3700              statisticskind + '_' + variable + "' !!"
3701            quit(-1)
3702        ovar = trjobj.variables[statisticskind + '_' + variable]
3703        dimt = otim.shape[0]
3704
3705        if trjfile == sims[0]:
3706            gunits = ovar.getncattr('units')
3707            lname = ovar.getncattr('long_name')
3708            tunits = otim.getncattr('units')
3709
3710        if tini != -1:
3711            tiniid = -1
3712            tendid = -1       
3713            for itv in range(dimt):
3714                if otim[itv] <= tini and otim[itv+1] >= tini: tiniid = itv
3715                if otim[itv] <= tend and otim[itv+1] >= tend: tendid = itv
3716
3717            if tiniid == -1 or tendid == -1:
3718                print errormsg
3719                print '  ' + main + ' time interval ', tini,',',tend,' not found: ',     \
3720                  tendid, ',', tiniid, ' !!'
3721                print '    data interval [',otim[0], otim[dimt-1],']'
3722                quit(-1)
3723            dimt = tendid - tiniid + 1
3724
3725        else:
3726            dimt = otim.shape[0]
3727
3728        valsv = np.zeros((2,dimt), dtype=np.float)
3729# Checking for time consistency
3730        if otim.getncattr('units') != tunits:
3731            print warnmsg
3732            print '  ' + fname + ': different time units in the plot!!'
3733            newtimes = gen.coincident_CFtimes(otim[:], tunits, otim.getncattr('units'))
3734        else:
3735            newtimes = otim[:]
3736
3737        if tini == -1:
3738            valsv[1,:] = newtimes[:]
3739            valsv[0,:] = ovar[:]
3740        else:
3741            valsv[1,:] = newtimes[tiniid:tendid+1]
3742            valsv[0,:] = ovar[tiniid:tendid+1]
3743
3744        vartimetrjv.append(valsv)
3745        trjobj.close()
3746
3747    drw.plot_TimeSeries(vartimetrjv, drw.units_lunits(gunits), tunits,               \
3748      'val_trajectories_' + statisticskind, gvarname, timetit, tkind, timefmt, title,\
3749      leglabels, locleg, gkind)
3750
3751def variable_values(values):
3752    """ Function to give back values for a given variable
3753      values= [varname] name of the variable
3754    """
3755
3756    fname = 'variable_values'
3757
3758    values = drw.variables_values(values)
3759
3760    print fname,'values:',values
3761    print fname,'variable_name:',values[0]
3762    print fname,'standard_name:',values[1]
3763    print fname,'min,max:',str(values[2]) + ',' + str(values[3])
3764    print fname,'long_name:',values[4]
3765    print fname,'units:',values[5]
3766    print fname,'shad_colors:',values[6]
3767    print fname,'all_values:',drw.numVector_String(values,',')
3768
3769    return
3770
3771def draw_ptZvals(ncfile, values, variable):
3772    """ Function to plot a given list of points and values
3773      ncfile= netCDF file to use
3774      values= [fvname]:[XYvar]:[pointype]:[pointsize]:[graphlimits]:[nxtype]:
3775        [figuretitle]:[colorbar]:[mapvalue]:[kindfig]
3776        fvname: name of the variable in the graph
3777        XYvar: [lon],[lat] variable names
3778        ptype: type of the point
3779        ptsize: size of the point
3780        graphlimits: minLON,minLAT,maxLON,maxLAT limits of the graph 'None' for the full size
3781        nxtype: minimum and maximum type
3782          'auto': values taken from the extrems of the data
3783          [min],[max]: given minimum and maximum values
3784        figtitle: title of the figure
3785        cbar: color bar
3786        mapv: map characteristics: [proj],[res]
3787          see full documentation: http://matplotlib.org/basemap/
3788          [proj]: projection
3789            * 'cyl', cilindric
3790            * 'lcc', lambert-conformal
3791          [res]: resolution:
3792            * 'c', crude
3793            * 'l', low
3794            * 'i', intermediate
3795            * 'h', high
3796            * 'f', full
3797        kfig: kind of figure
3798      variable= name of the variable to plot
3799    """
3800    fname = 'draw_ptZvals'
3801    import numpy.ma as ma
3802
3803    if values == 'h':
3804        print fname + '_____________________________________________________________'
3805        print draw_ptZvals.__doc__
3806        quit()
3807
3808    expectargs = '[fvname]:[XYvar]:[pointype]:[pointsize]:[graphlmits]:[nxtype]:' +  \
3809      '[figuretit]:[colorbar]:[mapvalue]:[kindfig]'
3810 
3811    drw.check_arguments(fname,values,expectargs,':')
3812
3813    fvname = values.split(':')[0]
3814    XYvar = values.split(':')[1]
3815    pointype = values.split(':')[2]
3816    pointsize = int(values.split(':')[3])
3817    graphlimits = values.split(':')[4]
3818    nxtype = values.split(':')[5]
3819    figuretitle = values.split(':')[6].replace('!',' ')
3820    colorbar = values.split(':')[7]
3821    mapvalue = values.split(':')[8]
3822    kindfig = values.split(':')[9]
3823
3824    onc = NetCDFFile(ncfile, 'r')
3825   
3826    if not onc.variables.has_key(variable):
3827        print errormsg
3828        print '  ' + fname + ": file '" + ncfile + "' does not have variable '" +    \
3829          variable + "' !!"
3830        quit(-1)
3831
3832# points
3833    lonvarn = XYvar.split(',')[0]
3834    latvarn = XYvar.split(',')[1]
3835
3836    if not onc.variables.has_key(lonvarn):
3837        print errormsg
3838        print '  ' + fname + ": file '" + ncfile + "' does not have longitude " +    \
3839          "variable '" + lonvarn + "' !!"
3840        quit(-1)
3841   
3842    if not onc.variables.has_key(latvarn):
3843        print errormsg
3844        print '  ' + fname + ": file '" + ncfile + "' does not have latitude " +    \
3845          "variable '" + latvarn + "' !!"
3846        quit(-1)
3847
3848    olonvar = onc.variables[lonvarn]
3849    olatvar = onc.variables[latvarn]
3850    ovarvar = onc.variables[variable]
3851
3852    Lpts = len(olonvar[:].flatten())
3853
3854    pointvalues = ma.masked_array(np.zeros((Lpts,3), dtype=np.float))
3855    pointvalues[:,0] = olonvar[:].flatten()
3856    pointvalues[:,1] = olatvar[:].flatten()
3857    pointvalues[:,2] = ovarvar[:].flatten()
3858
3859    varattrs = ovarvar.ncattrs()
3860    if drw.searchInlist(varattrs, 'units'):
3861        fvunits = ovarvar.getncattr('units')
3862    else:
3863        fvunits = drw.variables_values(variable)[5]
3864
3865# map value
3866    if mapvalue == 'None': mapvalue = None
3867
3868# Graph limits
3869    if graphlimits != 'None':
3870        graphlts = np.zeros((4), dtype=np.float)
3871        for il in range(4): graphlts[il] = np.float(graphlimits.split(',')[il])
3872        pointvalues[:,0] = ma.masked_outside(pointvalues[:,0], graphlts[0],          \
3873          graphlts[2])
3874        pointvalues[:,1] = ma.masked_outside(pointvalues[:,1], graphlts[3],          \
3875          graphlts[2])
3876
3877#        for ip in range(Lpts): 
3878#            if pointvalues[ip,0] < graphlts[0] or pointvalues[ip,0] > graphlts[2]    \
3879#              or pointvalues[ip,1] < graphlts[1] or pointvalues[ip,1] > graphlts[3]:
3880#                print ip,pointvalues[ip,0:2], graphlts
3881#                pointvalues[ip,2] = None
3882    else:
3883        graphlts = None
3884
3885    drw.plot_ptZvals(fvname,fvunits,pointvalues,pointype,pointsize,graphlts, nxtype, \
3886      figuretitle,colorbar,mapvalue,kindfig)
3887
3888    return
3889
3890#draw_ptZvals('OBSnetcdf.nc', 'pracc:lon,lat:o:80:2,42,7,47,:values!of!values:Blues:cyl,l:pdf', 'pr')
3891
3892def draw_vectors(ncfile, values, varns):
3893    """ Function to plot wind vectors
3894      values= [dimname]|[vardimname]|[value]:[vecvals]:[windlabs]:[mapvalues]:
3895        [gtit]:[kindfig]:[figuren]
3896        'X/Y/Z/T'|[dimname]|[vardimname]|[value]: ',', list for each basic dimension '|' separated of:
3897          [dimname]: name of the dimension in the file
3898          [vardimname]: name of the variable with the values for the dimension in the file
3899          [value]: which value of the given dimension is required:
3900            * [integer]: which value of the dimension
3901            * -1: all along the dimension
3902            * -9: last value of the dimension
3903            * [beg]:[end] slice from [beg] to [end]
3904            * NOTE, no dim name all the dimension size
3905          No value takes all the range of the dimension
3906        [vecvals]= [frequency],[color],[length]
3907          [frequency]: [xfreq]@[yfreq] frequency of values allong each axis ('None', all grid points;
3908            'auto', computed automatically to have 20 vectors along each axis)
3909          [color]: color of the vectors
3910            'singlecol'@[colorn]: all the vectors same color ('auto': for 'red')
3911            'wind'@[colorbar],[sminv]|[smaxv]: color of the vectors according to wind speed sqrt(u^2+v^2) and given [colorbar]
3912              all vectors the same length
3913              [smin/axv]: minimum and maximum value for the shading or:
3914               'Srange': for full range
3915               'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean)
3916               'Saroundminmax@val': for min*val,max*val
3917               'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val),
3918                 percentile_(100-val)-median)
3919               'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean)
3920               'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median)
3921               'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val),
3922                 percentile_(100-val)-median)
3923 
3924            '3rdvar'@[colorbar]@[varn]@[units],[sminv]|[smaxv]: color of the vectors according to a 3rd variable (to be added at -v) and given [colorbar]
3925              all vectors the same length
3926          [length]: length of the wind vectors ('auto', for 9)
3927        [windlabs]= [windname],[windunits]
3928          [windname]: name of the wind variable in the graph
3929          [windunits]: units of the wind variable in the graph ('None', for the value in the file)
3930        [mapvalues]= map characteristics: [proj],[res]
3931          see full documentation: http://matplotlib.org/basemap/
3932          [proj]: projection
3933            * 'cyl', cilindric
3934            * 'lcc', lambert conformal
3935          [res]: resolution:
3936            * 'c', crude
3937            * 'l', low
3938            * 'i', intermediate
3939            * 'h', high
3940            * 'f', full
3941        gtit= title of the graph ('|', for spaces)
3942        kindfig= kind of figure
3943        figuren= name of the figure
3944      ncfile= file to use
3945      varns= [uwind],[ywind] ',' list of the name of the variables with the u-wind,y-wind component
3946    """
3947    fname = 'draw_vectors'
3948
3949    if values == 'h':
3950        print fname + '_____________________________________________________________'
3951        print draw_vectors.__doc__
3952        quit()
3953
3954    expectargs = '[X/Y/Z/T]|[dimname]|[vardimname]|[value]:[vecvals]:[windlabs]:' +  \
3955      '[mapvalues]:[gtit]:[kindfig]:[figuren]'
3956 
3957    drw.check_arguments(fname,values,expectargs,':')
3958
3959    dimvals = values.split(':')[0]
3960    vecvals = values.split(':')[1]
3961    windlabels = values.split(':')[2]
3962    mapvalues = values.split(':')[3]
3963    gtit = values.split(':')[4]
3964    kindfig = values.split(':')[5]
3965    figuren = values.split(':')[6]
3966
3967    of = NetCDFFile(ncfile,'r')
3968
3969    dims = {}
3970    for dimv in dimvals.split(','):
3971        dns = dimv.split('|')
3972        dims[dns[0]] = [dns[1], dns[2], dns[3]]
3973
3974    varNs = []
3975    for dn in dims.keys():
3976        if dn == 'X':
3977            varNs.append(dims[dn][1])
3978            dimx = len(of.dimensions[dims[dn][0]])
3979        elif dn == 'Y':
3980            varNs.append(dims[dn][1])
3981            dimy = len(of.dimensions[dims[dn][0]])
3982
3983    ivar = 0
3984    for wvar in varns.split(','):
3985        if not drw.searchInlist(of.variables.keys(), wvar):
3986            print errormsg
3987            print '  ' + fname + ": file does not have variable '" + wvar + "' !!"
3988            quit(-1)
3989        if ivar == 0:
3990            varNs.append(wvar)
3991        else:
3992            varNs.append(wvar)
3993
3994    ivar = 0
3995    for varN in varNs:
3996        varslice = []
3997
3998        ovarN = of.variables[varN]
3999        vard = ovarN.dimensions
4000        for vdn in vard:
4001            found = False
4002            for dd in dims.keys():
4003                if dims[dd][0] == vdn:
4004                    if dims[dd][2].find('@') != -1:
4005                        rvals = dims[dd][2].split('@')
4006                        varslice.append(slice(int(rvals[0]), int(rvals[1])))
4007                    elif dims[dd][2] == '-1':
4008                        varslice.append(slice(0,len(of.dimensions[dims[dd][0]])))
4009                    else:
4010                        varslice.append(int(dims[dd][2]))
4011
4012                    found = True
4013                    break
4014            if not found:
4015                varslice.append(slice(0,len(of.dimensions[dims[dd][0]])))
4016
4017        if varN == dims['X'][1]:
4018            lonvals0 = np.squeeze(ovarN[tuple(varslice)])
4019        elif varN == dims['Y'][1]:
4020            latvals0 = np.squeeze(ovarN[tuple(varslice)])
4021        elif ivar == 2:
4022            uwvals = np.squeeze(np.array(ovarN[tuple(varslice)]))
4023        elif ivar == 3:
4024            vwvals = np.squeeze(ovarN[tuple(varslice)])
4025
4026        ivar = ivar + 1
4027
4028#    print 'Final shapes:',lonvals0.shape,':',latvals0.shape,':',uwvals.shape,':',
4029#      vwvals.shape
4030
4031    if len(uwvals.shape) != 2 or len(vwvals.shape) != 2:
4032        print errormsg
4033        print '  ' + fname + ': wrong size of the wind fields! they must be ' +      \
4034          '2-dimensional!'
4035        print '    u-winds shape:',uwvals.shape,'dims:',of.variables[varNs[2]]
4036        print '    v-winds shape:',vwvals.shape,'dims:',of.variables[varNs[3]]
4037        print '      provide more values for their dimensions!!'
4038        quit(-1)
4039
4040    if len(lonvals0.shape) == 1:
4041        lonvals, latvals = np.meshgrid(lonvals0, latvals0)
4042    else:
4043        lonvals = lonvals0
4044        latvals = latvals0
4045
4046# Vector values
4047    if vecvals.split(',')[0] == 'None':
4048        freqv = None
4049    else:
4050        freqv = vecvals.split(',')[0] 
4051    colorvals = vecvals.split(',')[1]
4052    coln = colorvals.split('@')[0]
4053    colv = colorvals.split('@')[1]
4054    if coln == 'singlecol':
4055        colorv = colv
4056        shading_nx = None
4057    elif coln == 'wind':
4058        colorv = np.sqrt(uwvals**2 + vwvals**2)
4059        # Min/Max colorbar
4060        shadminmax = vecvals.split(',')[3]
4061        shading_nx = shadminmax.split('|')
4062        print ' Lluis shading_nx:', shading_nx
4063    elif coln == '3rdvar':
4064        if len(varn.split(',')) != 3:
4065            print errormsg
4066            print '  ' + fname + ": color of vectors should be according to '" +     \
4067              coln + "' but a third varibale is not provided !!"
4068            quit(-1)
4069        ocolvec = of.variables[varNs[4]]
4070        colorv = ocolvec[:]
4071        stdvn, lonvn, unitsvn = drw.var_3desc(ocolvec)
4072        colorvals = colorvals + '@' + stdvn + '@' + unitsvn
4073        # Min/Max colorbar
4074        shadminmax = vecvals.split(',')[5]
4075        shading_nx = shadminmax.split('|')
4076    else:
4077        print errormsg
4078        print '  ' + fname + ": color type '" + coln + "' not ready !!"
4079        quit(-1)
4080
4081    lengthv = vecvals.split(',')[2]
4082
4083# Vector labels
4084    windname = windlabels.split(',')[0]
4085    windunits = windlabels.split(',')[1]
4086
4087    drw.plot_vector(lonvals, latvals, uwvals, vwvals, freqv, colorvals, colorv,      \
4088      lengthv, shading_nx, windname, windunits, mapvalues, gtit, kindfig, figuren)
4089
4090    of.close()
4091
4092    return
4093
4094def draw_basins(ncfile, values, varns):
4095    """ Function to plot river basins with their discharge vector and basins id (from 'routing.nc')
4096      values= [lonlatbox]:[mapres]:[cbarname]:[xtrmbasin]:[mapdraw]:[veclength]:[freq]:
4097        [ifreq]:[plotcountry]:[basinidn]:[gtit]:[kindfig]:[figuren]
4098        [lonlatbox]= [lonSW],[lonNE],[latSW],[latNE] coordinates of the lon/lat box
4099        [mapres]= resolution of the mapping information
4100        [cbarname]= colorbar name for the colors
4101        [xtrmbasin]= [minbasin],[maxbasin] minimum and maximum basin numbers
4102        [mapdraw]= whether to draw the map (and project the data) or not ('True/False')
4103        [veclength]= length of the vectors of discharge at each grid cell
4104        [freq]= frequency of values allong each axis (None, all grid points;
4105          'auto', computed automatically to have 20 vectors along each axis)
4106        [plotcountry]= whether country lines should be plotted or not ('True/False')
4107        [plotbasinid]= whether id of the basins should be plotted or not ('True/False')
4108        [gtit]= title of the graph ('|', for spaces)
4109        [kindfig]= kind of figure
4110        [figuren]= name of the figure
4111      ncfile= file to use
4112    """
4113    fname = 'draw_basins'
4114
4115    if values == 'h':
4116        print fname + '_____________________________________________________________'
4117        print draw_vectors.__doc__
4118        quit()
4119
4120    expectargs = '[lonlatbox]:[mapres]:[cbarname]:[xtrmbasin]:[mapdraw]:' +          \
4121      '[veclength]:[freq]:[plotcountry]:[basinidn]:[gtit]:[kindfig]:[figuren]'
4122 
4123    drw.check_arguments(fname,values,expectargs,':')
4124
4125    varn='basins'
4126    lonname = 'nav_lon'
4127    latname = 'nav_lat'
4128    flowname = 'trip'
4129
4130    lonlims =[]
4131    latlims =[]
4132
4133    lonlims.append(np.float(values.split(':')[0].split(',')[0]))
4134    lonlims.append(np.float(values.split(':')[0].split(',')[1]))
4135    latlims.append(np.float(values.split(':')[0].split(',')[2]))
4136    latlims.append(np.float(values.split(':')[0].split(',')[3]))
4137    map_res = values.split(':')[1]
4138    cbarname = values.split(':')[2]
4139    vtit = 'basins'
4140    minbasin = np.int(values.split(':')[3].split(',')[0])
4141    maxbasin = np.int(values.split(':')[3].split(',')[1])
4142    mapdraw = gen.Str_Bool(values.split(':')[4])
4143    veclength = np.float(values.split(':')[5])
4144    freq0 = values.split(':')[6]
4145    plotcountry = gen.Str_Bool(values.split(':')[7])
4146    plotbasinid = gen.Str_Bool(values.split(':')[8])
4147    gtit = values.split(':')[9].replace('|',' ')
4148    kindfig = values.split(':')[10]
4149    figuren = values.split(':')[11]
4150
4151    if freq0 == 'None': freq = None
4152
4153    ofile = NetCDFFile(ncfile, 'r')
4154
4155    obasins = ofile.variables[varn]
4156    olon = ofile.variables[lonname]
4157    olat = ofile.variables[latname]
4158    oflow = ofile.variables[flowname]
4159
4160    lons = olon[:]
4161    lats = olat[:]
4162
4163    lon, lat = drw.lonlat2D(lons, lats)
4164
4165    nlon = lonlims[0]
4166    xlon = lonlims[1]
4167    nlat = latlims[0]
4168    xlat = latlims[1]
4169
4170    imin, imax, jmin, jmax = gen.ijlonlat(lon, lat, nlon, xlon, nlat, xlat)
4171
4172    drw.plot_basins(lon[jmin:jmax,imin:imax], lat[jmin:jmax,imin:imax],              \
4173      oflow[jmin:jmax,imin:imax], freq, cbarname+'@basin@-',                         \
4174      obasins[jmin:jmax,imin:imax], veclength, minbasin, maxbasin, 'outflow', '-',   \
4175      'cyl,'+map_res, plotcountry, plotbasinid, gtit, kindfig, figuren)
4176
4177    ofile.close()
4178
4179    return
4180
4181def draw_basinsold(ncfile, values, varns):
4182    """ Function to plot wind basins
4183      values= [dimname]|[vardimname]|[value]:[vecvals]:[windlabs]:[mapvalues]:
4184        [gtit]:[kindfig]:[figuren]
4185        'X/Y/Z/T'|[dimname]|[vardimname]|[value]: ',', list for each basic dimension '|' separated of:
4186          [dimname]: name of the dimension in the file
4187          [vardimname]: name of the variable with the values for the dimension in the file
4188          [value]: which value of the given dimension (-1, all; [ibeg]@[iend], i-range beginning, end)
4189          No value takes all the range of the dimension
4190        [vecvals]= [frequency],[color],[length]
4191          [frequency]: [xfreq]@[yfreq] frequency of values allong each axis ('None', all grid points;
4192            'auto', computed automatically to have 20 vectors along each axis)
4193          [color]: [colorbar]@[varn]@[units]: color of the vectors according to a 3rd variable (to be added at -v) and given [colorbar]
4194              all vectors the same length
4195          [length]: length of the wind vectors ('auto', for 9)
4196        [windlabs]= [windname],[windunits]
4197          [windname]: name of the wind variable in the graph
4198          [windunits]: units of the wind variable in the graph ('None', for the value in the file)
4199        [mapvalues]= map characteristics: [proj],[res]
4200          see full documentation: http://matplotlib.org/basemap/
4201          [proj]: projection
4202            * 'cyl', cilindric
4203            * 'lcc', lambert conformal
4204          [res]: resolution:
4205            * 'c', crude
4206            * 'l', low
4207            * 'i', intermediate
4208            * 'h', high
4209            * 'f', full
4210        gtit= title of the graph ('|', for spaces)
4211        kindfig= kind of figure
4212        figuren= name of the figure
4213      ncfile= file to use
4214      varns= [lon],[lat],[outflow],[basinID] ',' list of the name of the variables with the lon,lat, the outflow and the basin ID
4215    """
4216    fname = 'draw_basins'
4217
4218    if values == 'h':
4219        print fname + '_____________________________________________________________'
4220        print draw_vectors.__doc__
4221        quit()
4222
4223    expectargs = '[X/Y/Z/T]|[dimname]|[vardimname]|[value]:[vecvals]:[windlabs]:' +  \
4224      '[mapvalues]:[gtit]:[kindfig]:[figuren]'
4225 
4226    drw.check_arguments(fname,values,expectargs,':')
4227
4228    dimvals = values.split(':')[0]
4229    vecvals = values.split(':')[1]
4230    windlabels = values.split(':')[2]
4231    mapvalues = values.split(':')[3]
4232    gtit = values.split(':')[4]
4233    kindfig = values.split(':')[5]
4234    figuren = values.split(':')[6]
4235
4236    of = NetCDFFile(ncfile,'r')
4237
4238    dims = {}
4239    for dimv in dimvals.split(','):
4240        dns = dimv.split('|')
4241        dims[dns[0]] = [dns[1], dns[2], dns[3]]
4242
4243    varNs = []
4244    for dn in dims.keys():
4245        if dn == 'X':
4246            varNs.append(dims[dn][1])
4247            dimx = len(of.dimensions[dims[dn][0]])
4248        elif dn == 'Y':
4249            varNs.append(dims[dn][1])
4250            dimy = len(of.dimensions[dims[dn][0]])
4251
4252    ivar = 0
4253    for wvar in varns.split(','):
4254        if not drw.searchInlist(of.variables.keys(), wvar):
4255            print errormsg
4256            print '  ' + fname + ": file does not have variable '" + wvar + "' !!"
4257            quit(-1)
4258        if ivar == 0:
4259            varNs.append(wvar)
4260        else:
4261            varNs.append(wvar)
4262
4263    ivar = 0
4264    for varN in varNs:
4265        varslice = []
4266
4267        ovarN = of.variables[varN]
4268        vard = ovarN.dimensions
4269        for vdn in vard:
4270            found = False
4271            for dd in dims.keys():
4272                if dims[dd][0] == vdn:
4273                    if dims[dd][2].find('@') != -1:
4274                        rvals = dims[dd][2].split('@')
4275                        varslice.append(slice(int(rvals[0]), int(rvals[1])))
4276                    elif dims[dd][2] == '-1':
4277                        varslice.append(slice(0,len(of.dimensions[dims[dd][0]])))
4278                    else:
4279                        varslice.append(int(dims[dd][2]))
4280
4281                    found = True
4282                    break
4283            if not found:
4284                varslice.append(slice(0,len(of.dimensions[dims[dd][0]])))
4285
4286        if varN == dims['X'][1]:
4287            lonvals0 = np.squeeze(ovarN[tuple(varslice)])
4288        elif varN == dims['Y'][1]:
4289            latvals0 = np.squeeze(ovarN[tuple(varslice)])
4290
4291        ivar = ivar + 1
4292
4293    if len(lonvals0.shape) == 1:
4294        lonvals, latvals = np.meshgrid(lonvals0, latvals0)
4295    else:
4296        lonvals = lonvals0
4297        latvals = latvals0
4298
4299# Vector values
4300    if vecvals.split(',')[0] == 'None':
4301        freqv = None
4302    else:
4303        freqv = vecvals.split(',')[0] 
4304
4305    colorvals = vecvals.split(',')[1]
4306    if len(varn.split(',')) != 3:
4307        print errormsg
4308        print '  ' + fname + ": color of vectors should be according to '" +         \
4309          coln + "' but a third varibale is not provided !!"
4310        quit(-1)
4311
4312    ocolvec = of.variables[varNs[3]]
4313    colorv = ocolvec[:]
4314    stdvn, lonvn, unitsvn = drw.var_3desc(ocolvec)
4315    colorvals = colorvals + '@' + stdvn + '@' + unitsvn
4316
4317    lengthv = vecvals.split(',')[2]
4318
4319# Vector labels
4320    windname = windlabels.split(',')[0]
4321    windunits = windlabels.split(',')[1]
4322
4323# Vector angles
4324    oflow = ofile.variables[varNs[2]]
4325    angle = (oflow[:] - 1)*np.pi/4
4326    xflow = np.where(oflow[:] < 9, np.float(lengthv)*np.sin(angle), 0.)
4327    yflow = np.where(oflow[:] < 9, np.float(lengthv)*np.cos(angle), 0.)
4328
4329    drw.plot_basins(lonvals, latvals, xflow, yflow, freqv, colorvals, colorv,      \
4330      lengthv, windname, windunits, mapvalues, gtit, kindfig, figuren)
4331
4332    of.close()
4333
4334    return
4335
4336def draw_river_desc(ncfile, values, riverns):
4337    """ Function to plot rivers' description from ORCHIDEE's routing scheme
4338      values= [dimname]|[vardimname]|[value]:[basinvals]:[upstreamvals]:[mapvalues]:
4339        [gtit]:[kindfig]:[legvals]:[figuren]
4340        'X/Y'|[dimname]|[vardimname]|[value]: ',', list for each basic dimension '|' separated of:
4341          [dimname]: name of the dimension in the file
4342          [vardimname]: name of the variable with the values for the dimension in the file
4343          [value]: which value of the given dimension is required:
4344            * [integer]: which value of the dimension
4345            * -1: all along the dimension
4346            * -9: last value of the dimension
4347            * [beg]:[end] slice from [beg] to [end]
4348            * NOTE, no dim name all the dimension size
4349          No value takes all the range of the dimension
4350        [basinsvals]= [colorline]
4351          [basincolor]: ',' list of colors of the line to use to mark the basins contours (single value also possible)
4352        [upstreamvals]= [upstreamvarn],[colorbar]
4353          [upstreamcolor]: colorbar to use to plot the basins upstream values
4354        [mapvalues]= map characteristics: [proj],[res]
4355          see full documentation: http://matplotlib.org/basemap/
4356          [proj]: projection
4357            * 'cyl', cilindric
4358            * 'lcc', lambert conformal
4359          [res]: resolution:
4360            * 'c', crude
4361            * 'l', low
4362            * 'i', intermediate
4363            * 'h', high
4364            * 'f', full
4365        gtit= title of the graph ('|', for spaces)
4366        kindfig= kind of figure
4367        [legvals]=[locleg]|[fontsize]:
4368          [locleg]: location of the legend (0, autmoatic)
4369            1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
4370            5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
4371            9: 'upper center', 10: 'center'
4372          [fontsize]: font size for the legend (auto for 12)
4373        figuren= name of the figure
4374      ncfile= file to use
4375      riverns= ',' list of the name of the rivers to plot
4376    """
4377    import numpy.ma as ma
4378    fname = 'draw_river_desc'
4379
4380    if values == 'h':
4381        print fname + '_____________________________________________________________'
4382        print draw_river_desc.__doc__
4383        quit()
4384
4385    expectargs = '[X/Y/Z/T]|[dimname]|[vardimname]|[value]:[basinvals]:' +           \
4386      '[upstreamvals]:[mapvalues]:[gtit]:[kindfig]:[legloc]:[figuren]'
4387 
4388    drw.check_arguments(fname,values,expectargs,':')
4389
4390    dimvals = values.split(':')[0]
4391    basinvals = values.split(':')[1]
4392    upstreamvals = values.split(':')[2]
4393    mapvals = values.split(':')[3]
4394    gtit = values.split(':')[4]
4395    kindfig = values.split(':')[5]
4396    legloc = int(values.split(':')[6])
4397    figuren = values.split(':')[7]
4398
4399    basincol = basinvals
4400    if basincol.find(',') != 1:
4401        basincolor = basincol.split(',')
4402    else:
4403        basincolor = [basincol]
4404
4405    upstreamcolor = upstreamvals
4406
4407    of = NetCDFFile(ncfile,'r')
4408
4409    dims = {}
4410    for dimv in dimvals.split(','):
4411        dns = dimv.split('|')
4412        dims[dns[0]] = [dns[1], dns[2], dns[3]]
4413
4414    varNs = []
4415    for dn in dims.keys():
4416        if dn == 'X':
4417            varNs.append(dims[dn][1])
4418            dimx = len(of.dimensions[dims[dn][0]])
4419        elif dn == 'Y':
4420            varNs.append(dims[dn][1])
4421            dimy = len(of.dimensions[dims[dn][0]])
4422
4423    if riverns.find(',') != -1:
4424        riverns = riverns.split(',')
4425    else:
4426        riverns = [riverns]
4427
4428    rivers = []
4429    riversubbasins = {}
4430    riversupstream = {}
4431    riversoutflow = {}
4432    for rivern in riverns:
4433        print rivern
4434
4435# subBasins
4436        basinvar = rivern + '_coding'
4437        if not drw.searchInlist(of.variables.keys(), basinvar):
4438            print errormsg
4439            print '  ' + fname + ": file does not have variable '" + basinvar + "' !!"
4440            quit(-1)
4441        rivers.append(rivern)
4442        obasin = of.variables[basinvar]
4443        riversubbasins[rivern] = obasin[:]
4444        if rivern == riverns[0]:
4445            finalmask = obasin[:].mask
4446        else:
4447            finalmask = finalmask * obasin[:].mask
4448
4449# upstream
4450        upstreamvar = rivern + '_upstream'
4451        if not drw.searchInlist(of.variables.keys(), upstreamvar):
4452            print errormsg
4453            print '  ' + fname + ": file does not have variable '" + upstreamvar + "' !!"
4454            quit(-1)
4455        oupstream = of.variables[upstreamvar]
4456        riversupstream[rivern] = oupstream[:]
4457        if rivern == riverns[0]:
4458            uunits = oupstream.getncattr('units')
4459
4460# River metadata
4461        fracvar = rivern + '_frac'
4462        if not drw.searchInlist(of.variables.keys(), fracvar):
4463            print errormsg
4464            print '  ' + fname + ": file does not have variable '" + fracvar + "' !!"
4465            quit(-1)
4466        ofrac = of.variables[fracvar]
4467        riversoutflow[rivern] = [ofrac.getncattr('Longitude_of_outflow_point'),      \
4468          ofrac.getncattr('Latitude_of_outflow_point')]
4469
4470    ivar = 0
4471    for varN in varNs:
4472        varslice = []
4473
4474        ovarN = of.variables[varN]
4475        vard = ovarN.dimensions
4476        for vdn in vard:
4477            found = False
4478            for dd in dims.keys():
4479                if dims[dd][0] == vdn:
4480                    if dims[dd][2].find('@') != -1:
4481                        rvals = dims[dd][2].split('@')
4482                        varslice.append(slice(int(rvals[0]), int(rvals[1])))
4483                    elif dims[dd][2] == '-1':
4484                        varslice.append(slice(0,len(of.dimensions[dims[dd][0]])))
4485                    else:
4486                        varslice.append(int(dims[dd][2]))
4487
4488                    found = True
4489                    break
4490            if not found:
4491                varslice.append(slice(0,len(of.dimensions[dims[dd][0]])))
4492
4493        if varN == dims['X'][1]:
4494            lonvals0 = np.squeeze(ovarN[tuple(varslice)])
4495        elif varN == dims['Y'][1]:
4496            latvals0 = np.squeeze(ovarN[tuple(varslice)])
4497
4498        ivar = ivar + 1
4499
4500    if len(lonvals0.shape) == 1:
4501        lonvals, latvals = np.meshgrid(lonvals0, latvals0)
4502    else:
4503        lonvals = lonvals0
4504        latvals = latvals0
4505
4506# Masking only the lon,lat with rivers
4507    malonvals = ma.masked_array(lonvals, mask=finalmask)
4508    malatvals = ma.masked_array(latvals, mask=finalmask)
4509
4510    if mapvals == 'None':
4511        mapvalues = None
4512    else:
4513        mapvalues = mapvals
4514
4515    drw.plot_river_desc(malonvals, malatvals, rivers, riversubbasins, riversupstream, riversoutflow,  \
4516      basincolor, upstreamcolor, uunits, mapvalues, gtit, kindfig, legloc, figuren)
4517
4518    of.close()
4519
4520def draw_vertical_levels(ncfile, values, varn):
4521    """ plotting vertical levels distribution
4522    draw_vertical_levels(ncfile, values, varn)
4523      ncfile= file to use
4524      values= [zlogs]:[plogs]:[title]:[graphic_kind]:[legvals]
4525        zlogs= zlog,dzlog
4526        zlog: to use logarithmic scale on the height axis ('true/false')
4527        dzlog: to use logarithmic scale on the difference of height between levels axis ('true/false')
4528        plogs= plog,dplog
4529        plog: to use logarithmic scale on the height axis ('true/false')
4530        dplog: to use logarithmic scale on the difference of height between levels axis ('true/false')
4531        title: title of the graph ('!' for spaces)
4532        graphic_kind: kind of figure (jpg, pdf, png)
4533        [legvals]=[locleg]|[fontsize]
4534          [locleg]: location of the legend (0, autmoatic)
4535            1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
4536            5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
4537            9: 'upper center', 10: 'center'
4538          [fontsize]: font size for the legend (auto for 12)
4539      varn= [varnheight],[varnpres]
4540        varnheight: name of the variable with the height of the vertical levels
4541          'WRFz': for WRF z-levels (computed as (PH + PHB)/g, from a PHB(0,i,j) = 0)
4542        varnpres: name of the variable with the pressure of the vertical levels ('None', for no pressure plot)
4543          'WRFp': for WRF p-levels (computed as P + PB, from a PHB(0,i,j) = 0)
4544    """
4545    fname = 'draw_vertical_levels'
4546
4547    if values == 'h':
4548        print fname + '_____________________________________________________________'
4549        print draw_vertical_levels.__doc__
4550        quit()
4551
4552    expectargs = '[zlogs]:[plogs]:[title]:[graphic_kind]:[legloc]'
4553 
4554    drw.check_arguments(fname,values,expectargs,':')
4555
4556    zlog = values.split(':')[0].split(',')[0]
4557    dzlog = values.split(':')[0].split(',')[1]
4558    plog = values.split(':')[1].split(',')[0]
4559    dplog = values.split(':')[1].split(',')[1]
4560    title = values.split(':')[2].replace('!',' ')
4561    kindfig = values.split(':')[3]
4562    legvals = values.split(':')[4]
4563
4564    if varn.find(',') == -1:
4565        varnheight = varn
4566        varnpres = None
4567        pvals = None
4568        print warnmsg
4569        print '  ' + fname + ': assuming no pressure variable!!'
4570    else:
4571        varnheight = varn.split(',')[0]
4572        varnpres = varn.split(',')[1]
4573        if varnpres == 'None': 
4574            varnpres = None
4575            pvals = None
4576
4577    if not os.path.isfile(ncfile):
4578        print errormsg
4579        print '  ' + fname + ': file "' + ncfile + '" does not exist !!'
4580        quit(-1)   
4581
4582    objf = NetCDFFile(ncfile, 'r')
4583
4584    if varnheight == 'WRFz': 
4585        if not gen.searchInlist(objf.variables,'PH'):
4586            print errormsg
4587            print '  ' + fname + ": WRF file '" + ncfile + "' does not have " +      \
4588              "variable 'PH' !!"
4589            quit(-1)
4590        if not gen.searchInlist(objf.variables,'PHB'):
4591            print errormsg
4592            print '  ' + fname + ": WRF file '" + ncfile + "' does not have " +      \
4593              "variable 'PHB' !!"
4594            quit(-1)
4595
4596        objph = objf.variables['PH']
4597        objphb = objf.variables['PHB']
4598        geop = objph[:] + objphb[:]
4599
4600        ijz0 = gen.index_mat(geop[0,], 0.)
4601        zvals = geop[0, :, ijz0[0], ijz0[1]] / 9.8
4602    else:
4603        if not gen.searchInlist(objf.variables, varnheight):
4604            print errormsg
4605            print '  ' + fname + ": file '" + ncfile + "' does not have height " +   \
4606              " variable '" + varnheight + "' !!"
4607            quit(-1)
4608        objvar = objf.variables[varn]
4609        if len(objvar.shape) == 4:
4610            print warnmsg
4611            print '  ' + fname + ": assuming that height variable '" + varnheight +  \
4612              "' with shape: dt,dz,dy,dx. Tacking first time-step"
4613
4614            ijz0 = gen.index_mat(objvar[0,0,], 0.)
4615            zvals = objvar[0, :, ijz0[0], ijz0[1]]
4616        elif len(objvar.shape) == 3:
4617            print warnmsg
4618            print '  ' + fname + ": assuming that height variable '" + varnheight +  \
4619              "' with shape: dz,dy,dx"
4620
4621            ijz0 = gen.index_mat(objvar[0,], 0.)
4622            zvals = objvar[:, ijz0[0], ijz0[1]]
4623       
4624        elif len(objvar.shape) == 2:
4625            print warnmsg
4626            print '  ' + fname + ": assuming that height variable '" + varnheight +  \
4627              "' with shape: dz,dyx"
4628
4629            ijz0 = gen.index_mat(objvar[0,], 0.)
4630            zvals = objvar[:, ijz0[0]]
4631        else:
4632            zvals = objvar[:]
4633
4634# Pressure
4635    if varnpres is not None:
4636        if varnpres == 'WRFp': 
4637            if not gen.searchInlist(objf.variables,'P'):
4638                print errormsg
4639                print '  ' + fname + ": WRF file '" + ncfile + "' does not have " +      \
4640                  "variable 'P' !!"
4641                quit(-1)
4642            if not gen.searchInlist(objf.variables,'PB'):
4643                print errormsg
4644                print '  ' + fname + ": WRF file '" + ncfile + "' does not have " +      \
4645                  "variable 'PB' !!"
4646                quit(-1)
4647
4648            objph = objf.variables['P']
4649            objphb = objf.variables['PB']
4650            pres = objph[:] + objphb[:]
4651
4652            pvals = pres[0, :, ijz0[0], ijz0[1]]
4653        else:
4654            if not gen.searchInlist(objf.variables, varnpres):
4655                print errormsg
4656                print '  ' + fname + ": file '" + ncfile + "' does not have pressure " + \
4657                  " variable '" + varnpres + "' !!"
4658                quit(-1)
4659            objvar = objf.variables[varnpres]
4660            if len(objvar.shape) == 4:
4661                print warnmsg
4662                print '  ' + fname + ": assuming that pressure variable '" + varnpres +  \
4663                  "' with shape: dt,dz,dy,dx. Tacking first time-step"
4664   
4665                pvals = objvar[0, :, ijz0[0], ijz0[1]]
4666            elif len(objvar.shape) == 3:
4667                print warnmsg
4668                print '  ' + fname + ": assuming that pressure variable '" + varnpres +  \
4669                  "' with shape: dz,dy,dx"
4670   
4671                pvals = objvar[:, ijz0[0], ijz0[1]]
4672           
4673            elif len(objvar.shape) == 2:
4674                print warnmsg
4675                print '  ' + fname + ": assuming that pressure variable '" + varnpres +  \
4676                  "' with shape: dz,dyx"
4677   
4678                pvals = objvar[:, ijz0[0]]
4679            else:
4680                pvals = objvar[:]
4681
4682# Logarithmic axes
4683    if zlog == 'true':
4684        zlogv = True
4685    elif zlog == 'false':
4686        zlogv = False
4687    else:
4688        print errormsg
4689        print '  ' + fname + ": wrong value for zlog: '" + zlog + "' !!"
4690        print "    must be either: 'true' or 'false'"
4691        quit(-1)
4692
4693    if dzlog == 'true':
4694        dzlogv = True
4695    elif dzlog == 'false':
4696        dzlogv = False
4697    else:
4698        print errormsg
4699        print '  ' + fname + ": wrong value for dzlog: '" + dzlog + "' !!"
4700        print "    must be either: 'true' or 'false'"
4701        quit(-1)
4702
4703    if pvals is not None:
4704        if plog == 'true':
4705            plogv = True
4706        elif plog == 'false':
4707            plogv = False
4708        else:
4709            print errormsg
4710            print '  ' + fname + ": wrong value for plog: '" + plog + "' !!"
4711            print "    must be either: 'true' or 'false'"
4712            quit(-1)
4713        if dplog == 'true':
4714            dplogv = True
4715        elif dplog == 'false':
4716            dplogv = False
4717        else:
4718            print errormsg
4719            print '  ' + fname + ": wrong value for dplog: '" + dplog + "' !!"
4720            print "    must be either: 'true' or 'false'"
4721            quit(-1)
4722
4723    # Legend values
4724    legloc, legsize = drw.legend_values(legvals,'|')
4725
4726    drw.plot_vertical_lev(zvals, pvals, zlogv, dzlogv, plogv, dplogv, title, kindfig,\
4727      legloc, legsize)
4728
4729    objf.close()
4730
4731    return
4732
4733def draw_subbasin(ncfile, values):
4734    """ Function to plot subbasin from 'routnig.nc' ORCDHIEE
4735      ncfile= file to use produced with nc_var.py#subbasin function
4736      values= [subasiname]:[rangecolors]:[mapv]:[basinlinewidth]:[drawsubid]:[gtit]:[figkind]:[legvals]:[figurename]
4737        [subasiname]= name of the subbasin ('!' for spaces)
4738        [rcolor]= '@', list of 'r|g|b' 1-based colors (as much as first level sub-flow). 'None' for automatic
4739        [mapv]= map characteristics: [proj],[res]
4740          see full documentation: http://matplotlib.org/basemap/
4741          [proj]: projection
4742            * 'cyl', cilindric
4743            * 'lcc', lambert conformal
4744          [res]: resolution:
4745            * 'c', crude
4746            * 'l', low
4747            * 'i', intermediate
4748            * 'h', high
4749            * 'f', full
4750        [basinlinewidth]= with of the line to draw the basin
4751        [drawsubid]= wehther sub-flow ids should be plot or not
4752        [graphtit]= title of the graph ('|', for spaces)
4753        [legvals]=[locleg]|[fontsize]:
4754          [locleg]: location of the legend (0, autmoatic)
4755            1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
4756            5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
4757            9: 'upper center', 10: 'center'
4758          [fontsize]: font size for the legend (auto for 12)
4759        [figname]= name of the figure
4760    """
4761    fname = 'draw_subbasin'
4762
4763    if values == 'h':
4764        print fname + '_____________________________________________________________'
4765        print draw_subbasin.__doc__
4766        quit()
4767
4768    expectargs = '[subasiname]:[rangecolors]:[mapv]:[basinlinewidth]:[drawsubid]:' + \
4769      '[gtit]:[figkind]:[legloc]:[figurename]'
4770 
4771    drw.check_arguments(fname,values,expectargs,':')
4772
4773    subbasiname = values.split(':')[0].replace('!',' ')
4774    rangecolors = values.split(':')[1]
4775    mapv = values.split(':')[2]
4776    basinlinewidth = np.float(values.split(':')[3])
4777    drawsubid = gen.Str_Bool(values.split(':')[4])
4778    gtit = values.split(':')[5].replace('!',' ')
4779    figkind = values.split(':')[6]
4780    legloc = int(values.split(':')[7])
4781    figurename = values.split(':')[8]
4782
4783    if not os.path.isfile(ncfile):
4784        print errormsg
4785        print '  ' + fname + ': file "' + ncfile + '" does not exist !!'
4786        quit(-1)   
4787
4788    objf = NetCDFFile(ncfile, 'r')
4789
4790    searchvars = ['lon', 'lat', 'lonsubflow', 'latsubflow', 'outsubflow']
4791    for searchvar in searchvars: 
4792        if not gen.searchInlist(objf.variables,searchvar):
4793            print errormsg
4794            print '  ' + fname + ": WRF file '" + ncfile + "' does not have " +      \
4795              "variable '" + searchvar + "' !!"
4796            quit(-1)
4797   
4798# lon,lat
4799    olon = objf.variables['lon']
4800    olat = objf.variables['lat']
4801    lon = olon[:]
4802    lat = olat[:]
4803
4804# sub-flow names
4805    osubnames = objf.variables['subflow']
4806    subnames = drw.get_str_nc(osubnames, osubnames.shape[1])
4807
4808# sub-flow lat, lon
4809    latlonsub = {}
4810    outflowsub = {}
4811    osublon = objf.variables['lonsubflow']
4812    osublat = objf.variables['latsubflow']
4813    oNsubflow = objf.variables['Nsubflow']
4814    ooutsubflow = objf.variables['outsubflow']
4815    Nsubflow = oNsubflow[:]
4816    isub = 0
4817    for Ssub in subnames:
4818        sublatlon = []
4819        suboutflow = []
4820        for igrid in range(Nsubflow[isub]):
4821            sublatlon.append([osublat[isub,igrid], osublon[isub,igrid]])
4822            suboutflow.append(ooutsubflow[isub,igrid])
4823        latlonsub[Ssub] = sublatlon
4824        outflowsub[Ssub] = suboutflow
4825        isub = isub + 1
4826
4827# colors
4828    if rangecolors == 'None':
4829        rangecols = None
4830    else:
4831        cols = rangecolors.split('@')
4832        Ncols = len(cols)
4833        rangecols = []
4834        for icol in range(Ncols):
4835            cval = cols[icol].split('|')
4836            rangecols.append([np.float(cval[0]),np.float(cval[1]),np.float(cval[2])])
4837
4838    drw.plot_subbasin(subbasiname, lon, lat, subnames, latlonsub, outflowsub,        \
4839      rangecols, mapv, basinlinewidth, drawsubid, gtit, figkind, legloc, figurename)
4840
4841    objf.close()
4842
4843    return
4844
4845def draw_2lines(ncfiles, values, varnames):
4846    """ Fucntion to plot two lines in different axes (x/x2 or y/y2)
4847      values= [commonvardim]:[varangeA]:[varangeB]:[varangeaxis]:[axisvals]:[figvarns]:[colors]:
4848       [widths]:[styles]:[sizemarks]:[marks]:[graphtitle]:[labelaxis]:[legvals]:[figname]:[figkind]:[close]
4849        [commonvardim]: name of the common variable-dimension
4850        [varangeA]: ',' separated list of range (min,max) for A values ('None', automatic; 'Extrs' from values extremes)
4851        [varangeB]: ',' separated list of range (min,max) for B values ('None', automatic; 'Extrs' from values extremes)
4852        [varangeaxis]: ',' separated list of range (min,max) for common axis values ('None', automatic; 'Extrs' from
4853          values extremes)
4854        [axisvals]: which is the axis to plot the values ('x' or 'y')
4855        [figvarns]: ',' separated list of names of the variables in the  plot
4856        [colors]: ',' list with color names of the lines for the variables ('None', automatic)
4857        [widths]: ',' list with widths of the lines for the variables ('None', automatic)
4858        [styles]: ',' list with the styles of the lines ('None', automatic)
4859        [sizemarks]: ',' list with the size of the markers of the lines ('None', automatic)
4860        [marks]: ',' list with the markers of the lines ('None', automatic)
4861        [graphtitle]: title of the figure ('!' for spaces)
4862        [labelaxis]: label in the figure of the common axis ('!' for spaces)
4863        [legvals]=[locleg]|[fontsize]:
4864          [locleg]: location of the legend (0, autmoatic)
4865            1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
4866            5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
4867            9: 'upper center', 10: 'center'
4868          [fontsize]: font size for the legend (auto for 12)
4869        [figname]: name of the figure
4870        [figkind]: kind of figure
4871        [close]: Whether figure should be finished or not
4872      ncfiles= ',' separated list of files to use
4873      varnames=  ',' separated list of variables names in the files to plot
4874    """
4875    fname = 'draw_2lines'
4876
4877    if values == 'h':
4878        print fname + '_____________________________________________________________'
4879        print draw_2lines.__doc__
4880        quit()
4881
4882    expectargs = '[commonvardim]:[varangeA]:[varangeB]:' +           \
4883     '[varangeaxis]:[axisvals]:[figvarns]:[colors]:[widths]:[styles]:[sizemarks]:' + \
4884     '[marks]:[graphtitle]:[labelaxis]:[lloc]:[figname]:[figkind]:[close]'
4885 
4886    drw.check_arguments(fname,values,expectargs,':')
4887
4888    commonvardim = values.split(':')[0]
4889    varangeA0 = values.split(':')[1]
4890    varangeB0 = values.split(':')[2]
4891    varangeaxis0 = values.split(':')[3]
4892    axisvals = values.split(':')[4]
4893    figvarns = values.split(':')[5].split(',')
4894    colors = gen.str_list(values.split(':')[6],',')
4895    widths = gen.str_list_k(values.split(':')[7],',','np.float')
4896    styles = gen.str_list(values.split(':')[8],',')
4897    sizemarks = gen.str_list_k(values.split(':')[9],',','np.float')
4898    marks = gen.str_list(values.split(':')[10],',')
4899    graphtitle = values.split(':')[11].replace('!',' ')
4900    labelaxis = values.split(':')[12].replace('!',' ')
4901    legvals = values.split(':')[13]
4902    figname = values.split(':')[14]
4903    figkind = values.split(':')[15]
4904    close = gen.Str_Bool(values.split(':')[16])
4905
4906    files = ncfiles.split(',')
4907    invarns = varnames.split(',')
4908
4909    varunits = []
4910
4911    # Values line A
4912    if not os.path.isfile(files[0]):
4913        print errormsg
4914        print '  ' + fname + ": file '" + files[0] + "' does not exist !!"
4915        quit(-1)
4916
4917    oncA = NetCDFFile(files[0], 'r')
4918
4919    if not gen.searchInlist(oncA.variables.keys(), invarns[0]):
4920        print errormsg
4921        print '  ' + fname + ": A file '" + files[0] + "' does not have variable '" +\
4922          invarns[0] + "' !!"
4923        quit(-1)
4924
4925    objvA = oncA.variables[invarns[0]]
4926    varvalsA = objvA[:]
4927    varangeA = np.zeros((2),dtype=np.float)
4928
4929    if gen.searchInlist(objvA.ncattrs(), 'units'):
4930        varunits.append(drw.units_lunits(objvA.getncattr('units')))
4931    else:
4932        valsA = gen.variables_values(invarns[0])
4933        varunits.append(drw.units_lunits(valsA[5]))
4934    if varangeA0 == 'None':
4935        varangeA = [valsA[2], valsA[3]]
4936    elif varangeA0 == 'Extrs':
4937        varangeA = [np.min(varvalsA), np.max(varvalsA)]
4938    else:
4939        for iv in range(2): varangeA[iv] = np.float(varangeA0.split(',')[iv])
4940
4941    if not gen.searchInlist(oncA.variables.keys(), commonvardim):
4942        print errormsg
4943        print '  ' + fname + ": A file '" + files[0] + "' does not have common " +   \
4944          "dimvar '" + commonvardim + "' !!"
4945        quit(-1)
4946    objvd = oncA.variables[commonvardim]
4947    varvalsaxisA = objvd[:]   
4948
4949    oncA.close()
4950
4951    # Values line B
4952    if not os.path.isfile(files[1]):
4953        print errormsg
4954        print '  ' + fname + ": file '" + files[1] + "' does not exist !!"
4955        quit(-1)
4956
4957    oncB = NetCDFFile(files[1], 'r')
4958
4959    if not gen.searchInlist(oncB.variables.keys(), invarns[1]):
4960        print errormsg
4961        print '  ' + fname + ": B file '" + files[1] + "' does not have variable '" +\
4962          invarns[1] + "' !!"
4963        quit(-1)
4964
4965    objvB = oncB.variables[invarns[1]]
4966    varvalsB = objvB[:]
4967    varangeB = np.zeros((2),dtype=np.float)
4968
4969    if gen.searchInlist(objvB.ncattrs(), 'units'):
4970        varunits.append(drw.units_lunits(objvB.getncattr('units')))
4971    else:
4972        valsB = gen.variables_values(invarns[1])
4973        varunits.append(drw.units_lunits(valsB[5]))
4974    if varangeB0 == 'None':
4975        varangeB = [valsB[2], valsB[3]]
4976    elif varangeB0 == 'Extrs':
4977        varangeA = [np.min(varvalsA), np.max(varvalsA)]
4978    else:
4979        for iv in range(2): varangeB[iv] = np.float(varangeB0.split(',')[iv])
4980
4981    # Common vardim
4982    if not gen.searchInlist(oncB.variables.keys(), commonvardim):
4983        print errormsg
4984        print '  ' + fname + ": B file '" + files[1] + "' does not have common " +   \
4985          "dimvar '" + commonvardim + "' !!"
4986        quit(-1)
4987    objvd = oncB.variables[commonvardim]
4988    varvalsaxisB = objvd[:]
4989
4990    # Range of the axis
4991    varangeaxis = np.zeros((2),dtype=np.float)
4992
4993    valsVD = gen.variables_values(commonvardim)
4994    if gen.searchInlist(objvd.ncattrs(), 'units'):
4995        dimvarunits = drw.units_lunits(objvd.getncattr('units'))
4996    else:
4997        dimvarunits = drw.units_lunits(valsVD[5])
4998    if varangeaxis0 == 'None':
4999        varangeaxis = [valsVD[2], valsVD[3]]
5000    elif varangeaxis0 == 'Extrs':
5001        varangeaxis[0] = np.min([np.min(varvalsaxisA), np.min(varvalsaxisB)])
5002        varangeaxis[1] = np.max([np.max(varvalsaxisA), np.max(varvalsaxisB)])
5003    else:
5004        for iv in range(2): varangeaxis[iv] = np.float(varangeaxis0.split(',')[iv])
5005   
5006    oncB.close()
5007
5008    labelaxis = valsVD[0] + ' (' + dimvarunits + ')'
5009
5010    # Lines characteristics
5011    colvalues, linekinds, pointkinds, lwidths, psizes = drw.ColorsLinesPointsStyles( \
5012      2, colors, styles, marks, widths, sizemarks, 'None')
5013
5014    # legend
5015    lloc, lsize = drw.legend_values(legvals,'|')
5016
5017    drw.plot_2lines(varvalsA, varvalsB, varvalsaxisA, varvalsaxisB, varangeA,        \
5018      varangeB, varangeaxis, axisvals, figvarns, varunits, colvalues, lwidths,       \
5019      linekinds, psizes, pointkinds, graphtitle, labelaxis, lloc, lsize, figname,    \
5020      figkind, close)
5021
5022def draw_2lines_time(ncfiles, values, varnames):
5023    """ Function to plot two time-lines in different axes (x/x2 or y/y2)
5024      values= [timevardim]:[varangeA]:[varangeB]:[timeaxisfmt]:[timeaxis]:[figvarns]:[colors]:
5025       [widths]:[styles]:[sizemarks]:[marks]:[graphtitle]:[labelaxis]:[legvals]:[figname]:[figkind]:[close]
5026        [timevardim]: name of the common variable-dimension time
5027        [varangeA]: ',' separated list of range (min,max) for A values ('None', automatic; 'Extrs' from values extremes)
5028        [varangeB]: ',' separated list of range (min,max) for B values ('None', automatic; 'Extrs' from values extremes)
5029        [timeaxisfmt]=[tkind];[tfmt]: format of the ticks for the time axis:
5030           [kind]: kind of time to appear in the graph
5031             'Nval': according to a given number of values as 'Nval',[Nval]
5032             'exct': according to an exact time unit as 'exct',[tunit];
5033               tunit= [Nunits],[tu]; [tu]= 'c': centuries, 'y': year, 'm': month,
5034                'w': week, 'd': day, 'h': hour, 'i': minute, 's': second,
5035                'l': milisecond
5036           [tfmt]; desired format
5037        [timeaxis]: which is the time axis in the plot ('x' or 'y')
5038        [figvarns]: ',' separated list of names of the variables in the  plot
5039        [colors]: ',' list with color names of the lines for the variables ('None', automatic)
5040        [widths]: ',' list with widths of the lines for the variables ('None', automatic)
5041        [styles]: ',' list with the styles of the lines ('None', automatic)
5042        [sizemarks]: ',' list with the size of the markers of the lines ('None', automatic)
5043        [marks]: ',' list with the markers of the lines ('None', automatic)
5044        [graphtitle]: title of the figure ('!' for spaces)
5045        [labelaxis]: label in the figure of the common axis ('!' for spaces)
5046        [legvals]=[locleg]|[fontsize]:
5047          [locleg]: location of the legend (0, autmoatic)
5048            1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
5049            5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
5050            9: 'upper center', 10: 'center'
5051          [fontsize]: font size for the legend (auto for 12)
5052        [figname]: name of the figure
5053        [figkind]: kind of figure
5054        [close]: Whether figure should be finished or not
5055      ncfiles= ',' separated list of files to use
5056      varnames=  ',' separated list of variables names in the files to plot
5057    """
5058    fname = 'draw_2lines_time'
5059
5060    if values == 'h':
5061        print fname + '_____________________________________________________________'
5062        print draw_2lines_time.__doc__
5063        quit()
5064
5065    expectargs = '[timevardim]:[varangeA]:[varangeB]:[timeaxisfmt]:[timeaxis]:' +    \
5066     '[figvarns]:[colors]:[widths]:[styles]:[sizemarks]:[marks]:[graphtitle]:' +     \
5067     '[labelaxis]:[lloc]:[figname]:[figkind]:[close]'
5068 
5069    drw.check_arguments(fname,values,expectargs,':')
5070
5071    timevardim = values.split(':')[0]
5072    varangeA0 = values.split(':')[1]
5073    varangeB0 = values.split(':')[2]
5074    timeaxisfmt = values.split(':')[3]
5075    timeaxis = values.split(':')[4]
5076    figvarns = values.split(':')[5].split(',')
5077    colors = gen.str_list(values.split(':')[6],',')
5078    widths = gen.str_list_k(values.split(':')[7],',','np.float')
5079    styles = gen.str_list(values.split(':')[8],',')
5080    sizemarks = gen.str_list_k(values.split(':')[9],',','np.float')
5081    marks = gen.str_list(values.split(':')[10],',')
5082    graphtitle = values.split(':')[11].replace('!',' ')
5083    labelaxis = values.split(':')[12].replace('!',' ')
5084    legvals = values.split(':')[13]
5085    figname = values.split(':')[14]
5086    figkind = values.split(':')[15]
5087    close = gen.Str_Bool(values.split(':')[16])
5088
5089    files = ncfiles.split(',')
5090    invarns = varnames.split(',')
5091
5092    varunits = []
5093
5094    # Values line A
5095    if not os.path.isfile(files[0]):
5096        print errormsg
5097        print '  ' + fname + ": file '" + files[0] + "' does not exist !!"
5098        quit(-1)
5099
5100    oncA = NetCDFFile(files[0], 'r')
5101
5102    if not gen.searchInlist(oncA.variables.keys(), invarns[0]):
5103        print errormsg
5104        print '  ' + fname + ": A file '" + files[0] + "' does not have variable '" +\
5105          invarns[0] + "' !!"
5106        quit(-1)
5107    if not gen.searchInlist(oncA.variables.keys(), timevardim):
5108        print errormsg
5109        print '  ' + fname + ": A file '" + files[0] + "' does not have time " +     \
5110          "variable '" + timevardim + "' !!"
5111        quit(-1)
5112
5113    objvA = oncA.variables[invarns[0]]
5114    varvalsA = objvA[:]
5115    varangeA = np.zeros((2),dtype=np.float)
5116    objtA = oncA.variables[timevardim]
5117    timevalsA = objtA[:]
5118    trangeA = [np.min(timevalsA), np.max(timevalsA)]
5119    tunitsA = objtA.getncattr('units')
5120
5121    if len(varvalsA.shape) != 1:
5122        print errormsg
5123        print '  ' + fname + ": variable '" + invarns[0] + "' has wrong shape:",     \
5124          varvalsA.shape, 'it must be 1D !!'
5125        quit(-1)
5126
5127    if gen.searchInlist(objvA.ncattrs(), 'units'):
5128        varunits.append(drw.units_lunits(objvA.getncattr('units')))
5129    else:
5130        valsA = gen.variables_values(invarns[0])
5131        varunits.append(drw.units_lunits(valsA[5]))
5132    if varangeA0 == 'None':
5133        varangeA = [valsA[2], valsA[3]]
5134    elif varangeA0 == 'Extrs':
5135        varangeA = [np.min(varvalsA), np.max(varvalsA)]
5136    else:
5137        for iv in range(2): varangeA[iv] = np.float(varangeA0.split(',')[iv])
5138
5139    oncA.close()
5140
5141    # Values line B
5142    if not os.path.isfile(files[1]):
5143        print errormsg
5144        print '  ' + fname + ": file '" + files[1] + "' does not exist !!"
5145        quit(-1)
5146
5147    oncB = NetCDFFile(files[1], 'r')
5148
5149    if not gen.searchInlist(oncB.variables.keys(), invarns[1]):
5150        print errormsg
5151        print '  ' + fname + ": B file '" + files[1] + "' does not have variable '" +\
5152          invarns[1] + "' !!"
5153        quit(-1)
5154    if not gen.searchInlist(oncB.variables.keys(), timevardim):
5155        print errormsg
5156        print '  ' + fname + ": B file '" + files[1] + "' does not have time " +     \
5157          "variable '" + timevardim + "' !!"
5158        quit(-1)
5159
5160    objvB = oncB.variables[invarns[1]]
5161    varvalsB = objvB[:]
5162    varangeB = np.zeros((2),dtype=np.float)
5163    objtB = oncB.variables[timevardim]
5164    timevalsB = objtB[:]
5165    tunitsB = objtB.getncattr('units')
5166
5167    if gen.searchInlist(objvB.ncattrs(), 'units'):
5168        varunits.append(drw.units_lunits(objvB.getncattr('units')))
5169    else:
5170        valsB = gen.variables_values(invarns[1])
5171        varunits.append(drw.units_lunits(valsB[5]))
5172    if varangeB0 == 'None':
5173        varangeB = [valsB[2], valsB[3]]
5174    elif varangeB0 == 'Extrs':
5175        varangeA = [np.min(varvalsA), np.max(varvalsA)]
5176    else:
5177        for iv in range(2): varangeB[iv] = np.float(varangeB0.split(',')[iv])
5178   
5179    oncB.close()
5180
5181    # Time axis taking time units in line A as reference
5182    varvalsaxisB = gen.coincident_CFtimes(timevalsB, tunitsA, tunitsB)
5183    trangeB = [np.min(varvalsaxisB), np.max(varvalsaxisB)]
5184
5185    varangeaxis = [np.min([trangeA[0],trangeB[0]]), np.max([trangeA[1],trangeB[1]])]
5186
5187    timevals = np.arange(varangeaxis[0],varangeaxis[1])
5188    tkind = timeaxisfmt.split(';')[0]
5189    tformat = timeaxisfmt.split(';')[1]
5190    tpos, tlabels = drw.CFtimes_plot(timevals, tunitsA, tkind, tformat)
5191
5192    # Lines characteristics
5193    colvalues, linekinds, pointkinds, lwidths, psizes = drw.ColorsLinesPointsStyles( \
5194      2, colors, styles, marks, widths, sizemarks, 'None')
5195
5196    # legend
5197    lloc, lsize = drw.legend_values(legvals,'|')
5198
5199    drw.plot_2lines_time(varvalsA, varvalsB, timevalsA, varvalsaxisB, varangeA,      \
5200      varangeB, tpos, tlabels, timeaxis, figvarns, varunits, colvalues, lwidths,     \
5201      linekinds, psizes, pointkinds, graphtitle, labelaxis, lloc, lsize, figname,    \
5202      figkind, close)
5203
5204def draw_WindRose(ncfile, values, varnames):
5205    """ Function to plot a wind rose (from where the dinw blows)
5206      values=[dimvariables][kindRose]:[imgtit]:[imgkind]:[kindlabelsangle]:[freqfileout]:[fname]:[close]
5207        [dimvariables]: ';' list of [dimn]|[dvalue] dimension and slice along dimension to retrieve the winds
5208          [dimn]: name of the dimension
5209          [dvalue]: value for the slice in the given dimension
5210            * [integer]: which value of the dimension
5211            * -1: all along the dimension
5212            * -9: last value of the dimension
5213            * [beg],[end],[freq] slice from [beg] to [end] every [freq]
5214            * NOTE, no dim name all the dimension size
5215          No value takes all the range of the dimension
5216        [kindRose]: [kind];[value1];[...[valueN]] Kind of rose to plot and values of the kind
5217          'fill': filling the area since the center of the rose
5218          'anglespeedfreq': grid of frequencies of each angle and speed following a given discretization
5219            values: ;[Nang];[Nspeed];[maxspeed];[cbar];[maxfreq]
5220          'linepoint': consecutive (time, height, level, ...) line-point angle and speed values. Three different species
5221            'multicol': line-marker color changing according to a third variable [extravarn]
5222               values: [extravarn];[line];[marker];[colbar];[Nang]
5223            'multicoltime': line-marker color changing according to a temporal variable [extravarn]
5224               values: [extravarn];[line];[marker];[colbar];[Nang];[timekind];[timefmt];[timelabel]
5225            'singlecol': same color for the line-marker
5226               values: [line];[marker];[col];[Nang]
5227          'scatter': a marker for each wind at different values (time, height, level, ...). Three different species
5228            'multicol':marker color changing according to a third variable [extravarn]
5229               values: [extravarn];[marker];[colbar];[Nang]
5230            'multicoltime': marker color changing according to a temporal variable [extravarn]
5231               values: [extravarn];[line];[marker];[colbar];[Nang];[timekind];[timefmt];[timelabel]
5232            'singlecol': same color for all the markers
5233              values: [marker];[col];[Nang]
5234           meaning (where apply):
5235             [extravarn]: name of the extra variable
5236             [line]: type of the line to draw
5237             [marker]: type of marker to use
5238             [colbar]: name of the colorbar ('auto' for 'spectral_r')
5239             [Nang]: number of angles to divide the rose ('auto' for 8)
5240             [Nspeed]: number of speeds to divide the wind speed distribution ('auto' for 8)
5241             [maxspeed]: maximum wind speed used to compute the frequency of distributions ('auto' for 40.)
5242             [timekind]; time computation of ticks
5243               'Nval': according to a given number of values as 'Nval',[Nval]
5244               'exct': according to an exact time unit as 'exct',[tunit];
5245                 tunit= [Nunits],[tu]; [tu]= 'c': centuries, 'y': year, 'm': month,
5246                  'w': week, 'd': day, 'h': hour, 'i': minute, 's': second,
5247                  'l': milisecond
5248             [timefmt]; desired format of time labels (C-like)
5249             [timelabel]; label of time colorbar at the graph ('!' for spaces)
5250        imgtit: title of the image ('!' for spaces)
5251        imgkind: kind of output of the image
5252        kindlabelsangle: kind of labels for the angles of the wind Rose
5253          'cardianals': Following combinations of 'N', 'E', 'S', 'W' according to Nang
5254        freqfileout: whether the file with the frequencies of wind angle and speeds should be created (only working
5255          for 'anglespeedfreq')
5256        fname: name of the figure
5257        close: whether figure should be closed or not
5258      ncfile= netCDF file with the winds and extra variable (if required)
5259      varnames= [windun],[windvn] variables' name
5260    """
5261    fname = 'draw_WindRose'
5262
5263    if values == 'h':
5264        print fname + '_____________________________________________________________'
5265        print draw_WindRose.__doc__
5266        quit()
5267
5268    expectargs = '[dimvariables]:[kindRose]:[imgtit]:[imgkind]:[kindlabelsangle]:' + \
5269      '[freqfileout]:[fname]:[close]'
5270    drw.check_arguments(fname,values,expectargs,':')
5271
5272    dimvariables = values.split(':')[0]
5273    KindRose = values.split(':')[1]
5274    imgtit = values.split(':')[2].replace('!',' ')
5275    imgkind = values.split(':')[3]
5276    kindlabelsangle = values.split(':')[4]
5277    freqfileout = gen.Str_Bool(values.split(':')[5])
5278    fname = values.split(':')[6]
5279    close = gen.Str_Bool(values.split(':')[7])
5280   
5281    uvarn = varnames.split(',')[0]
5282    vvarn = varnames.split(',')[1]
5283
5284    windrosekinds = ['fill', 'linepoint', 'scatter']
5285
5286    if KindRose.find(';') == -1:
5287        print errormsg
5288        print '  ' + fname + ": all types '" + KindRose + "' require extra values !!"
5289        print "    'anglespeedfreq';[Nang];[Nspeed];[maxspeed];[freqcbar];[maxfreq]"
5290        print "    'linepoint';'singlecol';[line];[marker];[col];[Nang]"
5291        print "    'linepoint';'multiecoltime';[extravar];[line];[marker];[colbar];"+\
5292          "[Nang];[timekind];[timefmt];[timelabel]"
5293        print "    'linepoint';'multiecol';[extravar];[line];[marker];[colbar];[Nang]"
5294        print "    'scatter';'multiecol';[extravar];[marker];[colbar]"
5295        print "    'scatter';'multiecoltime';[extravar];[marker];[colbar];[Nang];" + \
5296          "[timekind];[timefmt];[timelabel]"
5297        print "    'scatter';'singlecol';[marker];[col];[Nang]"
5298        print "  values provided: '" + KindRose + "'" 
5299        quit(-1)
5300
5301    lpvals = KindRose.split(';')
5302    lkind = lpvals[1]
5303
5304    extravarn = None
5305
5306    if lpvals[0] == 'anglespeedfreq':
5307        if len(lpvals) != 6:
5308            print errormsg
5309            print '  ' + fname + ": 'anglespeedfreq' requires 6 values !!"
5310            print "    'anglespeedfreq';[Nang];[Nspeed];[maxspeed];[freqcbar];[maxfreq]"
5311            print '    provided:', lpvals
5312            quit(-1)     
5313    elif lpvals[0] == 'linepoint':
5314        if lkind == 'multicol':
5315            if len(lpvals) != 7:
5316                print errormsg
5317                print '  ' + fname + ": line-point kind '" + lkind + "' requires " + \
5318                  "6 values !!"
5319                print "    'multiecol';[extravarn];[line];[marker];[colbar];[Nang]"
5320                print '    provided:', lpvals
5321                quit(-1)     
5322            extravarn = lpvals[2]
5323        elif lkind == 'multicoltime':
5324            if len(lpvals) != 10:
5325                print errormsg
5326                print '  '+fname + ": scatter kind '"+lkind+ "' requires 9 values !!"
5327                print "    'multicol';[extravarn];[line];[marker];[colbar];[Nang];"+ \
5328                  "[timekind];[timefmt];[timelabel]"
5329                print '    provided:', lpvals
5330                quit(-1)     
5331            extravarn = lpvals[2]
5332            timekind = lpvals[6]
5333            timefmt = lpvals[7]
5334        elif lkind == 'singlecol':
5335            if len(lpvals) != 6:
5336                print errormsg
5337                print '  '+fname+": line-point kind '"+lkind+ "' requires 5 values !!"
5338                print "    'singlecol';[line];[marker];[col];[Nang]"
5339                print '    provided:', lpvals
5340                quit(-1)     
5341        else:
5342            print errormsg
5343            print '  ' + fname + ": line-point kind '" + lkind + "' not ready !!"
5344            print '    ready ones: multicol, multicoltime, singlecol '
5345            quit(-1)
5346
5347    elif lpvals[0] == 'scatter':
5348        if lkind == 'multicol':
5349            if len(lpvals) != 6:
5350                print errormsg
5351                print '  '+fname+": scatter kind '"+lkind+"' requires 5 values !!"
5352                print "    'multicol';[extravarn];[marker];[colbar];[Nang]"
5353                print '    provided:', lpvals
5354                quit(-1)     
5355            extravarn = lpvals[2]
5356        elif lkind == 'multicoltime':
5357            if len(lpvals) != 9:
5358                print errormsg
5359                print '  ' + fname + ": scatter kind '"+lkind+"' requires 8 values !!"
5360                print "    'multicol';[extravarn];[marker];[colbar];[Nang];" +       \
5361                  "[timekind];[timefmt];[timelabel]"
5362                print '    provided:', lpvals
5363                quit(-1)     
5364            extravarn = lpvals[2]
5365            timekind = lpvals[5]
5366            timefmt = lpvals[6]
5367        elif lkind == 'singlecol':
5368            if len(lpvals) != 5:
5369                print errormsg
5370                print '  '+fname + ": scatter kind '"+lkind+ "' requires 4 values !!"
5371                print "    'singlecol';[marker];[col];[Nang]"
5372                print '    provided:', lpvals
5373                quit(-1)     
5374        else:
5375            print errormsg
5376            print '  ' + fname + ": scatter kind '" + lkind + "' not ready !!"
5377            print '    ready ones: multicol, multicoltime, singlecol '
5378            quit(-1)
5379
5380    else:
5381        print gen.errormsg
5382        print '  ' +  fname + ": kind of WindRose '" + rosekind + "' not ready !!"
5383        print '    available ones:', windrosekinds
5384        quit(-1)
5385
5386    onc = NetCDFFile(ncfile,'r')
5387    oncvars = onc.variables.keys()
5388
5389    if not gen.searchInlist(oncvars,uvarn):
5390        print errormsg
5391        print '  ' + fname + ": file '" + ncfile + "' does not have variable " +     \
5392          "u_wind '" + uvarn + "' !!"
5393        print '    available variables:', oncvars
5394        quit(-1)
5395    if not gen.searchInlist(oncvars,vvarn):
5396        print errormsg
5397        print '  ' + fname + ": file '" + ncfile + "' does not have variable " +     \
5398          "v_wind '" + vvarn + "' !!"
5399        print '    available variables:', oncvars
5400        quit(-1)
5401
5402    if extravarn is not None:
5403        if not gen.searchInlist(oncvars,extravarn):
5404            print errormsg
5405            print '  ' + fname + ": file '" + ncfile + "' does not have extra " +    \
5406              "variable '" + extravarn + "' !!"
5407            print '    available variables:', oncvars
5408            quit(-1)
5409
5410    # Getting the slice
5411    dictslice = {}
5412    for dnv in dimvariables.split(';'):
5413        dimn = dnv.split('|')[0]
5414        dimv = dnv.split('|')[1]
5415        if dimv.find(',') != -1: 
5416            dictslice[dimn] = list(np.array(dimv.split(','), dtype=int))
5417        else:
5418            dictslice[dimn] = int(dimv)
5419
5420    # Getting variables
5421    ou = onc.variables[uvarn]
5422    sliceu, du = ncvar.SliceVarDict(ou, dictslice)
5423    uv = ou[tuple(sliceu)]
5424    ov = onc.variables[vvarn]
5425    slicev, dv = ncvar.SliceVarDict(ov, dictslice)
5426    vv = ov[tuple(slicev)]
5427    wunit = ov.getncattr('units')
5428    if extravarn is not None:
5429        oe = onc.variables[extravarn]
5430        slicee, de = ncvar.SliceVarDict(oe, dictslice)
5431        extrav = oe[tuple(slicee)]
5432        dime = extrav.shape[0]
5433        extraunit = oe.getncattr('units')
5434    else:
5435        dime = uv.shape[0]
5436        extrav = None
5437        extraunit = None
5438
5439    onc.close()
5440
5441    # Wind Rose is with the winds from where they come from!
5442    ang = np.arctan2(-vv, -uv)
5443    speed = np.sqrt(uv*uv + vv*vv)
5444
5445    # re-setting to [0, 2pi]
5446    ang = np.where(ang <= 0., 2.*np.pi+ang, ang)
5447    ang = np.where(np.mod(ang,2.*np.pi) == 0., 0., ang)
5448
5449    drw.plot_WindRose(ang, speed, dime, lpvals, kindlabelsangle, wunit, imgtit,      \
5450      imgkind, fname, close, ncfile, outputfile=freqfileout, ev=extrav,              \
5451      eunit=extraunit)
5452
5453    return
5454
5455#quit()
5456
5457####### ###### ##### #### ### ## #
5458
5459ngraphics = "'" + drw.numVector_String(namegraphics, "', '") + "'"
5460 
5461### Options
5462##string_operation="operation to make: " + '\n' + " out, output values -S inidim1,[inidim2,...]:enddim1,[enddim2,...]"
5463string_operation="""operation to make:
5464  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]
5465  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]
5466    [ckind]:
5467      'cmap': as it gets from colorbar
5468      'fixc,[colname]': fixed color [colname], all stright lines
5469      'fixsignc,[colname]': fixed color [colname], >0 stright, <0 dashed  line
5470"""
5471####### ###### ##### #### ### ## #
5472
5473# Not checking file operation
5474Notcheckingfile = ['draw_2D_shad_cont', 'draw_2D_shad_cont_time',                    \
5475  'draw_2D_shad_line', 'draw_2D_shad_line_time', 'draw_2lines', 'draw_2lines_time',  \
5476  'draw_lines',                                                                      \
5477  'draw_lines_time', 'draw_points', 'draw_topo_geogrid_boxes', 'draw_trajectories',  \
5478  'draw_vals_trajectories', 'variable_values']
5479
5480errormsg='ERROR -- error -- ERROR -- error'
5481
5482# From: http://stackoverflow.com/questions/4041238/why-use-def-main
5483def main():
5484#######    #######
5485## MAIN
5486    #######
5487
5488    parser = OptionParser()
5489    parser.add_option("-f", "--netCDF_file", dest="ncfile", 
5490     help="file to use", metavar="FILE")
5491    parser.add_option("-o", "--operation", type='choice', dest="operation", 
5492      choices=namegraphics, help="operation to make: " + ngraphics, metavar="OPER")
5493    parser.add_option("-S", "--valueS", dest="values", 
5494      help="[WHEN APPLICABLE] values to use according to the operation", 
5495      metavar="VALUES")
5496    parser.add_option("-v", "--variable", dest="varname",
5497      help="[WHEN APPLICABLE] variable to check", metavar="VAR")
5498
5499    (opts, args) = parser.parse_args()
5500
5501    varn=opts.varname
5502    oper=opts.operation
5503
5504    if opts.operation is None:
5505        print errormsg
5506        print '  No operation provided !!'
5507        print "  an operation must be provided as '-o [operationname]' "
5508        quit(-1)
5509
5510    if opts.ncfile is not None and not os.path.isfile(opts.ncfile) and                   \
5511      not drw.searchInlist(Notcheckingfile, oper):
5512        print errormsg
5513        print '  ' + mainn + ': File ' + opts.ncfile + ' does not exist !!'
5514        quit(-1)
5515
5516    if oper == 'create_movie':
5517        create_movie(opts.ncfile, opts.values, opts.varname)
5518    elif oper == 'draw_2D_shad':
5519        draw_2D_shad(opts.ncfile, opts.values, opts.varname)
5520    elif oper == 'draw_2D_shad_time':
5521        draw_2D_shad_time(opts.ncfile, opts.values, opts.varname)
5522    elif oper == 'draw_2D_shad_cont':
5523        draw_2D_shad_cont(opts.ncfile, opts.values, opts.varname)
5524    elif oper == 'draw_2D_shad_cont_time':
5525        draw_2D_shad_cont_time(opts.ncfile, opts.values, opts.varname)
5526    elif oper == 'draw_2D_shad_line':
5527        draw_2D_shad_line(opts.ncfile, opts.values, opts.varname)
5528    elif oper == 'draw_2D_shad_line_time':
5529        draw_2D_shad_line_time(opts.ncfile, opts.values, opts.varname)
5530    elif oper == 'draw_barbs':
5531        draw_barbs(opts.ncfile, opts.values, opts.varname)
5532    elif oper == 'draw_basins':
5533        draw_basins(opts.ncfile, opts.values, opts.varname)
5534    elif oper == 'draw_Neighbourghood_evol':
5535        draw_Neighbourghood_evol(opts.ncfile, opts.values, opts.varname)
5536    elif oper == 'draw_2lines':
5537        draw_2lines(opts.ncfile, opts.values, opts.varname)
5538    elif oper == 'draw_2lines_time':
5539        draw_2lines_time(opts.ncfile, opts.values, opts.varname)
5540    elif oper == 'draw_lines':
5541        draw_lines(opts.ncfile, opts.values, opts.varname)
5542    elif oper == 'draw_lines_time':
5543        draw_lines_time(opts.ncfile, opts.values, opts.varname)
5544    elif oper == 'draw_points':
5545        draw_points(opts.ncfile, opts.values)
5546    elif oper == 'draw_points_lonlat':
5547        draw_points_lonlat(opts.ncfile, opts.values)
5548    elif oper == 'draw_ptZvals':
5549        draw_ptZvals(opts.ncfile, opts.values, opts.varname)
5550    elif oper == 'draw_river_desc':
5551        draw_river_desc(opts.ncfile, opts.values, opts.varname)
5552    elif oper == 'draw_subbasin':
5553        draw_subbasin(opts.ncfile, opts.values)
5554    elif oper == 'draw_timeSeries':
5555        draw_timeSeries(opts.ncfile, opts.values, opts.varname)
5556    elif oper == 'draw_topo_geogrid':
5557        draw_topo_geogrid(opts.ncfile, opts.values)
5558    elif oper == 'draw_topo_geogrid_boxes':
5559        draw_topo_geogrid_boxes(opts.ncfile, opts.values)
5560    elif oper == 'draw_trajectories':
5561        draw_trajectories(opts.ncfile, opts.values, opts.varname)
5562    elif oper == 'draw_vals_trajectories':
5563        draw_vals_trajectories(opts.ncfile, opts.values, opts.varname)
5564    elif oper == 'draw_vectors':
5565        draw_vectors(opts.ncfile, opts.values, opts.varname)
5566    elif oper == 'draw_vertical_levels':
5567        draw_vertical_levels(opts.ncfile, opts.values, opts.varname)
5568    elif oper == 'list_graphics':
5569    # From: http://www.diveintopython.net/power_of_introspection/all_together.html
5570        import drawing as myself
5571        object = myself
5572        for opern in namegraphics:
5573            if  opern != 'list_graphics': 
5574                print opern + '_______ ______ _____ ____ ___ __ _'
5575                print getattr(object, opern).__doc__
5576    elif oper == 'draw_WindRose':
5577        draw_WindRose(opts.ncfile, opts.values, opts.varname)
5578    elif oper == 'variable_values':
5579        variable_values(opts.values)
5580    else:
5581        print errormsg
5582        print '  ' + main + ": the graphic '" + oper + "' is not ready !!"
5583        print errormsg
5584        quit()
5585
5586if __name__ == '__main__':
5587    main()
5588
Note: See TracBrowser for help on using the repository browser.