Skip to content

Physical

The physics domain model: region tags and their materials, boundary and body conditions, and the property functions their values come from.

femforge.physical

The physics domain model: per-region tags and their materials, the boundary/body conditions, and the property functions those values are written as.

Modules:

  • conditions –

    Conditions attached to a region, each carrying its physics, its body or boundary target and its own Elmer sif emission.

  • domain –

    The simulation domain: the materials and per-region tag overrides shared by the mesh and FEA backends.

  • expressions –

    Typed expression AST over bare SI magnitudes for variable-dependent material properties: evaluates in Python, renders to Elmer MATC or Lua, serializes to JSON.

  • property_functions –

    Material properties as pint-aware callables (Static, Calibration, ClosedForm, Expression) behind the PropertyFunction protocol.

  • readout –

    Short readouts of quantities and directions, at three significant figures on fixed unit ladders.

  • units –

    The shared pint unit registry, its typed quantity facades and the dimensionality-constrained quantity field types.

Classes:

  • BoundarySite –

    The boundary group a boundary condition lands on, as the condition sees it when it emits.

  • CalculateMagneticForce –

    Lumps the magnetic force, and optionally the torque, over the bodies its tag matches into one Elmer Component.

  • CoilDrive –

    A driven massive coil: the bodies that share one CoilDrive form one coil that carries current.

  • CoilTerminal –

    One end of an open coil, its start or end electrode.

  • Condition –

    A source or constraint of one physics on the bodies or boundaries a tag selects; each subclass is one shipped condition.

  • ConditionGlyph –

    The kind of scene glyph and legend row a condition draws as.

  • ConditionTarget –

    Whether a condition attaches to a 3D body or a 2D boundary.

  • Convection –

    Newton cooling of an outer surface to an ambient temperature.

  • CurrentDensity –

    A uniform signed out-of-plane current density J = N·I/A over a winding window, the homogenized drive of a stranded coil in a 2D solve.

  • FixedDisplacement –

    A prescribed displacement on a boundary, clamped to zero in every direction by default.

  • FixedTemperature –

    A fixed temperature on a boundary.

  • FixedVoltage –

    A fixed voltage potential on an electrode, one end of a phase's terminal pair.

  • HeatFlux –

    A prescribed heat flux through a boundary.

  • HeatSource –

    A volumetric heat source in a body.

  • JouleHeat –

    Heats a body with the Joule losses of its solved current.

  • Magnetization –

    The magnetization direction of a permanent magnet.

  • SummaryPart –

    One value of a condition as the Setup tab reads it, with the glyph or word read before it.

  • SurfaceForce –

    A total force spread uniformly over a named face as a traction.

  • DomainConfig –

    The materials the mesher matches to STEP parts, plus the per-region EntityTag overrides (conditions / mesh refinement).

  • EntityTag –

    A per-region override matched to a mesh entity by its authored tags; carries the region's self-describing conditions.

  • Add –

    The sum of two subexpressions.

  • Const –

    A literal SI magnitude.

  • Div –

    The quotient of two subexpressions.

  • ExprNode –

    Base node: shared config + Python operator composition, so laws are authored as plain arithmetic.

  • Mul –

    The product of two subexpressions.

  • Neg –

    The negation of a subexpression.

  • Param –

    A named parameter (e.g. temperature), bound at evaluation/render time.

  • Pow –

    One subexpression raised to the power of another.

  • Sub –

    The difference of two subexpressions.

  • BasePropertyFunction –

    Pydantic base implementing parameter checking once; subclasses declare parameters / result_dimensionality and implement _evaluate.

  • Calibration –

    A property defined by sample points and interpolated between them (1-D only for now).

  • CalibrationPoint –

    One measured sample: input quantities by name and the resulting output.

  • ClosedForm –

    A property defined by an explicit Python callable, pint-in / pint-out; the callable is code, not JSON-serializable.

  • Expression –

    A property defined by a serializable typed expression AST (physical.expressions) — ClosedForm as data instead of code.

  • PropertyDimensionError –

    A supplied parameter had the wrong dimensionality.

  • PropertyError –

    Base class for every property-function error.

  • PropertyFunction –

    A material property as a function of zero or more named pint quantities, returning a pint Quantity.

  • PropertyFunctionField –

    Annotated metadata for a PropertyFunction constrained to dimensionality.

  • PropertyParameterError –

    A required parameter was not supplied when evaluating a property.

  • PropertyRangeError –

    A parameter fell outside the calibrated range and extrapolation is off.

  • Static –

    A constant property: zero parameters, always returns value.

  • Quantity –

    A pint quantity with a float magnitude.

  • Unit –

    A pint unit, typed so that arithmetic with units and numbers keeps its type.

  • VectorQuantity –

    A pint quantity with a Vec3 magnitude.

Functions:

  • shipped_conditions –

    The condition classes ConditionUnion admits, in its order.

  • conditions_for –

    The conditions on tags that belong to physics and attach to target.

  • as_expr –

    Wrap a bare number into Const; pass nodes through (the operator-composition coercion point).

  • evaluate –

    Module-level convenience mirroring expr.evaluate.

  • render –

    Backend source for expr with parameter references substituted (e.g. {"temperature": "tx(0)"}).

  • property_function_type –

    A PropertyFunction constrained to dimensionality, usable as a Pydantic field.

  • quantity –

    Statically-typed face of U.Quantity(...): a float magnitude yields Quantity, a Vec3 yields VectorQuantity.

Attributes:

  • ConditionUnion –

    Any concrete condition, discriminated by its kind.

  • Expr –

    Any expression node, discriminated by its op.

  • U –

    The shared pint unit registry, as in 5 * U.mm or U.Quantity(1.2, "T").

ConditionUnion module-attribute

Any concrete condition, discriminated by its kind.

Expr module-attribute

Expr = Union[Const, Param, Add, Sub, Mul, Div, Pow, Neg]

Any expression node, discriminated by its op.

U module-attribute

U = cast('_TypedRegistry', pint.UnitRegistry(autoconvert_offset_to_baseunit=True))

The shared pint unit registry, as in 5 * U.mm or U.Quantity(1.2, "T").

BoundarySite dataclass

BoundarySite(name: str, measure: float | None, frame: Frame)

The boundary group a boundary condition lands on, as the condition sees it when it emits.

Attributes:

  • name (str) –

    The boundary group's name.

  • measure (float | None) –

    A [m²]: The group's measured size, area in 3D and length times one metre of depth in 2D; None for an adjacency group.

  • frame (Frame) –

    The solve frame the group's model maps onto.

name instance-attribute

name: str

The boundary group's name.

measure instance-attribute

measure: float | None

A [m²]: The group's measured size, area in 3D and length times one metre of depth in 2D; None for an adjacency group.

frame instance-attribute

frame: Frame

The solve frame the group's model maps onto.

CalculateMagneticForce pydantic-model

Bases: Condition

Lumps the magnetic force, and optionally the torque, over the bodies its tag matches into one Elmer Component.

Fields:

kind pydantic-field

kind: Literal['calculate_magnetic_force'] = 'calculate_magnetic_force'

Discriminator that names this condition type in a serialized config.

physics pydantic-field

The physics whose solve this condition feeds.

target pydantic-field

Whether the condition attaches to a body or a boundary.

label pydantic-field

label: str | None = None

The Component's Name; None uses the authoring tag's name.

calculate_magnetic_force pydantic-field

calculate_magnetic_force: bool = True

Lump the nodal magnetic force over the master bodies.

calculate_magnetic_torque pydantic-field

calculate_magnetic_torque: bool = False

Also lump the magnetic torque (requires torque_origin/torque_axis).

torque_origin pydantic-field

torque_origin: Vec3Field | None = None

r_0 [m]: Torque pivot point.

torque_axis pydantic-field

torque_axis: DirectionField | None = None

Torque axis direction.

to_elmer

to_elmer() -> dict[str, float | str]

The CalcFields force and torque flags, plus the torque origin and axis when set.

Source code in src/femforge/physical/conditions.py
def to_elmer(self) -> dict[str, float | str]:
    """The CalcFields force and torque flags, plus the torque origin and axis when set."""
    out: dict[str, float | str] = {}
    if self.calculate_magnetic_force:
        out["Calculate Magnetic Force"] = "Logical True"
    if self.calculate_magnetic_torque:
        out["Calculate Magnetic Torque"] = "Logical True"
    if self.torque_origin is not None:
        out["Torque Origin(3)"] = f"Real {self.torque_origin.x:.6g} {self.torque_origin.y:.6g} {self.torque_origin.z:.6g}"
    if self.torque_axis is not None:
        out["Torque Axis(3)"] = f"Real {self.torque_axis.x:.6g} {self.torque_axis.y:.6g} {self.torque_axis.z:.6g}"
    return out

check_frame

check_frame(frame: Frame) -> None

Raise when torque is requested under a frame whose force lumping yields none.

Source code in src/femforge/physical/conditions.py
def check_frame(self, frame: Frame) -> None:
    """Raise when torque is requested under a ``frame`` whose force lumping yields none."""
    torque: bool = self.calculate_magnetic_torque or self.torque_origin is not None or self.torque_axis is not None

    if torque and not frame.lumps_torque:
        raise ValueError(f"CalculateMagneticForce torque has no form in the {frame.label} frame; drop calculate_magnetic_torque, torque_origin and torque_axis.")

summary

summary(emitted: Mapping[str, float | str] | None = None, *, frame: Frame | None = None) -> tuple[SummaryLine, ...]

That the condition is an output the scene draws no glyph for; emitted and frame are ignored.

Parameters:

  • emitted (Mapping[str, float | str] | None, default: None ) –

    The keywords the force Component received, by name.

  • frame (Frame | None, default: None ) –

    The frame the run solved in.

