Changeset 1490 in lmdz_wrf for trunk


Ignore:
Timestamp:
Apr 4, 2017, 3:23:20 AM (8 years ago)
Author:
lfita
Message:

Adding:

`addDim': Operation to add a new dimension in a file

Fixing minor typos

Location:
trunk/tools
Files:
3 edited

Legend:

Unmodified
Added
Removed
  • trunk/tools/documentation/ncmanage/intro.html

    r1403 r1490  
    8282        <LI><SPAN CLASS="codetxt">ivattrs:</SPAN> Give all the attributes of a variable and its type</LI>
    8383        <LI><SPAN CLASS="codetxt">LMDZ_toCF:</SPAN> Function to pass a LMDZ original file to CF-conventions</LI>
    84         <LI><SPAN CLASS="codetxt">maskvar:</SPAN> Function to mask a variable using a mask. It is assumed that mask[...,dimM,dimJ,dimK] and </LI>
     84        <LI><SPAN CLASS="codetxt">maskvar:</SPAN> Function to mask a variable using a mask. It is assumed that mask[...,dimM,dimJ,dimK] and var[...,dimM,dimJ,dimK] share the last dimensions </LI>
    8585        <LI><SPAN CLASS="codetxt">model_characteristics:</SPAN> Function to provide major characteristics of a given model output</LI>
    8686        <LI><SPAN CLASS="codetxt">ncreplace:</SPAN> Function to replace something from a netCDF file</LI>
  • trunk/tools/nc_var.py

    r1484 r1490  
    5151import generic_tools as gen
    5252
     53# addDim: Operation to add a new dimension in a file
    5354# addVar: Operation to add a new variable in a file using exisintg dimensions
    5455# addvals: Function to add values to a given variable at a given dimension
     
    159160# WRF_toCF: Function to pass a WRF original file to CF-conventions
    160161
    161 operations=['addVar', 'addvals', 'CDO_toCF', 'chdimname', 'changevartype',          \
     162operations=['addDim', 'addVar', 'addvals', 'CDO_toCF', 'chdimname', 'changevartype', \
    162163  'checkallvars', 'checkAllValues', 'checkNaNs',                                     \
    163164  'chgtimestep', 'chvarname', 'cleaning_varsfile', 'compute_deaccum',                \
     
    265266    quit(-1)
    266267
    267 if oper == 'addVar':
     268if oper == 'addDim':
     269    ncvar.addDim(opts.values, opts.ncfile, opts.varname)
     270elif oper == 'addVar':
    268271    ncvar.addVar(opts.values, opts.ncfile, opts.varname)
    269272elif oper == 'addvals':
  • trunk/tools/nc_var_tools.py

    r1488 r1490  
    1818
    1919####### Contents:
     20# addDim: Operation to add a new dimension in a file
    2021# add_dims: Function to add dimensions from a given netCDF object to another one
    2122# add_globattrs: Function to add global attributes from a given netCDF object to another one
     
    12431244    attrv = int(attrv0)
    12441245  elif attrk == 'R':
    1245     attrv = float8(attrv0)
     1246    attrv = np.float(attrv0)
    12461247  elif attrk == 'D':
    12471248    attrv = np.float64(attrv0)
     
    39163917    return
    39173918
    3918 def maskvar(values, filename, varn):
     3919def maskvar(values, filename, varparameters):
    39193920    """ Function to mask a variable using a mask. It is assumed that mask[...,dimM,dimJ,dimK] and
    39203921      var[...,dimM,dimJ,dimK] share the last dimensions
     
    39223923      [maskfilename]= file with the mask
    39233924      [maskvar]= name of the variable with the mask
    3924       [dimsmask]= dimensions d1,d2,d3,... to use from variable [mask] (ahead of the sharing ones with [var])
    3925       [timename]= name of the variable time in [filename]
     3925      [dimsmask]= ',' list of [dimn]|[sec] to use for slicing [maskvar]
     3926        [sec]: section
     3927          * [integer]: which value of the dimension
     3928          * -1: all along the dimension
     3929          * -9: last value of the dimension
     3930          * [beg]@[end] slice from [beg] to [end]
     3931        * NOTE: no value provided is for all dimension range
     3932      [maskvalue]= value to use for maskking
    39263933    filename= netCF file name
    3927     varn= variable name
     3934    varparameters= [varn]|[dimsmask]
     3935      [varn]: variable name
     3936      [samedimsmask]: ',' list of name of dimensions which fits [maskvar] slice
    39283937    """
    39293938    fname='maskvar'
    39303939
    3931     fillValue=1.e20
     3940    if values == 'h':
     3941        print fname + '_____________________________________________________________'
     3942        print maskvar.__doc__
     3943        quit()
     3944
    39323945    ofile = 'mask_' + varn + '.nc'
    39333946
    39343947    maskfilename = values.split(':')[0]
    39353948    maskvar = values.split(':')[1]
    3936     maskdims = np.array(values.split(':')[2].split(','), dtype=int)
    3937     timename = values.split(':')[3]
     3949    dimsmask = values.split(':')[3]
     3950    maskvalue = values.split(':')[4]
     3951
     3952    varn = varparameters.splice(':')[0]
     3953    samedimsmask = varparameters.splice(':')[1].split(',')
    39383954
    39393955    ncf = NetCDFFile(filename,'r')
     
    39413957    if not ncf.variables.has_key(varn):
    39423958        print errormsg
    3943         print '    ' + fname + ': File  "' + filename + '" does not have variable "' + varn + '" !!!!'
     3959        print '    ' + fname + ": File  '" + filename + "' does not have variable '"+\
     3960          varn + '" !!!!'
    39443961        print errormsg
    39453962        ncf.close()
     
    39483965    varobj = ncf.variables[varn]
    39493966    varinf = variable_inf(varobj)
    3950     timeobj = ncf.variables[timename]
    3951     timeinf = cls_time_information(ncf, timename)
    39523967
    39533968    ncfmask = NetCDFFile(maskfilename,'r')
     
    39553970    if not ncfmask.variables.has_key(maskvar):
    39563971        print errormsg
    3957         print '    ' + fname + ': File  "' + maskfilename + '" does not have variable mask "' + maskvar + '" !!!!'
     3972        print '    ' + fname + ": File  '" + maskfilename + "' does not have " +     \
     3973          " variable mask '" + maskvar + "' !!"
    39583974        print errormsg
    39593975        ncf.close()
     
    39623978
    39633979    varmaskobj = ncfmask.variables[maskvar]
    3964     varmaskinf = variable_inf(varmaskobj)
    3965 
    3966     sdims=[]
    3967     for ivdim in range(varinf.Ndims):
    3968         vardim = varinf.Ndims - ivdim - 1
    3969         maskdim = varmaskinf.Ndims - ivdim - 1
    3970         if varinf.dims[vardim] == varmaskinf.dims[vardim]:
    3971             sdims.append(varinf.dims[vardim])
     3980    maskvalues, maskdims = slice_variable(varmaskobj, dimsmask.replace('|',':').     \
     3981      replace(',','|'))
     3982
     3983    ncfmask.close()
     3984
     3985    # Looking for variable & mask compatibility
     3986    runningsize = 1
     3987    rundims = []
     3988    testslicevar = []
     3989    runshape = []
     3990    for dimn in varobj.dimensions.keys():
     3991        Ldim = len(ncf.dimensions[dimn])
     3992        if gen.searchInlist(samedimsmask,dimn):
     3993            testslicevar.append(slice(0,Ldim,None))
    39723994        else:
    3973             break
    3974 
    3975     samedims = sdims[::-1]
    3976     print '  ' + fname + ': variable: ', varinf.dims, ' and mask: ', varmaskinf.dims,' share: ', samedims
    3977 
    3978 # masking
    3979 ##
    3980     Nsamedims=len(samedims)
    3981 
    3982     if not Nsamedims + len(maskdims) == varmaskinf.Ndims:
    3983         print errormsg
    3984         print '  ' + fname + ': desired dimensions of mask ', maskdims, ' and coincident dims with variable ',Nsamedims, ' does not match mask dims ',varmaskinf.Ndims,' !!!!'
    3985         print errormsg
    3986         ncf.close()
    3987         ncfmask.close()
    3988         quit(-1)
    3989 
    3990     if varmaskinf.Ndims > Nsamedims:
    3991         maskvals = load_ncvariable_lastdims(ncfmask, maskvar, maskdims, Nsamedims)
    3992     else:
    3993         maskvals = maskvarobj[:]
    3994 
    3995     ncfmask.close()
     3995            runningsize = runningsize*Ldim
     3996            rundims.append(dimn)
     3997            runshape.append(Ldim)
     3998            testslicevar.append(0)
     3999    testvar = varobj[tuple(testslicevar)]
     4000
     4001    gen.same_shape(testvar,maskvalues)
    39964002
    39974003# Creation of the new file
     
    40054011        else:
    40064012            ncfnew.createDimension(varinf.dimns[idim], varinf.dims[idim])
    4007 
    4008     newvar = ncfnew.createVariable(varn, varinf.dtype, varinf.dimns, fill_value=fillValue)
     4013    # FillVallue
     4014    if varinf.dtype == type(np.int(1)):
     4015        fillValue = gen.fillValueI
     4016    elif varinf.dtype == type('c'):
     4017        fillValue = gen.fillValueC
     4018    elif varinf.dtype == type(np.int16(1)) or varinf.dtype == type(np.int32(1)):
     4019        fillValue = gen.fillValueI16
     4020    elif varinf.dtype == type(np.float(1.)):
     4021        fillValue = gen.fillValueF
     4022    elif varinf.dtype == type(np.float32(1.)) or varinf.dtype == type(np.float64(1.)):
     4023        fillValue = gen.fillValueF64
     4024
     4025    newvar = ncfnew.createVariable(varn, varinf.dtype, varinf.dimns,                 \
     4026      fill_value=fillValue)
    40094027    for attrn in varinf.attributes:
    40104028        if not attrn == '_FillValue':
    40114029            attr = newvar.setncattr(attrn, varobj.getncattr(attrn))
    40124030
    4013     attr = newvar.setncattr('mask', 'variable masked using ' + values.split(':')[2] + ' of variable ' + maskvar + ' from file ' + maskfilename)
     4031    attr = newvar.setncattr('mask', 'variable masked using ' + values.split(':')[2] +\
     4032      ' of variable ' + maskvar + ' from file ' + maskfilename)
    40144033
    40154034    ncfnew.sync()
     
    40214040
    40224041    ncfnew = NetCDFFile(ofile,'a')
     4042    varobj = ncfnew.variables[varn]
     4043
     4044    # Masking following that dimensions which are not coincident with the mask
     4045    maskval = gen.retype(maskvalue,varinf.dtype)
     4046    if runshape > 1:
     4047        idim = 0
     4048        runslice = list(runshape)
     4049        while idim <= runningsize:
     4050            slicevar = []
     4051            inosim = len(runshape)
     4052            for dimn in varobj.dimensions.keys():
     4053                Ldim = len(ncf.dimensions[dimn])
     4054                if gen.searchInlist(samedimsmask,dimn):
     4055                    slicevar.append(slice(0,Ldim,None))
     4056                else:
     4057                    slicevar.append()
     4058            testvar = varobj[tuple(testslicevar)]
     4059           
     4060
     4061    else:
     4062        maskedvals = ma.masked(varobj[:],maskval)
     4063
     4064    varobj[:] = maskedvals
     4065
     4066
     4067       
     4068
     4069
    40234070
    40244071    Nptmask = 1
     
    76217668                    print errormsg
    76227669                    print '  ' + fname + ': given: ',len(vals),' but variable ' +    \
    7623                       'reaquires: ',values.shape[1],'!!!'
     7670                      'requires: ',values.shape[1],'!!!'
    76247671                    exit(-1)
    76257672                for i1 in range(len(vals)):
     
    1840518452    return
    1840618453
     18454def addDim(values, ncfile, dimn):
     18455    """ Operation to add a new dimension in a file
     18456      values= [size]
     18457        [size]: size of the dimension ('unlimited' for unlimited)
     18458      ncfile= name of the file
     18459      dimn= name of the new dimension
     18460    """
     18461    fname = 'addDim'
     18462
     18463    if values == 'h':
     18464        print fname + '_____________________________________________________________'
     18465        print addDim.__doc__
     18466        quit()
     18467
     18468    onc = NetCDFFile(ncfile, 'a')
     18469
     18470    if onc.dimensions.has_key(dimn):
     18471        print errormsg
     18472        print '  ' + fname + ": file '" + ncfile + "' already has dimension '" +     \
     18473          dimn + "' !!"
     18474        onc.close()
     18475        quit(-1)
     18476
     18477    if values == 'unlimited':
     18478        Ldim = None
     18479    else:
     18480        Ldim = int(values)
     18481
     18482    newdim = onc.createDimension(dimn, Ldim)
     18483    onc.sync()
     18484    onc.close()
     18485
     18486    print fname + ": succesful addition of dimension '" + dimn + "' size:", Ldim,'!!'
     18487
     18488    return
     18489
     18490
    1840718491def addVar(values, ncfile, varn):
    1840818492    """ Operation to add a new variable in a file using exisintg dimensions
Note: See TracChangeset for help on using the changeset viewer.