Changeset 1233 in lmdz_wrf for trunk


Ignore:
Timestamp:
Oct 26, 2016, 3:37:25 PM (9 years ago)
Author:
lfita
Message:

Improving `compute_opersvarsfiles' with more operations and options and clarity

Location:
trunk/tools
Files:
3 edited

Legend:

Unmodified
Added
Removed
  • trunk/tools/generic_tools.py

    r1232 r1233  
    98929892
    98939893    matAshape = list(matA.shape)
    9894     print fname + '; Lluis matAshape:', matAshape
    98959894
    98969895    # From: https://en.wikipedia.org/wiki/Finite_difference_coefficient
     
    1029310292
    1029410293    return newmat, Lopn[opn]
    10295 print matoperations('centerderiv,1,8,0',np.arange(81.).reshape(9,9))
    10296 print matoperations('forwrdderiv,2,2,0',np.arange(81.).reshape(9,9))
    10297 print matoperations('upthres,4,3',np.arange(81).reshape(9,9))
    10298 print matoperations('lowthres@oper,37,divc,7',np.arange(81).reshape(9,9))
    1029910294
    1030010295#quit()
  • trunk/tools/nc_var.py

    r1219 r1233  
    3131## e.g. # nc_var.py -o reproject -f analysis/LMDZ/AR40/hurs_histins.nc -S 'lon,lat,analysis/WRF/current/hurs_wrfout.nc,lon,lat,npp,time@time' -v hurs
    3232## e.g. # nc_var.py -o field_stats_dim -f /home/lluis/PY/wrfout_d01_2001-11-11_00:00:00 -S 'full,None,None,west_east,XLONG,False' -v 'T2'
     33## e.g. # nc_var.py -o compute_opersvarsfiles -S 'west_east|XLONG|-1;south_north|XLAT|-1;Time|Times|3@add|wrfout_d01_2001-11-11_00:00:00|T2%west_east|XLONG|-1;south_north|XLAT|-1;Time|Times|3@subc,273.15|wrfout_d01_2001-11-11_00:00:00|None' -v 'tempC,air!temperature,C'
    3334
    3435from optparse import OptionParser
  • trunk/tools/nc_var_tools.py

    r1219 r1233  
    68826882#compute_deaccum('time', 'control/sellonlatbox_PRECIP_dayaccum.nc', 'PRECIP')
    68836883
    6884 def compute_opersvarsfiles(values, varname):
     6884def compute_opersvarsfiles(values, varinfo):
    68856885    """ Function to compute opersvarfiles: operation of variables from different files
    68866886      (OPER1.FILE1_VAR1 OPER2.FILE2_VAR2), operations are going to be secuentially
    68876887      made
    6888         values= [dimvons]@[operfilevars]
    6889           [dimnvons]: [dimo1]|[dimo2]|[...|[dimoN]] '|' seaprated list of names with the
    6890             variables which contain the values of the dimensions of the compute variable
    6891           operfilevars: [oper1]|[file1]|[varN],[...,[operK]|[fileM]|[varN]] ',' separated list of
    6892              triplets of [operation], [file], [variable name to use]
    6893            * [oper]: operations: add,sub,mul,div,pot
    6894         varname= name to the final variable
     6888        values= '%' separated list of dimension ranges and file,operation,variable to compute
     6889          [dimranges1]@[operfile1var]%[dimranges2]@[operfile2var]%[...[dimrangesM]@[operfileMvar]]
     6890          dimranges: ';' separated list of dimension, dimension-variable names and their ranges ('|' separated)
     6891            [dim1]|[dimv1]|[range];[dim2]|[dimv2]|[range];[...|[dimN]|[dimvN]|[range]]
     6892            with [range] as:
     6893                       -1, all the values
     6894                       -9, last values
     6895                      int, a single value
     6896            [beg,end,frq], from a beginning to an end with a given frequency
     6897          operfilevar: [oper]|[file]|[var] '|' separated list of triplets of [operation], [file], [variable name to use]
     6898           * [oper]: operations (being [prevalues] the values computed until the operation)
     6899             'add': adding [var] ([prevalues] + [var])
     6900             'addc',[modval1]: add [modval1] to [prevalues]
     6901             'centerderiv',[N],[ord],[dim]: un-scaled center [N]-derivative of order [ord] along dimension [dim] of [var]
     6902             'div': dividing by [var] ([prevalues] / [var])
     6903             'divc',[modval1]: [prevalues] divide by [modval1]
     6904             'forwrdderiv',[N],[ord],[dim]: un-scaled forward [N]-derivative of order [ord] along dimension [dim] of [var]
     6905             'inv': inverting [prevalues] (1/[prevalues])
     6906             'lowthres',[modval1],[modval2]: if [prevalues] < [modval1]; prevalues = [modval2]
     6907             'lowthres@oper',[modval1],[oper],[modval2]: if [prevalues] < [modval1]; prevalues = [oper] (operation as [modval2])
     6908             'mul': multiplying by [var] ([prevvalues] * [var])
     6909             'mulc',[modval1]: [prevalues] multiplied by [modval1]
     6910             'pot': powering with [var] ([prevalues] ** [var])
     6911             'potc',[modval1]: [prevalues] ** [modval1]
     6912             'sub': substracting [var] ([prevalues] - [var])
     6913             'subc',[modval1]: remove [modval1] of [prevalues]
     6914             'upthres',[modval1],[modval2]: if [prevalues] > [modval1]; prevalues = [modval2]
     6915             'upthres@oper',[modval1],[oper],[modval2]: if [prevalues] > [modval1]; prevalues = [oper] (operation with [modval2])
     6916           * [file]: name of the file
     6917           * [var]: variable to use ('None' for the case with constant operations: 'addc', 'divc', 'inv', 'lowthres',
     6918              'lowthres@oper', 'mulc', 'potc', 'subc', 'upthres', 'upthres@oper'
     6919        varinfo= [varname],[Lvarname],[varunits]
     6920          varname: name of the final variable
     6921          Lvarname: long name of the final variable ('!' for spaces)
     6922          varunits: units of the final variable ('!' for spaces)
    68956923    """
    6896 #    import numpy.ma as ma
     6924    import numpy.ma as ma
    68976925    fname='compute_opersvarsfiles'
    68986926
     
    69026930        quit()
    69036931
    6904     dimovars = values.split('@')[0].split('|')
    6905     filevars = values.split('@')[1].split(',')
     6932    # List of operations which need to be started with a matrix of zeros
     6933    opinizero = ['add', 'sub']
     6934    # List of operations which need to be started with a matrix of ones
     6935    opinione = ['mul', 'div', 'pot']
     6936
     6937    varname = varinfo.split(',')[0]
     6938    Lvarname = varinfo.split(',')[1].replace('!',' ')
     6939    varunits = varinfo.split(',')[2].replace('!',' ')
    69066940
    69076941    ofile = 'opersvarsfiles_' + varname + '.nc'
    69086942
    6909     Nfilevars = len(filevars)
    6910 
    6911     operation = 'operation: '
     6943    fileopers = values.split('%')
     6944
     6945    # Getting range,files,operations, ...
     6946    Nfileopers = len(fileopers)
     6947    filens = []
     6948    ranges = []
     6949    opers = []
     6950    varns = []
     6951    for fileoper in fileopers:
     6952        ranges.append(fileoper.split('@')[0])
     6953        fnop = fileoper.split('@')[1]
     6954        opers.append(fnop.split('|')[0])
     6955        filens.append(fnop.split('|')[1])
     6956        varns.append(fnop.split('|')[2])
     6957
     6958    print '  ' + fname + 'Files/Operations to perform _______'
     6959    for ifop in range(Nfileopers):
     6960        print '    ' + filens[ifop] + ' range: ' + ranges[ifop] + ' operation: ' +   \
     6961          opers[ifop] + ' variable: ' + varns[ifop]
     6962
    69126963    newunits = '-'
    69136964    opervars = []
    6914 
    6915     for ifv in range(Nfilevars):
    6916         opern = filevars[ifv].split('|')[0]
    6917         filen = filevars[ifv].split('|')[1]
    6918         varn = filevars[ifv].split('|')[2]
     6965    # Dictionary with the sizes of the dimensions of prevalues
     6966    Dds = {}
     6967    # Dictionary with the values of the dimension-variables of the dimensions of `prevalues'
     6968    Ddv = {}
     6969    # Dictionary with the dimensions of the dimension-variables of the dimensions of `prevalues'
     6970    Dddv = {}
     6971    # Dictionary with the type of the dimension-variables of the dimensions of `prevalues'
     6972    Dtdv = {}
     6973    # Dictionary with the attributes dictionay of the dimension-variables of the dimensions of `prevalues'
     6974    Dadv = {}
     6975
     6976    prevalues = None
     6977    for ifv in range(Nfileopers):
     6978        opern = opers[ifv]
     6979        filen = filens[ifv]
     6980        varn = varns[ifv]
     6981        rng = ranges[ifv].split(';')
     6982
    69196983        opervars.append(varn)
    69206984
     
    69266990        objnc = NetCDFFile(filen, 'r')
    69276991
    6928         if not objnc.variables.has_key(varn):
    6929             print errormsg
    6930             print '  ' + fname + ': netCDF file "' + filen +                         \
    6931               '" does not have variable "' + varn + '" !!!!'
    6932             quit(-1)
    6933 
    6934         varobj = objnc.variables[varn]
    6935         varvals = varobj[:]
    6936 
    6937 # Creation of the operated variable
    6938         if ifv == 0:
    6939             vardims = varobj.dimensions
    6940             vartype = varobj.dtype
    6941 
    6942             if opern == 'add' or opern == 'sub':
    6943                 newvarv = np.zeros(tuple(varobj.shape), dtype=np.float)
    6944             elif opern == 'mul' or opern == 'div' or opern == 'pot':
    6945                 newvarv = np.ones(tuple(varobj.shape), dtype=np.float)
     6992        # Operation with a variable
     6993        if varn != 'None' or prevalues is None:
     6994            if not objnc.variables.has_key(varn):
     6995                print errormsg
     6996                print '  ' + fname + ': netCDF file "' + filen +                     \
     6997                  '" does not have variable "' + varn + '" !!!!'
     6998                quit(-1)
     6999
     7000            varobj = objnc.variables[varn]
     7001            # Slice values
     7002            dictslice = {}
     7003
     7004            Ddimvs = []
     7005            for rg in rng:
     7006                dimn = rg.split('|')[0]
     7007                dimv = rg.split('|')[1]
     7008                dimr = rg.split('|')[2]
     7009                if dimr.find(',') != -1:
     7010                    dictslice[dimn] = list(np.array(dimr.split(','), dtype=int))
     7011                else:
     7012                    dictslice[dimn] = int(dimr)
     7013                # Dimension-variable
     7014                if not objnc.variables.has_key(dimv):
     7015                    print errormsg
     7016                    print '  ' + fname + ": file '" + filen + "' does not have " +   \
     7017                      "dimension-variable '" + dimv + "' !!"
     7018                    quit(-1)
     7019                # Keeping the dimensions
     7020                Ddimvs.append([dimn, dimv, dimr])
     7021
     7022            # Getting values of the variable
     7023            varslice, dimvarvals = SliceVarDict(varobj, dictslice)
     7024            varvals = varobj[tuple(varslice)]
     7025
     7026            # Getting values of the correspondant dimensions of the variable
     7027            for iddd in range(len(Ddimvs)):
     7028                DD = Ddimvs[iddd]
     7029                dimn = DD[0]
     7030                dimv = DD[1]
     7031                dimr = DD[2]
     7032                if dimv != 'WRFt':
     7033                    odimv = objnc.variables[dimv]
     7034                    varslice, Dddv[dimn] = SliceVarDict(odimv, dictslice)
     7035                    Ddv[dimn] = odimv[tuple(varslice)]
     7036                    Dtdv[dimn] = odimv.dtype
     7037                    dicattrs = {}
     7038                    for attrn in odimv.ncattrs():
     7039                        attrval = odimv.getncattr(attrn)
     7040                        dicattrs[attrn] = attrval
     7041                    Dadv[dimn] = dicattrs
     7042                else:
     7043                    datesv = []
     7044                    wrft = objnc.variables['Times']
     7045                    slicewrft, dwrfd = SliceVarDict(wrft, dictslice)
     7046                    fdates = wrft[tuple(slicewrft)]
     7047                    refdate = '19491201000000'
     7048                    tunitsval = 'minutes'
     7049                    yrref=refdate[0:4]
     7050                    monref=refdate[4:6]
     7051                    dayref=refdate[6:8]
     7052                    horref=refdate[8:10]
     7053                    minref=refdate[10:12]
     7054                    secref=refdate[12:14]
     7055
     7056                    refdateS = yrref + '-' + monref + '-' + dayref + ' ' + horref +  \
     7057                      ':' + minref + ':' + secref
     7058
     7059                    dt = fdates.shape[0]
     7060                    cftimes = np.zeros((dt), dtype=np.float)
     7061                    for it in range(dt):
     7062                        wrfdates = gen.datetimeStr_conversion(timewrfv[it,:],        \
     7063                          'WRFdatetime', 'matYmdHMS')
     7064                        cftimes[it] = gen.realdatetime1_CFcompilant(wrfdates,        \
     7065                          refdate, tunitsval)
     7066                    tunits = tunitsval + ' since ' + refdateS
     7067                    Dddv[dimn] = 'Time'
     7068                    Ddv[dimn] = cftimes
     7069                    Dtdv[dimn] = np.float
     7070                    Dadv[dimn] = {'stadard_name': 'time', 'long_name': 'time',       \
     7071                      'units': tunitsval + ' since ' + refdateS}
     7072
     7073            # Getting sizes of the dimensions
     7074            for dvn in dimvarvals:
     7075                dimobj = objnc.dimensions[dvn]
     7076                if dimobj.isunlimited():
     7077                    Dds[dvn] = None
     7078                else:
     7079                    Dds[dvn] = len(dimobj)
     7080
     7081            # operation
     7082            if prevalues is None:
     7083                # Creation of an empty variable to start with
     7084                if gen.searchInlist(opinizero,opern):
     7085                    inimat = np.zeros(varvals.shape, dtype=varobj.dtype)
     7086                elif gen.searchInlist(opinione,opern):
     7087                    inimat = np.ones(varvals.shape, dtype=varobj.dtype)
     7088
     7089                prevalues, operS = gen.matoperations(opern, varvals, inimat)
    69467090            else:
    6947                 print errormsg
    6948                 print '  ' + fname + ': operation "' + opern + '" is not ready !!!!'
    6949                 quit(-1)
    6950 
    6951         if gen.searchInlist(varobj.ncattrs(), '_FillValue'):
    6952             NOvalue = varobj.getncattr('_FillValue')
    6953             print warnmsg
    6954             print '    ' + fname + ': variable with a missing value:',NOvalue
    6955 
    6956         if opern == 'add':
    6957             if gen.searchInlist(varobj.ncattrs(), '_FillValue'):
    6958                 if type(varvals) != type(np.arange(1)):
    6959                     print type(varvals), type(np.arange(1))
    6960                     prevals = varvals.filled(0.)
    6961                 else:
    6962                     prevals = varvals
    6963                 newvarv = newvarv + prevals
    6964             else:
    6965                 newvarv = newvarv + varvals
    6966             operation = operation + ' +' + varn
    6967             newunits = gen.variables_values(varname)[5]
    6968         elif opern == 'sub':
    6969             if gen.searchInlist(varobj.ncattrs(), '_FillValue'):
    6970                 if type(varvals) != type(np.arange(1)):
    6971                     prevals = varvals.filled(0.)
    6972                 else:
    6973                     prevals = varvals
    6974                 newvarv = newvarv - prevals
    6975             else:
    6976                 newvarv = newvarv - varvals
    6977             operation = operation + ' -' + varn
    6978             newunits = gen.variables_values(varname)[5]
    6979         elif opern == 'mul':
    6980             if gen.searchInlist(varobj.ncattrs(), '_FillValue'):
    6981                 prevals = varvals.filled(1.)
    6982                 newvarv = newvarv * prevals
    6983             else:
    6984                 newvarv = newvarv * varvals
    6985             operation = operation + ' *' + varn
    6986             newunits = gen.variables_values(varname)[5]
    6987         elif opern == 'div':
    6988             if gen.searchInlist(varobj.ncattrs(), '_FillValue'):
    6989                 prevals = varvals.filled(1.)
    6990                 newvarv = newvarv / prevals
    6991             else:
    6992                 newvarv = newvarv / varvals
    6993             operation = operation + ' /' + varn
    6994             newunits = gen.variables_values(varname)[5]
    6995         elif opern == 'pot':
    6996             if gen.searchInlist(varobj.ncattrs(), '_FillValue'):
    6997                 prevals = varvals.filled(1.)
    6998                 newvarv = newvarv ** prevals
    6999             else:
    7000                 newvarv = newvarv ** varvals
    7001             operation = operation + ' **' + varn
    7002             newunits = gen.variables_values(varname)[5]
     7091                prevalues, operS = gen.matoperations(opern, prevalues, varvals)
     7092            operS = ' ' + operS + '[' + varn + ']'
     7093        else:
     7094            prevalues, operS = gen.matoperations(opern, prevalues)
     7095            operS = ' ' + operS
     7096
     7097        if opern == opers[0]:
     7098            operationS = operS
     7099        else:
     7100            operationS = operationS + operS
     7101
     7102        objnc.close()
    70037103
    70047104# Creation of the new file
    70057105    objofile = NetCDFFile(ofile, 'w')
    70067106
    7007 # Dimensions
    7008     for dimn in vardims:
    7009         dimobj = objnc.dimensions[dimn]
    7010         if dimobj.isunlimited():
    7011             print '      ' + fname + ': Unlimited dimension '
    7012             dimsize = None
    7013         else:
    7014             dimsize = len(dimobj)
    7015 
    7016         newdim = objofile.createDimension(dimn, dimsize)
    7017 
    7018 # Variables for dimensions
    7019     for varn in dimovars:
    7020 
    7021         if not gen.searchInlist(list(objnc.variables.keys()), varn):
    7022             print warnmsg
    7023             print '  ' + fname + " file does not have dimension variable '" + varn + \
    7024               "' skipping it !!"
    7025         else:
    7026             dvarobj = objnc.variables[varn]
    7027             # Adding that dimensions of the variable which might not be in the output
    7028             for vdn in dvarobj.dimensions:
    7029                 if not objofile.dimensions.has_key(vdn):
    7030                     addvdno = objnc.dimensions[vdn]
    7031                     if addvdno.isunlimited():
    7032                         objofile.createDimension(vdn, None)
    7033                     else:
    7034                         objofile.createDimension(vdn, len(addvdno))
    7035             # Adding new variable to output
    7036             newvar = objofile.createVariable(varn, dvarobj.dtype, dvarobj.dimensions)
    7037             for attrn in  dvarobj.ncattrs():
    7038                 attrval = dvarobj.getncattr(attrn)
    7039                 newattr = newvar.setncattr(attrn, attrval)
    7040             newvar[:] = dvarobj[:]
    7041 
    7042     newvar = objofile.createVariable(varname, vartype, vardims)
    7043     newvar[:] = newvarv
    7044     varattrs = varobj.ncattrs()
    7045     if gen.searchInlist(varattrs,'long_name'):
    7046         operation = varobj.getncattr('long_name') + '; ' + operation
    7047 
    7048     newattr = basicvardef(newvar, varname, operation, newunits)
    7049     stdattrs = ['standard_name', 'long_name', 'units']
    7050     for attrn in varattrs:
    7051         if not gen.searchInlist(stdattrs, attrn) and attrn != '_FillValue':
    7052             attrv = varobj.getncattr(attrn)
    7053             newattr = set_attribute(newvar,attrn,attrv)
     7107    # Dimensions
     7108    for dimn in dimvarvals:
     7109        newdim = objofile.createDimension(dimn, Dds[dimn])
     7110    objofile.sync()
     7111
     7112    # Variables for dimensions
     7113    for dvn in dimvarvals:
     7114        for idn in Dddv[dvn]:
     7115            if not objofile.dimensions.has_key(idn): objofile.createDimension(idn,   \
     7116              Dds[idn])
     7117        newvar = objofile.createVariable(dvn, Dtdv[dvn], tuple(Dddv[dvn]))
     7118        dictatr = Dadv[dvn]
     7119        for attrn in dictatr.keys():
     7120            newattr = newvar.setncattr(attrn, dictatr[attrn])
     7121        newvar[:] = Ddv[dvn]
     7122    objofile.sync()
     7123
     7124    # Computed variable
     7125    vartype = prevalues.dtype
     7126    if type(prevalues) == type(ma.asarray([1,1])):
     7127        maskvalue = prevalues.fill_value
     7128        newvar = objofile.createVariable(varname, nctype(vartype), dimvarvals,       \
     7129          fill_valu=maskvalue)
     7130    else:
     7131        newvar = objofile.createVariable(varname, nctype(vartype), dimvarvals)
     7132    newvar[:] = prevalues[:]
     7133
     7134    newattr = basicvardef(newvar, varname, Lvarname, varunits)
    70547135
    70557136# Global attributes
    7056     for attrn in objnc.ncattrs():
    7057         attrval = objnc.getncattr(attrn)
    7058         newattr = objofile.setncattr(attrn, attrval)
    7059    
    7060     objnc.close()
     7137    objofile.setncattr('script',  fname)
     7138    objofile.setncattr('version',  '1.0')
     7139    objofile.setncattr('author',  'L. Fita')
     7140    newattr = set_attributek(objofile, 'institution', unicode('Laboratoire de M' +   \
     7141      unichr(233) + 't' + unichr(233) + 'orologie Dynamique'), 'U')
     7142    objofile.setncattr('university',  'Pierre et Marie Curie')
     7143    objofile.setncattr('country',  'France')
     7144    newattr = set_attributek(objofile, 'used_operation',  operationS, 'S')
     7145    newattr = set_attributek(objofile, 'used_files',  ', '.join(filens) ,'S')
     7146    newattr = set_attributek(objofile, 'used_ranges',  ', '.join(ranges) ,'S')
    70617147
    70627148    objofile.sync()
Note: See TracChangeset for help on using the changeset viewer.