Unit-aware models

Use unit annotations on Pydantic model fields to accept physical-unit inputs while storing ordinary numeric values. Choose the declaration that matches the field:

  • A plain float has no unit metadata or unit conversion.

  • Unit("MW") stores a magnitude in a fixed natural unit.

  • PerUnit(base="base_power") stores a value relative to another field.

  • A BaseQuantity subclass stores a Pint quantity when the value itself needs units and unit-aware arithmetic.

The helpers and mixins below are exported from infrasys. See the units API reference for their signatures.

Declare unit-aware fields

Use typing.Annotated to attach Unit() or PerUnit() to a field. Put HasUnits before BaseModel or Component in the inheritance list.

from typing import Annotated

from pydantic import BaseModel

from infrasys import HasUnits, PerUnit, Unit


class Generator(HasUnits, BaseModel):
    base_power: Annotated[float, Unit("MW")]
    output: Annotated[float, PerUnit(base="base_power")]
    ramp: Annotated[float, PerUnit("MW/min", base="base_power")]
    voltage: Annotated[float, Unit("kV")]


generator = Generator.model_validate(
    {
        "base_power": 100,
        "output": {"value": 50000, "unit": "kW"},
        "ramp": {"value": 600, "unit": "MW/hour"},
        "voltage": {"value": 13800, "unit": "V"},
    }
)
print(generator.model_dump())
print(generator.model_dump_json())
print(Generator.unit_specs["output"])
{'base_power': 100.0, 'output': 0.5, 'ramp': 0.1, 'voltage': 13.8}
{"base_power":100.0,"output":0.5,"ramp":0.1,"voltage":13.8}
PerUnitSpec(unit='MW', base='base_power')

A bare number is already in the field’s declared representation. For Unit, that is the declared natural unit. For PerUnit, it is relative to the base. A labelled mapping is converted as part of Pydantic validation. For example, 50000 kW is 50 MW, or 0.5 on a 100 MW base. Other validators follow Pydantic’s Annotated ordering, so a BeforeValidator can run before unit conversion.

A per-unit base must be a field annotated with a natural Unit, declared before its dependent field. If the natural unit is omitted from PerUnit, it is inherited from the base. Specify it for a rate such as MW/min. The natural unit divided by the base unit must be dimensionless or an inverse-time rate. Converting a natural-unit input requires a finite, non-zero base.

The label "pu" is reserved for an already-normalized per-unit input, such as {"value": 0.5, "unit": "pu"}. It is not a natural unit for Unit or PerUnit. Unit can also convert labelled scalar inputs without HasUnits. The mixin adds unit-aware representations and resolves bases for PerUnit fields.

Generator.unit_specs maps field names to their resolved field-level unit specifications. Unit annotations on individual collection items do not create an entry. Reused annotations and inherited models resolve their bases for the owning model. A separate nested unit-aware model resolves its own base. It must not be wrapped in an outer PerUnit field, which requires a unit-free model.

Scalar JSON contains the stored numbers, not the declared natural units or base relationships. The default validation and serialization JSON Schemas describe input and output shapes, but do not include those relationships. Revalidate the JSON with the same model contract to recover the unit metadata. Unit-aware components can also round-trip through System.to_json() and System.from_json() when their classes are importable. See Serialization.

Validate defaults and assignments

Pydantic validates unit inputs when it validates a model. A plain BaseModel does not validate defaults or later assignments by default. Infrasys Component enables both. For a plain model, enable them with ConfigDict when needed:

from typing import Annotated

from pydantic import BaseModel, ConfigDict, Field

from infrasys import HasUnits, PerUnit, Unit


class Meter(HasUnits, BaseModel):
    model_config = ConfigDict(validate_assignment=True, validate_default=True)
    base_power: Annotated[float, Unit("MW")] = 100
    output: Annotated[float, PerUnit(base="base_power")] = Field(
        default_factory=lambda: {"value": 50, "unit": "MW"}
    )


meter = Meter()
print(meter.output)
meter.output = {"value": 25, "unit": "MW"}
print(meter.output)
meter.base_power = 200
print(meter.output)
0.5
0.25
0.25

Without assignment validation, assigning a mapping after construction can leave the mapping in the field without conversion. Changing a base field does not rescale per-unit values already stored in other fields.

Invalid or incompatible labelled units and missing, zero, or non-finite bases for natural-unit conversion raise a Pydantic ValidationError. Invalid PerUnit base references and incompatible declarations are rejected when the model schema is built.

Per-unit collections and models

A PerUnit field can contain a typed collection or a Pydantic model whose fields have no unit annotations of their own. One input unit applies to the numeric values in the collection or model. Bare structured values are already per-unit.

from typing import Annotated

from pydantic import BaseModel

from infrasys import HasUnits, PerUnit, Unit


class Limits(BaseModel):
    minimum: float
    maximum: float


class Profile(HasUnits, BaseModel):
    base_power: Annotated[float, Unit("MW")]
    output: Annotated[float | list[float], PerUnit(base="base_power")]
    limits: Annotated[Limits, PerUnit(base="base_power")]


profile = Profile.model_validate(
    {
        "base_power": 100,
        "output": {"value": [25, 75], "unit": "MW"},
        "limits": {"value": {"minimum": 20, "maximum": 80}, "unit": "MW"},
    }
)
print(profile.model_dump(mode="json")["output"])
print(profile.model_dump(mode="json")["limits"])
print(Profile.model_validate_json(profile.model_dump_json()) == profile)

