Project#

MemberKindWhat it is
Read the project The cases, sites, runs and sessions of the project, read from its directory.
casespropertyThe cases of the project: the plan joined to the outcomes, one row each.
rootpropertyThe project directory, the folder of project.toml.
runspropertyThe runs of this project: call it for a RunSet, runs(site="J0014010").
sessionspropertyThe calibration sessions of the project, by directory name.
sitespropertyThe sites of the project, one row each, with the outlet as a point.
storepropertyThe index of this project, refreshed from the run directories, read only.
Launch the cases The words of hmp project and hmp campaign: plan the cases, launch them, collect the summary, publish it.
collectmethodWrite summary/: one table per case and per site, figures, report, README.
planmethodResolve the cases of a [sites] project and write plan/<hash>/.
publishmethodCopy summary/ out of the tree, for a reader without HydroModPy.
statusmethodReturn where each case of the plan stands, read from the disk.
Build one model Configure one model from a TOML file and build its catchment, data and mesh.
best_runsmethodReturn the best completed run of each site, one row each, as a table.
build_geographicmethodMark geographic/domain runtime ready and invalidate downstream state.
build_meshmethodBuild the catchment mesh from the current geographic context.
configpropertyA frozen copy of the configuration of this project, taken at each read.
datapropertyAccessor for the input-data cache scoped to this project.
data_loadedpropertySet of data types already loaded for this project.
domainpropertySpatial domain (mesh, layers, zones). Triggers build.
gcmethodCollect what the project no longer needs, the words of hmp catalog gc.
geographicpropertyGeographic runtime object (DEM, watershed, CRS). Triggers build.
has_meshpropertyTrue once the mesh has been built for the project.
launchmethodLaunch the cases of the plan, one process per case.
load_datamethodLoad the external forcings declared in [data].
loaded_datapropertyLoaded data context (recharge, geology, hydrometry, etc.). Triggers build.
preparemethodEagerly build the model phase (geographic, data, mesh). Returns self.
rebuild_geographicmethodRerun the geographic pipeline and invalidate the mesh.
reload_datamethodReload a subset of data variables without touching the others.
setup_workspacemethodBootstrap shared runtime state for the project session.
time_gridpropertyResolved simulation time grid.
Run one model Run, calibrate or spin up the model this project configures.
calibratemethodRun a calibration campaign on this project.
rerunmethodLaunch a new simulation from a persisted run snapshot.
simulatemethodRun one simulation through the configured workflow and return its result.
spinupmethodRun the cyclic spin-up loop on this project.
Lifecycle Release the index handle and the preprocessing files.
closemethodClose the Catalog and clean up preprocessing files.
class Project(
config,
*,
base=None,
document=None,
source=None,
solver=None,
headless=False,
no_display=False,
environment=None,
)[source]#

Setup-once, run-many interface for HydroModPy simulations.

Project(config) is cheap: it validates the configuration and builds an empty runtime context. The heavy model phase (geographic, data, mesh) is built lazily on the first simulate() (or eagerly via prepare() or the per-phase verbs build_geographic / load_data / build_mesh). Run many simulations with parameter overrides; inspect past runs through runs and inputs through data.

Parameters:
  • config (str, Path, HydroModPyConfig, dict, or JSON str) – A TOML path, a fully-built HydroModPyConfig, a dict payload, or a JSON string (auto-detected).

  • base (str or Path, optional) – The folder the relative paths of the configuration are read from. A TOML path reads them from its project root when base is not given. A dict or a JSON string has no folder of its own and is refused without it: the current folder is never used.

  • document (dict, optional) – The document a built configuration was loaded from, which the planner of the data reads. Without it, the document is what the configuration writes.

  • source (str or Path, optional) – The file a built configuration was read from, when it came from one.

  • solver (str, optional) – Flow solver of a configuration that declares no process. One that declares another solver is refused: the plan and the replay read the configuration.

  • headless (bool, optional) – Draw no figure (useful for calibration loops where generating figures per iteration is wasteful). A choice of this launch: it changes neither the identity of a run, nor its sealed configuration, nor what it keeps.

  • no_display (bool, optional) – The same, said by the option of hmp run.

