当前位置: 首页>>代码示例>>Python>>正文


Python Dataset.variables[name][:]方法代码示例

本文整理汇总了Python中netCDF4.Dataset.variables[name][:]方法的典型用法代码示例。如果您正苦于以下问题:Python Dataset.variables[name][:]方法的具体用法?Python Dataset.variables[name][:]怎么用?Python Dataset.variables[name][:]使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在netCDF4.Dataset的用法示例。


在下文中一共展示了Dataset.variables[name][:]方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: add_vars_to_file

# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import variables[name][:] [as 别名]
def add_vars_to_file(f1,f2,inputvars,inputatts,varnames,outputdir,output_sub,func,output_prefix):
    '''Add the list of data (inputvars) and names (varnames) to file (filename)
    
    Note: the dimensions of the inputvars must match some existing 
          dimension in the input file. 
    
    filename is the name of an existing netcdf file
    input vars is a list of numpy arrays
    varnames is a list of strings 
    output_prefix = prefix to be added to the new filename
            default is "added_"

    A new file will be created titled: output_prefix+filename
    '''
    outputfilename=output_prefix+f1.split("/")[-1]
    for i in range(len(output_sub)):
        outputfilename=outputfilename.replace(output_sub[i][0],output_sub[i][1])
    # outputfilename=outputfilename.strip(".nc") #strip off the .nc term first... 
    # only strip .nc for nio, netCDF4 expects you to insert the nc
    
    # if there wasn't a directory specified, make sure we aren't specifying "/"
    # if not outputdir:
    #     if len(f1.split("/"))>1:
    #         outputdir="/".join(f1.split("/")[:-1])+"/"
    #     else:
    #         outputdir=""
    # if there wasn't a directory specified, make sure we aren't specifying "/"
    if len(outputdir)==1:
        outputdir=""
    outputf=Dataset(outputdir+outputfilename, 'w',format="NETCDF4")
    inputf1=Dataset(f1, 'r')
    inputf2=Dataset(f2, 'r')
    
    maxlen=0
    # loop over the input variables finding the maximum number of 
    # dimensions we need to know about
    for d in inputvars:
        maxlen=max(maxlen,len(d.shape))
    
    # create an array to hold the references to the dimensions corresponding
    #  to the dimensions of each input variable
    outputdims=np.empty((len(inputvars),maxlen),dtype="S16")
    if len(outputdims.shape)==1:
        outputdims=outputdims.reshape((outputdims.shape[0],1))
    
    dimnum=0
    # loop over the dimensions in the input file
    for i,dim in enumerate(inputf1.dimensions.keys()):
        dimlen=len(inputf1.dimensions[dim]) #in netCDF4python parlence we need a len() around dimension (?)
                                            # for Nio change len above to int
        
        # create that dimension in the outputfile too
        outputf.createDimension(dim,dimlen) #Nio=create_dimension
        # find any input variables that match this dimension
        for j,thisvar in enumerate(inputvars):
            finddim=np.where(np.array(thisvar.shape)==dimlen)
            if len(finddim[0])>0:
                # if we found a match
                # save the dimension in the output dims array
                for k in finddim[0]:
                    outputdims[j,k]=dim
    
    i=0
    # copy the requested variables into the file
    for v,atts,name in zip(inputvars,inputatts,varnames):
        # create the variable
        outputf.createVariable(name,"f",tuple(outputdims[i,:len(v.shape)])) #Nio=create_variable
        # store the data
        outputf.variables[name][:]=v.astype("f")
        outputf.variables[name].setncatts(atts)
        i+=1
        
    # finally, combine the requested variables from the input files to the output file
    v1=output_sub[0][0]
    v2=output_sub[1][0]
    vout=output_sub[0][1]
    thisvar=inputf1.variables[v1]
    var1=thisvar[:]
    var2=inputf2.variables[v2][:]
    
    outputvar=func([var1,var2])
    # create the variable, dimensions and typecode are identical to the input file
    outputf.createVariable(str(vout),thisvar.dtype,thisvar.dimensions) #Nio=create_variable, dtype=typecode()
    # copy the data over
    outputf.variables[str(vout)][:]=outputvar
            
    
    inputf1.close()
    inputf2.close()
    outputf.close()
开发者ID:gutmann,项目名称:scripted_sufferin_succotash,代码行数:92,代码来源:combine_nc_vars.py

示例2: add_vars_to_file

# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import variables[name][:] [as 别名]
def add_vars_to_file(filename,inputvars,varnames,output_prefix="added_"):
    '''Add the list of data (inputvars) and names (varnames) to file (filename)
    
    Note: the dimensions of the inputvars must match some existing 
          dimension in the input file. 
    
    filename is the name of an existing netcdf file
    input vars is a list of numpy arrays
    varnames is a list of strings 
    output_prefix = prefix to be added to the new filename
            default is "added_"

    A new file will be created titled: output_prefix+filename
    '''
    outputfilename=output_prefix+filename.split("/")[-1]
    outputfilename=outputfilename.strip(".nc") #strip off the .nc term first
    # if there wasn't a directory specified, make sure we aren't specifying "/"
    if len(filename.split("/"))>1:
        outputdir="/".join(filename.split("/")[:-1])+"/"
    else:
        outputdir=""
    # if there wasn't a directory specified, make sure we aren't specifying "/"
    if len(outputdir)==1:
        outputdir=""
    outputf=Dataset(outputdir+outputfilename, 'w',format="nc")
    inputf=Dataset(filename, 'r')
    maxlen=0
    # loop over the input variables finding the maximum number of 
    # dimensions we need to know about
    for d in inputvars:
        maxlen=max(maxlen,len(d.shape))
    # create an array to hold the references to the dimensions corresponding
    #  to the dimensions of each input variable
    outputdims=np.array((len(inputvars),maxlen),dtype="S16")
    if len(outputdims.shape)==1:
        outputdims=outputdims.reshape((outputdims.shape[0],1))
    dimnum=0
    # loop over the dimensions in the input file
    for i,dim in enumerate(inputf.dimensions.keys()):
        dimlen=int(inputf.dimensions[dim]) #in netCDF4python parlence we need a len() around dimension (?)
        
        # create that dimension in the outputfile too
        outputf.create_dimension(dim,dimlen)
        # find any input variables that match this dimension
        for j,thisvar in enumerate(inputvars):
            finddim=np.where(np.array(thisvar.shape)==dimlen)
            if len(finddim[0])>0:
                # if we found a match
                # save the dimension in the output dims array
                for k in finddim[0]:
                    outputdims[j,k]=dim

    # loop through the existing variables in the input file
    # copying them to the output file (originally allowed subsetting in time)
    for v in inputf.variables:
        thisvar=inputf.variables[v]
        # create the variable
        outputf.create_variable(str(v),thisvar.typecode(),thisvar.dimensions)
        # copy the data over
        outputf.variables[str(v)][:]=inputf.variables[v][:]
            
    i=0
    # finally copy the new variables into the file as well
    for v,name in zip(inputvars,varnames):
        # create the variable
        outputf.create_variable(name,"f",tuple(outputdims[i,:len(v.shape)]))
        # store the data
        outputf.variables[name][:]=v.astype("f")
        i+=1
    
    inputf.close()
    outputf.close()
开发者ID:gutmann,项目名称:scripted_sufferin_succotash,代码行数:74,代码来源:nc_addvars.py

示例3: tides2nc

# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import variables[name][:] [as 别名]
    def tides2nc(self,outfile):
        """
        Saves the tidal harmonic data to netcdf
        """
        
        # Write the grid variables
        self.writeNC(outfile)

        nc = Dataset(outfile,'a')
        
        nc.Title = 'SUNTANS harmonic output'
        nc.Constituent_Names = ' '.join(self.frqnames)
        reftime = datetime.strftime(self.reftime,'%Y-%m-%d %H:%M:%S')
        nc.ReferenceDate = reftime
        nc.SimulationTime = '%s - %s'%(datetime.strftime(self.time[self.tstep[0]],'%Y-%m-%d %H:%M:%S'),datetime.strftime(self.time[self.tstep[-1]],'%Y-%m-%d %H:%M:%S'))
        # Add another dimension
        nc.createDimension('Ntide', self.Ntide)
        
        
        nc.close()
        
        # Create the output variables
        for vv in self.varnames:
            print 'Creating variable: %s'%vv

            ndim = self._returnDim(vv)
            if ndim == 2:
                dims = ('Ntide','Nc')
                coords = 'omega xv yv'
            elif ndim == 3:
                dims = ('Ntide','Nk','Nc')
                coords = 'omega z_r xv yv'	

            if vv in ['ubar','vbar']:
                units='m s-1'
            else:
                units = self.nc.variables[vv].units

            name = vv+'_amp'
            longname = '%s - harmonic amplitude'%vv
            self.create_nc_var(outfile, name, dims,\
                {'long_name':longname,'units':units,'coordinates':coords},\
                dtype='f8',zlib=1,complevel=1,fill_value=999999.0)
                
            name = vv+'_phs'
            longname = '%s - harmonic phase'%vv
            self.create_nc_var(outfile, name, dims,\
                {'long_name':longname,'units':'radians','coordinates':coords,'reference_time':reftime},\
                dtype='f8',zlib=1,complevel=1,fill_value=999999.0)
                
            ndim = self._returnDim(vv)
            if ndim == 2:
                dims = ('Nc')
                coords = 'omega xv yv'
            elif ndim == 3:
                dims = ('Nk','Nc')
                coords = 'omega z_r xv yv'
                
            name = vv+'_Mean'
            longname = '%s - Temporal mean'%vv
            self.create_nc_var(outfile, name, dims,\
                {'long_name':longname,'units':units,'coordinates':coords},\
                dtype='f8',zlib=1,complevel=1,fill_value=999999.0)
        
        self.create_nc_var(outfile,'omega', ('Ntide',), {'long_name':'frequency','units':'rad s-1'})
        
        nc = Dataset(outfile,'a')
        nc.variables['omega'][:]=self.frq
        
        for vv in self.varnames:
            name = vv+'_amp'
            nc.variables[name][:]=self.Amp[vv]
            name = vv+'_phs'
            nc.variables[name][:]=self.Phs[vv]
            name = vv+'_Mean'
            nc.variables[name][:]=self.Mean[vv]
        nc.close()        
        
        print 'Completed writing harmonic output to:\n   %s'%outfile
