Changeset 2343 in lmdz_wrf


Ignore:
Timestamp:
Feb 15, 2019, 8:58:17 PM (6 years ago)
Author:
lfita
Message:

Adding:

  • `except_fillValue': Function to fill a file with fill_Value except a given value of a variable
    • Adding selection of kind of filling outside selection
Location:
trunk/tools
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/tools/nc_var.py

    r2325 r2343  
    7171## e.g. # nc_var.py -o compute_slices_stats_areaweighted -S 'XLONG,-74.,-36.4,4.;XLAT,-63.,19.,4.;HGT,500.,7000.,500.@Time|WRFtime:west_east|XLONG:south_north|XLAT@Time@west_east|lon_bnds,south_north|lat_bnds@XLONG|lat_bnds;lon_bnds,XLAT|lat_bnds;lon_bnds@Time' -f wrfout_bnds.nc -v T2,U10,V10,Q2
    7272## e.g. # nc_var.py -o compute_slices_stats_areaweighted -S 'lat,-63.,19.,2.;orog,500.,7000.,500.;rangefaces,fixed,-2.5|-0.5,-0.5|0.5,0.5|2.5@time|time:lon|lon:lat|lat@time@lon|lon_bnds,lat|lat_bnds@lon|lon_bnds,lat|lat_bnds@lat,lon@time' -f /media/lluis/ExtDiskC_ext3/DATA/estudios/Andes/DATA/concatenated/historical/tasmin/tasmin_Amon_ACCESS1-0_historical_r1i1p1_185001-200512_Andes_19600101000000-19900101000000.nc -v tasmin
     73## e.g. # nc_var.py -o except_fillValue -S 'orog:range,500.,7000.:None' -f /home/lluis/estudios/Andes/cmip_data/fx/orog_fx_ACCESS1-0_historical_r0i0p0.nc -v 'all'
    7374
    7475from optparse import OptionParser
     
    118119# dimToUnlimited: Operation to create an unlimited dimension from an existing one
    119120# dimVar_creation: Function to add a 1D variable with the size of a given dimension in a file
     121# except_fillValue: Function to fill a file with fill_Value except a given value of a variable
    120122# fattradd: Adding attributes from a reference file
    121123# fdimadd: Adding dimension from another reference file
     
    229231  'DataSetSection', 'DataSetSection_multidims', 'DataSetSection_multivars',          \
    230232  'DYNAMICO_toCF', 'dimrename', 'dimrm', 'dimToUnlimited', 'dimVar_creation',        \
    231   'fattradd',                                                                        \
     233  'except_fillValue', 'fattradd',                                                    \
    232234  'fdimadd', 'fgaddattr', 'field_stats', 'field_stats_dim', 'file_creation',         \
    233235  'file_oper_alongdims', 'filter_2dim',                                              \
     
    397399elif oper == 'dimVar_creation':
    398400    ncvar.dimVar_creation(opts.values, opts.ncfile)
     401elif oper == 'except_fillValue':
     402    ncvar.except_fillValue(opts.values, opts.ncfile, opts.varname)
    399403elif oper == 'fattradd':
    400404    ncvar.fattradd(var, opts.values, opts.ncfile)
  • trunk/tools/nc_var_tools.py

    r2339 r2343  
    7575# dimToUnlimited: Operation to create an unlimited dimension from an existing one
    7676# dimVar_creation: Function to add a 1D variable with the size of a given dimension in a file
     77# except_fillValue: Function to fill a file with fill_Value except a given value of a variable
    7778# fattradd: Adding attributes from a reference file
    7879# fgaddattr: Adding global attributes from a reference file
     
    2939829399def except_fillValue(values, ncfile, variable):
    2939929400    """ Function to fill a file with fill_Value except a given value of a variable
    29400       values= [varname]:[value]:[rmdims]
     29401      values= [varname]:[value]:[rmdims]:[fill]
    2940129402        [varname]: name of the variable to use its values for the filling
    2940229403        [value]: value of the variable from which grid points will not be filled by
     
    2940629407            range [ivaule],[evalue]
    2940729408        [rmdims]: ',' separated list of [dimn]@[dimv] name of dimensions and value to
    29408           remove from [varname] to find the value
     29409          remove from [varname] to find the value ('None' for any)
    2940929410          [dimn]: name of the dimension from [varname]
    2941029411          [dimv]: value of [dimn] to use
     29412        [fill]: kind of filling for the values outside selection
     29413          'fill_value': using standard fill_values according to the type of variable
     29414          'value',[value]: using [value] according to the type of variable
    2941129415      ncfile= netCDF file to fill
    29412       variable= name of the variables to use
     29416      variable= ',' list of name of the variables to fill ('all' for all variables)
    2941329417    """
    2941429418    fname = 'except_fillValue'
    2941529419
    2941629420    availvalue = ["'exact',[value]", "'range',[ivalue],[evalue]"]
     29421    availfill = ["'fill_value'", "'value',[value]"]
    2941729422
    2941829423    if values == 'h':
     
    2942129426        quit()
    2942229427
    29423     expectargs = '[varname]:[value]:[rmdims]'
     29428    expectargs = '[varname]:[value]:[rmdims]:[fill]'
    2942429429    gen.check_arguments(fname, values, expectargs, ':')
    2942529430
    2942629431    varname = values.split(':')[0]
    2942729432    value = values.split(':')[1]
    29428     rmdims = values.split(':')[2]
    29429 
     29433    rmdims00 = values.split(':')[2]
     29434    fill = values.split(':')[3]
     29435
     29436    # Getting dimensions to remove from varname to make the selection
     29437    if rmdims00 != 'None':
     29438        rmdims0 = gen.str_list(rmdims00, ',')
     29439    else:
     29440        rmdims0 = None
     29441
     29442    # Getting kind of selection
    2943029443    if value[0:5] == 'exact':
     29444        kind = 'exact'
    2943129445        varvalue = value.split(',')[1]
     29446        print infmsg
     29447        print '  ' + fname + ": masking by '" + kind + "' not equal ", varvalue
    2943229448    elif value[0:5] == 'range':
     29449        kind = 'range'
    2943329450        ivarvalue = value.split(',')[1]
    2943429451        evarvalue = value.split(',')[2]
     29452        print infmsg
     29453        print '  ' + fname + ": masking by '" + kind + "' within [", ivarvalue, ',', \
     29454          evarvalue, ']'
    2943529455    else:
    2943629456        print errormsg
     
    2943929459        quit(-1)
    2944029460
    29441    
    29442 
     29461    # Getting kind of filling
     29462    if fill[0:10] == 'fill_value':
     29463        kfill = 'fval'
     29464    elif fill[0:5] == 'value':
     29465        kfill = 'val'
     29466        kfillv = fill.split(',')[1]
     29467    else:
     29468        print errormsg
     29469        print '  ' + fname + ": kind of filling '" + fill +  "' not ready !!"
     29470        print '    available ones:', availfill
     29471        quit(-1)
     29472       
    2944329473    onc = NetCDFFile(ncfile, 'r')
    2944429474    if not onc.variables.has_key(varname):
     
    2944629476        print '  ' + fname + ": file '" + + "' does not have variable '" + varname + \
    2944729477          "' !!"
    29448         varns = list(onc.variables.keys())
    29449         varns.sort()
    29450         print '    available ones:', varns
     29478        Varns = list(onc.variables.keys())
     29479        Varns.sort()
     29480        print '    available ones:', Varns
    2945129481        quit(-1)
    2945229482
     29483    if rmdims0 is not None:
     29484        rmdims = {}
     29485        for rmd in rmdims0:
     29486            dn = rmd.split('@')[0]
     29487            dv = rmd.split('@')[1]
     29488            if not gen.searchInlist(onc.dimensions,dn):
     29489                print errormsg   
     29490                print '  ' + fname + ": file '" + + "' does not have dimension '" +  \
     29491                  dn + "' !!"
     29492                dimns = list(onc.dimensions)
     29493                dimns.sort()
     29494                print '    available ones:', dimns
     29495                quit(-1)
     29496            rmdims[dn] = dv
     29497    else:
     29498        rmdims = None
     29499
    2945329500    ovar = onc.variables[varname]
     29501    if rmdims is not None:
     29502        rmdns = list(rmdims.keys())
     29503        rmdvs = list(rmdims.values())
     29504        varv, rmdims, rmshape = ovar_reducedims(ovar, rmdns, rmdvs)
     29505    else:
     29506        varv = ovar[:]
     29507        rmdims = ovar.dimensions
     29508        rmshape = ovar.shape
     29509
     29510    if variable != 'all':
     29511        varns = gen.str_list(variable, ',')
     29512    else:
     29513        varns = onc.variables.keys()
     29514
     29515    # Filling the variables
     29516    ofilen = fname + '.nc'
     29517    onewnc = NetCDFFile(ofilen, 'w')
    2945429518   
     29519    # Getting variable of filling
     29520    idim = 0
     29521    newrmdims = []
     29522    for dn in rmdims:
     29523        onewnc.createDimension(dn+'fill', rmshape[idim])
     29524        newrmdims.append(dn+'fill')
     29525        idim = idim + 1
     29526
     29527    # Removing the variables which do not have the fill dimensions
     29528    newvarns = varns + []
     29529    for varn in varns:
     29530        if not onc.variables.has_key(varn):
     29531            print errormsg
     29532            print '  ' + fname + ": file '" + + "' does not have variable '" + varn+ \
     29533              "' !!"
     29534            Varns = list(onc.variables.keys())
     29535            Varns.sort()
     29536            print '    available ones:', Varns
     29537            quit(-1)
     29538        ovar = onc.variables[varn]
     29539        dvns = ovar.dimensions
     29540        for drmn in rmdims:
     29541            if not gen.searchInlist(dvns, drmn):
     29542                print infmsg
     29543                print '  ' +fname + ": variable '" + varn + "' does not have fill "+ \
     29544                  " dimension '" + drmn + "', removing variable from list"
     29545                newvarns.remove(varn)
     29546                break
     29547    varns = newvarns + []
     29548
     29549    if kind == 'exact':
     29550        varvalue = gen.typemod(varvalue, varv.dtype)
     29551        mavarv = ma.masked_not_equal(varv, varvalue)
     29552    elif kind == 'range':
     29553        ivarvalue = gen.typemod(ivarvalue, varv.dtype)
     29554        evarvalue = gen.typemod(evarvalue, varv.dtype)
     29555        mavarv = ma.masked_outside(varv, ivarvalue, evarvalue)
     29556    mamask = mavarv.mask
     29557
     29558    if ovar.dtype == type(1):
     29559        newvar= onewnc.createVariable(varname + 'fill', ovar.dtype, tuple(newrmdims),\
     29560          fill_value=gen.fillValueI)
     29561        mavarv.filled(gen.fillValueI)
     29562    elif ovar.dtype == type(1.):
     29563        newvar= onewnc.createVariable(varname + 'fill', ovar.dtype, tuple(newrmdims),\
     29564          fill_value=gen.fillValueF)
     29565        mavarv.filled(gen.fillValueF)
     29566    elif ovar.dtype == type(np.float32(1.)) or ovar.dtype == type(np.float64(1.)):
     29567        newvar= onewnc.createVariable(varname + 'fill', ovar.dtype, tuple(newrmdims),\
     29568          fill_value=gen.fillValueD)
     29569        mavarv.filled(gen.fillValueD)
     29570    else:
     29571        print errormsg
     29572        print '  ' + fname + ': type of variable ', ovar.dtype, 'not ready !!'
     29573        print '    available ones:', type(1), type(1.), type(np.float32(1.)),        \
     29574          type(np.float64(1.))
     29575        quit(-1)
     29576
     29577    newvar[:] = mavarv
     29578    vattrs = ovar.ncattrs()
     29579    for attrn in vattrs:
     29580        if attrn != '_FillValue':
     29581            attrv = ovar.getncattr(attrn)
     29582            newvar.setncattr(attrn, attrv)
     29583    if kind == 'exact':
     29584        newvar.setncattr('only_exact',varvalue)
     29585    elif kind == 'range':
     29586        mavarv = ma.masked_outside(varv, ivarvalue, evarvalue)
     29587        newvar.setncattr('only_within_beg',ivarvalue)
     29588        newvar.setncattr('only_within_end',evarvalue)
     29589
     29590    onewnc.sync()
     29591
     29592    # getting variables and slicing
     29593    for varn in varns:
     29594        print varn + " ..."
     29595        ovar = onc.variables[varn]
     29596
     29597        vdims = list(ovar.dimensions)
     29598        for dn in vdims:
     29599            odim = onc.dimensions[dn]
     29600            if not gen.searchInlist(onewnc.dimensions, dn):
     29601                if odim.isunlimited(): onewnc.createDimension(dn, None)
     29602                else: onewnc.createDimension(dn, len(onc.dimensions[dn]))
     29603
     29604        vshape = ovar.shape
     29605        newdims = vdims + []
     29606        for dn in rmdims:
     29607            if gen.searchInlist(newdims, dn): newdims.remove(dn)
     29608
     29609        slicesvar = gen.provide_slices(vdims, vshape, newdims)
     29610        Nslices = len(slicesvar)
     29611
     29612        if ovar.dtype == type(1):
     29613            if kfill == 'fval':
     29614                fillv = gen.fillValueI
     29615            else:
     29616                fillv = int(kfillv)
     29617        elif ovar.dtype == type(1.):
     29618            if kfill == 'fval':
     29619                fillv = gen.fillValueF
     29620            else:
     29621                fillv = np.float(kfillv)
     29622        elif ovar.dtype== type(np.float32(1.)) or ovar.dtype== type(np.float64(1.)):
     29623            if kfill == 'fval':
     29624                fillv = gen.fillValueD
     29625            else:
     29626                if ovar.dtype== type(np.float32(1.)): fillv = np.float32(kfillv)
     29627                else: fillv = np.float64(kfillv)
     29628        else:
     29629            print errormsg
     29630            print '  ' +fname+ ': fill type of variable ', ovar.dtype, 'not ready !!'
     29631            print '    available ones:', type(1), type(1.), type(np.float32(1.)),    \
     29632              type(np.float64(1.))
     29633            quit(-1)
     29634
     29635        if kfill == 'fval':
     29636            newvar = onewnc.createVariable(varn, ovar.dtype, tuple(vdims),           \
     29637              fill_value=fillv)
     29638        else:
     29639            newvar = onewnc.createVariable(varn, ovar.dtype, tuple(vdims))
     29640
     29641        for islc in range(Nslices):
     29642            slcv = slicesvar[islc]
     29643            filled = ma.masked_array(ovar[tuple(slcv)], mask=mamask)
     29644            fill = filled.filled(fillv)
     29645            newvar[tuple(slcv)] = fill
     29646
     29647        vattrs = ovar.ncattrs()
     29648        for attrn in vattrs:
     29649            if attrn != '_FillValue':
     29650                attrv = ovar.getncattr(attrn)
     29651                newvar.setncattr(attrn, attrv)
     29652        newvar.setncattr('fill', varname + 'fill')
     29653        onewnc.sync()
     29654
     29655        # Looking for coordinates (let's be pro!)
     29656        if gen.searchInlist(vattrs, 'coordinates'):
     29657            coords = ovar.getncattr('coordinates')
     29658            print infmsg
     29659            print '  ' + fname + ": variable '" + varn + "' with coordinates " +     \
     29660              "attribtue:" + coords + " !!"
     29661            print '  adding coordinates if they are not yet in file'
     29662            cordv = coords.split(' ')
     29663            add_vars(onc, onewnc, cordv)               
     29664           
     29665    # Global attributes
     29666    add_global_PyNCplot(onewnc, 'nc_var_tools', fname, '1.0')
     29667    onewnc.sync()
     29668
     29669    vattrs = onc.ncattrs()
     29670    for attrn in vattrs:
     29671        attrv = onc.getncattr(attrn)
     29672        onewnc.setncattr(attrn, attrv)
     29673    onewnc.sync()
     29674
     29675    onc.close()
     29676    onewnc.close()
     29677   
     29678    print fname + ": successful writting of file '" + ofilen + "' !!"
     29679
     29680    return
     29681
     29682#except_fillValue('orog:range,500.,7000.:None:value,0', '/home/lluis/estudios/Andes/cmip_data/fx/orog_fx_ACCESS1-0_historical_r0i0p0.nc', 'all')
    2945529683
    2945629684#quit()
Note: See TracChangeset for help on using the changeset viewer.