Examples

>>> import hydromodpy as hmp
>>> project = hmp.Project("project.toml")
>>> run = project.simulate(set={"Sy": 0.05})
>>> project.close()

Read the project#

The cases, sites, runs and sessions of the project, read from its directory.

property Project.cases: pd.DataFrame[source]#

the plan joined to the outcomes, one row each.

Status (planned, invalid, skipped, stale_plan for a case of the plan that has no directory; running, completed, partial, failed, aborted, stale for one that has), label, headline metric with its window, and one column per global parameter.

Type:

The cases of the project

property Project.root: Path[source]#

The project directory, the folder of project.toml.

property Project.runs: ProjectRunsAccessor[source]#

call it for a RunSet, runs(site="J0014010").

Reads the index, refreshed from the run directories; builds nothing.

Type:

The runs of this project

property Project.sessions: ProjectSessions[source]#

The calibration sessions of the project, by directory name.

property Project.sites: gpd.GeoDataFrame[source]#

The sites of the project, one row each, with the outlet as a point.

property Project.store: Catalog[source]#

The index of this project, refreshed from the run directories, read only.

Launch the cases#

The words of hmp project and hmp campaign: plan the cases, launch them, collect the summary, publish it.

Project.collect(*, write_sites=False, mixed_windows=False)[source]#

Write summary/: one table per case and per site, figures, report, README.

The words of hmp campaign collect.

Project.plan(*, set=None, force=False)[source]#

Resolve the cases of a [sites] project and write plan/<hash>/.

The words of hmp project plan, with the changes of --set by dotted path. A plan is not rewritten while one of its cases runs, unless force.

Project.publish(to, *, format='dir', public=False)[source]#

Copy summary/ out of the tree, for a reader without HydroModPy.

The words of hmp publish summary --to DEST. A summary carries no results and no inputs, so there is nothing to leave out. Returns the copy. Raises FileNotFoundError before collect() wrote summary/. It is hydromodpy.publish("summary", ...) read in this project.

Project.status()[source]#

Return where each case of the plan stands, read from the disk.

It is hydromodpy.status(project, plan=True).

Build one model#

Configure one model from a TOML file and build its catchment, data and mesh.

Project.best_runs(
metric='nse',
*,
by='site',
label=('calibrated', 'evaluated'),
mixed_windows=False,
)[source]#

Return the best completed run of each site, one row each, as a table.

best names one Run everywhere else: proj.runs().best(metric) is the run itself.

The metric is read at the gauge of each run, in the window of its rule; best follows its direction. The calibrated runs are ranked by default, the evaluated ones included (scored out of their calibration window); label="calibrated" keeps the runs scored in it, label=None ranks every completed run. by=None gives the single best run of the project. A site of completed runs left out is named once in a warning, with why: no run scored (declare [metrics] window), or none of label.

Returns:

pandas.DataFrame – site and recipe, the group first, then case_id, rel_dir, sim_id, label, the global parameters (K …), the metric under its own name, station, window_start, window_end.

Return type:

pd.DataFrame

Examples

>>> proj = hmp.open("projects/bretagne_k")
>>> proj.best_runs("nse", by="site")
Project.build_geographic(*, reuse_dem=False)[source]#

Mark geographic/domain runtime ready and invalidate downstream state.

Project.build_mesh(**overrides)[source]#

Build the catchment mesh from the current geographic context.

property Project.config: HydroModPyConfig[source]#

A frozen copy of the configuration of this project, taken at each read.

Assigning to it raises FrozenConfigError. A run takes its changes by simulate(set=...). A configuration takes them by HydroModPyConfig.with_changes, and the result opens a new Project.

property Project.data: ProjectDataAccessor[source]#