empty = Profile.model_validate(
    {"base_power": 100, "output": [], "limits": {"minimum": 0.2, "maximum": 0.8}}
)
print(empty.model_dump(mode="json")["output"])
{'value': [0.25, 0.75], 'unit': 'pu'}
{'value': {'minimum': 0.2, 'maximum': 0.8}, 'unit': 'pu'}
True
{'value': [], 'unit': 'pu'}

Structured values serialize with a "pu" envelope so they can be reloaded without converting them twice. A field declared as float serializes as a number, as does the scalar branch of float | list[float]. An optional field set to None remains None. A RootModel uses an envelope even when its root is a scalar or None. For a labelled collection union, the mapping or sequence branch must be unambiguous.

Natural-unit mappings for structured models support field names and simple validation aliases. They reject complex AliasChoices or AliasPath aliases, undeclared fields even when extra fields are allowed, and non-null fields typed as Any or object. Pydantic validators, serializers, aliases, and serialization filters still apply. The "unit" key in a per-unit envelope is distinct from the "units" key in BaseQuantity.to_dict().

A bare mapping can be ambiguous if its value and unit entries themselves look like a unit envelope. Such inputs are interpreted as envelopes. To preserve the mapping as data, wrap it in an additional {"value": ..., "unit": "pu"} envelope.

Annotate individual collection items

Put Unit or PerUnit on the item type when each item should accept its own unit mapping:

from typing import Annotated

from pydantic import BaseModel

from infrasys import HasUnits, PerUnit, Unit


class Samples(HasUnits, BaseModel):
    base_power: Annotated[float, Unit("MW")]
    values: list[Annotated[float, PerUnit(base="base_power")]]


samples = Samples.model_validate(
    {"base_power": 100, "values": [0.2, {"value": 50, "unit": "MW"}]}
)
print(samples.model_dump(mode="json")["values"])
print(sorted(Samples.unit_specs))
[0.2, 0.5]
['base_power']

Here each scalar item serializes as a number. In contrast, annotating the whole list with PerUnit gives the list one unit and one serialized envelope.

Display unit-aware values

UnitSystem selects how scalar fields appear in repr(). It does not change stored values or Pydantic serialization. HasPerUnit adds an instance-local system base for display.

from typing import Annotated

from infrasys import HasPerUnit, PerUnit, Unit, UnitSystem, unit_system


class DisplayGenerator(HasPerUnit):
    base_power: Annotated[float, Unit("MVA")]
    output: Annotated[float, PerUnit("MW", base="base_power")]
    ramp: Annotated[float, PerUnit("MW/min", base="base_power")]


device = DisplayGenerator(base_power=100, output=0.5, ramp=0.1)
device.bind_system_base(200)
for mode in (UnitSystem.COMPONENT_BASE, UnitSystem.SYSTEM_BASE, UnitSystem.NATURAL_UNITS):
    with unit_system(mode):
        print(mode.value, repr(device))

restored = DisplayGenerator.model_validate_json(device.model_dump_json())
print(device.system_base, restored.system_base)
COMPONENT_BASE DisplayGenerator(base_power='100.0 MVA', output='0.5 pu', ramp='0.1 pu/min')
SYSTEM_BASE DisplayGenerator(base_power='100.0 MVA', output='0.25 pu (system)', ramp='0.05 pu/min (system)')
NATURAL_UNITS DisplayGenerator(base_power='100.0 MVA', output='50 MW', ramp='10 MW/min')
200.0 None

COMPONENT_BASE is the default. SYSTEM_BASE uses the system power base passed to bind_system_base() in MVA. If no system base is bound, values remain on their component base. Fields with a non-power base also remain on their component base. Pass None to clear the system base. The bound system base is display state and is not serialized. Infrasys System does not bind it automatically, so bind it again after loading a model. NATURAL_UNITS displays the declared natural unit, including the time unit of a rate.

unit_system() temporarily sets the strategy and restores it on exit. The setting is local to the current execution context. set_unit_system() and get_unit_system() set and retrieve that context’s strategy. Only scalar values receive unit formatting. Structured values keep their native model representation, and fields declared with Field(repr=False) stay hidden.

Cost curve units

infrasys.cost_curves.UnitSystem is separate from the display strategy above. It sets the power_units field on cost and fuel curves:

from infrasys.cost_curves import CostCurve, UnitSystem as CostUnitSystem
from infrasys.value_curves import LinearCurve


curve = CostCurve(value_curve=LinearCurve(1), power_units=CostUnitSystem.COMPONENT_BASE)
print(curve.model_dump(mode="json")["power_units"])
COMPONENT_BASE

The accepted values are SYSTEM_BASE, COMPONENT_BASE, and NATURAL_UNITS. DEVICE_BASE is not accepted.

Convert outside a model

convert_to_internal() accepts a number or a UnitInput mapping. Pass the unit specification and any required base as keyword arguments:

from infrasys import PerUnit, UnitSystem
from infrasys.units import convert_to_internal, format_for_display


spec = PerUnit(base="base_power")
value = convert_to_internal(
    {"value": 50, "unit": "MW"},
    spec=spec,
    base_value=100,
    base_unit="MW",
)
print(value)
print(
    format_for_display(
        value, spec=spec, unit_system=UnitSystem.NATURAL_UNITS, base_value=100, base_unit="MW"
    )
)
0.5
50 MW

format_for_display() formats an internal scalar using an explicitly selected unit system. Both helpers and BaseQuantity use the shared ureg registry.