Changeset 418 in lmdz_wrf


Ignore:
Timestamp:
May 19, 2015, 6:23:51 PM (10 years ago)
Author:
lfita
Message:

Adding 'selvar' to select a list of variables from an existing file.
New functions:

'add_dims': add dimensions from a given netCDF object to another one
'add_vars': add variables from a given netCDF object to another one
'add_globattrs': add global attributes from a given netCDF object to another one

Location:
trunk/tools
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/tools/nc_var.py

    r409 r418  
    11#!/usr/bin/python
    2 ## g.e. ccrc468-17 # ./nc_var.py -v time -f 123/CCRC_NARCliM_Sydney_All_1990-1999_pr10max.nc -o out -S 1:-1
    3 ## g.e. ccrc468-17 # ./nc_var.py -v prac -f xyz/CCRC_NARCliM_Sydney_DAM_1990-1999_prac.nc -o mname -S pluja
    4 ## g.e. ccrc468-17 # ./nc_var.py -v lluis -f CCRC_NARCliM_Sydney_MOM_1990-1999_prac.nc -o addref -S 'prac:standard_name@lluis_variable:long_name@test variable lluis:units@m s-1:0.'
    5 ## g.e. ccrc468-17 # ./nc_var.py -v lluis66 -f ~/UNSW-CCRC-WRF/tools/python/CCRC_NARCliM_Sydney_MOM_1990-1999_prac.nc -o addattr -S 'comment|Lluis Fita-123456'
    6 ## g.e. ccrc468-17 # ./nc_var.py -v lluis66 -f ~/UNSW-CCRC-WRF/tools/python/CCRC_NARCliM_Sydney_MOM_1990-1999_prac.nc -o rmvattr -S 'comment'
    7 ## g.e. acuna # ./nc_var.py -f /d4/lflmd/etudes/WRF_LMDZ/WaquaL/WRF/control/wrfout/wrfout_d01_1979-12-01_00:00:00 -o checkallvars -S 'DateStrLen,Time,soil_layers_stag,bottom_top_stag,bottom_top,west_east_stag,west_east,south_north,south_north_stag:-3,1,2,2,2,-2,-2,-2,-2'
    8 ## g.e. foudre # nc_var.py -f ~/etudes/WRF_LMDZ/tests/wrf_input/AR40.0/wrfout_d01_1979-01-01_00\:00\:00 -o checkallvars -S 'bottom_top_plus1,num_orchidee_soil_levels,lmdz_ksoil_types,DIM0009,DateStrLen,Time,soil_layers_stag,bottom_top_stag,bottom_top,west_east_stag,west_east,south_north,south_north_stag:2,0,0,1,-3,1,2,2,2,-2,-2,-2,-2'
    9 ## g.e. # nc_var.py -o field_stats -f ~/etudes/domains/Polynesie/geo_em.d03.nc -S full -v HGT_M
    10 ## g.e. # nc_var.py -o filter_2dim -S '80,y,x,lon,lat' -f 'tahiti_5m_ll.grd' -v 'z'
     2## e.g. ccrc468-17 # ./nc_var.py -v time -f 123/CCRC_NARCliM_Sydney_All_1990-1999_pr10max.nc -o out -S 1:-1
     3## e.g. ccrc468-17 # ./nc_var.py -v prac -f xyz/CCRC_NARCliM_Sydney_DAM_1990-1999_prac.nc -o mname -S pluja
     4## e.g. ccrc468-17 # ./nc_var.py -v lluis -f CCRC_NARCliM_Sydney_MOM_1990-1999_prac.nc -o addref -S 'prac:standard_name@lluis_variable:long_name@test variable lluis:units@m s-1:0.'
     5## e.g. ccrc468-17 # ./nc_var.py -v lluis66 -f ~/UNSW-CCRC-WRF/tools/python/CCRC_NARCliM_Sydney_MOM_1990-1999_prac.nc -o addattr -S 'comment|Lluis Fita-123456'
     6## e.g. ccrc468-17 # ./nc_var.py -v lluis66 -f ~/UNSW-CCRC-WRF/tools/python/CCRC_NARCliM_Sydney_MOM_1990-1999_prac.nc -o rmvattr -S 'comment'
     7## e.g. acuna # ./nc_var.py -f /d4/lflmd/etudes/WRF_LMDZ/WaquaL/WRF/control/wrfout/wrfout_d01_1979-12-01_00:00:00 -o checkallvars -S 'DateStrLen,Time,soil_layers_stag,bottom_top_stag,bottom_top,west_east_stag,west_east,south_north,south_north_stag:-3,1,2,2,2,-2,-2,-2,-2'
     8## e.g. foudre # nc_var.py -f ~/etudes/WRF_LMDZ/tests/wrf_input/AR40.0/wrfout_d01_1979-01-01_00\:00\:00 -o checkallvars -S 'bottom_top_plus1,num_orchidee_soil_levels,lmdz_ksoil_types,DIM0009,DateStrLen,Time,soil_layers_stag,bottom_top_stag,bottom_top,west_east_stag,west_east,south_north,south_north_stag:2,0,0,1,-3,1,2,2,2,-2,-2,-2,-2'
     9## e.g. # nc_var.py -o field_stats -f ~/etudes/domains/Polynesie/geo_em.d03.nc -S full -v HGT_M
     10## e.g. # nc_var.py -o filter_2dim -S '80,y,x,lon,lat' -f 'tahiti_5m_ll.grd' -v 'z'
     11## e.g. # nc_var.py -o selvar -f /home/lluis/PY/met_em.d01.1979-01-01_00:00:00.nc -S 'west_east@XLONG_M,south_north@XLAT_M,num_metgrid_levels@int,Time@Times' -v TT,UU,VV,SKINTEMP
    1112
    1213from optparse import OptionParser
     
    3031  'ncreplace', 'ncstepdiff', 'netcdf_concatenation', 'netcdf_fold_concatenation',    \
    3132  'remapnn',                                                                         \
    32   'seasmean', 'sellonlatbox', 'sellonlatlevbox', 'setvar_asciivalues',               \
     33  'seasmean', 'sellonlatbox', 'sellonlatlevbox', 'selvar', 'setvar_asciivalues',     \
    3334  'sorttimesmat', 'spacemean', 'statcompare_files', 'submns', 'subyrs', 'TimeInf',   \
    3435  'timemean', 'valmod', 'valmod_dim','varaddattrk', 'varaddattr', 'varaddref',       \
     
    197198elif oper == 'sellonlatlevbox':
    198199    ncvar.sellonlatlevbox(opts.values, opts.ncfile, opts.varname)
     200elif oper == 'selvar':
     201    ncvar.selvar(opts.values, opts.ncfile, opts.varname)
    199202elif oper == 'setvar_asciivalues':
    200203    ncvar.setvar_asciivalues(opts.values, opts.ncfile, opts.varname)
  • trunk/tools/nc_var_tools.py

    r410 r418  
    1451914519
    1452014520#changevartype('i', 'test.nc', 'var')
     14521
     14522def add_dims(oc,nc,dnames):
     14523    """ Function to add dimensions from a given netCDF object to another one
     14524      oc: source netcdfile object
     14525      nc: netcdfile object to add dimensions
     14526      dnames: list of name of dimensions to add
     14527    """
     14528    fname = 'add_dims'
     14529
     14530    for dn in dnames:
     14531        print '  ' + fname + ': adding dim:',dn,' ...'
     14532        if oc.dimensions[dn].isunlimited():
     14533            newdim = nc.createDimension(dn, None)
     14534        else:
     14535            newdim = nc.createDimension(dn, len(oc.dimensions[dn]))
     14536
     14537    nc.sync()
     14538
     14539    return
     14540
     14541def add_vars(oc,nc,vnames):
     14542    """ Function to add variables from a given netCDF object to another one
     14543      oc: source netcdfile object
     14544      nc: netcdfile object to add dimensions
     14545      vnames: list of name of variables to add
     14546    """
     14547    fname = 'add_vars'
     14548
     14549    for vn in vnames:
     14550        print '  ' + fname + ': adding var:',vn,' ...'
     14551
     14552        varo = oc.variables[vn]
     14553        vartype = varo.dtype
     14554        vardims = varo.dimensions
     14555        varattrs = varo.ncattrs()
     14556
     14557        for vdn in vardims:
     14558            if not searchInlist(nc.dimensions,vdn):
     14559                print warnmsg
     14560                print '  ' + fname + ": adding dimension '" + vdn +                  \
     14561                  "' from variable '" + vdn + "' which is not in file !!"
     14562                add_dims(oc,nc,[vdn])
     14563
     14564        if searchInlist(varattrs,'_FillValue'):
     14565            newvar = nc.createVariable(vn, vartype, vardims,                         \
     14566              fill_value=varo.getncattr('_FillValue'))
     14567        else:
     14568            newvar = nc.createVariable(vn, vartype, vardims)
     14569
     14570        for attrn in varattrs:
     14571            attrv = varo.getncattr(attrn)
     14572            newattr = set_attribute(newvar, attrn, attrv)
     14573
     14574        newvar[:] = varo[:]
     14575
     14576    nc.sync()
     14577
     14578    return
     14579
     14580def add_globattrs(oc,nc,attrns):
     14581    """ Function to add global attributes from a given netCDF object to another one
     14582      oc: source netcdfile object
     14583      nc: netcdfile object to add dimensions
     14584      vnames: list of name of dimensions to add ('all', for all attributes)
     14585    """
     14586    fname = 'add_globattrs'
     14587
     14588    allfattrs = oc.ncattrs()
     14589
     14590    if attrns == 'all':
     14591        fattrns = allfattrs
     14592    else:
     14593        fattrns = attrns
     14594
     14595    for an in fattrns:
     14596        if not searchInlist(allfattrs,an):
     14597            print errormsg
     14598            print '  ' + fname + ": file has not global attribute '" + an + "' !!"
     14599            quit(-1)
     14600
     14601        print '  ' + fname + ': adding attr:',an,' ...'
     14602       
     14603        av = oc.getncattr(an)
     14604        newattr = set_attribute(nc, an, av)
     14605
     14606    nc.sync()
     14607
     14608    return
     14609
     14610def selvar(values, ncfile, varn):
     14611    """ Function to select a series of variables from a netcdf file. Variables with
     14612      the values of the associated dimensions will be also retrieved
     14613      values= ',' list of couples [dimname]@[vardimname]
     14614        [dimname]: name of the dimension
     14615        [vardimname]: name of the variable with values for the dimension ('int', for
     14616          counter of integers with the dimension length)
     14617      ncfile= netCDF file to use
     14618      varnames= ',' list of variables to retrieve
     14619    """
     14620    fname = 'selvar'
     14621
     14622    if values == 'h':
     14623        print fname + '_____________________________________________________________'
     14624        print selvar.__doc__
     14625        quit()
     14626
     14627    varnames = varn.split(',')
     14628    dimvals = values.split(',')
     14629
     14630    ofile = fname + '_new.nc'
     14631
     14632    onc = NetCDFFile(ncfile, 'r')
     14633
     14634    for varn in varnames:
     14635        if not searchInlist(onc.variables, varn):
     14636            print errormsg
     14637            print '  ' + fname + ": file '"  + ncfile + "' has not variable '" +     \
     14638              varn + "' !!"
     14639            quit(-1)
     14640
     14641    dimsv = {}
     14642    vardims = []
     14643    for dimv in dimvals:
     14644        dimn = dimv.split('@')[0]
     14645        if not searchInlist(onc.dimensions, dimn):
     14646            print errormsg
     14647            print '  ' + fname + ": file '"  + ncfile + "' has not dimension '" +    \
     14648              dimn + "' !!"
     14649            quit(-1)
     14650        varn = dimv.split('@')[1]
     14651        if not varn == 'int' and not searchInlist(onc.variables, varn):
     14652            print errormsg
     14653            print '  ' + fname + ": file '"  + ncfile + "' has not variable '" +     \
     14654              varn + "' !!"
     14655            quit(-1)
     14656        dimsv[dimn] = varn
     14657        if varn != 'int': vardims.append(varn)
     14658
     14659    newnc = NetCDFFile(ofile, 'w')
     14660
     14661# Creation of dimensions
     14662    add_dims(onc,newnc,dimsv.keys())
     14663
     14664# Getting variables from dimensions
     14665    add_vars(onc,newnc,vardims)
     14666
     14667# Getting variables
     14668    for varn in varnames:
     14669        varobj = onc.variables[varn]
     14670        vardims = varobj.dimensions
     14671        for dimn in vardims:
     14672            if not searchInlist(vardims,dimn):
     14673                print errormsg
     14674                print '  ' + fname + ": no assigned variable to dimension '" +       \
     14675                  dimn + "' !!"
     14676                quit(-1)
     14677
     14678    add_vars(onc,newnc,varnames)
     14679
     14680# Getting global attributes
     14681    add_globattrs(onc,newnc,'all')
     14682
     14683    onc.close()
     14684    newnc.close()
     14685
     14686    print "Successfull written of file '" + ofile + "' !!"
     14687
     14688    return
     14689
     14690selvar('x@lon,y@lat,time@time,shan@int', '/home/lluis/PY/test.nc', 'var')
    1452114691#quit()
    1452214692
Note: See TracChangeset for help on using the changeset viewer.