Accessor for the input-data cache scoped to this project.

property Project.data_loaded: set[str][source]#

Set of data types already loaded for this project.

property Project.domain: Domain | None[source]#

Spatial domain (mesh, layers, zones). Triggers build.

Project.gc(
*,
dry_run=False,
keep_versions=5,
max_age_days=None,
trial_fields_days=90,
solver_files_days=None,
)[source]#

Collect what the project no longer needs, the words of hmp catalog gc.

Marks the attempts of dead runs aborted, trashes the versions beyond keep_versions and the runs older than max_age_days, removes the scratch of dead runs and the earlier attempts of sealed ones, evicts the product store down to its cap, and removes the fields of kept trials older than trial_fields_days, all but the best. With solver_files_days it also removes the solver/ folder of sealed runs older than that, a rule off by default. With dry_run it reports the plan and the bytes of each category, and changes nothing.

property Project.geographic: CatchmentDelineation | None[source]#

Geographic runtime object (DEM, watershed, CRS). Triggers build.

property Project.has_mesh: bool[source]#

True once the mesh has been built for the project.

Project.launch(
*,
parallel=None,
only=(),
site=None,
until=None,
fresh=False,
force=False,
resume=False,
prepare_parallel=None,
environment=None,
)[source]#

Launch the cases of the plan, one process per case.

The words of hmp run project.toml: only keeps the cases in those states ("failed", ("failed", "stale")), site the cases of one site, until="data" stops after the data phase. parallel is the budget of solves side by side; a calibration case counts its own [calibration] parallel. simulate() runs one simulation. environment rides on every launched case: it reaches the children of run_plan as options of their own command line, typed with the words of environment_from_args(). None reuses the environment the project was opened with. A launch that runs to the end and completes a case writes summary/, whose folder the report gives as summary.

Project.load_data(*, types=None)[source]#

Load the external forcings declared in [data].

property Project.loaded_data: LoadedDataContext[source]#

Loaded data context (recharge, geology, hydrometry, etc.). Triggers build.

Project.prepare()[source]#

Eagerly build the model phase (geographic, data, mesh). Returns self.

Project.rebuild_geographic(*, reuse_dem=False)[source]#

Rerun the geographic pipeline and invalidate the mesh.

Project.reload_data(*, types)[source]#

Reload a subset of data variables without touching the others.

Project.setup_workspace()[source]#

Bootstrap shared runtime state for the project session.

This Project-level verb prepares the workspace/catalog anchor and the shared geographic/domain/process objects used by later data, mesh, and solver phases. It is not a standalone Pipeline step; Pipeline runs get the same setup through BuildGeographicStep.

property Project.time_grid: ResolvedSimulationTimeGrid | ResolvedSteadySimulationTimeGrid | None[source]#

Resolved simulation time grid.

Run one model#

Run, calibrate or spin up the model this project configures.

Project.calibrate(
*,
config_path=None,
parameters=None,
outputs=None,
objective_blocks=None,
phases=None,
protocol=None,
method=None,
max_trials=None,
save_runs=None,
seed=None,
phase=None,
case=None,
resume=False,
force=False,
dry_run=False,
workspace=None,
project=None,
project_label=None,
metric_fn=None,
objective=None,
report=True,
)[source]#

Run a calibration campaign on this project.

Three modes are supported:

  • TOML mode (config_path supplied): delegate to run_calibration_cli with the given TOML path.

  • Python mode (parameters supplied): build a CalibrationConfig in memory from the declarations and run the same loop.

  • Embedded mode (neither supplied): use the [calibration] section carried by this project’s config, so a fully in-memory HydroModPyConfig calibrates without re-declaring parameters.

A configuration declaring [[calibration.phases]] routes to run_staged_calibration() in TOML mode, and in embedded mode when this project was built from a file. Python mode routes there too when phases is given, and so does an embedded declaration on a project built in memory: both write the calibration document the staged runner needs (next to this project’s sessions/) and run it from there, since there is no source file to fork each phase from otherwise. Python mode without phases declares its own single-stage parameter space, so the phases of the project config do not apply to it.

