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


Python Dataset.sync方法代码示例

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


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

示例1: main

# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import sync [as 别名]
def main():

	os.system('clear')
	input_filename='input_files/Isomip_ice_geometry.nc'
	new_filename='output_files/ISOMIP_MIB.nc'

	#f=Dataset(input_geometry_filename,'r')
	#g=Dataset(new_filename,'w') # w if for creating a file

	rho_ice=850.

	with nc.Dataset(input_filename) as file:
		ocean_mask = file.variables['openOceanMask'][:,:]
		upperSurface = file.variables['upperSurface'][:,:]
		lowerSurface = file.variables['lowerSurface'][:,:]
		h_ice=upperSurface-lowerSurface
		mass=h_ice*rho_ice
		x = file.variables['x'][:]
		y = file.variables['y'][:]


	M= mass.shape
	ny=M[0]
	nx=M[1]
	print nx,ny
	print mass.shape

	#subsampling data onto a grid half the size
	MIB=np.zeros((ny/2,nx/2))
	print MIB.shape
	for i in range(0,nx,2):
		for j in range(0,ny,2):
			MIB[j/2,i/2]=mass[j,i]

	
	#Creating the topog file
	g=Dataset(new_filename,'w') # w if for creating a file

	time=g.createDimension('time',1)
	yt=g.createDimension('yt',ny)
	xt=g.createDimension('xt',nx)

	mass_h=g.createVariable('mass','f4',('time','yt','xt'))
	g.variables['mass'][:]=mass

	#Creating subsampled version
	yh=g.createDimension('yh',ny/2)
	xh=g.createDimension('xh',nx/2)
	MIB_h=g.createVariable('MIB','f4',('time','yh','xh'))
	g.variables['MIB'][:]=MIB


	g.sync()
	g.close()





	print 'Script complete'
开发者ID:sternalon,项目名称:Scripts_and_analysis,代码行数:62,代码来源:iceshelf_mass_file_create.py

示例2: setUp

# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import sync [as 别名]
    def setUp(self):
        self.nc_names = [
            os.path.join(
                'test', 'data', 'tmp',
                'jempatmdu_000{}_map.nc'.format(i)
            )
            for i in range(4)
        ]
        tmpdir = os.path.join('test', 'data', 'tmp')
        if os.path.exists(tmpdir):
            shutil.rmtree(tmpdir)

        os.mkdir(tmpdir)

        # on inspection found all the relevant vars are not also ds
        for idx, name in enumerate(self.nc_names):

            nc = Dataset(name, 'w')

            nc.createDimension('nFlowElem', 8)
            nc.createVariable('FlowElem_xcc', float, ('nFlowElem',))
            nc.createVariable('FlowElem_ycc', float, ('nFlowElem',))
            nc.createVariable('FlowElemDomain', float, ('nFlowElem',))
            nc.createVariable('taus', float, ('nFlowElem',))

            vars_ = nc.variables
            # TODO fill in variables
            if idx == 0:
                vars_['FlowElemDomain'][:] = [0, 0, 0, 0, 1, 2, 2, 3]
                vars_['FlowElem_xcc'][:] =\
                    [32.3, 34.5, 36.7, 38.1, 48.3, 33.3, 2.1, 1.0]
                vars_['FlowElem_ycc'][:] =\
                    [132.3, 134.5, 136.7, 138.1, 8.3, 133.3, 12.1, 111.0]

            elif idx == 1:
                vars_['FlowElemDomain'][:] = [0, 1, 1, 1, 1, 2, 2, 3]
                vars_['FlowElem_xcc'][:] =\
                    [32.3, 39.255, 40.25, 40.55, 41.1, 123.3, 4.1, 5.0]
                vars_['FlowElem_ycc'][:] =\
                    [232.3, 139.255, 140.25, 140.55, 141.1, 138.1, 8.3, 133.3]

            elif idx == 2:
                vars_['FlowElemDomain'][:] = [0, 1, 2, 2, 2, 2, 3, 3]
                vars_['FlowElem_xcc'][:] =\
                    [32.3, 29.255, 42.2, 43.01, 44.2, 45.5, 14.1, 52.1]
                vars_['FlowElem_ycc'][:] =\
                    [232.3, 139.255, 142.2, 143.01, 144.2, 145.5, 8.3, 133.3]

            elif idx == 3:
                vars_['FlowElemDomain'][:] = [1, 1, 1, 2, 3, 3, 3, 3]
                vars_['FlowElem_xcc'][:] =\
                    [32.3, 29.255, 42.2, 43.01, 49.2, 50.7, 51.6, 52.2]
                vars_['FlowElem_ycc'][:] =\
                    [232.3, 139.255, 142.2, 143.01, 149.2, 150.7, 151.6, 152.2]

            vars_['taus'][:] = np.arange(8) * (idx + 1)

            # seemed like this was unnecessary, but it's better practice
            nc.sync()
            nc.close()
