Changeset 1532 in lmdz_wrf


Ignore:
Timestamp:
Apr 19, 2017, 5:35:13 PM (8 years ago)
Author:
lfita
Message:

Starting to add `maskvarVal': Function to mask a variable as combination of values from other variables from another file and using

a list of resultant variables to mask a variable by inter-matching values

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/tools/nc_var_tools.py

    r1530 r1532  
    39333933      [maskvalue]= value to use for maskking ('mask' value for using an already masked variable)
    39343934    filename= netCF file name
    3935     varparameters= [varn]|[dimsmask]
     3935    varparameters= [varn]:[dimsmask]
    39363936      [varn]: variable name
    39373937      [samedimsmask]: ',' list of name of dimensions which fits [maskvarn] slice
     
    40984098
    40994099    return
     4100
     4101def maskvarVal(values, filename, varparameters):
     4102    """ Function to mask a variable as combination of values from other variables from another file and using
     4103      a list of resultant variables to mask a variable by inter-matching values
     4104    values= [maskfilename]:[maskvarns]:[dimsmask]
     4105      [maskfilename]= file with the mask
     4106      [maskvarns]= ',' list of [maskvarn1]|maskval1]|[comp],[...[maskvarnN]|[maskvalN]|[compN]] triplets of
     4107        variable name, value and comparison to use to mask
     4108          [comp]: comparisons
     4109            'eq:' masking all values equal than [maskvali]
     4110            'ge:' masking all values bigger or equal than [maskvali]
     4111            'gt:' masking all values bigger than [maskvali]
     4112            'le:' masking all values smaller or equal than [maskvali]
     4113            'lt:' masking all values smaller than [maskvali]
     4114      [dimsmask]= ',' list of [dimn]|[sec] to use for slicing all [maskvari]
     4115        [sec]: section
     4116          * [integer]: which value of the dimension
     4117          * -1: all along the dimension
     4118          * -9: last value of the dimension
     4119          * [beg]@[end] slice from [beg] to [end]
     4120          * NOTE: no value provided is for all dimension range
     4121       [matchingmaskvars]: ',' of name of variables from masking file, the non-masked values of which will be
     4122         used to mask the variable
     4123    filename= netCF file name
     4124    varparameters= [varn]:[dimsmask]
     4125      [varns]: ',' list of variable names in the same order than [matchingmaskvars] to search for coincidencies
     4126      [applydimsmask]: ',' list of name of dimensions along which apply the mask
     4127    """
     4128    fname='maskvarVal'
     4129
     4130    if values == 'h':
     4131        print fname + '_____________________________________________________________'
     4132        print maskvarVal.__doc__
     4133        quit()
     4134
     4135    expectargs = '[maskfilename]:[maskvarns]:[dimsmask]'
     4136    gen.check_arguments(fname,values,expectargs,':')
     4137
     4138    maskfilename = values.split(':')[0]
     4139    maskvarns = gen.str_list(values.split(':')[1], ',')
     4140    dimsmask = values.split(':')[2]
     4141
     4142    varns = gen.str_list(varparameters.split(':')[0], ',')
     4143    applydimsmask = gen.str_list(varparameters.split(':')[1], ',')
     4144
     4145    ofile = 'mask_' + '-'.join(varns) + '.nc'
     4146
     4147    # Masking variables
     4148    ncfmask = NetCDFFile(maskfilename,'r')
     4149
     4150    applymasks = []
     4151    for mvarns in maskvarns:
     4152        maskvarn = mvarns.split('|')[0]
     4153        maskval = mvarns.split('|')[1]
     4154        maskcomp = mvarns.split('|')[2]
     4155        if not ncfmask.variables.has_key(maskvarn):
     4156            print errormsg
     4157            print '    ' + fname + ": File  '" + maskfilename + "' does not have " + \
     4158              " variable mask '" + maskvarn + "' !!"
     4159            print errormsg
     4160            ncf.close()
     4161            ncfmask.close()
     4162            quit(-1)
     4163
     4164        varmaskobj = ncfmask.variables[maskvarn]
     4165        varmaskinf = variable_inf(varmaskobj)
     4166        mval = gen.retype(maskval,varmaskinf.type)
     4167        maskvalues, maskdims = slice_variable(varmaskobj, dimsmask.replace('|',':'). \
     4168          replace(',','|'))
     4169        if maskcomp == 'eq':
     4170            applymasks[ma.masked_equal(maskvalues, mval)]
     4171        elif maskcomp == 'ge':
     4172            applymasks[ma.masked_equal(maskvalues, mval)]
     4173
     4174    print 'NOT finished !!!!'
     4175    quit(-1)
     4176
     4177    ncfmask.close()
     4178
     4179
     4180
     4181
     4182    ncf = NetCDFFile(filename,'r')
     4183
     4184
     4185
     4186
     4187    for varn in varns:
     4188        if not ncf.variables.has_key(varn):
     4189            print errormsg
     4190            print '    ' + fname + ": File  '" + filename + "' does not have " +     \
     4191              "variable '" + varn + '" !!!!'
     4192            print errormsg
     4193            ncf.close()
     4194        quit(-1)
     4195
     4196    varobj = ncf.variables[varn]
     4197    varinf = variable_inf(varobj)
     4198
     4199
     4200    # Looking for variable & mask compatibility
     4201    runningsize = 1
     4202    rundims = []
     4203    testslicevar = []
     4204    runshape = []
     4205    for dimn in varobj.dimensions:
     4206        Ldim = len(ncf.dimensions[dimn])
     4207        if gen.searchInlist(samedimsmask,dimn):
     4208            testslicevar.append(slice(0,Ldim,None))
     4209        else:
     4210            runningsize = runningsize*Ldim
     4211            rundims.append(dimn)
     4212            runshape.append(Ldim)
     4213            testslicevar.append(0)
     4214    testvar = varobj[tuple(testslicevar)]
     4215
     4216    gen.same_shape(testvar,maskvalues)
     4217
     4218# Creation of the new file
     4219##
     4220    ncfnew = NetCDFFile(ofile,'w')
     4221   
     4222    for idim in range(varinf.Ndims):
     4223        newdimv = ncf.dimensions[varinf.dimns[idim]]
     4224        if newdimv.isunlimited():
     4225            ncfnew.createDimension(varinf.dimns[idim], None)
     4226        else:
     4227            ncfnew.createDimension(varinf.dimns[idim], varinf.dims[idim])
     4228    # FillVallue
     4229    if varinf.dtype == type(np.int(1)):
     4230        fillValue = gen.fillValueI
     4231    elif varinf.dtype == type('c'):
     4232        fillValue = gen.fillValueC
     4233    elif varinf.dtype == type(np.int16(1)) or varinf.dtype == type(np.int32(1)):
     4234        fillValue = gen.fillValueI16
     4235    elif varinf.dtype == type(np.float(1.)):
     4236        fillValue = gen.fillValueF
     4237    elif varinf.dtype == type(np.float32(1.)) or varinf.dtype == type(np.float64(1.)):
     4238        fillValue = gen.fillValueF64
     4239    else:
     4240        print errormsg
     4241        print '  ' + fname + ': type of variable:', varinf.dtype, 'not ready!!'
     4242        quit(-1)
     4243
     4244    if maskvalue != 'mask':
     4245        maskval = gen.retype(maskvalue,varinf.dtype)
     4246    else:
     4247        print infmsg
     4248        print '  ' + fname + ': maskgin with already masked variable'
     4249        varmaskv = maskvalues.mask
     4250
     4251    newvar = ncfnew.createVariable(varn, varinf.dtype, varinf.dimns,                 \
     4252      fill_value=fillValue)
     4253    for attrn in varinf.attributes:
     4254        if not attrn == '_FillValue':
     4255            attr = newvar.setncattr(attrn, varobj.getncattr(attrn))
     4256
     4257    attr = newvar.setncattr('mask', 'variable masked using ' + values.split(':')[2]+ \
     4258      ' of variable ' + maskvarn + ' from file ' + maskfilename)
     4259    newvar[:] = varobj[:]
     4260
     4261    ncfnew.sync()
     4262    ncfnew.close()
     4263
     4264    for varns in ncf.variables:
     4265        if not varns == varn:
     4266            try:
     4267                with gen.Capturing() as output:
     4268                    fvaradd(filename + ',' + varns, ofile)
     4269            except:
     4270                print errmsg
     4271                print 'fvaradd(' + filename + ', ' + varns + ',' + ofilen + ')'
     4272                for s1out in output: print s1out
     4273                quit(-1)
     4274
     4275    ncfnew = NetCDFFile(ofile,'a')
     4276    varobj = ncfnew.variables[varn]
     4277
     4278    # Masking following that dimensions which are not coincident with the mask
     4279
     4280    # Check if there are some coincident dimensional names between both variables
     4281    vdimns = list(varinf.dimns)
     4282    mdimns = maskdims
     4283
     4284    for dimn in mdimns:
     4285        if gen.searchInlist(vdimns,dimn): vdimns.remove(dimn)
     4286
     4287    #slices = gen.provide_slices(varinf.dimns, varinf.dims, list(varmaskinf.dimns))
     4288    slices = gen.provide_slices(varinf.dimns, varinf.dims, vdimns)
     4289
     4290    if maskvalue != 'mask':
     4291        maskTOuse = ma.masked_equal(maskvalues, maskval)
     4292        maskTOusev = maskTOuse.mask
     4293    else:
     4294        maskTOusev = maskvalues.mask
     4295
     4296    for ir in range(runningsize):
     4297        islice = slices[ir]
     4298        varvals = varobj[tuple(islice)]
     4299        maskvarvals = np.where(maskTOusev, fillValue, varvals)
     4300        newvar[tuple(islice)] = maskvarvals
     4301
     4302    ncfnew.sync()
     4303    ncfnew.close()
     4304    ncf.close()
     4305
     4306    print 'masked file "' + ofile + '" generated !!!'
     4307
     4308    return
     4309
    41004310
    41014311def chgtimestep(values, origfile, varN):
Note: See TracChangeset for help on using the changeset viewer.