Parameters:
  • config_path (str | Path | None) – Calibration TOML path for TOML mode.

  • parameters (dict[str, dict] | None) – Python-mode parameter declarations.

  • outputs (dict[str, dict] | None) – Python-mode output declarations.

  • objective_blocks (list[dict] | None) – Python-mode objective block declarations.

  • phases (list[dict] | None) – Python-mode phase declarations, one dict per phase, same keys as [[calibration.phases]]. Runs staged, through the same document and runner as a TOML calibration that declares phases.

  • method (str | None) – Optimizer method name. Unset, the one the criteria call for: a root search for one log parameter scored on signed criteria only, a minimiser otherwise.

  • max_trials (int | None) – Maximum number of optimizer iterations.

  • save_runs (str | None) – Policy controlling which trial runs remain persisted.

  • seed (int | None) – Optional optimizer seed.

  • phase (str | None) – Run only the named phase of a staged calibration.

  • protocol (str | dict | None) – Name of a calibration protocol, or a table naming one. It is laid over this project’s own [calibration] section, which keeps the parameters and outputs the protocol reads, so it excludes config_path and parameters.

  • case (str | None) – Name of the case, so of the session, of an in-memory calibration. A file names its case with [simulation] name.

  • resume (bool) – Reopen the latest session of the case; the trials already journaled preload the cache.

  • force (bool) – Search again when a completed session of the case holds the same solution key. Without it, a file or the [calibration] of this project that such a session answers gives back that session’s report, extra["identical_to"] naming its folder, and nothing runs.

  • dry_run (bool) – Return the plan a launch would follow, a dict, after the checks of hmp check, and run nothing. A calibration held in memory needs a project built from a file to name its case.

  • workspace (str | Path | None) – Runner options: the project root, the project name written in the session (project_label wins), a metric extractor, and "module:callable" naming one.

  • project (str | None) – Runner options: the project root, the project name written in the session (project_label wins), a metric extractor, and "module:callable" naming one.

  • project_label (str | None) – Runner options: the project root, the project name written in the session (project_label wins), a metric extractor, and "module:callable" naming one.

  • metric_fn (Any) – Runner options: the project root, the project name written in the session (project_label wins), a metric extractor, and "module:callable" naming one.

  • objective (str | None) – Runner options: the project root, the project name written in the session (project_label wins), a metric extractor, and "module:callable" naming one.

  • report (bool) – Write the report of each session directory once the search is over. False skips it, as hmp calibrate --no-report does.

Returns:

CalibrationReport – What the calibration found, with or without phases, in every mode. With dry_run, the plan.

Raises:
  • ConfigMissingError – Raised when neither config_path nor parameters is supplied.

  • ConfigError – Raised when phase is given and config_path cannot be read, because the answer is what the file says, and when the preflight, the checks of hmp check, refuses the calibration, before anything is prepared.

  • CalibrationError – Raised when [[calibration.phases]] cannot be run as declared, and when phase names a phase no configuration declares.

classmethod Project.rerun(
run,
*,
name=None,
set=None,
solver=None,
headless=False,
no_display=False,
)[source]#

Launch a new simulation from a persisted run snapshot.

run remains a read-only result view; this Project-level helper owns the orchestration required to rebuild the configuration, execute the workflow, and record the new run with parent_sim_id pointing to the original simulation.

Parameters:
  • run (Run) – Persisted run to use as the reproducible source snapshot.

  • name (str | None) – Optional name for the derived run.

  • set (Mapping[str, Any] | None) – Values to set on the stored configuration, as in simulate(): a dotted path, the grammar of --set, or a name of hmp config targets. The result is validated, so an unknown key raises.

  • solver (str | None) – Options forwarded to the derived Project.

  • headless (bool) – Options forwarded to the derived Project.

  • no_display (bool) – Options forwarded to the derived Project.

