axsdb.units

Unit handling components, based on the Pint library.

Note

By default, Pint’s application registry is used.

Functions:

ensure_units(value, default_units[, convert])

Ensure that a value is wrapped in a Pint quantity container.

get_unit_registry()

Access the internal unit registry.

parse_units(value)

Parse a unit string into a unit-only pint.Quantity (magnitude 1), caching the result.

set_unit_registry(ureg)

Set internal unit registry.

xarray_to_quantity(da)

Converts a DataArray to a Quantity.

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:
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 what get_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 units attribute, 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 own pint.set_application_registry() instead of set_unit_registry(), this cache keeps returning quantities bound to the previous registry. Always call set_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:

pint.Quantity

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 None to reset to the default (the application registry).

axsdb.units.xarray_to_quantity(da: DataArray) Quantity[source]

Converts a DataArray to a Quantity. The array’s attrs metadata mapping must contain a units field.

Parameters:

da (DataArray) – DataArray instance which will be converted.

Returns:

The corresponding Pint quantity.

Return type:

quantity

Raises:

ValueError – If array attributes do not contain a units field.

Notes

This function can also be used on coordinate variables.