Units¶
See the unit-aware model guide for help choosing a field representation.
Annotations and mapping types¶
- infrasys.units.Unit(unit: str) UnitSpec[str]¶
Describe a field whose bare values are stored in the specified unit.
- infrasys.units.PerUnit(unit: str | None = None, *, base: str) PerUnitSpec[str] | PerUnitSpec[str | None]¶
Describe per-unit storage relative to a base field.
If
unitis omitted, the field inherits the base field’s natural unit. Bare inputs are already per-unit. Labelled natural-unit inputs are converted using the specified base. Specifyunitwhen the natural unit differs, such as"MW/min"for a rate. Structured inputs use typed collections or unit-free models. A labelled collection union must have an unambiguous mapping or sequence branch. A collection field serializes in a{"value": ..., "unit": "pu"}envelope. A scalar-or-sequence field uses that envelope for sequences and leaves scalar values unwrapped.
- infrasys.units.unit_spec(unit: str) UnitSpec[str]¶
Describe a field whose bare values are stored in the specified unit.
- class infrasys.units.UnitSpec(unit: UnitType)¶
Immutable metadata descriptor for a field stored in natural units.
- class infrasys.units.UnitInput¶
A unit mapping with separately typed magnitude and unit fields.
Model mixins¶
- class infrasys.units.HasUnits¶
Add unit metadata and representations to a Pydantic model.
Unit specifications are collected whenever Pydantic builds a model schema. Base units are resolved from the owning model without mutating annotations.
- class infrasys.units.HasPerUnit¶
Add system-base representation state to a unit-aware model.
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- HasPerUnit.bind_system_base(base_power: SupportsFloat | None) None¶
Set the system base used for per-unit display.
- Parameters:
base_power (SupportsFloat or None) – System base power in MVA, or
Noneto clear it. Only fields relative to a power base use this reference in system-base display.- Raises:
ValueError – If
base_poweris nonnumeric, non-finite, or zero.
Representation modes¶
- class infrasys.units.UnitSystem(*values)¶
Unit representation strategies for unit-aware model values.
The selected strategy controls how
HasUnitsvalues appear in model__repr__output. It does not alter internal values or serialization.- COMPONENT_BASE¶
Represent relative values in per-unit against each component’s base.
- Type:
str
- SYSTEM_BASE¶
Represent relative values in per-unit against a bound system base.
- Type:
str
- NATURAL_UNITS¶
Represent relative values using their declared natural units.
- Type:
str
- infrasys.units.get_unit_system() UnitSystem¶
Get the unit representation strategy for the current execution context.
- Returns:
Current strategy for unit-aware model representations.
- Return type:
- infrasys.units.set_unit_system(unit_system: UnitSystem) UnitSystem¶
Set and return the strategy in the current execution context.
- Parameters:
unit_system (UnitSystem) – Representation strategy to apply to unit-aware model
__repr__output.- Returns:
The strategy active after setting it.
- Return type:
- infrasys.units.unit_system(mode: UnitSystem) Iterator[None]¶
Temporarily select a unit representation strategy.
- Parameters:
mode (UnitSystem) – Strategy to apply to unit-aware model
__repr__output in the context.- Yields:
None
Examples
>>> previous = get_unit_system() >>> with unit_system(UnitSystem.NATURAL_UNITS): ... assert get_unit_system() is UnitSystem.NATURAL_UNITS >>> assert get_unit_system() is previous
Conversion functions and registry¶
- infrasys.units.convert_to_internal(value: int | float | UnitInput[SupportsFloat | str, str], *, spec: UnitSpec[Any], base_value: float | None = None, base_unit: str | None = None) float¶
Convert an input value to its internal representation.
- Parameters:
value (int, float, or UnitInput) – Input value. Dict inputs contain
valueandunitkeys.spec (UnitSpec) – Unit metadata for the field.
base_value (float or None, optional) – Base quantity value used for per-unit conversion.
base_unit (str or None, optional) – Unit string declared by the base field.
- Returns:
Value in internal representation.
- Return type:
float
- Raises:
ValueError – If input is malformed, units are unknown or incompatible, or a required base is missing, zero, or non-finite.
- infrasys.units.format_for_display(value: float, *, spec: UnitSpec[Any], unit_system: UnitSystem, base_value: float | None = None, base_unit: str | None = None, system_base: SupportsFloat | None = None) str¶
Format an internal value for the selected unit representation.
- Parameters:
value (float) – Internal value, using per-unit storage for relative quantities.
spec (UnitSpec) – Unit metadata for the field.
unit_system (UnitSystem) – Representation strategy for the model value.
base_value (float or None, optional) – Base field value for natural-unit conversion.
base_unit (str or None, optional) – Unit declared by the base field.
system_base (SupportsFloat or None, optional) – System power base in MVA. Fields based on non-power quantities keep their component-base representation.
- Returns:
Value formatted with its display unit.
- Return type:
str
- Raises:
ValueError – If
system_baseis nonnumeric, non-finite, or zero.
- infrasys.units.ureg = <pint.registry.UnitRegistry object>¶
The unit registry stores the definitions and relationships between units.
- Parameters:
filename – path of the units definition file to load or line-iterable object. Empty string to load the default definition file. (default) None to leave the UnitRegistry empty.
force_ndarray (bool) – convert any input, scalar or not to a numpy.ndarray. (Default: False)
force_ndarray_like (bool) – convert all inputs other than duck arrays to a numpy.ndarray. (Default: False)
default_as_delta – In the context of a multiplication of units, interpret non-multiplicative units as their delta counterparts. (Default: False)
autoconvert_offset_to_baseunit – If True converts offset units in quantities are converted to their plain units in multiplicative context. If False no conversion happens. (Default: False)
on_redefinition (str) – action to take in case a unit is redefined. ‘warn’, ‘raise’, ‘ignore’ (Default: ‘raise’)
auto_reduce_dimensions – If True, reduce dimensionality on appropriate operations. (Default: False)
autoconvert_to_preferred – If True, converts preferred units on appropriate operations. (Default: False)
preprocessors – list of callables which are iteratively ran on any input expression or unit string or None for no preprocessor. (Default=None)
fmt_locale – locale identifier string, used in format_babel or None. (Default=None)
case_sensitive (bool, optional) – Control default case sensitivity of unit parsing. (Default: True)
cache_folder (str or pathlib.Path or None, optional) – Specify the folder in which cache files are saved and loaded from. If None, the cache is disabled. (default)