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

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

Adding range' values option for draw_vector'

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