Skip to content

fluxopt.schema

JSON Schema and dict/JSON round-trip for the element layer.

The user-facing elements are pydantic.dataclasses, so pydantic can emit a JSON Schema for each type and round-trip instances to plain dicts. This is the machine-readable contract behind a future config front-end, GUI, or LLM-assisted authoring surface.

Structural round-trip (:func:to_dict / :func:from_dict) preserves ids, scalars, nested elements, and :class:~fluxopt.types.ProfileRef references. Inline array-valued Variate fields (raw time-series) do not serialize — use a ProfileRef instead, so profiles live in data files rather than in the config (see docs/design/config-and-pydantic-direction.md). Such fields also appear as permissive {} in the JSON Schema.

Functions:

Name Description
element_schema

Return the JSON Schema for one element type.

all_element_schemas

Return JSON Schemas for every element type, keyed by class name.

to_dict

Serialize an element to a JSON-safe dict.

from_dict

Reconstruct an element from a dict produced by :func:to_dict.

Attributes:

Name Type Description
ELEMENT_TYPES tuple[type, ...]

Every user-facing element type, in declaration order.

ELEMENT_TYPES module-attribute

ELEMENT_TYPES: tuple[type, ...] = (
    Carrier,
    Effect,
    Flow,
    Sizing,
    Investment,
    Status,
    Storage,
    Port,
    Converter,
)

Every user-facing element type, in declaration order.

element_schema

element_schema(element_type: type) -> dict[str, Any]

Return the JSON Schema for one element type.

Parameters:

Name Type Description Default

element_type

type

An element dataclass (e.g. Flow, Effect).

required
Source code in src/fluxopt/schema.py
def element_schema(element_type: type) -> dict[str, Any]:
    """Return the JSON Schema for one element type.

    Args:
        element_type: An element dataclass (e.g. ``Flow``, ``Effect``).
    """
    return TypeAdapter(element_type).json_schema()

all_element_schemas

all_element_schemas() -> Mapping[str, dict[str, Any]]

Return JSON Schemas for every element type, keyed by class name.

Source code in src/fluxopt/schema.py
def all_element_schemas() -> Mapping[str, dict[str, Any]]:
    """Return JSON Schemas for every element type, keyed by class name."""
    return {t.__name__: element_schema(t) for t in ELEMENT_TYPES}

to_dict

to_dict(element: object) -> dict[str, Any]

Serialize an element to a JSON-safe dict.

Nested elements and ProfileRef references are included; inline array-valued Variate fields are not serializable — reference them with a ProfileRef instead.

Parameters:

Name Type Description Default

element

object

Any element instance (e.g. Flow, Converter).

required

Raises:

Type Description
ValueError

If the element holds inline array values, listing each offending field.

Source code in src/fluxopt/schema.py
def to_dict(element: object) -> dict[str, Any]:
    """Serialize an element to a JSON-safe dict.

    Nested elements and ``ProfileRef`` references are
    included; inline array-valued ``Variate`` fields are not serializable —
    reference them with a ``ProfileRef`` instead.

    Args:
        element: Any element instance (e.g. ``Flow``, ``Converter``).

    Raises:
        ValueError: If the element holds inline array values, listing each
            offending field.
    """
    try:
        return TypeAdapter(type(element)).dump_python(element, mode='json')
    except Exception as exc:
        arrays: list[str] = []
        _inline_array_paths(element, type(element).__name__, arrays)
        if arrays:
            msg = (
                'cannot serialize inline array values at: '
                + '; '.join(arrays)
                + ' — reference them with ProfileRef(dataset=..., variable=...) and supply the data via profiles={...} at solve time'
            )
            raise ValueError(msg) from exc
        raise

from_dict

from_dict(element_type: type[T], data: Mapping[str, Any]) -> T

Reconstruct an element from a dict produced by :func:to_dict.

Parameters:

Name Type Description Default

element_type

type[T]

The element class to build (e.g. Flow).

required

data

Mapping[str, Any]

A mapping of field values.

required
Source code in src/fluxopt/schema.py
def from_dict[T](element_type: type[T], data: Mapping[str, Any]) -> T:
    """Reconstruct an element from a dict produced by :func:`to_dict`.

    Args:
        element_type: The element class to build (e.g. ``Flow``).
        data: A mapping of field values.
    """
    return TypeAdapter(element_type).validate_python(data)