Changeset 1597 in lmdz_wrf


Ignore:
Timestamp:
Aug 3, 2017, 12:51:19 AM (8 years ago)
Author:
lfita
Message:

Adding:

  • `merge_files': Function to merge variables from two files
Location:
trunk/tools
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/tools/nc_var.py

    r1497 r1597  
    4747## e.g. # nc_var.py -o rm_FillValue -f new_ORCHIDEE_13PFTmap_2010_cmpi6_LUH2v2h.nc -S 0 -v mask
    4848## e.g. # nc_var.py -o curve_section -f /home/lluis/PY/test.nc -S 'gridline,x,y,8.,8.,16.,16.,32' -v all
     49## e.g. # nc_var.py -o merge_files -S 'plev|plev,time|time:merged.nc' -f 'ncobs/AliceSprings/snd_94326_198201-198201.nc,ncobs/AliceSprings/snd_94326_198202-198202.nc' -v 'plev,time'
    4950
    5051from optparse import OptionParser
     
    113114# lonlat_polygon: Function to define a lon/lat region giving the coordinates of the vertexs of a given polygon
    114115# maskvar: Function to mask a variable using another variable to mask it. Only need to share at least 1 dimension with the same size (no need same name)
     116# merge_files: Function to merge variables from two files
    115117# model_characteristics: Function to provide major characterisitcs of a given model output
    116118# mthDYNAMICO_toCF: Function to pass a mthDYNAMICO original file to CF-conventions
     
    182184  'grmattr', 'idims', 'igattrs', 'increaseDimvar', 'isgattrs',                       \
    183185  'isvattrs', 'ivars', 'ivattrs', 'LMDZ_toCF', 'lonlat_polygon', 'maskvar',          \
    184   'model_characteristics',                                                           \
     186  'merge_files', 'model_characteristics',                                            \
    185187  'mthDYNAMICO_toCF', 'ncreplace', 'ncstepdiff', 'netcdf_concatenation',             \
    186188  'netcdf_fold_concatenation',                                                       \
     
    244246# Operations which file name is not a real file
    245247NotCheckingFile = ['DatesFiles', 'compute_opersvarsfiles', 'file_creation',          \
    246   'list_operations',                                                                 \
     248  'list_operations', 'merge_files',                                                  \
    247249  'model_characteristics', 'netcdf_concatenation', 'netcdf_fold_concatenation',      \
    248250  'netcdf_fold_concatenation_HMT']
     
    389391elif oper == 'maskvar':
    390392    ncvar.maskvar(opts.values, opts.ncfile, opts.varname)
     393elif oper == 'merge_files':
     394    ncvar.merge_files(opts.values, opts.ncfile, opts.varname)
    391395elif oper == 'model_characteristics':
    392396    ncvar.model_characteristics(opts.values, opts.ncfile)
  • trunk/tools/nc_var_tools.py

    r1591 r1597  
    9292# lonlat_polygon: Function to define a lon/lat region giving the coordinates of the vertexs of a given polygon
    9393# maskvar: 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
     94# merge_files: Function to merge variables from two files
    9495# ModelChar: Class object to determine major characterisitcs of a given model output
    9596# model_characteristics: Functino to provide major characterisitcs of a given model output
     
    2016520166#lonlat_polygon('/home/lluis/PY/star.dat','/home/lluis/PY/wrfout_d01_1995-01-01_00:00:00', 'XLONG,XLAT')
    2016620167
     20168def merge_files(values, ncfiles, variable):
     20169    """ Function to merge variables from two files
     20170      values= [dimvar]:[mergedfilen]
     20171        [dimvarn]: ',' list of couples [dimvarn]|[dimn] of the name of dimension and the variable with its values
     20172          related to the variables to merge
     20173        [mergedfilen]: name of the merged file
     20174      ncfile= ',' list of file names to merge
     20175      variable= ',' list of names of variables to merge ('all' for all variables)
     20176    """
     20177    fname = 'merge_files'
     20178
     20179    if values == 'h':
     20180        print fname + '_____________________________________________________________'
     20181        print merge_files.__doc__
     20182        quit()
     20183
     20184    expectargs = '[dimvar]:[mergedfilen]'
     20185    gen.check_arguments(fname, values, expectargs, ':')
     20186
     20187    dimvarns = gen.str_list(values.split(':')[0], ',')
     20188    mergedfilen = values.split(':')[1]
     20189
     20190    filen1 = ncfiles.split(',')[0]
     20191    filen2 = ncfiles.split(',')[1]
     20192
     20193    if not os.path.isfile(filen1):
     20194        print errormsg
     20195        print '  ' + fname + ": file named '" + filen1 + "' does not exist !!"
     20196        quit(-1)
     20197
     20198    if not os.path.isfile(filen2):
     20199        print errormsg
     20200        print '  ' + fname + ": file named '" + filen2 + "' does not exist !!"
     20201        quit(-1)
     20202
     20203    onc1 = NetCDFFile(filen1, 'r')
     20204    onc2 = NetCDFFile(filen2, 'r')
     20205
     20206    dimn1 = onc1.dimensions
     20207    dimn2 = onc2.dimensions
     20208    varn1 = onc1.variables.keys()
     20209    varn2 = onc2.variables.keys()
     20210
     20211    # Getting dimension variables
     20212    dimvar = {}
     20213   
     20214    for dimvarn in dimvarns:
     20215        dimn = dimvarn.split('|')[0]
     20216        dvn = dimvarn.split('|')[1]
     20217
     20218        if not gen.searchInlist(dimn1, dimn):
     20219            print errormsg
     20220            print '  ' +fname+ ": file '" + filen1 + "' does not have dimension: '"+ \
     20221              dimn
     20222            print '    available ones:', dimn1
     20223            quit(-1)
     20224
     20225        if not gen.searchInlist(dimn2, dimn):
     20226            print errormsg
     20227            print '  ' +fname+ ": file '" + filen2 + "' does not have dimension: '"+ \
     20228              dimn
     20229            print '    available ones:', dimn2
     20230            quit(-1)
     20231
     20232        if not gen.searchInlist(varn1, dvn):
     20233            print errormsg
     20234            print '  ' +fname+ ": file '" + filen1 + "' does not have variable: '" + \
     20235              dimn
     20236            print '    available ones:', varn1
     20237            quit(-1)
     20238
     20239        if not gen.searchInlist(varn2, dvn):
     20240            print errormsg
     20241            print '  ' +fname+ ": file '" + filen2 + "' does not have variable: '" + \
     20242              dimn
     20243            print '    available ones:', varn2
     20244            quit(-1)
     20245
     20246        dimvar[dimn] = dvn
     20247
     20248    if variable == 'all':
     20249        # concident variables
     20250        setvarn1 = set(varn1)
     20251        setvarn2 = set(varn2)
     20252        coincidentvarn = list(setvarn1.intersection(setvarn2))
     20253    else:
     20254        coincidentvarn = gen.str_list(variable, ',')
     20255
     20256    # Creation of merged file
     20257    onewnc = NetCDFFile(mergedfilen, 'w')
     20258
     20259    # Looping on coincident variables
     20260    for varn in coincidentvarn:
     20261        print '  ' + fname + ": merging on variable '" + varn + "' ...."
     20262        ovar1 = onc1.variables[varn]
     20263        ovar2 = onc2.variables[varn]
     20264
     20265        dimvn1 = ovar1.dimensions
     20266        dimvn2 = ovar2.dimensions
     20267
     20268        # Assuming same name of dimensions. Too busy to generalize it... ;)
     20269        NOcoindimns = list(set(dimvn1).symmetric_difference(set(dimvn2)))
     20270        if len(NOcoindimns) != 0:
     20271            print errormsg
     20272            print '  ' + fname + ": variable to merge '" + varn + "' have " +        \
     20273              "different dimensions in files!!"
     20274            print "    file '" + filen1 + "' dimensions: ", dimvn1
     20275            print "    file '" + filen2 + "' dimensions: ", dimvn2
     20276            quit(-1)
     20277
     20278        # Getting values of the dimensions
     20279        dimvals = {}
     20280        for dimn in dimvn1:
     20281            odvar1 = onc1.variables[dimvar[dimn]]
     20282            odvar2 = onc2.variables[dimvar[dimn]]
     20283
     20284            vdd1 = odvar1[:]
     20285            vdd2 = odvar2[:]
     20286            if len(vdd1.shape) != 1:
     20287                print errormsg
     20288                print '  ' + fname + ": dimension-variable '" + dimvar[dimn] +       \
     20289                  "' is not 1D!!"
     20290                print "    shape", vdd1.shape
     20291                quit(-1)
     20292 
     20293            lvdd1 = list(vdd1)
     20294            lvdd2 = list(vdd2)
     20295
     20296            # Looking for non coincident values
     20297            notvdd = list(set(lvdd2).difference(set(lvdd1)))
     20298            Lnotvdd = len(notvdd)
     20299
     20300            dimv = np.zeros((len(vdd1)+Lnotvdd), dtype=vdd1.dtype)
     20301            if Lnotvdd == 0:
     20302                newdimv = np.array(lvdd1)
     20303            else:
     20304                # Getting the right order and sense
     20305                notvdd.sort()
     20306                if lvdd1[1] < lvdd1[0]:
     20307                    notvdd.reverse()
     20308
     20309                # Getting dimension values starting with filen1 as reference
     20310                print infmsg
     20311                print '    ' + fname + ": dimension '" + dimvar[dimn] + "' with ",   \
     20312                  Lnotvdd, "different values !!"
     20313                print '    size from file1:', len(lvdd1), 'file2:', len(lvdd2)
     20314
     20315                # Filling dimension
     20316                newdimv = np.array(gen.InsertVal_list_sign(lvdd1, notvdd))
     20317
     20318            # Creation of dimension
     20319            Lnewdim = len(newdimv)
     20320            if not gen.searchInlist(onewnc.dimensions, dimn):
     20321                print infmsg
     20322                print '    ' + fname + ": creation of dimension '" + dimn+ "' (" +   \
     20323                  str(Lnewdim) + ") !!"
     20324
     20325                if onc1.dimensions[dimn].isunlimited():
     20326                    newdim = onewnc.createDimension(dimn, None)
     20327                else:
     20328                    newdim = onewnc.createDimension(dimn, Lnewdim)
     20329
     20330            # Creation of variable-dimension
     20331            if not onewnc.variables.has_key(dimvar[dimn]):
     20332                print infmsg
     20333                print '    ' + fname + ": creation of variable '" + dimvar[dimn] +   \
     20334                  "'", newdimv.shape, "!!"
     20335                if gen.searchInlist(odvar1.ncattrs(), '_FillValue'):
     20336                    newvar = onewnc.createVariable(dimvar[dimn], nctype(vdd1.dtype), \
     20337                      (dimn), fill_value=ovar1.getncattr('_FillValue'))
     20338                else:
     20339                    newvar = onewnc.createVariable(dimvar[dimn], nctype(vdd1.dtype), \
     20340                      (dimn))
     20341                newvar[:] = newdimv[:]
     20342                for attrn in odvar1.ncattrs():
     20343                    attrv = odvar1.getncattr(attrn)
     20344                    if attrn != '_FillValue': newattr = set_attribute(newvar, attrn, \
     20345                       attrv)
     20346
     20347            onewnc.sync()
     20348
     20349        # Looking for the values of the variables and filling netCDF file
     20350        vvar1 = ovar1[:]
     20351        vvar2 = ovar2[:]
     20352        Lv1 = len(vvar1)
     20353        Lv2 = len(vvar2)
     20354
     20355        v1dim = ovar1.dimensions[0]
     20356        odimv = onewnc.variables[dimvar[v1dim]]
     20357        dimv = odimv[:]
     20358        Lnewdim = len(dimv)
     20359       
     20360        newvarvals = np.zeros((Lnewdim), vdd1.dtype)
     20361        iv1 = 0
     20362        iv2 = 0
     20363        for iv in range(Lnewdim):
     20364            if dimv[iv] == vdd1[iv1]:
     20365                newvarvals[iv] = vvar1[iv1]
     20366                iv1 = np.min([iv1 + 1, Lv1-1])
     20367            else:
     20368                newvarvals[iv] = vvar2[iv2]
     20369                iv2 = np.min([iv2 + 1, Lv2-1])
     20370
     20371        # Creation of variable
     20372        if not onewnc.variables.has_key(varn):
     20373            print infmsg
     20374            print '    '+fname+": creation of variable '" +varn+  "' (" +dimn+ ") !!"
     20375            if gen.searchInlist(ovar1.ncattrs(), '_FillValue'):
     20376                newvar = onewnc.createVariable(dimvar[dimn], nctype(vdd1.dtype),     \
     20377                  (dimn), fill_value=ovar1.getncattr('_FillValue'))
     20378            else:
     20379                newvar = onewnc.createVariable(dimvar[dimn], nctype(vdd1.dtype),     \
     20380                  (dimn))
     20381        newvar[:] = newdimv
     20382        for attrn in ovar1.ncattrs():
     20383            attrv = ovar1.getncattr(attrn)
     20384            if attrn != '_FillValue': newattr = set_attribute(newvar, attrn, attrv)
     20385
     20386        onewnc.sync()
     20387
     20388    # Global attributes
     20389    gattrs = onc1.ncattrs()
     20390    for attrn in gattrs:
     20391        attrv = onc1.getncattr(attrn)
     20392        newattr = set_attribute(onewnc, attrn, attrv)
     20393    onewnc.sync()
     20394
     20395    # Adding PyNCplot
     20396    add_global_PyNCplot(onewnc, main, fname, '0.1')
     20397    onewnc.sync()
     20398
     20399    onewnc.close()
     20400    print fname + ": Variables succesfuly  merged in file '" + mergedfilen + "' !!"
     20401    return
    2016720402
    2016820403#quit()
Note: See TracChangeset for help on using the changeset viewer.