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

Last change on this file since 1400 was 1389, checked in by lfita, 8 years ago

Fixing removal of non-checking dimension-variables

File size: 58.0 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', '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('WRFgreop')
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 + ' ...'
1131
1132for idiag in range(Ndiags):
1133    print '    diagnostic:',diags[idiag]
1134    diag = diags[idiag].split('|')[0]
1135    depvars = diags[idiag].split('|')[1].split('@')
1136    if diags[idiag].split('|')[1].find('@') != -1:
1137        depvars = diags[idiag].split('|')[1].split('@')
1138        if depvars[0] == 'deaccum': diag='deaccum'
1139        if depvars[0] == 'accum': diag='accum'
1140        for depv in depvars:
1141            if not ncobj.variables.has_key(depv) and not                             \
1142              gen.searchInlist(NONcheckingvars, depv) and                            \
1143              not gen.searchInlist(methods, depv) and not depvars[0] == 'deaccum'    \
1144              and not depvars[0] == 'accum':
1145                print errormsg
1146                print '  ' + main + ": file '" + opts.ncfile +                       \
1147                  "' does not have variable '" + depv + "' !!"
1148                quit(-1)
1149    else:
1150        depvars = diags[idiag].split('|')[1]
1151        if not ncobj.variables.has_key(depvars) and not                              \
1152          gen.searchInlist(NONcheckingvars, depvars) and                             \
1153          not gen.searchInlist(methods, depvars):
1154            print errormsg
1155            print '  ' + main + ": file '" + opts.ncfile +                           \
1156              "' does not have variable '" + depvars + "' !!"
1157            quit(-1)
1158
1159    print "\n    Computing '" + diag + "' from: ", depvars, '...'
1160
1161# acraintot: accumulated total precipitation from WRF RAINC, RAINNC
1162    if diag == 'ACRAINTOT':
1163           
1164        var0 = ncobj.variables[depvars[0]]
1165        var1 = ncobj.variables[depvars[1]]
1166        diagout = var0[:] + var1[:]
1167
1168        dnamesvar = var0.dimensions
1169        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1170
1171        ncvar.insert_variable(ncobj, 'pracc', diagout, dnamesvar, dvnamesvar, newnc)
1172
1173# accum: acumulation of any variable as (Variable, time [as [tunits]
1174#   from/since ....], newvarname)
1175    elif diag == 'accum':
1176
1177        var0 = ncobj.variables[depvars[0]]
1178        var1 = ncobj.variables[depvars[1]]
1179
1180        dnamesvar = var0.dimensions
1181        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1182
1183        diagout, diagoutd, diagoutvd = compute_accum(var0,dnamesvar,dvnamesvar)
1184
1185        CFvarn = ncvar.variables_values(depvars[0])[0]
1186
1187# Removing the flux
1188        if depvars[1] == 'XTIME':
1189            dtimeunits = var1.getncattr('description')
1190            tunits = dtimeunits.split(' ')[0]
1191        else:
1192            dtimeunits = var1.getncattr('units')
1193            tunits = dtimeunits.split(' ')[0]
1194
1195        dtime = (var1[1] - var1[0])*timeunits_seconds(tunits)
1196
1197        ncvar.insert_variable(ncobj, CFvarn + 'acc', diagout*dtime, diagoutd, diagoutvd, newnc)
1198
1199# cllmh with cldfra, pres
1200    elif diag == 'cllmh':
1201           
1202        var0 = ncobj.variables[depvars[0]]
1203        if depvars[1] == 'WRFp':
1204            var1 = WRFp
1205        else:
1206            var01 = ncobj.variables[depvars[1]]
1207            if len(size(var1.shape)) < len(size(var0.shape)):
1208                var1 = np.brodcast_arrays(var01,var0)[0]
1209            else:
1210                var1 = var01
1211
1212        diagout, diagoutd, diagoutvd = Forcompute_cllmh(var0,var1,dnames,dvnames)
1213
1214        # Removing the nonChecking variable-dimensions from the initial list
1215        varsadd = []
1216        for nonvd in NONchkvardims:
1217            if gen.searchInlist(diagoutvd,nonvd): diagoutvd.remove(nonvd)
1218            varsadd.append(nonvd)
1219
1220        ncvar.insert_variable(ncobj, 'cll', diagout[0,:], diagoutd, diagoutvd, newnc)
1221        ncvar.insert_variable(ncobj, 'clm', diagout[1,:], diagoutd, diagoutvd, newnc)
1222        ncvar.insert_variable(ncobj, 'clh', diagout[2,:], diagoutd, diagoutvd, newnc)
1223
1224# clt with cldfra
1225    elif diag == 'clt':
1226           
1227        var0 = ncobj.variables[depvars]
1228        diagout, diagoutd, diagoutvd = Forcompute_clt(var0,dnames,dvnames)
1229
1230        # Removing the nonChecking variable-dimensions from the initial list
1231        varsadd = []
1232        for nonvd in NONchkvardims:
1233            if gen.searchInlist(diagoutvd,nonvd): diagoutvd.remove(nonvd)
1234            varsadd.append(nonvd)
1235           
1236        ncvar.insert_variable(ncobj, 'clt', diagout, diagoutd, diagoutvd, newnc)
1237
1238# deaccum: deacumulation of any variable as (Variable, time [as [tunits]
1239#   from/since ....], newvarname)
1240    elif diag == 'deaccum':
1241
1242        var0 = ncobj.variables[depvars[1]]
1243        var1 = ncobj.variables[depvars[2]]
1244
1245        dnamesvar = var0.dimensions
1246        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1247
1248        diagout, diagoutd, diagoutvd = compute_deaccum(var0,dnamesvar,dvnamesvar)
1249
1250# Transforming to a flux
1251        if depvars[2] == 'XTIME':
1252            dtimeunits = var1.getncattr('description')
1253            tunits = dtimeunits.split(' ')[0]
1254        else:
1255            dtimeunits = var1.getncattr('units')
1256            tunits = dtimeunits.split(' ')[0]
1257
1258        dtime = (var1[1] - var1[0])*timeunits_seconds(tunits)
1259        ncvar.insert_variable(ncobj, depvars[3], diagout/dtime, diagoutd, diagoutvd, newnc)
1260
1261# LMDZrh (pres, t, r)
1262    elif diag == 'LMDZrh':
1263           
1264        var0 = ncobj.variables[depvars[0]][:]
1265        var1 = ncobj.variables[depvars[1]][:]
1266        var2 = ncobj.variables[depvars[2]][:]
1267
1268        diagout, diagoutd, diagoutvd = compute_rh(var0,var1,var2,dnames,dvnames)
1269        ncvar.insert_variable(ncobj, 'hur', diagout, diagoutd, diagoutvd, newnc)
1270
1271# LMDZrhs (psol, t2m, q2m)
1272    elif diag == 'LMDZrhs':
1273           
1274        var0 = ncobj.variables[depvars[0]][:]
1275        var1 = ncobj.variables[depvars[1]][:]
1276        var2 = ncobj.variables[depvars[2]][:]
1277
1278        dnamesvar = ncobj.variables[depvars[0]].dimensions
1279        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1280
1281        diagout, diagoutd, diagoutvd = compute_rh(var0,var1,var2,dnamesvar,dvnamesvar)
1282
1283        ncvar.insert_variable(ncobj, 'hurs', diagout, diagoutd, diagoutvd, newnc)
1284
1285# mslp: mean sea level pressure (pres, psfc, terrain, temp, qv)
1286    elif diag == 'mslp' or diag == 'WRFmslp':
1287           
1288        var1 = ncobj.variables[depvars[1]][:]
1289        var2 = ncobj.variables[depvars[2]][:]
1290        var4 = ncobj.variables[depvars[4]][:]
1291
1292        if diag == 'WRFmslp':
1293            var0 = WRFp
1294            var3 = WRFt
1295            dnamesvar = ncobj.variables['P'].dimensions
1296        else:
1297            var0 = ncobj.variables[depvars[0]][:]
1298            var3 = ncobj.variables[depvars[3]][:]
1299            dnamesvar = ncobj.variables[depvars[0]].dimensions
1300
1301        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1302
1303        diagout, diagoutd, diagoutvd = compute_mslp(var0, var1, var2, var3, var4,    \
1304          dnamesvar, dvnamesvar)
1305
1306        ncvar.insert_variable(ncobj, 'psl', diagout, diagoutd, diagoutvd, newnc)
1307
1308# OMEGAw (omega, p, t) from NCL formulation (https://www.ncl.ucar.edu/Document/Functions/Contributed/omega_to_w.shtml)
1309    elif diag == 'OMEGAw':
1310           
1311        var0 = ncobj.variables[depvars[0]][:]
1312        var1 = ncobj.variables[depvars[1]][:]
1313        var2 = ncobj.variables[depvars[2]][:]
1314
1315        dnamesvar = ncobj.variables[depvars[0]].dimensions
1316        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1317
1318        diagout, diagoutd, diagoutvd = compute_OMEGAw(var0,var1,var2,dnamesvar,dvnamesvar)
1319
1320        ncvar.insert_variable(ncobj, 'wa', diagout, diagoutd, diagoutvd, newnc)
1321
1322# raintot: instantaneous total precipitation from WRF as (RAINC + RAINC) / dTime
1323    elif diag == 'RAINTOT':
1324
1325        var0 = ncobj.variables[depvars[0]]
1326        var1 = ncobj.variables[depvars[1]]
1327        if depvars[2] != 'WRFtime':
1328            var2 = ncobj.variables[depvars[2]]
1329        else:
1330            var2 = np.arange(var0.shape[0], dtype=int)
1331
1332        var = var0[:] + var1[:]
1333
1334        dnamesvar = var0.dimensions
1335        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1336
1337        diagout, diagoutd, diagoutvd = compute_deaccum(var,dnamesvar,dvnamesvar)
1338
1339# Transforming to a flux
1340        if var2.shape[0] > 1:
1341            if depvars[2] != 'WRFtime':
1342                dtimeunits = var2.getncattr('units')
1343                tunits = dtimeunits.split(' ')[0]
1344   
1345                dtime = (var2[1] - var2[0])*timeunits_seconds(tunits)
1346            else:
1347                var2 = ncobj.variables['Times']
1348                time1 = var2[0,:]
1349                time2 = var2[1,:]
1350                tmf1 = ''
1351                tmf2 = ''
1352                for ic in range(len(time1)):
1353                    tmf1 = tmf1 + time1[ic]
1354                    tmf2 = tmf2 + time2[ic]
1355                dtdate1 = dtime.datetime.strptime(tmf1,"%Y-%m-%d_%H:%M:%S")
1356                dtdate2 = dtime.datetime.strptime(tmf2,"%Y-%m-%d_%H:%M:%S")
1357                diffdate12 = dtdate2 - dtdate1
1358                dtime = diffdate12.total_seconds()
1359                print 'dtime:',dtime
1360        else:
1361            print warnmsg
1362            print '  ' + fname + ": only 1 time-step for '" + diag + "' !!"
1363            print '    leaving a zero value!'
1364            diagout = var0*0.
1365            dtime=1.
1366
1367        ncvar.insert_variable(ncobj, 'pr', diagout/dtime, diagoutd, diagoutvd, newnc)
1368
1369# rhs (psfc, t, q) from TimeSeries files
1370    elif diag == 'TSrhs':
1371           
1372        p0=100000.
1373        var0 = ncobj.variables[depvars[0]][:]
1374        var1 = (ncobj.variables[depvars[1]][:])*(var0/p0)**(2./7.)
1375        var2 = ncobj.variables[depvars[2]][:]
1376
1377        dnamesvar = ncobj.variables[depvars[0]].dimensions
1378        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1379
1380        diagout, diagoutd, diagoutvd = compute_rh(var0,var1,var2,dnamesvar,dvnamesvar)
1381
1382        ncvar.insert_variable(ncobj, 'hurs', diagout, diagoutd, diagoutvd, newnc)
1383
1384# td (psfc, t, q) from TimeSeries files
1385    elif diag == 'TStd' or diag == 'td':
1386           
1387        var0 = ncobj.variables[depvars[0]][:]
1388        var1 = ncobj.variables[depvars[1]][:] - 273.15
1389        var2 = ncobj.variables[depvars[2]][:]
1390
1391        dnamesvar = ncobj.variables[depvars[0]].dimensions
1392        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1393
1394        diagout, diagoutd, diagoutvd = compute_td(var0,var1,var2,dnamesvar,dvnamesvar)
1395
1396        ncvar.insert_variable(ncobj, 'tds', diagout, diagoutd, diagoutvd, newnc)
1397
1398# td (psfc, t, q) from TimeSeries files
1399    elif diag == 'TStdC' or diag == 'tdC':
1400           
1401        var0 = ncobj.variables[depvars[0]][:]
1402# Temperature is already in degrees Celsius
1403        var1 = ncobj.variables[depvars[1]][:]
1404        var2 = ncobj.variables[depvars[2]][:]
1405
1406        dnamesvar = ncobj.variables[depvars[0]].dimensions
1407        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1408
1409        diagout, diagoutd, diagoutvd = compute_td(var0,var1,var2,dnamesvar,dvnamesvar)
1410
1411        ncvar.insert_variable(ncobj, 'tds', diagout, diagoutd, diagoutvd, newnc)
1412
1413# wds (u, v)
1414    elif diag == 'TSwds' or diag == 'wds' :
1415 
1416        var0 = ncobj.variables[depvars[0]][:]
1417        var1 = ncobj.variables[depvars[1]][:]
1418
1419        dnamesvar = ncobj.variables[depvars[0]].dimensions
1420        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1421
1422        diagout, diagoutd, diagoutvd = compute_wds(var0,var1,dnamesvar,dvnamesvar)
1423
1424        ncvar.insert_variable(ncobj, 'wds', diagout, diagoutd, diagoutvd, newnc)
1425
1426# wss (u, v)
1427    elif diag == 'TSwss' or diag == 'wss':
1428           
1429        var0 = ncobj.variables[depvars[0]][:]
1430        var1 = ncobj.variables[depvars[1]][:]
1431
1432        dnamesvar = ncobj.variables[depvars[0]].dimensions
1433        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1434
1435        diagout, diagoutd, diagoutvd = compute_wss(var0,var1,dnamesvar,dvnamesvar)
1436
1437        ncvar.insert_variable(ncobj, 'wss', diagout, diagoutd, diagoutvd, newnc)
1438
1439# turbulence (var)
1440    elif diag == 'turbulence':
1441
1442        var0 = ncobj.variables[depvars][:]
1443
1444        dnamesvar = list(ncobj.variables[depvars].dimensions)
1445        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1446
1447        diagout, diagoutd, diagoutvd = compute_turbulence(var0,dnamesvar,dvnamesvar)
1448        valsvar = gen.variables_values(depvars)
1449
1450        newvarn = depvars + 'turb'
1451        print main + '; Lluis newvarn:', newvarn
1452        ncvar.insert_variable(ncobj, newvarn, diagout, diagoutd, 
1453          diagoutvd, newnc)
1454        print main + '; Lluis variables:', newnc.variables.keys()
1455        varobj = newnc.variables[newvarn]
1456        attrv = varobj.long_name
1457        attr = varobj.delncattr('long_name')
1458        newattr = ncvar.set_attribute(varobj, 'long_name', attrv +                   \
1459          " Taylor decomposition turbulence term")
1460
1461# WRFbils fom WRF as HFX + LH
1462    elif diag == 'WRFbils':
1463           
1464        var0 = ncobj.variables[depvars[0]][:]
1465        var1 = ncobj.variables[depvars[1]][:]
1466
1467        diagout = var0 + var1
1468        dnamesvar = list(ncobj.variables[depvars[0]].dimensions)
1469        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1470
1471        ncvar.insert_variable(ncobj, 'bils', diagout, dnamesvar, dvnamesvar, newnc)
1472
1473# WRFgeop geopotential from WRF as PH + PHB
1474    elif diag == 'WRFgeop':
1475        var0 = ncobj.variables[depvars[0]][:]
1476        var1 = ncobj.variables[depvars[1]][:]
1477
1478        # de-staggering geopotential
1479        diagout0 = var0 + var1
1480        dt = diagout0.shape[0]
1481        dz = diagout0.shape[1]
1482        dy = diagout0.shape[2]
1483        dx = diagout0.shape[3]
1484
1485        diagout = np.zeros((dt,dz-1,dy,dx), dtype=np.float)
1486        diagout = 0.5*(diagout0[:,1:dz,:,:]+diagout0[:,0:dz-1,:,:])
1487
1488        # Removing the nonChecking variable-dimensions from the initial list
1489        varsadd = []
1490        diagoutvd = list(dvnames)
1491        for nonvd in NONchkvardims:
1492            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1493            varsadd.append(nonvd)
1494
1495        ncvar.insert_variable(ncobj, 'zg', diagout, dnames, diagoutvd, newnc)
1496
1497# WRFp pressure from WRF as P + PB
1498    elif diag == 'WRFp':
1499           
1500        diagout = WRFp
1501
1502        ncvar.insert_variable(ncobj, 'pres', diagout, dnames, dvnames, newnc)
1503
1504# WRFpos
1505    elif diag == 'WRFpos':
1506           
1507        dnamesvar = ncobj.variables['MAPFAC_M'].dimensions
1508        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1509
1510        ncvar.insert_variable(ncobj, 'WRFpos', WRFpos, dnamesvar, dvnamesvar, newnc)
1511
1512# WRFprw WRF water vapour path WRFdens, QVAPOR
1513    elif diag == 'WRFprw':
1514           
1515        var0 = WRFdens
1516        var1 = ncobj.variables[depvars[1]]
1517
1518        dnamesvar = list(var1.dimensions)
1519        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1520
1521        diagout, diagoutd, diagoutvd = compute_prw(var0, var1, dnamesvar,dvnamesvar)
1522
1523        ncvar.insert_variable(ncobj, 'prw', diagout, diagoutd, diagoutvd, newnc)
1524
1525# WRFrh (P, T, QVAPOR)
1526    elif diag == 'WRFrh':
1527           
1528        dnamesvar = list(ncobj.variables[depvars[2]].dimensions)
1529        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1530
1531        ncvar.insert_variable(ncobj, 'hur', WRFrh, dnames, dvnames, newnc)
1532
1533# WRFrhs (PSFC, T2, Q2)
1534    elif diag == 'WRFrhs':
1535           
1536        var0 = ncobj.variables[depvars[0]][:]
1537        var1 = ncobj.variables[depvars[1]][:]
1538        var2 = ncobj.variables[depvars[2]][:]
1539
1540        dnamesvar = list(ncobj.variables[depvars[2]].dimensions)
1541        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1542
1543        diagout, diagoutd, diagoutvd = compute_rh(var0,var1,var2,dnamesvar,dvnamesvar)
1544        ncvar.insert_variable(ncobj, 'hurs', diagout, diagoutd, diagoutvd, newnc)
1545
1546# rvors (u10, v10, WRFpos)
1547    elif diag == 'WRFrvors':
1548           
1549        var0 = ncobj.variables[depvars[0]]
1550        var1 = ncobj.variables[depvars[1]]
1551
1552        diagout = rotational_z(var0, var1, distx)
1553
1554        dnamesvar = ncobj.variables[depvars[0]].dimensions
1555        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1556
1557        ncvar.insert_variable(ncobj, 'rvors', diagout, dnamesvar, dvnamesvar, newnc)
1558
1559# WRFt (T, P, PB)
1560    elif diag == 'WRFt':
1561        var0 = ncobj.variables[depvars[0]][:]
1562        var1 = ncobj.variables[depvars[1]][:]
1563        var2 = ncobj.variables[depvars[2]][:]
1564
1565        p0=100000.
1566        p=var1 + var2
1567
1568        WRFt = (var0 + 300.)*(p/p0)**(2./7.)
1569
1570        dnamesvar = list(ncobj.variables[depvars[0]].dimensions)
1571        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1572
1573        # Removing the nonChecking variable-dimensions from the initial list
1574        varsadd = []
1575        diagoutvd = list(dvnames)
1576        for nonvd in NONchkvardims:
1577            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1578            varsadd.append(nonvd)
1579
1580        ncvar.insert_variable(ncobj, 'ta', WRFt, dnames, diagoutvd, newnc)
1581
1582# WRFua (U, V, SINALPHA, COSALPHA) to be rotated !!
1583    elif diag == 'WRFua':
1584        var0 = ncobj.variables[depvars[0]][:]
1585        var1 = ncobj.variables[depvars[1]][:]
1586        var2 = ncobj.variables[depvars[2]][:]
1587        var3 = ncobj.variables[depvars[3]][:]
1588
1589        # un-staggering variables
1590        unstgdims = [var0.shape[0], var0.shape[1], var0.shape[2], var0.shape[3]-1]
1591        ua = np.zeros(tuple(unstgdims), dtype=np.float)
1592        unstgvar0 = np.zeros(tuple(unstgdims), dtype=np.float)
1593        unstgvar1 = np.zeros(tuple(unstgdims), dtype=np.float)
1594        unstgvar0 = 0.5*(var0[:,:,:,0:var0.shape[3]-1] + var0[:,:,:,1:var0.shape[3]])
1595        unstgvar1 = 0.5*(var1[:,:,0:var1.shape[2]-1,:] + var1[:,:,1:var1.shape[2],:])
1596
1597        for iz in range(var0.shape[1]):
1598            ua[:,iz,:,:] = unstgvar0[:,iz,:,:]*var3 - unstgvar1[:,iz,:,:]*var2
1599
1600#        dnamesvar = list(ncobj.variables[depvars[0]].dimensions)
1601        dnamesvar = ['Time','bottom_top','south_north','west_east']
1602        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1603
1604        ncvar.insert_variable(ncobj, 'ua', ua, dnames, dvnames, newnc)
1605
1606# WRFua (U, V, SINALPHA, COSALPHA) to be rotated !!
1607    elif diag == 'WRFva':
1608        var0 = ncobj.variables[depvars[0]][:]
1609        var1 = ncobj.variables[depvars[1]][:]
1610        var2 = ncobj.variables[depvars[2]][:]
1611        var3 = ncobj.variables[depvars[3]][:]
1612
1613        # un-staggering variables
1614        unstgdims = [var0.shape[0], var0.shape[1], var0.shape[2], var0.shape[3]-1]
1615        va = np.zeros(tuple(unstgdims), dtype=np.float)
1616        unstgvar0 = np.zeros(tuple(unstgdims), dtype=np.float)
1617        unstgvar1 = np.zeros(tuple(unstgdims), dtype=np.float)
1618        unstgvar0 = 0.5*(var0[:,:,:,0:var0.shape[3]-1] + var0[:,:,:,1:var0.shape[3]])
1619        unstgvar1 = 0.5*(var1[:,:,0:var1.shape[2]-1,:] + var1[:,:,1:var1.shape[2],:])
1620        for iz in range(var0.shape[1]):
1621            va[:,iz,:,:] = unstgvar0[:,iz,:,:]*var2 + unstgvar1[:,iz,:,:]*var3
1622
1623        dnamesvar = ['Time','bottom_top','south_north','west_east']
1624        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1625
1626        ncvar.insert_variable(ncobj, 'va', va, dnames, dvnames, newnc)
1627
1628# WRFtime
1629    elif diag == 'WRFtime':
1630           
1631        diagout = WRFtime
1632
1633        dnamesvar = ['Time']
1634        dvnamesvar = ['Times']
1635
1636        ncvar.insert_variable(ncobj, 'time', diagout, dnamesvar, dvnamesvar, newnc)
1637
1638# ws (U, V)
1639    elif diag == 'ws':
1640           
1641        var0 = ncobj.variables[depvars[0]][:]
1642        var1 = ncobj.variables[depvars[1]][:]
1643        # un-staggering variables
1644        unstgdims = [var0.shape[0], var0.shape[1], var0.shape[2], var0.shape[3]-1]
1645        va = np.zeros(tuple(unstgdims), dtype=np.float)
1646        unstgvar0 = np.zeros(tuple(unstgdims), dtype=np.float)
1647        unstgvar1 = np.zeros(tuple(unstgdims), dtype=np.float)
1648        unstgvar0 = 0.5*(var0[:,:,:,0:var0.shape[3]-1] + var0[:,:,:,1:var0.shape[3]])
1649        unstgvar1 = 0.5*(var1[:,:,0:var1.shape[2]-1,:] + var1[:,:,1:var1.shape[2],:])
1650
1651        dnamesvar = ['Time','bottom_top','south_north','west_east']
1652        diagout = np.sqrt(unstgvar0*unstgvar0 + unstgvar1*unstgvar1)
1653
1654#        dnamesvar = ncobj.variables[depvars[0]].dimensions
1655        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1656
1657        ncvar.insert_variable(ncobj, 'ws', diagout, dnamesvar, dvnamesvar, newnc)
1658
1659# wss (u10, v10)
1660    elif diag == 'wss':
1661           
1662        var0 = ncobj.variables[depvars[0]][:]
1663        var1 = ncobj.variables[depvars[1]][:]
1664
1665        diagout = np.sqrt(var0*var0 + var1*var1)
1666
1667        dnamesvar = ncobj.variables[depvars[0]].dimensions
1668        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1669
1670        ncvar.insert_variable(ncobj, 'wss', diagout, dnamesvar, dvnamesvar, newnc)
1671
1672# WRFheight height from WRF geopotential as WRFGeop/g
1673    elif diag == 'WRFheight':
1674           
1675        diagout = WRFgeop/grav
1676
1677        ncvar.insert_variable(ncobj, 'zhgt', diagout, dnames, dvnames, newnc)
1678
1679    else:
1680        print errormsg
1681        print '  ' + main + ": diagnostic '" + diag + "' not ready!!!"
1682        print '    available diagnostics: ', availdiags
1683        quit(-1)
1684
1685    newnc.sync()
1686    # Adding that additional variables required to compute some diagnostics which
1687    #   where not in the original file
1688    for vadd in varsadd:
1689        if not gen.searchInlist(newnc.variables.keys(),vadd):
1690            attrs = dictcompvars[vadd]
1691            vvn = attrs['name']
1692            if not gen.searchInlist(newnc.variables.keys(), vvn):
1693                iidvn = dvnames.index(vadd)
1694                dnn = dnames[iidvn]
1695                if vadd == 'WRFtime':
1696                    dvarvals = WRFtime[:]
1697                newvar = newnc.createVariable(vvn, 'f8', (dnn))
1698                newvar[:] = dvarvals
1699                for attn in attrs.keys():
1700                    if attn != 'name':
1701                        attv = attrs[attn]
1702                        ncvar.set_attribute(newvar, attn, attv)
1703
1704#   end of diagnostics
1705
1706# Global attributes
1707##
1708atvar = ncvar.set_attribute(newnc, 'program', 'diagnostics.py')
1709atvar = ncvar.set_attribute(newnc, 'version', '1.0')
1710atvar = ncvar.set_attribute(newnc, 'author', 'Fita Borrell, Lluis')
1711atvar = ncvar.set_attribute(newnc, 'institution', 'Laboratoire Meteorologie ' +      \
1712  'Dynamique')
1713atvar = ncvar.set_attribute(newnc, 'university', 'Universite Pierre et Marie ' +     \
1714  'Curie -- Jussieu')
1715atvar = ncvar.set_attribute(newnc, 'centre', 'Centre national de la recherche ' +    \
1716  'scientifique')
1717atvar = ncvar.set_attribute(newnc, 'city', 'Paris')
1718atvar = ncvar.set_attribute(newnc, 'original_file', opts.ncfile)
1719
1720gorigattrs = ncobj.ncattrs()
1721
1722for attr in gorigattrs:
1723    attrv = ncobj.getncattr(attr)
1724    atvar = ncvar.set_attribute(newnc, attr, attrv)
1725
1726ncobj.close()
1727newnc.close()
1728
1729print '\n' + main + ': successfull writting of diagnostics file "' + ofile + '" !!!'
Note: See TracBrowser for help on using the repository browser.