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

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

Fixing limit variables issue on `plot_lines_time'

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