本文整理汇总了Python中Scientific.IO.NetCDF.NetCDFFile.createDimension方法的典型用法代码示例。如果您正苦于以下问题:Python NetCDFFile.createDimension方法的具体用法?Python NetCDFFile.createDimension怎么用?Python NetCDFFile.createDimension使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Scientific.IO.NetCDF.NetCDFFile
的用法示例。
在下文中一共展示了NetCDFFile.createDimension方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: OPENPIV2D2C
# 需要导入模块: from Scientific.IO.NetCDF import NetCDFFile [as 别名]
# 或者: from Scientific.IO.NetCDF.NetCDFFile import createDimension [as 别名]
def OPENPIV2D2C(filename,ux_out,uy_out,x_out,y_out,flag1,flag2,flag3):
"""Storage in NetCDF format: 2D2C PIV datas with 3 flags used in OPENPIV"""
# open a new netCDF file for writing.
ncfile = Dataset(filename,'w')
# create the x and y dimensions.
nx,ny=ux_out.shape
ncfile.createDimension('x',nx)
ncfile.createDimension('y',ny)
# create the variable (4 byte integer in this case)
# first argument is name of variable, second is datatype, third is
# a tuple with the names of dimensions.
#data = ncfile.createVariable('data',np.dtype('int32').char,('x','y'))
xvar = ncfile.createVariable('xvar','d',('x','y'))
yvar = ncfile.createVariable('yvar','d',('x','y'))
ux = ncfile.createVariable('ux','d',('x','y'))
uy = ncfile.createVariable('uy','d',('x','y'))
Flags1 = ncfile.createVariable('flag1','d',('x','y'))
Flags2 = ncfile.createVariable('flag2','d',('x','y'))
Flags3 = ncfile.createVariable('flag3','d',('x','y'))
# write data to variable.
xvar[:] = x_out
yvar[:] = y_out
ux[:] = ux_out
uy[:] = uy_out
Flags1[:] = flag1
Flags2[:] = flag2
Flags3[:] = flag3
# close the file.
ncfile.close()
print '*** SUCCESS writing:',filename
示例2: gen
# 需要导入模块: from Scientific.IO.NetCDF import NetCDFFile [as 别名]
# 或者: from Scientific.IO.NetCDF.NetCDFFile import createDimension [as 别名]
def gen(self):
ncfile = Dataset(self.fname, 'w')
tm = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
# set dimension info
ncfile.createDimension('grid_size', self.obj.grid_size)
# set variable info
grid_center_lat_var = ncfile.createVariable('grid_center_lat', dtype('d').char, ('grid_size',))
grid_center_lon_var = ncfile.createVariable('grid_center_lon', dtype('d').char, ('grid_size',))
physical_variable = ncfile.createVariable('physical_variable', dtype('d').char, ('grid_size',))
grid_center_lat_var[:] = np.array(self.obj.grid_center_lat)
grid_center_lon_var[:] = np.array(self.obj.grid_center_lon)
physical_variable[:] = np.array(self.obj.physical_variable)
setattr(ncfile, 'title', 'Threp ' + self.fname)
setattr(ncfile, 'createdate', tm)
setattr(ncfile, 'map_method', self.method)
setattr(ncfile, 'conventions', 'Threp')
setattr(ncfile, 'src_grid', self.obj.src_grid_name)
setattr(ncfile, 'dst_grid', self.obj.dst_grid_name)
ncfile.close()
print '*** Successfully generated netcdf file for ncl usage. ***'
示例3: openOutputFile
# 需要导入模块: from Scientific.IO.NetCDF import NetCDFFile [as 别名]
# 或者: from Scientific.IO.NetCDF.NetCDFFile import createDimension [as 别名]
def openOutputFile(self):
# Create file
os.system('mkdir -p results/%s-%s' % (self.Case1,self.Case2))
FileName = 'results/%s-%s/Cam3Feedbacks.%s-%s.%03i.nc' % \
(self.Case1,self.Case2,self.Case1,self.Case2,self.FileNumber)
if not os.path.exists(FileName):
print 'creating %s ...' % FileName
File = NetCDFFile(FileName,'w')
File.createDimension('lat',len(self.data.lat))
var = File.createVariable('lat','f',('lat',))
var.long_name = 'latitude'
var.units = 'degrees_north'
var[:] = self.data.lat.astype('f')
File.createDimension('lon',len(self.data.lon))
var = File.createVariable('lon','f',('lon',))
var.long_name = 'longitude'
var.units = 'degrees_east'
var[:] = self.data.lon.astype('f')
# create variables
for Field in ['dR_Ts','dR_lapse','dR_q','dR_cld_sw','dR_cld_lw','dR_alb','dR_co2']:
var = File.createVariable(Field,'f',('lat','lon'))
var.long_name = 'TOA radiative perturbation'
var.units = 'W m-2'
var[:,:] = 0.
File.NsnapsDone = 0
return 0, File
else:
File = NetCDFFile(FileName,'a')
NsnapsDone = int(File.NsnapsDone[0])
if NsnapsDone < len(self.data.time):
return NsnapsDone, File
else:
print 'No more snaps to be done'
sys.exit(0)
示例4: test_modis
# 需要导入模块: from Scientific.IO.NetCDF import NetCDFFile [as 别名]
# 或者: from Scientific.IO.NetCDF.NetCDFFile import createDimension [as 别名]
def test_modis():
modis_file = "MYD06_L2.A2010100.0755.051.2010108054555.hdf"
print "****** Reading MODIS data from file: ", modis_file
modis = FEMODIS.front_end_modis_cloud_1km_dev(modis_file)
tim=modis.get_time()
lat=modis.get_latitude()
lon=modis.get_longitude()
dat=modis.get_data()
print dat.keys()
cwp=dat['Cloud_Water_Path']
# print lat, lon, lwp
ncfile = Dataset('modis_1km.nc','w')
ndim = len(lat)
ncfile.createDimension('time',ndim)
time = ncfile.createVariable('time',dtype('float32').char,('time', ))
lats = ncfile.createVariable('latitude',dtype('float32').char,('time', ))
lons = ncfile.createVariable('longitude',dtype('float32').char,('time', ))
cwps = ncfile.createVariable('cloud_water_path',dtype('float32').char,('time', ))
time[:] = N.cast['float32'](tim)
lats[:] = N.cast['float32'](lat)
lons[:] = N.cast['float32'](lon)
cwps[:] = N.cast['float32'](cwp[1])
ncfile.close()
示例5: write
# 需要导入模块: from Scientific.IO.NetCDF import NetCDFFile [as 别名]
# 或者: from Scientific.IO.NetCDF.NetCDFFile import createDimension [as 别名]
def write(self):
ncfile = Dataset(self.fname, 'w')
tm = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
# set dimension info
ncfile.createDimension('src_grid_size', self.obj.src_grid_size)
ncfile.createDimension('dst_grid_size', self.obj.dst_grid_size)
ncfile.createDimension('n_wgt', self.n_wgt)
ncfile.createDimension('src_grid_rank', self.obj.src_grid_rank)
ncfile.createDimension('dst_grid_rank', self.obj.dst_grid_rank)
ncfile.createDimension('num_wgts', 1)
ncfile.createDimension('src_grid_corners', self.obj.src_grid_corners)
ncfile.createDimension('dst_grid_corners', self.obj.dst_grid_corners)
# set variable info
src_grid_dims_var = ncfile.createVariable('src_grid_dims', dtype('int32').char, ('src_grid_rank',))
dst_grid_dims_var = ncfile.createVariable('dst_grid_dims', dtype('int32').char, ('dst_grid_rank',))
src_grid_center_lat_var = ncfile.createVariable('src_grid_center_lat', dtype('d').char, ('src_grid_size',))
src_grid_center_lon_var = ncfile.createVariable('src_grid_center_lon', dtype('d').char, ('src_grid_size',))
dst_grid_center_lat_var = ncfile.createVariable('dst_grid_center_lat', dtype('d').char, ('dst_grid_size',))
dst_grid_center_lon_var = ncfile.createVariable('dst_grid_center_lon', dtype('d').char, ('dst_grid_size',))
src_grid_imask_var = ncfile.createVariable('src_grid_imask', dtype('i').char, ('src_grid_size',))
dst_grid_imask_var = ncfile.createVariable('dst_grid_imask', dtype('i').char, ('dst_grid_size',))
remap_src_indx_var = ncfile.createVariable('remap_src_indx', dtype('i').char, ('n_wgt',))
remap_dst_indx_var = ncfile.createVariable('remap_dst_indx', dtype('i').char, ('n_wgt',))
remap_matrix_var = ncfile.createVariable('remap_matrix', dtype('d').char, ('n_wgt',))
src_grid_dims_var[:] = self.obj.src_grid_dims
dst_grid_dims_var[:] = self.obj.dst_grid_dims
src_grid_center_lat_var[:] = np.array(self.obj.original_src_grid_center_lat)
src_grid_center_lon_var[:] = np.array(self.obj.original_src_grid_center_lon)
dst_grid_center_lat_var[:] = np.array(self.obj.dst_grid_center_lat)
dst_grid_center_lon_var[:] = np.array(self.obj.dst_grid_center_lon)
#src_grid_imask_var[:] = np.array(self.obj.original_src_grid_imask)
buffer1 = [np.int32(i) for i in self.obj.original_src_grid_imask]
src_grid_imask_var[:] = np.array(buffer1)
buffer2 = [np.int32(i) for i in self.obj.dst_grid_imask]
dst_grid_imask_var[:] = np.array(buffer2)
#dst_grid_imask_var[:] = np.array(self.obj.dst_grid_imask)
buffer3 = [np.int32(i) for i in self.obj.remap_src_indx]
remap_src_indx_var[:] = np.array(buffer3)
#remap_src_indx_var[:] = np.array(self.obj.remap_src_indx)
buffer4 = [np.int32(i) for i in self.obj.remap_dst_indx]
remap_dst_indx_var[:] = np.array(buffer4)
#remap_dst_indx_var[:] = np.array(self.obj.remap_dst_indx)
remap_matrix_var[:] = np.array(self.obj.remap_matrix_compact)
setattr(ncfile, 'title', 'Threp ' + self.fname)
setattr(ncfile, 'createdate', tm)
setattr(ncfile, 'map_method', self.method)
setattr(ncfile, 'conventions', 'Threp')
setattr(ncfile, 'src_grid', self.obj.src_grid_name)
setattr(ncfile, 'dst_grid', self.obj.dst_grid_name)
ncfile.close()
print '*** Successfully generate remap matrix file. ***'
示例6: write_to_file
# 需要导入模块: from Scientific.IO.NetCDF import NetCDFFile [as 别名]
# 或者: from Scientific.IO.NetCDF.NetCDFFile import createDimension [as 别名]
def write_to_file(CS,nmax_coarse, nmax_fine, nblocks ,hw_ph,filename):
"""
Writes the results of a computation to a netcdf file.
Takes a Compute_Loop_Function object as input; it is assumed that
this object has already computed what we wish to write!
"""
#--------------------------------------------
# Write to netcdf file
#--------------------------------------------
ncfile = Dataset(filename,'w')
# --- set various attributes, identifying the parameters of the computation ----
setattr(ncfile,'mu',CS.mu)
setattr(ncfile,'beta',CS.beta)
setattr(ncfile,'acell',acell)
setattr(ncfile,'Area',Area)
setattr(ncfile,'nmax_coarse',nmax_coarse)
setattr(ncfile,'nmax_fine',nmax_fine)
setattr(ncfile,'n_blocks_coarse_to_fine',nblocks)
setattr(ncfile,'Gamma_width',CS.Gamma)
setattr(ncfile,'phonon_frequency',hw_ph)
# --- Create dimensions ----
ncfile.createDimension("number_of_frequencies",CS.list_hw.shape[0])
ncfile.createDimension("xy",2)
ncfile.createDimension("gamma_i",2)
ncfile.createDimension("uv",2)
ncfile.createDimension("phonon_alpha_kappa",6)
# --- Write data ----
Q = ncfile.createVariable("q_phonon",'d',('xy',))
REPH = ncfile.createVariable("Re_E_phonon",'d',('phonon_alpha_kappa',))
IEPH = ncfile.createVariable("Im_E_phonon",'d',('phonon_alpha_kappa',))
HW = ncfile.createVariable("list_hw",'d',('number_of_frequencies',))
RH = ncfile.createVariable("Re_H",'d',('xy','gamma_i','uv','number_of_frequencies'))
IH = ncfile.createVariable("Im_H",'d',('xy','gamma_i','uv','number_of_frequencies'))
Q[:] = CS.q
REPH[:] = N.real(CS.E_ph)
IEPH[:] = N.imag(CS.E_ph)
HW[:] = N.real(CS.list_hw)
RH[:,:,:,:] = N.real(CS.Hq)
IH[:,:,:,:] = N.imag(CS.Hq)
ncfile.close()
示例7: CoordTransfer
# 需要导入模块: from Scientific.IO.NetCDF import NetCDFFile [as 别名]
# 或者: from Scientific.IO.NetCDF.NetCDFFile import createDimension [as 别名]
class CoordTransfer(Exception):
def __init__(self, srcfile, dstfile, newfile):
self.srcfile = srcfile
self.dstfile = dstfile
self.newfile = newfile
def loadsrcoords(self):
self.ncfile = Dataset(self.srcfile, 'r')
variable_name = 'grid_center_lat'
__grid_center_lat = self.ncfile.variables[variable_name][:]
variable_name = 'grid_center_lon'
__grid_center_lon = self.ncfile.variables[variable_name][:]
self.__grid_center_lat = __grid_center_lat.tolist()
self.__grid_center_lon = __grid_center_lon.tolist()
def loadstinfo(self):
self.nc_obj = Loadnc(self.dstfile)
self.grid_size, self.grid_corners, self.grid_rank, self.grid_dims, ach1, ach2, self.grid_imask = self.nc_obj.load()
def transfercoord(self):
self.resncfile = Dataset(self.newfile, 'w')
tm = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
# set dimension info
self.resncfile.createDimension('grid_size', self.grid_size)
self.resncfile.createDimension('grid_rank', self.grid_rank)
self.resncfile.createDimension('grid_corners', self.grid_corners)
# set variable info
grid_dims_var = self.resncfile.createVariable('grid_dims', dtype('int32').char, ('grid_rank',))
grid_center_lat_var = self.resncfile.createVariable('grid_center_lat', dtype('d').char, ('grid_size',))
grid_center_lat_var.units = 'degrees'
grid_center_lon_var = self.resncfile.createVariable('grid_center_lon', dtype('d').char, ('grid_size',))
grid_center_lon_var.units = 'degrees'
grid_imask_var = self.resncfile.createVariable('grid_imask', dtype('i').char, ('grid_size',))
grid_imask_var.units = 'unitless'
grid_dims_var[:] = self.grid_dims
grid_center_lat_var[:] = np.array(self.__grid_center_lat)
grid_center_lon_var[:] = np.array(self.__grid_center_lon)
buffer1 = [np.int32(i) for i in self.grid_imask]
grid_imask_var[:] = np.array(buffer1)
setattr(self.resncfile, 'title', 'Threp ' + self.newfile)
setattr(self.resncfile, 'createdate', tm)
setattr(self.resncfile, 'conventions', 'Threp')
setattr(self.resncfile, 'grid', self.newfile)
def finish(self):
self.resncfile.close()
self.nc_obj.closenc()
示例8: filter_netcdf
# 需要导入模块: from Scientific.IO.NetCDF import NetCDFFile [as 别名]
# 或者: from Scientific.IO.NetCDF.NetCDFFile import createDimension [as 别名]
def filter_netcdf(filename1, filename2, first=0, last=None, step=1):
"""Filter data file, selecting timesteps first:step:last.
Read netcdf filename1, pick timesteps first:step:last and save to
nettcdf file filename2
"""
from Scientific.IO.NetCDF import NetCDFFile
# Get NetCDF
infile = NetCDFFile(filename1, netcdf_mode_r) #Open existing file for read
outfile = NetCDFFile(filename2, netcdf_mode_w) #Open new file
# Copy dimensions
for d in infile.dimensions:
outfile.createDimension(d, infile.dimensions[d])
# Copy variable definitions
for name in infile.variables:
var = infile.variables[name]
outfile.createVariable(name, var.dtype.char, var.dimensions)
# Copy the static variables
for name in infile.variables:
if name == 'time' or name == 'stage':
pass
else:
outfile.variables[name][:] = infile.variables[name][:]
# Copy selected timesteps
time = infile.variables['time']
stage = infile.variables['stage']
newtime = outfile.variables['time']
newstage = outfile.variables['stage']
if last is None:
last = len(time)
selection = range(first, last, step)
for i, j in enumerate(selection):
log.critical('Copying timestep %d of %d (%f)'
% (j, last-first, time[j]))
newtime[i] = time[j]
newstage[i,:] = stage[j,:]
# Close
infile.close()
outfile.close()
示例9: write
# 需要导入模块: from Scientific.IO.NetCDF import NetCDFFile [as 别名]
# 或者: from Scientific.IO.NetCDF.NetCDFFile import createDimension [as 别名]
def write(cls, filename, data, header=""):
'''
Write a set of output variables into a NetCDF file.
:param filename: the path to the output NetCDF file.
:type filename: str
:param data: the data to be written out.
:type data: dict of Framework.OutputVariables.IOutputVariable
:param header: the header to add to the output file.
:type header: str
'''
filename = os.path.splitext(filename)[0]
filename = "%s%s" % (filename,cls.extensions[0])
# The NetCDF output file is opened for writing.
outputFile = NetCDFFile(filename, 'w')
if header:
outputFile.header = header
# Loop over the OutputVariable instances to write.
for var in data.values():
varName = str(var.name).strip().encode('string-escape').replace('/', '|')
# The NetCDF dimensions are created for all the dimensions of the OutputVariable instance.
dimensions = []
for i,v in enumerate(var.shape):
name = str("%s_%d" % (varName,i))
dimensions.append(name)
outputFile.createDimension(name, int(v))
# A NetCDF variable instance is created for the running OutputVariable instance.
NETCDFVAR = outputFile.createVariable(varName, numpy.dtype(var.dtype).char, tuple(dimensions))
# The array stored in the OutputVariable instance is written to the NetCDF file.
NETCDFVAR.assignValue(var)
# All the attributes stored in the OutputVariable instance are written to the NetCDF file.
for k, v in vars(var).items():
setattr(NETCDFVAR,str(k),str(v))
# The NetCDF file is closed.
outputFile.close()
示例10: gen_realdata
# 需要导入模块: from Scientific.IO.NetCDF import NetCDFFile [as 别名]
# 或者: from Scientific.IO.NetCDF.NetCDFFile import createDimension [as 别名]
def gen_realdata(path, filename, var):
ncfile = Dataset(path + filename, 'r')
filename = './realdata/T42_' + var + '-' + filename.split('.')[-2] + '.nc'
nc = Dataset(filename, 'w')
tm = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
nx = 128
ny = 64
grid_size = ncfile.dimensions['n_a']
# load data
data = ncfile.variables[var][:, :, :]
long_name = ncfile.variables[var].long_name
units = ncfile.variables[var].units
missing_value = ncfile.variables[var].missing_value
_FillValue = ncfile.variables[var]._FillValue
cell_method = ncfile.variables[var].cell_method
tmp = []
for i in range(1):
for j in range(ny):
for k in range(nx):
tmp.append(data[i][j][k])
data = scipy.array(tmp)
# create variables
nc.createDimension('grid_size', nx * ny)
# create varibels
data_var = nc.createVariable('data', dtype('d').char, ('grid_size',))
data_var[:] = data
data_var.long_name = long_name
data_var.units = units
data_var.missing_value = missing_value
data_var._FillValue = _FillValue
data_var.cell_method = cell_method
string = 'Threp' + var + ' data'
setattr(nc, 'title', string)
setattr(nc, 'createdata', tm)
nc.close()
ncfile.close()
print '*** Successfully generating real data file. ***'
示例11: writeNetCDF
# 需要导入模块: from Scientific.IO.NetCDF import NetCDFFile [as 别名]
# 或者: from Scientific.IO.NetCDF.NetCDFFile import createDimension [as 别名]
def writeNetCDF(self, filename):
from Scientific.IO.NetCDF import NetCDFFile
ncfile = NetCDFFile(filename, "w")
for dim, i in (("x", 0), ("y", 1), ("z", 2)):
ncfile.createDimension(dim, self.voxels[i])
ncfile.createVariable(dim, "d", (dim,))[:] = arange(self.voxels[i]) * self.vector[i][i]
ncfile.createVariable("data", "d", ("x", "y", "z"))
ncfile.variables["data"][:] = self.data
ncfile.Natom = self.Natom
ncfile.origin = self.origin
for n in range(self.Natom):
setattr(ncfile, "atom%i.Type" % n, self.atomType[n])
setattr(ncfile, "atom%i.Pos" % n, self.atomPos[n])
ncfile.close()
示例12: load_geoinfo
# 需要导入模块: from Scientific.IO.NetCDF import NetCDFFile [as 别名]
# 或者: from Scientific.IO.NetCDF.NetCDFFile import createDimension [as 别名]
def load_geoinfo(SrcFilename, DstFilename, GridSize, LatName, LonName):
# get lat/long values from 400/640 level files
ncfile = front_end_NetCDF_helper()
ncfile.open(SrcFilename)
# read lat array
SrcLatData = ncfile.read_data(LatName)
# print SrcLatData
# read lon array
SrcLonData = ncfile.read_data(LonName)
# print SrcLonData
ncfile.close()
# create down-sampled long array
DstLonData = N.zeros(GridSize)
#
for DstLonNo in range(0, GridSize):
SrcLonNo = DstLonNo * 2
# down-sampling strategy 1, use avarage
# DstLonData[DstLonNo] = (SrcLonData[SrcLonNo] + SrcLonData[SrcLonNo+1])/2.0
# print DstLonNo, SrcLonNo, DstLonData[DstLonNo], SrcLonData[SrcLonNo], SrcLonData[SrcLonNo+1]
# start with 0 and skip alternate points
DstLonData[DstLonNo] = SrcLonData[SrcLonNo]
# print DstLonNo, SrcLonNo, DstLonData[DstLonNo], SrcLonData[SrcLonNo]
# write NetCDF file
# open output file
dst_ncfile = NetCDFFile(DstFilename, "w")
# define dimensions
dst_lat_dim = dst_ncfile.createDimension(LatName, GridSize)
dst_lon_dim = dst_ncfile.createDimension(LonName, GridSize)
# define variables
dst_lat_var = dst_ncfile.createVariable(LatName, "d", (LatName,))
# dst_lat_var.setattr (
# NetCDFFile.setattr (dst_lat_var, 'attrname', attr_val)
dst_lon_var = dst_ncfile.createVariable(LonName, "d", (LonName,))
# write lat data
dst_lat_var.assignValue(SrcLatData)
# write lon data
dst_lon_var.assignValue(DstLonData)
# close output file
dst_ncfile.close()
示例13: writeNcFile
# 需要导入模块: from Scientific.IO.NetCDF import NetCDFFile [as 别名]
# 或者: from Scientific.IO.NetCDF.NetCDFFile import createDimension [as 别名]
def writeNcFile(data, fileName=None, oldStyle=1):
if not ncOk:
raise Exception('module Scientific.IO.NetCDF not found, writeNcFile() failed!')
if not fileName:
fileName = data['name']+'_weather.nc'
f = NetCDFFile(fileName, 'w')
f.createDimension('time', data['time'].shape[0])
f.file_format = file_format
if oldStyle:
f.createDimension('scalar', 1)
if data.has_key('comment'):
f.comment = data['comment']
else:
f.comment = 'created by MeteonormFile.py (v%s)' % version
if data.has_key('source_file'):
f.source_file = str(data['source_file'])
for vn in ('latitude', 'longitude', 'height'):
setattr(f, vn, data[vn])
if oldStyle:
v = f.createVariable(vn, 'd', ('scalar', ))
v[:] = [data[vn]]
setattr(f, 'longitude_0', 15.0*data['timezone'])
if oldStyle:
v = f.createVariable('longitude_0', 'd', ('scalar', ))
v[:] = [15.0 * data['timezone']]
for vn in variables.keys():
t = variables[vn][1]
v = f.createVariable(vn, t, ('time',))
v[:] = data[vn].astype(t)
oname = variables[vn][0]
if oname.startswith('<'): oname = oname[1:]
if oname.endswith('>'): oname = oname[:-1]
v.original_name = oname
v.unit = variables[vn][2]
f.sync()
f.close()
示例14: write_to_file
# 需要导入模块: from Scientific.IO.NetCDF import NetCDFFile [as 别名]
# 或者: from Scientific.IO.NetCDF.NetCDFFile import createDimension [as 别名]
def write_to_file(CS, nmax_coarse, nmax_fine, nblocks, hw_ph, filename):
"""
Writes the results of a computation to a netcdf file.
Takes a Compute_Loop_Function object as input; it is assumed that
this object has already computed what we wish to write!
"""
# --------------------------------------------
# Write to netcdf file
# --------------------------------------------
ncfile = Dataset(filename, "w")
# --- set various attributes, identifying the parameters of the computation ----
setattr(ncfile, "mu", CS.mu)
setattr(ncfile, "beta", CS.beta)
setattr(ncfile, "acell", acell)
setattr(ncfile, "Area", Area)
setattr(ncfile, "nmax_coarse", nmax_coarse)
setattr(ncfile, "nmax_fine", nmax_fine)
setattr(ncfile, "n_blocks_coarse_to_fine", nblocks)
setattr(ncfile, "Green_Gamma_width", CS.Green_Gamma_width)
setattr(ncfile, "kernel_Gamma_width", CS.kernel_Gamma_width)
setattr(ncfile, "phonon_frequency", hw_ph)
# --- Create dimensions ----
ncfile.createDimension("xy", 2)
ncfile.createDimension("L_AB", 2)
ncfile.createDimension("phonon_alpha_kappa", 6)
# --- Write data ----
Q = ncfile.createVariable("q_phonon", "d", ("xy",))
REPH = ncfile.createVariable("Re_E_phonon", "d", ("phonon_alpha_kappa",))
IEPH = ncfile.createVariable("Im_E_phonon", "d", ("phonon_alpha_kappa",))
Re_R = ncfile.createVariable("Re_R", "d", ("xy", "L_AB"))
Im_R = ncfile.createVariable("Im_R", "d", ("xy", "L_AB"))
Re_I = ncfile.createVariable("Re_I", "d", ("xy", "L_AB"))
Im_I = ncfile.createVariable("Im_I", "d", ("xy", "L_AB"))
Q[:] = CS.q
REPH[:] = N.real(CS.E_ph)
IEPH[:] = N.imag(CS.E_ph)
Re_R[:, :] = N.real(CS.Rq)
Im_R[:, :] = N.imag(CS.Rq)
Re_I[:, :] = N.real(CS.Iq)
Im_I[:, :] = N.imag(CS.Iq)
ncfile.close()
return
示例15: test
# 需要导入模块: from Scientific.IO.NetCDF import NetCDFFile [as 别名]
# 或者: from Scientific.IO.NetCDF.NetCDFFile import createDimension [as 别名]
def test(self):
# Create file
FileName = '%s_out.nc' % self.Case
print 'creating %s ...' % FileName
File = NetCDFFile(FileName,'w')
File.createDimension('time',None)
var = File.createVariable('time','f',('time',))
var.long_name = 'time'
var.units = ' '
File.createDimension('lat',len(self.data.lat))
var = File.createVariable('lat','f',('lat',))
var.long_name = 'latitude'
var.units = 'degrees_north'
var[:] = self.data.lat.astype('f')
File.createDimension('lon',len(self.data.lon))
var = File.createVariable('lon','f',('lon',))
var.long_name = 'longitude'
var.units = 'degrees_east'
var[:] = self.data.lon.astype('f')
for Field in ['SwToa','LwToa','SwToaCf','LwToaCf']:
var = File.createVariable(Field,'f',('time','lat','lon'))
var.long_name = ''
var.units = 'W m-2'
lmax = 3
for l in range(lmax):
print 'doing %s of %s' % (l+1,lmax)
# get data
Data = self.getFields(l)[0]
Data.update(self.Fixed)
# compute
self.r(**Data)
File.variables['SwToa'][l] = self.r['SwToa'].astype('f')
File.variables['LwToa'][l] = -self.r['LwToa'].astype('f')
File.variables['SwToaCf'][l] = self.r['SwToaCf'].astype('f')
File.variables['LwToaCf'][l] = self.r['LwToaCf'].astype('f')
File.close()