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

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

Final version of `plot_river_track'

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