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

Last change on this file since 1944 was 1909, checked in by lfita, 7 years ago

Adding:

  • `fog_FRAML50': fog and visibility following Gultepe and Milbrandt, (2010)
  • `var_hus': relative humidity using August-Roche-Magnus approximation [1]

Fixing: fog_K84' and fog_RUC'

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