Changeset 790 in lmdz_wrf


Ignore:
Timestamp:
May 31, 2016, 4:19:32 PM (9 years ago)
Author:
lfita
Message:

Adding in `DataSetSection_multivars' option for string variables and one single value

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/tools/nc_var_tools.py

    r789 r790  
    46344634    Lchar = length of the string in the netCDF file
    46354635    """
     4636    fname = 'get_str_nc'
     4637
     4638    Nvalues = varo.shape[0]
     4639
     4640    strings = []
     4641
     4642    for ival in range(Nvalues):
     4643        stringv = varo[ival,:]
     4644        string = str('')
     4645        for ich in range(Lchar):
     4646            charval = str(stringv[ich:ich+1]).replace('[','').replace(']','').replace("'","")
     4647            if charval == '--' or len(charval) == 0:
     4648                break
     4649            else:
     4650                if ich == 0:
     4651                    string = charval
     4652                else:
     4653                    string = string + charval
     4654
     4655        strings.append(string.strip())
     4656
     4657    return strings
     4658
     4659def get_str_nc_word(varo, Lchar):
     4660    """ Function to get string values in a netCDF variable as a chains of 1char values
     4661    varo= netCDF variable object
     4662    Lchar = length of the string in the netCDF file
     4663    """
    46364664
    46374665    Nvalues = varo.shape[0]
     
    1230412332      onc= output netcdf object
    1230512333      vn= variable name to include
    12306       sliced= dictioary with the dimension name as key and [beg, end, int] as values
     12334      sliced= dictionary with the dimension name as key and [beg, end, int] as values
    1230712335    """
    1230812336    fname = 'put_variable_slice'
    1230912337
    12310     if not searchInlist(inc.variables,vn):
     12338    if not gen.searchInlist(inc.variables,vn):
    1231112339        print errormsg
    1231212340        print ' ' + fname + ": variable '" + vn + "' is not in file!!"
     
    1231512343    ov = inc.variables[vn]
    1231612344
    12317     dnvs = ov.dimensions
     12345#    dnvs = ov.dimensions
     12346    dnvs = []
    1231812347    varslice = []
    1231912348# Getting variable's dimensions
    12320     for dnv in dnvs:
    12321         if not searchInlist(onc.dimensions,dnv):
    12322             od = inc.dimensions[dnv]
    12323             if od.isunlimited():
    12324                 dsize = None
     12349    for dnv in ov.dimensions:
     12350        if gen.searchInlist(sliced.keys(),dnv):
     12351            newdimsize = sliced[dnv][1] - sliced[dnv][0]
     12352        else:
     12353            newdimsize = 10
     12354        if not gen.searchInlist(onc.dimensions,dnv):
     12355# Avoiding montone dimensions!
     12356            if newdimsize > 0:
     12357                od = inc.dimensions[dnv]
     12358                if od.isunlimited():
     12359                    dsize = None
     12360                else:
     12361                    dsize = len(od)
     12362                newdim = onc.createDimension(dnv, dsize)
     12363        if gen.searchInlist(sliced.keys(),dnv):
     12364            if newdimsize > 0:
     12365                varslice.append(slice(sliced[dnv][0], sliced[dnv][1], sliced[dnv][2]))
     12366                dnvs.append(dnv)
    1232512367            else:
    12326                 dsize = len(od)
    12327             newdim = onc.createDimension(dnv, dsize)
    12328         if searchInlist(sliced.keys(),dnv):
    12329             varslice.append(slice(sliced[dnv][0], sliced[dnv][1], sliced[dnv][2]))
     12368                varslice.append(sliced[dnv][0])
    1233012369        else:
    1233112370            varslice.append(slice(0,len(inc.dimensions[dnv])))
     12371            dnvs.append(dnv)
    1233212372# Getting variable
    1233312373    varattrs = ov.ncattrs()
    12334     if searchInlist(varattrs, '_FillValue'):
     12374    if gen.searchInlist(varattrs, '_FillValue'):
    1233512375        varfil = ov._FillValue
    1233612376    else:
     
    1233812378    vartype = ov.dtype
    1233912379
    12340     newvar = onc.createVariable(vn, vartype, dnvs, fill_value=varfil)
    12341 #    print 'Lluis shapes newvar:',newvar.shape,'slice:',varslice
    12342     newvar[:] = ov[tuple(varslice)]
     12380    newvar = onc.createVariable(vn, vartype, tuple(dnvs), fill_value=varfil)
     12381    finalvals = np.squeeze(ov[tuple(varslice)])
     12382    newvar[:] = finalvals
    1234312383
    1234412384    for attrs in varattrs:
     
    1235312393      values= [varn1],[beg1],[end1],[int1]@[...[[varnM],[begM],[endM],[intM]]]
    1235412394        [varni]: name of the variable ('WRFt', for WRF time varibale)
    12355         [begi],[endi],[inti]: beginning, end and interval along the dimension-axis
     12395        [begi],[endi],[inti]: beginning, end and interval along the variable
    1235612396          [endi] = -1, maximum value
    1235712397          [inti] = -1, all the values within the range
    12358           NOTE: dimensions without section by the variables are taken allover their size
     12398          NOTE: variables without section by the variables are taken allover their size
    1235912399      filen= netCDF with the data-set
    1236012400      varn= ',' list of variables ('all', for all variables)
     
    1237312413    Nvars = len(values.split('@'))
    1237412414
     12415    nciobj = NetCDFFile(filen,'r')
     12416
    1237512417# Slicing variables
    1237612418    varns = []
     
    1238412426    for ivar in range(Nvars):
    1238512427        val = values.split('@')[ivar]
    12386         varns.append(val.split(',')[0])
    12387         begvs[ivar] = np.float(val.split(',')[1])
    12388         endvs[ivar] = np.float(val.split(',')[2])
    12389         intvs[ivar] = np.float(val.split(',')[3])
    12390         ofiletile = ofiletile + '_' + varns[ivar] + '_B' + str(begvs[ivar]) + '-E' + \
    12391           str(endvs[ivar]) + '-I' + str(intvs[ivar])
    12392         if intvs[ivar] != -1:
    12393             slicevalS = slicevalS + varns[ivar] + ' (' + str(begvs[ivar]) + ',' +    \
    12394               str(endvs[ivar]) + ',' + str(intvs[ivar]) + '); '
     12428        vn = val.split(',')[0]
     12429        if not gen.searchInlist(nciobj.variables,vn):
     12430            print errormsg
     12431            print '  ' + fname + ": file '" + filen + "' does not have variable '" + \
     12432              vn + "' !!"
     12433            print '    it has:', nciobj.variables
     12434            quit(-1)
     12435
     12436        ostrvar = nciobj.variables[vn]
     12437        varns.append(vn)
     12438        if val.split(',')[3] == 'str':
     12439            strvalue = val.split(',')[1].replace('!',' ')
     12440            print warnmsg
     12441            print '  ' + fname + ": String value for variable '" + val + "' !!"
     12442            print '    assuming string variable as [Nvalues, Lstring]'
     12443            print "    from which only is required '" + strvalue + "'"
     12444            strvals = get_str_nc(ostrvar, ostrvar.shape[1])
     12445            if not gen.searchInlist(strvals, strvalue):
     12446                print errormsg
     12447                print '  ' + fname + ": variable '" + val + "' does not have " +     \
     12448                  "value: '" + strvalue + "' !!"
     12449                print '    values:', strvals
     12450                quit(-1)
     12451            indstrvalue = strvals.index(strvalue)
     12452            begvs[ivar] = np.float(indstrvalue)
     12453            endvs[ivar] = np.float(indstrvalue)
     12454            intvs[ivar] = -99.
     12455            ofiletile = ofiletile + '_' + varns[ivar] + '_S'
    1239512456        else:
    12396             slicevalS = slicevalS + varns[ivar] + ' (' + str(begvs[ivar]) + ',' +    \
    12397               str(endvs[ivar]) + ',1); '
     12457            begvs[ivar] = np.float(val.split(',')[1])
     12458            endvs[ivar] = np.float(val.split(',')[2])
     12459            intvs[ivar] = np.float(val.split(',')[3])
     12460            ofiletile = ofiletile + '_' + varns[ivar] + '_B' + str(begvs[ivar]) + '-E' + \
     12461              str(endvs[ivar]) + '-I' + str(intvs[ivar])
     12462            if intvs[ivar] != -1:
     12463                slicevalS = slicevalS + varns[ivar] + ' (' + str(begvs[ivar]) + ',' +    \
     12464                  str(endvs[ivar]) + ',' + str(intvs[ivar]) + '); '
     12465            else:
     12466                slicevalS = slicevalS + varns[ivar] + ' (' + str(begvs[ivar]) + ',' +    \
     12467                  str(endvs[ivar]) + ',1); '
    1239812468
    1239912469    ofile = ofile=filen.split('.')[0] + ofiletile + '.nc'
    1240012470
    12401     nciobj = NetCDFFile(filen,'r')
    1240212471    ncoobj = NetCDFFile(ofile,'w')
    1240312472
     
    1241712486        print '  ' + fname + ": masking with '" + varns[ivar] + "':",  begvs[ivar],  \
    1241812487          ',', endvs[ivar], ',', intvs[ivar]
    12419         if not searchInlist(nciobj.variables,varns[ivar]) and not                    \
    12420           searchInlist(NOcheck,varns[ivar]):
     12488        if not gen.searchInlist(nciobj.variables,varns[ivar]) and not                \
     12489          gen.searchInlist(NOcheck,varns[ivar]):
    1242112490            print errormsg
    1242212491            print ' ' + fname + ": variable '" + varns[ivar] + "' is not in ' +      \
     
    1244212511            vardims = ovar.dimensions
    1244312512
    12444         if endvs[ivar] == -1: endvs[ivar] = np.max(vals)
    12445         maskinf = ma.masked_less(vals, begvs[ivar])
    12446         masksup = ma.masked_greater(vals, endvs[ivar])
    12447 
    12448         if intvs[ivar] != -1:
    12449             print errormsg
    12450             print '  ' + fname + ': non-consecutive slices not ready!!'
    12451             quit(-1)
    12452         finalmask = maskinf.mask + masksup.mask
    12453         idn = 0
     12513        if intvs[ivar] != -99.:
     12514            if endvs[ivar] == -1: endvs[ivar] = np.max(vals)
     12515            maskinf = ma.masked_less(vals, begvs[ivar])
     12516            masksup = ma.masked_greater(vals, endvs[ivar])
     12517
     12518            if intvs[ivar] != -1:
     12519                print errormsg
     12520                print '  ' + fname + ': non-consecutive slices not ready!!'
     12521                quit(-1)
     12522            finalmask = maskinf.mask + masksup.mask
     12523            idn = 0
     12524        else:
     12525            ostrvar = nciobj.variables[varns[ivar]]
     12526            finalmask = np.ones((ostrvar.shape), dtype= bool)
     12527            finalmask[int(begvs[ivar]),:] = False
    1245412528
    1245512529        slicedims = {}
    1245612530       
     12531        iidim = 0
    1245712532        for dn in vardims:
    1245812533            ddn = len(nciobj.dimensions[dn])
    1245912534            dinds = np.arange(ddn)
    1246012535            rightvals = np.where(finalmask, False, True)
    12461             slicedims[dn]=[np.min(dinds[rightvals]), np.max(dinds[rightvals])+1, None]
     12536
     12537            if intvs[ivar] != -99.:
     12538                slicedims[dn]=[np.min(dinds[rightvals][0,:]), np.max(dinds[rightvals][0,:])+1, None]
     12539            else:
     12540                if iidim == 0:
     12541                    slicedims[dn]=[int(begvs[ivar]), int(begvs[ivar]), None]
     12542                else:
     12543                    slicedims[dn]=[0, ddn, None]
     12544
     12545            iidim = iidim + 1
    1246212546
    1246312547        print '  ' + fname + ': slicing variables with______'
     
    1247212556            dimsize = None
    1247312557        else:
    12474             dimsize = slicedims[nd][1] - slicedims[nd][0] + 1
    12475         newdim = ncoobj.createDimension(nd, dimsize)
     12558            dimsize = slicedims[nd][1] - slicedims[nd][0]
     12559        if dimsize > 0: newdim = ncoobj.createDimension(nd, dimsize)
    1247612560    ncoobj.sync()
    1247712561
Note: See TracChangeset for help on using the changeset viewer.