The Unit Class¶
The primary functionality of cf_units
is supplied by the Unit
class:
- class cf_units.Unit(unit, calendar=None)[source]¶
A class to represent S.I. units and support common operations to manipulate such units in a consistent manner as per UDUNITS-2.
These operations include scaling the unit, offsetting the unit by a constant or time, inverting the unit, raising the unit by a power, taking a root of the unit, taking a log of the unit, multiplying the unit by a constant or another unit, dividing the unit by a constant or another unit, comparing units, copying units and converting unit data to single precision or double precision floating point numbers.
This class also supports time and calendar defintion and manipulation.
- calendar = None¶
Represents the unit calendar name, see cf_units.CALENDARS
- category = None¶
Is this an unknown unit, a no-unit, or a UDUNITS-2 unit.
- property cftime_unit¶
Returns a string suitable for passing as a unit to cftime.num2date and cftime.date2num.
- change_calendar(calendar)[source]¶
Returns a new unit with the requested calendar, modifying the reference date if necessary. Only works with calendars that represent the real world (standard, proleptic_gregorian, julian) and with short time intervals (days or less).
For example:
>>> from cf_units import Unit >>> u = Unit('days since 1500-01-01', calendar='proleptic_gregorian') >>> u.change_calendar('standard') Unit('days since 1499-12-23T00:00:00', calendar='standard')
- convert(value, other, ctype=<class 'numpy.float64'>, inplace=False)[source]¶
Converts a single value or NumPy array of values from the current unit to the other target unit.
If the units are not convertible, then no conversion will take place.
Args:
- value (int/float/numpy.ndarray):
Value/s to be converted.
- other (string/Unit):
Target unit to convert to.
- ctype (cf_units.FLOAT32/cf_units.FLOAT64):
Floating point 32-bit single-precision (cf_units.FLOAT32) or 64-bit double-precision (cf_units.FLOAT64) used for conversion when value is not a NumPy array or is a NumPy array composed of NumPy integers. The default is 64-bit double-precision conversion.
- inplace (bool):
If
False
, return a deep copy of the value array. IfTrue
, convert the values in-place. A new array will be created ifvalue
is an integer NumPy array.
- Returns:
float or numpy.ndarray of appropriate float type.
For example:
>>> import cf_units >>> import numpy as np >>> c = cf_units.Unit('deg_c') >>> f = cf_units.Unit('deg_f') >>> c.convert(0, f) 31.999999999999886 >>> c.convert(0, f, cf_units.FLOAT32) 32.0 >>> a64 = np.arange(3, dtype=np.float64) >>> c.convert(a64, f) array([32. , 33.8, 35.6]) >>> a32 = np.arange(3, dtype=np.float32) >>> c.convert(a32, f) array([32. , 33.8, 35.6], dtype=float32)
Note
Conversion between unit calendars is not permitted unless the calendars are aliases, see
cf_units.CALENDAR_ALIASES
.>>> from cf_units import Unit >>> a = Unit('days since 1850-1-1', calendar='gregorian') >>> b = Unit('days since 1851-1-1', calendar='standard') >>> a.convert(365.75, b) 0.75
- date2num(date)[source]¶
Returns the numeric time value calculated from the datetime object using the current calendar and unit time reference.
The current unit time reference must be of the form: ‘<time-unit> since <time-origin>’ i.e. ‘hours since 1970-01-01 00:00:00’
Works for scalars, sequences and numpy arrays. Returns a scalar if input is a scalar, else returns a numpy array.
Return type will be of type integer if (all) the times can be encoded exactly as an integer with the specified units, otherwise a float type will be returned.
Args:
- date (datetime):
A datetime object or a sequence of datetime objects. The datetime objects should not include a time-zone offset.
- Returns:
float/integer or numpy.ndarray of floats/integers
For example:
>>> import cf_units >>> import datetime >>> u = cf_units.Unit('hours since 1970-01-01 00:00:00', ... calendar=cf_units.CALENDAR_STANDARD) >>> u.date2num(datetime.datetime(1970, 1, 1, 5, 30)) 5.5 >>> u.date2num([datetime.datetime(1970, 1, 1, 5, 30), ... datetime.datetime(1970, 1, 1, 6, 30)]) array([5.5, 6.5]) >>> # Integer type preferentially returned if possible: >>> u.date2num([datetime.datetime(1970, 1, 1, 5, 0), ... datetime.datetime(1970, 1, 1, 6, 0)]) array([5, 6])
- property definition¶
(read-only) The symbolic decomposition of the unit.
Formats the binary unit into a string representation using method
cf_units.Unit.format()
with keyword argument option=cf_units.UT_DEFINITION.- Returns:
string.
For example:
>>> import cf_units >>> u = cf_units.Unit('watts') >>> u.definition 'm2.kg.s-3'
- format(option=None)[source]¶
Return a formatted string representation of the binary unit.
Args:
- option (cf_units.UT_FORMATS):
Set the option of the formatted string representation. Valid encoding options may be at most one of the following enumerations: * Unit.UT_ASCII * Unit.UT_ISO_8859_1 * Unit.UT_LATIN1 * Unit.UT_UTF8
Any combination of the following may also be used: * Unit.UT_NAMES * Unit.UT_DEFINITION
Multiple options may be combined within a list. The default option is cf_units.UT_ASCII.
- Returns:
string.
For example:
>>> import cf_units >>> u = cf_units.Unit('meters') >>> u.format() 'm' >>> u.format(cf_units.UT_NAMES) 'meter' >>> u.format(cf_units.UT_DEFINITION) 'm'
- invert()[source]¶
Invert the unit i.e. find the reciprocal of the unit, and return the Unit result.
- Returns:
Unit.
For example:
>>> import cf_units >>> u = cf_units.Unit('meters') >>> u.invert() Unit('m-1')
- is_convertible(other)[source]¶
Return whether two units are convertible.
Args:
other (Unit): Unit to be compared.
- Returns:
Boolean.
For example:
>>> import cf_units >>> u = cf_units.Unit('meters') >>> v = cf_units.Unit('kilometers') >>> u.is_convertible(v) True
- is_dimensionless()[source]¶
Return whether the unit is dimensionless.
- Returns:
Boolean.
For example:
>>> import cf_units >>> u = cf_units.Unit('meters') >>> u.is_dimensionless() False >>> u = cf_units.Unit('1') >>> u.is_dimensionless() True
- is_long_time_interval()[source]¶
Defines whether this unit describes a time unit with a long time interval (“months” or “years”). These long time intervals are supported by UDUNITS2 but are not supported by cftime. This discrepancy means we cannot run self.num2date() on a time unit with a long time interval.
Deprecated since version 3.3.0: Invalid long time intervals are now defended against within cftime - do not use this routine, as cftime knows best what it can and cannot support.
- Returns:
Boolean.
For example:
>>> import cf_units >>> u = cf_units.Unit('days since epoch') >>> u.is_long_time_interval() False >>> u = cf_units.Unit('years since epoch') >>> u.is_long_time_interval() True
- is_no_unit()[source]¶
Return whether the unit is defined to be a no_unit unit.
Typically, a quantity such as a string, will have no associated unit to describe it. Such a class of quantity may be defined using the no_unit unit.
- Returns:
Boolean.
For example:
>>> import cf_units >>> u = cf_units.Unit('no unit') >>> u.is_no_unit() True >>> u = cf_units.Unit('meters') >>> u.is_no_unit() False
- is_time()[source]¶
Determine whether this unit is a related SI Unit of time.
- Returns:
Boolean.
For example:
>>> import cf_units >>> u = cf_units.Unit('hours') >>> u.is_time() True >>> v = cf_units.Unit('meter') >>> v.is_time() False
- is_time_reference()[source]¶
Return whether the unit is a time reference unit of the form ‘<time-unit> since <time-origin>’ i.e. unit=’days since 1970-01-01 00:00:00’
- Returns:
Boolean.
For example:
>>> import cf_units >>> u = cf_units.Unit('days since epoch') >>> u.is_time_reference() True
- is_unknown()[source]¶
Return whether the unit is defined to be an unknown unit.
- Returns:
Boolean.
For example:
>>> import cf_units >>> u = cf_units.Unit('unknown') >>> u.is_unknown() True >>> u = cf_units.Unit('meters') >>> u.is_unknown() False
- is_vertical()[source]¶
Determine whether the unit is a related SI Unit of pressure or distance.
- Returns:
Boolean.
For example:
>>> import cf_units >>> u = cf_units.Unit('millibar') >>> u.is_vertical() True >>> v = cf_units.Unit('km') >>> v.is_vertical() True
- log(base)[source]¶
Returns the logorithmic unit corresponding to the given logorithmic base.
Args:
base (int/float): Value of the logorithmic base.
- Returns:
None.
For example:
>>> import cf_units >>> u = cf_units.Unit('meters') >>> u.log(2) Unit('lb(re 1 m)')
- property modulus¶
(read-only) Return the modulus value of the unit.
- Convenience method that returns the unit modulus value as follows,
‘radians’ - pi*2
‘degrees’ - 360.0
Otherwise None.
- Returns:
float.
For example:
>>> import cf_units >>> u = cf_units.Unit('degrees') >>> u.modulus 360.0
- property name¶
(read-only) The full name of the unit.
Formats the binary unit into a string representation using method
cf_units.Unit.format()
with keyword argument option=cf_units.UT_NAMES.- Returns:
string.
For example:
>>> import cf_units >>> u = cf_units.Unit('watts') >>> u.name 'watt'
- num2date(time_value, only_use_cftime_datetimes=True, only_use_python_datetimes=False)[source]¶
Returns a datetime-like object calculated from the numeric time value using the current calendar and the unit time reference.
The current unit time reference must be of the form: ‘<time-unit> since <time-origin>’ i.e. ‘hours since 1970-01-01 00:00:00’
By default, the datetime instances returned are cftime.datetime objects, regardless of calendar. If the only_use_cftime_datetimes keyword is set to False, they are datetime.datetime objects if the date falls in the Gregorian calendar (i.e. calendar is ‘proleptic_gregorian’, ‘standard’ or gregorian’ and the date is after 1582-10-15). The datetime instances do not contain a time-zone offset, even if the specified unit contains one.
Works for scalars, sequences and numpy arrays. Returns a scalar if input is a scalar, else returns a numpy array.
Args:
- time_value (float):
Numeric time value/s. Maximum resolution is 1 second.
Kwargs:
- only_use_cftime_datetimes (bool):
If True, will always return cftime datetime objects, regardless of calendar. If False, returns datetime.datetime instances where possible. Defaults to True.
- only_use_python_datetimes (bool):
If True, will always return datetime.datetime instances where possible, and raise an exception if not. Ignored if only_use_cftime_datetimes is True. Defaults to False.
- Returns:
datetime, or numpy.ndarray of datetime object.
For example:
>>> import cf_units >>> u = cf_units.Unit('hours since 1970-01-01 00:00:00', ... calendar=cf_units.CALENDAR_STANDARD) >>> print(u.num2date(6)) 1970-01-01 06:00:00 >>> dts = u.num2date([6, 7]) >>> [str(dt) for dt in dts] ['1970-01-01 06:00:00', '1970-01-01 07:00:00']
- num2pydate(time_value)[source]¶
Convert time value(s) to python datetime.datetime objects, or raise an exception if this is not possible. Same as:
unit.num2date(time_value, only_use_cftime_datetimes=False, only_use_python_datetimes=True)
- offset_by_time(origin)[source]¶
Returns the time unit offset with respect to the time origin.
Args:
origin (float): Time origin as returned by the
cf_units.encode_time()
method.
- Returns:
None.
For example:
>>> import cf_units >>> u = cf_units.Unit('hours') >>> u.offset_by_time(cf_units.encode_time(1970, 1, 1, 0, 0, 0)) Unit('h @ 19700101T000000.0000000 UTC')
- origin = None¶
The original string used to create this unit.
- root(root)[source]¶
Returns the given root of the unit.
Args:
root (int): Value by which the unit root is taken.
- Returns:
None.
For example:
>>> import cf_units >>> u = cf_units.Unit('meters^2') >>> u.root(2) Unit('m')
Note
Taking a fractional root of a unit is not supported.
- property symbol¶
(read-only) The symbolic representation of the unit.
Formats the binary unit into a string representation using method
cf_units.Unit.format()
.- Returns:
string.
For example:
>>> import cf_units >>> u = cf_units.Unit('watts') >>> u.symbol 'W'
- title(value)[source]¶
Return the unit value as a title string.
Args:
value (float): Unit value to be incorporated into title string.
- Returns:
string.
For example:
>>> import cf_units >>> u = cf_units.Unit('hours since epoch', ... calendar=cf_units.CALENDAR_STANDARD) >>> u.title(10) '1970-01-01 10:00:00'
- ut_unit = None¶
Reference to the quantity defining the UDUNITS-2 unit.