本文整理汇总了Python中cf_units.Unit类的典型用法代码示例。如果您正苦于以下问题:Python Unit类的具体用法?Python Unit怎么用?Python Unit使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Unit类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _add_iris_coord
def _add_iris_coord(cube, name, points, dim, calendar=None):
"""
Add a Coord to a Cube from a Pandas index or columns array.
If no calendar is specified for a time series, Gregorian is assumed.
"""
units = Unit("unknown")
if calendar is None:
calendar = cf_units.CALENDAR_GREGORIAN
# Convert pandas datetime objects to python datetime obejcts.
if isinstance(points, DatetimeIndex):
points = np.array([i.to_datetime() for i in points])
# Convert datetime objects to Iris' current datetime representation.
if points.dtype == object:
dt_types = (datetime.datetime, netcdftime.datetime)
if all([isinstance(i, dt_types) for i in points]):
units = Unit("hours since epoch", calendar=calendar)
points = units.date2num(points)
points = np.array(points)
if (np.issubdtype(points.dtype, np.number) and
iris.util.monotonic(points, strict=True)):
coord = DimCoord(points, units=units)
coord.rename(name)
cube.add_dim_coord(coord, dim)
else:
coord = AuxCoord(points, units=units)
coord.rename(name)
cube.add_aux_coord(coord, dim)
示例2: units_convertible
def units_convertible(units1, units2, reftimeistime=True):
"""Return True if a Unit representing the string units1 can be converted
to a Unit representing the string units2, else False."""
try:
u1 = Unit(units1)
u2 = Unit(units2)
except ValueError:
return False
return u1.is_convertible(units2)
示例3: _convert_coord_unit_to_datetime
def _convert_coord_unit_to_datetime(coord, dt):
"""Converts a datetime to be in the unit of a specified Coord.
"""
if isinstance(coord, iris.coords.Coord):
# The unit class is then cf_units.Unit.
iris_unit = coord.units
else:
iris_unit = Unit(coord.units)
return iris_unit.num2date(dt)
示例4: test_360_day_calendar
def test_360_day_calendar(self):
n = 360
calendar = '360_day'
time_unit = Unit('days since 1970-01-01 00:00', calendar=calendar)
time_coord = AuxCoord(np.arange(n), 'time', units=time_unit)
expected_ydata = np.array([CalendarDateTime(time_unit.num2date(point),
calendar)
for point in time_coord.points])
line1, = iplt.plot(time_coord)
result_ydata = line1.get_ydata()
self.assertArrayEqual(expected_ydata, result_ydata)
示例5: test_gregorian_calendar_conversion_setup
def test_gregorian_calendar_conversion_setup(self):
# Reproduces a situation where a unit's gregorian calendar would not
# match (using the `is` operator) to the literal string 'gregorian',
# causing an `is not` test to return a false negative.
cal_str = cf_units.CALENDAR_GREGORIAN
calendar = self.MyStr(cal_str)
self.assertIsNot(calendar, cal_str)
u1 = Unit('hours since 1970-01-01 00:00:00', calendar=calendar)
u2 = Unit('hours since 1969-11-30 00:00:00', calendar=calendar)
u1point = np.array([8.], dtype=np.float32)
expected = np.array([776.], dtype=np.float32)
result = u1.convert(u1point, u2)
return expected, result
示例6: test_360_day_calendar
def test_360_day_calendar(self):
n = 360
calendar = '360_day'
time_unit = Unit('days since 1970-01-01 00:00', calendar=calendar)
time_coord = AuxCoord(np.arange(n), 'time', units=time_unit)
times = [time_unit.num2date(point) for point in time_coord.points]
times = [netcdftime.datetime(atime.year, atime.month, atime.day,
atime.hour, atime.minute, atime.second)
for atime in times]
expected_ydata = np.array([CalendarDateTime(time, calendar)
for time in times])
line1, = iplt.plot(time_coord)
result_ydata = line1.get_ydata()
self.assertArrayEqual(expected_ydata, result_ydata)
示例7: __init__
def __init__(self):
self.u = Unit('days since 1600-01-01 00:00:00', calendar=CALENDAR_STANDARD)
self.points = np.arange(1, 5, 1)
self.coord = iris.coords.DimCoord(self.points, units=self.u)
self.start = datetime.datetime(2000, 1, 1)
self.end = datetime.datetime(2003, 4, 24)
self.start = self.u.date2num(self.start)
self.end = self.u.date2num(self.end)
示例8: setUp
def setUp(self):
self.section = {"year": 2007, "month": 1, "day": 15, "hour": 0, "minute": 3, "second": 0}
self.unit = Unit("hours since epoch", calendar=CALENDAR_GREGORIAN)
dt = datetime(
self.section["year"],
self.section["month"],
self.section["day"],
self.section["hour"],
self.section["minute"],
self.section["second"],
)
self.point = self.unit.date2num(dt)
示例9: setUp
def setUp(self):
self.section = {'year': 2007,
'month': 1,
'day': 15,
'hour': 0,
'minute': 3,
'second': 0}
self.unit = Unit('hours since epoch', calendar=CALENDAR_GREGORIAN)
dt = datetime(self.section['year'], self.section['month'],
self.section['day'], self.section['hour'],
self.section['minute'], self.section['second'])
self.point = self.unit.date2num(dt)
示例10: Test
class Test(tests.IrisTest):
def setUp(self):
self.section = {'year': 2007,
'month': 1,
'day': 15,
'hour': 0,
'minute': 3,
'second': 0}
self.unit = Unit('hours since epoch', calendar=CALENDAR_GREGORIAN)
dt = datetime(self.section['year'], self.section['month'],
self.section['day'], self.section['hour'],
self.section['minute'], self.section['second'])
self.point = self.unit.date2num(dt)
def _check(self, section, standard_name=None):
expected = DimCoord(self.point, standard_name=standard_name,
units=self.unit)
# The call being tested.
coord = reference_time_coord(section)
self.assertEqual(coord, expected)
def test_start_of_forecast_0(self):
section = deepcopy(self.section)
section['significanceOfReferenceTime'] = 0
self._check(section, 'forecast_reference_time')
def test_start_of_forecast_1(self):
section = deepcopy(self.section)
section['significanceOfReferenceTime'] = 1
self._check(section, 'forecast_reference_time')
def test_observation_time(self):
section = deepcopy(self.section)
section['significanceOfReferenceTime'] = 3
self._check(section, 'time')
def test_unknown_significance(self):
section = deepcopy(self.section)
section['significanceOfReferenceTime'] = 5
emsg = 'unsupported significance'
with self.assertRaisesRegexp(TranslationError, emsg):
self._check(section)
示例11: Test
class Test(tests.IrisTest):
def setUp(self):
self.section = {"year": 2007, "month": 1, "day": 15, "hour": 0, "minute": 3, "second": 0}
self.unit = Unit("hours since epoch", calendar=CALENDAR_GREGORIAN)
dt = datetime(
self.section["year"],
self.section["month"],
self.section["day"],
self.section["hour"],
self.section["minute"],
self.section["second"],
)
self.point = self.unit.date2num(dt)
def _check(self, section, standard_name=None):
expected = DimCoord(self.point, standard_name=standard_name, units=self.unit)
# The call being tested.
coord = reference_time_coord(section)
self.assertEqual(coord, expected)
def test_start_of_forecast(self):
section = deepcopy(self.section)
section["significanceOfReferenceTime"] = 1
self._check(section, "forecast_reference_time")
def test_observation_time(self):
section = deepcopy(self.section)
section["significanceOfReferenceTime"] = 3
self._check(section, "time")
def test_unknown_significance(self):
section = deepcopy(self.section)
section["significanceOfReferenceTime"] = 0
emsg = "unsupported significance"
with self.assertRaisesRegexp(TranslationError, emsg):
self._check(section)
示例12: _check_variable_attrs
def _check_variable_attrs(dataset, var_name, required_attributes=None):
'''
Convenience method to check a variable attributes based on the
expected_vars dict
'''
score = 0
out_of = 0
messages = []
if var_name not in dataset.variables:
# No need to check the attrs if the variable doesn't exist
return (score, out_of, messages)
var = dataset.variables[var_name]
# Get the expected attrs to check
check_attrs = required_attributes or required_var_attrs.get(var_name, {})
var_attrs = set(var.ncattrs())
for attr in check_attrs:
if attr == 'dtype':
# dtype check is special, see above
continue
out_of += 1
score += 1
# Check if the attribute is present
if attr not in var_attrs:
messages.append('Variable {} must contain attribute: {}'
''.format(var_name, attr))
score -= 1
continue
# Attribute exists, let's check if there was a value we need to compare against
if check_attrs[attr] is not None:
if getattr(var, attr) != check_attrs[attr]:
# No match, this may be an error, but first an exception for units
if attr == 'units':
msg = ('Variable {} units attribute must be '
'convertible to {}'.format(var_name, check_attrs[attr]))
try:
cur_unit = Unit(var.units)
comp_unit = Unit(check_attrs[attr])
if not cur_unit.is_convertible(comp_unit):
messages.append(msg)
score -= 1
except ValueError:
messages.append(msg)
score -= 1
else:
messages.append('Variable {} attribute {} must be {}'.format(var_name, attr, check_attrs[attr]))
score -= 1
else:
# Final check to make sure the attribute isn't an empty string
try:
# try stripping whitespace, and return an error if empty
att_strip = getattr(var, attr).strip()
if not att_strip:
messages.append('Variable {} attribute {} is empty'
''.format(var_name, attr))
score -= 1
except AttributeError:
pass
return (score, out_of, messages)
示例13: NAME_to_cube
def NAME_to_cube(filenames, callback):
"""
Returns a generator of cubes given a list of filenames and a callback.
"""
for filename in filenames:
header, column_headings, data_arrays = load_NAME_III(filename)
for i, data_array in enumerate(data_arrays):
# turn the dictionary of column headers with a list of header
# information for each field into a dictionary of headers for just
# this field. Ignore the first 4 columns of grid position (data was
# located with the data array).
field_headings = dict((k, v[i + 4])
for k, v in column_headings.items())
# make an cube
cube = iris.cube.Cube(data_array)
# define the name and unit
name = ('%s %s' % (field_headings['species'],
field_headings['quantity']))
name = name.upper().replace(' ', '_')
cube.rename(name)
# Some units are badly encoded in the file, fix this by putting a
# space in between. (if gs is not found, then the string will be
# returned unchanged)
cube.units = field_headings['unit'].replace('gs', 'g s')
# define and add the singular coordinates of the field (flight
# level, time etc.)
cube.add_aux_coord(icoords.AuxCoord(field_headings['z_level'],
long_name='flight_level',
units='1'))
# define the time unit and use it to serialise the datetime for the
# time coordinate
time_unit = Unit('hours since epoch', calendar=CALENDAR_GREGORIAN)
time_coord = icoords.AuxCoord(
time_unit.date2num(field_headings['time']),
standard_name='time',
units=time_unit)
cube.add_aux_coord(time_coord)
# build a coordinate system which can be referenced by latitude and
# longitude coordinates
lat_lon_coord_system = icoord_systems.GeogCS(6371229)
# build regular latitude and longitude coordinates which have
# bounds
start = header['X grid origin'] + header['X grid resolution']
step = header['X grid resolution']
count = header['X grid size']
pts = start + np.arange(count, dtype=np.float32) * step
lon_coord = icoords.DimCoord(pts, standard_name='longitude',
units='degrees',
coord_system=lat_lon_coord_system)
lon_coord.guess_bounds()
start = header['Y grid origin'] + header['Y grid resolution']
step = header['Y grid resolution']
count = header['Y grid size']
pts = start + np.arange(count, dtype=np.float32) * step
lat_coord = icoords.DimCoord(pts, standard_name='latitude',
units='degrees',
coord_system=lat_lon_coord_system)
lat_coord.guess_bounds()
# add the latitude and longitude coordinates to the cube, with
# mappings to data dimensions
cube.add_dim_coord(lat_coord, 0)
cube.add_dim_coord(lon_coord, 1)
# implement standard iris callback capability. Although callbacks
# are not used in this example, the standard mechanism for a custom
# loader to implement a callback is shown:
cube = iris.io.run_callback(callback, cube,
[header, field_headings, data_array],
filename)
# yield the cube created (the loop will continue when the next()
# element is requested)
yield cube
示例14: units_temporal
def units_temporal(units):
u = Unit(units)
return u.is_time_reference()
示例15: test_non_gregorian_calendar_conversion_dtype
def test_non_gregorian_calendar_conversion_dtype(self):
data = np.arange(4, dtype=np.float32)
u1 = Unit('hours since 2000-01-01 00:00:00', calendar='360_day')
u2 = Unit('hours since 2000-01-02 00:00:00', calendar='360_day')
result = u1.convert(data, u2)
self.assertEqual(result.dtype, np.float32)