本文整理汇总了Python中Scientific.IO.NetCDF.NetCDFFile类的典型用法代码示例。如果您正苦于以下问题:Python NetCDFFile类的具体用法?Python NetCDFFile怎么用?Python NetCDFFile使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了NetCDFFile类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self, filename, whatToRead = None):
"""Construct a reader from a filename."""
self.whatToRead = whatToRead
try:
self.nc = NetCDFFile(filename, 'r')
except IOError:
self.nc = NetCDFFile(filename + ".nc", 'r')
示例2: openOutputFile
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)
示例3: select_file
def select_file(self, filename):
self.currentFilename = filename
f = NetCDFFile(filename,"r")
variables = f.variables
if not variables.has_key('molecular_trace'):
raise DensitySuperpositionError('Trace file format not compatible with Plugin')
self.dim.SetValue(str(variables['molecular_trace'].getValue().shape))
f.close()
示例4: get_single_model_data
def get_single_model_data(dataset,start_dates,var,lat,lon,plev=None,models='all',n_ens=None):
data_dir_main=get_data_dir_main()
fname_coords=get_fname_coords(lat,lon,plev=plev)
fname='get_seasfc_data_'+dataset+'_'+var+fname_coords
nc_file=NetCDFFile(data_dir_main+fname+'.nc')
#Convert intuitive variable name to name used inside files
var_data_name=get_var_data_name(var)
if models=='all':
if dataset=='ENSEMBLES':
models=['ECMWF', 'INGV', 'Kiel', 'MetFr', 'MO']
data_fc_sm={} #dict to hold single model forecasts
for start_date in start_dates:
data_fc_sm[start_date]={}
for model in models:
data_name=model.lower()+'_'+start_date.lower()+'_'+var_data_name
data_fc_sm[start_date][model]={}
if n_ens:
data_fc_sm[start_date][model]['data']=nc_file.variables[data_name][...,:n_ens] #reads in data with dimensions [forecast month, year of forecast start, ensemble member]
else:
data_fc_sm[start_date][model]['data']=nc_file.variables[data_name][:]
#Get the array containing the corresponding dates of the verification dataset in YYYYMM format.
#This array has dimension [forecast month, year of forecast start]
ver_month_arr_name_pos=getattr(nc_file.variables[data_name],'coordinates').find('verifying_month')
ver_month_arr_name=getattr(nc_file.variables[data_name],'coordinates')[ver_month_arr_name_pos:ver_month_arr_name_pos+17]
data_fc_sm[start_date][model]['verifying_month']=nc_file.variables[ver_month_arr_name][:]
#Get lead times
if len(nc_file.variables['forecast_lead_month'])==data_fc_sm[start_date][model]['data'].shape[0]:
lead_time_dim_name='forecast_lead_month'
elif 'forecast_lead_month_0' in nc_file.variables and len(nc_file.variables['forecast_lead_month_0'])==data_fc_sm[start_date][model]['data'].shape[0]:
lead_time_dim_name='forecast_lead_month_0'
else:
print 'Forecast lead time dimension not known', dataset, start_date, model
data_fc_sm[start_date][model]['lead times']=nc_file.variables[lead_time_dim_name][:]
if dataset=='ENSEMBLES':
lead_time_units='months'
data_fc_sm[start_date][model]['lead time units']=lead_time_units
nc_file.close()
return data_fc_sm
示例5: load_file
def load_file(file_name = file_name, time_start = time_start,
time_end = time_end, lat_start = lat_start, lat_end = lat_end,
lon_start = lon_start, lon_end = lon_end, masked_value = masked_value):
nc = NetCDFFile(file_name, 'r')
new_array = nc.variables['Cflx'][time_start:time_end, lat_start:lat_end,
lon_start:lon_end]
nc.close()
new_array = ma.masked_values(new_array, masked_value)
new_array = new_array*1e08
return new_array
示例6: __parinit__
def __parinit__(self, pid, nprocs, filename, split_dimension,
mode = 'r', local_access = False):
"""
@param filename: the name of the netCDF file
@type filename: C{str}
@param split_dimension: the name of the dimension along which the data
is distributed over the processors
@type split_dimension: C{str}
@param mode: read ('r'), write ('w'), or append ('a')
@type mode: C{str}
@param local_access: if C{False}, processor 0 is the only one to
access the file, all others communicate with
processor 0. If C{True} (only for reading), each
processor accesses the file directly. In the
latter case, the file must be accessible on all
processors under the same name. A third mode is
'auto', which uses some heuristics to decide
if the file is accessible everywhere: it checks
for existence of the file, then compares
the size on all processors, and finally verifies
that the same variables exist everywhere, with
identical names, types, and sizes.
@type local_access: C{bool} or C{str}
"""
if mode != 'r':
local_access = 0
self.pid = pid
self.nprocs = nprocs
self.filename = filename
self.split = split_dimension
self.local_access = local_access
self.read_only = mode == 'r'
if local_access or pid == 0:
self.file = NetCDFFile(filename, mode)
try:
length = self.file.dimensions[split_dimension]
if length is None:
length = -1
except KeyError:
length = None
variables = {}
for name, var in self.file.variables.items():
variables[name] = (name, var.dimensions)
if length < 0 and split_dimension in var.dimensions:
index = list(var.dimensions).index(split_dimension)
length = var.shape[index]
else:
self.file = None
self.split = split_dimension
length = None
variables = None
if not local_access:
length = self.broadcast(length)
variables = self.broadcast(variables)
if length is not None:
self._divideData(length)
self.variables = {}
for name, var in variables.items():
self.variables[name] = _ParNetCDFVariable(self, var[0], var[1],
split_dimension)
示例7: open
def open (self, filename):
self.ncfile = NetCDFFile(filename,'r')
# initialize variable name list
self.VarNameList = {}
for VarName in self.ncfile.variables.keys():
self.VarNameList[VarName] = True
示例8: __init__
def __init__(self, filename):
from Scientific.IO.NetCDF import NetCDFFile
self.nc = NetCDFFile(filename, 'w')
self.nc.file_format = 'ETSF Nanoquanta'
self.nc.file_format_version = np.array([3.3], dtype=np.float32)
self.nc.Conventions = 'http://www.etsf.eu/fileformats/'
self.nc.history = 'File generated by ASE'
示例9: __init__
def __init__(self, filename):
self.filename = filename
self.file = NetCDFFile(self.filename, 'r')
try:
self.block_size = self.file.dimensions['minor_step_number']
except KeyError:
self.block_size = 1
self._countSteps()
示例10: on_superpose
def on_superpose(self, event):
self.on_clear()
rendtype = self.rendlist.GetValue()
opacity = float(self.opacity.GetValue())
filename = self.get_file()
f = NetCDFFile(filename,"r")
variables = f.variables
data = variables['molecular_trace'].getValue()
origin = variables['origin'].getValue()
spacing = variables['spacing'].getValue()
f.close()
mi, ma = self.draw_isosurface(data, rendtype, opacity, origin, spacing)
self.isov_slider.SetRange(mi, ma)
self.isov_slider.Enable()
示例11: ncep2fall3d
def ncep2fall3d(ncep_filename, fall3d_ncep_filename, verbose=True):
"""Convert standard NCEP file to fall3d NCEP format
"""
# Copy standard NCEP file to fall3d NCEP file
s = 'cp %s %s' % (ncep_filename, fall3d_ncep_filename)
os.system(s)
# Open files
infile = NetCDFFile(ncep_filename)
outfile = NetCDFFile(ncep_filename, 'a')
# Establish special global attributes for fall3 NCEP format
print 'Found dimensions:', infile.dimensions.keys()
print 'Found variables:', infile.variables.keys()
lon = infile.variables['lon'][:]
lonmin = min(lon)
lonmax = max(lon)
lat = infile.variables['lat'][:]
latmin = min(lat)
latmax = max(lat)
nx = infile.dimensions['lon']
ny = infile.dimensions['lat']
np = infile.dimensions['pres']
nt = infile.dimensions['time']
print nx, ny, np, nt
infile.close()
outfile.close()
示例12: __init__
def __init__(self,
quantity_name,
file_name,
time_step_count,
time_step,
lon,
lat):
"""Instantiate a Write_nc instance (NetCDF file writer).
time_step_count is the number of time steps.
time_step is the time step size
pre-condition: quantity_name must be 'HA', 'UA'or 'VA'.
"""
self.quantity_name = quantity_name
quantity_units = {'HA':'CENTIMETERS',
'UA':'CENTIMETERS/SECOND',
'VA':'CENTIMETERS/SECOND'}
multiplier_dic = {'HA':100.0, # To convert from m to cm
'UA':100.0, # and m/s to cm/sec
'VA':-100.0} # MUX files have positive x in the
# Southern direction. This corrects
# for it, when writing nc files.
self.quantity_multiplier = multiplier_dic[self.quantity_name]
#self.file_name = file_name
self.time_step_count = time_step_count
self.time_step = time_step
# NetCDF file definition
self.outfile = NetCDFFile(file_name, netcdf_mode_w)
outfile = self.outfile
#Create new file
nc_lon_lat_header(outfile, lon, lat)
# TIME
outfile.createDimension(time_name, None)
outfile.createVariable(time_name, precision, (time_name,))
#QUANTITY
outfile.createVariable(self.quantity_name, precision,
(time_name, lat_name, lon_name))
outfile.variables[self.quantity_name].missing_value = -1.e+034
outfile.variables[self.quantity_name].units = \
quantity_units[self.quantity_name]
outfile.variables[lon_name][:]= ensure_numeric(lon)
outfile.variables[lat_name][:]= ensure_numeric(lat)
示例13: modify_filter
def modify_filter(gridfilename, ttlname, indflag = 1):
tm = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
ncfile = Dataset(gridfilename, 'a')
if indflag:
grid_center_lat_var = ncfile.variables['grid_center_lat']
setattr(grid_center_lat_var, 'units', 'degrees')
grid_center_lon_var = ncfile.variables['grid_center_lon']
setattr(grid_center_lon_var, 'units', 'degrees')
grid_corner_lat_var = ncfile.variables['grid_corner_lat']
setattr(grid_corner_lat_var, 'units', 'degrees')
grid_corner_lon_var = ncfile.variables['grid_corner_lon']
setattr(grid_corner_lon_var, 'units', 'degrees')
setattr(ncfile, 'title', ttlname)
setattr(ncfile, 'modifydate', tm)
if hasattr(ncfile, 'grid_name'):
delattr(ncfile, 'grid_name')
if hasattr(ncfile, 'map_method'):
delattr(ncfile, 'map_method')
ncfile.sync()
ncfile.close()
示例14: test_modis
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()
示例15: OPENPIV2D2C
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