Package: calibration#
Fitting model parameters to observations. A [calibration] table names the parameters to vary, the outputs to compare, the criterion that scores them and the search method. The package turns that table into a search. An optimizer proposes parameter values, one trial runs the model with them, the outputs are scored against the observations, and the session is written to disk as it goes.
The package is a layer because it sits above the solvers and below the entry points. It runs a solver only through the generic ports of solver.base, so a backend can be added or replaced without touching calibration. It never imports display.
A calibration occupies two sibling directories of one name, sessions/<case>/ for what the search evaluated and runs/<case>/ for the calibrated run. Inside the loop a trial lives in memory, and only a promoted trial becomes a run on disk.
calibration reads core, schema, catchment, mesh, model, data, results, solver and itself, as tests/unit/architecture/layer_matrix.yaml says. config, workflow, project, cli and the root facade read it. workflow is reached only through the TrialPipeline that project installs.
The two ports of the package are optim/ (search methods) and evaluation/ (what one trial answers), and each has its own README. The order of the parts and the modules other layers may import are in tests/unit/architecture/calibration_layout.yaml.
The page docs/source/contribute/architecture/packages/calibration.rst lists the modules and holds the ten steps of a calibration and where to add what. The phases are in docs/source/how-to/write-calibration-phases.rst.
Modules#
top level
Module |
What it does |
Lines |
|---|---|---|
config.py |
Pydantic model for the |
1 369 |
config_network.py |
The matching-network options and the network outputs of a calibration. |
936 |
config_objective.py |
The protocol, parameter and objective blocks of a calibration. |
263 |
config_outputs.py |
The calibration outputs: point, boundary, cell and lake records and the output union. |
387 |
config_phases.py |
The phases of a calibration, their regime, their uncertainty and the aggregate block. |
705 |
config_terms.py |
The words a calibration TOML uses: value aliases, windows, renamed keys. |
225 |
parameter_resolution.py |
What a calibration parameter means, resolved from the name it was given. |
540 |
persistence.py |
The journal of one calibration session, written as the search goes. |
814 |
preflight.py |
Everything a calibration needs, checked before the first solve. |
1 078 |
preflight_network.py |
The preflight checks of the matching-network criterion. |
435 |
preflight_report.py |
The finding constructor and the report lines of the calibration preflight. |
244 |
preflight_searches.py |
What a calibration document says about its searches: the roots, the phases that search and the outputs they score. |
171 |
report.py |
What a calibration returns, and the words about it. |
525 |
targets.py |
What this project exposes to a calibration. |
512 |
criteria/
Module |
What it does |
Lines |
|---|---|---|
base.py |
What a criterion is, and what it has to say about itself. |
140 |
formulas.py |
What each metric of the registry computes, written once as a formula. |
124 |
hydrographic_network_distance.py |
The hydrographic-network distance, as one criterion object. |
164 |
registry.py |
Where a criterion is resolved by the name a TOML writes. |
49 |
series.py |
Every metric of the registry, as a criterion. |
157 |
evaluation/: An evaluator turns one parameter sample into one cost. The port stops at the cost because the scoring path reads the live workflow context of a trial, which only the pipeline produces, and a port around simulated outputs would take the shape of the one implementation that can produce them. port.py holds the Protocol and its value types, and registry.py holds evaluators.
Module |
What it does |
Lines |
|---|---|---|
analytic_bowl.py |
An evaluator with no model behind it, for rehearsing a calibration montage. |
181 |
port.py |
What a calibration trial evaluator is: parameters in, a cost out. |
152 |
registry.py |
|
120 |
metrics/
Module |
What it does |
Lines |
|---|---|---|
composite.py |
What a trial context can answer with, for both scoring routes. |
558 |
gauge_snap.py |
Move a gauge onto the most accumulated cell within a radius, on request. |
110 |
observable_scoring.py |
Score model observables without a live workflow context. |
782 |
observed_pairing.py |
Pair a weighted block’s outputs with the records the project loaded. |
244 |
series.py |
Series helpers: observation loading, time-index resolution, runoff postprocess. |
242 |
solver_extract.py |
Solver-bridge extractors used by metric extractors. |
1 373 |
trial_series_capture.py |
Thread-local capture of the simulated/observed series one trial scored. |
66 |
observations/
Module |
What it does |
Lines |
|---|---|---|
network_geometry.py |
The bridge between one run and the static geometry of its stream criterion. |
410 |
network_source.py |
Where the mapped stream network of a network criterion comes from. |
314 |
observed_network.py |
The mapped stream network, projected onto the solver mesh. |
505 |
optim/adapters/
Module |
What it does |
Lines |
|---|---|---|
bisection_adapter.py |
One-dimensional root search on the sign of a residual, as one flat module. |
795 |
cma_adapter.py |
CMA-ES optimizer adapter backed by the |
293 |
da_mh_gp_adapter.py |
Delayed-Acceptance Metropolis-Hastings with Gaussian-process surrogate. |
494 |
gp_mapping_adapter.py |
Gaussian-process surrogate adapter with Expected Improvement acquisition. |
424 |
grid_adapter.py |
Grid-search adapter - deterministic, no external dependency. |
108 |
lhs_adapter.py |
Stratified Latin hypercube adapter, built on |
135 |
lhs_zoom_adapter.py |
Latin hypercubes in turn, each one drawn in the zone the trials so far leave open. |
211 |
optuna_adapter.py |
Optuna adapter - TPE / CMA-ES / Random / NSGA-II. |
120 |
random_search_adapter.py |
Random-search adapter using |
58 |
scipy_adapter.py |
SciPy optimizer adapter. |
450 |
optim/: An optimizer proposes parameter points and ingests the costs of their trials, so the search loop of engine.py drives every method the same way. The registry is optimizers in optimizer.py. The rest of this folder is what the loop shares around the port: the objective, the parameters, the sampling, the stopping rules, the cost cache and the diagnostics.
Module |
What it does |
Lines |
|---|---|---|
cache.py |
Content-addressable calibration cache. |
158 |
cost_margin.py |
How well the trials determined each calibrated value. |
452 |
design.py |
Space-filling designs: points of the unit cube for a calibration or an experiment plan. |
231 |
diagnostics.py |
Lightweight diagnostics helpers for calibration iteration traces. |
218 |
engine.py |
CalibrationEngine - orchestrates an ask/tell loop. |
474 |
fosm.py |
A linearized covariance around the answer a search returned. |
191 |
method_config.py |
Option models for calibration methods. |
553 |
nelder_mead.py |
Nelder-Mead simplex that can evaluate several candidates of one step at once. |
457 |
objective.py |
Objective Protocol - computes a cost from observed vs simulated data. |
730 |
optimizer.py |
Optimizer registry, on the shared plugin engine. |
392 |
parameters.py |
Calibrable parameters: annotations, space, search spaces, discovery. |
498 |
progress_reporter.py |
Console progress reporting for the calibration ask/tell loop. |
97 |
sampling.py |
Sampling helpers: where a search starts and how it draws, in each parameter’s search space. |
60 |
stopping.py |
One statement of precision, whatever engine walks the search. |
328 |
protocols/
Module |
What it does |
Lines |
|---|---|---|
base.py |
What a named calibration protocol is. |
269 |
boilerplate.py |
A Methods paragraph the run writes about itself. |
206 |
matching_hydrographic_network.py |
The two-stage calibration against the mapped hydrographic network. |
1 056 |
registry.py |
Where a named calibration protocol is resolved. |
510 |
runners/
Module |
What it does |
Lines |
|---|---|---|
cli_runner.py |
CLI entry point |
120 |
document.py |
Reading a calibration document: the TOML, its defaults, the names it resolves. |
385 |
failure_watch.py |
Stop a search whose trials all fail instead of letting it finish empty. |
97 |
kept_solves.py |
Trial solves kept on disk until their promotion. |
310 |
lanes.py |
Lanes of a calibration: the last solved trial of each lane is the parent of the next. |
217 |
materialize.py |
Materialize a self-contained TOML overlay for one calibration candidate. |
318 |
phase_regime.py |
What a phase’s flow regime writes into the model its trials run. |
203 |
pipeline_evaluator.py |
The evaluator that runs HydroModPy itself, and the default of every document. |
115 |
prepared_model.py |
The checks that need the prepared model, run once right after the preparation. |
379 |
programmatic_runner.py |
Programmatic entry point |
232 |
promotion.py |
Promotion of calibration trials to runs, and what a session leaves on disk. |
925 |
recap.py |
What the end of a calibration tells its reader, read off the run itself. |
396 |
restarts.py |
Repeating a whole search to say how far apart its answers land. |
223 |
resume.py |
Find a phase that already ran in the session of a case, instead of running it again. |
136 |
sandbox.py |
Per-trial solver sandbox for parallel calibration. |
219 |
search.py |
One search of a calibration: the ask/tell loop and what it reports about its result. |
1 107 |
search_record.py |
What a search writes into the trial journal: the trace, the extras and the interval lines. |
518 |
session.py |
Where a calibration session lives, and how its case is named. |
303 |
session_scope.py |
The session of a calibration: opening it, scoping its close, promoting its trials. |
649 |
soil_phase.py |
A calibration phase with |
145 |
staged_report.py |
The tables and the method sentences a staged calibration writes. |
514 |
staged_runner.py |
Calibration run in phases: each stage calibrates, then passes its values on. |
1 338 |
state.py |
Shared state primitives reused by the calibration runners. |
386 |
trial.py |
Trial primitive - “prepare once, evaluate many”. |
1 199 |
verdict.py |
What qualifies a trial, beside its cost. |
78 |
worker_pool.py |
The trials of a search in worker processes that last. |
326 |
Inside the package#
A modeller who writes phases in a TOML file reads Write calibration phases.
Import rules#
A part imports only what its row of tests/unit/architecture/calibration_layout.yaml allows.
tests/unit/architecture/test_package_layouts.py checks every import, at module level, inside
a function and under TYPE_CHECKING. The same file lists the modules that other layers may
read, and it forbids any import of a solver backend (solver_access).
How a calibration flows#
Load.
HydroModPyConfigvalidates[calibration]. A named protocol is expanded (expand_calibration_protocol) and each parameter name becomes a config path (resolve_parameter_targets). An unknown criterion or evaluator is refused here. An unknown search method loads and is refused by the preflight, before anything is prepared.Check. Every launch runs
preflight_launchon the document it will run, with--set,--overlayand each phase’s overrides written in. It solves nothing, and an error stops the launch.hmp checkprints the same findings.Start. A runner of
runners/names the case, which is the stem of the file that carries[calibration]unless[simulation] nameis set. It reservessessions/<case>/, freezes the resolved document there asconfig.toml, then builds the parameter space, the optimizer, the evaluator and theCalibrationEngine.Prepare once. Geography, mesh and data are built a single time, through the
TrialPipelinethatprojectinstalls.earliest_affected_stepfinds the first workflow step that reads a calibrated config path. The steps before it run once and every trial shares them. The steps from it to the solve and the extraction run again for each trial (run_trial_light). The persistent steps run only for a promoted trial (promote_prepared_trial). Shared products come from the product store, so a trial that leaves the soil alone never rebuilds the soil reservoir.Trial. The engine asks the optimizer for a point and skips it when its params hash is cached. The default evaluator (
runners/pipeline_evaluator.py) sets the values, solves, extracts the outputs and pairs them with the observations. When every calibrated path is a property profile (K or Sy), the next trials of a lane only rewrite the property file and solve again (runners/lanes.py). The cost is the same to the bit as a full build.Score.
optim/objective.pyturns the paired series into one cost, block by block, with the kernels ofcriteria/.Write. Each trial goes to
sessions/<case>/trials.jsonlas events (proposed,finished,linked). Only the session, in the parent process, writes the journal.Promote. Once per phase,
runners/promotion.pypromotes whatsave_runsnames. The best trial of the last phase becomesruns/<case>/, paired with the session by version. A trial that may be promoted keeps its solver folder, so its promotion extracts again and does not solve again. A promotion failure closes the sessionpartial, neverfailed.Close.
session.jsontakes the status (completed,partial,failed,aborted). SIGTERM or SIGINT writesabortedin under a second and promotes the best trial so far.hmp calibrate --resumereads back a phase that completed with the same fingerprint and solves the cut phase again, with its trials preloading the cache.Report.
report_sessionwrites the session report, andhmp show SESSION --reportwrites it again.
What a calibration writes#
A calibration writes two sibling directories of one name, sessions/<case>/ for what the
search evaluated and runs/<case>/ for the calibrated run. Inside the loop a trial lives in
memory, and Zarr and Parquet exist only for promoted trials. The index is rebuilt from the
session files and the calibration never opens it. The layout is in Storage layout
and the arrays and series are listed in Outputs of a run.
The params hash (optim/cache.py) keys the cache. It covers the model, its inputs, the
outputs, the objective blocks, the scoring window and what the evaluator reads. The method,
its options, the seed, the budget and the bounds are outside it, so a search that changes one
of them replays points already solved. calibration.use_cache preloads the hashes of
every trials.jsonl of the project.
Where to add what#
A search method is a module in
optim/adapters/on the template of Add a calibration method, plus its options model inoptim/method_config.py. Its test istests/unit/calibration/test_optim_adapters_<method>_adapter.py.A criterion a TOML can name is one row in
hydromodpy/core/scoring/metric_table.py, and its kernel(sim, obs) -> floatgoes incriteria/series.pyunder its name inMETRICS.tests/unit/core/scoring/test_metric_table.pykeeps the two equal.An evaluator satisfies the port of
evaluation/port.py. Its dotted path is added to_BUILTIN_PATHSofevaluation/registry.py, or it is published in thehydromodpy.calibration.evaluatorentry-point group.A calibration protocol is a module in
protocols/that satisfiesCalibrationProtocol(protocols/base.py), an instance in_PROTOCOLSofprotocols/registry.py, and its options model inconfig_network.py.A phase option is a field on
CalibPhaseDeclinconfig_phases.pyand its effect in_phase_configofrunners/staged_runner.py. A protocol that needs it writes it into the phases it expands.A
[calibration]field goes on the model of its table, with a profile and a description. The parameter reference is computed from the model at the next documentation build.
Reading path#
Start with this page, then calibration_layout.yaml, then runners/search.py and
optim/engine.py. runners/trial.py holds the prepare-once and evaluate-many primitive.