Changeset 337 in lmdz_wrf


Ignore:
Timestamp:
Feb 28, 2015, 4:22:10 PM (10 years ago)
Author:
lfita
Message:

Working version for a 3D trajectory

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/tools/validation_sim.py

    r333 r337  
    11
    22# L. Fita, LMD-Jussieu. February 2015
    3 ## e.g. # validation_sim.py -d X@west_east@None,Y@south_north@None,T@Time@time -D X@XLONG@longitude,Y@XLAT@latitude,T@time@time -k single-station -l 4.878773,43.915876,12. -o /home/lluis/DATA/obs/HyMeX/IOP15/sfcEnergyBalance_Avignon/OBSnetcdf.nc -s /home/lluis/PY/wrfout_d01_2012-10-18_00:00:00.tests -v HFX@H,LH@LE,GRDFLX@G
     3## e.g. sfcEneAvigon # validation_sim.py -d X@west_east@None,Y@south_north@None,T@Time@time -D X@XLONG@longitude,Y@XLAT@latitude,T@time@time -k single-station -l 4.878773,43.915876,12. -o /home/lluis/DATA/obs/HyMeX/IOP15/sfcEnergyBalance_Avignon/OBSnetcdf.nc -s /home/lluis/PY/wrfout_d01_2012-10-18_00:00:00.tests -v HFX@H,LH@LE,GRDFLX@G
     4## e.g. AIREP # validation_sim.py -d X@west_east@lon2D,Y@south_north@lat2D,Z@bottom_top@z2D,T@Time@time -D X@XLONG@longitude,Y@XLAT@latitude,Z@WRFz@alti,T@time@time -k trajectory -o /home/lluis/DATA/obs/HyMeX/IOP15/AIREP/2012/10/AIREP_121018.nc -s /home/lluis/PY/wrfout_d01_2012-10-18_00:00:00.tests -v WRFT@t
     5## e.g. ATRCore # validation_sim.py -d X@west_east@lon2D,Y@south_north@lat2D,Z@bottom_top@z2D,T@Time@CFtime -D X@XLONG@longitude,Y@XLAT@latitude,Z@WRFz@altitude,T@time@time -k trajectory -o /home/lluis/DATA/obs/HyMeX/IOP15/ATRCore/V3/ATR_1Hz-HYMEXBDD-SOP1-v3_20121018_as120051.nc -s /home/lluis/PY/wrfout_d01_2012-10-18_00:00:00.tests -v WRFT@air_temperature@subc@273.15
     6## e.g. BAMED # validation_sim.py -d X@west_east@lon2D,Y@south_north@lat2D,Z@bottom_top@z2D,T@Time@CFtime -D X@XLONG@longitude,Y@XLAT@latitude,Z@WRFz@altitude,T@time@time -k trajectory -o /home/lluis/DATA/obs/HyMeX/IOP15/BAMED/BAMED_SOP1_B12_TOT5.nc -s /home/lluis/PY/wrfout_d01_2012-10-18_00:00:00.tests -v WRFT@tas_north
     7
    48import numpy as np
    59import os
     
    2125
    2226StringLength = 50
     27
     28# Number of grid points to take as 'environment' around the observed point
     29Ngrid = 1
    2330
    2431def searchInlist(listname, nameFind):
     
    162169      matB= matrix with the pother set of values
    163170      val= couple of values to search
    164     >>> index_mat(np.arange(27).reshape(3,3,3),np.arange(100,127).reshape(3,3,3),[22,111])
     171    >>> index_2mat(np.arange(27).reshape(3,3,3),np.arange(100,127).reshape(3,3,3),[22,111])
    165172    [2 1 1]
    166173    """
     
    182189    maxB = np.max(matB)
    183190
     191    Ndims = len(matAshape)
     192#    valpos = np.ones((Ndims), dtype=int)*-1.
     193    valpos = np.zeros((Ndims), dtype=int)
     194
    184195    if val[0] < minA or val[0] > maxA:
    185196        print warnmsg
    186197        print '  ' + fname + ': first value:',val[0],'outside matA range',minA,',',  \
    187198          maxA,'!!'
     199        return valpos
    188200    if val[1] < minB or val[1] > maxB:
    189201        print warnmsg
    190202        print '  ' + fname + ': second value:',val[1],'outside matB range',minB,',',  \
    191203          maxB,'!!'
     204        return valpos
    192205
    193206    dist = np.zeros(tuple(matAshape), dtype=np.float)
     
    196209    mindist = np.min(dist)
    197210   
    198     matlist = list(dist.flatten())
    199     ifound = matlist.index(mindist)
    200 
    201     Ndims = len(matAshape)
    202     valpos = np.zeros((Ndims), dtype=int)
     211    if mindist != mindist:
     212        print '  ' + fname + ': wrong minimal distance',mindist,'!!'
     213        return valpos
     214    else:
     215        matlist = list(dist.flatten())
     216        ifound = matlist.index(mindist)
     217
    203218    baseprevdims = np.zeros((Ndims), dtype=int)
    204 
    205219    for dimid in range(Ndims):
    206220        baseprevdims[dimid] = np.product(matAshape[dimid+1:Ndims])
     
    213227    return valpos
    214228
    215 def index_mat(mat,val):
     229def index_mat(matA,val):
    216230    """ Function to provide the coordinates of a given value inside a matrix
     231    index_mat(matA,val)
     232      matA= matrix with one set of values
     233      val= couple of values to search
     234    >>> index_mat(np.arange(27),22.3)
     235    22
     236    """
     237    fname = 'index_mat'
     238
     239    matAshape = matA.shape
     240
     241    minA = np.min(matA)
     242    maxA = np.max(matA)
     243
     244    Ndims = len(matAshape)
     245#    valpos = np.ones((Ndims), dtype=int)*-1.
     246    valpos = np.zeros((Ndims), dtype=int)
     247
     248    if val < minA or val > maxA:
     249        print warnmsg
     250        print '  ' + fname + ': first value:',val,'outside matA range',minA,',',     \
     251          maxA,'!!'
     252        return valpos
     253
     254    dist = np.zeros(tuple(matAshape), dtype=np.float)
     255    dist = (matA - np.float(val))**2
     256
     257    mindist = np.min(dist)
     258    if mindist != mindist:
     259        print '  ' + fname + ': wrong minimal distance',mindist,'!!'
     260        return valpos
     261   
     262    matlist = list(dist.flatten())
     263    valpos = matlist.index(mindist)
     264
     265    return valpos
     266
     267def index_mat_exact(mat,val):
     268    """ Function to provide the coordinates of a given exact value inside a matrix
    217269    index_mat(mat,val)
    218270      mat= matrix with values
     
    433485    return varvalues, dimnslice
    434486
     487def func_compute_varNOcheck(ncobj, varn):
     488    """ Function to compute variables which are not originary in the file
     489      ncobj= netCDF object file
     490      varn = variable to compute:
     491        'WRFdens': air density from WRF variables
     492        'WRFght': geopotential height from WRF variables
     493        'WRFp': pressure from WRF variables
     494        'WRFrh': relative humidty fom WRF variables
     495        'WRFt': temperature from WRF variables
     496        'WRFz': height from WRF variables
     497    """
     498    fname = 'compute_varNOcheck'
     499
     500    if varn == 'WRFdens':
     501#        print '    ' + main + ': computing air density from WRF as ((MU + MUB) * ' + \
     502#          'DNW)/g ...'
     503        grav = 9.81
     504
     505# Just we need in in absolute values: Size of the central grid cell
     506##    dxval = ncobj.getncattr('DX')
     507##    dyval = ncobj.getncattr('DY')
     508##    mapfac = ncobj.variables['MAPFAC_M'][:]
     509##    area = dxval*dyval*mapfac
     510        dimensions = ncobj.variables['MU'].dimensions
     511
     512        mu = (ncobj.variables['MU'][:] + ncobj.variables['MUB'][:])
     513        dnw = ncobj.variables['DNW'][:]
     514
     515        varNOcheckv = np.zeros((mu.shape[0], dnw.shape[1], mu.shape[1], mu.shape[2]), \
     516          dtype=np.float)
     517        levval = np.zeros((mu.shape[1], mu.shape[2]), dtype=np.float)
     518
     519        for it in range(mu.shape[0]):
     520            for iz in range(dnw.shape[1]):
     521                levval.fill(np.abs(dnw[it,iz]))
     522                varNOcheck[it,iz,:,:] = levval
     523                varNOcheck[it,iz,:,:] = mu[it,:,:]*varNOcheck[it,iz,:,:]/grav
     524
     525    elif varn == 'WRFght':
     526#        print '    ' + main + ': computing geopotential height from WRF as PH + PHB ...'
     527        varNOcheckv = ncobj.variables['PH'][:] + ncobj.variables['PHB'][:]
     528        dimensions = ncobj.variables['PH'].dimensions
     529
     530    elif varn == 'WRFp':
     531#        print '  ' + fname + ': Retrieving pressure value from WRF as P + PB'
     532        varNOcheckv = ncobj.variables['P'][:] + ncobj.variables['PB'][:]
     533        dimensions = ncobj.variables['P'].dimensions
     534
     535    elif varn == 'WRFrh':
     536#        print '    ' + main + ": computing relative humidity from WRF as 'Tetens'" +\
     537#         ' equation (T,P) ...'
     538        p0=100000.
     539        p=ncobj.variables['P'][:] + ncobj.variables['PB'][:]
     540        tk = (ncobj.variables['T'][:] + 300.)*(p/p0)**(2./7.)
     541        qv = ncobj.variables['QVAPOR'][:]
     542
     543        data1 = 10.*0.6112*np.exp(17.67*(tk-273.16)/(tk-29.65))
     544        data2 = 0.622*data1/(0.01*p-(1.-0.622)*data1)
     545
     546        varNOcheckv = qv/data2
     547        dimensions = ncobj.variables['P'].dimensions
     548
     549    elif varn == 'WRFt':
     550#        print '    ' + main + ': computing temperature from WRF as inv_potT(T + 300) ...'
     551        p0=100000.
     552        p=ncobj.variables['P'][:] + ncobj.variables['PB'][:]
     553
     554        varNOcheckv = (ncobj.variables['T'][:] + 300.)*(p/p0)**(2./7.)
     555        dimensions = ncobj.variables['T'].dimensions
     556
     557    elif varn == 'WRFz':
     558        grav = 9.81
     559#        print '    ' + main + ': computing geopotential height from WRF as PH + PHB ...'
     560        varNOcheckv = (ncobj.variables['PH'][:] + ncobj.variables['PHB'][:])/grav
     561        dimensions = ncobj.variables['PH'].dimensions
     562
     563    else:
     564        print erromsg
     565        print '  ' + fname + ": variable '" + varn + "' nor ready !!"
     566        quit(-1)
     567
     568    return varNOcheck
     569
     570class compute_varNOcheck(object):
     571    """ Class to compute variables which are not originary in the file
     572      ncobj= netCDF object file
     573      varn = variable to compute:
     574        'WRFdens': air density from WRF variables
     575        'WRFght': geopotential height from WRF variables
     576        'WRFp': pressure from WRF variables
     577        'WRFrh': relative humidty fom WRF variables
     578        'WRFt': temperature from WRF variables
     579        'WRFz': height from WRF variables
     580    """
     581    fname = 'compute_varNOcheck'
     582
     583    def __init__(self, ncobj, varn):
     584
     585        if ncobj is None:
     586            self = None
     587            self.dimensions = None
     588            self.shape = None
     589            self.__values = None
     590        else:
     591            if varn == 'WRFdens':
     592#        print '    ' + main + ': computing air density from WRF as ((MU + MUB) * ' + \
     593#          'DNW)/g ...'
     594                grav = 9.81
     595
     596# Just we need in in absolute values: Size of the central grid cell
     597##    dxval = ncobj.getncattr('DX')
     598##    dyval = ncobj.getncattr('DY')
     599##    mapfac = ncobj.variables['MAPFAC_M'][:]
     600##    area = dxval*dyval*mapfac
     601                dimensions = ncobj.variables['MU'].dimensions
     602                shape = ncobj.variables['MU'].shape
     603
     604                mu = (ncobj.variables['MU'][:] + ncobj.variables['MUB'][:])
     605                dnw = ncobj.variables['DNW'][:]
     606
     607                varNOcheckv = np.zeros((mu.shape[0], dnw.shape[1], mu.shape[1], mu.shape[2]), \
     608                  dtype=np.float)
     609                levval = np.zeros((mu.shape[1], mu.shape[2]), dtype=np.float)
     610
     611                for it in range(mu.shape[0]):
     612                    for iz in range(dnw.shape[1]):
     613                        levval.fill(np.abs(dnw[it,iz]))
     614                        varNOcheck[it,iz,:,:] = levval
     615                        varNOcheck[it,iz,:,:] = mu[it,:,:]*varNOcheck[it,iz,:,:]/grav
     616
     617            elif varn == 'WRFght':
     618#        print '    ' + main + ': computing geopotential height from WRF as PH + PHB ...'
     619                varNOcheckv = ncobj.variables['PH'][:] + ncobj.variables['PHB'][:]
     620                dimensions = ncobj.variables['PH'].dimensions
     621                shape = ncobj.variables['PH'].shape
     622
     623            elif varn == 'WRFp':
     624#        print '  ' + fname + ': Retrieving pressure value from WRF as P + PB'
     625                varNOcheckv = ncobj.variables['P'][:] + ncobj.variables['PB'][:]
     626                dimensions = ncobj.variables['P'].dimensions
     627                shape = ncobj.variables['P'].shape
     628
     629            elif varn == 'WRFrh':
     630#        print '    ' + main + ": computing relative humidity from WRF as 'Tetens'" +\
     631#         ' equation (T,P) ...'
     632                p0=100000.
     633                p=ncobj.variables['P'][:] + ncobj.variables['PB'][:]
     634                tk = (ncobj.variables['T'][:] + 300.)*(p/p0)**(2./7.)
     635                qv = ncobj.variables['QVAPOR'][:]
     636
     637                data1 = 10.*0.6112*np.exp(17.67*(tk-273.16)/(tk-29.65))
     638                data2 = 0.622*data1/(0.01*p-(1.-0.622)*data1)
     639
     640                varNOcheckv = qv/data2
     641                dimensions = ncobj.variables['P'].dimensions
     642                shape = ncobj.variables['P'].shape
     643
     644
     645            elif varn == 'WRFt':
     646#        print '    ' + main + ': computing temperature from WRF as inv_potT(T + 300) ...'
     647                p0=100000.
     648                p=ncobj.variables['P'][:] + ncobj.variables['PB'][:]
     649
     650                varNOcheckv = (ncobj.variables['T'][:] + 300.)*(p/p0)**(2./7.)
     651                dimensions = ncobj.variables['T'].dimensions
     652                shape = ncobj.variables['P'].shape
     653
     654            elif varn == 'WRFz':
     655                grav = 9.81
     656#        print '    ' + main + ': computing geopotential height from WRF as PH + PHB ...'
     657                varNOcheckv = (ncobj.variables['PH'][:] + ncobj.variables['PHB'][:])/grav
     658                dimensions = ncobj.variables['PH'].dimensions
     659                shape = ncobj.variables['PH'].shape
     660
     661            else:
     662                print erromsg
     663                print '  ' + fname + ": variable '" + varn + "' nor ready !!"
     664                quit(-1)
     665
     666            print type(ncobj.variables)
     667   
     668            self.dimensions = dimensions
     669            self.shape = shape
     670            self.__values = varNOcheckv
     671
     672    def __getitem__(self,elem):
     673        return self.__values[elem]
     674
    435675
    436676####### ###### ##### #### ### ## #
     
    443683  "(e.g., lightning strikes), 'single-station': single station on a fixed position,"+\
    444684  "'trajectory': following a trajectory"
    445 simopers =['sumc','subc','mulc','divc']
    446 #sumc,[constant]: add [constant] to variables values
    447 #subc,[constant]: substract [constant] to variables values
    448 #mulc,[constant]: multipy by [constant] to variables values
    449 #divc,[constant]: divide by [constant] to variables values
     685simopers = ['sumc','subc','mulc','divc']
     686opersinf = 'sumc,[constant]: add [constant] to variables values; subc,[constant]: '+ \
     687  'substract [constant] to variables values; mulc,[constant]: multipy by ' +         \
     688  '[constant] to variables values; divc,[constant]: divide by [constant] to ' +      \
     689  'variables values'
     690varNOcheck = ['WRFdens', 'WRFght', 'WRFp', 'WRFrh', 'WRFt', 'WRFz']
     691varNOcheckinf = "'WRFdens': air density from WRF variables; 'WRFght': geopotential"+ \
     692  " height from WRF variables; 'WRFp': pressure from WRF variables; 'WRFrh': " +     \
     693 "relative humidty fom WRF variables; 'WRFt': temperature from WRF variables; " +    \
     694 "'WRFz': height from WRF variables"
     695
     696dimshelp = "[DIM]@[simdim]@[obsdim] ',' list of couples of dimensions names from " + \
     697  "each source ([DIM]='X','Y','Z','T'; None, no value)"
     698vardimshelp = "[DIM]@[simvardim]@[obsvardim] ',' list of couples of variables " +    \
     699  "names with dimensions values from each source ([DIM]='X','Y','Z','T'; None, " +   \
     700  "no value, WRFdiagnosted variables also available: " + varNOcheckinf + ")"
     701varshelp="[simvar]@[obsvar]@[[oper]@[val]] ',' list of couples of variables to " +   \
     702  "validate and if necessary operation and value operations: " + opersinf +          \
     703  "(WRFdiagnosted variables also available: " + varNOcheckinf + ")"
     704statsn = ['minimum', 'maximum', 'mean', 'mean2', 'standard deviation']
    450705
    451706parser = OptionParser()
    452 parser.add_option("-d", "--dimensions", dest="dims",
    453   help="[DIM]@[simdim]@[obsdim] ',' list of couples of dimensions names from each source ([DIM]='X','Y','Z','T'; None, no value)",
    454   metavar="VALUES")
     707parser.add_option("-d", "--dimensions", dest="dims", help=dimshelp, metavar="VALUES")
    455708parser.add_option("-D", "--vardimensions", dest="vardims",
    456   help="[DIM]@[simvardim]@[obsvardim] ',' list of couples of variables names with dimensions values from each source ([DIM]='X','Y','Z','T'; None, no value)", metavar="VALUES")
     709  help=vardimshelp, metavar="VALUES")
    457710parser.add_option("-k", "--kindObs", dest="obskind", type='choice', choices=kindobs,
    458711  help=strkObs, metavar="FILE")
     
    464717parser.add_option("-s", "--simulation", dest="fsim",
    465718  help="simulation file to validate", metavar="FILE")
     719parser.add_option("-t", "--trajectoryfile", dest="trajf",
     720  help="file with grid points of the trajectory in the simulation grid ('simtrj')",
     721  metavar="FILE")
    466722parser.add_option("-v", "--variables", dest="vars",
    467   help="[simvar]@[obsvar]@[[oper]@[val]] ',' list of couples of variables to validate and if necessary operation and value", metavar="VALUES")
     723  help=varshelp, metavar="VALUES")
    468724
    469725(opts, args) = parser.parse_args()
     
    612868          dims[dn][0] + "' !!"
    613869        quit(-1)
    614     if not osim.variables.has_key(vardims[dn][0]):
     870    if not osim.variables.has_key(vardims[dn][0]) and not                            \
     871      searchInlist(varNOcheck,vardims[dn][0]):
    615872        print errormsg
    616873        print '  ' + main + ": simulation file does not have varibale dimension '" + \
    617874          vardims[dn][0] + "' !!"
    618875        quit(-1)
    619     valdimsim[dn] = osim.variables[vardims[dn][0]][:]
     876    if searchInlist(varNOcheck,vardims[dn][0]):
     877        valdimsim[dn] = compute_varNOcheck(osim, vardims[dn][0])
     878    else:
     879        valdimsim[dn] = osim.variables[vardims[dn][0]][:]
    620880
    621881# General characteristics
     
    625885print main +': observational time-steps:',dimtobs,'simulation:',dimtsim
    626886
     887notfound = np.zeros((dimtobs), dtype=int)
     888
    627889if obskind == 'multi-points':
    628890    trajpos = np.zeros((2,dimt),dtype=int)
    629     for it in dimtobs:
     891    for it in range(dimtobs):
    630892        trajpos[:,it] = index_2mat(valdimsim['X'],valdimsim['Y'],                    \
    631893          [valdimobs['X'][it],valdimobss['Y'][it]])
     
    648910
    649911elif obskind == 'trajectory':
    650     if dims.has_key('Z'):
    651         trajpos = np.zeros((3,dimt),dtype=int)
    652         for it in dimtobs:
    653             trajpos[0:1,it] = index_2mat(valdimsim['Y'],valdimsim['X'],              \
    654               [valdimobs['Y'][it],valdimobss['X'][it]])
    655             trajpos[2,it] = index_mat(valdimsim['Z'],valdimobs['Z'][it])
     912    if opts.trajf is not None:
     913        if not os.path.isfile(opts.fsim):
     914            print errormsg
     915            print '   ' + main + ": simulation file '" + opts.fsim + "' does not exist !!"
     916            quit(-1)
     917        else:
     918            otrjf = NetCDFFile(opts.fsim, 'r')
     919            trajpos[0,:] = otrjf.variables['obssimtrj'][0]
     920            trajpos[1,:] = otrjf.variables['obssimtrj'][1]
     921            otrjf.close()
    656922    else:
    657         trajpos = np.zeros((2,dimt),dtype=int)
    658         for it in dimtobs:
    659             trajpos[:,it] = index_2mat(valdimsim['Y'],valdimsim['X'],                \
    660               [valdimobs['Y'][it],valdimobss['X'][it]])
     923        if dims.has_key('Z'):
     924            trajpos = np.zeros((3,dimtobs),dtype=int)
     925            for it in range(dimtobs):
     926                if np.mod(it*100./dimtobs,10.) == 0.:
     927                    print '    trajectory done: ',it*100./dimtobs,'%'
     928                stsimpos = index_2mat(valdimsim['Y'],valdimsim['X'],                 \
     929                  [valdimobs['Y'][it],valdimobs['X'][it]])
     930                stationpos = np.zeros((2), dtype=int)
     931                iid = 0
     932                for idn in osim.variables[vardims['X'][0]].dimensions:
     933                    if idn == dims['X'][0]:
     934                        stationpos[1] = stsimpos[iid]
     935                    elif idn == dims['Y'][0]:
     936                        stationpos[0] = stsimpos[iid]
     937                    iid = iid + 1
     938                if stationpos[0] == 0 and stationpos[1] == 0: notfound[it] = 1
     939             
     940                trajpos[0,it] = stationpos[0]
     941                trajpos[1,it] = stationpos[1]
     942# In the simulation 'Z' varies with time ... non-hydrostatic model! ;)
     943#                trajpos[2,it] = index_mat(valdimsim['Z'][it,:,stationpos[0],         \
     944#                  stationpos[1]], valdimobs['Z'][it])
     945        else:
     946            trajpos = np.zeros((2,dimtobs),dtype=int)
     947            for it in range(dimtobs):
     948                stsimpos = index_2mat(valdimsim['Y'],valdimsim['X'],                 \
     949                  [valdimobs['Y'][it],valdimobss['X'][it]])
     950                stationpos = np.zeros((2), dtype=int)
     951                iid = 0
     952                for idn in osim.variables[vardims['X'][0]].dimensions:
     953                    if idn == dims['X'][0]:
     954                        stationpos[1] = stsimpos[iid]
     955                    elif idn == dims['Y'][0]:
     956                        stationpos[0] = stsimpos[iid]
     957                    iid = iid + 1
     958                if stationpos[0] == 0 and stationpos[1] == 0: notfound[it] = 1
     959
     960                trajpos[0,it] = stationspos[0]
     961                trajpos[1,it] = stationspos[1]
     962
     963        print main + ': not found',np.sum(notfound),'points of the trajectory'
    661964
    662965# Getting times
     
    670973# Concident times
    671974##
    672 coindtvalues = []
     975coindtvalues0 = []
    673976for it in range(dimtsim):   
    674977    ot = 0
     
    678981            ot = ito
    679982            tdist = simobstimes[it] - valdimobs['T'][ito]
    680             coindtvalues.append([it,ito,simobstimes[it],valdimobs['T'][ito],tdist])
    681 
    682 Ncoindt = len(coindtvalues)
     983            coindtvalues0.append([it, ito, simobstimes[it], valdimobs['T'][ito],      \
     984              tdist])
     985
     986coindtvalues = np.array(coindtvalues0, dtype=np.float)
     987
     988Ncoindt = len(coindtvalues[:,0])
    683989print main + ': found',Ncoindt,'coincident times between simulation and observations'
     990
     991if Ncoindt == 0:
     992    print warnmsg
     993    print main + ': no coincident times found !!'
     994    print '  stopping it'
     995    quit(-1)
    684996
    685997# Validating
     
    6901002# Dimensions
    6911003newdim = onewnc.createDimension('time',None)
     1004newdim = onewnc.createDimension('obstime',None)
    6921005newdim = onewnc.createDimension('couple',2)
    6931006newdim = onewnc.createDimension('StrLength',StringLength)
     1007newdim = onewnc.createDimension('xaround',Ngrid*2+1)
     1008newdim = onewnc.createDimension('yaround',Ngrid*2+1)
     1009newdim = onewnc.createDimension('stats',5)
    6941010
    6951011# Variable dimensions
    6961012##
    697 newvar = onewnc.createVariable('simtime','f8',('time'))
    698 basicvardef(newvar, 'simtime', 'time simulation', obstunits )
    699 set_attribute(newvar, 'calendar', 'standard')
    700 newvar[:] = coindtvalues[:][2]
    701 
    7021013newvar = onewnc.createVariable('obstime','f8',('time'))
    7031014basicvardef(newvar, 'obstime', 'time observations', obstunits )
    7041015set_attribute(newvar, 'calendar', 'standard')
    705 newvar[:] = coindtvalues[:][3]
     1016newvar[:] = coindtvalues[:,3]
    7061017
    7071018newvar = onewnc.createVariable('couple', 'c', ('couple','StrLength'))
     
    7091020writing_str_nc(newvar, ['sim','obs'], StringLength)
    7101021
     1022newvar = onewnc.createVariable('statistics', 'c', ('stats','StrLength'))
     1023basicvardef(newvar, 'statistics', 'statitics from values', '-')
     1024writing_str_nc(newvar, statsn, StringLength)
     1025
     1026if obskind == 'trajectory':
     1027    if dims.has_key('Z'):
     1028        newdim = onewnc.createDimension('trj',3)
     1029    else:
     1030        newdim = onewnc.createDimension('trj',2)
     1031
     1032    newvar = onewnc.createVariable('obssimtrj','i',('obstime','trj'))
     1033    basicvardef(newvar, 'obssimtrj', 'trajectory on the simulation grid', '-')
     1034    newvar[:] = trajpos.transpose()
     1035
     1036if dims.has_key('Z'):
     1037    newdim = onewnc.createDimension('simtrj',4)
     1038    trjsim = np.zeros((4,Ncoindt), dtype=int)
     1039    trjsimval = np.zeros((4,Ncoindt), dtype=np.float)
     1040else:
     1041    newdim = onewnc.createDimension('simtrj',3)
     1042    trjsim = np.zeros((3,Ncoindt), dtype=int)
     1043    trjsimval = np.zeros((3,Ncoindt), dtype=np.float)
     1044
    7111045Nvars = len(valvars)
    7121046for ivar in range(Nvars):
    7131047    simobsvalues = []
     1048# Values spatially around the point (+/- [Ngrid] points)
     1049    simobsSvalues = []
    7141050
    7151051    varsimobs = valvars[ivar][0] + '_' + valvars[ivar][1]
     
    7201056          "' !!"
    7211057        quit(-1)
     1058
    7221059    if not osim.variables.has_key(valvars[ivar][0]):
    723         print errormsg
    724         print '  ' + main + ": simulation file has not '" + valvars[ivar][0] + "' !!"
    725         quit(-1)
     1060        if not searchInlist(varNOcheck, valvars[ivar][0]):
     1061            print errormsg
     1062            print '  ' + main + ": simulation file has not '" + valvars[ivar][0] +   \
     1063              "' !!"
     1064            quit(-1)
     1065        else:
     1066            ovsim = compute_varNOcheck(osim, valvars[ivar][0])
     1067    else:
     1068        ovsim = osim.variables[valvars[ivar][0]]
    7261069
    7271070    ovobs = oobs.variables[valvars[ivar][1]]
    728     ovsim = osim.variables[valvars[ivar][0]]
     1071    if dims.has_key('Z'):
     1072        simobsSvalues = np.zeros((Ncoindt, Ngrid*2+1, Ngrid*2+1, Ngrid*2+1),         \
     1073          dtype = np.float)
     1074    else:
     1075        simobsSvalues = np.zeros((Ncoindt, Ngrid*2+1, Ngrid*2+1), dtype = np.float)
    7291076
    7301077    if obskind == 'multi-points':
    7311078        for it in range(Ncoindt):
    732             slicev = dims['X'][0]+':'+str(trajpos[2,it]) + '|' +                     \
    733               dims['Y'][0]+':'+str(trajpos[1,it]) + '|' +                            \
     1079            slicev = dims['X'][0] + ':' + str(trajpos[2,it]) + '|' +                 \
     1080              dims['Y'][0]+ ':' + str(trajpos[1,it]) + '|' +                         \
     1081              dims['T'][0]+ ':' + str(coindtvalues[it][0])
     1082            slicevar, dimslice = slice_variable(ovsim, slicev)
     1083            simobsvalues.append([ slicevar, ovobs[coindtvalues[it][1]]])
     1084            slicev = dims['X'][0] + ':' + str(trajpos[2,it]-Ngrid) + '@' +           \
     1085              str(trajpos[2,it]+Ngrid) + '|' + dims['Y'][0] + ':' +                  \
     1086              str(trajpos[1,it]-Ngrid) + '@' + str(trajpos[1,it]+Ngrid) + '|' +      \
    7341087              dims['T'][0]+':'+str(coindtvalues[it][0])
    7351088            slicevar, dimslice = slice_variable(ovsim, slicev)
    736             simobsvalues.append([ ovsim[slicevar], ovobs[coindtvalues[it][1]]])
     1089            simobsSvalues[it,:,:] = slicevar
     1090
    7371091    elif obskind == 'single-station':
    7381092        for it in range(Ncoindt):
    739             slicev = dims['X'][0]+':'+str(stationpos[1]) + '|' +                       \
    740               dims['Y'][0]+':'+str(stationpos[0]) + '|' +                              \
     1093            slicev = dims['X'][0]+':'+str(stationpos[1]) + '|' +                      \
     1094              dims['Y'][0]+':'+str(stationpos[0]) + '|' +                             \
    7411095              dims['T'][0]+':'+str(coindtvalues[it][0])
    7421096            slicevar, dimslice = slice_variable(ovsim, slicev)
    743             simobsvalues.append([ slicevar, ovobs[coindtvalues[it][1]]])
     1097            simobsvalues.append([ slicevar, ovobs[coindtvalues[it,1]]])
     1098            slicev = dims['X'][0] + ':' + str(trajpos[2,it]-Ngrid) + '@' +           \
     1099              str(trajpos[2,it]+Ngrid) + '|' + dims['Y'][0] + ':' +                  \
     1100              str(trajpos[1,it]-Ngrid) + '@' + str(trajpos[1,it]+Ngrid) + '|' +      \
     1101              dims['T'][0] + ':' + str(coindtvalues[it,0])
     1102            slicevar, dimslice = slice_variable(ovsim, slicev)
     1103            simobsSvalues[it,:,:] = slicevar
    7441104    elif obskind == 'trajectory':
    7451105        if dims.has_key('Z'):
    7461106            for it in range(Ncoindt):
    747                 slicev = dims['X'][0]+':'+str(trajpos[2,it]) + '|' +                 \
    748                   dims['Y'][0]+':'+str(trajpos[1,it]) + '|' +                        \
    749                   dims['Z'][0]+':'+str(trajpos[0,it]) + '|' +                        \
    750                   dims['T'][0]+':'+str(coindtvalues[it][0])
    751                 slicevar, dimslice = slice_variable(ovsim, slicev)
    752                 simobsvalues.append([ ovsim[slicevar], ovobs[coindtvalues[it][1]]])
    753                 print simobsvalues[varsimobs][:][it]
     1107                if notfound[it] == 0:
     1108                    ito = int(coindtvalues[it,1])
     1109                    trajpos[2,ito] = index_mat(valdimsim['Z'][it,:,trajpos[1,ito],   \
     1110                     trajpos[0,ito]], valdimobs['Z'][ito])
     1111                    slicev = dims['X'][0]+':'+str(trajpos[0,ito]) + '|' +            \
     1112                      dims['Y'][0]+':'+str(trajpos[1,ito]) + '|' +                   \
     1113                      dims['Z'][0]+':'+str(trajpos[2,ito]) + '|' +                   \
     1114                      dims['T'][0]+':'+str(int(coindtvalues[it,0]))
     1115                    slicevar, dimslice = slice_variable(ovsim, slicev)
     1116                    simobsvalues.append([ slicevar, ovobs[int(ito)]])
     1117                    slicev = dims['X'][0] + ':' + str(trajpos[0,ito]-Ngrid) + '@' +  \
     1118                      str(trajpos[0,ito]+Ngrid+1) + '|' + dims['Y'][0] + ':' +       \
     1119                      str(trajpos[1,ito]-Ngrid) + '@' + str(trajpos[1,ito]+Ngrid+1)+ \
     1120                      '|' + dims['Z'][0] + ':' + str(trajpos[2,ito]-Ngrid) + '@' +   \
     1121                      str(trajpos[2,ito]+Ngrid+1) + '|' + dims['T'][0] + ':' +       \
     1122                      str(int(coindtvalues[it,0]))
     1123                    slicevar, dimslice = slice_variable(ovsim, slicev)
     1124                    simobsSvalues[it,:,:,:] = slicevar
     1125                    if ivar == 0:
     1126                        trjsim[0,it] = trajpos[0,ito]
     1127                        trjsim[1,it] = trajpos[1,ito]
     1128                        trjsim[2,it] = trajpos[2,ito]
     1129                        trjsim[3,it] = coindtvalues[it,0]
     1130                else:
     1131                    simobsvalues.append([fillValueF, fillValueF])
     1132                    simobsSvalues[it,:,:,:]= np.ones((Ngrid*2+1,Ngrid*2+1,Ngrid*2+1),\
     1133                      dtype = np.float)*fillValueF
    7541134        else:
    7551135            for it in range(Ncoindt):
    756                 slicev = dims['X'][0]+':'+str(trajpos[2,it]) + '|' +                 \
    757                   dims['Y'][0]+':'+str(trajpos[1,it]) + '|' +                        \
    758                   dims['T'][0]+':'+str(coindtvalues[it][0])
    759                 slicevar, dimslice = slice_variable(ovsim, slicev)
    760                 simobsvalues.append([ ovsim[slicevar], ovobs[coindtvalues[it][1]]])
     1136                if notfound[it] == 0:
     1137                    ito = coindtvalues[it,1]
     1138                    slicev = dims['X'][0]+':'+str(trajpos[2,ito]) + '|' +            \
     1139                      dims['Y'][0]+':'+str(trajpos[1,ito]) + '|' +                   \
     1140                      dims['T'][0]+':'+str(coindtvalues[ito,0])
     1141                    slicevar, dimslice = slice_variable(ovsim, slicev)
     1142                    simobsvalues.append([ slicevar, ovobs[coindtvalues[it,1]]])
     1143                    slicev = dims['X'][0] + ':' + str(trajpos[0,it]-Ngrid) + '@' +   \
     1144                      str(trajpos[0,it]+Ngrid) + '|' + dims['Y'][0] + ':' +          \
     1145                      str(trajpos[1,it]-Ngrid) + '@' + str(trajpos[1,it]+Ngrid) +    \
     1146                      '|' + dims['T'][0] + ':' + str(coindtvalues[it,0])
     1147                    slicevar, dimslice = slice_variable(ovsim, slicev)
     1148                    simobsSvalues[it,:,:] = slicevar
     1149                else:
     1150                    simobsvalues.append([fillValue, fillValue])
     1151                    simobsSvalues[it,:,:] = np.ones((Ngrid*2+1,Ngrid*2+1),           \
     1152                      dtype = np.float)*fillValueF
    7611153                print simobsvalues[varsimobs][:][it]
    7621154
    763     newvar = onewnc.createVariable(varsimobs, 'f', ('time','couple'))
    764     descvar = 'couples of simulated: ' + valvars[ivar][0] + ' and observed ' +        \
     1155# Statistics around values
     1156    aroundstats = np.zeros((5,Ncoindt), dtype=np.float)
     1157    for it in range(Ncoindt):
     1158        aroundstats[0,it] = np.min(simobsSvalues[it,])
     1159        aroundstats[1,it] = np.max(simobsSvalues[it,])
     1160        aroundstats[2,it] = np.mean(simobsSvalues[it,])
     1161        aroundstats[3,it] = np.mean(simobsSvalues[it,]*simobsSvalues[it,])
     1162        aroundstats[4,it] = np.sqrt(aroundstats[3,it] - aroundstats[2,it]*           \
     1163          aroundstats[2,it])
     1164
     1165# Values to netCDF
     1166    newvar = onewnc.createVariable(varsimobs, 'f', ('time','couple'),                \
     1167      fill_value=fillValueF)
     1168    descvar = 'couples of simulated: ' + valvars[ivar][0] + ' and observed ' +       \
    7651169      valvars[ivar][1]
    7661170    basicvardef(newvar, varsimobs, descvar, ovobs.getncattr('units'))
    767  
    7681171    newvar[:] = np.array(simobsvalues)
    7691172
     1173# Around values
     1174    if dims.has_key('Z'):
     1175        newdim = onewnc.createDimension('zaround',Ngrid*2+1)
     1176        newvar = onewnc.createVariable( valvars[ivar][0] + 'around', 'f',            \
     1177          ('time','zaround','yaround','xaround'), fill_value=fillValueF)
     1178    else:
     1179        newvar = onewnc.createVariable( valvars[ivar][0] + 'around', 'f',            \
     1180          ('time','yaround','xaround'), fill_value=fillValueF)
     1181
     1182    descvar = 'around simulated values +/- grid values: ' + valvars[ivar][0]
     1183    basicvardef(newvar, varsimobs + 'around', descvar, ovobs.getncattr('units'))
     1184    newvar[:] = simobsSvalues
     1185
     1186# Statistics
     1187    newvar = onewnc.createVariable(varsimobs + 'staround', 'f', ('time','stats'),   \
     1188      fill_value=fillValueF)
     1189    descvar = 'around simulated statisitcs: ' + valvars[ivar][0]
     1190    basicvardef(newvar, varsimobs + 'staround', descvar, ovobs.getncattr('units'))
     1191    newvar[:] = aroundstats.transpose()
     1192
    7701193    onewnc.sync()
     1194
     1195newvar = onewnc.createVariable('simtrj','i',('time','simtrj'))
     1196basicvardef(newvar, 'simtrj', 'coordinates [X,Y,Z,T] of the coincident trajectory ' +\
     1197  'in sim', obstunits)
     1198newvar[:] = trjsim.transpose()
    7711199
    7721200# Global attributes
Note: See TracChangeset for help on using the changeset viewer.