Changeset 2377 in lmdz_wrf


Ignore:
Timestamp:
Mar 7, 2019, 7:29:25 PM (6 years ago)
Author:
lfita
Message:

Adding error on `add_vars' when input object does not have a given variable

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/tools/nc_var_tools.py

    r2372 r2377  
    370370    """ Function to add variables from a given netCDF object to another one
    371371      oc: source netcdfile object
    372       nc: netcdfile object to add dimensions
     372      nc: netcdfile object to add variables
    373373      vnames: list of name of variables to add
    374374    """
     
    378378        if not gen.searchInlist(nc.variables,vn):
    379379            print '  ' + fname + ': adding var:',vn,' ...'
     380
     381            if not oc.variables.has_key(vn):
     382                print errormsg
     383                print '  '+fname+ ": input netCDF object does not have variable '" + \
     384                  vn + "' !!"
     385                Varns = list(oc.variables.keys())
     386                Varns.sort()
     387                print '    available ones:', Varns
     388                quit(-1)
    380389
    381390            varo = oc.variables[vn]
     
    3040930418#except_fillValue('orog:range,500.,7000.:None:value,0', '/home/lluis/estudios/Andes/cmip_data/fx/orog_fx_ACCESS1-0_historical_r0i0p0.nc', 'all')
    3041030419
    30411 
    3041230420def usefile_compute_slices_stats_areaweighted(values, ncfile, variable):
    3041330421    """ Function to compute stats of variables of a file splitting variables by
     
    3080030808#usefile_compute_slices_stats_areaweighted(values, '/media/lluis/ExtDiskC_ext4/bkup/llamp/estudios/dominios/SA5k/geo_em.d01.nc', 'LANDUSEF')
    3080130809
     30810def compress_data(values, ncfile, variable):
     30811    """ Function to compress (only provide values for a criteria) the values of a 2D
     30812          file following a given criteria from one of its variables
     30813      values=[compressvar]:[slicecompressvar]:[criteria]:[axesdimvars]
     30814        [compressvarn]: name of variable to use to define the criteria
     30815        [slicecompressvar]: ',' list of selection values of [dimn]|[val] for only the
     30816          dimensions of [compressvar] in order to construct a 2D variable to use
     30817          for the compression ('all', to use all dimensions)
     30818        [criteria]: criteria to use for the compression following [compresssvar] values
     30819          'singlevalue',[value]: only the points where [compressvar] = [value]
     30820          'range',[begval],[endval]: only the points where [begval] <= [compressvar]
     30821            <= [value]
     30822        [axesdimvars]: ',' separated list of [AxisN]|[dimnN]|[vardimnN]
     30823          dimension name [dimn] and its associated dimension-variable for the X, Y, Z
     30824          and T axes, (use additional capital letters for extra axes)
     30825      ncfile= netCDF file to use
     30826      variable: ',' list of variables to compress ('all' for all variables)
     30827    """
     30828    fname = 'compress_data'
     30829
     30830    availcrit = ["'singlevalue',[value]" , "'range',[begval],[endval]"]
     30831
     30832    if values == 'h':
     30833        print fname + '_____________________________________________________________'
     30834        print compress_data.__doc__
     30835        quit()
     30836
     30837    expectargs = '[compressvarn]:[slicecompressvar]:[criteria]:[axesdimvars]'
     30838    gen.check_arguments(fname, values, expectargs, ':')
     30839
     30840    compressvarn = values.split(':')[0]
     30841    slicecompressvar = values.split(':')[1]
     30842    criteria = values.split(':')[2]
     30843    axesdimvars = values.split(':')[3].split(',')
     30844
     30845    onc = NetCDFFile(ncfile, 'r')
     30846
     30847    if not onc.variables.has_key(compressvarn):
     30848        print errormsg
     30849        print '  ' + fname + ": file '" + ncfile + "' does not have compress " +     \
     30850          "variable '" + compressvarn + "' !!"
     30851        Varns = onc.variables.keys()
     30852        Varns.sort()
     30853        print '    available ones:', Varns
     30854        onc.close()
     30855        quit(-1)
     30856
     30857    ocompressvar = onc.variables[compressvarn]
     30858    if slicecompressvar == 'all':
     30859        compressvar = ocompressvar[:]
     30860    else:
     30861        slicevar = []
     30862        slicedims = gen.stringS_dictvar(slicecompressvar, ',', '|')
     30863        vardims = ocompressvar.dimensions
     30864        for vd in vardims:
     30865            if slicedims.has_key(vd): slicevar.append(slicedims[vd])
     30866            else: slicevar.append(slice(0,len(onc.dimensions[vd])))
     30867        compressvar = ocompressvar[tuple(slicevar)]
     30868
     30869    if len(compressvar.shape) != 2:
     30870        print errormsg
     30871        print '  ' + fname + ": slice from the compressed var '" + compressvarn +    \
     30872          "' must be of rank 2 and it has a shape:", compressvar.shape, '!!'
     30873        print "    provide a ',' list of '[dimn]|[value]' as 'slicecompressvar' " +  \
     30874          "variable in order to obtain a 2D slice of the var to use to compress"
     30875        print '    dimensions of the compress variable:', ocompressvar.dimensions
     30876        onc.close()
     30877        quit(-1)
     30878
     30879    crit = criteria.split(',')
     30880    if crit[0] == 'single':
     30881        compressv = gen.typemod(crit[1], ocompressvar.dtype)
     30882        compressmask = ma.masked_not_equal(compressvar,compressv)
     30883    elif crit[0] == 'range':
     30884        icompressv = gen.typemod(crit[1], ocompressvar.dtype)
     30885        ecompressv = gen.typemod(crit[2], ocompressvar.dtype)
     30886        compressmask = ma.masked_outside(compressvar,icompressv,ecompressv)
     30887    else:
     30888        print errormsg
     30889        print '  ' + fname + ": compressing criteria '" + crit[0] + "' not ready !!"
     30890        print '    avaialable ones:', availcrit
     30891        quit(-1)
     30892
     30893    Nvals = np.sum(~compressmask.mask)
     30894    if Nvals == 0:
     30895        print errormsg
     30896        print '  ' + fname + ": for compress variable '" + compressvarn+ "' sliced "+\
     30897          slicecompressvar, "and criteria '" + criteria + "' no values are obtained!!"
     30898        print '    fix either the slice and/or the criteria'
     30899        quit(-1)
     30900    else:
     30901        print infmsg
     30902        print '  ' + fname + ': compressed number of values:', Nvals
     30903
     30904    # Getting axis dimension-variables
     30905    axisdims = {}
     30906    for axdv in axesdimvars:
     30907        axN = axdv.split('|')[0]
     30908        dn = axdv.split('|')[1]
     30909        dv = axdv.split('|')[2]
     30910        axisdims[axN] = [dn, dv]
     30911
     30912    # Creation of the output file
     30913    onewnc = NetCDFFile(fname + '.nc', 'w')
     30914
     30915    # Dimensions
     30916    newdim = onewnc.createDimension(compressvarn, Nvals)
     30917    dnv = axisdims['X']
     30918    newdim = onewnc.createDimension(dnv[0], len(onc.dimensions[dnv[0]]))
     30919    compressS = dnv[0]
     30920    dnv = axisdims['Y']
     30921    newdim = onewnc.createDimension(dnv[0], len(onc.dimensions[dnv[0]]))
     30922    compressS = dnv[0] + ' ' + dnv[1]
     30923
     30924    # Space Dimension variables
     30925    dnv = axisdims['X']
     30926    add_vars(onc,onewnc,[dnv[1]])
     30927    dnv = axisdims['Y']
     30928    add_vars(onc,onewnc,[dnv[1]])
     30929
     30930    # Variable
     30931    icvar = np.arange(np.prod(compressvar.shape))
     30932    icc = icvar[~compressmask.mask]
     30933
     30934    newvar = onenc.createVariable(compressvar, 'i', ('compressvar'))
     30935    cfvarvals = gen.variablesvalues(compressvar)
     30936    basicvardef(newvar, cfvarvals[1], cfvarvals[4], cfvarvals[5])
     30937    newvar.setncattr('compress', compressS)
     30938    newvar[:] = icc
     30939   
     30940    return
     30941
     30942
     30943values = 'XLAND:Time|0:single,1:X|west_east|XLONG_M,Y|south_north|XLAT_M'
     30944
     30945compress_data(values, '/home/lluis/PY/wrfout_d01_1995-01-01_00:00:00', 'T2')
     30946
    3080230947#quit()
    3080330948
Note: See TracChangeset for help on using the changeset viewer.