Source code in src/femforge/physical/conditions.py
def summary(self, emitted: Mapping[str, float | str] | None = None, *, frame: Frame | None = None) -> tuple[SummaryLine, ...]:
    """That the condition is an output the scene draws no glyph for; ``emitted`` and ``frame`` are ignored.

    Args:
        emitted: The keywords the force Component received, by name.
        frame: The frame the run solved in.
    """
    return ((SummaryPart("(Output, No Glyph)"),),)

CoilDrive pydantic-model

Bases: Condition

A driven massive coil: the bodies that share one CoilDrive form one coil that carries current.

Reverse the drive by swapping the terminal roles, not with a negative current.

Fields:

kind pydantic-field

kind: Literal['coil_drive'] = 'coil_drive'

Discriminator that names this condition type in a serialized config.

physics pydantic-field

The physics whose solve this condition feeds.

target pydantic-field

Whether the condition attaches to a body or a boundary.

current pydantic-field

current: Current

I_coil [A]: The total coil current CoilSolver normalizes this coil's solved distribution to.

to_elmer

to_elmer() -> dict[str, float | str]

The Desired Coil Current and the massive Coil Type.

Source code in src/femforge/physical/conditions.py
def to_elmer(self) -> dict[str, float | str]:
    """The ``Desired Coil Current`` and the massive ``Coil Type``."""
    out: dict[str, float | str] = super().to_elmer()
    # Massive: one solid conductor whose current distribution is the solved conduction field (the PCB winding),
    # as opposed to "stranded" (a wound bundle with imposed uniform fill).
    out["Coil Type"] = '"massive"'
    return out

CoilTerminal pydantic-model

Bases: Condition

One end of an open coil, its start or end electrode.

The electrode's end face must lie on the domain boundary (GeometryConfig.terminate_electrodes); positive coil current flows from start to end.

Fields:

kind pydantic-field

kind: Literal['coil_terminal'] = 'coil_terminal'

Discriminator that names this condition type in a serialized config.

physics pydantic-field

The physics whose solve this condition feeds.

target pydantic-field

Whether the condition attaches to a body or a boundary.

role pydantic-field

role: Literal['start', 'end']

Which end of the coil this electrode is; CoilSolver's normalized current flows start -> end.

to_elmer

to_elmer() -> dict[str, float | str]

The Coil Start or Coil End flag for this role.

Source code in src/femforge/physical/conditions.py
def to_elmer(self) -> dict[str, float | str]:
    """The ``Coil Start`` or ``Coil End`` flag for this ``role``."""
    return {"Coil Start" if self.role == "start" else "Coil End": "Logical True"}

summary

summary(emitted: Mapping[str, float | str] | None = None, *, frame: Frame | None = None) -> tuple[SummaryLine, ...]

The role, Start or End; emitted and frame are ignored.

Parameters:

  • emitted (Mapping[str, float | str] | None, default: None ) –

    The keywords the electrode's sif block received, by name.

  • frame (Frame | None, default: None ) –

    The frame the run solved in.

Source code in src/femforge/physical/conditions.py
def summary(self, emitted: Mapping[str, float | str] | None = None, *, frame: Frame | None = None) -> tuple[SummaryLine, ...]:
    """The ``role``, ``Start`` or ``End``; ``emitted`` and ``frame`` are ignored.

    Args:
        emitted: The keywords the electrode's sif block received, by name.
        frame: The frame the run solved in.
    """
    return ((SummaryPart(title(self.role)),),)

Condition pydantic-model

Bases: BaseModel

A source or constraint of one physics on the bodies or boundaries a tag selects; each subclass is one shipped condition.

Config:

  • arbitrary_types_allowed: True
  • use_attribute_docstrings: True

Fields:

external_only class-attribute

external_only: bool = False

Boundary-target conditions with this set land only on a body's external (domain-boundary) surface groups, not its interfaces — e.g. a coil terminal is the electrode's exposed end face, not its interior contacts.

section class-attribute

section: SifSection

The sif section this condition's keywords land in; BOUNDARY_CONDITION exactly when target is BOUNDARY.

glyph class-attribute

glyph: ConditionGlyph | None

The scene glyph this condition draws as; None for an output that draws nothing.

combine class-attribute

combine: Combine = Combine.MATCH

How its keywords combine with another condition's in the same sif block.

physics pydantic-field

physics: Physics

The physics whose solve this condition feeds.

target pydantic-field

Whether the condition attaches to a body or a boundary.

to_elmer

to_elmer(*args: Any, **kwargs: Any) -> dict[str, float | str]

This condition's Elmer sif keyword dict, reflected from each field's ElmerKeyword metadata; an unset field emits nothing.

Source code in src/femforge/physical/conditions.py
def to_elmer(self, *args: Any, **kwargs: Any) -> dict[str, float | str]:  # pyright: ignore[reportExplicitAny, reportAny]  # variadic: subclass to_elmer signatures diverge (Magnetization takes a magnitude)
    """This condition's Elmer sif keyword dict, reflected from each field's ``ElmerKeyword`` metadata; an unset field emits nothing."""
    out: dict[str, float | str] = {}
    for name, field in type(self).model_fields.items():
        spec: ElmerKeyword | None = _elmer_keyword(field)

        if spec is None:
            continue

        value: Quantity | None = getattr(self, name)  # pyright: ignore[reportAny]  # getattr is Any

        if value is None:
            continue

        out[spec.key] = _si(value, spec.unit)
    return out

on_boundary

on_boundary(site: BoundarySite) -> dict[str, float | str]

This condition's keywords on the boundary group site; the default ignores the site.

Source code in src/femforge/physical/conditions.py
def on_boundary(self, site: BoundarySite) -> dict[str, float | str]:
    """This condition's keywords on the boundary group ``site``; the default ignores the site."""
    return self.to_elmer()

yields_to

yields_to(emitted: Mapping[str, SifValue]) -> tuple[tuple[str, str], ...]

Each load keyword in emitted paired with the fixed-value keyword that makes Elmer ignore it in the same block; the default yields to none.

Source code in src/femforge/physical/conditions.py
def yields_to(self, emitted: Mapping[str, SifValue]) -> tuple[tuple[str, str], ...]:
    """Each load keyword in ``emitted`` paired with the fixed-value keyword that makes Elmer ignore it in the same block; the default yields to none."""
    return ()

check_frame

check_frame(frame: Frame) -> None

Raise when this condition cannot drive a frame solve.

Source code in src/femforge/physical/conditions.py
def check_frame(self, frame: Frame) -> None:
    """Raise when this condition cannot drive a ``frame`` solve."""

solve_components

solve_components(frame: Frame) -> tuple[tuple[int, float], ...]

The 1-based solve coordinates and values of this condition's vector in frame; the default has none.

Source code in src/femforge/physical/conditions.py
def solve_components(self, frame: Frame) -> tuple[tuple[int, float], ...]:
    """The 1-based solve coordinates and values of this condition's vector in ``frame``; the default has none."""
    return ()

dropped_fields

dropped_fields(frame: Frame) -> tuple[str, ...]

The authored fields frame has no solve coordinate for; the default drops none.

Source code in src/femforge/physical/conditions.py
def dropped_fields(self, frame: Frame) -> tuple[str, ...]:
    """The authored fields ``frame`` has no solve coordinate for; the default drops none."""
    return ()

summary

summary(emitted: Mapping[str, float | str] | None = None, *, frame: Frame | None = None) -> tuple[SummaryLine, ...]

How the Setup tab reads this condition: one line of its sif-keyword fields, each after its glyph when there are several; the default ignores emitted and frame.

Parameters:

  • emitted (Mapping[str, float | str] | None, default: None ) –

    The keywords the condition's sif block received, by name.

  • frame (Frame | None, default: None ) –

    The frame the run solved in; None reads the authored axes as the solve axes.

Source code in src/femforge/physical/conditions.py
def summary(self, emitted: Mapping[str, float | str] | None = None, *, frame: Frame | None = None) -> tuple[SummaryLine, ...]:
    """How the Setup tab reads this condition: one line of its sif-keyword fields, each after its glyph when there are several; the default ignores ``emitted`` and ``frame``.

    Args:
        emitted: The keywords the condition's sif block received, by name.
        frame: The frame the run solved in; None reads the authored axes as the solve axes.
    """

    def glyph_of(field: FieldInfo) -> str:
        match: re.Match[str] | None = FIELD_DOCSTRING.match(field.description or "")
        symbol: str | None = match.group("symbol") if match is not None else None

        return symbol.split("_")[0] if symbol else ""

    values: list[tuple[FieldInfo, Quantity]] = []

    for name, field in type(self).model_fields.items():
        value: Quantity | None = getattr(self, name) if _elmer_keyword(field) is not None else None

        if value is not None:
            values.append((field, value))

    labelled: bool = len(values) > 1
    parts: SummaryLine = tuple(SummaryPart(readout(value), label=glyph_of(field) if labelled else "") for field, value in values)

    return (parts,)

ConditionGlyph

Bases: StrEnum

The kind of scene glyph and legend row a condition draws as.

Attributes:

SURFACE_FORCE class-attribute instance-attribute

SURFACE_FORCE = 'surface_force'

A load arrow on a face.

FIXED_DISPLACEMENT class-attribute instance-attribute

FIXED_DISPLACEMENT = 'fixed_displacement'

A held face.

MAGNETIZATION class-attribute instance-attribute

MAGNETIZATION = 'magnetization'

A magnet's direction arrow.

CURRENT_DENSITY class-attribute instance-attribute

CURRENT_DENSITY = 'current_density'

A coil drive's current marker.

THERMAL class-attribute instance-attribute

