Skip to content

Typing

typing

Custom Typing Helpers.

This module centralizes type aliases used throughout the project and makes it easy to keep runtime imports lightweight while still providing precise type information. The goal is to express common shapes and dtypes once, so internal modules can share consistent, readable annotations without repeating NumPy typing boilerplate.

Examples:

>>> from flepimop2.typing import Float64NDArray
>>> Float64NDArray
numpy.ndarray[tuple[typing.Any, ...], numpy.dtype[numpy.float64]]

Float64NDArray = npt.NDArray[np.float64] module-attribute

Alias for a NumPy ndarray with float64 data type.

IdentifierString = Annotated[str, Field(min_length=1, max_length=255, pattern='^[a-z]([a-z0-9\\_]*[a-z0-9])?$'), AfterValidator(_identifier_string)] module-attribute

A string type representing a valid identifier for named configuration elements.

RaiseOnMissing = RaiseOnMissingType() module-attribute

Sentinel value indicating an error should be raised if a value is missing.

Array

Bases: Protocol

Minimal Array-API duck type.

Captures only the surface that flepimop2 itself touches at cross-plugin boundaries: a shape tuple, a dtype, and the __array_namespace__ marker that identifies a value as belonging to an Array-API-compliant <https://data-apis.org/array-api/latest/>_ backend (NumPy >= 2.0, JAX >= 0.4.32, PyTorch >= 2.1, CuPy, dask, ...).

Concrete consumers (e.g. an ODE engine) remain free to require a specific backend internally; using Array at module boundaries lets producers and consumers agree on shape without forcing dtype coercion or NumPy-only payloads.

Examples:

>>> import numpy as np
>>> from flepimop2.typing import Array
>>> isinstance(np.zeros((2, 3)), Array)
True

dtype property

The array's dtype (backend-defined).

shape property

The array's shape.

__array_namespace__(*, api_version=None)

Return the Array-API namespace for this array.

Source code in src/flepimop2/typing.py
def __array_namespace__(self, *, api_version: Any = None) -> object:  # noqa: PLW3201, ANN401
    """Return the Array-API namespace for this array."""

item()

Return a 0-d array as a Python scalar.

Source code in src/flepimop2/typing.py
def item(self) -> Any:  # noqa: ANN401
    """Return a 0-d array as a Python scalar."""

ExitCode

Bases: IntEnum

Standard process exit codes used by CLI commands.

Attributes:

Name Type Description
OKAY

Exit code 0, indicating successful execution.

GENERAL

Exit code 1, indicating a general error.

CONFIGURATION

Exit code 3, indicating a configuration related error.

PatchConflictMode

Bases: StrEnum

Strategies for handling overlapping configuration keys during patching.

Examples:

>>> from flepimop2.typing import PatchConflictMode
>>> PatchConflictMode.from_string("merge")
<PatchConflictMode.MERGE: 'merge'>
>>> PatchConflictMode.from_string("replace")
<PatchConflictMode.REPLACE: 'replace'>
>>> PatchConflictMode.from_string("override")
Traceback (most recent call last):
    ...
ValueError: Unknown patch conflict mode 'override'; expected one of: error, merge, replace.

from_string(value) classmethod

Parse a patch conflict mode from its string form.

Parameters:

Name Type Description Default
value str

The conflict mode string.

required

Returns:

Type Description
Self

The parsed PatchConflictMode.

Raises:

Type Description
ValueError

If value is not a valid patch conflict mode.

Source code in src/flepimop2/typing.py
@classmethod
def from_string(cls, value: str) -> Self:
    """
    Parse a patch conflict mode from its string form.

    Args:
        value: The conflict mode string.

    Returns:
        The parsed `PatchConflictMode`.

    Raises:
        ValueError: If `value` is not a valid patch conflict mode.
    """
    try:
        return cls(value)
    except ValueError as exc:
        modes = ", ".join(sorted(mode.value for mode in cls))
        msg = f"Unknown patch conflict mode {value!r}; expected one of: {modes}."
        raise ValueError(msg) from exc

RaiseOnMissingType

A sentinel type indicating an error should be raised if a value is missing.

__reduce__()

Helper for pickling the RaiseOnMissingType singleton.

Returns:

Type Description
Literal['RaiseOnMissing']

The string "RaiseOnMissing".

Source code in src/flepimop2/typing.py
def __reduce__(self) -> Literal["RaiseOnMissing"]:
    """
    Helper for pickling the `RaiseOnMissingType` singleton.

    Returns:
        The string "RaiseOnMissing".
    """
    return "RaiseOnMissing"

__repr__()

String representation of the RaiseOnMissingType.

Returns:

Type Description
Literal['RaiseOnMissing']

The string "RaiseOnMissing".

Source code in src/flepimop2/typing.py
def __repr__(self) -> Literal["RaiseOnMissing"]:
    """
    String representation of the `RaiseOnMissingType`.

    Returns:
        The string "RaiseOnMissing".
    """
    return "RaiseOnMissing"

StateChangeEnum

Bases: StrEnum

Enumeration of types of state changes in a system.

Examples:

>>> from flepimop2.typing import StateChangeEnum
>>> StateChangeEnum.DELTA
<StateChangeEnum.DELTA: 'delta'>
>>> StateChangeEnum.FLOW
<StateChangeEnum.FLOW: 'flow'>

DELTA = 'delta' class-attribute instance-attribute

The state change is described directly by the changes in the state variables, i.e. \( x(t + \Delta t) = x(t) + \Delta x \).

ERROR = 'error' class-attribute instance-attribute

The state change is mis-specified.

FLOW = 'flow' class-attribute instance-attribute

The state change is described directly by the flow rates, or derivatives, of the state variables. I.e. \( dx/dt = f(x, t) \).

STATE = 'state' class-attribute instance-attribute

The state change is described directly by the new state values, i.e. \( x(t + \Delta t) = x_{new} \).

SystemProtocol

Bases: Protocol

Type-definition (Protocol) for system stepper functions.

__call__(time, state, **kwargs)

Protocol for system stepper functions.

Source code in src/flepimop2/typing.py
def __call__(
    self, time: np.float64, state: Float64NDArray, **kwargs: Any
) -> Float64NDArray:
    """Protocol for system stepper functions."""
    ...

as_system_protocol(func)

Decorator to mark a function as a SystemProtocol.

Parameters:

Name Type Description Default
func _SystemCallable[_P]

A callable matching the SystemProtocol signature.

required

Returns:

Type Description
SystemProtocol

The function cast as SystemProtocol.

Source code in src/flepimop2/typing.py
def as_system_protocol(func: _SystemCallable[_P]) -> SystemProtocol:
    """
    Decorator to mark a function as a SystemProtocol.

    Args:
        func: A callable matching the SystemProtocol signature.

    Returns:
        The function cast as SystemProtocol.
    """
    return cast("SystemProtocol", func)