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

Last change on this file since 2074 was 1980, checked in by lfita, 6 years ago

Adding:

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