本文整理汇总了Python中netCDF4.Dataset.Conventions方法的典型用法代码示例。如果您正苦于以下问题:Python Dataset.Conventions方法的具体用法?Python Dataset.Conventions怎么用?Python Dataset.Conventions使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类netCDF4.Dataset
的用法示例。
在下文中一共展示了Dataset.Conventions方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: init_file
# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import Conventions [as 别名]
def init_file(self, filename, time_units="seconds since 1970-01-01T00:00"):
"""
Initializes netCDF file for writing
Args:
filename: Name of the netCDF file
time_units: Units for the time variable in format "<time> since <date string>"
Returns:
Dataset object
"""
if os.access(filename, os.R_OK):
out_data = Dataset(filename, "r+")
else:
out_data = Dataset(filename, "w")
if len(self.data.shape) == 2:
for d, dim in enumerate(["y", "x"]):
out_data.createDimension(dim, self.data.shape[d])
else:
for d, dim in enumerate(["y", "x"]):
out_data.createDimension(dim, self.data.shape[d+1])
out_data.createDimension("time", len(self.times))
time_var = out_data.createVariable("time", "i8", ("time",))
time_var[:] = date2num(self.times.to_pydatetime(), time_units)
time_var.units = time_units
out_data.Conventions = "CF-1.6"
return out_data
示例2: CreateOutputFile
# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import Conventions [as 别名]
def CreateOutputFile(FileName,data):
# Create file
File = NetCDFFile(FileName,'w')
# Define some global attribs
File.Conventions='COARDS'
# Time is record dimension
File.createDimension('time',None)
var = File.createVariable('time','d',('time',))
var.long_name = 'time'
var.units = 'year'
# axes
try:
File.createDimension('level',data.File.dimensions['level'])
var = File.createVariable('level','f',('level',))
var.long_name = 'pressure level'
var.units = 'mb'
var[:] = data.File.variables['level'][:].astype('f')
except: pass
File.createDimension('lat',data.File.dimensions['lat'])
var = File.createVariable('lat','f',('lat',))
var.long_name = 'latitude'
var.units = 'degrees_north'
var[:] = data.File.variables['lat'][:]
File.createDimension('lon',data.File.dimensions['lon'])
var = File.createVariable('lon','f',('lon',))
var.long_name = 'longitude'
var.units = 'degrees_east'
var[:] = data.File.variables['lon'][:]
# create variables
var = File.createVariable(Field,'f',\
data.Field.dimensions)
var.long_name = data.Field.long_name
var.units = data.Field.units
return File
示例3: new
# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import Conventions [as 别名]
def new(self, secs):
"""
Creates a new seNorge netCDF file.
Convention: Climate and Forecast (CF) version 1.4
@param secs: in seconds since 1970-01-01 00:00:00
"""
# create new file
rootgrp = Dataset(self.filename, 'w') # create new file using netcdf4
# rootgrp = netcdf_file(self.filename, 'w') # create new file using scipy.IO
# add root dimensions
rootgrp.createDimension('time', size=self.default_senorge_time)
rootgrp.createDimension('x', size=self.default_senorge_width)
rootgrp.createDimension('y', size=self.default_senorge_height)
# add root attributes
rootgrp.Conventions = "CF-1.4"
rootgrp.institution = "Norwegian Water Resources and Energy Directorate (NVE)"
rootgrp.source = ""
rootgrp.history = ""
rootgrp.references = ""
rootgrp.comment = "Data distributed via www.senorge.no"
self.rootgrp = rootgrp
# add coordinates
time = self.rootgrp.createVariable('time', 'f8', ('time',))
time.units = 'seconds since 1970-01-01 00:00:00 +00:00'
time.long_name = 'time'
time.standard_name = 'time'
time[:] = secs
self._set_utm()
self._set_latlon()
示例4: writeCMIP5File
# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import Conventions [as 别名]
def writeCMIP5File(modelName,scenario,myvarname,lon,lat,time,mydata,mydataanomaly,outfilename):
myformat='NETCDF3_CLASSIC'
if os.path.exists(outfilename):
os.remove(outfilename)
print "Results written to netcdf file: %s"%(outfilename)
if myvarname=="sic": myvar="SIC"
f1 = Dataset(outfilename, mode='w', format=myformat)
f1.title = "IPCC AR5 %s"%(myvar)
f1.description = "IPCC AR5 running averages of %s for model %s for scenario %s"%(myvar,modelName,scenario)
f1.history = "Created " + str(datetime.now())
f1.source = "Trond Kristiansen ([email protected])"
f1.type = "File in NetCDF3 format created using iceExtract.py"
f1.Conventions = "CF-1.0"
"""Define dimensions"""
f1.createDimension('x', len(lon))
f1.createDimension('y', len(lat))
f1.createDimension('time', None)
vnc = f1.createVariable('longitude', 'd', ('x',),zlib=False)
vnc.long_name = 'Longitude'
vnc.units = 'degree_east'
vnc.standard_name = 'longitude'
vnc[:] = lon
vnc = f1.createVariable('latitude', 'd', ('y',),zlib=False)
vnc.long_name = 'Latitude'
vnc.units = 'degree_north'
vnc.standard_name = 'latitude'
vnc[:] = lat
v_time = f1.createVariable('time', 'd', ('time',),zlib=False)
v_time.long_name = 'Years'
v_time.units = 'Years'
v_time.field = 'time, scalar, series'
v_time[:]=time
v_temp=f1.createVariable('SIC', 'd', ('time', 'y', 'x',),zlib=False)
v_temp.long_name = "Sea-ice area fraction (%)"
v_temp.units = "%"
v_temp.time = "time"
v_temp.field="SIC, scalar, series"
v_temp.missing_value = 1e20
if myvarname=='sic':
f1.variables['SIC'][:,:,:] = mydata
f1.close()
示例5: tamoc_nc_file
# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import Conventions [as 别名]
def tamoc_nc_file(fname, title, summary, source):
"""
Write the header meta data to an netCDF file for a TAMOC output
The TAMOC suite stores its output by detaul in a netCDF dataset file.
This function writes the standard TAMOC metadata to the header of the
netCDF file.
Parameters
----------
fname : str
File name of the file to write
title: str
String stating the TAMOC module where the data originated and the
type of data contained.
summary : str
String summarizing what is contained in the dataset or information
needed to interpret the dataset
source : str
String describing the source of the data in the dataset or of related
datasets
Returns
-------
nc : `netCDF4.Dataset` object
The `netCDF4.Dataset` object containing the open netCDF4 file where
the data should be stored.
"""
# Create the netCDF dataset object
nc = Dataset(fname, 'w', format='NETCDF4_CLASSIC')
# Write the netCDF header data for a TAMOC suite output
nc.Conventions = 'TAMOC Modeling Suite Output File'
nc.Metadata_Conventions = 'TAMOC Python Model'
nc.featureType = 'profile'
nc.cdm_data_type = 'Profile'
nc.nodc_template_version = \
'NODC_NetCDF_Profile_Orthogonal_Template_v1.0'
nc.title = title
nc.summary = summary
nc.source = source
nc.creator_url = 'http://github.com/socolofs/tamoc'
nc.date_created = datetime.today().isoformat(' ')
nc.date_modified = datetime.today().isoformat(' ')
nc.history = 'Creation'
# Return the netCDF dataset
return nc
示例6: interpolate_to_netcdf
# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import Conventions [as 别名]
def interpolate_to_netcdf(self, in_lon, in_lat, out_path, date_unit="seconds since 1970-01-01T00:00",
interp_type="spline"):
"""
Calls the interpolation function and then saves the MRMS data to a netCDF file. It will also create
separate directories for each variable if they are not already available.
"""
if interp_type == "spline":
out_data = self.interpolate_grid(in_lon, in_lat)
else:
out_data = self.max_neighbor(in_lon, in_lat)
if not os.access(out_path + self.variable, os.R_OK):
try:
os.mkdir(out_path + self.variable)
except OSError:
print(out_path + self.variable + " already created")
out_file = out_path + self.variable + "/" + "{0}_{1}_{2}.nc".format(self.variable,
self.start_date.strftime("%Y%m%d-%H:%M"),
self.end_date.strftime("%Y%m%d-%H:%M"))
out_obj = Dataset(out_file, "w")
out_obj.createDimension("time", out_data.shape[0])
out_obj.createDimension("y", out_data.shape[1])
out_obj.createDimension("x", out_data.shape[2])
data_var = out_obj.createVariable(self.variable, "f4", ("time", "y", "x"), zlib=True,
fill_value=-9999.0,
least_significant_digit=3)
data_var[:] = out_data
data_var.long_name = self.variable
data_var.coordinates = "latitude longitude"
if "MESH" in self.variable or "QPE" in self.variable:
data_var.units = "mm"
elif "Reflectivity" in self.variable:
data_var.units = "dBZ"
elif "Rotation" in self.variable:
data_var.units = "s-1"
else:
data_var.units = ""
out_lon = out_obj.createVariable("longitude", "f4", ("y", "x"), zlib=True)
out_lon[:] = in_lon
out_lon.units = "degrees_east"
out_lat = out_obj.createVariable("latitude", "f4", ("y", "x"), zlib=True)
out_lat[:] = in_lat
out_lat.units = "degrees_north"
dates = out_obj.createVariable("time", "i8", ("time",), zlib=True)
dates[:] = np.round(date2num(self.all_dates.to_pydatetime(), date_unit)).astype(np.int64)
dates.long_name = "Valid date"
dates.units = date_unit
out_obj.Conventions="CF-1.6"
out_obj.close()
return
示例7: generate_nc
# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import Conventions [as 别名]
def generate_nc(parser_context):
parser = XLSParser()
with open(parser_context.filepath, 'r') as f:
doc = f.read()
info = parser.extract_worksheets(doc)
nccl = info[parser_context.worksheet]
#header_line = 3
#columns = nccl[header_line]
#data_range = (4, 66)
data_rows = nccl[parser_context.data_range[0]:parser_context.data_range[1]]
print 'Generating',parser_context.output_file
nc = Dataset(parser_context.output_file, 'w')
nc.createDimension('time', len(data_rows)*12)
nc.GDAL = "GDAL 1.9.2, released 2012/10/08"
nc.history = "Created dynamically in IPython Notebook 2013-11-14"
nc.title = nccl[0][0]
nc.summary = nccl[1][0]
nc.naming_authority = 'GLOS'
nc.source = 'GLERL'
nc.standard_name_vocabulary = "http://www.cgd.ucar.edu/cms/eaton/cf-metadata/standard_name.html"
nc.project = 'GLOS'
nc.Conventions = "CF-1.6"
time = nc.createVariable('time', 'f8', ('time',))
time.standard_name = 'time'
time.units = 'seconds since 1970-01-01'
time.long_name = 'Time'
time.axis = 'T'
precip = nc.createVariable(parser_context.variable, 'f8', ('time',), fill_value=parser_context.fill_value)
#precip.standard_name = 'precipitation_amount'
precip.standard_name = parser_context.standard_name
precip.units = parser_context.units
for i,row in enumerate(data_rows):
for j in xrange(12):
the_date = datetime(row[0], j+1, 1)
timestamp = calendar.timegm(the_date.utctimetuple())
time[i*12 + j] = timestamp
try:
value = float(row[j+1])
except ValueError:
continue
except TypeError:
continue
precip[i*12 + j] = value
nc.close()
示例8: write_nc_file
# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import Conventions [as 别名]
def write_nc_file(daily_results, filename, nc, anom_mode=False):
#Grab every 4th time value to represent daily
daily_time_var = nc.variables['time'][::4]
nc_out = Dataset(filename, mode='w', format='NETCDF4')
nc_out.createDimension('lon', LONS)
nc_out.createDimension('lat', LATS)
nc_out.createDimension('time', None) #UNLIMITED
nc_out.createDimension('month', MONTHS_YEAR)
nc_out.title = ''
nc_out.institution = ''
nc_out.project = ''
nc_out.contact = '[email protected]'
nc_out.Conventions = "CF-1.6"
longitude = nc_out.createVariable('lon', 'f8', ('lon',))
longitude.standard_name = 'longitude'
longitude.long_name = 'longitude'
longitude.units = 'degrees_east'
longitude.modulo = 360.0
longitude.axis = 'X'
longitude[:] = np.arange(0, 360.0, 2.0)
latitude = nc_out.createVariable('lat', 'f8', ('lat',))
latitude.standard_name = 'latitude'
latitude.long_name = 'latitude'
latitude.units = 'degrees_north'
latitude.axis = 'Y'
latitude[:] = np.arange(-90.0, 92.0, 2.0)
time = nc_out.createVariable('time', 'f8', ('time',))
time.units = 'hours since 1-1-1 0:0:0'
time.calendar = 'standard' #Gregorian
time[:] = daily_time_var
if anom_mode:
daily_mean = nc_out.createVariable('daily_anom', 'f8', ('time', 'lat', 'lon'))
daily_mean.long_name = 'z500 daily anomaly vs 1981-2010'
else:
daily_mean = nc_out.createVariable('daily_mean', 'f8', ('time', 'lat', 'lon'))
daily_mean.long_name = 'z500 daily mean'
daily_mean[:] = daily_results
nc_out.close()
示例9: createNetCDFFileUV
# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import Conventions [as 别名]
def createNetCDFFileUV(grdROMS, outfilename, myformat, mytype):
if (myformat=='NETCDF4'):
myzlib = True
else:
myzlib = False
if os.path.exists(outfilename):
os.remove(outfilename)
print(('Creating atmospheric forcing file for UV wind - %s'%(outfilename)))
f1 = Dataset(outfilename, mode='w', format=myformat)
f1.title="Atmospheric frocing file used by the ROMS model"
f1.description="Created for the %s grid file"%(grdROMS.grdName)
f1.grdFile="%s"%(grdROMS.grdfilename)
f1.history = 'Created ' + time.ctime(time.time())
f1.source = 'Trond Kristiansen ([email protected])'
f1.type = "File in %s format created using MODEL2ROMS"%(myformat)
f1.link = "https://github.com/trondkr/model2roms"
f1.Conventions = "CF-1.0"
""" Define dimensions """
f1.createDimension('xi_rho', grdROMS.xi_rho)
f1.createDimension('eta_rho', grdROMS.eta_rho)
f1.createDimension('wind_time', None)
vnc = f1.createVariable('lon_rho', 'd', ('eta_rho','xi_rho',),zlib=myzlib, fill_value=grdROMS.fill_value)
vnc.long_name = 'Longitude of RHO-points'
vnc.units = 'degree_east'
vnc.standard_name = 'longitude'
vnc[:,:] = grdROMS.lon_rho
vnc = f1.createVariable('lat_rho', 'd', ('eta_rho','xi_rho',),zlib=myzlib, fill_value=grdROMS.fill_value)
vnc.long_name = 'Latitude of RHO-points'
vnc.units = 'degree_north'
vnc.standard_name = 'latitude'
vnc[:,:] = grdROMS.lat_rho
v_time = f1.createVariable('wind_time', 'd', ('wind_time',),zlib=myzlib, fill_value=grdROMS.fill_value)
if mytype == "NORESM":
v_time.long_name = 'Days since 1800-01-01 00:00:00'
v_time.units = 'Days since 1800-01-01 00:00:00'
else:
v_time.long_name = 'Days since 1948-01-01 00:00:00'
v_time.units = 'Days since 1948-01-01 00:00:00'
v_time.field = 'time, scalar, series'
v_time.calendar='noleap'
v_temp_west=f1.createVariable('Vwind', 'f', ('wind_time', 'eta_rho', 'xi_rho',),zlib=myzlib, fill_value=grdROMS.fill_value)
v_temp_west.long_name = "Eta-component of wind"
v_temp_west.units = "meter second-1"
v_temp_west.field = "Vwind, scalar, series"
v_temp_west.missing_value = grdROMS.fill_value
v_temp_west.time = "wind_time"
v_temp_west=f1.createVariable('Uwind', 'f', ('wind_time', 'eta_rho', 'xi_rho',),zlib=myzlib, fill_value=grdROMS.fill_value)
v_temp_west.long_name = "Xi-component of wind"
v_temp_west.units = "meter second-1"
v_temp_west.field = "Uwind, scalar, series"
v_temp_west.missing_value = grdROMS.fill_value
v_temp_west.time = "wind_time"
f1.close()
示例10: createnetCDF
# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import Conventions [as 别名]
def createnetCDF(fieldfile):
''' Creates the netCDF file to then be opened in field2nc.
'''
ncfile = '/group_workspaces/jasmin/hiresgw/mj07/'+fieldfile+'.theta.nc'
f = Dataset(ncfile,'w')
zres = 180
latres = 768
lonres = 1024
# Create dimensions
time = f.createDimension('time',None)
z_hybrid_height = f.createDimension('z_hybrid_height',zres)
latitude = f.createDimension('latitude',latres)
longitude = f.createDimension('longitude',lonres)
bound = f.createDimension('bound',2)
# Create variables (added s on the end to differentiate between dimensions
# and variables)
times = f.createVariable('time','f4',('time',),zlib=True)
z_hybrid_heights = f.createVariable('z_hybrid_height','f4',
('z_hybrid_height',),zlib=True)
latitudes = f.createVariable('latitude','f4',('latitude',),zlib=True)
bounds_latitude = f.createVariable('bounds_latitude','f8',
('latitude','bound',),zlib=True)
longitudes = f.createVariable('longitude','f4',('longitude',),zlib=True)
bounds_longitude = f.createVariable('bounds_longitude','f8',
('longitude','bound',),zlib=True)
v = f.createVariable('theta','f4',('time','z_hybrid_height','latitude',
'longitude',),zlib=True)
# Add in attributes
f.Conventions = 'CF-1.6'
times.units = 'hours since 1991-03-01 00:00:00'
times.standard_name = 'time'
times.calendar = '360_day'
times.axis = 'T'
z_hybrid_heights.positive = 'up'
z_hybrid_heights.long_name = 'atmosphere hybrid height coordinate'
z_hybrid_heights.standard_name = 'atmosphere_hybrid_height_coordinate'
z_hybrid_heights.units = 'm'
z_hybrid_heights.axis = 'Z'
latitudes.bounds = 'bounds_latitude'
latitudes.units = 'degrees_north'
latitudes.standard_name = 'latitude'
latitudes.point_spacing = 'even'
latitudes.axis = 'Y'
longitudes.bounds = 'bounds_longitude'
longitudes.modulo = 360.
longitudes.point_spacing = 'even'
longitudes.standard_name = 'longitude'
longitudes.units = 'degrees_east'
longitudes.axis = 'X'
longitudes.topology = 'circular'
v.long_name = 'THETA'
v.standard_name = 'air_potential_temperature'
v.units = 'K'
v.missing_value = -1.073742e+09
# Add in values of lat, lon and height
f2 = cdms2.open('/group_workspaces/jasmin/hiresgw/xjanp/'+fieldfile)
var = f2.getVariables()
v2 = var[9]
z2 = f2.getVariables()[0]
zvals = z2.domain[0][0][:]
# Check the length of the latitude dimension
if v2.shape[2] == 768:
latvals = np.linspace(-90+90./768,90-90./768,768)
elif v2.shape[2] == 769:
latvals = np.linspace(-90,90,769)
else: raise ValueError('Unhandled latitude dimension')
# Check the length of the latitude dimension
if v2.shape[3] == 1024 and v2.shape[2] == 768:
lonvals = np.linspace(0,360-306./1024,1024)
elif v2.shape[3] == 1024 and v2.shape[2] == 769:
lonvals = np.linspace(360./(1024*2),360.-360./(1024*2),1024)
else: raise ValueError('Unhandled longitude dimension')
print v2.name_in_file
print v2.shape
#print v2.
latitudes[:] = latvals[:]
longitudes[:] = lonvals[:]
z_hybrid_heights[:] = zvals[:]
f2.close()
f.close()
示例11: len
# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import Conventions [as 别名]
lonsa[:] = lons_anal
latsa[:] = lats_anal
lonsf[:] = lons_fcst
latsf[:] = lats_fcst
conusmask[:] = conusmask_ccpa
thrnumv[:] = xc[:]
thrvalv[:] = thresh[:]
rootgrp.latcorners = [lats_anal[0,0], lats_anal[0,-1], lats_anal[-1,0], lats_anal[-1,-1]]
rootgrp.loncorners = [lons_anal[0,0], lons_anal[0,-1], lons_anal[-1,0], lons_anal[-1,-1]]
rootgrp.stream = "s4" # ????
rootgrp.title = "Reforecast V2 accum. ensemble-mean precip forecast and analyzed CDF + rank correlation"
rootgrp.Conventions = "CF-1.0" # ????
rootgrp.history = "Revised Mar 2016 by Hamill"
rootgrp.institution = \
"Reforecast from ERSL/PSD using NCEP/EMC GEFS, circa 2012"
rootgrp.platform = "Model"
rootgrp.references = "http://www.esrl.noaa.gov/psd/forecasts/reforecast2/"
# ---- open ensemble data file for each year, read in data, and augment cdf
# information for that year if the sample is within the month of interest
# or the neighboring month
rankcorr_fa = -99.99*np.ones((nja,nia),dtype=np.float)
nyears = len(range(2002,2016))
print 'nsamps = ',92*nyears
precipa = np.zeros((nja,nia),dtype=np.float)
precipf3d = np.zeros((92*nyears,njf,nif),dtype=np.float)
示例12: ConvertNCCF
# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import Conventions [as 别名]
def ConvertNCCF(TheFileIn,TheFileOut,TheTimes,TheDaysArray,TheCLats,TheCLongs,TheClimPeriod,TheMissing,TheType):
''' Discover what is in the file '''
''' Open and read in all bits '''
''' Write out in cf compliant style '''
ncf=Dataset(TheFileIn,'r')
nc_dims = list(ncf.dimensions) # list of dimensions [dim for dim in ncf.dimensions]
nc_vars = list(ncf.variables) # list of nc variables [var for var in ncf.variables]
nc_attrs = ncf.ncattrs() # list of global attributes
ndims=len(nc_dims)
nvars=len(nc_vars)
ngatts=len(nc_attrs)
# Get all global attributes
TheGAtts=np.empty(ngatts,dtype=object) # an empty array with the right number of string elements
for (noo,att) in enumerate(nc_attrs): # enumerate and use elements of the list
TheGAtts[noo]=ncf.getncattr(att) # get each global attribute and populate array
# Get all dimensions
TheDims=np.empty(ndims) # an empty array with the right number of string elements
for (noo,dim) in enumerate(nc_dims): # enumerate and use elements of the list
TheDims[noo]=len(ncf.dimensions[dim]) # get length of each dimension
# NO DIMENSION ATTRIBUTES -
# TheDimAttrNames=[[] for i in xrange(ndims)] # create list of lists - one for the attribute names of each dimension
# TheDimAttrs=[[] for i in xrange(ndims)] # create list of lists - one for the attributes of each dimension
# for (noo,dim) in enumerate(nc_dims): # enumerate and use elements of the list
# TheDimAttrNames[noo]=ncf.dimensions[dim].ncattrs() # fill names
# for (nee,nats) in enumerate(TheDimAttrNames[noo]): # loop through each name and get the attribute
# TheDimAttrs[noo][nee]=f.dimensions[dim].getncattr(nats)
# Get all variables, and their attributes
TheVarAttrNames=[[] for i in xrange(nvars)] # create list of lists - one for the attribute names of each dimension
TheVarAttrs=[[] for i in xrange(nvars)] # create list of lists - one for the attributes of each dimension
TheVars=[[] for i in xrange(nvars)] # create list of lists - one for the attributes of each dimension
for (noo,var) in enumerate(nc_vars): # enumerate and use elements of the list
TheVarAttrNames[noo]=ncf.variables[var].ncattrs() # fill names
for (nee,nats) in enumerate(TheVarAttrNames[noo]): # loop through each name and get the attribute
TheVarAttrs[noo].append(ncf.variables[var].getncattr(nats))
TheVars[noo]=ncf.variables[nc_vars[noo]][:]
# Now write out, checking if the standard stuff is not there, and if not, then add in
ncfw=Dataset(TheFileOut,'w',format='NETCDF3_CLASSIC')
# Set up the global attributes
# Is there a description?
moo=np.where(np.array(nc_attrs) == 'description')
if (moo[0] >= 0):
ncfw.description=TheGAtts[moo[0]]
else:
ncfw.description="HadISDH monthly mean land surface "+TheType+" climate monitoring product from 1973 onwards. Quality control, homogenisation, uncertainty estimation, averaging over gridboxes (no smoothing or interpolation)."
# Is there a title?
moo=np.where(np.array(nc_attrs) == 'title')
if (moo[0] >= 0):
ncfw.title=TheGAtts[moo[0]]
else:
ncfw.title="HadISDH monthly mean land surface "+TheType+" climate monitoring product from 1973 onwards."
# Is there an institution?
moo=np.where(np.array(nc_attrs) == 'institution')
if (moo[0] >= 0):
ncfw.institution=TheGAtts[moo[0]]
else:
ncfw.institution="Met Office Hadley Centre (UK), National Climatic Data Centre (USA), Climatic Research Unit (UK), National Physical Laboratory (UK), Bjerknes Centre for Climate Research (Norway)"
# Is there a history?
moo=np.where(np.array(nc_attrs) == 'history')
if (moo[0] >= 0):
ncfw.history=TheGAtts[moo[0]]
else:
ncfw.history="Updated 4 February 2014"
# Is there a source?
moo=np.where(np.array(nc_attrs) == 'source')
if (moo[0] >= 0):
ncfw.source=TheGAtts[moo[0]]
else:
ncfw.source="HadISD.1.0.2.2013f (Dunn et al., 2012)"
# Is there a comment?
moo=np.where(np.array(nc_attrs) == 'comment')
if (moo[0] >= 0):
ncfw.comment=TheGAtts[moo[0]]
else:
ncfw.comment=""
# Is there a reference?
moo=np.where(np.array(nc_attrs) == 'reference')
if (moo[0] >= 0):
ncfw.reference=TheGAtts[moo[0]]
else:
ncfw.reference="Willett, K. M., Dunn, R. J. H., Thorne, P. W., Bell, S., de Podesta, M., Parker, D. E., Jones, P. D., and Williams Jr., C. N.: HadISDH land surface multi-variable humidity and temperature record for climate monitoring, Clim. Past, 10, 1983-2006, doi:10.5194/cp-10-1983-2014, 2014."
# Is there a version?
moo=np.where(np.array(nc_attrs) == 'version')
if (moo[0] >= 0):
ncfw.version=TheGAtts[moo[0]]
else:
ncfw.version="HadISDH.2.0.0.2013p"
# Is there a Conventions?
moo=np.where(np.array(nc_attrs) == 'Conventions')
if (moo[0] >= 0):
ncfw.Conventions=TheGAtts[moo[0]]
else:
ncfw.Conventions="CF-1.0"
#.........这里部分代码省略.........
示例13: Dataset
# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import Conventions [as 别名]
cmplgrp = Dataset('/Users/Bora/Desktop/REU/Bond/DDCode/03.nc','a')
time_1= cmplgrp.createDimension('time', None)
lat= cmplgrp.createDimension('latitude', 241)
lon= cmplgrp.createDimension('longitude', 480)
times= cmplgrp.createVariable('time',np.int32,('time',))
latitudes= cmplgrp.createVariable('latitude',np.float32,('latitude',))
longitudes=cmplgrp.createVariable('longitude',np.float32,('longitude',))
temp= cmplgrp.createVariable('t2m',np.short,('time','latitude','longitude',))
#crs = cmplgrp.createVariable('crs','i4')
import time
cmplgrp.history = 'Created ' + time.ctime(time.time())
cmplgrp.Conventions = 'CF-1.6'
latitudes.long_name = 'latitude'
latitudes.units = 'degrees_north'
longitudes.units = 'degrees_east'
longitudes.long_name='longitude'
times.long_name = 'time'
times.units = 'days since 2000-1-1 0:0:0'
times.calendar='noleap'
temp.long_name = '2 meter temperature averages for 20 years'
temp.units = 'K'
示例14: createinitfile
# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import Conventions [as 别名]
def createinitfile(confM2R, ntime, var, data1=None, data2=None, data3=None, data4=None):
# Create initial file for use with ROMS. This is the same as extracting time 0 from
# the climatology file.
if (confM2R.myformat == 'NETCDF4'):
myzlib = True
else:
myzlib = False
grdROMS = confM2R.grdROMS
if not grdROMS.ioInitInitialized:
grdROMS.ioInitInitialized = True
if os.path.exists(confM2R.initname):
os.remove(confM2R.initname)
f1 = Dataset(confM2R.initname, mode='w', format=confM2R.myformat)
f1.title = "Initial forcing file (INIT) used for foring of the ROMS model"
f1.description = "Created for the %s grid file" % (confM2R.romsgridpath)
f1.grd_file = "Gridfile: %s" % (confM2R.romsgridpath)
f1.history = "Created " + time.ctime(time.time())
f1.source = "Trond Kristiansen ([email protected])"
f1.type = "File in %s format created using MODEL2ROMS" % (confM2R.myformat)
f1.link = "https://github.com/trondkr/model2roms"
f1.Conventions = "CF-1.0"
# Define dimensions
f1.createDimension('xi_rho', grdROMS.xi_rho)
f1.createDimension('eta_rho', grdROMS.eta_rho)
f1.createDimension('xi_u', grdROMS.xi_u)
f1.createDimension('eta_u', grdROMS.eta_u)
f1.createDimension('xi_v', grdROMS.xi_v)
f1.createDimension('eta_v', grdROMS.eta_v)
f1.createDimension('xi_psi', grdROMS.xi_psi)
f1.createDimension('eta_psi', grdROMS.eta_psi)
f1.createDimension('ocean_time', None)
f1.createDimension('s_rho', len(grdROMS.s_rho))
f1.createDimension('s_w', len(grdROMS.s_w))
vnc = f1.createVariable('lon_rho', 'd', ('eta_rho', 'xi_rho',), zlib=myzlib, fill_value=grdROMS.fillval)
vnc.long_name = 'Longitude of RHO-points'
vnc.units = 'degree_east'
vnc.standard_name = 'longitude'
vnc[:, :] = grdROMS.lon_rho
vnc = f1.createVariable('lat_rho', 'd', ('eta_rho', 'xi_rho',), zlib=myzlib, fill_value=grdROMS.fillval)
vnc.long_name = 'Latitude of RHO-points'
vnc.units = 'degree_north'
vnc.standard_name = 'latitude'
vnc[:, :] = grdROMS.lat_rho
vnc = f1.createVariable('lon_u', 'd', ('eta_u', 'xi_u',), zlib=myzlib, fill_value=grdROMS.fillval)
vnc.long_name = 'Longitude of U-points'
vnc.units = 'degree_east'
vnc.standard_name = 'longitude'
vnc[:, :] = grdROMS.lon_u
vnc = f1.createVariable('lat_u', 'd', ('eta_u', 'xi_u',), zlib=myzlib, fill_value=grdROMS.fillval)
vnc.long_name = 'Latitude of U-points'
vnc.units = 'degree_north'
vnc.standard_name = 'latitude'
vnc[:, :] = grdROMS.lat_u
vnc = f1.createVariable('lon_v', 'd', ('eta_v', 'xi_v',), zlib=myzlib, fill_value=grdROMS.fillval)
vnc.long_name = 'Longitude of V-points'
vnc.units = 'degree_east'
vnc.standard_name = 'longitude'
vnc[:, :] = grdROMS.lon_v
vnc = f1.createVariable('lat_v', 'd', ('eta_v', 'xi_v',), zlib=myzlib, fill_value=grdROMS.fillval)
vnc.long_name = 'Latitude of V-points'
vnc.units = 'degree_north'
vnc.standard_name = 'latitude'
vnc[:, :] = grdROMS.lat_v
vnc = f1.createVariable('lat_psi', 'd', ('eta_psi', 'xi_psi',), zlib=myzlib, fill_value=grdROMS.fillval)
vnc.long_name = 'Latitude of PSI-points'
vnc.units = 'degree_north'
vnc.standard_name = 'latitude'
vnc[:, :] = grdROMS.lat_psi
vnc = f1.createVariable('lon_psi', 'd', ('eta_psi', 'xi_psi',), zlib=myzlib, fill_value=grdROMS.fillval)
vnc.long_name = 'Longitude of PSI-points'
vnc.units = 'degree_east'
vnc.standard_name = 'longitude'
vnc[:, :] = grdROMS.lon_psi
vnc = f1.createVariable('h', 'd', ('eta_rho', 'xi_rho',), zlib=myzlib, fill_value=grdROMS.fillval)
vnc.long_name = 'Final bathymetry at RHO points'
vnc.units = 'meter'
vnc.field = "bath, scalar"
vnc[:, :] = grdROMS.h
vnc = f1.createVariable('s_rho', 'd', ('s_rho',), zlib=myzlib, fill_value=grdROMS.fillval)
vnc.long_name = "S-coordinate at RHO-points"
vnc.valid_min = -1.
vnc.valid_max = 0.
vnc.positive = "up"
if grdROMS.vtransform == 2:
vnc.standard_name = "ocean_s_coordinate_g2"
vnc.formula_terms = "s: s_rho C: Cs_r eta: zeta depth: h depth_c: hc"
#.........这里部分代码省略.........
示例15: makenetcdf_
# 需要导入模块: from netCDF4 import Dataset [as 别名]
# 或者: from netCDF4.Dataset import Conventions [as 别名]
#.........这里部分代码省略.........
if fields[4] == "":
sals[i, 0] = -9999
else:
sals[i, 0] = fields[4]
if fields[5] == "":
fco2s[i, 0] = -9999
else:
fco2s[i, 0] = fields[5]
if len(fields[6]) == 0:
fco2qcs[i, 0] = -128
else:
fco2qcs[i, 0] = makeqcvalue_(int(fields[6]))
depthvar[:,:] = depths
positionvar[:,:] = positions
sstvar[:,:] = temps
sssvar[:,:] = sals
fco2var[:,:] = fco2s
fco2qcvar[:,:] = fco2qcs
depthdmvar[:,:] = dms
sstdmvar[:,:] = dms
sssdmvar[:,:] = dms
fco2dmvar[:,:] = dms
# Global attributes
nc.id = filenameroot
nc.data_type = "OceanSITES trajectory data"
nc.netcdf_version = "netCDF-4 classic model"
nc.format_version = "1.2"
nc.Conventions = "CF-1.6 OceanSITES-Manual-1.2 Copernicus-InSituTAC-SRD-1.3 "\
+ "Copernicus-InSituTAC-ParametersList-3.1.0"
nc.cdm_data_type = "Trajectory"
nc.data_mode = "R"
nc.area = "Global Ocean"
nc.geospatial_lat_min = str(minlat)
nc.geospatial_lat_max = str(maxlat)
nc.geospatial_lon_min = str(minlon)
nc.geospatial_lon_max = str(maxlon)
nc.geospatial_vertical_min = "5.00"
nc.geospatial_vertical_max = "5.00"
nc.last_latitude_observation = lats[-1]
nc.last_longitude_observation = lons[-1]
nc.last_date_observation = endtime.strftime("%Y-%m-%dT%H:%M:%SZ")
nc.time_coverage_start = starttime.strftime("%Y-%m-%dT%H:%M:%SZ")
nc.time_coverage_end = endtime.strftime("%Y-%m-%dT%H:%M:%SZ")
#datasetdate = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
#nc.date_update = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
#nc.history = datasetdate + " : Creation"
nc.update_interval = "daily"
nc.data_assembly_center = "BERGEN"
nc.institution = "University of Bergen / Geophysical Institute"
nc.institution_edmo_code = "4595"
nc.institution_references = " "
nc.contact = "[email protected]"
nc.title = "Global Ocean - In Situ near-real time carbon observation"
nc.author = "cmems-service"