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

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

Adding `found' when the dimension is already found in slice_variable

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