开发者ID:VirtualWatershed,项目名称:CoRD,代码行数:62,代码来源:test_cord.py

示例3: make_scalar_vars_ismip6_conforming

# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import sync [as 别名]
def make_scalar_vars_ismip6_conforming(filename, ismip6_vars_dict):
    '''
    Make file ISMIP6 conforming
    '''
    
    # Open file
    nc = CDF(filename, 'a')

    pism_to_ismip6_dict = dict((v.pism_name, k) for k, v in ismip6_vars_dict.iteritems())
    
    for pism_var in nc.variables:
        nc_var = nc.variables[pism_var]
        if pism_var in pism_to_ismip6_dict.keys():
            ismip6_var = pism_to_ismip6_dict[pism_var]
            print('Processing {} / {}'.format(pism_var, ismip6_var))
            if not pism_var == ismip6_var:
                print('  Renaming {pism_var} to {ismip6_var}'.format(pism_var=pism_var, ismip6_var=ismip6_var))
                nc.renameVariable(pism_var, ismip6_var)
                nc.sync()
            if not nc_var.units == ismip6_vars_dict[ismip6_var].units:
                o_units = ismip6_vars_dict[ismip6_var].units            
                i_units = nc_var.units
                print('  Converting {pism_var} from {i_units} to {o_units}'.format(pism_var=pism_var, i_units=i_units, o_units=o_units))    
                i_f = cf_units.Unit(i_units)
                o_f = cf_units.Unit(o_units)
                nc_var[:] = i_f.convert(nc_var[:], o_f)
                nc_var.units = o_units
                nc_var.standard_name = ismip6_vars_dict[ismip6_var].standard_name
    nc.close()
开发者ID:pism,项目名称:initMIP,代码行数:31,代码来源:resources_ismip6.py

示例4: getoutfile

# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import sync [as 别名]
def getoutfile(metpath, outpath, ntimes):
    """
    Requires
        metpath - path to METCRO2D file
        outpath - path for output file
    Returns
        open NetCDF output file
    """
    os.system('ncks -O -dVAR,0 -vRN,TFLAG  %s mettemp.nc' % metpath)
    os.system('ncdump -vTFLAG mettemp.nc > mettemp.cdl')
    os.system('sed -E -e \'s/VAR-LIST = .*/VAR-LIST = "NMF             ";/\' -e "s/RN/NMF/g" -e \'s/units = "CM      /units = "fraction/g\' -e \'s/nonconvec. pcpn per met TSTEP/natural mitigation factor/g\' mettemp.cdl > nmf.cdl')
    os.system('ncgen -o %s  nmf.cdl' % outpath)
    outf = Dataset(outpath, 'a')
    outf.NVARS = 1
    tflag = outf.variables['TFLAG']
    sdate = outf.SDATE
    stime = outf.STIME
    datestart = datetime.datetime.strptime('%d %06d' % (sdate, stime), '%Y%j %H%M%S')
    for ti in range(ntimes):
        #datenow = datetime.time(hours = ti)
        datenow = datestart + datetime.timedelta(hours = ti)
        tflag[ti, 0, :] = int(datenow.strftime('%Y%j')), int(datenow.strftime('%H%M%S'))
        #tflag[ti, 0, :] = int(datenow.strfdelta('%Y%j')), int(datenow.strfdelta('%H%M%S'))
    outf.sync()    
    return outf 
开发者ID:mpperezp,项目名称:RPM_MITIGATION,代码行数:27,代码来源:PAVED_p(x,t).py

示例5: wrf_sgrid_2d

# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import sync [as 别名]
def wrf_sgrid_2d(fname='tmp_sgrid_wrf_2.nc'):
    nc = Dataset(fname, 'w')
    nc.createDimension('Time', 2)
    nc.createDimension('DateStrLen', 3)
    nc.createDimension('west_east', 4)
    nc.createDimension('south_north', 5)
    nc.createDimension('west_east_stag', 5)
    nc.createDimension('bottom_top', 3)
    nc.createDimension('south_north_stag', 6)
    nc.createDimension('bottom_top_stag', 4)
    times = nc.createVariable('Times', np.dtype(str), ('Time', 'DateStrLen'))  # noqa
    xtimes = nc.createVariable('XTIME', 'f8', ('Time', ))
    us = nc.createVariable('U', 'f4', ('Time', 'bottom_top', 'south_north', 'west_east_stag'))  # noqa
    us.grid = 'grid'
    us.location = 'edge1'
    fake_u = nc.createVariable('FAKE_U', 'f4', ('Time', 'bottom_top', 'south_north', 'west_east_stag'))  # noqa
    fake_u.grid = 'grid'
    vs = nc.createVariable('V', 'f4', ('Time', 'bottom_top', 'south_north_stag', 'west_east'))  # noqa
    vs.grid = 'grid'
    vs.location = 'edge2'
    ws = nc.createVariable('W', 'f4', ('Time', 'bottom_top_stag', 'south_north', 'west_east'))  # noqa
    ws.grid = 'grid'
    ws.location = 'face'
    temps = nc.createVariable('T', 'f4', ('Time', 'bottom_top', 'south_north', 'west_east'))  # noqa
    temps.grid = 'grid'
    temps.location = 'face'
    snow = nc.createVariable('SNOW', 'f4', ('Time', 'south_north', 'west_east'))  # noqa
    snow.grid = 'grid'
    xlats = nc.createVariable('XLAT', 'f4', ('south_north', 'west_east'))
    xlongs = nc.createVariable('XLONG', 'f4', ('south_north', 'west_east'))
    znus = nc.createVariable('ZNU', 'f4', ('Time', 'bottom_top'))
    znws = nc.createVariable('ZNW', 'f4', ('Time', 'bottom_top_stag'))
    xtimes.standard_name = 'time'
    grid = nc.createVariable('grid', 'i2')
    grid.cf_role = 'grid_topology'
    grid.topology_dimension = 2
    grid.node_dimensions = 'west_east_stag south_north_stag'
    grid.face_dimensions = ('west_east: west_east_stag (padding: none) '
                            'south_north: south_north_stag (padding: none)'
                            )
    grid.face_coordinates = 'XLONG XLAT'
    grid.vertical_dimensions = 'bottom_top: bottom_top_stag (padding: none)'  # noqa
    grid.edge1_dimensions = 'west_east_stag south_north: south_north_stag (padding: none)'  # noqa
    grid.edge2_dimensions = 'west_east: west_east_stag (padding: none) south_north_stag'  # noqa
    times[:] = np.random.random(size=(2, 3)).astype(str)
    xtimes[:] = np.random.random(size=(2,))
    us[:, :, :, :] = np.random.random(size=(2, 3, 5, 5))
    fake_u[:, :, :, :] = np.random.random(size=(2, 3, 5, 5))
    vs[:, :, :, :] = np.random.random(size=(2, 3, 6, 4))
    ws[:, :, :, :] = np.random.random(size=(2, 4, 5, 4))
    temps[:, :, :, :] = np.random.random(size=(2, 3, 5, 4))
    snow[:, :, :] = np.random.random(size=(2, 5, 4))
    xlats[:, :] = np.random.random(size=(5, 4))
    xlongs[:, :] = np.random.random(size=(5, 4))
    znus[:, :] = np.random.random(size=(2, 3))
    znws[:, :] = np.random.random(size=(2, 4))
    nc.sync()
    yield nc
    nc.close()
    os.remove(fname)
开发者ID:ChrisBarker-NOAA,项目名称:pysgrid,代码行数:62,代码来源:write_nc_test_files.py

示例6: wa_from_div

# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import sync [as 别名]
def wa_from_div(options):
    data=Dataset(options.in_file)
    output=Dataset(options.out_file,'w')
    replicate_netcdf_file(output,data)

    #Retrieve data and create output:
    vars_space=dict()
    for var in ['div','wa']:
        if var=='wa': replicate_netcdf_var(output,data,var)
        vars_space[var]=data.variables[var][:,:,:,:].astype(np.float,copy=False)
    for var in ['mass']:
        vars_space[var]=(data.variables[var][1:,:,:,:].astype(np.float,copy=False) -
                         data.variables[var][:-1,:,:,:].astype(np.float,copy=False))
    
    data.close()
    
    #Compute the mass divergence:
    DIV = vars_space['mass'] + vars_space['div']
    vars_space['wa'][:,1:,...]=-np.cumsum(np.ma.array(DIV).anom(1),axis=1) 
    #vars_space['wa'][1:-1,1:,:]=np.ma.array(DIV).anom(0) 
    vars_space['wa'][:,0,...]=0.0
    for var in ['wa']:
        output.variables[var][:]=vars_space[var]

    output.sync()
    output.close()
    return
