Changeset 883 in lmdz_wrf for trunk/tools


Ignore:
Timestamp:
Jun 18, 2016, 8:04:54 PM (9 years ago)
Author:
lfita
Message:

Working in a new and clearer 'oper_along_dims'

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/tools/nc_var_tools.py

    r882 r883  
    7575# netcdf_fold_concatenation: Function to concatenate netCDF files in a given folder for a given set of variables
    7676# operation_alongdims: Function to operate along different dimensions of a variable
     77# operdim: Function to operate along a series of dimensions
    7778# ovar_onc: Function to copy an object variable to a nother netcdf object
    7879# Partialmap_Entiremap: Function to transform from a partial global map (e.g.: only land points) to an entire one Coincidence of points is done throughout a first guess from fractions of the total domain of search
     
    87568757    return varvalues, dimnslice
    87578758
     8759def operdim(varv, vardims, doper, oper):
     8760    """ Function to operate along a series of dimensions
     8761      varv: matrix values
     8762      vardims: dimension names of the variable
     8763      doper: names of the dimensions to operate
     8764      oper: operation to perform
     8765    """
     8766    fname = 'operdim'
     8767
     8768    operslice = []
     8769    for dn in vardims:
     8770        if not gen.searchInlist(doper, dn):
     8771            operslice.append(False)
     8772        else:
     8773            operslice.append(True)
     8774
     8775    operddims = []
     8776    noper = 0
     8777    for idim in range(len(varv.shape)):
     8778        if operslice[idim]:
     8779            if oper == 'max':
     8780                varoper = np.max(varv, axis=idim-noper)
     8781            elif oper == 'mean':
     8782                varoper = np.mean(varv, axis=idim-noper)
     8783            elif oper == 'mean2':
     8784                varoper = np.mean(varv, axis=idim-noper)
     8785            elif oper == 'min':
     8786                varoper = np.min(varv, axis=idim-noper)
     8787            elif oper == 'sum':
     8788                varoper = np.sum(varv, axis=idim-noper)
     8789            else:
     8790                print errormsg
     8791                print '  ' + fname + ': operation "' + oper + '" not ready!!'
     8792                quit(-1)
     8793            noper = noper + 1
     8794        else:
     8795            operddims.append(vardims[idim])
     8796           
     8797    return operedvals, opereddims
     8798
    87588799def operation_alongdims(ovar,dimvals,dimsoper,opkind):
    87598800    """ Function to operate along different dimensions of a variable
     
    89338974
    89348975# Getting slice dimensions
    8935     dimslice = []
    8936     dimvalslice = []
     8976    dimslice = {}
    89378977    for dv in dimvals:
    89388978        dnv = dv.slice('|')[0]
    89398979        dvv = dv.slice('|')[1]
    8940         dimslice.append(dnv)
    8941         dimvalslice.append(dvv)
    8942 
     8980        if dvv.find(':') != -1:
     8981            beg = int(dvv.slice(':')[0])
     8982            end = int(dvv.slice(':')[1])
     8983            dimslice[dnv] = [beg, end, 1]
     8984        else
     8985            dimslice[dnv] = int(dvv)
    89438986
    89448987# Creation of output file
     
    89478990
    89488991    print '  ' + fname + ": '" + operkind + "' with:",dimsoper,'_______'
     8992    newNdim = 0
     8993    newNvar = 0
    89498994    for vn in varns:
    89508995        print "'" + vn + "' ... .. ."
     
    89629007
    89639008        if tocopmute:
     9009            varslice, varsliceddims = VarSliceDict(ov,dimslice)
     9010            varvals0 = ov[tuple(varslice)]
     9011            varvals = np.squeeze(varvals0)
     9012
     9013            finalvarvals, finaldims = operdim(varvals, varsliceddims, dimsoper, operkind)
     9014
     9015            # Adding dimensions
     9016            idn = 0
     9017            for dn in finaldims:
     9018                if newNdim == 0:
     9019                    if not objnc.dimensions[dn].isunlimited:
     9020                        objnewnc.createDimension(dn, finalvarvals[idn])
     9021                    else:
     9022                        objnewnc.createDimension(dn, None)
     9023                    newNdim = newNdim + 1
     9024                else:
     9025                    if not gen.searchInlist(objnewnc, dn):
     9026                        if not objnc.dimensions[dn].isunlimited:
     9027                            objnewnc.createDimension(dn, finalvarvals[idn])
     9028                        else:
     9029                            objnewnc.createDimension(dn, None)
     9030                        newNdim = newNdim + 1
     9031                idn = idn + 1
     9032
     9033            # Adding variable
     9034            varinf = variable_inf(ov)
     9035            if varinf.FillValue is not None:
     9036                 newvar = objnewnc.createVariable(vn + oper, nctype(varinf.dtype),   \
     9037                   tuple(finaldims), fillValue=varinf.FillValue)
     9038            else:
     9039                 newvar = objnewnc.createVariable(vn + oper, nctype(varinf.dtype),   \
     9040                   tuple(finaldims))
     9041                newNvar = newNvar + 1
     9042
     9043# new variable
     9044            oldvarattr = ov.ncattrs()
     9045   
     9046            varname = gen.variables_values(vn)[0]
     9047            if gen.searchInlist(oldvarattr, 'standard_name'):
     9048                stdname = ov.getncattr('standard_name')
     9049            else:
     9050                stdname = gen.variables_values(vn)[1]
    89649051       
    8965 
    8966 
    8967 
    8968     return
     9052            if gen.searchInlist(oldvarattr, 'long_name'):
     9053                lname = ov.getncattr('long_name')
     9054            else:
     9055                lname = gen.variables_values(vn)[4].replace('|',' ')
     9056
     9057            if gen.searchInlist(oldvarattr, 'units'):
     9058                uname = ov.getncattr('units')
     9059            else:
     9060                uname = gen.variables_values(vn)[5]
     9061   
     9062            newattr = basicvardef(newvar, stdname + operkind, lname + ' '+ operkind +\
     9063              ' along ' + dimsoperS, uname)
     9064
     9065            newvar[:] = newvarv
     9066            for idim in range(len(objvar.shape)):
     9067                if dimvals.find('|') != -1:
     9068                    dimn = dimvals.split('|')[idim].split(':')[0]
     9069                else:
     9070                    dimn = dimvals.split(':')[0]
     9071                dimv = '{:d}'.format(len(objnc.dimensions[dimn]))
     9072                if idim == 0:
     9073                    origdimsS = dimn + '(' + dimv + ')'
     9074                else:
     9075                    origdimsS = origdimsS + ' ' + dimn + '(' + dimv + ')'
     9076
     9077            newattr = set_attribute(newvar, 'orig_dimensions', origdimsS)
     9078   
     9079# global attributes
     9080    objnewnc.setncattr('author', 'L. Fita')
     9081    objnewnc.setncattr('institution', 'Laboratire de Meteorologie Dynamique')
     9082    objnewnc.setncattr('university', 'Pierre Marie Curie - Jussieu')
     9083    objnewnc.setncattr('center', 'Centre National de Recherches Scientifiques')
     9084    objnewnc.setncattr('city', 'Paris')
     9085    objnewnc.setncattr('country', 'France')
     9086    objnewnc.setncattr('script', 'nc_var_tools.py')
     9087    objnewnc.setncattr('function', 'file_oper_alongdims')
     9088    objnewnc.setncattr('version', '1.0')
     9089    objnewnc.setncattr('data_file', ncfile)
     9090
     9091    gorigattrs = objnc.ncattrs()
     9092    for attr in gorigattrs:
     9093        attrv = objnc.getncattr(attr)
     9094        atvar = set_attribute(objnewnc, attr, attrv)
     9095
     9096    objnc.close()
     9097
     9098    objnewnc.sync()
     9099    objnewnc.close()
     9100
     9101    print '  ' + fname + ': successful creation of file "' + ofile + '" !!!'
     9102
     9103    return
     9104
     9105# LLUIS
    89699106
    89709107def file_oper_alongdims_old(values, ncfile, varn):
     
    1286112998          [value] = int, a single value
    1286212999          [value] = [beg, end, frq], from a beginning to an end with a given frequency
     13000      returning:
     13001        slicevals: list with the values of the slice
     13002        slicefinaldims: final dimensions of the slice (without monotonic dimensions)
    1286313003    """
    1286413004    fname = 'SliceVarDict'
     
    1286713007
    1286813008    slicevals = []
     13009    slicefinaldims = []
    1286913010    idim = 0
    1287013011    for dim in ovar.dimensions:
     
    1287313014            if type(dictv) == type([1]):
    1287413015                slicevals.append( slice(dictv[0], dictv[1], dictv[2]) )
     13016                slicefinaldims.append(dim)
    1287513017            elif type(dictv) == type(int(1)):
    1287613018                if dictv == -1:
    1287713019                    slicevals.append(slice(0,varshape[idim]))
     13020                    slicefinaldims.append(dim)
    1287813021                else
    1287913022                    slicevals.append(dictv)
    1288013023        else:
    1288113024            slicevals.append(slice(0,varshape[idim]))
     13025            slicefinaldims.append(dim)
     13026
    1288213027        idim = idim + 1
    1288313028
    12884     return slicevals
     13029    return slicevals, slicefinaldims
    1288513030
    1288613031def varDimension(oncf, dname):
Note: See TracChangeset for help on using the changeset viewer.