THERMAL = 'thermal'

A thermal source or boundary value.

VOLTAGE class-attribute instance-attribute

VOLTAGE = 'voltage'

A fixed voltage potential.

COIL_TERMINAL class-attribute instance-attribute

COIL_TERMINAL = 'coil_terminal'

A coil's start or end electrode.

ConditionTarget

Bases: StrEnum

Whether a condition attaches to a 3D body or a 2D boundary.

Attributes:

  • BODY –

    Attach to a body.

  • BOUNDARY –

    Attach to a boundary surface.

BODY class-attribute instance-attribute

BODY = 'body'

Attach to a body.

BOUNDARY class-attribute instance-attribute

BOUNDARY = 'boundary'

Attach to a boundary surface.

Convection pydantic-model

Bases: Condition

Newton cooling of an outer surface to an ambient temperature.

It lands on the outer shell only, since a film coefficient on an interior interface would bypass the conduction path.

Fields:

kind pydantic-field

kind: Literal['convection'] = 'convection'

Discriminator that names this condition type in a serialized config.

physics pydantic-field

physics: Physics = Physics.THERMAL

The physics whose solve this condition feeds.

target pydantic-field

Whether the condition attaches to a body or a boundary.

coefficient pydantic-field

coefficient: HeatTransferCoefficient

h [W/(m²·K)]: Convective heat-transfer coefficient.

ext_temperature pydantic-field

ext_temperature: Temperature

T_amb [K]: External (ambient) temperature the boundary exchanges with.

yields_to

yields_to(emitted: Mapping[str, SifValue]) -> tuple[tuple[str, str], ...]

The film exchange, which a fixed temperature on the same boundary overrides.

Source code in src/femforge/physical/conditions.py
def yields_to(self, emitted: Mapping[str, SifValue]) -> tuple[tuple[str, str], ...]:
    """The film exchange, which a fixed temperature on the same boundary overrides."""
    return tuple((key, str(ElmerVariable.TEMPERATURE)) for key in emitted)

CurrentDensity pydantic-model

Bases: Condition

A uniform signed out-of-plane current density J = N·I/A over a winding window, the homogenized drive of a stranded coil in a 2D solve.

Fields:

kind pydantic-field

kind: Literal['current_density'] = 'current_density'

Discriminator that names this condition type in a serialized config.

physics pydantic-field

The physics whose solve this condition feeds.

target pydantic-field

Whether the condition attaches to a body or a boundary.

value pydantic-field

value: CurrentDensity

J [A/m²]: Signed out-of-plane current density imposed uniformly over the body: azimuthal under Axisymmetric, along +normal under Cartesian2D.

check_frame

check_frame(frame: Frame) -> None

Raise when frame has no 2D magnetostatic solve for this drive to feed.

Source code in src/femforge/physical/conditions.py
def check_frame(self, frame: Frame) -> None:
    """Raise when ``frame`` has no 2D magnetostatic solve for this drive to feed."""
    if not frame.supports(Physics.MAGNETOSTATICS_2D):
        raise ValueError(f"CurrentDensity is the out-of-plane coil drive of '{Physics.MAGNETOSTATICS_2D.value}', which the {frame.label} frame has no form for.")

FixedDisplacement pydantic-model

Bases: Condition

A prescribed displacement on a boundary, clamped to zero in every direction by default.

Fields:

kind pydantic-field

kind: Literal['fixed_displacement'] = 'fixed_displacement'

Discriminator that names this condition type in a serialized config.

physics pydantic-field

The physics whose solve this condition feeds.

target pydantic-field

Whether the condition attaches to a body or a boundary.

x pydantic-field

x: Length | None

u_x [m]: Prescribed displacement along the authored X axis; None leaves it free.

y pydantic-field

y: Length | None

u_y [m]: Prescribed displacement along the authored Y axis; None leaves it free.

z pydantic-field

z: Length | None

u_z [m]: Prescribed displacement along the authored Z axis; None leaves it free.

solve_components

solve_components(frame: Frame) -> tuple[tuple[int, float], ...]

Each 1-based solve coordinate the constrained axes run along in frame, with its signed prescribed value; raises when the mapping is ill posed.

Source code in src/femforge/physical/conditions.py
def solve_components(self, frame: Frame) -> tuple[tuple[int, float], ...]:
    """Each 1-based solve coordinate the constrained axes run along in ``frame``, with its signed prescribed value; raises when the mapping is ill posed."""
    solve_axes: tuple[Vec3, ...] = _solve_axes(frame)
    constraints: tuple[tuple[Component, Vec3, float | None], ...] = self._constraints()

    for name, axis, value in constraints:
        if value is None or value == 0.0:
            continue

        in_plane: Vec3 = sum((solve_axis * axis.dot(solve_axis) for solve_axis in solve_axes), start=Vec3(0.0, 0.0, 0.0))

        # A residual vector, not sqrt(1 - Σcos²): the 12-digit Direction rounding puts the latter right at the tolerance.
        if (axis - in_plane).magnitude() > ALIGNMENT_TOLERANCE:
            raise ValueError(f"FixedDisplacement prescribes a nonzero {name}, which has no form in the {frame.label} frame; set {name}=None.")

    components: list[tuple[int, float]] = []

    for index, solve_axis in enumerate(solve_axes, start=1):
        held: list[tuple[str, float, float]] = []
        free: list[str] = []

        for name, axis, value in constraints:
            cosine: float = _snapped(axis.dot(solve_axis))

            if cosine == 0.0:
                continue

            if value is None:
                free.append(name)

                continue

            held.append((name, cosine, value))

        if held and free:
            raise ValueError(
                f"FixedDisplacement constrains {held[0][0]} but leaves {free[0]} free, and the {frame.label} frame solves coordinate {index} as a mix of the two; "
                f"constrain {free[0]} too, or orient the frame so its x_dir runs along {held[0][0]}."
            )

        if held:
            terms: list[float] = [cosine * value for _, cosine, value in held]
            components.append((index, sum(terms, start=0.0)))

    return tuple(components)

to_elmer

to_elmer() -> dict[str, float | str]

Raise: the keywords depend on the frame, which only on_boundary knows.

Source code in src/femforge/physical/conditions.py
def to_elmer(self) -> dict[str, float | str]:
    """Raise: the keywords depend on the frame, which only [`on_boundary`][femforge.physical.conditions.FixedDisplacement.on_boundary] knows."""
    raise ValueError("FixedDisplacement maps its axes through the frame of the boundary it lands on; it emits through on_boundary only.")

on_boundary

on_boundary(site: BoundarySite) -> dict[str, float | str]

The Displacement i keywords of the solve coordinates the constrained axes run along in the frame of site, signed by their alignment; an axis off the solve plane adds none.

Source code in src/femforge/physical/conditions.py
def on_boundary(self, site: BoundarySite) -> dict[str, float | str]:
    """The ``Displacement i`` keywords of the solve coordinates the constrained axes run along in the frame of ``site``, signed by their alignment; an axis off the solve plane adds none."""
    components: tuple[tuple[int, float], ...] = self.solve_components(site.frame)

    return {f"{ElmerVariable.DISPLACEMENT} {index}": value for index, value in components}

check_frame

check_frame(frame: Frame) -> None

Raise when a nonzero component leaves the solve plane or a constrained axis runs oblique to a free one in frame.

Source code in src/femforge/physical/conditions.py
def check_frame(self, frame: Frame) -> None:
    """Raise when a nonzero component leaves the solve plane or a constrained axis runs oblique to a free one in ``frame``."""
    _ = self.solve_components(frame)

dropped_fields

dropped_fields(frame: Frame) -> tuple[str, ...]

The constrained authored axes that run along no solve coordinate of frame, such as ("z",) under a Cartesian 2D frame normal to Z.

Source code in src/femforge/physical/conditions.py
def dropped_fields(self, frame: Frame) -> tuple[str, ...]:
    """The constrained authored axes that run along no solve coordinate of ``frame``, such as ``("z",)`` under a Cartesian 2D frame normal to Z."""
    solve_axes: tuple[Vec3, ...] = _solve_axes(frame)
    dropped: list[str] = []

    for name, axis, value in self._constraints():
        if value is None:
            continue

        if all(_snapped(axis.dot(solve_axis)) == 0.0 for solve_axis in solve_axes):
            dropped.append(name)

    return tuple(dropped)

summary

summary(emitted: Mapping[str, float | str] | None = None, *, frame: Frame | None = None) -> tuple[SummaryLine, ...]

X 0 · Y Free · Z –: each authored axis in order, held at the value its solve coordinate received, Free, or – when frame drops it.

Parameters:

  • emitted (Mapping[str, float | str] | None, default: None ) –

    The keywords the boundary's sif block received, by name; None reads the authored values.

  • frame (Frame | None, default: None ) –

    The frame the boundary's model solved in; None reads the authored axes as the solve axes.

Source code in src/femforge/physical/conditions.py
def summary(self, emitted: Mapping[str, float | str] | None = None, *, frame: Frame | None = None) -> tuple[SummaryLine, ...]:
    """``X 0 · Y Free · Z –``: each authored axis in order, held at the value its solve coordinate received, ``Free``, or ``–`` when ``frame`` drops it.

    Args:
        emitted: The keywords the boundary's sif block received, by name; None reads the authored values.
        frame: The frame the boundary's model solved in; None reads the authored axes as the solve axes.
    """
    solve_axes: tuple[Vec3, ...] = _solve_axes(frame)
    received: dict[int, float | str] = dict(_numbers(emitted, str(ElmerVariable.DISPLACEMENT)))

    def shown(value: float) -> str:
        return "0" if value == 0.0 else readout(quantity(value, "m"))

    def part(component: Component, axis: Vec3, value: float | None) -> SummaryPart:
        label: str = component.upper()

        if value is None:
            return SummaryPart("Free", label=label, component=component)

        cosines: list[float] = [_snapped(axis.dot(solve_axis)) for solve_axis in solve_axes]
        aligned: list[tuple[int, float]] = [(index, cosine) for index, cosine in enumerate(cosines, start=1) if cosine != 0.0]

        if not aligned:
            return SummaryPart(DROPPED, label=label, component=component)

        index, cosine = aligned[0]
        solved: float | str | None = received.get(index)

        if len(aligned) == 1 and abs(cosine) == 1.0 and isinstance(solved, float):
            return SummaryPart(shown(cosine * solved), label=label, component=component)

        return SummaryPart(shown(value), label=label, component=component)

    parts: SummaryLine = tuple(part(name, axis, value) for name, axis, value in self._constraints())

    return (parts,)