开发者ID:laliberte,项目名称:pydiv,代码行数:29,代码来源:pydiv.py

示例7: create_awips2_netcdf3

# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import sync [as 别名]
def create_awips2_netcdf3(filename, image, start_dt,
                          depictor_name, channel, source_name, satellite_name,
                          **grid_info):
    nc_name = os.path.abspath(filename)
    nc = Dataset(nc_name, mode='w', format="NETCDF3_CLASSIC")
    y_dim = nc.createDimension("y", size=image.shape[0])
    x_dim = nc.createDimension("x", size=image.shape[1])

    time_var = nc.createVariable("validTime", "f8")
    time_var.units = "seconds since 1970-1-1 00:00:00.00 0:00"
    time_var[:] = float(calendar.timegm(start_dt.utctimetuple())) + float(start_dt.microsecond)/1e6

    image_var = nc.createVariable("image", "i1", ("y", "x"))
    image_var.set_auto_maskandscale(False)
    image_var[:] = clip_to_data_type(image, DTYPE_UINT8)

    nc.depictorName = depictor_name
    nc.channel = channel
    nc.source = source_name
    nc.satelliteName = satellite_name

    for k, v in grid_info.items():
        attr_name = GRID_ATTR_NAME.get(k, k)
        attr_type = GRID_ATTR_TYPE.get(k, None)
        LOG.debug("Setting grid information for NetCDF file: %s -> %s", attr_name, v)
        if attr_type is not None:
            v = attr_type(v)
        setattr(nc, attr_name, v)

    nc.sync()
    nc.close()
    LOG.debug("Data transferred into NC file correctly")
开发者ID:huangynj,项目名称:polar2grid,代码行数:34,代码来源:awips_netcdf.py

示例8: create_clipped_icethickness_file

# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import sync [as 别名]
def create_clipped_icethickness_file(h_ice,area,mass,grid_area,gravity,New_ice_thickness_filename):
	#Creating clipped file
        [ny, nx]= h_ice.shape ; 
	
        g=Dataset(New_ice_thickness_filename,'w') # w if for creating a file

        g.createDimension('nx',nx)
        g.createDimension('ny',ny)

        thick_h=g.createVariable('thick','f8',('ny','nx'))
        area_h=g.createVariable('area','f8',('ny','nx'))
        p_surf_h=g.createVariable('p_surf','f8',('ny','nx'))

        thick_h.units = 'm'
        thick_h.standard_name = 'ice shelf thickness (clipped)'
        area_h.units = 'm2'
        area_h.standard_name = 'ice shelf area'
        p_surf_h.units = 'Pa'
        p_surf_h.standard_name = 'surface pressure due to ice shelf'

	p_surf=(gravity*mass)/grid_area
        g.variables['thick'][:]=h_ice
        g.variables['area'][:]=area
        g.variables['p_surf'][:]=p_surf
        print 'Creating clipped ice file: ' , New_ice_thickness_filename
        
        g.sync()
        g.close()
开发者ID:sternalon,项目名称:Scripts_and_analysis,代码行数:30,代码来源:create_thickness_file.py

示例9: wrf_sgrid

# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import sync [as 别名]
def wrf_sgrid():
    fname = tempfile.mktemp(suffix=".nc")
    nc = Dataset(fname, "w")
    nc.createDimension("Time", 2)
    nc.createDimension("DateStrLen", 3)
    nc.createDimension("west_east", 4)
    nc.createDimension("south_north", 5)
    nc.createDimension("west_east_stag", 5)
    nc.createDimension("bottom_top", 3)
    nc.createDimension("south_north_stag", 6)
    nc.createDimension("bottom_top_stag", 4)
    times = nc.createVariable("Times", np.dtype(str), ("Time", "DateStrLen"))  # noqa
    xtimes = nc.createVariable("XTIME", "f8", ("Time",))
    us = nc.createVariable("U", "f4", ("Time", "bottom_top", "south_north", "west_east_stag"))  # noqa
    us.grid = "grid"
    us.location = "edge1"
    fake_u = nc.createVariable("FAKE_U", "f4", ("Time", "bottom_top", "south_north", "west_east_stag"))  # noqa
    fake_u.grid = "grid"
    vs = nc.createVariable("V", "f4", ("Time", "bottom_top", "south_north_stag", "west_east"))  # noqa
    vs.grid = "grid"
    vs.location = "edge2"
    ws = nc.createVariable("W", "f4", ("Time", "bottom_top_stag", "south_north", "west_east"))  # noqa
    ws.grid = "grid"
    ws.location = "face"
    temps = nc.createVariable("T", "f4", ("Time", "bottom_top", "south_north", "west_east"))  # noqa
    temps.grid = "grid"
    temps.location = "face"
    snow = nc.createVariable("SNOW", "f4", ("Time", "south_north", "west_east"))  # noqa
    snow.grid = "grid"
    xlats = nc.createVariable("XLAT", "f4", ("south_north", "west_east"))
    xlongs = nc.createVariable("XLONG", "f4", ("south_north", "west_east"))
    znus = nc.createVariable("ZNU", "f4", ("Time", "bottom_top"))
    znws = nc.createVariable("ZNW", "f4", ("Time", "bottom_top_stag"))
    xtimes.standard_name = "time"
    grid = nc.createVariable("grid", "i2")
    grid.cf_role = "grid_topology"
    grid.topology_dimension = 2
    grid.node_dimensions = "west_east_stag south_north_stag"
    grid.face_dimensions = "west_east: west_east_stag (padding: none) " "south_north: south_north_stag (padding: none)"
    grid.face_coordinates = "XLONG XLAT"
    grid.vertical_dimensions = "bottom_top: bottom_top_stag (padding: none)"  # noqa
    grid.edge1_dimensions = "west_east_stag south_north: south_north_stag (padding: none)"  # noqa
    grid.edge2_dimensions = "west_east: west_east_stag (padding: none) south_north_stag"  # noqa
    times[:] = np.random.random(size=(2, 3)).astype(str)
    xtimes[:] = np.random.random(size=(2,))
    us[:, :, :, :] = np.random.random(size=(2, 3, 5, 5))
    fake_u[:, :, :, :] = np.random.random(size=(2, 3, 5, 5))
    vs[:, :, :, :] = np.random.random(size=(2, 3, 6, 4))
    ws[:, :, :, :] = np.random.random(size=(2, 4, 5, 4))
    temps[:, :, :, :] = np.random.random(size=(2, 3, 5, 4))
    snow[:, :, :] = np.random.random(size=(2, 5, 4))
    xlats[:, :] = np.random.random(size=(5, 4))
    xlongs[:, :] = np.random.random(size=(5, 4))
    znus[:, :] = np.random.random(size=(2, 3))
    znws[:, :] = np.random.random(size=(2, 4))
    nc.sync()
    yield nc
    nc.close()
    os.remove(fname)
开发者ID:NOAA-ORR-ERD,项目名称:pysgrid,代码行数:61,代码来源:write_nc_test_files.py

示例10: wrf_sgrid

# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import sync [as 别名]
def wrf_sgrid(fname='tmp_sgrid_wrf.nc'):
    """
    Write an SGrid file using 3D conventions.

    """
    nc = Dataset(fname, 'w')
    # Create dimensions.
    nc.createDimension('Time', 2)
    nc.createDimension('DateStrLen', 3)
    nc.createDimension('west_east', 4)
    nc.createDimension('south_north', 5)
    nc.createDimension('west_east_stag', 5)
    nc.createDimension('bottom_top', 3)
    nc.createDimension('south_north_stag', 6)
    nc.createDimension('bottom_top_stag', 4)
    # Create variables.
    times = nc.createVariable('Times', np.dtype(str), ('Time', 'DateStrLen'))  # noqa
    xtimes = nc.createVariable('XTIME', 'f8', ('Time',))
    xtimes.standard_name = 'time'
    us = nc.createVariable('U', 'f4', ('Time', 'bottom_top', 'south_north', 'west_east_stag'))  # noqa
    us.grid = 'grid'
    us.location = 'face1'
    vs = nc.createVariable('V', 'f4', ('Time', 'bottom_top', 'south_north_stag', 'west_east'))  # noqa
    vs.grid = 'grid'
    vs.location = 'face2'
    ws = nc.createVariable('W', 'f4', ('Time', 'bottom_top_stag', 'south_north', 'west_east'))  # noqa
    ws.grid = 'grid'
    ws.location = 'face3'
    temps = nc.createVariable('T', 'f4', ('Time', 'bottom_top', 'south_north', 'west_east'))  # noqa
    temps.grid = 'grid'
    temps.location = 'volume'
    xlats = nc.createVariable('XLAT', 'f4', ('Time', 'south_north', 'west_east'))  # noqa
    xlongs = nc.createVariable('XLONG', 'f4', ('Time', 'south_north', 'west_east'))  # noqa
    znus = nc.createVariable('ZNU', 'f4', ('Time', 'bottom_top'))
    znws = nc.createVariable('ZNW', 'f4', ('Time', 'bottom_top_stag'))
    grid = nc.createVariable('grid', 'i2')
    grid.cf_role = 'grid_topology'
    grid.topology_dimension = 3
    grid.node_dimensions = 'west_east_stag south_north_stag bottom_top_stag'  # noqa
    grid.volume_dimensions = ('west_east: west_east_stag (padding: none) '
                                'south_north: south_north_stag (padding: none) '  # noqa
                                'bottom_top: bottom_top_stag (padding: none)')  # noqa
    grid.volume_coordinates = 'XLONG XLAT ZNU'
    # create fake data
    times[:] = np.random.random(size=(2, 3)).astype(str)
    xtimes[:] = np.random.random(size=(2,))
    us[:, :, :, :] = np.random.random(size=(2, 3, 5, 5))
    vs[:, :, :, :] = np.random.random(size=(2, 3, 6, 4))
    ws[:, :, :, :] = np.random.random(size=(2, 4, 5, 4))
    temps[:, :, :, :] = np.random.random(size=(2, 3, 5, 4))
    xlats[:, :, :] = np.random.random(size=(2, 5, 4))
    xlongs[:, :, :] = np.random.random(size=(2, 5, 4))
    znus[:, :] = np.random.random(size=(2, 3))
    znws[:, :] = np.random.random(size=(2, 4))
    nc.sync()
    yield nc
    nc.close()
    os.remove(fname)
