Changeset 1869 in lmdz_wrf for trunk


Ignore:
Timestamp:
Mar 26, 2018, 11:24:40 PM (7 years ago)
Author:
lfita
Message:

Working with `getdim_listonc'

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/tools/nc_var_tools.py

    r1868 r1869  
    7777# get_1str_nc: Function to get 1 string value in a netCDF variable as a chain of 1char values
    7878# get_attribute: Function to get an attribute from a netCDF file
     79# getdim_listonc: Function to get a dimension object from a list of netCDF file object
    7980# getvar_listonc: Function to get a variable object from a list of netCDF file object
    8081# get_namelist_vars: Function to get namelist-like  values ([varname] = [value])
     
    2286722868#quit()
    2286822869
     22870def getdim_listonc(dimn, fns, listoc):
     22871    """ Function to get a dimension object from a list of netCDF file object
     22872      dimn= name of the dimension to be found
     22873      fns= list with the name of the files
     22874      listoc= list of NetCDF file objects
     22875    """
     22876    fname = 'getvar_listonc'
     22877
     22878    allfs = {}
     22879    for ioc in range(len(listoc)):
     22880        oc = listoc[ioc]
     22881        # Seems that ObjNetcdf.filepath() requires netcdf >= 4.1.2....
     22882        #  Thus avoiding to use the functionality
     22883        #allfs[oc.filepath()] = ...
     22884        allfs[fns[ioc]] = [oc.dimensions, oc.variables.keys()]
     22885
     22886    # Looping for all files
     22887    found = False
     22888    for ioc in range(len(listoc)):
     22889        oc = listoc[ioc]
     22890        # Seems that ObjNetcdf.filepath() requires netcdf >= 4.1.2....
     22891        #  Thus avoiding to use the functionality
     22892        oncvars = allfs[fns[ioc]]
     22893        oncvars.sort()
     22894        if gen.searchInlist(oc.dimensions,dimn):
     22895            od = oc.dimensions[dimn]
     22896            found = True
     22897            break
     22898
     22899    if not found:
     22900        print errormsg
     22901        print '  ' + fname + "': any netcdf file '" + ','.join(fns) + "' contain " + \
     22902          "dimension '" + dimn + "' !!"
     22903        print '    available ones _______'
     22904        ioc = 0
     22905        for fn in fns:
     22906            print fn, ':', allfs[fn][0]
     22907            listoc[ioc].close()
     22908            ioc = ioc + 1
     22909        quit(-1)
     22910
     22911    return od
     22912
     22913def projection2D_information(PROJn, AXinf, projinf, dx, dy, Fns, oncs):
     22914    """ Function to get the basic information of the 2D-projection: new dimensions, variables, ...
     22915      Reproducing: class Projection from wrfncxnj.py
     22916        PROJn= name of the projection
     22917        AXinf= dictionary with the informatino of the axes 'X', 'Y', 'Z', 'T'
     22918        projinf= dictionary with all the information of the projection
     22919        Fns= list with the name of the files
     22920        oncs= list of netCDF objects from which retrieve the information
     22921      Returns:
     22922        newdim: dictionary new dimensions to be added {dimn1: dimlength1, ..., dimnN: dimlengthN}
     22923        newvar: dictionary new variables to be added {varn1: [stdn1, longn1, units1], ..., varnM: [stdnM, longnM, unitsM]}
     22924        newvarv: dictionary values new variables to be added {varn1: [values,...], ..., varnM: [values,...]}
     22925        nonCFattr: list of attributes from PROJn non-CF and non to be added to the file
     22926    """
     22927    fname = 'projection2D_information'
     22928
     22929    availproj = ['Lambert_Conformal', 'Rotated_Pole/Rotate_Latituded_Longitude',     \
     22930      'Mercator']
     22931
     22932    # Explanation of certain attributes in projection file
     22933    projfileexpl = {'x_resolution': 'Resolution in file alon x axis',                \
     22934      'y_resolution': 'Resolution in file alon y axis',                              \
     22935      'proj_units': 'units of the projection (e.g.: km, m, degrees,...)',            \
     22936      'fileXvals': 'variable with the reference values for the projection ' +        \
     22937        'along X axis (e.g.: values for rlon)',                                      \
     22938      'fileYvals': 'variable with the reference values for the projection ' +        \
     22939        'along Y axis (e.g.: values for rlat)'}
     22940    CFprojweb = 'http://cfconventions.org/Data/cf-conventions/cf-conventions-1.7/' + \
     22941      'build/ch05s06.html'
     22942
     22943    isrotated = False
     22944    if PROJn.find('rotated') != -1 or PROJn.find('Rotated') != -1:
     22945        isrotated = True
     22946        projpiec = PROJn.split('_')
     22947        if PROJn.find('rotated') != -1:
     22948            projpiec.remove('rotated')
     22949        else:
     22950            projpiec.remove('Rotated')
     22951        projn = '_'.join(projpiec)
     22952
     22953    if PROJn == "Lambert_Conformal":
     22954        proj_attr = ["grid_mapping_name", "cone_type", "northern_parallel",          \
     22955          "southern_parallel", "longitude_of_central_meridian",                      \
     22956          "latitude_of_projection_origin", 'x_resolution', 'y_resolution',           \
     22957          'proj_units']
     22958        # Removing the non-CF attributes
     22959        nonCFattr = ['x_resolution', 'y_resolution', 'proj_units']
     22960        for atn in proj_attr:
     22961            if not projinf.has_key(atn):
     22962                print errormsg
     22963                print '  ' + fname + ": to process projection '" + PROJn +           \
     22964                  "' is required to provide argument '" + atn + "' in the " +        \
     22965                  "'[projectfile]' !!"
     22966                if projfileexpl.has_key(atn):
     22967                    print '    ', atn, ':', projfileexpl[atn]
     22968                else:
     22969                    print '    ', atn, ': CF-attribute, please visit: ', CFprojweb
     22970                print '    values provided:', projinf
     22971                quit(-1)
     22972        newdim = {}
     22973        newvar = {}
     22974        newvarv = {}
     22975
     22976        newdim['x'] = dx
     22977        newvar['x'] = ['projection_x_coordinate', 'x coordinate of projection', 'km']
     22978        Xres = np.float(projinf['x_resolution'][0])
     22979        if projinf['proj_units'][0] == 'km':
     22980            scale = 1.
     22981        elif projinf['proj_units'][0] == 'm':
     22982            scale = 1000.
     22983        else:
     22984            print errormsg
     22985            print '  ' + fname + ": Resolution units '" + projinf['proj_units'][0] + \
     22986              "' not ready !!"
     22987            print '    available ones:', ['km', 'm']
     22988            quit(-1)
     22989        newvarv['x'] = (np.arange(1,dx+1)-dx/2)*Xres/scale
     22990        # updating values on axes
     22991        axv = AXinf['X']
     22992        axv['dimn'] = 'x'
     22993        axv['vdimn'] = 'lon'
     22994        AXinf['X'] = axv
     22995
     22996        newdim['y'] = dy
     22997        newvar['y'] = ['projection_y_coordinate', 'y coordinate of projection', 'km']
     22998        Yres = np.float(projinf['y_resolution'][0])
     22999        newvarv['y'] = (np.arange(1,dy+1)-dy/2)*Yres/scale
     23000        # updating values on axes
     23001        axv = AXinf['Y']
     23002        axv['dimn'] = 'y'
     23003        axv['vdimn'] = 'lat'
     23004        AXinf['Y'] = axv
     23005
     23006    elif PROJn == "Rotated_Pole" or PROJn == 'Rotated_Latitude_Longitude':
     23007        proj_attr = ["grid_mapping_name", "grid_north_pole_latitude",                \
     23008          "grid_north_pole_longitude", 'fileXvals', 'fileYvals']
     23009        # Removing the non-CF attributes
     23010        nonCFattr = ['fileXvals', 'fileYvals']
     23011        for atn in proj_attr:
     23012            if not projinf.has_key(atn):
     23013                print errormsg
     23014                print '  ' + fname + ": to process projection '" + PROJn +           \
     23015                  "' is required to provide argument '" + atn + "' in the " +        \
     23016                  "'[projectfile]' !!"
     23017                if projfileexpl.has_key(atn):
     23018                    print '    ', atn, ':', projfileexpl[atn]
     23019                else:
     23020                    print '    ', atn, ': CF-attribute, please visit: ', CFprojweb
     23021                print '    values provided:', projinf
     23022                quit(-1)
     23023        newdim = {}
     23024        newvar = {}
     23025        newvarv = {}
     23026
     23027        newdim['rlon'] = dx
     23028        newvar['rlon'] = ['grid_longitude', 'longitude in rotated pole grid',        \
     23029          'degrees']
     23030
     23031        ovar = getvar_listonc(projinf['fileXvals'][0], Fns, oncs)
     23032        oXvar = ovar[0]
     23033        if len(oXvar.shape) == 3:
     23034            newvarv['rlon'] = oXvar[0,0,:]
     23035        elif len(oXvar.shape) == 2:
     23036            newvarv['rlon'] = oXvar[0,:]
     23037        elif len(oXvar.shape) == 1:
     23038            newvarv['rlon'] = oXvar[:]
     23039        else:
     23040            print errormsg
     23041            print '  ' + fname + ": rank ", oXvar.shape, " of values for X ref " +   \
     23042              "not ready !!"
     23043            quit(-1)
     23044        # updating values on axes
     23045        axv = AXinf['X']
     23046        axv['dimn'] = 'rlon'
     23047        axv['vdimn'] = 'lon'
     23048        AXinf['X'] = axv
     23049
     23050        newdim['rlat'] = dy
     23051        newvar['rlat'] = ['grid_latitude', 'latitude in rotated pole grid', 'degrees']
     23052        ovar = getvar_listonc(projinf['fileYvals'][0], Fns, oncs)
     23053        oYvar = ovar[0]
     23054        if len(oYvar.shape) == 3:
     23055            newvarv['rlat'] = oYvar[0,0,:]
     23056        elif len(oYvar.shape) == 2:
     23057            newvarv['rlat'] = oYvar[0,:]
     23058        elif len(oYvar.shape) == 1:
     23059            newvarv['rlat'] = oYvar[:]
     23060        else:
     23061            print errormsg
     23062            print '  ' + fname + ": rank ", oYvar.shape, " of values for Y ref " +   \
     23063              "not ready !!"
     23064            quit(-1)
     23065        # updating values on axes
     23066        axv = AXinf['Y']
     23067        axv['dimn'] = 'rlat'
     23068        axv['vdimn'] = 'lat'
     23069        AXinf['Y'] = axv
     23070
     23071    elif PROJn == "Mercator":
     23072        proj_attr = ["grid_mapping_name", "longitude_of_projection_origin",          \
     23073          "standard_parallel", 'x_resolution', 'y_resolution', 'proj_units']
     23074        # Removing the non-CF attributes
     23075        nonCFattr = ['x_resolution', 'y_resolution', 'proj_units']
     23076        for atn in proj_attr:
     23077            if not projinf.has_key(atn):
     23078                print errormsg
     23079                print '  ' + fname + ": to process projection '" + PROJn +           \
     23080                  "' is required to provide argument '" + atn + "' in the " +        \
     23081                  "'[projectfile]' !!"
     23082                if projfileexpl.has_key(atn):
     23083                    print '    ', atn, ':', projfileexpl[atn]
     23084                else:
     23085                    print '    ', atn, ': CF-attribute, please visit: ', CFprojweb
     23086                print '    values provided:', projinf
     23087                quit(-1)
     23088
     23089        newdim = {}
     23090        newvar = {}
     23091        newvarv = {}
     23092
    2286923093def getvar_listonc(varn, fns, listoc):
    2287023094    """ Function to get a variable object from a list of netCDF file object
     
    2352923753                else:
    2353023754                    CFvardimvalues.append(dn)
    23531                     varslice.append(slice(0,len(onc.dimensions[dn])))
     23755                    oaxisd = getdim_listonc(dn, afNs, allonc)
     23756                    varslice.append(slice(0,len(oaxisd)))
    2353223757                    if dn == dimn and CFdimvalues['length'] != -1:
    23533                         CFdimvalues['length'] = len(onc.dimensions[dn])
     23758                        CFdimvalues['length'] = len(oaxisd)
    2353423759            axsiv = oaxisv[tuple(varslice)]
    2353523760        else:
Note: See TracChangeset for help on using the changeset viewer.