Add a solver#

A solver is one class bound to the key <process_type>_<name>, for example flow_modflow6 or transport_mt3dms. The shipped backends are listed in Solvers. This page adds another flow backend, or a transport solver. Both solver ports are experimental (Contracts and design patterns).

Files to create#

For a new flow backend called mysolver:

hydromodpy/solver/mysolver/
|-- __init__.py
|-- adapter.py          MysolverFlowAdapter, the class of the contract below
|-- options.py          the Pydantic class of [solver.mysolver], if it has settings
|-- extractors/flow.py  MysolverOutputAdapter, the extractor
`-- README.md           the contract of the backend

hydromodpy/solver/linear_reservoir/ is the smallest real backend, so read it first. A MODFLOW-family backend reuses hydromodpy/solver/modflow_common/flow_run.py for the build and solve flow. A transport adapter is filed beside its engine, as Modflow6GwtTransportAdapter is in solver/modflow6/transport.py. python -m tools.docs.check_readmes counts a backend folder as a port and checks its README, which follows Plug into a port.

Contract#

An adapter implements the SolverAdapter Protocol. The attributes have no default. The registry refuses a class that leaves one out, or that gives a value outside its vocabulary, and it names the fault.

@runtime_checkable
class SolverAdapter(Protocol):
    """One adapter serves one ``(process_type, name)`` key.

    An adapter receives the frozen ``Model`` of the run
    (:class:`hydromodpy.model.model.Model`, the model of its flow for a
    transport), its validated options (an instance of ``options``, or ``None``)
    and the :class:`~hydromodpy.solver.base.plan.RunSlot` the runner filled. It
    returns a :class:`~hydromodpy.solver.base.plan.SolverRun`. It never changes
    the ``Model``: a solve leaves it as it found it, and an auxiliary solve runs
    on a variant that is a new object. An adapter reads nothing of the setup,
    the configuration or the store. ``build`` also receives the ``SolverRun``
    objects the runs it depends on produced, ``upstream``: empty for a flow,
    one run of the family its ``requires`` names for a transport, which reads
    the ``Model`` and the folder of that flow and takes ``face_flow`` from it.

    The runner calls ``validate``, then ``build``, then ``run`` unless
    ``slot.stop_before_solve``. The extract step calls ``extract``, and the
    export step calls ``cleanup`` when the run keeps no solver files.
    """

    name: ClassVar[str]
    """The solver name a TOML writes in ``solver.backend``, for example ``modflow6``."""

    process_type: ClassVar[str]
    """What the backend computes, ``flow`` or ``transport``. With ``name`` it makes the key."""

    accepted_meshes: ClassVar[frozenset[str]]
    """The mesh engine ids whose cells the backend reads.

    ``ANY_PLANAR_ENGINE`` of ``mesh/port.py`` stands for every engine whose cells
    are planar and that is not lumped; ``engine_accepted`` of ``mesh/registry.py``
    is the rule. A transport declares none: it reads the mesh of the flow it follows.
    """

    geometry: ClassVar[str]
    """The member of ``Model.geometry`` the backend builds its grid on, one of ``GEOMETRIES``.

    A transport declares the value of the flow it follows.
    """

    writes: ClassVar[tuple[str, ...]]
    """The fields, tables and series the extractor writes, by their stored names.

    A field is its Zarr path (``head``, ``budget/drain``), a table its view name
    (``budgets``). A ``*`` stands only for a part the user names, such as a
    species, a lake or a station. The geometry the extractor adds to the mesh
    group (``z_interfaces``, the descent arrays) belongs to the mesh layout and
    is not listed.
    """

    reads: ClassVar[tuple[str, ...]]
    """The products of an earlier run the backend reads: ``face_flow`` for a transport, none for a flow.

    Every name is one :data:`hydromodpy.results.field_registry.FIELD_REGISTRY`
    describes, and ``face_flow`` comes with ``connection_cells`` beside it in
    the store. A transport reads the flow of the run that precedes it.
    """

    supports: ClassVar[frozenset[str]]
    """The traits of the ``Model`` the backend honours, from the closed set of ``model/supports.py``.

    A boundary kind, an option of ``ModelOptions`` or an initial state. A trait
    left out is refused before the run rather than ignored by the solve.
    """

    options: ClassVar[type[BaseModel] | None]
    """The Pydantic class of the backend's own table, or ``None`` when it reads none."""

    category: ClassVar[str]
    """How the backend resolves space, one of ``CATEGORIES``. The seal writes it to the manifest."""

    native_step: ClassVar[str | None]
    """The step the solver advances at, as a pandas frequency alias.

    ``None`` means it advances at the step of ``Model.time``.
    """

    cell_column: ClassVar[Callable[..., CellColumn] | None]
    """The rule that gives the top and the bottom of each cell, or ``None`` when the backend reads none.

    A function of ``model/domain/cell_column.py``, called as ``cell_column(cell_mesh=...,
    domain=..., top_sampling=..., channel_mask=...)`` by ``prepare_solver``. It puts the
    result on ``Model.geometry.column``, which the backend reads instead of sampling the
    DEM itself. Write it with ``staticmethod``, so an instance does not bind it.
    """

    mutable: ClassVar[frozenset[str]]
    """The calibration parameters the backend can change between two solves of one model."""

    requires: ClassVar[tuple[tuple[str, str], ...]]
    """The ``(process_type, name)`` keys an earlier run of the plan must have run."""

    def validate(self, model: Any, options: BaseModel | None, slot: RunSlot) -> None:
        """Refuse a run this backend cannot solve, before anything is built."""

    def build(
        self,
        model: Any,
        options: BaseModel | None,
        slot: RunSlot,
        upstream: tuple[SolverRun, ...] = (),
    ) -> SolverRun:
        """Build the solver model of ``model`` in memory, under ``slot``.

        A flow follows no run, so ``upstream`` stays empty. A transport receives
        exactly one run, of the family its ``requires`` names, and works in the
        folder of that flow. Nothing is written and nothing is solved: the
        result has ``written`` and ``solved`` false and carries the solver model.
        """

    def run(self, solver_run: SolverRun) -> SolverRun:
        """Write the input files unless ``solver_run.written``, solve, and return the solved run.

        The result lists the input files written in ``input_files``, has
        ``written`` and ``solved`` true, and names the folder the solver wrote in
        as ``output_dir``. A solve that fails raises a
        :class:`~hydromodpy.core.exceptions.SolverError` naming the run by
        ``solver_run.slot.name``; the runner sets its ``run_id``.
        """

    def cleanup(self, solver_run: SolverRun) -> None:
        """Remove the scratch files of a run once its results are stored."""

    def extract(self, solver_run: SolverRun, store: Any, retention: Retention) -> None:
        """Write the fields, tables and series of a solved run into its ``RunStore``.

        ``retention`` says which per-cell budget terms the run keeps. Every
        name written is one ``writes`` declares.
        """

The runner calls validate, then build, then run. build makes the solver model in memory and writes nothing. run writes the input files unless solver_run.written is set, solves, and returns the run with solved true. The extract step calls extract, and the export step calls cleanup when the run keeps no solver files. An adapter reads nothing of the setup, the configuration or the store, and a static gate in tests/unit/architecture/ checks it.

build receives the frozen Model, the options and a RunSlot, and it returns a SolverRun. Both are declared in hydromodpy/solver/base/plan.py.

@dataclass(frozen=True, kw_only=True)
class SolverRun:
    """What ``build``, ``run`` and ``rerun`` of a solver adapter return, one value for all three.

    ``model`` is the frozen ``hydromodpy.model.model.Model`` the run is built
    from, the model of its flow for a transport. ``options`` is the validated
    table of the backend, ``cfg.solver.options_of(name)``, or ``None`` for a
    backend that reads none. ``slot`` is where it solves.

    ``solver_model`` is the object the adapter built, read by a transport that
    follows the flow and by the observables of a calibration trial. It is
    ``None`` for a mesh run, which produces no model, after a resume past the
    solver, and once the derive step releases it.

    ``output_dir`` is the folder the solver wrote its raw files in (``.hds``,
    ``.cbc``), set by ``run``. ``input_files`` lists the input files ``run``
    wrote, relative to the run folder, which ``rerun`` copies. ``written`` says
    the input files are on disk, so ``run`` does not write them again.
    ``solved`` says the solve ran.

    ``metrics`` carries execution metadata the run produced about itself. The
    catalog only persists what converts to a finite float and skips the rest,
    which is why a mesh run can put its nested build summary here.

    ``solve_s`` is the wall time of the solve alone, in seconds, measured by
    the backend around the call that solves, or ``None`` when the run did not
    solve. It is not in ``metrics``, because the time of a solve is not a
    result of the run: the ``run_solver`` step writes it to ``profile.json``.

    ``initial_state_converged`` says whether the permanent solve that gave a flow
    run its starting state converged. ``None`` is a run that did not start from
    such a solve, which is every run but a flow run with a steady start. It is not
    in ``metrics`` because the catalog stores what is there and a new row would
    change the table of every run. The runner reads it before it starts a
    transport run that follows the flow, and refuses when it is ``False``.

    ``reran`` says the run came from ``rerun`` of a previous run and not from
    ``build``. The runner sets it, and the ``run_solver`` step writes the solve
    line of the profile with ``reused = "rerun"`` when it is true.
    """

    slot: RunSlot
    model: Any = None
    options: BaseModel | None = None
    solver_model: SolverModel | None = None
    output_dir: Path | None = None
    input_files: tuple[str, ...] = ()
    written: bool = False
    solved: bool = False
    metrics: Mapping[str, Any] = field(default_factory=dict)
    solve_s: float | None = None
    initial_state_converged: bool | None = None
    reran: bool = False

    def __post_init__(self) -> None:
        if not isinstance(self.slot, RunSlot):
            raise TypeError(f"SolverRun.slot is a RunSlot, got {type(self.slot).__name__}.")
        object.__setattr__(self, "output_dir", _optional_path(self.output_dir))
        object.__setattr__(self, "input_files", tuple(str(name) for name in self.input_files))
        if self.solve_s is not None:
            solve_s = float(self.solve_s)
            if not solve_s >= 0.0:
                raise SolverInputError(
                    f"SolverRun.solve_s is a duration in seconds, at least 0; got {self.solve_s!r}."
                )
            object.__setattr__(self, "solve_s", solve_s)

A flow backend receives no upstream run. A transport receives exactly one, the flow named by its requires, and reads face_flow from it. A flow adapter writes face_flow and connection_cells only when retention.face_flows is true.

Three members are optional, because the registry requires every member of the Protocol body. RERUN_MEMBERS and OPTIONAL_MEMBERS in adapter_protocol.py list them, and the port test reads both lists.

  • rerun(previous, model, slot) exists if and only if mutable is not empty. It solves a model that differs from previous.model only by properties named in mutable. It returns None when the change needs a build.

  • observables and declared_observables serve a calibration trial from the run folder, and come together or not at all. A backend refuses what it cannot produce with ObservableNotAvailableError.

The extractor is a second class under the same key, typed by OutputAdapter of the same module. It declares process_type and solver_name (the name of the adapter) as ClassVar[str], and its extract(solver_run, store, retention) writes the fields and tables of writes.

Minimal skeleton#

# hydromodpy/solver/mysolver/adapter.py
from dataclasses import replace
from typing import ClassVar

from pydantic import BaseModel

from hydromodpy.solver.base.plan import RunSlot, SolverRun
from .options import MysolverOptions


class MysolverFlowAdapter:
    name: ClassVar[str] = "mysolver"
    process_type: ClassVar[str] = "flow"
    accepted_meshes: ClassVar[frozenset[str]] = frozenset({"regular", "triangle"})
    geometry: ClassVar[str] = "cells"
    writes: ClassVar[tuple[str, ...]] = ("head", "budgets")
    reads: ClassVar[tuple[str, ...]] = ()
    supports: ClassVar[frozenset[str]] = frozenset({"recharge", "steady_start"})
    options: ClassVar[type[BaseModel] | None] = MysolverOptions
    category: ClassVar[str] = "distributed"
    native_step: ClassVar[str | None] = None
    cell_column: ClassVar = None
    mutable: ClassVar[frozenset[str]] = frozenset()
    requires: ClassVar[tuple[tuple[str, str], ...]] = ()

    def validate(self, model, options, slot: RunSlot) -> None: ...

    def build(self, model, options, slot: RunSlot, upstream=()) -> SolverRun:
        return SolverRun(slot=slot, model=model, options=options, solver_model=...)

    def run(self, solver_run: SolverRun) -> SolverRun:
        return replace(solver_run, output_dir=..., written=True, solved=True)

    def extract(self, solver_run: SolverRun, store, retention) -> None: ...

    def cleanup(self, solver_run: SolverRun) -> None: ...

Register#

Add one line to each of the two tables _BUILTIN_PATHS and _BUILTIN_EXTRACTOR_PATHS of hydromodpy/solver/base/registry.py, under the key flow_mysolver. A backend outside the tree publishes both entry-point groups hydromodpy.solver and hydromodpy.solver.extractor instead. Plug into a port explains how both ways resolve a key. What the TOML says ——————

A file chooses the backend with solver.backend = "mysolver". The value is checked against solvers.names("flow") while the file is read, so a plugin needs no patch to HydroModPy. The settings are the table [solver.mysolver]. SolverConfig validates it with the options class of the adapter, and a backend whose options is None refuses the table. The runner reads it with cfg.solver.options_of(name) and hands it to build.

A field of the options class takes a Profile and a description, as in solver/linear_reservoir/options.py. The description is the help that a check shows next to the error.

A file that uses a trait the backend leaves out of supports is refused with IncompatibleCapabilitiesError. The check never names a backend, so a new backend needs no line in config/. A transport is checked against its requires the same way. The mesh engines named in accepted_meshes are checked before any meshing.

Tests to add#

  • Unit tests under tests/unit/solver/<backend>/ for validate, build, run and cleanup, on a small Model and a RunSlot in a temporary folder. A backend that carries rerun adds a test that compares a rerun with a new build, file by file.

  • The contract test tests/ports/test_solver.py runs over solvers.names(), so the new backend meets it with no line added.

  • tests/scenarios/test_backends_write_what_they_declare.py plays a small project under each in-tree backend and checks that the store holds only names its writes declares.

  • A case under tests/validation/ with an analytical reference, and a @pytest.mark.solver_sanity mark when the backend wraps a binary.

See Add a test for the full ladder.

The imports the layer matrix allows are in Layer graph. Fix a failing architecture gate says what to do when the gate refuses one.

See also#