开发者ID:ofringer,项目名称:suntanspy,代码行数:81,代码来源:suntides.py

示例4: tides2nc

# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import variables[name][:] [as 别名]
    def tides2nc(self, outfile):
        """
        Saves the tidal harmonic data to netcdf
        """

        # Write the grid variables
        self.writeNC(outfile)

        nc = Dataset(outfile, "a")

        nc.Title = "SUNTANS harmonic output"
        nc.Constituent_Names = " ".join(self.frqnames)
        reftime = datetime.strftime(self.reftime, "%Y-%m-%d %H:%M:%S")
        nc.ReferenceDate = reftime
        nc.SimulationTime = "%s - %s" % (
            datetime.strftime(self.time[self.tstep[0]], "%Y-%m-%d %H:%M:%S"),
            datetime.strftime(self.time[self.tstep[-1]], "%Y-%m-%d %H:%M:%S"),
        )
        # Add another dimension
        nc.createDimension("Ntide", self.Ntide)

        nc.close()

        # Create the output variables
        for vv in self.varnames:
            print "Creating variable: %s" % vv

            ndim = self._returnDim(vv)
            if ndim == 2:
                dims = ("Ntide", "Nc")
                coords = "omega xv yv"
            elif ndim == 3:
                dims = ("Ntide", "Nk", "Nc")
                coords = "omega z_r xv yv"

            if vv in ["ubar", "vbar"]:
                units = "m s-1"
            else:
                units = self.nc.variables[vv].units

            name = vv + "_amp"
            longname = "%s - harmonic amplitude" % vv
            self.create_nc_var(
                outfile,
                name,
                dims,
                {"long_name": longname, "units": units, "coordinates": coords},
                dtype="f8",
                zlib=1,
                complevel=1,
                fill_value=999999.0,
            )

            name = vv + "_phs"
            longname = "%s - harmonic phase" % vv
            self.create_nc_var(
                outfile,
                name,
                dims,
                {"long_name": longname, "units": "radians", "coordinates": coords, "reference_time": reftime},
                dtype="f8",
                zlib=1,
                complevel=1,
                fill_value=999999.0,
            )

            ndim = self._returnDim(vv)
            if ndim == 2:
                dims = "Nc"
                coords = "omega xv yv"
            elif ndim == 3:
                dims = ("Nk", "Nc")
                coords = "omega z_r xv yv"

            name = vv + "_Mean"
            longname = "%s - Temporal mean" % vv
            self.create_nc_var(
                outfile,
                name,
                dims,
                {"long_name": longname, "units": units, "coordinates": coords},
                dtype="f8",
                zlib=1,
                complevel=1,
                fill_value=999999.0,
            )

        self.create_nc_var(outfile, "omega", ("Ntide",), {"long_name": "frequency", "units": "rad s-1"})

        nc = Dataset(outfile, "a")
        nc.variables["omega"][:] = self.frq

        for vv in self.varnames:
            name = vv + "_amp"
            nc.variables[name][:] = self.Amp[vv]
            name = vv + "_phs"
            nc.variables[name][:] = self.Phs[vv]
            name = vv + "_Mean"
            nc.variables[name][:] = self.Mean[vv]
        nc.close()
#.........这里部分代码省略.........
开发者ID:mrayson,项目名称:soda,代码行数:103,代码来源:suntides.py


注:本文中的netCDF4.Dataset.variables[name][:]方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。