开发者ID:ChrisBarker-NOAA,项目名称:pysgrid,代码行数:60,代码来源:write_nc_test_files.py

示例11: NCDump

# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import sync [as 别名]
class NCDump(object):
    def __init__(self, output_filename, message_data):

        self.message_data = message_data

        # dump the data in netcdf
        logger.debug('Ready to go.')
        logger.debug('Dumping to netcdf...')
        self.ncfile = Dataset(output_filename, 'w', format='NETCDF3_CLASSIC')

        x_dim = self.ncfile.createDimension(
            'x', self.message_data.grid['quad_grid'].shape[0])
        y_dim = self.ncfile.createDimension(
            'y', self.message_data.grid['quad_grid'].shape[1])
        i_dim = self.ncfile.createDimension(
            'i', None)   # random index, for wkt
        i_dim = self.ncfile.createDimension(
            'k', self.message_data.grid['imaxk'].shape[0])   # no idea what it is, needed for imaxk, jmaxk
        flow_elem_dim = self.ncfile.createDimension(
            'nFlowElem1', self.message_data.grid['nFlowElem1d']+
            self.message_data.grid['nFlowElem2d'])  # Apparently no boundary nodes
        flow_elem2_dim = self.ncfile.createDimension(
            'nFlowElem2',
            self.message_data.grid['nFlowElem1d'] +
            self.message_data.grid['nFlowElem1dBounds'] +
            self.message_data.grid['nFlowElem2d'] +
            # Apparently WITH boundary nodes
            self.message_data.grid['nFlowElem2dBounds'])

    def dump_nc(self, var_name, var_type, dimensions, unit, values=None):
        """In some weird cases, this function can crash with a RuntimeError
        from NETCDF: RuntimeError: NetCDF: Operation not allowed in define mode

        Thus it is preferred that the function runs in a try/except.
        """
        logger.debug('dumping %s...' % var_name)
        if values is None:
            values = self.message_data.grid[var_name]
        self.v = self.ncfile.createVariable(var_name, var_type, dimensions)
        logger.info('dimensions %s' % str(dimensions))
        logger.info('len(unit) %d' % len(unit))
        if len(unit) == 0:
            self.v[:] = values
        elif len(unit) == 1:
            self.v[:] = values
        elif len(unit) == 2:
            self.v[:, :] = values

        self.v.units = unit
        self.v.standard_name = var_name

    def close(self):
        logger.debug('Closing...')
        self.ncfile.sync()
        self.ncfile.close()
        logger.debug('Done')
开发者ID:nens,项目名称:threedi-wms,代码行数:58,代码来源:messages.py

示例12: deltares_sgrid_no_optional_attr

# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import sync [as 别名]
def deltares_sgrid_no_optional_attr():
    fname = tempfile.mktemp(suffix=".nc")
    nc = Dataset(fname, "w")
    # Define dimensions.
    nc.createDimension("MMAXZ", 4)
    nc.createDimension("NMAXZ", 4)
    nc.createDimension("MMAX", 4)
    nc.createDimension("NMAX", 4)
    nc.createDimension("KMAX", 2)
    nc.createDimension("KMAX1", 3)
    nc.createDimension("time", 2)
    # Define variables.
    xcor = nc.createVariable("XCOR", "f4", ("MMAX", "NMAX"))  # nodes
    ycor = nc.createVariable("YCOR", "f4", ("MMAX", "NMAX"))  # nodes
    xz = nc.createVariable("XZ", "f4", ("MMAXZ", "NMAXZ"))  # centers
    yz = nc.createVariable("YZ", "f4", ("MMAXZ", "NMAXZ"))  # centers
    u1 = nc.createVariable("U1", "f4", ("time", "KMAX", "MMAX", "NMAXZ"))
    v1 = nc.createVariable("V1", "f4", ("time", "KMAX", "MMAXZ", "NMAX"))
    w = nc.createVariable("W", "f4", ("time", "KMAX1", "MMAXZ", "NMAXZ"))
    times = nc.createVariable("time", "f8", ("time",))
    grid = nc.createVariable("grid", "i4")
    # Define variable attributes.
    grid.cf_role = "grid_topology"
    grid.topology_dimension = 2
    grid.node_dimensions = "MMAX NMAX"
    grid.face_dimensions = "MMAXZ: MMAX (padding: low) NMAXZ: NMAX (padding: low)"  # noqa
    grid.vertical_dimensions = "KMAX: KMAX1 (padding: none)"
    xcor.standard_name = "projection_x_coordinate"
    xcor.long_name = "X-coordinate of grid points"
    ycor.standard_name = "projection_y_coordinate"
    ycor.long_name = "Y-coordinate of grid points"
    xz.standard_name = "projection_x_coordinate"
    xz.long_name = "X-coordinate of cell centres"
    yz.standard_name = "projection_y_coordinate"
    yz.long_name = "Y-coordinate of cell centres"
    times.standard_name = "time"
    u1.grid = "some grid"
    u1.axes = "X: NMAXZ Y: MMAX Z: KMAX"
    u1.standard_name = "sea_water_x_velocity"
    v1.grid = "some grid"
    v1.axes = "X: NMAX Y: MMAXZ Z: KMAX"
    v1.standard_name = "sea_water_y_velocity"
    w.grid = "grid"
    w.location = "face"
    # Create variable data.
    xcor[:] = np.random.random((4, 4))
    ycor[:] = np.random.random((4, 4))
    xz[:] = np.random.random((4, 4))
    yz[:] = np.random.random((4, 4))
    u1[:] = np.random.random((2, 2, 4, 4))
    v1[:] = np.random.random((2, 2, 4, 4))
    times[:] = np.random.random((2,))
    nc.sync()
    yield nc
    nc.close()
    os.remove(fname)
开发者ID:NOAA-ORR-ERD,项目名称:pysgrid,代码行数:58,代码来源:write_nc_test_files.py

示例13: deltares_sgrid_no_optional_attr

# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import sync [as 别名]
def deltares_sgrid_no_optional_attr(fname='tmp_sgrid_deltares_no_opt_attr.nc'):
    nc = Dataset(fname, 'w')
    # Define dimensions.
    nc.createDimension('MMAXZ', 4)
    nc.createDimension('NMAXZ', 4)
    nc.createDimension('MMAX', 4)
    nc.createDimension('NMAX', 4)
    nc.createDimension('KMAX', 2)
    nc.createDimension('KMAX1', 3)
    nc.createDimension('time', 2)
    # Define variables.
    xcor = nc.createVariable('XCOR', 'f4', ('MMAX', 'NMAX'))  # nodes
    ycor = nc.createVariable('YCOR', 'f4', ('MMAX', 'NMAX'))  # nodes
    xz = nc.createVariable('XZ', 'f4', ('MMAXZ', 'NMAXZ'))  # centers
    yz = nc.createVariable('YZ', 'f4', ('MMAXZ', 'NMAXZ'))  # centers
    u1 = nc.createVariable('U1', 'f4', ('time', 'KMAX', 'MMAX', 'NMAXZ'))
    v1 = nc.createVariable('V1', 'f4', ('time', 'KMAX', 'MMAXZ', 'NMAX'))
    w = nc.createVariable('W', 'f4', ('time', 'KMAX1', 'MMAXZ', 'NMAXZ'))
    times = nc.createVariable('time', 'f8', ('time',))
    grid = nc.createVariable('grid', 'i4')
    # Define variable attributes.
    grid.cf_role = 'grid_topology'
    grid.topology_dimension = 2
    grid.node_dimensions = 'MMAX NMAX'
    grid.face_dimensions = 'MMAXZ: MMAX (padding: low) NMAXZ: NMAX (padding: low)'  # noqa
    grid.vertical_dimensions = 'KMAX: KMAX1 (padding: none)'
    xcor.standard_name = 'projection_x_coordinate'
    xcor.long_name = 'X-coordinate of grid points'
    ycor.standard_name = 'projection_y_coordinate'
    ycor.long_name = 'Y-coordinate of grid points'
    xz.standard_name = 'projection_x_coordinate'
    xz.long_name = 'X-coordinate of cell centres'
    yz.standard_name = 'projection_y_coordinate'
    yz.long_name = 'Y-coordinate of cell centres'
    times.standard_name = 'time'
    u1.grid = 'some grid'
    u1.axes = 'X: NMAXZ Y: MMAX Z: KMAX'
    u1.standard_name = 'sea_water_x_velocity'
    v1.grid = 'some grid'
    v1.axes = 'X: NMAX Y: MMAXZ Z: KMAX'
    v1.standard_name = 'sea_water_y_velocity'
    w.grid = 'grid'
    w.location = 'face'
    # Create variable data.
    xcor[:] = np.random.random((4, 4))
    ycor[:] = np.random.random((4, 4))
    xz[:] = np.random.random((4, 4))
    yz[:] = np.random.random((4, 4))
    u1[:] = np.random.random((2, 2, 4, 4))
    v1[:] = np.random.random((2, 2, 4, 4))
    times[:] = np.random.random((2,))
    nc.sync()
    yield nc
    nc.close()
    os.remove(fname)
开发者ID:ChrisBarker-NOAA,项目名称:pysgrid,代码行数:57,代码来源:write_nc_test_files.py

示例14: fill

# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import sync [as 别名]
def fill(nc_name, image, template, start_dt,
        channel, source, sat_name):
    """Copy a template file to destination and fill it
    with the provided image data.

    WARNING: Timing information is not added
    """
    nc_name = os.path.abspath(nc_name)
    template = os.path.abspath(template)
    if not os.path.exists(template):
        log.error("Template does not exist %s" % template)
        raise ValueError("Template does not exist %s" % template)

    if os.path.exists(nc_name):
        log.error("Output file %s already exists" % nc_name)
        raise ValueError("Output file %s already exists" % nc_name)

    try:
        shutil.copyfile(template, nc_name)
    except StandardError:
        log.error("Could not copy template file %s to destination %s" % (template,nc_name))
        raise ValueError("Could not copy template file %s to destination %s" % (template,nc_name))

    nc = Dataset(nc_name, "a")
    if nc.file_format != "NETCDF3_CLASSIC":
        log.warning("Expected file format NETCDF3_CLASSIC got %s" % (nc.file_format))

    image_var = nc.variables["image"]
    if image_var.shape != image.shape:
        log.error("Image shapes aren't equal, expected %s got %s" % (str(image_var.shape),str(image.shape)))
        raise ValueError("Image shapes aren't equal, expected %s got %s" % (str(image_var.shape),str(image.shape)))

    # Convert to signed byte keeping large values large
    large_idxs = numpy.nonzero(image > 255)
    small_idxs = numpy.nonzero(image < 0)
    image[large_idxs] = 255
    image[small_idxs] = 0

    image_var[:] = image
    time_var = nc.variables["validTime"]
    time_var[:] = float(calendar.timegm( start_dt.utctimetuple() )) + float(start_dt.microsecond)/1e6

    # Add AWIPS 2 global attributes
    nc.channel = channel
    nc.source = source
    nc.satelliteName = sat_name

    nc.sync() # Just in case
    nc.close()
    log.debug("Data transferred into NC file correctly")
开发者ID:gina-alaska,项目名称:polar2grid,代码行数:52,代码来源:awips_netcdf.py

示例15: flush

# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import sync [as 别名]
 def flush(self):      
     try:
         if self.pftPo is None:
             self.boost()
     except AttributeError:
         self.boost()
     
     dst = self.source[:-3]+'.boosted.nc'
     from shutil import copyfile
     copyfile(self.source, dst)
     from netCDF4 import Dataset
     nc = Dataset(dst, mode="a")
     nc.variables['PCT_PFT'][:] = self.pftPo[:,::-1,:]
     nc.sync()
     nc.close()
开发者ID:guoliu,项目名称:pyFire,代码行数:17,代码来源:PFTbuild.py


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