Returns:

Run – Persisted run view for the derived simulation.

Raises:
  • ConfigMissingError – If run has no persisted config snapshot.

  • PipelineError – If the derived pipeline produces no new Run, e.g. dry_run mode.

Return type:

Run

Project.simulate(
*,
set=None,
name=None,
resume=None,
from_step=None,
until_step=None,
dry_run=False,
frozen=False,
no_display=False,
fresh=False,
force=False,
lineage=None,
calibrated_by=None,
)[source]#

Run one simulation through the configured workflow and return its result.

Builds the model phase on first call (lazy), then runs the Pipeline. A run bounded by until_step before setup_process needs no shared model phase: it executes its own steps and builds nothing else, which is how a catchment is delineated without loading data or meshing. Call once per point to sweep a parameter. Once the attempt is closed, the index of the project is refreshed from the run directory and the Run view is returned.

Parameters:
  • set (Mapping[str, Any] | None) – Changes of the configuration of this run. A key is a dotted path, the grammar of --set, or a name of hmp config targets such as K, Sy or thickness, or first_clim, in the unit the configuration declares for it. They are applied before its plan is built, written in its sealed config.toml, recorded by dotted path in lineage.overrides, and a rerun repeats them.

  • name (str | None) – Run name, the case the directory is named after. Defaults to [simulation] name of the configuration, and to run_0001, run_0002… only when the configuration names no run.

  • resume (str | None) – Name of an interrupted case to continue in place from its journal.

  • from_step (str | None) – Bounds of a partial run: names of pipeline steps, listed in STEP_NAMES.

  • until_step (str | None) – Bounds of a partial run: names of pipeline steps, listed in STEP_NAMES.

  • dry_run (bool) – Say what this run would do, and run nothing.

  • frozen (bool) – Require frozen input-data references.

  • no_display (bool) – Skip display rendering for this run.

  • fresh (bool) – File everything a previous attempt left under attempts/<k>/ and start the case over.

  • force (bool) – Claim a stale case whose process cannot be proven dead.

  • lineage (Lineage | None) – The lineage block and the promoting session the run is sealed with; a promotion or a rerun passes them.

  • calibrated_by (CalibratedBy | None) – The lineage block and the promoting session the run is sealed with; a promotion or a rerun passes them.

Returns:

Run or PlanDraft or None – The persisted run view, or its PlanDraft for a dry run. A window that stops before prepare_solver gives a partial run with no variables, which says its steps. None when the run claims no directory: a window that stops before setup_process.

Raises:
  • PipelineError – If a workflow step fails during execution.

  • SolverError – If the configured solver crashes or fails to converge.

  • ResumeError – If resume references an incompatible journal state.

  • ConfigError – If from_step or until_step names no pipeline step.

Return type:

Run | PlanDraft | None

Examples

>>> run = project.simulate(set={"Sy": 0.05}, name="probe")
>>> run.label()

See also

hydromodpy.run

Functional facade for one-off TOML execution.

hydromodpy.results.run.view.Run

Per-simulation result view returned by successful runs.

Project.spinup(*, spinup=None, name_prefix='spinup')[source]#

Run the cyclic spin-up loop on this project.

Restarts the representative window each cycle from the previous cycle’s state until the aquifer heads and the lake stage converge. Defaults to the [spinup] section of this project’s config; pass spinup to override it in memory. Feed result.restart_from to a production run’s [flow] restart_from.

Parameters:
  • spinup (SpinupConfig | None) – Spin-up settings override. None uses config.spinup.

  • name_prefix (str) – Prefix for the per-cycle run names recorded in the catalog.

Returns:

hydromodpy.project.spinup.SpinupResult – The loop outcome (converged state, restart_from handle).

Return type:

SpinupResult

Lifecycle#

Release the index handle and the preprocessing files.

Project.close()[source]#

Close the Catalog and clean up preprocessing files.