FixedTemperature pydantic-model

Bases: Condition

A fixed temperature on a boundary.

Fields:

kind pydantic-field

kind: Literal['fixed_temperature'] = 'fixed_temperature'

Discriminator that names this condition type in a serialized config.

physics pydantic-field

physics: Physics = Physics.THERMAL

The physics whose solve this condition feeds.

target pydantic-field

Whether the condition attaches to a body or a boundary.

value pydantic-field

value: Temperature

T [K]: Fixed temperature imposed on the boundary.

FixedVoltage pydantic-model

Bases: Condition

A fixed voltage potential on an electrode, one end of a phase's terminal pair.

The run also integrates the current through the electrode.

Fields:

kind pydantic-field

kind: Literal['fixed_voltage'] = 'fixed_voltage'

Discriminator that names this condition type in a serialized config.

physics pydantic-field

The physics whose solve this condition feeds.

target pydantic-field

Whether the condition attaches to a body or a boundary.

value pydantic-field

value: Voltage

V [V]: The voltage potential held on the boundary.

to_elmer

to_elmer() -> dict[str, float | str]

The electrode potential plus the Save Scalars flag that makes SaveScalars integrate the electrode current.

Source code in src/femforge/physical/conditions.py
def to_elmer(self) -> dict[str, float | str]:
    """The electrode potential plus the ``Save Scalars`` flag that makes SaveScalars integrate the electrode current."""
    out: dict[str, float | str] = super().to_elmer()
    # Mark the electrode for SaveScalars boundary integration (the per-phase current measurement).
    out["Save Scalars"] = "Logical True"
    return out

HeatFlux pydantic-model

Bases: Condition

A prescribed heat flux through a boundary.

Fields:

kind pydantic-field

kind: Literal['heat_flux'] = 'heat_flux'

Discriminator that names this condition type in a serialized config.

physics pydantic-field

physics: Physics = Physics.THERMAL

The physics whose solve this condition feeds.

target pydantic-field

Whether the condition attaches to a body or a boundary.

value pydantic-field

value: HeatFlux

q_s [W/m²]: Heat flux through the boundary.

yields_to

yields_to(emitted: Mapping[str, SifValue]) -> tuple[tuple[str, str], ...]

The heat flux, which a fixed temperature on the same boundary overrides.

Source code in src/femforge/physical/conditions.py
def yields_to(self, emitted: Mapping[str, SifValue]) -> tuple[tuple[str, str], ...]:
    """The heat flux, which a fixed temperature on the same boundary overrides."""
    return tuple((key, str(ElmerVariable.TEMPERATURE)) for key in emitted)

HeatSource pydantic-model

Bases: Condition

A volumetric heat source in a body.

With temperature_coefficient set, the source scales linearly with the local temperature, the σ(T) Joule feedback of a prescribed-current winding.

Fields:

kind pydantic-field

kind: Literal['heat_source'] = 'heat_source'

Discriminator that names this condition type in a serialized config.

physics pydantic-field

physics: Physics = Physics.THERMAL

The physics whose solve this condition feeds.

target pydantic-field

Whether the condition attaches to a body or a boundary.

power_density pydantic-field

power_density: PowerDensity

q [W/m³]: Heat generation density at reference_temperature when a coefficient is set, else the constant source.

temperature_coefficient pydantic-field

temperature_coefficient: float | None = None

α [1/K]: Linear coefficient in q(T) = power_density·(1 + α·(T − reference_temperature)); None emits the constant.

reference_temperature pydantic-field

reference_temperature: Temperature | None = None

T_ref [K]: The temperature power_density holds at; required with temperature_coefficient.

to_elmer

to_elmer() -> dict[str, float | str]

The Volumetric Heat Source keyword, a MATC expression in temperature when temperature_coefficient is set.

Source code in src/femforge/physical/conditions.py
def to_elmer(self) -> dict[str, float | str]:
    """The ``Volumetric Heat Source`` keyword, a MATC expression in temperature when ``temperature_coefficient`` is set."""
    out: dict[str, float | str] = super().to_elmer()
    if self.temperature_coefficient is not None:
        if self.reference_temperature is None:
            raise ValueError("temperature_coefficient requires reference_temperature (the temperature power_density holds at).")
        source_at_reference: float = _si(self.power_density, U.W / U.m**3)
        reference_kelvin: float = _si(self.reference_temperature, U.K)
        out["Volumetric Heat Source"] = f'Variable Temperature\n    Real MATC "{source_at_reference:.9g}*(1.0+{self.temperature_coefficient:.9g}*(tx(0)-{reference_kelvin:.9g}))"'
    return out

JouleHeat pydantic-model

Bases: Condition

Heats a body with the Joule losses of its solved current.

It takes no value: HeatSolve integrates the loss density StatCurrentSolve solves for.

Fields:

kind pydantic-field

kind: Literal['joule_heat'] = 'joule_heat'

Discriminator that names this condition type in a serialized config.

physics pydantic-field

The physics whose solve this condition feeds.

target pydantic-field

Whether the condition attaches to a body or a boundary.

to_elmer

to_elmer() -> dict[str, float | str]

The Joule Heat flag.

Source code in src/femforge/physical/conditions.py
def to_elmer(self) -> dict[str, float | str]:
    """The ``Joule Heat`` flag."""
    return {"Joule Heat": "Logical True"}

Magnetization pydantic-model

Bases: Condition

The magnetization direction of a permanent magnet.

The magnitude |M| = Bᵣ/μ₀ comes from the magnet's material.

Fields:

kind pydantic-field

kind: Literal['magnetization'] = 'magnetization'

Discriminator that names this condition type in a serialized config.

physics pydantic-field

The physics whose solve this condition feeds.

target pydantic-field

Whether the condition attaches to a body or a boundary.

direction pydantic-field

direction: DirectionField | None

Magnetization direction in the authored model's frame, None for an unmagnetized body; magnitude comes from the material.

to_elmer

to_elmer(magnitude: float, frame: Frame) -> dict[str, float | str]

The Magnetization components of magnitude (A/m) along the direction, in frame's solve coordinates.

Source code in src/femforge/physical/conditions.py
def to_elmer(self, magnitude: float, frame: Frame) -> dict[str, float | str]:
    """The ``Magnetization`` components of ``magnitude`` (A/m) along the direction, in ``frame``'s solve coordinates."""
    unit: Vec3 | None = self.direction

    if unit is None:
        raise ValueError("A Magnetization without a direction has no components to emit.")

    components: tuple[float, ...] = frame.solve_vector(unit)

    return {f"Magnetization {index}": f"{component * magnitude:.6g}" for index, component in enumerate(components, start=1)}

check_frame

check_frame(frame: Frame) -> None

Raise when frame has no form for the direction.

Source code in src/femforge/physical/conditions.py
def check_frame(self, frame: Frame) -> None:
    """Raise when ``frame`` has no form for the direction."""
    # A missing direction is left to Sim.validate, which reports it as a missing direction rather than a frame mismatch.
    if self.direction is None:
        return

    try:
        _ = frame.solve_vector(self.direction)
    except ValueError as error:
        raise ValueError(f"Magnetization direction {self.direction} has no form in the {frame.label} frame: {error}") from None

solve_components

solve_components(frame: Frame) -> tuple[tuple[int, float], ...]

The solve components of the unit direction in frame; none without a direction.

Source code in src/femforge/physical/conditions.py
def solve_components(self, frame: Frame) -> tuple[tuple[int, float], ...]:
    """The solve components of the unit direction in ``frame``; none without a direction."""
    if self.direction is None:
        return ()

    components: tuple[float, ...] = frame.solve_vector(self.direction)

    return tuple(enumerate(components, start=1))

summary

summary(emitted: Mapping[str, float | str] | None = None, *, frame: Frame | None = None) -> tuple[SummaryLine, ...]

The authored direction, then the remanence Br = μ₀·M of the emitted Magnetization i components in solve order; frame is ignored.

Parameters:

  • emitted (Mapping[str, float | str] | None, default: None ) –

    The keywords the magnet's Material block received, by name.

  • frame (Frame | None, default: None ) –

    The frame the run solved in.

Source code in src/femforge/physical/conditions.py
def summary(self, emitted: Mapping[str, float | str] | None = None, *, frame: Frame | None = None) -> tuple[SummaryLine, ...]:
    """The authored direction, then the remanence ``Br = μ₀·M`` of the emitted ``Magnetization i`` components in solve order; ``frame`` is ignored.

    Args:
        emitted: The keywords the magnet's Material block received, by name.
        frame: The frame the run solved in.
    """
    if self.direction is None:
        return ((SummaryPart("No Direction"),),)

    direction: SummaryLine = (SummaryPart(f"Along {along(self.direction)}"),)
    components: list[tuple[int, float | str]] = _numbers(emitted, "Magnetization")

    if not components:
        return (direction,)

    mu_0: float = quantity(1.0, "mu_0").m_as("T*m/A")

    return (direction, (_components_part(components, "T", "Br", scale=mu_0),))

