source: lmdz_wrf/trunk/tools/diag_tools.py @ 2828

Last change on this file since 2828 was 2766, checked in by lfita, 5 years ago

Fixing 2Dhgradient

File size: 103.1 KB
Line 
1# Tools for the compute of diagnostics
2# L. Fita, CIMA. CONICET-UBA, CNRS UMI-IFAECI, Buenos Aires, Argentina
3
4# Available general pupose diagnostics (model independent) providing (varv1, varv2, ..., dimns, dimvns)
5# compute_accum: Function to compute the accumulation of a variable
6# compute_cllmh: Function to compute cllmh: low/medium/hight cloud fraction following
7#   newmicro.F90 from LMDZ compute_clt(cldfra, pres, dimns, dimvns)
8# compute_clt: Function to compute the total cloud fraction following 'newmicro.F90' from LMDZ
9# compute_clivi: Function to compute cloud-ice water path (clivi)
10# compute_clwvl: Function to compute condensed water path (clwvl)
11# compute_deaccum: Function to compute the deaccumulation of a variable
12# compute_mslp: Function to compute mslp: mean sea level pressure following p_interp.F90 from WRF
13# compute_OMEGAw: Function to transform OMEGA [Pas-1] to velocities [ms-1]
14# compute_prw: Function to compute water vapour path (prw)
15# compute_rh: Function to compute relative humidity following 'Tetens' equation (T,P) ...'
16# compute_td: Function to compute the dew point temperature
17# compute_turbulence: Function to compute the rubulence term of the Taylor's decomposition ...'
18# C_diagnostic: Class to compute generic variables
19# compute_wd: Function to compute the wind direction 3D
20# compute_wds: Function to compute the wind direction
21# compute_wss: Function to compute the wind speed
22# compute_WRFhur: Function to compute WRF relative humidity following Teten's equation
23# compute_WRFta: Function to compute WRF air temperature
24# compute_WRFtd: Function to compute WRF dew-point air temperature
25# compute_WRFua: Function to compute geographical rotated WRF x-wind
26# compute_WRFva: Function to compute geographical rotated WRF y-wind
27# compute_WRFuava: Function to compute geographical rotated WRF 3D winds
28# compute_WRFuas: Function to compute geographical rotated WRF 2-meter x-wind
29# compute_WRFvas: Function to compute geographical rotated WRF 2-meter y-wind
30# compute_WRFuasvas: Fucntion to compute geographical rotated WRF 2-meter winds
31# derivate_centered: Function to compute the centered derivate of a given field
32# Forcompute_cellbnds: Function to compute cellboundaries using wind-staggered lon,
33#   lats as intersection of their related parallels and meridians
34# Forcompute_cellbndsreg: Function to compute cellboundaries using lon, lat from a
35#   reglar lon/lat projection as intersection of their related parallels and meridians
36# Forcompute_cllmh: Function to compute cllmh: low/medium/hight cloud fraction
37#   following newmicro.F90 from LMDZ via Fortran subroutine
38# Forcompute_clt: Function to compute the total cloud fraction following
39#   'newmicro.F90' from LMDZ via a Fortran module
40# Forcompute_fog_K84: Computation of fog and visibility following Kunkel, (1984)
41# Forcompute_fog_RUC: Computation of fog and visibility following RUC method Smirnova, (2000)
42# Forcompute_fog_FRAML50: fog and visibility following Gultepe and Milbrandt, (2010)
43# Forcompute_front_R04: Function to compute front following Rodrigues et al.(2004)
44# Forcompute_frontogenesis: Function to compute frontogenesis
45# Forcompute_potevap_orPM: Function to compute potential evapotranspiration following
46#   Penman-Monteith formulation implemented in ORCHIDEE
47# Forcompute_psl_ptarget: Function to compute the sea-level pressure following
48#   target_pressure value found in `p_interp.F'
49# Forcompute_range_faces: Function to compute faces [uphill, valley, downhill] of sections of a
50#   mountain rage, along a given face
51# Forcompute_zmla_gen: Function to compute the boundary layer height following a
52#   generic method with Fortran
53# Forcompute_zwind: Function to compute the wind at a given height following the
54#   power law method
55# Forcompute_zwind_log: Function to compute the wind at a given height following the
56#   logarithmic law method
57# Forcompute_zwindMO: Function to compute the wind at a given height following the
58#   Monin-Obukhov theory
59# W_diagnostic: Class to compute WRF diagnostics variables
60
61# Others just providing variable values
62# var_cllmh: Fcuntion to compute cllmh on a 1D column
63# var_clt: Function to compute the total cloud fraction following 'newmicro.F90' from
64#   LMDZ using 1D vertical column values
65# var_convini: Function returns convective initialization (pr(t) > 0.0001) in time units
66# var_hur: Function to compute relative humidity following 'August - Roche - Magnus'
67#   formula
68# var_hur_Uhus: Function to compute relative humidity following 'August-Roche-Magnus'
69#   formula using hus
70# var_hur_tas_tds: Function to compute hur relative humidity from tas and tds
71# var_mslp: Fcuntion to compute mean sea-level pressure
72# var_td: Function to compute dew-point air temperature from temperature and pressure
73#   values
74# var_td_Uhus: Function to compute dew-point air temperature from temperature and
75#   pressure values using hus
76# var_tws_S11: Function to compute Wet Bulb temperature after Stull, 2011
77# var_timemax: This function returns the time at which variable reaches its maximum in time
78#   units
79# var_timeoverthres: This function returns the time at which (varv(t) > thres) in time units
80# var_virtualTemp: This function returns virtual temperature in K,
81# var_WRFtime: Function to copmute CFtimes from WRFtime variable
82# var_wd: Function to compute the wind direction
83# var_wd: Function to compute the wind speed
84# rotational_z: z-component of the rotatinoal of horizontal vectorial field
85# turbulence_var: Function to compute the Taylor's decomposition turbulence term from
86#   a a given variable
87
88import numpy as np
89from netCDF4 import Dataset as NetCDFFile
90import os
91import re
92import nc_var_tools as ncvar
93import generic_tools as gen
94import datetime as dtime
95import module_ForDiag as fdin
96import module_ForDef as fdef
97
98main = 'diag_tools.py'
99errormsg = 'ERROR -- error -- ERROR -- error'
100warnmsg = 'WARNING -- warning -- WARNING -- warning'
101
102# Constants
103grav = fdef.module_definitions.grav
104
105# Available WRFiag
106Wavailablediags = ['hur', 'p', 'ta', 'td', 'ua', 'va', 'uas', 'vas', 'wd', 'ws', 'zg']
107
108# Available General diagnostics
109Cavailablediags = ['hur', 'hur_Uhus', 'td', 'td_Uhus', 'wd', 'ws']
110
111# Gneral information
112##
113def reduce_spaces(string):
114    """ Function to give words of a line of text removing any extra space
115    """
116    values = string.replace('\n','').split(' ')
117    vals = []
118    for val in values:
119         if len(val) > 0:
120             vals.append(val)
121
122    return vals
123
124def variable_combo(varn,combofile):
125    """ Function to provide variables combination from a given variable name
126      varn= name of the variable
127      combofile= ASCII file with the combination of variables
128        [varn] [combo]
129          [combo]: '@' separated list of variables to use to generate [varn]
130            [WRFdt] to get WRF time-step (from general attributes)
131    >>> variable_combo('WRFprls','/home/lluis/PY/diagnostics.inf')
132    deaccum@RAINNC@XTIME@prnc
133    """
134    fname = 'variable_combo'
135
136    if varn == 'h':
137        print fname + '_____________________________________________________________'
138        print variable_combo.__doc__
139        quit()
140
141    if not os.path.isfile(combofile):
142        print errormsg
143        print '  ' + fname + ": file with combinations '" + combofile +              \
144          "' does not exist!!"
145        quit(-1)
146
147    objf = open(combofile, 'r')
148
149    found = False
150    for line in objf:
151        linevals = reduce_spaces(line)
152        varnf = linevals[0]
153        combo = linevals[1].replace('\n','')
154        if varn == varnf: 
155            found = True
156            break
157
158    if not found:
159        print errormsg
160        print '  ' + fname + ": variable '" + varn + "' not found in '" + combofile +\
161          "' !!"
162        combo='ERROR'
163
164    objf.close()
165
166    return combo
167
168# Mathematical operators
169##
170def compute_accum(varv, dimns, dimvns):
171    """ Function to compute the accumulation of a variable
172    compute_accum(varv, dimnames, dimvns)
173      [varv]= values to accum (assuming [t,])
174      [dimns]= list of the name of the dimensions of the [varv]
175      [dimvns]= list of the name of the variables with the values of the
176        dimensions of [varv]
177    """
178    fname = 'compute_accum'
179
180    deacdims = dimns[:]
181    deacvdims = dimvns[:]
182
183    slicei = []
184    slicee = []
185
186    Ndims = len(varv.shape)
187    for iid in range(0,Ndims):
188        slicei.append(slice(0,varv.shape[iid]))
189        slicee.append(slice(0,varv.shape[iid]))
190
191    slicee[0] = np.arange(varv.shape[0])
192    slicei[0] = np.arange(varv.shape[0])
193    slicei[0][1:varv.shape[0]] = np.arange(varv.shape[0]-1)
194
195    vari = varv[tuple(slicei)]
196    vare = varv[tuple(slicee)]
197
198    ac = vari*0.
199    for it in range(1,varv.shape[0]):
200        ac[it,] = ac[it-1,] + vare[it,]
201
202    return ac, deacdims, deacvdims
203
204def compute_deaccum(varv, dimns, dimvns):
205    """ Function to compute the deaccumulation of a variable
206    compute_deaccum(varv, dimnames, dimvns)
207      [varv]= values to deaccum (assuming [t,])
208      [dimns]= list of the name of the dimensions of the [varv]
209      [dimvns]= list of the name of the variables with the values of the
210        dimensions of [varv]
211    """
212    fname = 'compute_deaccum'
213
214    deacdims = dimns[:]
215    deacvdims = dimvns[:]
216
217    slicei = []
218    slicee = []
219
220    Ndims = len(varv.shape)
221    for iid in range(0,Ndims):
222        slicei.append(slice(0,varv.shape[iid]))
223        slicee.append(slice(0,varv.shape[iid]))
224
225    slicee[0] = np.arange(varv.shape[0])
226    slicei[0] = np.arange(varv.shape[0])
227    slicei[0][1:varv.shape[0]] = np.arange(varv.shape[0]-1)
228
229    vari = varv[tuple(slicei)]
230    vare = varv[tuple(slicee)]
231
232    deac = vare - vari
233
234    return deac, deacdims, deacvdims
235
236def derivate_centered(var,dim,dimv):
237    """ Function to compute the centered derivate of a given field
238      centered derivate(n) = (var(n-1) + var(n+1))/(2*dn).
239    [var]= variable
240    [dim]= which dimension to compute the derivate
241    [dimv]= dimension values (can be of different dimension of [var])
242    >>> derivate_centered(np.arange(16).reshape(4,4)*1.,1,1.)
243    [[  0.   1.   2.   0.]
244     [  0.   5.   6.   0.]
245     [  0.   9.  10.   0.]
246     [  0.  13.  14.   0.]]
247    """
248
249    fname = 'derivate_centered'
250   
251    vark = var.dtype
252
253    if hasattr(dimv, "__len__"):
254# Assuming that the last dimensions of var [..., N, M] are the same of dimv [N, M]
255        if len(var.shape) != len(dimv.shape):
256            dimvals = np.zeros((var.shape), dtype=vark)
257            if len(var.shape) - len(dimv.shape) == 1:
258                for iz in range(var.shape[0]):
259                    dimvals[iz,] = dimv
260            elif len(var.shape) - len(dimv.shape) == 2:
261                for it in range(var.shape[0]):
262                    for iz in range(var.shape[1]):
263                        dimvals[it,iz,] = dimv
264            else:
265                print errormsg
266                print '  ' + fname + ': dimension difference between variable',      \
267                  var.shape,'and variable with dimension values',dimv.shape,         \
268                  ' not ready !!!'
269                quit(-1)
270        else:
271            dimvals = dimv
272    else:
273# dimension values are identical everywhere!
274# from: http://stackoverflow.com/questions/16807011/python-how-to-identify-if-a-variable-is-an-array-or-a-scalar   
275        dimvals = np.ones((var.shape), dtype=vark)*dimv
276
277    derivate = np.zeros((var.shape), dtype=vark)
278    if dim > len(var.shape) - 1:
279        print errormsg
280        print '  ' + fname + ': dimension',dim,' too big for given variable of ' +   \
281          'shape:', var.shape,'!!!'
282        quit(-1)
283
284    slicebef = []
285    sliceaft = []
286    sliceder = []
287
288    for id in range(len(var.shape)):
289        if id == dim:
290            slicebef.append(slice(0,var.shape[id]-2))
291            sliceaft.append(slice(2,var.shape[id]))
292            sliceder.append(slice(1,var.shape[id]-1))
293        else:
294            slicebef.append(slice(0,var.shape[id]))
295            sliceaft.append(slice(0,var.shape[id]))
296            sliceder.append(slice(0,var.shape[id]))
297
298    if hasattr(dimv, "__len__"):
299        derivate[tuple(sliceder)] = (var[tuple(slicebef)] + var[tuple(sliceaft)])/   \
300          ((dimvals[tuple(sliceaft)] - dimvals[tuple(slicebef)]))
301        print (dimvals[tuple(sliceaft)] - dimvals[tuple(slicebef)])
302    else:
303        derivate[tuple(sliceder)] = (var[tuple(slicebef)] + var[tuple(sliceaft)])/   \
304          (2.*dimv)
305
306#    print 'before________'
307#    print var[tuple(slicebef)]
308
309#    print 'after________'
310#    print var[tuple(sliceaft)]
311
312    return derivate
313
314def rotational_z(Vx,Vy,pos):
315    """ z-component of the rotatinoal of horizontal vectorial field
316    \/ x (Vx,Vy,Vz) = \/xVy - \/yVx
317    [Vx]= Variable component x
318    [Vy]=  Variable component y
319    [pos]= poisition of the grid points
320    >>> rotational_z(np.arange(16).reshape(4,4)*1., np.arange(16).reshape(4,4)*1., 1.)
321    [[  0.   1.   2.   0.]
322     [ -4.   0.   0.  -7.]
323     [ -8.   0.   0. -11.]
324     [  0.  13.  14.   0.]]
325    """
326
327    fname =  'rotational_z'
328
329    ndims = len(Vx.shape)
330    rot1 = derivate_centered(Vy,ndims-1,pos)
331    rot2 = derivate_centered(Vx,ndims-2,pos)
332
333    rot = rot1 - rot2
334
335    return rot
336
337# Diagnostics
338##
339def Forcompute_cape_afwa(ta, hur, pa, zg, hgt, parcelm, dimns, dimvns):
340    """ Function to compute the CAPE, CIN, ZLFC, PLFC, LI following WRF
341      'phys/module_diaf_afwa.F' methodology
342    Forcompute_cape_afwa(ta, hur, pa, hgt, zsfc, parcelm, dimns, dimvns)
343      [ta]= air-temperature values (assuming [[t],z,y,x]) [K]
344      [pa]= pressure values (assuming [[t],z,y,x]) [Pa]
345      [zg]= gopotential height (assuming [[t],z,y,x]) [gpm]
346      [hgt]= topographical height (assuming [m]
347      [parcelm]= method of air-parcel to use
348      [dimns]= list of the name of the dimensions of [pa]
349      [dimvns]= list of the name of the variables with the values of the
350        dimensions of [pa]
351    """
352    fname = 'Forcompute_cape_afwa'
353
354    psldims = dimns[:]
355    pslvdims = dimvns[:]
356
357    if len(pa.shape) == 4:
358        cape = np.zeros((pa.shape[0],pa.shape[2],pa.shape[3]), dtype=np.float)
359        cin = np.zeros((pa.shape[0],pa.shape[2],pa.shape[3]), dtype=np.float)
360        zlfc = np.zeros((pa.shape[0],pa.shape[2],pa.shape[3]), dtype=np.float)
361        plfc = np.zeros((pa.shape[0],pa.shape[2],pa.shape[3]), dtype=np.float)
362        li = np.zeros((pa.shape[0],pa.shape[2],pa.shape[3]), dtype=np.float)
363
364        dx = pa.shape[3]
365        dy = pa.shape[2]
366        dz = pa.shape[1]
367        dt = pa.shape[0]
368        psldims.pop(1)
369        pslvdims.pop(1)
370
371        pcape,pcin,pzlfc,pplfc,pli= fdin.module_fordiagnostics.compute_cape_afwa4d(  \
372          ta=ta[:].transpose(), hur=hur[:].transpose(), press=pa[:].transpose(),     \
373          zg=zg[:].transpose(), hgt=hgt.transpose(), parcelmethod=parcelm, d1=dx,    \
374          d2=dy, d3=dz, d4=dt)
375        cape = pcape.transpose()
376        cin = pcin.transpose()
377        zlfc = pzlfc.transpose()
378        plfc = pplfc.transpose()
379        li = pli.transpose()
380    else:
381        print errormsg
382        print '  ' + fname + ': rank', len(pa.shape), 'not ready !!'
383        print '  it only computes 4D [t,z,y,x] rank values'
384        quit(-1)
385
386    return cape, cin, zlfc, plfc, li, psldims, pslvdims
387
388
389
390def var_clt(cfra):
391    """ Function to compute the total cloud fraction following 'newmicro.F90' from
392      LMDZ using 1D vertical column values
393      [cldfra]= cloud fraction values (assuming [[t],z,y,x])
394    """
395    ZEPSEC=1.0E-12
396
397    fname = 'var_clt'
398
399    zclear = 1.
400    zcloud = 0.
401
402    dz = cfra.shape[0]
403    for iz in range(dz):
404        zclear =zclear*(1.-np.max([cfra[iz],zcloud]))/(1.-np.min([zcloud,1.-ZEPSEC]))
405        clt = 1. - zclear
406        zcloud = cfra[iz]
407
408    return clt
409
410def compute_clt(cldfra, dimns, dimvns):
411    """ Function to compute the total cloud fraction following 'newmicro.F90' from
412      LMDZ
413    compute_clt(cldfra, dimnames)
414      [cldfra]= cloud fraction values (assuming [[t],z,y,x])
415      [dimns]= list of the name of the dimensions of [cldfra]
416      [dimvns]= list of the name of the variables with the values of the
417        dimensions of [cldfra]
418    """
419    fname = 'compute_clt'
420
421    cltdims = dimns[:]
422    cltvdims = dimvns[:]
423
424    if len(cldfra.shape) == 4:
425        clt = np.zeros((cldfra.shape[0],cldfra.shape[2],cldfra.shape[3]),            \
426          dtype=np.float)
427        dx = cldfra.shape[3]
428        dy = cldfra.shape[2]
429        dz = cldfra.shape[1]
430        dt = cldfra.shape[0]
431        cltdims.pop(1)
432        cltvdims.pop(1)
433
434        for it in range(dt):
435            for ix in range(dx):
436                for iy in range(dy):
437                    zclear = 1.
438                    zcloud = 0.
439                    gen.percendone(it*dx*dy + ix*dy + iy, dx*dy*dt, 5, 'diagnosted')
440                    clt[it,iy,ix] = var_clt(cldfra[it,:,iy,ix])
441
442    else:
443        clt = np.zeros((cldfra.shape[1],cldfra.shape[2]), dtype=np.float)
444        dx = cldfra.shape[2]
445        dy = cldfra.shape[1]
446        dy = cldfra.shape[0]
447        cltdims.pop(0)
448        cltvdims.pop(0)
449        for ix in range(dx):
450            for iy in range(dy):
451                zclear = 1.
452                zcloud = 0.
453                gen.percendone(ix*dy + iy, dx*dy*dt, 5, 'diagnosted')
454                clt[iy,ix] = var_clt(cldfra[:,iy,ix])
455
456    return clt, cltdims, cltvdims
457
458def Forcompute_clt(cldfra, dimns, dimvns):
459    """ Function to compute the total cloud fraction following 'newmicro.F90' from
460      LMDZ via a Fortran module
461    compute_clt(cldfra, dimnames)
462      [cldfra]= cloud fraction values (assuming [[t],z,y,x])
463      [dimns]= list of the name of the dimensions of [cldfra]
464      [dimvns]= list of the name of the variables with the values of the
465        dimensions of [cldfra]
466    """
467    fname = 'Forcompute_clt'
468
469    cltdims = dimns[:]
470    cltvdims = dimvns[:]
471
472
473    if len(cldfra.shape) == 4:
474        clt = np.zeros((cldfra.shape[0],cldfra.shape[2],cldfra.shape[3]),            \
475          dtype=np.float)
476        dx = cldfra.shape[3]
477        dy = cldfra.shape[2]
478        dz = cldfra.shape[1]
479        dt = cldfra.shape[0]
480        cltdims.pop(1)
481        cltvdims.pop(1)
482
483        clt = fdin.module_fordiagnostics.compute_clt4d2(cldfra[:])
484
485    else:
486        clt = np.zeros((cldfra.shape[1],cldfra.shape[2]), dtype=np.float)
487        dx = cldfra.shape[2]
488        dy = cldfra.shape[1]
489        dy = cldfra.shape[0]
490        cltdims.pop(0)
491        cltvdims.pop(0)
492
493        clt = fdin.module_fordiagnostics.compute_clt3d1(cldfra[:])
494
495    return clt, cltdims, cltvdims
496
497def var_cllmh(cfra, p):
498    """ Fcuntion to compute cllmh on a 1D column
499    """
500
501    fname = 'var_cllmh'
502
503    ZEPSEC =1.0E-12
504    prmhc = 440.*100.
505    prmlc = 680.*100.
506
507    zclearl = 1.
508    zcloudl = 0.
509    zclearm = 1.
510    zcloudm = 0.
511    zclearh = 1.
512    zcloudh = 0.
513
514    dvz = cfra.shape[0]
515
516    cllmh = np.ones((3), dtype=np.float)
517
518    for iz in range(dvz):
519        if p[iz] < prmhc:
520            cllmh[2] = cllmh[2]*(1.-np.max([cfra[iz], zcloudh]))/(1.-                \
521              np.min([zcloudh,1.-ZEPSEC]))
522            zcloudh = cfra[iz]
523        elif p[iz] >= prmhc and p[iz] < prmlc:
524            cllmh[1] = cllmh[1]*(1.-np.max([cfra[iz], zcloudm]))/(1.-                \
525              np.min([zcloudm,1.-ZEPSEC]))
526            zcloudm = cfra[iz]
527        elif p[iz] >= prmlc:
528            cllmh[0] = cllmh[0]*(1.-np.max([cfra[iz], zcloudl]))/(1.-                \
529              np.min([zcloudl,1.-ZEPSEC]))
530            zcloudl = cfra[iz]
531
532    cllmh = 1.- cllmh
533
534    return cllmh
535
536def Forcompute_cellbnds(ulon, ulat, vlon, vlat, dimns, dimvns):
537    """ Function to compute cellboundaries using wind-staggered lon, lats as
538      intersection of their related parallels and meridians
539    compute_cellbnds(ulon, ulat, vlon, vlat, dimns, dimvns)
540      [ulon]= x-staggered longitudes (assuming [y,x+1])
541      [ulat]= x-staggered latitudes (assuming [y,x+1])
542      [vlon]= y-staggered longitudes (assuming [y+1,x])
543      [vlat]= y-staggered latitudes (assuming [y+1,x])
544      [dimns]= list of the name of the dimensions of [cldfra]
545      [dimvns]= list of the name of the variables with the values of the
546        dimensions of [ulon]
547    """
548    fname = 'Forcompute_cellbnds'
549
550    dims = dimns[:]
551    vdims = dimvns[:]
552
553    if len(ulon.shape) == 2:
554        sdx = ulon.shape[1]
555        dy = ulon.shape[0]
556        dx = vlon.shape[1]
557        sdy = vlon.shape[0]
558
559        ulont = ulon.transpose()
560        ulatt = ulat.transpose()
561        vlont = vlon.transpose()
562        vlatt = vlat.transpose()
563
564        xbndst, ybndst = fdin.module_fordiagnostics.compute_cellbnds(ulon=ulont,     \
565          ulat=ulatt, vlon=vlont, vlat=vlatt, dx=dx, dy=dy, sdx=sdx, sdy=sdy)
566    else:
567        print errormsg
568        print '  ' + fname + ": wrong rank of variables !!"
569        print '    2D matrices are expected and its found instead'
570        print '    ulon shape:', ulon.shape
571        print '    ulat shape:', ulat.shape
572        print '    vlon shape:', vlon.shape
573        print '    vlat shape:', vlat.shape
574        quit(-1)
575   
576    xbnds = xbndst.transpose()
577    ybnds = ybndst.transpose()
578
579    return xbnds, ybnds, dims, vdims
580
581
582def Forcompute_cellbndsreg(lon, lat, dimns, dimvns):
583    """ Function to compute cellboundaries using lon, lat from a reglar lon/lat
584      projection as intersection of their related parallels and meridians
585    compute_cellbnds(ulon, ulat, vlon, vlat, dimns, dimvns)
586      [ulon]= x-staggered longitudes (assuming [y,x+1])
587      [ulat]= x-staggered latitudes (assuming [y,x+1])
588      [vlon]= y-staggered longitudes (assuming [y+1,x])
589      [vlat]= y-staggered latitudes (assuming [y+1,x])
590      [dimns]= list of the name of the dimensions of [cldfra]
591      [dimvns]= list of the name of the variables with the values of the
592        dimensions of [ulon]
593    """
594    fname = 'Forcompute_cellbndsreg'
595
596    dims = dimns[:]
597    vdims = dimvns[:]
598
599    if len(lon.shape) == 2:
600        dy = lon.shape[0]
601        dx = lon.shape[1]
602
603        lont = lon.transpose()
604        latt = lat.transpose()
605
606        xbndst, ybndst = fdin.module_fordiagnostics.compute_cellbndsreg(lon=lont,    \
607          lat=latt, dx=dx, dy=dy)
608    else:
609        print errormsg
610        print '  ' + fname + ": wrong rank of variables !!"
611        print '    2D matrices are expected and its found instead'
612        print '    lon shape:', lon.shape
613        print '    lat shape:', lat.shape
614        quit(-1)
615   
616    xbnds = xbndst.transpose()
617    ybnds = ybndst.transpose()
618
619    return xbnds, ybnds, dims, vdims
620
621def Forcompute_cllmh(cldfra, pres, dimns, dimvns):
622    """ Function to compute cllmh: low/medium/hight cloud fraction following newmicro.F90 from LMDZ via Fortran subroutine
623    compute_clt(cldfra, pres, dimns, dimvns)
624      [cldfra]= cloud fraction values (assuming [[t],z,y,x])
625      [pres] = pressure field
626      [dimns]= list of the name of the dimensions of [cldfra]
627      [dimvns]= list of the name of the variables with the values of the
628        dimensions of [cldfra]
629    """
630    fname = 'Forcompute_cllmh'
631
632    cllmhdims = dimns[:]
633    cllmhvdims = dimvns[:]
634
635    if len(cldfra.shape) == 4:
636        dx = cldfra.shape[3]
637        dy = cldfra.shape[2]
638        dz = cldfra.shape[1]
639        dt = cldfra.shape[0]
640        cllmhdims.pop(1)
641        cllmhvdims.pop(1)
642
643        cllmh = fdin.module_fordiagnostics.compute_cllmh4d2(cldfra[:], pres[:])
644       
645    else:
646        dx = cldfra.shape[2]
647        dy = cldfra.shape[1]
648        dz = cldfra.shape[0]
649        cllmhdims.pop(0)
650        cllmhvdims.pop(0)
651
652        cllmh = fdin.module_fordiagnostics.compute_cllmh3d1(cldfra[:], pres[:])
653
654    return cllmh, cllmhdims, cllmhvdims
655
656def compute_cllmh(cldfra, pres, dimns, dimvns):
657    """ Function to compute cllmh: low/medium/hight cloud fraction following newmicro.F90 from LMDZ
658    compute_clt(cldfra, pres, dimns, dimvns)
659      [cldfra]= cloud fraction values (assuming [[t],z,y,x])
660      [pres] = pressure field
661      [dimns]= list of the name of the dimensions of [cldfra]
662      [dimvns]= list of the name of the variables with the values of the
663        dimensions of [cldfra]
664    """
665    fname = 'compute_cllmh'
666
667    cllmhdims = dimns[:]
668    cllmhvdims = dimvns[:]
669
670    if len(cldfra.shape) == 4:
671        dx = cldfra.shape[3]
672        dy = cldfra.shape[2]
673        dz = cldfra.shape[1]
674        dt = cldfra.shape[0]
675        cllmhdims.pop(1)
676        cllmhvdims.pop(1)
677
678        cllmh = np.ones(tuple([3, dt, dy, dx]), dtype=np.float)
679
680        for it in range(dt):
681            for ix in range(dx):
682                for iy in range(dy):
683                    gen.percendone(it*dx*dy + ix*dy + iy, dx*dy*dt, 5, 'diagnosted')
684                    cllmh[:,it,iy,ix] = var_cllmh(cldfra[it,:,iy,ix], pres[it,:,iy,ix])
685       
686    else:
687        dx = cldfra.shape[2]
688        dy = cldfra.shape[1]
689        dz = cldfra.shape[0]
690        cllmhdims.pop(0)
691        cllmhvdims.pop(0)
692
693        cllmh = np.ones(tuple([3, dy, dx]), dtype=np.float)
694
695        for ix in range(dx):
696            for iy in range(dy):
697                gen.percendone(ix*dy + iy,dx*dy, 5, 'diagnosted')
698                cllmh[:,iy,ix] = var_cllmh(cldfra[:,iy,ix], pres[:,iy,ix])
699
700    return cllmh, cllmhdims, cllmhvdims
701
702def compute_clivi(dens, qtot, dimns, dimvns):
703    """ Function to compute cloud-ice water path (clivi)
704      [dens] = density [in kgkg-1] (assuming [t],z,y,x)
705      [qtot] = added mixing ratio of all cloud-ice species in [kgkg-1] (assuming [t],z,y,x)
706      [dimns]= list of the name of the dimensions of [q]
707      [dimvns]= list of the name of the variables with the values of the
708        dimensions of [q]
709    """
710    fname = 'compute_clivi'
711
712    clividims = dimns[:]
713    clivivdims = dimvns[:]
714
715    if len(qtot.shape) == 4:
716        clividims.pop(1)
717        clivivdims.pop(1)
718    else:
719        clividims.pop(0)
720        clivivdims.pop(0)
721
722    data1 = dens*qtot
723    clivi = np.sum(data1, axis=1)
724
725    return clivi, clividims, clivivdims
726
727
728def compute_clwvl(dens, qtot, dimns, dimvns):
729    """ Function to compute condensed water path (clwvl)
730      [dens] = density [in kgkg-1] (assuming [t],z,y,x)
731      [qtot] = added mixing ratio of all cloud-water species in [kgkg-1] (assuming [t],z,y,x)
732      [dimns]= list of the name of the dimensions of [q]
733      [dimvns]= list of the name of the variables with the values of the
734        dimensions of [q]
735    """
736    fname = 'compute_clwvl'
737
738    clwvldims = dimns[:]
739    clwvlvdims = dimvns[:]
740
741    if len(qtot.shape) == 4:
742        clwvldims.pop(1)
743        clwvlvdims.pop(1)
744    else:
745        clwvldims.pop(0)
746        clwvlvdims.pop(0)
747
748    data1 = dens*qtot
749    clwvl = np.sum(data1, axis=1)
750
751    return clwvl, clwvldims, clwvlvdims
752
753def var_virtualTemp (temp,rmix):
754    """ This function returns virtual temperature in K,
755      temp: temperature [K]
756      rmix: mixing ratio in [kgkg-1]
757    """
758
759    fname = 'var_virtualTemp'
760
761    virtual=temp*(0.622+rmix)/(0.622*(1.+rmix))
762
763    return virtual
764
765def var_convini(pr, time, dimns, dimvns):
766    """ This function returns convective initialization (pr(t) > 0.0001) in time units
767      pr: precipitation fux [kgm-2s-1]
768      time: time in CF coordinates
769    """
770    fname = 'var_convini'
771
772    dt = pr.shape[0]
773    dy = pr.shape[1]
774    dx = pr.shape[2]
775
776    vardims = dimns[:]
777    varvdims = dimvns[:]
778
779    vardims.pop(0)
780    varvdims.pop(0)
781
782    prmin = 0.0001
783    convini = np.ones((dy, dx), dtype=np.float)*gen.fillValueF
784    for it in range(dt):
785# NOT working ?
786#        convini = np.where(convini == gen.fillValueF and pr[it,:,:] >= prmin,        \
787#          time[it], fillValueF)
788        for j in range(dy):
789            for i in range(dx):
790                if convini[j,i] == gen.fillValueF and pr[it,j,i] >= prmin:
791                    convini[j,i] = time[it]
792                    break
793
794    return convini, vardims, varvdims
795
796def var_timemax(varv, time, dimns, dimvns):
797    """ This function returns the time at which variable reaches its maximum in time
798        units
799      varv: values of the variable to use
800      time: time in CF coordinates
801    """
802    fname = 'var_timemax'
803
804    dt = varv.shape[0]
805    dy = varv.shape[1]
806    dx = varv.shape[2]
807
808    vardims = dimns[:]
809    varvdims = dimvns[:]
810
811    vardims.pop(0)
812    varvdims.pop(0)
813
814    timemax = np.ones((dy, dx), dtype=np.float)*gen.fillValueF
815    varmax = np.max(varv, axis=0)
816    for j in range(dy):
817        for i in range(dx):
818            it = gen.index_vec(varv[:,j,i], varmax[j,i])
819            timemax[j,i] = time[it]
820
821    return timemax, vardims, varvdims
822
823def var_timeoverthres(varv, time, thres, dimns, dimvns):
824    """ This function returns the time at which (varv(t) > thres) in time units
825      varv: values of the variable to use
826      time: time in CF coordinates
827      thres: threshold to overpass
828    """
829    fname = 'var_timeoverthres'
830
831    dt = varv.shape[0]
832    dy = varv.shape[1]
833    dx = varv.shape[2]
834
835    vardims = dimns[:]
836    varvdims = dimvns[:]
837
838    vardims.pop(0)
839    varvdims.pop(0)
840
841    timeoverthres = np.ones((dy, dx), dtype=np.float)*gen.fillValueF
842    for it in range(dt):
843        for j in range(dy):
844            for i in range(dx):
845                if timeoverthres[j,i] == gen.fillValueF and varv[it,j,i] >= thres:
846                    timeoverthres[j,i] = time[it]
847                    break
848
849    return timeoverthres, vardims, varvdims
850
851def Forcompute_zint(var, zinterlev, zweights, dimns, dimvns):
852    """ Function to compute a vertical integration of volumetric quantities
853    Forcompute_mrso(smois, dsoil, dimns, dimvns)
854      [var]= values (assuming [[t],z,y,x]) [volumetric units]
855      [zinterlev]= depth of each layer (assuming [z]) [same z units as var]
856      [zweights]= weights to apply to each level (just in case...)
857      [dimns]= list of the name of the dimensions of [smois]
858      [dimvns]= list of the name of the variables with the values of the
859        dimensions of [smois]
860    """
861    fname = 'Forcompute_zint'
862
863    vardims = dimns[:]
864    varvdims = dimvns[:]
865
866    if len(var.shape) == 4:
867        zint = np.zeros((var.shape[0],var.shape[2],var.shape[3]), dtype=np.float)
868        dx = var.shape[3]
869        dy = var.shape[2]
870        dz = var.shape[1]
871        dt = var.shape[0]
872        vardims.pop(1)
873        varvdims.pop(1)
874
875        zintvart=fdin.module_fordiagnostics.compute_zint4d(var4d=var[:].transpose(), \
876          dlev=zinterlev[:].transpose(), zweight=zweights[:].transpose(), d1=dx,     \
877          d2=dy, d3=dz, d4=dt)
878        zintvar = zintvart.transpose()
879    else:
880        print errormsg
881        print '  ' + fname + ': rank', len(var.shape), 'not ready !!'
882        print '  it only computes 4D [t,z,y,x] rank values'
883        quit(-1)
884
885    return zintvar, vardims, varvdims
886
887def var_mslp(pres, psfc, ter, tk, qv):
888    """ Function to compute mslp on a 1D column
889    """
890
891    fname = 'var_mslp'
892
893    N = 1.0
894    expon=287.04*.0065/9.81
895    pref = 40000.
896
897# First find where about 400 hPa is located
898    dz=len(pres) 
899
900    kref = -1
901    pinc = pres[0] - pres[dz-1]
902
903    if pinc < 0.:
904        for iz in range(1,dz):
905            if pres[iz-1] >= pref and pres[iz] < pref: 
906                kref = iz
907                break
908    else:
909        for iz in range(dz-1):
910            if pres[iz] >= pref and pres[iz+1] < pref: 
911                kref = iz
912                break
913
914    if kref == -1:
915        print errormsg
916        print '  ' + fname + ': no reference pressure:',pref,'found!!'
917        print '    values:',pres[:]
918        quit(-1)
919
920    mslp = 0.
921
922# We are below both the ground and the lowest data level.
923
924# First, find the model level that is closest to a "target" pressure
925# level, where the "target" pressure is delta-p less that the local
926# value of a horizontally smoothed surface pressure field.  We use
927# delta-p = 150 hPa here. A standard lapse rate temperature profile
928# passing through the temperature at this model level will be used
929# to define the temperature profile below ground.  This is similar
930# to the Benjamin and Miller (1990) method, using 
931# 700 hPa everywhere for the "target" pressure.
932
933# ptarget = psfc - 15000.
934    ptarget = 70000.
935    dpmin=1.e4
936    kupper = 0
937    if pinc > 0.:
938        for iz in range(dz-1,0,-1):
939            kupper = iz
940            dp=np.abs( pres[iz] - ptarget )
941            if dp < dpmin: exit
942            dpmin = np.min([dpmin, dp])
943    else:
944        for iz in range(dz):
945            kupper = iz
946            dp=np.abs( pres[iz] - ptarget )
947            if dp < dpmin: exit
948            dpmin = np.min([dpmin, dp])
949
950    pbot=np.max([pres[0], psfc])
951#    zbot=0.
952
953#    tbotextrap=tk(i,j,kupper,itt)*(pbot/pres_field(i,j,kupper,itt))**expon
954#    tvbotextrap=virtual(tbotextrap,qv(i,j,1,itt))
955
956#    data_out(i,j,itt,1) = (zbot+tvbotextrap/.0065*(1.-(interp_levels(1)/pbot)**expon))
957    tbotextrap = tk[kupper]*(psfc/ptarget)**expon
958    tvbotextrap = var_virtualTemp(tbotextrap, qv[kupper])
959    mslp = psfc*( (tvbotextrap+0.0065*ter)/tvbotextrap)**(1./expon)
960
961    return mslp
962
963def compute_mslp(pressure, psurface, terrain, temperature, qvapor, dimns, dimvns):
964    """ Function to compute mslp: mean sea level pressure following p_interp.F90 from WRF
965    var_mslp(pres, ter, tk, qv, dimns, dimvns)
966      [pressure]= pressure field [Pa] (assuming [[t],z,y,x])
967      [psurface]= surface pressure field [Pa]
968      [terrain]= topography [m]
969      [temperature]= temperature [K]
970      [qvapor]= water vapour mixing ratio [kgkg-1]
971      [dimns]= list of the name of the dimensions of [cldfra]
972      [dimvns]= list of the name of the variables with the values of the
973        dimensions of [pres]
974    """
975
976    fname = 'compute_mslp'
977
978    mslpdims = list(dimns[:])
979    mslpvdims = list(dimvns[:])
980
981    if len(pressure.shape) == 4:
982        mslpdims.pop(1)
983        mslpvdims.pop(1)
984    else:
985        mslpdims.pop(0)
986        mslpvdims.pop(0)
987
988    if len(pressure.shape) == 4:
989        dx = pressure.shape[3]
990        dy = pressure.shape[2]
991        dz = pressure.shape[1]
992        dt = pressure.shape[0]
993
994        mslpv = np.zeros(tuple([dt, dy, dx]), dtype=np.float)
995
996# Terrain... to 2D !
997        terval = np.zeros(tuple([dy, dx]), dtype=np.float)
998        if len(terrain.shape) == 3:
999            terval = terrain[0,:,:]
1000        else:
1001            terval = terrain
1002
1003        for ix in range(dx):
1004            for iy in range(dy):
1005                if terval[iy,ix] > 0.:
1006                    for it in range(dt):
1007                        mslpv[it,iy,ix] = var_mslp(pressure[it,:,iy,ix],             \
1008                          psurface[it,iy,ix], terval[iy,ix], temperature[it,:,iy,ix],\
1009                          qvapor[it,:,iy,ix])
1010
1011                        gen.percendone(it*dx*dy + ix*dy + iy, dx*dy*dt, 5, 'diagnosted')
1012                else:
1013                    mslpv[:,iy,ix] = psurface[:,iy,ix]
1014
1015    else:
1016        dx = pressure.shape[2]
1017        dy = pressure.shape[1]
1018        dz = pressure.shape[0]
1019
1020        mslpv = np.zeros(tuple([dy, dx]), dtype=np.float)
1021
1022# Terrain... to 2D !
1023        terval = np.zeros(tuple([dy, dx]), dtype=np.float)
1024        if len(terrain.shape) == 3:
1025            terval = terrain[0,:,:]
1026        else:
1027            terval = terrain
1028
1029        for ix in range(dx):
1030            for iy in range(dy):
1031                gen.percendone(ix*dy + iy,dx*dy, 5, 'diagnosted')
1032                if terval[iy,ix] > 0.:
1033                    mslpv[iy,ix] = var_mslp(pressure[:,iy,ix], psurface[iy,ix],      \
1034                      terval[iy,ix], temperature[:,iy,ix], qvapor[:,iy,ix])
1035                else:
1036                    mslpv[iy,ix] = psfc[iy,ix]
1037
1038    return mslpv, mslpdims, mslpvdims
1039
1040def Forcompute_gradient2Dh(var, x, y, dimns, dimvns):
1041    """ Function to compute 1st order horizontal 2D gradient of any given variable
1042    Forcompute_gradient(var, x, y, dimns, dimvns)
1043      [var]= variable (assuming [[t],z,y,x]) [??]
1044      [x]= distance along x-axis (assuming [y,x]) [?]
1045      [y]= distance along y-axis (assuming [y,x]) [?]
1046      [dimns]= list of the name of the dimensions of [pa]
1047      [dimvns]= list of the name of the variables with the values of the
1048        dimensions
1049    """
1050    fname = 'Forcompute_gradient'
1051
1052    vardims = dimns[:]
1053    varvdims = dimvns[:]
1054
1055    if len(var.shape) == 2:
1056        dx = var.shape[1]
1057        dy = var.shape[0]
1058        gradt=fdin.module_fordiagnostics.compute_gradient2dh1rk(                     \
1059          v=var[:].transpose(), x=x[:].transpose(), y=y[:].transpose(), d1=dx,       \
1060          d2=dy)
1061    elif len(var.shape) == 3:
1062        dx = var.shape[2]
1063        dy = var.shape[1]
1064        dt = var.shape[0]
1065        gradt=fdin.module_fordiagnostics.compute_gradient2dh3rk(                     \
1066          v=var[:].transpose(), x=x[:].transpose(), y=y[:].transpose(), d1=dx,       \
1067          d2=dy, d3=dt)
1068    elif len(var.shape) == 4:
1069        dx = var.shape[3]
1070        dy = var.shape[2]
1071        dz = var.shape[1]
1072        dt = var.shape[0]
1073        gradt=fdin.module_fordiagnostics.compute_gradient2dh4rk( \
1074          v=var[:].transpose(), x=x[:].transpose(), y=y[:].transpose(), d1=dx,        \
1075          d2=dy, d3=dz, d4=dt)
1076    else:
1077        print errormsg
1078        print '  ' + fname + ': rank', len(var.shape), 'not ready !!'
1079        print '  it only computes 2D [y,x], 3D [t,y,x], or 4D [t,y,x] rank values'
1080        quit(-1)
1081    grad = gradt.transpose()
1082
1083    return grad, vardims, varvdims
1084
1085def Forcompute_psl_ecmwf(ps, hgt, ta1, pa2, unpa1, dimns, dimvns):
1086    """ Function to compute the sea-level pressure following Mats Hamrud and Philippe Courtier [Pa]
1087    Forcompute_psl_ptarget(ps, hgt, ta1, pa2, unpa1, dimns, dimvns)
1088      [ps]= surface pressure values (assuming [[t],y,x]) [Pa]
1089      [hgt]= opography (assuming [y,x]) [m]
1090      [ta1]= air-temperature values at first half-mass level (assuming [[t],y,x]) [K]
1091      [pa2]= pressure values at second full-mass levels (assuming [[t],y,x]) [Pa]
1092      [unpa1]= pressure values at first half-mass levels (assuming [[t],y,x]) [Pa]
1093      [dimns]= list of the name of the dimensions of [pa]
1094      [dimvns]= list of the name of the variables with the values of the
1095        dimensions of [pa]
1096    """
1097    fname = 'Forcompute_psl_ecmwf'
1098
1099    vardims = dimns[:]
1100    varvdims = dimvns[:]
1101
1102    if len(pa2.shape) == 3:
1103        psl = np.zeros((pa2.shape[0],pa2.shape[1],pa2.shape[2]), dtype=np.float)
1104        dx = pa2.shape[2]
1105        dy = pa2.shape[1]
1106        dt = pa2.shape[0]
1107        pslt= fdin.module_fordiagnostics.compute_psl_ecmwf( ps=ps[:].transpose(),    \
1108          hgt=hgt[:].transpose(), t=ta1[:].transpose(), press=pa2[:].transpose(),    \
1109          unpress=unpa1[:].transpose(), d1=dx, d2=dy, d4=dt)
1110        psl = pslt.transpose()
1111    else:
1112        print errormsg
1113        print '  ' + fname + ': rank', len(pa2.shape), 'not ready !!'
1114        print '  it only computes 3D [t,y,x] rank values'
1115        quit(-1)
1116
1117    return psl, vardims, varvdims
1118
1119def Forcompute_psl_ptarget(pa, ps, ta, hgt, qv, target_pressure, dimns, dimvns):
1120    """ Function to compute the sea-level pressure following target_pressure value
1121      found in `p_interp.F'
1122    Forcompute_psl_ptarget(pa, ps, ta, hgt, qv, dimns, dimvns)
1123      [pa]= pressure values (assuming [[t],z,y,x]) [Pa]
1124      [ps]= surface pressure values (assuming [[t],y,x]) [Pa]
1125      [ta]= air-temperature values (assuming [[t],z,y,x]) [K]
1126      [hgt]= opography (assuming [y,x]) [m]
1127      [qv]= water vapour mixing ratio (assuming [[t],z,y,x]) [kgkg-1]
1128      [dimns]= list of the name of the dimensions of [pa]
1129      [dimvns]= list of the name of the variables with the values of the
1130        dimensions of [pa]
1131    """
1132    fname = 'Forcompute_psl_ptarget'
1133
1134    psldims = dimns[:]
1135    pslvdims = dimvns[:]
1136
1137    if len(pa.shape) == 4:
1138        psl = np.zeros((pa.shape[0],pa.shape[2],pa.shape[3]), dtype=np.float)
1139        dx = pa.shape[3]
1140        dy = pa.shape[2]
1141        dz = pa.shape[1]
1142        dt = pa.shape[0]
1143        psldims.pop(1)
1144        pslvdims.pop(1)
1145
1146        pslt= fdin.module_fordiagnostics.compute_psl_ptarget4d2(                     \
1147          press=pa[:].transpose(), ps=ps[:].transpose(), hgt=hgt[:].transpose(),     \
1148          ta=ta[:].transpose(), qv=qv[:].transpose(), ptarget=target_pressure,       \
1149          d1=dx, d2=dy, d3=dz, d4=dt)
1150        psl = pslt.transpose()
1151    else:
1152        print errormsg
1153        print '  ' + fname + ': rank', len(pa.shape), 'not ready !!'
1154        print '  it only computes 4D [t,z,y,x] rank values'
1155        quit(-1)
1156
1157    return psl, psldims, pslvdims
1158
1159def Forcompute_zmla_gen(theta, qratio, zpl, hgt, dimns, dimvns):
1160    """ Function to compute the boundary layer height following a generic method
1161      with Fortran
1162    Forcompute_zmla_gen(theta, qratio, zpl, hgt, zmla, dimns, dimvns)
1163      [theta]= potential air-temperature values (assuming [[t],z,y,x]) [K]
1164      [qratio]= water mixing ratio (assuming [[t],z,y,x]) [kgkg-1]
1165      [zpl]= height from sea level (assuming [[t],z,y,x]) [m]
1166      [hgt]= topographical height (assuming [m]
1167      [zmla]= boundary layer height [m]
1168      [dimns]= list of the name of the dimensions of [theta]
1169      [dimvns]= list of the name of the variables with the values of the
1170        dimensions of [theta]
1171    """
1172    fname = 'Forcompute_zmla_gen'
1173
1174    zmladims = dimns[:]
1175    zmlavdims = dimvns[:]
1176
1177    if len(theta.shape) == 4:
1178        zmla= np.zeros((theta.shape[0],theta.shape[2],theta.shape[3]), dtype=np.float)
1179
1180        dx = theta.shape[3]
1181        dy = theta.shape[2]
1182        dz = theta.shape[1]
1183        dt = theta.shape[0]
1184        zmladims.pop(1)
1185        zmlavdims.pop(1)
1186
1187        pzmla= fdin.module_fordiagnostics.compute_zmla_generic4d(                    \
1188          tpot=theta[:].transpose(), qratio=qratio[:].transpose(),                   \
1189          z=zpl[:].transpose(), hgt=hgt.transpose(), d1=dx, d2=dy, d3=dz, d4=dt)
1190        zmla = pzmla.transpose()
1191
1192    elif len(theta.shape) == 2:
1193        zmla= np.zeros((theta.shape[0], theta.shape[1]), dtype=np.float)
1194
1195        dz = theta.shape[1]
1196        dt = theta.shape[0]
1197        zmladims.pop(1)
1198        zmlavdims.pop(1)
1199
1200        pzmla= fdin.module_fordiagnostics.compute_zmla_generic2d(                    \
1201          tpot=theta[:].transpose(), qratio=qratio[:].transpose(),                   \
1202          z=zpl[:].transpose(), hgt=hgt, d1=dz, d2=dt)
1203        zmla = pzmla.transpose()
1204
1205    else:
1206        print errormsg
1207        print '  ' + fname + ': rank', len(theta.shape), 'not ready !!'
1208        print '  it only computes 4D [t,z,y,x] rank values'
1209        quit(-1)
1210
1211    return zmla, zmladims, zmlavdims
1212
1213def Forcompute_zwind(ua, va, z, uas, vas, sina, cosa, zval, dimns, dimvns):
1214    """ Function to compute the wind at a given height following the power law method
1215    Forcompute_zwind(ua, va, zsl, uas, vas, hgt, sina, cosa, zval, dimns, dimvns)
1216      [ua]= x-component of unstaggered 3D wind (assuming [[t],z,y,x]) [ms-1]
1217      [va]= y-component of unstaggered 3D wind (assuming [[t],z,y,x]) [ms-1]
1218      [z]= height above surface [m]
1219      [uas]= x-component of unstaggered 10 m wind (assuming [[t],z,y,x]) [ms-1]
1220      [vas]= y-component of unstaggered 10 m wind (assuming [[t],z,y,x]) [ms-1]
1221      [sina]= local sine of map rotation [1.]
1222      [cosa]= local cosine of map rotation [1.]
1223      [zval]= desired height for winds [m]
1224      [dimns]= list of the name of the dimensions of [ua]
1225      [dimvns]= list of the name of the variables with the values of the
1226        dimensions of [ua]
1227    """
1228    fname = 'Forcompute_zwind'
1229
1230    vardims = dimns[:]
1231    varvdims = dimvns[:]
1232
1233    if len(ua.shape) == 4:
1234        var1= np.zeros((ua.shape[0],ua.shape[2],ua.shape[3]), dtype=np.float)
1235        var2= np.zeros((ua.shape[0],ua.shape[2],ua.shape[3]), dtype=np.float)
1236
1237        dx = ua.shape[3]
1238        dy = ua.shape[2]
1239        dz = ua.shape[1]
1240        dt = ua.shape[0]
1241        vardims.pop(1)
1242        varvdims.pop(1)
1243
1244        pvar1, pvar2= fdin.module_fordiagnostics.compute_zwind4d(ua=ua.transpose(),  \
1245          va=va[:].transpose(), z=z[:].transpose(), uas=uas.transpose(),             \
1246          vas=vas.transpose(), sina=sina.transpose(), cosa=cosa.transpose(),         \
1247          zextrap=zval, d1=dx, d2=dy, d3=dz, d4=dt)
1248        var1 = pvar1.transpose()
1249        var2 = pvar2.transpose()
1250    else:
1251        print errormsg
1252        print '  ' + fname + ': rank', len(ua.shape), 'not ready !!'
1253        print '  it only computes 4D [t,z,y,x] rank values'
1254        quit(-1)
1255
1256    return var1, var2, vardims, varvdims
1257
1258def Forcompute_zwind_log(ua, va, z, uas, vas, sina, cosa, zval, dimns, dimvns):
1259    """ Function to compute the wind at a given height following the logarithmic law method
1260    Forcompute_zwind(ua, va, zsl, uas, vas, hgt, sina, cosa, zval, dimns, dimvns)
1261      [ua]= x-component of unstaggered 3D wind (assuming [[t],z,y,x]) [ms-1]
1262      [va]= y-component of unstaggered 3D wind (assuming [[t],z,y,x]) [ms-1]
1263      [z]= height above surface [m]
1264      [uas]= x-component of unstaggered 10 m wind (assuming [[t],z,y,x]) [ms-1]
1265      [vas]= y-component of unstaggered 10 m wind (assuming [[t],z,y,x]) [ms-1]
1266      [sina]= local sine of map rotation [1.]
1267      [cosa]= local cosine of map rotation [1.]
1268      [zval]= desired height for winds [m]
1269      [dimns]= list of the name of the dimensions of [ua]
1270      [dimvns]= list of the name of the variables with the values of the
1271        dimensions of [ua]
1272    """
1273    fname = 'Forcompute_zwind_log'
1274
1275    vardims = dimns[:]
1276    varvdims = dimvns[:]
1277
1278    if len(ua.shape) == 4:
1279        var1= np.zeros((ua.shape[0],ua.shape[2],ua.shape[3]), dtype=np.float)
1280        var2= np.zeros((ua.shape[0],ua.shape[2],ua.shape[3]), dtype=np.float)
1281
1282        dx = ua.shape[3]
1283        dy = ua.shape[2]
1284        dz = ua.shape[1]
1285        dt = ua.shape[0]
1286        vardims.pop(1)
1287        varvdims.pop(1)
1288
1289        pvar1, pvar2= fdin.module_fordiagnostics.compute_zwind_log4d(                \
1290          ua=ua.transpose(), va=va[:].transpose(), z=z[:].transpose(),               \
1291          uas=uas.transpose(), vas=vas.transpose(), sina=sina.transpose(),           \
1292          cosa=cosa.transpose(), zextrap=zval, d1=dx, d2=dy, d3=dz, d4=dt)
1293        var1 = pvar1.transpose()
1294        var2 = pvar2.transpose()
1295    else:
1296        print errormsg
1297        print '  ' + fname + ': rank', len(ua.shape), 'not ready !!'
1298        print '  it only computes 4D [t,z,y,x] rank values'
1299        quit(-1)
1300
1301    return var1, var2, vardims, varvdims
1302
1303def Forcompute_zwindMO(ust, znt, rmol, uas, vas, sina, cosa, zval, dimns, dimvns):
1304    """ Function to compute the wind at a given height following the Monin-Obukhov theory
1305    Forcompute_zwind(ust, znt, rmol, uas, vas, sina, cosa, zval, dimns, dimvns)
1306      [ust]: u* in similarity theory (assuming [[t],y,x]) [ms-1]
1307      [znt]: thermal time-varying roughness length (assuming [[t],y,x]) [m]
1308      [rmol]: inverse of Obukhov length (assuming [[t],y,x]) [m-1]
1309      [uas]= x-component of unstaggered 10 m wind (assuming [[t],y,x]) [ms-1]
1310      [vas]= y-component of unstaggered 10 m wind (assuming [[t],y,x]) [ms-1]
1311      [sina]= local sine of map rotation [1.]
1312      [cosa]= local cosine of map rotation [1.]
1313      [zval]= desired height for winds [m]
1314      [dimns]= list of the name of the dimensions of [uas]
1315      [dimvns]= list of the name of the variables with the values of the
1316        dimensions of [uas]
1317    """
1318    fname = 'Forcompute_zwindMO'
1319
1320    vardims = dimns[:]
1321    varvdims = dimvns[:]
1322
1323    if len(uas.shape) == 3:
1324        var1= np.zeros((uas.shape[0],uas.shape[1],uas.shape[2]), dtype=np.float)
1325        var2= np.zeros((uas.shape[0],uas.shape[1],uas.shape[2]), dtype=np.float)
1326
1327        dx = uas.shape[2]
1328        dy = uas.shape[1]
1329        dt = uas.shape[0]
1330
1331        pvar1, pvar2 = fdin.module_fordiagnostics.compute_zwindmo3d(                 \
1332          ust=ust.transpose(), znt=znt[:].transpose(), rmol=rmol[:].transpose(),     \
1333          uas=uas.transpose(), vas=vas.transpose(), sina=sina.transpose(),           \
1334          cosa=cosa.transpose(), newz=zval, d1=dx, d2=dy, d3=dt)
1335        var1 = pvar1.transpose()
1336        var2 = pvar2.transpose()
1337    else:
1338        print errormsg
1339        print '  ' + fname + ': rank', len(uas.shape), 'not ready !!'
1340        print '  it only computes 3D [t,y,x] rank values'
1341        quit(-1)
1342
1343    return var1, var2, vardims, varvdims
1344
1345def Forcompute_potevap_orPM(rho1, ust, uas, vas, tas, ps, qv1, dimns, dimvns):
1346    """ Function to compute potential evapotranspiration following Penman-Monteith
1347      formulation implemented in ORCHIDEE in src_sechiba/enerbil.f90
1348    Forcompute_potevap_orPM(rho1, uas, vas, tas, ps, qv2, qv1, dimns, dimvns)
1349      [rho1]= air-density at the first layer (assuming [[t],y,m]) [kgm-3]
1350      [ust]= u* in similarity theory (assuming [[t],y,x]) [ms-1]
1351      [uas]= x-component of unstaggered 10 m wind (assuming [[t],y,x]) [ms-1]
1352      [vas]= y-component of unstaggered 10 m wind (assuming [[t],y,x]) [ms-1]
1353      [tas]= 2m air temperature [K]
1354      [ps]= surface pressure [Pa]
1355      [qv1]= mixing ratio at the first atmospheric layer [kgkg-1]
1356      [dimns]= list of the name of the dimensions of [uas]
1357      [dimvns]= list of the name of the variables with the values of the
1358        dimensions of [uas]
1359    """
1360    fname = 'Forcompute_potevap_orPM'
1361
1362    vardims = dimns[:]
1363    varvdims = dimvns[:]
1364
1365    if len(uas.shape) == 3:
1366        var1= np.zeros((uas.shape[0],uas.shape[1],uas.shape[2]), dtype=np.float)
1367        var2= np.zeros((uas.shape[0],uas.shape[1],uas.shape[2]), dtype=np.float)
1368
1369        dx = uas.shape[2]
1370        dy = uas.shape[1]
1371        dt = uas.shape[0]
1372
1373        pvar = fdin.module_fordiagnostics.compute_potevap_orpm3d(                    \
1374          rho1=rho1.transpose(), ust=ust.transpose(), uas=uas.transpose(),           \
1375          vas=vas.transpose(), tas=tas.transpose(), ps=ps.transpose(),               \
1376          qv1=qv1.transpose(), d1=dx, d2=dy, d3=dt)
1377        var = pvar.transpose()
1378    else:
1379        print errormsg
1380        print '  ' + fname + ': rank', len(uas.shape), 'not ready !!'
1381        print '  it only computes 3D [t,y,x] rank values'
1382        quit(-1)
1383
1384    return var, vardims, varvdims
1385
1386def Forcompute_fog_K84(qcloud, qice, dimns, dimvns):
1387    """ Function to compute fog and visibility following Kunkel, (1984)
1388    Forcompute_fog_K84(qcloud, qice, dimns, dimvns)
1389      [qcloud]= cloud mixing ratio [kgk-1]
1390      [qice]= ice mixing ratio [kgk-1]
1391      [dimns]= list of the name of the dimensions of [uas]
1392      [dimvns]= list of the name of the variables with the values of the
1393        dimensions of [qcloud]
1394    """
1395    fname = 'Forcompute_fog_K84'
1396
1397    vardims = dimns[:]
1398    varvdims = dimvns[:]
1399
1400    if len(qcloud.shape) == 4:
1401        var= np.zeros((qcloud.shape[0],qcloud.shape[2],qcloud.shape[3]), dtype=np.float)
1402
1403        dx = qcloud.shape[3]
1404        dy = qcloud.shape[2]
1405        dz = qcloud.shape[1]
1406        dt = qcloud.shape[0]
1407        vardims.pop(1)
1408        varvdims.pop(1)
1409
1410        pvar1, pvar2 = fdin.module_fordiagnostics.compute_fog_k84(                   \
1411          qc=qcloud[:,0,:,:].transpose(), qi=qice[:,0,:,:].transpose(), d1=dx, d2=dy,\
1412          d3=dt)
1413        var1 = pvar1.transpose()
1414        var2 = pvar2.transpose()
1415    else:
1416        print errormsg
1417        print '  ' + fname + ': rank', len(qcloud.shape), 'not ready !!'
1418        print '  it only computes 4D [t,z,y,x] rank values'
1419        quit(-1)
1420
1421    return var1, var2, vardims, varvdims
1422
1423def Forcompute_fog_RUC(qvapor, temp, pres, dimns, dimvns):
1424    """ Function to compute fog and visibility following RUC method Smirnova, (2000)
1425    Forcompute_fog_RUC(qcloud, qice, dimns, dimvns)
1426      [qvapor]= water vapor mixing ratio [kgk-1]
1427      [temp]= temperature [K]
1428      [pres]= pressure [Pa]
1429      [dimns]= list of the name of the dimensions of [uas]
1430      [dimvns]= list of the name of the variables with the values of the
1431        dimensions of [qcloud]
1432    """
1433    fname = 'Forcompute_fog_RUC'
1434
1435    vardims = dimns[:]
1436    varvdims = dimvns[:]
1437
1438    if len(qvapor.shape) == 4:
1439        var= np.zeros((qvapor.shape[0],qvapor.shape[2],qvapor.shape[3]), dtype=np.float)
1440
1441        dx = qvapor.shape[3]
1442        dy = qvapor.shape[2]
1443        dz = qvapor.shape[1]
1444        dt = qvapor.shape[0]
1445        vardims.pop(1)
1446        varvdims.pop(1)
1447
1448        pvar1, pvar2 = fdin.module_fordiagnostics.compute_fog_ruc(                   \
1449          qv=qvapor[:,0,:,:].transpose(), ta=temp[:,0,:,:].transpose(),              \
1450          pres=pres[:,0,:,:].transpose(), d1=dx, d2=dy, d3=dt)
1451        var1 = pvar1.transpose()
1452        var2 = pvar2.transpose()
1453    elif len(qvapor.shape) == 3:
1454        var= np.zeros((qvapor.shape[0],qvapor.shape[1],qvapor.shape[2]), dtype=np.float)
1455
1456        dx = qvapor.shape[2]
1457        dy = qvapor.shape[1]
1458        dt = qvapor.shape[0]
1459
1460        pvar1, pvar2 = fdin.module_fordiagnostics.compute_fog_ruc(                   \
1461          qv=qvapor[:].transpose(), ta=temp[:].transpose(), pres=pres[:].transpose(),\
1462          d1=dx, d2=dy, d3=dt)
1463        var1 = pvar1.transpose()
1464        var2 = pvar2.transpose()
1465    else:
1466        print errormsg
1467        print '  ' + fname + ': rank', len(qcloud.shape), 'not ready !!'
1468        print '  it only computes 4D [t,z,y,x] or 3D [t,z,y,x] rank values'
1469        quit(-1)
1470
1471    return var1, var2, vardims, varvdims
1472
1473def Forcompute_fog_FRAML50(qvapor, temp, pres, dimns, dimvns):
1474    """ Function to compute fog (vis < 1km) and visibility following FRAM-L 50 % prob
1475         Gultepe, and Milbrandt, (2010), J. Appl. Meteor. Climatol.
1476    Forcompute_fog_FRAML50(qvapor, temp, pres, dimns, dimvns)
1477      [qvapor]= vapor mixing ratio [kgk-1]
1478      [temp]= temperature [K]
1479      [pres]= pressure [Pa]
1480      [dimns]= list of the name of the dimensions of [uas]
1481      [dimvns]= list of the name of the variables with the values of the
1482        dimensions of [qvapor]
1483    """
1484    fname = 'Forcompute_fog_FRAML50'
1485
1486    vardims = dimns[:]
1487    varvdims = dimvns[:]
1488
1489    if len(qvapor.shape) == 4:
1490        var= np.zeros((qvapor.shape[0],qvapor.shape[2],qvapor.shape[3]), dtype=np.float)
1491
1492        dx = qvapor.shape[3]
1493        dy = qvapor.shape[2]
1494        dz = qvapor.shape[1]
1495        dt = qvapor.shape[0]
1496        vardims.pop(1)
1497        varvdims.pop(1)
1498
1499        pvar1, pvar2 = fdin.module_fordiagnostics.compute_fog_framl50(               \
1500          qv=qvapor[:,0,:,:].transpose(), ta=temp[:,0,:,:].transpose(),              \
1501          pres=pres[:,0,:,:].transpose(), d1=dx, d2=dy, d3=dt)
1502        var1 = pvar1.transpose()
1503        var2 = pvar2.transpose()
1504    elif len(qvapor.shape) == 3:
1505        var= np.zeros((qvapor.shape[0],qvapor.shape[1],qvapor.shape[2]), dtype=np.float)
1506
1507        dx = qvapor.shape[2]
1508        dy = qvapor.shape[1]
1509        dt = qvapor.shape[0]
1510
1511        pvar1, pvar2 = fdin.module_fordiagnostics.compute_fog_framl50(               \
1512          qv=qvapor[:].transpose(), ta=temp[:].transpose(), pres=pres[:].transpose(),\
1513          d1=dx, d2=dy, d3=dt)
1514        var1 = pvar1.transpose()
1515        var2 = pvar2.transpose()
1516    else:
1517        print errormsg
1518        print '  ' + fname + ': rank', len(qvapor.shape), 'not ready !!'
1519        print '  it only computes 4D [t,z,y,x] or 3D [t,y,x] rank values'
1520        quit(-1)
1521
1522    return var1, var2, vardims, varvdims
1523
1524def Forcompute_range_faces(lon, lat, hgt, dsx, dsy, ds, face, dsfilt, dsnewrng,      \
1525  hvalleyrng, dimns, dimvns):
1526    """ Function to compute faces [uphill, valley, downhill] of sections of a mountain
1527      rage, along a given face
1528    Forcompute_range_faces(lon, lat, hgt, face, dimns, dimvns)
1529      [lon]= longitude values (assuming [y,x]) [degrees east]
1530      [lat]= latitude values (assuming [y,x]) [degrees north]
1531      [hgt]= height values (assuming [y,x]) [m]
1532      [dsx]= distance between grid points along x-axis (assuming [y,x]) [m]
1533      [dsy]= distance between grid points along y-axis (assuming [y,x]) [m]
1534      [ds]= distance between grid points (assuming [y,x]) [m]
1535      face= which face (axis along which produce slices) to use to compute the
1536        faces: WE, SN
1537      dsfilt= distance to filter orography smaller scale of it [m]
1538      dsnewrng= distance to start a new mountain range [m]
1539      hvalleyrng: maximum height of a valley to mark change of range [m]
1540      [dimns]= list of the name of the dimensions of [smois]
1541      [dimvns]= list of the name of the variables with the values of the
1542        dimensions of [smois]
1543    """
1544    fname = 'Forcompute_range_faces'
1545
1546    vardims = dimns[:]
1547    varvdims = dimvns[:]
1548
1549    if len(hgt.shape) == 2:
1550        faces = np.zeros(hgt.shape, dtype=np.float)
1551        dx = hgt.shape[1]
1552        dy = hgt.shape[0]
1553
1554        hgtmaxt, pthgtmaxt, dhgtt, peakst, valleyst, ofacest, ffacest, rngt,         \
1555          rnghgtmaxt, ptrnghgtmaxt =                                                 \
1556          fdin.module_fordiagnostics.compute_range_faces(lon=lon[:].transpose(),     \
1557          lat=lat[:].transpose(), hgt=hgt[:].transpose(), xdist=ds[:].transpose(),   \
1558          ydist=ds[:].transpose(), dist=ds[:].transpose(), face=face, dsfilt=dsfilt, \
1559          dsnewrange=dsnewrng, hvalrng=hvalleyrng, d1=dx, d2=dy)
1560
1561        hgtmax = hgtmaxt.transpose()
1562        pthgtmax = pthgtmaxt.transpose()
1563        dhgt = dhgtt.transpose()
1564        peaks = peakst.transpose()
1565        valleys = valleyst.transpose()
1566        origfaces = ofacest.transpose()
1567        filtfaces = ffacest.transpose()
1568        ranges = rngt.transpose()
1569        rangeshgtmax = rnghgtmaxt.transpose()
1570        ptrangeshgtmax = ptrnghgtmaxt.transpose()
1571
1572    else:
1573        print errormsg
1574        print '  ' + fname + ': rank', len(var.shape), 'not ready !!'
1575        print '  it only computes 2D [y,x] rank values'
1576        quit(-1)
1577
1578    return hgtmax, pthgtmax, dhgt, peaks, valleys, origfaces, filtfaces, vardims,    \
1579      varvdims, ranges, rangeshgtmax, ptrangeshgtmax
1580
1581def Forcompute_front_R04(tas, uas, vas, dxs, dys, dtas, dwss, dimns, dimvns):
1582    """ Function to compute front following Rodrigues et al.(2004), Rev. Bras.
1583          Geofis. 22, 135-151
1584    Forcompute_front_R04(tas, vas, dimns, dimvns)
1585      [tas]= surface air-temperature values (assuming [[t],y,x]) [K]
1586      [uas]= latitudinal wind (assuming [[t],y,x]) [ms-1]
1587      [vas]= meridional wind (assuming [[t],y,x]) [ms-1]
1588      [dxs]= grid spacing between grid points along x-axis (assuming [y,x]) [m]
1589      [dys]= grid spacing between grid points along y-axis (assuming [y,x]) [m]
1590      [dtas]= sensitivity to the thermal temporal increment [K]
1591      [ddwss]= sensitivity to the wind gradient [ms-1m-1]
1592      [dimns]= list of the name of the dimensions of [pa]
1593      [dimvns]= list of the name of the variables with the values of the
1594        dimensions of [pa]
1595    """
1596    fname = 'Forcompute_front_R04'
1597
1598    frontdims = dimns[:]
1599    frontvdims = dimvns[:]
1600
1601    if len(tas.shape) == 3:
1602        front = np.zeros((tas.shape[0],tas.shape[1],tas.shape[2]), dtype=np.float)
1603
1604        dx = tas.shape[2]
1605        dy = tas.shape[1]
1606        dt = tas.shape[0]
1607
1608        pfront, pdt1tas, pdd1wss, pdt2tas =                                          \
1609          fdin.module_fordiagnostics.compute_front_r04d3(tas=tas[:].transpose(),     \
1610          uas=uas[:].transpose(), vas=vas[:].transpose(), ddtas=dtas, ddwss=dwss,    \
1611          dsx=dxs[:].transpose(), dsy=dys[:].transpose(), d1=dx, d2=dy, d3=dt)
1612        front = pfront.transpose()
1613        dt1tas = pdt1tas.transpose()
1614        dd1wss = pdd1wss.transpose()
1615        dt2tas = pdt2tas.transpose()
1616
1617    else:
1618        print errormsg
1619        print '  ' + fname + ': rank', len(tas.shape), 'not ready !!'
1620        print '  it only computes 3D [t,y,x] rank values'
1621        quit(-1)
1622
1623    return front, dt1tas, dd1wss, dt2tas, frontdims, frontvdims
1624
1625def Forcompute_frontogenesis(theta, ua, va, wa, press, dxs, dys, dzs, dts, dimns,    \
1626  dimvns):
1627    """ Function to compute frontogenesis
1628    Forcompute_frontogenesis(ta, ua, va, wa, press, dxs, dys, dzs, dts, dimns, dimvns)
1629      [theta]= potential air-temperature values (assuming [[t],z,y,x]) [K]
1630      [ua]= latitudinal wind (assuming [[t],z,y,x]) [ms-1]
1631      [va]= meridional wind (assuming [[t],z,y,x]) [ms-1]
1632      [wa]= vertical wind (assuming [[t],z,y,x]) [ms-1]
1633      [press]= pressure (assuming [[t],z,y,x]) [Pa]
1634      [dxs]= grid spacing between grid points along x-axis (assuming [y,x]) [m]
1635      [dys]= grid spacing between grid points along y-axis (assuming [y,x]) [m]
1636      [dzs]= grid spacing between grid points along z-axis (assuming [z]) [m]
1637      [dts]= time-step [s]
1638      [dimns]= list of the name of the dimensions of [pa]
1639      [dimvns]= list of the name of the variables with the values of the
1640        dimensions of [pa]
1641    """
1642    fname = 'Forcompute_frontogenesis'
1643
1644    frontdims = dimns[:]
1645    frontvdims = dimvns[:]
1646
1647    if len(theta.shape) == 4:
1648        dx = theta.shape[3]
1649        dy = theta.shape[2]
1650        dz = theta.shape[1]
1651        dt = theta.shape[0]
1652
1653        xdiab = np.zeros((dt,dz,dy,dx), dtype=np.float)
1654        ydiab = np.zeros((dt,dz,dy,dx), dtype=np.float)
1655        zdiab = np.zeros((dt,dz,dy,dx), dtype=np.float)
1656        xdef = np.zeros((dt,dz,dy,dx), dtype=np.float)
1657        ydef = np.zeros((dt,dz,dy,dx), dtype=np.float)
1658        zdef = np.zeros((dt,dz,dy,dx), dtype=np.float)
1659        xtilt = np.zeros((dt,dz,dy,dx), dtype=np.float)
1660        ytilt = np.zeros((dt,dz,dy,dx), dtype=np.float)
1661        zdiv = np.zeros((dt,dz,dy,dx), dtype=np.float)
1662        f = np.zeros((3,dt,dz,dy,dx), dtype=np.float)
1663
1664        thetat = theta.transpose()
1665        uat = ua.transpose()
1666        vat = va.transpose()
1667        wat = wa.transpose()
1668        presst = press.transpose()
1669        dxst = dxs.transpose()
1670        dyst = dys.transpose()
1671
1672        pxdiab, pydiab, pzdiab, pxdef, pydef, pzdef, pxtilt, pytilt, pzdiv, pf =     \
1673          fdin.module_fordiagnostics.compute_frontogenesis(theta=thetat, ua=uat,     \
1674          va=vat, wa=wat, press=presst, dsx=dxst, dsy=dyst, dsz=dzs, dst=dts, d1=dx, \
1675          d2=dy, d3=dz, d4=dt)
1676        xdiab = pxdiab.transpose()
1677        ydiab = pydiab.transpose()
1678        zdiab = pzdiab.transpose()
1679        xdef = pxdef.transpose()
1680        ydef = pydef.transpose()
1681        zdef = pzdef.transpose()
1682        xtilt = pxtilt.transpose()
1683        ytilt = pytilt.transpose()
1684        zdiv = pzdiv.transpose()
1685        f = pf.transpose()
1686    else:
1687        print errormsg
1688        print '  ' + fname + ': rank', len(theta.shape), 'not ready !!'
1689        print '  it only computes 4D [t,z,y,x] rank values'
1690        quit(-1)
1691
1692    return xdiab, ydiab, zdiab, xdef, ydef, zdef, xtilt, ytilt, zdiv, f, frontdims, frontvdims
1693
1694####### ###### ##### #### ### ## # END Fortran diagnostics
1695
1696def compute_OMEGAw(omega, p, t, dimns, dimvns):
1697    """ Function to transform OMEGA [Pas-1] to velocities [ms-1]
1698      tacking: https://www.ncl.ucar.edu/Document/Functions/Contributed/omega_to_w.shtml
1699      [omega] = vertical velocity [in ms-1] (assuming [t],z,y,x)
1700      [p] = pressure in [Pa] (assuming [t],z,y,x)
1701      [t] = temperature in [K] (assuming [t],z,y,x)
1702      [dimns]= list of the name of the dimensions of [q]
1703      [dimvns]= list of the name of the variables with the values of the
1704        dimensions of [q]
1705    """
1706    fname = 'compute_OMEGAw'
1707
1708    rgas = 287.058            # J/(kg-K) => m2/(s2 K)
1709    g    = 9.80665            # m/s2
1710
1711    wdims = dimns[:]
1712    wvdims = dimvns[:]
1713
1714    rho  = p/(rgas*t)         # density => kg/m3
1715    w    = -omega/(rho*g)     
1716
1717    return w, wdims, wvdims
1718
1719def compute_prw(dens, q, dimns, dimvns):
1720    """ Function to compute water vapour path (prw)
1721      [dens] = density [in kgkg-1] (assuming [t],z,y,x)
1722      [q] = mixing ratio in [kgkg-1] (assuming [t],z,y,x)
1723      [dimns]= list of the name of the dimensions of [q]
1724      [dimvns]= list of the name of the variables with the values of the
1725        dimensions of [q]
1726    """
1727    fname = 'compute_prw'
1728
1729    prwdims = dimns[:]
1730    prwvdims = dimvns[:]
1731
1732    if len(q.shape) == 4:
1733        prwdims.pop(1)
1734        prwvdims.pop(1)
1735    else:
1736        prwdims.pop(0)
1737        prwvdims.pop(0)
1738
1739    data1 = dens*q
1740    prw = np.sum(data1, axis=1)
1741
1742    return prw, prwdims, prwvdims
1743
1744def compute_rh(p, t, q, dimns, dimvns):
1745    """ Function to compute relative humidity following 'Tetens' equation (T,P) ...'
1746      [t]= temperature (assuming [[t],z,y,x] in [K])
1747      [p] = pressure field (assuming in [hPa])
1748      [q] = mixing ratio in [kgkg-1]
1749      [dimns]= list of the name of the dimensions of [t]
1750      [dimvns]= list of the name of the variables with the values of the
1751        dimensions of [t]
1752    """
1753    fname = 'compute_rh'
1754
1755    rhdims = dimns[:]
1756    rhvdims = dimvns[:]
1757
1758    data1 = 10.*0.6112*np.exp(17.67*(t-273.16)/(t-29.65))
1759    data2 = 0.622*data1/(0.01*p-(1.-0.622)*data1)
1760
1761    rh = q/data2
1762
1763    return rh, rhdims, rhvdims
1764
1765def compute_td(p, temp, qv, dimns, dimvns):
1766    """ Function to compute the dew point temperature
1767      [p]= pressure [Pa]
1768      [temp]= temperature [C]
1769      [qv]= mixing ratio [kgkg-1]
1770      [dimns]= list of the name of the dimensions of [p]
1771      [dimvns]= list of the name of the variables with the values of the
1772        dimensions of [p]
1773    """
1774    fname = 'compute_td'
1775
1776#    print '    ' + fname + ': computing dew-point temperature from TS as t and Tetens...'
1777# tacking from: http://en.wikipedia.org/wiki/Dew_point
1778    tk = temp
1779    data1 = 10.*0.6112*np.exp(17.67*(tk-273.16)/(tk-29.65))
1780    data2 = 0.622*data1/(0.01*p-(1.-0.622)*data1)
1781
1782    rh = qv/data2
1783               
1784    pa = rh * data1
1785    td = 257.44*np.log(pa/6.1121)/(18.678-np.log(pa/6.1121))
1786
1787    tddims = dimns[:]
1788    tdvdims = dimvns[:]
1789
1790    return td, tddims, tdvdims
1791
1792def var_WRFtime(timewrfv, refdate='19491201000000', tunitsval='minutes'):
1793    """ Function to copmute CFtimes from WRFtime variable
1794      refdate= [YYYYMMDDMIHHSS] format of reference date
1795      tunitsval= CF time units
1796      timewrfv= matrix string values of WRF 'Times' variable
1797    """
1798    fname = 'var_WRFtime'
1799
1800    yrref=refdate[0:4]
1801    monref=refdate[4:6]
1802    dayref=refdate[6:8]
1803    horref=refdate[8:10]
1804    minref=refdate[10:12]
1805    secref=refdate[12:14]
1806
1807    refdateS = yrref + '-' + monref + '-' + dayref + ' ' + horref + ':' + minref +   \
1808      ':' + secref
1809
1810    dt = timewrfv.shape[0]
1811    WRFtime = np.zeros((dt), dtype=np.float)
1812
1813    for it in range(dt):
1814        wrfdates = gen.datetimeStr_conversion(timewrfv[it,:],'WRFdatetime', 'matYmdHMS')
1815        WRFtime[it] = gen.realdatetime1_CFcompilant(wrfdates, refdate, tunitsval)
1816
1817    tunits = tunitsval + ' since ' + refdateS
1818
1819    return WRFtime, tunits
1820
1821def turbulence_var(varv, dimvn, dimn):
1822    """ Function to compute the Taylor's decomposition turbulence term from a a given variable
1823      x*=<x^2>_t-(<X>_t)^2
1824    turbulence_var(varv,dimn)
1825      varv= values of the variable
1826      dimvn= names of the dimension of the variable
1827      dimn= names of the dimensions (as a dictionary with 'X', 'Y', 'Z', 'T')
1828    >>> turbulence_var(np.arange((27)).reshape(3,3,3),['time','y','x'],{'T':'time', 'Y':'y', 'X':'x'})
1829    [[ 54.  54.  54.]
1830     [ 54.  54.  54.]
1831     [ 54.  54.  54.]]
1832    """
1833    fname = 'turbulence_varv'
1834
1835    timedimid = dimvn.index(dimn['T'])
1836
1837    varv2 = varv*varv
1838
1839    vartmean = np.mean(varv, axis=timedimid)
1840    var2tmean = np.mean(varv2, axis=timedimid)
1841
1842    varvturb = var2tmean - (vartmean*vartmean)
1843
1844    return varvturb
1845
1846def compute_turbulence(v, dimns, dimvns):
1847    """ Function to compute the rubulence term of the Taylor's decomposition ...'
1848      x*=<x^2>_t-(<X>_t)^2
1849      [v]= variable (assuming [[t],z,y,x])
1850      [dimns]= list of the name of the dimensions of [v]
1851      [dimvns]= list of the name of the variables with the values of the
1852        dimensions of [v]
1853    """
1854    fname = 'compute_turbulence'
1855
1856    turbdims = dimns[:]
1857    turbvdims = dimvns[:]
1858
1859    turbdims.pop(0)
1860    turbvdims.pop(0)
1861
1862    v2 = v*v
1863
1864    vartmean = np.mean(v, axis=0)
1865    var2tmean = np.mean(v2, axis=0)
1866
1867    turb = var2tmean - (vartmean*vartmean)
1868
1869    return turb, turbdims, turbvdims
1870
1871def compute_wd(u, v, dimns, dimvns):
1872    """ Function to compute the wind direction
1873      [u]= W-E wind direction [ms-1, knot, ...]
1874      [v]= N-S wind direction [ms-1, knot, ...]
1875      [dimns]= list of the name of the dimensions of [u]
1876      [dimvns]= list of the name of the variables with the values of the
1877        dimensions of [u]
1878    """
1879    fname = 'compute_wds'
1880
1881#    print '    ' + fname + ': computing wind direction as ATAN2(v,u) ...'
1882    theta = np.arctan2(v,u)
1883    theta = np.where(theta < 0., theta + 2.*np.pi, theta)
1884
1885    var = 360.*theta/(2.*np.pi)
1886
1887    vardims = dimns[:]
1888    varvdims = dimvns[:]
1889
1890    return var, vardims, varvdims
1891
1892def compute_wds(u, v, dimns, dimvns):
1893    """ Function to compute the wind direction
1894      [u]= W-E wind direction [ms-1, knot, ...]
1895      [v]= N-S wind direction [ms-1, knot, ...]
1896      [dimns]= list of the name of the dimensions of [u]
1897      [dimvns]= list of the name of the variables with the values of the
1898        dimensions of [u]
1899    """
1900    fname = 'compute_wds'
1901
1902#    print '    ' + fname + ': computing wind direction as ATAN2(v,u) ...'
1903    theta = np.arctan2(v,u)
1904    theta = np.where(theta < 0., theta + 2.*np.pi, theta)
1905
1906    wds = 360.*theta/(2.*np.pi)
1907
1908    wdsdims = dimns[:]
1909    wdsvdims = dimvns[:]
1910
1911    return wds, wdsdims, wdsvdims
1912
1913def compute_wss(u, v, dimns, dimvns):
1914    """ Function to compute the wind speed
1915      [u]= W-E wind direction [ms-1, knot, ...]
1916      [v]= N-S wind direction [ms-1, knot, ...]
1917      [dimns]= list of the name of the dimensions of [u]
1918      [dimvns]= list of the name of the variables with the values of the
1919        dimensions of [u]
1920    """
1921    fname = 'compute_wss'
1922
1923#    print '    ' + fname + ': computing wind speed as SQRT(v**2 + u**2) ...'
1924    wss = np.sqrt(u*u + v*v)
1925
1926    wssdims = dimns[:]
1927    wssvdims = dimvns[:]
1928
1929    return wss, wssdims, wssvdims
1930
1931def timeunits_seconds(dtu):
1932    """ Function to transform a time units to seconds
1933    timeunits_seconds(timeuv)
1934      [dtu]= time units value to transform in seconds
1935    """
1936    fname='timunits_seconds'
1937
1938    if dtu == 'years':
1939        times = 365.*24.*3600.
1940    elif dtu == 'weeks':
1941        times = 7.*24.*3600.
1942    elif dtu == 'days':
1943        times = 24.*3600.
1944    elif dtu == 'hours':
1945        times = 3600.
1946    elif dtu == 'minutes':
1947        times = 60.
1948    elif dtu == 'seconds':
1949        times = 1.
1950    elif dtu == 'miliseconds':
1951        times = 1./1000.
1952    else:
1953        print errormsg
1954        print '  ' + fname  + ": time units '" + dtu + "' not ready !!"
1955        quit(-1)
1956
1957    return times
1958
1959def compute_WRFhur(t, p, qv, dimns, dimvns):
1960    """ Function to compute WRF relative humidity following Teten's equation
1961      t= orginal WRF temperature
1962      p= original WRF pressure (P + PB)
1963      formula:
1964          temp = theta*(p/p0)**(R/Cp)
1965
1966    """
1967    fname = 'compute_WRFtd'
1968
1969    tk = (t+300.)*(p/fdef.module_definitions.p0ref)**(fdef.module_definitions.rcp)
1970    data1 = 10.*0.6112*np.exp(17.67*(tk-273.16)/(tk-29.65))
1971    data2 = 0.622*data1/(0.01*p-(1.-0.622)*data1)
1972
1973    rh = qv/data2
1974               
1975    dnamesvar = ['Time','bottom_top','south_north','west_east']
1976    dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dimns,dimvns)
1977
1978    return rh, dnamesvar, dvnamesvar
1979
1980def compute_WRFua(u, v, sina, cosa, dimns, dimvns):
1981    """ Function to compute geographical rotated WRF 3D winds
1982      u= orginal WRF x-wind
1983      v= orginal WRF y-wind
1984      sina= original WRF local sinus of map rotation
1985      cosa= original WRF local cosinus of map rotation
1986      formula:
1987        ua = u*cosa-va*sina
1988        va = u*sina+va*cosa
1989    """
1990    fname = 'compute_WRFua'
1991
1992    var0 = u
1993    var1 = v
1994    var2 = sina
1995    var3 = cosa
1996
1997    # un-staggering variables
1998    unstgdims = [var0.shape[0], var0.shape[1], var0.shape[2], var0.shape[3]-1]
1999    ua = np.zeros(tuple(unstgdims), dtype=np.float)
2000    unstgvar0 = np.zeros(tuple(unstgdims), dtype=np.float)
2001    unstgvar1 = np.zeros(tuple(unstgdims), dtype=np.float)
2002    unstgvar0 = 0.5*(var0[:,:,:,0:var0.shape[3]-1] + var0[:,:,:,1:var0.shape[3]])
2003    unstgvar1 = 0.5*(var1[:,:,0:var1.shape[2]-1,:] + var1[:,:,1:var1.shape[2],:])
2004
2005    for iz in range(var0.shape[1]):
2006        ua[:,iz,:,:] = unstgvar0[:,iz,:,:]*var3 - unstgvar1[:,iz,:,:]*var2
2007
2008    dnamesvar = ['Time','bottom_top','south_north','west_east']
2009    dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dimns,dimvns)
2010
2011    return ua, dnamesvar, dvnamesvar
2012
2013def compute_WRFva(u, v, sina, cosa, dimns, dimvns):
2014    """ Function to compute geographical rotated WRF 3D winds
2015      u= orginal WRF x-wind
2016      v= orginal WRF y-wind
2017      sina= original WRF local sinus of map rotation
2018      cosa= original WRF local cosinus of map rotation
2019      formula:
2020        ua = u*cosa-va*sina
2021        va = u*sina+va*cosa
2022    """
2023    fname = 'compute_WRFva'
2024
2025    var0 = u
2026    var1 = v
2027    var2 = sina
2028    var3 = cosa
2029
2030    # un-staggering variables
2031    unstgdims = [var0.shape[0], var0.shape[1], var0.shape[2], var0.shape[3]-1]
2032    va = np.zeros(tuple(unstgdims), dtype=np.float)
2033    unstgvar0 = np.zeros(tuple(unstgdims), dtype=np.float)
2034    unstgvar1 = np.zeros(tuple(unstgdims), dtype=np.float)
2035    unstgvar0 = 0.5*(var0[:,:,:,0:var0.shape[3]-1] + var0[:,:,:,1:var0.shape[3]])
2036    unstgvar1 = 0.5*(var1[:,:,0:var1.shape[2]-1,:] + var1[:,:,1:var1.shape[2],:])
2037
2038    for iz in range(var0.shape[1]):
2039        va[:,iz,:,:] = unstgvar0[:,iz,:,:]*var2 + unstgvar1[:,iz,:,:]*var3
2040
2041    dnamesvar = ['Time','bottom_top','south_north','west_east']
2042    dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dimns,dimvns)
2043
2044    return va, dnamesvar, dvnamesvar
2045
2046def compute_WRFuava(u, v, sina, cosa, dimns, dimvns):
2047    """ Function to compute geographical rotated WRF 3D winds
2048      u= orginal WRF x-wind
2049      v= orginal WRF y-wind
2050      sina= original WRF local sinus of map rotation
2051      cosa= original WRF local cosinus of map rotation
2052      formula:
2053        ua = u*cosa-va*sina
2054        va = u*sina+va*cosa
2055    """
2056    fname = 'compute_WRFuava'
2057
2058    var0 = u
2059    var1 = v
2060    var2 = sina
2061    var3 = cosa
2062
2063    # un-staggering variables
2064    unstgdims = [var0.shape[0], var0.shape[1], var0.shape[2], var0.shape[3]-1]
2065    ua = np.zeros(tuple(unstgdims), dtype=np.float)
2066    va = np.zeros(tuple(unstgdims), dtype=np.float)
2067    unstgvar0 = np.zeros(tuple(unstgdims), dtype=np.float)
2068    unstgvar1 = np.zeros(tuple(unstgdims), dtype=np.float)
2069    unstgvar0 = 0.5*(var0[:,:,:,0:var0.shape[3]-1] + var0[:,:,:,1:var0.shape[3]])
2070    unstgvar1 = 0.5*(var1[:,:,0:var1.shape[2]-1,:] + var1[:,:,1:var1.shape[2],:])
2071
2072    for iz in range(var0.shape[1]):
2073        ua[:,iz,:,:] = unstgvar0[:,iz,:,:]*var3 - unstgvar1[:,iz,:,:]*var2
2074        va[:,iz,:,:] = unstgvar0[:,iz,:,:]*var2 + unstgvar1[:,iz,:,:]*var3
2075
2076    dnamesvar = ['Time','bottom_top','south_north','west_east']
2077    dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dimns,dimvns)
2078
2079    return ua, va, dnamesvar, dvnamesvar
2080
2081def compute_WRFuas(u10, v10, sina, cosa, dimns, dimvns):
2082    """ Function to compute geographical rotated WRF 2-meter x-wind
2083      u10= orginal WRF 10m x-wind
2084      v10= orginal WRF 10m y-wind
2085      sina= original WRF local sinus of map rotation
2086      cosa= original WRF local cosinus of map rotation
2087      formula:
2088        uas = u10*cosa-va10*sina
2089        vas = u10*sina+va10*cosa
2090    """
2091    fname = 'compute_WRFuas'
2092
2093    var0 = u10
2094    var1 = v10
2095    var2 = sina
2096    var3 = cosa
2097
2098    uas = np.zeros(var0.shape, dtype=np.float)
2099    vas = np.zeros(var0.shape, dtype=np.float)
2100
2101    uas = var0*var3 - var1*var2
2102
2103    dnamesvar = ['Time','south_north','west_east']
2104    dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dimns,dimvns)
2105
2106    return uas, dnamesvar, dvnamesvar
2107
2108def compute_WRFvas(u10, v10, sina, cosa, dimns, dimvns):
2109    """ Function to compute geographical rotated WRF 2-meter y-wind
2110      u10= orginal WRF 10m x-wind
2111      v10= orginal WRF 10m y-wind
2112      sina= original WRF local sinus of map rotation
2113      cosa= original WRF local cosinus of map rotation
2114      formula:
2115        uas = u10*cosa-va10*sina
2116        vas = u10*sina+va10*cosa
2117    """
2118    fname = 'compute_WRFvas'
2119
2120    var0 = u10
2121    var1 = v10
2122    var2 = sina
2123    var3 = cosa
2124
2125    uas = np.zeros(var0.shape, dtype=np.float)
2126    vas = np.zeros(var0.shape, dtype=np.float)
2127
2128    vas = var0*var2 + var1*var3
2129
2130    dnamesvar = ['Time','south_north','west_east']
2131    dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dimns,dimvns)
2132
2133    return vas, dnamesvar, dvnamesvar
2134
2135def compute_WRFuasvas(u10, v10, sina, cosa, dimns, dimvns):
2136    """ Function to compute geographical rotated WRF 2-meter winds
2137      u10= orginal WRF 10m x-wind
2138      v10= orginal WRF 10m y-wind
2139      sina= original WRF local sinus of map rotation
2140      cosa= original WRF local cosinus of map rotation
2141      formula:
2142        uas = u10*cosa-va10*sina
2143        vas = u10*sina+va10*cosa
2144    """
2145    fname = 'compute_WRFuasvas'
2146
2147    var0 = u10
2148    var1 = v10
2149    var2 = sina
2150    var3 = cosa
2151
2152    uas = np.zeros(var0.shape, dtype=np.float)
2153    vas = np.zeros(var0.shape, dtype=np.float)
2154
2155    uas = var0*var3 - var1*var2
2156    vas = var0*var2 + var1*var3
2157
2158    dnamesvar = ['Time','south_north','west_east']
2159    dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dimns,dimvns)
2160
2161    return uas, vas, dnamesvar, dvnamesvar
2162
2163def compute_WRFta(t, p, dimns, dimvns):
2164    """ Function to compute WRF air temperature
2165      t= orginal WRF temperature
2166      p= original WRF pressure (P + PB)
2167      formula:
2168          temp = theta*(p/p0)**(R/Cp)
2169
2170    """
2171    fname = 'compute_WRFta'
2172
2173    ta = (t+300.)*(p/fdef.module_definitions.p0ref)**(fdef.module_definitions.rcp)
2174
2175    dnamesvar = ['Time','bottom_top','south_north','west_east']
2176    dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dimns,dimvns)
2177
2178    return ta, dnamesvar, dvnamesvar
2179
2180def compute_WRFtd(t, p, qv, dimns, dimvns):
2181    """ Function to compute WRF dew-point air temperature
2182      t= orginal WRF temperature
2183      p= original WRF pressure (P + PB)
2184      formula:
2185          temp = theta*(p/p0)**(R/Cp)
2186
2187    """
2188    fname = 'compute_WRFtd'
2189
2190    tk = (t+300.)*(p/fdef.module_definitions.p0ref)**(fdef.module_definitions.rcp)
2191    data1 = 10.*0.6112*np.exp(17.67*(tk-273.16)/(tk-29.65))
2192    data2 = 0.622*data1/(0.01*p-(1.-0.622)*data1)
2193
2194    rh = qv/data2
2195               
2196    pa = rh * data1
2197    td = 257.44*np.log(pa/6.1121)/(18.678-np.log(pa/6.1121))
2198
2199    dnamesvar = ['Time','bottom_top','south_north','west_east']
2200    dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dimns,dimvns)
2201
2202    return td, dnamesvar, dvnamesvar
2203
2204def compute_WRFwd(u, v, sina, cosa, dimns, dimvns):
2205    """ Function to compute the wind direction
2206      u= W-E wind direction [ms-1]
2207      v= N-S wind direction [ms-1]
2208      sina= original WRF local sinus of map rotation
2209      cosa= original WRF local cosinus of map rotation
2210    """
2211    fname = 'compute_WRFwd'
2212    var0 = u
2213    var1 = v
2214    var2 = sina
2215    var3 = cosa
2216
2217    # un-staggering variables
2218    unstgdims = [var0.shape[0], var0.shape[1], var0.shape[2], var0.shape[3]-1]
2219    ua = np.zeros(tuple(unstgdims), dtype=np.float)
2220    va = np.zeros(tuple(unstgdims), dtype=np.float)
2221    unstgvar0 = np.zeros(tuple(unstgdims), dtype=np.float)
2222    unstgvar1 = np.zeros(tuple(unstgdims), dtype=np.float)
2223    unstgvar0 = 0.5*(var0[:,:,:,0:var0.shape[3]-1] + var0[:,:,:,1:var0.shape[3]])
2224    unstgvar1 = 0.5*(var1[:,:,0:var1.shape[2]-1,:] + var1[:,:,1:var1.shape[2],:])
2225
2226    for iz in range(var0.shape[1]):
2227        ua[:,iz,:,:] = unstgvar0[:,iz,:,:]*var3 - unstgvar1[:,iz,:,:]*var2
2228        va[:,iz,:,:] = unstgvar0[:,iz,:,:]*var2 + unstgvar1[:,iz,:,:]*var3
2229
2230    theta = np.arctan2(va,ua)
2231    theta = np.where(theta < 0., theta + 2.*np.pi, theta)
2232
2233    wd = 360.*theta/(2.*np.pi)
2234
2235    dnamesvar = ['Time','bottom_top','south_north','west_east']
2236    dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dimns,dimvns)
2237
2238    return wd
2239
2240####### Variables (as they arrive without dimensions staff)
2241
2242def var_hur(p, t, q):
2243    """ Function to compute relative humidity following 'August - Roche - Magnus' formula
2244      [t]= temperature (assuming [[t],z,y,x] in [K])
2245      [p] = pressure field (assuming in [Pa])
2246      [q] = mixing ratio in [kgkg-1]
2247      ref.: M. G. Lawrence, BAMS, 2005, 225
2248    >>> print var_rh(101300., 290., 3.)
2249    0.250250256174
2250    """
2251    fname = 'var_hur'
2252
2253    # Enthalpy of vaporization [Jkg-1]
2254    L = 2.453*10.**6
2255    # Gas constant for water vapor [JK-1Kg-1]
2256    Rv = 461.5 
2257
2258    # Computing saturated pressure
2259    #es = 10.*0.6112*np.exp(17.67*(t-273.16)/(t-29.65))
2260    #es = 6.11*np.exp(L/Rv*(1.-273./t)/273.)
2261
2262    # August - Roche - Magnus formula
2263    es = 6.1094*np.exp(17.625*(t-273.15)/((t-273.15)+243.04))
2264
2265    # Saturated mixing ratio [g/kg]
2266    ws = 0.622*es/(0.01*p-es)
2267
2268    hur = q/(ws*1000.)
2269
2270    #print 'q:', q[5,5,5,5], 't:', t[5,5,5,5], 'p:', p[5,5,5,5]
2271    #print 'es:', es[5,5,5,5], 'ws:', ws[5,5,5,5], 'hur:', hur[5,5,5,5]
2272
2273    return hur
2274
2275def var_hur_Uhus(p, t, hus):
2276    """ Function to compute relative humidity following 'August - Roche - Magnus' formula using hus
2277      [t]= temperature (assuming [[t],z,y,x] in [K])
2278      [p] = pressure field (assuming in [Pa])
2279      [hus] = specific humidty [1]
2280      ref.: M. G. Lawrence, BAMS, 2005, 225
2281    >>> print var_rh(101300., 290., 3.)
2282    0.250250256174
2283    """
2284    fname = 'var_hur_Uhus'
2285
2286    # Enthalpy of vaporization [Jkg-1]
2287    L = 2.453*10.**6
2288    # Gas constant for water vapor [JK-1Kg-1]
2289    Rv = 461.5 
2290
2291    # Computing saturated pressure
2292    #es = 10.*0.6112*np.exp(17.67*(t-273.16)/(t-29.65))
2293    #es = 6.11*np.exp(L/Rv*(1.-273./t)/273.)
2294
2295    # August - Roche - Magnus formula
2296    es = 6.1094*np.exp(17.625*(t-273.15)/((t-273.15)+243.04))
2297
2298    # Saturated mixing ratio [g/kg]
2299    ws = 0.622*es/(0.01*p-es)
2300
2301    # Mixing ratio
2302    q = hus/(1.+hus)
2303
2304    hur = q/ws
2305
2306    #print 'q:', q[5,5,5,5], 't:', t[5,5,5,5], 'p:', p[5,5,5,5]
2307    #print 'es:', es[5,5,5,5], 'ws:', ws[5,5,5,5], 'hur:', hur[5,5,5,5]
2308
2309    return hur
2310
2311def var_hur_tas_tds(tas, tds, dimns, dimvns):
2312    """ Function to compute hur relative humidity from tas and tds
2313      tas= surface temperature [K]
2314      tds= dew point temperature [K]
2315      Magnus formula with D. Bolton, 1980, Mon. Wea. Rev. values:
2316            gamma = log(hur/100) + b*tas/(c+tas)
2317            tdps = c*gamma/(b-gamma)
2318         hur = 100*expr[b(tdps/(c+tdps)-tas/(c+tas))]
2319
2320    """
2321    fname = 'compute_hur_tas_tds'
2322
2323    dnamesvar = dimns
2324    dvnamesvar = dimvns
2325
2326    tasC = tas - fdef.module_definitions.svpt0
2327    tdsC = tds - fdef.module_definitions.svpt0
2328
2329    # Magnus formula with D. Bolton, 1980, Mon. Wea. Rev. values
2330    b = 17.67
2331    c = 243.5
2332
2333    hur = np.exp(b*(tdsC/(c+tdsC)-tasC/(c+tasC)))
2334               
2335    return hur, dnamesvar, dvnamesvar
2336
2337def var_td(t, p, qv):
2338    """ Function to compute dew-point air temperature from temperature and pressure values
2339      t= temperature [K]
2340      p= pressure (Pa)
2341      formula:
2342          temp = theta*(p/p0)**(R/Cp)
2343
2344    """
2345    fname = 'compute_td'
2346
2347    tk = (t)*(p/fdef.module_definitions.p0ref)**(fdef.module_definitions.rcp)
2348    data1 = 10.*0.6112*np.exp(17.67*(tk-273.16)/(tk-29.65))
2349    data2 = 0.622*data1/(0.01*p-(1.-0.622)*data1)
2350
2351    rh = qv/data2
2352               
2353    pa = rh * data1
2354    td = 257.44*np.log(pa/6.1121)/(18.678-np.log(pa/6.1121))
2355
2356    return td
2357
2358def var_td_Uhus(t, p, hus):
2359    """ Function to compute dew-point air temperature from temperature and pressure values using hus
2360      t= temperature [K]
2361      hus= specific humidity [1]
2362      formula:
2363          temp = theta*(p/p0)**(R/Cp)
2364
2365    """
2366    fname = 'compute_td'
2367
2368    tk = (t)*(p/fdef.module_definitions.p0ref)**(fdef.module_definitions.rcp)
2369    data1 = 10.*0.6112*np.exp(17.67*(tk-273.16)/(tk-29.65))
2370    data2 = 0.622*data1/(0.01*p-(1.-0.622)*data1)
2371
2372    qv = hus/(1.+hus)
2373
2374    rh = qv/data2
2375               
2376    pa = rh * data1
2377    td = 257.44*np.log(pa/6.1121)/(18.678-np.log(pa/6.1121))
2378
2379    return td
2380
2381def var_tws_S11(ta0, hur0):
2382    """ Function to compute Wet Bulb temperature using equation after:
2383      Stull, R. (2011), J. Appl. Meteor. Climatol. 50(11):2267-2269,
2384        doi: 10.1175/JAMC-D-11-0143.1
2385      [ta]= temperature (assuming [[t],z,y,x] in [K])
2386      [hur] = relative humidity (assuming in [1])
2387    >>> var_rh_S11(293.15, 0.5)
2388    13.699341969
2389    """
2390    fname = 'var_tws_S11'
2391
2392    ta = ta0 - 273.15
2393    hur = hur0*100.
2394
2395    # Does it has any sense not in surface?
2396    tws = ta*np.arctan(0.151977*np.sqrt(hur+8.313659)) + np.arctan(ta+hur) -         \
2397      np.arctan(hur-1.676331) + 0.00391838*(hur)**(1.5)*np.arctan(0.023101*hur) -    \
2398      4.686035
2399
2400    return tws
2401
2402def var_wd(u, v):
2403    """ Function to compute the wind direction
2404      [u]= W-E wind direction [ms-1, knot, ...]
2405      [v]= N-S wind direction [ms-1, knot, ...]
2406    """
2407    fname = 'var_wd'
2408
2409    theta = np.arctan2(v,u)
2410    theta = np.where(theta < 0., theta + 2.*np.pi, theta)
2411
2412    wd = 360.*theta/(2.*np.pi)
2413
2414    return wd
2415
2416def var_ws(u, v):
2417    """ Function to compute the wind speed
2418      [u]= W-E wind direction [ms-1, knot, ...]
2419      [v]= N-S wind direction [ms-1, knot, ...]
2420    """
2421    fname = 'var_ws'
2422
2423    ws = np.sqrt(u*u + v*v)
2424
2425    return ws
2426
2427class C_diagnostic(object):
2428    """ Class to compute generic variables
2429      Cdiag: name of the diagnostic to compute
2430      ncobj: netcdf object with data
2431      sfcvars: dictionary with CF equivalencies of surface variables inside file
2432      vars3D: dictionary with CF equivalencies of 3D variables inside file
2433      dictdims: dictionary with CF equivalencies of dimensions inside file
2434        self.values = Values of the diagnostic
2435        self.dims = Dimensions of the diagnostic
2436        self.units = units of the diagnostic
2437        self.incvars = list of variables from the input netCDF object
2438    """ 
2439    def __init__(self, Cdiag, ncobj, sfcvars, vars3D, dictdims):
2440        fname = 'C_diagnostic'
2441        self.values = None
2442        self.dims = None
2443        self.incvars = ncobj.variables
2444        self.units = None
2445
2446        if Cdiag == 'hur':
2447            """ Computing relative humidity
2448            """
2449            vn = 'hur'
2450            CF3Dvars = ['ta', 'plev', 'q']
2451            for v3D in CF3Dvars:
2452                if not vars3D.has_key(v3D):
2453                    print gen.errormsg
2454                    print '  ' + fname + ": missing variable '" + v3D +              \
2455                      "' attribution to compute '" + vn + "' !!"
2456                    print '  Equivalence of 3D variables provided _______'
2457                    gen.printing_dictionary(vars3D)
2458                    quit(-1)
2459                if not self.incvars.has_key(vars3D[v3D]):
2460                    print gen.errormsg
2461                    print '  ' + fname + ": missing variable '" + vars3D[v3D] +      \
2462                      "' in input file to compute '" + vn + "' !!"
2463                    print '  available variables:', self.incvars.keys()
2464                    print '  looking for variables _______' 
2465                    gen.printing_dictionary(vars3D)
2466                    quit(-1)
2467
2468            ta = ncobj.variables[vars3D['ta']][:]
2469            p = ncobj.variables[vars3D['plev']][:]
2470            q = ncobj.variables[vars3D['q']][:]
2471
2472            if len(ta.shape) != len(p.shape):
2473                p = gen.fill_Narray(p, ta*0., filldim=[0,2,3])
2474
2475            self.values = var_hur(p, ta, q)
2476            self.dims = [dictdims['time'], dictdims['plev'], dictdims['lat'],        \
2477              dictdims['lon']]
2478            self.units = '1'
2479
2480        if Cdiag == 'hur_Uhus':
2481            """ Computing relative humidity using hus
2482            """
2483            vn = 'hur'
2484            CF3Dvars = ['ta', 'plev', 'hus']
2485            for v3D in CF3Dvars:
2486                if not vars3D.has_key(v3D):
2487                    print gen.errormsg
2488                    print '  ' + fname + ": missing variable '" + v3D +              \
2489                      "' attribution to compute '" + vn + "' !!"
2490                    print '  Equivalence of 3D variables provided _______'
2491                    gen.printing_dictionary(vars3D)
2492                    quit(-1)
2493                if not self.incvars.has_key(vars3D[v3D]):
2494                    print gen.errormsg
2495                    print '  ' + fname + ": missing variable '" + vars3D[v3D] +      \
2496                      "' in input file to compute '" + vn + "' !!"
2497                    print '  available variables:', self.incvars.keys()
2498                    print '  looking for variables _______' 
2499                    gen.printing_dictionary(vars3D)
2500                    quit(-1)
2501
2502            ta = ncobj.variables[vars3D['ta']][:]
2503            p = ncobj.variables[vars3D['plev']][:]
2504            hus = ncobj.variables[vars3D['hus']][:]
2505
2506            if len(ta.shape) != len(p.shape):
2507                p = gen.fill_Narray(p, ta*0., filldim=[0,2,3])
2508
2509            self.values = var_hur_Uhus(p, ta, hus)
2510            self.dims = [dictdims['time'], dictdims['plev'], dictdims['lat'],        \
2511              dictdims['lon']]
2512            self.units = '1'
2513
2514        elif Cdiag == 'td':
2515            """ Computing dew-point temperature
2516            """
2517            vn = 'td'
2518            CF3Dvars = ['ta', 'plev', 'q']
2519            for v3D in CF3Dvars:
2520                if not vars3D.has_key(v3D):
2521                    print gen.errormsg
2522                    print '  ' + fname + ": missing variable '" + v3D +              \
2523                      "' attribution to compute '" + vn + "' !!"
2524                    print '  Equivalence of 3D variables provided _______'
2525                    gen.printing_dictionary(vars3D)
2526                    quit(-1)
2527                if not self.incvars.has_key(vars3D[v3D]):
2528                    print gen.errormsg
2529                    print '  ' + fname + ": missing variable '" + vars3D[v3D] +      \
2530                      "' in input file to compute '" + vn + "' !!"
2531                    print '  available variables:', self.incvars.keys()
2532                    print '  looking for variables _______' 
2533                    gen.printing_dictionary(vars3D)
2534                    quit(-1)
2535
2536            ta = ncobj.variables[vars3D['ta']][:]
2537            p = ncobj.variables[vars3D['plev']][:]
2538            q = ncobj.variables[vars3D['q']][:]
2539
2540            if len(ta.shape) != len(p.shape):
2541                p = gen.fill_Narray(p, ta*0., filldim=[0,2,3])
2542
2543            self.values = var_td(ta, p, q)
2544            self.dims = [dictdims['time'], dictdims['plev'], dictdims['lat'],        \
2545              dictdims['lon']]
2546            self.units = 'K'
2547
2548        elif Cdiag == 'td_Uhus':
2549            """ Computing dew-point temperature
2550            """
2551            vn = 'td'
2552            CF3Dvars = ['ta', 'plev', 'hus']
2553            for v3D in CF3Dvars:
2554                if not vars3D.has_key(v3D):
2555                    print gen.errormsg
2556                    print '  ' + fname + ": missing variable '" + v3D +              \
2557                      "' attribution to compute '" + vn + "' !!"
2558                    print '  Equivalence of 3D variables provided _______'
2559                    gen.printing_dictionary(vars3D)
2560                    quit(-1)
2561                if not self.incvars.has_key(vars3D[v3D]):
2562                    print gen.errormsg
2563                    print '  ' + fname + ": missing variable '" + vars3D[v3D] +      \
2564                      "' in input file to compute '" + vn + "' !!"
2565                    print '  available variables:', self.incvars.keys()
2566                    print '  looking for variables _______' 
2567                    gen.printing_dictionary(vars3D)
2568                    quit(-1)
2569
2570            ta = ncobj.variables[vars3D['ta']][:]
2571            p = ncobj.variables[vars3D['plev']][:]
2572            hus = ncobj.variables[vars3D['hus']][:]
2573
2574            if len(ta.shape) != len(p.shape):
2575                p = gen.fill_Narray(p, ta*0., filldim=[0,2,3])
2576
2577            self.values = var_td_Uhus(ta, p, hus)
2578            self.dims = [dictdims['time'], dictdims['plev'], dictdims['lat'],        \
2579              dictdims['lon']]
2580            self.units = 'K'
2581
2582        elif Cdiag == 'wd':
2583            """ Computing wind direction
2584            """
2585            vn = 'wd'
2586            CF3Dvars = ['ua', 'va']
2587            for v3D in CF3Dvars:
2588                if not vars3D.has_key(v3D):
2589                    print gen.errormsg
2590                    print '  ' + fname + ": missing variable '" + v3D +              \
2591                      "self.' attribution to compute '" + vn + "' !!"
2592                    print '  Equivalence of 3D variables provided _______'
2593                    gen.printing_dictionary(vars3D)
2594                    quit(-1)
2595                if not self.incvars.has_key(vars3D[v3D]):
2596                    print gen.errormsg
2597                    print '  ' + fname + ": missing variable '" + vars3D[v3D] +      \
2598                      "' in input file to compute '" + vn + "' !!"
2599                    print '  available variables:', self.incvars.keys()
2600                    print '  looking for variables _______' 
2601                    gen.printing_dictionary(vars3D)
2602                    quit(-1)
2603   
2604            ua = ncobj.variables[vars3D['ua']][:]
2605            va = ncobj.variables[vars3D['va']][:]
2606   
2607            self.values = var_wd(ua, va)
2608            self.dims = [dictdims['time'], dictdims['plev'], dictdims['lat'],        \
2609              dictdims['lon']]
2610            self.units = 'degree'
2611
2612        elif Cdiag == 'ws':
2613            """ Computing wind speed
2614            """
2615            vn = 'ws'
2616            CF3Dvars = ['ua', 'va']
2617            for v3D in CF3Dvars:
2618                if not vars3D.has_key(v3D):
2619                    print gen.errormsg
2620                    print '  ' + fname + ": missing variable '" + v3D +              \
2621                      "' attribution to compute '" + vn + "' !!"
2622                    print '  Equivalence of 3D variables provided _______'
2623                    gen.printing_dictionary(vars3D)
2624                    quit(-1)
2625                if not self.incvars.has_key(vars3D[v3D]):
2626                    print gen.errormsg
2627                    print '  ' + fname + ": missing variable '" + vars3D[v3D] +      \
2628                      "' in input file to compute '" + vn + "' !!"
2629                    print '  available variables:', self.incvars.keys()
2630                    print '  looking for variables _______' 
2631                    gen.printing_dictionary(vars3D)
2632                    quit(-1)
2633
2634            ua = ncobj.variables[vars3D['ua']][:]
2635            va = ncobj.variables[vars3D['va']][:]
2636
2637            self.values = var_ws(ua, va)
2638            self.dims = [dictdims['time'], dictdims['plev'], dictdims['lat'],        \
2639              dictdims['lon']]
2640            self.units = ncobj.variables[vars3D['ua']].units
2641
2642        else:
2643            print gen.errormsg
2644            print '  ' + fname + ": variable '" + Wdiag + "' not ready !!"
2645            print '  available ones:', Cavailablediags
2646            quit(-1)
2647
2648class W_diagnostic(object):
2649    """ Class to compute WRF diagnostics variables
2650      Wdiag: name of the diagnostic to compute
2651      ncobj: netcdf object with data
2652      sfcvars: dictionary with CF equivalencies of surface variables inside file
2653      vars3D: dictionary with CF equivalencies of 3D variables inside file
2654      indims: list of dimensions inside file
2655      invardims: list of dimension-variables inside file
2656      dictdims: dictionary with CF equivalencies of dimensions inside file
2657        self.values = Values of the diagnostic
2658        self.dims = Dimensions of the diagnostic
2659        self.units = units of the diagnostic
2660        self.incvars = list of variables from the input netCDF object
2661    """   
2662    def __init__(self, Wdiag, ncobj, sfcvars, vars3D, indims, invardims, dictdims):
2663        fname = 'W_diagnostic'
2664
2665        self.values = None
2666        self.dims = None
2667        self.incvars = ncobj.variables
2668        self.units = None
2669
2670        if Wdiag == 'hur':
2671            """ Computing relative humidity
2672            """
2673            vn = 'hur'
2674            CF3Dvars = ['ta', 'hus']
2675            for v3D in CF3Dvars:
2676                if not vars3D.has_key(v3D):
2677                    print gen.errormsg
2678                    print '  ' + fname + ": missing variable '" + v3D +              \
2679                      "' attribution to compute '" + vn + "' !!"
2680                    print '  Equivalence of 3D variables provided _______'
2681                    gen.printing_dictionary(vars3D)
2682                    quit(-1)
2683
2684            ta = ncobj.variables['T'][:]
2685            p = ncobj.variables['P'][:] + ncobj.variables['PB'][:]
2686            hur = ncobj.variables['QVAPOR'][:]
2687   
2688            vals, dims, vdims = compute_WRFhur(ta, p, hur, indims, invardims)
2689            self.values = vals
2690            self.dims = [dictdims['time'], dictdims['plev'], dictdims['lat'],        \
2691              dictdims['lon']]
2692            self.units = '1'
2693
2694        elif Wdiag == 'p':
2695            """ Computing air pressure
2696            """
2697            vn = 'p'
2698
2699            self.values = ncobj.variables['PB'][:] + ncobj.variables['P'][:]
2700            self.dims = [dictdims['time'], dictdims['plev'], dictdims['lat'],        \
2701              dictdims['lon']]
2702            self.units = ncobj.variables['PB'].units
2703
2704        elif Wdiag == 'ta':
2705            """ Computing air temperature
2706            """
2707            vn = 'ta'
2708            CF3Dvars = ['ta']
2709            for v3D in CF3Dvars:
2710                if not vars3D.has_key(v3D):
2711                    print gen.errormsg
2712                    print '  ' + fname + ": missing variable '" + v3D +              \
2713                      "' attribution to compute '" + vn + "' !!"
2714                    print '  Equivalence of 3D variables provided _______'
2715                    gen.printing_dictionary(vars3D)
2716                    quit(-1)
2717
2718            ta = ncobj.variables['T'][:]
2719            p = ncobj.variables['P'][:] + ncobj.variables['PB'][:]
2720   
2721            vals, dims, vdims = compute_WRFta(ta, p, indims, invardims)
2722            self.values = vals
2723            self.dims = [dictdims['time'], dictdims['plev'], dictdims['lat'],        \
2724              dictdims['lon']]
2725            self.units = 'K'
2726
2727        elif Wdiag == 'td':
2728            """ Computing dew-point temperature
2729            """
2730            vn = 'td'
2731            CF3Dvars = ['ta', 'hus']
2732            for v3D in CF3Dvars:
2733                if not vars3D.has_key(v3D):
2734                    print gen.errormsg
2735                    print '  ' + fname + ": missing variable '" + v3D +              \
2736                      "' attribution to compute '" + vn + "' !!"
2737                    print '  Equivalence of 3D variables provided _______'
2738                    gen.printing_dictionary(vars3D)
2739                    quit(-1)
2740
2741            ta = ncobj.variables['T'][:]
2742            p = ncobj.variables['P'][:] + ncobj.variables['PB'][:]
2743            hus = ncobj.variables['QVAPOR'][:]
2744   
2745            vals, dims, vdims = compute_WRFtd(ta, p, hus, indims, invardims)
2746            self.values = vals
2747            self.dims = [dictdims['time'], dictdims['plev'], dictdims['lat'],        \
2748              dictdims['lon']]
2749            self.units = 'K'
2750   
2751        elif Wdiag == 'ua':
2752            """ Computing x-wind
2753            """
2754            vn = 'ua'
2755            CF3Dvars = ['ua', 'va']
2756            for v3D in CF3Dvars:
2757                if not vars3D.has_key(v3D):
2758                    print gen.errormsg
2759                    print '  ' + fname + ": missing variable '" + v3D +              \
2760                      "' attribution to compute '" + vn + "' !!"
2761                    print '  Equivalence of 3D variables provided _______'
2762                    gen.printing_dictionary(vars3D)
2763                    quit(-1)
2764
2765            ua = ncobj.variables['U'][:]
2766            va = ncobj.variables['V'][:]
2767            sina = ncobj.variables['SINALPHA'][:]
2768            cosa = ncobj.variables['COSALPHA'][:]
2769   
2770            vals, dims, vdims = compute_WRFua(ua, va, sina, cosa, indims, invardims)
2771            self.values = vals
2772            self.dims = [dictdims['time'], dictdims['plev'], dictdims['lat'],        \
2773              dictdims['lon']]
2774            self.units = ncobj.variables['U'].units
2775   
2776        elif Wdiag == 'uas':
2777            """ Computing 10m x-wind
2778            """
2779            vn = 'uas'
2780            CFsfcvars = ['uas', 'vas']
2781            for vsf in CFsfcvars:
2782                if not sfcvars.has_key(vsf):
2783                    print gen.errormsg
2784                    print '  ' + fname + ": missing variable '" + vsf +              \
2785                      "' attribution to compute '" + vn + "' !!"
2786                    print '  Equivalence of sfc variables provided _______'
2787                    gen.printing_dictionary(sfcvars)
2788                    quit(-1)
2789   
2790            uas = ncobj.variables['U10'][:]
2791            vas = ncobj.variables['V10'][:]
2792            sina = ncobj.variables['SINALPHA'][:]
2793            cosa = ncobj.variables['COSALPHA'][:]
2794   
2795            vals,dims,vdims = compute_WRFuas(uas, vas, sina, cosa, indims, invardims)
2796            self.values = vals
2797            self.dims = [dictdims['time'], dictdims['plev'], dictdims['lat'],        \
2798              dictdims['lon']]
2799            self.units = ncobj.variables['U10'].units
2800   
2801        elif Wdiag == 'va':
2802            """ Computing y-wind
2803            """
2804            vn = 'ua'
2805            CF3Dvars = ['ua', 'va']
2806            for v3D in CF3Dvars:
2807                if not vars3D.has_key(v3D):
2808                    print gen.errormsg
2809                    print '  ' + fname + ": missing variable '" + v3D +              \
2810                      "' attribution to compute '" + vn + "' !!"
2811                    print '  Equivalence of 3D variables provided _______'
2812                    gen.printing_dictionary(vars3D)
2813                    quit(-1)
2814   
2815            ua = ncobj.variables['U'][:]
2816            va = ncobj.variables['V'][:]
2817            sina = ncobj.variables['SINALPHA'][:]
2818            cosa = ncobj.variables['COSALPHA'][:]
2819   
2820            vals, dims, vdims = compute_WRFva(ua, va, sina, cosa, indims, invardims)
2821            self.values = vals
2822            self.dims = [dictdims['time'], dictdims['plev'], dictdims['lat'],        \
2823              dictdims['lon']]
2824            self.units = ncobj.variables['U'].units
2825   
2826        elif Wdiag == 'vas':
2827            """ Computing 10m y-wind
2828            """
2829            vn = 'uas'
2830            CFsfcvars = ['uas', 'vas']
2831            for vsf in CFsfcvars:
2832                if not sfcvars.has_key(vsf):
2833                    print gen.errormsg
2834                    print '  ' + fname + ": missing variable '" + vsf +              \
2835                      "' attribution to compute '" + vn + "' !!"
2836                    print '  Equivalence of sfc variables provided _______'
2837                    gen.printing_dictionary(sfcvars)
2838                    quit(-1)
2839   
2840            uas = ncobj.variables['U10'][:]
2841            vas = ncobj.variables['V10'][:]
2842            sina = ncobj.variables['SINALPHA'][:]
2843            cosa = ncobj.variables['COSALPHA'][:]
2844   
2845            vals,dims,vdims = compute_WRFvas(uas, vas, sina, cosa, indims, invardims)
2846            self.values = vals
2847            self.dims = [dictdims['time'], dictdims['plev'], dictdims['lat'],        \
2848              dictdims['lon']]
2849            self.units = ncobj.variables['U10'].units
2850
2851        elif Wdiag == 'wd':
2852            """ Computing wind direction
2853            """
2854            vn = 'wd'
2855            CF3Dvars = ['ua', 'va']
2856            for v3D in CF3Dvars:
2857                if not vars3D.has_key(v3D):
2858                    print gen.errormsg
2859                    print '  ' + fname + ": missing variable '" + v3D +              \
2860                      "' attribution to compute '" + vn + "' !!"
2861                    print '  Equivalence of 3D variables provided _______'
2862                    gen.printing_dictionary(vars3D)
2863                    quit(-1)
2864
2865            ua = ncobj.variables['U10'][:]
2866            va = ncobj.variables['V10'][:]
2867            sina = ncobj.variables['SINALPHA'][:]
2868            cosa = ncobj.variables['COSALPHA'][:]
2869   
2870            vals, dims, vdims = compute_WRFwd(ua, va, sina, cosa, indims, invardims)
2871            self.values = vals
2872            self.dims = [dictdims['time'], dictdims['plev'], dictdims['lat'],        \
2873              dictdims['lon']]
2874            self.units = 'degree'
2875
2876        elif Wdiag == 'ws':
2877            """ Computing wind speed
2878            """
2879            vn = 'ws'
2880            CF3Dvars = ['ua', 'va']
2881            for v3D in CF3Dvars:
2882                if not vars3D.has_key(v3D):
2883                    print gen.errormsg
2884                    print '  ' + fname + ": missing variable '" + v3D +              \
2885                      "' attribution to compute '" + vn + "' !!"
2886                    print '  Equivalence of 3D variables provided _______'
2887                    gen.printing_dictionary(vars3D)
2888                    quit(-1)
2889   
2890            ua = ncobj.variables['U10'][:]
2891            va = ncobj.variables['V10'][:]
2892   
2893            self.values = var_ws(ua, va)
2894            self.dims = [dictdims['time'], dictdims['plev'], dictdims['lat'],        \
2895              dictdims['lon']]
2896            self.units = ncobj.variables['U10'].units
2897
2898        elif Wdiag == 'zg':
2899            """ Computing geopotential
2900            """
2901            vn = 'zg'
2902
2903            self.values = ncobj.variables['PHB'][:] + ncobj.variables['PH'][:]
2904            self.dims = [dictdims['time'], dictdims['plev'], dictdims['lat'],        \
2905              dictdims['lon']]
2906            self.units = ncobj.variables['PHB'].units
2907
2908        else:
2909            print gen.errormsg
2910            print '  ' + fname + ": variable '" + Wdiag + "' not ready !!"
2911            print '  available ones:', Wavailablediags
2912            quit(-1)
Note: See TracBrowser for help on using the repository browser.