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

Last change on this file since 2296 was 2285, checked in by lfita, 6 years ago

Fixing `compute_cellbnds', right values at the x-axis borders

File size: 84.3 KB
Line 
1# Python script to comput diagnostics
2# From L. Fita work in different places: CCRC (Australia), LMD (France)
3# More information at: http://www.xn--llusfb-5va.cat/python/PyNCplot
4#
5# pyNCplot and its component nc_var.py comes with ABSOLUTELY NO WARRANTY.
6# This work is licendes under a Creative Commons
7#   Attribution-ShareAlike 4.0 International License (http://creativecommons.org/licenses/by-sa/4.0)
8#
9# L. Fita, CIMA. CONICET-UBA, CNRS UMI-IFAECI, C.A. Buenos Aires, Argentina
10# File diagnostics.inf provides the combination of variables to get the desired diagnostic
11#   To be used with module_ForDiagnostics.F90, module_ForDiagnosticsVars.F90, module_generic.F90
12#      foudre: f2py -m module_ForDiagnostics --f90exec=/usr/bin/gfortran-4.7 -c module_generic.F90 module_ForDiagnosticsVars.F90 module_ForDiagnostics.F90 >& run_f2py.log
13#      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
14
15## e.g. # diagnostics.py -d 'Time@WRFtime,bottom_top@ZNU,south_north@XLAT,west_east@XLONG' -v 'clt|CLDFRA,cllmh|CLDFRA@WRFp,RAINTOT|RAINC@RAINNC@RAINSH@XTIME' -f WRF_LMDZ/NPv31/wrfout_d01_1980-03-01_00:00:00
16## e.g. # diagnostics.py -f /home/lluis/PY/diagnostics.inf -d variable_combo -v WRFprc
17
18# Available general pupose diagnostics (model independent) providing (varv1, varv2, ..., dimns, dimvns)
19# compute_accum: Function to compute the accumulation of a variable
20# compute_cllmh: Function to compute cllmh: low/medium/hight cloud fraction following
21#   newmicro.F90 from LMDZ compute_clt(cldfra, pres, dimns, dimvns)
22# compute_clt: Function to compute the total cloud fraction following 'newmicro.F90' from LMDZ
23# compute_clivi: Function to compute cloud-ice water path (clivi)
24# compute_clwvl: Function to compute condensed water path (clwvl)
25# compute_deaccum: Function to compute the deaccumulation of a variable
26# compute_mslp: Function to compute mslp: mean sea level pressure following p_interp.F90 from WRF
27# compute_OMEGAw: Function to transform OMEGA [Pas-1] to velocities [ms-1]
28# compute_prw: Function to compute water vapour path (prw)
29# compute_range_faces: Function to compute faces [uphill, valley, downhill] of sections of a mountain
30#   range, along a given face
31# compute_rh: Function to compute relative humidity following 'Tetens' equation (T,P) ...'
32# compute_td: Function to compute the dew point temperature
33# compute_turbulence: Function to compute the rubulence term of the Taylor's decomposition ...'
34# compute_wds: Function to compute the wind direction
35# compute_wss: Function to compute the wind speed
36# compute_WRFuava: Function to compute geographical rotated WRF 3D winds
37# compute_WRFuasvas: Fucntion to compute geographical rotated WRF 2-meter winds
38# derivate_centered: Function to compute the centered derivate of a given field
39# def Forcompute_cllmh: Function to compute cllmh: low/medium/hight cloud fraction following newmicro.F90 from LMDZ via Fortran subroutine
40# Forcompute_clt: Function to compute the total cloud fraction following 'newmicro.F90' from LMDZ via a Fortran module
41# Forcompute_psl_ptarget: Function to compute the sea-level pressure following target_pressure value found in `p_interp.F'
42
43# Others just providing variable values
44# var_cllmh: Fcuntion to compute cllmh on a 1D column
45# var_clt: Function to compute the total cloud fraction following 'newmicro.F90' from LMDZ using 1D vertical column values
46# var_mslp: Fcuntion to compute mean sea-level pressure
47# var_virtualTemp: This function returns virtual temperature in K,
48# var_WRFtime: Function to copmute CFtimes from WRFtime variable
49# rotational_z: z-component of the rotatinoal of horizontal vectorial field
50# turbulence_var: Function to compute the Taylor's decomposition turbulence term from a a given variable
51# timeoverthres: When a given variable [varname] overpass a given [value]. Being [CFvarn] the name of the diagnostics in
52#   variables_values.dat
53# timemax ([varname], time). When a given variable [varname] got its maximum
54
55from optparse import OptionParser
56import numpy as np
57from netCDF4 import Dataset as NetCDFFile
58import os
59import re
60import nc_var_tools as ncvar
61import generic_tools as gen
62import datetime as dtime
63import module_ForDiag as fdin
64import module_ForDef as fdef
65import diag_tools as diag
66
67main = 'diagnostics.py'
68errormsg = 'ERROR -- error -- ERROR -- error'
69warnmsg = 'WARNING -- warning -- WARNING -- warning'
70
71# Constants
72grav = 9.81
73
74
75####### ###### ##### #### ### ## #
76comboinf="\nIF -d 'variable_combo', provides information of the combination to obtain -v [varn] with the ASCII file with the combinations as -f [combofile]"
77
78parser = OptionParser()
79parser.add_option("-f", "--netCDF_file", dest="ncfile", help="file to use", metavar="FILE")
80parser.add_option("-d", "--dimensions", dest="dimns", 
81  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). NOTE: same order as in file!!!!" + comboinf, 
82  metavar="LABELS")
83parser.add_option("-v", "--variables", dest="varns", 
84  help=" [varn1]|[var11]@[...[varN1]],[...,[varnM]|[var1M]@[...[varLM]]] ',' list of variables to compute [varnK] and its necessary ones [var1K]...[varPK]", metavar="VALUES")
85
86(opts, args) = parser.parse_args()
87
88#######    #######
89## MAIN
90    #######
91availdiags = ['ACRAINTOT', 'accum', 'clt', 'cllmh', 'convini', 'deaccum', 'fog_K84', \
92  'fog_RUC', 'LMDZrh', 'mslp', 'OMEGAw', 'RAINTOT', 'range_faces',                   \
93  'rvors', 'td', 'timemax', 'timeoverthres', 'turbulence', 'uavaFROMwswd',           \
94  'WRFbnds', 'WRFcape_afwa', 'WRFclivi', 'WRFclwvi', 'WRF_denszint', 'WRFgeop',      \
95  'WRFmrso', 'WRFmrsos', 'WRFpotevap_orPM', 'WRFp', 'WRFpsl_ecmwf',                  \
96  'WRFpsl_ptarget', 'WRFrvors', 'WRFslw', 'ws', 'wds', 'wss', 'WRFheight',           \
97  'WRFheightrel', 'WRFtda', 'WRFtdas', 'WRFua', 'WRFva', 'WRFzwind', 'WRFzwind_log', \
98  'WRFzwindMO']
99
100methods = ['accum', 'deaccum']
101
102# Variables not to check
103NONcheckingvars = ['accum', 'cllmh', 'deaccum', 'face', 'LONLATdxdy',                \
104  'reglonlatbnds', 'TSrhs', 'TStd', 'TSwds', 'TSwss',                                \
105  'WRFbils',  'WRFbnds',                                                             \
106  'WRFclivi', 'WRFclwvi', 'WRFdens', 'WRFdx', 'WRFdxdy', 'WRFdxdywps', 'WRFdy',      \
107  'WRFgeop', 'WRFp', 'WRFtd',                                                        \
108  'WRFpos', 'WRFprc', 'WRFprls', 'WRFrh', 'LMDZrh', 'LMDZrhs',                       \
109  'WRFrhs', 'WRFrvors',                                                              \
110  'WRFt', 'WRFtime', 'WRFua', 'WRFva', 'WRFwds', 'WRFwss', 'WRFheight', 'WRFz',      \
111  'WRFzg']
112
113# diagnostics not to check their dependeny
114NONcheckdepvars = ['accum', 'deaccum', 'timeoverthres', 'WRF_denszint',              \
115  'WRFzwind_log', 'WRFzwind', 'WRFzwindMO']
116
117NONchkvardims = ['WRFtime']
118
119ofile = 'diagnostics.nc'
120
121dimns = opts.dimns
122varns = opts.varns
123
124# Special method. knowing variable combination
125##
126if opts.dimns == 'variable_combo':
127    print warnmsg
128    print '  ' + main + ': knowing variable combination !!!'
129    combination = variable_combo(opts.varns,opts.ncfile)
130    print '     COMBO: ' + combination
131    quit(-1)
132
133if opts.ncfile is None:
134    print errormsg
135    print '   ' + main + ": No file provided !!"
136    print '     is mandatory to provide a file -f [filename]'
137    quit(-1)
138
139if opts.dimns is None:
140    print errormsg
141    print '   ' + main + ": No description of dimensions are provided !!"
142    print '     is mandatory to provide description of dimensions as -d [dimn]@[vardimname],... '
143    quit(-1)
144
145if opts.varns is None:
146    print errormsg
147    print '   ' + main + ": No variable to diagnose is provided !!"
148    print '     is mandatory to provide a variable to diagnose as -v [diagn]|[varn1]@... '
149    quit(-1)
150
151if not os.path.isfile(opts.ncfile):
152    print errormsg
153    print '   ' + main + ": file '" + opts.ncfile + "' does not exist !!"
154    quit(-1)
155
156ncobj = NetCDFFile(opts.ncfile, 'r')
157
158# Looking for specific variables that might be use in more than one diagnostic
159WRFgeop_compute = False
160WRFp_compute = False
161WRFt_compute = False
162WRFrh_compute = False
163WRFght_compute = False
164WRFdens_compute = False
165WRFpos_compute = False
166WRFtime_compute = False
167WRFz_compute = False
168WRFdxdy_compute = False
169WRFdxdywps_compute = False
170LONLATdxdy_compute = False
171
172# File creation
173newnc = NetCDFFile(ofile,'w')
174
175# dimensions
176dimvalues = dimns.split(',')
177dnames = []
178dvnames = []
179
180for dimval in dimvalues:
181    dn = dimval.split('@')[0]
182    dnv = dimval.split('@')[1]
183    dnames.append(dn)
184    dvnames.append(dnv)
185    # Is there any dimension-variable which should be computed?
186    if dnv == 'WRFgeop':WRFgeop_compute = True
187    if dnv == 'WRFp': WRFp_compute = True
188    if dnv == 'WRFt': WRFt_compute = True
189    if dnv == 'WRFrh': WRFrh_compute = True
190    if dnv == 'WRFght': WRFght_compute = True
191    if dnv == 'WRFdens': WRFdens_compute = True
192    if dnv == 'WRFpos': WRFpos_compute = True
193    if dnv == 'WRFtime': WRFtime_compute = True
194    if dnv == 'WRFz':WRFz_compute = True
195    if dnv == 'WRFdxdy':WRFdxdy_compute = True
196    if dnv == 'WRFdxdywps':WRFdxdywps_compute = True
197    if dnv == 'LONLATdxdy':LONLATdxdy_compute = True
198
199# diagnostics to compute
200diags = varns.split(',')
201Ndiags = len(diags)
202
203for idiag in range(Ndiags):
204    if diags[idiag].split('|')[1].find('@') == -1:
205        depvars = diags[idiag].split('|')[1]
206        if depvars == 'WRFgeop':WRFgeop_compute = True
207        if depvars == 'WRFp': WRFp_compute = True
208        if depvars == 'WRFt': WRFt_compute = True
209        if depvars == 'WRFrh': WRFrh_compute = True
210        if depvars == 'WRFght': WRFght_compute = True
211        if depvars == 'WRFdens': WRFdens_compute = True
212        if depvars == 'WRFpos': WRFpos_compute = True
213        if depvars == 'WRFtime': WRFtime_compute = True
214        if depvars == 'WRFz': WRFz_compute = True
215    else:
216        depvars = diags[idiag].split('|')[1].split('@')
217        if gen.searchInlist(depvars, 'WRFgeop'): WRFgeop_compute = True
218        if gen.searchInlist(depvars, 'WRFp'): WRFp_compute = True
219        if gen.searchInlist(depvars, 'WRFt'): WRFt_compute = True
220        if gen.searchInlist(depvars, 'WRFrh'): WRFrh_compute = True
221        if gen.searchInlist(depvars, 'WRFght'): WRFght_compute = True
222        if gen.searchInlist(depvars, 'WRFdens'): WRFdens_compute = True
223        if gen.searchInlist(depvars, 'WRFpos'): WRFpos_compute = True
224        if gen.searchInlist(depvars, 'WRFtime'): WRFtime_compute = True
225        if gen.searchInlist(depvars, 'WRFz'): WRFz_compute = True
226        if gen.searchInlist(depvars, 'WRFdxdy'): WRFdxdy_compute = True
227        if gen.searchInlist(depvars, 'WRFdxdywps'): WRFdxdywps_compute = True
228        if gen.searchInlist(depvars, 'LONLATdxdy'): LONLATdxdy_compute = True
229
230# Dictionary with the new computed variables to be able to add them
231dictcompvars = {}
232if WRFgeop_compute:
233    print '  ' + main + ': Retrieving geopotential value from WRF as PH + PHB'
234    dimv = ncobj.variables['PH'].shape
235    WRFgeop = ncobj.variables['PH'][:] + ncobj.variables['PHB'][:]
236
237    # Attributes of the variable
238    Vvals = gen.variables_values('WRFgeop')
239    dictcompvars['WRFgeop'] = {'name': Vvals[0], 'standard_name': Vvals[1],          \
240      'long_name': Vvals[4].replace('|',' '), 'units': Vvals[5]}
241
242if WRFp_compute:
243    print '  ' + main + ': Retrieving pressure value from WRF as P + PB'
244    dimv = ncobj.variables['P'].shape
245    WRFp = ncobj.variables['P'][:] + ncobj.variables['PB'][:]
246
247    # Attributes of the variable
248    Vvals = gen.variables_values('WRFp')
249    dictcompvars['WRFgeop'] = {'name': Vvals[0], 'standard_name': Vvals[1],          \
250      'long_name': Vvals[4].replace('|',' '), 'units': Vvals[5]}
251
252if WRFght_compute:
253    print '    ' + main + ': computing geopotential height from WRF as PH + PHB ...' 
254    WRFght = ncobj.variables['PH'][:] + ncobj.variables['PHB'][:]
255
256    # Attributes of the variable
257    Vvals = gen.variables_values('WRFght')
258    dictcompvars['WRFgeop'] = {'name': Vvals[0], 'standard_name': Vvals[1],          \
259      'long_name': Vvals[4].replace('|',' '), 'units': Vvals[5]}
260
261if WRFrh_compute:
262    print '    ' + main + ": computing relative humidity from WRF as 'Tetens'" +     \
263      ' equation (T,P) ...'
264    p0=100000.
265    p=ncobj.variables['P'][:] + ncobj.variables['PB'][:]
266    tk = (ncobj.variables['T'][:] + 300.)*(p/p0)**(2./7.)
267    qv = ncobj.variables['QVAPOR'][:]
268
269    data1 = 10.*0.6112*np.exp(17.67*(tk-273.16)/(tk-29.65))
270    data2 = 0.622*data1/(0.01*p-(1.-0.622)*data1)
271
272    WRFrh = qv/data2
273
274    # Attributes of the variable
275    Vvals = gen.variables_values('WRFrh')
276    dictcompvars['WRFrh'] = {'name': Vvals[0], 'standard_name': Vvals[1],            \
277      'long_name': Vvals[4].replace('|',' '), 'units': Vvals[5]}
278
279if WRFt_compute:
280    print '    ' + main + ': computing temperature from WRF as inv_potT(T + 300) ...'
281    p0=100000.
282    p=ncobj.variables['P'][:] + ncobj.variables['PB'][:]
283
284    WRFt = (ncobj.variables['T'][:] + 300.)*(p/p0)**(2./7.)
285
286    # Attributes of the variable
287    Vvals = gen.variables_values('WRFt')
288    dictcompvars['WRFt'] = {'name': Vvals[0], 'standard_name': Vvals[1],             \
289      'long_name': Vvals[4].replace('|',' '), 'units': Vvals[5]}
290
291if WRFdens_compute:
292    print '    ' + main + ': computing air density from WRF as ((MU + MUB) * ' +     \
293      'DNW)/g ...'
294
295# Just we need in in absolute values: Size of the central grid cell
296##    dxval = ncobj.getncattr('DX')
297##    dyval = ncobj.getncattr('DY')
298##    mapfac = ncobj.variables['MAPFAC_M'][:]
299##    area = dxval*dyval*mapfac
300
301    mu = (ncobj.variables['MU'][:] + ncobj.variables['MUB'][:])
302    dnw = ncobj.variables['DNW'][:]
303
304    WRFdens = np.zeros((mu.shape[0], dnw.shape[1], mu.shape[1], mu.shape[2]),        \
305      dtype=np.float)
306    levval = np.zeros((mu.shape[1], mu.shape[2]), dtype=np.float)
307
308    for it in range(mu.shape[0]):
309        for iz in range(dnw.shape[1]):
310            levval.fill(np.abs(dnw[it,iz]))
311            WRFdens[it,iz,:,:] = levval
312            WRFdens[it,iz,:,:] = mu[it,:,:]*WRFdens[it,iz,:,:]/grav
313
314    # Attributes of the variable
315    Vvals = gen.variables_values('WRFdens')
316    dictcompvars['WRFdens'] = {'name': Vvals[0], 'standard_name': Vvals[1],          \
317      'long_name': Vvals[4].replace('|',' '), 'units': Vvals[5]}
318
319if WRFpos_compute:
320# WRF positions from the lowest-leftest corner of the matrix
321    print '    ' + main + ': computing position from MAPFAC_M as sqrt(DY*j**2 + ' +  \
322      'DX*x**2)*MAPFAC_M ...'
323
324    mapfac = ncobj.variables['MAPFAC_M'][:]
325
326    distx = np.float(ncobj.getncattr('DX'))
327    disty = np.float(ncobj.getncattr('DY'))
328
329    print 'distx:',distx,'disty:',disty
330
331    dx = mapfac.shape[2]
332    dy = mapfac.shape[1]
333    dt = mapfac.shape[0]
334
335    WRFpos = np.zeros((dt, dy, dx), dtype=np.float)
336
337    for i in range(1,dx):
338        WRFpos[0,0,i] = distx*i/mapfac[0,0,i]
339    for j in range(1,dy):
340        i=0
341        WRFpos[0,j,i] = WRFpos[0,j-1,i] + disty/mapfac[0,j,i]
342        for i in range(1,dx):
343#            WRFpos[0,j,i] = np.sqrt((disty*j)**2. + (distx*i)**2.)/mapfac[0,j,i]
344#            WRFpos[0,j,i] = np.sqrt((disty*j)**2. + (distx*i)**2.)
345             WRFpos[0,j,i] = WRFpos[0,j,i-1] + distx/mapfac[0,j,i]
346
347    for it in range(1,dt):
348        WRFpos[it,:,:] = WRFpos[0,:,:]
349
350if WRFtime_compute:
351    print '    ' + main + ': computing time from WRF as CFtime(Times) ...'
352
353    refdate='19491201000000'
354    tunitsval='minutes'
355
356    timeobj = ncobj.variables['Times']
357    timewrfv = timeobj[:]
358
359    yrref=refdate[0:4]
360    monref=refdate[4:6]
361    dayref=refdate[6:8]
362    horref=refdate[8:10]
363    minref=refdate[10:12]
364    secref=refdate[12:14]
365
366    refdateS = yrref + '-' + monref + '-' + dayref + ' ' + horref + ':' + minref +   \
367      ':' + secref
368
369
370    if len(timeobj.shape) == 2:
371        dt = timeobj.shape[0]
372    else:
373        dt = 1
374    WRFtime = np.zeros((dt), dtype=np.float)
375
376    if len(timeobj.shape) == 2:
377        for it in range(dt):
378            wrfdates = gen.datetimeStr_conversion(timewrfv[it,:],'WRFdatetime',      \
379              'matYmdHMS')
380            WRFtime[it] = gen.realdatetime1_CFcompilant(wrfdates, refdate, tunitsval)
381    else:
382        wrfdates = gen.datetimeStr_conversion(timewrfv[:],'WRFdatetime',             \
383          'matYmdHMS')
384        WRFtime[0] = gen.realdatetime1_CFcompilant(wrfdates, refdate, tunitsval)
385
386    tunits = tunitsval + ' since ' + refdateS
387
388    # Attributes of the variable
389    dictcompvars['WRFtime'] = {'name': 'time', 'standard_name': 'time',              \
390      'long_name': 'time', 'units': tunits, 'calendar': 'gregorian'}
391
392if WRFz_compute:
393    print '  ' + main + ': Retrieving z: height above surface value from WRF as ' +  \
394      'unstagger(PH + PHB)/9.8-hgt'
395    dimv = ncobj.variables['PH'].shape
396    WRFzg = (ncobj.variables['PH'][:] + ncobj.variables['PHB'][:])/9.8
397
398    unzgd = (dimv[0], dimv[1]-1, dimv[2], dimv[3])
399    unzg = np.zeros(unzgd, dtype=np.float)
400    unzg = 0.5*(WRFzg[:,0:dimv[1]-1,:,:] + WRFzg[:,1:dimv[1],:,:])
401
402    WRFz = np.zeros(unzgd, dtype=np.float)
403    for iz in range(dimv[1]-1):
404        WRFz[:,iz,:,:] = unzg[:,iz,:,:] - ncobj.variables['HGT'][:]
405
406    # Attributes of the variable
407    Vvals = gen.variables_values('WRFz')
408    dictcompvars['WRFz'] = {'name': Vvals[0], 'standard_name': Vvals[1],             \
409      'long_name': Vvals[4].replace('|',' '), 'units': Vvals[5]}
410
411if WRFdxdy_compute:
412    print '  ' + main + ': Retrieving dxdy: real distance between grid points ' +    \
413      'from WRF as dx=(XLONG(i+1)-XLONG(i))*DX/MAPFAC_M, dy=(XLAT(j+1)-XLAT(i))*DY/'+\
414      'MAPFAC_M, ds=sqrt(dx**2+dy**2)'
415    dimv = ncobj.variables['XLONG'].shape
416    WRFlon = ncobj.variables['XLONG'][0,:,:]
417    WRFlat = ncobj.variables['XLAT'][0,:,:]
418    WRFmapfac_m = ncobj.variables['MAPFAC_M'][0,:,:]
419    DX = ncobj.DX
420    DY = ncobj.DY
421
422    dimx = dimv[2]
423    dimy = dimv[1]
424
425    WRFdx = np.zeros((dimy,dimx), dtype=np.float)
426    WRFdy = np.zeros((dimy,dimx), dtype=np.float)
427
428    WRFdx[:,0:dimx-1]=(WRFlon[:,1:dimx]-WRFlon[:,0:dimx-1])*DX/WRFmapfac_m[:,0:dimx-1]
429    WRFdy[0:dimy-1,:]=(WRFlat[1:dimy,:]-WRFlat[0:dimy-1,:])*DY/WRFmapfac_m[0:dimy-1,:]
430    WRFds = np.sqrt(WRFdx**2 + WRFdy**2)
431
432    # Attributes of the variable
433    Vvals = gen.variables_values('WRFdx')
434    dictcompvars['WRFdx'] = {'name': Vvals[0], 'standard_name': Vvals[1],             \
435      'long_name': Vvals[4].replace('|',' '), 'units': Vvals[5]}
436    Vvals = gen.variables_values('WRFdy')
437    dictcompvars['WRFdy'] = {'name': Vvals[0], 'standard_name': Vvals[1],             \
438      'long_name': Vvals[4].replace('|',' '), 'units': Vvals[5]}
439    Vvals = gen.variables_values('WRFds')
440    dictcompvars['WRFds'] = {'name': Vvals[0], 'standard_name': Vvals[1],            \
441      'long_name': Vvals[4].replace('|',' '), 'units': Vvals[5]}
442
443if WRFdxdywps_compute:
444    print '  ' + main + ': Retrieving dxdy: real distance between grid points ' +    \
445      'from wpsWRF as dx=(XLONG_M(i+1)-XLONG_M(i))*DX/MAPFAC_M, ' +                  \
446      'dy=(XLAT_M(j+1)-XLAT_M(i))*DY/MAPFAC_M, ds=sqrt(dx**2+dy**2)'
447    dimv = ncobj.variables['XLONG_M'].shape
448    WRFlon = ncobj.variables['XLONG_M'][0,:,:]
449    WRFlat = ncobj.variables['XLAT_M'][0,:,:]
450    WRFmapfac_m = ncobj.variables['MAPFAC_M'][0,:,:]
451    DX = ncobj.DX
452    DY = ncobj.DY
453
454    dimx = dimv[2]
455    dimy = dimv[1]
456
457    WRFdx = np.zeros((dimy,dimx), dtype=np.float)
458    WRFdy = np.zeros((dimy,dimx), dtype=np.float)
459
460    WRFdx[:,0:dimx-1]=(WRFlon[:,1:dimx]-WRFlon[:,0:dimx-1])*DX/WRFmapfac_m[:,0:dimx-1]
461    WRFdy[0:dimy-1,:]=(WRFlat[1:dimy,:]-WRFlat[0:dimy-1,:])*DY/WRFmapfac_m[0:dimy-1,:]
462    WRFds = np.sqrt(WRFdx**2 + WRFdy**2)
463
464    # Attributes of the variable
465    Vvals = gen.variables_values('WRFdx')
466    dictcompvars['WRFdx'] = {'name': Vvals[0], 'standard_name': Vvals[1],             \
467      'long_name': Vvals[4].replace('|',' '), 'units': Vvals[5]}
468    Vvals = gen.variables_values('WRFdy')
469    dictcompvars['WRFdy'] = {'name': Vvals[0], 'standard_name': Vvals[1],             \
470      'long_name': Vvals[4].replace('|',' '), 'units': Vvals[5]}
471    Vvals = gen.variables_values('WRFds')
472    dictcompvars['WRFds'] = {'name': Vvals[0], 'standard_name': Vvals[1],            \
473      'long_name': Vvals[4].replace('|',' '), 'units': Vvals[5]}
474
475if LONLATdxdy_compute:
476    print '  ' + main + ': Retrieving dxdy: real distance between grid points ' +    \
477      'from a regular lonlat projection as dx=(lon[i+1]-lon[i])*raddeg*Rearth*' +    \
478      'cos(abs(lat[i])); dy=(lat[j+1]-lat[i])*raddeg*Rearth; ds=sqrt(dx**2+dy**2); '+\
479      'raddeg = pi/180; Rearth=6370.0e03'
480    dimv = ncobj.variables['lon'].shape
481    lon = ncobj.variables['lon'][:]
482    lat = ncobj.variables['lat'][:]
483
484    WRFlon, WRFlat = gen.lonlat2D(lon,lat)
485
486    dimx = WRFlon.shape[1]
487    dimy = WRFlon.shape[0]
488
489    WRFdx = np.zeros((dimy,dimx), dtype=np.float)
490    WRFdy = np.zeros((dimy,dimx), dtype=np.float)
491
492    raddeg = np.pi/180.
493
494    Rearth = fdef.module_definitions.earthradii
495
496    WRFdx[:,0:dimx-1]=(WRFlon[:,1:dimx]-WRFlon[:,0:dimx-1])*raddeg*Rearth*           \
497      np.cos(np.abs(WRFlat[:,0:dimx-1]*raddeg))
498    WRFdy[0:dimy-1,:]=(WRFlat[1:dimy,:]-WRFlat[0:dimy-1,:])*raddeg*Rearth
499    WRFds = np.sqrt(WRFdx**2 + WRFdy**2)
500
501    # Attributes of the variable
502    Vvals = gen.variables_values('WRFdx')
503    dictcompvars['WRFdx'] = {'name': Vvals[0], 'standard_name': Vvals[1],             \
504      'long_name': Vvals[4].replace('|',' '), 'units': Vvals[5]}
505    Vvals = gen.variables_values('WRFdy')
506    dictcompvars['WRFdy'] = {'name': Vvals[0], 'standard_name': Vvals[1],             \
507      'long_name': Vvals[4].replace('|',' '), 'units': Vvals[5]}
508    Vvals = gen.variables_values('WRFds')
509    dictcompvars['WRFds'] = {'name': Vvals[0], 'standard_name': Vvals[1],             \
510      'long_name': Vvals[4].replace('|',' '), 'units': Vvals[5]}
511
512### ## #
513# Going for the diagnostics
514### ## #
515print '  ' + main + ' ...'
516varsadd = []
517
518for idiag in range(Ndiags):
519    print '    diagnostic:',diags[idiag]
520    diagn = diags[idiag].split('|')[0]
521    depvars = diags[idiag].split('|')[1].split('@')
522    if not gen.searchInlist(NONcheckdepvars, diagn):
523        if diags[idiag].split('|')[1].find('@') != -1:
524            depvars = diags[idiag].split('|')[1].split('@')
525            if depvars[0] == 'deaccum': diagn='deaccum'
526            if depvars[0] == 'accum': diagn='accum'
527            for depv in depvars:
528                # Checking without extra arguments of a depending variable (':', separated)
529                if depv.find(':') != -1: depv=depv.split(':')[0]
530                if not ncobj.variables.has_key(depv) and not                         \
531                  gen.searchInlist(NONcheckingvars, depv) and                        \
532                  not gen.searchInlist(methods, depv) and not depvars[0] == 'deaccum'\
533                  and not depvars[0] == 'accum' and not depv[0:2] == 'z=':
534                    print errormsg
535                    print '  ' + main + ": file '" + opts.ncfile +                   \
536                      "' does not have variable '" + depv + "' !!"
537                    quit(-1)
538        else:
539            depvars = diags[idiag].split('|')[1]
540            if not ncobj.variables.has_key(depvars) and not                          \
541              gen.searchInlist(NONcheckingvars, depvars) and                         \
542              not gen.searchInlist(methods, depvars):
543                print errormsg
544                print '  ' + main + ": file '" + opts.ncfile +                       \
545                  "' does not have variable '" + depvars + "' !!"
546                quit(-1)
547
548    print "\n    Computing '" + diagn + "' from: ", depvars, '...'
549
550# acraintot: accumulated total precipitation from WRF RAINC, RAINNC, RAINSH
551    if diagn == 'ACRAINTOT':
552           
553        var0 = ncobj.variables[depvars[0]]
554        var1 = ncobj.variables[depvars[1]]
555        var2 = ncobj.variables[depvars[2]]
556
557        diagout = var0[:] + var1[:] + var2[:]
558
559        dnamesvar = var0.dimensions
560        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
561
562        # Removing the nonChecking variable-dimensions from the initial list
563        varsadd = []
564        for nonvd in NONchkvardims:
565            if gen.searchInlist(dvnamesvar,nonvd): dvnamesvar.remove(nonvd)
566            varsadd.append(nonvd)
567
568        ncvar.insert_variable(ncobj, 'pracc', diagout, dnamesvar, dvnamesvar, newnc)
569
570# accum: acumulation of any variable as (Variable, time [as [tunits]
571#   from/since ....], newvarname)
572    elif diagn == 'accum':
573
574        var0 = ncobj.variables[depvars[0]]
575        var1 = ncobj.variables[depvars[1]]
576
577        dnamesvar = var0.dimensions
578        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
579
580        diagout, diagoutd, diagoutvd = diag.compute_accum(var0,dnamesvar,dvnamesvar)
581        # Removing the nonChecking variable-dimensions from the initial list
582        varsadd = []
583        diagoutvd = list(dvnames)
584        for nonvd in NONchkvardims:
585            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
586            varsadd.append(nonvd)
587
588        CFvarn = ncvar.variables_values(depvars[0])[0]
589
590# Removing the flux
591        if depvars[1] == 'XTIME':
592            dtimeunits = var1.getncattr('description')
593            tunits = dtimeunits.split(' ')[0]
594        else:
595            dtimeunits = var1.getncattr('units')
596            tunits = dtimeunits.split(' ')[0]
597
598        dtime = (var1[1] - var1[0])*diag.timeunits_seconds(tunits)
599
600        ncvar.insert_variable(ncobj, CFvarn + 'acc', diagout*dtime, diagoutd, diagoutvd, newnc)
601
602# cllmh with cldfra, pres
603    elif diagn == 'cllmh':
604           
605        var0 = ncobj.variables[depvars[0]]
606        if depvars[1] == 'WRFp':
607            var1 = WRFp
608        else:
609            var01 = ncobj.variables[depvars[1]]
610            if len(size(var1.shape)) < len(size(var0.shape)):
611                var1 = np.brodcast_arrays(var01,var0)[0]
612            else:
613                var1 = var01
614
615        diagout, diagoutd, diagoutvd = diag.Forcompute_cllmh(var0,var1,dnames,dvnames)
616
617        # Removing the nonChecking variable-dimensions from the initial list
618        varsadd = []
619        for nonvd in NONchkvardims:
620            if gen.searchInlist(diagoutvd,nonvd): diagoutvd.remove(nonvd)
621            varsadd.append(nonvd)
622
623        ncvar.insert_variable(ncobj, 'cll', diagout[0,:], diagoutd, diagoutvd, newnc)
624        ncvar.insert_variable(ncobj, 'clm', diagout[1,:], diagoutd, diagoutvd, newnc)
625        ncvar.insert_variable(ncobj, 'clh', diagout[2,:], diagoutd, diagoutvd, newnc)
626
627# clt with cldfra
628    elif diagn == 'clt':
629           
630        var0 = ncobj.variables[depvars]
631        diagout, diagoutd, diagoutvd = diag.Forcompute_clt(var0,dnames,dvnames)
632
633        # Removing the nonChecking variable-dimensions from the initial list
634        varsadd = []
635        for nonvd in NONchkvardims:
636            if gen.searchInlist(diagoutvd,nonvd): diagoutvd.remove(nonvd)
637            varsadd.append(nonvd)
638           
639        ncvar.insert_variable(ncobj, 'clt', diagout, diagoutd, diagoutvd, newnc)
640
641# convini (pr, time)
642    elif diagn == 'convini':
643           
644        var0 = ncobj.variables[depvars[0]][:]
645        var1 = ncobj.variables[depvars[1]][:]
646        otime = ncobj.variables[depvars[1]]
647
648        dnamesvar = ncobj.variables[depvars[0]].dimensions
649        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
650
651        diagout, diagoutd, diagoutvd  = diag.var_convini(var0, var1, dnames, dvnames)
652
653        ncvar.insert_variable(ncobj, 'convini', diagout, diagoutd, diagoutvd, newnc, \
654          fill=gen.fillValueF)
655        # Getting the right units
656        ovar = newnc.variables['convini']
657        if gen.searchInlist(otime.ncattrs(), 'units'): 
658            tunits = otime.getncattr('units')
659            ncvar.set_attribute(ovar, 'units', tunits)
660            newnc.sync()
661
662# deaccum: deacumulation of any variable as (Variable, time [as [tunits]
663#   from/since ....], newvarname)
664    elif diagn == 'deaccum':
665
666        var0 = ncobj.variables[depvars[0]]
667        var1 = ncobj.variables[depvars[1]]
668
669        dnamesvar = var0.dimensions
670        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
671
672        diagout, diagoutd, diagoutvd = diag.compute_deaccum(var0,dnamesvar,dvnamesvar)
673        # Removing the nonChecking variable-dimensions from the initial list
674        varsadd = []
675        diagoutvd = list(dvnames)
676        for nonvd in NONchkvardims:
677            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
678            varsadd.append(nonvd)
679
680# Transforming to a flux
681        if depvars[1] == 'XTIME':
682            dtimeunits = var1.getncattr('description')
683            tunits = dtimeunits.split(' ')[0]
684        else:
685            dtimeunits = var1.getncattr('units')
686            tunits = dtimeunits.split(' ')[0]
687
688        dtime = (var1[1] - var1[0])*diag.timeunits_seconds(tunits)
689        ncvar.insert_variable(ncobj, depvars[2], diagout/dtime, diagoutd, diagoutvd, \
690          newnc)
691
692# fog_K84: Computation of fog and visibility following Kunkel, (1984) as QCLOUD, QICE
693    elif diagn == 'fog_K84':
694
695        var0 = ncobj.variables[depvars[0]]
696        var1 = ncobj.variables[depvars[1]]
697
698        dnamesvar = list(var0.dimensions)
699        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
700
701        diag1, diag2, diagoutd, diagoutvd = diag.Forcompute_fog_K84(var0, var1,      \
702          dnamesvar, dvnamesvar)
703        # Removing the nonChecking variable-dimensions from the initial list
704        varsadd = []
705        diagoutvd = list(dvnames)
706        for nonvd in NONchkvardims:
707            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
708            varsadd.append(nonvd)
709        ncvar.insert_variable(ncobj, 'fog', diag1, diagoutd, diagoutvd, newnc)
710        ncvar.insert_variable(ncobj, 'fogvisblty', diag2, diagoutd, diagoutvd, newnc)
711
712# fog_RUC: Computation of fog and visibility following Kunkel, (1984) as QVAPOR,
713#    WRFt, WRFp or Q2, T2, PSFC
714    elif diagn == 'fog_RUC':
715
716        var0 = ncobj.variables[depvars[0]]
717        print gen.infmsg
718        if depvars[1] == 'WRFt':
719            print '  ' + main + ": computing '" + diagn + "' using 3D variables !!"
720            var1 = WRFt
721            var2 = WRFp
722        else:
723            print '  ' + main + ": computing '" + diagn + "' using 2D variables !!"
724            var1 = ncobj.variables[depvars[1]]
725            var2 = ncobj.variables[depvars[2]]
726
727        dnamesvar = list(var0.dimensions)
728        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
729
730        diag1, diag2, diagoutd, diagoutvd = diag.Forcompute_fog_RUC(var0, var1, var2,\
731          dnamesvar, dvnamesvar)
732        # Removing the nonChecking variable-dimensions from the initial list
733        varsadd = []
734        diagoutvd = list(dvnames)
735        for nonvd in NONchkvardims:
736            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
737            varsadd.append(nonvd)
738        ncvar.insert_variable(ncobj, 'fog', diag1, diagoutd, diagoutvd, newnc)
739        ncvar.insert_variable(ncobj, 'fogvisblty', diag2, diagoutd, diagoutvd, newnc)
740
741# fog_FRAML50: Computation of fog and visibility following Gultepe, I. and
742#   J.A. Milbrandt, 2010 as QVAPOR, WRFt, WRFp or Q2, T2, PSFC
743    elif diagn == 'fog_FRAML50':
744
745        var0 = ncobj.variables[depvars[0]]
746        print gen.infmsg
747        if depvars[1] == 'WRFt':
748            print '  ' + main + ": computing '" + diagn + "' using 3D variables !!"
749            var1 = WRFt
750            var2 = WRFp
751        else:
752            print '  ' + main + ": computing '" + diagn + "' using 2D variables !!"
753            var1 = ncobj.variables[depvars[1]]
754            var2 = ncobj.variables[depvars[2]]
755
756        dnamesvar = list(var0.dimensions)
757        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
758
759        diag1, diag2, diagoutd, diagoutvd = diag.Forcompute_fog_FRAML50(var0, var1,  \
760          var2, dnamesvar, dvnamesvar)
761        # Removing the nonChecking variable-dimensions from the initial list
762        varsadd = []
763        diagoutvd = list(dvnames)
764        for nonvd in NONchkvardims:
765            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
766            varsadd.append(nonvd)
767        ncvar.insert_variable(ncobj, 'fog', diag1, diagoutd, diagoutvd, newnc)
768        ncvar.insert_variable(ncobj, 'fogvisblty', diag2, diagoutd, diagoutvd, newnc)
769
770# LMDZrh (pres, t, r)
771    elif diagn == 'LMDZrh':
772           
773        var0 = ncobj.variables[depvars[0]][:]
774        var1 = ncobj.variables[depvars[1]][:]
775        var2 = ncobj.variables[depvars[2]][:]
776
777        diagout, diagoutd, diagoutvd = diag.compute_rh(var0,var1,var2,dnames,dvnames)
778        ncvar.insert_variable(ncobj, 'hur', diagout, diagoutd, diagoutvd, newnc)
779
780# LMDZrhs (psol, t2m, q2m)
781    elif diagn == 'LMDZrhs':
782           
783        var0 = ncobj.variables[depvars[0]][:]
784        var1 = ncobj.variables[depvars[1]][:]
785        var2 = ncobj.variables[depvars[2]][:]
786
787        dnamesvar = ncobj.variables[depvars[0]].dimensions
788        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
789
790        diagout, diagoutd, diagoutvd = diag.compute_rh(var0,var1,var2,dnamesvar,dvnamesvar)
791
792        ncvar.insert_variable(ncobj, 'hurs', diagout, diagoutd, diagoutvd, newnc)
793
794# range_faces: LON, LAT, HGT, WRFdxdy, 'face:['WE'/'SN']:[dsfilt]:[dsnewrange]:[hvalleyrange]'
795    elif diagn == 'range_faces':
796           
797        var0 = ncobj.variables[depvars[0]][:]
798        var1 = ncobj.variables[depvars[1]][:]
799        var2 = ncobj.variables[depvars[2]][:]
800        face = depvars[4].split(':')[1]
801        dsfilt = np.float(depvars[4].split(':')[2])
802        dsnewrange = np.float(depvars[4].split(':')[3])
803        hvalleyrange = np.float(depvars[4].split(':')[4])
804
805        dnamesvar = list(ncobj.variables[depvars[2]].dimensions)
806        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
807        lon, lat = gen.lonlat2D(var0, var1)
808        if len(var2.shape) == 3:
809            print warnmsg
810            print '  ' + diagn + ": shapping to 2D variable '" + depvars[2] + "' !!"
811            hgt = var2[0,:,:]
812            dnamesvar.pop(0)
813            dvnamesvar.pop(0)           
814        else:
815            hgt = var2[:]
816
817        orogmax, ptorogmax, dhgt, peaks, valleys, origfaces, diagout, diagoutd,      \
818          diagoutvd, rng, rngorogmax, ptrngorogmax= diag.Forcompute_range_faces(lon, \
819           lat, hgt, WRFdx, WRFdy, WRFds, face, dsfilt, dsnewrange, hvalleyrange,    \
820           dnamesvar, dvnamesvar)
821
822        # Removing the nonChecking variable-dimensions from the initial list
823        varsadd = []
824        diagoutvd = list(dvnames)
825        for nonvd in NONchkvardims:
826            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
827            varsadd.append(nonvd)
828
829        ncvar.insert_variable(ncobj, 'dx', WRFdx, diagoutd, diagoutvd, newnc)
830        ncvar.insert_variable(ncobj, 'dy', WRFdy, diagoutd, diagoutvd, newnc)
831        ncvar.insert_variable(ncobj, 'ds', WRFds, diagoutd, diagoutvd, newnc)
832
833        # adding variables to output file
834        if face == 'WE': axis = 'lon'
835        elif face == 'SN': axis = 'lat'
836
837        ncvar.insert_variable(ncobj, 'range', rng, diagoutd, diagoutvd, newnc,       \
838          fill=gen.fillValueI)
839        ovar = newnc.variables['range']
840        ncvar.set_attribute(ovar, 'deriv', axis)
841
842        ncvar.insert_variable(ncobj, 'orogmax', rngorogmax, diagoutd, diagoutvd,     \
843          newnc, fill=gen.fillValueF)
844        newnc.renameVariable('orogmax', 'rangeorogmax')
845        ovar = newnc.variables['rangeorogmax']
846        ncvar.set_attribute(ovar, 'deriv', axis)
847        stdn = ovar.standard_name
848        ncvar.set_attribute(ovar, 'standard_name', 'range_' + stdn)
849        Ln = ovar.long_name
850        ncvar.set_attribute(ovar, 'long_name', 'range ' + stdn)
851
852        ncvar.insert_variable(ncobj, 'ptorogmax', ptrngorogmax, diagoutd, diagoutvd, \
853          newnc)
854        newnc.renameVariable('ptorogmax', 'rangeptorogmax')
855        ovar = newnc.variables['rangeptorogmax']
856        ncvar.set_attribute(ovar, 'deriv', axis)
857        stdn = ovar.standard_name
858        ncvar.set_attribute(ovar, 'standard_name', 'range_' + stdn)
859        Ln = ovar.long_name
860        ncvar.set_attribute(ovar, 'long_name', 'range ' + stdn)
861
862        ncvar.insert_variable(ncobj, 'orogmax', orogmax, diagoutd, diagoutvd,        \
863          newnc)
864        ovar = newnc.variables['orogmax']
865        ncvar.set_attribute(ovar, 'deriv', axis)
866
867        ncvar.insert_variable(ncobj, 'ptorogmax', ptorogmax, diagoutd, diagoutvd,    \
868          newnc)
869        ovar = newnc.variables['ptorogmax']
870        ncvar.set_attribute(ovar, 'deriv', axis)
871
872        ncvar.insert_variable(ncobj, 'orogderiv', dhgt, diagoutd, diagoutvd, newnc)
873        ovar = newnc.variables['orogderiv']
874        ncvar.set_attribute(ovar, 'deriv', axis)
875
876        ncvar.insert_variable(ncobj, 'peak', peaks, diagoutd, diagoutvd, newnc)
877        ncvar.insert_variable(ncobj, 'valley', valleys, diagoutd, diagoutvd, newnc)
878
879        ncvar.insert_variable(ncobj, 'rangefaces', diagout, diagoutd, diagoutvd,    \
880          newnc)
881        newnc.renameVariable('rangefaces', 'rangefacesfilt')
882        ovar = newnc.variables['rangefacesfilt']
883        ncvar.set_attribute(ovar, 'face', face)
884        ncvar.set_attributek(ovar, 'dist_filter', dsfilt, 'F')
885
886        ncvar.insert_variable(ncobj, 'rangefaces', origfaces, diagoutd, diagoutvd,  \
887          newnc, fill=gen.fillValueI)
888        ovar = newnc.variables['rangefaces']
889        ncvar.set_attribute(ovar, 'face', face)
890        ncvar.set_attributek(ovar, 'dist_newrange', dsnewrange, 'F')
891        ncvar.set_attributek(ovar, 'h_valley_newrange', hvalleyrange, 'F')
892
893# cell_bnds: grid cell bounds from lon, lat from a reglar lon/lat projection  as
894#   intersection of their related parallels and meridians
895    elif diagn == 'reglonlatbnds':
896           
897        var00 = ncobj.variables[depvars[0]][:]
898        var01 = ncobj.variables[depvars[1]][:]
899
900        var0, var1 = gen.lonlat2D(var00,var01)
901
902        dnamesvar = []
903        dnamesvar.append('bnds')
904        if (len(var00.shape) == 3):
905            dnamesvar.append(ncobj.variables[depvars[0]].dimensions[1])
906            dnamesvar.append(ncobj.variables[depvars[0]].dimensions[2])
907        elif (len(var00.shape) == 2):
908            dnamesvar.append(ncobj.variables[depvars[0]].dimensions[0])
909            dnamesvar.append(ncobj.variables[depvars[0]].dimensions[1])
910        elif (len(var00.shape) == 1):
911            dnamesvar.append(ncobj.variables[depvars[0]].dimensions[0])
912            dnamesvar.append(ncobj.variables[depvars[1]].dimensions[0])
913        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
914
915        cellbndsx, cellbndsy, diagoutd, diagoutvd = diag.Forcompute_cellbndsreg(var0,\
916          var1, dnamesvar, dvnamesvar)
917
918        # Removing the nonChecking variable-dimensions from the initial list
919        varsadd = []
920        diagoutvd = list(dvnames)
921        for nonvd in NONchkvardims:
922            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
923            varsadd.append(nonvd)
924        # creation of bounds dimension
925        newdim = newnc.createDimension('bnds', 4)
926
927        ncvar.insert_variable(ncobj, 'lon_bnds', cellbndsx, diagoutd, diagoutvd, newnc)
928        ncvar.insert_variable(ncobj, 'lat_bnds', cellbndsy, diagoutd, diagoutvd, newnc)
929
930# cell_bnds: grid cell bounds from XLONG_U, XLAT_U, XLONG_V, XLAT_V as intersection
931#   of their related parallels and meridians
932    elif diagn == 'WRFbnds':
933           
934        var0 = ncobj.variables[depvars[0]][0,:,:]
935        var1 = ncobj.variables[depvars[1]][0,:,:]
936        var2 = ncobj.variables[depvars[2]][0,:,:]
937        var3 = ncobj.variables[depvars[3]][0,:,:]
938
939        dnamesvar = []
940        dnamesvar.append('bnds')
941        dnamesvar.append(ncobj.variables[depvars[0]].dimensions[1])
942        dnamesvar.append(ncobj.variables[depvars[2]].dimensions[2])
943        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
944
945        cellbndsx, cellbndsy, diagoutd, diagoutvd = diag.Forcompute_cellbnds(var0,   \
946          var1, var2, var3, dnamesvar, dvnamesvar)
947
948        # Removing the nonChecking variable-dimensions from the initial list
949        varsadd = []
950        diagoutvd = list(dvnames)
951        for nonvd in NONchkvardims:
952            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
953            varsadd.append(nonvd)
954        # creation of bounds dimension
955        newdim = newnc.createDimension('bnds', 4)
956
957        ncvar.insert_variable(ncobj, 'lon_bnds', cellbndsx, diagoutd, diagoutvd, newnc)
958        newnc.sync()
959        ncvar.insert_variable(ncobj, 'lat_bnds', cellbndsy, diagoutd, diagoutvd, newnc)
960        newnc.sync()
961
962        ovar = newnc.variables['XLONG']
963        ovar.setncattr('bounds', 'lon_bnds lat_bnds')
964        ovar = newnc.variables['XLAT']
965        ovar.setncattr('bounds', 'lon_bnds lat_bnds')
966
967# mrso: total soil moisture SMOIS, DZS
968    elif diagn == 'WRFmrso':
969           
970        var0 = ncobj.variables[depvars[0]][:]
971        var10 = ncobj.variables[depvars[1]][:]
972        dnamesvar = list(ncobj.variables[depvars[0]].dimensions)
973        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
974
975        var1 = var0.copy()*0.
976        var2 = var0.copy()*0.+1.
977        # Must be a better way....
978        for j in range(var0.shape[2]):
979          for i in range(var0.shape[3]):
980              var1[:,:,j,i] = var10
981
982        diagout, diagoutd, diagoutvd = diag.Forcompute_zint(var0, var1, var2,        \
983          dnamesvar, dvnamesvar)
984
985        # Removing the nonChecking variable-dimensions from the initial list
986        varsadd = []
987        diagoutvd = list(dvnames)
988        for nonvd in NONchkvardims:
989            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
990            varsadd.append(nonvd)
991        ncvar.insert_variable(ncobj, 'mrso', diagout, diagoutd, diagoutvd, newnc)
992
993# mrsos: First layer soil moisture SMOIS, DZS
994    elif diagn == 'WRFmrsos':
995           
996        var0 = ncobj.variables[depvars[0]][:]
997        var1 = ncobj.variables[depvars[1]][:]
998        diagoutd = list(ncobj.variables[depvars[0]].dimensions)
999        diagoutvd = ncvar.var_dim_dimv(diagoutd,dnames,dvnames)
1000
1001        diagoutd.pop(1)
1002        diagoutvd.pop(1)
1003
1004        diagout= np.zeros((var0.shape[0],var0.shape[2],var0.shape[3]), dtype=np.float)
1005
1006        # Must be a better way....
1007        for j in range(var0.shape[2]):
1008          for i in range(var0.shape[3]):
1009              diagout[:,j,i] = var0[:,0,j,i]*var1[:,0]
1010
1011        # Removing the nonChecking variable-dimensions from the initial list
1012        varsadd = []
1013        diagoutvd = list(dvnames)
1014        for nonvd in NONchkvardims:
1015            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1016            varsadd.append(nonvd)
1017        ncvar.insert_variable(ncobj, 'mrsos', diagout, diagoutd, diagoutvd, newnc)
1018
1019# mslp: mean sea level pressure (pres, psfc, terrain, temp, qv)
1020    elif diagn == 'mslp' or diagn == 'WRFmslp':
1021           
1022        var1 = ncobj.variables[depvars[1]][:]
1023        var2 = ncobj.variables[depvars[2]][:]
1024        var4 = ncobj.variables[depvars[4]][:]
1025
1026        if diagn == 'WRFmslp':
1027            var0 = WRFp
1028            var3 = WRFt
1029            dnamesvar = ncobj.variables['P'].dimensions
1030        else:
1031            var0 = ncobj.variables[depvars[0]][:]
1032            var3 = ncobj.variables[depvars[3]][:]
1033            dnamesvar = ncobj.variables[depvars[0]].dimensions
1034
1035        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1036
1037        diagout, diagoutd, diagoutvd = diag.compute_mslp(var0, var1, var2, var3, var4,    \
1038          dnamesvar, dvnamesvar)
1039
1040        # Removing the nonChecking variable-dimensions from the initial list
1041        varsadd = []
1042        diagoutvd = list(dvnames)
1043        for nonvd in NONchkvardims:
1044            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1045            varsadd.append(nonvd)
1046        ncvar.insert_variable(ncobj, 'psl', diagout, diagoutd, diagoutvd, newnc)
1047
1048# OMEGAw (omega, p, t) from NCL formulation (https://www.ncl.ucar.edu/Document/Functions/Contributed/omega_to_w.shtml)
1049    elif diagn == 'OMEGAw':
1050           
1051        var0 = ncobj.variables[depvars[0]][:]
1052        var1 = ncobj.variables[depvars[1]][:]
1053        var2 = ncobj.variables[depvars[2]][:]
1054
1055        dnamesvar = ncobj.variables[depvars[0]].dimensions
1056        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1057
1058        diagout, diagoutd, diagoutvd = diag.compute_OMEGAw(var0,var1,var2,dnamesvar,dvnamesvar)
1059
1060        ncvar.insert_variable(ncobj, 'wa', diagout, diagoutd, diagoutvd, newnc)
1061
1062# raintot: instantaneous total precipitation from WRF as (RAINC + RAINC + RAINSH) / dTime
1063    elif diagn == 'RAINTOT':
1064
1065        var0 = ncobj.variables[depvars[0]]
1066        var1 = ncobj.variables[depvars[1]]
1067        var2 = ncobj.variables[depvars[2]]
1068
1069        if depvars[3] != 'WRFtime':
1070            var3 = ncobj.variables[depvars[3]]
1071        else:
1072            var3 = np.arange(var0.shape[0], dtype=int)
1073
1074        var = var0[:] + var1[:] + var2[:]
1075
1076        dnamesvar = var0.dimensions
1077        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1078
1079        diagout, diagoutd, diagoutvd = diag.compute_deaccum(var,dnamesvar,dvnamesvar)
1080
1081# Transforming to a flux
1082        if var3.shape[0] > 1:
1083            if depvars[3] != 'WRFtime':
1084                dtimeunits = var3.getncattr('units')
1085                tunits = dtimeunits.split(' ')[0]
1086   
1087                dtime = (var3[1] - var3[0])*diag.timeunits_seconds(tunits)
1088            else:
1089                var3 = ncobj.variables['Times']
1090                time1 = var3[0,:]
1091                time2 = var3[1,:]
1092                tmf1 = ''
1093                tmf2 = ''
1094                for ic in range(len(time1)):
1095                    tmf1 = tmf1 + time1[ic]
1096                    tmf2 = tmf2 + time2[ic]
1097                dtdate1 = dtime.datetime.strptime(tmf1,"%Y-%m-%d_%H:%M:%S")
1098                dtdate2 = dtime.datetime.strptime(tmf2,"%Y-%m-%d_%H:%M:%S")
1099                diffdate12 = dtdate2 - dtdate1
1100                dtime = diffdate12.total_seconds()
1101                print 'dtime:',dtime
1102        else:
1103            print warnmsg
1104            print '  ' + main + ": only 1 time-step for '" + diag + "' !!"
1105            print '    leaving a zero value!'
1106            diagout = var0[:]*0.
1107            dtime=1.
1108
1109        # Removing the nonChecking variable-dimensions from the initial list
1110        varsadd = []
1111        for nonvd in NONchkvardims:
1112            if gen.searchInlist(diagoutvd,nonvd): diagoutvd.remove(nonvd)
1113            varsadd.append(nonvd)
1114           
1115        ncvar.insert_variable(ncobj, 'pr', diagout/dtime, diagoutd, diagoutvd, newnc)
1116
1117# timemax ([varname], time). When a given variable [varname] got its maximum
1118    elif diagn == 'timemax':
1119           
1120        var0 = ncobj.variables[depvars[0]][:]
1121        var1 = ncobj.variables[depvars[1]][:]
1122
1123        otime = ncobj.variables[depvars[1]]
1124
1125        dnamesvar = ncobj.variables[depvars[0]].dimensions
1126        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1127
1128        diagout, diagoutd, diagoutvd  = diag.var_timemax(var0, var1, dnames,         \
1129          dvnames)
1130
1131        ncvar.insert_variable(ncobj, 'timemax', diagout, diagoutd, diagoutvd, newnc, \
1132          fill=gen.fillValueF)
1133        # Getting the right units
1134        ovar = newnc.variables['timemax']
1135        if gen.searchInlist(otime.ncattrs(), 'units'): 
1136            tunits = otime.getncattr('units')
1137            ncvar.set_attribute(ovar, 'units', tunits)
1138            newnc.sync()
1139        ncvar.set_attribute(ovar, 'variable', depvars[0])
1140
1141# timeoverthres ([varname], time, [value], [CFvarn]). When a given variable [varname]   
1142#   overpass a given [value]. Being [CFvarn] the name of the diagnostics in
1143#   variables_values.dat
1144    elif diagn == 'timeoverthres':
1145           
1146        var0 = ncobj.variables[depvars[0]][:]
1147        var1 = ncobj.variables[depvars[1]][:]
1148        var2 = np.float(depvars[2])
1149        var3 = depvars[3]
1150
1151        otime = ncobj.variables[depvars[1]]
1152
1153        dnamesvar = ncobj.variables[depvars[0]].dimensions
1154        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1155
1156        diagout, diagoutd, diagoutvd  = diag.var_timeoverthres(var0, var1, var2,     \
1157          dnames, dvnames)
1158
1159        ncvar.insert_variable(ncobj, var3, diagout, diagoutd, diagoutvd, newnc, \
1160          fill=gen.fillValueF)
1161        # Getting the right units
1162        ovar = newnc.variables[var3]
1163        if gen.searchInlist(otime.ncattrs(), 'units'): 
1164            tunits = otime.getncattr('units')
1165            ncvar.set_attribute(ovar, 'units', tunits)
1166            newnc.sync()
1167        ncvar.set_attribute(ovar, 'overpassed_threshold', var2)
1168
1169# rhs (psfc, t, q) from TimeSeries files
1170    elif diagn == 'TSrhs':
1171           
1172        p0=100000.
1173        var0 = ncobj.variables[depvars[0]][:]
1174        var1 = (ncobj.variables[depvars[1]][:])*(var0/p0)**(2./7.)
1175        var2 = ncobj.variables[depvars[2]][:]
1176
1177        dnamesvar = ncobj.variables[depvars[0]].dimensions
1178        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1179
1180        diagout, diagoutd, diagoutvd = diag.compute_rh(var0,var1,var2,dnamesvar,dvnamesvar)
1181
1182        ncvar.insert_variable(ncobj, 'hurs', diagout, diagoutd, diagoutvd, newnc)
1183
1184# slw: total soil liquid water SH2O, DZS
1185    elif diagn == 'WRFslw':
1186           
1187        var0 = ncobj.variables[depvars[0]][:]
1188        var10 = ncobj.variables[depvars[1]][:]
1189        dnamesvar = list(ncobj.variables[depvars[0]].dimensions)
1190        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1191
1192        var1 = var0.copy()*0.
1193        var2 = var0.copy()*0.+1.
1194        # Must be a better way....
1195        for j in range(var0.shape[2]):
1196          for i in range(var0.shape[3]):
1197              var1[:,:,j,i] = var10
1198
1199        diagout, diagoutd, diagoutvd = diag.Forcompute_zint(var0, var1, var2,        \
1200          dnamesvar, dvnamesvar)
1201
1202        # Removing the nonChecking variable-dimensions from the initial list
1203        varsadd = []
1204        diagoutvd = list(dvnames)
1205        for nonvd in NONchkvardims:
1206            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1207            varsadd.append(nonvd)
1208        ncvar.insert_variable(ncobj, 'slw', diagout, diagoutd, diagoutvd, newnc)
1209
1210# td (psfc, t, q) from TimeSeries files
1211    elif diagn == 'TStd' or diagn == 'td':
1212           
1213        var0 = ncobj.variables[depvars[0]][:]
1214        var1 = ncobj.variables[depvars[1]][:] - 273.15
1215        var2 = ncobj.variables[depvars[2]][:]
1216
1217        dnamesvar = ncobj.variables[depvars[0]].dimensions
1218        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1219
1220        diagout, diagoutd, diagoutvd = diag.compute_td(var0,var1,var2,dnamesvar,dvnamesvar)
1221
1222        ncvar.insert_variable(ncobj, 'tdas', diagout, diagoutd, diagoutvd, newnc)
1223
1224# td (psfc, t, q) from TimeSeries files
1225    elif diagn == 'TStdC' or diagn == 'tdC':
1226           
1227        var0 = ncobj.variables[depvars[0]][:]
1228# Temperature is already in degrees Celsius
1229        var1 = ncobj.variables[depvars[1]][:]
1230        var2 = ncobj.variables[depvars[2]][:]
1231
1232        dnamesvar = ncobj.variables[depvars[0]].dimensions
1233        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1234
1235        diagout, diagoutd, diagoutvd = diag.compute_td(var0,var1,var2,dnamesvar,dvnamesvar)
1236
1237        # Removing the nonChecking variable-dimensions from the initial list
1238        varsadd = []
1239        for nonvd in NONchkvardims:
1240            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1241            varsadd.append(nonvd)
1242
1243        ncvar.insert_variable(ncobj, 'tdas', diagout, diagoutd, diagoutvd, newnc)
1244
1245# wds (u, v)
1246    elif diagn == 'TSwds' or diagn == 'wds' :
1247 
1248        var0 = ncobj.variables[depvars[0]][:]
1249        var1 = ncobj.variables[depvars[1]][:]
1250
1251        dnamesvar = ncobj.variables[depvars[0]].dimensions
1252        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1253
1254        diagout, diagoutd, diagoutvd = diag.compute_wds(var0,var1,dnamesvar,dvnamesvar)
1255
1256        # Removing the nonChecking variable-dimensions from the initial list
1257        varsadd = []
1258        for nonvd in NONchkvardims:
1259            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1260            varsadd.append(nonvd)
1261
1262        ncvar.insert_variable(ncobj, 'wds', diagout, diagoutd, diagoutvd, newnc)
1263
1264# wss (u, v)
1265    elif diagn == 'TSwss' or diagn == 'wss':
1266           
1267        var0 = ncobj.variables[depvars[0]][:]
1268        var1 = ncobj.variables[depvars[1]][:]
1269
1270        dnamesvar = ncobj.variables[depvars[0]].dimensions
1271        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1272
1273        diagout, diagoutd, diagoutvd = diag.compute_wss(var0,var1,dnamesvar,dvnamesvar)
1274
1275        # Removing the nonChecking variable-dimensions from the initial list
1276        varsadd = []
1277        for nonvd in NONchkvardims:
1278            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1279            varsadd.append(nonvd)
1280
1281        ncvar.insert_variable(ncobj, 'wss', diagout, diagoutd, diagoutvd, newnc)
1282
1283# turbulence (var)
1284    elif diagn == 'turbulence':
1285
1286        var0 = ncobj.variables[depvars][:]
1287
1288        dnamesvar = list(ncobj.variables[depvars].dimensions)
1289        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1290
1291        diagout, diagoutd, diagoutvd = diag.compute_turbulence(var0,dnamesvar,dvnamesvar)
1292        valsvar = gen.variables_values(depvars)
1293
1294        newvarn = depvars + 'turb'
1295        ncvar.insert_variable(ncobj, newvarn, diagout, diagoutd, 
1296          diagoutvd, newnc)
1297        varobj = newnc.variables[newvarn]
1298        attrv = varobj.long_name
1299        attr = varobj.delncattr('long_name')
1300        newattr = ncvar.set_attribute(varobj, 'long_name', attrv +                   \
1301          " Taylor decomposition turbulence term")
1302
1303# ua va from ws wd (deg)
1304    elif diagn == 'uavaFROMwswd':
1305           
1306        var0 = ncobj.variables[depvars[0]][:]
1307        var1 = ncobj.variables[depvars[1]][:]
1308
1309        ua = var0*np.cos(var1*np.pi/180.)
1310        va = var0*np.sin(var1*np.pi/180.)
1311
1312        dnamesvar = ncobj.variables[depvars[0]].dimensions
1313        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1314
1315        ncvar.insert_variable(ncobj, 'ua', ua, dnamesvar, dvnamesvar, newnc)
1316        ncvar.insert_variable(ncobj, 'va', va, dnamesvar, dvnamesvar, newnc)
1317
1318# ua va from obs ws wd (deg)
1319    elif diagn == 'uavaFROMobswswd':
1320           
1321        var0 = ncobj.variables[depvars[0]][:]
1322        var1 = ncobj.variables[depvars[1]][:]
1323
1324        ua = var0*np.cos((var1+180.)*np.pi/180.)
1325        va = var0*np.sin((var1+180.)*np.pi/180.)
1326
1327        dnamesvar = ncobj.variables[depvars[0]].dimensions
1328        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1329
1330        ncvar.insert_variable(ncobj, 'ua', ua, dnamesvar, dvnamesvar, newnc)
1331        ncvar.insert_variable(ncobj, 'va', va, dnamesvar, dvnamesvar, newnc)
1332
1333# WRFbils fom WRF as HFX + LH
1334    elif diagn == 'WRFbils':
1335           
1336        var0 = ncobj.variables[depvars[0]][:]
1337        var1 = ncobj.variables[depvars[1]][:]
1338
1339        diagout = var0 + var1
1340        dnamesvar = list(ncobj.variables[depvars[0]].dimensions)
1341        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1342
1343        ncvar.insert_variable(ncobj, 'bils', diagout, dnamesvar, dvnamesvar, newnc)
1344
1345# WRFcape_afwa CAPE, CIN, ZLFC, PLFC, LI following WRF 'phys/module_diaf_afwa.F'
1346#   methodology as WRFt, WRFrh, WRFp, WRFgeop, HGT
1347    elif diagn == 'WRFcape_afwa':
1348        var0 = WRFt
1349        var1 = WRFrh
1350        var2 = WRFp
1351        dz = WRFgeop.shape[1]
1352        # de-staggering
1353        var3 = 0.5*(WRFgeop[:,0:dz-1,:,:]+WRFgeop[:,1:dz,:,:])/9.8
1354        var4 = ncobj.variables[depvars[4]][0,:,:]
1355
1356        dnamesvar = list(ncobj.variables['T'].dimensions)
1357        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1358
1359        diagout = np.zeros(var0.shape, dtype=np.float)
1360        diagout1, diagout2, diagout3, diagout4, diagout5, diagoutd, diagoutvd =      \
1361          diag.Forcompute_cape_afwa(var0, var1, var2, var3, var4, 3, dnamesvar,      \
1362          dvnamesvar)
1363
1364        # Removing the nonChecking variable-dimensions from the initial list
1365        varsadd = []
1366        for nonvd in NONchkvardims:
1367            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1368            varsadd.append(nonvd)
1369
1370        ncvar.insert_variable(ncobj, 'cape', diagout1, diagoutd, diagoutvd, newnc)
1371        ncvar.insert_variable(ncobj, 'cin', diagout2, diagoutd, diagoutvd, newnc)
1372        ncvar.insert_variable(ncobj, 'zlfc', diagout3, diagoutd, diagoutvd, newnc)
1373        ncvar.insert_variable(ncobj, 'plfc', diagout4, diagoutd, diagoutvd, newnc)
1374        ncvar.insert_variable(ncobj, 'li', diagout5, diagoutd, diagoutvd, newnc)
1375
1376# WRFclivi WRF water vapour path WRFdens, QICE, QGRAUPEL, QHAIL
1377    elif diagn == 'WRFclivi':
1378           
1379        var0 = WRFdens
1380        qtot = ncobj.variables[depvars[1]]
1381        qtotv = qtot[:]
1382        Nspecies = len(depvars) - 2
1383        for iv in range(Nspecies):
1384            if ncobj.variables.has_key(depvars[iv+2]):
1385                var1 = ncobj.variables[depvars[iv+2]][:]
1386                qtotv = qtotv + var1
1387
1388        dnamesvar = list(qtot.dimensions)
1389        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1390
1391        diagout, diagoutd, diagoutvd = diag.compute_clivi(var0, qtotv, dnamesvar,dvnamesvar)
1392
1393        # Removing the nonChecking variable-dimensions from the initial list
1394        varsadd = []
1395        diagoutvd = list(dvnames)
1396        for nonvd in NONchkvardims:
1397            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1398            varsadd.append(nonvd)
1399        ncvar.insert_variable(ncobj, 'clivi', diagout, diagoutd, diagoutvd, newnc)
1400
1401# WRFclwvi WRF water cloud-condensed path WRFdens, QCLOUD, QICE, QGRAUPEL, QHAIL
1402    elif diagn == 'WRFclwvi':
1403           
1404        var0 = WRFdens
1405        qtot = ncobj.variables[depvars[1]]
1406        qtotv = ncobj.variables[depvars[1]]
1407        Nspecies = len(depvars) - 2
1408        for iv in range(Nspecies):
1409            if ncobj.variables.has_key(depvars[iv+2]):
1410                var1 = ncobj.variables[depvars[iv+2]]
1411                qtotv = qtotv + var1[:]
1412
1413        dnamesvar = list(qtot.dimensions)
1414        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1415
1416        diagout, diagoutd, diagoutvd = diag.compute_clwvl(var0, qtotv, dnamesvar,dvnamesvar)
1417
1418        # Removing the nonChecking variable-dimensions from the initial list
1419        varsadd = []
1420        diagoutvd = list(dvnames)
1421        for nonvd in NONchkvardims:
1422            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1423            varsadd.append(nonvd)
1424        ncvar.insert_variable(ncobj, 'clwvi', diagout, diagoutd, diagoutvd, newnc)
1425
1426# WRF_denszint WRF vertical integration as WRFdens, sum(Q[water species1], ..., Q[water speciesN]), varn=[varN]
1427    elif diagn == 'WRF_denszint':
1428           
1429        var0 = WRFdens
1430        varn = depvars[1].split('=')[1]
1431        qtot = ncobj.variables[depvars[2]]
1432        qtotv = ncobj.variables[depvars[2]]
1433        Nspecies = len(depvars) - 2
1434        for iv in range(Nspecies):
1435            if ncobj.variables.has_key(depvars[iv+2]):
1436                var1 = ncobj.variables[depvars[iv+2]]
1437                qtotv = qtotv + var1[:]
1438
1439        dnamesvar = list(qtot.dimensions)
1440        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1441
1442        diagout, diagoutd, diagoutvd = diag.compute_clwvl(var0, qtotv, dnamesvar,dvnamesvar)
1443
1444        # Removing the nonChecking variable-dimensions from the initial list
1445        varsadd = []
1446        diagoutvd = list(dvnames)
1447        for nonvd in NONchkvardims:
1448            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1449            varsadd.append(nonvd)
1450        ncvar.insert_variable(ncobj, varn, diagout, diagoutd, diagoutvd, newnc)
1451
1452# WRFgeop geopotential from WRF as PH + PHB
1453    elif diagn == 'WRFgeop':
1454        var0 = ncobj.variables[depvars[0]][:]
1455        var1 = ncobj.variables[depvars[1]][:]
1456
1457        # de-staggering geopotential
1458        diagout0 = var0 + var1
1459        dt = diagout0.shape[0]
1460        dz = diagout0.shape[1]
1461        dy = diagout0.shape[2]
1462        dx = diagout0.shape[3]
1463
1464        diagout = np.zeros((dt,dz-1,dy,dx), dtype=np.float)
1465        diagout = 0.5*(diagout0[:,1:dz,:,:]+diagout0[:,0:dz-1,:,:])
1466
1467        # Removing the nonChecking variable-dimensions from the initial list
1468        varsadd = []
1469        diagoutvd = list(dvnames)
1470        for nonvd in NONchkvardims:
1471            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1472            varsadd.append(nonvd)
1473
1474        ncvar.insert_variable(ncobj, 'zg', diagout, dnames, diagoutvd, newnc)
1475
1476# WRFpotevap_orPM potential evapotranspiration following Penman-Monteith formulation
1477#   implemented in ORCHIDEE (in src_sechiba/enerbil.f90) as: WRFdens, UST, U10, V10, T2, PSFC, QVAPOR
1478    elif diagn == 'WRFpotevap_orPM':
1479        var0 = WRFdens[:,0,:,:]
1480        var1 = ncobj.variables[depvars[1]][:]
1481        var2 = ncobj.variables[depvars[2]][:]
1482        var3 = ncobj.variables[depvars[3]][:]
1483        var4 = ncobj.variables[depvars[4]][:]
1484        var5 = ncobj.variables[depvars[5]][:]
1485        var6 = ncobj.variables[depvars[6]][:,0,:,:]
1486
1487        dnamesvar = list(ncobj.variables[depvars[1]].dimensions)
1488        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1489
1490        diagout = np.zeros(var1.shape, dtype=np.float)
1491        diagout, diagoutd, diagoutvd = diag.Forcompute_potevap_orPM(var0, var1, var2,\
1492          var3, var4, var5, var6, dnamesvar, dvnamesvar)
1493
1494        # Removing the nonChecking variable-dimensions from the initial list
1495        varsadd = []
1496        for nonvd in NONchkvardims:
1497            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1498            varsadd.append(nonvd)
1499
1500        ncvar.insert_variable(ncobj, 'evspsblpot', diagout, diagoutd, diagoutvd, newnc)
1501
1502# WRFmslp_ptarget sea-level pressure following ECMWF method as PSFC, HGT, WRFt, WRFp, ZNU, ZNW
1503    elif diagn == 'WRFpsl_ecmwf':
1504        var0 = ncobj.variables[depvars[0]][:]
1505        var1 = ncobj.variables[depvars[1]][0,:,:]
1506        var2 = WRFt[:,0,:,:]
1507        var4 = WRFp[:,0,:,:]
1508        var5 = ncobj.variables[depvars[4]][0,:]
1509        var6 = ncobj.variables[depvars[5]][0,:]
1510
1511        # This is quite too appriximate!! passing pressure at half-levels to 2nd full
1512        #   level, using eta values at full (ZNW) and half (ZNU) mass levels
1513        var3 = WRFp[:,0,:,:] + (var6[1] - var5[0])*(WRFp[:,1,:,:] - WRFp[:,0,:,:])/  \
1514          (var5[1]-var5[0])
1515
1516        dnamesvar = list(ncobj.variables[depvars[0]].dimensions)
1517        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1518
1519        diagout = np.zeros(var0.shape, dtype=np.float)
1520        diagout, diagoutd, diagoutvd = diag.Forcompute_psl_ecmwf(var0, var1, var2,   \
1521          var3, var4, dnamesvar, dvnamesvar)
1522
1523        # Removing the nonChecking variable-dimensions from the initial list
1524        varsadd = []
1525        for nonvd in NONchkvardims:
1526            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1527            varsadd.append(nonvd)
1528
1529        ncvar.insert_variable(ncobj, 'psl', diagout, diagoutd, diagoutvd, newnc)
1530
1531# WRFmslp_ptarget sea-level pressure following ptarget method as WRFp, PSFC, WRFt, HGT, QVAPOR
1532    elif diagn == 'WRFpsl_ptarget':
1533        var0 = WRFp
1534        var1 = ncobj.variables[depvars[1]][:]
1535        var2 = WRFt
1536        var3 = ncobj.variables[depvars[3]][0,:,:]
1537        var4 = ncobj.variables[depvars[4]][:]
1538
1539        dnamesvar = list(ncobj.variables[depvars[4]].dimensions)
1540        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1541
1542        diagout = np.zeros(var0.shape, dtype=np.float)
1543        diagout, diagoutd, diagoutvd = diag.Forcompute_psl_ptarget(var0, var1, var2, \
1544          var3, var4, 700000., dnamesvar, dvnamesvar)
1545
1546        # Removing the nonChecking variable-dimensions from the initial list
1547        varsadd = []
1548        for nonvd in NONchkvardims:
1549            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1550            varsadd.append(nonvd)
1551
1552        ncvar.insert_variable(ncobj, 'psl', diagout, diagoutd, diagoutvd, newnc)
1553
1554# WRFp pressure from WRF as P + PB
1555    elif diagn == 'WRFp':
1556        var0 = ncobj.variables[depvars[0]][:]
1557        var1 = ncobj.variables[depvars[1]][:]
1558           
1559        diagout = var0 + var1
1560        diagoutd = list(ncobj.variables[depvars[0]].dimensions)
1561        diagoutvd = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1562
1563        # Removing the nonChecking variable-dimensions from the initial list
1564        varsadd = []
1565        for nonvd in NONchkvardims:
1566            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1567            varsadd.append(nonvd)
1568
1569        ncvar.insert_variable(ncobj, 'pres', diagout, diagoutd, diagoutvd, newnc)
1570
1571# WRFpos
1572    elif diagn == 'WRFpos':
1573           
1574        dnamesvar = ncobj.variables['MAPFAC_M'].dimensions
1575        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1576
1577        ncvar.insert_variable(ncobj, 'WRFpos', WRFpos, dnamesvar, dvnamesvar, newnc)
1578
1579# WRFprw WRF water vapour path WRFdens, QVAPOR
1580    elif diagn == 'WRFprw':
1581           
1582        var0 = WRFdens
1583        var1 = ncobj.variables[depvars[1]]
1584
1585        dnamesvar = list(var1.dimensions)
1586        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1587
1588        diagout, diagoutd, diagoutvd = diag.compute_prw(var0, var1, dnamesvar,dvnamesvar)
1589
1590        # Removing the nonChecking variable-dimensions from the initial list
1591        varsadd = []
1592        diagoutvd = list(dvnames)
1593        for nonvd in NONchkvardims:
1594            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1595            varsadd.append(nonvd)
1596        ncvar.insert_variable(ncobj, 'prw', diagout, diagoutd, diagoutvd, newnc)
1597
1598# WRFrh (P, T, QVAPOR)
1599    elif diagn == 'WRFrh':
1600           
1601        dnamesvar = list(ncobj.variables[depvars[2]].dimensions)
1602        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1603
1604        ncvar.insert_variable(ncobj, 'hur', WRFrh, dnames, dvnames, newnc)
1605
1606# WRFrhs (PSFC, T2, Q2)
1607    elif diagn == 'WRFrhs':
1608           
1609        var0 = ncobj.variables[depvars[0]][:]
1610        var1 = ncobj.variables[depvars[1]][:]
1611        var2 = ncobj.variables[depvars[2]][:]
1612
1613        dnamesvar = list(ncobj.variables[depvars[2]].dimensions)
1614        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1615
1616        diagout, diagoutd, diagoutvd = diag.compute_rh(var0,var1,var2,dnamesvar,dvnamesvar)
1617        ncvar.insert_variable(ncobj, 'hurs', diagout, diagoutd, diagoutvd, newnc)
1618
1619# rvors (u10, v10, WRFpos)
1620    elif diagn == 'WRFrvors':
1621           
1622        var0 = ncobj.variables[depvars[0]]
1623        var1 = ncobj.variables[depvars[1]]
1624
1625        diagout = rotational_z(var0, var1, distx)
1626
1627        dnamesvar = ncobj.variables[depvars[0]].dimensions
1628        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1629
1630        ncvar.insert_variable(ncobj, 'rvors', diagout, dnamesvar, dvnamesvar, newnc)
1631
1632# WRFt (T, P, PB)
1633    elif diagn == 'WRFt':
1634        var0 = ncobj.variables[depvars[0]][:]
1635        var1 = ncobj.variables[depvars[1]][:]
1636        var2 = ncobj.variables[depvars[2]][:]
1637
1638        p0=100000.
1639        p=var1 + var2
1640
1641        WRFt = (var0 + 300.)*(p/p0)**(2./7.)
1642
1643        dnamesvar = list(ncobj.variables[depvars[0]].dimensions)
1644        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1645
1646        # Removing the nonChecking variable-dimensions from the initial list
1647        varsadd = []
1648        diagoutvd = list(dvnames)
1649        for nonvd in NONchkvardims:
1650            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1651            varsadd.append(nonvd)
1652
1653        ncvar.insert_variable(ncobj, 'ta', WRFt, dnames, diagoutvd, newnc)
1654
1655# WRFtda (WRFrh, WRFt)
1656    elif diagn == 'WRFtda':
1657        ARM2 = fdef.module_definitions.arm2
1658        ARM3 = fdef.module_definitions.arm3
1659
1660        gammatarh = np.log(WRFrh) + ARM2*(WRFt-273.15)/((WRFt-273.15)+ARM3)
1661        td = ARM3*gammatarh/(ARM2-gammatarh)
1662
1663        dnamesvar = list(ncobj.variables['T'].dimensions)
1664        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1665
1666        # Removing the nonChecking variable-dimensions from the initial list
1667        varsadd = []
1668        diagoutvd = list(dvnames)
1669        for nonvd in NONchkvardims:
1670            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1671            varsadd.append(nonvd)
1672
1673        ncvar.insert_variable(ncobj, 'tda', td, dnames, diagoutvd, newnc)
1674
1675# WRFtdas (PSFC, T2, Q2)
1676    elif diagn == 'WRFtdas':
1677        ARM2 = fdef.module_definitions.arm2
1678        ARM3 = fdef.module_definitions.arm3
1679
1680        var0 = ncobj.variables[depvars[0]][:]
1681        var1 = ncobj.variables[depvars[1]][:]
1682        var2 = ncobj.variables[depvars[2]][:]
1683
1684        dnamesvar = list(ncobj.variables[depvars[1]].dimensions)
1685        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1686
1687        rhs, diagoutd, diagoutvd = diag.compute_rh(var0,var1,var2,dnamesvar,dvnamesvar)
1688
1689        gammatarhs = np.log(rhs) + ARM2*(var1-273.15)/((var1-273.15)+ARM3)
1690        tdas = ARM3*gammatarhs/(ARM2-gammatarhs) + 273.15
1691
1692        # Removing the nonChecking variable-dimensions from the initial list
1693        varsadd = []
1694        diagoutvd = list(dvnames)
1695        for nonvd in NONchkvardims:
1696            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1697            varsadd.append(nonvd)
1698
1699        ncvar.insert_variable(ncobj, 'tdas', tdas, dnames, diagoutvd, newnc)
1700
1701# WRFua (U, V, SINALPHA, COSALPHA) to be rotated !!
1702    elif diagn == 'WRFua':
1703        var0 = ncobj.variables[depvars[0]][:]
1704        var1 = ncobj.variables[depvars[1]][:]
1705        var2 = ncobj.variables[depvars[2]][:]
1706        var3 = ncobj.variables[depvars[3]][:]
1707
1708        # un-staggering variables
1709        if len(var0.shape) == 4:
1710            unstgdims = [var0.shape[0], var0.shape[1], var0.shape[2], var0.shape[3]-1]
1711        elif len(var0.shape) == 3:
1712            # Asuming sunding point (dimt, dimz, dimstgx)
1713            unstgdims = [var0.shape[0], var0.shape[1]]
1714
1715        ua = np.zeros(tuple(unstgdims), dtype=np.float)
1716        unstgvar0 = np.zeros(tuple(unstgdims), dtype=np.float)
1717        unstgvar1 = np.zeros(tuple(unstgdims), dtype=np.float)
1718
1719        if len(var0.shape) == 4:
1720            unstgvar0 = 0.5*(var0[:,:,:,0:var0.shape[3]-1] + var0[:,:,:,1:var0.shape[3]])
1721            unstgvar1 = 0.5*(var1[:,:,0:var1.shape[2]-1,:] + var1[:,:,1:var1.shape[2],:])
1722
1723            for iz in range(var0.shape[1]):
1724                ua[:,iz,:,:] = unstgvar0[:,iz,:,:]*var3 - unstgvar1[:,iz,:,:]*var2
1725
1726            dnamesvar = ['Time','bottom_top','south_north','west_east']
1727
1728        elif len(var0.shape) == 3:
1729            unstgvar0 = 0.5*(var0[:,:,0] + var0[:,:,1])
1730            unstgvar1 = 0.5*(var1[:,:,0] + var1[:,:,1])
1731            for iz in range(var0.shape[1]):
1732                ua[:,iz] = unstgvar0[:,iz]*var3 - unstgvar1[:,iz]*var2
1733
1734            dnamesvar = ['Time','bottom_top']
1735
1736        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1737
1738        # Removing the nonChecking variable-dimensions from the initial list
1739        varsadd = []
1740        diagoutvd = list(dvnames)
1741        for nonvd in NONchkvardims:
1742            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1743            varsadd.append(nonvd)
1744
1745        ncvar.insert_variable(ncobj, 'ua', ua, dnames, diagoutvd, newnc)
1746
1747# WRFua (U, V, SINALPHA, COSALPHA) to be rotated !!
1748    elif diagn == 'WRFva':
1749        var0 = ncobj.variables[depvars[0]][:]
1750        var1 = ncobj.variables[depvars[1]][:]
1751        var2 = ncobj.variables[depvars[2]][:]
1752        var3 = ncobj.variables[depvars[3]][:]
1753
1754        # un-staggering variables
1755        if len(var0.shape) == 4:
1756            unstgdims = [var0.shape[0], var0.shape[1], var0.shape[2], var0.shape[3]-1]
1757        elif len(var0.shape) == 3:
1758            # Asuming sunding point (dimt, dimz, dimstgx)
1759            unstgdims = [var0.shape[0], var0.shape[1]]
1760
1761        va = np.zeros(tuple(unstgdims), dtype=np.float)
1762        unstgvar0 = np.zeros(tuple(unstgdims), dtype=np.float)
1763        unstgvar1 = np.zeros(tuple(unstgdims), dtype=np.float)
1764
1765        if len(var0.shape) == 4:
1766            unstgvar0 = 0.5*(var0[:,:,:,0:var0.shape[3]-1] + var0[:,:,:,1:var0.shape[3]])
1767            unstgvar1 = 0.5*(var1[:,:,0:var1.shape[2]-1,:] + var1[:,:,1:var1.shape[2],:])
1768
1769            for iz in range(var0.shape[1]):
1770                va[:,iz,:,:] = unstgvar0[:,iz,:,:]*var2 + unstgvar1[:,iz,:,:]*var3
1771
1772            dnamesvar = ['Time','bottom_top','south_north','west_east']
1773
1774        elif len(var0.shape) == 3:
1775            unstgvar0 = 0.5*(var0[:,:,0] + var0[:,:,1])
1776            unstgvar1 = 0.5*(var1[:,:,0] + var1[:,:,1])
1777            for iz in range(var0.shape[1]):
1778                va[:,iz] = unstgvar0[:,iz]*var2 + unstgvar1[:,iz]*var3
1779
1780            dnamesvar = ['Time','bottom_top']
1781
1782        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1783
1784        # Removing the nonChecking variable-dimensions from the initial list
1785        varsadd = []
1786        diagoutvd = list(dvnames)
1787        for nonvd in NONchkvardims:
1788            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1789            varsadd.append(nonvd)
1790        ncvar.insert_variable(ncobj, 'va', va, dnames, diagoutvd, newnc)
1791
1792
1793# WRFwd (U, V, SINALPHA, COSALPHA) to be rotated !!
1794    elif diagn == 'WRFwd':
1795        var0 = ncobj.variables[depvars[0]][:]
1796        var1 = ncobj.variables[depvars[1]][:]
1797        var2 = ncobj.variables[depvars[2]][:]
1798        var3 = ncobj.variables[depvars[3]][:]
1799
1800        # un-staggering variables
1801        if len(var0.shape) == 4:
1802            unstgdims = [var0.shape[0], var0.shape[1], var0.shape[2], var0.shape[3]-1]
1803        elif len(var0.shape) == 3:
1804            # Asuming sunding point (dimt, dimz, dimstgx)
1805            unstgdims = [var0.shape[0], var0.shape[1]]
1806
1807        ua = np.zeros(tuple(unstgdims), dtype=np.float)
1808        va = np.zeros(tuple(unstgdims), dtype=np.float)
1809        unstgvar0 = np.zeros(tuple(unstgdims), dtype=np.float)
1810        unstgvar1 = np.zeros(tuple(unstgdims), dtype=np.float)
1811
1812        if len(var0.shape) == 4:
1813            unstgvar0 = 0.5*(var0[:,:,:,0:var0.shape[3]-1] + var0[:,:,:,1:var0.shape[3]])
1814            unstgvar1 = 0.5*(var1[:,:,0:var1.shape[2]-1,:] + var1[:,:,1:var1.shape[2],:])
1815
1816            for iz in range(var0.shape[1]):
1817                ua[:,iz,:,:] = unstgvar0[:,iz,:,:]*var3 - unstgvar1[:,iz,:,:]*var2
1818                va[:,iz,:,:] = unstgvar0[:,iz,:,:]*var2 + unstgvar1[:,iz,:,:]*var3
1819
1820            dnamesvar = ['Time','bottom_top','south_north','west_east']
1821
1822        elif len(var0.shape) == 3:
1823            unstgvar0 = 0.5*(var0[:,:,0] + var0[:,:,1])
1824            unstgvar1 = 0.5*(var1[:,:,0] + var1[:,:,1])
1825            for iz in range(var0.shape[1]):
1826                ua[:,iz] = unstgvar0[:,iz]*var3 - unstgvar1[:,iz]*var2
1827                va[:,iz] = unstgvar0[:,iz]*var2 + unstgvar1[:,iz]*var3
1828
1829            dnamesvar = ['Time','bottom_top']
1830
1831        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1832
1833        wd, dnames, dvnames = diag.compute_wd(ua, va, dnamesvar, dvnamesvar)
1834
1835        # Removing the nonChecking variable-dimensions from the initial list
1836        varsadd = []
1837        diagoutvd = list(dvnames)
1838        for nonvd in NONchkvardims:
1839            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1840            varsadd.append(nonvd)
1841
1842        ncvar.insert_variable(ncobj, 'wd', wd, dnames, diagoutvd, newnc)
1843
1844# WRFtime
1845    elif diagn == 'WRFtime':
1846           
1847        diagout = WRFtime
1848
1849        dnamesvar = ['Time']
1850        dvnamesvar = ['Times']
1851
1852        ncvar.insert_variable(ncobj, 'time', diagout, dnamesvar, dvnamesvar, newnc)
1853
1854# ws (U, V)
1855    elif diagn == 'ws':
1856           
1857        # un-staggering variables
1858        if len(var0.shape) == 4:
1859            unstgdims = [var0.shape[0], var0.shape[1], var0.shape[2], var0.shape[3]-1]
1860        elif len(var0.shape) == 3:
1861            # Asuming sunding point (dimt, dimz, dimstgx)
1862            unstgdims = [var0.shape[0], var0.shape[1]]
1863
1864        ua = np.zeros(tuple(unstgdims), dtype=np.float)
1865        va = np.zeros(tuple(unstgdims), dtype=np.float)
1866        unstgvar0 = np.zeros(tuple(unstgdims), dtype=np.float)
1867        unstgvar1 = np.zeros(tuple(unstgdims), dtype=np.float)
1868
1869        if len(var0.shape) == 4:
1870            unstgvar0 = 0.5*(var0[:,:,:,0:var0.shape[3]-1] + var0[:,:,:,1:var0.shape[3]])
1871            unstgvar1 = 0.5*(var1[:,:,0:var1.shape[2]-1,:] + var1[:,:,1:var1.shape[2],:])
1872
1873            for iz in range(var0.shape[1]):
1874                ua[:,iz,:,:] = unstgvar0[:,iz,:,:]*var3 - unstgvar1[:,iz,:,:]*var2
1875                va[:,iz,:,:] = unstgvar0[:,iz,:,:]*var2 + unstgvar1[:,iz,:,:]*var3
1876
1877            dnamesvar = ['Time','bottom_top','south_north','west_east']
1878
1879        elif len(var0.shape) == 3:
1880            unstgvar0 = 0.5*(var0[:,:,0] + var0[:,:,1])
1881            unstgvar1 = 0.5*(var1[:,:,0] + var1[:,:,1])
1882            for iz in range(var0.shape[1]):
1883                ua[:,iz] = unstgvar0[:,iz]*var3 - unstgvar1[:,iz]*var2
1884                va[:,iz] = unstgvar0[:,iz]*var2 + unstgvar1[:,iz]*var3
1885
1886            dnamesvar = ['Time','bottom_top']
1887
1888        diagout = np.sqrt(unstgvar0*unstgvar0 + unstgvar1*unstgvar1)
1889
1890#        dnamesvar = ncobj.variables[depvars[0]].dimensions
1891        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1892
1893        # Removing the nonChecking variable-dimensions from the initial list
1894        varsadd = []
1895        diagoutvd = list(dvnamesvar)
1896        for nonvd in NONchkvardims:
1897            if gen.searchInlist(dvnamesvar,nonvd): diagoutvd.remove(nonvd)
1898            varsadd.append(nonvd)
1899        ncvar.insert_variable(ncobj, 'ws', diagout, dnamesvar, diagoutvd, newnc)
1900
1901# wss (u10, v10)
1902    elif diagn == 'wss':
1903           
1904        var0 = ncobj.variables[depvars[0]][:]
1905        var1 = ncobj.variables[depvars[1]][:]
1906
1907        diagout = np.sqrt(var0*var0 + var1*var1)
1908
1909        dnamesvar = ncobj.variables[depvars[0]].dimensions
1910        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1911
1912        ncvar.insert_variable(ncobj, 'wss', diagout, dnamesvar, dvnamesvar, newnc)
1913
1914# WRFheight height from WRF geopotential as WRFGeop/g
1915    elif diagn == 'WRFheight':
1916           
1917        diagout = WRFgeop/grav
1918
1919        # Removing the nonChecking variable-dimensions from the initial list
1920        varsadd = []
1921        diagoutvd = list(dvnames)
1922        for nonvd in NONchkvardims:
1923            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1924            varsadd.append(nonvd)
1925
1926        ncvar.insert_variable(ncobj, 'zhgt', diagout, dnames, diagoutvd, newnc)
1927
1928# WRFheightrel relative-height from WRF geopotential as WRFgeop(PH + PHB)/g-HGT 'WRFheightrel|PH@PHB@HGT
1929    elif diagn == 'WRFheightrel':
1930        var0 = ncobj.variables[depvars[0]][:]
1931        var1 = ncobj.variables[depvars[1]][:]
1932        var2 = ncobj.variables[depvars[2]][:]
1933
1934        dimz = var0.shape[1]
1935        diagout = np.zeros(tuple(var0.shape), dtype=np.float)
1936        for iz in range(dimz):
1937            diagout[:,iz,:,:] = (var0[:,iz,:,:]+ var1[:,iz,:,:])/grav - var2
1938
1939        # Removing the nonChecking variable-dimensions from the initial list
1940        varsadd = []
1941        diagoutvd = list(dvnames)
1942        for nonvd in NONchkvardims:
1943            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1944            varsadd.append(nonvd)
1945
1946        ncvar.insert_variable(ncobj, 'zhgtrel', diagout, dnames, diagoutvd, newnc)
1947
1948# WRFzmla_gen generic boundary layer hieght computation from WRF theta, QVAPOR, WRFgeop, HGT,
1949    elif diagn == 'WRFzmlagen':
1950        var0 = ncobj.variables[depvars[0]][:]+300.
1951        var1 = ncobj.variables[depvars[1]][:]
1952        dimz = var0.shape[1]
1953        var2 = WRFgeop[:,1:dimz+1,:,:]/9.8
1954        var3 = ncobj.variables[depvars[3]][0,:,:]
1955
1956        diagout, diagoutd, diagoutvd = diag.Forcompute_zmla_gen(var0,var1,var2,var3, \
1957          dnames,dvnames)
1958
1959        # Removing the nonChecking variable-dimensions from the initial list
1960        varsadd = []
1961        for nonvd in NONchkvardims:
1962            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1963            varsadd.append(nonvd)
1964
1965        ncvar.insert_variable(ncobj, 'zmla', diagout, diagoutd, diagoutvd, newnc)
1966
1967# WRFzwind wind extrapolation at a given height using power law computation from WRF
1968#   U, V, WRFz, U10, V10, SINALPHA, COSALPHA, z=[zval]
1969    elif diagn == 'WRFzwind':
1970        var0 = ncobj.variables[depvars[0]][:]
1971        var1 = ncobj.variables[depvars[1]][:]
1972        var2 = WRFz
1973        var3 = ncobj.variables[depvars[3]][:]
1974        var4 = ncobj.variables[depvars[4]][:]
1975        var5 = ncobj.variables[depvars[5]][0,:,:]
1976        var6 = ncobj.variables[depvars[6]][0,:,:]
1977        var7 = np.float(depvars[7].split('=')[1])
1978
1979        # un-staggering 3D winds
1980        unstgdims = [var0.shape[0], var0.shape[1], var0.shape[2], var0.shape[3]-1]
1981        va = np.zeros(tuple(unstgdims), dtype=np.float)
1982        unvar0 = np.zeros(tuple(unstgdims), dtype=np.float)
1983        unvar1 = np.zeros(tuple(unstgdims), dtype=np.float)
1984        unvar0 = 0.5*(var0[:,:,:,0:var0.shape[3]-1] + var0[:,:,:,1:var0.shape[3]])
1985        unvar1 = 0.5*(var1[:,:,0:var1.shape[2]-1,:] + var1[:,:,1:var1.shape[2],:])
1986
1987        diagout1, diagout2, diagoutd, diagoutvd = diag.Forcompute_zwind(unvar0,      \
1988          unvar1, var2, var3, var4, var5, var6, var7, dnames, dvnames)
1989
1990        # Removing the nonChecking variable-dimensions from the initial list
1991        varsadd = []
1992        for nonvd in NONchkvardims:
1993            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1994            varsadd.append(nonvd)
1995
1996        ncvar.insert_variable(ncobj, 'uaz', diagout1, diagoutd, diagoutvd, newnc)
1997        ncvar.insert_variable(ncobj, 'vaz', diagout2, diagoutd, diagoutvd, newnc)
1998
1999# WRFzwind wind extrapolation at a given hieght using logarithmic law computation
2000#   from WRF U, V, WRFz, U10, V10, SINALPHA, COSALPHA, z=[zval]
2001    elif diagn == 'WRFzwind_log':
2002        var0 = ncobj.variables[depvars[0]][:]
2003        var1 = ncobj.variables[depvars[1]][:]
2004        var2 = WRFz
2005        var3 = ncobj.variables[depvars[3]][:]
2006        var4 = ncobj.variables[depvars[4]][:]
2007        var5 = ncobj.variables[depvars[5]][0,:,:]
2008        var6 = ncobj.variables[depvars[6]][0,:,:]
2009        var7 = np.float(depvars[7].split('=')[1])
2010
2011        # un-staggering 3D winds
2012        unstgdims = [var0.shape[0], var0.shape[1], var0.shape[2], var0.shape[3]-1]
2013        va = np.zeros(tuple(unstgdims), dtype=np.float)
2014        unvar0 = np.zeros(tuple(unstgdims), dtype=np.float)
2015        unvar1 = np.zeros(tuple(unstgdims), dtype=np.float)
2016        unvar0 = 0.5*(var0[:,:,:,0:var0.shape[3]-1] + var0[:,:,:,1:var0.shape[3]])
2017        unvar1 = 0.5*(var1[:,:,0:var1.shape[2]-1,:] + var1[:,:,1:var1.shape[2],:])
2018
2019        diagout1, diagout2, diagoutd, diagoutvd = diag.Forcompute_zwind_log(unvar0,  \
2020          unvar1, var2, var3, var4, var5, var6, var7, dnames, dvnames)
2021
2022        # Removing the nonChecking variable-dimensions from the initial list
2023        varsadd = []
2024        for nonvd in NONchkvardims:
2025            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
2026            varsadd.append(nonvd)
2027
2028        ncvar.insert_variable(ncobj, 'uaz', diagout1, diagoutd, diagoutvd, newnc)
2029        ncvar.insert_variable(ncobj, 'vaz', diagout2, diagoutd, diagoutvd, newnc)
2030
2031# WRFzwindMO wind extrapolation at a given height computation using Monin-Obukhow
2032#   theory from WRF UST, ZNT, RMOL, U10, V10, SINALPHA, COSALPHA, z=[zval]
2033#   NOTE: only useful for [zval] < 80. m
2034    elif diagn == 'WRFzwindMO':
2035        var0 = ncobj.variables[depvars[0]][:]
2036        var1 = ncobj.variables[depvars[1]][:]
2037        var2 = ncobj.variables[depvars[2]][:]
2038        var3 = ncobj.variables[depvars[3]][:]
2039        var4 = ncobj.variables[depvars[4]][:]
2040        var5 = ncobj.variables[depvars[5]][0,:,:]
2041        var6 = ncobj.variables[depvars[6]][0,:,:]
2042        var7 = np.float(depvars[7].split('=')[1])
2043
2044        diagout1, diagout2, diagoutd, diagoutvd = diag.Forcompute_zwindMO(var0, var1,\
2045          var2, var3, var4, var5, var6, var7, dnames, dvnames)
2046
2047        # Removing the nonChecking variable-dimensions from the initial list
2048        varsadd = []
2049        for nonvd in NONchkvardims:
2050            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
2051            varsadd.append(nonvd)
2052
2053        ncvar.insert_variable(ncobj, 'uaz', diagout1, diagoutd, diagoutvd, newnc)
2054        ncvar.insert_variable(ncobj, 'vaz', diagout2, diagoutd, diagoutvd, newnc)
2055
2056    else:
2057        print errormsg
2058        print '  ' + main + ": diagnostic '" + diagn + "' not ready!!!"
2059        print '    available diagnostics: ', availdiags
2060        quit(-1)
2061
2062    newnc.sync()
2063    # Adding that additional variables required to compute some diagnostics which
2064    #   where not in the original file
2065    print '  adding additional variables...'
2066    for vadd in varsadd:
2067        if not gen.searchInlist(newnc.variables.keys(),vadd) and                     \
2068          dictcompvars.has_key(vadd):
2069            attrs = dictcompvars[vadd]
2070            vvn = attrs['name']
2071            if not gen.searchInlist(newnc.variables.keys(), vvn):
2072                iidvn = dvnames.index(vadd)
2073                dnn = dnames[iidvn]
2074                if vadd == 'WRFtime':
2075                    dvarvals = WRFtime[:]
2076                newvar = newnc.createVariable(vvn, 'f8', (dnn))
2077                newvar[:] = dvarvals
2078                for attn in attrs.keys():
2079                    if attn != 'name':
2080                        attv = attrs[attn]
2081                        ncvar.set_attribute(newvar, attn, attv)
2082
2083#   end of diagnostics
2084
2085# Global attributes
2086##
2087ncvar.add_global_PyNCplot(newnc, main, None, '2.0')
2088
2089gorigattrs = ncobj.ncattrs()
2090for attr in gorigattrs:
2091    attrv = ncobj.getncattr(attr)
2092    atvar = ncvar.set_attribute(newnc, attr, attrv)
2093
2094ncobj.close()
2095newnc.close()
2096
2097print '\n' + main + ': successfull writting of diagnostics file "' + ofile + '" !!!'
Note: See TracBrowser for help on using the repository browser.