SummaryPart dataclass

SummaryPart(value: str, label: str = '', component: Component | None = None, tip: str = '')

One value of a condition as the Setup tab reads it, with the glyph or word read before it.

Attributes:

  • value (str) –

    The value as read, such as 100 N Along (1, 0, 0).

  • label (str) –

    The glyph or word read before the value, such as h or Traction; empty for none.

  • component (Component | None) –

    The authored axis the part reads, so the Setup tab can mark an axis the frame drops; None for any other part.

  • tip (str) –

    What a placeholder in the value stands for, such as the expression an expr replaces; empty for none.

value instance-attribute

value: str

The value as read, such as 100 N Along (1, 0, 0).

label class-attribute instance-attribute

label: str = ''

The glyph or word read before the value, such as h or Traction; empty for none.

component class-attribute instance-attribute

component: Component | None = None

The authored axis the part reads, so the Setup tab can mark an axis the frame drops; None for any other part.

tip class-attribute instance-attribute

tip: str = ''

What a placeholder in the value stands for, such as the expression an expr replaces; empty for none.

SurfaceForce pydantic-model

Bases: Condition

A total force spread uniformly over a named face as a traction.

Attach it to a TaggedFace's tag: the traction is the force over the face's measured area, which an adjacency group does not carry.

Fields:

kind pydantic-field

kind: Literal['surface_force'] = 'surface_force'

Discriminator that names this condition type in a serialized config.

physics pydantic-field

The physics whose solve this condition feeds.

target pydantic-field

Whether the condition attaches to a body or a boundary.

force pydantic-field

force: Force

F⃗ [N]: Total force spread uniformly over the face, in the authored frame.

yields_to

yields_to(emitted: Mapping[str, SifValue]) -> tuple[tuple[str, str], ...]

Each nonzero Force i, which a fixed Displacement i on the same boundary overrides.

Source code in src/femforge/physical/conditions.py
def yields_to(self, emitted: Mapping[str, SifValue]) -> tuple[tuple[str, str], ...]:
    """Each nonzero ``Force i``, which a fixed ``Displacement i`` on the same boundary overrides."""
    return tuple((key, f"{ElmerVariable.DISPLACEMENT} {key.removeprefix('Force ')}") for key, value in emitted.items() if key.startswith("Force ") and value != 0.0)

to_elmer

to_elmer() -> dict[str, float | str]

Raise: the traction needs the face area, which only on_boundary knows.

Source code in src/femforge/physical/conditions.py
def to_elmer(self) -> dict[str, float | str]:
    """Raise: the traction needs the face area, which only [`on_boundary`][femforge.physical.conditions.SurfaceForce.on_boundary] knows."""
    raise ValueError("SurfaceForce needs the area of the face it lands on; it emits through on_boundary only.")

on_boundary

on_boundary(site: BoundarySite) -> dict[str, float | str]

The Force i traction components, the solve-frame force share over the measured area of site.

Source code in src/femforge/physical/conditions.py
def on_boundary(self, site: BoundarySite) -> dict[str, float | str]:
    """The ``Force i`` traction components, the solve-frame force share over the measured area of ``site``."""
    measure: float | None = site.measure

    if measure is None or measure <= 0.0:
        raise ValueError(f"SurfaceForce on boundary group {site.name} has no measured area; attach SurfaceForce to a TaggedFace's EntityTag.")

    components: tuple[float, ...] = self._solve_force(site.frame)

    return {f"Force {index}": component / measure for index, component in enumerate(components, start=1)}

check_frame

check_frame(frame: Frame) -> None

Raise when frame has no form for the force direction.

Source code in src/femforge/physical/conditions.py
def check_frame(self, frame: Frame) -> None:
    """Raise when ``frame`` has no form for the force direction."""
    try:
        _ = self._solve_force(frame)
    except ValueError as error:
        raise ValueError(f"SurfaceForce has no form in the {frame.label} frame: {error}") from None

solve_components

solve_components(frame: Frame) -> tuple[tuple[int, float], ...]

The solve components, in N, of the share of the force the solve domain carries in frame: per metre of depth in Cartesian 2D.

Source code in src/femforge/physical/conditions.py
def solve_components(self, frame: Frame) -> tuple[tuple[int, float], ...]:
    """The solve components, in N, of the share of the force the solve domain carries in ``frame``: per metre of depth in Cartesian 2D."""
    components: tuple[float, ...] = self._solve_force(frame)

    return tuple(enumerate(components, start=1))

summary

summary(emitted: Mapping[str, float | str] | None = None, *, frame: Frame | None = None) -> tuple[SummaryLine, ...]

The authored total and its direction, then the signed traction the emitted Force i components hold on the face, in solve order; frame is ignored.

Parameters:

  • emitted (Mapping[str, float | str] | None, default: None ) –

    The keywords the face's sif block received, by name.

  • frame (Frame | None, default: None ) –

    The frame the run solved in.

Source code in src/femforge/physical/conditions.py
def summary(self, emitted: Mapping[str, float | str] | None = None, *, frame: Frame | None = None) -> tuple[SummaryLine, ...]:
    """The authored total and its direction, then the signed traction the emitted ``Force i`` components hold on the face, in solve order; ``frame`` is ignored.

    Args:
        emitted: The keywords the face's sif block received, by name.
        frame: The frame the run solved in.
    """
    total: SummaryLine = (SummaryPart(vector_readout(self.force)),)
    components: list[tuple[int, float | str]] = _numbers(emitted, "Force")

    if not components:
        return (total,)

    return (total, (_components_part(components, "Pa", "Traction"),))

DomainConfig pydantic-model

Bases: ConfigArea

The materials the mesher matches to STEP parts, plus the per-region EntityTag overrides (conditions / mesh refinement).

Fields:

materials pydantic-field

The candidate materials; the mesher matches each STEP entity to one by tag.

tags pydantic-field

tags: list[EntityTag]

The per-region overrides, matched to mesh entities by name; each carries its conditions and optional mesh_size.

check_frame

check_frame(frame: Frame) -> None

Raise when a condition here cannot drive a frame solve.

Source code in src/femforge/physical/domain.py
def check_frame(self, frame: Frame) -> None:
    """Raise when a condition here cannot drive a ``frame`` solve."""
    for tag in self.tags:
        for condition in tag.conditions:
            condition.check_frame(frame)

EntityTag pydantic-model

Bases: ConfigArea

A per-region override matched to a mesh entity by its authored tags; carries the region's self-describing conditions.

Fields:

selector pydantic-field

selector: TagDict

Compound-key selector: a mesh entity matches when its tag dict contains ALL of these key=value pairs (an empty selector matches every entity).

conditions pydantic-field

conditions: list[ConditionUnion]

Composable, self-describing conditions (body forces / boundary conditions) this region carries.

mesh_size pydantic-field

mesh_size: Length | None = None

h [mm]: Target mesh size for this region, such as a finer air gap; None inherits MeshConfig.global_mesh_size.

name property

name: str

Stable human-readable stem shared with gmsh/Elmer names: the uppercased part name for a lone Name selector, else sorted KeyValue pairs (CurrentDirEntry_Phase2).

matches

matches(tags: Mapping[str, str]) -> bool

Whether an entity's tag dict satisfies every selector pair.

Source code in src/femforge/physical/domain.py
def matches(self, tags: Mapping[str, str]) -> bool:
    """Whether an entity's tag dict satisfies every selector pair."""
    return all(tags.get(key) == value for key, value in self.selector.items())

print_tree

print_tree(tree: Tree) -> None

Add this tag and its conditions to tree.

Source code in src/femforge/physical/domain.py
def print_tree(self, tree: Tree) -> None:
    """Add this tag and its conditions to ``tree``."""
    report: Tree = tree.add(COLORS.H2(f"Tag: {self.name}"))
    for condition in self.conditions:
        report.add(COLORS.Prop(type(condition).__name__, f"{condition}"))

Add pydantic-model

Bases: _Binary

The sum of two subexpressions.

Fields:

  • left ('Expr')
  • right ('Expr')
  • op (Literal['add'])
  • _symbol (str)

op pydantic-field

op: Literal['add'] = 'add'

Discriminator that names this node type in serialized JSON.

evaluate

evaluate(env: Mapping[str, float]) -> float

The sum of both operands.

Source code in src/femforge/physical/expressions.py
def evaluate(self, env: Mapping[str, float]) -> float:
    """The sum of both operands."""
    return self.left.evaluate(env) + self.right.evaluate(env)

Const pydantic-model

Bases: ExprNode

A literal SI magnitude.

Fields:

op pydantic-field

op: Literal['const'] = 'const'

Discriminator that names this node type in serialized JSON.

value pydantic-field

value: float

c [?]: The literal magnitude, in SI units.

evaluate

evaluate(env: Mapping[str, float]) -> float

The literal value.

Source code in src/femforge/physical/expressions.py
def evaluate(self, env: Mapping[str, float]) -> float:
    """The literal value."""
    return self.value

render

render(refs: Mapping[str, str]) -> str

The literal at full float precision.

Source code in src/femforge/physical/expressions.py
def render(self, refs: Mapping[str, str]) -> str:
    """The literal at full float precision."""
    # repr keeps full float precision; MATC and Lua both read e-notation.
    return repr(self.value)

parameters

parameters() -> frozenset[str]

The empty set: a literal references no parameter.

Source code in src/femforge/physical/expressions.py
def parameters(self) -> frozenset[str]:
    """The empty set: a literal references no parameter."""
    return frozenset()

Div pydantic-model

Bases: _Binary

The quotient of two subexpressions.

