Changeset 2384 in lmdz_wrf for trunk


Ignore:
Timestamp:
Mar 8, 2019, 2:04:38 PM (6 years ago)
Author:
lfita
Message:

Adding:

  • `CFfile_creation': Operation to create a file folowing CF-conventions
Location:
trunk/tools
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/tools/nc_var.py

    r2382 r2384  
    7474## e.g. # nc_var.py -o usefile_compute_slices_stats_areaweighted -S 'compute_slices_stats_areaweighted.nc@XLAT_M-HGT_M-rangefaces@Time|WRFtime:west_east|XLONG_M:south_north|XLAT_M:land_cat|INTrange@Time,land_cat' -f 'geo_em.d01.nc' -v 'LANDUSEF'
    7575## e.g. # nc_var.py -o compress_data -S 'XLAND:Time|0:single,1:X|west_east|XLONG,Y|south_north|XLAT' -f wrfout_d01_1995-01-01_00:00:00 -v T2,LU_INDEX,Times
     76## e.g. # nc_var.py -o CFfile_creation -S 'lon|360,lat|180,time|None@20:global' -v 'tas#time;lat;lon#f#None,time#time#f8#units|seconds!since!1949-12-01!00:00:00|S' -f newCF.nc
    7677
    7778from optparse import OptionParser
     
    9091#   of matrices assuming regular lon/lat projections without taking into account Earth's curvature
    9192# CDO_toCF: Function to pass a CDO output file to CF-conventions
     93# CFfile_creation: Operation to create a file folowing CF-conventions
    9294# CFmorzization: Function to provide a CF-compilation version of a variable within a file
    9395# chdimname: Changing the name of the dimension
     
    229231
    230232operations=['addDim', 'addVar', 'addvals', 'area_weighted', 'CDO_toCF',              \
    231   'CFmorzization', 'chdimname', 'changevartype',                                     \
     233  'CFfile_creation', 'CFmorzization', 'chdimname', 'changevartype',                  \
    232234  'checkallvars', 'checkAllValues', 'checkNaNs',                                     \
    233235  'chgtimestep', 'chvarname', 'cleaning_varsfile', 'compress_data',                  \
     
    311313
    312314# Operations which file name is not a real file
    313 NotCheckingFile = ['area_weighted', 'DatesFiles', 'compute_opersvarsfiles',          \
    314   'file_creation',                                                                   \
     315NotCheckingFile = ['area_weighted', 'CFfile_creation','DatesFiles',                  \
     316  'compute_opersvarsfiles', 'file_creation',                                         \
    315317  'join_singlestation_obsfiles', 'join_sounding_obsfiles', 'list_operations',        \
    316318  'merge_files',                                                                     \
     
    352354elif oper == 'CDO_toCF':
    353355    ncvar.CDO_toCF(opts.ncfile)
     356elif oper == 'CFfile_creation':
     357    ncvar.CFfile_creation(opts.values, opts.ncfile, opts.varname)
    354358elif oper == 'CFmorzization':
    355359    ncvar.CFmorzization(opts.values, opts.ncfile, opts.varname)
  • trunk/tools/nc_var_tools.py

    r2383 r2384  
    3333# basicvardef: Function to give the basic attributes to a variable (std_name, long_name, units)
    3434# CDO_toCF: Function to pass a CDO output file to CF-conventions
     35# CFfile_creation: Operation to create a file folowing CF-conventions
    3536# CFmorzization: Function to provide a CF-compilation version of a variable within a file
    3637# CFvars: Function to adapt a given variable and file following CF-standards
     
    3106831069    """ Operation to create a file folowing CF-conventions
    3106931070      values= [dimensions]:[lonlatbox]
    31070         [dimensions]: lon|[dsizelon],lat|[dsizelat],...,[dimnN]:[dsizeN], ',' pairs of variable
    31071           name [dimn] and [size]
    31072           if [dsize] = 'None' (for UNLIMITED), give a third value with the real size
     31071        [dimensions]: lon|[dsizelon],lat|[dsizelat],...,[dimnN]|[dsizeN], ',' pairs
     31072          of variable name [dimn] and [size]
     31073          * if [dsize] = 'None' (for UNLIMITED), provide size of dimension as
     31074             'None'@[size]
    3107331075        [lonlatbox]: ',' separated list of the extremes of the domain [SWlon],[SWlat],
    3107431076          [NElon],[NElat] or 'global' for a global file [assuing lon/lat regular
    3107531077          projection]
    31076       ncfile= name of the file
    31077       variables= ',' list of variables to create [varn]:[dims]:[kind]:[varaddattributes]
     31078      ncfile= name of the file to produce
     31079      variables= ',' list of variables to create [varn]#[dims]#[kind]#[vaddattributes]
    3107831080          and its characterisitcs
    31079         [varn]: CF name of the variable (attributes will be retrived from
    31080            'variables_values.dat')
    31081         [dims]: ',' python sorted list of dimensions of the variable
     31081        [varn]: CF name of the variable (basic attributes: standard_name, long_name
     31082           and units, will be retrived from 'variables_values.dat')
     31083        [dims]: ';' sorted list of dimensions of the variable ([...], [t], [z], y, x)
    3108231084        [kind]: type of variable (standard netCDF4/C-like values, 'c', 'i', 'f',
    3108331085          'f8',...)
    31084         [varaddattributes]: ',' list of additional attributes and their values for
    31085           the variable [attrn]|[attrv]
     31086        [varaddattributes]: ';' list of additional attributes and their values for
     31087          the variable [attrn]|[attrv]|[attrk] ('None' for any) '!' for spaces in
     31088          string attributes
     31089          [attrn]: name of the attribute
     31090          [attrv]: value of the attribute
     31091          [attrk]: kind of the attribute('S': string, 'I': integer, 'F': float, ...)
    3108631092    """
    3108731093    fname = 'CFfile_creation'
     31094    availkind = ['c', 'i', 'f', 'f8']
    3108831095
    3108931096    if values == 'h':
     
    3110931116    onewnc = NetCDFFile(ncfile, 'w')
    3111031117
    31111     dimx = dimensions['lon']
    31112     dimy = dimensions['lat']
     31118    dimx = int(dimensions['lon'])
     31119    dimy = int(dimensions['lat'])
    3111331120
    3111431121    # Assuming regular lon/lat projection
    3111531122    if lonlatbox == 'global':
    31116         ddx = 360./(dimx-1)
     31123        ddx = 360./(dimx)
    3111731124        ddx2 = ddx/2.
    3111831125        lons = np.arange(-180.+ddx2,180.+ddx2,ddx)
    31119         ddy = 180./(dimy-1)
     31126        ddy = 180./(dimy)
    3112031127        ddy2 = ddy/2.
    3112131128        lats = np.arange(-90.+ddy2,90.+ddy2,ddy)
    3112231129    elif lonlatbox.count(',') == 3:
    3112331130        [lonSW, latSW, lonNE, latNE] = str_listk(lonlatbox, ',', 'F')
    31124         ddx = (lonNE-lonSW)/(dimx-1)
     31131        ddx = (lonNE-lonSW)/(dimx)
    3112531132        ddx2 = ddx/2.
    3112631133        lons = np.arange(lonSW-ddx2,lonNE+ddx2,ddx)
    31127         ddy = (latNE-latSW)/(dimy-1)
     31134        ddy = (latNE-latSW)/(dimy)
    3112831135        ddy2 = ddy/2.
    3112931136        lats = np.arange(latSW-ddy2,latNE+ddy2,ddy)
    3113031137
     31138    print 'Lluis shapes lons:', lons.shape, 'lats:', lats.shape
    3113131139    # Sorting lon/lat_bounds
    31132     lon_bnds = np.zeros((2,dimx), dtype=np.float64)
    31133     lat_bnds = np.zeros((2,dimy), dtype=np.float64)
     31140    lon_bnds = np.zeros((dimx,2), dtype=np.float64)
     31141    lat_bnds = np.zeros((dimy,2), dtype=np.float64)
    3113431142    for i in range(dimx):
    31135         lon_bnds[0,i] = lons[i]-ddx2
    31136         lon_bnds[1,i] = lons[i]+ddx2
     31143        lon_bnds[i,0] = lons[i]-ddx2
     31144        lon_bnds[i,1] = lons[i]+ddx2
    3113731145    for j in range(dimy):
    31138         lat_bnds[0,j] = lats[j]-ddy2
    31139         lat_bnds[1,j] = lats[j]+ddy2
     31146        lat_bnds[j,0] = lats[j]-ddy2
     31147        lat_bnds[j,1] = lats[j]+ddy2
    3114031148
    3114131149    # Dimensions
     
    3114731155    for dn in dimensions:
    3114831156        if dn != 'lon' and dn != 'lat':
    31149             if dn == 'time': dl = None
    31150             else: dl = dimensions[dn]
    31151             newdim = onewnc.createDimension(dn, None)
     31157            if dimensions[dn][0:4] == 'None': dl = None
     31158            else: dl = int(dimensions[dn])
     31159            newdim = onewnc.createDimension(dn, dl)
    3115231160    onewnc.sync()
    3115331161
     
    3115931167    newvar.setncattr('axis', 'X')
    3116031168    newvar.setncattr('_CoordinateAxisType', 'Lon')
     31169    newvar.setncattr('bounds', 'lon_bnds')
    3116131170
    3116231171    newvar = onewnc.createVariable('lat', 'f4', ('lat'))
     
    3116631175    newvar.setncattr('axis', 'Y')
    3116731176    newvar.setncattr('_CoordinateAxisType', 'Lat')
     31177    newvar.setncattr('bounds', 'lat_bnds')
     31178
     31179    # Creation of variable dimensions
     31180    newvar = onewnc.createVariable('lon_bnds', 'f4', ('lon', 'bnds'))
     31181    newvar[:] = lon_bnds[:]
     31182    newvar = onewnc.createVariable('lat_bnds', 'f4', ('lat', 'bnds'))
     31183    newvar[:] = lat_bnds[:]
     31184
     31185    # Projection
     31186    projn = 'regular_latlon'
     31187    newvar = onewnc.createVariable(projn, 'c')
     31188    newvar.setncattr('grid_mapping_name', 'latitude_longitude')
    3116831189
    3116931190    onewnc.sync()
    3117031191
    3117131192    varns = variables.split(',')
    31172     for varn in varns:
    31173         print varn
    31174 
    31175     dnames = []
    31176     dsize = []
    31177     for dim in dimensions:
    31178 #        print "  Adding: '" + dim + "' ..."
    31179         dimn = dim.split(':')[0]
    31180         dimv = dim.split(':')[1]
    31181         if dimv == 'None':
    31182             if len(dim.split(':')) != 3:
     31193    for varvn in varns:
     31194        varn = varvn.split('#')[0]
     31195        dims = varvn.split('#')[1].split(';')
     31196        kind = varvn.split('#')[2]
     31197
     31198        # Checking variable's dimensions
     31199        varshape = []
     31200        for dn in dims:
     31201            if not onewnc.dimensions.has_key(dn):
    3118331202                print errormsg
    31184                 print '  ' + fname + ": dimension '" + dimn + "' is None but the " + \
    31185                   'size is requried!!'
     31203                print '  ' + fname + ": CF netCDF file does not have dimension '" +  \
     31204                  dn + "' !!"
     31205                print "    provide values for the dimension as [dimensions]= " +     \
     31206                  "[dimnN]|[dsizeN]"
     31207                Dims = list(onewnc.dimensions.keys())
     31208                Dims.sort()
     31209                print '    available ones:', Dims
    3118631210                quit(-1)
    3118731211            else:
    31188                 dv = None
    31189                 dsize.append(int(dim.split(':')[2]))
     31212                if dimensions[dn][0:4] == 'None':
     31213                    dsize = int(dimensions[dn].split('@')[1])
     31214                else:
     31215                    dsize = len(onewnc.dimensions[dn])
     31216                varshape.append(dsize)
     31217
     31218        # Getting variable basic attributes
     31219        cfvarvals = gen.variables_values(varn)
     31220
     31221        print '  ' + fname + ": adding '" + varn + "' (", dims, ") '", kind, "' ..."
     31222
     31223        varaddattributes = varvn.split('#')[3]
     31224        if varaddattributes != 'None':
     31225            vaddattr = {}
     31226            addattr = varaddattributes.split(';')
     31227            for attr in addattr:
     31228                attrv = attr.split('|')
     31229                vaddattr[attrv[0]] = attrv[1:4]
     31230            print '    addiditional attributes _______'
     31231            gen.printing_dictionary(vaddattr)
    3119031232        else:
    31191             dv = int(dimv)
    31192             dsize.append(dv)
    31193 
    31194         dnames.append(dimn)
    31195 
    31196         newdim = onc.createDimension(dimn, dv)
     31233            vaddattr = None
     31234
     31235        # creation
     31236        if kind == 'c':
     31237            newvar = onewnc.createVariable(varn, 'c', tuple(dims))
     31238        if kind == 'f' or kind == 'f4':
     31239            newvar = onewnc.createVariable(varn, 'f4', tuple(dims),                  \
     31240              fill_value=gen.fillValueF)
     31241            newvar[:] = np.zeros(tuple(varshape), dtype=np.float)
     31242        elif kind == 'f8':
     31243            newvar = onewnc.createVariable(varn, 'f8', tuple(dims),                  \
     31244              fill_value= gen.fillValueD)
     31245            newvar[:] = np.zeros(tuple(varshape), dtype=np.float64)
     31246        elif kind == 'i':
     31247            newvar = onewnc.createVariable(varn, 'i', tuple(dims),                   \
     31248              fill_value=gen.fillValueI)
     31249            newvar[:] = np.zeros(tuple(varshape), dtype=int)
     31250        else:
     31251            print errormsg
     31252            print '  ' + fname + ": variable kind '" + kind + "' not ready!!"
     31253            print '    available ones:', availkind
     31254            quit(-1)
    3119731255   
    31198     onc.sync()
    31199 
    31200 # Variable
    31201     if kind == 'c':
    31202         newvar = onc.createVariable(varn, 'c', tuple(dnames))
    31203 #        newvar[:] = np.zeros(tuple(dsize), dtype=np.float)
    31204     if kind == 'f' or kind == 'f4':
    31205         newvar = onc.createVariable(varn, 'f4', tuple(dnames),                       \
    31206           fill_value=gen.fillValueF)
    31207         newvar[:] = np.zeros(tuple(dsize), dtype=np.float)
    31208     elif kind == 'f8':
    31209         newvar = onc.createVariable(varn, 'f8', tuple(dnames),                       \
    31210           fill_value= gen.fillValueD)
    31211         newvar[:] = np.zeros(tuple(dsize), dtype=np.float64)
    31212     elif kind == 'i':
    31213         newvar = onc.createVariable(varn, 'i', tuple(dnames),                        \
    31214           fill_value=gen.fillValueI)
    31215         newvar[:] = np.zeros(tuple(dsize), dtype=int)
    31216     else:
    31217         print errormsg
    31218         print '  ' + fname + ": variable kind '" + kind + "' not ready!!"
    31219         quit(-1)
    31220 
    31221     sname = attributes.split('@')[0].replace('!', ' ')
    31222     lname = attributes.split('@')[1].replace('!', ' ')
    31223     u = attributes.split('@')[2].replace('!', ' ')
    31224    
    31225     newattr = basicvardef(newvar, sname, lname, u)
    31226 
    31227     onc.sync()
    31228 
    31229 # Global attributes
    31230     newattr = set_attribute(onc, 'description', "file creation using " + fname )
    31231     onc.sync()
    31232     onc.close()
    31233 
    31234 #file_creation('time_counter:12,sizes:24|time@time@seconds since 1949-12-01 00:00:00|f8', 'test.nc', 't_instant')
     31256        basicvardef(newvar, cfvarvals[1], cfvarvals[4].replace('|',' '), cfvarvals[5])
     31257        newvar.setncattr('grid_mapping', projn)
     31258        if vaddattr is not None:
     31259            for attrn in vaddattr.keys():
     31260                attrv = vaddattr[attrn]
     31261                if attrv[1] == 'S':
     31262                    set_attributek(newvar, attrn, attrv[0].replace('!', ' '), attrv[1])
     31263                else:
     31264                    set_attributek(newvar, attrn, attrv[0], attrv[1])
     31265
     31266        onewnc.sync()
     31267
     31268    # Global attributes
     31269    onewnc.setncattr('Conventions', 'CF-1.5')
     31270    add_global_PyNCplot(onewnc, 'nc_var_tools', fname, '1.0')
     31271
     31272    onewnc.sync()
     31273    onewnc.close()
     31274
     31275    print fname + ": Successfully written CF-file '" + ncfile + "' !!"
     31276
     31277    return
     31278
     31279#values='lon|360,lat|180,time|None@20:global'
     31280#varsS='tas#time;lat;lon#f#None,time#time#f8#units|seconds!since!1949-12-01!00:00:00|S'
     31281#CFfile_creation(values, 'CFtest.nc', varsS)
    3123531282
    3123631283
Note: See TracChangeset for help on using the changeset viewer.