Changeset 1871 in lmdz_wrf


Ignore:
Timestamp:
Mar 27, 2018, 3:22:39 PM (7 years ago)
Author:
lfita
Message:

Working version of `CFmorzization' with extrafiles

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/tools/nc_var_tools.py

    r1869 r1871  
    2172621726
    2172721727                newvar = newnc.createVariable(vn, nctype(ovar.dtype), tuple(dimvar))
    21728                 print '    Lluis shapes newvar:', newvar.shape, 'ovar:', ovar.shape
    2172921728                newvar[:] = ovar[:]
    2173021729
     
    2291122910    return od
    2291222911
     22912def getvar_listonc(varn, fns, listoc):
     22913    """ Function to get a variable object from a list of netCDF file object
     22914      varn= name of the variable to be found
     22915      fns= list with the name of the files
     22916      listoc= list of NetCDF file objects
     22917    """
     22918    fname = 'getvar_listonc'
     22919
     22920    allfs = {}
     22921    for ioc in range(len(listoc)):
     22922        oc = listoc[ioc]
     22923        # Seems that ObjNetcdf.filepath() requires netcdf >= 4.1.2....
     22924        #  Thus avoiding to use the functionality
     22925        #allfs[oc.filepath()] = ...
     22926        allfs[fns[ioc]] = [oc.dimensions, oc.variables.keys()]
     22927
     22928    # Looping for all files
     22929    found = False
     22930    for ioc in range(len(listoc)):
     22931        oc = listoc[ioc]
     22932        # Seems that ObjNetcdf.filepath() requires netcdf >= 4.1.2....
     22933        #  Thus avoiding to use the functionality
     22934        oncvars = allfs[fns[ioc]]
     22935        oncvars.sort()
     22936        if oc.variables.has_key(varn):
     22937            ov = oc.variables[varn]
     22938            found = True
     22939            break
     22940
     22941    if not found:
     22942        print errormsg
     22943        print '  ' + fname + "': any netcdf file '" + ','.join(fns) + "' contain " + \
     22944          "variable '" + varn + "' !!"
     22945        print '    available ones _______'
     22946        ioc = 0
     22947        for fn in fns:
     22948            print fn, ':', allfs[fn][1]
     22949            listoc[ioc].close()
     22950            ioc = ioc + 1
     22951        quit(-1)
     22952
     22953    return ov
     22954
    2291322955def projection2D_information(PROJn, AXinf, projinf, dx, dy, Fns, oncs):
    2291422956    """ Function to get the basic information of the 2D-projection: new dimensions, variables, ...
     
    2293822980      'fileYvals': 'variable with the reference values for the projection ' +        \
    2293922981        'along Y axis (e.g.: values for rlat)'}
     22982    nonCFattr = list(projfileexpl.keys())
    2294022983    CFprojweb = 'http://cfconventions.org/Data/cf-conventions/cf-conventions-1.7/' + \
    2294122984      'build/ch05s06.html'
     
    2295723000          'proj_units']
    2295823001        # Removing the non-CF attributes
    22959         nonCFattr = ['x_resolution', 'y_resolution', 'proj_units']
    2296023002        for atn in proj_attr:
    2296123003            if not projinf.has_key(atn):
     
    2300823050          "grid_north_pole_longitude", 'fileXvals', 'fileYvals']
    2300923051        # Removing the non-CF attributes
    23010         nonCFattr = ['fileXvals', 'fileYvals']
    2301123052        for atn in proj_attr:
    2301223053            if not projinf.has_key(atn):
     
    2305323094        oYvar = ovar[0]
    2305423095        if len(oYvar.shape) == 3:
    23055             newvarv['rlat'] = oYvar[0,0,:]
     23096            newvarv['rlat'] = oYvar[0,:,0]
    2305623097        elif len(oYvar.shape) == 2:
    23057             newvarv['rlat'] = oYvar[0,:]
     23098            newvarv['rlat'] = oYvar[:,0]
    2305823099        elif len(oYvar.shape) == 1:
    2305923100            newvarv['rlat'] = oYvar[:]
     
    2307323114          "standard_parallel", 'x_resolution', 'y_resolution', 'proj_units']
    2307423115        # Removing the non-CF attributes
    23075         nonCFattr = ['x_resolution', 'y_resolution', 'proj_units']
    2307623116        for atn in proj_attr:
    2307723117            if not projinf.has_key(atn):
     
    2308723127                quit(-1)
    2308823128
    23089         newdim = {}
    23090         newvar = {}
    23091         newvarv = {}
    23092 
    23093 def getvar_listonc(varn, fns, listoc):
    23094     """ Function to get a variable object from a list of netCDF file object
    23095       varn= name of the variable to be found
    23096       fns= list with the name of the files
    23097       listoc= list of NetCDF file objects
    23098     """
    23099     fname = 'getvar_listonc'
    23100 
    23101     allfs = {}
    23102     for ioc in range(len(listoc)):
    23103         oc = listoc[ioc]
    23104         # Seems that ObjNetcdf.filepath() requires netcdf >= 4.1.2....
    23105         #  Thus avoiding to use the functionality
    23106         #allfs[oc.filepath()] = ...
    23107         allfs[fns[ioc]] = [oc.dimensions, oc.variables.keys()]
    23108 
    23109     # Looping for all files
    23110     found = False
    23111     for ioc in range(len(listoc)):
    23112         oc = listoc[ioc]
    23113         # Seems that ObjNetcdf.filepath() requires netcdf >= 4.1.2....
    23114         #  Thus avoiding to use the functionality
    23115         oncvars = allfs[fns[ioc]]
    23116         oncvars.sort()
    23117         if oc.variables.has_key(varn):
    23118             ov = oc.variables[varn]
    23119             found = True
    23120             break
    23121 
    23122     if not found:
    23123         print errormsg
    23124         print '  ' + fname + "': any netcdf file '" + ','.join(fns) + "' contain " + \
    23125           "variable '" + varn + "' !!"
    23126         print '    available ones _______'
    23127         ioc = 0
    23128         for fn in fns:
    23129             print fn, ':', allfs[fn][1]
    23130             listoc[ioc].close()
    23131             ioc = ioc + 1
    23132         quit(-1)
    23133 
    23134     return ov
    23135 
    23136 def projection2D_information(PROJn, AXinf, projinf, dx, dy, Fns, oncs):
    23137     """ Function to get the basic information of the 2D-projection: new dimensions, variables, ...
    23138       Reproducing: class Projection from wrfncxnj.py
    23139         PROJn= name of the projection
    23140         AXinf= dictionary with the informatino of the axes 'X', 'Y', 'Z', 'T'
    23141         projinf= dictionary with all the information of the projection
    23142         Fns= list with the name of the files
    23143         oncs= list of netCDF objects from which retrieve the information
    23144       Returns:
    23145         newdim: dictionary new dimensions to be added {dimn1: dimlength1, ..., dimnN: dimlengthN}
    23146         newvar: dictionary new variables to be added {varn1: [stdn1, longn1, units1], ..., varnM: [stdnM, longnM, unitsM]}
    23147         newvarv: dictionary values new variables to be added {varn1: [values,...], ..., varnM: [values,...]}
    23148         nonCFattr: list of attributes from PROJn non-CF and non to be added to the file
    23149     """
    23150     fname = 'projection2D_information'
    23151 
    23152     availproj = ['Lambert_Conformal', 'Rotated_Pole/Rotate_Latituded_Longitude',     \
    23153       'Mercator']
    23154 
    23155     # Explanation of certain attributes in projection file
    23156     projfileexpl = {'x_resolution': 'Resolution in file alon x axis',                \
    23157       'y_resolution': 'Resolution in file alon y axis',                              \
    23158       'proj_units': 'units of the projection (e.g.: km, m, degrees,...)',            \
    23159       'fileXvals': 'variable with the reference values for the projection ' +        \
    23160         'along X axis (e.g.: values for rlon)',                                      \
    23161       'fileYvals': 'variable with the reference values for the projection ' +        \
    23162         'along Y axis (e.g.: values for rlat)'}
    23163     CFprojweb = 'http://cfconventions.org/Data/cf-conventions/cf-conventions-1.7/' + \
    23164       'build/ch05s06.html'
    23165 
    23166     isrotated = False
    23167     if PROJn.find('rotated') != -1 or PROJn.find('Rotated') != -1:
    23168         isrotated = True
    23169         projpiec = PROJn.split('_')
    23170         if PROJn.find('rotated') != -1:
    23171             projpiec.remove('rotated')
    23172         else:
    23173             projpiec.remove('Rotated')
    23174         projn = '_'.join(projpiec)
    23175 
    23176     if PROJn == "Lambert_Conformal":
    23177         proj_attr = ["grid_mapping_name", "cone_type", "northern_parallel",          \
    23178           "southern_parallel", "longitude_of_central_meridian",                      \
    23179           "latitude_of_projection_origin", 'x_resolution', 'y_resolution',           \
    23180           'proj_units']
    23181         # Removing the non-CF attributes
    23182         nonCFattr = ['x_resolution', 'y_resolution', 'proj_units']
    23183         for atn in proj_attr:
    23184             if not projinf.has_key(atn):
    23185                 print errormsg
    23186                 print '  ' + fname + ": to process projection '" + PROJn +           \
    23187                   "' is required to provide argument '" + atn + "' in the " +        \
    23188                   "'[projectfile]' !!"
    23189                 if projfileexpl.has_key(atn):
    23190                     print '    ', atn, ':', projfileexpl[atn]
    23191                 else:
    23192                     print '    ', atn, ': CF-attribute, please visit: ', CFprojweb
    23193                 print '    values provided:', projinf
    23194                 quit(-1)
    2319523129        newdim = {}
    2319623130        newvar = {}
     
    2322723161        AXinf['Y'] = axv
    2322823162
    23229     elif PROJn == "Rotated_Pole" or PROJn == 'Rotated_Latitude_Longitude':
    23230         proj_attr = ["grid_mapping_name", "grid_north_pole_latitude",                \
    23231           "grid_north_pole_longitude", 'fileXvals', 'fileYvals']
    23232         # Removing the non-CF attributes
    23233         nonCFattr = ['fileXvals', 'fileYvals']
    23234         for atn in proj_attr:
    23235             if not projinf.has_key(atn):
    23236                 print errormsg
    23237                 print '  ' + fname + ": to process projection '" + PROJn +           \
    23238                   "' is required to provide argument '" + atn + "' in the " +        \
    23239                   "'[projectfile]' !!"
    23240                 if projfileexpl.has_key(atn):
    23241                     print '    ', atn, ':', projfileexpl[atn]
    23242                 else:
    23243                     print '    ', atn, ': CF-attribute, please visit: ', CFprojweb
    23244                 print '    values provided:', projinf
    23245                 quit(-1)
    23246         newdim = {}
    23247         newvar = {}
    23248         newvarv = {}
    23249 
    23250         newdim['rlon'] = dx
    23251         newvar['rlon'] = ['grid_longitude', 'longitude in rotated pole grid',        \
    23252           'degrees']
    23253 
    23254         ovar = getvar_listonc(projinf['fileXvals'][0], Fns, oncs)
    23255         oXvar = ovar[0]
    23256         if len(oXvar.shape) == 3:
    23257             newvarv['rlon'] = oXvar[0,0,:]
    23258         elif len(oXvar.shape) == 2:
    23259             newvarv['rlon'] = oXvar[0,:]
    23260         elif len(oXvar.shape) == 1:
    23261             newvarv['rlon'] = oXvar[:]
    23262         else:
    23263             print errormsg
    23264             print '  ' + fname + ": rank ", oXvar.shape, " of values for X ref " +   \
    23265               "not ready !!"
    23266             quit(-1)
    23267         # updating values on axes
    23268         axv = AXinf['X']
    23269         axv['dimn'] = 'rlon'
    23270         axv['vdimn'] = 'lon'
    23271         AXinf['X'] = axv
    23272 
    23273         newdim['rlat'] = dy
    23274         newvar['rlat'] = ['grid_latitude', 'latitude in rotated pole grid', 'degrees']
    23275         ovar = getvar_listonc(projinf['fileYvals'][0], Fns, oncs)
    23276         oYvar = ovar[0]
    23277         if len(oYvar.shape) == 3:
    23278             newvarv['rlat'] = oYvar[0,0,:]
    23279         elif len(oYvar.shape) == 2:
    23280             newvarv['rlat'] = oYvar[0,:]
    23281         elif len(oYvar.shape) == 1:
    23282             newvarv['rlat'] = oYvar[:]
    23283         else:
    23284             print errormsg
    23285             print '  ' + fname + ": rank ", oYvar.shape, " of values for Y ref " +   \
    23286               "not ready !!"
    23287             quit(-1)
    23288         # updating values on axes
    23289         axv = AXinf['Y']
    23290         axv['dimn'] = 'rlat'
    23291         axv['vdimn'] = 'lat'
    23292         AXinf['Y'] = axv
    23293 
    23294     elif PROJn == "Mercator":
    23295         proj_attr = ["grid_mapping_name", "longitude_of_projection_origin",          \
    23296           "standard_parallel", 'x_resolution', 'y_resolution', 'proj_units']
    23297         # Removing the non-CF attributes
    23298         nonCFattr = ['x_resolution', 'y_resolution', 'proj_units']
    23299         for atn in proj_attr:
    23300             if not projinf.has_key(atn):
    23301                 print errormsg
    23302                 print '  ' + fname + ": to process projection '" + PROJn +           \
    23303                   "' is required to provide argument '" + atn + "' in the " +        \
    23304                   "'[projectfile]' !!"
    23305                 if projfileexpl.has_key(atn):
    23306                     print '    ', atn, ':', projfileexpl[atn]
    23307                 else:
    23308                     print '    ', atn, ': CF-attribute, please visit: ', CFprojweb
    23309                 print '    values provided:', projinf
    23310                 quit(-1)
    23311 
    23312         newdim = {}
    23313         newvar = {}
    23314         newvarv = {}
    23315 
    23316         newdim['x'] = dx
    23317         newvar['x'] = ['projection_x_coordinate', 'x coordinate of projection', 'km']
    23318         Xres = np.float(projinf['x_resolution'][0])
    23319         if projinf['proj_units'][0] == 'km':
    23320             scale = 1.
    23321         elif projinf['proj_units'][0] == 'm':
    23322             scale = 1000.
    23323         else:
    23324             print errormsg
    23325             print '  ' + fname + ": Resolution units '" + projinf['proj_units'][0] + \
    23326               "' not ready !!"
    23327             print '    available ones:', ['km', 'm']
    23328             quit(-1)
    23329         newvarv['x'] = (np.arange(1,dx+1)-dx/2)*Xres/scale
    23330         # updating values on axes
    23331         axv = AXinf['X']
    23332         axv['dimn'] = 'x'
    23333         axv['vdimn'] = 'lon'
    23334         AXinf['X'] = axv
    23335 
    23336         newdim['y'] = dy
    23337         newvar['y'] = ['projection_y_coordinate', 'y coordinate of projection', 'km']
    23338         Yres = np.float(projinf['y_resolution'][0])
    23339         newvarv['y'] = (np.arange(1,dy+1)-dy/2)*Yres/scale
    23340         # updating values on axes
    23341         axv = AXinf['Y']
    23342         axv['dimn'] = 'y'
    23343         axv['vdimn'] = 'lat'
    23344         AXinf['Y'] = axv
    23345 
    2334623163    else:
    2334723164        print errormsg
     
    2336223179    """
    2336323180    fname = 'CFvars'
    23364     inCFvarfile = 'CFvariables.dat'
    23365     availactions = ['new_z_dim']
     23181
     23182    availactions = ['new_p_dim','new_z_dim']
     23183
     23184    folder = os.path.dirname(os.path.realpath(__file__))
     23185    inCFvarfile = folder + '/' + 'CFvariables.dat'
    2336623186
    2336723187    oCFf = open(inCFvarfile, 'r')
     
    2367023490    allfileNs = {}
    2367123491    for ionc in range(len(allonc)):
    23672         onc = allonc[ionc]
    23673         allfileNs[afNs[ionc]] = [onc.dimensions.keys(), onc.variables.keys()]
     23492        oc = allonc[ionc]
     23493        allfileNs[afNs[ionc]] = [oc.dimensions.keys(), oc.variables.keys()]
    2367423494
    2367523495    # Creation of new file name
     
    2383723657        addCFdimvals = {}
    2383823658        for newdn in newDim.keys():
     23659            print infmsg
     23660            print '      ' + fname + ": adding dimension '" + newdn + "' ..."
    2383923661            addCFdimvals[newdn] = {'dimn': newdn, 'vdimn': newdn,                    \
    2384023662              'stdn': newVar[newdn][0], 'longname': newVar[newdn][1],                \
    2384123663              'units': newVar[newdn][2], 'maxrank': 1,                               \
    23842               'length': filedimvals['X'].shape[1]}
     23664              'length': newDim[newdn]}
    2384323665            filedimvals[newdn] = newVARv[newdn]
     23666            gen.printing_dictionary(addCFdimvals[newdn])
    2384423667
    2384523668    print 'Values for variables-axes from file ________'
     
    2389523718        utsvarn = varinf[5]
    2389623719
     23720        oncvars = onc.variables.keys()
     23721        oncvars.sort()
     23722
    2389723723        # getting variable from file
    2389823724        if not onc.variables.has_key(vn):
     
    2395223778                if not gen.searchInlist(onewnc.variables.keys(), dvals['dimn']):
    2395323779                    ddvals = addCFdimvals[dvals['dimn']]
    23954                     newvar = onewnc.createVariable(dvals['dimn'], 'f8',              \
    23955                       tuple(dvals['dimn']))
     23780                    newvar = onewnc.createVariable(ddvals['vdimn'], 'f8',            \
     23781                      tuple([ddvals['dimn']]))
    2395623782                    basicvardef(newvar, ddvals['stdn'], ddvals['longname'],          \
    2395723783                      ddvals['units'])
    23958                     newvar[:] = filedimvals[dvals['dimn']]
     23784                    newvar[:] = filedimvals[ddvals['dimn']]
    2395923785                if not gen.searchInlist(onewnc.variables.keys(), dvals['vdimn']):
    2396023786                    newvar = onewnc.createVariable(dvals['vdimn'], 'f4',             \
     
    2396723793                          ivn != 'units' and ivn != 'maxrank' and ivn != 'length':
    2396823794                            set_attribute(newvar,ivn,dvals[ivn])
     23795            onewnc.sync()
    2396923796
    2397023797        # Variable
Note: See TracChangeset for help on using the changeset viewer.