Fields:

  • left ('Expr')
  • right ('Expr')
  • op (Literal['div'])
  • _symbol (str)

op pydantic-field

op: Literal['div'] = 'div'

Discriminator that names this node type in serialized JSON.

evaluate

evaluate(env: Mapping[str, float]) -> float

The left operand divided by the right one.

Source code in src/femforge/physical/expressions.py
def evaluate(self, env: Mapping[str, float]) -> float:
    """The left operand divided by the right one."""
    return self.left.evaluate(env) / self.right.evaluate(env)

ExprNode pydantic-model

Bases: BaseModel

Base node: shared config + Python operator composition, so laws are authored as plain arithmetic.

Config:

  • frozen: True
  • use_attribute_docstrings: True

evaluate

evaluate(env: Mapping[str, float]) -> float

This subtree's value with each parameter bound to a bare SI float.

Source code in src/femforge/physical/expressions.py
def evaluate(self, env: Mapping[str, float]) -> float:
    """This subtree's value with each parameter bound to a bare SI float."""
    raise NotImplementedError

render

render(refs: Mapping[str, str]) -> str

This subtree as backend source, with each parameter name replaced by its reference (e.g. tx(0)).

Source code in src/femforge/physical/expressions.py
def render(self, refs: Mapping[str, str]) -> str:
    """This subtree as backend source, with each parameter name replaced by its reference (e.g. ``tx(0)``)."""
    raise NotImplementedError

parameters

parameters() -> frozenset[str]

Every parameter name referenced in this subtree.

Source code in src/femforge/physical/expressions.py
def parameters(self) -> frozenset[str]:
    """Every parameter name referenced in this subtree."""
    raise NotImplementedError

Mul pydantic-model

Bases: _Binary

The product of two subexpressions.

Fields:

  • left ('Expr')
  • right ('Expr')
  • op (Literal['mul'])
  • _symbol (str)

op pydantic-field

op: Literal['mul'] = 'mul'

Discriminator that names this node type in serialized JSON.

evaluate

evaluate(env: Mapping[str, float]) -> float

The product of both operands.

Source code in src/femforge/physical/expressions.py
def evaluate(self, env: Mapping[str, float]) -> float:
    """The product of both operands."""
    return self.left.evaluate(env) * self.right.evaluate(env)

Neg pydantic-model

Bases: ExprNode

The negation of a subexpression.

Fields:

op pydantic-field

op: Literal['neg'] = 'neg'

Discriminator that names this node type in serialized JSON.

operand pydantic-field

operand: 'Expr'

The negated subexpression.

evaluate

evaluate(env: Mapping[str, float]) -> float

The negated operand.

Source code in src/femforge/physical/expressions.py
def evaluate(self, env: Mapping[str, float]) -> float:
    """The negated operand."""
    return -self.operand.evaluate(env)

render

render(refs: Mapping[str, str]) -> str

The negation as (-operand).

Source code in src/femforge/physical/expressions.py
def render(self, refs: Mapping[str, str]) -> str:
    """The negation as ``(-operand)``."""
    return f"(-{self.operand.render(refs)})"

parameters

parameters() -> frozenset[str]

The operand's parameters.

Source code in src/femforge/physical/expressions.py
def parameters(self) -> frozenset[str]:
    """The operand's parameters."""
    return self.operand.parameters()

Param pydantic-model

Bases: ExprNode

A named parameter (e.g. temperature), bound at evaluation/render time.

Fields:

op pydantic-field

op: Literal['param'] = 'param'

Discriminator that names this node type in serialized JSON.

name pydantic-field

name: str

The parameter name that env and refs bind.

evaluate

evaluate(env: Mapping[str, float]) -> float

The value env binds to this parameter.

Source code in src/femforge/physical/expressions.py
def evaluate(self, env: Mapping[str, float]) -> float:
    """The value ``env`` binds to this parameter."""
    if self.name not in env:
        raise KeyError(f"expression parameter {self.name!r} not bound; supplied: {sorted(env)}")
    return env[self.name]

render

render(refs: Mapping[str, str]) -> str

The backend reference refs binds to this parameter.

Source code in src/femforge/physical/expressions.py
def render(self, refs: Mapping[str, str]) -> str:
    """The backend reference ``refs`` binds to this parameter."""
    if self.name not in refs:
        raise KeyError(f"expression parameter {self.name!r} has no backend reference; supplied: {sorted(refs)}")
    return refs[self.name]

parameters

parameters() -> frozenset[str]

This parameter's name.

Source code in src/femforge/physical/expressions.py
def parameters(self) -> frozenset[str]:
    """This parameter's name."""
    return frozenset({self.name})

Pow pydantic-model

Bases: ExprNode

One subexpression raised to the power of another.

Fields:

op pydantic-field

op: Literal['pow'] = 'pow'

Discriminator that names this node type in serialized JSON.

base pydantic-field

base: 'Expr'

The base.

exponent pydantic-field

exponent: 'Expr'

The exponent.

evaluate

evaluate(env: Mapping[str, float]) -> float

The base raised to the exponent.

Source code in src/femforge/physical/expressions.py
def evaluate(self, env: Mapping[str, float]) -> float:
    """The base raised to the exponent."""
    # math.pow keeps the operation float-typed (the ** operator's stub admits complex).
    return math.pow(self.base.evaluate(env), self.exponent.evaluate(env))

render

render(refs: Mapping[str, str]) -> str

The power as (base ^ exponent).

Source code in src/femforge/physical/expressions.py
def render(self, refs: Mapping[str, str]) -> str:
    """The power as ``(base ^ exponent)``."""
    # ^ is exponentiation in both MATC and Lua.
    return f"({self.base.render(refs)} ^ {self.exponent.render(refs)})"

parameters

parameters() -> frozenset[str]

The parameters of the base and the exponent.

Source code in src/femforge/physical/expressions.py
def parameters(self) -> frozenset[str]:
    """The parameters of the base and the exponent."""
    return self.base.parameters() | self.exponent.parameters()

Sub pydantic-model

Bases: _Binary

The difference of two subexpressions.

Fields:

  • left ('Expr')
  • right ('Expr')
  • op (Literal['sub'])
  • _symbol (str)

op pydantic-field

op: Literal['sub'] = 'sub'

Discriminator that names this node type in serialized JSON.

evaluate

evaluate(env: Mapping[str, float]) -> float

The left operand minus the right one.

Source code in src/femforge/physical/expressions.py
def evaluate(self, env: Mapping[str, float]) -> float:
    """The left operand minus the right one."""
    return self.left.evaluate(env) - self.right.evaluate(env)

BasePropertyFunction pydantic-model

Bases: BaseModel

Pydantic base implementing parameter checking once; subclasses declare parameters / result_dimensionality and implement _evaluate.

Extra keyword arguments are ignored, so an operating point may carry more quantities than a property needs.

Config:

  • arbitrary_types_allowed: True
  • use_attribute_docstrings: True

parameters property

parameters: Mapping[str, str]

Required parameter name to expected dimensionality, as a pint string.

result_dimensionality property

result_dimensionality: str

Dimensionality of the returned quantity.

Calibration pydantic-model

Bases: BasePropertyFunction

A property defined by sample points and interpolated between them (1-D only for now).

Point inputs are validated against param_dims at construction; out-of-range raises unless extrapolate=True.

Fields:

Validators:

  • _validate_points

kind pydantic-field

kind: Literal['calibration'] = 'calibration'

Discriminator that names this property kind in serialized JSON.

param_dims pydantic-field

param_dims: dict[str, str]

The single parameter name and its expected dimensionality, as a pint string.

points pydantic-field

The samples to interpolate between.

method pydantic-field

method: Literal['linear', 'nearest', 'cubic'] = 'linear'

Interpolation between samples: linear, nearest, or monotone cubic (PCHIP).

extrapolate pydantic-field

extrapolate: bool = False

Clamp to the end samples outside the calibrated range instead of raising.

parameters property

parameters: Mapping[str, str]

param_dims as the call schema.

result_dimensionality property

result_dimensionality: str

The dimensionality of the sample outputs.

CalibrationPoint pydantic-model

Bases: BaseModel

One measured sample: input quantities by name and the resulting output.

Config:

  • arbitrary_types_allowed: True
  • use_attribute_docstrings: True

Fields:

Validators:

inputs pydantic-field

inputs: dict[str, Quantity]

[?]: The input quantities, keyed by parameter name.

output pydantic-field

output: Quantity

[?]: The property value measured at inputs.

ClosedForm pydantic-model

Bases: BasePropertyFunction

A property defined by an explicit Python callable, pint-in / pint-out; the callable is code, not JSON-serializable.

Fields:

param_dims pydantic-field

param_dims: dict[str, str]

Parameter name to expected dimensionality, as a pint string.

result_dim pydantic-field

result_dim: str

The dimensionality the callable must return, as a pint string.

expression pydantic-field

expression: Callable[..., Quantity]

The callable, given the declared parameters as keyword quantities.

parameters property

parameters: Mapping[str, str]

param_dims as the call schema.

result_dimensionality property

result_dimensionality: str

The declared result_dim.

Expression pydantic-model

Bases: BasePropertyFunction

A property defined by a serializable typed expression AST (physical.expressions) — ClosedForm as data instead of code.

body computes the result's SI magnitude in result_units from parameters bound as SI-base magnitudes, matching Elmer's tx.

Fields:

Validators:

  • _validate_body_parameters

kind pydantic-field

kind: Literal['expression'] = 'expression'

Discriminator that names this property kind in serialized JSON.

param_dims pydantic-field

param_dims: dict[str, str]

Parameter name to expected dimensionality, as a pint string.

result_units pydantic-field

result_units: str

