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

Last change on this file since 2734 was 2682, checked in by lfita, 6 years ago

Adding missing variable documentation in 'frontogenesis'

File size: 101.4 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_psl_ecmwf(ps, hgt, ta1, pa2, unpa1, dimns, dimvns):
1041    """ Function to compute the sea-level pressure following Mats Hamrud and Philippe Courtier [Pa]
1042    Forcompute_psl_ptarget(ps, hgt, ta1, pa2, unpa1, dimns, dimvns)
1043      [ps]= surface pressure values (assuming [[t],y,x]) [Pa]
1044      [hgt]= opography (assuming [y,x]) [m]
1045      [ta1]= air-temperature values at first half-mass level (assuming [[t],y,x]) [K]
1046      [pa2]= pressure values at second full-mass levels (assuming [[t],y,x]) [Pa]
1047      [unpa1]= pressure values at first half-mass levels (assuming [[t],y,x]) [Pa]
1048      [dimns]= list of the name of the dimensions of [pa]
1049      [dimvns]= list of the name of the variables with the values of the
1050        dimensions of [pa]
1051    """
1052    fname = 'Forcompute_psl_ecmwf'
1053
1054    vardims = dimns[:]
1055    varvdims = dimvns[:]
1056
1057    if len(pa2.shape) == 3:
1058        psl = np.zeros((pa2.shape[0],pa2.shape[1],pa2.shape[2]), dtype=np.float)
1059        dx = pa2.shape[2]
1060        dy = pa2.shape[1]
1061        dt = pa2.shape[0]
1062        pslt= fdin.module_fordiagnostics.compute_psl_ecmwf( ps=ps[:].transpose(),    \
1063          hgt=hgt[:].transpose(), t=ta1[:].transpose(), press=pa2[:].transpose(),    \
1064          unpress=unpa1[:].transpose(), d1=dx, d2=dy, d4=dt)
1065        psl = pslt.transpose()
1066    else:
1067        print errormsg
1068        print '  ' + fname + ': rank', len(pa2.shape), 'not ready !!'
1069        print '  it only computes 3D [t,y,x] rank values'
1070        quit(-1)
1071
1072    return psl, vardims, varvdims
1073
1074def Forcompute_psl_ptarget(pa, ps, ta, hgt, qv, target_pressure, dimns, dimvns):
1075    """ Function to compute the sea-level pressure following target_pressure value
1076      found in `p_interp.F'
1077    Forcompute_psl_ptarget(pa, ps, ta, hgt, qv, dimns, dimvns)
1078      [pa]= pressure values (assuming [[t],z,y,x]) [Pa]
1079      [ps]= surface pressure values (assuming [[t],y,x]) [Pa]
1080      [ta]= air-temperature values (assuming [[t],z,y,x]) [K]
1081      [hgt]= opography (assuming [y,x]) [m]
1082      [qv]= water vapour mixing ratio (assuming [[t],z,y,x]) [kgkg-1]
1083      [dimns]= list of the name of the dimensions of [pa]
1084      [dimvns]= list of the name of the variables with the values of the
1085        dimensions of [pa]
1086    """
1087    fname = 'Forcompute_psl_ptarget'
1088
1089    psldims = dimns[:]
1090    pslvdims = dimvns[:]
1091
1092    if len(pa.shape) == 4:
1093        psl = np.zeros((pa.shape[0],pa.shape[2],pa.shape[3]), dtype=np.float)
1094        dx = pa.shape[3]
1095        dy = pa.shape[2]
1096        dz = pa.shape[1]
1097        dt = pa.shape[0]
1098        psldims.pop(1)
1099        pslvdims.pop(1)
1100
1101        pslt= fdin.module_fordiagnostics.compute_psl_ptarget4d2(                     \
1102          press=pa[:].transpose(), ps=ps[:].transpose(), hgt=hgt[:].transpose(),     \
1103          ta=ta[:].transpose(), qv=qv[:].transpose(), ptarget=target_pressure,       \
1104          d1=dx, d2=dy, d3=dz, d4=dt)
1105        psl = pslt.transpose()
1106    else:
1107        print errormsg
1108        print '  ' + fname + ': rank', len(pa.shape), 'not ready !!'
1109        print '  it only computes 4D [t,z,y,x] rank values'
1110        quit(-1)
1111
1112    return psl, psldims, pslvdims
1113
1114def Forcompute_zmla_gen(theta, qratio, zpl, hgt, dimns, dimvns):
1115    """ Function to compute the boundary layer height following a generic method
1116      with Fortran
1117    Forcompute_zmla_gen(theta, qratio, zpl, hgt, zmla, dimns, dimvns)
1118      [theta]= potential air-temperature values (assuming [[t],z,y,x]) [K]
1119      [qratio]= water mixing ratio (assuming [[t],z,y,x]) [kgkg-1]
1120      [zpl]= height from sea level (assuming [[t],z,y,x]) [m]
1121      [hgt]= topographical height (assuming [m]
1122      [zmla]= boundary layer height [m]
1123      [dimns]= list of the name of the dimensions of [theta]
1124      [dimvns]= list of the name of the variables with the values of the
1125        dimensions of [theta]
1126    """
1127    fname = 'Forcompute_zmla_gen'
1128
1129    zmladims = dimns[:]
1130    zmlavdims = dimvns[:]
1131
1132    if len(theta.shape) == 4:
1133        zmla= np.zeros((theta.shape[0],theta.shape[2],theta.shape[3]), dtype=np.float)
1134
1135        dx = theta.shape[3]
1136        dy = theta.shape[2]
1137        dz = theta.shape[1]
1138        dt = theta.shape[0]
1139        zmladims.pop(1)
1140        zmlavdims.pop(1)
1141
1142        pzmla= fdin.module_fordiagnostics.compute_zmla_generic4d(                    \
1143          tpot=theta[:].transpose(), qratio=qratio[:].transpose(),                   \
1144          z=zpl[:].transpose(), hgt=hgt.transpose(), d1=dx, d2=dy, d3=dz, d4=dt)
1145        zmla = pzmla.transpose()
1146
1147    elif len(theta.shape) == 2:
1148        zmla= np.zeros((theta.shape[0], theta.shape[1]), dtype=np.float)
1149
1150        dz = theta.shape[1]
1151        dt = theta.shape[0]
1152        zmladims.pop(1)
1153        zmlavdims.pop(1)
1154
1155        pzmla= fdin.module_fordiagnostics.compute_zmla_generic2d(                    \
1156          tpot=theta[:].transpose(), qratio=qratio[:].transpose(),                   \
1157          z=zpl[:].transpose(), hgt=hgt, d1=dz, d2=dt)
1158        zmla = pzmla.transpose()
1159
1160    else:
1161        print errormsg
1162        print '  ' + fname + ': rank', len(theta.shape), 'not ready !!'
1163        print '  it only computes 4D [t,z,y,x] rank values'
1164        quit(-1)
1165
1166    return zmla, zmladims, zmlavdims
1167
1168def Forcompute_zwind(ua, va, z, uas, vas, sina, cosa, zval, dimns, dimvns):
1169    """ Function to compute the wind at a given height following the power law method
1170    Forcompute_zwind(ua, va, zsl, uas, vas, hgt, sina, cosa, zval, dimns, dimvns)
1171      [ua]= x-component of unstaggered 3D wind (assuming [[t],z,y,x]) [ms-1]
1172      [va]= y-component of unstaggered 3D wind (assuming [[t],z,y,x]) [ms-1]
1173      [z]= height above surface [m]
1174      [uas]= x-component of unstaggered 10 m wind (assuming [[t],z,y,x]) [ms-1]
1175      [vas]= y-component of unstaggered 10 m wind (assuming [[t],z,y,x]) [ms-1]
1176      [sina]= local sine of map rotation [1.]
1177      [cosa]= local cosine of map rotation [1.]
1178      [zval]= desired height for winds [m]
1179      [dimns]= list of the name of the dimensions of [ua]
1180      [dimvns]= list of the name of the variables with the values of the
1181        dimensions of [ua]
1182    """
1183    fname = 'Forcompute_zwind'
1184
1185    vardims = dimns[:]
1186    varvdims = dimvns[:]
1187
1188    if len(ua.shape) == 4:
1189        var1= np.zeros((ua.shape[0],ua.shape[2],ua.shape[3]), dtype=np.float)
1190        var2= np.zeros((ua.shape[0],ua.shape[2],ua.shape[3]), dtype=np.float)
1191
1192        dx = ua.shape[3]
1193        dy = ua.shape[2]
1194        dz = ua.shape[1]
1195        dt = ua.shape[0]
1196        vardims.pop(1)
1197        varvdims.pop(1)
1198
1199        pvar1, pvar2= fdin.module_fordiagnostics.compute_zwind4d(ua=ua.transpose(),  \
1200          va=va[:].transpose(), z=z[:].transpose(), uas=uas.transpose(),             \
1201          vas=vas.transpose(), sina=sina.transpose(), cosa=cosa.transpose(),         \
1202          zextrap=zval, d1=dx, d2=dy, d3=dz, d4=dt)
1203        var1 = pvar1.transpose()
1204        var2 = pvar2.transpose()
1205    else:
1206        print errormsg
1207        print '  ' + fname + ': rank', len(ua.shape), 'not ready !!'
1208        print '  it only computes 4D [t,z,y,x] rank values'
1209        quit(-1)
1210
1211    return var1, var2, vardims, varvdims
1212
1213def Forcompute_zwind_log(ua, va, z, uas, vas, sina, cosa, zval, dimns, dimvns):
1214    """ Function to compute the wind at a given height following the logarithmic 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_log'
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_zwind_log4d(                \
1245          ua=ua.transpose(), va=va[:].transpose(), z=z[:].transpose(),               \
1246          uas=uas.transpose(), vas=vas.transpose(), sina=sina.transpose(),           \
1247          cosa=cosa.transpose(), 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_zwindMO(ust, znt, rmol, uas, vas, sina, cosa, zval, dimns, dimvns):
1259    """ Function to compute the wind at a given height following the Monin-Obukhov theory
1260    Forcompute_zwind(ust, znt, rmol, uas, vas, sina, cosa, zval, dimns, dimvns)
1261      [ust]: u* in similarity theory (assuming [[t],y,x]) [ms-1]
1262      [znt]: thermal time-varying roughness length (assuming [[t],y,x]) [m]
1263      [rmol]: inverse of Obukhov length (assuming [[t],y,x]) [m-1]
1264      [uas]= x-component of unstaggered 10 m wind (assuming [[t],y,x]) [ms-1]
1265      [vas]= y-component of unstaggered 10 m wind (assuming [[t],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 [uas]
1270      [dimvns]= list of the name of the variables with the values of the
1271        dimensions of [uas]
1272    """
1273    fname = 'Forcompute_zwindMO'
1274
1275    vardims = dimns[:]
1276    varvdims = dimvns[:]
1277
1278    if len(uas.shape) == 3:
1279        var1= np.zeros((uas.shape[0],uas.shape[1],uas.shape[2]), dtype=np.float)
1280        var2= np.zeros((uas.shape[0],uas.shape[1],uas.shape[2]), dtype=np.float)
1281
1282        dx = uas.shape[2]
1283        dy = uas.shape[1]
1284        dt = uas.shape[0]
1285
1286        pvar1, pvar2 = fdin.module_fordiagnostics.compute_zwindmo3d(                 \
1287          ust=ust.transpose(), znt=znt[:].transpose(), rmol=rmol[:].transpose(),     \
1288          uas=uas.transpose(), vas=vas.transpose(), sina=sina.transpose(),           \
1289          cosa=cosa.transpose(), newz=zval, d1=dx, d2=dy, d3=dt)
1290        var1 = pvar1.transpose()
1291        var2 = pvar2.transpose()
1292    else:
1293        print errormsg
1294        print '  ' + fname + ': rank', len(uas.shape), 'not ready !!'
1295        print '  it only computes 3D [t,y,x] rank values'
1296        quit(-1)
1297
1298    return var1, var2, vardims, varvdims
1299
1300def Forcompute_potevap_orPM(rho1, ust, uas, vas, tas, ps, qv1, dimns, dimvns):
1301    """ Function to compute potential evapotranspiration following Penman-Monteith
1302      formulation implemented in ORCHIDEE in src_sechiba/enerbil.f90
1303    Forcompute_potevap_orPM(rho1, uas, vas, tas, ps, qv2, qv1, dimns, dimvns)
1304      [rho1]= air-density at the first layer (assuming [[t],y,m]) [kgm-3]
1305      [ust]= u* in similarity theory (assuming [[t],y,x]) [ms-1]
1306      [uas]= x-component of unstaggered 10 m wind (assuming [[t],y,x]) [ms-1]
1307      [vas]= y-component of unstaggered 10 m wind (assuming [[t],y,x]) [ms-1]
1308      [tas]= 2m air temperature [K]
1309      [ps]= surface pressure [Pa]
1310      [qv1]= mixing ratio at the first atmospheric layer [kgkg-1]
1311      [dimns]= list of the name of the dimensions of [uas]
1312      [dimvns]= list of the name of the variables with the values of the
1313        dimensions of [uas]
1314    """
1315    fname = 'Forcompute_potevap_orPM'
1316
1317    vardims = dimns[:]
1318    varvdims = dimvns[:]
1319
1320    if len(uas.shape) == 3:
1321        var1= np.zeros((uas.shape[0],uas.shape[1],uas.shape[2]), dtype=np.float)
1322        var2= np.zeros((uas.shape[0],uas.shape[1],uas.shape[2]), dtype=np.float)
1323
1324        dx = uas.shape[2]
1325        dy = uas.shape[1]
1326        dt = uas.shape[0]
1327
1328        pvar = fdin.module_fordiagnostics.compute_potevap_orpm3d(                    \
1329          rho1=rho1.transpose(), ust=ust.transpose(), uas=uas.transpose(),           \
1330          vas=vas.transpose(), tas=tas.transpose(), ps=ps.transpose(),               \
1331          qv1=qv1.transpose(), d1=dx, d2=dy, d3=dt)
1332        var = pvar.transpose()
1333    else:
1334        print errormsg
1335        print '  ' + fname + ': rank', len(uas.shape), 'not ready !!'
1336        print '  it only computes 3D [t,y,x] rank values'
1337        quit(-1)
1338
1339    return var, vardims, varvdims
1340
1341def Forcompute_fog_K84(qcloud, qice, dimns, dimvns):
1342    """ Function to compute fog and visibility following Kunkel, (1984)
1343    Forcompute_fog_K84(qcloud, qice, dimns, dimvns)
1344      [qcloud]= cloud mixing ratio [kgk-1]
1345      [qice]= ice mixing ratio [kgk-1]
1346      [dimns]= list of the name of the dimensions of [uas]
1347      [dimvns]= list of the name of the variables with the values of the
1348        dimensions of [qcloud]
1349    """
1350    fname = 'Forcompute_fog_K84'
1351
1352    vardims = dimns[:]
1353    varvdims = dimvns[:]
1354
1355    if len(qcloud.shape) == 4:
1356        var= np.zeros((qcloud.shape[0],qcloud.shape[2],qcloud.shape[3]), dtype=np.float)
1357
1358        dx = qcloud.shape[3]
1359        dy = qcloud.shape[2]
1360        dz = qcloud.shape[1]
1361        dt = qcloud.shape[0]
1362        vardims.pop(1)
1363        varvdims.pop(1)
1364
1365        pvar1, pvar2 = fdin.module_fordiagnostics.compute_fog_k84(                   \
1366          qc=qcloud[:,0,:,:].transpose(), qi=qice[:,0,:,:].transpose(), d1=dx, d2=dy,\
1367          d3=dt)
1368        var1 = pvar1.transpose()
1369        var2 = pvar2.transpose()
1370    else:
1371        print errormsg
1372        print '  ' + fname + ': rank', len(qcloud.shape), 'not ready !!'
1373        print '  it only computes 4D [t,z,y,x] rank values'
1374        quit(-1)
1375
1376    return var1, var2, vardims, varvdims
1377
1378def Forcompute_fog_RUC(qvapor, temp, pres, dimns, dimvns):
1379    """ Function to compute fog and visibility following RUC method Smirnova, (2000)
1380    Forcompute_fog_RUC(qcloud, qice, dimns, dimvns)
1381      [qvapor]= water vapor mixing ratio [kgk-1]
1382      [temp]= temperature [K]
1383      [pres]= pressure [Pa]
1384      [dimns]= list of the name of the dimensions of [uas]
1385      [dimvns]= list of the name of the variables with the values of the
1386        dimensions of [qcloud]
1387    """
1388    fname = 'Forcompute_fog_RUC'
1389
1390    vardims = dimns[:]
1391    varvdims = dimvns[:]
1392
1393    if len(qvapor.shape) == 4:
1394        var= np.zeros((qvapor.shape[0],qvapor.shape[2],qvapor.shape[3]), dtype=np.float)
1395
1396        dx = qvapor.shape[3]
1397        dy = qvapor.shape[2]
1398        dz = qvapor.shape[1]
1399        dt = qvapor.shape[0]
1400        vardims.pop(1)
1401        varvdims.pop(1)
1402
1403        pvar1, pvar2 = fdin.module_fordiagnostics.compute_fog_ruc(                   \
1404          qv=qvapor[:,0,:,:].transpose(), ta=temp[:,0,:,:].transpose(),              \
1405          pres=pres[:,0,:,:].transpose(), d1=dx, d2=dy, d3=dt)
1406        var1 = pvar1.transpose()
1407        var2 = pvar2.transpose()
1408    elif len(qvapor.shape) == 3:
1409        var= np.zeros((qvapor.shape[0],qvapor.shape[1],qvapor.shape[2]), dtype=np.float)
1410
1411        dx = qvapor.shape[2]
1412        dy = qvapor.shape[1]
1413        dt = qvapor.shape[0]
1414
1415        pvar1, pvar2 = fdin.module_fordiagnostics.compute_fog_ruc(                   \
1416          qv=qvapor[:].transpose(), ta=temp[:].transpose(), pres=pres[:].transpose(),\
1417          d1=dx, d2=dy, d3=dt)
1418        var1 = pvar1.transpose()
1419        var2 = pvar2.transpose()
1420    else:
1421        print errormsg
1422        print '  ' + fname + ': rank', len(qcloud.shape), 'not ready !!'
1423        print '  it only computes 4D [t,z,y,x] or 3D [t,z,y,x] rank values'
1424        quit(-1)
1425
1426    return var1, var2, vardims, varvdims
1427
1428def Forcompute_fog_FRAML50(qvapor, temp, pres, dimns, dimvns):
1429    """ Function to compute fog (vis < 1km) and visibility following FRAM-L 50 % prob
1430         Gultepe, and Milbrandt, (2010), J. Appl. Meteor. Climatol.
1431    Forcompute_fog_FRAML50(qvapor, temp, pres, dimns, dimvns)
1432      [qvapor]= vapor mixing ratio [kgk-1]
1433      [temp]= temperature [K]
1434      [pres]= pressure [Pa]
1435      [dimns]= list of the name of the dimensions of [uas]
1436      [dimvns]= list of the name of the variables with the values of the
1437        dimensions of [qvapor]
1438    """
1439    fname = 'Forcompute_fog_FRAML50'
1440
1441    vardims = dimns[:]
1442    varvdims = dimvns[:]
1443
1444    if len(qvapor.shape) == 4:
1445        var= np.zeros((qvapor.shape[0],qvapor.shape[2],qvapor.shape[3]), dtype=np.float)
1446
1447        dx = qvapor.shape[3]
1448        dy = qvapor.shape[2]
1449        dz = qvapor.shape[1]
1450        dt = qvapor.shape[0]
1451        vardims.pop(1)
1452        varvdims.pop(1)
1453
1454        pvar1, pvar2 = fdin.module_fordiagnostics.compute_fog_framl50(               \
1455          qv=qvapor[:,0,:,:].transpose(), ta=temp[:,0,:,:].transpose(),              \
1456          pres=pres[:,0,:,:].transpose(), d1=dx, d2=dy, d3=dt)
1457        var1 = pvar1.transpose()
1458        var2 = pvar2.transpose()
1459    elif len(qvapor.shape) == 3:
1460        var= np.zeros((qvapor.shape[0],qvapor.shape[1],qvapor.shape[2]), dtype=np.float)
1461
1462        dx = qvapor.shape[2]
1463        dy = qvapor.shape[1]
1464        dt = qvapor.shape[0]
1465
1466        pvar1, pvar2 = fdin.module_fordiagnostics.compute_fog_framl50(               \
1467          qv=qvapor[:].transpose(), ta=temp[:].transpose(), pres=pres[:].transpose(),\
1468          d1=dx, d2=dy, d3=dt)
1469        var1 = pvar1.transpose()
1470        var2 = pvar2.transpose()
1471    else:
1472        print errormsg
1473        print '  ' + fname + ': rank', len(qvapor.shape), 'not ready !!'
1474        print '  it only computes 4D [t,z,y,x] or 3D [t,y,x] rank values'
1475        quit(-1)
1476
1477    return var1, var2, vardims, varvdims
1478
1479def Forcompute_range_faces(lon, lat, hgt, dsx, dsy, ds, face, dsfilt, dsnewrng,      \
1480  hvalleyrng, dimns, dimvns):
1481    """ Function to compute faces [uphill, valley, downhill] of sections of a mountain
1482      rage, along a given face
1483    Forcompute_range_faces(lon, lat, hgt, face, dimns, dimvns)
1484      [lon]= longitude values (assuming [y,x]) [degrees east]
1485      [lat]= latitude values (assuming [y,x]) [degrees north]
1486      [hgt]= height values (assuming [y,x]) [m]
1487      [dsx]= distance between grid points along x-axis (assuming [y,x]) [m]
1488      [dsy]= distance between grid points along y-axis (assuming [y,x]) [m]
1489      [ds]= distance between grid points (assuming [y,x]) [m]
1490      face= which face (axis along which produce slices) to use to compute the
1491        faces: WE, SN
1492      dsfilt= distance to filter orography smaller scale of it [m]
1493      dsnewrng= distance to start a new mountain range [m]
1494      hvalleyrng: maximum height of a valley to mark change of range [m]
1495      [dimns]= list of the name of the dimensions of [smois]
1496      [dimvns]= list of the name of the variables with the values of the
1497        dimensions of [smois]
1498    """
1499    fname = 'Forcompute_range_faces'
1500
1501    vardims = dimns[:]
1502    varvdims = dimvns[:]
1503
1504    if len(hgt.shape) == 2:
1505        faces = np.zeros(hgt.shape, dtype=np.float)
1506        dx = hgt.shape[1]
1507        dy = hgt.shape[0]
1508
1509        hgtmaxt, pthgtmaxt, dhgtt, peakst, valleyst, ofacest, ffacest, rngt,         \
1510          rnghgtmaxt, ptrnghgtmaxt =                                                 \
1511          fdin.module_fordiagnostics.compute_range_faces(lon=lon[:].transpose(),     \
1512          lat=lat[:].transpose(), hgt=hgt[:].transpose(), xdist=ds[:].transpose(),   \
1513          ydist=ds[:].transpose(), dist=ds[:].transpose(), face=face, dsfilt=dsfilt, \
1514          dsnewrange=dsnewrng, hvalrng=hvalleyrng, d1=dx, d2=dy)
1515
1516        hgtmax = hgtmaxt.transpose()
1517        pthgtmax = pthgtmaxt.transpose()
1518        dhgt = dhgtt.transpose()
1519        peaks = peakst.transpose()
1520        valleys = valleyst.transpose()
1521        origfaces = ofacest.transpose()
1522        filtfaces = ffacest.transpose()
1523        ranges = rngt.transpose()
1524        rangeshgtmax = rnghgtmaxt.transpose()
1525        ptrangeshgtmax = ptrnghgtmaxt.transpose()
1526
1527    else:
1528        print errormsg
1529        print '  ' + fname + ': rank', len(var.shape), 'not ready !!'
1530        print '  it only computes 2D [y,x] rank values'
1531        quit(-1)
1532
1533    return hgtmax, pthgtmax, dhgt, peaks, valleys, origfaces, filtfaces, vardims,    \
1534      varvdims, ranges, rangeshgtmax, ptrangeshgtmax
1535
1536def Forcompute_front_R04(tas, uas, vas, dxs, dys, dtas, dwss, dimns, dimvns):
1537    """ Function to compute front following Rodrigues et al.(2004), Rev. Bras.
1538          Geofis. 22, 135-151
1539    Forcompute_front_R04(tas, vas, dimns, dimvns)
1540      [tas]= surface air-temperature values (assuming [[t],y,x]) [K]
1541      [uas]= latitudinal wind (assuming [[t],y,x]) [ms-1]
1542      [vas]= meridional wind (assuming [[t],y,x]) [ms-1]
1543      [dxs]= grid spacing between grid points along x-axis (assuming [y,x]) [m]
1544      [dys]= grid spacing between grid points along y-axis (assuming [y,x]) [m]
1545      [dtas]= sensitivity to the thermal temporal increment [K]
1546      [ddwss]= sensitivity to the wind gradient [ms-1m-1]
1547      [dimns]= list of the name of the dimensions of [pa]
1548      [dimvns]= list of the name of the variables with the values of the
1549        dimensions of [pa]
1550    """
1551    fname = 'Forcompute_front_R04'
1552
1553    frontdims = dimns[:]
1554    frontvdims = dimvns[:]
1555
1556    if len(tas.shape) == 3:
1557        front = np.zeros((tas.shape[0],tas.shape[1],tas.shape[2]), dtype=np.float)
1558
1559        dx = tas.shape[2]
1560        dy = tas.shape[1]
1561        dt = tas.shape[0]
1562
1563        pfront, pdt1tas, pdd1wss, pdt2tas =                                          \
1564          fdin.module_fordiagnostics.compute_front_r04d3(tas=tas[:].transpose(),     \
1565          uas=uas[:].transpose(), vas=vas[:].transpose(), ddtas=dtas, ddwss=dwss,    \
1566          dsx=dxs[:].transpose(), dsy=dys[:].transpose(), d1=dx, d2=dy, d3=dt)
1567        front = pfront.transpose()
1568        dt1tas = pdt1tas.transpose()
1569        dd1wss = pdd1wss.transpose()
1570        dt2tas = pdt2tas.transpose()
1571
1572    else:
1573        print errormsg
1574        print '  ' + fname + ': rank', len(tas.shape), 'not ready !!'
1575        print '  it only computes 3D [t,y,x] rank values'
1576        quit(-1)
1577
1578    return front, dt1tas, dd1wss, dt2tas, frontdims, frontvdims
1579
1580def Forcompute_frontogenesis(theta, ua, va, wa, press, dxs, dys, dzs, dts, dimns,    \
1581  dimvns):
1582    """ Function to compute frontogenesis
1583    Forcompute_frontogenesis(ta, ua, va, wa, press, dxs, dys, dzs, dts, dimns, dimvns)
1584      [theta]= potential air-temperature values (assuming [[t],z,y,x]) [K]
1585      [ua]= latitudinal wind (assuming [[t],z,y,x]) [ms-1]
1586      [va]= meridional wind (assuming [[t],z,y,x]) [ms-1]
1587      [wa]= vertical wind (assuming [[t],z,y,x]) [ms-1]
1588      [press]= pressure (assuming [[t],z,y,x]) [Pa]
1589      [dxs]= grid spacing between grid points along x-axis (assuming [y,x]) [m]
1590      [dys]= grid spacing between grid points along y-axis (assuming [y,x]) [m]
1591      [dzs]= grid spacing between grid points along z-axis (assuming [z]) [m]
1592      [dts]= time-step [s]
1593      [dimns]= list of the name of the dimensions of [pa]
1594      [dimvns]= list of the name of the variables with the values of the
1595        dimensions of [pa]
1596    """
1597    fname = 'Forcompute_frontogenesis'
1598
1599    frontdims = dimns[:]
1600    frontvdims = dimvns[:]
1601
1602    if len(theta.shape) == 4:
1603        dx = theta.shape[3]
1604        dy = theta.shape[2]
1605        dz = theta.shape[1]
1606        dt = theta.shape[0]
1607
1608        xdiab = np.zeros((dt,dz,dy,dx), dtype=np.float)
1609        ydiab = np.zeros((dt,dz,dy,dx), dtype=np.float)
1610        zdiab = np.zeros((dt,dz,dy,dx), dtype=np.float)
1611        xdef = np.zeros((dt,dz,dy,dx), dtype=np.float)
1612        ydef = np.zeros((dt,dz,dy,dx), dtype=np.float)
1613        zdef = np.zeros((dt,dz,dy,dx), dtype=np.float)
1614        xtilt = np.zeros((dt,dz,dy,dx), dtype=np.float)
1615        ytilt = np.zeros((dt,dz,dy,dx), dtype=np.float)
1616        zdiv = np.zeros((dt,dz,dy,dx), dtype=np.float)
1617        f = np.zeros((3,dt,dz,dy,dx), dtype=np.float)
1618
1619        thetat = theta.transpose()
1620        uat = ua.transpose()
1621        vat = va.transpose()
1622        wat = wa.transpose()
1623        presst = press.transpose()
1624        dxst = dxs.transpose()
1625        dyst = dys.transpose()
1626
1627        pxdiab, pydiab, pzdiab, pxdef, pydef, pzdef, pxtilt, pytilt, pzdiv, pf =     \
1628          fdin.module_fordiagnostics.compute_frontogenesis(theta=thetat, ua=uat,     \
1629          va=vat, wa=wat, press=presst, dsx=dxst, dsy=dyst, dsz=dzs, dst=dts, d1=dx, \
1630          d2=dy, d3=dz, d4=dt)
1631        xdiab = pxdiab.transpose()
1632        ydiab = pydiab.transpose()
1633        zdiab = pzdiab.transpose()
1634        xdef = pxdef.transpose()
1635        ydef = pydef.transpose()
1636        zdef = pzdef.transpose()
1637        xtilt = pxtilt.transpose()
1638        ytilt = pytilt.transpose()
1639        zdiv = pzdiv.transpose()
1640        f = pf.transpose()
1641    else:
1642        print errormsg
1643        print '  ' + fname + ': rank', len(theta.shape), 'not ready !!'
1644        print '  it only computes 4D [t,z,y,x] rank values'
1645        quit(-1)
1646
1647    return xdiab, ydiab, zdiab, xdef, ydef, zdef, xtilt, ytilt, zdiv, f, frontdims, frontvdims
1648
1649####### ###### ##### #### ### ## # END Fortran diagnostics
1650
1651def compute_OMEGAw(omega, p, t, dimns, dimvns):
1652    """ Function to transform OMEGA [Pas-1] to velocities [ms-1]
1653      tacking: https://www.ncl.ucar.edu/Document/Functions/Contributed/omega_to_w.shtml
1654      [omega] = vertical velocity [in ms-1] (assuming [t],z,y,x)
1655      [p] = pressure in [Pa] (assuming [t],z,y,x)
1656      [t] = temperature in [K] (assuming [t],z,y,x)
1657      [dimns]= list of the name of the dimensions of [q]
1658      [dimvns]= list of the name of the variables with the values of the
1659        dimensions of [q]
1660    """
1661    fname = 'compute_OMEGAw'
1662
1663    rgas = 287.058            # J/(kg-K) => m2/(s2 K)
1664    g    = 9.80665            # m/s2
1665
1666    wdims = dimns[:]
1667    wvdims = dimvns[:]
1668
1669    rho  = p/(rgas*t)         # density => kg/m3
1670    w    = -omega/(rho*g)     
1671
1672    return w, wdims, wvdims
1673
1674def compute_prw(dens, q, dimns, dimvns):
1675    """ Function to compute water vapour path (prw)
1676      [dens] = density [in kgkg-1] (assuming [t],z,y,x)
1677      [q] = mixing ratio in [kgkg-1] (assuming [t],z,y,x)
1678      [dimns]= list of the name of the dimensions of [q]
1679      [dimvns]= list of the name of the variables with the values of the
1680        dimensions of [q]
1681    """
1682    fname = 'compute_prw'
1683
1684    prwdims = dimns[:]
1685    prwvdims = dimvns[:]
1686
1687    if len(q.shape) == 4:
1688        prwdims.pop(1)
1689        prwvdims.pop(1)
1690    else:
1691        prwdims.pop(0)
1692        prwvdims.pop(0)
1693
1694    data1 = dens*q
1695    prw = np.sum(data1, axis=1)
1696
1697    return prw, prwdims, prwvdims
1698
1699def compute_rh(p, t, q, dimns, dimvns):
1700    """ Function to compute relative humidity following 'Tetens' equation (T,P) ...'
1701      [t]= temperature (assuming [[t],z,y,x] in [K])
1702      [p] = pressure field (assuming in [hPa])
1703      [q] = mixing ratio in [kgkg-1]
1704      [dimns]= list of the name of the dimensions of [t]
1705      [dimvns]= list of the name of the variables with the values of the
1706        dimensions of [t]
1707    """
1708    fname = 'compute_rh'
1709
1710    rhdims = dimns[:]
1711    rhvdims = dimvns[:]
1712
1713    data1 = 10.*0.6112*np.exp(17.67*(t-273.16)/(t-29.65))
1714    data2 = 0.622*data1/(0.01*p-(1.-0.622)*data1)
1715
1716    rh = q/data2
1717
1718    return rh, rhdims, rhvdims
1719
1720def compute_td(p, temp, qv, dimns, dimvns):
1721    """ Function to compute the dew point temperature
1722      [p]= pressure [Pa]
1723      [temp]= temperature [C]
1724      [qv]= mixing ratio [kgkg-1]
1725      [dimns]= list of the name of the dimensions of [p]
1726      [dimvns]= list of the name of the variables with the values of the
1727        dimensions of [p]
1728    """
1729    fname = 'compute_td'
1730
1731#    print '    ' + fname + ': computing dew-point temperature from TS as t and Tetens...'
1732# tacking from: http://en.wikipedia.org/wiki/Dew_point
1733    tk = temp
1734    data1 = 10.*0.6112*np.exp(17.67*(tk-273.16)/(tk-29.65))
1735    data2 = 0.622*data1/(0.01*p-(1.-0.622)*data1)
1736
1737    rh = qv/data2
1738               
1739    pa = rh * data1
1740    td = 257.44*np.log(pa/6.1121)/(18.678-np.log(pa/6.1121))
1741
1742    tddims = dimns[:]
1743    tdvdims = dimvns[:]
1744
1745    return td, tddims, tdvdims
1746
1747def var_WRFtime(timewrfv, refdate='19491201000000', tunitsval='minutes'):
1748    """ Function to copmute CFtimes from WRFtime variable
1749      refdate= [YYYYMMDDMIHHSS] format of reference date
1750      tunitsval= CF time units
1751      timewrfv= matrix string values of WRF 'Times' variable
1752    """
1753    fname = 'var_WRFtime'
1754
1755    yrref=refdate[0:4]
1756    monref=refdate[4:6]
1757    dayref=refdate[6:8]
1758    horref=refdate[8:10]
1759    minref=refdate[10:12]
1760    secref=refdate[12:14]
1761
1762    refdateS = yrref + '-' + monref + '-' + dayref + ' ' + horref + ':' + minref +   \
1763      ':' + secref
1764
1765    dt = timewrfv.shape[0]
1766    WRFtime = np.zeros((dt), dtype=np.float)
1767
1768    for it in range(dt):
1769        wrfdates = gen.datetimeStr_conversion(timewrfv[it,:],'WRFdatetime', 'matYmdHMS')
1770        WRFtime[it] = gen.realdatetime1_CFcompilant(wrfdates, refdate, tunitsval)
1771
1772    tunits = tunitsval + ' since ' + refdateS
1773
1774    return WRFtime, tunits
1775
1776def turbulence_var(varv, dimvn, dimn):
1777    """ Function to compute the Taylor's decomposition turbulence term from a a given variable
1778      x*=<x^2>_t-(<X>_t)^2
1779    turbulence_var(varv,dimn)
1780      varv= values of the variable
1781      dimvn= names of the dimension of the variable
1782      dimn= names of the dimensions (as a dictionary with 'X', 'Y', 'Z', 'T')
1783    >>> turbulence_var(np.arange((27)).reshape(3,3,3),['time','y','x'],{'T':'time', 'Y':'y', 'X':'x'})
1784    [[ 54.  54.  54.]
1785     [ 54.  54.  54.]
1786     [ 54.  54.  54.]]
1787    """
1788    fname = 'turbulence_varv'
1789
1790    timedimid = dimvn.index(dimn['T'])
1791
1792    varv2 = varv*varv
1793
1794    vartmean = np.mean(varv, axis=timedimid)
1795    var2tmean = np.mean(varv2, axis=timedimid)
1796
1797    varvturb = var2tmean - (vartmean*vartmean)
1798
1799    return varvturb
1800
1801def compute_turbulence(v, dimns, dimvns):
1802    """ Function to compute the rubulence term of the Taylor's decomposition ...'
1803      x*=<x^2>_t-(<X>_t)^2
1804      [v]= variable (assuming [[t],z,y,x])
1805      [dimns]= list of the name of the dimensions of [v]
1806      [dimvns]= list of the name of the variables with the values of the
1807        dimensions of [v]
1808    """
1809    fname = 'compute_turbulence'
1810
1811    turbdims = dimns[:]
1812    turbvdims = dimvns[:]
1813
1814    turbdims.pop(0)
1815    turbvdims.pop(0)
1816
1817    v2 = v*v
1818
1819    vartmean = np.mean(v, axis=0)
1820    var2tmean = np.mean(v2, axis=0)
1821
1822    turb = var2tmean - (vartmean*vartmean)
1823
1824    return turb, turbdims, turbvdims
1825
1826def compute_wd(u, v, dimns, dimvns):
1827    """ Function to compute the wind direction
1828      [u]= W-E wind direction [ms-1, knot, ...]
1829      [v]= N-S wind direction [ms-1, knot, ...]
1830      [dimns]= list of the name of the dimensions of [u]
1831      [dimvns]= list of the name of the variables with the values of the
1832        dimensions of [u]
1833    """
1834    fname = 'compute_wds'
1835
1836#    print '    ' + fname + ': computing wind direction as ATAN2(v,u) ...'
1837    theta = np.arctan2(v,u)
1838    theta = np.where(theta < 0., theta + 2.*np.pi, theta)
1839
1840    var = 360.*theta/(2.*np.pi)
1841
1842    vardims = dimns[:]
1843    varvdims = dimvns[:]
1844
1845    return var, vardims, varvdims
1846
1847def compute_wds(u, v, dimns, dimvns):
1848    """ Function to compute the wind direction
1849      [u]= W-E wind direction [ms-1, knot, ...]
1850      [v]= N-S wind direction [ms-1, knot, ...]
1851      [dimns]= list of the name of the dimensions of [u]
1852      [dimvns]= list of the name of the variables with the values of the
1853        dimensions of [u]
1854    """
1855    fname = 'compute_wds'
1856
1857#    print '    ' + fname + ': computing wind direction as ATAN2(v,u) ...'
1858    theta = np.arctan2(v,u)
1859    theta = np.where(theta < 0., theta + 2.*np.pi, theta)
1860
1861    wds = 360.*theta/(2.*np.pi)
1862
1863    wdsdims = dimns[:]
1864    wdsvdims = dimvns[:]
1865
1866    return wds, wdsdims, wdsvdims
1867
1868def compute_wss(u, v, dimns, dimvns):
1869    """ Function to compute the wind speed
1870      [u]= W-E wind direction [ms-1, knot, ...]
1871      [v]= N-S wind direction [ms-1, knot, ...]
1872      [dimns]= list of the name of the dimensions of [u]
1873      [dimvns]= list of the name of the variables with the values of the
1874        dimensions of [u]
1875    """
1876    fname = 'compute_wss'
1877
1878#    print '    ' + fname + ': computing wind speed as SQRT(v**2 + u**2) ...'
1879    wss = np.sqrt(u*u + v*v)
1880
1881    wssdims = dimns[:]
1882    wssvdims = dimvns[:]
1883
1884    return wss, wssdims, wssvdims
1885
1886def timeunits_seconds(dtu):
1887    """ Function to transform a time units to seconds
1888    timeunits_seconds(timeuv)
1889      [dtu]= time units value to transform in seconds
1890    """
1891    fname='timunits_seconds'
1892
1893    if dtu == 'years':
1894        times = 365.*24.*3600.
1895    elif dtu == 'weeks':
1896        times = 7.*24.*3600.
1897    elif dtu == 'days':
1898        times = 24.*3600.
1899    elif dtu == 'hours':
1900        times = 3600.
1901    elif dtu == 'minutes':
1902        times = 60.
1903    elif dtu == 'seconds':
1904        times = 1.
1905    elif dtu == 'miliseconds':
1906        times = 1./1000.
1907    else:
1908        print errormsg
1909        print '  ' + fname  + ": time units '" + dtu + "' not ready !!"
1910        quit(-1)
1911
1912    return times
1913
1914def compute_WRFhur(t, p, qv, dimns, dimvns):
1915    """ Function to compute WRF relative humidity following Teten's equation
1916      t= orginal WRF temperature
1917      p= original WRF pressure (P + PB)
1918      formula:
1919          temp = theta*(p/p0)**(R/Cp)
1920
1921    """
1922    fname = 'compute_WRFtd'
1923
1924    tk = (t+300.)*(p/fdef.module_definitions.p0ref)**(fdef.module_definitions.rcp)
1925    data1 = 10.*0.6112*np.exp(17.67*(tk-273.16)/(tk-29.65))
1926    data2 = 0.622*data1/(0.01*p-(1.-0.622)*data1)
1927
1928    rh = qv/data2
1929               
1930    dnamesvar = ['Time','bottom_top','south_north','west_east']
1931    dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dimns,dimvns)
1932
1933    return rh, dnamesvar, dvnamesvar
1934
1935def compute_WRFua(u, v, sina, cosa, dimns, dimvns):
1936    """ Function to compute geographical rotated WRF 3D winds
1937      u= orginal WRF x-wind
1938      v= orginal WRF y-wind
1939      sina= original WRF local sinus of map rotation
1940      cosa= original WRF local cosinus of map rotation
1941      formula:
1942        ua = u*cosa-va*sina
1943        va = u*sina+va*cosa
1944    """
1945    fname = 'compute_WRFua'
1946
1947    var0 = u
1948    var1 = v
1949    var2 = sina
1950    var3 = cosa
1951
1952    # un-staggering variables
1953    unstgdims = [var0.shape[0], var0.shape[1], var0.shape[2], var0.shape[3]-1]
1954    ua = np.zeros(tuple(unstgdims), dtype=np.float)
1955    unstgvar0 = np.zeros(tuple(unstgdims), dtype=np.float)
1956    unstgvar1 = np.zeros(tuple(unstgdims), dtype=np.float)
1957    unstgvar0 = 0.5*(var0[:,:,:,0:var0.shape[3]-1] + var0[:,:,:,1:var0.shape[3]])
1958    unstgvar1 = 0.5*(var1[:,:,0:var1.shape[2]-1,:] + var1[:,:,1:var1.shape[2],:])
1959
1960    for iz in range(var0.shape[1]):
1961        ua[:,iz,:,:] = unstgvar0[:,iz,:,:]*var3 - unstgvar1[:,iz,:,:]*var2
1962
1963    dnamesvar = ['Time','bottom_top','south_north','west_east']
1964    dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dimns,dimvns)
1965
1966    return ua, dnamesvar, dvnamesvar
1967
1968def compute_WRFva(u, v, sina, cosa, dimns, dimvns):
1969    """ Function to compute geographical rotated WRF 3D winds
1970      u= orginal WRF x-wind
1971      v= orginal WRF y-wind
1972      sina= original WRF local sinus of map rotation
1973      cosa= original WRF local cosinus of map rotation
1974      formula:
1975        ua = u*cosa-va*sina
1976        va = u*sina+va*cosa
1977    """
1978    fname = 'compute_WRFva'
1979
1980    var0 = u
1981    var1 = v
1982    var2 = sina
1983    var3 = cosa
1984
1985    # un-staggering variables
1986    unstgdims = [var0.shape[0], var0.shape[1], var0.shape[2], var0.shape[3]-1]
1987    va = np.zeros(tuple(unstgdims), dtype=np.float)
1988    unstgvar0 = np.zeros(tuple(unstgdims), dtype=np.float)
1989    unstgvar1 = np.zeros(tuple(unstgdims), dtype=np.float)
1990    unstgvar0 = 0.5*(var0[:,:,:,0:var0.shape[3]-1] + var0[:,:,:,1:var0.shape[3]])
1991    unstgvar1 = 0.5*(var1[:,:,0:var1.shape[2]-1,:] + var1[:,:,1:var1.shape[2],:])
1992
1993    for iz in range(var0.shape[1]):
1994        va[:,iz,:,:] = unstgvar0[:,iz,:,:]*var2 + unstgvar1[:,iz,:,:]*var3
1995
1996    dnamesvar = ['Time','bottom_top','south_north','west_east']
1997    dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dimns,dimvns)
1998
1999    return va, dnamesvar, dvnamesvar
2000
2001def compute_WRFuava(u, v, sina, cosa, dimns, dimvns):
2002    """ Function to compute geographical rotated WRF 3D winds
2003      u= orginal WRF x-wind
2004      v= orginal WRF y-wind
2005      sina= original WRF local sinus of map rotation
2006      cosa= original WRF local cosinus of map rotation
2007      formula:
2008        ua = u*cosa-va*sina
2009        va = u*sina+va*cosa
2010    """
2011    fname = 'compute_WRFuava'
2012
2013    var0 = u
2014    var1 = v
2015    var2 = sina
2016    var3 = cosa
2017
2018    # un-staggering variables
2019    unstgdims = [var0.shape[0], var0.shape[1], var0.shape[2], var0.shape[3]-1]
2020    ua = np.zeros(tuple(unstgdims), dtype=np.float)
2021    va = np.zeros(tuple(unstgdims), dtype=np.float)
2022    unstgvar0 = np.zeros(tuple(unstgdims), dtype=np.float)
2023    unstgvar1 = np.zeros(tuple(unstgdims), dtype=np.float)
2024    unstgvar0 = 0.5*(var0[:,:,:,0:var0.shape[3]-1] + var0[:,:,:,1:var0.shape[3]])
2025    unstgvar1 = 0.5*(var1[:,:,0:var1.shape[2]-1,:] + var1[:,:,1:var1.shape[2],:])
2026
2027    for iz in range(var0.shape[1]):
2028        ua[:,iz,:,:] = unstgvar0[:,iz,:,:]*var3 - unstgvar1[:,iz,:,:]*var2
2029        va[:,iz,:,:] = unstgvar0[:,iz,:,:]*var2 + unstgvar1[:,iz,:,:]*var3
2030
2031    dnamesvar = ['Time','bottom_top','south_north','west_east']
2032    dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dimns,dimvns)
2033
2034    return ua, va, dnamesvar, dvnamesvar
2035
2036def compute_WRFuas(u10, v10, sina, cosa, dimns, dimvns):
2037    """ Function to compute geographical rotated WRF 2-meter x-wind
2038      u10= orginal WRF 10m x-wind
2039      v10= orginal WRF 10m y-wind
2040      sina= original WRF local sinus of map rotation
2041      cosa= original WRF local cosinus of map rotation
2042      formula:
2043        uas = u10*cosa-va10*sina
2044        vas = u10*sina+va10*cosa
2045    """
2046    fname = 'compute_WRFuas'
2047
2048    var0 = u10
2049    var1 = v10
2050    var2 = sina
2051    var3 = cosa
2052
2053    uas = np.zeros(var0.shape, dtype=np.float)
2054    vas = np.zeros(var0.shape, dtype=np.float)
2055
2056    uas = var0*var3 - var1*var2
2057
2058    dnamesvar = ['Time','south_north','west_east']
2059    dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dimns,dimvns)
2060
2061    return uas, dnamesvar, dvnamesvar
2062
2063def compute_WRFvas(u10, v10, sina, cosa, dimns, dimvns):
2064    """ Function to compute geographical rotated WRF 2-meter y-wind
2065      u10= orginal WRF 10m x-wind
2066      v10= orginal WRF 10m y-wind
2067      sina= original WRF local sinus of map rotation
2068      cosa= original WRF local cosinus of map rotation
2069      formula:
2070        uas = u10*cosa-va10*sina
2071        vas = u10*sina+va10*cosa
2072    """
2073    fname = 'compute_WRFvas'
2074
2075    var0 = u10
2076    var1 = v10
2077    var2 = sina
2078    var3 = cosa
2079
2080    uas = np.zeros(var0.shape, dtype=np.float)
2081    vas = np.zeros(var0.shape, dtype=np.float)
2082
2083    vas = var0*var2 + var1*var3
2084
2085    dnamesvar = ['Time','south_north','west_east']
2086    dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dimns,dimvns)
2087
2088    return vas, dnamesvar, dvnamesvar
2089
2090def compute_WRFuasvas(u10, v10, sina, cosa, dimns, dimvns):
2091    """ Function to compute geographical rotated WRF 2-meter winds
2092      u10= orginal WRF 10m x-wind
2093      v10= orginal WRF 10m y-wind
2094      sina= original WRF local sinus of map rotation
2095      cosa= original WRF local cosinus of map rotation
2096      formula:
2097        uas = u10*cosa-va10*sina
2098        vas = u10*sina+va10*cosa
2099    """
2100    fname = 'compute_WRFuasvas'
2101
2102    var0 = u10
2103    var1 = v10
2104    var2 = sina
2105    var3 = cosa
2106
2107    uas = np.zeros(var0.shape, dtype=np.float)
2108    vas = np.zeros(var0.shape, dtype=np.float)
2109
2110    uas = var0*var3 - var1*var2
2111    vas = var0*var2 + var1*var3
2112
2113    dnamesvar = ['Time','south_north','west_east']
2114    dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dimns,dimvns)
2115
2116    return uas, vas, dnamesvar, dvnamesvar
2117
2118def compute_WRFta(t, p, dimns, dimvns):
2119    """ Function to compute WRF air temperature
2120      t= orginal WRF temperature
2121      p= original WRF pressure (P + PB)
2122      formula:
2123          temp = theta*(p/p0)**(R/Cp)
2124
2125    """
2126    fname = 'compute_WRFta'
2127
2128    ta = (t+300.)*(p/fdef.module_definitions.p0ref)**(fdef.module_definitions.rcp)
2129
2130    dnamesvar = ['Time','bottom_top','south_north','west_east']
2131    dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dimns,dimvns)
2132
2133    return ta, dnamesvar, dvnamesvar
2134
2135def compute_WRFtd(t, p, qv, dimns, dimvns):
2136    """ Function to compute WRF dew-point air temperature
2137      t= orginal WRF temperature
2138      p= original WRF pressure (P + PB)
2139      formula:
2140          temp = theta*(p/p0)**(R/Cp)
2141
2142    """
2143    fname = 'compute_WRFtd'
2144
2145    tk = (t+300.)*(p/fdef.module_definitions.p0ref)**(fdef.module_definitions.rcp)
2146    data1 = 10.*0.6112*np.exp(17.67*(tk-273.16)/(tk-29.65))
2147    data2 = 0.622*data1/(0.01*p-(1.-0.622)*data1)
2148
2149    rh = qv/data2
2150               
2151    pa = rh * data1
2152    td = 257.44*np.log(pa/6.1121)/(18.678-np.log(pa/6.1121))
2153
2154    dnamesvar = ['Time','bottom_top','south_north','west_east']
2155    dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dimns,dimvns)
2156
2157    return td, dnamesvar, dvnamesvar
2158
2159def compute_WRFwd(u, v, sina, cosa, dimns, dimvns):
2160    """ Function to compute the wind direction
2161      u= W-E wind direction [ms-1]
2162      v= N-S wind direction [ms-1]
2163      sina= original WRF local sinus of map rotation
2164      cosa= original WRF local cosinus of map rotation
2165    """
2166    fname = 'compute_WRFwd'
2167    var0 = u
2168    var1 = v
2169    var2 = sina
2170    var3 = cosa
2171
2172    # un-staggering variables
2173    unstgdims = [var0.shape[0], var0.shape[1], var0.shape[2], var0.shape[3]-1]
2174    ua = np.zeros(tuple(unstgdims), dtype=np.float)
2175    va = np.zeros(tuple(unstgdims), dtype=np.float)
2176    unstgvar0 = np.zeros(tuple(unstgdims), dtype=np.float)
2177    unstgvar1 = np.zeros(tuple(unstgdims), dtype=np.float)
2178    unstgvar0 = 0.5*(var0[:,:,:,0:var0.shape[3]-1] + var0[:,:,:,1:var0.shape[3]])
2179    unstgvar1 = 0.5*(var1[:,:,0:var1.shape[2]-1,:] + var1[:,:,1:var1.shape[2],:])
2180
2181    for iz in range(var0.shape[1]):
2182        ua[:,iz,:,:] = unstgvar0[:,iz,:,:]*var3 - unstgvar1[:,iz,:,:]*var2
2183        va[:,iz,:,:] = unstgvar0[:,iz,:,:]*var2 + unstgvar1[:,iz,:,:]*var3
2184
2185    theta = np.arctan2(va,ua)
2186    theta = np.where(theta < 0., theta + 2.*np.pi, theta)
2187
2188    wd = 360.*theta/(2.*np.pi)
2189
2190    dnamesvar = ['Time','bottom_top','south_north','west_east']
2191    dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dimns,dimvns)
2192
2193    return wd
2194
2195####### Variables (as they arrive without dimensions staff)
2196
2197def var_hur(p, t, q):
2198    """ Function to compute relative humidity following 'August - Roche - Magnus' formula
2199      [t]= temperature (assuming [[t],z,y,x] in [K])
2200      [p] = pressure field (assuming in [Pa])
2201      [q] = mixing ratio in [kgkg-1]
2202      ref.: M. G. Lawrence, BAMS, 2005, 225
2203    >>> print var_rh(101300., 290., 3.)
2204    0.250250256174
2205    """
2206    fname = 'var_hur'
2207
2208    # Enthalpy of vaporization [Jkg-1]
2209    L = 2.453*10.**6
2210    # Gas constant for water vapor [JK-1Kg-1]
2211    Rv = 461.5 
2212
2213    # Computing saturated pressure
2214    #es = 10.*0.6112*np.exp(17.67*(t-273.16)/(t-29.65))
2215    #es = 6.11*np.exp(L/Rv*(1.-273./t)/273.)
2216
2217    # August - Roche - Magnus formula
2218    es = 6.1094*np.exp(17.625*(t-273.15)/((t-273.15)+243.04))
2219
2220    # Saturated mixing ratio [g/kg]
2221    ws = 0.622*es/(0.01*p-es)
2222
2223    hur = q/(ws*1000.)
2224
2225    #print 'q:', q[5,5,5,5], 't:', t[5,5,5,5], 'p:', p[5,5,5,5]
2226    #print 'es:', es[5,5,5,5], 'ws:', ws[5,5,5,5], 'hur:', hur[5,5,5,5]
2227
2228    return hur
2229
2230def var_hur_Uhus(p, t, hus):
2231    """ Function to compute relative humidity following 'August - Roche - Magnus' formula using hus
2232      [t]= temperature (assuming [[t],z,y,x] in [K])
2233      [p] = pressure field (assuming in [Pa])
2234      [hus] = specific humidty [1]
2235      ref.: M. G. Lawrence, BAMS, 2005, 225
2236    >>> print var_rh(101300., 290., 3.)
2237    0.250250256174
2238    """
2239    fname = 'var_hur_Uhus'
2240
2241    # Enthalpy of vaporization [Jkg-1]
2242    L = 2.453*10.**6
2243    # Gas constant for water vapor [JK-1Kg-1]
2244    Rv = 461.5 
2245
2246    # Computing saturated pressure
2247    #es = 10.*0.6112*np.exp(17.67*(t-273.16)/(t-29.65))
2248    #es = 6.11*np.exp(L/Rv*(1.-273./t)/273.)
2249
2250    # August - Roche - Magnus formula
2251    es = 6.1094*np.exp(17.625*(t-273.15)/((t-273.15)+243.04))
2252
2253    # Saturated mixing ratio [g/kg]
2254    ws = 0.622*es/(0.01*p-es)
2255
2256    # Mixing ratio
2257    q = hus/(1.+hus)
2258
2259    hur = q/ws
2260
2261    #print 'q:', q[5,5,5,5], 't:', t[5,5,5,5], 'p:', p[5,5,5,5]
2262    #print 'es:', es[5,5,5,5], 'ws:', ws[5,5,5,5], 'hur:', hur[5,5,5,5]
2263
2264    return hur
2265
2266def var_hur_tas_tds(tas, tds, dimns, dimvns):
2267    """ Function to compute hur relative humidity from tas and tds
2268      tas= surface temperature [K]
2269      tds= dew point temperature [K]
2270      Magnus formula with D. Bolton, 1980, Mon. Wea. Rev. values:
2271            gamma = log(hur/100) + b*tas/(c+tas)
2272            tdps = c*gamma/(b-gamma)
2273         hur = 100*expr[b(tdps/(c+tdps)-tas/(c+tas))]
2274
2275    """
2276    fname = 'compute_hur_tas_tds'
2277
2278    dnamesvar = dimns
2279    dvnamesvar = dimvns
2280
2281    tasC = tas - fdef.module_definitions.svpt0
2282    tdsC = tds - fdef.module_definitions.svpt0
2283
2284    # Magnus formula with D. Bolton, 1980, Mon. Wea. Rev. values
2285    b = 17.67
2286    c = 243.5
2287
2288    hur = np.exp(b*(tdsC/(c+tdsC)-tasC/(c+tasC)))
2289               
2290    return hur, dnamesvar, dvnamesvar
2291
2292def var_td(t, p, qv):
2293    """ Function to compute dew-point air temperature from temperature and pressure values
2294      t= temperature [K]
2295      p= pressure (Pa)
2296      formula:
2297          temp = theta*(p/p0)**(R/Cp)
2298
2299    """
2300    fname = 'compute_td'
2301
2302    tk = (t)*(p/fdef.module_definitions.p0ref)**(fdef.module_definitions.rcp)
2303    data1 = 10.*0.6112*np.exp(17.67*(tk-273.16)/(tk-29.65))
2304    data2 = 0.622*data1/(0.01*p-(1.-0.622)*data1)
2305
2306    rh = qv/data2
2307               
2308    pa = rh * data1
2309    td = 257.44*np.log(pa/6.1121)/(18.678-np.log(pa/6.1121))
2310
2311    return td
2312
2313def var_td_Uhus(t, p, hus):
2314    """ Function to compute dew-point air temperature from temperature and pressure values using hus
2315      t= temperature [K]
2316      hus= specific humidity [1]
2317      formula:
2318          temp = theta*(p/p0)**(R/Cp)
2319
2320    """
2321    fname = 'compute_td'
2322
2323    tk = (t)*(p/fdef.module_definitions.p0ref)**(fdef.module_definitions.rcp)
2324    data1 = 10.*0.6112*np.exp(17.67*(tk-273.16)/(tk-29.65))
2325    data2 = 0.622*data1/(0.01*p-(1.-0.622)*data1)
2326
2327    qv = hus/(1.+hus)
2328
2329    rh = qv/data2
2330               
2331    pa = rh * data1
2332    td = 257.44*np.log(pa/6.1121)/(18.678-np.log(pa/6.1121))
2333
2334    return td
2335
2336def var_tws_S11(ta0, hur0):
2337    """ Function to compute Wet Bulb temperature using equation after:
2338      Stull, R. (2011), J. Appl. Meteor. Climatol. 50(11):2267-2269,
2339        doi: 10.1175/JAMC-D-11-0143.1
2340      [ta]= temperature (assuming [[t],z,y,x] in [K])
2341      [hur] = relative humidity (assuming in [1])
2342    >>> var_rh_S11(293.15, 0.5)
2343    13.699341969
2344    """
2345    fname = 'var_tws_S11'
2346
2347    ta = ta0 - 273.15
2348    hur = hur0*100.
2349
2350    # Does it has any sense not in surface?
2351    tws = ta*np.arctan(0.151977*np.sqrt(hur+8.313659)) + np.arctan(ta+hur) -         \
2352      np.arctan(hur-1.676331) + 0.00391838*(hur)**(1.5)*np.arctan(0.023101*hur) -    \
2353      4.686035
2354
2355    return tws
2356
2357def var_wd(u, v):
2358    """ Function to compute the wind direction
2359      [u]= W-E wind direction [ms-1, knot, ...]
2360      [v]= N-S wind direction [ms-1, knot, ...]
2361    """
2362    fname = 'var_wd'
2363
2364    theta = np.arctan2(v,u)
2365    theta = np.where(theta < 0., theta + 2.*np.pi, theta)
2366
2367    wd = 360.*theta/(2.*np.pi)
2368
2369    return wd
2370
2371def var_ws(u, v):
2372    """ Function to compute the wind speed
2373      [u]= W-E wind direction [ms-1, knot, ...]
2374      [v]= N-S wind direction [ms-1, knot, ...]
2375    """
2376    fname = 'var_ws'
2377
2378    ws = np.sqrt(u*u + v*v)
2379
2380    return ws
2381
2382class C_diagnostic(object):
2383    """ Class to compute generic variables
2384      Cdiag: name of the diagnostic to compute
2385      ncobj: netcdf object with data
2386      sfcvars: dictionary with CF equivalencies of surface variables inside file
2387      vars3D: dictionary with CF equivalencies of 3D variables inside file
2388      dictdims: dictionary with CF equivalencies of dimensions inside file
2389        self.values = Values of the diagnostic
2390        self.dims = Dimensions of the diagnostic
2391        self.units = units of the diagnostic
2392        self.incvars = list of variables from the input netCDF object
2393    """ 
2394    def __init__(self, Cdiag, ncobj, sfcvars, vars3D, dictdims):
2395        fname = 'C_diagnostic'
2396        self.values = None
2397        self.dims = None
2398        self.incvars = ncobj.variables
2399        self.units = None
2400
2401        if Cdiag == 'hur':
2402            """ Computing relative humidity
2403            """
2404            vn = 'hur'
2405            CF3Dvars = ['ta', 'plev', 'q']
2406            for v3D in CF3Dvars:
2407                if not vars3D.has_key(v3D):
2408                    print gen.errormsg
2409                    print '  ' + fname + ": missing variable '" + v3D +              \
2410                      "' attribution to compute '" + vn + "' !!"
2411                    print '  Equivalence of 3D variables provided _______'
2412                    gen.printing_dictionary(vars3D)
2413                    quit(-1)
2414                if not self.incvars.has_key(vars3D[v3D]):
2415                    print gen.errormsg
2416                    print '  ' + fname + ": missing variable '" + vars3D[v3D] +      \
2417                      "' in input file to compute '" + vn + "' !!"
2418                    print '  available variables:', self.incvars.keys()
2419                    print '  looking for variables _______' 
2420                    gen.printing_dictionary(vars3D)
2421                    quit(-1)
2422
2423            ta = ncobj.variables[vars3D['ta']][:]
2424            p = ncobj.variables[vars3D['plev']][:]
2425            q = ncobj.variables[vars3D['q']][:]
2426
2427            if len(ta.shape) != len(p.shape):
2428                p = gen.fill_Narray(p, ta*0., filldim=[0,2,3])
2429
2430            self.values = var_hur(p, ta, q)
2431            self.dims = [dictdims['time'], dictdims['plev'], dictdims['lat'],        \
2432              dictdims['lon']]
2433            self.units = '1'
2434
2435        if Cdiag == 'hur_Uhus':
2436            """ Computing relative humidity using hus
2437            """
2438            vn = 'hur'
2439            CF3Dvars = ['ta', 'plev', 'hus']
2440            for v3D in CF3Dvars:
2441                if not vars3D.has_key(v3D):
2442                    print gen.errormsg
2443                    print '  ' + fname + ": missing variable '" + v3D +              \
2444                      "' attribution to compute '" + vn + "' !!"
2445                    print '  Equivalence of 3D variables provided _______'
2446                    gen.printing_dictionary(vars3D)
2447                    quit(-1)
2448                if not self.incvars.has_key(vars3D[v3D]):
2449                    print gen.errormsg
2450                    print '  ' + fname + ": missing variable '" + vars3D[v3D] +      \
2451                      "' in input file to compute '" + vn + "' !!"
2452                    print '  available variables:', self.incvars.keys()
2453                    print '  looking for variables _______' 
2454                    gen.printing_dictionary(vars3D)
2455                    quit(-1)
2456
2457            ta = ncobj.variables[vars3D['ta']][:]
2458            p = ncobj.variables[vars3D['plev']][:]
2459            hus = ncobj.variables[vars3D['hus']][:]
2460
2461            if len(ta.shape) != len(p.shape):
2462                p = gen.fill_Narray(p, ta*0., filldim=[0,2,3])
2463
2464            self.values = var_hur_Uhus(p, ta, hus)
2465            self.dims = [dictdims['time'], dictdims['plev'], dictdims['lat'],        \
2466              dictdims['lon']]
2467            self.units = '1'
2468
2469        elif Cdiag == 'td':
2470            """ Computing dew-point temperature
2471            """
2472            vn = 'td'
2473            CF3Dvars = ['ta', 'plev', 'q']
2474            for v3D in CF3Dvars:
2475                if not vars3D.has_key(v3D):
2476                    print gen.errormsg
2477                    print '  ' + fname + ": missing variable '" + v3D +              \
2478                      "' attribution to compute '" + vn + "' !!"
2479                    print '  Equivalence of 3D variables provided _______'
2480                    gen.printing_dictionary(vars3D)
2481                    quit(-1)
2482                if not self.incvars.has_key(vars3D[v3D]):
2483                    print gen.errormsg
2484                    print '  ' + fname + ": missing variable '" + vars3D[v3D] +      \
2485                      "' in input file to compute '" + vn + "' !!"
2486                    print '  available variables:', self.incvars.keys()
2487                    print '  looking for variables _______' 
2488                    gen.printing_dictionary(vars3D)
2489                    quit(-1)
2490
2491            ta = ncobj.variables[vars3D['ta']][:]
2492            p = ncobj.variables[vars3D['plev']][:]
2493            q = ncobj.variables[vars3D['q']][:]
2494
2495            if len(ta.shape) != len(p.shape):
2496                p = gen.fill_Narray(p, ta*0., filldim=[0,2,3])
2497
2498            self.values = var_td(ta, p, q)
2499            self.dims = [dictdims['time'], dictdims['plev'], dictdims['lat'],        \
2500              dictdims['lon']]
2501            self.units = 'K'
2502
2503        elif Cdiag == 'td_Uhus':
2504            """ Computing dew-point temperature
2505            """
2506            vn = 'td'
2507            CF3Dvars = ['ta', 'plev', 'hus']
2508            for v3D in CF3Dvars:
2509                if not vars3D.has_key(v3D):
2510                    print gen.errormsg
2511                    print '  ' + fname + ": missing variable '" + v3D +              \
2512                      "' attribution to compute '" + vn + "' !!"
2513                    print '  Equivalence of 3D variables provided _______'
2514                    gen.printing_dictionary(vars3D)
2515                    quit(-1)
2516                if not self.incvars.has_key(vars3D[v3D]):
2517                    print gen.errormsg
2518                    print '  ' + fname + ": missing variable '" + vars3D[v3D] +      \
2519                      "' in input file to compute '" + vn + "' !!"
2520                    print '  available variables:', self.incvars.keys()
2521                    print '  looking for variables _______' 
2522                    gen.printing_dictionary(vars3D)
2523                    quit(-1)
2524
2525            ta = ncobj.variables[vars3D['ta']][:]
2526            p = ncobj.variables[vars3D['plev']][:]
2527            hus = ncobj.variables[vars3D['hus']][:]
2528
2529            if len(ta.shape) != len(p.shape):
2530                p = gen.fill_Narray(p, ta*0., filldim=[0,2,3])
2531
2532            self.values = var_td_Uhus(ta, p, hus)
2533            self.dims = [dictdims['time'], dictdims['plev'], dictdims['lat'],        \
2534              dictdims['lon']]
2535            self.units = 'K'
2536
2537        elif Cdiag == 'wd':
2538            """ Computing wind direction
2539            """
2540            vn = 'wd'
2541            CF3Dvars = ['ua', 'va']
2542            for v3D in CF3Dvars:
2543                if not vars3D.has_key(v3D):
2544                    print gen.errormsg
2545                    print '  ' + fname + ": missing variable '" + v3D +              \
2546                      "self.' attribution to compute '" + vn + "' !!"
2547                    print '  Equivalence of 3D variables provided _______'
2548                    gen.printing_dictionary(vars3D)
2549                    quit(-1)
2550                if not self.incvars.has_key(vars3D[v3D]):
2551                    print gen.errormsg
2552                    print '  ' + fname + ": missing variable '" + vars3D[v3D] +      \
2553                      "' in input file to compute '" + vn + "' !!"
2554                    print '  available variables:', self.incvars.keys()
2555                    print '  looking for variables _______' 
2556                    gen.printing_dictionary(vars3D)
2557                    quit(-1)
2558   
2559            ua = ncobj.variables[vars3D['ua']][:]
2560            va = ncobj.variables[vars3D['va']][:]
2561   
2562            self.values = var_wd(ua, va)
2563            self.dims = [dictdims['time'], dictdims['plev'], dictdims['lat'],        \
2564              dictdims['lon']]
2565            self.units = 'degree'
2566
2567        elif Cdiag == 'ws':
2568            """ Computing wind speed
2569            """
2570            vn = 'ws'
2571            CF3Dvars = ['ua', 'va']
2572            for v3D in CF3Dvars:
2573                if not vars3D.has_key(v3D):
2574                    print gen.errormsg
2575                    print '  ' + fname + ": missing variable '" + v3D +              \
2576                      "' attribution to compute '" + vn + "' !!"
2577                    print '  Equivalence of 3D variables provided _______'
2578                    gen.printing_dictionary(vars3D)
2579                    quit(-1)
2580                if not self.incvars.has_key(vars3D[v3D]):
2581                    print gen.errormsg
2582                    print '  ' + fname + ": missing variable '" + vars3D[v3D] +      \
2583                      "' in input file to compute '" + vn + "' !!"
2584                    print '  available variables:', self.incvars.keys()
2585                    print '  looking for variables _______' 
2586                    gen.printing_dictionary(vars3D)
2587                    quit(-1)
2588
2589            ua = ncobj.variables[vars3D['ua']][:]
2590            va = ncobj.variables[vars3D['va']][:]
2591
2592            self.values = var_ws(ua, va)
2593            self.dims = [dictdims['time'], dictdims['plev'], dictdims['lat'],        \
2594              dictdims['lon']]
2595            self.units = ncobj.variables[vars3D['ua']].units
2596
2597        else:
2598            print gen.errormsg
2599            print '  ' + fname + ": variable '" + Wdiag + "' not ready !!"
2600            print '  available ones:', Cavailablediags
2601            quit(-1)
2602
2603class W_diagnostic(object):
2604    """ Class to compute WRF diagnostics variables
2605      Wdiag: name of the diagnostic to compute
2606      ncobj: netcdf object with data
2607      sfcvars: dictionary with CF equivalencies of surface variables inside file
2608      vars3D: dictionary with CF equivalencies of 3D variables inside file
2609      indims: list of dimensions inside file
2610      invardims: list of dimension-variables inside file
2611      dictdims: dictionary with CF equivalencies of dimensions inside file
2612        self.values = Values of the diagnostic
2613        self.dims = Dimensions of the diagnostic
2614        self.units = units of the diagnostic
2615        self.incvars = list of variables from the input netCDF object
2616    """   
2617    def __init__(self, Wdiag, ncobj, sfcvars, vars3D, indims, invardims, dictdims):
2618        fname = 'W_diagnostic'
2619
2620        self.values = None
2621        self.dims = None
2622        self.incvars = ncobj.variables
2623        self.units = None
2624
2625        if Wdiag == 'hur':
2626            """ Computing relative humidity
2627            """
2628            vn = 'hur'
2629            CF3Dvars = ['ta', 'hus']
2630            for v3D in CF3Dvars:
2631                if not vars3D.has_key(v3D):
2632                    print gen.errormsg
2633                    print '  ' + fname + ": missing variable '" + v3D +              \
2634                      "' attribution to compute '" + vn + "' !!"
2635                    print '  Equivalence of 3D variables provided _______'
2636                    gen.printing_dictionary(vars3D)
2637                    quit(-1)
2638
2639            ta = ncobj.variables['T'][:]
2640            p = ncobj.variables['P'][:] + ncobj.variables['PB'][:]
2641            hur = ncobj.variables['QVAPOR'][:]
2642   
2643            vals, dims, vdims = compute_WRFhur(ta, p, hur, indims, invardims)
2644            self.values = vals
2645            self.dims = [dictdims['time'], dictdims['plev'], dictdims['lat'],        \
2646              dictdims['lon']]
2647            self.units = '1'
2648
2649        elif Wdiag == 'p':
2650            """ Computing air pressure
2651            """
2652            vn = 'p'
2653
2654            self.values = ncobj.variables['PB'][:] + ncobj.variables['P'][:]
2655            self.dims = [dictdims['time'], dictdims['plev'], dictdims['lat'],        \
2656              dictdims['lon']]
2657            self.units = ncobj.variables['PB'].units
2658
2659        elif Wdiag == 'ta':
2660            """ Computing air temperature
2661            """
2662            vn = 'ta'
2663            CF3Dvars = ['ta']
2664            for v3D in CF3Dvars:
2665                if not vars3D.has_key(v3D):
2666                    print gen.errormsg
2667                    print '  ' + fname + ": missing variable '" + v3D +              \
2668                      "' attribution to compute '" + vn + "' !!"
2669                    print '  Equivalence of 3D variables provided _______'
2670                    gen.printing_dictionary(vars3D)
2671                    quit(-1)
2672
2673            ta = ncobj.variables['T'][:]
2674            p = ncobj.variables['P'][:] + ncobj.variables['PB'][:]
2675   
2676            vals, dims, vdims = compute_WRFta(ta, p, indims, invardims)
2677            self.values = vals
2678            self.dims = [dictdims['time'], dictdims['plev'], dictdims['lat'],        \
2679              dictdims['lon']]
2680            self.units = 'K'
2681
2682        elif Wdiag == 'td':
2683            """ Computing dew-point temperature
2684            """
2685            vn = 'td'
2686            CF3Dvars = ['ta', 'hus']
2687            for v3D in CF3Dvars:
2688                if not vars3D.has_key(v3D):
2689                    print gen.errormsg
2690                    print '  ' + fname + ": missing variable '" + v3D +              \
2691                      "' attribution to compute '" + vn + "' !!"
2692                    print '  Equivalence of 3D variables provided _______'
2693                    gen.printing_dictionary(vars3D)
2694                    quit(-1)
2695
2696            ta = ncobj.variables['T'][:]
2697            p = ncobj.variables['P'][:] + ncobj.variables['PB'][:]
2698            hus = ncobj.variables['QVAPOR'][:]
2699   
2700            vals, dims, vdims = compute_WRFtd(ta, p, hus, indims, invardims)
2701            self.values = vals
2702            self.dims = [dictdims['time'], dictdims['plev'], dictdims['lat'],        \
2703              dictdims['lon']]
2704            self.units = 'K'
2705   
2706        elif Wdiag == 'ua':
2707            """ Computing x-wind
2708            """
2709            vn = 'ua'
2710            CF3Dvars = ['ua', 'va']
2711            for v3D in CF3Dvars:
2712                if not vars3D.has_key(v3D):
2713                    print gen.errormsg
2714                    print '  ' + fname + ": missing variable '" + v3D +              \
2715                      "' attribution to compute '" + vn + "' !!"
2716                    print '  Equivalence of 3D variables provided _______'
2717                    gen.printing_dictionary(vars3D)
2718                    quit(-1)
2719
2720            ua = ncobj.variables['U'][:]
2721            va = ncobj.variables['V'][:]
2722            sina = ncobj.variables['SINALPHA'][:]
2723            cosa = ncobj.variables['COSALPHA'][:]
2724   
2725            vals, dims, vdims = compute_WRFua(ua, va, sina, cosa, indims, invardims)
2726            self.values = vals
2727            self.dims = [dictdims['time'], dictdims['plev'], dictdims['lat'],        \
2728              dictdims['lon']]
2729            self.units = ncobj.variables['U'].units
2730   
2731        elif Wdiag == 'uas':
2732            """ Computing 10m x-wind
2733            """
2734            vn = 'uas'
2735            CFsfcvars = ['uas', 'vas']
2736            for vsf in CFsfcvars:
2737                if not sfcvars.has_key(vsf):
2738                    print gen.errormsg
2739                    print '  ' + fname + ": missing variable '" + vsf +              \
2740                      "' attribution to compute '" + vn + "' !!"
2741                    print '  Equivalence of sfc variables provided _______'
2742                    gen.printing_dictionary(sfcvars)
2743                    quit(-1)
2744   
2745            uas = ncobj.variables['U10'][:]
2746            vas = ncobj.variables['V10'][:]
2747            sina = ncobj.variables['SINALPHA'][:]
2748            cosa = ncobj.variables['COSALPHA'][:]
2749   
2750            vals,dims,vdims = compute_WRFuas(uas, vas, sina, cosa, indims, invardims)
2751            self.values = vals
2752            self.dims = [dictdims['time'], dictdims['plev'], dictdims['lat'],        \
2753              dictdims['lon']]
2754            self.units = ncobj.variables['U10'].units
2755   
2756        elif Wdiag == 'va':
2757            """ Computing y-wind
2758            """
2759            vn = 'ua'
2760            CF3Dvars = ['ua', 'va']
2761            for v3D in CF3Dvars:
2762                if not vars3D.has_key(v3D):
2763                    print gen.errormsg
2764                    print '  ' + fname + ": missing variable '" + v3D +              \
2765                      "' attribution to compute '" + vn + "' !!"
2766                    print '  Equivalence of 3D variables provided _______'
2767                    gen.printing_dictionary(vars3D)
2768                    quit(-1)
2769   
2770            ua = ncobj.variables['U'][:]
2771            va = ncobj.variables['V'][:]
2772            sina = ncobj.variables['SINALPHA'][:]
2773            cosa = ncobj.variables['COSALPHA'][:]
2774   
2775            vals, dims, vdims = compute_WRFva(ua, va, sina, cosa, indims, invardims)
2776            self.values = vals
2777            self.dims = [dictdims['time'], dictdims['plev'], dictdims['lat'],        \
2778              dictdims['lon']]
2779            self.units = ncobj.variables['U'].units
2780   
2781        elif Wdiag == 'vas':
2782            """ Computing 10m y-wind
2783            """
2784            vn = 'uas'
2785            CFsfcvars = ['uas', 'vas']
2786            for vsf in CFsfcvars:
2787                if not sfcvars.has_key(vsf):
2788                    print gen.errormsg
2789                    print '  ' + fname + ": missing variable '" + vsf +              \
2790                      "' attribution to compute '" + vn + "' !!"
2791                    print '  Equivalence of sfc variables provided _______'
2792                    gen.printing_dictionary(sfcvars)
2793                    quit(-1)
2794   
2795            uas = ncobj.variables['U10'][:]
2796            vas = ncobj.variables['V10'][:]
2797            sina = ncobj.variables['SINALPHA'][:]
2798            cosa = ncobj.variables['COSALPHA'][:]
2799   
2800            vals,dims,vdims = compute_WRFvas(uas, vas, sina, cosa, indims, invardims)
2801            self.values = vals
2802            self.dims = [dictdims['time'], dictdims['plev'], dictdims['lat'],        \
2803              dictdims['lon']]
2804            self.units = ncobj.variables['U10'].units
2805
2806        elif Wdiag == 'wd':
2807            """ Computing wind direction
2808            """
2809            vn = 'wd'
2810            CF3Dvars = ['ua', 'va']
2811            for v3D in CF3Dvars:
2812                if not vars3D.has_key(v3D):
2813                    print gen.errormsg
2814                    print '  ' + fname + ": missing variable '" + v3D +              \
2815                      "' attribution to compute '" + vn + "' !!"
2816                    print '  Equivalence of 3D variables provided _______'
2817                    gen.printing_dictionary(vars3D)
2818                    quit(-1)
2819
2820            ua = ncobj.variables['U10'][:]
2821            va = ncobj.variables['V10'][:]
2822            sina = ncobj.variables['SINALPHA'][:]
2823            cosa = ncobj.variables['COSALPHA'][:]
2824   
2825            vals, dims, vdims = compute_WRFwd(ua, va, sina, cosa, indims, invardims)
2826            self.values = vals
2827            self.dims = [dictdims['time'], dictdims['plev'], dictdims['lat'],        \
2828              dictdims['lon']]
2829            self.units = 'degree'
2830
2831        elif Wdiag == 'ws':
2832            """ Computing wind speed
2833            """
2834            vn = 'ws'
2835            CF3Dvars = ['ua', 'va']
2836            for v3D in CF3Dvars:
2837                if not vars3D.has_key(v3D):
2838                    print gen.errormsg
2839                    print '  ' + fname + ": missing variable '" + v3D +              \
2840                      "' attribution to compute '" + vn + "' !!"
2841                    print '  Equivalence of 3D variables provided _______'
2842                    gen.printing_dictionary(vars3D)
2843                    quit(-1)
2844   
2845            ua = ncobj.variables['U10'][:]
2846            va = ncobj.variables['V10'][:]
2847   
2848            self.values = var_ws(ua, va)
2849            self.dims = [dictdims['time'], dictdims['plev'], dictdims['lat'],        \
2850              dictdims['lon']]
2851            self.units = ncobj.variables['U10'].units
2852
2853        elif Wdiag == 'zg':
2854            """ Computing geopotential
2855            """
2856            vn = 'zg'
2857
2858            self.values = ncobj.variables['PHB'][:] + ncobj.variables['PH'][:]
2859            self.dims = [dictdims['time'], dictdims['plev'], dictdims['lat'],        \
2860              dictdims['lon']]
2861            self.units = ncobj.variables['PHB'].units
2862
2863        else:
2864            print gen.errormsg
2865            print '  ' + fname + ": variable '" + Wdiag + "' not ready !!"
2866            print '  available ones:', Wavailablediags
2867            quit(-1)
Note: See TracBrowser for help on using the repository browser.