source: lmdz_wrf/trunk/tools/drawing_tools.py @ 740

Last change on this file since 740 was 705, checked in by lfita, 9 years ago

Adding draw_river_desc' to plot rivers' description after river_desc.nc' from ORCDHIEE

File size: 236.1 KB
Line 
1# -*- coding: iso-8859-15 -*-
2#import pylab as plt
3# From http://stackoverflow.com/questions/13336823/matplotlib-python-error
4import numpy as np
5import matplotlib as mpl
6mpl.use('Agg')
7from matplotlib.pylab import *
8import matplotlib.pyplot as plt
9from mpl_toolkits.basemap import Basemap
10import os
11from netCDF4 import Dataset as NetCDFFile
12import nc_var_tools as ncvar
13
14errormsg = 'ERROR -- error -- ERROR -- error'
15warnmsg = 'WARNING -- waring -- WARNING -- warning'
16
17fillValue = 1.e20
18fillValueF = 1.e20
19
20colorsauto = ['#FF0000', '#00FF00', '#0000FF', '#FF00FF', '#00FFFF', '#FFAA00',     \
21  '#AA0000', '#00AA00', '#0000AA', '#AA00AA', '#00AAAA', '#AA3200']
22pointkindsauto = ['.', ',', 'x', '+', '*', '|', '_', 'o', '<', '>', 'v', '^',       \
23  's', 'D', 'p' ,'h' ,'H']
24linekindsauto = ['-', '--', '-.', ':']
25linewidthsauto = [1.]
26pointsizesauto = [7.]
27
28####### Funtions
29# searchInlist:
30# datetimeStr_datetime:
31# dateStr_date:
32# numVector_String:
33# timeref_datetime:
34# slice_variable: Function to return a slice of a given variable according to values to its dimension
35# interpolate_locs:
36# datetimeStr_conversion:
37# percendone:
38# netCDFdatetime_realdatetime:
39# file_nlines:
40# variables_values:
41# check_colorBar:
42# units_lunits:
43# ASCII_LaTeX:
44# pretty_int:
45# DegGradSec_deg:
46# intT2dt:
47# lonlat2D: Function to return lon, lat 2D matrices from any lon,lat matrix
48# lonlat_values:
49# date_CFtime:
50# pot_values:
51# CFtimes_plot:
52# color_lines:
53# output_kind:
54# check_arguments:
55# Str_Bool:
56# plot_points:
57# plot_2Dfield:
58# plot_2Dfield_easy:
59# plot_topo_geogrid:
60# plot_topo_geogrid_boxes:
61# plot_2D_shadow:
62# plot_2D_shadow_time: Plotting a 2D field with one of the axes being time
63# plot_Neighbourghood_evol:Plotting neighbourghood evolution# plot_Trajectories
64# plot_2D_shadow_contour:
65# plot_2D_shadow_contour_time:
66# dxdy_lonlat: Function to provide lon/lat 2D lilke-matrices from any sort of dx,dy values
67# plot_2D_shadow_line:
68# plot_lines: Function to plot a collection of lines
69# plot_ZQradii: Function to plot following radial averages only at exact grid poins
70
71# From nc_var_tools.py
72def reduce_spaces(string):
73    """ Function to give words of a line of text removing any extra space
74    """
75    values = string.replace('\n','').split(' ')
76    vals = []
77    for val in values:
78         if len(val) > 0:
79             vals.append(val)
80
81    return vals
82
83def searchInlist(listname, nameFind):
84    """ Function to search a value within a list
85    listname = list
86    nameFind = value to find
87    >>> searInlist(['1', '2', '3', '5'], '5')
88    True
89    """
90    for x in listname:
91      if x == nameFind:
92        return True
93        break
94    return False
95
96def datetimeStr_datetime(StringDT):
97    """ Function to transform a string date ([YYYY]-[MM]-[DD]_[HH]:[MI]:[SS] format) to a date object
98    >>> datetimeStr_datetime('1976-02-17_00:00:00')
99    1976-02-17 00:00:00
100    """
101    import datetime as dt
102
103    fname = 'datetimeStr_datetime'
104
105    dateD = np.zeros((3), dtype=int)
106    timeT = np.zeros((3), dtype=int)
107
108#    quit()
109
110    dateD[0] = int(StringDT[0:4])
111    dateD[1] = int(StringDT[5:7])
112    dateD[2] = int(StringDT[8:10])
113
114    trefT = StringDT.find(':')
115    if not trefT == -1:
116#        print '  ' + fname + ': refdate with time!'
117        timeT[0] = int(StringDT[11:13])
118        timeT[1] = int(StringDT[14:16])
119        timeT[2] = int(StringDT[17:19])
120
121    if int(dateD[0]) == 0:
122        print warnmsg
123        print '    ' + fname + ': 0 reference year!! changing to 1'
124        dateD[0] = 1 
125 
126    newdatetime = dt.datetime(dateD[0], dateD[1], dateD[2], timeT[0], timeT[1], timeT[2])
127
128    return newdatetime
129
130def dateStr_date(StringDate):
131  """ Function to transform a string date ([YYYY]-[MM]-[DD] format) to a date object
132  >>> dateStr_date('1976-02-17')
133  1976-02-17
134  """
135  import datetime as dt
136
137  dateD = StringDate.split('-')
138  if int(dateD[0]) == 0:
139    print warnmsg
140    print '    dateStr_date: 0 reference year!! changing to 1'
141    dateD[0] = 1
142  newdate = dt.date(int(dateD[0]), int(dateD[1]), int(dateD[2]))
143  return newdate
144
145def numVector_String(vec,char):
146    """ Function to transform a vector of numbers to a single string [char] separated
147    numVector_String(vec,char)
148      vec= vector with the numerical values
149      char= single character to split the values
150    >>> print numVector_String(np.arange(10),' ')
151    0 1 2 3 4 5 6 7 8 9
152    """
153    fname = 'numVector_String'
154
155    if vec == 'h':
156        print fname + '_____________________________________________________________'
157        print numVector_String.__doc__
158        quit()
159
160    Nvals = len(vec)
161
162    string=''
163    for i in range(Nvals):
164        if i == 0:
165            string = str(vec[i])
166        else:
167            string = string + char + str(vec[i])
168
169    return string
170
171def timeref_datetime(refd, timeval, tu):
172    """ Function to transform from a [timeval] in [tu] units from the time referece [tref] to datetime object
173    refd: time of reference (as datetime object)
174    timeval: time value (as [tu] from [tref])
175    tu: time units
176    >>> timeref = date(1949,12,1,0,0,0)
177    >>> timeref_datetime(timeref, 229784.36, hours)
178    1976-02-17 08:21:36
179    """
180    import datetime as dt
181    import numpy as np
182
183## Not in timedelta
184#    if tu == 'years':
185#        realdate = refdate + dt.timedelta(years=float(timeval))
186#    elif tu == 'months':
187#        realdate = refdate + dt.timedelta(months=float(timeval))
188    if tu == 'weeks':
189        realdate = refd + dt.timedelta(weeks=float(timeval))
190    elif tu == 'days':
191        realdate = refd + dt.timedelta(days=float(timeval))
192    elif tu == 'hours':
193        realdate = refd + dt.timedelta(hours=float(timeval))
194    elif tu == 'minutes':
195        realdate = refd + dt.timedelta(minutes=float(timeval))
196    elif tu == 'seconds':
197        realdate = refd + dt.timedelta(seconds=float(timeval))
198    elif tu == 'milliseconds':
199        realdate = refd + dt.timedelta(milliseconds=float(timeval))
200    else:
201          print errormsg
202          print '    timeref_datetime: time units "' + tu + '" not ready!!!!'
203          quit(-1)
204
205    return realdate
206
207def slice_variable(varobj, dimslice):
208    """ Function to return a slice of a given variable according to values to its
209      dimensions
210    slice_variable(varobj, dims)
211      varobj= object wit the variable
212      dimslice= [[dimname1]:[value1]|[[dimname2]:[value2], ...] pairs of dimension
213        [value]:
214          * [integer]: which value of the dimension
215          * -1: all along the dimension
216          * [beg]:[end] slice from [beg] to [end]
217          * -9: last value of the dimension
218
219    """
220    fname = 'slice_variable'
221
222    if varobj == 'h':
223        print fname + '_____________________________________________________________'
224        print slice_variable.__doc__
225        quit()
226
227    vardims = varobj.dimensions
228    Ndimvar = len(vardims)
229
230    Ndimcut = len(dimslice.split('|'))
231    if Ndimcut == 0:
232        Ndimcut = 1
233        dimcut = list(dimslice)
234
235    dimsl = dimslice.split('|')
236
237    varvalsdim = []
238    dimnslice = []
239    monodim = []
240    for idd in range(Ndimvar):
241        found = False
242        for idc in range(Ndimcut):
243            dimcutn = dimsl[idc].split(':')[0]
244            dimcutv = dimsl[idc].split(':')[1]
245            if vardims[idd] == dimcutn:
246                posfrac = dimcutv.find('@')
247                if posfrac != -1:
248                    inifrac = int(dimcutv.split('@')[0])
249                    endfrac = int(dimcutv.split('@')[1])
250                    varvalsdim.append(slice(inifrac,endfrac))
251                    dimnslice.append(vardims[idd])
252                else:
253                    if int(dimcutv) == -1:
254                        varvalsdim.append(slice(0,varobj.shape[idd]))
255                        dimnslice.append(vardims[idd])
256                    elif int(dimcutv) == -9:
257                        varvalsdim.append(varobj.shape[idd]-1)
258                        monodim.append(vardims[idd])
259                    else:
260                        varvalsdim.append(int(dimcutv))
261                        monodim.append(vardims[idd])
262                found = True
263                break
264        if not found and not searchInlist(dimnslice,vardims[idd]) and                \
265          not searchInlist(monodim,vardims[idd]):
266            varvalsdim.append(slice(0,varobj.shape[idd]))
267            dimnslice.append(vardims[idd])
268    varvalues = varobj[tuple(varvalsdim)]
269
270    varvalues = np.squeeze(varobj[tuple(varvalsdim)])
271
272    return varvalues, dimnslice
273
274def interpolate_locs(locs,coords,kinterp):
275    """ Function to provide interpolate locations on a given axis
276    interpolate_locs(locs,axis,kinterp)
277      locs= locations to interpolate
278      coords= axis values with the reference of coordinates
279      kinterp: kind of interpolation
280        'lin': linear
281    >>> coordinates = np.arange((10), dtype=np.float)
282    >>> values = np.array([-1.2, 2.4, 5.6, 7.8, 12.0])
283    >>> interpolate_locs(values,coordinates,'lin')
284    [ -1.2   2.4   5.6   7.8  13. ]
285    >>> coordinates[0] = 0.5
286    >>> coordinates[2] = 2.5
287    >>> interpolate_locs(values,coordinates,'lin')
288    [ -3.4          1.93333333   5.6          7.8         13.        ]
289    """
290
291    fname = 'interpolate_locs'
292
293    if locs == 'h':
294        print fname + '_____________________________________________________________'
295        print interpolate_locs.__doc__
296        quit()
297
298    Nlocs = locs.shape[0]
299    Ncoords = coords.shape[0]
300
301    dcoords = coords[Ncoords-1] - coords[0]
302
303    intlocs = np.zeros((Nlocs), dtype=np.float)
304    minc = np.min(coords)
305    maxc = np.max(coords)
306
307    for iloc in range(Nlocs):
308        for icor in range(Ncoords-1):
309            if locs[iloc] < minc and dcoords > 0.:
310                a = 0.
311                b = 1. / (coords[1] - coords[0])
312                c = coords[0]
313            elif locs[iloc] > maxc and dcoords > 0.:
314                a = (Ncoords-1)*1.
315                b = 1. / (coords[Ncoords-1] - coords[Ncoords-2])
316                c = coords[Ncoords-2]
317            elif locs[iloc] < minc and dcoords < 0.:
318                a = (Ncoords-1)*1.
319                b = 1. / (coords[Ncoords-1] - coords[Ncoords-2])
320                c = coords[Ncoords-2]
321            elif locs[iloc] > maxc and dcoords < 0.:
322                a = 0.
323                b = 1. / (coords[1] - coords[0])
324                c = coords[0]
325            elif locs[iloc] >= coords[icor] and locs[iloc] < coords[icor+1] and dcoords > 0.:
326                a = icor*1.
327                b = 1. / (coords[icor+1] - coords[icor])
328                c = coords[icor]
329                print coords[icor], locs[iloc], coords[icor+1], ':', icor, '->', a, b
330            elif locs[iloc] <= coords[icor] and locs[iloc] > coords[icor+1] and dcoords < 0.:
331                a = icor*1.
332                b = 1. / (coords[icor+1] - coords[icor])
333                c = coords[icor]
334
335        if kinterp == 'lin':
336            intlocs[iloc] = a + (locs[iloc] - c)*b
337        else:
338            print errormsg
339            print '  ' + fname + ": interpolation kind '" + kinterp + "' not ready !!!!!"
340            quit(-1)
341
342    return intlocs
343
344def datetimeStr_conversion(StringDT,typeSi,typeSo):
345    """ Function to transform a string date to an another date object
346    StringDT= string with the date and time
347    typeSi= type of datetime string input
348    typeSo= type of datetime string output
349      [typeSi/o]
350        'cfTime': [time],[units]; ]time in CF-convention format [units] = [tunits] since [refdate]
351        'matYmdHMS': numerical vector with [[YYYY], [MM], [DD], [HH], [MI], [SS]]
352        'YmdHMS': [YYYY][MM][DD][HH][MI][SS] format
353        'Y-m-d_H:M:S': [YYYY]-[MM]-[DD]_[HH]:[MI]:[SS] format
354        'Y-m-d H:M:S': [YYYY]-[MM]-[DD] [HH]:[MI]:[SS] format
355        'Y/m/d H-M-S': [YYYY]/[MM]/[DD] [HH]-[MI]-[SS] format
356        'WRFdatetime': [Y], [Y], [Y], [Y], '-', [M], [M], '-', [D], [D], '_', [H],
357          [H], ':', [M], [M], ':', [S], [S]
358    >>> datetimeStr_conversion('1976-02-17_08:32:05','Y-m-d_H:M:S','matYmdHMS')
359    [1976    2   17    8   32    5]
360    >>> datetimeStr_conversion(str(137880)+',minutes since 1979-12-01_00:00:00','cfTime','Y/m/d H-M-S')
361    1980/03/05 18-00-00
362    """
363    import datetime as dt
364
365    fname = 'datetimeStr_conversion'
366
367    if StringDT[0:1] == 'h':
368        print fname + '_____________________________________________________________'
369        print datetimeStr_conversion.__doc__
370        quit()
371
372    if typeSi == 'cfTime':
373        timeval = np.float(StringDT.split(',')[0])
374        tunits = StringDT.split(',')[1].split(' ')[0]
375        Srefdate = StringDT.split(',')[1].split(' ')[2]
376
377# Does reference date contain a time value [YYYY]-[MM]-[DD] [HH]:[MI]:[SS]
378##
379        yrref=Srefdate[0:4]
380        monref=Srefdate[5:7]
381        dayref=Srefdate[8:10]
382
383        trefT = Srefdate.find(':')
384        if not trefT == -1:
385#            print '  ' + fname + ': refdate with time!'
386            horref=Srefdate[11:13]
387            minref=Srefdate[14:16]
388            secref=Srefdate[17:19]
389            refdate = datetimeStr_datetime( yrref + '-' + monref + '-' + dayref +    \
390              '_' + horref + ':' + minref + ':' + secref)
391        else:
392            refdate = datetimeStr_datetime( yrref + '-' + monref + '-' + dayref +    \
393              + '_00:00:00')
394
395        if tunits == 'weeks':
396            newdate = refdate + dt.timedelta(weeks=float(timeval))
397        elif tunits == 'days':
398            newdate = refdate + dt.timedelta(days=float(timeval))
399        elif tunits == 'hours':
400            newdate = refdate + dt.timedelta(hours=float(timeval))
401        elif tunits == 'minutes':
402            newdate = refdate + dt.timedelta(minutes=float(timeval))
403        elif tunits == 'seconds':
404            newdate = refdate + dt.timedelta(seconds=float(timeval))
405        elif tunits == 'milliseconds':
406            newdate = refdate + dt.timedelta(milliseconds=float(timeval))
407        else:
408              print errormsg
409              print '    timeref_datetime: time units "' + tunits + '" not ready!!!!'
410              quit(-1)
411
412        yr = newdate.year
413        mo = newdate.month
414        da = newdate.day
415        ho = newdate.hour
416        mi = newdate.minute
417        se = newdate.second
418    elif typeSi == 'matYmdHMS':
419        yr = StringDT[0]
420        mo = StringDT[1]
421        da = StringDT[2]
422        ho = StringDT[3]
423        mi = StringDT[4]
424        se = StringDT[5]
425    elif typeSi == 'YmdHMS':
426        yr = int(StringDT[0:4])
427        mo = int(StringDT[4:6])
428        da = int(StringDT[6:8])
429        ho = int(StringDT[8:10])
430        mi = int(StringDT[10:12])
431        se = int(StringDT[12:14])
432    elif typeSi == 'Y-m-d_H:M:S':
433        dateDT = StringDT.split('_')
434        dateD = dateDT[0].split('-')
435        timeT = dateDT[1].split(':')
436        yr = int(dateD[0])
437        mo = int(dateD[1])
438        da = int(dateD[2])
439        ho = int(timeT[0])
440        mi = int(timeT[1])
441        se = int(timeT[2])
442    elif typeSi == 'Y-m-d H:M:S':
443        dateDT = StringDT.split(' ')
444        dateD = dateDT[0].split('-')
445        timeT = dateDT[1].split(':')
446        yr = int(dateD[0])
447        mo = int(dateD[1])
448        da = int(dateD[2])
449        ho = int(timeT[0])
450        mi = int(timeT[1])
451        se = int(timeT[2])
452    elif typeSi == 'Y/m/d H-M-S':
453        dateDT = StringDT.split(' ')
454        dateD = dateDT[0].split('/')
455        timeT = dateDT[1].split('-')
456        yr = int(dateD[0])
457        mo = int(dateD[1])
458        da = int(dateD[2])
459        ho = int(timeT[0])
460        mi = int(timeT[1])
461        se = int(timeT[2])
462    elif typeSi == 'WRFdatetime':
463        yr = int(StringDT[0])*1000 + int(StringDT[1])*100 + int(StringDT[2])*10 +    \
464          int(StringDT[3])
465        mo = int(StringDT[5])*10 + int(StringDT[6])
466        da = int(StringDT[8])*10 + int(StringDT[9])
467        ho = int(StringDT[11])*10 + int(StringDT[12])
468        mi = int(StringDT[14])*10 + int(StringDT[15])
469        se = int(StringDT[17])*10 + int(StringDT[18])
470    else:
471        print errormsg
472        print '  ' + fname + ': type of String input date "' + typeSi +              \
473          '" not ready !!!!'
474        quit(-1)
475
476    if typeSo == 'matYmdHMS':
477        dateYmdHMS = np.zeros((6), dtype=int)
478        dateYmdHMS[0] =  yr
479        dateYmdHMS[1] =  mo
480        dateYmdHMS[2] =  da
481        dateYmdHMS[3] =  ho
482        dateYmdHMS[4] =  mi
483        dateYmdHMS[5] =  se
484    elif typeSo == 'YmdHMS':
485        dateYmdHMS = str(yr).zfill(4) + str(mo).zfill(2) + str(da).zfill(2) +        \
486          str(ho).zfill(2) + str(mi).zfill(2) + str(se).zfill(2)
487    elif typeSo == 'Y-m-d_H:M:S':
488        dateYmdHMS = str(yr).zfill(4) + '-' + str(mo).zfill(2) + '-' +               \
489          str(da).zfill(2) + '_' + str(ho).zfill(2) + ':' + str(mi).zfill(2) + ':' + \
490          str(se).zfill(2)
491    elif typeSo == 'Y-m-d H:M:S':
492        dateYmdHMS = str(yr).zfill(4) + '-' + str(mo).zfill(2) + '-' +               \
493          str(da).zfill(2) + ' ' + str(ho).zfill(2) + ':' + str(mi).zfill(2) + ':' + \
494          str(se).zfill(2)
495    elif typeSo == 'Y/m/d H-M-S':
496        dateYmdHMS = str(yr).zfill(4) + '/' + str(mo).zfill(2) + '/' +               \
497          str(da).zfill(2) + ' ' + str(ho).zfill(2) + '-' + str(mi).zfill(2) + '-' + \
498          str(se).zfill(2)
499    elif typeSo == 'WRFdatetime':
500        dateYmdHMS = []
501        yM = yr/1000
502        yC = (yr-yM*1000)/100
503        yD = (yr-yM*1000-yC*100)/10
504        yU = yr-yM*1000-yC*100-yD*10
505
506        mD = mo/10
507        mU = mo-mD*10
508       
509        dD = da/10
510        dU = da-dD*10
511
512        hD = ho/10
513        hU = ho-hD*10
514
515        miD = mi/10
516        miU = mi-miD*10
517
518        sD = se/10
519        sU = se-sD*10
520
521        dateYmdHMS.append(str(yM))
522        dateYmdHMS.append(str(yC))
523        dateYmdHMS.append(str(yD))
524        dateYmdHMS.append(str(yU))
525        dateYmdHMS.append('-')
526        dateYmdHMS.append(str(mD))
527        dateYmdHMS.append(str(mU))
528        dateYmdHMS.append('-')
529        dateYmdHMS.append(str(dD))
530        dateYmdHMS.append(str(dU))
531        dateYmdHMS.append('_')
532        dateYmdHMS.append(str(hD))
533        dateYmdHMS.append(str(hU))
534        dateYmdHMS.append(':')
535        dateYmdHMS.append(str(miD))
536        dateYmdHMS.append(str(miU))
537        dateYmdHMS.append(':')
538        dateYmdHMS.append(str(sD))
539        dateYmdHMS.append(str(sU))
540    else:
541        print errormsg
542        print '  ' + fname + ': type of output date "' + typeSo + '" not ready !!!!'
543        quit(-1)
544
545    return dateYmdHMS
546
547def percendone(nvals,tot,percen,msg):
548    """ Function to provide the percentage of an action across the matrix
549    nvals=number of values
550    tot=total number of values
551    percen=percentage frequency for which the message is wanted
552    msg= message
553    """
554    from sys import stdout
555
556    num = int(tot * percen/100)
557    if (nvals%num == 0): 
558        print '\r        ' + msg + '{0:8.3g}'.format(nvals*100./tot) + ' %',
559        stdout.flush()
560
561    return ''
562
563def netCDFdatetime_realdatetime(units, tcalendar, times):
564    """ Function to transfrom from netCDF CF-compilant times to real time
565    """
566    import datetime as dt
567
568    txtunits = units.split(' ')
569    tunits = txtunits[0]
570    Srefdate = txtunits[len(txtunits) - 1]
571
572# Calendar type
573##
574    is360 = False
575    if tcalendar is not None:
576      print '  netCDFdatetime_realdatetime: There is a calendar attribute'
577      if tcalendar == '365_day' or tcalendar == 'noleap':
578          print '    netCDFdatetime_realdatetime: No leap years!'
579          isleapcal = False
580      elif tcalendar == 'proleptic_gregorian' or tcalendar == 'standard' or tcalendar == 'gregorian':
581          isleapcal = True
582      elif tcalendar == '360_day':
583          is360 = True
584          isleapcal = False
585      else:
586          print errormsg
587          print '    netCDFdatetime_realdatetime: Calendar "' + tcalendar + '" not prepared!'
588          quit(-1)
589
590# Does reference date contain a time value [YYYY]-[MM]-[DD] [HH]:[MI]:[SS]
591##
592    timeval = Srefdate.find(':')
593
594    if not timeval == -1:
595        print '  netCDFdatetime_realdatetime: refdate with time!'
596        refdate = datetimeStr_datetime(Srefdate)
597    else:
598        refdate = dateStr_date(Srefdate + '_00:00:00')
599
600    dimt = len(times)
601#    datetype = type(dt.datetime(1972,02,01))
602#    realdates = np.array(dimt, datetype)
603#    print realdates
604
605## Not in timedelta
606#  if tunits == 'years':
607#    for it in range(dimt):
608#      realdate = refdate + dt.timedelta(years=float(times[it]))
609#      realdates[it] = int(realdate.year)
610#  elif tunits == 'months':
611#    for it in range(dimt):
612#      realdate = refdate + dt.timedelta(months=float(times[it]))
613#      realdates[it] = int(realdate.year)
614#    realdates = []
615    realdates = np.zeros((dimt, 6), dtype=int)
616    if tunits == 'weeks':
617        for it in range(dimt):
618            realdate = refdate + dt.timedelta(weeks=float(times[it]))
619            realdates[it,:]=[realdate.year, realdate.month, realdate.day, realdate.hour, realdate.minute, realdate.second]
620    elif tunits == 'days':
621        for it in range(dimt):
622            realdate = refdate + dt.timedelta(days=float(times[it]))
623            realdates[it,:]=[realdate.year, realdate.month, realdate.day, realdate.hour, realdate.minute, realdate.second]
624    elif tunits == 'hours':
625        for it in range(dimt):
626            realdate = refdate + dt.timedelta(hours=float(times[it]))
627#            if not isleapcal:
628#                Nleapdays = cal.leapdays(int(refdate.year), int(realdate.year))
629#                realdate = realdate - dt.timedelta(days=Nleapdays)
630#            if is360:
631#                Nyears360 = int(realdate.year) - int(refdate.year) + 1
632#                realdate = realdate -dt.timedelta(days=Nyears360*5)
633#            realdates[it] = realdate
634#        realdates = refdate + dt.timedelta(hours=float(times))
635            realdates[it,:]=[realdate.year, realdate.month, realdate.day, realdate.hour, realdate.minute, realdate.second]
636    elif tunits == 'minutes':
637        for it in range(dimt):
638            realdate = refdate + dt.timedelta(minutes=float(times[it]))
639            realdates[it,:]=[realdate.year, realdate.month, realdate.day, realdate.hour, realdate.minute, realdate.second]
640    elif tunits == 'seconds':
641        for it in range(dimt):
642            realdate = refdate + dt.timedelta(seconds=float(times[it]))
643            realdates[it,:]=[realdate.year, realdate.month, realdate.day, realdate.hour, realdate.minute, realdate.second]
644    elif tunits == 'milliseconds':
645        for it in range(dimt):
646            realdate = refdate + dt.timedelta(milliseconds=float(times[it]))
647            realdates[it,:]=[realdate.year, realdate.month, realdate.day, realdate.hour, realdate.minute, realdate.second]
648    elif tunits == 'microseconds':
649        for it in range(dimt):
650            realdate = refdate + dt.timedelta(microseconds=float(times[it]))
651            realdates[it,:]=[realdate.year, realdate.month, realdate.day, realdate.hour, realdate.minute, realdate.second]
652    else:
653        print errormsg
654        print '  netCDFdatetime_realdatetime: time units "' + tunits + '" is not ready!!!'
655        quit(-1)
656
657    return realdates
658
659def file_nlines(filen):
660    """ Function to provide the number of lines of a file
661    filen= name of the file
662    >>> file_nlines('trajectory.dat')
663    49
664    """
665    fname = 'file_nlines'
666
667    if not os.path.isfile(filen):
668        print errormsg
669        print '  ' + fname + ' file: "' + filen + '" does not exist !!'
670        quit(-1)
671
672    fo = open(filen,'r')
673
674    nlines=0
675    for line in fo: nlines = nlines + 1
676
677    fo.close()
678
679    return nlines
680
681def realdatetime1_CFcompilant(time, Srefdate, tunits):
682    """ Function to transform a matrix with a real time value ([year, month, day,
683      hour, minute, second]) to a netCDF one
684        time= matrix with time
685        Srefdate= reference date ([YYYY][MM][DD][HH][MI][SS] format)
686        tunits= units of time respect to Srefdate
687    >>> realdatetime1_CFcompilant([1976, 2, 17, 8, 20, 0], '19491201000000', 'hours')
688    229784.33333333
689    """ 
690
691    import datetime as dt
692    yrref=int(Srefdate[0:4])
693    monref=int(Srefdate[4:6])
694    dayref=int(Srefdate[6:8])
695    horref=int(Srefdate[8:10])
696    minref=int(Srefdate[10:12])
697    secref=int(Srefdate[12:14])
698 
699    refdate=dt.datetime(yrref, monref, dayref, horref, minref, secref)
700
701    if tunits == 'weeks':
702        cfdate = dt.datetime(time[0],time[1],time[2],time[3],time[4],time[5])-refdate
703        cfdates = (cfdate.days + cfdate.seconds/(3600.*24.))/7.
704    elif tunits == 'days':
705        cfdate = dt.datetime(time[0],time[1],time[2],time[3],time[4],time[5]) - refdate
706        cfdates = cfdate.days + cfdate.seconds/(3600.*24.)
707    elif tunits == 'hours':
708        cfdate = dt.datetime(time[0],time[1],time[2],time[3],time[4],time[5]) - refdate
709        cfdates = cfdate.days*24. + cfdate.seconds/3600.
710    elif tunits == 'minutes':
711        cfdate = dt.datetime(time[0],time[1],time[2],time[3],time[4],time[5]) - refdate
712        cfdates = cfdate.days*24.*60. + cfdate.seconds/60.
713    elif tunits == 'seconds':
714        cfdate = dt.datetime(time[0],time[1],time[2],time[3],time[4],time[5]) - refdate
715        cfdates = cfdate.days*24.*3600. + cfdate.seconds
716    elif tunits == 'milliseconds':
717        cfdate = dt.datetime(time[0],time[1],time[2],time[3],time[4],time[5]) - refdate
718        cfdates = cfdate.days*1000.*24.*3600. + cfdate.seconds*1000.
719    elif tunits == 'microseconds':
720        cfdate = dt.datetime(time[0],time[1],time[2],time[3],time[4],times[5]) - refdate
721        cfdates = cfdate.days*1000000.*24.*3600. + cfdate.seconds*1000000.
722    else:
723        print errormsg
724        print '  ' + fname + ': time units "' + tunits + '" is not ready!!!'
725        quit(-1)
726
727    return cfdates
728
729def basicvardef(varobj, vstname, vlname, vunits):
730    """ Function to give the basic attributes to a variable
731    varobj= netCDF variable object
732    vstname= standard name of the variable
733    vlname= long name of the variable
734    vunits= units of the variable
735    """
736    attr = varobj.setncattr('standard_name', vstname)
737    attr = varobj.setncattr('long_name', vlname)
738    attr = varobj.setncattr('units', vunits)
739
740    return 
741
742def variables_values(varName):
743    """ Function to provide values to plot the different variables values from ASCII file
744      'variables_values.dat'
745    variables_values(varName)
746      [varName]= name of the variable
747        return: [var name], [std name], [minimum], [maximum],
748          [long name]('|' for spaces), [units], [color palette] (following:
749          http://matplotlib.org/1.3.1/examples/color/colormaps_reference.html)
750     [varn]: original name of the variable
751       NOTE: It might be better doing it with an external ASII file. But then we
752         got an extra dependency...
753    >>> variables_values('WRFght')
754    ['z', 'geopotential_height', 0.0, 80000.0, 'geopotential|height', 'm2s-2', 'rainbow']
755    """
756    import subprocess as sub
757
758    fname='variables_values'
759
760    if varName == 'h':
761        print fname + '_____________________________________________________________'
762        print variables_values.__doc__
763        quit()
764
765# This does not work....
766#    folderins = sub.Popen(["pwd"], stdout=sub.PIPE)
767#    folder = list(folderins.communicate())[0].replace('\n','')
768# From http://stackoverflow.com/questions/4934806/how-can-i-find-scripts-directory-with-python
769    folder = os.path.dirname(os.path.realpath(__file__))
770
771    infile = folder + '/variables_values.dat'
772
773    if not os.path.isfile(infile):
774        print errormsg
775        print '  ' + fname + ": File '" + infile + "' does not exist !!"
776        quit(-1)
777
778# Variable name might come with a statistical surname...
779    stats=['min','max','mean','stdv', 'sum']
780
781# Variables with a statistical section on their name...
782    NOstatsvars = ['zmaxth', 'zmax_th', 'lmax_th', 'lmaxth']
783
784    ifst = False
785    if not searchInlist(NOstatsvars, varName.lower()):
786        for st in stats:
787            if varName.find(st) > -1:
788                print '    '+ fname + ": varibale '" + varName + "' with a " +       \
789                  "statistical surname: '",st,"' !!"
790                Lst = len(st)
791                LvarName = len(varName)
792                varn = varName[0:LvarName - Lst]
793                ifst = True
794                break
795    if not ifst:
796        varn = varName
797
798    ncf = open(infile, 'r')
799
800    for line in ncf:
801        if line[0:1] != '#':
802            values = line.replace('\n','').split(',')
803            if len(values) != 8:
804                print errormsg
805                print "problem in varibale:'", values[0],                            \
806                  'it should have 8 values and it has',len(values)
807                quit(-1)
808
809            if varn[0:6] == 'varDIM': 
810# Variable from a dimension (all with 'varDIM' prefix)
811                Lvarn = len(varn)
812                varvals = [varn[6:Lvarn+1], varn[6:Lvarn+1], 0., 1.,                 \
813                  "variable|from|size|of|dimension|'" + varn[6:Lvarn+1] + "'", '1',  \
814                   'rainbow']
815            else:
816                varvals = [values[1].replace(' ',''), values[2].replace(' ',''),     \
817                  np.float(values[3]), np.float(values[4]),values[5].replace(' ',''),\
818                  values[6].replace(' ',''), values[7].replace(' ','')]
819            if values[0] == varn:
820                ncf.close()
821                return varvals
822                break
823
824    print errormsg
825    print '  ' + fname + ": variable '" + varn + "' not defined !!!"
826    ncf.close()
827    quit(-1)
828
829    return 
830
831def variables_values_old(varName):
832    """ Function to provide values to plot the different variables
833    variables_values(varName)
834      [varName]= name of the variable
835        return: [var name], [std name], [minimum], [maximum],
836          [long name]('|' for spaces), [units], [color palette] (following:
837          http://matplotlib.org/1.3.1/examples/color/colormaps_reference.html)
838     [varn]: original name of the variable
839       NOTE: It might be better doing it with an external ASII file. But then we
840         got an extra dependency...
841    >>> variables_values('WRFght')
842    ['z', 'geopotential_height', 0.0, 80000.0, 'geopotential|height', 'm2s-2', 'rainbow']
843    """
844    fname='variables_values'
845
846    if varName == 'h':
847        print fname + '_____________________________________________________________'
848        print variables_values.__doc__
849        quit()
850
851# Variable name might come with a statistical surname...
852    stats=['min','max','mean','stdv', 'sum']
853
854    ifst = False
855    for st in stats:
856        if varName.find(st) > -1:
857            print '    '+ fname + ": varibale '" + varName + "' with a statistical "+\
858              " surname: '",st,"' !!"
859            Lst = len(st)
860            LvarName = len(varName)
861            varn = varName[0:LvarName - Lst]
862            ifst = True
863            break
864    if not ifst:
865        varn = varName
866
867    if varn[0:6] == 'varDIM': 
868# Variable from a dimension (all with 'varDIM' prefix)
869        Lvarn = len(varn)
870        varvals = [varn[6:Lvarn+1], varn[6:Lvarn+1], 0., 1.,                         \
871          "variable|from|size|of|dimension|'" + varn[6:Lvarn+1] + "'", '1', 'rainbox']
872    elif varn == 'a_tht' or varn == 'LA_THT':
873        varvals = ['ath', 'total_thermal_plume_cover', 0., 1.,                       \
874        'total|column|thermal|plume|cover', '1', 'YlGnBu']
875    elif varn == 'acprc' or varn == 'RAINC':
876        varvals = ['acprc', 'accumulated_cmulus_precipitation', 0., 3.e4,            \
877          'accumulated|cmulus|precipitation', 'mm', 'Blues']
878    elif varn == 'acprnc' or varn == 'RAINNC':
879        varvals = ['acprnc', 'accumulated_non-cmulus_precipitation', 0., 3.e4,       \
880          'accumulated|non-cmulus|precipitation', 'mm', 'Blues']
881    elif varn == 'bils' or varn == 'LBILS':
882        varvals = ['bils', 'surface_total_heat_flux', -100., 100.,                   \
883          'surface|total|heat|flux', 'Wm-2', 'seismic']
884    elif varn == 'landcat' or varn == 'category':
885        varvals = ['landcat', 'land_categories', 0., 22., 'land|categories', '1',    \
886          'rainbow']
887    elif varn == 'c' or varn == 'QCLOUD' or varn == 'oliq' or varn == 'OLIQ':
888        varvals = ['c', 'condensed_water_mixing_ratio', 0., 3.e-4,                   \
889          'condensed|water|mixing|ratio', 'kgkg-1', 'BuPu']
890    elif varn == 'ci' or varn == 'iwcon' or varn == 'LIWCON':
891        varvals = ['ci', 'cloud_iced_water_mixing_ratio', 0., 0.0003,                \
892         'cloud|iced|water|mixing|ratio', 'kgkg-1', 'Purples']
893    elif varn == 'cl' or varn == 'lwcon' or varn == 'LLWCON':
894        varvals = ['cl', 'cloud_liquidwater_mixing_ratio', 0., 0.0003,               \
895         'cloud|liquid|water|mixing|ratio', 'kgkg-1', 'Blues']
896    elif varn == 'cld' or varn == 'CLDFRA' or varn == 'rneb' or varn == 'lrneb' or   \
897      varn == 'LRNEB':
898        varvals = ['cld', 'cloud_area_fraction', 0., 1., 'cloud|fraction', '1',      \
899          'gist_gray']
900    elif varn == 'cldc' or varn == 'rnebcon' or varn == 'lrnebcon' or                \
901      varn == 'LRNEBCON':
902        varvals = ['cldc', 'convective_cloud_area_fraction', 0., 1.,                 \
903          'convective|cloud|fraction', '1', 'gist_gray']
904    elif varn == 'cldl' or varn == 'rnebls' or varn == 'lrnebls' or varn == 'LRNEBLS':
905        varvals = ['cldl', 'large_scale_cloud_area_fraction', 0., 1.,                \
906          'large|scale|cloud|fraction', '1', 'gist_gray']
907    elif varn == 'clt' or varn == 'CLT' or varn == 'cldt' or                         \
908      varn == 'Total cloudiness':
909        varvals = ['clt', 'cloud_area_fraction', 0., 1., 'total|cloud|cover', '1',   \
910          'gist_gray']
911    elif varn == 'cll' or varn == 'cldl' or varn == 'LCLDL' or                       \
912      varn == 'Low-level cloudiness':
913        varvals = ['cll', 'low_level_cloud_area_fraction', 0., 1.,                   \
914          'low|level|(p|>|680|hPa)|cloud|fraction', '1', 'gist_gray']
915    elif varn == 'clm' or varn == 'cldm' or varn == 'LCLDM' or                       \
916      varn == 'Mid-level cloudiness':
917        varvals = ['clm', 'mid_level_cloud_area_fraction', 0., 1.,                   \
918          'medium|level|(440|<|p|<|680|hPa)|cloud|fraction', '1', 'gist_gray']
919    elif varn == 'clh' or varn == 'cldh' or varn == 'LCLDH' or                       \
920      varn == 'High-level cloudiness':
921        varvals = ['clh', 'high_level_cloud_area_fraction', 0., 1.,                  \
922          'high|level|(p|<|440|hPa)|cloud|fraction', '1', 'gist_gray']
923    elif varn == 'clmf' or varn == 'fbase' or varn == 'LFBASE':
924        varvals = ['clmf', 'cloud_base_max_flux', -0.3, 0.3, 'cloud|base|max|flux',  \
925          'kgm-2s-1', 'seismic']
926    elif varn == 'clp' or varn == 'pbase' or varn == 'LPBASE':
927        varvals = ['clp', 'cloud_base_pressure', -0.3, 0.3, 'cloud|base|pressure',   \
928          'Pa', 'Reds']
929    elif varn == 'cpt' or varn == 'ptconv' or varn == 'LPTCONV':
930        varvals = ['cpt', 'convective_point', 0., 1., 'convective|point', '1',       \
931          'seismic']
932    elif varn == 'dqajs' or varn == 'LDQAJS':
933        varvals = ['dqajs', 'dry_adjustment_water_vapor_tendency', -0.0003, 0.0003,  \
934        'dry|adjustment|water|vapor|tendency', 'kg/kg/s', 'seismic']
935    elif varn == 'dqcon' or varn == 'LDQCON':
936        varvals = ['dqcon', 'convective_water_vapor_tendency', -3e-8, 3.e-8,         \
937        'convective|water|vapor|tendency', 'kg/kg/s', 'seismic']
938    elif varn == 'dqdyn' or varn == 'LDQDYN':
939        varvals = ['dqdyn', 'dynamics_water_vapor_tendency', -3.e-7, 3.e-7,          \
940        'dynamics|water|vapor|tendency', 'kg/kg/s', 'seismic']
941    elif varn == 'dqeva' or varn == 'LDQEVA':
942        varvals = ['dqeva', 'evaporation_water_vapor_tendency', -3.e-6, 3.e-6,       \
943        'evaporation|water|vapor|tendency', 'kg/kg/s', 'seismic']
944    elif varn == 'dqlscst' or varn == 'LDQLSCST':
945        varvals = ['dqlscst', 'stratocumulus_water_vapor_tendency', -3.e-7, 3.e-7,   \
946        'stratocumulus|water|vapor|tendency', 'kg/kg/s', 'seismic']
947    elif varn == 'dqlscth' or varn == 'LDQLSCTH': 
948        varvals = ['dqlscth', 'thermals_water_vapor_tendency', -3.e-7, 3.e-7,        \
949        'thermal|plumes|water|vapor|tendency', 'kg/kg/s', 'seismic']
950    elif varn == 'dqlsc' or varn == 'LDQLSC':
951        varvals = ['dqlsc', 'condensation_water_vapor_tendency', -3.e-6, 3.e-6,      \
952        'condensation|water|vapor|tendency', 'kg/kg/s', 'seismic']
953    elif varn == 'dqphy' or varn == 'LDQPHY':
954        varvals = ['dqphy', 'physics_water_vapor_tendency', -3.e-7, 3.e-7,           \
955        'physics|water|vapor|tendency', 'kg/kg/s', 'seismic']
956    elif varn == 'dqthe' or varn == 'LDQTHE':
957        varvals = ['dqthe', 'thermals_water_vapor_tendency', -3.e-7, 3.e-7,          \
958        'thermal|plumes|water|vapor|tendency', 'kg/kg/s', 'seismic']
959    elif varn == 'dqvdf' or varn == 'LDQVDF':
960        varvals = ['dqvdf', 'vertical_difussion_water_vapor_tendency', -3.e-8, 3.e-8,\
961        'vertical|difussion|water|vapor|tendency', 'kg/kg/s', 'seismic']
962    elif varn == 'dqwak' or varn == 'LDQWAK':
963        varvals = ['dqwak', 'wake_water_vapor_tendency', -3.e-7, 3.e-7,              \
964        'wake|water|vapor|tendency', 'kg/kg/s', 'seismic']
965    elif varn == 'dta' or varn == 'tnt' or varn == 'LTNT':
966        varvals = ['dta', 'tendency_air_temperature', -3.e-3, 3.e-3,                 \
967        'tendency|of|air|temperature', 'K/s', 'seismic']
968    elif varn == 'dtac' or varn == 'tntc' or varn == 'LTNTC':
969        varvals = ['dtac', 'moist_convection_tendency_air_temperature', -3.e-3,      \
970        3.e-3, 'moist|convection|tendency|of|air|temperature', 'K/s', 'seismic']
971    elif varn == 'dtar' or varn == 'tntr' or varn == 'LTNTR':
972        varvals = ['dtar', 'radiative_heating_tendency_air_temperature', -3.e-3,     \
973          3.e-3, 'radiative|heating|tendency|of|air|temperature', 'K/s', 'seismic']
974    elif varn == 'dtascpbl' or varn == 'tntscpbl' or varn == 'LTNTSCPBL':
975        varvals = ['dtascpbl',                                                       \
976          'stratiform_cloud_precipitation_BL_mixing_tendency_air_temperature',       \
977          -3.e-6, 3.e-6,                                                             \
978          'stratiform|cloud|precipitation|Boundary|Layer|mixing|tendency|air|'       +
979          'temperature', 'K/s', 'seismic']
980    elif varn == 'dtajs' or varn == 'LDTAJS':
981        varvals = ['dtajs', 'dry_adjustment_thermal_tendency', -3.e-5, 3.e-5,        \
982        'dry|adjustment|thermal|tendency', 'K/s', 'seismic']
983    elif varn == 'dtcon' or varn == 'LDTCON':
984        varvals = ['dtcon', 'convective_thermal_tendency', -3.e-5, 3.e-5,            \
985        'convective|thermal|tendency', 'K/s', 'seismic']
986    elif varn == 'dtdyn' or varn == 'LDTDYN':
987        varvals = ['dtdyn', 'dynamics_thermal_tendency', -3.e-4, 3.e-4,              \
988        'dynamics|thermal|tendency', 'K/s', 'seismic']
989    elif varn == 'dteva' or varn == 'LDTEVA':
990        varvals = ['dteva', 'evaporation_thermal_tendency', -3.e-3, 3.e-3,           \
991        'evaporation|thermal|tendency', 'K/s', 'seismic']
992    elif varn == 'dtlscst' or varn == 'LDTLSCST':
993        varvals = ['dtlscst', 'stratocumulus_thermal_tendency', -3.e-4, 3.e-4,       \
994        'stratocumulus|thermal|tendency', 'K/s', 'seismic']
995    elif varn == 'dtlscth' or varn == 'LDTLSCTH':
996        varvals = ['dtlscth', 'thermals_thermal_tendency', -3.e-4, 3.e-4,            \
997        'thermal|plumes|thermal|tendency', 'K/s', 'seismic']
998    elif varn == 'dtlsc' or varn == 'LDTLSC':
999        varvals = ['dtlsc', 'condensation_thermal_tendency', -3.e-3, 3.e-3,          \
1000        'condensation|thermal|tendency', 'K/s', 'seismic']
1001    elif varn == 'dtlwr' or varn == 'LDTLWR':
1002        varvals = ['dtlwr', 'long_wave_thermal_tendency', -3.e-3, 3.e-3, \
1003        'long|wave|radiation|thermal|tendency', 'K/s', 'seismic']
1004    elif varn == 'dtphy' or varn == 'LDTPHY':
1005        varvals = ['dtphy', 'physics_thermal_tendency', -3.e-4, 3.e-4,               \
1006        'physics|thermal|tendency', 'K/s', 'seismic']
1007    elif varn == 'dtsw0' or varn == 'LDTSW0':
1008        varvals = ['dtsw0', 'cloudy_sky_short_wave_thermal_tendency', -3.e-4, 3.e-4, \
1009        'cloudy|sky|short|wave|radiation|thermal|tendency', 'K/s', 'seismic']
1010    elif varn == 'dtthe' or varn == 'LDTTHE':
1011        varvals = ['dtthe', 'thermals_thermal_tendency', -3.e-4, 3.e-4,              \
1012        'thermal|plumes|thermal|tendency', 'K/s', 'seismic']
1013    elif varn == 'dtvdf' or varn == 'LDTVDF':
1014        varvals = ['dtvdf', 'vertical_difussion_thermal_tendency', -3.e-5, 3.e-5,    \
1015        'vertical|difussion|thermal|tendency', 'K/s', 'seismic']
1016    elif varn == 'dtwak' or varn == 'LDTWAK':
1017        varvals = ['dtwak', 'wake_thermal_tendency', -3.e-4, 3.e-4,                  \
1018        'wake|thermal|tendency', 'K/s', 'seismic']
1019    elif varn == 'ducon' or varn == 'LDUCON':
1020        varvals = ['ducon', 'convective_eastward_wind_tendency', -3.e-3, 3.e-3,      \
1021        'convective|eastward|wind|tendency', 'ms-2', 'seismic']
1022    elif varn == 'dudyn' or varn == 'LDUDYN':
1023        varvals = ['dudyn', 'dynamics_eastward_wind_tendency', -3.e-3, 3.e-3,        \
1024        'dynamics|eastward|wind|tendency', 'ms-2', 'seismic']
1025    elif varn == 'duvdf' or varn == 'LDUVDF':
1026        varvals = ['duvdf', 'vertical_difussion_eastward_wind_tendency', -3.e-3,     \
1027         3.e-3, 'vertical|difussion|eastward|wind|tendency', 'ms-2', 'seismic']
1028    elif varn == 'dvcon' or varn == 'LDVCON':
1029        varvals = ['dvcon', 'convective_difussion_northward_wind_tendency', -3.e-3,  \
1030         3.e-3, 'convective|northward|wind|tendency', 'ms-2', 'seismic']
1031    elif varn == 'dvdyn' or varn == 'LDVDYN':
1032        varvals = ['dvdyn', 'dynamics_northward_wind_tendency', -3.e-3,              \
1033         3.e-3, 'dynamics|difussion|northward|wind|tendency', 'ms-2', 'seismic']
1034    elif varn == 'dvvdf' or varn == 'LDVVDF':
1035        varvals = ['dvvdf', 'vertical_difussion_northward_wind_tendency', -3.e-3,    \
1036         3.e-3, 'vertical|difussion|northward|wind|tendency', 'ms-2', 'seismic']
1037    elif varn == 'etau' or varn == 'ZNU':
1038        varvals = ['etau', 'etau', 0., 1, 'eta values on half (mass) levels', '-',   \
1039        'reds']
1040    elif varn == 'evspsbl' or varn == 'LEVAP' or varn == 'evap' or varn == 'SFCEVPde':
1041        varvals = ['evspsbl', 'water_evaporation_flux', 0., 1.5e-4,                  \
1042          'water|evaporation|flux', 'kgm-2s-1', 'Blues']
1043    elif varn == 'evspsbl' or varn == 'SFCEVPde':
1044        varvals = ['evspsblac', 'water_evaporation_flux_ac', 0., 1.5e-4,             \
1045          'accumulated|water|evaporation|flux', 'kgm-2', 'Blues']
1046    elif varn == 'g' or varn == 'QGRAUPEL':
1047        varvals = ['g', 'grauepl_mixing_ratio', 0., 0.0003, 'graupel|mixing|ratio',  \
1048          'kgkg-1', 'Purples']
1049    elif varn == 'h2o' or varn == 'LH2O':
1050        varvals = ['h2o', 'water_mass_fraction', 0., 3.e-2,                          \
1051          'mass|fraction|of|water', '1', 'Blues']
1052    elif varn == 'h' or varn == 'QHAIL':
1053        varvals = ['h', 'hail_mixing_ratio', 0., 0.0003, 'hail|mixing|ratio',        \
1054          'kgkg-1', 'Purples']
1055    elif varn == 'hfls' or varn == 'LH' or varn == 'LFLAT' or varn == 'flat':
1056        varvals = ['hfls', 'surface_upward_latent_heat_flux', -400., 400.,           \
1057          'upward|latnt|heat|flux|at|the|surface', 'Wm-2', 'seismic']
1058    elif varn == 'hfss' or varn == 'LSENS' or varn == 'sens' or varn == 'HFX':
1059        varvals = ['hfss', 'surface_upward_sensible_heat_flux', -150., 150.,         \
1060          'upward|sensible|heat|flux|at|the|surface', 'Wm-2', 'seismic']
1061    elif varn == 'hfso' or varn == 'GRDFLX':
1062        varvals = ['hfso', 'downward_heat_flux_in_soil', -150., 150.,                \
1063          'Downward|soil|heat|flux', 'Wm-2', 'seismic']
1064    elif varn == 'hus' or varn == 'WRFrh' or varn == 'LMDZrh' or varn == 'rhum' or   \
1065      varn == 'LRHUM':
1066        varvals = ['hus', 'specific_humidity', 0., 1., 'specific|humidty', '1',      \
1067          'BuPu']
1068    elif varn == 'huss' or varn == 'WRFrhs' or varn == 'LMDZrhs' or varn == 'rh2m' or\
1069      varn == 'LRH2M':
1070        varvals = ['huss', 'specific_humidity', 0., 1., 'specific|humidty|at|2m',    \
1071          '1', 'BuPu']
1072    elif varn == 'i' or varn == 'QICE':
1073        varvals = ['i', 'iced_water_mixing_ratio', 0., 0.0003,                       \
1074         'iced|water|mixing|ratio', 'kgkg-1', 'Purples']
1075    elif varn == 'lat' or varn == 'XLAT' or varn == 'XLAT_M' or varn == 'latitude':
1076        varvals = ['lat', 'latitude', -90., 90., 'latitude', 'degrees North',        \
1077          'seismic']
1078    elif varn == 'lcl' or varn == 's_lcl' or varn == 'ls_lcl' or varn == 'LS_LCL':
1079        varvals = ['lcl', 'condensation_level', 0., 2500., 'level|of|condensation',  \
1080          'm', 'Greens']
1081    elif varn == 'lambdath' or varn == 'lambda_th' or varn == 'LLAMBDA_TH':
1082        varvals = ['lambdath', 'thermal_plume_vertical_velocity', -30., 30.,         \
1083          'thermal|plume|vertical|velocity', 'm/s', 'seismic']
1084    elif varn == 'lmaxth' or varn == 'LLMAXTH':
1085        varvals = ['lmaxth', 'upper_level_thermals', 0., 100., 'upper|level|thermals'\
1086          , '1', 'Greens']
1087    elif varn == 'lon' or varn == 'XLONG' or varn == 'XLONG_M':
1088        varvals = ['lon', 'longitude', -180., 180., 'longitude', 'degrees East',     \
1089          'seismic']
1090    elif varn == 'longitude':
1091        varvals = ['lon', 'longitude', 0., 360., 'longitude', 'degrees East',        \
1092          'seismic']
1093    elif varn == 'orog' or varn == 'HGT' or varn == 'HGT_M':
1094        varvals = ['orog', 'orography',  0., 3000., 'surface|altitude', 'm','terrain']
1095    elif varn == 'pfc' or varn == 'plfc' or varn == 'LPLFC':
1096        varvals = ['pfc', 'pressure_free_convection', 100., 1100.,                   \
1097          'pressure|free|convection', 'hPa', 'BuPu']
1098    elif varn == 'plcl' or varn == 'LPLCL':
1099        varvals = ['plcl', 'pressure_lifting_condensation_level', 700., 1100.,       \
1100          'pressure|lifting|condensation|level', 'hPa', 'BuPu']
1101    elif varn == 'pr' or varn == 'RAINTOT' or varn == 'precip' or                    \
1102      varn == 'LPRECIP' or varn == 'Precip Totale liq+sol':
1103        varvals = ['pr', 'precipitation_flux', 0., 1.e-4, 'precipitation|flux',      \
1104          'kgm-2s-1', 'BuPu']
1105    elif varn == 'prprof' or varn == 'vprecip' or varn == 'LVPRECIP':
1106        varvals = ['prprof', 'precipitation_profile', 0., 1.e-3,                     \
1107          'precipitation|profile', 'kg/m2/s', 'BuPu']
1108    elif varn == 'prprofci' or varn == 'pr_con_i' or varn == 'LPR_CON_I':
1109        varvals = ['prprofci', 'precipitation_profile_convective_i', 0., 1.e-3,      \
1110          'precipitation|profile|convective|i', 'kg/m2/s', 'BuPu']
1111    elif varn == 'prprofcl' or varn == 'pr_con_l' or varn == 'LPR_CON_L':
1112        varvals = ['prprofcl', 'precipitation_profile_convective_l', 0., 1.e-3,      \
1113          'precipitation|profile|convective|l', 'kg/m2/s', 'BuPu']
1114    elif varn == 'prprofli' or varn == 'pr_lsc_i' or varn == 'LPR_LSC_I':
1115        varvals = ['prprofli', 'precipitation_profile_large_scale_i', 0., 1.e-3,     \
1116          'precipitation|profile|large|scale|i', 'kg/m2/s', 'BuPu']
1117    elif varn == 'prprofll' or varn == 'pr_lsc_l' or varn == 'LPR_LSC_L':
1118        varvals = ['prprofll', 'precipitation_profile_large_scale_l', 0., 1.e-3,     \
1119          'precipitation|profile|large|scale|l', 'kg/m2/s', 'BuPu']
1120    elif varn == 'pracc' or varn == 'ACRAINTOT':
1121        varvals = ['pracc', 'precipitation_amount', 0., 100.,                        \
1122          'accumulated|precipitation', 'kgm-2', 'BuPu']
1123    elif varn == 'prc' or varn == 'LPLUC' or varn == 'pluc' or varn == 'WRFprc' or   \
1124      varn == 'RAINCde':
1125        varvals = ['prc', 'convective_precipitation_flux', 0., 2.e-4,                \
1126          'convective|precipitation|flux', 'kgm-2s-1', 'Blues']
1127    elif varn == 'prci' or varn == 'pr_con_i' or varn == 'LPR_CON_I':
1128        varvals = ['prci', 'convective_ice_precipitation_flux', 0., 0.003,           \
1129          'convective|ice|precipitation|flux', 'kgm-2s-1', 'Purples']
1130    elif varn == 'prcl' or varn == 'pr_con_l' or varn == 'LPR_CON_L':
1131        varvals = ['prcl', 'convective_liquid_precipitation_flux', 0., 0.003,        \
1132          'convective|liquid|precipitation|flux', 'kgm-2s-1', 'Blues']
1133    elif varn == 'pres' or varn == 'presnivs' or varn == 'pressure' or               \
1134      varn == 'lpres' or varn == 'LPRES':
1135        varvals = ['pres', 'air_pressure', 0., 103000., 'air|pressure', 'Pa',        \
1136          'Blues']
1137    elif varn == 'prls' or varn == 'WRFprls' or varn == 'LPLUL' or varn == 'plul' or \
1138       varn == 'RAINNCde':
1139        varvals = ['prls', 'large_scale_precipitation_flux', 0., 2.e-4,              \
1140          'large|scale|precipitation|flux', 'kgm-2s-1', 'Blues']
1141    elif varn == 'prsn' or varn == 'SNOW' or varn == 'snow' or varn == 'LSNOW':
1142        varvals = ['prsn', 'snowfall', 0., 1.e-4, 'snowfall|flux', 'kgm-2s-1', 'BuPu']
1143    elif varn == 'prw' or varn == 'WRFprh':
1144        varvals = ['prw', 'atmosphere_water_vapor_content', 0., 10.,                 \
1145          'water|vapor"path', 'kgm-2', 'Blues']
1146    elif varn == 'ps' or varn == 'psfc' or varn =='PSFC' or varn == 'psol' or        \
1147      varn == 'Surface Pressure':
1148        varvals=['ps', 'surface_air_pressure', 85000., 105400., 'surface|pressure',  \
1149          'hPa', 'cool']
1150    elif varn == 'psl' or varn == 'mslp' or varn =='WRFmslp':
1151        varvals=['psl', 'air_pressure_at_sea_level', 85000., 104000.,                \
1152          'mean|sea|level|pressure', 'Pa', 'Greens']
1153    elif varn == 'qth' or varn == 'q_th' or varn == 'LQ_TH':
1154        varvals = ['qth', 'thermal_plume_total_water_content', 0., 25.,              \
1155          'total|water|cotent|in|thermal|plume', 'mm', 'YlOrRd']
1156    elif varn == 'r' or varn == 'QVAPOR' or varn == 'ovap' or varn == 'LOVAP':
1157        varvals = ['r', 'water_mixing_ratio', 0., 0.03, 'water|mixing|ratio',        \
1158          'kgkg-1', 'BuPu']
1159    elif varn == 'r2' or varn == 'Q2':
1160        varvals = ['r2', 'water_mixing_ratio_at_2m', 0., 0.03, 'water|mixing|' +     \
1161          'ratio|at|2|m','kgkg-1', 'BuPu']
1162    elif varn == 'rsds' or varn == 'SWdnSFC' or varn == 'SWdn at surface' or         \
1163      varn == 'SWDOWN':
1164        varvals=['rsds', 'surface_downwelling_shortwave_flux_in_air',  0., 1200.,    \
1165          'downward|SW|surface|radiation', 'Wm-2' ,'Reds']
1166    elif varn == 'rsdsacc':
1167        varvals=['rsdsacc', 'accumulated_surface_downwelling_shortwave_flux_in_air', \
1168          0., 1200., 'accumulated|downward|SW|surface|radiation', 'Wm-2' ,'Reds']
1169    elif varn == 'rvor' or varn == 'WRFrvor':
1170        varvals = ['rvor', 'air_relative_vorticity', -2.5E-3, 2.5E-3,                \
1171          'air|relative|vorticity', 's-1', 'seismic']
1172    elif varn == 'rvors' or varn == 'WRFrvors':
1173        varvals = ['rvors', 'surface_air_relative_vorticity', -2.5E-3, 2.5E-3,       \
1174          'surface|air|relative|vorticity', 's-1', 'seismic']
1175    elif varn == 's' or varn == 'QSNOW':
1176        varvals = ['s', 'snow_mixing_ratio', 0., 0.0003, 'snow|mixing|ratio',        \
1177          'kgkg-1', 'Purples']
1178    elif varn == 'stherm' or varn == 'LS_THERM':
1179        varvals = ['stherm', 'thermals_excess', 0., 0.8, 'thermals|excess', 'K',     \
1180          'Reds']
1181    elif varn == 'ta' or varn == 'WRFt' or varn == 'temp' or varn == 'LTEMP' or      \
1182      varn == 'Air temperature':
1183        varvals = ['ta', 'air_temperature', 195., 320., 'air|temperature', 'K',      \
1184          'YlOrRd']
1185    elif varn == 'tah' or varn == 'theta' or varn == 'LTHETA':
1186        varvals = ['tah', 'potential_air_temperature', 195., 320.,                   \
1187          'potential|air|temperature', 'K', 'YlOrRd']
1188    elif varn == 'tas' or varn == 'T2' or varn == 't2m' or varn == 'T2M' or          \
1189      varn == 'Temperature 2m':
1190        varvals = ['tas', 'air_temperature', 240., 310., 'air|temperature|at|2m', \
1191          K', 'YlOrRd']
1192    elif varn == 'tds' or varn == 'TH2':
1193        varvals = ['tds', 'air_dew_point_temperature', 240., 310.,                   \
1194          'air|dew|point|temperature|at|2m', 'K', 'YlGnBu']
1195    elif varn == 'tke' or varn == 'TKE' or varn == 'tke' or varn == 'LTKE':
1196        varvals = ['tke', 'turbulent_kinetic_energy', 0., 0.003,                     \
1197          'turbulent|kinetic|energy', 'm2/s2', 'Reds']
1198    elif varn == 'time'or varn == 'time_counter':
1199        varvals = ['time', 'time', 0., 1000., 'time',                                \
1200          'hours|since|1949/12/01|00:00:00', 'Reds']
1201    elif varn == 'tmla' or varn == 's_pblt' or varn == 'LS_PBLT':
1202        varvals = ['tmla', 'atmosphere_top_boundary_layer_temperature', 250., 330.,  \
1203          'atmosphere|top|boundary|layer|temperature', 'K', 'Reds']
1204    elif varn == 'ua' or varn == 'vitu' or varn == 'U' or varn == 'Zonal wind' or    \
1205      varn == 'LVITU':
1206        varvals = ['ua', 'eastward_wind', -30., 30., 'eastward|wind', 'ms-1',        \
1207          'seismic']
1208    elif varn == 'uas' or varn == 'u10m' or varn == 'U10' or varn =='Vent zonal 10m':
1209        varvals = ['uas', 'eastward_wind', -30., 30., 'eastward|2m|wind',    \
1210          'ms-1', 'seismic']
1211    elif varn == 'va' or varn == 'vitv' or varn == 'V' or varn == 'Meridional wind'  \
1212      or varn == 'LVITV':
1213        varvals = ['va', 'northward_wind', -30., 30., 'northward|wind', 'ms-1',      \
1214          'seismic']
1215    elif varn == 'vas' or varn == 'v10m' or varn == 'V10' or                         \
1216      varn =='Vent meridien 10m':
1217        varvals = ['vas', 'northward_wind', -30., 30., 'northward|2m|wind', 'ms-1',  \
1218          'seismic']
1219    elif varn == 'wakedeltaq' or varn == 'wake_deltaq' or varn == 'lwake_deltaq' or  \
1220      varn == 'LWAKE_DELTAQ':
1221        varvals = ['wakedeltaq', 'wake_delta_vapor', -0.003, 0.003,                  \
1222          'wake|delta|mixing|ratio', '-', 'seismic']
1223    elif varn == 'wakedeltat' or varn == 'wake_deltat' or varn == 'lwake_deltat' or  \
1224      varn == 'LWAKE_DELTAT':
1225        varvals = ['wakedeltat', 'wake_delta_temp', -0.003, 0.003,                   \
1226          'wake|delta|temperature', '-', 'seismic']
1227    elif varn == 'wakeh' or varn == 'wake_h' or varn == 'LWAKE_H':
1228        varvals = ['wakeh', 'wake_height', 0., 1000., 'height|of|the|wakes', 'm',    \
1229          'YlOrRd']
1230    elif varn == 'wakeomg' or varn == 'wake_omg' or varn == 'lwake_omg' or           \
1231      varn == 'LWAKE_OMG':
1232        varvals = ['wakeomg', 'wake_omega', 0., 3., 'wake|omega', \
1233          '-', 'BuGn']
1234    elif varn == 'wakes' or varn == 'wake_s' or varn == 'LWAKE_S':
1235        varvals = ['wakes', 'wake_area_fraction', 0., 0.5, 'wake|spatial|fraction',  \
1236          '1', 'BuGn']
1237    elif varn == 'wa' or varn == 'W' or varn == 'Vertical wind':
1238        varvals = ['wa', 'upward_wind', -10., 10., 'upward|wind', 'ms-1',            \
1239          'seismic']
1240    elif varn == 'wap' or varn == 'vitw' or varn == 'LVITW':
1241        varvals = ['wap', 'upward_wind', -3.e-10, 3.e-10, 'upward|wind', 'mPa-1',    \
1242          'seismic']
1243    elif varn == 'wss' or varn == 'SPDUV':
1244        varvals = ['wss', 'air_velocity',  0., 30., 'surface|horizontal|wind|speed', \
1245          'ms-1', 'Reds']
1246# Water budget
1247# Water budget de-accumulated
1248    elif varn == 'ccond' or varn == 'CCOND' or varn == 'ACCCONDde':
1249        varvals = ['ccond', 'cw_cond',  0., 30.,                                     \
1250          'cloud|water|condensation', 'mm', 'Reds']
1251    elif varn == 'wbr' or varn == 'ACQVAPORde':
1252        varvals = ['wbr', 'wbr',  0., 30., 'Water|Budget|water|wapor', 'mm', 'Blues']
1253    elif varn == 'diabh' or varn == 'DIABH' or varn == 'ACDIABHde':
1254        varvals = ['diabh', 'diabh',  0., 30., 'diabatic|heating', 'K', 'Reds']
1255    elif varn == 'wbpw' or varn == 'WBPW' or varn == 'WBACPWde':
1256        varvals = ['wbpw', 'water_budget_pw',  0., 30., 'Water|Budget|water|content',\
1257           'mms-1', 'Reds']
1258    elif varn == 'wbf' or varn == 'WBACF' or varn == 'WBACFde':
1259        varvals = ['wbf', 'water_budget_hfcqv',  0., 30.,                       \
1260          'Water|Budget|horizontal|convergence|of|water|vapour|(+,|' +   \
1261          'conv.;|-,|div.)', 'mms-1', 'Reds']
1262    elif varn == 'wbfc' or varn == 'WBFC' or varn == 'WBACFCde':
1263        varvals = ['wbfc', 'water_budget_fc',  0., 30.,                         \
1264          'Water|Budget|horizontal|convergence|of|cloud|(+,|conv.;|-,|' +\
1265          'div.)', 'mms-1', 'Reds']
1266    elif varn == 'wbfp' or varn == 'WBFP' or varn == 'WBACFPde':
1267        varvals = ['wbfp', 'water_budget_cfp',  0., 30.,                        \
1268          'Water|Budget|horizontal|convergence|of|precipitation|(+,|' +  \
1269          'conv.;|-,|div.)', 'mms-1', 'Reds']
1270    elif varn == 'wbz' or varn == 'WBZ' or varn == 'WBACZde':
1271        varvals = ['wbz', 'water_budget_z',  0., 30.,                           \
1272          'Water|Budget|vertical|convergence|of|water|vapour|(+,|conv.' +\
1273          ';|-,|div.)', 'mms-1', 'Reds']
1274    elif varn == 'wbc' or varn == 'WBC' or varn == 'WBACCde':
1275        varvals = ['wbc', 'water_budget_c',  0., 30.,                           \
1276          'Water|Budget|Cloud|water|species','mms-1', 'Reds']
1277    elif varn == 'wbqvd' or varn == 'WBQVD' or varn == 'WBACQVDde':
1278        varvals = ['wbqvd', 'water_budget_qvd',  0., 30.,                       \
1279          'Water|Budget|water|vapour|divergence', 'mms-1', 'Reds']
1280    elif varn == 'wbqvblten' or varn == 'WBQVBLTEN' or varn == 'WBACQVBLTENde':
1281        varvals = ['wbqvblten', 'water_budget_qv_blten',  0., 30.,              \
1282          'Water|Budget|QV|tendency|due|to|pbl|parameterization',        \
1283          'kg kg-1 s-1', 'Reds']
1284    elif varn == 'wbqvcuten' or varn == 'WBQVCUTEN' or varn == 'WBACQVCUTENde':
1285        varvals = ['wbqvcuten', 'water_budget_qv_cuten',  0., 30.,              \
1286          'Water|Budget|QV|tendency|due|to|cu|parameterization',         \
1287          'kg kg-1 s-1', 'Reds']
1288    elif varn == 'wbqvshten' or varn == 'WBQVSHTEN' or varn == 'WBACQVSHTENde':
1289        varvals = ['wbqvshten', 'water_budget_qv_shten',  0., 30.,              \
1290          'Water|Budget|QV|tendency|due|to|shallow|cu|parameterization', \
1291          'kg kg-1 s-1', 'Reds']
1292    elif varn == 'wbpr' or varn == 'WBP' or varn == 'WBACPde':
1293        varvals = ['wbpr', 'water_budget_pr',  0., 30.,                         \
1294          'Water|Budget|recipitation', 'mms-1', 'Reds']
1295    elif varn == 'wbpw' or varn == 'WBPW' or varn == 'WBACPWde':
1296        varvals = ['wbpw', 'water_budget_pw',  0., 30.,                         \
1297          'Water|Budget|water|content', 'mms-1', 'Reds']
1298    elif varn == 'wbcondt' or varn == 'WBCONDT' or varn == 'WBACCONDTde':
1299        varvals = ['wbcondt', 'water_budget_condt',  0., 30.,                   \
1300          'Water|Budget|condensation|and|deposition', 'mms-1', 'Reds']
1301    elif varn == 'wbqcm' or varn == 'WBQCM' or varn == 'WBACQCMde':
1302        varvals = ['wbqcm', 'water_budget_qcm',  0., 30.,                       \
1303          'Water|Budget|hydrometeor|change|and|convergence', 'mms-1', 'Reds']
1304    elif varn == 'wbsi' or varn == 'WBSI' or varn == 'WBACSIde':
1305        varvals = ['wbsi', 'water_budget_si',  0., 30.,                         \
1306          'Water|Budget|hydrometeor|sink', 'mms-1', 'Reds']
1307    elif varn == 'wbso' or varn == 'WBSO' or varn == 'WBACSOde':
1308        varvals = ['wbso', 'water_budget_so',  0., 30.,                         \
1309          'Water|Budget|hydrometeor|source', 'mms-1', 'Reds']
1310# Water Budget accumulated
1311    elif varn == 'ccondac' or varn == 'ACCCOND':
1312        varvals = ['ccondac', 'cw_cond_ac',  0., 30.,                                \
1313          'accumulated|cloud|water|condensation', 'mm', 'Reds']
1314    elif varn == 'rac' or varn == 'ACQVAPOR':
1315        varvals = ['rac', 'ac_r',  0., 30., 'accumualted|water|wapor', 'mm', 'Blues']
1316    elif varn == 'diabhac' or varn == 'ACDIABH':
1317        varvals = ['diabhac', 'diabh_ac',  0., 30., 'accumualted|diabatic|heating',  \
1318          'K', 'Reds']
1319    elif varn == 'wbpwac' or varn == 'WBACPW':
1320        varvals = ['wbpwac', 'water_budget_pw_ac',  0., 30.,                         \
1321          'Water|Budget|accumulated|water|content', 'mm', 'Reds']
1322    elif varn == 'wbfac' or varn == 'WBACF':
1323        varvals = ['wbfac', 'water_budget_hfcqv_ac',  0., 30.,                       \
1324          'Water|Budget|accumulated|horizontal|convergence|of|water|vapour|(+,|' +   \
1325          'conv.;|-,|div.)', 'mm', 'Reds']
1326    elif varn == 'wbfcac' or varn == 'WBACFC':
1327        varvals = ['wbfcac', 'water_budget_fc_ac',  0., 30.,                         \
1328          'Water|Budget|accumulated|horizontal|convergence|of|cloud|(+,|conv.;|-,|' +\
1329          'div.)', 'mm', 'Reds']
1330    elif varn == 'wbfpac' or varn == 'WBACFP':
1331        varvals = ['wbfpac', 'water_budget_cfp_ac',  0., 30.,                        \
1332          'Water|Budget|accumulated|horizontal|convergence|of|precipitation|(+,|' +  \
1333          'conv.;|-,|div.)', 'mm', 'Reds']
1334    elif varn == 'wbzac' or varn == 'WBACZ':
1335        varvals = ['wbzac', 'water_budget_z_ac',  0., 30.,                           \
1336          'Water|Budget|accumulated|vertical|convergence|of|water|vapour|(+,|conv.' +\
1337          ';|-,|div.)', 'mm', 'Reds']
1338    elif varn == 'wbcac' or varn == 'WBACC':
1339        varvals = ['wbcac', 'water_budget_c_ac',  0., 30.,                           \
1340          'Water|Budget|accumulated|Cloud|water|species','mm', 'Reds']
1341    elif varn == 'wbqvdac' or varn == 'WBACQVD':
1342        varvals = ['wbqvdac', 'water_budget_qvd_ac',  0., 30.,                       \
1343          'Water|Budget|accumulated|water|vapour|divergence', 'mm', 'Reds']
1344    elif varn == 'wbqvbltenac' or varn == 'WBACQVBLTEN':
1345        varvals = ['wbqvbltenac', 'water_budget_qv_blten_ac',  0., 30.,              \
1346          'Water|Budget|accumulated|QV|tendency|due|to|pbl|parameterization',        \
1347          'kg kg-1 s-1', 'Reds']
1348    elif varn == 'wbqvcutenac' or varn == 'WBACQVCUTEN':
1349        varvals = ['wbqvcutenac', 'water_budget_qv_cuten_ac',  0., 30.,              \
1350          'Water|Budget|accumulated|QV|tendency|due|to|cu|parameterization',         \
1351          'kg kg-1 s-1', 'Reds']
1352    elif varn == 'wbqvshtenac' or varn == 'WBACQVSHTEN':
1353        varvals = ['wbqvshtenac', 'water_budget_qv_shten_ac',  0., 30.,              \
1354          'Water|Budget|accumulated|QV|tendency|due|to|shallow|cu|parameterization', \
1355          'kg kg-1 s-1', 'Reds']
1356    elif varn == 'wbprac' or varn == 'WBACP':
1357        varvals = ['wbprac', 'water_budget_pr_ac',  0., 30.,                         \
1358          'Water|Budget|accumulated|precipitation', 'mm', 'Reds']
1359    elif varn == 'wbpwac' or varn == 'WBACPW':
1360        varvals = ['wbpwac', 'water_budget_pw_ac',  0., 30.,                         \
1361          'Water|Budget|accumulated|water|content', 'mm', 'Reds']
1362    elif varn == 'wbcondtac' or varn == 'WBACCONDT':
1363        varvals = ['wbcondtac', 'water_budget_condt_ac',  0., 30.,                   \
1364          'Water|Budget|accumulated|condensation|and|deposition', 'mm', 'Reds']
1365    elif varn == 'wbqcmac' or varn == 'WBACQCM':
1366        varvals = ['wbqcmac', 'water_budget_qcm_ac',  0., 30.,                       \
1367          'Water|Budget|accumulated|hydrometeor|change|and|convergence', 'mm', 'Reds']
1368    elif varn == 'wbsiac' or varn == 'WBACSI':
1369        varvals = ['wbsiac', 'water_budget_si_ac',  0., 30.,                         \
1370          'Water|Budget|accumulated|hydrometeor|sink', 'mm', 'Reds']
1371    elif varn == 'wbsoac' or varn == 'WBACSO':
1372        varvals = ['wbsoac', 'water_budget_so_ac',  0., 30.,                         \
1373          'Water|Budget|accumulated|hydrometeor|source', 'mm', 'Reds']
1374
1375    elif varn == 'xtime' or varn == 'XTIME':
1376        varvals = ['xtime', 'time',  0., 1.e5, 'time',                               \
1377          'minutes|since|simulation|start', 'Reds']
1378    elif varn == 'x' or varn == 'X':
1379        varvals = ['x', 'x',  0., 100., 'x', '-', 'Reds']
1380    elif varn == 'y' or varn == 'Y':
1381        varvals = ['y', 'y',  0., 100., 'y', '-', 'Blues']
1382    elif varn == 'z' or varn == 'Z':
1383        varvals = ['z', 'z',  0., 100., 'z', '-', 'Greens']
1384    elif varn == 'zg' or varn == 'WRFght' or varn == 'Geopotential height' or        \
1385      varn == 'geop' or varn == 'LGEOP':
1386        varvals = ['zg', 'geopotential_height', 0., 80000., 'geopotential|height',   \
1387          'm2s-2', 'rainbow']
1388    elif varn == 'zmaxth' or varn == 'zmax_th'  or varn == 'LZMAX_TH':
1389        varvals = ['zmaxth', 'thermal_plume_height', 0., 4000.,                     \
1390          'maximum|thermals|plume|height', 'm', 'YlOrRd']
1391    elif varn == 'zmla' or varn == 's_pblh' or varn == 'LS_PBLH':
1392        varvals = ['zmla', 'atmosphere_boundary_layer_thickness', 0., 2500.,         \
1393          'atmosphere|boundary|layer|thickness', 'm', 'Blues']
1394    else:
1395        print errormsg
1396        print '  ' + fname + ": variable '" + varn + "' not defined !!!"
1397        quit(-1)
1398
1399    return varvals
1400
1401def lonlat2D(lon,lat):
1402    """ Function to return lon, lat 2D matrices from any lon,lat matrix
1403      lon= matrix with longitude values
1404      lat= matrix with latitude values
1405    """
1406    fname = 'lonlat2D'
1407
1408    if len(lon.shape) != len(lat.shape):
1409        print errormsg
1410        print '  ' + fname + ': longitude values with shape:', lon.shape,            \
1411          'is different that latitude values with shape:', lat.shape, '(dif. size) !!'
1412        quit(-1)
1413
1414    if len(lon.shape) == 3:
1415        lonvv = lon[0,:,:]
1416        latvv = lat[0,:,:]
1417    elif len(lon.shape) == 2:
1418        lonvv = lon[:]
1419        latvv = lat[:]
1420    elif len(lon.shape) == 1:
1421        lonlatv = np.meshgrid(lon[:],lat[:])
1422        lonvv = lonlatv[0]
1423        latvv = lonlatv[1]
1424
1425    return lonvv, latvv
1426
1427#######    #######    #######    #######    #######    #######    #######    #######    #######    #######
1428
1429def check_colorBar(cbarn):
1430    """ Check if the given colorbar exists in matplotlib
1431    """
1432    fname = 'check_colorBar'
1433
1434# Possible color bars
1435    colorbars = ['binary', 'Blues', 'BuGn', 'BuPu', 'gist_yarg', 'GnBu', 'Greens',   \
1436      'Greys', 'Oranges', 'OrRd', 'PuBu', 'PuBuGn', 'PuRd', 'Purples', 'RdPu',       \
1437      'Reds', 'YlGn', 'YlGnBu', 'YlOrBr', 'YlOrRd', 'afmhot', 'autumn', 'bone',      \
1438      'cool', 'copper', 'gist_gray', 'gist_heat', 'gray', 'hot', 'pink', 'spring',   \
1439      'summer', 'winter', 'BrBG', 'bwr', 'coolwarm', 'PiYG', 'PRGn', 'PuOr', 'RdBu', \
1440      'RdGy', 'RdYlBu', 'RdYlGn', 'seismic', 'Accent', 'Dark2', 'hsv', 'Paired',     \
1441      'Pastel1', 'Pastel2', 'Set1', 'Set2', 'Set3', 'spectral', 'gist_earth',        \
1442      'gist_ncar', 'gist_rainbow', 'gist_stern', 'jet', 'brg', 'CMRmap', 'cubehelix',\
1443      'gnuplot', 'gnuplot2', 'ocean', 'rainbow', 'terrain', 'flag', 'prism']
1444
1445    if not searchInlist(colorbars,cbarn):
1446        print warnmsg
1447        print '  ' + fname + ' color bar: "' + cbarn + '" does not exist !!'
1448        print '  a standard one will be use instead !!'
1449
1450    return
1451
1452def units_lunits(u):
1453    """ Fucntion to provide LaTeX equivalences from a given units
1454      u= units to transform
1455    >>> units_lunits('kgkg-1')
1456    '$kgkg^{-1}$'   
1457    """
1458    fname = 'units_lunits'
1459
1460    if u == 'h':
1461        print fname + '_____________________________________________________________'
1462        print units_lunits.__doc__
1463        quit()
1464
1465# Units which does not change
1466    same = ['1', 'category', 'day', 'deg', 'degree', 'degrees', 'degrees East',      \
1467      'degrees Nord', 'degrees North', 'g', 'gpm', 'hour', 'hPa', 'K', 'Km', 'kg',   \
1468      'km', 'm', 'minute', 'mm', 'month', 'Pa', 's', 'second', 'um', 'year', '-']
1469
1470    if searchInlist(same,u):
1471        lu = '$' + u + '$'
1472    elif len(u.split(' ')) > 1 and u.split(' ')[1] == 'since':
1473        uparts = u.split(' ')
1474        ip=0
1475        for up in uparts:
1476            if ip == 0:
1477               lu = '$' + up
1478            else:
1479               lu = lu + '\ ' + up
1480            ip=ip+1
1481        lu = lu + '$'
1482    else:
1483        if u == '': lu='-'
1484        elif u == 'C': lu='$^{\circ}C$'
1485        elif u == 'days': lu='$day$'
1486        elif u == 'degrees_east': lu='$degrees\ East$'
1487        elif u == 'degree_east': lu='$degrees\ East$'
1488        elif u == 'degrees longitude': lu='$degrees\ East$'
1489        elif u == 'degrees latitude': lu='$degrees\ North$'
1490        elif u == 'degrees_north': lu='$degrees\ North$'
1491        elif u == 'degree_north': lu='$degrees\ North$'
1492        elif u == 'deg C': lu='$^{\circ}C$'
1493        elif u == 'degC': lu='$^{\circ}C$'
1494        elif u == 'deg K': lu='$K$'
1495        elif u == 'degK': lu='$K$'
1496        elif u == 'g/g': lu='$gg^{-1}$'
1497        elif u == 'hours': lu='$hour$'
1498        elif u == 'J/kg': lu='$Jkg^{-1}$'
1499        elif u == 'Jkg-1': lu='$Jkg^{-1}$'
1500        elif u == 'K/m': lu='$Km^{-1}$'
1501        elif u == 'Km-1': lu='$Km^{-1}$'
1502        elif u == 'K/s': lu='$Ks^{-1}$'
1503        elif u == 'Ks-1': lu='$Ks^{-1}$'
1504        elif u == 'K s-1': lu='$Ks^{-1}$'
1505        elif u == 'kg/kg': lu='$kgkg^{-1}$'
1506        elif u == 'kgkg-1': lu='$kgkg^{-1}$'
1507        elif u == 'kg kg-1': lu='$kgkg^{-1}$'
1508        elif u == '(kg/kg)/s': lu='$kgkg^{-1}s^{-1}$'
1509        elif u == 'kgkg-1s-1': lu='$kgkg^{-1}s^{-1}$'
1510        elif u == 'kg kg-1 s-1': lu='$kgkg^{-1}s^{-1}$'
1511        elif u == 'kg/m2': lu='$kgm^{-2}$'
1512        elif u == 'kgm-2': lu='$kgm^{-2}$'
1513        elif u == 'kg m-2': lu='$kgm^{-2}$'
1514        elif u == 'Kg m-2': lu='$kgm^{-2}$'
1515        elif u == 'kg/m2/s': lu='$kgm^{-2}s^{-1}$'
1516        elif u == 'kg/(m2*s)': lu='$kgm^{-2}s^{-1}$'
1517        elif u == 'kg/(s*m2)': lu='$kgm^{-2}s^{-1}$'
1518        elif u == 'kgm-2s-1': lu='$kgm^{-2}s^{-1}$'
1519        elif u == 'kg m-2 s-1': lu='$kgm^{-2}s^{-1}$'
1520        elif u == '1/m': lu='$m^{-1}$'
1521        elif u == 'm-1': lu='$m^{-1}$'
1522        elif u == 'm^2': lu='$m^{2}$'
1523        elif u == 'm2/s': lu='$m2s^{-1}$'
1524        elif u == 'm2s-1': lu='$m2s^{-1}$'
1525        elif u == 'm2/s2': lu='$m2s^{-2}$'
1526        elif u == 'm/s': lu='$ms^{-1}$'
1527        elif u == 'mmh-3': lu='$mmh^{-3}$'
1528        elif u == 'ms-1': lu='$ms^{-1}$'
1529        elif u == 'm s-1': lu='$ms^{-1}$'
1530        elif u == 'm/s2': lu='$ms^{-2}$'
1531        elif u == 'ms-2': lu='$ms^{-2}$'
1532        elif u == 'minutes': lu='$minute$'
1533        elif u == 'Pa/s': lu='$Pas^{-1}$'
1534        elif u == 'Pas-1': lu='$Pas^{-1}$'
1535        elif u == 'W m-2': lu='$Wm^{-2}$'
1536        elif u == 'Wm-2': lu='$Wm^{-2}$'
1537        elif u == 'W/m2': lu='$Wm^{-2}$'
1538        elif u == '1/s': lu='$s^{-1}$'
1539        elif u == 's-1': lu='$s^{-1}$'
1540        elif u == 'seconds': lu='$second$'
1541        elif u == '%': lu='\%'
1542        elif u == '?': lu='-'
1543        else:
1544            print errormsg
1545            print '  ' + fname + ': units "' + u + '" not ready!!!!'
1546            quit(-1)
1547
1548    return lu
1549
1550def ASCII_LaTeX(ln):
1551    """ Function to transform from an ASCII line to LaTeX codification
1552      >>> ASCII_LaTeX('Laboratoire de Météorologie Dynamique però Hovmöller')
1553      Laboratoire de M\'et\'eorologie Dynamique per\`o Hovm\"oller
1554    """
1555    fname='ASCII_LaTeX'
1556
1557    if ln == 'h':
1558        print fname + '_____________________________________________________________'
1559        print ASCII_LaTeX.__doc__
1560        quit()
1561
1562    newln = ln.replace('\\', '\\textbackslash')
1563
1564    newln = newln.replace('á', "\\'a")
1565    newln = newln.replace('é', "\\'e")
1566    newln = newln.replace('í', "\\'i")
1567    newln = newln.replace('ó', "\\'o")
1568    newln = newln.replace('ú', "\\'u")
1569
1570    newln = newln.replace('à', "\\`a")
1571    newln = newln.replace('Ú', "\\`e")
1572    newln = newln.replace('ì', "\\`i")
1573    newln = newln.replace('ò', "\\`o")
1574    newln = newln.replace('ù', "\\`u")
1575
1576    newln = newln.replace('â', "\\^a")
1577    newln = newln.replace('ê', "\\^e")
1578    newln = newln.replace('î', "\\^i")
1579    newln = newln.replace('ÃŽ', "\\^o")
1580    newln = newln.replace('û', "\\^u")
1581
1582    newln = newln.replace('À', '\\"a')
1583    newln = newln.replace('ë', '\\"e')
1584    newln = newln.replace('ï', '\\"i')
1585    newln = newln.replace('ö', '\\"o')
1586    newln = newln.replace('ÃŒ', '\\"u')
1587
1588    newln = newln.replace('ç', '\c{c}')
1589    newln = newln.replace('ñ', '\~{n}')
1590
1591    newln = newln.replace('Á', "\\'A")
1592    newln = newln.replace('É', "\\'E")
1593    newln = newln.replace('Í', "\\'I")
1594    newln = newln.replace('Ó', "\\'O")
1595    newln = newln.replace('Ú', "\\'U")
1596
1597    newln = newln.replace('À', "\\`A")
1598    newln = newln.replace('È', "\\`E")
1599    newln = newln.replace('Ì', "\\`I")
1600    newln = newln.replace('Ò', "\\`O")
1601    newln = newln.replace('Ù', "\\`U")
1602
1603    newln = newln.replace('Â', "\\^A")
1604    newln = newln.replace('Ê', "\\^E")
1605    newln = newln.replace('Î', "\\^I")
1606    newln = newln.replace('Ô', "\\^O")
1607    newln = newln.replace('Û', "\\^U")
1608
1609    newln = newln.replace('Ä', '\\"A')
1610    newln = newln.replace('Ë', '\\"E')
1611    newln = newln.replace('Ï', '\\"I')
1612    newln = newln.replace('Ö', '\\"O')
1613    newln = newln.replace('Ü', '\\"U')
1614
1615    newln = newln.replace('Ç', '\\c{C}')
1616    newln = newln.replace('Ñ', '\\~{N}')
1617
1618    newln = newln.replace('¡', '!`')
1619    newln = newln.replace('¿', '¿`')
1620    newln = newln.replace('%', '\\%')
1621    newln = newln.replace('#', '\\#')
1622    newln = newln.replace('&', '\\&')
1623    newln = newln.replace('$', '\\$')
1624    newln = newln.replace('_', '\\_')
1625    newln = newln.replace('·', '\\textperiodcentered')
1626    newln = newln.replace('<', '$<$')
1627    newln = newln.replace('>', '$>$')
1628    newln = newln.replace('', '*')
1629#    newln = newln.replace('º', '$^{\\circ}$')
1630    newln = newln.replace('ª', '$^{a}$')
1631    newln = newln.replace('º', '$^{o}$')
1632    newln = newln.replace('°', '$^{\\circ}$')
1633    newln = newln.replace('\n', '\\\\\n')
1634    newln = newln.replace('\t', '\\medskip')
1635
1636    return newln
1637
1638def pretty_int(minv,maxv,Nint):
1639    """ Function to plot nice intervals
1640      minv= minimum value
1641      maxv= maximum value
1642      Nint= number of intervals
1643    >>> pretty_int(23.50,67.21,5)
1644    [ 25.  30.  35.  40.  45.  50.  55.  60.  65.]
1645    >>> pretty_int(-23.50,67.21,15)
1646    [  0.  20.  40.  60.]
1647    pretty_int(14.75,25.25,5)
1648    [ 16.  18.  20.  22.  24.]
1649    """ 
1650    fname = 'pretty_int'
1651    nice_int = [1,2,5]
1652
1653#    print 'minv: ',minv,'maxv:',maxv,'Nint:',Nint
1654
1655    interval = np.abs(maxv - minv)
1656
1657    potinterval = np.log10(interval)
1658    Ipotint = int(potinterval)
1659    intvalue = np.float(interval / np.float(Nint))
1660
1661# new
1662    potinterval = np.log10(intvalue)
1663    Ipotint = int(potinterval)
1664
1665#    print 'interval:', interval, 'intavlue:', intvalue, 'potinterval:', potinterval, \
1666#     'Ipotint:', Ipotint, 'intvalue:', intvalue
1667
1668    mindist = 10.e15
1669    for inice in nice_int:
1670#        print inice,':',inice*10.**Ipotint,np.abs(inice*10.**Ipotint - intvalue),mindist
1671        if np.abs(inice*10.**Ipotint - intvalue) < mindist:
1672            mindist = np.abs(inice*10.**Ipotint - intvalue)
1673            closestint = inice
1674
1675    Ibeg = int(minv / (closestint*10.**Ipotint))
1676
1677    values = []
1678    val = closestint*(Ibeg)*10.**(Ipotint)
1679
1680#    print 'closestint:',closestint,'Ibeg:',Ibeg,'val:',val
1681
1682    while val < maxv:
1683        values.append(val)
1684        val = val + closestint*10.**Ipotint
1685
1686    return np.array(values, dtype=np.float)
1687
1688def DegGradSec_deg(grad,deg,sec):
1689    """ Function to transform from a coordinate in grad deg sec to degrees (decimal)
1690    >>> DegGradSec_deg(39.,49.,26.)
1691    39.8238888889
1692    """
1693    fname = 'DegGradSec_deg'
1694
1695    if grad == 'h':
1696        print fname + '_____________________________________________________________'
1697        print DegGradSec_deg.__doc__
1698        quit()
1699
1700    deg = grad + deg/60. + sec/3600.
1701
1702    return deg
1703
1704def intT2dt(intT,tu):
1705    """ Function to provide an 'timedelta' object from a given interval value
1706      intT= interval value
1707      tu= interval units, [tu]= 'd': day, 'w': week, 'h': hour, 'i': minute, 's': second,
1708        'l': milisecond
1709
1710      >>> intT2dt(3.5,'s')
1711      0:00:03.500000
1712
1713      >>> intT2dt(3.5,'w')
1714      24 days, 12:00:00
1715    """
1716    import datetime as dt 
1717
1718    fname = 'intT2dt'
1719
1720    if tu == 'w':
1721        dtv = dt.timedelta(weeks=np.float(intT))
1722    elif tu == 'd':
1723        dtv = dt.timedelta(days=np.float(intT))
1724    elif tu == 'h':
1725        dtv = dt.timedelta(hours=np.float(intT))
1726    elif tu == 'i':
1727        dtv = dt.timedelta(minutes=np.float(intT))
1728    elif tu == 's':
1729        dtv = dt.timedelta(seconds=np.float(intT))
1730    elif tu == 'l':
1731        dtv = dt.timedelta(milliseconds=np.float(intT))
1732    else:
1733        print errormsg
1734        print '  ' + fname + ': time units "' + tu + '" not ready!!!!'
1735        quit(-1)
1736
1737    return dtv
1738
1739def lonlat_values(mapfile,lonvn,latvn):
1740    """ Function to obtain the lon/lat matrices from a given netCDF file
1741    lonlat_values(mapfile,lonvn,latvn)
1742      [mapfile]= netCDF file name
1743      [lonvn]= variable name with the longitudes
1744      [latvn]= variable name with the latitudes
1745    """
1746
1747    fname = 'lonlat_values'
1748
1749    if mapfile == 'h':
1750        print fname + '_____________________________________________________________'
1751        print lonlat_values.__doc__
1752        quit()
1753
1754    if not os.path.isfile(mapfile):
1755        print errormsg
1756        print '  ' + fname + ": map file '" + mapfile + "' does not exist !!"
1757        quit(-1)
1758
1759    ncobj = NetCDFFile(mapfile, 'r')
1760    lonobj = ncobj.variables[lonvn]
1761    latobj = ncobj.variables[latvn]
1762
1763    if len(lonobj.shape) == 3:
1764        lonv = lonobj[0,:,:]
1765        latv = latobj[0,:,:]
1766    elif len(lonobj.shape) == 2:
1767        lonv = lonobj[:,:]
1768        latv = latobj[:,:]
1769    elif len(lonobj.shape) == 1:
1770        lon0 = lonobj[:]
1771        lat0 = latobj[:]
1772        lonv = np.zeros( (len(lat0),len(lon0)), dtype=np.float )
1773        latv = np.zeros( (len(lat0),len(lon0)), dtype=np.float )
1774        for iy in range(len(lat0)):
1775            lonv[iy,:] = lon0
1776        for ix in range(len(lon0)):
1777            latv[:,ix] = lat0
1778    else:
1779        print errormsg
1780        print '  ' + fname + ': lon/lat variables shape:',lonobj.shape,'not ready!!'
1781        quit(-1)
1782
1783    return lonv, latv
1784
1785def date_CFtime(ind,refd,tunits):
1786    """ Function to transform from a given date object a CF-convention time
1787      ind= date object to transform
1788      refd= reference date
1789      tunits= units for time
1790        >>> date_CFtime(dt.datetime(1976,02,17,08,30,00), dt.datetime(1949,12,01,00,00,00), 'seconds')
1791        827224200.0
1792    """
1793    import datetime as dt
1794
1795    fname = 'date_CFtime'
1796
1797    dt = ind - refd
1798
1799    if tunits == 'weeks':
1800        value = dt.days/7. + dt.seconds/(3600.*24.*7.)
1801    elif tunits == 'days':
1802        value = dt.days + dt.seconds/(3600.*24.)
1803    elif tunits == 'hours':
1804        value = dt.days*24. + dt.seconds/(3600.)
1805    elif tunits == 'minutes':
1806        value = dt.days*24.*60. + dt.seconds/(60.)
1807    elif tunits == 'seconds':
1808        value = dt.days*24.*3600. + dt.seconds
1809    elif tunits == 'milliseconds':
1810        value = dt.days*24.*3600.*1000. + dt.seconds*1000.
1811    else:
1812        print errormsg
1813        print '  ' + fname + ': reference time units "' + trefu + '" not ready!!!!'
1814        quit(-1)
1815
1816    return value
1817
1818def pot_values(values, uvals):
1819    """ Function to modify a seies of values by their potency of 10
1820      pot_values(values, uvals)
1821      values= values to modify
1822      uvals= units of the values
1823      >>> vals = np.sin(np.arange(20)*np.pi/5.+0.01)*10.e-5
1824      >>> pot_values(vals,'ms-1')
1825      (array([  0.00000000e+00,   5.87785252e-01,   9.51056516e-01,
1826         9.51056516e-01,   5.87785252e-01,   1.22464680e-16,
1827        -5.87785252e-01,  -9.51056516e-01,  -9.51056516e-01,
1828        -5.87785252e-01,  -2.44929360e-16,   5.87785252e-01,
1829         9.51056516e-01,   9.51056516e-01,   5.87785252e-01,
1830         3.67394040e-16,  -5.87785252e-01,  -9.51056516e-01,
1831        -9.51056516e-01,  -5.87785252e-01]), -4, 'x10e-4 ms-1', 'x10e-4')
1832    """
1833
1834    fname = 'pot_values'
1835
1836    if np.min(values) != 0.:
1837        potmin = int( np.log10( np.abs(np.min(values)) ) )
1838    else:
1839        potmin = 0
1840
1841    if np.max(values) != 0.:
1842        potmax = int( np.log10( np.abs(np.max(values)) ) )
1843    else:
1844        potmax = 0
1845
1846    if potmin * potmax > 9:
1847        potval = -np.min([np.abs(potmin), np.abs(potmax)]) * np.abs(potmin) / potmin
1848
1849        newvalues = values*10.**potval
1850        potvalue = - potval
1851        potS = 'x10e' + str(potvalue)
1852        newunits = potS + ' ' + uvals
1853    else:
1854        newvalues = values
1855        potvalue = None
1856        potS = ''
1857        newunits = uvals
1858
1859    return newvalues, potvalue, newunits, potS
1860
1861def CFtimes_plot(timev,units,kind,tfmt):
1862    """ Function to provide a list of string values from a CF time values in order
1863      to use them in a plot, according to the series of characteristics.
1864      String outputs will be suited to the 'human-like' output
1865        timev= time values (real values)
1866        units= units string according to CF conventions ([tunits] since
1867          [YYYY]-[MM]-[DD] [[HH]:[MI]:[SS]])
1868        kind= kind of output
1869          'Nval': according to a given number of values as 'Nval',[Nval]
1870          'exct': according to an exact time unit as 'exct',[tunit];
1871            tunit= [Nunits],[tu]; [tu]= 'c': centuries, 'y': year, 'm': month,
1872              'w': week, 'd': day, 'h': hour, 'i': minute, 's': second,
1873              'l': milisecond
1874        tfmt= desired format
1875          >>> CFtimes_plot(np.arange(100)*1.,'hours since 1979-12-01 00:00:00', 'Nval,5',"%Y/%m/%d %H:%M:%S")
1876            0.0 1979/12/01 00:00:00
1877            24.75 1979/12/02 00:45:00
1878            49.5 1979/12/03 01:30:00
1879            74.25 1979/12/04 02:15:00
1880            99.0 1979/12/05 03:00:00
1881          >>> CFtimes_plot(np.arange(100)*1.,'hours since 1979-12-01 00:00:00', 'exct,2,d',"%Y/%m/%d %H:%M:%S")
1882            0.0 1979/12/01 00:00:00
1883            48.0 1979/12/03 00:00:00
1884            96.0 1979/12/05 00:00:00
1885            144.0 1979/12/07 00:00:00
1886    """ 
1887    import datetime as dt 
1888
1889# Seconds between 0001 and 1901 Jan - 01
1890    secs0001_1901=59958144000.
1891
1892    fname = 'CFtimes_plot'
1893
1894    if timev == 'h':
1895        print fname + '_____________________________________________________________'
1896        print CFtimes_plot.__doc__
1897        quit()
1898
1899    secsYear = 365.*24.*3600.
1900    secsWeek = 7.*24.*3600.
1901    secsDay = 24.*3600.
1902    secsHour = 3600.
1903    secsMinute = 60.
1904    secsMilisecond = 1./1000.
1905    secsMicrosecond = 1./1000000.
1906
1907# Does reference date contain a time value [YYYY]-[MM]-[DD] [HH]:[MI]:[SS]
1908##
1909    trefT = units.find(':')
1910    txtunits = units.split(' ')
1911    Ntxtunits = len(txtunits)
1912
1913    if Ntxtunits == 3:
1914        Srefdate = txtunits[Ntxtunits - 1]
1915    else:
1916        Srefdate = txtunits[Ntxtunits - 2]
1917
1918    if not trefT == -1:
1919#        print '  ' + fname + ': refdate with time!'
1920        if Ntxtunits == 3:
1921            refdate = datetimeStr_datetime(Srefdate)
1922        else:
1923            refdate = datetimeStr_datetime(Srefdate + '_' + txtunits[Ntxtunits - 1])
1924    else:
1925        refdate = datetimeStr_datetime(Srefdate + '_00:00:00')
1926
1927    trefunits=units.split(' ')[0]
1928    if trefunits == 'weeks':
1929        trefu = 'w'
1930    elif trefunits == 'days':
1931        trefu = 'd'
1932    elif trefunits == 'hours':
1933        trefu = 'h'
1934    elif trefunits == 'minutes':
1935        trefu = 'm'
1936    elif trefunits == 'seconds':
1937        trefu = 's'
1938    elif trefunits == 'milliseconds':
1939        trefu = 'l'
1940    else:
1941        print errormsg
1942        print '  ' + fname + ': reference time units "' + trefu + '" not ready!!!!'
1943        quit(-1)
1944
1945    okind=kind.split(',')[0]
1946    dtv = len(timev)
1947 
1948    if refdate.year == 1:
1949        print warnmsg
1950        print '  ' + fname + ': changing reference date: ',refdate,                  \
1951          'to 1901-01-01_00:00:00 !!!'
1952        refdate = datetimeStr_datetime('1901-01-01_00:00:00')
1953        if trefu == 'w': timev = timev - secs0001_1901/(7.*24.*3600.)
1954        if trefu == 'd': timev = timev - secs0001_1901/(24.*3600.)
1955        if trefu == 'h': timev = timev - secs0001_1901/(3600.)
1956        if trefu == 'm': timev = timev - secs0001_1901/(60.)
1957        if trefu == 's': timev = timev - secs0001_1901
1958        if trefu == 'l': timev = timev - secs0001_1901*1000.
1959
1960    firstT = timev[0]
1961    lastT = timev[dtv-1]
1962
1963# First and last times as datetime objects
1964    firstTdt = timeref_datetime(refdate, firstT, trefunits)
1965    lastTdt = timeref_datetime(refdate, lastT, trefunits)
1966
1967# First and last times as [year, mon, day, hour, minut, second] vectors
1968    firstTvec = np.zeros((6), dtype= np.float)
1969    lastTvec = np.zeros((6), dtype= np.float)
1970    chTvec = np.zeros((6), dtype= bool)
1971
1972    firstTvec = np.array([firstTdt.year, firstTdt.month, firstTdt.day, firstTdt.hour,\
1973      firstTdt.minute, firstTdt.second])
1974    lastTvec = np.array([lastTdt.year, lastTdt.month, lastTdt.day, lastTdt.hour,     \
1975      lastTdt.minute, lastTdt.second])
1976
1977    chdate= lastTvec - firstTvec
1978    chTvec = np.where (chdate != 0., True, False)
1979   
1980    TOTdt = lastTdt - firstTdt
1981    TOTdtsecs = TOTdt.days*secsDay + TOTdt.seconds + TOTdt.microseconds*secsMicrosecond
1982
1983    timeout = []
1984    if okind == 'Nval':
1985        nvalues = int(kind.split(',')[1])
1986        intervT = (lastT - firstT)/(nvalues-1)
1987        dtintervT = intT2dt(intervT, trefu)
1988
1989        for it in range(nvalues):
1990            timeout.append(firstTdt + dtintervT*it)
1991    elif okind == 'exct':
1992        Nunits = int(kind.split(',')[1])
1993        tu = kind.split(',')[2]
1994
1995# Generic incremental dt [seconds] according to all the possibilities ['c', 'y', 'm',
1996#   'w', 'd', 'h', 'i', 's', 'l'], some of them approximated (because they are not
1997#   already necessary!)
1998        basedt = np.zeros((9), dtype=np.float)
1999        basedt[0] = (365.*100. + 25.)*24.*3600.
2000        basedt[1] = secsYear
2001        basedt[2] = 31.*24.*3600.
2002        basedt[3] = secsWeek
2003        basedt[4] = secsDay
2004        basedt[5] = secsHour
2005        basedt[6] = secsMinute
2006        basedt[7] = 1.
2007        basedt[8] = secsMilisecond
2008
2009# Increment according to the units of the CF dates
2010        if trefunits == 'weeks':
2011            basedt = basedt/(secsWeek)
2012        elif trefunits == 'days':
2013            basedt = basedt/(secsDay)
2014        elif trefunits == 'hours':
2015            basedt = basedt/(secsHour)
2016        elif trefunits == 'minutes':
2017            basedt = basedt/(secsMinute)
2018        elif trefunits == 'seconds':
2019            basedt = basedt
2020        elif trefunits == 'milliseconds':
2021            basedt = basedt*secsMilisecond
2022
2023        if tu == 'c':
2024            ti = firstTvec[0]
2025            tf = lastTvec[0] 
2026            centi = firstTvec[0] / 100
2027
2028            datev = firstTdt
2029            while datev < lastTdt:
2030                yr = datev.year + Nunits*100
2031                mon = datev.month
2032                datev = dt.datetime(yr, mon, 1, 0, 0, 0)
2033                timeout.append(datev)
2034
2035        elif tu == 'y':
2036            ti = firstTvec[0]
2037            tf = lastTvec[0]
2038            yeari = firstTvec[0]
2039
2040            TOTsteps = int(TOTdtsecs/(Nunits*31*secsDay)) + 1
2041
2042            datev = firstTdt
2043            while datev < lastTdt:
2044                yr = datev.year + Nunits
2045                mon = datev.month
2046                datev = dt.datetime(yr, mon, 1, 0, 0, 0)
2047                timeout.append(datev)
2048
2049        elif tu == 'm':
2050            ti = firstTvec[1]
2051            tf = lastTvec[1]
2052           
2053            yr = firstTvec[0]
2054            mon = firstTvec[1]
2055
2056            TOTsteps = int(TOTdtsecs/(Nunits*31*secsDay)) + 1
2057
2058            datev = firstTdt
2059            while datev < lastTdt:
2060                mon = datev.month + Nunits
2061                if mon > 12:
2062                    yr = yr + 1
2063                    mon = 1
2064                datev = dt.datetime(yr, mon, 1, 0, 0, 0)
2065                timeout.append(datev)
2066
2067        elif tu == 'w':
2068            datev=firstTdt
2069            it=0
2070            while datev <= lastTdt:
2071                datev = firstTdt + dt.timedelta(days=7*Nunits*it)
2072                timeout.append(datev)
2073                it = it + 1
2074        elif tu == 'd':
2075#            datev=firstTdt
2076            yr = firstTvec[0]
2077            mon = firstTvec[1]
2078            day = firstTvec[2]
2079 
2080            Iunits = np.mod(day,Nunits)
2081            if np.sum(firstTvec[2:5]) > 0:
2082                firstTdt = dt.datetime(yr, mon, day+1, 0, 0, 0)
2083                datev = dt.datetime(yr, mon, day+1, 0, 0, 0)
2084            elif Iunits != 0:
2085                nNunits = int(day/Nunits)
2086                firstTdt = dt.datetime(yr, mon, nNunits*Nunits, 0, 0, 0)
2087                datev = dt.datetime(yr, mon, nNunits*Nunits, 0, 0, 0)
2088            else:
2089                firstTdt = dt.datetime(yr, mon, day, 0, 0, 0)
2090                datev = dt.datetime(yr, mon, day, 0, 0, 0)
2091
2092            it=0
2093            while datev <= lastTdt:
2094                datev = firstTdt + dt.timedelta(days=Nunits*it)
2095                timeout.append(datev)
2096                it = it + 1
2097
2098        elif tu == 'h':
2099            datev=firstTdt
2100            yr = firstTvec[0]
2101            mon = firstTvec[1]
2102            day = firstTvec[2]
2103            hour = firstTvec[3]
2104
2105            Iunits = np.mod(hour,Nunits)
2106            if np.sum(firstTvec[4:5]) > 0 or Iunits != 0:
2107                tadvance = 2*Nunits
2108                if tadvance >= 24:
2109                    firstTdt = dt.datetime(yr, mon, day+1, 0, 0, 0)
2110                    datev = dt.datetime(yr, mon, day+1, 0, 0, 0)
2111                else:
2112                    nNunits = int(hour/Nunits)
2113                    firstTdt = dt.datetime(yr, mon, day, nNunits*Nunits, 0, 0)
2114                    datev = dt.datetime(yr, mon, day, nNunits*Nunits, 0, 0)
2115            else:
2116                firstTdt = dt.datetime(yr, mon, day, hour, 0, 0)
2117                datev = dt.datetime(yr, mon, day, hour, 0, 0)
2118
2119            it=0
2120            while datev <= lastTdt:
2121                datev = firstTdt + dt.timedelta(seconds=Nunits*3600*it)
2122                timeout.append(datev)
2123                it = it + 1                 
2124        elif tu == 'i':
2125            datev=firstTdt
2126            yr = firstTvec[0]
2127            mon = firstTvec[1]
2128            day = firstTvec[2]
2129            hour = firstTvec[3]
2130            minu = firstTvec[4]
2131
2132            Iunits = np.mod(minu,Nunits)
2133            if firstTvec[5] > 0 or Iunits != 0:
2134                tadvance = 2*Nunits
2135                if tadvance >= 60:
2136                    firstTdt = dt.datetime(yr, mon, day, hour, 0, 0)
2137                    datev = dt.datetime(yr, mon, day, hour, 0, 0)
2138                else:
2139                    nNunits = int(minu/Nunits)
2140                    firstTdt = dt.datetime(yr, mon, day, hour, nNunits*Nunits, 0)
2141                    datev = dt.datetime(yr, mon, day, hour, nNunits*Nunits, 0)
2142            else:
2143                firstTdt = dt.datetime(yr, mon, day, hour, minu, 0)
2144                datev = dt.datetime(yr, mon, day, hour, minu, 0)
2145            it=0
2146            while datev <= lastTdt:
2147                datev = firstTdt + dt.timedelta(seconds=Nunits*60*it)
2148                timeout.append(datev)
2149                it = it + 1                 
2150        elif tu == 's':
2151            datev=firstTdt
2152            yr = firstTvec[0]
2153            mon = firstTvec[1]
2154            day = firstTvec[2]
2155            hour = firstTvec[3]
2156            min = firstTvec[4]
2157            secu = firstTvec[5]
2158
2159            Iunits = np.mod(secu,Nunits)
2160            if firstTvec[5] > 0 or Iunits != 0:
2161                tadvance = 2*Nunits
2162                if tadvance >= 60:
2163                    firstTdt = dt.datetime(yr, mon, day, hour, min, 0)
2164                    datev = dt.datetime(yr, mon, day, hour, min, 0)
2165                else:
2166                    nNunits = int(minu/Nunits)
2167                    firstTdt = dt.datetime(yr, mon, day, hour, min, nNunits*Nunits)
2168                    datev = dt.datetime(yr, mon, day, hour, min, nNunits*Nunits)
2169            else:
2170                firstTdt = dt.datetime(yr, mon, day, hour, min, secu)
2171                datev = dt.datetime(yr, mon, day, hour, min, secu)
2172            it=0
2173            while datev <= lastTdt:
2174                datev = firstTdt + dt.timedelta(seconds=Nunits*it)
2175                timeout.append(datev)
2176                it = it + 1                 
2177        elif tu == 'l':
2178            datev=firstTdt
2179            it=0
2180            while datev <= lastTdt:
2181                datev = firstTdt + dt.timedelta(seconds=Nunits*it/1000.)
2182                timeout.append(datev)
2183                it = it + 1
2184        else:
2185            print errormsg
2186            print '  '  + fname + ': exact units "' + tu + '" not ready!!!!!'
2187            quit(-1)
2188
2189    else:
2190        print errormsg
2191        print '  ' + fname + ': output kind "' + okind + '" not ready!!!!'
2192        quit(-1)
2193
2194    dtout = len(timeout)
2195
2196    timeoutS = []
2197    timeoutv = np.zeros((dtout), dtype=np.float)
2198
2199    for it in range(dtout):
2200        timeoutS.append(timeout[it].strftime(tfmt))
2201        timeoutv[it] = date_CFtime(timeout[it], refdate, trefunits)
2202       
2203#        print it,':',timeoutv[it], timeoutS[it]
2204
2205    if len(timeoutv) < 1 or len(timeoutS) < 1:
2206        print errormsg
2207        print '  ' + fname + ': no time values are generated!'
2208        print '    values passed:',timev
2209        print '    units:',units
2210        print '    desired kind:',kind
2211        print '    format:',tfmt
2212        print '    function values ___ __ _'
2213        print '      reference date:',refdate
2214        print '      first date:',firstTdt
2215        print '      last date:',lastTdt
2216        print '      icrement:',basedt,trefunits
2217
2218        quit(-1)
2219
2220    return timeoutv, timeoutS
2221
2222def color_lines(Nlines):
2223    """ Function to provide a color list to plot lines
2224    color_lines(Nlines)
2225      Nlines= number of lines
2226    """
2227
2228    fname = 'color_lines'
2229
2230    colors = ['r', 'b', 'g', 'p', 'g']
2231
2232    colorv = []
2233
2234    colorv.append('k')
2235    for icol in range(Nlines):
2236        colorv.append(colors[icol])
2237
2238
2239    return colorv
2240
2241def output_kind(kindf, namef, close):
2242    """ Function to generate the output of the figure
2243      kindf= kind of the output
2244        null: show in screen
2245        [jpg/pdf/png/ps]: standard output types
2246      namef= name of the figure (without extension)
2247      close= if the graph has to be close or not [True/False]
2248    """
2249    fname = 'output_kind'
2250
2251    if kindf == 'h':
2252        print fname + '_____________________________________________________________'
2253        print output_kind.__doc__
2254        quit()
2255
2256    if kindf == 'null':
2257        print 'showing figure...'
2258        plt.show()
2259    elif kindf == 'gif':
2260        plt.savefig(namef + ".gif")
2261        if close: print "Successfully generation of figure '" + namef + ".jpg' !!!"
2262    elif kindf == 'jpg':
2263        plt.savefig(namef + ".jpg")
2264        if close: print "Successfully generation of figure '" + namef + ".jpg' !!!"
2265    elif kindf == 'pdf':
2266        plt.savefig(namef + ".pdf")
2267        if close: print "Successfully generation of figure '" + namef + ".pdf' !!!"
2268    elif kindf == 'png':
2269        plt.savefig(namef + ".png")
2270        if close: print "Successfully generation of figure '" + namef + ".png' !!!"
2271    elif kindf == 'ps':
2272        plt.savefig(namef + ".ps")
2273        if close: print "Successfully generation of figure '" + namef + ".ps' !!!"
2274    else:
2275        print errormsg
2276        print '  ' + fname + ' output format: "' + kindf + '" not ready !!'
2277        print errormsg
2278        quit(-1)
2279
2280    if close:
2281        plt.close()
2282
2283    return
2284
2285def check_arguments(funcname,args,expectargs,char):
2286    """ Function to check the number of arguments if they are coincident
2287    check_arguments(funcname,Nargs,args,char)
2288      funcname= name of the function/program to check
2289      args= passed arguments
2290      expectargs= expected arguments
2291      char= character used to split the arguments
2292    """
2293
2294    fname = 'check_arguments'
2295
2296    Nvals = len(args.split(char))
2297    Nargs = len(expectargs.split(char))
2298
2299    if Nvals != Nargs:
2300        print errormsg
2301        print '  ' + fname + ': wrong number of arguments:',Nvals," passed to  '",   \
2302          funcname, "' which requires:",Nargs,'!!'
2303        print '     # given expected _______'
2304        Nmax = np.max([Nvals, Nargs])
2305        for ia in range(Nmax):
2306            if ia > Nvals-1:
2307                aval = ' '
2308            else:
2309                aval = args.split(char)[ia]
2310            if ia > Nargs-1:
2311                aexp = ' '
2312            else:
2313                aexp = expectargs.split(char)[ia]
2314
2315            print '    ', ia, aval, aexp
2316        quit(-1)
2317
2318    return
2319
2320def Str_Bool(val):
2321    """ Function to transform from a String value to a boolean one
2322    >>> Str_Bool('True')
2323    True
2324    >>> Str_Bool('0')
2325    False
2326    >>> Str_Bool('no')
2327    False
2328    """
2329
2330    fname = 'Str_Bool'
2331
2332    if val == 'True' or val == 'true' or val == '1' or val == 'yes': 
2333        boolv = True
2334    elif val == 'False' or val == 'false' or val == '0' or val== 'no':
2335        boolv = False
2336    else:
2337        print errormsg
2338        print '  ' + fname + ": value '" + val + "' not ready!!"
2339        quit(-1)
2340
2341    return boolv
2342
2343def coincident_CFtimes(tvalB, tunitA, tunitB):
2344    """ Function to make coincident times for two different sets of CFtimes
2345    tvalB= time values B
2346    tunitA= time units times A to which we want to make coincidence
2347    tunitB= time units times B
2348    >>> coincident_CFtimes(np.arange(10),'seconds since 1949-12-01 00:00:00',
2349      'hours since 1949-12-01 00:00:00')
2350    [     0.   3600.   7200.  10800.  14400.  18000.  21600.  25200.  28800.  32400.]
2351    >>> coincident_CFtimes(np.arange(10),'seconds since 1949-12-01 00:00:00',
2352      'hours since 1979-12-01 00:00:00')
2353    [  9.46684800e+08   9.46688400e+08   9.46692000e+08   9.46695600e+08
2354       9.46699200e+08   9.46702800e+08   9.46706400e+08   9.46710000e+08
2355       9.46713600e+08   9.46717200e+08]
2356    """
2357    import datetime as dt
2358    fname = 'coincident_CFtimes'
2359
2360    trefA = tunitA.split(' ')[2] + ' ' + tunitA.split(' ')[3]
2361    trefB = tunitB.split(' ')[2] + ' ' + tunitB.split(' ')[3]
2362    tuA = tunitA.split(' ')[0]
2363    tuB = tunitB.split(' ')[0]
2364
2365    if tuA != tuB:
2366        if tuA == 'microseconds':
2367            if tuB == 'microseconds':
2368                tB = tvalB*1.
2369            elif tuB == 'seconds':
2370                tB = tvalB*10.e6
2371            elif tuB == 'minutes':
2372                tB = tvalB*60.*10.e6
2373            elif tuB == 'hours':
2374                tB = tvalB*3600.*10.e6
2375            elif tuB == 'days':
2376                tB = tvalB*3600.*24.*10.e6
2377            else:
2378                print errormsg
2379                print '  ' + fname + ": combination of time untis: '" + tuA +        \
2380                  "' & '" + tuB + "' not ready !!"
2381                quit(-1)
2382        elif tuA == 'seconds':
2383            if tuB == 'microseconds':
2384                tB = tvalB/10.e6
2385            elif tuB == 'seconds':
2386                tB = tvalB*1.
2387            elif tuB == 'minutes':
2388                tB = tvalB*60.
2389            elif tuB == 'hours':
2390                tB = tvalB*3600.
2391            elif tuB == 'days':
2392                tB = tvalB*3600.*24.
2393            else:
2394                print errormsg
2395                print '  ' + fname + ": combination of time untis: '" + tuA +        \
2396                  "' & '" + tuB + "' not ready !!"
2397                quit(-1)
2398        elif tuA == 'minutes':
2399            if tuB == 'microseconds':
2400                tB = tvalB/(60.*10.e6)
2401            elif tuB == 'seconds':
2402                tB = tvalB/60.
2403            elif tuB == 'minutes':
2404                tB = tvalB*1.
2405            elif tuB == 'hours':
2406                tB = tvalB*60.
2407            elif tuB == 'days':
2408                tB = tvalB*60.*24.
2409            else:
2410                print errormsg
2411                print '  ' + fname + ": combination of time untis: '" + tuA +        \
2412                  "' & '" + tuB + "' not ready !!"
2413                quit(-1)
2414        elif tuA == 'hours':
2415            if tuB == 'microseconds':
2416                tB = tvalB/(3600.*10.e6)
2417            elif tuB == 'seconds':
2418                tB = tvalB/3600.
2419            elif tuB == 'minutes':
2420                tB = tvalB/60.
2421            elif tuB == 'hours':
2422                tB = tvalB*1.
2423            elif tuB == 'days':
2424                tB = tvalB*24.
2425            else:
2426                print errormsg
2427                print '  ' + fname + ": combination of time untis: '" + tuA +        \
2428                  "' & '" + tuB + "' not ready !!"
2429                quit(-1)
2430        elif tuA == 'days':
2431            if tuB == 'microseconds':
2432                tB = tvalB/(24.*3600.*10.e6)
2433            elif tuB == 'seconds':
2434                tB = tvalB/(24.*3600.)
2435            elif tuB == 'minutes':
2436                tB = tvalB/(24.*60.)
2437            elif tuB == 'hours':
2438                tB = tvalB/24.
2439            elif tuB == 'days':
2440                tB = tvalB*1.
2441            else:
2442                print errormsg
2443                print '  ' + fname + ": combination of time untis: '" + tuA +        \
2444                  "' & '" + tuB + "' not ready !!"
2445                quit(-1)
2446        else:
2447            print errormsg
2448            print '  ' + fname + ": time untis: '" + tuA + "' not ready !!"
2449            quit(-1)
2450    else:
2451        tB = tvalB*1.
2452
2453    if trefA != trefB:
2454        trefTA = dt.datetime.strptime(trefA, '%Y-%m-%d %H:%M:%S')
2455        trefTB = dt.datetime.strptime(trefB, '%Y-%m-%d %H:%M:%S')
2456
2457        difft = trefTB - trefTA
2458        diffv = difft.days*24.*3600.*10.e6 + difft.seconds*10.e6 + difft.microseconds
2459        print '  ' + fname + ': different reference refA:',trefTA,'refB',trefTB
2460        print '    difference:',difft,':',diffv,'microseconds'
2461
2462        if tuA == 'microseconds':
2463            tB = tB + diffv
2464        elif tuA == 'seconds':
2465            tB = tB + diffv/10.e6
2466        elif tuA == 'minutes':
2467            tB = tB + diffv/(60.*10.e6)
2468        elif tuA == 'hours':
2469            tB = tB + diffv/(3600.*10.e6)
2470        elif tuA == 'dayss':
2471            tB = tB + diffv/(24.*3600.*10.e6)
2472        else:
2473            print errormsg
2474            print '  ' + fname + ": time untis: '" + tuA + "' not ready !!"
2475            quit(-1)
2476
2477    return tB
2478
2479####### ###### ##### #### ### ## #
2480
2481def plot_TimeSeries(valtimes, vunits, tunits, hfileout, vtit, ttit, tkind, tformat,  \
2482  tit, linesn, lloc, kfig,coll,ptl,ptf):
2483    """ Function to draw time-series
2484      valtimes= list of arrays to plot [vals1[1values, 1times], [...,valsM[Mvals,Mtimes]])
2485      vunits= units of the values
2486      tunits= units of the times
2487      hfileout= header of the output figure. Final name: [hfileout]_[vtit].[kfig]
2488      vtit= variable title to be used in the graph
2489      ttit= time title to be used in the graph
2490      tkind= kind of time values to appear in the x-axis
2491        'Nval': according to a given number of values as 'Nval',[Nval]
2492        'exct': according to an exact time unit as 'exct',[tunit];
2493          tunit= [Nunits],[tu]; [tu]= 'c': centuries, 'y': year, 'm': month,
2494            'w': week, 'd': day, 'h': hour, 'i': minute, 's': second,
2495            'l': milisecond
2496      tformat= desired format of times
2497      tit= title of the graph
2498      linesn= list of values fot the legend
2499      lloc= location of the legend (0, autmoatic)
2500        1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
2501        5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
2502        9: 'upper center', 10: 'center'
2503      kfig= type of figure: jpg, png, pds, ps
2504      coll= ',' list of colors for the lines, None for automatic, single
2505          value all the same
2506      ptl= ',' list of type of points for the lines, None for automatic, single
2507          value all the same
2508      ptf= frequency of point plotting, 'all' for all time steps
2509    """
2510    fname = 'plot_TimeSeries'
2511
2512    if valtimes == 'h':
2513        print fname + '_____________________________________________________________'
2514        print plot_TimeSeries.__doc__
2515        quit()
2516
2517    Nlines = len(valtimes)
2518# Canging line kinds every 7 lines (end of standard colors)
2519    Npts = len(pointkindsauto)
2520    linekinds = []
2521    pointkinds = []
2522    if ptl is None:
2523        if ptf is None:
2524            for ptype in range(Npts):
2525                for ip in range(7):
2526                    linekinds.append(pointkindsauto[ptype] + '-')
2527        else:
2528            for ptype in range(Npts):
2529                for ip in range(7):
2530                    linekinds.append('-')
2531                    pointkinds.append(pointkindsauto[ptype])
2532    else:
2533        if ptf is None:
2534            if len(ptl) > 1:
2535               for pt in ptl:
2536                    linekinds.append(pt + '-')
2537            else:
2538                for il in range(Nlines):
2539                    linekinds.append(ptl+'-')
2540        else:
2541            if len(ptl) > 1:
2542               for pt in ptl:
2543                    linekinds.append('-')
2544                    pointkinds.append(pt)
2545            else:
2546                for il in range(Nlines):
2547                    linekinds.append('-')
2548                pointkinds = ptl
2549
2550    Nvalues = []
2551    Ntimes = []
2552
2553    for il in range(Nlines):
2554        array = valtimes[il]
2555
2556        if Nlines == 1:
2557            print warnmsg
2558            print '  ' + fname + ': drawing only one line!'
2559
2560            Nvalues.append(array.shape[1])
2561            Ntimes.append(array.shape[0])
2562            tmin = np.min(array[1])
2563            tmax = np.max(array[1])
2564            vmin = np.min(array[0])
2565            vmax = np.max(array[0])
2566        else:
2567            Nvalues.append(array.shape[1])
2568            Ntimes.append(array.shape[0])
2569            tmin = np.min(array[1,:])
2570            tmax = np.max(array[1,:])
2571            vmin = np.min(array[0,:])
2572            vmax = np.max(array[0,:])
2573
2574        if il == 0:
2575            xmin = tmin
2576            xmax = tmax
2577            ymin = vmin
2578            ymax = vmax
2579        else:
2580            if tmin < xmin: xmin = tmin
2581            if tmax > xmax: xmax = tmax
2582            if vmin < ymin: ymin = vmin
2583            if vmax > ymax: ymax = vmax
2584
2585    dx = np.max(Ntimes)
2586    dy = np.min(Nvalues)
2587
2588    plt.rc('text', usetex=True)
2589
2590    print vtit
2591    if vtit == 'ps':
2592        plt.ylim(98000.,ymax)
2593    else:
2594        plt.ylim(ymin,ymax)
2595
2596    plt.xlim(xmin,xmax)
2597#    print 'x lim:',xmin,xmax
2598#    print 'y lim:',ymin,ymax
2599
2600    N7lines=0
2601    for il in range(Nlines):
2602        array = valtimes[il]
2603        if vtit == 'ps':
2604            array[0,:] = np.where(array[0,:] < 98000., None, array[0,:])
2605
2606        if ptf is None:
2607            if coll is None:
2608                if ptf is None:
2609                    plt.plot(array[1,:],array[0,:], linekinds[il], label=linesn[il])
2610                else:
2611                    plt.plot(array[1,:],array[0,:], linekinds[il], label=linesn[il])
2612                    plt.plot(array[1,::ptf],array[0,::ptf], pointkinds[il],          \
2613                      label=linesn[il])
2614            else:
2615                if ptf is None:
2616                    plt.plot(array[1,:],array[0,:], linekinds[il], label=linesn[il], \
2617                      color=coll[il])
2618                else:
2619                    plt.plot(array[1,:],array[0,:], linekinds[il], label=linesn[il], \
2620                      color=coll[il])
2621                    plt.plot(array[1,::ptf],array[0,::ptf], pointkinds[il],          \
2622                      label=linesn[il], color=coll[il])
2623        else:
2624            if coll is None:
2625                if ptf is None:
2626                    plt.plot(array[1,:],array[0,:], linekinds[il], label=linesn[il])
2627                else:
2628                    plt.plot(array[1,:],array[0,:], linekinds[il], label=linesn[il])
2629                    plt.plot(array[1,::ptf],array[0,::ptf], pointkinds[il],          \
2630                      label=linesn[il])
2631            else:
2632                if ptf is None:
2633                    plt.plot(array[1,:],array[0,:], linekinds[il], label=linesn[il], \
2634                      color=coll[il])
2635                else:
2636                    plt.plot(array[1,:],array[0,:], linekinds[il], label=linesn[il], \
2637                      color=coll[il])
2638                    plt.plot(array[1,::ptf],array[0,::ptf], pointkinds[il],          \
2639                      label=linesn[il], color=coll[il])
2640
2641    timevals = np.arange(xmin,xmax)*1.
2642
2643    tpos, tlabels = CFtimes_plot(timevals, tunits, tkind, tformat)
2644
2645    if len(tpos) > 10:
2646        print warnmsg
2647        print '  ' + fname + ': with "' + tkind + '" there are', len(tpos), 'xticks !'
2648
2649    plt.xticks(tpos, tlabels)
2650#    plt.Axes.set_xticklabels(tlabels)
2651
2652
2653    plt.legend(loc=lloc)
2654    plt.xlabel(ttit)
2655    plt.ylabel(vtit + " (" + vunits + ")")
2656    plt.title(tit.replace('_','\_').replace('&','\&'))
2657
2658    figname = hfileout + '_' + vtit
2659   
2660    output_kind(kfig, figname, True)
2661
2662    return
2663
2664#Nt = 50
2665#Nlines = 3
2666
2667#vtvalsv = []
2668
2669#valsv = np.zeros((2,Nt), dtype=np.float)
2670## First
2671#valsv[0,:] = np.arange(Nt)
2672#valsv[1,:] = np.arange(Nt)*180.
2673#vtvalsv.append(valsv)
2674#del(valsv)
2675
2676#valsv = np.zeros((2,Nt/2), dtype=np.float)
2677## Second
2678#valsv[0,:] = np.arange(Nt/2)
2679#valsv[1,:] = np.arange(Nt/2)*180.*2.
2680#vtvalsv.append(valsv)
2681#del(valsv)
2682
2683#valsv = np.zeros((2,Nt/4), dtype=np.float)
2684## Third
2685#valsv[0,:] = np.arange(Nt/4)
2686#valsv[1,:] = np.arange(Nt/4)*180.*4.
2687#vtvalsv.append(valsv)
2688#del(valsv)
2689
2690#varu='mm'
2691#timeu='seconds'
2692
2693#title='test'
2694#linesname = ['line 1', 'line 2', 'line 3']
2695
2696#plot_TimeSeries(vtvalsv, units_lunits(varu), timeu, 'test', 'vartest', 'time', title, linesname, 'png')
2697#quit()
2698
2699def plot_points(xval, yval, vlon, vlat, extravals, extrapar, vtit, mapv, figk, color,\
2700  labels, lloc, kfig, figname):
2701    """ plotting points
2702      [x/yval]: x,y values to plot
2703      vlon= 2D-matrix with the longitudes
2704      vlat= 2D-matrix with the latitudes
2705      extravals= extra values to be added into the plot (None for nothing)
2706      extrapar= [varname, min, max, cbar, varunits] of the extra variable
2707      vtit= title of the graph ('|' for spaces)
2708      mapv= map characteristics: [proj],[res]
2709        see full documentation: http://matplotlib.org/basemap/
2710        [proj]: projection
2711          * 'cyl', cilindric
2712          * 'lcc', lambert-conformal
2713        [res]: resolution:
2714          * 'c', crude
2715          * 'l', low
2716          * 'i', intermediate
2717          * 'h', high
2718          * 'f', full
2719      figK= kind of figure
2720        'legend': only points in the map with the legend with the names
2721        'labelled',[txtsize],[txtcol]: points with the names and size, color of text
2722      color= color for the points/labels ('auto', for "red")
2723      labels= list of labels for the points (None, no labels)
2724      lloc = localisation of the legend
2725      kfig= kind of figure (jpg, pdf, png)
2726      figname= name of the figure
2727
2728    """
2729    fname = 'plot_points'
2730# Canging line kinds every 7 pts (end of standard colors)
2731    ptkinds=['.','x','o','*','+','8','>','D','h','p','s']
2732
2733    Npts = len(xval)
2734    if Npts > len(ptkinds)*7:
2735        print errormsg
2736        print '  ' + fname + ': too many',Npts,'points!!'
2737        print "    enlarge 'ptkinds' list"
2738        quit(-1)
2739
2740    N7pts = 0
2741
2742    if color == 'auto':
2743        ptcol = "red"
2744    else:
2745        ptcol = color
2746
2747    dx=vlon.shape[1]
2748    dy=vlat.shape[0]
2749
2750    plt.rc('text', usetex=True)
2751
2752    if not mapv is None:
2753#        vlon = np.where(vlon[:] < 0., 360. + vlon[:], vlon[:])
2754#        xvala = np.array(xval)
2755#        xvala = np.where(xvala < 0., 360. + xvala, xvala)
2756#        xval = list(xvala)
2757
2758        map_proj=mapv.split(',')[0]
2759        map_res=mapv.split(',')[1]
2760
2761        nlon = np.min(vlon)
2762        xlon = np.max(vlon)
2763        nlat = np.min(vlat)
2764        xlat = np.max(vlat)
2765
2766        lon2 = vlon[dy/2,dx/2]
2767        lat2 = vlat[dy/2,dx/2]
2768
2769        print 'lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:',     \
2770          xlon, ',', xlat
2771
2772        if map_proj == 'cyl':
2773            m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat,         \
2774              urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res)
2775        elif map_proj == 'lcc':
2776            m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \
2777              llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res)
2778        else:
2779            print errormsg
2780            print '  ' + fname + ": map projecion '" + map_proj + "' not ready!!"
2781            print '    available: cyl, lcc'
2782            quit(-1)
2783
2784#        lons, lats = np.meshgrid(vlon, vlat)
2785#        lons = np.where(lons < 0., lons + 360., lons)
2786
2787        x,y = m(vlon,vlat)
2788
2789        m.drawcoastlines()
2790
2791        meridians = pretty_int(nlon,xlon,5)
2792        m.drawmeridians(meridians,labels=[True,False,False,True])
2793
2794        parallels = pretty_int(nlat,xlat,5)
2795        m.drawparallels(parallels,labels=[False,True,True,False])
2796    else:
2797        x = vlon
2798        y = vlat
2799#        plt.xlim(0,dx-1)
2800#        plt.ylim(0,dy-1)
2801
2802# Extra values
2803    if extravals is not None:
2804        plt.pcolormesh(x, y, extravals, cmap=plt.get_cmap(extrapar[3]),              \
2805          vmin=extrapar[1], vmax=extrapar[2])
2806        cbar = plt.colorbar()
2807        cbar.set_label(extrapar[0].replace('_','\_') +'('+ units_lunits(extrapar[4])+\
2808          ')')
2809
2810    if labels is not None:
2811        for iv in range(len(xval)):
2812            if np.mod(iv,7) == 0: N7pts = N7pts + 1
2813#            print iv,xval[iv],yval[iv],labels[iv],ptkinds[N7pts]
2814            plt.plot(xval[iv],yval[iv], ptkinds[N7pts],label=labels[iv])
2815
2816        if figk[0:8] == 'labelled':
2817            txtsize=int(figk.split(',')[1])
2818            txtcol=figk.split(',')[2]
2819            for iv in range(len(xval)):
2820                plt.annotate(labels[iv], xy=(xval[iv],yval[iv]), xycoords='data',    \
2821                  fontsize=txtsize, color=txtcol)
2822        elif figk == 'legend':
2823            plt.legend(loc=lloc)
2824
2825    else: 
2826        plt.plot(xval, yval, '.', color=ptcol)
2827
2828    graphtit = vtit.replace('_','\_').replace('&','\&')
2829
2830    plt.title(graphtit.replace('|', ' '))
2831   
2832    output_kind(kfig, figname, True)
2833
2834    return
2835
2836def plot_list_points(xval, yval, varxn, varyn, vtit, figk, color, ptk, pts, labels, lloc, kfig, figname):
2837    """ plotting points
2838      [x/yval]: x,y values to plot
2839      var[x/y]n: names of the x,y variables
2840      vtit= title of the graph ('|' for spaces)
2841      figK= kind of figure
2842        'legend': only points in the map with the legend with the names
2843        'labelled',[txtsize],[txtcol]: points with the names and size, color of text
2844      color= color for the points/labels ('auto', for "red")
2845      ptk= kind of point
2846      pts= point size
2847      labels= list of labels for the points (None, no labels)
2848      lloc = localisation of the legend
2849      kfig= kind of figure (jpg, pdf, png)
2850      figname= name of the figure
2851
2852    """
2853    fname = 'plot_points'
2854# Canging line kinds every 7 pts (end of standard colors)
2855    ptkinds=['.','x','o','*','+','8','>','D','h','p','s']
2856
2857    if color == 'auto':
2858        ptcol = "red"
2859    else:
2860        ptcol = color
2861
2862    plt.rc('text', usetex=True)
2863
2864    if labels is not None:
2865        for iv in range(len(xval)):
2866#            print iv,xval[iv],yval[iv],labels[iv],ptkinds[N7pts]
2867            plt.plot(xval[iv],yval[iv], ptk, markersize=pts, label=labels[iv])
2868
2869        if figk[0:8] == 'labelled':
2870            txtsize=int(figk.split(',')[1])
2871            txtcol=figk.split(',')[2]
2872            for iv in range(len(xval)):
2873                plt.annotate(labels[iv], xy=(xval[iv],yval[iv]), xycoords='data',    \
2874                  fontsize=txtsize, color=txtcol)
2875        elif figk == 'legend':
2876            plt.legend(loc=lloc)
2877
2878    else: 
2879        plt.plot(xval, yval, ptk, markersize=pts, color=ptcol)
2880
2881    plt.xlabel(varxn)
2882    plt.ylabel(varyn)
2883
2884    graphtit = vtit.replace('_','\_').replace('&','\&')
2885
2886    plt.title(graphtit.replace('|', ' '))
2887   
2888    output_kind(kfig, figname, True)
2889
2890    return
2891
2892def plot_2Dfield(varv,dimn,colorbar,vn,vx,unit,olon,olat,ifile,vtit,zvalue,time,tk,  \
2893   tkt,tobj,tvals,tind,kfig,mapv,reva):
2894    """ Adding labels and other staff to the graph
2895      varv= 2D values to plot
2896      dimn= dimension names to plot
2897      colorbar= name of the color bar to use
2898      vn,vm= minmum and maximum values to plot
2899      unit= units of the variable
2900      olon,olat= longitude, latitude objects
2901      ifile= name of the input file
2902      vtit= title of the variable
2903      zvalue= value on the z axis
2904      time= value on the time axis
2905      tk= kind of time (WRF)
2906      tkt= kind of time taken
2907      tobj= tim object
2908      tvals= values of the time variable
2909      tind= time index
2910      kfig= kind of figure (jpg, pdf, png)
2911      mapv= map characteristics: [proj],[res]
2912        see full documentation: http://matplotlib.org/basemap/
2913        [proj]: projection
2914          * 'cyl', cilindric
2915        [res]: resolution:
2916          * 'c', crude
2917          * 'l', low
2918          * 'i', intermediate
2919          * 'h', high
2920          * 'f', full
2921      reva= reverse the axes (x-->y, y-->x)
2922    """
2923##    import matplotlib as mpl
2924##    mpl.use('Agg')
2925##    import matplotlib.pyplot as plt
2926
2927    if reva:
2928        print '  reversing the axes of the figure (x-->y, y-->x)!!'
2929        varv = np.transpose(varv)
2930        dimn0 = []
2931        dimn0.append(dimn[1] + '')
2932        dimn0.append(dimn[0] + '')
2933        dimn = dimn0
2934
2935    fname = 'plot_2Dfield'
2936    dx=varv.shape[1]
2937    dy=varv.shape[0]
2938
2939    plt.rc('text', usetex=True)
2940#    plt.rc('font', family='serif')
2941
2942    if not mapv is None:
2943        if len(olon[:].shape) == 3:
2944            lon0 = np.where(olon[0,] < 0., 360. + olon[0,], olon[0,])
2945            lat0 = olat[0,]
2946        elif len(olon[:].shape) == 2:
2947            lon0 = np.where(olon[:] < 0., 360. + olon[:], olon[:])
2948            lat0 = olat[:]
2949        elif len(olon[:].shape) == 1:
2950            lon00 = np.where(olon[:] < 0., 360. + olon[:], olon[:])
2951            lat00 = olat[:]
2952            lon0 = np.zeros( (len(lat00),len(lon00)), dtype=np.float )
2953            lat0 = np.zeros( (len(lat00),len(lon00)), dtype=np.float )
2954
2955            for iy in range(len(lat00)):
2956                lon0[iy,:] = lon00
2957            for ix in range(len(lon00)):
2958                lat0[:,ix] = lat00
2959
2960        map_proj=mapv.split(',')[0]
2961        map_res=mapv.split(',')[1]
2962
2963        nlon = lon0[0,0]
2964        xlon = lon0[dy-1,dx-1]
2965        nlat = lat0[0,0]
2966        xlat = lat0[dy-1,dx-1]
2967
2968        lon2 = lon0[dy/2,dx/2]
2969        lat2 = lat0[dy/2,dx/2]
2970
2971        print '    lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:', \
2972          xlon, ',', xlat
2973
2974        if map_proj == 'cyl':
2975            m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat,         \
2976              urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res)
2977        elif map_proj == 'lcc':
2978            m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \
2979              llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res)
2980
2981        if len(olon[:].shape) == 1:
2982            lons, lats = np.meshgrid(olon[:], olat[:])
2983        else:
2984            lons = olon[0,:]
2985            lats = olat[:,0]
2986 
2987        lons = np.where(lons < 0., lons + 360., lons)
2988
2989        x,y = m(lons,lats)
2990        plt.pcolormesh(x,y,varv, cmap=plt.get_cmap(colorbar), vmin=vn, vmax=vx)
2991        cbar = plt.colorbar()
2992
2993        m.drawcoastlines()
2994#        if (nlon > 180. or xlon > 180.):
2995#            nlon0 = nlon
2996#            xlon0 = xlon
2997#            if (nlon > 180.): nlon0 = nlon - 360.
2998#            if (xlon > 180.): xlon0 = xlon - 360.
2999#            meridians = pretty_int(nlon0,xlon0,5)           
3000#            meridians = np.where(meridians < 0., meridians + 360., meridians)
3001#        else:
3002#            meridians = pretty_int(nlon,xlon,5)
3003
3004        meridians = pretty_int(nlon,xlon,5)
3005
3006        m.drawmeridians(meridians,labels=[True,False,False,True])
3007        parallels = pretty_int(nlat,xlat,5)
3008        m.drawparallels(parallels,labels=[False,True,True,False])
3009
3010    else:
3011        plt.xlim(0,dx-1)
3012        plt.ylim(0,dy-1)
3013
3014        plt.pcolormesh(varv, cmap=plt.get_cmap(colorbar), vmin=vn, vmax=vx)
3015        cbar = plt.colorbar()
3016
3017        plt.xlabel(dimn[1].replace('_','\_'))
3018        plt.ylabel(dimn[0].replace('_','\_'))
3019
3020# set the limits of the plot to the limits of the data
3021#    plt.axis([x.min(), x.max(), y.min(), y.max()])
3022
3023#    plt.plot(varv)
3024    cbar.set_label(unit)
3025
3026    figname = ifile.replace('.','_') + '_' + vtit
3027    graphtit = vtit.replace('_','\_').replace('&','\&')
3028
3029    if zvalue != 'null':
3030        graphtit = graphtit + ' at z= ' + zvalue
3031        figname = figname + '_z' + zvalue
3032    if tkt == 'tstep':
3033        graphtit = graphtit + ' at time-step= ' + time.split(',')[1]
3034        figname = figname + '_t' + time.split(',')[1].zfill(4)
3035    elif tkt == 'CFdate':
3036        graphtit = graphtit + ' at ' + tobj.strfmt("%Y%m%d%H%M%S")
3037        figname = figname + '_t' + tobj.strfmt("%Y%m%d%H%M%S")
3038
3039    if tk == 'WRF':
3040#        datev = str(timevals[timeind][0:9])
3041        datev = tvals[tind][0] + tvals[tind][1] + tvals[tind][2] + \
3042          timevals[timeind][3] + timevals[timeind][4] + timevals[timeind][5] +       \
3043          timevals[timeind][6] + timevals[timeind][7] + timevals[timeind][8] +       \
3044          timevals[timeind][9]
3045#        timev = str(timevals[timeind][11:18])
3046        timev = timevals[timeind][11] + timevals[timeind][12] +                      \
3047          timevals[timeind][13] + timevals[timeind][14] + timevals[timeind][15] +    \
3048          timevals[timeind][16] + timevals[timeind][17] + timevals[timeind][18]
3049        graphtit = vtit.replace('_','\_') + ' (' + datev + ' ' + timev + ')'
3050
3051    plt.title(graphtit)
3052   
3053    output_kind(kfig, figname, True)
3054
3055    return
3056
3057def plot_2Dfield_easy(varv,dimxv,dimyv,dimn,colorbar,vn,vx,unit,ifile,vtit,kfig,reva):
3058    """ Adding labels and other staff to the graph
3059      varv= 2D values to plot
3060      dim[x/y]v = values at the axes of x and y
3061      dimn= dimension names to plot
3062      colorbar= name of the color bar to use
3063      vn,vm= minmum and maximum values to plot
3064      unit= units of the variable
3065      ifile= name of the input file
3066      vtit= title of the variable
3067      kfig= kind of figure (jpg, pdf, png)
3068      reva= reverse the axes (x-->y, y-->x)
3069    """
3070##    import matplotlib as mpl
3071##    mpl.use('Agg')
3072##    import matplotlib.pyplot as plt
3073    fname = 'plot_2Dfield'
3074
3075    if reva:
3076        print '  reversing the axes of the figure (x-->y, y-->x)!!'
3077        varv = np.transpose(varv)
3078        dimn0 = []
3079        dimn0.append(dimn[1] + '')
3080        dimn0.append(dimn[0] + '')
3081        dimn = dimn0
3082        if len(dimyv.shape) == 2:
3083            x = np.transpose(dimyv)
3084        else:
3085            if len(dimxv.shape) == 2:
3086                ddx = len(dimyv)
3087                ddy = dimxv.shape[1]
3088            else:
3089                ddx = len(dimyv)
3090                ddy = len(dimxv)
3091
3092            x = np.zeros((ddy,ddx), dtype=np.float)
3093            for j in range(ddy):
3094                x[j,:] = dimyv
3095
3096        if len(dimxv.shape) == 2:
3097            y = np.transpose(dimxv)
3098        else:
3099            if len(dimyv.shape) == 2:
3100                ddx = dimyv.shape[0]
3101                ddy = len(dimxv)
3102            else:
3103                ddx = len(dimyv)
3104                ddy = len(dimxv)
3105
3106            y = np.zeros((ddy,ddx), dtype=np.float)
3107            for i in range(ddx):
3108                y[:,i] = dimxv
3109    else:
3110        if len(dimxv.shape) == 2:
3111            x = dimxv
3112        else:
3113            x = np.zeros((len(dimyv),len(dimxv)), dtype=np.float)
3114            for j in range(len(dimyv)):
3115                x[j,:] = dimxv
3116
3117        if len(dimyv.shape) == 2:
3118            y = dimyv
3119        else:
3120            y = np.zeros((len(dimyv),len(dimxv)), dtype=np.float)
3121            for i in range(len(dimxv)):
3122                x[:,i] = dimyv
3123
3124    dx=varv.shape[1]
3125    dy=varv.shape[0]
3126
3127    plt.rc('text', usetex=True)
3128    plt.xlim(0,dx-1)
3129    plt.ylim(0,dy-1)
3130
3131    plt.pcolormesh(x, y, varv, cmap=plt.get_cmap(colorbar), vmin=vn, vmax=vx)
3132#    plt.pcolormesh(varv, cmap=plt.get_cmap(colorbar), vmin=vn, vmax=vx)
3133    cbar = plt.colorbar()
3134
3135    plt.xlabel(dimn[1].replace('_','\_'))
3136    plt.ylabel(dimn[0].replace('_','\_'))
3137
3138# set the limits of the plot to the limits of the data
3139    plt.axis([x.min(), x.max(), y.min(), y.max()])
3140#    if varv.shape[1] / varv.shape[0] > 10:
3141#        plt.axes().set_aspect(0.001)
3142#    else:
3143#        plt.axes().set_aspect(np.float(varv.shape[0])/np.float(varv.shape[1]))
3144
3145    cbar.set_label(unit)
3146
3147    figname = ifile.replace('.','_') + '_' + vtit
3148    graphtit = vtit.replace('_','\_').replace('&','\&')
3149
3150    plt.title(graphtit)
3151
3152    output_kind(kfig, figname, True)
3153   
3154    return
3155
3156def plot_Trajectories(lonval, latval, linesn, olon, olat, lonlatLims, gtit, kfig,    \
3157  mapv, obsname):
3158    """ plotting Trajectories
3159      [lon/latval]= lon,lat values to plot (as list of vectors)
3160      linesn: name of the lines
3161      o[lon/lat]= object with the longitudes and the latitudes of the map to plot
3162      lonlatLims: limits of longitudes and latitudes [lonmin, latmin, lonmax, latmax]
3163      gtit= title of the graph
3164      kfig= kind of figure (jpg, pdf, png)
3165      mapv= map characteristics: [proj],[res]
3166        see full documentation: http://matplotlib.org/basemap/
3167        [proj]: projection
3168          * 'cyl', cilindric
3169          * 'lcc', lambert conformal
3170        [res]: resolution:
3171          * 'c', crude
3172          * 'l', low
3173          * 'i', intermediate
3174          * 'h', high
3175          * 'f', full
3176      obsname= name of the observations in graph (can be None for without).
3177        Observational trajectory would be the last one
3178    """
3179    fname = 'plot_Trajectories'
3180
3181    if lonval == 'h':
3182        print fname + '_____________________________________________________________'
3183        print plot_Trajectories.__doc__
3184        quit()
3185
3186# Canging line kinds every 7 lines (end of standard colors)
3187    linekinds=['.-','x-','o-']
3188
3189    Ntraj = len(lonval)
3190
3191    if obsname is not None:
3192        Ntraj = Ntraj - 1
3193
3194    N7lines = 0
3195
3196    plt.rc('text', usetex=True)
3197
3198    if not mapv is None:
3199        if len(olon[:].shape) == 3:
3200#            lon0 = np.where(olon[0,] < 0., 360. + olon[0,], olon[0,])
3201            lon0 = olon[0,]
3202            lat0 = olat[0,]
3203        elif len(olon[:].shape) == 2:
3204#            lon0 = np.where(olon[:] < 0., 360. + olon[:], olon[:])
3205            lon0 = olon[:]
3206            lat0 = olat[:]
3207        elif len(olon[:].shape) == 1:
3208#            lon00 = np.where(olon[:] < 0., 360. + olon[:], olon[:])
3209            lon00 = olon[:]
3210            lat00 = olat[:]
3211            lon0 = np.zeros( (len(lat00),len(lon00)), dtype=np.float )
3212            lat0 = np.zeros( (len(lat00),len(lon00)), dtype=np.float )
3213
3214            for iy in range(len(lat00)):
3215                lon0[iy,:] = lon00
3216            for ix in range(len(lon00)):
3217                lat0[:,ix] = lat00
3218
3219        map_proj=mapv.split(',')[0]
3220        map_res=mapv.split(',')[1]
3221
3222        dx = lon0.shape[1]
3223        dy = lon0.shape[0]
3224
3225        nlon = lon0[0,0]
3226        xlon = lon0[dy-1,dx-1]
3227        nlat = lat0[0,0]
3228        xlat = lat0[dy-1,dx-1]
3229
3230        lon2 = lon0[dy/2,dx/2]
3231        lat2 = lat0[dy/2,dx/2]
3232
3233        if lonlatLims is not None:
3234            plt.xlim(lonlatLims[0], lonlatLims[2])
3235            plt.ylim(lonlatLims[1], lonlatLims[3])
3236            if map_proj == 'cyl':
3237                nlon = lonlatLims[0]
3238                nlat = lonlatLims[1]
3239                xlon = lonlatLims[2]
3240                xlat = lonlatLims[3]
3241
3242        print 'lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:',     \
3243          xlon, ',', xlat
3244
3245        if map_proj == 'cyl':
3246            m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat,         \
3247              urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res)
3248        elif map_proj == 'lcc':
3249            m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \
3250              llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res)
3251
3252        if len(olon.shape) == 3:
3253#            lons, lats = np.meshgrid(olon[0,:,:], olat[0,:,:])
3254            lons = olon[0,:,:]
3255            lats = olat[0,:,:]
3256
3257        elif len(olon.shape) == 2:
3258#            lons, lats = np.meshgrid(olon[:,:], olat[:,:])
3259            lons = olon[:,:]
3260            lats = olat[:,:]
3261        else:
3262            dx = olon.shape
3263            dy = olat.shape
3264#            print errormsg
3265#            print '  ' + fname + ': shapes of lon/lat objects', olon.shape,          \
3266#              'not ready!!!'
3267
3268        for il in range(Ntraj):
3269            plt.plot(lonval[il], latval[il], linekinds[N7lines], label= linesn[il])
3270            if il == 6: N7lines = N7lines + 1
3271
3272        m.drawcoastlines()
3273
3274        meridians = pretty_int(nlon,xlon,5)
3275        m.drawmeridians(meridians,labels=[True,False,False,True])
3276
3277        parallels = pretty_int(nlat,xlat,5)
3278        m.drawparallels(parallels,labels=[False,True,True,False])
3279
3280        plt.xlabel('W-E')
3281        plt.ylabel('S-N')
3282
3283    else:
3284        if len(olon.shape) == 3:
3285            dx = olon.shape[2]
3286            dy = olon.shape[1]
3287        elif len(olon.shape) == 2:
3288            dx = olon.shape[1]
3289            dy = olon.shape[0]
3290        else:
3291            dx = olon.shape
3292            dy = olat.shape
3293#            print errormsg
3294#            print '  ' + fname + ': shapes of lon/lat objects', olon.shape,          \
3295#              'not ready!!!'
3296
3297        if lonlatLims is not None:
3298            plt.xlim(lonlatLims[0], lonlatLims[2])
3299            plt.ylim(lonlatLims[1], lonlatLims[3])
3300        else:
3301            plt.xlim(np.min(olon[:]),np.max(olon[:]))
3302            plt.ylim(np.min(olat[:]),np.max(olat[:]))
3303
3304        for il in range(Ntraj):
3305            plt.plot(lonval[il], latval[il], linekinds[N7lines], label= linesn[il])
3306            if il == 6: N7lines = N7lines + 1
3307
3308        plt.xlabel('x-axis')
3309        plt.ylabel('y-axis')
3310
3311    figname = 'trajectories'
3312    graphtit = gtit
3313
3314    if obsname is not None:
3315        plt.plot(lonval[Ntraj], latval[Ntraj], linestyle='-', color='k',             \
3316          linewidth=3, label= obsname)
3317
3318    plt.title(graphtit.replace('_','\_').replace('&','\&'))
3319    plt.legend()
3320   
3321    output_kind(kfig, figname, True)
3322
3323    return
3324
3325def plot_topo_geogrid(varv, olon, olat, mint, maxt, lonlatLims, gtit, kfig, mapv,    \
3326  closeif):
3327    """ plotting geo_em.d[nn].nc topography from WPS files
3328    plot_topo_geogrid(domf, mint, maxt, gtit, kfig, mapv)
3329      varv= topography values
3330      o[lon/lat]= longitude and latitude objects
3331      [min/max]t: minimum and maximum values of topography to draw
3332      lonlatLims: limits of longitudes and latitudes [lonmin, latmin, lonmax, latmax]
3333      gtit= title of the graph
3334      kfig= kind of figure (jpg, pdf, png)
3335      mapv= map characteristics: [proj],[res]
3336        see full documentation: http://matplotlib.org/basemap/
3337        [proj]: projection
3338          * 'cyl', cilindric
3339          * 'lcc', lamvbert conformal
3340        [res]: resolution:
3341          * 'c', crude
3342          * 'l', low
3343          * 'i', intermediate
3344          * 'h', high
3345          * 'f', full
3346      closeif= Boolean value if the figure has to be closed
3347    """
3348    fname = 'plot_topo_geogrid'
3349
3350    if varv == 'h':
3351        print fname + '_____________________________________________________________'
3352        print plot_topo_geogrid.__doc__
3353        quit()
3354
3355    dx=varv.shape[1]
3356    dy=varv.shape[0]
3357
3358    plt.rc('text', usetex=True)
3359#    plt.rc('font', family='serif')
3360
3361    if not mapv is None:
3362        if len(olon[:].shape) == 3:
3363            lon0 = olon[0,]
3364            lat0 = olat[0,]
3365        elif len(olon[:].shape) == 2:
3366            lon0 = olon[:]
3367            lat0 = olat[:]
3368        elif len(olon[:].shape) == 1:
3369            lon00 = olon[:]
3370            lat00 = olat[:]
3371            lon0 = np.zeros( (len(lat00),len(lon00)), dtype=np.float )
3372            lat0 = np.zeros( (len(lat00),len(lon00)), dtype=np.float )
3373
3374            for iy in range(len(lat00)):
3375                lon0[iy,:] = lon00
3376            for ix in range(len(lon00)):
3377                lat0[:,ix] = lat00
3378
3379        map_proj=mapv.split(',')[0]
3380        map_res=mapv.split(',')[1]
3381        dx = lon0.shape[1]
3382        dy = lon0.shape[0]
3383
3384        if lonlatLims is not None:
3385            print '  ' + fname + ': cutting the domain to plot !!!!'
3386            print '    limits: W-E', lonlatLims[0], lonlatLims[2]
3387            print '    limits: N-S', lonlatLims[1], lonlatLims[3]
3388            nlon =  lonlatLims[0]
3389            xlon =  lonlatLims[2]
3390            nlat =  lonlatLims[1]
3391            xlat =  lonlatLims[3]
3392
3393            if map_proj == 'lcc':
3394                lon2 = (lonlatLims[0] + lonlatLims[2])/2.
3395                lat2 = (lonlatLims[1] + lonlatLims[3])/2.
3396        else:
3397            nlon = lon0[0,0]
3398            xlon = lon0[dy-1,dx-1]
3399            nlat = lat0[0,0]
3400            xlat = lat0[dy-1,dx-1]
3401            lon2 = lon0[dy/2,dx/2]
3402            lat2 = lat0[dy/2,dx/2]
3403
3404        plt.xlim(nlon, xlon)
3405        plt.ylim(nlat, xlat)
3406        print 'lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:',     \
3407          xlon, ',', xlat
3408
3409        if map_proj == 'cyl':
3410            m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat,         \
3411              urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res)
3412        elif map_proj == 'lcc':
3413            m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \
3414              llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res)
3415        else:
3416            print errormsg
3417            print '  ' + fname + ": map projection '" + map_proj + "' not ready !!"
3418            quit(-1)
3419
3420        if len(olon[:].shape) == 1:
3421            lons, lats = np.meshgrid(olon[:], olat[:])
3422        else:
3423            if len(olon[:].shape) == 3:
3424                lons = olon[0,:,:]
3425                lats = olat[0,:,:]
3426            else:
3427                lons = olon[:]
3428                lats = olat[:]
3429 
3430        x,y = m(lons,lats)
3431
3432        plt.pcolormesh(x,y,varv, cmap=plt.get_cmap('terrain'), vmin=mint, vmax=maxt)
3433        cbar = plt.colorbar()
3434
3435        m.drawcoastlines()
3436
3437        meridians = pretty_int(nlon,xlon,5)
3438        m.drawmeridians(meridians,labels=[True,False,False,True])
3439
3440        parallels = pretty_int(nlat,xlat,5)
3441        m.drawparallels(parallels,labels=[False,True,True,False])
3442
3443        plt.xlabel('W-E')
3444        plt.ylabel('S-N')
3445    else:
3446        print emsg
3447        print '  ' + fname + ': A projection parameter is needed None given !!'
3448        quit(-1)   
3449
3450    figname = 'domain'
3451    graphtit = gtit.replace('_','\_')
3452    cbar.set_label('height ($m$)')
3453
3454    plt.title(graphtit.replace('_','\_').replace('&','\&'))
3455   
3456    output_kind(kfig, figname, closeif)
3457
3458    return
3459
3460def plot_topo_geogrid_boxes(varv, boxesX, boxesY, boxlabels, olon, olat, mint, maxt, \
3461  lonlatLims, gtit, kfig, mapv, gloc, closeif):
3462    """ plotting geo_em.d[nn].nc topography from WPS files
3463    plot_topo_geogrid(domf, mint, maxt, gtit, kfig, mapv)
3464      varv= topography values
3465      boxesX/Y= 4-line sets to draw the boxes
3466      boxlabels= labels for the legend of the boxes
3467      o[lon/lat]= longitude and latitude objects
3468      [min/max]t: minimum and maximum values of topography to draw
3469      lonlatLims: limits of longitudes and latitudes [lonmin, latmin, lonmax, latmax]
3470      gtit= title of the graph
3471      kfig= kind of figure (jpg, pdf, png)
3472      mapv= map characteristics: [proj],[res]
3473        see full documentation: http://matplotlib.org/basemap/
3474        [proj]: projection
3475          * 'cyl', cilindric
3476          * 'lcc', lamvbert conformal
3477        [res]: resolution:
3478          * 'c', crude
3479          * 'l', low
3480          * 'i', intermediate
3481          * 'h', high
3482          * 'f', full
3483      gloc= location of the legend (0, autmoatic)
3484        1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
3485        5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
3486        9: 'upper center', 10: 'center'
3487      closeif= Boolean value if the figure has to be closed
3488    """
3489    fname = 'plot_topo_geogrid'
3490
3491    if varv == 'h':
3492        print fname + '_____________________________________________________________'
3493        print plot_topo_geogrid.__doc__
3494        quit()
3495
3496    cols = color_lines(len(boxlabels))
3497
3498    dx=varv.shape[1]
3499    dy=varv.shape[0]
3500
3501    plt.rc('text', usetex=True)
3502#    plt.rc('font', family='serif')
3503
3504    if not mapv is None:
3505        if len(olon[:].shape) == 3:
3506            lon0 = olon[0,]
3507            lat0 = olat[0,]
3508        elif len(olon[:].shape) == 2:
3509            lon0 = olon[:]
3510            lat0 = olat[:]
3511        elif len(olon[:].shape) == 1:
3512            lon00 = olon[:]
3513            lat00 = olat[:]
3514            lon0 = np.zeros( (len(lat00),len(lon00)), dtype=np.float )
3515            lat0 = np.zeros( (len(lat00),len(lon00)), dtype=np.float )
3516
3517            for iy in range(len(lat00)):
3518                lon0[iy,:] = lon00
3519            for ix in range(len(lon00)):
3520                lat0[:,ix] = lat00
3521
3522        map_proj=mapv.split(',')[0]
3523        map_res=mapv.split(',')[1]
3524        dx = lon0.shape[1]
3525        dy = lon0.shape[0]
3526
3527        if lonlatLims is not None:
3528            print '  ' + fname + ': cutting the domain to plot !!!!'
3529            print '    limits: W-E', lonlatLims[0], lonlatLims[2]
3530            print '    limits: N-S', lonlatLims[1], lonlatLims[3]
3531            nlon =  lonlatLims[0]
3532            xlon =  lonlatLims[2]
3533            nlat =  lonlatLims[1]
3534            xlat =  lonlatLims[3]
3535
3536            if map_proj == 'lcc':
3537                lon2 = (lonlatLims[0] + lonlatLims[2])/2.
3538                lat2 = (lonlatLims[1] + lonlatLims[3])/2.
3539        else:
3540            nlon = np.min(lon0)
3541            xlon = np.max(lon0)
3542            nlat = np.min(lat0)
3543            xlat = np.max(lat0)
3544            lon2 = lon0[dy/2,dx/2]
3545            lat2 = lat0[dy/2,dx/2]
3546
3547        plt.xlim(nlon, xlon)
3548        plt.ylim(nlat, xlat)
3549        print 'lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:',     \
3550          xlon, ',', xlat
3551
3552        if map_proj == 'cyl':
3553            m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat,         \
3554              urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res)
3555        elif map_proj == 'lcc':
3556            m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \
3557              llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res)
3558        else:
3559            print errormsg
3560            print '  ' + fname + ": projection '" + map_proj + "' does not exist!!"
3561            print '    existing ones: cyl, lcc'
3562            quit(-1)
3563
3564        if len(olon[:].shape) == 1:
3565            lons, lats = np.meshgrid(olon[:], olat[:])
3566        else:
3567            if len(olon[:].shape) == 3:
3568                lons = olon[0,:,:]
3569                lats = olat[0,:,:]
3570            else:
3571                lons = olon[:]
3572                lats = olat[:]
3573 
3574        x,y = m(lons,lats)
3575
3576        plt.pcolormesh(x,y,varv, cmap=plt.get_cmap('terrain'), vmin=mint, vmax=maxt)
3577        cbar = plt.colorbar()
3578
3579        Nboxes = len(boxesX)/4
3580        for ibox in range(Nboxes):
3581            plt.plot(boxesX[ibox*4], boxesY[ibox*4], linestyle='-', linewidth=3,     \
3582              label=boxlabels[ibox], color=cols[ibox])
3583            plt.plot(boxesX[ibox*4+1], boxesY[ibox*4+1], linestyle='-', linewidth=3, \
3584              color=cols[ibox])
3585            plt.plot(boxesX[ibox*4+2], boxesY[ibox*4+2], linestyle='-', linewidth=3, \
3586              color=cols[ibox])
3587            plt.plot(boxesX[ibox*4+3], boxesY[ibox*4+3], linestyle='-', linewidth=3, \
3588              color=cols[ibox])
3589
3590        m.drawcoastlines()
3591
3592        meridians = pretty_int(nlon,xlon,5)
3593        m.drawmeridians(meridians,labels=[True,False,False,True])
3594
3595        parallels = pretty_int(nlat,xlat,5)
3596        m.drawparallels(parallels,labels=[False,True,True,False])
3597
3598        plt.xlabel('W-E')
3599        plt.ylabel('S-N')
3600    else:
3601        print emsg
3602        print '  ' + fname + ': A projection parameter is needed None given !!'
3603        quit(-1)   
3604
3605    figname = 'domain_boxes'
3606    graphtit = gtit.replace('_','\_').replace('&','\&')
3607    cbar.set_label('height ($m$)')
3608
3609    plt.title(graphtit)
3610    plt.legend(loc=gloc)
3611   
3612    output_kind(kfig, figname, closeif)
3613
3614    return
3615
3616def plot_2D_shadow(varsv,vnames,dimxv,dimyv,dimxu,dimyu,dimn,          \
3617  colorbar,vs,uts,vtit,kfig,reva,mapv,ifclose):
3618    """ Adding labels and other staff to the graph
3619      varsv= 2D values to plot with shading
3620      vnames= variable names for the figure
3621      dim[x/y]v = values at the axes of x and y
3622      dim[x/y]u = units at the axes of x and y
3623      dimn= dimension names to plot
3624      colorbar= name of the color bar to use
3625      vs= minmum and maximum values to plot in shadow or:
3626        'Srange': for full range
3627        'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean)
3628        'Saroundminmax@val': for min*val,max*val
3629        'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val),
3630          percentile_(100-val)-median)
3631        'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean)
3632        'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median)
3633        'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val),
3634           percentile_(100-val)-median)
3635      uts= units of the variable to shadow
3636      vtit= title of the variable
3637      kfig= kind of figure (jpg, pdf, png)
3638      reva= ('|' for combination)
3639        * 'transpose': reverse the axes (x-->y, y-->x)
3640        * 'flip'@[x/y]: flip the axis x or y
3641      mapv= map characteristics: [proj],[res]
3642        see full documentation: http://matplotlib.org/basemap/
3643        [proj]: projection
3644          * 'cyl', cilindric
3645          * 'lcc', lambert conformal
3646        [res]: resolution:
3647          * 'c', crude
3648          * 'l', low
3649          * 'i', intermediate
3650          * 'h', high
3651          * 'f', full
3652      ifclose= boolean value whether figure should be close (finish) or not
3653    """
3654##    import matplotlib as mpl
3655##    mpl.use('Agg')
3656##    import matplotlib.pyplot as plt
3657    fname = 'plot_2D_shadow'
3658
3659#    print dimyv[73,21]
3660#    dimyv[73,21] = -dimyv[73,21]
3661#    print 'Lluis dimsv: ',np.min(dimxv), np.max(dimxv), ':', np.min(dimyv), np.max(dimyv)
3662
3663    if varsv == 'h':
3664        print fname + '_____________________________________________________________'
3665        print plot_2D_shadow.__doc__
3666        quit()
3667
3668    if len(varsv.shape) != 2:
3669        print errormsg
3670        print '  ' + fname + ': wrong variable shape:',varsv.shape,'is has to be 2D!!'
3671        quit(-1)
3672
3673    reva0 = ''
3674    if reva.find('|') != 0:
3675        revas = reva.split('|')
3676    else:
3677        revas = [reva]
3678        reva0 = reva
3679
3680    for rev in revas:
3681        if reva[0:4] == 'flip':
3682            reva0 = 'flip'
3683            if len(reva.split('@')) != 2:
3684                 print errormsg
3685                 print '  ' + fname + ': flip is given', reva, 'but not axis!'
3686                 quit(-1)
3687
3688        if rev == 'transpose':
3689            print '  reversing the axes of the figure (x-->y, y-->x)!!'
3690            varsv = np.transpose(varsv)
3691            dxv = dimyv
3692            dyv = dimxv
3693            dimxv = dxv
3694            dimyv = dyv
3695
3696    if len(dimxv[:].shape) == 3:
3697        xdims = '1,2'
3698    elif len(dimxv[:].shape) == 2:
3699        xdims = '0,1'
3700    elif len(dimxv[:].shape) == 1:
3701        xdims = '0'
3702
3703    if len(dimyv[:].shape) == 3:
3704        ydims = '1,2'
3705    elif len(dimyv[:].shape) == 2:
3706        ydims = '0,1'
3707    elif len(dimyv[:].shape) == 1:
3708        ydims = '0'
3709
3710#    lon0 = dimxv
3711#    lat0 = dimyv
3712    lon0, lat0 = dxdy_lonlat(dimxv,dimyv, xdims, ydims)
3713
3714    if not mapv is None:
3715        map_proj=mapv.split(',')[0]
3716        map_res=mapv.split(',')[1]
3717
3718        dx = lon0.shape[1]
3719        dy = lat0.shape[0]
3720
3721        nlon = lon0[0,0]
3722        xlon = lon0[dy-1,dx-1]
3723        nlat = lat0[0,0]
3724        xlat = lat0[dy-1,dx-1]
3725
3726# Thats too much! :)
3727#        if lonlatLims is not None:
3728#            print '  ' + fname + ': cutting the domain to plot !!!!'
3729#            plt.xlim(lonlatLims[0], lonlatLims[2])
3730#            plt.ylim(lonlatLims[1], lonlatLims[3])
3731#            print '    limits: W-E', lonlatLims[0], lonlatLims[2]
3732#            print '    limits: N-S', lonlatLims[1], lonlatLims[3]
3733
3734#            if map_proj == 'cyl':
3735#                nlon = lonlatLims[0]
3736#                nlat = lonlatLims[1]
3737#                xlon = lonlatLims[2]
3738#                xlat = lonlatLims[3]
3739#            elif map_proj == 'lcc':
3740#                lon2 = (lonlatLims[0] + lonlatLims[2])/2.
3741#                lat2 = (lonlatLims[1] + lonlatLims[3])/2.
3742#                nlon =  lonlatLims[0]
3743#                xlon =  lonlatLims[2]
3744#                nlat =  lonlatLims[1]
3745#                xlat =  lonlatLims[3]
3746
3747        lon2 = lon0[dy/2,dx/2]
3748        lat2 = lat0[dy/2,dx/2]
3749
3750        print 'lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:',     \
3751          xlon, ',', xlat
3752
3753        if map_proj == 'cyl':
3754            m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat,         \
3755              urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res)
3756        elif map_proj == 'lcc':
3757            m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \
3758              llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res)
3759        else:
3760            print errormsg
3761            print '  ' + fname + ": map projection '" + map_proj + "' not defined!!!"
3762            print '    available: cyl, lcc'
3763            quit(-1)
3764 
3765        x,y = m(lon0,lat0)
3766
3767    else:
3768        x = lon0
3769        y = lat0
3770
3771    vsend = np.zeros((2), dtype=np.float)
3772# Changing limits of the colors
3773    if type(vs[0]) != type(np.float(1.)):
3774        if vs[0] == 'Srange':
3775            vsend[0] = np.min(varsv)
3776        elif vs[0][0:11] == 'Saroundmean':
3777            meanv = np.mean(varsv)
3778            permean = np.float(vs[0].split('@')[1])
3779            minv = np.min(varsv)*permean
3780            maxv = np.max(varsv)*permean
3781            minextrm = np.min([np.abs(meanv-minv), np.abs(maxv-meanv)])
3782            vsend[0] = meanv-minextrm
3783            vsend[1] = meanv+minextrm
3784        elif vs[0][0:13] == 'Saroundminmax':
3785            permean = np.float(vs[0].split('@')[1])
3786            minv = np.min(varsv)*permean
3787            maxv = np.max(varsv)*permean
3788            vsend[0] = minv
3789            vsend[1] = maxv
3790        elif vs[0][0:17] == 'Saroundpercentile':
3791            medianv = np.median(varsv)
3792            valper = np.float(vs[0].split('@')[1])
3793            minv = np.percentile(varsv, valper)
3794            maxv = np.percentile(varsv, 100.-valper)
3795            minextrm = np.min([np.abs(medianv-minv), np.abs(maxv-medianv)])
3796            vsend[0] = medianv-minextrm
3797            vsend[1] = medianv+minextrm
3798        elif vs[0][0:5] == 'Smean':
3799            meanv = np.mean(varsv)
3800            permean = np.float(vs[0].split('@')[1])
3801            minv = np.min(varsv)*permean
3802            maxv = np.max(varsv)*permean
3803            minextrm = np.min([np.abs(meanv-minv), np.abs(maxv-meanv)])
3804            vsend[0] = -minextrm
3805            vsend[1] = minextrm
3806        elif vs[0][0:7] == 'Smedian':
3807            medianv = np.median(varsv)
3808            permedian = np.float(vs[0].split('@')[1])
3809            minv = np.min(varsv)*permedian
3810            maxv = np.max(varsv)*permedian
3811            minextrm = np.min([np.abs(medianv-minv), np.abs(maxv-medianv)])
3812            vsend[0] = -minextrm
3813            vsend[1] = minextrm
3814        elif vs[0][0:11] == 'Spercentile':
3815            medianv = np.median(varsv)
3816            valper = np.float(vs[0].split('@')[1])
3817            minv = np.percentile(varsv, valper)
3818            maxv = np.percentile(varsv, 100.-valper)
3819            minextrm = np.min([np.abs(medianv-minv), np.abs(maxv-medianv)])
3820            vsend[0] = -minextrm
3821            vsend[1] = minextrm
3822        else:
3823            print errormsg
3824            print '  ' + fname + ": range '" + vs[0] + "' not ready!!!"
3825            quit(-1)
3826        print '    ' + fname + ': modified shadow min,max:',vsend
3827    else:
3828        vsend[0] = vs[0]
3829
3830    if type(vs[0]) != type(np.float(1.)):
3831        if vs[1] == 'range':
3832            vsend[1] = np.max(varsv)
3833    else:
3834        vsend[1] = vs[1]
3835
3836    plt.rc('text', usetex=True)
3837
3838    plt.pcolormesh(x, y, varsv, cmap=plt.get_cmap(colorbar), vmin=vsend[0], vmax=vsend[1])
3839    cbar = plt.colorbar()
3840
3841    if not mapv is None:
3842        if colorbar == 'gist_gray':
3843            m.drawcoastlines(color="red")
3844        else:
3845            m.drawcoastlines()
3846
3847        meridians = pretty_int(nlon,xlon,5)
3848        m.drawmeridians(meridians,labels=[True,False,False,True])
3849        parallels = pretty_int(nlat,xlat,5)
3850        m.drawparallels(parallels,labels=[False,True,True,False])
3851
3852        plt.xlabel('W-E')
3853        plt.ylabel('S-N')
3854    else:
3855        plt.xlabel(variables_values(dimn[1])[0].replace('_','\_') + ' (' +           \
3856          units_lunits(dimxu) + ')')
3857        plt.ylabel(variables_values(dimn[0])[0].replace('_','\_') + ' (' +           \
3858          units_lunits(dimyu) + ')')
3859
3860    txpos = pretty_int(x.min(),x.max(),5)
3861    typos = pretty_int(y.min(),y.max(),5)
3862    txlabels = list(txpos)
3863    for i in range(len(txlabels)): txlabels[i] = str(txlabels[i])
3864    tylabels = list(typos)
3865    for i in range(len(tylabels)): tylabels[i] = str(tylabels[i])
3866
3867# set the limits of the plot to the limits of the data
3868
3869    if searchInlist(revas,'transpose'):
3870        x0 = y
3871        y0 = x
3872        x = x0
3873        y = y0
3874#    print 'Lluis reva0:',reva0,'x min,max:',x.min(),x.max(),' y min,max:',y.min(),y.max()
3875
3876    if reva0 == 'flip':
3877        if reva.split('@')[1] == 'x':
3878            plt.axis([x.max(), x.min(), y.min(), y.max()])
3879        elif reva.split('@')[1] == 'y':
3880            plt.axis([x.min(), x.max(), y.max(), y.min()])
3881        else:
3882            plt.axis([x.max(), x.min(), y.max(), y.min()])
3883    else:
3884        plt.axis([x.min(), x.max(), y.min(), y.max()])
3885
3886    if mapv is None:
3887        plt.xticks(txpos, txlabels)
3888        plt.yticks(typos, tylabels)
3889
3890# units labels
3891    cbar.set_label(vnames.replace('_','\_') + ' (' + units_lunits(uts) + ')')
3892
3893    figname = '2Dfields_shadow'
3894    graphtit = vtit.replace('_','\_').replace('&','\&')
3895
3896    plt.title(graphtit)
3897   
3898    output_kind(kfig, figname, ifclose)
3899
3900    return
3901
3902#Nvals=50
3903#vals1 = np.zeros((Nvals,Nvals), dtype= np.float)
3904#for j in range(Nvals):
3905#    for i in range(Nvals):
3906#      vals1[j,i]=np.sqrt((j-Nvals/2)**2. + (i-Nvals/2)**2.)
3907
3908#plot_2D_shadow(vals1, 'var1', np.arange(50)*1., np.arange(50)*1., 'ms-1',            \
3909#  'm', ['lat','lon'], 'rainbow', [0, Nvals], 'ms-1', 'test var1', 'pdf', 'None',     \
3910#  None, True)
3911#quit()
3912
3913def transform(vals, dxv, dyv, dxt, dyt, dxl, dyl, dxtit, dytit, trans):
3914    """ Function to transform the values and the axes
3915      vals= values to transform
3916      d[x/y]v= original values for the [x/y]-axis
3917      d[x/y]t= original ticks for the [x/y]-axis
3918      d[x/y]l= original tick-labels for the [x/y]-axis
3919      d[x/y]tit= original titels for the [x/y]-axis
3920      trans= '|' separated list of operations of transformation
3921        'transpose': Transpose matrix of values (x-->y, y-->x)
3922        'flip@[x/y]': Flip the given axis
3923    """
3924    fname = 'transform'
3925
3926    return newvals, newdxv, newdyv
3927
3928def plot_2D_shadow_time(varsv,vnames,dimxv,dimyv,dimxu,dimyu,dimn,colorbar,vs,uts,   \
3929  vtit,kfig,reva,taxis,tpos,tlabs,ifclose):
3930    """ Plotting a 2D field with one of the axes being time
3931      varsv= 2D values to plot with shading
3932      vnames= shading variable name for the figure
3933      dim[x/y]v= values at the axes of x and y
3934      dim[x/y]u= units at the axes of x and y
3935      dimn= dimension names to plot
3936      colorbar= name of the color bar to use
3937      vs= minmum and maximum values to plot in shadow or:
3938        'Srange': for full range
3939        'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean)
3940        'Saroundminmax@val': for min*val,max*val
3941        'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val),
3942          percentile_(100-val)-median)
3943        'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean)
3944        'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median)
3945        'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val),
3946           percentile_(100-val)-median)
3947      uts= units of the variable to shadow
3948      vtit= title of the variable
3949      kfig= kind of figure (jpg, pdf, png)
3950      reva=
3951        * 'transpose': reverse the axes (x-->y, y-->x)
3952        * 'flip'@[x/y]: flip the axis x or y
3953      taxis= Which is the time-axis
3954      tpos= positions of the time ticks
3955      tlabs= labels of the time ticks
3956      ifclose= boolean value whether figure should be close (finish) or not
3957    """
3958    fname = 'plot_2D_shadow_time'
3959
3960    if varsv == 'h':
3961        print fname + '_____________________________________________________________'
3962        print plot_2D_shadow_time.__doc__
3963        quit()
3964
3965# Definning ticks labels
3966    if taxis == 'x':
3967        txpos = tpos
3968        txlabels = tlabs
3969        plxlabel = dimxu
3970        typos = pretty_int(np.min(dimyv),np.max(dimyv),10)
3971        tylabels = list(typos)
3972        for i in range(len(tylabels)): tylabels[i] = str(tylabels[i])
3973        plylabel = variables_values(dimn[0])[0].replace('_','\_') + ' (' +           \
3974          units_lunits(dimyu) + ')'
3975    else:
3976        txpos = pretty_int(np.min(dimxv),np.max(dimxv),10)
3977        txlabels = list(txpos)
3978        plxlabel = variables_values(dimn[1])[0].replace('_','\_') + ' (' +           \
3979          units_lunits(dimxu) + ')'
3980        typos = tpos
3981        tylabels = tlabs
3982        plylabel = dimyu
3983
3984# Transposing/flipping axis
3985    if reva.find('|') != 0:
3986        revas = reva.split('|')
3987        reva0 = ''
3988    else:
3989        revas = [reva]
3990        reva0 = reva
3991
3992    for rev in revas:
3993        if rev[0:4] == 'flip':
3994            reva0 = 'flip'
3995            if len(reva.split('@')) != 2:
3996                 print errormsg
3997                 print '  ' + fname + ': flip is given', reva, 'but not axis!'
3998                 quit(-1)
3999            else:
4000                 print "  flipping '" + rev.split('@')[1] + "' axis !"
4001
4002        if rev == 'transpose':
4003            print '  reversing the axes of the figure (x-->y, y-->x)!!'
4004# Flipping values of variable
4005            varsv = np.transpose(varsv)
4006            dxv = dimyv
4007            dyv = dimxv
4008            dimxv = dxv
4009            dimyv = dyv
4010
4011    if len(dimxv.shape) == 3:
4012        dxget='1,2'
4013    elif len(dimxv.shape) == 2:
4014        dxget='0,1'
4015    elif len(dimxv.shape) == 1:
4016        dxget='0'
4017    else:
4018        print errormsg
4019        print '  ' + fname + ': shape of x-values:',dimxv.shape,'not ready!!'
4020        quit(-1)
4021
4022    if len(dimyv.shape) == 3:
4023        dyget='1,2'
4024    elif len(dimyv.shape) == 2:
4025        dyget='0,1'
4026    elif len(dimyv.shape) == 1:
4027        dyget='0'
4028    else:
4029        print errormsg
4030        print '  ' + fname + ': shape of y-values:',dimyv.shape,'not ready!!'
4031        quit(-1)
4032
4033    x,y = dxdy_lonlat(dimxv,dimyv,dxget,dyget)
4034
4035    plt.rc('text', usetex=True)
4036
4037    vsend = np.zeros((2), dtype=np.float)
4038# Changing limits of the colors
4039    if type(vs[0]) != type(np.float(1.)):
4040        if vs[0] == 'Srange':
4041            vsend[0] = np.min(varsv)
4042        elif vs[0][0:11] == 'Saroundmean':
4043            meanv = np.mean(varsv)
4044            permean = np.float(vs[0].split('@')[1])
4045            minv = np.min(varsv)*permean
4046            maxv = np.max(varsv)*permean
4047            minextrm = np.min([np.abs(meanv-minv), np.abs(maxv-meanv)])
4048            vsend[0] = meanv-minextrm
4049            vsend[1] = meanv+minextrm
4050        elif vs[0][0:13] == 'Saroundminmax':
4051            permean = np.float(vs[0].split('@')[1])
4052            minv = np.min(varsv)*permean
4053            maxv = np.max(varsv)*permean
4054            vsend[0] = minv
4055            vsend[1] = maxv
4056        elif vs[0][0:17] == 'Saroundpercentile':
4057            medianv = np.median(varsv)
4058            valper = np.float(vs[0].split('@')[1])
4059            minv = np.percentile(varsv, valper)
4060            maxv = np.percentile(varsv, 100.-valper)
4061            minextrm = np.min([np.abs(medianv-minv), np.abs(maxv-medianv)])
4062            vsend[0] = medianv-minextrm
4063            vsend[1] = medianv+minextrm
4064        elif vs[0][0:5] == 'Smean':
4065            meanv = np.mean(varsv)
4066            permean = np.float(vs[0].split('@')[1])
4067            minv = np.min(varsv)*permean
4068            maxv = np.max(varsv)*permean
4069            minextrm = np.min([np.abs(meanv-minv), np.abs(maxv-meanv)])
4070            vsend[0] = -minextrm
4071            vsend[1] = minextrm
4072        elif vs[0][0:7] == 'Smedian':
4073            medianv = np.median(varsv)
4074            permedian = np.float(vs[0].split('@')[1])
4075            minv = np.min(varsv)*permedian
4076            maxv = np.max(varsv)*permedian
4077            minextrm = np.min([np.abs(medianv-minv), np.abs(maxv-medianv)])
4078            vsend[0] = -minextrm
4079            vsend[1] = minextrm
4080        elif vs[0][0:11] == 'Spercentile':
4081            medianv = np.median(varsv)
4082            valper = np.float(vs[0].split('@')[1])
4083            minv = np.percentile(varsv, valper)
4084            maxv = np.percentile(varsv, 100.-valper)
4085            minextrm = np.min([np.abs(medianv-minv), np.abs(maxv-medianv)])
4086            vsend[0] = -minextrm
4087            vsend[1] = minextrm
4088        else:
4089            print errormsg
4090            print '  ' + fname + ": range '" + vs[0] + "' not ready!!!"
4091            quit(-1)
4092        print '    ' + fname + ': modified shadow min,max:',vsend
4093    else:
4094        vsend[0] = vs[0]
4095
4096    if type(vs[0]) != type(np.float(1.)):
4097        if vs[1] == 'range':
4098            vsend[1] = np.max(varsv)
4099    else:
4100        vsend[1] = vs[1]
4101
4102    plt.pcolormesh(x, y, varsv, cmap=plt.get_cmap(colorbar), vmin=vsend[0], vmax=vsend[1])
4103    cbar = plt.colorbar()
4104
4105#    print 'Lluis reva0:',reva0,'x min,max:',x.min(),x.max(),' y min,max:',y.min(),y.max()
4106
4107# set the limits of the plot to the limits of the data
4108    if reva0 == 'flip':
4109        if reva.split('@')[1] == 'x':
4110            plt.axis([x.max(), x.min(), y.min(), y.max()])
4111        elif reva.split('@')[1] == 'y':
4112            plt.axis([x.min(), x.max(), y.max(), y.min()])
4113        else:
4114            plt.axis([x.max(), x.min(), y.max(), y.min()])
4115    else:
4116        plt.axis([x.min(), x.max(), y.min(), y.max()])
4117
4118    if searchInlist(revas, 'transpose'):
4119        plt.xticks(typos, tylabels)
4120        plt.yticks(txpos, txlabels)
4121        plt.xlabel(plylabel)
4122        plt.ylabel(plxlabel)
4123    else:
4124        plt.xticks(txpos, txlabels)
4125        plt.yticks(typos, tylabels)
4126        plt.xlabel(plxlabel)
4127        plt.ylabel(plylabel)
4128
4129# units labels
4130    cbar.set_label(vnames.replace('_','\_') + ' (' + units_lunits(uts) + ')')
4131
4132    figname = '2Dfields_shadow_time'
4133    graphtit = vtit.replace('_','\_').replace('&','\&')
4134
4135    plt.title(graphtit)
4136   
4137    output_kind(kfig, figname, ifclose)
4138
4139    return
4140
4141def plot_2D_shadow_contour(varsv,varcv,vnames,dimxv,dimyv,dimxu,dimyu,dimn,          \
4142  colorbar,ckind,clabfmt,vs,vc,uts,vtit,kfig,reva,mapv):
4143    """ Adding labels and other staff to the graph
4144      varsv= 2D values to plot with shading
4145      varcv= 2D values to plot with contours
4146      vnames= variable names for the figure
4147      dim[x/y]v = values at the axes of x and y
4148      dim[x/y]u = units at the axes of x and y
4149      dimn= dimension names to plot
4150      colorbar= name of the color bar to use
4151      ckind= contour kind
4152        'cmap': as it gets from colorbar
4153        'fixc,[colname]': fixed color [colname], all stright lines
4154        'fixsigc,[colname]': fixed color [colname], >0 stright, <0 dashed  line
4155      clabfmt= format of the labels in the contour plot (None, no labels)
4156      vs= minmum and maximum values to plot in shadow
4157      vc= vector with the levels for the contour
4158      uts= units of the variable [u-shadow, u-contour]
4159      vtit= title of the variable
4160      kfig= kind of figure (jpg, pdf, png)
4161      reva=
4162        * 'transpose': reverse the axes (x-->y, y-->x)
4163        * 'flip'@[x/y]: flip the axis x or y
4164      mapv= map characteristics: [proj],[res]
4165        see full documentation: http://matplotlib.org/basemap/
4166        [proj]: projection
4167          * 'cyl', cilindric
4168          * 'lcc', lamvbert conformal
4169        [res]: resolution:
4170          * 'c', crude
4171          * 'l', low
4172          * 'i', intermediate
4173          * 'h', high
4174          * 'f', full
4175    """
4176##    import matplotlib as mpl
4177##    mpl.use('Agg')
4178##    import matplotlib.pyplot as plt
4179    fname = 'plot_2D_shadow_contour'
4180
4181    if varsv == 'h':
4182        print fname + '_____________________________________________________________'
4183        print plot_2D_shadow_contour.__doc__
4184        quit()
4185
4186    if reva[0:4] == 'flip':
4187        reva0 = 'flip'
4188        if len(reva.split('@')) != 2:
4189             print errormsg
4190             print '  ' + fname + ': flip is given', reva, 'but not axis!'
4191             quit(-1)
4192    else:
4193        reva0 = reva
4194
4195    if reva0 == 'transpose':
4196        print '  reversing the axes of the figure (x-->y, y-->x)!!'
4197        varsv = np.transpose(varsv)
4198        varcv = np.transpose(varcv)
4199        dxv = dimyv
4200        dyv = dimxv
4201        dimxv = dxv
4202        dimyv = dyv
4203
4204    if not mapv is None:
4205        if len(dimxv[:].shape) == 3:
4206            lon0 = dimxv[0,]
4207            lat0 = dimyv[0,]
4208        elif len(dimxv[:].shape) == 2:
4209            lon0 = dimxv[:]
4210            lat0 = dimyv[:]
4211        elif len(dimxv[:].shape) == 1:
4212            lon00 = dimxv[:]
4213            lat00 = dimyv[:]
4214            lon0 = np.zeros( (len(lat00),len(lon00)), dtype=np.float )
4215            lat0 = np.zeros( (len(lat00),len(lon00)), dtype=np.float )
4216
4217            for iy in range(len(lat00)):
4218                lon0[iy,:] = lon00
4219            for ix in range(len(lon00)):
4220                lat0[:,ix] = lat00
4221
4222        map_proj=mapv.split(',')[0]
4223        map_res=mapv.split(',')[1]
4224
4225        dx = lon0.shape[1]
4226        dy = lon0.shape[0]
4227
4228        nlon = lon0[0,0]
4229        xlon = lon0[dy-1,dx-1]
4230        nlat = lat0[0,0]
4231        xlat = lat0[dy-1,dx-1]
4232
4233# Thats too much! :)
4234#        if lonlatLims is not None:
4235#            print '  ' + fname + ': cutting the domain to plot !!!!'
4236#            plt.xlim(lonlatLims[0], lonlatLims[2])
4237#            plt.ylim(lonlatLims[1], lonlatLims[3])
4238#            print '    limits: W-E', lonlatLims[0], lonlatLims[2]
4239#            print '    limits: N-S', lonlatLims[1], lonlatLims[3]
4240
4241#            if map_proj == 'cyl':
4242#                nlon = lonlatLims[0]
4243#                nlat = lonlatLims[1]
4244#                xlon = lonlatLims[2]
4245#                xlat = lonlatLims[3]
4246#            elif map_proj == 'lcc':
4247#                lon2 = (lonlatLims[0] + lonlatLims[2])/2.
4248#                lat2 = (lonlatLims[1] + lonlatLims[3])/2.
4249#                nlon =  lonlatLims[0]
4250#                xlon =  lonlatLims[2]
4251#                nlat =  lonlatLims[1]
4252#                xlat =  lonlatLims[3]
4253
4254        lon2 = lon0[dy/2,dx/2]
4255        lat2 = lat0[dy/2,dx/2]
4256
4257        print 'lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:',     \
4258          xlon, ',', xlat
4259
4260        if map_proj == 'cyl':
4261            m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat,         \
4262              urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res)
4263        elif map_proj == 'lcc':
4264            m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \
4265              llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res)
4266
4267        if len(dimxv.shape) == 1:
4268            lons, lats = np.meshgrid(dimxv, dimyv)
4269        else:
4270            if len(dimxv.shape) == 3:
4271                lons = dimxv[0,:,:]
4272                lats = dimyv[0,:,:]
4273            else:
4274                lons = dimxv[:]
4275                lats = dimyv[:]
4276 
4277        x,y = m(lons,lats)
4278
4279    else:
4280        if len(dimxv.shape) == 2:
4281            x = dimxv
4282        else:
4283            if len(dimyv.shape) == 1:
4284                x = np.zeros((len(dimyv),len(dimxv)), dtype=np.float)
4285                for j in range(len(dimyv)):
4286                    x[j,:] = dimxv
4287            else:
4288                x = np.zeros((dimyv.shape), dtype=np.float)
4289                if x.shape[0] == dimxv.shape[0]:
4290                    for j in range(x.shape[1]):
4291                        x[:,j] = dimxv
4292                else:
4293                    for j in range(x.shape[0]):
4294                        x[j,:] = dimxv
4295
4296        if len(dimyv.shape) == 2:
4297            y = dimyv
4298        else:
4299            if len(dimxv.shape) == 1:
4300                y = np.zeros((len(dimyv),len(dimxv)), dtype=np.float)
4301                for i in range(len(dimxv)):
4302                    y[:,i] = dimyv
4303            else:
4304                y = np.zeros((dimxv.shape), dtype=np.float)
4305
4306                if y.shape[0] == dimyv.shape[0]:
4307                    for i in range(y.shape[1]):
4308                        y[i,:] = dimyv
4309                else:
4310                    for i in range(y.shape[0]):
4311                        y[i,:] = dimyv
4312
4313    plt.rc('text', usetex=True)
4314
4315    plt.pcolormesh(x, y, varsv, cmap=plt.get_cmap(colorbar), vmin=vs[0], vmax=vs[1])
4316    cbar = plt.colorbar()
4317
4318# contour
4319##
4320    contkind = ckind.split(',')[0]
4321    if contkind == 'cmap':
4322        cplot = plt.contour(x, y, varcv, levels=vc)
4323    elif  contkind == 'fixc':
4324        plt.rcParams['contour.negative_linestyle'] = 'solid'
4325        coln = ckind.split(',')[1]
4326        cplot = plt.contour(x, y, varcv, levels=vc, colors=coln)
4327    elif  contkind == 'fixsigc':
4328        coln = ckind.split(',')[1]
4329        cplot = plt.contour(x, y, varcv, levels=vc, colors=coln)
4330    else:
4331        print errormsg
4332        print '  ' + fname + ': contour kind "' + contkind + '" not defined !!!!!'
4333        quit(-1)
4334
4335    if clabfmt is not None:
4336        plt.clabel(cplot, fmt=clabfmt)
4337        mincntS = format(vc[0], clabfmt[1:len(clabfmt)])
4338        maxcntS = format(vc[len(vc)-1], clabfmt[1:len(clabfmt)])
4339    else:
4340        mincntS = '{:g}'.format(vc[0])
4341        maxcntS = '{:g}'.format(vc[len(vc)-1])       
4342
4343    if not mapv is None:
4344        m.drawcoastlines()
4345
4346        meridians = pretty_int(nlon,xlon,5)
4347        m.drawmeridians(meridians,labels=[True,False,False,True])
4348        parallels = pretty_int(nlat,xlat,5)
4349        m.drawparallels(parallels,labels=[False,True,True,False])
4350
4351        plt.xlabel('W-E')
4352        plt.ylabel('S-N')
4353    else:
4354        plt.xlabel(variables_values(dimn[1])[0] + ' (' + units_lunits(dimxu) + ')')
4355        plt.ylabel(variables_values(dimn[0])[0] + ' (' + units_lunits(dimyu) + ')')
4356
4357        txpos = pretty_int(x.min(),x.max(),5)
4358        typos = pretty_int(y.min(),y.max(),5)
4359        txlabels = list(txpos)
4360        for i in range(len(txlabels)): txlabels[i] = '{:.1f}'.format(txlabels[i])
4361        tylabels = list(typos)
4362        for i in range(len(tylabels)): tylabels[i] = '{:.1f}'.format(tylabels[i])
4363        plt.xticks(txpos, txlabels)
4364        plt.yticks(typos, tylabels)
4365
4366# set the limits of the plot to the limits of the data
4367    if reva0 == 'flip':
4368        if reva.split('@')[1] == 'x':
4369            plt.axis([x.max(), x.min(), y.min(), y.max()])
4370        else:
4371            plt.axis([x.min(), x.max(), y.max(), y.min()])
4372    else:
4373        plt.axis([x.min(), x.max(), y.min(), y.max()])
4374
4375
4376# units labels
4377    cbar.set_label(vnames[0].replace('_','\_') + ' (' + units_lunits(uts[0]) + ')')
4378    plt.annotate(vnames[1].replace('_','\_') +' (' + units_lunits(uts[1]) + ') [' +  \
4379      mincntS + ', ' + maxcntS + ']', xy=(0.55,0.04), xycoords='figure fraction',    \
4380      color=coln)
4381
4382    figname = '2Dfields_shadow-contour'
4383    graphtit = vtit.replace('_','\_').replace('&','\&')
4384
4385    plt.title(graphtit)
4386   
4387    output_kind(kfig, figname, True)
4388
4389    return
4390
4391#Nvals=50
4392#vals1 = np.zeros((Nvals,Nvals), dtype= np.float)
4393#vals2 = np.zeros((Nvals,Nvals), dtype= np.float)
4394#for j in range(Nvals):
4395#    for i in range(Nvals):
4396#      vals1[j,i]=np.sqrt((j-Nvals/2)**2. + (i-Nvals/2)**2.)
4397#      vals2[j,i]=np.sqrt((j-Nvals/2)**2. + (i-Nvals/2)**2.) - Nvals/2
4398
4399#prettylev=pretty_int(-Nvals/2,Nvals/2,10)
4400
4401#plot_2D_shadow_contour(vals1, vals2, ['var1', 'var2'], np.arange(50)*1.,             \
4402#  np.arange(50)*1., ['x-axis','y-axis'], 'rainbow', 'fixc,b', "%.2f", [0, Nvals],    \
4403#  prettylev, ['$ms^{-1}$','$kJm^{-1}s^{-1}$'], 'test var1 & var2', 'pdf', False)
4404
4405def plot_2D_shadow_contour_time(varsv,varcv,vnames,valv,timv,timpos,timlab,valu,     \
4406  timeu,axist,dimn,colorbar,ckind,clabfmt,vs,vc,uts,vtit,kfig,reva,mapv):
4407    """ Adding labels and other staff to the graph
4408      varsv= 2D values to plot with shading
4409      varcv= 2D values to plot with contours
4410      vnames= variable names for the figure
4411      valv = values at the axes which is not time
4412      timv = values for the axis time
4413      timpos = positions at the axis time
4414      timlab = labes at the axis time
4415      valu = units at the axes which is not time
4416      timeu = units at the axes which is not time
4417      axist = which is the axis time
4418      dimn= dimension names to plot
4419      colorbar= name of the color bar to use
4420      ckind= contour kind
4421        'cmap': as it gets from colorbar
4422        'fixc,[colname]': fixed color [colname], all stright lines
4423        'fixsigc,[colname]': fixed color [colname], >0 stright, <0 dashed  line
4424      clabfmt= format of the labels in the contour plot (None, no labels)
4425      vs= minmum and maximum values to plot in shadow
4426      vc= vector with the levels for the contour
4427      uts= units of the variable [u-shadow, u-contour]
4428      vtit= title of the variable
4429      kfig= kind of figure (jpg, pdf, png)
4430      reva=
4431        * 'transpose': reverse the axes (x-->y, y-->x)
4432        * 'flip'@[x/y]: flip the axis x or y
4433      mapv= map characteristics: [proj],[res]
4434        see full documentation: http://matplotlib.org/basemap/
4435        [proj]: projection
4436          * 'cyl', cilindric
4437          * 'lcc', lamvbert conformal
4438        [res]: resolution:
4439          * 'c', crude
4440          * 'l', low
4441          * 'i', intermediate
4442          * 'h', high
4443          * 'f', full
4444    """
4445##    import matplotlib as mpl
4446##    mpl.use('Agg')
4447##    import matplotlib.pyplot as plt
4448    fname = 'plot_2D_shadow_contour'
4449
4450    if varsv == 'h':
4451        print fname + '_____________________________________________________________'
4452        print plot_2D_shadow_contour.__doc__
4453        quit()
4454
4455    if axist == 'x':
4456        dimxv = timv.copy()
4457        dimyv = valv.copy()
4458    else:
4459        dimxv = valv.copy()
4460        dimyv = timv.copy()
4461
4462    if reva[0:4] == 'flip':
4463        reva0 = 'flip'
4464        if len(reva.split('@')) != 2:
4465             print errormsg
4466             print '  ' + fname + ': flip is given', reva, 'but not axis!'
4467             quit(-1)
4468    else:
4469        reva0 = reva
4470
4471    if reva0 == 'transpose':
4472        if axist == 'x': 
4473            axist = 'y'
4474        else:
4475            axist = 'x'
4476
4477    if not mapv is None:
4478        if len(dimxv[:].shape) == 3:
4479            lon0 = dimxv[0,]
4480            lat0 = dimyv[0,]
4481        elif len(dimxv[:].shape) == 2:
4482            lon0 = dimxv[:]
4483            lat0 = dimyv[:]
4484        elif len(dimxv[:].shape) == 1:
4485            lon00 = dimxv[:]
4486            lat00 = dimyv[:]
4487            lon0 = np.zeros( (len(lat00),len(lon00)), dtype=np.float )
4488            lat0 = np.zeros( (len(lat00),len(lon00)), dtype=np.float )
4489
4490            for iy in range(len(lat00)):
4491                lon0[iy,:] = lon00
4492            for ix in range(len(lon00)):
4493                lat0[:,ix] = lat00
4494        if reva0 == 'transpose':
4495            print '  reversing the axes of the figure (x-->y, y-->x)!!'
4496            varsv = np.transpose(varsv)
4497            varcv = np.transpose(varcv)
4498            lon0 = np.transpose(lon0)
4499            lat0 = np.transpose(lat0)
4500
4501        map_proj=mapv.split(',')[0]
4502        map_res=mapv.split(',')[1]
4503
4504        dx = lon0.shape[1]
4505        dy = lon0.shape[0]
4506
4507        nlon = lon0[0,0]
4508        xlon = lon0[dy-1,dx-1]
4509        nlat = lat0[0,0]
4510        xlat = lat0[dy-1,dx-1]
4511
4512# Thats too much! :)
4513#        if lonlatLims is not None:
4514#            print '  ' + fname + ': cutting the domain to plot !!!!'
4515#            plt.xlim(lonlatLims[0], lonlatLims[2])
4516#            plt.ylim(lonlatLims[1], lonlatLims[3])
4517#            print '    limits: W-E', lonlatLims[0], lonlatLims[2]
4518#            print '    limits: N-S', lonlatLims[1], lonlatLims[3]
4519
4520#            if map_proj == 'cyl':
4521#                nlon = lonlatLims[0]
4522#                nlat = lonlatLims[1]
4523#                xlon = lonlatLims[2]
4524#                xlat = lonlatLims[3]
4525#            elif map_proj == 'lcc':
4526#                lon2 = (lonlatLims[0] + lonlatLims[2])/2.
4527#                lat2 = (lonlatLims[1] + lonlatLims[3])/2.
4528#                nlon =  lonlatLims[0]
4529#                xlon =  lonlatLims[2]
4530#                nlat =  lonlatLims[1]
4531#                xlat =  lonlatLims[3]
4532
4533        lon2 = lon0[dy/2,dx/2]
4534        lat2 = lat0[dy/2,dx/2]
4535
4536        print 'lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:',     \
4537          xlon, ',', xlat
4538
4539        if map_proj == 'cyl':
4540            m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat,         \
4541              urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res)
4542        elif map_proj == 'lcc':
4543            m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \
4544              llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res)
4545
4546        if len(dimxv.shape) == 1:
4547            lons, lats = np.meshgrid(dimxv, dimyv)
4548        else:
4549            if len(dimxv.shape) == 3:
4550                lons = dimxv[0,:,:]
4551                lats = dimyv[0,:,:]
4552            else:
4553                lons = dimxv[:]
4554                lats = dimyv[:]
4555 
4556        x,y = m(lons,lats)
4557
4558    else:
4559        if reva0  == 'transpose':
4560            print '  reversing the axes of the figure (x-->y, y-->x)!!'
4561            varsv = np.transpose(varsv)
4562            varcv = np.transpose(varcv)
4563            dimn0 = []
4564            dimn0.append(dimn[1] + '')
4565            dimn0.append(dimn[0] + '')
4566            dimn = dimn0
4567            if len(dimyv.shape) == 2:
4568                x = np.transpose(dimyv)
4569            else:
4570                if len(dimxv.shape) == 2:
4571                    ddx = len(dimyv)
4572                    ddy = dimxv.shape[1]
4573                else:
4574                    ddx = len(dimyv)
4575                    ddy = len(dimxv)
4576   
4577                x = np.zeros((ddy,ddx), dtype=np.float)
4578                for j in range(ddy):
4579                    x[j,:] = dimyv
4580
4581            if len(dimxv.shape) == 2:
4582                y = np.transpose(dimxv)
4583            else:
4584                if len(dimyv.shape) == 2:
4585                    ddx = dimyv.shape[0]
4586                    ddy = len(dimxv)
4587                else:
4588                    ddx = len(dimyv)
4589                    ddy = len(dimxv)
4590
4591                y = np.zeros((ddy,ddx), dtype=np.float)
4592                for i in range(ddx):
4593                    y[:,i] = dimxv
4594        else:
4595            if len(dimxv.shape) == 2:
4596                x = dimxv
4597            else:
4598                if len(dimyv.shape) == 1:
4599                    x = np.zeros((len(dimyv),len(dimxv)), dtype=np.float)
4600                    for j in range(len(dimyv)):
4601                        x[j,:] = dimxv
4602                else:
4603                    x = np.zeros((dimyv.shape), dtype=np.float)
4604                    if x.shape[0] == dimxv.shape[0]:
4605                        for j in range(x.shape[1]):
4606                            x[:,j] = dimxv
4607                    else:
4608                        for j in range(x.shape[0]):
4609                            x[j,:] = dimxv
4610
4611            if len(dimyv.shape) == 2:
4612                y = dimyv
4613            else:
4614                if len(dimxv.shape) == 1:
4615                    y = np.zeros((len(dimyv),len(dimxv)), dtype=np.float)
4616                    for i in range(len(dimxv)):
4617                        y[:,i] = dimyv
4618                else:
4619                    y = np.zeros((dimxv.shape), dtype=np.float)
4620                    if y.shape[0] == dimyv.shape[0]:
4621                        for i in range(y.shape[1]):
4622                            y[:,i] = dimyv
4623                    else:
4624                        for i in range(y.shape[0]):
4625                            y[i,:] = dimyv
4626
4627    dx=varsv.shape[1]
4628    dy=varsv.shape[0]
4629   
4630    plt.rc('text', usetex=True)
4631
4632    if axist == 'x':
4633        valpos = pretty_int(y.min(),y.max(),10)
4634        vallabels = list(valpos)
4635        for i in range(len(vallabels)): vallabels[i] = str(vallabels[i])
4636    else:
4637        valpos = pretty_int(x.min(),x.max(),10)
4638        vallabels = list(valpos)
4639        for i in range(len(vallabels)): vallabels[i] = str(vallabels[i])
4640
4641    if reva0 == 'flip':
4642        if reva.split('@')[1] == 'x':
4643            varsv[:,0:dx-1] = varsv[:,dx-1:0:-1]
4644            varcv[:,0:dx-1] = varcv[:,dx-1:0:-1]
4645            plt.xticks(valpos, vallabels[::-1])
4646        else:
4647            varsv[0:dy-1,:] = varsv[dy-1:0:-1,:]
4648            varcv[0:dy-1,:] = varcv[dy-1:0:-1,:]
4649            plt.yticks(valpos, vallabels[::-1])
4650    else:
4651        plt.xlim(0,dx-1)
4652        plt.ylim(0,dy-1)
4653
4654    plt.pcolormesh(x, y, varsv, cmap=plt.get_cmap(colorbar), vmin=vs[0], vmax=vs[1])
4655    cbar = plt.colorbar()
4656   
4657# contour
4658##
4659    contkind = ckind.split(',')[0]
4660    if contkind == 'cmap':
4661        cplot = plt.contour(x, y, varcv, levels=vc)
4662    elif  contkind == 'fixc':
4663        plt.rcParams['contour.negative_linestyle'] = 'solid'
4664        coln = ckind.split(',')[1]
4665        cplot = plt.contour(x, y, varcv, levels=vc, colors=coln)
4666    elif  contkind == 'fixsigc':
4667        coln = ckind.split(',')[1]
4668        cplot = plt.contour(x, y, varcv, levels=vc, colors=coln)
4669    else:
4670        print errormsg
4671        print '  ' + fname + ': contour kind "' + contkind + '" not defined !!!!!'
4672        quit(-1)
4673
4674    if clabfmt is not None:
4675        plt.clabel(cplot, fmt=clabfmt)
4676        mincntS = format(vc[0], clabfmt[1:len(clabfmt)])
4677        maxcntS = format(vc[len(vc)-1], clabfmt[1:len(clabfmt)])
4678    else:
4679        mincntS = '{:g}'.format(vc[0])
4680        maxcntS = '{:g}'.format(vc[len(vc)-1])       
4681
4682    if not mapv is None:
4683        m.drawcoastlines()
4684
4685        meridians = pretty_int(nlon,xlon,5)
4686        m.drawmeridians(meridians,labels=[True,False,False,True])
4687        parallels = pretty_int(nlat,xlat,5)
4688        m.drawparallels(parallels,labels=[False,True,True,False])
4689
4690        plt.xlabel('W-E')
4691        plt.ylabel('S-N')
4692    else:
4693        if axist == 'x':
4694            plt.xlabel(timeu)
4695            plt.xticks(timpos, timlab)
4696            plt.ylabel(variables_values(dimn[0])[0] + ' (' + units_lunits(valu) + ')')
4697            plt.yticks(valpos, vallabels)
4698        else:
4699            plt.xlabel(variables_values(dimn[1])[0] + ' (' + units_lunits(valu) + ')')
4700            plt.xticks(valpos, vallabels)
4701            plt.ylabel(timeu)
4702            plt.yticks(timpos, timlab)
4703
4704# set the limits of the plot to the limits of the data
4705    plt.axis([x.min(), x.max(), y.min(), y.max()])
4706
4707# units labels
4708    cbar.set_label(vnames[0].replace('_','\_') + ' (' + units_lunits(uts[0]) + ')')
4709    plt.annotate(vnames[1].replace('_','\_') +' (' + units_lunits(uts[1]) + ') [' +  \
4710      mincntS + ', ' + maxcntS + ']', xy=(0.55,0.04), xycoords='figure fraction',    \
4711      color=coln)
4712
4713    figname = '2Dfields_shadow-contour'
4714    graphtit = vtit.replace('_','\_').replace('&','\&')
4715
4716    plt.title(graphtit)
4717   
4718    output_kind(kfig, figname, True)
4719
4720    return
4721
4722def dxdy_lonlat(dxv,dyv,ddx,ddy):
4723    """ Function to provide lon/lat 2D lilke-matrices from any sort of dx,dy values
4724    dxdy_lonlat(dxv,dyv,Lv,lv)
4725      dx: values for the x
4726      dy: values for the y
4727      ddx: ',' list of which dimensions to use from values along x
4728      ddy: ',' list of which dimensions to use from values along y
4729    """
4730
4731    fname = 'dxdy_lonlat'
4732
4733    if ddx.find(',') > -1:
4734        dxk = 2
4735        ddxv = ddx.split(',')
4736        ddxy = int(ddxv[0])
4737        ddxx = int(ddxv[1])
4738    else:
4739        dxk = 1
4740        ddxy = int(ddx)
4741        ddxx = int(ddx)
4742
4743    if ddy.find(',') > -1:
4744        dyk = 2
4745        ddyv = ddy.split(',')
4746        ddyy = int(ddyv[0])
4747        ddyx = int(ddyv[1])
4748    else:
4749        dyk = 1
4750        ddyy = int(ddy)
4751        ddyx = int(ddy)
4752
4753    ddxxv = dxv.shape[ddxx]
4754    ddxyv = dxv.shape[ddxy]
4755    ddyxv = dyv.shape[ddyx]
4756    ddyyv = dyv.shape[ddyy]
4757
4758    slicex = []
4759    if len(dxv.shape) > 1:
4760        for idim in range(len(dxv.shape)):
4761            if idim == ddxx or idim == ddxy:
4762                slicex.append(slice(0,dxv.shape[idim]))
4763            else:
4764                slicex.append(0)
4765    else:
4766        slicex.append(slice(0,len(dxv)))
4767
4768    slicey = []
4769    if len(dyv.shape) > 1:
4770        for idim in range(len(dyv.shape)):
4771            if idim == ddyx or idim == ddyy:
4772                slicey.append(slice(0,dyv.shape[idim]))
4773            else:
4774                slicey.append(0)
4775    else:
4776        slicey.append(slice(0,len(dyv)))
4777
4778    if dxk == 2 and dyk == 2:
4779        if ddxxv != ddyxv:
4780            print errormsg
4781            print '  ' + fname + ': wrong dx dimensions! ddxx=',ddxxv,'ddyx=',ddyxv
4782            print '    choose another for x:',dxv.shape,'or y:',dyv.shape
4783            quit(-1)
4784        if ddxyv != ddyyv:
4785            print errormsg
4786            print '  ' + fname + ': wrong dy dimensions! ddxy=',ddxyv,'ddyy=',ddyv
4787            print '    choose another for x:',dxv.shape,'or y:',dyv.shape
4788            quit(-1)
4789        dx = ddxxv
4790        dy = ddxyv
4791
4792        print '  ' + fname + ': final dimension 2D lon/lat-like matrices:',dy,',',dx
4793        lonv = np.zeros((dy,dx), dtype=np.float)
4794        latv = np.zeros((dy,dx), dtype=np.float)
4795
4796
4797        lonv = dxv[tuple(slicex)]
4798        latv = dyv[tuple(slicey)]
4799
4800    elif dxk == 2 and dyk == 1:
4801        if not ddxxv == ddyxv and not ddxyv == ddyyv:
4802            print errormsg
4803            print '  ' + fname + ': wrong dimensions! ddxx=',ddxxv,'ddyx=',ddyxv,    \
4804              'ddyx=',ddyxv,'ddyy=',ddyyv
4805            print '    choose another for x:',dxv.shape,'or y:',dyv.shape
4806            quit(-1)
4807        dx = ddxvv
4808        dy = ddxyv
4809
4810        print '  ' + fname + ': final dimension 2D lon/lat-like matrices:',dy,',',dx
4811        lonv = np.zeros((dy,dx), dtype=np.float)
4812        latv = np.zeros((dy,dx), dtype=np.float)
4813        lonv = dxv[tuple(slicex)]
4814
4815        if ddxxv == ddyxv: 
4816            for iy in range(dy):
4817                latv[iy,:] = dyv[tuple(slicey)]
4818        else:
4819            for ix in range(dx):
4820                latv[:,ix] = dyv[tuple(slicey)]
4821
4822    elif dxk == 1 and dyk == 2:
4823        if not ddxxv == ddyxv and not ddxyv == ddyyv:
4824            print errormsg
4825            print '  ' + fname + ': wrong dimensions! ddxx=',ddxxv,'ddyx=',ddyxv,    \
4826              'ddyx=',ddyxv,'ddyy=',ddyyv
4827            print '    choose another for x:',dxv.shape,'or y:',dyv.shape
4828            quit(-1)
4829        dx = ddyxv
4830        dy = ddyyv
4831 
4832        print '  ' + fname + ': final dimension 2D lon/lat-like matrices:',dy,',',dx
4833        lonv = np.zeros((dy,dx), dtype=np.float)
4834        latv = np.zeros((dy,dx), dtype=np.float)
4835
4836        latv = dyv[tuple(slicey)]
4837
4838        if ddyxv == ddxxv: 
4839            for iy in range(dy):
4840                lonv[iy,:] = dxv[tuple(slicex)]
4841        else:
4842            for ix in range(dx):
4843                lonv[:,ix] = dxv[tuple(slicex)]
4844
4845
4846    elif dxk == 1 and dyk == 1:
4847        dx = ddxxv
4848        dy = ddyyv
4849 
4850#        print 'dx:',dx,'dy:',dy
4851
4852        lonv = np.zeros((dy,dx), dtype=np.float)
4853        latv = np.zeros((dy,dx), dtype=np.float)
4854
4855        for iy in range(dy):
4856            lonv[iy,:] = dxv[tuple(slicex)]
4857        for ix in range(dx):
4858            latv[:,ix] = dyv[tuple(slicey)]
4859
4860    return lonv,latv
4861
4862def dxdy_lonlatDIMS(dxv,dyv,dnx,dny,dd):
4863    """ Function to provide lon/lat 2D lilke-matrices from any sort of dx,dy values for a given
4864      list of values
4865    dxdy_lonlat(dxv,dyv,Lv,lv)
4866      dxv: values for the x
4867      dyv: values for the y
4868      dnx: mnames of the dimensions for values on x
4869      dny: mnames of the dimensions for values on y
4870      dd: list of [dimname]|[val] for the dimensions use
4871        [dimname]: name of the dimension
4872        [val]: value (-1 for all the range)
4873    """
4874    fname = 'dxdy_lonlatDIMS'
4875
4876    slicex = []
4877    ipos=0
4878    for dn in dnx:
4879        for idd in range(len(dd)):
4880            dname = dd[idd].split('|')[0]
4881            dvalue = dd[idd].split('|')[1]
4882            if dn == dname:
4883                if dvalue.find('@') != -1:
4884                    slicex.append(slice(int(dvalue.split('@')[0]),                   \
4885                      int(dvalue.split('@')[1])))
4886                else:
4887                    if int(dvalue) == -1:
4888                        slicex.append(slice(0,dxv.shape[ipos]))
4889                    elif int(dvalue) == -9:
4890                        slicex.append(dxv.shape[ipos]-1)
4891                    else:
4892                        slicex.append(int(dvalue))
4893                    break
4894        ipos = ipos + 1
4895
4896    slicey = []
4897    ipos=0
4898    for dn in dny:
4899        for idd in range(len(dd)):
4900            dname = dd[idd].split('|')[0]
4901            dvalue = dd[idd].split('|')[1]
4902            if dn == dname:
4903                if dvalue.find('@') != -1:
4904                    slicey.append(slice(int(dvalue.split('@')[0]),                   \
4905                      int(dvalue.split('@')[1])))
4906                else:
4907                    if int(dvalue) == -1:
4908                        slicey.append(slice(0,dyv.shape[ipos]))
4909                    elif int(dvalue) == -9:
4910                        slicey.append(dyv.shape[ipos]-1)
4911                    else:
4912                        slicey.append(int(dvalue))
4913                    break
4914        ipos = ipos + 1
4915
4916    lonv = dxv[tuple(slicex)]
4917    latv = dyv[tuple(slicey)]
4918
4919    if len(lonv.shape) != len(latv.shape):
4920        print '  ' + fname + ': dimension size on x:', len(lonv.shape), 'and on y:', \
4921          len(latv.shape),'do not coincide!!'
4922        quit(-1)
4923
4924    return lonv,latv
4925
4926def plot_2D_shadow_line(varsv,varlv,vnames,vnamel,dimxv,dimyv,dimxu,dimyu,dimn,             \
4927  colorbar,colln,vs,uts,utl,vtit,kfig,reva,mapv,ifclose):
4928    """ Plotting a 2D field with shadows and another one with a line
4929      varsv= 2D values to plot with shading
4930      varlv= 1D values to plot with line
4931      vnames= variable names for the shadow variable in the figure
4932      vnamel= variable names for the line varibale in the figure
4933      dim[x/y]v = values at the axes of x and y
4934      dim[x/y]u = units at the axes of x and y
4935      dimn= dimension names to plot
4936      colorbar= name of the color bar to use
4937      colln= color for the line
4938      vs= minmum and maximum values to plot in shadow
4939      uts= units of the variable to shadow
4940      utl= units of the variable to line
4941      vtit= title of the variable
4942      kfig= kind of figure (jpg, pdf, png)
4943      reva=
4944        * 'transpose': reverse the axes (x-->y, y-->x)
4945        * 'flip'@[x/y]: flip the axis x or y
4946      mapv= map characteristics: [proj],[res]
4947        see full documentation: http://matplotlib.org/basemap/
4948        [proj]: projection
4949          * 'cyl', cilindric
4950          * 'lcc', lambert conformal
4951        [res]: resolution:
4952          * 'c', crude
4953          * 'l', low
4954          * 'i', intermediate
4955          * 'h', high
4956          * 'f', full
4957      ifclose= boolean value whether figure should be close (finish) or not
4958    """
4959##    import matplotlib as mpl
4960##    mpl.use('Agg')
4961##    import matplotlib.pyplot as plt
4962    fname = 'plot_2D_shadow_line'
4963
4964    if varsv == 'h':
4965        print fname + '_____________________________________________________________'
4966        print plot_2D_shadow_line.__doc__
4967        quit()
4968
4969    if reva[0:4] == 'flip':
4970        reva0 = 'flip'
4971        if len(reva.split('@')) != 2:
4972             print errormsg
4973             print '  ' + fname + ': flip is given', reva, 'but not axis!'
4974             quit(-1)
4975    else:
4976        reva0 = reva
4977
4978    if reva0 == 'transpose':
4979        print '  reversing the axes of the figure (x-->y, y-->x)!!'
4980        varsv = np.transpose(varsv)
4981        dxv = dimyv
4982        dyv = dimxv
4983        dimxv = dxv
4984        dimyv = dyv
4985
4986    if len(dimxv[:].shape) == 3:
4987        lon0 = dimxv[0,]
4988    elif len(dimxv[:].shape) == 2:
4989        lon0 = dimxv[:]
4990
4991    if len(dimyv[:].shape) == 3:
4992        lat0 = dimyv[0,]
4993    elif len(dimyv[:].shape) == 2:
4994        lat0 = dimyv[:]
4995
4996    if len(dimxv[:].shape) == 1 and len(dimyv[:].shape) == 1:
4997        lon00 = dimxv[:]
4998        lon0 = np.zeros( (len(lat00),len(lon00)), dtype=np.float )
4999
5000        for iy in range(len(lat00)):
5001            lon0[iy,:] = lon00
5002        for ix in range(len(lon00)):
5003            lat0[:,ix] = lat00
5004
5005    if not mapv is None:
5006        map_proj=mapv.split(',')[0]
5007        map_res=mapv.split(',')[1]
5008
5009        dx = lon0.shape[1]
5010        dy = lat0.shape[0]
5011
5012        nlon = lon0[0,0]
5013        xlon = lon0[dy-1,dx-1]
5014        nlat = lat0[0,0]
5015        xlat = lat0[dy-1,dx-1]
5016
5017# Thats too much! :)
5018#        if lonlatLims is not None:
5019#            print '  ' + fname + ': cutting the domain to plot !!!!'
5020#            plt.xlim(lonlatLims[0], lonlatLims[2])
5021#            plt.ylim(lonlatLims[1], lonlatLims[3])
5022#            print '    limits: W-E', lonlatLims[0], lonlatLims[2]
5023#            print '    limits: N-S', lonlatLims[1], lonlatLims[3]
5024
5025#            if map_proj == 'cyl':
5026#                nlon = lonlatLims[0]
5027#                nlat = lonlatLims[1]
5028#                xlon = lonlatLims[2]
5029#                xlat = lonlatLims[3]
5030#            elif map_proj == 'lcc':
5031#                lon2 = (lonlatLims[0] + lonlatLims[2])/2.
5032#                lat2 = (lonlatLims[1] + lonlatLims[3])/2.
5033#                nlon =  lonlatLims[0]
5034#                xlon =  lonlatLims[2]
5035#                nlat =  lonlatLims[1]
5036#                xlat =  lonlatLims[3]
5037
5038        lon2 = lon0[dy/2,dx/2]
5039        lat2 = lat0[dy/2,dx/2]
5040
5041        print 'lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:',     \
5042          xlon, ',', xlat
5043
5044        if map_proj == 'cyl':
5045            m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat,         \
5046              urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res)
5047        elif map_proj == 'lcc':
5048            m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \
5049              llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res)
5050        else:
5051            print errormsg
5052            print '  ' + fname + ": map projection '" + map_proj + "' not defined!!!"
5053            print '    available: cyl, lcc'
5054            quit(-1)
5055
5056        if len(dimxv.shape) == 1:
5057            lons, lats = np.meshgrid(dimxv, dimyv)
5058        else:
5059            if len(dimxv.shape) == 3:
5060                lons = dimxv[0,:,:]
5061            else:
5062                lons = dimxv[:]
5063
5064            if len(dimyv.shape) == 3:
5065                lats = dimyv[0,:,:]
5066            else:
5067                lats = dimyv[:]
5068 
5069        x,y = m(lons,lats)
5070
5071    else:
5072        if len(dimxv.shape) == 3:
5073            x = dimxv[0,:,:]
5074        elif len(dimxv.shape) == 2:
5075            x = dimxv
5076        else:
5077# Attempt of simplier way...
5078#            x = np.zeros((lon0.shape), dtype=np.float)
5079#            for j in range(lon0.shape[0]):
5080#                x[j,:] = dimxv
5081
5082## This way is too complicated and maybe not necessary ? (assuming dimxv.shape == dimyv.shape)
5083            if len(dimyv.shape) == 1:
5084                x = np.zeros((len(dimyv),len(dimxv)), dtype=np.float)
5085                for j in range(len(dimxv)):
5086                    x[j,:] = dimxv
5087            else:
5088                x = np.zeros((dimyv.shape), dtype=np.float)
5089                if x.shape[0] == dimxv.shape[0]:
5090                    for j in range(x.shape[1]):
5091                        x[:,j] = dimxv
5092                else:
5093                    for j in range(x.shape[0]):
5094                        x[j,:] = dimxv
5095
5096        if len(dimyv.shape) == 3:
5097            y = dimyv[0,:,:]
5098        elif len(dimyv.shape) == 2:
5099            y = dimyv
5100        else:
5101#            y = np.zeros((lat0.shape), dtype=np.float)
5102#            for i in range(lat0.shape[1]):
5103#                x[:,i] = dimyv
5104
5105# Idem
5106            if len(dimxv.shape) == 1:
5107                y = np.zeros((len(dimyv),len(dimxv)), dtype=np.float)
5108                for i in range(len(dimxv)):
5109                    y[:,i] = dimyv
5110            else:
5111                y = np.zeros((dimxv.shape), dtype=np.float)
5112                if y.shape[0] == dimyv.shape[0]:
5113                    for i in range(y.shape[1]):
5114                        y[:,i] = dimyv
5115                else:
5116                    for j in range(y.shape[0]):
5117                        y[j,:] = dimyv
5118
5119    plt.rc('text', usetex=True)
5120
5121    plt.pcolormesh(x, y, varsv, cmap=plt.get_cmap(colorbar), vmin=vs[0], vmax=vs[1])
5122    cbar = plt.colorbar()
5123
5124    if not mapv is None:
5125        m.drawcoastlines()
5126
5127        meridians = pretty_int(nlon,xlon,5)
5128        m.drawmeridians(meridians,labels=[True,False,False,True])
5129        parallels = pretty_int(nlat,xlat,5)
5130        m.drawparallels(parallels,labels=[False,True,True,False])
5131
5132        plt.xlabel('W-E')
5133        plt.ylabel('S-N')
5134    else:
5135        plt.xlabel(variables_values(dimn[1])[0] + ' (' + units_lunits(dimxu) + ')')
5136        plt.ylabel(variables_values(dimn[0])[0] + ' (' + units_lunits(dimyu) + ')')
5137
5138# Line
5139##
5140
5141    if reva0 == 'flip' and reva.split('@')[1] == 'y':
5142        b=-np.max(y[0,:])/np.max(varlv)
5143        a=np.max(y[0,:])
5144    else:
5145        b=np.max(y[0,:])/np.max(varlv)
5146        a=0.
5147
5148    newlinv = varlv*b+a
5149    if reva0 == 'transpose':
5150        plt.plot(newlinv, x[0,:], '-', color=colln, linewidth=2)
5151    else:
5152        plt.plot(x[0,:], newlinv, '-', color=colln, linewidth=2)
5153
5154    txpos = pretty_int(x.min(),x.max(),10)
5155    typos = pretty_int(y.min(),y.max(),10)
5156    txlabels = list(txpos)
5157    for i in range(len(txlabels)): txlabels[i] = str(txlabels[i])
5158    tylabels = list(typos)
5159    for i in range(len(tylabels)): tylabels[i] = str(tylabels[i])
5160
5161    tllabels = pretty_int(np.min(varlv),np.max(varlv),len(txlabels))
5162    for it in range(len(tllabels)):
5163        yval = (tllabels[it]*b+a)
5164        plt.plot([x.max()*0.97, x.max()], [yval, yval], '-', color='k')
5165        plt.annotate(tllabels[it], xy=(1.01,tllabels[it]/np.max(varlv)),             \
5166          xycoords='axes fraction')
5167
5168# set the limits of the plot to the limits of the data
5169    if reva0 == 'flip':
5170        if reva.split('@')[1] == 'x':
5171            plt.axis([x.max(), x.min(), y.min(), y.max()])
5172        else:
5173            plt.axis([x.min(), x.max(), y.max(), y.min()])
5174    else:
5175        plt.axis([x.min(), x.max(), y.min(), y.max()])
5176
5177    plt.tick_params(axis='y',right='off')
5178    if mapv is None:
5179        plt.xticks(txpos, txlabels)
5180        plt.yticks(typos, tylabels)
5181
5182    tllabels = pretty_int(np.min(varlv),np.max(varlv),len(txlabels))
5183    for it in range(len(tllabels)):
5184        plt.annotate(tllabels[it], xy=(1.01,tllabels[it]/np.max(varlv)), xycoords='axes fraction')
5185
5186# units labels
5187    cbar.set_label(vnames.replace('_','\_') + ' (' + units_lunits(uts) + ')')
5188
5189    plt.annotate(vnamel +' (' + units_lunits(utl) + ')', xy=(0.75,0.04), 
5190      xycoords='figure fraction', color=colln)
5191    figname = '2Dfields_shadow_line'
5192    graphtit = vtit.replace('_','\_').replace('&','\&')
5193
5194    plt.title(graphtit)
5195   
5196    output_kind(kfig, figname, ifclose)
5197
5198    return
5199
5200def plot_Neighbourghood_evol(varsv, dxv, dyv, vnames, ttits, tpos, tlabels, colorbar, \
5201  Nng, vs, uts, gtit, kfig, ifclose):
5202    """ Plotting neighbourghood evolution
5203      varsv= 2D values to plot with shading
5204      vnames= shading variable name for the figure
5205      d[x/y]v= values at the axes of x and y
5206      ttits= titles of both time axis
5207      tpos= positions of the time ticks
5208      tlabels= labels of the time ticks
5209      colorbar= name of the color bar to use
5210      Nng= Number of grid points of the full side of the box (odd value)
5211      vs= minmum and maximum values to plot in shadow or:
5212        'Srange': for full range
5213        'Saroundmean@val': for mean-xtrm,mean+xtrm where xtrm = np.min(mean-min@val,max@val-mean)
5214        'Saroundminmax@val': for min*val,max*val
5215        'Saroundpercentile@val': for median-xtrm,median+xtrm where xtrm = np.min(median-percentile_(val),
5216          percentile_(100-val)-median)
5217        'Smean@val': for -xtrm,xtrm where xtrm = np.min(mean-min*@val,max*@val-mean)
5218        'Smedian@val': for -xtrm,xtrm where xtrm = np.min(median-min@val,max@val-median)
5219        'Spercentile@val': for -xtrm,xtrm where xtrm = np.min(median-percentile_(val),
5220           percentile_(100-val)-median)
5221      uts= units of the variable to shadow
5222      gtit= title of the graph
5223      kfig= kind of figure (jpg, pdf, png)
5224      ifclose= boolean value whether figure should be close (finish) or not
5225    """
5226    import numpy.ma as ma
5227
5228    fname = 'plot_Neighbourghood_evol'
5229
5230    if varsv == 'h':
5231        print fname + '_____________________________________________________________'
5232        print plot_Neighbourghood_evol.__doc__
5233        quit()
5234
5235    if len(varsv.shape) != 2:
5236        print errormsg
5237        print '  ' + fname + ': wrong number of dimensions of the values: ',         \
5238          varsv.shape
5239        quit(-1)
5240
5241    varsvmask = ma.masked_equal(varsv,fillValue)
5242
5243    vsend = np.zeros((2), dtype=np.float)
5244# Changing limits of the colors
5245    if type(vs[0]) != type(np.float(1.)):
5246        if vs[0] == 'Srange':
5247            vsend[0] = np.min(varsvmask)
5248        elif vs[0][0:11] == 'Saroundmean':
5249            meanv = np.mean(varsvmask)
5250            permean = np.float(vs[0].split('@')[1])
5251            minv = np.min(varsvmask)*permean
5252            maxv = np.max(varsvmask)*permean
5253            minextrm = np.min([np.abs(meanv-minv), np.abs(maxv-meanv)])
5254            vsend[0] = meanv-minextrm
5255            vsend[1] = meanv+minextrm
5256        elif vs[0][0:13] == 'Saroundminmax':
5257            permean = np.float(vs[0].split('@')[1])
5258            minv = np.min(varsvmask)*permean
5259            maxv = np.max(varsvmask)*permean
5260            vsend[0] = minv
5261            vsend[1] = maxv
5262        elif vs[0][0:17] == 'Saroundpercentile':
5263            medianv = np.median(varsvmask)
5264            valper = np.float(vs[0].split('@')[1])
5265            minv = np.percentile(varsvmask, valper)
5266            maxv = np.percentile(varsvmask, 100.-valper)
5267            minextrm = np.min([np.abs(medianv-minv), np.abs(maxv-medianv)])
5268            vsend[0] = medianv-minextrm
5269            vsend[1] = medianv+minextrm
5270        elif vs[0][0:5] == 'Smean':
5271            meanv = np.mean(varsvmask)
5272            permean = np.float(vs[0].split('@')[1])
5273            minv = np.min(varsvmask)*permean
5274            maxv = np.max(varsvmask)*permean
5275            minextrm = np.min([np.abs(meanv-minv), np.abs(maxv-meanv)])
5276            vsend[0] = -minextrm
5277            vsend[1] = minextrm
5278        elif vs[0][0:7] == 'Smedian':
5279            medianv = np.median(varsvmask)
5280            permedian = np.float(vs[0].split('@')[1])
5281            minv = np.min(varsvmask)*permedian
5282            maxv = np.max(varsvmask)*permedian
5283            minextrm = np.min([np.abs(medianv-minv), np.abs(maxv-medianv)])
5284            vsend[0] = -minextrm
5285            vsend[1] = minextrm
5286        elif vs[0][0:11] == 'Spercentile':
5287            medianv = np.median(varsvmask)
5288            valper = np.float(vs[0].split('@')[1])
5289            minv = np.percentile(varsvmask, valper)
5290            maxv = np.percentile(varsvmask, 100.-valper)
5291            minextrm = np.min([np.abs(medianv-minv), np.abs(maxv-medianv)])
5292            vsend[0] = -minextrm
5293            vsend[1] = minextrm
5294        else:
5295            print errormsg
5296            print '  ' + fname + ": range '" + vs[0] + "' not ready!!!"
5297            quit(-1)
5298        print '    ' + fname + ': modified shadow min,max:',vsend
5299    else:
5300        vsend[0] = vs[0]
5301
5302    if type(vs[0]) != type(np.float(1.)):
5303        if vs[1] == 'range':
5304            vsend[1] = np.max(varsv)
5305    else:
5306        vsend[1] = vs[1]
5307
5308    plt.rc('text', usetex=True)
5309
5310#    plt.pcolormesh(dxv, dyv, varsv, cmap=plt.get_cmap(colorbar), vmin=vsend[0], vmax=vsend[1])
5311    plt.pcolormesh(varsvmask, cmap=plt.get_cmap(colorbar), vmin=vsend[0], vmax=vsend[1])
5312    cbar = plt.colorbar()
5313
5314    newtposx = (tpos[0][:] - np.min(dxv)) * len(dxv) * Nng / (np.max(dxv) - np.min(dxv))
5315    newtposy = (tpos[1][:] - np.min(dyv)) * len(dyv) * Nng / (np.max(dyv) - np.min(dyv))
5316
5317    plt.xticks(newtposx, tlabels[0])
5318    plt.yticks(newtposy, tlabels[1])
5319    plt.xlabel(ttits[0])
5320    plt.ylabel(ttits[1])
5321
5322    plt.axes().set_aspect('equal')
5323# From: http://stackoverflow.com/questions/14406214/moving-x-axis-to-the-top-of-a-plot-in-matplotlib
5324    plt.axes().xaxis.tick_top
5325    plt.axes().xaxis.set_ticks_position('top')
5326
5327# units labels
5328    cbar.set_label(vnames.replace('_','\_') + ' (' + units_lunits(uts) + ')')
5329
5330    figname = 'Neighbourghood_evol'
5331    graphtit = gtit.replace('_','\_').replace('&','\&')
5332
5333    plt.title(graphtit, position=(0.5,1.05))
5334   
5335    output_kind(kfig, figname, ifclose)
5336
5337    return
5338
5339def plot_lines(vardv, varvv, vaxis, dtit, linesn, vtit, vunit, gtit, gloc, kfig):
5340    """ Function to plot a collection of lines
5341      vardv= list of set of dimension values
5342      varvv= list of set of values
5343      vaxis= which axis will be used for the values ('x', or 'y')
5344      dtit= title for the common dimension
5345      linesn= names for the legend
5346      vtit= title for the vaxis
5347      vunit= units of the vaxis
5348      gtit= main title
5349      gloc= location of the legend (0, autmoatic)
5350        1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
5351        5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
5352        9: 'upper center', 10: 'center'
5353      kfig= kind of figure
5354      plot_lines([np.arange(10)], [np.sin(np.arange(10)*np.pi/2.5)], 'y', 'time (s)',      \
5355  ['2.5'], 'sin', '-', 'sinus frequency dependency', 'pdf')
5356    """
5357    fname = 'plot_lines'
5358
5359    if vardv == 'h':
5360        print fname + '_____________________________________________________________'
5361        print plot_lines.__doc__
5362        quit()
5363
5364# Canging line kinds every 7 lines (end of standard colors)
5365    linekinds=['.-','x-','o-']
5366    pointkindsauto=['.', ',', 'x', 'o', '*', '+', '<', '|', '_', '>', '1', '8', 's', \
5367      'p', 'h', 'D']
5368
5369    Ntraj = len(vardv)
5370
5371    N7lines = 0
5372
5373    xmin = 100000.
5374    xmax = -100000.
5375    ymin = 100000.
5376    ymax = -100000.
5377    for il in range(Ntraj):
5378        minv = np.min(varvv[il])
5379        maxv = np.max(varvv[il])
5380        mind = np.min(vardv[il])
5381        maxd = np.max(vardv[il])
5382
5383        if minv < xmin: xmin = minv
5384        if maxv > xmax: xmax = maxv
5385        if mind < ymin: ymin = mind
5386        if maxd > ymax: ymax = maxd
5387
5388    print 'x:',xmin,',',xmax,'y:',ymin,ymax
5389
5390    plt.rc('text', usetex=True)
5391
5392    if vaxis == 'x':
5393        for il in range(Ntraj):
5394            plt.plot(varvv[il], vardv[il], linekinds[N7lines], label= linesn[il])
5395            if il == 6: N7lines = N7lines + 1
5396
5397        plt.xlabel(vtit + ' (' + vunit + ')')
5398        plt.ylabel(dtit)
5399        plt.xlim(xmin,xmax)
5400        plt.ylim(ymin,ymax)
5401
5402    else:
5403        for il in range(Ntraj):
5404            plt.plot(vardv[il], varvv[il], linekinds[N7lines], label= linesn[il])
5405            if il == 6: N7lines = N7lines + 1
5406
5407        plt.xlabel(dtit)
5408        plt.ylabel(vtit + ' (' + vunit + ')')
5409       
5410        plt.xlim(ymin,ymax)
5411        plt.ylim(xmin,xmax)
5412
5413    figname = 'lines'
5414    graphtit = gtit.replace('_','\_').replace('&','\&')
5415
5416    plt.title(graphtit)
5417    plt.legend(loc=gloc)
5418   
5419    output_kind(kfig, figname, True)
5420
5421    return
5422
5423def ColorsLinesPointsStyles(Nstyles, colors, lines, points, lwidths, psizes, ptfreq):
5424    """ Function to provide the colors, lines & points styles
5425      Nstyles= total number of styles
5426      colors= list of colors, None for no value
5427      lines= list of lines, None for no value
5428      points= list of points, None for no value
5429      lwidths= list of line widths, None for no value
5430      psizes= list of point sizes, None for no value
5431      ptfreq= frequency for the points, None for all values
5432    >>> Nstyles = 3
5433    >>> colors = ['blue']
5434    >>> lines = ['-']
5435    >>> points = ['x', '*', 'o']
5436    >>> lwidths = ['1']
5437    >>> psizes = ['2']
5438    >>> ptfreq = 2
5439    >>> colors, lines, points = ColorsLinesPointsStyles(Nstyles, colors, lines, points, lwidths, psizes, ptfreq)
5440    ['blue', 'blue', 'blue']
5441    ['-', '-', '-']
5442    ['x', '*', 'o']
5443    ['2', '2', '2']
5444    ['1', '1', '1']
5445    """
5446    fname = 'ColorsLinesPointsStyles'
5447
5448    usecolors = []
5449    uselines = []
5450    usepoints = []
5451    usewlines = []
5452    usespoints = []
5453
5454# Colors
5455    if colors is None:
5456        Ncols = len(colorsauto)
5457        for ic in range(Nstyles):
5458            iic = np.mod(ic,Ncols) - 1
5459            if iic == 0: iic = Ncols - 1
5460            usecolors.append(colorsauto[iic])
5461    else:
5462        Ncols = len(colors)
5463        if Ncols == 1:
5464            for ic in range(Nstyles):
5465                usecolors.append(colors[0])
5466        else:
5467            if Ncols != Nstyles:
5468                print errormsg
5469                print '  ' + fname + ': number of provided colors:', Ncols,          \
5470                  'and required:', Nstyles,'differ !!'
5471                quit(-1)
5472            usecolors = colors
5473
5474# Lines
5475    if lines is None:
5476        Nklns = len(linekindsauto)
5477        for il in range(Nstyles):
5478            iil = np.mod(il,Nklns) - 1
5479            if iil == 0: iil = Nklns - 1
5480            uselines.append(linekindsauto[iil])
5481    else:
5482        Nklns = len(lines)
5483        if Nklns == 1:
5484            for il in range(Nstyles):
5485                uselines.append(lines[0])
5486        else:
5487            if Nklns != Nstyles:
5488                print errormsg
5489                print '  ' + fname + ': number of provided lines:', Nklns,           \
5490                  'and required:', Nstyles,'differ !!'
5491                quit(-1)
5492            uselines = lines
5493
5494# Points
5495    if points is None:
5496        Nkpts = len(pointkindsauto)
5497        for ip in range(Nstyles):
5498            iip = np.mod(ip,Nkpts) - 1
5499            if iip == 0: iip = Nkpts - 1
5500            usepoints.append(pointkindsauto[iip])
5501    else:
5502        Nkpts = len(points)
5503        if Nkpts == 1:
5504            for ip in range(Nstyles):
5505                usepoints.append(points[0])
5506        else:
5507            if Nkpts != Nstyles:
5508                print errormsg
5509                print '  ' + fname + ': number of provided points:', Nkpts,          \
5510                  'and required:', Nstyles,'differ !!'
5511                quit(-1)
5512            usepoints = points
5513
5514# Line widths
5515    if lwidths is None:
5516        Nwlns = len(linewidthsauto)
5517        for il in range(Nstyles):
5518            iil = np.mod(il,Nwlns) - 1
5519            if iil == 0: iil = Nwlns - 1
5520            usewlines.append(linewidthsauto[iil])
5521    else:
5522        Nwlns = len(lwidths)
5523        if Nwlns == 1:
5524            for il in range(Nstyles):
5525                usewlines.append(lwidths[0])
5526        else:
5527            if Nwlns != Nstyles:
5528                print errormsg
5529                print '  ' + fname + ': number of provided line widthss:', Nwlns,    \
5530                  'and required:', Nstyles, 'differ !!'
5531                quit(-1)
5532            usewlines = lwidths
5533
5534# Point sizes
5535    if psizes is None:
5536        Nspts = len(pointsizesauto)
5537        for ip in range(Nstyles):
5538            iip = np.mod(ip,Nspts) - 1
5539            if iip == 0: iip = Nspts - 1
5540            usespoints.append(pointsizesauto[iip])
5541    else:
5542        Nspts = len(psizes)
5543        if Nspts == 1:
5544            for ip in range(Nstyles):
5545                usespoints.append(psizes[0])
5546        else:
5547            if Nspts != Nstyles:
5548                print errormsg
5549                print '  ' + fname + ': number of provided point sizes:', Nspts,     \
5550                  'and required:', Nstyles, 'differ !!'
5551                quit(-1)
5552            usespoints = psizes
5553
5554    Ncols = len(usecolors)
5555    Nlins = len(uselines)
5556    Npnts = len(usepoints)
5557
5558    lkinds = []
5559    pkinds = []
5560
5561    lcolors = usecolors
5562
5563# Old way
5564#    if ptfreq is not None:
5565#        lkinds = uselines
5566#        pkinds = usepoints
5567#    else:
5568#        pkinds = usepoints
5569#        lkinds = uselines
5570#        for ilp in range(Nstyles):
5571#            lkinds.append(usepoints[ilp] + uselines[ilp])
5572           
5573    return lcolors, uselines, usepoints, usewlines, usespoints
5574
5575#Nstyles = 3
5576#colors = ['blue']
5577#lines = ['-']
5578#points = ['x', '*', 'o']
5579#lwidths = ['2']
5580#psizes = ['1']
5581#ptfreq = 2
5582#print ColorsLinesPointsStyles(Nstyles, colors, lines, points, lwidths, psizes, ptfreq)
5583
5584def LinesPointsStyles(Nstyles, lines, points, ptfreq):
5585    """ Function to provide the lines & points styles
5586      Nstyles= total number of styles
5587      lines= list of lines, None for no value
5588      points= list of points, None for no value
5589      ptfreq= frequency for the points, None for all values
5590    >>> Nstyles = 3
5591    >>> lines = ['-']
5592    >>> points = ['x', '*', 'o']
5593    >>> ptfreq = 2
5594    >>> lines, points = LinesPointsStyles(Nstyles, lines, points, ptfreq)
5595    ['-', '-', '-']
5596    ['x', '*', 'o']
5597    """
5598    fname = 'LinesPointsStyles'
5599
5600# Canging line kinds every 7 lines (end of standard colors)
5601    uselines = []
5602    usepoints = []
5603    if lines is None:
5604        Nklns = len(linekindsauto)
5605        for il in range(Nstyles):
5606            iil = np.mod(il,Nklns)
5607            uselines.append(linekindsauto[iil])
5608    else:
5609        Nklns = len(lines)
5610        if Nklns == 1:
5611            for il in range(Nstyles):
5612                uselines.append(lines[0])
5613        else:
5614            if Nklns != Nstyles:
5615                print errormsg
5616                print '  ' + fname + ': number of provided lines:', Nklns,           \
5617                  'and required:', Nstyles,'differ !!'
5618                quit(-1)
5619            uselines = lines
5620
5621    if points is None:
5622        Nkpts = len(pointkindsauto)
5623        for ip in range(Nstyles):
5624            iip = np.mod(ip,Nkpts)
5625            usepoints.append(pointkindsauto[iip])
5626    else:
5627        Nkpts = len(points)
5628        if Nkpts == 1:
5629            for ip in range(Nstyles):
5630                usepoints.append(points[0])
5631        else:
5632            if Nkpts != Nstyles:
5633                print errormsg
5634                print '  ' + fname + ': number of provided points:', Nkpts,          \
5635                  'and required:', Nstyles,'differ !!'
5636                quit(-1)
5637            usepoints = points
5638
5639    Nlins = len(uselines)
5640    Npnts = len(usepoints)
5641
5642    lkinds = []
5643    pkinds = []
5644    if ptfreq is not None:
5645        lkinds = uselines
5646        pkinds = usepoints
5647    else:
5648        pkinds = usepoints
5649        for ilp in range(Nstyles):
5650            lkinds.append(usepoints[ilp] + uselines[ilp])
5651           
5652    return lkinds, pkinds
5653
5654def plot_lines_time(vardv, varvv, vaxis, dtit, linesn0, vtit, vunit, tpos, tlabs,    \
5655  gtit, gloc, kfig, lsl, coll, ptl, lwidth, psize, ptf):
5656    """ Function to plot a collection of lines with a time axis
5657      vardv= list of set of dimension values
5658      varvv= list of set of values
5659      vaxis= which axis will be used for the time values ('x', or 'y')
5660      dtit= title for the common dimension
5661      linesn= names for the legend (None, no legend)
5662      vtit= title for the vaxis
5663      vunit= units of the vaxis
5664      tpos= positions of the time ticks
5665      tlabs= labels of the time ticks
5666      gtit= main title
5667      gloc= location of the legend (0, autmoatic)
5668        1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
5669        5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
5670        9: 'upper center', 10: 'center'
5671      kfig= kind of figure
5672      lsl= ',' list of line styles
5673      coll= ',' list of colors for the lines, None for automatic, single
5674          value all the same
5675      ptl= ',' list of type of points for the lines, None for automatic, single
5676          value all the same
5677      lwidth= ',' list of line widths
5678      psize= ',' list of point sizes
5679      ptf= frequency of point plotting, 'all' for all time steps
5680
5681      plot_lines([np.arange(10)], [np.sin(np.arange(10)*np.pi/2.5)], 'y', 'time (s)',      \
5682  ['2.5'], 'sin', '-', 'sinus frequency dependency', 'pdf')
5683    """
5684    fname = 'plot_lines_time'
5685
5686    if vardv == 'h':
5687        print fname + '_____________________________________________________________'
5688        print plot_lines.__doc__
5689        quit()
5690
5691    Ntraj = len(vardv)
5692
5693    colvalues, linekinds, pointkinds, lwidths, psizes = ColorsLinesPointsStyles(     \
5694      Ntraj, coll, lsl, ptl, lwidth, psize,  ptf)
5695
5696    plt.rc('text', usetex=True)
5697    xtrmvv = [fillValueF,-fillValueF]
5698    xtrmdv = [fillValueF,-fillValueF]
5699
5700# Do we have legend?
5701##
5702    if linesn0 is None:
5703        linesn = []
5704        for itrj in range(Ntraj):
5705            linesn.append(str(itrj))
5706    else:
5707        linesn = linesn0
5708
5709    if vaxis == 'x':
5710        for il in range(Ntraj):
5711            plt.plot(varvv[il], vardv[il], linekinds[il], marker=pointkinds[il],     \
5712              label=linesn[il], color=colvalues[il], linewidth=lwidths[il],          \
5713              markersize=psizes[il], markevery=ptf)
5714
5715# Old way
5716#            if ptf is None:
5717#                plt.plot(varvv[il], vardv[il], linekinds[il], label= linesn[il],     \
5718#                  color=colvalues[il], linewidth=lwidths[il], markersize=psizes[il])
5719#            else:
5720#                plt.plot(varvv[il], vardv[il], linekinds[il], color=colvalues[il],   \
5721#                  linewidth=lwidths[il])
5722#                plt.plot(varvv[il][::ptf], vardv[il][::ptf], pointkinds[il],         \
5723#                  label= linesn[il], color=colvalues[il], linewidth=lwidths[il],     \
5724#                  markersize=psizes[il])
5725
5726            minvv = np.min(varvv[il])
5727            maxvv = np.max(varvv[il])
5728            mindv = np.min(vardv[il])
5729            maxdv = np.max(vardv[il])
5730
5731            if minvv < xtrmvv[0]: xtrmvv[0] = minvv
5732            if maxvv > xtrmvv[1]: xtrmvv[1] = maxvv
5733            if mindv < xtrmdv[0]: xtrmdv[0] = mindv
5734            if maxdv > xtrmdv[1]: xtrmdv[1] = maxdv
5735
5736        plt.xlabel(vtit + ' (' + vunit + ')')
5737        plt.ylabel(dtit)
5738#        plt.xlim(np.min(varTvv),np.max(varTvv))
5739#        plt.ylim(np.min(varTdv),np.max(varTdv))
5740        plt.xlim(xtrmvv[0],xtrmvv[1])
5741        plt.ylim(xtrmdv[0],xtrmdv[1])
5742
5743        plt.yticks(tpos, tlabs)
5744    else:
5745        for il in range(Ntraj):
5746            plt.plot(vardv[il], varvv[il], linekinds[il], marker=pointkinds[il],     \
5747              label=linesn[il], color=colvalues[il], linewidth=lwidths[il],          \
5748              markersize=psizes[il], markevery=ptf)
5749
5750# Old way
5751#            if ptf is None:
5752#                plt.plot(vardv[il], varvv[il], linekinds[il], label= linesn[il],     \
5753#                  color=colvalues[il], linewidth=lwidths[il], markersize=psizes[il], markevery=ptf)
5754#            else:
5755#                plt.plot(vardv[il], varvv[il], linekinds[il], color=coll[il],        \
5756#                  linewidth=lwidths[il])
5757#                plt.plot(vardv[il][::ptf], varvv[il][::ptf], pointkinds[il],         \
5758#                  label= linesn[il], color=colvalues[il], linewidth=lwidths[il],     \
5759#                  markersize=psizes[il])
5760
5761            minvv = np.min(varvv[il])
5762            maxvv = np.max(varvv[il])
5763            mindv = np.min(vardv[il])
5764            maxdv = np.max(vardv[il])
5765
5766            if minvv < xtrmvv[0]: xtrmvv[0] = minvv
5767            if maxvv > xtrmvv[1]: xtrmvv[1] = maxvv
5768            if mindv < xtrmdv[0]: xtrmdv[0] = mindv
5769            if maxdv > xtrmdv[1]: xtrmdv[1] = maxdv
5770
5771        plt.xlabel(dtit)
5772        plt.ylabel(vtit + ' (' + vunit + ')')
5773
5774        plt.xlim(xtrmdv[0],xtrmdv[1])
5775        plt.ylim(xtrmvv[0],xtrmvv[1])
5776
5777#        plt.xlim(np.min(varTdv),np.max(varTdv))
5778#        plt.ylim(np.min(varTvv),np.max(varTvv))
5779        plt.xticks(tpos, tlabs)
5780
5781    figname = 'lines_time'
5782    graphtit = gtit.replace('_','\_').replace('&','\&')
5783
5784    plt.title(graphtit)
5785    if linesn0 is not None:
5786        if Ntraj < 10:
5787            plt.legend(loc=gloc)
5788        elif 10 < Ntraj < 20:
5789            plt.legend(loc=gloc, prop={'size':10})
5790        else:
5791            plt.legend(loc=gloc, prop={'size':8})
5792
5793    print plt.xlim(),':', plt.ylim()
5794   
5795    output_kind(kfig, figname, True)
5796
5797    return
5798
5799def plot_barbs(xvals,yvals,uvals,vvals,vecfreq,veccolor,veclength,windn,wuts,mapv,graphtit,kfig,figname):
5800    """ Function to plot wind barbs
5801      xvals= x position of the values
5802      yvals= y position of the values
5803      uvals= values for the x-wind
5804      uvals= values for the y-wind
5805      vecfreq= [xfreq],[yfreq] frequency of values allong each axis (None, all grid points;
5806        'auto', computed automatically to have 20 vectors along each axis)
5807      veccolor= color of the vectors (None, for 'red')
5808      veclength= length of the wind barbs (None, for 9)
5809      windn= name of the wind variable in the graph
5810      wuts= units of the wind variable in the graph
5811      mapv= map characteristics: [proj],[res]
5812        see full documentation: http://matplotlib.org/basemap/
5813        [proj]: projection
5814          * 'cyl', cilindric
5815          * 'lcc', lambert conformal
5816        [res]: resolution:
5817          * 'c', crude
5818          * 'l', low
5819          * 'i', intermediate
5820          * 'h', high
5821          * 'f', full
5822      graphtit= title of the graph ('|', for spaces)
5823      kfig= kind of figure
5824      figname= name of the figure
5825    """
5826    fname = 'plot_barbs'
5827 
5828    dx=xvals.shape[1]
5829    dy=xvals.shape[0]
5830
5831# Frequency of vectors
5832    if vecfreq is None:
5833        xfreq = 1
5834        yfreq = 1
5835    elif vecfreq == 'auto':
5836        xfreq = dx/20
5837        yfreq = dy/20
5838    else:
5839        xfreq=int(vecfreq.split('@')[0])
5840        yfreq=int(vecfreq.split('@')[1])
5841
5842    if veccolor == 'auto':
5843        vcolor = "red"
5844    else:
5845        vcolor = veccolor
5846
5847    if veclength == 'auto':
5848        vlength = 9
5849    else:
5850        vlength = veclength
5851
5852    plt.rc('text', usetex=True)
5853
5854    if not mapv is None:
5855        lon00 = np.where(xvals[:] < 0., 360. + xvals[:], xvals[:])
5856        lat00 = yvals[:]
5857
5858        map_proj=mapv.split(',')[0]
5859        map_res=mapv.split(',')[1]
5860
5861        nlon = np.min(xvals[::yfreq,::xfreq])
5862        xlon = np.max(xvals[::yfreq,::xfreq])
5863        nlat = np.min(yvals[::yfreq,::xfreq])
5864        xlat = np.max(yvals[::yfreq,::xfreq])
5865
5866        lon2 = xvals[dy/2,dx/2]
5867        lat2 = yvals[dy/2,dx/2]
5868
5869        print 'lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:',     \
5870          xlon, ',', xlat
5871
5872        if map_proj == 'cyl':
5873            m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat,         \
5874              urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res)
5875        elif map_proj == 'lcc':
5876            m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \
5877              llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res)
5878        else:
5879            print errormsg
5880            print '  ' + fname + ": projection '" + map_proj + "' not ready!!"
5881            print '    projections available: cyl, lcc'
5882            quit(-1)
5883
5884        m.drawcoastlines()
5885
5886        meridians = pretty_int(nlon,xlon,5)
5887        m.drawmeridians(meridians,labels=[True,False,False,True],color="black")
5888
5889        parallels = pretty_int(nlat,xlat,5)
5890        m.drawparallels(parallels,labels=[False,True,True,False],color="black")
5891
5892        plt.xlabel('W-E')
5893        plt.ylabel('S-N')
5894
5895    plt.barbs(xvals[::yfreq,::xfreq], yvals[::yfreq,::xfreq], uvals[::yfreq,::xfreq],\
5896      vvals[::yfreq,::xfreq], color=vcolor, pivot='tip')
5897
5898    plt.annotate(windn.replace('_','\_') +' (' + units_lunits(wuts) + ')',           \
5899      xy=(0.85,-0.10), xycoords='axes fraction', color=vcolor)
5900
5901    plt.title(graphtit.replace('|',' ').replace('&','\&'))
5902
5903## NOT WORKING ##
5904
5905# No legend so it is imposed
5906##    windlabel=windn.replace('_','\_') +' (' + units_lunits(wuts[1]) + ')'
5907##    vecpatch = mpatches.Patch(color=vcolor, label=windlabel)
5908
5909##    plt.legend(handles=[vecpatch])
5910
5911##    vecline = mlines.Line2D([], [], color=vcolor, marker='.', markersize=10, label=windlabel)
5912##    plt.legend(handles=[vecline], loc=1)
5913
5914    output_kind(kfig, figname, True)
5915
5916    return
5917
5918def plot_ptZvals(vname,vunits,points,ptype,ptsize,graphlims,minmax,figtitle,cbar,    \
5919  mapv,kfig):
5920    """ Function to plot a given list of points and values
5921      vname= name of the variable in the graph
5922      vunits= units of the variable
5923      points= [lon,lat,val] matrix of values
5924      ptype= type of the point
5925      ptsize= size of the point
5926      graphlims= minLON,minLAT,maxLON,maxLAT limits of the graph, None for the full size
5927      minmax= minimum and maximum type
5928        'auto': values taken from the extrems of the data
5929        [min],[max]: given minimum and maximum values
5930      figtitle= title of the figure
5931      cbar= color bar
5932      mapv= map characteristics: [proj],[res]
5933        see full documentation: http://matplotlib.org/basemap/
5934        [proj]: projection
5935          * 'cyl', cilindric
5936          * 'lcc', lambert-conformal
5937        [res]: resolution:
5938          * 'c', crude
5939          * 'l', low
5940          * 'i', intermediate
5941          * 'h', high
5942          * 'f', full
5943      kfig= kind of figure
5944    """
5945    fname = 'plot_ptZvals'
5946
5947    figname = 'pointsZval'
5948
5949    minlon = points[:,0].min()
5950    maxlon = points[:,0].max() 
5951
5952    minlat = points[:,1].min()
5953    maxlat = points[:,1].max()
5954
5955    minval = points[:,2].min()
5956    maxval = points[:,2].max()
5957
5958#    print 'min/max val;',minval,maxval
5959
5960    lonrange = (points[:,0] - minlon)/(maxlon - minlon)
5961    latrange = (points[:,1] - minlat)/(maxlat - minlat)
5962    colorrange = (points[:,2] - minval)/(maxval - minval)
5963
5964    plt.rc('text', usetex=True)
5965
5966    if mapv is not None:
5967        vlon = points[:,0]
5968        vlat = points[:,1]
5969        dx = len(vlon)
5970        dy = len(vlat)
5971
5972#        vlon = np.where(vlon[:] < 0., 360. + vlon[:], vlon[:])
5973#        xvala = np.array(xval)
5974#        xvala = np.where(xvala < 0., 360. + xvala, xvala)
5975#        xval = list(xvala)
5976
5977        map_proj=mapv.split(',')[0]
5978        map_res=mapv.split(',')[1]
5979
5980        if graphlims is not None:
5981            nlon = graphlims[0]
5982            xlon = graphlims[2]
5983            nlat = graphlims[1]
5984            xlat = graphlims[3]
5985        else:
5986            nlon = np.min(vlon)
5987            xlon = np.max(vlon)
5988            nlat = np.min(vlat)
5989            xlat = np.max(vlat)
5990
5991        lon2 = vlon[dy/2]
5992        lat2 = vlat[dy/2]
5993
5994        print 'lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:',     \
5995          xlon, ',', xlat
5996
5997        if map_proj == 'cyl':
5998            m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat,         \
5999              urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res)
6000        elif map_proj == 'lcc':
6001            m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \
6002              llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res)
6003        else:
6004            print errormsg
6005            print '  ' + fname + ": map projecion '" + map_proj + "' not ready!!"
6006            print '    available: cyl, lcc'
6007            quit(-1)
6008
6009#        lons, lats = np.meshgrid(vlon, vlat)
6010#        lons = np.where(lons < 0., lons + 360., lons)
6011
6012        x,y = m(vlon,vlat)
6013
6014        m.drawcoastlines()
6015
6016        meridians = pretty_int(nlon,xlon,5)
6017        m.drawmeridians(meridians,labels=[True,False,False,True])
6018
6019        parallels = pretty_int(nlat,xlat,5)
6020        m.drawparallels(parallels,labels=[False,True,True,False])
6021#    else:
6022#        x = vlon
6023#        y = vlat
6024#        plt.xlim(0,dx-1)
6025#        plt.ylim(0,dy-1)
6026 
6027    if minmax == 'auto':
6028        plt.scatter(points[:,0], points[:,1], c=points[:,2], s=ptsize, cmap=cbar,    \
6029          marker=ptype)
6030    else:
6031        minv = np.float(minmax.split(',')[0])
6032        maxv = np.float(minmax.split(',')[1])
6033
6034        plt.scatter(points[:,0], points[:,1], c=points[:,2], s=ptsize, cmap=cbar,    \
6035          marker=ptype, vmin=minv, vmax=maxv)
6036
6037    cbar = plt.colorbar()
6038    cbar.set_label(vname.replace('_','\_') +' ('+ units_lunits(vunits) + ')')
6039
6040    plt.title(figtitle)
6041    if graphlims is not None:
6042        plt.xlim(graphlims[0], graphlims[2])
6043        plt.ylim(graphlims[1], graphlims[3])
6044
6045    output_kind(kfig, figname, True)
6046
6047    return
6048
6049#pts = np.zeros((10,3), dtype=np.float)
6050#pts[:,0] = np.arange(10,20)*1.
6051#pts[:,1] = np.arange(30,40)*1.
6052#pts[:,2] = np.arange(-5,5)*1.
6053
6054#plot_ptZvals('vals','kgm-2',pts,'.',300, 'values of values', 'seismic', 'cyl,l', 'pdf')
6055
6056def plot_ZQradii(Zmeans, graphtit, kfig, figname):
6057    """ Function to plot following radial averages only at exact grid poins
6058      Zmeans= radial means
6059      radii= values of the taken radii
6060      graphtit= title of the graph ('|', for spaces)
6061      kfig= kind of figure
6062      figname= name of the figure
6063    """
6064
6065    fname = 'plot_ZQradii'
6066
6067    output_kind(kfig, figname, True)
6068
6069    return
6070
6071def plot_vector(xvals,yvals,uvals,vvals,vecfreq,vecoln,veccolor,veclength,windn,wuts,\
6072  mapv,graphtit,kfig,figname):
6073    """ Function to plot vectors
6074      xvals= values for the x-axis
6075      yvals= values for the y-axis
6076      uvals= values for the x-wind
6077      vvals= values for the y-wind
6078      vecfreq= [xfreq],[yfreq] frequency of values allong each axis (None, all grid points;
6079        'auto', computed automatically to have 20 vectors along each axis)
6080      veccoln= name for the color of the vectors
6081        'singlecol'@[colorn]: all the vectors same color ('auto': for 'red')
6082        'wind'@[colorbar]: color of the vectors according to wind speed sqrt(u^2+v^2) and given [colorbar]
6083        '3rdvar'@[colorbar]@[varn]@[units]: color of the vectors according to a 3rd variable (to be added at -v) and given [colorbar]
6084      veccolor= color of the vectors
6085      veclength= length of the wind vectors:
6086        'singlecol': 'auto', for 9
6087        'wind' and '3rdvar': 'auto' length as wind speed, otherwise fix length
6088      windn= name of the wind variable in the graph
6089      wuts= units of the wind variable in the graph
6090      mapv= map characteristics: [proj],[res]
6091        see full documentation: http://matplotlib.org/basemap/
6092        [proj]: projection
6093          * 'cyl', cilindric
6094          * 'lcc', lambert conformal
6095        [res]: resolution:
6096          * 'c', crude
6097          * 'l', low
6098          * 'i', intermediate
6099          * 'h', high
6100          * 'f', full
6101      graphtit= title of the graph ('|', for spaces)
6102      kfig= kind of figure
6103      figname= name of the figure
6104    """
6105    fname = 'plot_vector'
6106
6107    dx=xvals.shape[1]
6108    dy=xvals.shape[0]
6109
6110# Frequency of vectors
6111    if vecfreq is None:
6112        xfreq = 1
6113        yfreq = 1
6114    elif vecfreq == 'auto':
6115        xfreq = dx/20
6116        yfreq = dy/20
6117    else:
6118        xfreq=int(vecfreq.split('@')[0])
6119        yfreq=int(vecfreq.split('@')[1])
6120
6121# Vector length
6122    if veclength == 'auto':
6123        vlength = 9
6124    else:
6125        vlength = veclength
6126
6127# Colors
6128    VecN = vecoln.split('@')[0]
6129    if VecN == 'singlecol':
6130        if veccolor == 'auto':
6131            vcolor = "red"
6132        else:
6133            vcolor = veccolor
6134    elif VecN == 'wind' or VecN == '3rdvar':
6135        vcolor = vecoln.split('@')[1]
6136
6137    plt.rc('text', usetex=True)
6138
6139    if not mapv is None:
6140        lon00 = np.where(xvals[:] < 0., 360. + xvals[:], xvals[:])
6141        lat00 = yvals[:]
6142
6143        map_proj=mapv.split(',')[0]
6144        map_res=mapv.split(',')[1]
6145
6146        nlon = np.min(xvals[::yfreq,::xfreq])
6147        xlon = np.max(xvals[::yfreq,::xfreq])
6148        nlat = np.min(yvals[::yfreq,::xfreq])
6149        xlat = np.max(yvals[::yfreq,::xfreq])
6150
6151        lon2 = xvals[dy/2,dx/2]
6152        lat2 = yvals[dy/2,dx/2]
6153
6154        print 'lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:',     \
6155          xlon, ',', xlat
6156
6157        if map_proj == 'cyl':
6158            m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat,         \
6159              urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res)
6160        elif map_proj == 'lcc':
6161            m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \
6162              llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res)
6163        else:
6164            print errormsg
6165            print '  ' + fname + ": projection '" + map_proj + "' not ready!!"
6166            print '    projections available: cyl, lcc'
6167            quit(-1)
6168
6169        m.drawcoastlines()
6170
6171        meridians = pretty_int(nlon,xlon,5)
6172        m.drawmeridians(meridians,labels=[True,False,False,True],color="black")
6173
6174        parallels = pretty_int(nlat,xlat,5)
6175        m.drawparallels(parallels,labels=[False,True,True,False],color="black")
6176
6177        plt.xlabel('W-E')
6178        plt.ylabel('S-N')
6179
6180    if VecN == 'singlecol':
6181        plt.quiver(xvals[::yfreq,::xfreq], yvals[::yfreq,::xfreq],                   \
6182          uvals[::yfreq,::xfreq], vvals[::yfreq,::xfreq], color=vcolor, pivot='middle')
6183        plt.annotate(windn.replace('_','\_') +' (' + units_lunits(wuts) + ')',       \
6184          xy=(0.80,-0.15), xycoords='axes fraction', color=vcolor)
6185    else:
6186        if veclength != 'auto':
6187            wind = np.sqrt(uvals**2 + vvals**2)
6188            uvals = np.where(wind == 0., 0., uvals)
6189            vvals = np.where(wind == 0., 0., vvals)
6190            uvals = np.float(veclength)*uvals/wind
6191            vvals = np.float(veclength)*vvals/wind
6192
6193        plt.quiver(xvals[::yfreq,::xfreq], yvals[::yfreq,::xfreq],                   \
6194          uvals[::yfreq,::xfreq], vvals[::yfreq,::xfreq], 
6195          veccolor[::yfreq,::xfreq], cmap=plt.get_cmap(vcolor), pivot='middle')
6196        cbar = plt.colorbar()
6197
6198        if VecN == 'wind':
6199            cbar.set_label('$\sqrt{u^{2} + v^{2}}$ (' + units_lunits(wuts) + ')')
6200        else:
6201            vN = vecoln.split('@')[2]
6202            vU = vecoln.split('@')[3]
6203            cbar.set_label(vN + ' (' + units_lunits(vU) + ')')
6204
6205        plt.annotate(windn.replace('_','\_') +' (' + units_lunits(wuts) + ')',       \
6206          xy=(0.80,-0.15), xycoords='axes fraction', color='black')
6207
6208    plt.title(graphtit.replace('|',' ').replace('&','\&'))
6209
6210    output_kind(kfig, figname, True)
6211
6212    return
6213
6214def plot_basins(xvals,yvals,fvals,vecfreq,vecoln,veccolor,veclength,windn,wuts,\
6215  mapv,graphtit,kfig,figname):
6216    """ Function to plot vectors
6217      xvals= values for the x-axis
6218      yvals= values for the y-axis
6219      fvals= values for the flow (1-8: N, NE, E, ..., NW; 97: sub-basin; 98: small to sea; 99: large to sea)
6220      vecfreq= [xfreq],[yfreq] frequency of values allong each axis (None, all grid points;
6221        'auto', computed automatically to have 20 vectors along each axis)
6222      veccoln= name for the color of the vectors (as '3rdvar@[basinsvar]@[varn]@[units]' from plot_vector)
6223      veccolor= color of the vectors
6224      veclength= length of the wind vectors:
6225        'singlecol': 'auto', for 9
6226        'wind' and '3rdvar': 'auto' length as wind speed, otherwise fix length
6227      windn= name of the wind variable in the graph
6228      wuts= units of the wind variable in the graph
6229      mapv= map characteristics: [proj],[res]
6230        see full documentation: http://matplotlib.org/basemap/
6231        [proj]: projection
6232          * 'cyl', cilindric
6233          * 'lcc', lambert conformal
6234        [res]: resolution:
6235          * 'c', crude
6236          * 'l', low
6237          * 'i', intermediate
6238          * 'h', high
6239          * 'f', full
6240      graphtit= title of the graph ('|', for spaces)
6241      kfig= kind of figure
6242      figname= name of the figure
6243    """
6244    fname = 'plot_basins'
6245
6246    dx=xvals.shape[1]
6247    dy=xvals.shape[0]
6248
6249# Frequency of vectors
6250    if vecfreq is None:
6251        xfreq = 1
6252        yfreq = 1
6253    elif vecfreq == 'auto':
6254        xfreq = dx/20
6255        yfreq = dy/20
6256    else:
6257        xfreq=int(vecfreq.split('@')[0])
6258        yfreq=int(vecfreq.split('@')[1])
6259
6260# Vector length
6261    if veclength == 'auto':
6262        vlength = 9
6263    else:
6264        vlength = veclength
6265
6266# flow direction
6267    angle = (fvals[::yfreq,::xfreq] - 1)*np.pi/4
6268    uvals = np.where(fvals[::yfreq,::xfreq] < 9, np.float(veclength)*np.sin(angle), 0.)
6269    vvals = np.where(fvals[::yfreq,::xfreq] < 9, np.float(veclength)*np.cos(angle), 0.)
6270
6271# Colors
6272    vcolor = vecoln.split('@')[0]
6273
6274    plt.rc('text', usetex=True)
6275
6276    ddx = np.abs(xvals[dy/2+1,dx/2] - xvals[dy/2,dx/2])
6277    ddy = np.abs(yvals[dy/2,dx/2+1] - yvals[dy/2,dx/2])
6278    fontcharac = {'family': 'serif', 'weight': 'normal', 'size': 3}
6279
6280# Setting up colors for each label
6281#   From: http://stackoverflow.com/questions/15235630/matplotlib-pick-up-one-color-associated-to-one-value-in-a-colorbar
6282    my_cmap = plt.cm.get_cmap(vcolor)
6283    vcolmin = np.min(veccolor[::yfreq,::xfreq])
6284    vcolmax = np.max(veccolor[::yfreq,::xfreq])
6285    vcolmin = 0.
6286    vcolmax = 2500.
6287    norm = mpl.colors.Normalize(vcolmin, vcolmax)
6288    print 'min col:',vcolmin,'max col:',vcolmax
6289
6290    xlabpos = []
6291    ylabpos = []
6292    labels = []
6293    labcol = []
6294    flow = []
6295    flowvals = []
6296   
6297    for j in range(0,dy,yfreq):
6298        for i in range(0,dx,xfreq):
6299            if veccolor[j,i] != '--':
6300                xlabpos.append(xvals[j,i])
6301                ylabpos.append(yvals[j,i])
6302                labels.append(int(veccolor[j,i]))
6303                labcol.append(my_cmap(norm(veccolor[j,i])))
6304                flowvals.append(fvals[j,i])
6305
6306    if not mapv is None:
6307        lon00 = np.where(xvals[:] < 0., 360. + xvals[:], xvals[:])
6308        lat00 = yvals[:]
6309
6310        map_proj=mapv.split(',')[0]
6311        map_res=mapv.split(',')[1]
6312
6313        nlon = np.min(xvals[::yfreq,::xfreq])
6314        xlon = np.max(xvals[::yfreq,::xfreq])
6315        nlat = np.min(yvals[::yfreq,::xfreq])
6316        xlat = np.max(yvals[::yfreq,::xfreq])
6317
6318        lon2 = xvals[dy/2,dx/2]
6319        lat2 = yvals[dy/2,dx/2]
6320
6321        print 'lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:',     \
6322          xlon, ',', xlat
6323
6324        if map_proj == 'cyl':
6325            m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat,         \
6326              urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res)
6327        elif map_proj == 'lcc':
6328            m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \
6329              llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res)
6330        else:
6331            print errormsg
6332            print '  ' + fname + ": projection '" + map_proj + "' not ready!!"
6333            print '    projections available: cyl, lcc'
6334            quit(-1)
6335
6336        m.drawcoastlines()
6337
6338        meridians = pretty_int(nlon,xlon,5)
6339        m.drawmeridians(meridians,labels=[True,False,False,True],color="black")
6340
6341        parallels = pretty_int(nlat,xlat,5)
6342        m.drawparallels(parallels,labels=[False,True,True,False],color="black")
6343
6344        plt.xlabel('W-E')
6345        plt.ylabel('S-N')
6346
6347    if veclength != 'auto':
6348        wind = np.sqrt(uvals**2 + vvals**2)
6349        uvals = np.where(wind == 0., 0., uvals)
6350        vvals = np.where(wind == 0., 0., vvals)
6351        uvals = np.float(veclength)*uvals/wind
6352        vvals = np.float(veclength)*vvals/wind
6353
6354    plt.quiver(xvals[::yfreq,::xfreq], yvals[::yfreq,::xfreq],                       \
6355      uvals[::yfreq,::xfreq], vvals[::yfreq,::xfreq], veccolor[::yfreq,::xfreq],     \
6356       cmap=plt.get_cmap(vcolor), pivot='middle')
6357    cbar = plt.colorbar()
6358
6359    vN = vecoln.split('@')[1]
6360    vU = vecoln.split('@')[2]
6361    cbar.set_label(vN + ' (' + units_lunits(vU) + ')')
6362
6363    for i in range(len(xlabpos)):
6364        plt.text(xlabpos[i]+0.5*ddx, ylabpos[i]+0.95*ddy, labels[i],                  \
6365          color=labcol[i], fontdict=fontcharac)
6366
6367# Sea-flow
6368    for i in range(len(xlabpos)):
6369        if flowvals[i] == 97:
6370            plt.plot(xlabpos[i], ylabpos[i], 'x', color=labcol[i])
6371        elif flowvals[i] == 98:
6372            plt.plot(xlabpos[i], ylabpos[i], '*', color=labcol[i])
6373        elif flowvals[i] == 99:
6374            plt.plot(xlabpos[i], ylabpos[i], 'h', color=labcol[i])
6375
6376    plt.annotate(windn.replace('_','\_') +' (' + units_lunits(wuts) + ')',           \
6377      xy=(0.80,-0.15), xycoords='axes fraction', color='black')
6378
6379    plt.title(graphtit.replace('|',' ').replace('&','\&'))
6380
6381    output_kind(kfig, figname, True)
6382
6383    return
6384
6385def var_3desc(ovar):
6386    """ Function to provide std_name, long_name and units from an object variable
6387      ovar= object variable
6388    """
6389    fname = 'var_desc'
6390    varattrs = ovar.ncattrs()
6391
6392    if searchInlist(varattrs,'std_name'):
6393        stdn = ovar.getncattr('std_name')
6394    else:
6395        vvalues = variables_values(ovar._name)
6396        stdn = vvalues[1]
6397
6398    if searchInlist(varattrs,'long_name'):
6399        lonn = ovar.getncattr('long_name')
6400    else:
6401        lonn = vvalues[4].replace('|',' ')
6402
6403    if searchInlist(varattrs,'units'):
6404        un = ovar.getncattr('units')
6405    else:
6406        un = vvalues[5]
6407
6408    return stdn, lonn, un
6409
6410def plot_river_desc(lons, lats, rns, rss, rus, ros, bcolor, ucolor, uuts, mapv,      \
6411  graphtit, kfig, lloc, figname):
6412    """ Function to plot rivers from 'river_desc.nc' ORCDHIEE
6413      lons= values for the x-axis
6414      lats= values for the y-axis
6415      rns= list of the name of the rivers to plot
6416      rss= dictionary with the lon,lats of the subbasins of each river
6417      rus= dictionary with the lon,lats of the upstream values of each river
6418      ros= dictionary with the lon,lats of the outflow points of each river
6419      bcolor= color of the lines for the subbasins
6420      ucolor= bar color for the upstreams
6421      uuts= units of the upstream
6422      mapv= map characteristics: [proj],[res]
6423        see full documentation: http://matplotlib.org/basemap/
6424        [proj]: projection
6425          * 'cyl', cilindric
6426          * 'lcc', lambert conformal
6427        [res]: resolution:
6428          * 'c', crude
6429          * 'l', low
6430          * 'i', intermediate
6431          * 'h', high
6432          * 'f', full
6433      graphtit= title of the graph ('|', for spaces)
6434      lloc= location of the legend (0, automatic)
6435        1: 'upper right', 2: 'upper left', 3: 'lower left', 4: 'lower right',
6436        5: 'right', 6: 'center left', 7: 'center right', 8: 'lower center',
6437        9: 'upper center', 10: 'center'      kfig= kind of figure
6438      figname= name of the figure
6439    """
6440    fname = 'plot_basins'
6441
6442    colvalues, linekinds, pointkinds, lwidths, psizes = ColorsLinesPointsStyles(     \
6443      len(rns), bcolor, ['-'], ['.'], [1.], [1.],  None)
6444
6445    dx=lons.shape[1]
6446    dy=lats.shape[0]
6447
6448    plt.rc('text', usetex=True)
6449
6450    nlon = np.min(lons)
6451    xlon = np.max(lons)
6452    nlat = np.min(lats)
6453    xlat = np.max(lats)
6454
6455    dlon = xlon - nlon
6456    dlat = xlat - nlat
6457
6458# Making bigger the area to map
6459    nlon = np.min(lons)-dlon*0.1
6460    xlon = np.max(lons)+dlon*0.1
6461    nlat = np.min(lats)-dlat*0.1
6462    xlat = np.max(lats)+dlat*0.1 
6463
6464    plt.xlim(nlon,xlon)
6465    plt.ylim(nlat,xlat)
6466
6467    if not mapv is None:
6468        lon00 = np.where(lons[:] < 0., 360. + lons[:], lons[:])
6469        lat00 = lats[:]
6470
6471        map_proj=mapv.split(',')[0]
6472        map_res=mapv.split(',')[1]
6473
6474        lon2 = (nlon + xlon)/2.
6475        lat2 = (nlat + xlat)/2.
6476
6477        print 'lon2:', lon2, 'lat2:', lat2, 'SW pt:', nlon, ',', nlat, 'NE pt:',     \
6478          xlon, ',', xlat
6479
6480        if map_proj == 'cyl':
6481            m = Basemap(projection=map_proj, llcrnrlon=nlon, llcrnrlat=nlat,         \
6482              urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res)
6483        elif map_proj == 'lcc':
6484            m = Basemap(projection=map_proj, lat_0=lat2, lon_0=lon2, llcrnrlon=nlon, \
6485              llcrnrlat=nlat, urcrnrlon=xlon, urcrnrlat= xlat, resolution=map_res)
6486        else:
6487            print errormsg
6488            print '  ' + fname + ": projection '" + map_proj + "' not ready!!"
6489            print '    projections available: cyl, lcc'
6490            quit(-1)
6491
6492        m.drawcoastlines()
6493
6494        meridians = pretty_int(nlon,xlon,5)
6495        m.drawmeridians(meridians,labels=[True,False,False,True],color="black")
6496
6497        parallels = pretty_int(nlat,xlat,5)
6498        m.drawparallels(parallels,labels=[False,True,True,False],color="black")
6499
6500        plt.xlabel('W-E')
6501        plt.ylabel('S-N')
6502
6503    umin = 10.e20
6504    umax = -umin
6505    for rn in rns:
6506        nrns = np.min(rus[rn])
6507        xrns = np.max(rus[rn])
6508
6509        if umin > nrns: umin = nrns
6510        if umax < xrns: umax = xrns
6511
6512    i = 0
6513    for rn in rns:
6514        plt.pcolormesh(lons, lats, rus[rn], vmin=umin, vmax=umax,                    \
6515          cmap=plt.get_cmap(ucolor), norm=matplotlib.colors.LogNorm())
6516#        plt.pcolormesh(lons, lats, rss[rn], cmap=plt.get_cmap(ucolor))
6517        if rn == rns[0]: cbar = plt.colorbar()
6518        riverarea = rss[rn]
6519
6520        riverarea.mask = ma.nomask       
6521        rarea = np.where(riverarea == 999999999, -5, riverarea)
6522        rarea = np.where(rarea > 0, 1, 0)
6523        plt.contour(lons, lats, rarea, levels = [0.], colors=colvalues[i],           \
6524          linewidths=1.5)
6525
6526        oflow = ros[rn]
6527        plt.plot(oflow[0], oflow[1], 'h', color=colvalues[i], label=rn)
6528#        plt.annotate(rn, xy=(0., i*0.05), xycoords='axes fraction', color=colvalues[i])
6529        i = i+1
6530
6531
6532# Attempts to plot sub-basins
6533
6534# Gradient subbasins (not working)
6535#        gradriver = np.zeros((dy,dx), dtype=int)
6536#        for j in range(dy-2):
6537#            for i in range(dx-2):
6538#                gradriver[j,i] = riverarea[j,i+1]-riverarea[j,i]+riverarea[j+1,i]-  \
6539#                  riverarea[j,i]
6540#        garea = np.where(gradriver != 0, 1, gradriver)
6541#        print garea
6542#        plt.contour(lons, lats, garea, levels = [0.], colors='red', linewidths=1.)
6543
6544# Not working
6545#        subbasins = np.sort(np.unique(rarea))
6546#        for subb in subbasins:
6547#            if subb > 0.:
6548#                sarea = np.where(rarea != subb, 0, rarea)
6549#                plt.contour(lons, lats, sarea, levels = [1.], colors='gray', linewidths=1.)
6550
6551    cbar.set_label('upstream (' + units_lunits(uuts) + ')')
6552    plt.legend(loc=lloc)
6553
6554#    plt.annotate(windn.replace('_','\_') +' (' + units_lunits(wuts) + ')',           \
6555#      xy=(0.80,-0.15), xycoords='axes fraction', color='black')
6556
6557    plt.title(graphtit.replace('|',' ').replace('&','\&'))
6558
6559    output_kind(kfig, figname, True)
6560
6561    return
6562
Note: See TracBrowser for help on using the repository browser.