The pint units of the magnitude body computes.

body pydantic-field

body: Expr

The law over parameters bound as SI-base magnitudes.

parameters property

parameters: Mapping[str, str]

param_dims as the call schema.

result_dimensionality property

result_dimensionality: str

The dimensionality of result_units.

PropertyDimensionError

PropertyDimensionError(fn: 'PropertyFunction', name: str, expected: str, got: object)

Bases: PropertyError

A supplied parameter had the wrong dimensionality.

Parameters:

  • fn ('PropertyFunction') –

    The property that rejected the call.

  • name (str) –

    The offending parameter, or <result> for a closed form's return value.

  • expected (str) –

    The dimensionality the parameter needs.

  • got (object) –

    The dimensionality, or the type, that was supplied.

Source code in src/femforge/physical/property_functions.py
def __init__(self, fn: "PropertyFunction", name: str, expected: str, got: object) -> None:
    """Record which parameter of ``fn`` had the wrong dimensionality.

    Args:
        fn: The property that rejected the call.
        name: The offending parameter, or ``<result>`` for a closed form's return value.
        expected: The dimensionality the parameter needs.
        got: The dimensionality, or the type, that was supplied.
    """
    self.fn: PropertyFunction = fn
    self.name: str = name
    self.expected: str = expected
    self.got: object = got
    super().__init__(f"{type(fn).__name__} parameter {name!r} expected {expected or 'dimensionless'}, got {got}.")

PropertyError

Bases: Exception

Base class for every property-function error.

PropertyFunction

Bases: Protocol

A material property as a function of zero or more named pint quantities, returning a pint Quantity.

Methods:

  • __call__ –

    Evaluate. Raises a typed error if a required parameter is missing or has the wrong dimensionality.

Attributes:

  • parameters (Mapping[str, str]) –

    Required parameter name -> expected dimensionality (pint string); this IS the call schema.

  • result_dimensionality (str) –

    Dimensionality of the returned quantity, e.g. '[power]/[length]/[temperature]'.

parameters property

parameters: Mapping[str, str]

Required parameter name -> expected dimensionality (pint string); this IS the call schema.

result_dimensionality property

result_dimensionality: str

Dimensionality of the returned quantity, e.g. '[power]/[length]/[temperature]'.

__call__

__call__(**kwargs: Quantity) -> Quantity

Evaluate. Raises a typed error if a required parameter is missing or has the wrong dimensionality.

Source code in src/femforge/physical/property_functions.py
def __call__(self, **kwargs: Quantity) -> Quantity:
    """Evaluate. Raises a typed error if a required parameter is missing or has the wrong dimensionality."""
    ...

PropertyFunctionField

PropertyFunctionField(dimensionality: str)

Annotated metadata for a PropertyFunction constrained to dimensionality.

Coerces bare quantities/strings into Static, validates result dimensionality, and exports quantity_type's unit-annotated JSON schema.

Source code in src/femforge/physical/property_functions.py
def __init__(self, dimensionality: str) -> None:
    """Constrain the field to properties of ``dimensionality``."""
    self.dimensionality = dimensionality

PropertyParameterError

PropertyParameterError(fn: 'PropertyFunction', missing: set[str])

Bases: PropertyError

A required parameter was not supplied when evaluating a property.

Source code in src/femforge/physical/property_functions.py
def __init__(self, fn: "PropertyFunction", missing: set[str]) -> None:
    """Name the parameters of ``fn`` the call left out."""
    self.fn: PropertyFunction = fn
    self.missing: set[str] = set(missing)
    wanted: str = ", ".join(f"{name}=<{dim or 'dimensionless'}>" for name, dim in fn.parameters.items())
    names: str = ", ".join(sorted(self.missing))
    super().__init__(f"{type(fn).__name__} requires [{wanted}]; not supplied: {names}.")

PropertyRangeError

PropertyRangeError(fn: 'PropertyFunction', name: str, value: object, low: object, high: object)

Bases: PropertyError

A parameter fell outside the calibrated range and extrapolation is off.

Parameters:

  • fn ('PropertyFunction') –

    The calibration that rejected the call.

  • name (str) –

    The out-of-range parameter.

  • value (object) –

    The supplied value.

  • low (object) –

    The lowest calibrated value.

  • high (object) –

    The highest calibrated value.

Source code in src/femforge/physical/property_functions.py
def __init__(self, fn: "PropertyFunction", name: str, value: object, low: object, high: object) -> None:
    """Record a parameter of ``fn`` that fell outside the calibrated range.

    Args:
        fn: The calibration that rejected the call.
        name: The out-of-range parameter.
        value: The supplied value.
        low: The lowest calibrated value.
        high: The highest calibrated value.
    """
    self.fn: PropertyFunction = fn
    self.name: str = name
    super().__init__(f"{type(fn).__name__} parameter {name!r}={value} is outside the calibrated range [{low}, {high}]; set extrapolate=True to allow.")

Static pydantic-model

Bases: BasePropertyFunction

A constant property: zero parameters, always returns value.

Authored as Static(value="8.7 W/(m*K)"); ignores any operating-point arguments.

Fields:

Validators:

  • _coerce_value → value

value pydantic-field

value: Quantity

[?]: The constant returned at every operating point.

parameters property

parameters: Mapping[str, str]

No parameters: a constant ignores the operating point.

result_dimensionality property

result_dimensionality: str

The dimensionality of value.

Quantity

Bases: PlainQuantity[float]

A pint quantity with a float magnitude.

Methods:

  • to –

    This quantity converted to the units other names.

to

to(other: object = None, *contexts: object, **ctx_kwargs: object) -> Quantity

This quantity converted to the units other names.

Parameters:

  • other (object, default: None ) –

    The target units, as a unit, a quantity or a unit string.

  • contexts (object, default: () ) –

    The pint contexts, by name or object, that enable the conversion.

  • ctx_kwargs (object, default: {} ) –

    The parameters those contexts take.

Source code in src/femforge/physical/units.py
def to(self, other: object = None, *contexts: object, **ctx_kwargs: object) -> Quantity:
    """This quantity converted to the units ``other`` names.

    Args:
        other: The target units, as a unit, a quantity or a unit string.
        contexts: The pint contexts, by name or object, that enable the conversion.
        ctx_kwargs: The parameters those contexts take.
    """
    ...

Unit

Bases: PlainUnit

A pint unit, typed so that arithmetic with units and numbers keeps its type.

VectorQuantity

Bases: PlainQuantity[Vec3]

A pint quantity with a Vec3 magnitude.

Methods:

  • to –

    This vector quantity converted to the units other names.

to

to(other: object = None, *contexts: object, **ctx_kwargs: object) -> VectorQuantity

This vector quantity converted to the units other names.

Parameters:

  • other (object, default: None ) –

    The target units, as a unit, a quantity or a unit string.

  • contexts (object, default: () ) –

    The pint contexts, by name or object, that enable the conversion.

  • ctx_kwargs (object, default: {} ) –

    The parameters those contexts take.

Source code in src/femforge/physical/units.py
def to(self, other: object = None, *contexts: object, **ctx_kwargs: object) -> VectorQuantity:
    """This vector quantity converted to the units ``other`` names.

    Args:
        other: The target units, as a unit, a quantity or a unit string.
        contexts: The pint contexts, by name or object, that enable the conversion.
        ctx_kwargs: The parameters those contexts take.
    """
    ...

shipped_conditions

shipped_conditions() -> tuple[type[Condition], ...]

The condition classes ConditionUnion admits, in its order.

Source code in src/femforge/physical/conditions.py
def shipped_conditions() -> tuple[type[Condition], ...]:
    """The condition classes ``ConditionUnion`` admits, in its order."""
    parts: tuple[object, ...] = get_args(ConditionUnion)

    return cast("tuple[type[Condition], ...]", get_args(parts[0]))

conditions_for

conditions_for(tags: Iterable[EntityTag], physics: Physics | Iterable[Physics], target: ConditionTarget) -> list[Condition]

The conditions on tags that belong to physics and attach to target.

Parameters:

Source code in src/femforge/physical/domain.py
def conditions_for(tags: Iterable["EntityTag"], physics: Physics | Iterable[Physics], target: ConditionTarget) -> list[Condition]:
    """The conditions on ``tags`` that belong to ``physics`` and attach to ``target``.

    Args:
        tags: The region overrides that match the region.
        physics: One [`Physics`][femforge.elmer.physics.Physics], or several, such as a coupled preset's constituents.
        target: Whether to collect body or boundary conditions.
    """
    wanted: frozenset[Physics] = frozenset({physics}) if isinstance(physics, Physics) else frozenset(physics)
    matching: list[Condition] = []
    for tag in tags:
        for condition in tag.conditions:
            if condition.physics in wanted and condition.target == target:
                matching.append(condition)
    return matching

as_expr

as_expr(value: 'ExprNode | float') -> 'Expr'

Wrap a bare number into Const; pass nodes through (the operator-composition coercion point).

Source code in src/femforge/physical/expressions.py
def as_expr(value: "ExprNode | float") -> "Expr":
    """Wrap a bare number into [`Const`][]; pass nodes through (the operator-composition coercion point)."""
    if isinstance(value, ExprNode):
        return value  # pyright: ignore[reportReturnType]  # every concrete node is a union member; ExprNode itself is never instantiated
    return Const(value=float(value))

evaluate

evaluate(expr: 'Expr', env: Mapping[str, float]) -> float

Module-level convenience mirroring expr.evaluate.

Source code in src/femforge/physical/expressions.py
def evaluate(expr: "Expr", env: Mapping[str, float]) -> float:
    """Module-level convenience mirroring ``expr.evaluate``."""
    return expr.evaluate(env)

render

