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

Last change on this file since 2347 was 2346, checked in by lfita, 6 years ago

Adding on `WRFbnds', checking if there is 'XLONG' or 'XLONG_M'

File size: 84.8 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        if newnc.variables.has_key('XLONG'):
963            ovar = newnc.variables['XLONG']
964            ovar.setncattr('bounds', 'lon_bnds lat_bnds')
965            ovar = newnc.variables['XLAT']
966            ovar.setncattr('bounds', 'lon_bnds lat_bnds')
967        elif newnc.variables.has_key('XLONG_M'):
968            ovar = newnc.variables['XLONG_M']
969            ovar.setncattr('bounds', 'lon_bnds lat_bnds')
970            ovar = newnc.variables['XLAT_M']
971            ovar.setncattr('bounds', 'lon_bnds lat_bnds')
972        else:
973            print errormsg
974            print '  ' + fname + ": error computing diagnostic '" + diagn + "' !!"
975            print "    neither: 'XLONG', 'XLONG_M' have been found"
976            quit(-1)
977
978# mrso: total soil moisture SMOIS, DZS
979    elif diagn == 'WRFmrso':
980           
981        var0 = ncobj.variables[depvars[0]][:]
982        var10 = ncobj.variables[depvars[1]][:]
983        dnamesvar = list(ncobj.variables[depvars[0]].dimensions)
984        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
985
986        var1 = var0.copy()*0.
987        var2 = var0.copy()*0.+1.
988        # Must be a better way....
989        for j in range(var0.shape[2]):
990          for i in range(var0.shape[3]):
991              var1[:,:,j,i] = var10
992
993        diagout, diagoutd, diagoutvd = diag.Forcompute_zint(var0, var1, var2,        \
994          dnamesvar, dvnamesvar)
995
996        # Removing the nonChecking variable-dimensions from the initial list
997        varsadd = []
998        diagoutvd = list(dvnames)
999        for nonvd in NONchkvardims:
1000            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1001            varsadd.append(nonvd)
1002        ncvar.insert_variable(ncobj, 'mrso', diagout, diagoutd, diagoutvd, newnc)
1003
1004# mrsos: First layer soil moisture SMOIS, DZS
1005    elif diagn == 'WRFmrsos':
1006           
1007        var0 = ncobj.variables[depvars[0]][:]
1008        var1 = ncobj.variables[depvars[1]][:]
1009        diagoutd = list(ncobj.variables[depvars[0]].dimensions)
1010        diagoutvd = ncvar.var_dim_dimv(diagoutd,dnames,dvnames)
1011
1012        diagoutd.pop(1)
1013        diagoutvd.pop(1)
1014
1015        diagout= np.zeros((var0.shape[0],var0.shape[2],var0.shape[3]), dtype=np.float)
1016
1017        # Must be a better way....
1018        for j in range(var0.shape[2]):
1019          for i in range(var0.shape[3]):
1020              diagout[:,j,i] = var0[:,0,j,i]*var1[:,0]
1021
1022        # Removing the nonChecking variable-dimensions from the initial list
1023        varsadd = []
1024        diagoutvd = list(dvnames)
1025        for nonvd in NONchkvardims:
1026            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1027            varsadd.append(nonvd)
1028        ncvar.insert_variable(ncobj, 'mrsos', diagout, diagoutd, diagoutvd, newnc)
1029
1030# mslp: mean sea level pressure (pres, psfc, terrain, temp, qv)
1031    elif diagn == 'mslp' or diagn == 'WRFmslp':
1032           
1033        var1 = ncobj.variables[depvars[1]][:]
1034        var2 = ncobj.variables[depvars[2]][:]
1035        var4 = ncobj.variables[depvars[4]][:]
1036
1037        if diagn == 'WRFmslp':
1038            var0 = WRFp
1039            var3 = WRFt
1040            dnamesvar = ncobj.variables['P'].dimensions
1041        else:
1042            var0 = ncobj.variables[depvars[0]][:]
1043            var3 = ncobj.variables[depvars[3]][:]
1044            dnamesvar = ncobj.variables[depvars[0]].dimensions
1045
1046        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1047
1048        diagout, diagoutd, diagoutvd = diag.compute_mslp(var0, var1, var2, var3, var4,    \
1049          dnamesvar, dvnamesvar)
1050
1051        # Removing the nonChecking variable-dimensions from the initial list
1052        varsadd = []
1053        diagoutvd = list(dvnames)
1054        for nonvd in NONchkvardims:
1055            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1056            varsadd.append(nonvd)
1057        ncvar.insert_variable(ncobj, 'psl', diagout, diagoutd, diagoutvd, newnc)
1058
1059# OMEGAw (omega, p, t) from NCL formulation (https://www.ncl.ucar.edu/Document/Functions/Contributed/omega_to_w.shtml)
1060    elif diagn == 'OMEGAw':
1061           
1062        var0 = ncobj.variables[depvars[0]][:]
1063        var1 = ncobj.variables[depvars[1]][:]
1064        var2 = ncobj.variables[depvars[2]][:]
1065
1066        dnamesvar = ncobj.variables[depvars[0]].dimensions
1067        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1068
1069        diagout, diagoutd, diagoutvd = diag.compute_OMEGAw(var0,var1,var2,dnamesvar,dvnamesvar)
1070
1071        ncvar.insert_variable(ncobj, 'wa', diagout, diagoutd, diagoutvd, newnc)
1072
1073# raintot: instantaneous total precipitation from WRF as (RAINC + RAINC + RAINSH) / dTime
1074    elif diagn == 'RAINTOT':
1075
1076        var0 = ncobj.variables[depvars[0]]
1077        var1 = ncobj.variables[depvars[1]]
1078        var2 = ncobj.variables[depvars[2]]
1079
1080        if depvars[3] != 'WRFtime':
1081            var3 = ncobj.variables[depvars[3]]
1082        else:
1083            var3 = np.arange(var0.shape[0], dtype=int)
1084
1085        var = var0[:] + var1[:] + var2[:]
1086
1087        dnamesvar = var0.dimensions
1088        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1089
1090        diagout, diagoutd, diagoutvd = diag.compute_deaccum(var,dnamesvar,dvnamesvar)
1091
1092# Transforming to a flux
1093        if var3.shape[0] > 1:
1094            if depvars[3] != 'WRFtime':
1095                dtimeunits = var3.getncattr('units')
1096                tunits = dtimeunits.split(' ')[0]
1097   
1098                dtime = (var3[1] - var3[0])*diag.timeunits_seconds(tunits)
1099            else:
1100                var3 = ncobj.variables['Times']
1101                time1 = var3[0,:]
1102                time2 = var3[1,:]
1103                tmf1 = ''
1104                tmf2 = ''
1105                for ic in range(len(time1)):
1106                    tmf1 = tmf1 + time1[ic]
1107                    tmf2 = tmf2 + time2[ic]
1108                dtdate1 = dtime.datetime.strptime(tmf1,"%Y-%m-%d_%H:%M:%S")
1109                dtdate2 = dtime.datetime.strptime(tmf2,"%Y-%m-%d_%H:%M:%S")
1110                diffdate12 = dtdate2 - dtdate1
1111                dtime = diffdate12.total_seconds()
1112                print 'dtime:',dtime
1113        else:
1114            print warnmsg
1115            print '  ' + main + ": only 1 time-step for '" + diag + "' !!"
1116            print '    leaving a zero value!'
1117            diagout = var0[:]*0.
1118            dtime=1.
1119
1120        # Removing the nonChecking variable-dimensions from the initial list
1121        varsadd = []
1122        for nonvd in NONchkvardims:
1123            if gen.searchInlist(diagoutvd,nonvd): diagoutvd.remove(nonvd)
1124            varsadd.append(nonvd)
1125           
1126        ncvar.insert_variable(ncobj, 'pr', diagout/dtime, diagoutd, diagoutvd, newnc)
1127
1128# timemax ([varname], time). When a given variable [varname] got its maximum
1129    elif diagn == 'timemax':
1130           
1131        var0 = ncobj.variables[depvars[0]][:]
1132        var1 = ncobj.variables[depvars[1]][:]
1133
1134        otime = ncobj.variables[depvars[1]]
1135
1136        dnamesvar = ncobj.variables[depvars[0]].dimensions
1137        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1138
1139        diagout, diagoutd, diagoutvd  = diag.var_timemax(var0, var1, dnames,         \
1140          dvnames)
1141
1142        ncvar.insert_variable(ncobj, 'timemax', diagout, diagoutd, diagoutvd, newnc, \
1143          fill=gen.fillValueF)
1144        # Getting the right units
1145        ovar = newnc.variables['timemax']
1146        if gen.searchInlist(otime.ncattrs(), 'units'): 
1147            tunits = otime.getncattr('units')
1148            ncvar.set_attribute(ovar, 'units', tunits)
1149            newnc.sync()
1150        ncvar.set_attribute(ovar, 'variable', depvars[0])
1151
1152# timeoverthres ([varname], time, [value], [CFvarn]). When a given variable [varname]   
1153#   overpass a given [value]. Being [CFvarn] the name of the diagnostics in
1154#   variables_values.dat
1155    elif diagn == 'timeoverthres':
1156           
1157        var0 = ncobj.variables[depvars[0]][:]
1158        var1 = ncobj.variables[depvars[1]][:]
1159        var2 = np.float(depvars[2])
1160        var3 = depvars[3]
1161
1162        otime = ncobj.variables[depvars[1]]
1163
1164        dnamesvar = ncobj.variables[depvars[0]].dimensions
1165        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1166
1167        diagout, diagoutd, diagoutvd  = diag.var_timeoverthres(var0, var1, var2,     \
1168          dnames, dvnames)
1169
1170        ncvar.insert_variable(ncobj, var3, diagout, diagoutd, diagoutvd, newnc, \
1171          fill=gen.fillValueF)
1172        # Getting the right units
1173        ovar = newnc.variables[var3]
1174        if gen.searchInlist(otime.ncattrs(), 'units'): 
1175            tunits = otime.getncattr('units')
1176            ncvar.set_attribute(ovar, 'units', tunits)
1177            newnc.sync()
1178        ncvar.set_attribute(ovar, 'overpassed_threshold', var2)
1179
1180# rhs (psfc, t, q) from TimeSeries files
1181    elif diagn == 'TSrhs':
1182           
1183        p0=100000.
1184        var0 = ncobj.variables[depvars[0]][:]
1185        var1 = (ncobj.variables[depvars[1]][:])*(var0/p0)**(2./7.)
1186        var2 = ncobj.variables[depvars[2]][:]
1187
1188        dnamesvar = ncobj.variables[depvars[0]].dimensions
1189        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1190
1191        diagout, diagoutd, diagoutvd = diag.compute_rh(var0,var1,var2,dnamesvar,dvnamesvar)
1192
1193        ncvar.insert_variable(ncobj, 'hurs', diagout, diagoutd, diagoutvd, newnc)
1194
1195# slw: total soil liquid water SH2O, DZS
1196    elif diagn == 'WRFslw':
1197           
1198        var0 = ncobj.variables[depvars[0]][:]
1199        var10 = ncobj.variables[depvars[1]][:]
1200        dnamesvar = list(ncobj.variables[depvars[0]].dimensions)
1201        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1202
1203        var1 = var0.copy()*0.
1204        var2 = var0.copy()*0.+1.
1205        # Must be a better way....
1206        for j in range(var0.shape[2]):
1207          for i in range(var0.shape[3]):
1208              var1[:,:,j,i] = var10
1209
1210        diagout, diagoutd, diagoutvd = diag.Forcompute_zint(var0, var1, var2,        \
1211          dnamesvar, dvnamesvar)
1212
1213        # Removing the nonChecking variable-dimensions from the initial list
1214        varsadd = []
1215        diagoutvd = list(dvnames)
1216        for nonvd in NONchkvardims:
1217            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1218            varsadd.append(nonvd)
1219        ncvar.insert_variable(ncobj, 'slw', diagout, diagoutd, diagoutvd, newnc)
1220
1221# td (psfc, t, q) from TimeSeries files
1222    elif diagn == 'TStd' or diagn == 'td':
1223           
1224        var0 = ncobj.variables[depvars[0]][:]
1225        var1 = ncobj.variables[depvars[1]][:] - 273.15
1226        var2 = ncobj.variables[depvars[2]][:]
1227
1228        dnamesvar = ncobj.variables[depvars[0]].dimensions
1229        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1230
1231        diagout, diagoutd, diagoutvd = diag.compute_td(var0,var1,var2,dnamesvar,dvnamesvar)
1232
1233        ncvar.insert_variable(ncobj, 'tdas', diagout, diagoutd, diagoutvd, newnc)
1234
1235# td (psfc, t, q) from TimeSeries files
1236    elif diagn == 'TStdC' or diagn == 'tdC':
1237           
1238        var0 = ncobj.variables[depvars[0]][:]
1239# Temperature is already in degrees Celsius
1240        var1 = ncobj.variables[depvars[1]][:]
1241        var2 = ncobj.variables[depvars[2]][:]
1242
1243        dnamesvar = ncobj.variables[depvars[0]].dimensions
1244        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1245
1246        diagout, diagoutd, diagoutvd = diag.compute_td(var0,var1,var2,dnamesvar,dvnamesvar)
1247
1248        # Removing the nonChecking variable-dimensions from the initial list
1249        varsadd = []
1250        for nonvd in NONchkvardims:
1251            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1252            varsadd.append(nonvd)
1253
1254        ncvar.insert_variable(ncobj, 'tdas', diagout, diagoutd, diagoutvd, newnc)
1255
1256# wds (u, v)
1257    elif diagn == 'TSwds' or diagn == 'wds' :
1258 
1259        var0 = ncobj.variables[depvars[0]][:]
1260        var1 = ncobj.variables[depvars[1]][:]
1261
1262        dnamesvar = ncobj.variables[depvars[0]].dimensions
1263        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1264
1265        diagout, diagoutd, diagoutvd = diag.compute_wds(var0,var1,dnamesvar,dvnamesvar)
1266
1267        # Removing the nonChecking variable-dimensions from the initial list
1268        varsadd = []
1269        for nonvd in NONchkvardims:
1270            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1271            varsadd.append(nonvd)
1272
1273        ncvar.insert_variable(ncobj, 'wds', diagout, diagoutd, diagoutvd, newnc)
1274
1275# wss (u, v)
1276    elif diagn == 'TSwss' or diagn == 'wss':
1277           
1278        var0 = ncobj.variables[depvars[0]][:]
1279        var1 = ncobj.variables[depvars[1]][:]
1280
1281        dnamesvar = ncobj.variables[depvars[0]].dimensions
1282        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1283
1284        diagout, diagoutd, diagoutvd = diag.compute_wss(var0,var1,dnamesvar,dvnamesvar)
1285
1286        # Removing the nonChecking variable-dimensions from the initial list
1287        varsadd = []
1288        for nonvd in NONchkvardims:
1289            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1290            varsadd.append(nonvd)
1291
1292        ncvar.insert_variable(ncobj, 'wss', diagout, diagoutd, diagoutvd, newnc)
1293
1294# turbulence (var)
1295    elif diagn == 'turbulence':
1296
1297        var0 = ncobj.variables[depvars][:]
1298
1299        dnamesvar = list(ncobj.variables[depvars].dimensions)
1300        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1301
1302        diagout, diagoutd, diagoutvd = diag.compute_turbulence(var0,dnamesvar,dvnamesvar)
1303        valsvar = gen.variables_values(depvars)
1304
1305        newvarn = depvars + 'turb'
1306        ncvar.insert_variable(ncobj, newvarn, diagout, diagoutd, 
1307          diagoutvd, newnc)
1308        varobj = newnc.variables[newvarn]
1309        attrv = varobj.long_name
1310        attr = varobj.delncattr('long_name')
1311        newattr = ncvar.set_attribute(varobj, 'long_name', attrv +                   \
1312          " Taylor decomposition turbulence term")
1313
1314# ua va from ws wd (deg)
1315    elif diagn == 'uavaFROMwswd':
1316           
1317        var0 = ncobj.variables[depvars[0]][:]
1318        var1 = ncobj.variables[depvars[1]][:]
1319
1320        ua = var0*np.cos(var1*np.pi/180.)
1321        va = var0*np.sin(var1*np.pi/180.)
1322
1323        dnamesvar = ncobj.variables[depvars[0]].dimensions
1324        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1325
1326        ncvar.insert_variable(ncobj, 'ua', ua, dnamesvar, dvnamesvar, newnc)
1327        ncvar.insert_variable(ncobj, 'va', va, dnamesvar, dvnamesvar, newnc)
1328
1329# ua va from obs ws wd (deg)
1330    elif diagn == 'uavaFROMobswswd':
1331           
1332        var0 = ncobj.variables[depvars[0]][:]
1333        var1 = ncobj.variables[depvars[1]][:]
1334
1335        ua = var0*np.cos((var1+180.)*np.pi/180.)
1336        va = var0*np.sin((var1+180.)*np.pi/180.)
1337
1338        dnamesvar = ncobj.variables[depvars[0]].dimensions
1339        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1340
1341        ncvar.insert_variable(ncobj, 'ua', ua, dnamesvar, dvnamesvar, newnc)
1342        ncvar.insert_variable(ncobj, 'va', va, dnamesvar, dvnamesvar, newnc)
1343
1344# WRFbils fom WRF as HFX + LH
1345    elif diagn == 'WRFbils':
1346           
1347        var0 = ncobj.variables[depvars[0]][:]
1348        var1 = ncobj.variables[depvars[1]][:]
1349
1350        diagout = var0 + var1
1351        dnamesvar = list(ncobj.variables[depvars[0]].dimensions)
1352        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1353
1354        ncvar.insert_variable(ncobj, 'bils', diagout, dnamesvar, dvnamesvar, newnc)
1355
1356# WRFcape_afwa CAPE, CIN, ZLFC, PLFC, LI following WRF 'phys/module_diaf_afwa.F'
1357#   methodology as WRFt, WRFrh, WRFp, WRFgeop, HGT
1358    elif diagn == 'WRFcape_afwa':
1359        var0 = WRFt
1360        var1 = WRFrh
1361        var2 = WRFp
1362        dz = WRFgeop.shape[1]
1363        # de-staggering
1364        var3 = 0.5*(WRFgeop[:,0:dz-1,:,:]+WRFgeop[:,1:dz,:,:])/9.8
1365        var4 = ncobj.variables[depvars[4]][0,:,:]
1366
1367        dnamesvar = list(ncobj.variables['T'].dimensions)
1368        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1369
1370        diagout = np.zeros(var0.shape, dtype=np.float)
1371        diagout1, diagout2, diagout3, diagout4, diagout5, diagoutd, diagoutvd =      \
1372          diag.Forcompute_cape_afwa(var0, var1, var2, var3, var4, 3, dnamesvar,      \
1373          dvnamesvar)
1374
1375        # Removing the nonChecking variable-dimensions from the initial list
1376        varsadd = []
1377        for nonvd in NONchkvardims:
1378            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1379            varsadd.append(nonvd)
1380
1381        ncvar.insert_variable(ncobj, 'cape', diagout1, diagoutd, diagoutvd, newnc)
1382        ncvar.insert_variable(ncobj, 'cin', diagout2, diagoutd, diagoutvd, newnc)
1383        ncvar.insert_variable(ncobj, 'zlfc', diagout3, diagoutd, diagoutvd, newnc)
1384        ncvar.insert_variable(ncobj, 'plfc', diagout4, diagoutd, diagoutvd, newnc)
1385        ncvar.insert_variable(ncobj, 'li', diagout5, diagoutd, diagoutvd, newnc)
1386
1387# WRFclivi WRF water vapour path WRFdens, QICE, QGRAUPEL, QHAIL
1388    elif diagn == 'WRFclivi':
1389           
1390        var0 = WRFdens
1391        qtot = ncobj.variables[depvars[1]]
1392        qtotv = qtot[:]
1393        Nspecies = len(depvars) - 2
1394        for iv in range(Nspecies):
1395            if ncobj.variables.has_key(depvars[iv+2]):
1396                var1 = ncobj.variables[depvars[iv+2]][:]
1397                qtotv = qtotv + var1
1398
1399        dnamesvar = list(qtot.dimensions)
1400        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1401
1402        diagout, diagoutd, diagoutvd = diag.compute_clivi(var0, qtotv, dnamesvar,dvnamesvar)
1403
1404        # Removing the nonChecking variable-dimensions from the initial list
1405        varsadd = []
1406        diagoutvd = list(dvnames)
1407        for nonvd in NONchkvardims:
1408            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1409            varsadd.append(nonvd)
1410        ncvar.insert_variable(ncobj, 'clivi', diagout, diagoutd, diagoutvd, newnc)
1411
1412# WRFclwvi WRF water cloud-condensed path WRFdens, QCLOUD, QICE, QGRAUPEL, QHAIL
1413    elif diagn == 'WRFclwvi':
1414           
1415        var0 = WRFdens
1416        qtot = ncobj.variables[depvars[1]]
1417        qtotv = ncobj.variables[depvars[1]]
1418        Nspecies = len(depvars) - 2
1419        for iv in range(Nspecies):
1420            if ncobj.variables.has_key(depvars[iv+2]):
1421                var1 = ncobj.variables[depvars[iv+2]]
1422                qtotv = qtotv + var1[:]
1423
1424        dnamesvar = list(qtot.dimensions)
1425        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1426
1427        diagout, diagoutd, diagoutvd = diag.compute_clwvl(var0, qtotv, dnamesvar,dvnamesvar)
1428
1429        # Removing the nonChecking variable-dimensions from the initial list
1430        varsadd = []
1431        diagoutvd = list(dvnames)
1432        for nonvd in NONchkvardims:
1433            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1434            varsadd.append(nonvd)
1435        ncvar.insert_variable(ncobj, 'clwvi', diagout, diagoutd, diagoutvd, newnc)
1436
1437# WRF_denszint WRF vertical integration as WRFdens, sum(Q[water species1], ..., Q[water speciesN]), varn=[varN]
1438    elif diagn == 'WRF_denszint':
1439           
1440        var0 = WRFdens
1441        varn = depvars[1].split('=')[1]
1442        qtot = ncobj.variables[depvars[2]]
1443        qtotv = ncobj.variables[depvars[2]]
1444        Nspecies = len(depvars) - 2
1445        for iv in range(Nspecies):
1446            if ncobj.variables.has_key(depvars[iv+2]):
1447                var1 = ncobj.variables[depvars[iv+2]]
1448                qtotv = qtotv + var1[:]
1449
1450        dnamesvar = list(qtot.dimensions)
1451        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1452
1453        diagout, diagoutd, diagoutvd = diag.compute_clwvl(var0, qtotv, dnamesvar,dvnamesvar)
1454
1455        # Removing the nonChecking variable-dimensions from the initial list
1456        varsadd = []
1457        diagoutvd = list(dvnames)
1458        for nonvd in NONchkvardims:
1459            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1460            varsadd.append(nonvd)
1461        ncvar.insert_variable(ncobj, varn, diagout, diagoutd, diagoutvd, newnc)
1462
1463# WRFgeop geopotential from WRF as PH + PHB
1464    elif diagn == 'WRFgeop':
1465        var0 = ncobj.variables[depvars[0]][:]
1466        var1 = ncobj.variables[depvars[1]][:]
1467
1468        # de-staggering geopotential
1469        diagout0 = var0 + var1
1470        dt = diagout0.shape[0]
1471        dz = diagout0.shape[1]
1472        dy = diagout0.shape[2]
1473        dx = diagout0.shape[3]
1474
1475        diagout = np.zeros((dt,dz-1,dy,dx), dtype=np.float)
1476        diagout = 0.5*(diagout0[:,1:dz,:,:]+diagout0[:,0:dz-1,:,:])
1477
1478        # Removing the nonChecking variable-dimensions from the initial list
1479        varsadd = []
1480        diagoutvd = list(dvnames)
1481        for nonvd in NONchkvardims:
1482            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1483            varsadd.append(nonvd)
1484
1485        ncvar.insert_variable(ncobj, 'zg', diagout, dnames, diagoutvd, newnc)
1486
1487# WRFpotevap_orPM potential evapotranspiration following Penman-Monteith formulation
1488#   implemented in ORCHIDEE (in src_sechiba/enerbil.f90) as: WRFdens, UST, U10, V10, T2, PSFC, QVAPOR
1489    elif diagn == 'WRFpotevap_orPM':
1490        var0 = WRFdens[:,0,:,:]
1491        var1 = ncobj.variables[depvars[1]][:]
1492        var2 = ncobj.variables[depvars[2]][:]
1493        var3 = ncobj.variables[depvars[3]][:]
1494        var4 = ncobj.variables[depvars[4]][:]
1495        var5 = ncobj.variables[depvars[5]][:]
1496        var6 = ncobj.variables[depvars[6]][:,0,:,:]
1497
1498        dnamesvar = list(ncobj.variables[depvars[1]].dimensions)
1499        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1500
1501        diagout = np.zeros(var1.shape, dtype=np.float)
1502        diagout, diagoutd, diagoutvd = diag.Forcompute_potevap_orPM(var0, var1, var2,\
1503          var3, var4, var5, var6, dnamesvar, dvnamesvar)
1504
1505        # Removing the nonChecking variable-dimensions from the initial list
1506        varsadd = []
1507        for nonvd in NONchkvardims:
1508            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1509            varsadd.append(nonvd)
1510
1511        ncvar.insert_variable(ncobj, 'evspsblpot', diagout, diagoutd, diagoutvd, newnc)
1512
1513# WRFmslp_ptarget sea-level pressure following ECMWF method as PSFC, HGT, WRFt, WRFp, ZNU, ZNW
1514    elif diagn == 'WRFpsl_ecmwf':
1515        var0 = ncobj.variables[depvars[0]][:]
1516        var1 = ncobj.variables[depvars[1]][0,:,:]
1517        var2 = WRFt[:,0,:,:]
1518        var4 = WRFp[:,0,:,:]
1519        var5 = ncobj.variables[depvars[4]][0,:]
1520        var6 = ncobj.variables[depvars[5]][0,:]
1521
1522        # This is quite too appriximate!! passing pressure at half-levels to 2nd full
1523        #   level, using eta values at full (ZNW) and half (ZNU) mass levels
1524        var3 = WRFp[:,0,:,:] + (var6[1] - var5[0])*(WRFp[:,1,:,:] - WRFp[:,0,:,:])/  \
1525          (var5[1]-var5[0])
1526
1527        dnamesvar = list(ncobj.variables[depvars[0]].dimensions)
1528        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1529
1530        diagout = np.zeros(var0.shape, dtype=np.float)
1531        diagout, diagoutd, diagoutvd = diag.Forcompute_psl_ecmwf(var0, var1, var2,   \
1532          var3, var4, dnamesvar, dvnamesvar)
1533
1534        # Removing the nonChecking variable-dimensions from the initial list
1535        varsadd = []
1536        for nonvd in NONchkvardims:
1537            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1538            varsadd.append(nonvd)
1539
1540        ncvar.insert_variable(ncobj, 'psl', diagout, diagoutd, diagoutvd, newnc)
1541
1542# WRFmslp_ptarget sea-level pressure following ptarget method as WRFp, PSFC, WRFt, HGT, QVAPOR
1543    elif diagn == 'WRFpsl_ptarget':
1544        var0 = WRFp
1545        var1 = ncobj.variables[depvars[1]][:]
1546        var2 = WRFt
1547        var3 = ncobj.variables[depvars[3]][0,:,:]
1548        var4 = ncobj.variables[depvars[4]][:]
1549
1550        dnamesvar = list(ncobj.variables[depvars[4]].dimensions)
1551        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1552
1553        diagout = np.zeros(var0.shape, dtype=np.float)
1554        diagout, diagoutd, diagoutvd = diag.Forcompute_psl_ptarget(var0, var1, var2, \
1555          var3, var4, 700000., dnamesvar, dvnamesvar)
1556
1557        # Removing the nonChecking variable-dimensions from the initial list
1558        varsadd = []
1559        for nonvd in NONchkvardims:
1560            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1561            varsadd.append(nonvd)
1562
1563        ncvar.insert_variable(ncobj, 'psl', diagout, diagoutd, diagoutvd, newnc)
1564
1565# WRFp pressure from WRF as P + PB
1566    elif diagn == 'WRFp':
1567        var0 = ncobj.variables[depvars[0]][:]
1568        var1 = ncobj.variables[depvars[1]][:]
1569           
1570        diagout = var0 + var1
1571        diagoutd = list(ncobj.variables[depvars[0]].dimensions)
1572        diagoutvd = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1573
1574        # Removing the nonChecking variable-dimensions from the initial list
1575        varsadd = []
1576        for nonvd in NONchkvardims:
1577            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1578            varsadd.append(nonvd)
1579
1580        ncvar.insert_variable(ncobj, 'pres', diagout, diagoutd, diagoutvd, newnc)
1581
1582# WRFpos
1583    elif diagn == 'WRFpos':
1584           
1585        dnamesvar = ncobj.variables['MAPFAC_M'].dimensions
1586        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1587
1588        ncvar.insert_variable(ncobj, 'WRFpos', WRFpos, dnamesvar, dvnamesvar, newnc)
1589
1590# WRFprw WRF water vapour path WRFdens, QVAPOR
1591    elif diagn == 'WRFprw':
1592           
1593        var0 = WRFdens
1594        var1 = ncobj.variables[depvars[1]]
1595
1596        dnamesvar = list(var1.dimensions)
1597        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1598
1599        diagout, diagoutd, diagoutvd = diag.compute_prw(var0, var1, dnamesvar,dvnamesvar)
1600
1601        # Removing the nonChecking variable-dimensions from the initial list
1602        varsadd = []
1603        diagoutvd = list(dvnames)
1604        for nonvd in NONchkvardims:
1605            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1606            varsadd.append(nonvd)
1607        ncvar.insert_variable(ncobj, 'prw', diagout, diagoutd, diagoutvd, newnc)
1608
1609# WRFrh (P, T, QVAPOR)
1610    elif diagn == 'WRFrh':
1611           
1612        dnamesvar = list(ncobj.variables[depvars[2]].dimensions)
1613        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1614
1615        ncvar.insert_variable(ncobj, 'hur', WRFrh, dnames, dvnames, newnc)
1616
1617# WRFrhs (PSFC, T2, Q2)
1618    elif diagn == 'WRFrhs':
1619           
1620        var0 = ncobj.variables[depvars[0]][:]
1621        var1 = ncobj.variables[depvars[1]][:]
1622        var2 = ncobj.variables[depvars[2]][:]
1623
1624        dnamesvar = list(ncobj.variables[depvars[2]].dimensions)
1625        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1626
1627        diagout, diagoutd, diagoutvd = diag.compute_rh(var0,var1,var2,dnamesvar,dvnamesvar)
1628        ncvar.insert_variable(ncobj, 'hurs', diagout, diagoutd, diagoutvd, newnc)
1629
1630# rvors (u10, v10, WRFpos)
1631    elif diagn == 'WRFrvors':
1632           
1633        var0 = ncobj.variables[depvars[0]]
1634        var1 = ncobj.variables[depvars[1]]
1635
1636        diagout = rotational_z(var0, var1, distx)
1637
1638        dnamesvar = ncobj.variables[depvars[0]].dimensions
1639        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1640
1641        ncvar.insert_variable(ncobj, 'rvors', diagout, dnamesvar, dvnamesvar, newnc)
1642
1643# WRFt (T, P, PB)
1644    elif diagn == 'WRFt':
1645        var0 = ncobj.variables[depvars[0]][:]
1646        var1 = ncobj.variables[depvars[1]][:]
1647        var2 = ncobj.variables[depvars[2]][:]
1648
1649        p0=100000.
1650        p=var1 + var2
1651
1652        WRFt = (var0 + 300.)*(p/p0)**(2./7.)
1653
1654        dnamesvar = list(ncobj.variables[depvars[0]].dimensions)
1655        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1656
1657        # Removing the nonChecking variable-dimensions from the initial list
1658        varsadd = []
1659        diagoutvd = list(dvnames)
1660        for nonvd in NONchkvardims:
1661            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1662            varsadd.append(nonvd)
1663
1664        ncvar.insert_variable(ncobj, 'ta', WRFt, dnames, diagoutvd, newnc)
1665
1666# WRFtda (WRFrh, WRFt)
1667    elif diagn == 'WRFtda':
1668        ARM2 = fdef.module_definitions.arm2
1669        ARM3 = fdef.module_definitions.arm3
1670
1671        gammatarh = np.log(WRFrh) + ARM2*(WRFt-273.15)/((WRFt-273.15)+ARM3)
1672        td = ARM3*gammatarh/(ARM2-gammatarh)
1673
1674        dnamesvar = list(ncobj.variables['T'].dimensions)
1675        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1676
1677        # Removing the nonChecking variable-dimensions from the initial list
1678        varsadd = []
1679        diagoutvd = list(dvnames)
1680        for nonvd in NONchkvardims:
1681            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1682            varsadd.append(nonvd)
1683
1684        ncvar.insert_variable(ncobj, 'tda', td, dnames, diagoutvd, newnc)
1685
1686# WRFtdas (PSFC, T2, Q2)
1687    elif diagn == 'WRFtdas':
1688        ARM2 = fdef.module_definitions.arm2
1689        ARM3 = fdef.module_definitions.arm3
1690
1691        var0 = ncobj.variables[depvars[0]][:]
1692        var1 = ncobj.variables[depvars[1]][:]
1693        var2 = ncobj.variables[depvars[2]][:]
1694
1695        dnamesvar = list(ncobj.variables[depvars[1]].dimensions)
1696        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1697
1698        rhs, diagoutd, diagoutvd = diag.compute_rh(var0,var1,var2,dnamesvar,dvnamesvar)
1699
1700        gammatarhs = np.log(rhs) + ARM2*(var1-273.15)/((var1-273.15)+ARM3)
1701        tdas = ARM3*gammatarhs/(ARM2-gammatarhs) + 273.15
1702
1703        # Removing the nonChecking variable-dimensions from the initial list
1704        varsadd = []
1705        diagoutvd = list(dvnames)
1706        for nonvd in NONchkvardims:
1707            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1708            varsadd.append(nonvd)
1709
1710        ncvar.insert_variable(ncobj, 'tdas', tdas, dnames, diagoutvd, newnc)
1711
1712# WRFua (U, V, SINALPHA, COSALPHA) to be rotated !!
1713    elif diagn == 'WRFua':
1714        var0 = ncobj.variables[depvars[0]][:]
1715        var1 = ncobj.variables[depvars[1]][:]
1716        var2 = ncobj.variables[depvars[2]][:]
1717        var3 = ncobj.variables[depvars[3]][:]
1718
1719        # un-staggering variables
1720        if len(var0.shape) == 4:
1721            unstgdims = [var0.shape[0], var0.shape[1], var0.shape[2], var0.shape[3]-1]
1722        elif len(var0.shape) == 3:
1723            # Asuming sunding point (dimt, dimz, dimstgx)
1724            unstgdims = [var0.shape[0], var0.shape[1]]
1725
1726        ua = np.zeros(tuple(unstgdims), dtype=np.float)
1727        unstgvar0 = np.zeros(tuple(unstgdims), dtype=np.float)
1728        unstgvar1 = np.zeros(tuple(unstgdims), dtype=np.float)
1729
1730        if len(var0.shape) == 4:
1731            unstgvar0 = 0.5*(var0[:,:,:,0:var0.shape[3]-1] + var0[:,:,:,1:var0.shape[3]])
1732            unstgvar1 = 0.5*(var1[:,:,0:var1.shape[2]-1,:] + var1[:,:,1:var1.shape[2],:])
1733
1734            for iz in range(var0.shape[1]):
1735                ua[:,iz,:,:] = unstgvar0[:,iz,:,:]*var3 - unstgvar1[:,iz,:,:]*var2
1736
1737            dnamesvar = ['Time','bottom_top','south_north','west_east']
1738
1739        elif len(var0.shape) == 3:
1740            unstgvar0 = 0.5*(var0[:,:,0] + var0[:,:,1])
1741            unstgvar1 = 0.5*(var1[:,:,0] + var1[:,:,1])
1742            for iz in range(var0.shape[1]):
1743                ua[:,iz] = unstgvar0[:,iz]*var3 - unstgvar1[:,iz]*var2
1744
1745            dnamesvar = ['Time','bottom_top']
1746
1747        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1748
1749        # Removing the nonChecking variable-dimensions from the initial list
1750        varsadd = []
1751        diagoutvd = list(dvnames)
1752        for nonvd in NONchkvardims:
1753            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1754            varsadd.append(nonvd)
1755
1756        ncvar.insert_variable(ncobj, 'ua', ua, dnames, diagoutvd, newnc)
1757
1758# WRFua (U, V, SINALPHA, COSALPHA) to be rotated !!
1759    elif diagn == 'WRFva':
1760        var0 = ncobj.variables[depvars[0]][:]
1761        var1 = ncobj.variables[depvars[1]][:]
1762        var2 = ncobj.variables[depvars[2]][:]
1763        var3 = ncobj.variables[depvars[3]][:]
1764
1765        # un-staggering variables
1766        if len(var0.shape) == 4:
1767            unstgdims = [var0.shape[0], var0.shape[1], var0.shape[2], var0.shape[3]-1]
1768        elif len(var0.shape) == 3:
1769            # Asuming sunding point (dimt, dimz, dimstgx)
1770            unstgdims = [var0.shape[0], var0.shape[1]]
1771
1772        va = np.zeros(tuple(unstgdims), dtype=np.float)
1773        unstgvar0 = np.zeros(tuple(unstgdims), dtype=np.float)
1774        unstgvar1 = np.zeros(tuple(unstgdims), dtype=np.float)
1775
1776        if len(var0.shape) == 4:
1777            unstgvar0 = 0.5*(var0[:,:,:,0:var0.shape[3]-1] + var0[:,:,:,1:var0.shape[3]])
1778            unstgvar1 = 0.5*(var1[:,:,0:var1.shape[2]-1,:] + var1[:,:,1:var1.shape[2],:])
1779
1780            for iz in range(var0.shape[1]):
1781                va[:,iz,:,:] = unstgvar0[:,iz,:,:]*var2 + unstgvar1[:,iz,:,:]*var3
1782
1783            dnamesvar = ['Time','bottom_top','south_north','west_east']
1784
1785        elif len(var0.shape) == 3:
1786            unstgvar0 = 0.5*(var0[:,:,0] + var0[:,:,1])
1787            unstgvar1 = 0.5*(var1[:,:,0] + var1[:,:,1])
1788            for iz in range(var0.shape[1]):
1789                va[:,iz] = unstgvar0[:,iz]*var2 + unstgvar1[:,iz]*var3
1790
1791            dnamesvar = ['Time','bottom_top']
1792
1793        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1794
1795        # Removing the nonChecking variable-dimensions from the initial list
1796        varsadd = []
1797        diagoutvd = list(dvnames)
1798        for nonvd in NONchkvardims:
1799            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1800            varsadd.append(nonvd)
1801        ncvar.insert_variable(ncobj, 'va', va, dnames, diagoutvd, newnc)
1802
1803
1804# WRFwd (U, V, SINALPHA, COSALPHA) to be rotated !!
1805    elif diagn == 'WRFwd':
1806        var0 = ncobj.variables[depvars[0]][:]
1807        var1 = ncobj.variables[depvars[1]][:]
1808        var2 = ncobj.variables[depvars[2]][:]
1809        var3 = ncobj.variables[depvars[3]][:]
1810
1811        # un-staggering variables
1812        if len(var0.shape) == 4:
1813            unstgdims = [var0.shape[0], var0.shape[1], var0.shape[2], var0.shape[3]-1]
1814        elif len(var0.shape) == 3:
1815            # Asuming sunding point (dimt, dimz, dimstgx)
1816            unstgdims = [var0.shape[0], var0.shape[1]]
1817
1818        ua = np.zeros(tuple(unstgdims), dtype=np.float)
1819        va = np.zeros(tuple(unstgdims), dtype=np.float)
1820        unstgvar0 = np.zeros(tuple(unstgdims), dtype=np.float)
1821        unstgvar1 = np.zeros(tuple(unstgdims), dtype=np.float)
1822
1823        if len(var0.shape) == 4:
1824            unstgvar0 = 0.5*(var0[:,:,:,0:var0.shape[3]-1] + var0[:,:,:,1:var0.shape[3]])
1825            unstgvar1 = 0.5*(var1[:,:,0:var1.shape[2]-1,:] + var1[:,:,1:var1.shape[2],:])
1826
1827            for iz in range(var0.shape[1]):
1828                ua[:,iz,:,:] = unstgvar0[:,iz,:,:]*var3 - unstgvar1[:,iz,:,:]*var2
1829                va[:,iz,:,:] = unstgvar0[:,iz,:,:]*var2 + unstgvar1[:,iz,:,:]*var3
1830
1831            dnamesvar = ['Time','bottom_top','south_north','west_east']
1832
1833        elif len(var0.shape) == 3:
1834            unstgvar0 = 0.5*(var0[:,:,0] + var0[:,:,1])
1835            unstgvar1 = 0.5*(var1[:,:,0] + var1[:,:,1])
1836            for iz in range(var0.shape[1]):
1837                ua[:,iz] = unstgvar0[:,iz]*var3 - unstgvar1[:,iz]*var2
1838                va[:,iz] = unstgvar0[:,iz]*var2 + unstgvar1[:,iz]*var3
1839
1840            dnamesvar = ['Time','bottom_top']
1841
1842        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1843
1844        wd, dnames, dvnames = diag.compute_wd(ua, va, dnamesvar, dvnamesvar)
1845
1846        # Removing the nonChecking variable-dimensions from the initial list
1847        varsadd = []
1848        diagoutvd = list(dvnames)
1849        for nonvd in NONchkvardims:
1850            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1851            varsadd.append(nonvd)
1852
1853        ncvar.insert_variable(ncobj, 'wd', wd, dnames, diagoutvd, newnc)
1854
1855# WRFtime
1856    elif diagn == 'WRFtime':
1857           
1858        diagout = WRFtime
1859
1860        dnamesvar = ['Time']
1861        dvnamesvar = ['Times']
1862
1863        ncvar.insert_variable(ncobj, 'time', diagout, dnamesvar, dvnamesvar, newnc)
1864
1865# ws (U, V)
1866    elif diagn == 'ws':
1867           
1868        # un-staggering variables
1869        if len(var0.shape) == 4:
1870            unstgdims = [var0.shape[0], var0.shape[1], var0.shape[2], var0.shape[3]-1]
1871        elif len(var0.shape) == 3:
1872            # Asuming sunding point (dimt, dimz, dimstgx)
1873            unstgdims = [var0.shape[0], var0.shape[1]]
1874
1875        ua = np.zeros(tuple(unstgdims), dtype=np.float)
1876        va = np.zeros(tuple(unstgdims), dtype=np.float)
1877        unstgvar0 = np.zeros(tuple(unstgdims), dtype=np.float)
1878        unstgvar1 = np.zeros(tuple(unstgdims), dtype=np.float)
1879
1880        if len(var0.shape) == 4:
1881            unstgvar0 = 0.5*(var0[:,:,:,0:var0.shape[3]-1] + var0[:,:,:,1:var0.shape[3]])
1882            unstgvar1 = 0.5*(var1[:,:,0:var1.shape[2]-1,:] + var1[:,:,1:var1.shape[2],:])
1883
1884            for iz in range(var0.shape[1]):
1885                ua[:,iz,:,:] = unstgvar0[:,iz,:,:]*var3 - unstgvar1[:,iz,:,:]*var2
1886                va[:,iz,:,:] = unstgvar0[:,iz,:,:]*var2 + unstgvar1[:,iz,:,:]*var3
1887
1888            dnamesvar = ['Time','bottom_top','south_north','west_east']
1889
1890        elif len(var0.shape) == 3:
1891            unstgvar0 = 0.5*(var0[:,:,0] + var0[:,:,1])
1892            unstgvar1 = 0.5*(var1[:,:,0] + var1[:,:,1])
1893            for iz in range(var0.shape[1]):
1894                ua[:,iz] = unstgvar0[:,iz]*var3 - unstgvar1[:,iz]*var2
1895                va[:,iz] = unstgvar0[:,iz]*var2 + unstgvar1[:,iz]*var3
1896
1897            dnamesvar = ['Time','bottom_top']
1898
1899        diagout = np.sqrt(unstgvar0*unstgvar0 + unstgvar1*unstgvar1)
1900
1901#        dnamesvar = ncobj.variables[depvars[0]].dimensions
1902        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1903
1904        # Removing the nonChecking variable-dimensions from the initial list
1905        varsadd = []
1906        diagoutvd = list(dvnamesvar)
1907        for nonvd in NONchkvardims:
1908            if gen.searchInlist(dvnamesvar,nonvd): diagoutvd.remove(nonvd)
1909            varsadd.append(nonvd)
1910        ncvar.insert_variable(ncobj, 'ws', diagout, dnamesvar, diagoutvd, newnc)
1911
1912# wss (u10, v10)
1913    elif diagn == 'wss':
1914           
1915        var0 = ncobj.variables[depvars[0]][:]
1916        var1 = ncobj.variables[depvars[1]][:]
1917
1918        diagout = np.sqrt(var0*var0 + var1*var1)
1919
1920        dnamesvar = ncobj.variables[depvars[0]].dimensions
1921        dvnamesvar = ncvar.var_dim_dimv(dnamesvar,dnames,dvnames)
1922
1923        ncvar.insert_variable(ncobj, 'wss', diagout, dnamesvar, dvnamesvar, newnc)
1924
1925# WRFheight height from WRF geopotential as WRFGeop/g
1926    elif diagn == 'WRFheight':
1927           
1928        diagout = WRFgeop/grav
1929
1930        # Removing the nonChecking variable-dimensions from the initial list
1931        varsadd = []
1932        diagoutvd = list(dvnames)
1933        for nonvd in NONchkvardims:
1934            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1935            varsadd.append(nonvd)
1936
1937        ncvar.insert_variable(ncobj, 'zhgt', diagout, dnames, diagoutvd, newnc)
1938
1939# WRFheightrel relative-height from WRF geopotential as WRFgeop(PH + PHB)/g-HGT 'WRFheightrel|PH@PHB@HGT
1940    elif diagn == 'WRFheightrel':
1941        var0 = ncobj.variables[depvars[0]][:]
1942        var1 = ncobj.variables[depvars[1]][:]
1943        var2 = ncobj.variables[depvars[2]][:]
1944
1945        dimz = var0.shape[1]
1946        diagout = np.zeros(tuple(var0.shape), dtype=np.float)
1947        for iz in range(dimz):
1948            diagout[:,iz,:,:] = (var0[:,iz,:,:]+ var1[:,iz,:,:])/grav - var2
1949
1950        # Removing the nonChecking variable-dimensions from the initial list
1951        varsadd = []
1952        diagoutvd = list(dvnames)
1953        for nonvd in NONchkvardims:
1954            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1955            varsadd.append(nonvd)
1956
1957        ncvar.insert_variable(ncobj, 'zhgtrel', diagout, dnames, diagoutvd, newnc)
1958
1959# WRFzmla_gen generic boundary layer hieght computation from WRF theta, QVAPOR, WRFgeop, HGT,
1960    elif diagn == 'WRFzmlagen':
1961        var0 = ncobj.variables[depvars[0]][:]+300.
1962        var1 = ncobj.variables[depvars[1]][:]
1963        dimz = var0.shape[1]
1964        var2 = WRFgeop[:,1:dimz+1,:,:]/9.8
1965        var3 = ncobj.variables[depvars[3]][0,:,:]
1966
1967        diagout, diagoutd, diagoutvd = diag.Forcompute_zmla_gen(var0,var1,var2,var3, \
1968          dnames,dvnames)
1969
1970        # Removing the nonChecking variable-dimensions from the initial list
1971        varsadd = []
1972        for nonvd in NONchkvardims:
1973            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
1974            varsadd.append(nonvd)
1975
1976        ncvar.insert_variable(ncobj, 'zmla', diagout, diagoutd, diagoutvd, newnc)
1977
1978# WRFzwind wind extrapolation at a given height using power law computation from WRF
1979#   U, V, WRFz, U10, V10, SINALPHA, COSALPHA, z=[zval]
1980    elif diagn == 'WRFzwind':
1981        var0 = ncobj.variables[depvars[0]][:]
1982        var1 = ncobj.variables[depvars[1]][:]
1983        var2 = WRFz
1984        var3 = ncobj.variables[depvars[3]][:]
1985        var4 = ncobj.variables[depvars[4]][:]
1986        var5 = ncobj.variables[depvars[5]][0,:,:]
1987        var6 = ncobj.variables[depvars[6]][0,:,:]
1988        var7 = np.float(depvars[7].split('=')[1])
1989
1990        # un-staggering 3D winds
1991        unstgdims = [var0.shape[0], var0.shape[1], var0.shape[2], var0.shape[3]-1]
1992        va = np.zeros(tuple(unstgdims), dtype=np.float)
1993        unvar0 = np.zeros(tuple(unstgdims), dtype=np.float)
1994        unvar1 = np.zeros(tuple(unstgdims), dtype=np.float)
1995        unvar0 = 0.5*(var0[:,:,:,0:var0.shape[3]-1] + var0[:,:,:,1:var0.shape[3]])
1996        unvar1 = 0.5*(var1[:,:,0:var1.shape[2]-1,:] + var1[:,:,1:var1.shape[2],:])
1997
1998        diagout1, diagout2, diagoutd, diagoutvd = diag.Forcompute_zwind(unvar0,      \
1999          unvar1, var2, var3, var4, var5, var6, var7, dnames, dvnames)
2000
2001        # Removing the nonChecking variable-dimensions from the initial list
2002        varsadd = []
2003        for nonvd in NONchkvardims:
2004            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
2005            varsadd.append(nonvd)
2006
2007        ncvar.insert_variable(ncobj, 'uaz', diagout1, diagoutd, diagoutvd, newnc)
2008        ncvar.insert_variable(ncobj, 'vaz', diagout2, diagoutd, diagoutvd, newnc)
2009
2010# WRFzwind wind extrapolation at a given hieght using logarithmic law computation
2011#   from WRF U, V, WRFz, U10, V10, SINALPHA, COSALPHA, z=[zval]
2012    elif diagn == 'WRFzwind_log':
2013        var0 = ncobj.variables[depvars[0]][:]
2014        var1 = ncobj.variables[depvars[1]][:]
2015        var2 = WRFz
2016        var3 = ncobj.variables[depvars[3]][:]
2017        var4 = ncobj.variables[depvars[4]][:]
2018        var5 = ncobj.variables[depvars[5]][0,:,:]
2019        var6 = ncobj.variables[depvars[6]][0,:,:]
2020        var7 = np.float(depvars[7].split('=')[1])
2021
2022        # un-staggering 3D winds
2023        unstgdims = [var0.shape[0], var0.shape[1], var0.shape[2], var0.shape[3]-1]
2024        va = np.zeros(tuple(unstgdims), dtype=np.float)
2025        unvar0 = np.zeros(tuple(unstgdims), dtype=np.float)
2026        unvar1 = np.zeros(tuple(unstgdims), dtype=np.float)
2027        unvar0 = 0.5*(var0[:,:,:,0:var0.shape[3]-1] + var0[:,:,:,1:var0.shape[3]])
2028        unvar1 = 0.5*(var1[:,:,0:var1.shape[2]-1,:] + var1[:,:,1:var1.shape[2],:])
2029
2030        diagout1, diagout2, diagoutd, diagoutvd = diag.Forcompute_zwind_log(unvar0,  \
2031          unvar1, var2, var3, var4, var5, var6, var7, dnames, dvnames)
2032
2033        # Removing the nonChecking variable-dimensions from the initial list
2034        varsadd = []
2035        for nonvd in NONchkvardims:
2036            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
2037            varsadd.append(nonvd)
2038
2039        ncvar.insert_variable(ncobj, 'uaz', diagout1, diagoutd, diagoutvd, newnc)
2040        ncvar.insert_variable(ncobj, 'vaz', diagout2, diagoutd, diagoutvd, newnc)
2041
2042# WRFzwindMO wind extrapolation at a given height computation using Monin-Obukhow
2043#   theory from WRF UST, ZNT, RMOL, U10, V10, SINALPHA, COSALPHA, z=[zval]
2044#   NOTE: only useful for [zval] < 80. m
2045    elif diagn == 'WRFzwindMO':
2046        var0 = ncobj.variables[depvars[0]][:]
2047        var1 = ncobj.variables[depvars[1]][:]
2048        var2 = ncobj.variables[depvars[2]][:]
2049        var3 = ncobj.variables[depvars[3]][:]
2050        var4 = ncobj.variables[depvars[4]][:]
2051        var5 = ncobj.variables[depvars[5]][0,:,:]
2052        var6 = ncobj.variables[depvars[6]][0,:,:]
2053        var7 = np.float(depvars[7].split('=')[1])
2054
2055        diagout1, diagout2, diagoutd, diagoutvd = diag.Forcompute_zwindMO(var0, var1,\
2056          var2, var3, var4, var5, var6, var7, dnames, dvnames)
2057
2058        # Removing the nonChecking variable-dimensions from the initial list
2059        varsadd = []
2060        for nonvd in NONchkvardims:
2061            if gen.searchInlist(dvnames,nonvd): diagoutvd.remove(nonvd)
2062            varsadd.append(nonvd)
2063
2064        ncvar.insert_variable(ncobj, 'uaz', diagout1, diagoutd, diagoutvd, newnc)
2065        ncvar.insert_variable(ncobj, 'vaz', diagout2, diagoutd, diagoutvd, newnc)
2066
2067    else:
2068        print errormsg
2069        print '  ' + main + ": diagnostic '" + diagn + "' not ready!!!"
2070        print '    available diagnostics: ', availdiags
2071        quit(-1)
2072
2073    newnc.sync()
2074    # Adding that additional variables required to compute some diagnostics which
2075    #   where not in the original file
2076    print '  adding additional variables...'
2077    for vadd in varsadd:
2078        if not gen.searchInlist(newnc.variables.keys(),vadd) and                     \
2079          dictcompvars.has_key(vadd):
2080            attrs = dictcompvars[vadd]
2081            vvn = attrs['name']
2082            if not gen.searchInlist(newnc.variables.keys(), vvn):
2083                iidvn = dvnames.index(vadd)
2084                dnn = dnames[iidvn]
2085                if vadd == 'WRFtime':
2086                    dvarvals = WRFtime[:]
2087                newvar = newnc.createVariable(vvn, 'f8', (dnn))
2088                newvar[:] = dvarvals
2089                for attn in attrs.keys():
2090                    if attn != 'name':
2091                        attv = attrs[attn]
2092                        ncvar.set_attribute(newvar, attn, attv)
2093
2094#   end of diagnostics
2095
2096# Global attributes
2097##
2098ncvar.add_global_PyNCplot(newnc, main, None, '2.0')
2099
2100gorigattrs = ncobj.ncattrs()
2101for attr in gorigattrs:
2102    attrv = ncobj.getncattr(attr)
2103    atvar = ncvar.set_attribute(newnc, attr, attrv)
2104
2105ncobj.close()
2106newnc.close()
2107
2108print '\n' + main + ': successfull writting of diagnostics file "' + ofile + '" !!!'
Note: See TracBrowser for help on using the repository browser.