source: lmdz_wrf/trunk/tools/diagnostics.py @ 1422

Last change on this file since 1422 was 1419, checked in by lfita, 8 years ago

Fixing equation for the `WRFheightrel'

File size: 59.9 KB
Line 
1# Pthon script to comput diagnostics
2# L. Fita, LMD. CNR, UPMC-Jussieu, Paris, France
3# File diagnostics.inf provides the combination of variables to get the desired diagnostic
4#   To be used with module_ForDiagnostics.F90, module_ForDiagnosticsVars.F90, module_generic.F90
5#      foudre: f2py -m module_ForDiagnostics --f90exec=/usr/bin/gfortran-4.7 -c module_generic.F90 module_ForDiagnosticsVars.F90 module_ForDiagnostics.F90 >& run_f2py.log
6#      ciclad: f2py --f90flags="-fPIC" --f90exec=/usr/bin/gfortran -L/opt/canopy-1.3.0/Canopy_64bit/System/lib/ -L/usr/lib64/ -L/opt/canopy-1.3.0/Canopy_64bit/System/lib/ -m module_ForDiagnostics -c module_generic.F90 module_ForDiagnosticsVars.F90 module_ForDiagnostics.F90 >& run_f2py.log
7
8## e.g. # diagnostics.py -d 'Time@time,bottom_top@ZNU,south_north@XLAT,west_east@XLONG' -v 'clt|CLDFRA,cllmh|CLDFRA@WRFp,RAINTOT|RAINC@RAINNC@XTIME' -f WRF_LMDZ/NPv31/wrfout_d01_1980-03-01_00:00:00
9## e.g. # diagnostics.py -f /home/lluis/PY/diagnostics.inf -d variable_combo -v WRFprc
10
11from optparse import OptionParser
12import numpy as np
13from netCDF4 import Dataset as NetCDFFile
14import os
15import re
16import nc_var_tools as ncvar
17import generic_tools as gen
18import datetime as dtime
19import module_ForDiag as fdin
20
21main = 'diagnostics.py'
22errormsg = 'ERROR -- error -- ERROR -- error'
23warnmsg = 'WARNING -- warning -- WARNING -- warning'
24
25# Constants
26grav = 9.81
27
28# Gneral information
29##
30def reduce_spaces(string):
31    """ Function to give words of a line of text removing any extra space
32    """
33    values = string.replace('\n','').split(' ')
34    vals = []
35    for val in values:
36         if len(val) > 0:
37             vals.append(val)
38
39    return vals
40
41def variable_combo(varn,combofile):
42    """ Function to provide variables combination from a given variable name
43      varn= name of the variable
44      combofile= ASCII file with the combination of variables
45        [varn] [combo]
46          [combo]: '@' separated list of variables to use to generate [varn]
47            [WRFdt] to get WRF time-step (from general attributes)
48    >>> variable_combo('WRFprls','/home/lluis/PY/diagnostics.inf')
49    deaccum@RAINNC@XTIME@prnc
50    """
51    fname = 'variable_combo'
52
53    if varn == 'h':
54        print fname + '_____________________________________________________________'
55        print variable_combo.__doc__
56        quit()
57
58    if not os.path.isfile(combofile):
59        print errormsg
60        print '  ' + fname + ": file with combinations '" + combofile +              \
61          "' does not exist!!"
62        quit(-1)
63
64    objf = open(combofile, 'r')
65
66    found = False
67    for line in objf:
68        linevals = reduce_spaces(line)
69        varnf = linevals[0]
70        combo = linevals[1].replace('\n','')
71        if varn == varnf: 
72            found = True
73            break
74
75    if not found:
76        print errormsg
77        print '  ' + fname + ": variable '" + varn + "' not found in '" + combofile +\
78          "' !!"
79        combo='ERROR'
80
81    objf.close()
82
83    return combo
84
85# Mathematical operators
86##
87def compute_accum(varv, dimns, dimvns):
88    """ Function to compute the accumulation of a variable
89    compute_accum(varv, dimnames, dimvns)
90      [varv]= values to accum (assuming [t,])
91      [dimns]= list of the name of the dimensions of the [varv]
92      [dimvns]= list of the name of the variables with the values of the
93        dimensions of [varv]
94    """
95    fname = 'compute_accum'
96
97    deacdims = dimns[:]
98    deacvdims = dimvns[:]
99
100    slicei = []
101    slicee = []
102
103    Ndims = len(varv.shape)
104    for iid in range(0,Ndims):
105        slicei.append(slice(0,varv.shape[iid]))
106        slicee.append(slice(0,varv.shape[iid]))
107
108    slicee[0] = np.arange(varv.shape[0])
109    slicei[0] = np.arange(varv.shape[0])
110    slicei[0][1:varv.shape[0]] = np.arange(varv.shape[0]-1)
111
112    vari = varv[tuple(slicei)]
113    vare = varv[tuple(slicee)]
114
115    ac = vari*0.
116    for it in range(1,varv.shape[0]):
117        ac[it,] = ac[it-1,] + vare[it,]
118
119    return ac, deacdims, deacvdims
120
121def compute_deaccum(varv, dimns, dimvns):
122    """ Function to compute the deaccumulation of a variable
123    compute_deaccum(varv, dimnames, dimvns)
124      [varv]= values to deaccum (assuming [t,])
125      [dimns]= list of the name of the dimensions of the [varv]
126      [dimvns]= list of the name of the variables with the values of the
127        dimensions of [varv]
128    """
129    fname = 'compute_deaccum'
130
131    deacdims = dimns[:]
132    deacvdims = dimvns[:]
133
134    slicei = []
135    slicee = []
136
137    Ndims = len(varv.shape)
138    for iid in range(0,Ndims):
139        slicei.append(slice(0,varv.shape[iid]))
140        slicee.append(slice(0,varv.shape[iid]))
141
142    slicee[0] = np.arange(varv.shape[0])
143    slicei[0] = np.arange(varv.shape[0])
144    slicei[0][1:varv.shape[0]] = np.arange(varv.shape[0]-1)
145
146    vari = varv[tuple(slicei)]
147    vare = varv[tuple(slicee)]
148
149    deac = vare - vari
150
151    return deac, deacdims, deacvdims
152
153def derivate_centered(var,dim,dimv):
154    """ Function to compute the centered derivate of a given field
155      centered derivate(n) = (var(n-1) + var(n+1))/(2*dn).
156    [var]= variable
157    [dim]= which dimension to compute the derivate
158    [dimv]= dimension values (can be of different dimension of [var])
159    >>> derivate_centered(np.arange(16).reshape(4,4)*1.,1,1.)
160    [[  0.   1.   2.   0.]
161     [  0.   5.   6.   0.]
162     [  0.   9.  10.   0.]
163     [  0.  13.  14.   0.]]
164    """
165
166    fname = 'derivate_centered'
167   
168    vark = var.dtype
169
170    if hasattr(dimv, "__len__"):
171# Assuming that the last dimensions of var [..., N, M] are the same of dimv [N, M]
172        if len(var.shape) != len(dimv.shape):
173            dimvals = np.zeros((var.shape), dtype=vark)
174            if len(var.shape) - len(dimv.shape) == 1:
175                for iz in range(var.shape[0]):
176                    dimvals[iz,] = dimv
177            elif len(var.shape) - len(dimv.shape) == 2:
178                for it in range(var.shape[0]):
179                    for iz in range(var.shape[1]):
180                        dimvals[it,iz,] = dimv
181            else:
182                print errormsg
183                print '  ' + fname + ': dimension difference between variable',      \
184                  var.shape,'and variable with dimension values',dimv.shape,         \
185                  ' not ready !!!'
186                quit(-1)
187        else:
188            dimvals = dimv
189    else:
190# dimension values are identical everywhere!
191# from: http://stackoverflow.com/questions/16807011/python-how-to-identify-if-a-variable-is-an-array-or-a-scalar   
192        dimvals = np.ones((var.shape), dtype=vark)*dimv
193
194    derivate = np.zeros((var.shape), dtype=vark)
195    if dim > len(var.shape) - 1:
196        print errormsg
197        print '  ' + fname + ': dimension',dim,' too big for given variable of ' +   \
198          'shape:', var.shape,'!!!'
199        quit(-1)
200
201    slicebef = []
202    sliceaft = []
203    sliceder = []
204
205    for id in range(len(var.shape)):
206        if id == dim:
207            slicebef.append(slice(0,var.shape[id]-2))
208            sliceaft.append(slice(2,var.shape[id]))
209            sliceder.append(slice(1,var.shape[id]-1))
210        else:
211            slicebef.append(slice(0,var.shape[id]))
212            sliceaft.append(slice(0,var.shape[id]))
213            sliceder.append(slice(0,var.shape[id]))
214
215    if hasattr(dimv, "__len__"):
216        derivate[tuple(sliceder)] = (var[tuple(slicebef)] + var[tuple(sliceaft)])/   \
217          ((dimvals[tuple(sliceaft)] - dimvals[tuple(slicebef)]))
218        print (dimvals[tuple(sliceaft)] - dimvals[tuple(slicebef)])
219    else:
220        derivate[tuple(sliceder)] = (var[tuple(slicebef)] + var[tuple(sliceaft)])/   \
221          (2.*dimv)
222
223#    print 'before________'
224#    print var[tuple(slicebef)]
225
226#    print 'after________'
227#    print var[tuple(sliceaft)]
228
229    return derivate
230
231def rotational_z(Vx,Vy,pos):
232    """ z-component of the rotatinoal of horizontal vectorial field
233    \/ x (Vx,Vy,Vz) = \/xVy - \/yVx
234    [Vx]= Variable component x
235    [Vy]=  Variable component y
236    [pos]= poisition of the grid points
237    >>> rotational_z(np.arange(16).reshape(4,4)*1., np.arange(16).reshape(4,4)*1., 1.)
238    [[  0.   1.   2.   0.]
239     [ -4.   0.   0.  -7.]
240     [ -8.   0.   0. -11.]
241     [  0.  13.  14.   0.]]
242    """
243
244    fname =  'rotational_z'
245
246    ndims = len(Vx.shape)
247    rot1 = derivate_centered(Vy,ndims-1,pos)
248    rot2 = derivate_centered(Vx,ndims-2,pos)
249
250    rot = rot1 - rot2
251
252    return rot
253
254# Diagnostics
255##
256
257def var_clt(cfra):
258    """ Function to compute the total cloud fraction following 'newmicro.F90' from
259      LMDZ using 1D vertical column values
260      [cldfra]= cloud fraction values (assuming [[t],z,y,x])
261    """
262    ZEPSEC=1.0E-12
263
264    fname = 'var_clt'
265
266    zclear = 1.
267    zcloud = 0.
268
269    dz = cfra.shape[0]
270    for iz in range(dz):
271        zclear =zclear*(1.-np.max([cfra[iz],zcloud]))/(1.-np.min([zcloud,1.-ZEPSEC]))
272        clt = 1. - zclear
273        zcloud = cfra[iz]
274
275    return clt
276
277def compute_clt(cldfra, dimns, dimvns):
278    """ Function to compute the total cloud fraction following 'newmicro.F90' from
279      LMDZ
280    compute_clt(cldfra, dimnames)
281      [cldfra]= cloud fraction values (assuming [[t],z,y,x])
282      [dimns]= list of the name of the dimensions of [cldfra]
283      [dimvns]= list of the name of the variables with the values of the
284        dimensions of [cldfra]
285    """
286    fname = 'compute_clt'
287
288    cltdims = dimns[:]
289    cltvdims = dimvns[:]
290
291    if len(cldfra.shape) == 4:
292        clt = np.zeros((cldfra.shape[0],cldfra.shape[2],cldfra.shape[3]),            \
293          dtype=np.float)
294        dx = cldfra.shape[3]
295        dy = cldfra.shape[2]
296        dz = cldfra.shape[1]
297        dt = cldfra.shape[0]
298        cltdims.pop(1)
299        cltvdims.pop(1)
300
301        for it in range(dt):
302            for ix in range(dx):
303                for iy in range(dy):
304                    zclear = 1.
305                    zcloud = 0.
306                    ncvar.percendone(it*dx*dy + ix*dy + iy, dx*dy*dt, 5, 'diagnosted')
307                    clt[it,iy,ix] = var_clt(cldfra[it,:,iy,ix])
308
309    else:
310        clt = np.zeros((cldfra.shape[1],cldfra.shape[2]), dtype=np.float)
311        dx = cldfra.shape[2]
312        dy = cldfra.shape[1]
313        dy = cldfra.shape[0]
314        cltdims.pop(0)
315        cltvdims.pop(0)
316        for ix in range(dx):
317            for iy in range(dy):
318                zclear = 1.
319                zcloud = 0.
320                ncvar.percendone(ix*dy + iy, dx*dy*dt, 5, 'diagnosted')
321                clt[iy,ix] = var_clt(cldfra[:,iy,ix])
322
323    return clt, cltdims, cltvdims
324
325def Forcompute_clt(cldfra, dimns, dimvns):
326    """ Function to compute the total cloud fraction following 'newmicro.F90' from
327      LMDZ via a Fortran module
328    compute_clt(cldfra, dimnames)
329      [cldfra]= cloud fraction values (assuming [[t],z,y,x])
330      [dimns]= list of the name of the dimensions of [cldfra]
331      [dimvns]= list of the name of the variables with the values of the
332        dimensions of [cldfra]
333    """
334    fname = 'Forcompute_clt'
335
336    cltdims = dimns[:]
337    cltvdims = dimvns[:]
338
339
340    if len(cldfra.shape) == 4:
341        clt = np.zeros((cldfra.shape[0],cldfra.shape[2],cldfra.shape[3]),            \
342          dtype=np.float)
343        dx = cldfra.shape[3]
344        dy = cldfra.shape[2]
345        dz = cldfra.shape[1]
346        dt = cldfra.shape[0]
347        cltdims.pop(1)
348        cltvdims.pop(1)
349
350        clt = fdin.module_fordiagnostics.compute_clt4d2(cldfra[:])
351
352    else:
353        clt = np.zeros((cldfra.shape[1],cldfra.shape[2]), dtype=np.float)
354        dx = cldfra.shape[2]
355        dy = cldfra.shape[1]
356        dy = cldfra.shape[0]
357        cltdims.pop(0)
358        cltvdims.pop(0)
359
360        clt = fdin.module_fordiagnostics.compute_clt3d1(cldfra[:])
361
362    return clt, cltdims, cltvdims
363
364def var_cllmh(cfra, p):
365    """ Fcuntion to compute cllmh on a 1D column
366    """
367
368    fname = 'var_cllmh'
369
370    ZEPSEC =1.0E-12
371    prmhc = 440.*100.
372    prmlc = 680.*100.
373
374    zclearl = 1.
375    zcloudl = 0.
376    zclearm = 1.
377    zcloudm = 0.
378    zclearh = 1.
379    zcloudh = 0.
380
381    dvz = cfra.shape[0]
382
383    cllmh = np.ones((3), dtype=np.float)
384
385    for iz in range(dvz):
386        if p[iz] < prmhc:
387            cllmh[2] = cllmh[2]*(1.-np.max([cfra[iz], zcloudh]))/(1.-                \
388              np.min([zcloudh,1.-ZEPSEC]))
389            zcloudh = cfra[iz]
390        elif p[iz] >= prmhc and p[iz] < prmlc:
391            cllmh[1] = cllmh[1]*(1.-np.max([cfra[iz], zcloudm]))/(1.-                \
392              np.min([zcloudm,1.-ZEPSEC]))
393            zcloudm = cfra[iz]
394        elif p[iz] >= prmlc:
395            cllmh[0] = cllmh[0]*(1.-np.max([cfra[iz], zcloudl]))/(1.-                \
396              np.min([zcloudl,1.-ZEPSEC]))
397            zcloudl = cfra[iz]
398
399    cllmh = 1.- cllmh
400
401    return cllmh
402
403def Forcompute_cllmh(cldfra, pres, dimns, dimvns):
404    """ Function to compute cllmh: low/medium/hight cloud fraction following newmicro.F90 from LMDZ via Fortran subroutine
405    compute_clt(cldfra, pres, dimns, dimvns)
406      [cldfra]= cloud fraction values (assuming [[t],z,y,x])
407      [pres] = pressure field
408      [dimns]= list of the name of the dimensions of [cldfra]
409      [dimvns]= list of the name of the variables with the values of the
410        dimensions of [cldfra]
411    """
412    fname = 'Forcompute_cllmh'
413
414    cllmhdims = dimns[:]
415    cllmhvdims = dimvns[:]
416
417    if len(cldfra.shape) == 4:
418        dx = cldfra.shape[3]
419        dy = cldfra.shape[2]
420        dz = cldfra.shape[1]
421        dt = cldfra.shape[0]
422        cllmhdims.pop(1)
423        cllmhvdims.pop(1)
424
425        cllmh = fdin.module_fordiagnostics.compute_cllmh4d2(cldfra[:], pres[:])
426       
427    else:
428        dx = cldfra.shape[2]
429        dy = cldfra.shape[1]
430        dz = cldfra.shape[0]
431        cllmhdims.pop(0)
432        cllmhvdims.pop(0)
433
434        cllmh = fdin.module_fordiagnostics.compute_cllmh3d1(cldfra[:], pres[:])
435
436    return cllmh, cllmhdims, cllmhvdims
437
438def compute_cllmh(cldfra, pres, dimns, dimvns):
439    """ Function to compute cllmh: low/medium/hight cloud fraction following newmicro.F90 from LMDZ
440    compute_clt(cldfra, pres, dimns, dimvns)
441      [cldfra]= cloud fraction values (assuming [[t],z,y,x])
442      [pres] = pressure field
443      [dimns]= list of the name of the dimensions of [cldfra]
444      [dimvns]= list of the name of the variables with the values of the
445        dimensions of [cldfra]
446    """
447    fname = 'compute_cllmh'
448
449    cllmhdims = dimns[:]
450    cllmhvdims = dimvns[:]
451
452    if len(cldfra.shape) == 4:
453        dx = cldfra.shape[3]
454        dy = cldfra.shape[2]
455        dz = cldfra.shape[1]
456        dt = cldfra.shape[0]
457        cllmhdims.pop(1)
458        cllmhvdims.pop(1)
459
460        cllmh = np.ones(tuple([3, dt, dy, dx]), dtype=np.float)
461
462        for it in range(dt):
463            for ix in range(dx):
464                for iy in range(dy):
465                    ncvar.percendone(it*dx*dy + ix*dy + iy, dx*dy*dt, 5, 'diagnosted')
466                    cllmh[:,it,iy,ix] = var_cllmh(cldfra[it,:,iy,ix], pres[it,:,iy,ix])
467       
468    else:
469        dx = cldfra.shape[2]
470        dy = cldfra.shape[1]
471        dz = cldfra.shape[0]
472        cllmhdims.pop(0)
473        cllmhvdims.pop(0)
474
475        cllmh = np.ones(tuple([3, dy, dx]), dtype=np.float)
476
477        for ix in range(dx):
478            for iy in range(dy):
479                ncvar.percendone(ix*dy + iy,dx*dy, 5, 'diagnosted')
480                cllmh[:,iy,ix] = var_cllmh(cldfra[:,iy,ix], pres[:,iy,ix])
481
482    return cllmh, cllmhdims, cllmhvdims
483
484def var_virtualTemp (temp,rmix):
485    """ This function returns virtual temperature in K,
486      temp: temperature [K]
487      rmix: mixing ratio in [kgkg-1]
488    """
489
490    fname = 'var_virtualTemp'
491
492    virtual=temp*(0.622+rmix)/(0.622*(1.+rmix))
493
494    return virtual
495
496
497def var_mslp(pres, psfc, ter, tk, qv):
498    """ Function to compute mslp on a 1D column
499    """
500
501    fname = 'var_mslp'
502
503    N = 1.0
504    expon=287.04*.0065/9.81
505    pref = 40000.
506
507# First find where about 400 hPa is located
508    dz=len(pres) 
509
510    kref = -1
511    pinc = pres[0] - pres[dz-1]
512
513    if pinc < 0.:
514        for iz in range(1,dz):
515            if pres[iz-1] >= pref and pres[iz] < pref: 
516                kref = iz
517                break
518    else:
519        for iz in range(dz-1):
520            if pres[iz] >= pref and pres[iz+1] < pref: 
521                kref = iz
522                break
523
524    if kref == -1:
525        print errormsg
526        print '  ' + fname + ': no reference pressure:',pref,'found!!'
527        print '    values:',pres[:]
528        quit(-1)
529
530    mslp = 0.
531
532# We are below both the ground and the lowest data level.
533
534# First, find the model level that is closest to a "target" pressure
535# level, where the "target" pressure is delta-p less that the local
536# value of a horizontally smoothed surface pressure field.  We use
537# delta-p = 150 hPa here. A standard lapse rate temperature profile
538# passing through the temperature at this model level will be used
539# to define the temperature profile below ground.  This is similar
540# to the Benjamin and Miller (1990) method, using 
541# 700 hPa everywhere for the "target" pressure.
542
543# ptarget = psfc - 15000.
544    ptarget = 70000.
545    dpmin=1.e4
546    kupper = 0
547    if pinc > 0.:
548        for iz in range(dz-1,0,-1):
549            kupper = iz
550            dp=np.abs( pres[iz] - ptarget )
551            if dp < dpmin: exit
552            dpmin = np.min([dpmin, dp])
553    else:
554        for iz in range(dz):
555            kupper = iz
556            dp=np.abs( pres[iz] - ptarget )
557            if dp < dpmin: exit
558            dpmin = np.min([dpmin, dp])
559
560    pbot=np.max([pres[0], psfc])
561#    zbot=0.
562
563#    tbotextrap=tk(i,j,kupper,itt)*(pbot/pres_field(i,j,kupper,itt))**expon
564#    tvbotextrap=virtual(tbotextrap,qv(i,j,1,itt))
565
566#    data_out(i,j,itt,1) = (zbot+tvbotextrap/.0065*(1.-(interp_levels(1)/pbot)**expon))
567    tbotextrap = tk[kupper]*(psfc/ptarget)**expon
568    tvbotextrap = var_virtualTemp(tbotextrap, qv[kupper])
569    mslp = psfc*( (tvbotextrap+0.0065*ter)/tvbotextrap)**(1./expon)
570
571    return mslp
572
573def compute_mslp(pressure, psurface, terrain, temperature, qvapor, dimns, dimvns):
574    """ Function to compute mslp: mean sea level pressure following p_interp.F90 from WRF
575    var_mslp(pres, ter, tk, qv, dimns, dimvns)
576      [pressure]= pressure field [Pa] (assuming [[t],z,y,x])
577      [psurface]= surface pressure field [Pa]
578      [terrain]= topography [m]
579      [temperature]= temperature [K]
580      [qvapor]= water vapour mixing ratio [kgkg-1]
581      [dimns]= list of the name of the dimensions of [cldfra]
582      [dimvns]= list of the name of the variables with the values of the
583        dimensions of [pres]
584    """
585
586    fname = 'compute_mslp'
587
588    mslpdims = list(dimns[:])
589    mslpvdims = list(dimvns[:])
590
591    if len(pressure.shape) == 4:
592        mslpdims.pop(1)
593        mslpvdims.pop(1)
594    else:
595        mslpdims.pop(0)
596        mslpvdims.pop(0)
597
598    if len(pressure.shape) == 4:
599        dx = pressure.shape[3]
600        dy = pressure.shape[2]
601        dz = pressure.shape[1]
602        dt = pressure.shape[0]
603
604        mslpv = np.zeros(tuple([dt, dy, dx]), dtype=np.float)
605
606# Terrain... to 2D !
607        terval = np.zeros(tuple([dy, dx]), dtype=np.float)
608        if len(terrain.shape) == 3:
609            terval = terrain[0,:,:]
610        else:
611            terval = terrain
612
613        for ix in range(dx):
614            for iy in range(dy):
615                if terval[iy,ix] > 0.:
616                    for it in range(dt):
617                        mslpv[it,iy,ix] = var_mslp(pressure[it,:,iy,ix],             \
618                          psurface[it,iy,ix], terval[iy,ix], temperature[it,:,iy,ix],\
619                          qvapor[it,:,iy,ix])
620
621                        ncvar.percendone(it*dx*dy + ix*dy + iy, dx*dy*dt, 5, 'diagnosted')
622                else:
623                    mslpv[:,iy,ix] = psurface[:,iy,ix]
624
625    else:
626        dx = pressure.shape[2]
627        dy = pressure.shape[1]
628        dz = pressure.shape[0]
629
630        mslpv = np.zeros(tuple([dy, dx]), dtype=np.float)
631
632# Terrain... to 2D !
633        terval = np.zeros(tuple([dy, dx]), dtype=np.float)
634        if len(terrain.shape) == 3:
635            terval = terrain[0,:,:]
636        else:
637            terval = terrain
638
639        for ix in range(dx):
640            for iy in range(dy):
641                ncvar.percendone(ix*dy + iy,dx*dy, 5, 'diagnosted')
642                if terval[iy,ix] > 0.:
643                    mslpv[iy,ix] = var_mslp(pressure[:,iy,ix], psurface[iy,ix],          \
644                      terval[iy,ix], temperature[:,iy,ix], qvapor[:,iy,ix])
645                else:
646                    mslpv[iy,ix] = psfc[iy,ix]
647
648    return mslpv, mslpdims, mslpvdims
649
650def compute_OMEGAw(omega, p, t, dimns, dimvns):
651    """ Function to transform OMEGA [Pas-1] to velocities [ms-1]
652      tacking: https://www.ncl.ucar.edu/Document/Functions/Contributed/omega_to_w.shtml
653      [omega] = vertical velocity [in ms-1] (assuming [t],z,y,x)
654      [p] = pressure in [Pa] (assuming [t],z,y,x)
655      [t] = temperature in [K] (assuming [t],z,y,x)
656      [dimns]= list of the name of the dimensions of [q]
657      [dimvns]= list of the name of the variables with the values of the
658        dimensions of [q]
659    """
660    fname = 'compute_OMEGAw'
661
662    rgas = 287.058            # J/(kg-K) => m2/(s2 K)
663    g    = 9.80665            # m/s2
664
665    wdims = dimns[:]
666    wvdims = dimvns[:]
667
668    rho  = p/(rgas*t)         # density => kg/m3
669    w    = -omega/(rho*g)     
670
671    return w, wdims, wvdims
672
673def compute_prw(dens, q, dimns, dimvns):
674    """ Function to compute water vapour path (prw)
675      [dens] = density [in kgkg-1] (assuming [t],z,y,x)
676      [q] = mixing ratio in [kgkg-1] (assuming [t],z,y,x)
677      [dimns]= list of the name of the dimensions of [q]
678      [dimvns]= list of the name of the variables with the values of the
679        dimensions of [q]
680    """
681    fname = 'compute_prw'
682
683    prwdims = dimns[:]
684    prwvdims = dimvns[:]
685
686    if len(q.shape) == 4:
687        prwdims.pop(1)
688        prwvdims.pop(1)
689    else:
690        prwdims.pop(0)
691        prwvdims.pop(0)
692
693    data1 = dens*q
694    prw = np.sum(data1, axis=1)
695
696    return prw, prwdims, prwvdims
697
698def compute_rh(p, t, q, dimns, dimvns):
699    """ Function to compute relative humidity following 'Tetens' equation (T,P) ...'
700      [t]= temperature (assuming [[t],z,y,x] in [K])
701      [p] = pressure field (assuming in [hPa])
702      [q] = mixing ratio in [kgkg-1]
703      [dimns]= list of the name of the dimensions of [t]
704      [dimvns]= list of the name of the variables with the values of the
705        dimensions of [t]
706    """
707    fname = 'compute_rh'
708
709    rhdims = dimns[:]
710    rhvdims = dimvns[:]
711
712    data1 = 10.*0.6112*np.exp(17.67*(t-273.16)/(t-29.65))
713    data2 = 0.622*data1/(0.01*p-(1.-0.622)*data1)
714
715    rh = q/data2
716
717    return rh, rhdims, rhvdims
718
719def compute_td(p, temp, qv, dimns, dimvns):
720    """ Function to compute the dew point temperature
721      [p]= pressure [Pa]
722      [temp]= temperature [C]
723      [qv]= mixing ratio [kgkg-1]
724      [dimns]= list of the name of the dimensions of [p]
725      [dimvns]= list of the name of the variables with the values of the
726        dimensions of [p]
727    """
728    fname = 'compute_td'
729
730#    print '    ' + fname + ': computing dew-point temperature from TS as t and Tetens...'
731# tacking from: http://en.wikipedia.org/wiki/Dew_point
732    tk = temp
733    data1 = 10.*0.6112*np.exp(17.67*(tk-273.16)/(tk-29.65))
734    data2 = 0.622*data1/(0.01*p-(1.-0.622)*data1)
735
736    rh = qv/data2
737               
738    pa = rh * data1
739    td = 257.44*np.log(pa/6.1121)/(18.678-np.log(pa/6.1121))
740
741    tddims = dimns[:]
742    tdvdims = dimvns[:]
743
744    return td, tddims, tdvdims
745
746def turbulence_var(varv, dimvn, dimn):
747    """ Function to compute the Taylor's decomposition turbulence term from a a given variable
748      x*=<x^2>_t-(<X>_t)^2
749    turbulence_var(varv,dimn)
750      varv= values of the variable
751      dimvn= names of the dimension of the variable
752      dimn= names of the dimensions (as a dictionary with 'X', 'Y', 'Z', 'T')
753    >>> turbulence_var(np.arange((27)).reshape(3,3,3),['time','y','x'],{'T':'time', 'Y':'y', 'X':'x'})
754    [[ 54.  54.  54.]
755     [ 54.  54.  54.]
756     [ 54.  54.  54.]]
757    """
758    fname = 'turbulence_varv'
759
760    timedimid = dimvn.index(dimn['T'])
761
762    varv2 = varv*varv
763
764    vartmean = np.mean(varv, axis=timedimid)
765    var2tmean = np.mean(varv2, axis=timedimid)
766
767    varvturb = var2tmean - (vartmean*vartmean)
768
769    return varvturb
770
771def compute_turbulence(v, dimns, dimvns):
772    """ Function to compute the rubulence term of the Taylor's decomposition ...'
773      x*=<x^2>_t-(<X>_t)^2
774      [v]= variable (assuming [[t],z,y,x])
775      [dimns]= list of the name of the dimensions of [v]
776      [dimvns]= list of the name of the variables with the values of the
777        dimensions of [v]
778    """
779    fname = 'compute_turbulence'
780
781    turbdims = dimns[:]
782    turbvdims = dimvns[:]
783
784    turbdims.pop(0)
785    turbvdims.pop(0)
786
787    v2 = v*v
788
789    vartmean = np.mean(v, axis=0)
790    var2tmean = np.mean(v2, axis=0)
791
792    turb = var2tmean - (vartmean*vartmean)
793
794    return turb, turbdims, turbvdims
795
796def compute_wds(u, v, dimns, dimvns):
797    """ Function to compute the wind direction
798      [u]= W-E wind direction [ms-1, knot, ...]
799      [v]= N-S wind direction [ms-1, knot, ...]
800      [dimns]= list of the name of the dimensions of [u]
801      [dimvns]= list of the name of the variables with the values of the
802        dimensions of [u]
803    """
804    fname = 'compute_wds'
805
806#    print '    ' + fname + ': computing wind direction as ATAN2(v,u) ...'
807    theta = np.arctan2(v,u)
808    theta = np.where(theta < 0., theta + 2.*np.pi, theta)
809
810    wds = 360.*theta/(2.*np.pi)
811
812    wdsdims = dimns[:]
813    wdsvdims = dimvns[:]
814
815    return wds, wdsdims, wdsvdims
816
817def compute_wss(u, v, dimns, dimvns):
818    """ Function to compute the wind speed
819      [u]= W-E wind direction [ms-1, knot, ...]
820      [v]= N-S wind direction [ms-1, knot, ...]
821      [dimns]= list of the name of the dimensions of [u]
822      [dimvns]= list of the name of the variables with the values of the
823        dimensions of [u]
824    """
825    fname = 'compute_wss'
826
827#    print '    ' + fname + ': computing wind speed as SQRT(v**2 + u**2) ...'
828    wss = np.sqrt(u*u + v*v)
829
830    wssdims = dimns[:]
831    wssvdims = dimvns[:]
832
833    return wss, wssdims, wssvdims
834
835def timeunits_seconds(dtu):
836    """ Function to transform a time units to seconds
837    timeunits_seconds(timeuv)
838      [dtu]= time units value to transform in seconds
839    """
840    fname='timunits_seconds'
841
842    if dtu == 'years':
843        times = 365.*24.*3600.
844    elif dtu == 'weeks':
845        times = 7.*24.*3600.
846    elif dtu == 'days':
847        times = 24.*3600.
848    elif dtu == 'hours':
849        times = 3600.
850    elif dtu == 'minutes':
851        times = 60.
852    elif dtu == 'seconds':
853        times = 1.
854    elif dtu == 'miliseconds':
855        times = 1./1000.
856    else:
857        print errormsg
858        print '  ' + fname  + ": time units '" + dtu + "' not ready !!"
859        quit(-1)
860
861    return times
862
863####### ###### ##### #### ### ## #
864comboinf="\nIF -d 'variable_combo', provides information of the combination to obtain -v [varn] with the ASCII file with the combinations as -f [combofile]"
865
866parser = OptionParser()
867parser.add_option("-f", "--netCDF_file", dest="ncfile", help="file to use", metavar="FILE")
868parser.add_option("-d", "--dimensions", dest="dimns", 
869  help="[dimtn]@[dtvn],[dimzn]@[dzvn],[...,[dimxn]@[dxvn]], ',' list with the couples [dimDn]@[dDvn], [dimDn], name of the dimension D and name of the variable [dDvn] with the values of the dimension ('WRFtime', for WRF time copmutation)" + comboinf, 
870  metavar="LABELS")
871parser.add_option("-v", "--variables", dest="varns", 
872  help=" [varn1]|[var11]@[...[varN1]],[...,[varnM]|[var1M]@[...[varLM]]] ',' list of variables to compute [varnK] and its necessary ones [var1K]...[varPK]", metavar="VALUES")
873
874(opts, args) = parser.parse_args()
875
876#######    #######
877## MAIN
878    #######
879availdiags = ['ACRAINTOT', 'accum', 'clt', 'cllmh', 'deaccum', 'LMDZrh', 'mslp',     \
880  'OMEGAw', 'RAINTOT',                                                               \
881  'rvors', 'td', 'turbulence', 'WRFgeop', 'WRFp', 'WRFrvors', 'ws', 'wds', 'wss',    \
882  'WRFheight', 'WRFheightrel', 'WRFua', 'WRFva']
883
884methods = ['accum', 'deaccum']
885
886# Variables not to check
887NONcheckingvars = ['cllmh', 'deaccum', 'TSrhs', 'TStd', 'TSwds', 'TSwss', 'WRFbils', \
888  'WRFdens', 'WRFgeop',                                                              \
889  'WRFp', 'WRFtd',                                                                   \
890  'WRFpos', 'WRFprc', 'WRFprls', 'WRFrh', 'LMDZrh', 'LMDZrhs', 'WRFrhs', 'WRFrvors', \
891  'WRFt', 'WRFtime', 'WRFua', 'WRFva', 'WRFwds', 'WRFwss', 'WRFheight']
892
893NONchkvardims = ['WRFtime']
894
895ofile = 'diagnostics.nc'
896
897dimns = opts.dimns
898varns = opts.varns
899
900# Special method. knowing variable combination
901##
902if opts.dimns == 'variable_combo':
903    print warnmsg
904    print '  ' + main + ': knowing variable combination !!!'
905    combination = variable_combo(opts.varns,opts.ncfile)
906    print '     COMBO: ' + combination
907    quit(-1)
908
909if not os.path.isfile(opts.ncfile):
910    print errormsg
911    print '   ' + main + ": file '" + opts.ncfile + "' does not exist !!"
912    quit(-1)
913
914ncobj = NetCDFFile(opts.ncfile, 'r')
915
916# Looking for specific variables that might be use in more than one diagnostic
917WRFgeop_compute = False
918WRFp_compute = False
919WRFt_compute = False
920WRFrh_compute = False
921WRFght_compute = False
922WRFdens_compute = False
923WRFpos_compute = False
924WRFtime_compute = False
925
926# File creation
927newnc = NetCDFFile(ofile,'w')
928
929# dimensions
930dimvalues = dimns.split(',')
931dnames = []
932dvnames = []
933
934for dimval in dimvalues:
935    dn = dimval.split('@')[0]
936    dnv = dimval.split('@')[1]
937    dnames.append(dn)
938    dvnames.append(dnv)
939    # Is there any dimension-variable which should be computed?
940    if dnv == 'WRFgeop':WRFgeop_compute = True
941    if dnv == 'WRFp': WRFp_compute = True
942    if dnv == 'WRFt': WRFt_compute = True
943    if dnv == 'WRFrh': WRFrh_compute = True
944    if dnv == 'WRFght': WRFght_compute = True
945    if dnv == 'WRFdens': WRFdens_compute = True
946    if dnv == 'WRFpos': WRFpos_compute = True
947    if dnv == 'WRFtime': WRFtime_compute = True
948
949# diagnostics to compute
950diags = varns.split(',')
951Ndiags = len(diags)
952
953for idiag in range(Ndiags):
954    if diags[idiag].split('|')[1].find('@') == -1:
955        depvars = diags[idiag].split('|')[1]
956        if depvars == 'WRFgeop':WRFgeop_compute = True
957        if depvars == 'WRFp': WRFp_compute = True
958        if depvars == 'WRFt': WRFt_compute = True
959        if depvars == 'WRFrh': WRFrh_compute = True
960        if depvars == 'WRFght': WRFght_compute = True
961        if depvars == 'WRFdens': WRFdens_compute = True
962        if depvars == 'WRFpos': WRFpos_compute = True
963        if depvars == 'WRFtime': WRFtime_compute = True
964    else:
965        depvars = diags[idiag].split('|')[1].split('@')
966        if gen.searchInlist(depvars, 'WRFgeop'): WRFgeop_compute = True
967        if gen.searchInlist(depvars, 'WRFp'): WRFp_compute = True
968        if gen.searchInlist(depvars, 'WRFt'): WRFt_compute = True
969        if gen.searchInlist(depvars, 'WRFrh'): WRFrh_compute = True
970        if gen.searchInlist(depvars, 'WRFght'): WRFght_compute = True
971        if gen.searchInlist(depvars, 'WRFdens'): WRFdens_compute = True
972        if gen.searchInlist(depvars, 'WRFpos'): WRFpos_compute = True
973        if gen.searchInlist(depvars, 'WRFtime'): WRFtime_compute = True
974
975# Dictionary with the new computed variables to be able to add them
976dictcompvars = {}
977if WRFgeop_compute:
978    print '  ' + main + ': Retrieving geopotential value from WRF as PH + PHB'
979    dimv = ncobj.variables['PH'].shape
980    WRFgeop = ncobj.variables['PH'][:] + ncobj.variables['PHB'][:]
981
982    # Attributes of the variable
983    Vvals = gen.variables_values('WRFgeop')
984    dictcompvars['WRFgeop'] = {'name': Vvals[0], 'standard_name': Vvals[1],          \
985      'long_name': Vvals[4].replace('|',' '), 'units': Vvals[5]}
986
987if WRFp_compute:
988    print '  ' + main + ': Retrieving pressure value from WRF as P + PB'
989    dimv = ncobj.variables['P'].shape
990    WRFp = ncobj.variables['P'][:] + ncobj.variables['PB'][:]
991
992    # Attributes of the variable
993    Vvals = gen.variables_values('WRFp')
994    dictcompvars['WRFgeop'] = {'name': Vvals[0], 'standard_name': Vvals[1],          \
995      'long_name': Vvals[4].replace('|',' '), 'units': Vvals[5]}
996
997if WRFght_compute:
998    print '    ' + main + ': computing geopotential height from WRF as PH + PHB ...' 
999    WRFght = ncobj.variables['PH'][:] + ncobj.variables['PHB'][:]
1000
1001    # Attributes of the variable
1002    Vvals = gen.variables_values('WRFght')
1003    dictcompvars['WRFgeop'] = {'name': Vvals[0], 'standard_name': Vvals[1],          \
1004      'long_name': Vvals[4].replace('|',' '), 'units': Vvals[5]}
1005
1006if WRFrh_compute:
1007    print '    ' + main + ": computing relative humidity from WRF as 'Tetens'" +     \
1008      ' equation (T,P) ...'
1009    p0=100000.
1010    p=ncobj.variables['P'][:] + ncobj.variables['PB'][:]
1011    tk = (ncobj.variables['T'][:] + 300.)*(p/p0)**(2./7.)
1012    qv = ncobj.variables['QVAPOR'][:]
1013
1014    data1 = 10.*0.6112*np.exp(17.67*(tk-273.16)/(tk-29.65))
1015    data2 = 0.622*data1/(0.01*p-(1.-0.622)*data1)
1016
1017    WRFrh = qv/data2
1018
1019    # Attributes of the variable
1020    Vvals = gen.variables_values('WRFrh')
1021    dictcompvars['WRFrh'] = {'name': Vvals[0], 'standard_name': Vvals[1],            \
1022      'long_name': Vvals[4].replace('|',' '), 'units': Vvals[5]}
1023
1024if WRFt_compute:
1025    print '    ' + main + ': computing temperature from WRF as inv_potT(T + 300) ...'
1026    p0=100000.
1027    p=ncobj.variables['P'][:] + ncobj.variables['PB'][:]
1028
1029    WRFt = (ncobj.variables['T'][:] + 300.)*(p/p0)**(2./7.)
1030
1031    # Attributes of the variable
1032    Vvals = gen.variables_values('WRFt')
1033    dictcompvars['WRFt'] = {'name': Vvals[0], 'standard_name': Vvals[1],             \
1034      'long_name': Vvals[4].replace('|',' '), 'units': Vvals[5]}
1035
1036if WRFdens_compute:
1037    print '    ' + main + ': computing air density from WRF as ((MU + MUB) * ' +     \
1038      'DNW)/g ...'
1039
1040# Just we need in in absolute values: Size of the central grid cell
1041##    dxval = ncobj.getncattr('DX')
1042##    dyval = ncobj.getncattr('DY')
1043##    mapfac = ncobj.variables['MAPFAC_M'][:]
1044##    area = dxval*dyval*mapfac
1045
1046    mu = (ncobj.variables['MU'][:] + ncobj.variables['MUB'][:])
1047    dnw = ncobj.variables['DNW'][:]
1048
1049    WRFdens = np.zeros((mu.shape[0], dnw.shape[1], mu.shape[1], mu.shape[2]),        \
1050      dtype=np.float)
1051    levval = np.zeros((mu.shape[1], mu.shape[2]), dtype=np.float)
1052
1053    for it in range(mu.shape[0]):
1054        for iz in range(dnw.shape[1]):
1055            levval.fill(np.abs(dnw[it,iz]))
1056            WRFdens[it,iz,:,:] = levval
1057            WRFdens[it,iz,:,:] = mu[it,:,:]*WRFdens[it,iz,:,:]/grav
1058
1059    # Attributes of the variable
1060    Vvals = gen.variables_values('WRFdens')
1061    dictcompvars['WRFdens'] = {'name': Vvals[0], 'standard_name': Vvals[1],          \
1062      'long_name': Vvals[4].replace('|',' '), 'units': Vvals[5]}
1063
1064if WRFpos_compute:
1065# WRF positions from the lowest-leftest corner of the matrix
1066    print '    ' + main + ': computing position from MAPFAC_M as sqrt(DY*j**2 + ' +  \
1067      'DX*x**2)*MAPFAC_M ...'
1068
1069    mapfac = ncobj.variables['MAPFAC_M'][:]
1070
1071    distx = np.float(ncobj.getncattr('DX'))
1072    disty = np.float(ncobj.getncattr('DY'))
1073
1074    print 'distx:',distx,'disty:',disty
1075
1076    dx = mapfac.shape[2]
1077    dy = mapfac.shape[1]
1078    dt = mapfac.shape[0]
1079
1080    WRFpos = np.zeros((dt, dy, dx), dtype=np.float)
1081
1082    for i in range(1,dx):
1083        WRFpos[0,0,i] = distx*i/mapfac[0,0,i]
1084    for j in range(1,dy):
1085        i=0
1086        WRFpos[0,j,i] = WRFpos[0,j-1,i] + disty/mapfac[0,j,i]
1087        for i in range(1,dx):
1088#            WRFpos[0,j,i] = np.sqrt((disty*j)**2. + (distx*i)**2.)/mapfac[0,j,i]
1089#            WRFpos[0,j,i] = np.sqrt((disty*j)**2. + (distx*i)**2.)
1090             WRFpos[0,j,i] = WRFpos[0,j,i-1] + distx/mapfac[0,j,i]
1091
1092    for it in range(1,dt):
1093        WRFpos[it,:,:] = WRFpos[0,:,:]
1094
1095if WRFtime_compute:
1096    print '    ' + main + ': computing time from WRF as CFtime(Times) ...'
1097
1098    refdate='19491201000000'
1099    tunitsval='minutes'
1100
1101    timeobj = ncobj.variables['Times']
1102    timewrfv = timeobj[:]
1103
1104    yrref=refdate[0:4]
1105    monref=refdate[4:6]
1106    dayref=refdate[6:8]
1107    horref=refdate[8:10]
1108    minref=refdate[10:12]
1109    secref=refdate[12:14]
1110
1111    refdateS = yrref + '-' + monref + '-' + dayref + ' ' + horref + ':' + minref +   \
1112      ':' + secref
1113
1114    dt = timeobj.shape[0]
1115    WRFtime = np.zeros((dt), dtype=np.float)
1116
1117    for it in range(dt):
1118        wrfdates = gen.datetimeStr_conversion(timewrfv[it,:],'WRFdatetime', 'matYmdHMS')
1119        WRFtime[it] = gen.realdatetime1_CFcompilant(wrfdates, refdate, tunitsval)
1120
1121    tunits = tunitsval + ' since ' + refdateS
1122
1123    # Attributes of the variable
1124    dictcompvars['WRFtime'] = {'name': 'time', 'standard_name': 'time',              \
1125      'long_name': 'time', 'units': tunits, 'calendar': 'gregorian'}
1126
1127### ## #
1128# Going for the diagnostics
1129### ## #
1130print '  ' + main + ' ...'
1131varsadd = []
1132
1133for idiag in range(Ndiags):
1134    print '    diagnostic:',diags[idiag]
1135    diag = diags[idiag].split('|')[0]
1136    depvars = diags[idiag].split('|')[1].split('@')
1137    if diags[idiag].split('|')[1].find('@') != -1:
1138        depvars = diags[idiag].split('|')[1].split('@')
1139        if depvars[0] == 'deaccum': diag='deaccum'
1140        if depvars[0] == 'accum': diag='accum'
1141        for depv in depvars:
1142            if not ncobj.variables.has_key(depv) and not                             \
1143              gen.searchInlist(NONcheckingvars, depv) and                            \
1144              not gen.searchInlist(methods, depv) and not depvars[0] == 'deaccum'    \
1145              and not depvars[0] == 'accum':
1146                print errormsg
1147                print '  ' + main + ": file '" + opts.ncfile +                       \
1148                  "' does not have variable '" + depv + "' !!"
1149                quit(-1)
1150    else:
1151        depvars = diags[idiag].split('|')[1]
1152        if not ncobj.variables.has_key(depvars) and not                              \
1153          gen.searchInlist(NONcheckingvars, depvars) and                             \
1154          not gen.searchInlist(methods, depvars):
1155            print errormsg
1156            print '  ' + main + ": file '" + opts.ncfile +                           \
1157              "' does not have variable '" + depvars + "' !!"
1158            quit(-1)
1159
1160    print "\n    Computing '" + diag + "' from: ", depvars, '...'
1161
1162# acraintot: accumulated total precipitation from WRF RAINC, RAINNC
1163    if diag == 'ACRAINTOT':
1164           
1165        var0 = ncobj.variables[depvars[0]]
1166        var1 = ncobj.variables[depvars[1]]
1167        diagout = var0[:] + var1[:]
1168
1169        dnamesvar = var0.dimensions
1170        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1171
1172        ncvar.insert_variable(ncobj, 'pracc', diagout, dnamesvar, dvnamesvar, newnc)
1173
1174# accum: acumulation of any variable as (Variable, time [as [tunits]
1175#   from/since ....], newvarname)
1176    elif diag == 'accum':
1177
1178        var0 = ncobj.variables[depvars[0]]
1179        var1 = ncobj.variables[depvars[1]]
1180
1181        dnamesvar = var0.dimensions
1182        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1183
1184        diagout, diagoutd, diagoutvd = compute_accum(var0,dnamesvar,dvnamesvar)
1185
1186        CFvarn = ncvar.variables_values(depvars[0])[0]
1187
1188# Removing the flux
1189        if depvars[1] == 'XTIME':
1190            dtimeunits = var1.getncattr('description')
1191            tunits = dtimeunits.split(' ')[0]
1192        else:
1193            dtimeunits = var1.getncattr('units')
1194            tunits = dtimeunits.split(' ')[0]
1195
1196        dtime = (var1[1] - var1[0])*timeunits_seconds(tunits)
1197
1198        ncvar.insert_variable(ncobj, CFvarn + 'acc', diagout*dtime, diagoutd, diagoutvd, newnc)
1199
1200# cllmh with cldfra, pres
1201    elif diag == 'cllmh':
1202           
1203        var0 = ncobj.variables[depvars[0]]
1204        if depvars[1] == 'WRFp':
1205            var1 = WRFp
1206        else:
1207            var01 = ncobj.variables[depvars[1]]
1208            if len(size(var1.shape)) < len(size(var0.shape)):
1209                var1 = np.brodcast_arrays(var01,var0)[0]
1210            else:
1211                var1 = var01
1212
1213        diagout, diagoutd, diagoutvd = Forcompute_cllmh(var0,var1,dnames,dvnames)
1214
1215        # Removing the nonChecking variable-dimensions from the initial list
1216        varsadd = []
1217        for nonvd in NONchkvardims:
1218            if gen.searchInlist(diagoutvd,nonvd): diagoutvd.remove(nonvd)
1219            varsadd.append(nonvd)
1220
1221        ncvar.insert_variable(ncobj, 'cll', diagout[0,:], diagoutd, diagoutvd, newnc)
1222        ncvar.insert_variable(ncobj, 'clm', diagout[1,:], diagoutd, diagoutvd, newnc)
1223        ncvar.insert_variable(ncobj, 'clh', diagout[2,:], diagoutd, diagoutvd, newnc)
1224
1225# clt with cldfra
1226    elif diag == 'clt':
1227           
1228        var0 = ncobj.variables[depvars]
1229        diagout, diagoutd, diagoutvd = Forcompute_clt(var0,dnames,dvnames)
1230
1231        # Removing the nonChecking variable-dimensions from the initial list
1232        varsadd = []
1233        for nonvd in NONchkvardims:
1234            if gen.searchInlist(diagoutvd,nonvd): diagoutvd.remove(nonvd)
1235            varsadd.append(nonvd)
1236           
1237        ncvar.insert_variable(ncobj, 'clt', diagout, diagoutd, diagoutvd, newnc)
1238
1239# deaccum: deacumulation of any variable as (Variable, time [as [tunits]
1240#   from/since ....], newvarname)
1241    elif diag == 'deaccum':
1242
1243        var0 = ncobj.variables[depvars[1]]
1244        var1 = ncobj.variables[depvars[2]]
1245
1246        dnamesvar = var0.dimensions
1247        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1248
1249        diagout, diagoutd, diagoutvd = compute_deaccum(var0,dnamesvar,dvnamesvar)
1250
1251# Transforming to a flux
1252        if depvars[2] == 'XTIME':
1253            dtimeunits = var1.getncattr('description')
1254            tunits = dtimeunits.split(' ')[0]
1255        else:
1256            dtimeunits = var1.getncattr('units')
1257            tunits = dtimeunits.split(' ')[0]
1258
1259        dtime = (var1[1] - var1[0])*timeunits_seconds(tunits)
1260        ncvar.insert_variable(ncobj, depvars[3], diagout/dtime, diagoutd, diagoutvd, newnc)
1261
1262# LMDZrh (pres, t, r)
1263    elif diag == 'LMDZrh':
1264           
1265        var0 = ncobj.variables[depvars[0]][:]
1266        var1 = ncobj.variables[depvars[1]][:]
1267        var2 = ncobj.variables[depvars[2]][:]
1268
1269        diagout, diagoutd, diagoutvd = compute_rh(var0,var1,var2,dnames,dvnames)
1270        ncvar.insert_variable(ncobj, 'hur', diagout, diagoutd, diagoutvd, newnc)
1271
1272# LMDZrhs (psol, t2m, q2m)
1273    elif diag == 'LMDZrhs':
1274           
1275        var0 = ncobj.variables[depvars[0]][:]
1276        var1 = ncobj.variables[depvars[1]][:]
1277        var2 = ncobj.variables[depvars[2]][:]
1278
1279        dnamesvar = ncobj.variables[depvars[0]].dimensions
1280        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1281
1282        diagout, diagoutd, diagoutvd = compute_rh(var0,var1,var2,dnamesvar,dvnamesvar)
1283
1284        ncvar.insert_variable(ncobj, 'hurs', diagout, diagoutd, diagoutvd, newnc)
1285
1286# mslp: mean sea level pressure (pres, psfc, terrain, temp, qv)
1287    elif diag == 'mslp' or diag == 'WRFmslp':
1288           
1289        var1 = ncobj.variables[depvars[1]][:]
1290        var2 = ncobj.variables[depvars[2]][:]
1291        var4 = ncobj.variables[depvars[4]][:]
1292
1293        if diag == 'WRFmslp':
1294            var0 = WRFp
1295            var3 = WRFt
1296            dnamesvar = ncobj.variables['P'].dimensions
1297        else:
1298            var0 = ncobj.variables[depvars[0]][:]
1299            var3 = ncobj.variables[depvars[3]][:]
1300            dnamesvar = ncobj.variables[depvars[0]].dimensions
1301
1302        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1303
1304        diagout, diagoutd, diagoutvd = compute_mslp(var0, var1, var2, var3, var4,    \
1305          dnamesvar, dvnamesvar)
1306
1307        ncvar.insert_variable(ncobj, 'psl', diagout, diagoutd, diagoutvd, newnc)
1308
1309# OMEGAw (omega, p, t) from NCL formulation (https://www.ncl.ucar.edu/Document/Functions/Contributed/omega_to_w.shtml)
1310    elif diag == 'OMEGAw':
1311           
1312        var0 = ncobj.variables[depvars[0]][:]
1313        var1 = ncobj.variables[depvars[1]][:]
1314        var2 = ncobj.variables[depvars[2]][:]
1315
1316        dnamesvar = ncobj.variables[depvars[0]].dimensions
1317        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1318
1319        diagout, diagoutd, diagoutvd = compute_OMEGAw(var0,var1,var2,dnamesvar,dvnamesvar)
1320
1321        ncvar.insert_variable(ncobj, 'wa', diagout, diagoutd, diagoutvd, newnc)
1322
1323# raintot: instantaneous total precipitation from WRF as (RAINC + RAINC) / dTime
1324    elif diag == 'RAINTOT':
1325
1326        var0 = ncobj.variables[depvars[0]]
1327        var1 = ncobj.variables[depvars[1]]
1328        if depvars[2] != 'WRFtime':
1329            var2 = ncobj.variables[depvars[2]]
1330        else:
1331            var2 = np.arange(var0.shape[0], dtype=int)
1332
1333        var = var0[:] + var1[:]
1334
1335        dnamesvar = var0.dimensions
1336        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1337
1338        diagout, diagoutd, diagoutvd = compute_deaccum(var,dnamesvar,dvnamesvar)
1339
1340# Transforming to a flux
1341        if var2.shape[0] > 1:
1342            if depvars[2] != 'WRFtime':
1343                dtimeunits = var2.getncattr('units')
1344                tunits = dtimeunits.split(' ')[0]
1345   
1346                dtime = (var2[1] - var2[0])*timeunits_seconds(tunits)
1347            else:
1348                var2 = ncobj.variables['Times']
1349                time1 = var2[0,:]
1350                time2 = var2[1,:]
1351                tmf1 = ''
1352                tmf2 = ''
1353                for ic in range(len(time1)):
1354                    tmf1 = tmf1 + time1[ic]
1355                    tmf2 = tmf2 + time2[ic]
1356                dtdate1 = dtime.datetime.strptime(tmf1,"%Y-%m-%d_%H:%M:%S")
1357                dtdate2 = dtime.datetime.strptime(tmf2,"%Y-%m-%d_%H:%M:%S")
1358                diffdate12 = dtdate2 - dtdate1
1359                dtime = diffdate12.total_seconds()
1360                print 'dtime:',dtime
1361        else:
1362            print warnmsg
1363            print '  ' + fname + ": only 1 time-step for '" + diag + "' !!"
1364            print '    leaving a zero value!'
1365            diagout = var0*0.
1366            dtime=1.
1367
1368        ncvar.insert_variable(ncobj, 'pr', diagout/dtime, diagoutd, diagoutvd, newnc)
1369
1370# rhs (psfc, t, q) from TimeSeries files
1371    elif diag == 'TSrhs':
1372           
1373        p0=100000.
1374        var0 = ncobj.variables[depvars[0]][:]
1375        var1 = (ncobj.variables[depvars[1]][:])*(var0/p0)**(2./7.)
1376        var2 = ncobj.variables[depvars[2]][:]
1377
1378        dnamesvar = ncobj.variables[depvars[0]].dimensions
1379        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1380
1381        diagout, diagoutd, diagoutvd = compute_rh(var0,var1,var2,dnamesvar,dvnamesvar)
1382
1383        ncvar.insert_variable(ncobj, 'hurs', diagout, diagoutd, diagoutvd, newnc)
1384
1385# td (psfc, t, q) from TimeSeries files
1386    elif diag == 'TStd' or diag == 'td':
1387           
1388        var0 = ncobj.variables[depvars[0]][:]
1389        var1 = ncobj.variables[depvars[1]][:] - 273.15
1390        var2 = ncobj.variables[depvars[2]][:]
1391
1392        dnamesvar = ncobj.variables[depvars[0]].dimensions
1393        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1394
1395        diagout, diagoutd, diagoutvd = compute_td(var0,var1,var2,dnamesvar,dvnamesvar)
1396
1397        ncvar.insert_variable(ncobj, 'tds', diagout, diagoutd, diagoutvd, newnc)
1398
1399# td (psfc, t, q) from TimeSeries files
1400    elif diag == 'TStdC' or diag == 'tdC':
1401           
1402        var0 = ncobj.variables[depvars[0]][:]
1403# Temperature is already in degrees Celsius
1404        var1 = ncobj.variables[depvars[1]][:]
1405        var2 = ncobj.variables[depvars[2]][:]
1406
1407        dnamesvar = ncobj.variables[depvars[0]].dimensions
1408        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1409
1410        diagout, diagoutd, diagoutvd = compute_td(var0,var1,var2,dnamesvar,dvnamesvar)
1411
1412        ncvar.insert_variable(ncobj, 'tds', diagout, diagoutd, diagoutvd, newnc)
1413
1414# wds (u, v)
1415    elif diag == 'TSwds' or diag == 'wds' :
1416 
1417        var0 = ncobj.variables[depvars[0]][:]
1418        var1 = ncobj.variables[depvars[1]][:]
1419
1420        dnamesvar = ncobj.variables[depvars[0]].dimensions
1421        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1422
1423        diagout, diagoutd, diagoutvd = compute_wds(var0,var1,dnamesvar,dvnamesvar)
1424
1425        ncvar.insert_variable(ncobj, 'wds', diagout, diagoutd, diagoutvd, newnc)
1426
1427# wss (u, v)
1428    elif diag == 'TSwss' or diag == 'wss':
1429           
1430        var0 = ncobj.variables[depvars[0]][:]
1431        var1 = ncobj.variables[depvars[1]][:]
1432
1433        dnamesvar = ncobj.variables[depvars[0]].dimensions
1434        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1435
1436        diagout, diagoutd, diagoutvd = compute_wss(var0,var1,dnamesvar,dvnamesvar)
1437
1438        ncvar.insert_variable(ncobj, 'wss', diagout, diagoutd, diagoutvd, newnc)
1439
1440# turbulence (var)
1441    elif diag == 'turbulence':
1442
1443        var0 = ncobj.variables[depvars][:]
1444
1445        dnamesvar = list(ncobj.variables[depvars].dimensions)
1446        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1447
1448        diagout, diagoutd, diagoutvd = compute_turbulence(var0,dnamesvar,dvnamesvar)
1449        valsvar = gen.variables_values(depvars)
1450
1451        newvarn = depvars + 'turb'
1452        print main + '; Lluis newvarn:', newvarn
1453        ncvar.insert_variable(ncobj, newvarn, diagout, diagoutd, 
1454          diagoutvd, newnc)
1455        print main + '; Lluis variables:', newnc.variables.keys()
1456        varobj = newnc.variables[newvarn]
1457        attrv = varobj.long_name
1458        attr = varobj.delncattr('long_name')
1459        newattr = ncvar.set_attribute(varobj, 'long_name', attrv +                   \
1460          " Taylor decomposition turbulence term")
1461
1462# WRFbils fom WRF as HFX + LH
1463    elif diag == 'WRFbils':
1464           
1465        var0 = ncobj.variables[depvars[0]][:]
1466        var1 = ncobj.variables[depvars[1]][:]
1467
1468        diagout = var0 + var1
1469        dnamesvar = list(ncobj.variables[depvars[0]].dimensions)
1470        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1471
1472        ncvar.insert_variable(ncobj, 'bils', diagout, dnamesvar, dvnamesvar, newnc)
1473
1474# WRFgeop geopotential from WRF as PH + PHB
1475    elif diag == 'WRFgeop':
1476        var0 = ncobj.variables[depvars[0]][:]
1477        var1 = ncobj.variables[depvars[1]][:]
1478
1479        # de-staggering geopotential
1480        diagout0 = var0 + var1
1481        dt = diagout0.shape[0]
1482        dz = diagout0.shape[1]
1483        dy = diagout0.shape[2]
1484        dx = diagout0.shape[3]
1485
1486        diagout = np.zeros((dt,dz-1,dy,dx), dtype=np.float)
1487        diagout = 0.5*(diagout0[:,1:dz,:,:]+diagout0[:,0:dz-1,:,:])
1488
1489        # Removing the nonChecking variable-dimensions from the initial list
1490        varsadd = []
1491        diagoutvd = list(dvnames)
1492        for nonvd in NONchkvardims:
1493            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1494            varsadd.append(nonvd)
1495
1496        ncvar.insert_variable(ncobj, 'zg', diagout, dnames, diagoutvd, newnc)
1497
1498# WRFp pressure from WRF as P + PB
1499    elif diag == 'WRFp':
1500           
1501        diagout = WRFp
1502
1503        ncvar.insert_variable(ncobj, 'pres', diagout, dnames, dvnames, newnc)
1504
1505# WRFpos
1506    elif diag == 'WRFpos':
1507           
1508        dnamesvar = ncobj.variables['MAPFAC_M'].dimensions
1509        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1510
1511        ncvar.insert_variable(ncobj, 'WRFpos', WRFpos, dnamesvar, dvnamesvar, newnc)
1512
1513# WRFprw WRF water vapour path WRFdens, QVAPOR
1514    elif diag == 'WRFprw':
1515           
1516        var0 = WRFdens
1517        var1 = ncobj.variables[depvars[1]]
1518
1519        dnamesvar = list(var1.dimensions)
1520        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1521
1522        diagout, diagoutd, diagoutvd = compute_prw(var0, var1, dnamesvar,dvnamesvar)
1523
1524        ncvar.insert_variable(ncobj, 'prw', diagout, diagoutd, diagoutvd, newnc)
1525
1526# WRFrh (P, T, QVAPOR)
1527    elif diag == 'WRFrh':
1528           
1529        dnamesvar = list(ncobj.variables[depvars[2]].dimensions)
1530        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1531
1532        ncvar.insert_variable(ncobj, 'hur', WRFrh, dnames, dvnames, newnc)
1533
1534# WRFrhs (PSFC, T2, Q2)
1535    elif diag == 'WRFrhs':
1536           
1537        var0 = ncobj.variables[depvars[0]][:]
1538        var1 = ncobj.variables[depvars[1]][:]
1539        var2 = ncobj.variables[depvars[2]][:]
1540
1541        dnamesvar = list(ncobj.variables[depvars[2]].dimensions)
1542        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1543
1544        diagout, diagoutd, diagoutvd = compute_rh(var0,var1,var2,dnamesvar,dvnamesvar)
1545        ncvar.insert_variable(ncobj, 'hurs', diagout, diagoutd, diagoutvd, newnc)
1546
1547# rvors (u10, v10, WRFpos)
1548    elif diag == 'WRFrvors':
1549           
1550        var0 = ncobj.variables[depvars[0]]
1551        var1 = ncobj.variables[depvars[1]]
1552
1553        diagout = rotational_z(var0, var1, distx)
1554
1555        dnamesvar = ncobj.variables[depvars[0]].dimensions
1556        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1557
1558        ncvar.insert_variable(ncobj, 'rvors', diagout, dnamesvar, dvnamesvar, newnc)
1559
1560# WRFt (T, P, PB)
1561    elif diag == 'WRFt':
1562        var0 = ncobj.variables[depvars[0]][:]
1563        var1 = ncobj.variables[depvars[1]][:]
1564        var2 = ncobj.variables[depvars[2]][:]
1565
1566        p0=100000.
1567        p=var1 + var2
1568
1569        WRFt = (var0 + 300.)*(p/p0)**(2./7.)
1570
1571        dnamesvar = list(ncobj.variables[depvars[0]].dimensions)
1572        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1573
1574        # Removing the nonChecking variable-dimensions from the initial list
1575        varsadd = []
1576        diagoutvd = list(dvnames)
1577        for nonvd in NONchkvardims:
1578            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1579            varsadd.append(nonvd)
1580
1581        ncvar.insert_variable(ncobj, 'ta', WRFt, dnames, diagoutvd, newnc)
1582
1583# WRFua (U, V, SINALPHA, COSALPHA) to be rotated !!
1584    elif diag == 'WRFua':
1585        var0 = ncobj.variables[depvars[0]][:]
1586        var1 = ncobj.variables[depvars[1]][:]
1587        var2 = ncobj.variables[depvars[2]][:]
1588        var3 = ncobj.variables[depvars[3]][:]
1589
1590        # un-staggering variables
1591        unstgdims = [var0.shape[0], var0.shape[1], var0.shape[2], var0.shape[3]-1]
1592        ua = np.zeros(tuple(unstgdims), dtype=np.float)
1593        unstgvar0 = np.zeros(tuple(unstgdims), dtype=np.float)
1594        unstgvar1 = np.zeros(tuple(unstgdims), dtype=np.float)
1595        unstgvar0 = 0.5*(var0[:,:,:,0:var0.shape[3]-1] + var0[:,:,:,1:var0.shape[3]])
1596        unstgvar1 = 0.5*(var1[:,:,0:var1.shape[2]-1,:] + var1[:,:,1:var1.shape[2],:])
1597
1598        for iz in range(var0.shape[1]):
1599            ua[:,iz,:,:] = unstgvar0[:,iz,:,:]*var3 - unstgvar1[:,iz,:,:]*var2
1600
1601        dnamesvar = ['Time','bottom_top','south_north','west_east']
1602        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1603
1604        # Removing the nonChecking variable-dimensions from the initial list
1605        varsadd = []
1606        diagoutvd = list(dvnames)
1607        for nonvd in NONchkvardims:
1608            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1609            varsadd.append(nonvd)
1610
1611        ncvar.insert_variable(ncobj, 'ua', ua, dnames, diagoutvd, newnc)
1612
1613# WRFua (U, V, SINALPHA, COSALPHA) to be rotated !!
1614    elif diag == 'WRFva':
1615        var0 = ncobj.variables[depvars[0]][:]
1616        var1 = ncobj.variables[depvars[1]][:]
1617        var2 = ncobj.variables[depvars[2]][:]
1618        var3 = ncobj.variables[depvars[3]][:]
1619
1620        # un-staggering variables
1621        unstgdims = [var0.shape[0], var0.shape[1], var0.shape[2], var0.shape[3]-1]
1622        va = np.zeros(tuple(unstgdims), dtype=np.float)
1623        unstgvar0 = np.zeros(tuple(unstgdims), dtype=np.float)
1624        unstgvar1 = np.zeros(tuple(unstgdims), dtype=np.float)
1625        unstgvar0 = 0.5*(var0[:,:,:,0:var0.shape[3]-1] + var0[:,:,:,1:var0.shape[3]])
1626        unstgvar1 = 0.5*(var1[:,:,0:var1.shape[2]-1,:] + var1[:,:,1:var1.shape[2],:])
1627        for iz in range(var0.shape[1]):
1628            va[:,iz,:,:] = unstgvar0[:,iz,:,:]*var2 + unstgvar1[:,iz,:,:]*var3
1629
1630        dnamesvar = ['Time','bottom_top','south_north','west_east']
1631        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1632
1633        # Removing the nonChecking variable-dimensions from the initial list
1634        varsadd = []
1635        diagoutvd = list(dvnames)
1636        for nonvd in NONchkvardims:
1637            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1638            varsadd.append(nonvd)
1639        ncvar.insert_variable(ncobj, 'va', va, dnames, diagoutvd, newnc)
1640
1641# WRFtime
1642    elif diag == 'WRFtime':
1643           
1644        diagout = WRFtime
1645
1646        dnamesvar = ['Time']
1647        dvnamesvar = ['Times']
1648
1649        ncvar.insert_variable(ncobj, 'time', diagout, dnamesvar, dvnamesvar, newnc)
1650
1651# ws (U, V)
1652    elif diag == 'ws':
1653           
1654        var0 = ncobj.variables[depvars[0]][:]
1655        var1 = ncobj.variables[depvars[1]][:]
1656        # un-staggering variables
1657        unstgdims = [var0.shape[0], var0.shape[1], var0.shape[2], var0.shape[3]-1]
1658        va = np.zeros(tuple(unstgdims), dtype=np.float)
1659        unstgvar0 = np.zeros(tuple(unstgdims), dtype=np.float)
1660        unstgvar1 = np.zeros(tuple(unstgdims), dtype=np.float)
1661        unstgvar0 = 0.5*(var0[:,:,:,0:var0.shape[3]-1] + var0[:,:,:,1:var0.shape[3]])
1662        unstgvar1 = 0.5*(var1[:,:,0:var1.shape[2]-1,:] + var1[:,:,1:var1.shape[2],:])
1663
1664        dnamesvar = ['Time','bottom_top','south_north','west_east']
1665        diagout = np.sqrt(unstgvar0*unstgvar0 + unstgvar1*unstgvar1)
1666
1667#        dnamesvar = ncobj.variables[depvars[0]].dimensions
1668        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1669
1670        # Removing the nonChecking variable-dimensions from the initial list
1671        varsadd = []
1672        diagoutvd = list(dvnamesvar)
1673        for nonvd in NONchkvardims:
1674            if gen.searchInlist(dvnamesvar,nonvd): diagoutvd.remove(nonvd)
1675            varsadd.append(nonvd)
1676        ncvar.insert_variable(ncobj, 'ws', diagout, dnamesvar, diagoutvd, newnc)
1677
1678# wss (u10, v10)
1679    elif diag == 'wss':
1680           
1681        var0 = ncobj.variables[depvars[0]][:]
1682        var1 = ncobj.variables[depvars[1]][:]
1683
1684        diagout = np.sqrt(var0*var0 + var1*var1)
1685
1686        dnamesvar = ncobj.variables[depvars[0]].dimensions
1687        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1688
1689        ncvar.insert_variable(ncobj, 'wss', diagout, dnamesvar, dvnamesvar, newnc)
1690
1691# WRFheight height from WRF geopotential as WRFGeop/g
1692    elif diag == 'WRFheight':
1693           
1694        diagout = WRFgeop/grav
1695
1696        # Removing the nonChecking variable-dimensions from the initial list
1697        varsadd = []
1698        diagoutvd = list(dvnames)
1699        for nonvd in NONchkvardims:
1700            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1701            varsadd.append(nonvd)
1702
1703        ncvar.insert_variable(ncobj, 'zhgt', diagout, dnames, diagoutvd, newnc)
1704
1705# WRFheightrel relative-height from WRF geopotential as WRFgeop(PH + PHB)/g-HGT 'WRFheightrel|PH@PHB@HGT
1706    elif diag == 'WRFheightrel':
1707        var0 = ncobj.variables[depvars[0]][:]
1708        var1 = ncobj.variables[depvars[1]][:]
1709        var2 = ncobj.variables[depvars[2]][:]
1710
1711        dimz = var0.shape[1]
1712        diagout = np.zeros(tuple(var0.shape), dtype=np.float)
1713        for iz in range(dimz):
1714            diagout[:,iz,:,:] = (var0[:,iz,:,:]+ var1[:,iz,:,:])/grav - var2
1715
1716        # Removing the nonChecking variable-dimensions from the initial list
1717        varsadd = []
1718        diagoutvd = list(dvnames)
1719        for nonvd in NONchkvardims:
1720            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1721            varsadd.append(nonvd)
1722
1723        ncvar.insert_variable(ncobj, 'zhgtrel', diagout, dnames, diagoutvd, newnc)
1724
1725    else:
1726        print errormsg
1727        print '  ' + main + ": diagnostic '" + diag + "' not ready!!!"
1728        print '    available diagnostics: ', availdiags
1729        quit(-1)
1730
1731    newnc.sync()
1732    # Adding that additional variables required to compute some diagnostics which
1733    #   where not in the original file
1734    for vadd in varsadd:
1735        if not gen.searchInlist(newnc.variables.keys(),vadd):
1736            attrs = dictcompvars[vadd]
1737            vvn = attrs['name']
1738            if not gen.searchInlist(newnc.variables.keys(), vvn):
1739                iidvn = dvnames.index(vadd)
1740                dnn = dnames[iidvn]
1741                if vadd == 'WRFtime':
1742                    dvarvals = WRFtime[:]
1743                newvar = newnc.createVariable(vvn, 'f8', (dnn))
1744                newvar[:] = dvarvals
1745                for attn in attrs.keys():
1746                    if attn != 'name':
1747                        attv = attrs[attn]
1748                        ncvar.set_attribute(newvar, attn, attv)
1749
1750#   end of diagnostics
1751
1752# Global attributes
1753##
1754atvar = ncvar.set_attribute(newnc, 'program', 'diagnostics.py')
1755atvar = ncvar.set_attribute(newnc, 'version', '1.0')
1756atvar = ncvar.set_attribute(newnc, 'author', 'Fita Borrell, Lluis')
1757atvar = ncvar.set_attribute(newnc, 'institution', 'Laboratoire Meteorologie ' +      \
1758  'Dynamique')
1759atvar = ncvar.set_attribute(newnc, 'university', 'Universite Pierre et Marie ' +     \
1760  'Curie -- Jussieu')
1761atvar = ncvar.set_attribute(newnc, 'centre', 'Centre national de la recherche ' +    \
1762  'scientifique')
1763atvar = ncvar.set_attribute(newnc, 'city', 'Paris')
1764atvar = ncvar.set_attribute(newnc, 'original_file', opts.ncfile)
1765
1766gorigattrs = ncobj.ncattrs()
1767
1768for attr in gorigattrs:
1769    attrv = ncobj.getncattr(attr)
1770    atvar = ncvar.set_attribute(newnc, attr, attrv)
1771
1772ncobj.close()
1773newnc.close()
1774
1775print '\n' + main + ': successfull writting of diagnostics file "' + ofile + '" !!!'
Note: See TracBrowser for help on using the repository browser.