render(expr: 'Expr', *, refs: Mapping[str, str]) -> str

Backend source for expr with parameter references substituted (e.g. {"temperature": "tx(0)"}).

Source code in src/femforge/physical/expressions.py
def render(expr: "Expr", *, refs: Mapping[str, str]) -> str:
    """Backend source for ``expr`` with parameter references substituted (e.g. ``{"temperature": "tx(0)"}``)."""
    return expr.render(refs)

property_function_type

property_function_type(dimensionality: str) -> object

A PropertyFunction constrained to dimensionality, usable as a Pydantic field.

Source code in src/femforge/physical/property_functions.py
def property_function_type(dimensionality: str) -> object:
    """A [`PropertyFunction`][] constrained to ``dimensionality``, usable as a Pydantic field."""
    return Annotated[PropertyFunction, PropertyFunctionField(dimensionality)]

quantity

quantity(value: float, units: Unit | str | None = None) -> Quantity
quantity(value: Vec3, units: Unit | str | None = None) -> VectorQuantity
quantity(value: float | Vec3, units: Unit | str | None = None) -> Quantity | VectorQuantity

Statically-typed face of U.Quantity(...): a float magnitude yields Quantity, a Vec3 yields VectorQuantity.

Prefer a string for composite units ("newton * meter").

Source code in src/femforge/physical/units.py
def quantity(value: float | Vec3, units: Unit | str | None = None) -> Quantity | VectorQuantity:
    """
    Statically-typed face of ``U.Quantity(...)``: a ``float`` magnitude yields [`Quantity`][], a Vec3 yields [`VectorQuantity`][].

    Prefer a string for composite units (``"newton * meter"``).
    """
    return cast("Quantity | VectorQuantity", U.Quantity(value, units))  # pyright: ignore[reportCallIssue, reportArgumentType]

femforge.physical.readout

Short readouts of quantities and directions, at three significant figures on fixed unit ladders.

Classes:

  • Rung –

    One unit a ladder can read a quantity in: its pint expression and the label it prints.

  • Ladder –

    The units one dimensionality reads in, smallest first.

Functions:

  • readout –

    value at three significant figures in the largest rung of its ladder that reads at least 1, or in unit when given.

  • along –

    The unit direction of direction as its three components at three significant figures, such as (0.6, 0.8, 0).

  • vector_readout –

    The magnitude of value and the direction it points along, such as 100 N Along (1, 0, 0).

  • components_readout –

    Signed components in the SI unit as one tuple in the rung their largest reads in, such as (500, -0.2) kPa; a text component reads as itself.

Attributes:

LENGTH module-attribute

LENGTH = Ladder((Rung('mm', 'mm'), Rung('m', 'm')))

Lengths in mm or m.

AREA module-attribute

AREA = Ladder((Rung('mm**2', 'mm²'), Rung('m**2', 'm²')))

Areas in mm² or m².

FORCE module-attribute

FORCE = Ladder((Rung('N', 'N'), Rung('kN', 'kN'), Rung('MN', 'MN')))

Forces in N, kN or MN.

PRESSURE module-attribute

PRESSURE = Ladder((Rung('Pa', 'Pa'), Rung('kPa', 'kPa'), Rung('MPa', 'MPa'), Rung('GPa', 'GPa')))

Pressures and tractions in Pa up to GPa.

CURRENT_DENSITY module-attribute

CURRENT_DENSITY = Ladder((Rung('A/m**2', 'A/m²'), Rung('A/mm**2', 'A/mm²')))

Current densities in A/m² or A/mm².

VOLTAGE module-attribute

VOLTAGE = Ladder((Rung('V', 'V'), Rung('kV', 'kV')))

Voltages in V or kV.

TEMPERATURE module-attribute

TEMPERATURE = Ladder((Rung('K', 'K'),))

Temperatures in K.

HEAT_FLUX module-attribute

HEAT_FLUX = Ladder((Rung('W/m**2', 'W/m²'), Rung('kW/m**2', 'kW/m²'), Rung('MW/m**2', 'MW/m²')))

Heat fluxes in W/m² up to MW/m².

HEAT_TRANSFER module-attribute

HEAT_TRANSFER = Ladder((Rung('W/(m**2*K)', 'W/(m²·K)'),))

Heat-transfer coefficients in W/(m²·K).

POWER_DENSITY module-attribute

POWER_DENSITY = Ladder((Rung('W/m**3', 'W/m³'), Rung('kW/m**3', 'kW/m³'), Rung('MW/m**3', 'MW/m³'), Rung('GW/m**3', 'GW/m³')))

Power densities in W/m³ up to GW/m³.

CURRENT module-attribute

CURRENT = Ladder((Rung('A', 'A'), Rung('kA', 'kA')))

Currents in A or kA.

FLUX_DENSITY module-attribute

FLUX_DENSITY = Ladder((Rung('mT', 'mT'), Rung('T', 'T')), zero=Rung('T', 'T'))

Flux densities in mT or T.

LADDERS module-attribute

Every ladder, scanned in order for the first that matches a quantity.

Rung dataclass

Rung(unit: str, label: str)

One unit a ladder can read a quantity in: its pint expression and the label it prints.

Attributes:

  • unit (str) –

    The pint unit expression, such as mm**2.

  • label (str) –

    The unit as the readout prints it, such as mm².

unit instance-attribute

unit: str

The pint unit expression, such as mm**2.

label instance-attribute

label: str

The unit as the readout prints it, such as mm².

Ladder dataclass

Ladder(rungs: tuple[Rung, ...], zero: Rung | None = None)

The units one dimensionality reads in, smallest first.

Methods:

  • matches –

    Whether value has this ladder's dimensionality.

Attributes:

  • rungs (tuple[Rung, ...]) –

    The rungs, smallest unit first.

  • zero (Rung | None) –

    The rung a zero reads in; the smallest when None.

rungs instance-attribute

rungs: tuple[Rung, ...]

The rungs, smallest unit first.

zero class-attribute instance-attribute

zero: Rung | None = None

The rung a zero reads in; the smallest when None.

matches

matches(value: Quantity) -> bool

Whether value has this ladder's dimensionality.

Source code in src/femforge/physical/readout.py
def matches(self, value: Quantity) -> bool:
    """Whether ``value`` has this ladder's dimensionality."""
    return quantity(1.0, self.rungs[0].unit).dimensionality == value.dimensionality

readout

readout(value: Quantity, *, unit: Unit | None = None) -> str

value at three significant figures in the largest rung of its ladder that reads at least 1, or in unit when given.

Source code in src/femforge/physical/readout.py
def readout(value: Quantity, *, unit: Unit | None = None) -> str:
    """``value`` at three significant figures in the largest rung of its ladder that reads at least 1, or in ``unit`` when given."""
    if unit is not None:
        rungs: list[Rung] = [rung for ladder in LADDERS for rung in ladder.rungs if U.Unit(rung.unit) == unit]
        label: str = rungs[0].label if rungs else f"{unit:~P}"

        return f"{_significant(value.m_as(unit))} {label}"

    rung: Rung | None = _rung(value)

    if rung is None:
        compact: Quantity = value.to_compact()

        return f"{_significant(compact.magnitude)} {compact.units:~P}"

    return f"{_significant(value.m_as(rung.unit))} {rung.label}"

along

along(direction: Vec3) -> str

The unit direction of direction as its three components at three significant figures, such as (0.6, 0.8, 0).

Source code in src/femforge/physical/readout.py
def along(direction: Vec3) -> str:
    """The unit direction of ``direction`` as its three components at three significant figures, such as ``(0.6, 0.8, 0)``."""
    unit: Vec3 = direction.normalized()
    components: list[str] = ["0" if abs(component) <= ZERO_COMPONENT else _significant(component) for component in unit.to_tuple()]

    return f"({', '.join(components)})"

vector_readout

vector_readout(value: VectorQuantity) -> str

The magnitude of value and the direction it points along, such as 100 N Along (1, 0, 0).

Source code in src/femforge/physical/readout.py
def vector_readout(value: VectorQuantity) -> str:
    """The magnitude of ``value`` and the direction it points along, such as ``100 N Along (1, 0, 0)``."""
    vector: Vec3 = value.magnitude
    size: Quantity = quantity(vector.magnitude(), str(value.units))

    if vector.magnitude() == 0.0:
        return readout(size)

    return f"{readout(size)} Along {along(vector)}"

components_readout

components_readout(components: Sequence[float | str], unit: str) -> str

Signed components in the SI unit as one tuple in the rung their largest reads in, such as (500, -0.2) kPa; a text component reads as itself.

Parameters:

  • components (Sequence[float | str]) –

    The components, in solve order.

  • unit (str) –

    The pint unit the components are in, such as Pa.

Source code in src/femforge/physical/readout.py
def components_readout(components: Sequence[float | str], unit: str) -> str:
    """Signed ``components`` in the SI ``unit`` as one tuple in the rung their largest reads in, such as ``(500, -0.2) kPa``; a text component reads as itself.

    Args:
        components: The components, in solve order.
        unit: The pint unit the components are in, such as ``Pa``.
    """

    def text_of(component: float | str) -> str:
        if isinstance(component, str):
            return component

        if abs(component) <= ZERO_COMPONENT * largest:
            return "0"

        return _significant(quantity(component, unit).m_as(shown))

    largest: float = max((abs(component) for component in components if not isinstance(component, str)), default=0.0)
    size: Quantity = quantity(largest, unit)
    rung: Rung | None = _rung(size)
    shown: str = rung.unit if rung is not None else str(size.to_compact().units)
    label: str = rung.label if rung is not None else f"{U.Unit(shown):~P}"
    texts: list[str] = [text_of(component) for component in components]

    return f"({', '.join(texts)}) {label}"