Add a calibration method#
Calibration runs an ask/tell loop. An optimizer proposes a parameter point, the engine
evaluates it, and the optimizer ingests the result. The methods that ship are listed in
Calibration methods and metrics. Each one is an adapter under
hydromodpy/calibration/optim/adapters/. Calibration internals describes
the loop around it.
Files to create#
One module for a method called mymethod:
hydromodpy/calibration/optim/adapters/<method>_adapter.py.
from typing import ClassVar
from pydantic import BaseModel
from hydromodpy.calibration.optim.optimizer import (
EngineTraits,
EvaluationResult,
ParamSuggestion,
)
from hydromodpy.calibration.optim.parameters import ParameterSpace
class MyMethodConfig(BaseModel):
tolerance: float = 1e-3
class MyMethodAdapter:
name: ClassVar[str] = "mymethod"
options: ClassVar[type[BaseModel] | None] = MyMethodConfig
traits = EngineTraits(takes_max_trials=True)
def __init__(self, space: ParameterSpace, *, max_trials: int = 100, tolerance=1e-3):
self._space, self._max_trials = space, max_trials
self._seen = 0
self._best: EvaluationResult | None = None
def ask(self, n: int = 1) -> list[ParamSuggestion]: ...
def tell(self, results: list[EvaluationResult]) -> None:
self._seen += len(results)
for result in results:
if self._best is None or result.cost < self._best.cost:
self._best = result
def best(self) -> EvaluationResult | None:
return self._best
def converged(self) -> bool:
return self._seen >= self._max_trials
An optional dependency is imported at module level. A missing package raises an
ImportError that names the extra to install, and the other methods stay available.
Contract#
An adapter implements the Optimizer Protocol. The registry reads the id from the
name attribute, and a class may carry more members than the Protocol lists.
@runtime_checkable
class Optimizer(Protocol):
"""Ask/tell Protocol implemented by optimizer adapters.
The port's members are ``ask``, ``tell``, ``best`` and ``converged``:
``ask`` proposes one or more parameter points, ``tell`` feeds completed
evaluations back, and ``best`` and ``converged`` expose the state needed
by ``CalibrationEngine``. A class may carry more, such as ``suggest_next``
on the adapters that plan their own points; the registry reads none of it
and ``name`` is read off a class as its id, not declared here.
"""
def ask(self, n: int = 1) -> list[ParamSuggestion]: ...
def tell(self, results: list[EvaluationResult]) -> None: ...
def best(self) -> EvaluationResult | None: ...
def converged(self) -> bool: ...
ask proposes points in the search space of each parameter (identity, log or
logit, set in [calibration.parameters.*]). The engine converts them back to
physical units. tell feeds back the matching batch of results. The session journal
writes each point that ask returns as a proposed line, in list order and before any
evaluation, so the order is part of the contract. An adapter that reorders its points
between two calls changes the trial numbers. The adapter keeps its state in its own
instance and never writes it to disk, because the engine owns persistence and resume.
converged says whether the engine met a rule of its own. stop_state in
optim/stopping.py turns it into the stop state of the session. An engine that declares
no stopping option and spends its whole budget is reported as having spent it, whatever
converged says.
A search of your own needs no registration. Hand an object that satisfies Optimizer to
CalibrationEngine(optimizer=...) in optim/engine.py.
Declaring the options#
options is the Pydantic class of the settings the adapter accepts, with one field per
constructor keyword and no method field. method_options_problem checks a phase,
[calibration] and the protocol’s steady_method_options and
transient_method_options against it when the file loads. A wrong key or type is refused
there, with the phase named, and hmp check runs the same check.
Declaring the traits#
An engine refuses an impossible pairing in its constructor. That is late, because a staged
calibration builds the optimizer of phase two after phase one has spent its budget. The
class attribute traits states the same facts where a check reads them before anything
solves. Each field says what it means in its own docstring.
@dataclass(frozen=True)
class EngineTraits:
"""What a search engine can and cannot be handed.
An engine refuses an impossible pairing in its constructor, which is right
but late: a staged calibration builds phase two's optimizer only when phase
two starts, after phase one has spent its whole solve budget. Declaring the
same facts here lets a check read them before anything solves.
The defaults are permissive on purpose: an engine that constrains nothing
declares nothing, and one that says nothing is taken at its word rather
than assumed to be limited.
"""
max_parameters: int | None = None
"""How many parameters the engine can move at once. ``None`` means any number."""
required_search_space: str | None = None
"""The search space the engine's stopping rule is written in."""
needs_signed_residual: bool = False
"""Whether the engine reads a signed residual the criterion has to publish."""
supports_parallel: bool = True
"""Whether several trials of one batch can be evaluated at once."""
reach: Callable[[Mapping[str, Any], int], int] | None = None
"""How many solves the engine can use at once, from its method options and the number
of parameters. ``None`` says no limit. An engine without ``supports_parallel`` reads as 1."""
precision_option: str | None = None
"""Name of this engine's own option that a user-level precision writes.
``None`` says the engine has no parameter-side stopping rule at all, and a
declared precision is then refused rather than quietly dropped: a search that
stops on its budget cannot honor a precision, and saying so is the only
honest answer."""
accepts_a_start_point: bool = False
"""Whether the engine can be told where to begin, in transformed space.
Only two do, and it is what a restart-based uncertainty needs: repeating a
search that always begins at the same point returns the same answer, so the
spread it would report would be zero by construction."""
draws_a_normal: bool = True
"""Whether the engine can draw a parameter declared with the ``normal`` sampling.
An engine that cannot refuses it in its constructor, and the preflight reads
this to refuse it before anything is prepared."""
restarts_explore_differently: bool = True
"""Whether repeating this engine can land anywhere else.
Permissive by default, like every trait here: a stochastic sampler explores
differently on a new seed and says nothing. An exhaustive sweep and a root
search declare ``False``, because repeating them is the same computation twice
and reporting its spread as an uncertainty would be a lie about a certainty."""
precision_reads: Literal["search_width", "relative_value"] | None = None
"""How that option reads its number. ``search_width`` is an absolute width in
the space the search walks, so the precision is converted into that space.
``relative_value`` is already a relative width on the parameter's own value,
so the number passes through."""
takes_max_trials: bool = False
"""Whether the engine is built knowing the evaluations it may spend.
The surrogate that sizes its initial design on the budget, and the strategy
that plans its restarts on it, need the number before the first ask. The
runner hands it the ``max_trials`` of the search (``"auto"`` resolved), so
the budget is written once, in ``max_trials``, and never as a method option."""
reads_cost_as: str | None = None
"""The metric the engine assumes its cost is, when it builds on the number.
``None`` for an engine that only compares costs. The sampler that turns the
cost into a likelihood declares the metric that likelihood is written for,
and a search scored on another one is warned before it runs."""
fixed_plan: bool = False
"""Whether the engine can be asked for all that is left and hands out what is ready.
One queue then takes the points, so no point waits for the result of another."""
takes_width: bool = False
"""Whether the engine is built knowing the ``parallel`` of the search, as ``width``."""
takes_interval_width: bool = False
"""Whether the engine is built knowing the margin of the phase, as ``interval_width``.
The margin is the :class:`~hydromodpy.calibration.optim.cost_margin.IntervalWidth` the
report reads its interval with, so an engine that narrows its search on it and the report
say the same thing at two moments."""
libraries: tuple[str, ...] = ()
"""The distributions the engine runs on, by distribution name.
A session writes their installed versions beside the method, so a search
says what it ran on. An engine that names none records none."""
announced: bool = True
"""Whether the method is in the list the docs and the refusals print.
``False`` for a method that still runs when a file names it, but that
the project does not offer yet. The default says nothing, like every trait
here."""
Two traits decide how the engine meets a precision. calibration.precision is a
relative precision on the parameter, and it is translated into the option that
precision_option names. With precision_reads="relative_value" the number passes
through, and it needs required_search_space="log". With "search_width" it is
converted into the variable the search walks, log10(1 + precision) decades in log space
and a fraction of the interval otherwise. An engine that stops on its budget declares
neither, and a precision handed to it is refused with a message that names what bounds it.
The budget is one number, calibration.max_trials. An engine that sizes its plan on
it declares takes_max_trials=True and receives it as the max_trials argument, with
"auto" resolved. No method option counts evaluations.
[calibration.uncertainty] method = "multistart" repeats the search. An engine whose
repeats cannot differ, such as grid and bisection, declares
restarts_explore_differently=False and a file that asks for restarts on it is refused
before the first solve. An engine that takes start_at declares
accepts_a_start_point=True, and it begins there instead of at its own default.
Register#
There is no dict of methods to edit beyond the path table. An in-tree class is one line in
_BUILTIN_PATHS of hydromodpy/calibration/optim/optimizer.py, under the id its
name declares. A method outside the tree publishes one entry point in the group
hydromodpy.calibration.optimizer. Plug into a port explains how both ways
resolve a name. The id is the name that CalibrationConfig.method accepts.
Test#
Unit tests under
tests/unit/calibration/for the constructor options,ask,tellandbest.tests/ports/test_optimizer.pyruns overoptimizers.names(), so the new method meets the port test with no line added.A recovery test on a synthetic case, with a method-specific tolerance, in the style of
METHOD_ABS_TOLintests/regression/fast/calibration/test_brutsaert_methods.py. The cases themselves are undervalidation_cases/calibration/.One short
hmp runcalibration on a tiny case undertests/integration/calibration/.
The imports the layer matrix allows are in Layer graph, and
optim may import criteria and nothing else inside the package.
A method that reads simulation results does it through the engine API, never through the
run store.
See also#
Package: calibration for the calibration package map.
Calibration internals for the loop, the storage rules and the Python API.
Add a figure if the method has diagnostics of its own.