本文整理汇总了Python中netCDF4.Dataset.Description方法的典型用法代码示例。如果您正苦于以下问题:Python Dataset.Description方法的具体用法?Python Dataset.Description怎么用?Python Dataset.Description使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类netCDF4.Dataset
的用法示例。
在下文中一共展示了Dataset.Description方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: writeNC
# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import Description [as 别名]
def writeNC(self,outfile):
"""
Export the grid variables to a netcdf file
"""
from netCDF4 import Dataset
from soda.dataio.suntans.suntans_ugrid import ugrid
nc = Dataset(outfile, 'w', format='NETCDF4_CLASSIC')
nc.Description = 'Unstructured grid file'
nc.Author = ''
#nc.Created = datetime.now().isoformat()
nc.createDimension('Nc', self.Nc)
nc.createDimension('Np', self.Np)
try:
nc.createDimension('Ne', self.Ne)
except:
print 'No dimension: Ne'
nc.createDimension('Nk', self.Nkmax)
nc.createDimension('Nkw', self.Nkmax+1)
nc.createDimension('numsides', self.MAXFACES)
nc.createDimension('two', 2)
nc.createDimension('time', 0) # Unlimited
# Write the grid variables
def write_nc_var(var, name, dimensions, attdict, dtype='f8'):
tmp=nc.createVariable(name, dtype, dimensions)
for aa in attdict.keys():
tmp.setncattr(aa,attdict[aa])
nc.variables[name][:] = var
gridvars = ['suntans_mesh','cells','face','nfaces',\
'edges','neigh','grad','xp','yp','xv','yv','xe','ye',\
'normal','n1','n2','df','dg','def',\
'Ac','dv','dz','z_r','z_w','Nk','Nke','mark']
self.Nk += 1 # Set to one-base in the file (reset to zero-base after)
self.suntans_mesh=[0]
for vv in gridvars:
if self.__dict__.has_key(vv):
if self.VERBOSE:
print 'Writing variables: %s'%vv
write_nc_var(self[vv],vv,\
ugrid[vv]['dimensions'],\
ugrid[vv]['attributes'],\
dtype=ugrid[vv]['dtype'])
# Special treatment for "def"
if vv == 'def' and self.__dict__.has_key('DEF'):
if self.VERBOSE:
print 'Writing variables: %s'%vv
write_nc_var(self['DEF'],vv,ugrid[vv]['dimensions'],\
ugrid[vv]['attributes'],\
dtype=ugrid[vv]['dtype'])
nc.close()
self.Nk -= 1 # set back to zero base
示例2: create_nc
# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import Description [as 别名]
def create_nc(self,ncfile):
"""
Create the particle netcdf file
NetCDF variable and dimension names are consistent with partrac data.
"""
if self.verbose:
print '\nInitialising particle netcdf file: %s...\n'%ncfile
# Global Attributes
nc = Dataset(ncfile, 'w', format='NETCDF4_CLASSIC')
nc.Description = 'Particle trajectory file'
nc.Author = os.getenv('USER')
nc.Created = datetime.now().isoformat()
# Dimensions
nc.createDimension('ntrac', self.N)
nc.createDimension('nt', 0) # Unlimited
# Create variables
def create_nc_var( name, dimensions, attdict, dtype='f8'):
tmp=nc.createVariable(name, dtype, dimensions)
for aa in attdict.keys():
tmp.setncattr(aa,attdict[aa])
basetimestr = 'seconds since %s'%(datetime.strftime(self.basetime,\
'%Y-%m-%d %H:%M:%S'))
create_nc_var('tp',('nt'),{'units':basetimestr\
,'long_name':"time at drifter locations"},dtype='f8')
create_nc_var('xp',('ntrac','nt'),{'units':'m',\
'long_name':"Easting coordinate of drifter",'time':'tp'},dtype='f8')
create_nc_var('yp',('ntrac','nt'),{'units':'m',\
'long_name':"Northing coordinate of drifter",'time':'tp'},dtype='f8')
create_nc_var('zp',('ntrac','nt'),{'units':'m',\
'long_name':"vertical position of drifter (negative is downward from surface)",'time':'tp'},dtype='f8')
if self.has_age:
create_nc_var('age',('ntrac','nt'),{'units':'seconds',\
'long_name':"Particle age",'time':'tp'},dtype='f8')
create_nc_var('agemax',('ntrac','nt'),{'units':'seconds',\
'long_name':"Maximum particle age",'time':'tp'},dtype='f8')
# Keep the pointer to the open file as an attribute
self._nc = nc
示例3: initParticleNC
# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import Description [as 别名]
def initParticleNC(self,outfile,Np,age=False):
"""
Export the grid variables to a netcdf file
"""
import os
if self.verbose:
print '\nInitialising particle netcdf file: %s...\n'%outfile
# Global Attributes
nc = Dataset(outfile, 'w', format='NETCDF4_CLASSIC')
nc.Description = 'Particle trajectory file'
nc.Author = os.getenv('USER')
nc.Created = datetime.now().isoformat()
#tseas = self.time_sec[1] - self.time_sec[0]
#nsteps = np.floor(tseas/self.dt)
#nc.nsteps = '%f (number of linear interpolation steps in time between model outputs)'%nsteps
#nc.tseas = '%d (Time step (seconds) between model outputs'%tseas
#nc.dt = '%f (Particle model time steps [seconds])'%self.dt
nc.dataset_location = '%s'%self.ncfile
# Dimensions
nc.createDimension('ntrac', Np)
nc.createDimension('nt', 0) # Unlimited
# Create variables
def create_nc_var( name, dimensions, attdict, dtype='f8'):
tmp=nc.createVariable(name, dtype, dimensions)
for aa in attdict.keys():
tmp.setncattr(aa,attdict[aa])
create_nc_var('tp',('nt'),{'units':'seconds since 1990-01-01 00:00:00','long_name':"time at drifter locations"},dtype='f8')
create_nc_var('xp',('ntrac','nt'),{'units':'m','long_name':"Easting coordinate of drifter",'time':'tp'},dtype='f8')
create_nc_var('yp',('ntrac','nt'),{'units':'m','long_name':"Northing coordinate of drifter",'time':'tp'},dtype='f8')
create_nc_var('zp',('ntrac','nt'),{'units':'m','long_name':"vertical position of drifter (negative is downward from surface)",'time':'tp'},dtype='f8')
if age:
create_nc_var('age',('ntrac','nt'),{'units':'seconds','long_name':"Particle age",'time':'tp'},dtype='f8')
create_nc_var('agemax',('ntrac','nt'),{'units':'seconds','long_name':"Maximum particle age",'time':'tp'},dtype='f8')
nc.close()
示例4: suntans2untrim
# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import Description [as 别名]
def suntans2untrim(ncfile,outfile,tstart,tend,grdfile=None):
"""
Converts a suntans averages netcdf file into untrim format
for use in particle tracking
"""
####
# Step 1: Load the suntans data object
####
sun = Spatial(ncfile,klayer=[-99])
# Calculate some other variables
sun.de = sun.get_edgevar(sun.dv,method='min')
sun.mark[sun.mark==5]=0
sun.mark[sun.mark==3]=2
sun.facemark = np.zeros((sun.Nc,),dtype=np.int)
# Update the grad variable from the ascii grid file if supplied
if not grdfile == None:
print 'Updating grid with ascii values...'
grd = Grid(grdfile)
sun.grad = grd.grad[:,::-1]
###
# Step 2: Write the grid variables to a netcdf file
###
nc = Dataset(outfile,'w',format='NETCDF4_CLASSIC')
# Global variable
nc.Description = 'UnTRIM history file converted from SUNTANS output'
# Write the dimensions
for dd in untrim_griddims.keys():
if dd == 'time':
nc.createDimension(untrim_griddims[dd],0)
elif dd =='numsides':
nc.createDimension(untrim_griddims[dd],sun.maxfaces)
else:
nc.createDimension(untrim_griddims[dd],sun[dd])
for dd in other_dims:
nc.createDimension(dd,other_dims[dd])
###
# Step 3: Initialize all of the grid variables
###
def create_nc_var(name, dimensions, attdict,data=None, \
dtype='f8',zlib=False,complevel=0,fill_value=999999.0):
tmp=nc.createVariable(name, dtype, dimensions,\
zlib=zlib,complevel=complevel,fill_value=fill_value)
for aa in attdict.keys():
tmp.setncattr(aa,attdict[aa])
if not data==None:
nc.variables[name][:] = data
# Make sure the masked cells have a value of -1
mask = sun['cells'].mask.copy()
sun['cells'][mask]=FILLVALUE
sun['face'][mask]=FILLVALUE
for vv in untrim_gridvars.keys():
vname = untrim_gridvars[vv]
print 'Writing grid variable %s (%s)...'%(vname,vv)
if vv=='time':
continue
# add dz_min attribute to z_r variable
if vv == 'z_r':
ugrid[vname]['attributes'].update({'dz_min':1e-5})
#sun[vv][:]=sun[vv][::-1]
sun[vv][:]=sun['z_w'][0:-1][::-1]
# Reverse the order of grad(???)
if vv=='grad':
sun[vv][:]=sun[vv][:,::-1]
## Fix one-based indexing
#if vv in ['cells','edges','grad']:
# mask = sun[vv][:]==-1
# tmp = sun[vv][:]+1
# tmp[mask]=-1
# #sun[vv][:]=sun[vv][:]+1
# create_nc_var(vname,ugrid[vname]['dimensions'],ugrid[vname]['attributes'],\
# data=tmp,dtype=ugrid[vname]['dtype'])
create_nc_var(vname,ugrid[vname]['dimensions'],ugrid[vname]['attributes'],\
data=sun[vv],dtype=ugrid[vname]['dtype'])
# Initialize the two time variables
vname=untrim_gridvars['time']
create_nc_var(vname,ugrid[vname]['dimensions'],ugrid[vname]['attributes'],\
dtype=ugrid[vname]['dtype'])
vname = 'Mesh2_data_time_string'
create_nc_var(vname,ugrid[vname]['dimensions'],ugrid[vname]['attributes'],\
dtype=ugrid[vname]['dtype'])
#.........这里部分代码省略.........
示例5: makeMonoRTMCDF
# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import Description [as 别名]
def makeMonoRTMCDF(sonde_file,alta,T_z,P_z,RH_z):
'''
makeMonoRTMCDF
This function creates a netCDF file containing the thermodynamic profile
that will be used to run the MonoRTM. The netCDF file is formatted off of
the ARM radiosonde format, as Dave Turner's (NSSL) MonoRTM wrapper script
that is called by the MWRoe program requires a netCDF file in this format.
Parameters
----------
sonde_file : a string that is the sonde file name to be written to.
alta : an array containing the height grid [meters]
T_z : an array containing the temperature profile [C]
P_z : an array containing the pressure profile [mb]
RH_z : an array contianing the relative humidity profile [%]
Returns
-------
None
'''
# Initialize the CDF file.
sf_tmp_grp = Dataset(sonde_file, 'w', format='NETCDF3_CLASSIC')
# Set the needed dimensions.
time_dim = sf_tmp_grp.createDimension('time', None)
# Create the needed variables.
base_time = sf_tmp_grp.createVariable('base_time','i4')
time_offset = sf_tmp_grp.createVariable('time_offset','f8',('time',))
pres = sf_tmp_grp.createVariable('pres','f4',('time',))
tdry = sf_tmp_grp.createVariable('tdry','f4',('time',))
rh = sf_tmp_grp.createVariable('rh','f4',('time',))
dp = sf_tmp_grp.createVariable('dp','f4',('time',))
wspd = sf_tmp_grp.createVariable('wspd','f4',('time',))
deg = sf_tmp_grp.createVariable('deg','f4',('time',))
lat = sf_tmp_grp.createVariable('lat','f4',('time',))
lon = sf_tmp_grp.createVariable('lon','f4',('time',))
alt = sf_tmp_grp.createVariable('alt','f4',('time',))
# Set the needed attributes.
sf_tmp_grp.Description = 'Temporary / artificial radiosonde file to generate MonoRTM calcs for the MWR T/Q retrievals'
sf_tmp_grp.Primary_source = 'MWR thermodynamic retrieval primary function: compute_thermodynamic_mwr_retrievals'
sf_tmp_grp.Secondary_source = 'MWR thermodynamic retrieval secondary function: create_temp_sonde_file'
sf_tmp_grp.Time_last_created = tm.ctime(tm.time())
base_time.long_name = 'Time since 1 Jan 1970 00:00:00 UTC'
base_time.units = 'seconds'
time_offset.long_name = 'Time offset from base_time'
time_offset.units = 'seconds'
pres.long_name = 'Pressure'
pres.units = 'hPa'
tdry.long_name = 'Dry bulb temperature'
tdry.units = 'C'
rh.long_name = 'Relative humidity'
rh.units = '%'
dp.long_name = 'Dewpoint temperature'
dp.units = 'C'
wspd.long_name = 'Wind speed'
wspd.units = 'm/s'
deg.long_name = 'Wind direction'
deg.units = 'Degrees'
lat.long_name = 'Latitude'
lat.units = 'degrees North'
lon.long_name = 'Longitude'
lon.units = 'degrees East'
alt.long_name = 'Altitude above mean sea level'
alt.units = 'm'
alt_nums = np.array(range(len(alta)))
# Set the variables using the input profiles.
base_time[:] = int(tm.time())
time_offset[:] = 2 * alt_nums
pres[:] = P_z
tdry[:] = T_z
rh[:] = RH_z
dp[:] = 1.0 * alt_nums
wspd[:] = 1.0 * alt_nums
deg[:] = 1.0 * alt_nums
lat[:] = 1.0 * alt_nums
lon[:] = 1.0 * alt_nums
alt[:] = alta
# Close the CDF file.
sf_tmp_grp.close()
# Set the permissions for the CDF file.
os.system ("chmod 744" + " " + sonde_file)
示例6: writeNC
# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import Description [as 别名]
def writeNC(self, outfile):
"""
This function is used to create the netcdf file
"""
print 'under developing'
####create netcdf File####
nc = Dataset(outfile, 'w', format='NETCDF4_CLASSIC')
nc.Description = 'SUNTANS History file'
nc.Author = ''
nc.Created = datetime.now().isoformat()
####Create dimensions####
nc.createDimension('NVwind', self.Nstation)
nc.createDimension('NTair', self.Nstation)
nc.createDimension('Nrain', self.Nstation)
nc.createDimension('NUwind', self.Nstation)
nc.createDimension('NPair', self.Nstation)
nc.createDimension('NRH', self.Nstation)
nc.createDimension('Ncloud', self.Nstation)
nc.createDimension('nt', self.Nt)
nc.close()
####adding variables####
self.create_nc_var(outfile,'x_Vwind',('NVwind'),{'long_name':'Longitude at Vwind','units':'degrees_north'})
self.create_nc_var(outfile,'y_Vwind',('NVwind'),{'long_name':'Latitude at Vwind','units':'degrees_east'})
self.create_nc_var(outfile,'z_Vwind',('NVwind'),{'long_name':'Elevation at Vwind','units':'m'})
self.create_nc_var(outfile,'x_Tair',('NTair'),{'long_name':'Longitude at Tair','units':'degrees_north'})
self.create_nc_var(outfile,'y_Tair',('NTair'),{'long_name':'Latitude at Tair','units':'degrees_east'})
self.create_nc_var(outfile,'z_Tair',('NTair'),{'long_name':'Elevation at Tair','units':'m'})
self.create_nc_var(outfile,'x_rain',('Nrain'),{'long_name':'Longitude at rain','units':'degrees_north'})
self.create_nc_var(outfile,'y_rain',('Nrain'),{'long_name':'Latitude at rain','units':'degrees_east'})
self.create_nc_var(outfile,'z_rain',('Nrain'),{'long_name':'Elevation at rain','units':'m'})
self.create_nc_var(outfile,'x_Uwind',('NUwind'),{'long_name':'Longitude at Uwind','units':'degrees_north'})
self.create_nc_var(outfile,'y_Uwind',('NUwind'),{'long_name':'Latitude at Uwind','units':'degrees_east'})
self.create_nc_var(outfile,'z_Uwind',('NUwind'),{'long_name':'Elevation at Uwind','units':'m'})
self.create_nc_var(outfile,'x_Pair',('NPair'),{'long_name':'Longitude at Pair','units':'degrees_north'})
self.create_nc_var(outfile,'y_Pair',('NPair'),{'long_name':'Latitude at Pair','units':'degrees_east'})
self.create_nc_var(outfile,'z_Pair',('NPair'),{'long_name':'Elevation at Pair','units':'m'})
self.create_nc_var(outfile,'x_RH',('NRH'),{'long_name':'Longitude at RH','units':'degrees_north'})
self.create_nc_var(outfile,'y_RH',('NRH'),{'long_name':'Latitude at RH','units':'degrees_east'})
self.create_nc_var(outfile,'z_RH',('NRH'),{'long_name':'Elevation at RH','units':'m'})
self.create_nc_var(outfile,'x_cloud',('Ncloud'),{'long_name':'Longitude at cloud','units':'degrees_north'})
self.create_nc_var(outfile,'y_cloud',('Ncloud'),{'long_name':'Latitude at cloud','units':'degrees_east'})
self.create_nc_var(outfile,'z_cloud',('Ncloud'),{'long_name':'Elevation at cloud','units':'m'})
self.create_nc_var(outfile,'Time',('nt'),{'units':'seconds since 1990-01-01 00:00:00','long_name':'time'})
self.create_nc_var(outfile,'Vwind',('nt','NVwind'),{'units':'m s-1','long_name':'Northward wind velocity component','coordinates':'x_Vwind,y_Vwind'})
self.create_nc_var(outfile,'Tair',('nt','NTair'),{'units':'Celsius','long_name':'Air Temperature','coordinates':'x_Tair,y_Tair'})
self.create_nc_var(outfile,'rain',('nt','Nrain'),{'units':'kg m2 s-1','long_name':'rain fall rate','coordinates':'x_rain,y_rain'})
self.create_nc_var(outfile,'Uwind',('nt','NUwind'),{'long_name':'Eastward wind velocity component','coordinates':'x_Uwind,y_Uwind','units':'m s-1'})
self.create_nc_var(outfile,'Pair',('nt','NPair'),{'units':'hPa','long_name':'Air Pressure','coordinates':'x_Pair,y_Pair'})
self.create_nc_var(outfile,'RH',('nt','NRH'),{'units':'percent','long_name':'Relative Humidity','coordinates':'x_RH,y_RH'})
self.create_nc_var(outfile,'cloud',('nt','Ncloud'),{'units':'dimensionless','long_name':'Cloud cover fraction','coordinates':'x_cloud,y_cloud'})
######Now writting the variables######
nc = Dataset(outfile,'a')
nc.variables['x_Vwind'][:]=self.lat
nc.variables['y_Vwind'][:]=self.lon
nc.variables['z_Vwind'][:]=self.z
nc.variables['x_Tair'][:]=self.lat
nc.variables['y_Tair'][:]=self.lon
nc.variables['z_Tair'][:]=self.z
nc.variables['x_rain'][:]=self.lat
nc.variables['y_rain'][:]=self.lon
nc.variables['z_rain'][:]=self.z
nc.variables['x_Uwind'][:]=self.lat
nc.variables['y_Uwind'][:]=self.lon
nc.variables['z_Uwind'][:]=self.z
nc.variables['x_Pair'][:]=self.lat
nc.variables['y_Pair'][:]=self.lon
nc.variables['z_Pair'][:]=self.z
nc.variables['x_RH'][:]=self.lat
nc.variables['y_RH'][:]=self.lon
nc.variables['z_RH'][:]=self.z
nc.variables['x_cloud'][:]=self.lat
nc.variables['y_cloud'][:]=self.lon
nc.variables['z_cloud'][:]=self.z
nc.variables['Time'][:]=self.time
nc.variables['Vwind'][:]=self.Vwind
nc.variables['Tair'][:]=self.Tair
nc.variables['rain'][:]=self.rain
nc.variables['Uwind'][:]=self.Uwind
nc.variables['Pair'][:]=self.Pair
nc.variables['RH'][:]=self.RH
nc.variables['cloud'][:]=self.cloud
#.........这里部分代码省略.........
示例7: make_3D_NetCDF
# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import Description [as 别名]
def make_3D_NetCDF(ncfilename, wd, debug=False):
""" Create NetCDF of 3D arrays for all variables in 2D NetCDF file
Takes a table form NetCDF and build 3D arrays from lat and lon
in the given file. """
# --- Read existing & setup new NetCDF file
ncfile2D = Dataset(ncfilename, 'r', format='NETCDF4')
# Setup dimensions
vars = ncfile2D.variables
if debug:
print[i for i in vars]
lats, lons, Epoch = [ncfile2D[i] for i in 'LAT', 'LON', 'Epoch']
if debug:
print[len(i) for i in lats, lons, Epoch]
lats, lons, Epoch = [np.array(i) for i in lats, lons, Epoch]
lats, lons = [list(sorted(set(i))) for i in lats, lons]
# remove fill value. ( 9.969209968386869e+36 ) <= Improve this approach...
[i.pop(-1) for i in lons, lats]
# setup 3D NetCDF file
ncfilename = ncfilename.split('.nc')[0]+'_3D.nc'
ncfile = Dataset(ncfilename, 'w', format='NETCDF4')
ncfile.createDimension('lat', len(lats))
ncfile.createDimension('lon', len(lons))
ncfile.createDimension('time', None)
# Define the coordinate variables. They will hold the coordinate
# information, that is, the latitudes and longitudes.
time = ncfile.createVariable('time', 'f4', ('time',))
lat = ncfile.createVariable('lat', 'f4', ('lat',))
lon = ncfile.createVariable('lon', 'f4', ('lon',))
# --- Add meta data
# Assign units attributes to coordinate var data. This attaches a
# text attribute to each of the coordinate variables, containing the
# units.
lat.units = 'degrees_north'
lat.long_name = 'Latitude'
lat.standard_name = 'Latitude'
lat.axis = "Y"
lon.units = 'degrees_east'
lon.long_name = 'Longitude'
lon.standard_name = 'Longitude'
lon.axis = "X"
time.units = 'seconds since 1970-01-01 00:00:00'
time.calendar = "standard"
time.standard_name = 'Time'
time.axis = "T"
# set global varibles
ncfile.Description = 'planeflight output from '.format(wd)
ncfile.Contact = 'Tomas Sherwen ([email protected])'
# ncfile.History = 'Created {}'.format( time.ctime(time.time()) )
ncfile.Grid = 'lat: {}-{}, lon: {}-{}'.format(lats[0], lats[-1],
lons[0], lons[-1])
# ncfile.Temp_Res = "Hourly"
# ncfile.SpatialCoverage='Global'
# write data to coordinate vars.
lon[:] = lons
lat[:] = lats
# Get unique timesteps
timesteps = sorted(set(Epoch))
# masked 1st value ( headers? )
timesteps.pop(0)
# set time dimension to timestep values
time[:] = timesteps
# select only 3D vars
vars3D = get_3D_vars(vars)
# --- Loop 3D species and create variables (with set dimensions)
for var in vars3D:
ncfile.createVariable(var, var2type(var), ('time', 'lat', 'lon'), )
# close NetCDF
ncfile.close()
# --- Loop through timesteps (epoch) and add to NetCDF
# Loop over timesteps
for t in timesteps:
# open NetCDF in append mode
ncfile = Dataset(ncfilename, 'a', format='NETCDF4')
# get 1st and last indices for time stamp
start, end = [(i.min(), i.max())
for i in np.where(ncfile2D.variables['Epoch'] == t)][0]
# Extract Data for timestep & species
for var in vars3D:
data_ = ncfile2D.variables[var][start:end]
lons_ = ncfile2D.variables['LON'][start:end]
#.........这里部分代码省略.........