axsdb.units¶
Unit handling components, based on the Pint library.
Note
By default, Pint’s application registry is used.
Functions:
|
Ensure that a value is wrapped in a Pint quantity container. |
Access the internal unit registry. |
|
|
Parse a unit string into a unit-only |
|
Set internal unit registry. |
- axsdb.units.ensure_units(value: Any, default_units: Unit, convert: bool = False) Quantity[source]¶
Ensure that a value is wrapped in a Pint quantity container.
- Parameters:
value – Checked value.
default_units (pint.Unit) – Units to use to initialize the
pint.Quantityifvalueis not apint.Quantity.convert (bool, default: False) – If
True,valuewill also be converted todefault_unitsif it is apint.Quantity.
- Return type:
Converted
value.
- axsdb.units.get_unit_registry() UnitRegistry[source]¶
Access the internal unit registry. By default, the Pint application registry is returned.
- axsdb.units.parse_units(value: str | Quantity) Quantity[source]¶
Parse a unit string into a unit-only
pint.Quantity(magnitude 1), caching the result. This matches whatget_unit_registry()(unit_str)returns, but avoids re-parsing the same string repeatedly.Pint’s unit-string parsing (tokenizing, name/symbol lookup) is comparatively expensive, so repeatedly parsing the same string (e.g. a NetCDF variable’s
unitsattribute, read on every call in a hot loop) is wasteful. This caches the result globally, keyed on the string.Warning
This cache is only invalidated by
set_unit_registry(). If you swap the active registry via Pint’s ownpint.set_application_registry()instead ofset_unit_registry(), this cache keeps returning quantities bound to the previous registry. Always callset_unit_registry()when changing the registry used with this package.- Parameters:
value (str or pint.Quantity) – Unit string to parse, or an already-parsed unit quantity (returned unchanged).
- Returns:
The parsed unit quantity.
- Return type:
- axsdb.units.set_unit_registry(ureg: UnitRegistry | None) None[source]¶
Set internal unit registry.
- Parameters:
ureg (pint.UnitRegistry or None) – New default unit registry. Set to
Noneto reset to the default (the application registry).
- axsdb.units.xarray_to_quantity(da: DataArray) Quantity[source]¶
Converts a
DataArrayto aQuantity. The array’sattrsmetadata mapping must contain aunitsfield.- Parameters:
da (DataArray) –
DataArrayinstance which will be converted.- Returns:
The corresponding Pint quantity.
- Return type:
quantity
- Raises:
ValueError – If array attributes do not contain a
unitsfield.
Notes
This function can also be used on coordinate variables.