Run#

MemberKindWhat it is
The run itself
checkspropertyWhat the seal measured: budget, convergence, coverage, calibration.
config_snapshotpropertyRaw config payload stored in the catalog as a dict.
deletemethodMove this run to trash/ (reversible). Raises if protected or running.
deliveriespropertyLatest delivery line of each file and destination, in the order they first appear.
dirpropertyDirectory of this run, runs/<name> or a trial of a session.
exportmethodExport data of this run to files; return the files written.
exportspropertyFiles under exports/ that exports/index.json records, by path.
figuremethodDraw the variable or preset *name* of this run.
figurespropertyFigures under figures/ that figures/index.json records, by path.
flow_regimepropertyFlow regime recorded by the workflow, such as steady or transient.
hydromodpy_configpropertyValidated HydroModPyConfig rebuilt from the stored snapshot.
inputspropertyEvery input this run loaded, as inputs.json lists it.
labelmethodReturn the label of this run today, with its rule version and reasons.
n_cellspropertyNumber of active cells or faces in the persisted simulation mesh.
n_layerspropertyNumber of vertical layers in the persisted simulation mesh.
n_timestepspropertyNumber of persisted timesteps when the workflow is time-dependent.
namepropertyOptional human-readable run name.
notemethodAppend a timestamped note to annotations.json of this run. Returns self.
projectpropertyProject label associated with this run.
readmethodRead a variable of this run, one type for each nature of variable.
recordpropertyThe seal of this run, read from its directory, never from the index.
showmethodRead one thing of this run: table, field, series, profile, figure or report.
sim_idpropertySimulation UUID persisted in the catalog.
sitepropertyName of the site this run was computed on, None on a synthetic domain.
solverpropertyFlow solver name recorded for this run.
statuspropertyRun status stored in the catalog.
stepspropertyPipeline steps this run has done, in order: all of them once it is sealed.
tablemethodReturn the sealed table *name* of this run.
tagmethodAdd (+tag or bare) or remove (-tag) tags. Returns self.
tagspropertyOptional tags attached to this simulation.
Fields, rasters and mesh
catchment_maskpropertyBoolean mask of the catchment: the basin of D at the catchment outlet.
dempropertyDEM as float64 with the source nodata sentinel replaced by NaN.
fieldmethodRead one period of one field, persisted or recomputed on the fly, as an array.
geographicmethodReturn a persisted geographic feature for this run.
geographic_rastermethodReturn one geographic raster persisted for this run.
gridpropertyScalar grid metadata: cell_size, shape, extent, CRS, area.
has_fieldmethodReturn true when a field is available for this run.
meshpropertyUnstructured simulation mesh used by field arrays.
outletpropertyOutlet coordinates (x, y) in the simulation CRS.
Tables and time series
budgetmethodReturn water budget rows for this simulation.
has_tablemethodReturn True when the run holds at least one row of table.
mass_balancepropertyMass-balance diagnostics ordered by timestep.
metricspropertyEvery score the seal of this run records, read from manifest.json.
observedmethodReturn observed timeseries ingested for this simulation.
parameterspropertyCalibratable parameters persisted for this run.
recharge_forcingmethodInput recharge rate of the model domain per stress period, in m/s.
scoremethodScore the stored series of this run again, on any window, after the fact.
score_networkmethodScore the stream-network criterion of this run again, as its trial scored it.
stationsmethodReturn the sorted station ids carrying one variable, simulated by default.
time_indexpropertyDatetime index aligned with the simulation's stress periods.
timeseriesmethodReturn one time series, simulated unless source says otherwise.
Hydrographic network
available_hydrographic_network_rolesmethodReturn the canonical hydrographic-network roles this run can serve.
has_hydrographic_networkmethodReturn true when the requested hydrographic-network role exists.
hydrographic_networkmethodReturn one hydrographic network by canonical role.
hydrographic_network_comparisonmethodReturn one tolerance-based geometric comparison between two stored networks.
hydrographic_network_comparison_metricsmethodReturn one flat metrics record for the stored hydrographic-network comparison.
hydrographic_network_namingmethodReturn canonical naming hints for one hydrographic-network role.
class Run(sim_id, catalog, *, read_config=None, render=None)[source]#

Read one persisted simulation from a HydroModPy catalog.

Run is a lightweight view over one row in the simulations table. It exposes metadata, tabular outputs, field arrays, geographic features, and convenience helpers without requiring callers to know whether data are stored in DuckDB, Parquet, or Zarr.

Parameters:
  • sim_id (str) – Simulation UUID stored in the catalog.

  • catalog (Catalog) – Open Catalog that owns the run metadata and storage paths.

Raises:

hydromodpy.results.errors.RunNotFoundError – On first attribute access if sim_id is not present in the catalog.

Examples

>>> import hydromodpy as hmp
>>> proj = hmp.open("~/hmp_workspace/projects/nancon")
>>> run = proj["baseline"]
>>> run.label()
>>> run.field("head", time=-1)

See also

hydromodpy.results.catalog.facade.Catalog

Workspace-level catalog that creates Run instances.

hydromodpy.results.run.group.RunSet

Collection view for many runs.

The run itself#

property Run.checks: Checks[source]#

budget, convergence, coverage, calibration.

Raises RunNotSealedError for a run that never completed.

Type:

What the seal measured

property Run.config_snapshot: dict | None[source]#

Raw config payload stored in the catalog as a dict.

Returns the JSON-decoded snapshot persisted at registration time (full HydroModPyConfig.model_dump(mode='json')), re-anchored on the project that holds this run. Use hydromodpy_config for a validated Pydantic instance.

Run.delete()[source]#

Move this run to trash/ (reversible). Raises if protected or running.

property Run.deliveries: tuple[PublishedLine, ...][source]#

Latest delivery line of each file and destination, in the order they first appear.

property Run.dir: Path[source]#

Directory of this run, runs/<name> or a trial of a session.

Run.export(
variable,
*,
time=None,
period=None,
format=None,
folder=None,
file=None,
crs=None,
resolution=None,
layer=None,
nodata=-9999.0,
)[source]#

Export data of this run to files; return the files written.

The words of an [[export]] block: variable says what (a name, a list, or "all"), time or period when, folder or file where. The format follows the data unless format or the extension of file names one: a field at one date goes to GeoTIFF, over several dates to one NetCDF, a series or the budget to CSV, a vector layer to GeoPackage, a raster layer to GeoTIFF. Files land in runs/<run>/exports/; a relative folder or file is read from there. Each file carries the identity of the run and is recorded in exports/index.json.

Examples

>>> run.export("all")
>>> run.export(["head", "watertable_depth"], time="2001-08-15")
>>> run.export("discharge", period=("2001-01-01", "2002-12-31"))
>>> run.export(
...     "watertable_depth", time="last", file="nappe_wgs84.tif", crs="EPSG:4326"
... )
property Run.exports: list[Path][source]#

Files under exports/ that exports/index.json records, by path.

Run.figure(
name=None,
*,
request=None,
draw=None,
save=None,
dpi=None,
theme=None,
engine=None,
time=None,
data=False,
**options,
)[source]#

Draw the variable or preset name of this run.

The run’s [display] is not applied. request is a request written as a mapping, as one [[display.figure]] table. draw is a Python function draw(subject, ax, theme) that draws on one axes.

Parameters:
  • name (str | None) – A variable ("head") or a preset.

  • request (Mapping[str, Any] | None) – A request as a mapping, instead of name.

  • draw (Callable[..., Any] | None) – A function that draws the figure, instead of name.

  • save (str | Path | None) – A file, or a folder that receives <name>.png. With it the figure is written and its path comes back.

  • dpi (int | None) – Resolution of the PNG. None takes 150.

  • theme (str | None) – A theme of the request path. None takes the one of the run.

  • engine (str | None) – The engine of the request path, static or interactive.

  • time (str | None) – The instant a figure that draws one shows: a date, "first" or "last". None leaves the figure its own default.

  • data (bool) – With it the tables behind the figure come back, keyed a, b and a:<value> per small multiple, and nothing is drawn.

  • **options (Any) – The fields of a request.

Raises:
  • hydromodpy.core.exceptions.CommandUsageError – If the run was not opened by hydromodpy.open or a project.

  • ValueError – If a field is not one the request takes, or the run lacks what it needs.

property Run.figures: list[Path][source]#

Figures under figures/ that figures/index.json records, by path.

property Run.flow_regime: str | None[source]#

Flow regime recorded by the workflow, such as steady or transient.

property Run.hydromodpy_config: BaseModel[source]#

Validated HydroModPyConfig rebuilt from the stored snapshot.

The run reads it through the read_config function its opener passed: a run opened by hmp.open or by a Project carries the one that validates a sealed snapshot, migration included. Raises ConfigError when this handle carries none: open the run through hmp.open or pass read_config, the validation of HydroModPyConfig.from_snapshot(run.config_snapshot). With a function, a snapshot this version no longer validates raises ValueError and config_snapshot still gives the raw mapping.

property Run.inputs: list[InputEntry][source]#

Every input this run loaded, as inputs.json lists it.

Raises RunNotSealedError for a run that never completed.

Run.label()[source]#

Return the label of this run today, with its rule version and reasons.

The label is computed on each call from the sealed checks, the version that produced the run and the known issues of this build: a newer build may declass a run without rewriting it.

property Run.n_cells: int | None[source]#

Number of active cells or faces in the persisted simulation mesh.

property Run.n_layers: int | None[source]#

Number of vertical layers in the persisted simulation mesh.

property Run.n_timesteps: int | None[source]#

Number of persisted timesteps when the workflow is time-dependent.

property Run.name: str | None[source]#

Optional human-readable run name.

Run.note(text)[source]#

Append a timestamped note to annotations.json of this run. Returns self.

property Run.project: str[source]#

Project label associated with this run.

Run.read(variable, *, time=None, layer=None, sel=None, bbox=None)[source]#

Read a variable of this run, one type for each nature of variable.

  • a field gives an xarray.DataArray with the dimensions time, layer and cell it has. One period in time removes time.

  • a time series gives a pandas.Series indexed by date. It takes sel and no time.

  • a geographic feature gives a geopandas.GeoDataFrame, one row per shape. It takes no time.

  • "particles" gives a pandas.DataFrame, one row per recorded position. It takes no time.

Every field the run reports through has_field reads back here. A stored field is lazy when dask is installed. Fields rebuilt on the fly (water-table elevation and depth, seepage mask, drain outflow) are loaded at once, and time is ignored for a field without a time axis.

Parameters:
  • variable (str) – Name resolved against the field registry, then the timeseries table, then the geographic features.

  • time (Any) – The period of a field: an index (negative counts from the end), a date that resolves to the stress period holding it, "first" or "last", or a slice of indexes. None keeps every period.

  • layer (int | None) – Layer index of a three-dimensional field, 0 for the top layer.

  • sel (dict | None) – Selectors of the reader: {"station": ...} for a series, {"period": (start, end)} for a window of dates.

  • bbox (tuple[float, float, float, float] | None) – (xmin, ymin, xmax, ymax) in the CRS of the run; keeps the cells whose centre lies in the box.

Raises:
  • hydromodpy.results.errors.FieldNotFoundError – If no reader resolves variable.

  • ValueError – If time names a date outside the run, or is given for a series or a feature.

  • IndexError – If time is an index outside the run.

Examples

>>> head = run.read("head")
>>> last = run.read("head", time=-1, layer=0)
>>> ts = run.read("discharge", sel={"station": "outlet"})
property Run.record: RunRecord[source]#

The seal of this run, read from its directory, never from the index.

record.site is the basin (None on a synthetic domain), record.run.case_id the case, record.lineage where the run comes from, record.checks what the seal measured, record.inputs every input it loaded (inputs.json), record.metrics and record.score its scores under the metric rule. Raises RunNotSealedError for a run that never completed.

Run.show(what, **options)[source]#

Read one thing of this run: table, field, series, profile, figure or report.

It is the method of what hydromodpy.show reads for a run: name is the table, variable or figure, time, layer, sel and bbox steer a field, and preset, station and strict steer a report.

property Run.sim_id: str[source]#

Simulation UUID persisted in the catalog.

property Run.site: str | None[source]#

Name of the site this run was computed on, None on a synthetic domain.

The whole site block (gauge, outlet, fingerprint) is record.site.

property Run.solver: str | None[source]#

Flow solver name recorded for this run.

property Run.status: str | None[source]#

Run status stored in the catalog.

property Run.steps: tuple[str, ...][source]#

all of them once it is sealed.

Type:

Pipeline steps this run has done, in order

Run.table(name)[source]#

Return the sealed table name of this run.

metrics is the score table of the seal and parameters the parameter table. calibration is the cost the session that promoted the run scored it on, with the parts of that cost, such as the two distances of a network criterion. Any other name is a table of tables.parquet/ in the run directory. A name the run does not hold is refused with the names it does hold.

Run.tag(*specs)[source]#

Add (+tag or bare) or remove (-tag) tags. Returns self.

The tags live in annotations.json of the run; the index, when the project has one, reads them back.

property Run.tags: list[str] | None[source]#

Optional tags attached to this simulation.

Fields, rasters and mesh#

property Run.catchment_mask: ndarray#

the basin of D at the catchment outlet.

One value per mesh face, read-only, True for the faces of the basin stored as mesh/descent_basin. A run sealed before the basin was stored, a run with no descent (such as a Boussinesq run) and a run whose basin is only the largest one of a synthetic domain (no catchment) fall back, with an INFO line, to a 2D mask on the DEM raster, True where the DEM has a valid positive elevation; its shape is run.grid.shape. Cached on first access. The mask says which cells drain to the outlet; the share of each face inside the delineated polygon, which weighs a catchment total of a spatial quantity, is hydromodpy.results.derive.views.catchment_weights(run).

Type:

Boolean mask of the catchment

property Run.dem: ndarray#

DEM as float64 with the source nodata sentinel replaced by NaN.

Use this when plotting or applying NaN-aware reductions. For a bit-for-bit copy of the stored raster (native dtype, sentinel preserved), use run.geographic_raster("watershed_dem").data.

Run.field(variable, *, time=-1, layer=None, bbox=None)[source]#

Read one period of one field, persisted or recomputed on the fly, as an array.

Takes the words of Run.read(), for one period. Delegates to Catalog.query_field, which falls back to the virtual derivations (watertable elevation/depth, seepage mask, drain outflow) when the field is not persisted. This keeps has_field honest: a variable it reports as available always reads back as an array. Each call opens the store: many steps read through field_range().

Parameters:
  • variable (str) – Public field name registered in hydromodpy.results.field_registry.

  • time (int | str | date | Timestamp | datetime64) – One period: an index (negative counts from the end), a date that resolves to the stress period holding it, "first" or "last". The last by default.

  • layer (int | None) – Optional layer index, 0 for the top layer, for three-dimensional fields.

  • bbox (tuple[float, float, float, float] | None) – Optional (xmin, ymin, xmax, ymax) in the simulation CRS. Cells whose center (run.mesh.cell_centers()) falls outside the bounding box are set to NaN (for float dtypes) or 0 (for integer dtypes). The shape of the array does not change.

Returns:

numpy.ndarray – Field values for the requested time and layer selection.

Return type:

ndarray

Run.geographic(feature_name)[source]#

Return a persisted geographic feature for this run.

Parameters:

feature_name (str) – Feature table name stored in the catalog.

Returns:

geopandas.GeoDataFrame – Geographic feature rows for this simulation.

Return type:

gpd.GeoDataFrame

Run.geographic_raster(name)[source]#

Return one geographic raster persisted for this run.

Parameters:

name (str) – Raster name stored in the simulation Zarr store.

Returns:

RasterField – Array data and raster metadata.

Return type:

RasterField

property Run.grid: Grid#

cell_size, shape, extent, CRS, area.

A global model on the one-cell mesh answers like any run, from the one pixel its DEM stores.

Raises RuntimeError when geographic metadata has not been ingested.

Type:

Scalar grid metadata

Run.has_field(variable, *, subgroup=None)[source]#

Return true when a field is available for this run.

A field counts as available when it is persisted, or when it is a virtual field this store can rebuild (watertable elevation/depth and seepage mask from the stored head, drain outflow from the per-cell budget), so figures find them although no array of their own is written.

property Run.mesh: Mesh[source]#

Unstructured simulation mesh used by field arrays.

Raises:

RuntimeError – Raised for lumped simulations that have no spatial grid.

property Run.outlet: tuple[float, float]#

Outlet coordinates (x, y) in the simulation CRS.

Reads x_outlet / y_outlet from geographic_metadata. Raises RuntimeError if either is absent (e.g. catchment defined by a pre-drawn shapefile rather than a pour point).

Tables and time series#

Run.budget(component=None, *, zone_id=None, period=None, steps=None)[source]#

Return water budget rows for this simulation.

Parameters:
  • component (str | None) – Optional budget component filter.

  • zone_id (str | None) – Optional zone filter.

  • period (tuple | str | None) – Optional window of dates, (start, end) or a year as text. It keeps the stress periods it overlaps, as timeseries() does.

  • steps (tuple[int, int] | None) – Optional inclusive range of period indexes, (first, last).

Returns:

pandas.DataFrame – Budget rows matching the filters.

Return type:

DataFrame

Run.has_table(table)[source]#

Return True when the run holds at least one row of table.

Used by the display layer to decide whether a figure can render before calling it, so a run that never produced (for example) calibration iterations reports the figure as unavailable instead of raising mid-render.

property Run.mass_balance: DataFrame[source]#

Mass-balance diagnostics ordered by timestep.

property Run.metrics: DataFrame[source]#

Every score the seal of this run records, read from manifest.json.

The runtime numbers of the solve (variable runtime) are not scores.

Returns:

pandas.DataFrame – Long-form table: station, variable, metric, value and the window each score was computed on (window_start, window_end, n_samples, metric_rule_version), then n_clipped, the negative values a log-scale score clipped to zero (0 on nse_log when none, empty on a metric that never clips), and n_sim_nan, the periods of the window a NaN simulated value (a dry cell) took out of the pairs. A run scored without a window carries no row, and a run that never completed has no seal and no row.

Run.observed(variable, *, station=None, period=None)[source]#

Return observed timeseries ingested for this simulation.

Observation series are persisted in the timeseries table of the run with source = observed (see hydromodpy.data.ingest.observations.ingest_observations()).

Parameters:
  • variable (str) – Canonical variable name (discharge, head, …).

  • station (str, optional) – Station id to filter on. When None, every observed station for variable is returned.

  • period (tuple, optional) – Window (start, end), read as timeseries() reads it for an observation: what falls in the periods of the window, [lo, hi).

Returns:

pd.DataFrame – Long-form frame with columns station_id, datetime, value. Datetimes are tz-naive UTC.

Raises:

ValueError – When no observation rows match the filter.

Return type:

DataFrame

property Run.parameters: DataFrame[source]#

Calibratable parameters persisted for this run.

Returns a DataFrame indexed by param_name (or by the (param_name, zone_id) MultiIndex when a parameter is zonal) with columns value, unit, parameterization. Homogeneous scalars are trivially looked up via run.parameters.loc["thickness", "value"].

Run.recharge_forcing()[source]#

Input recharge rate of the model domain per stress period, in m/s.

Run.score(windows=None, metrics=None, months=None, station=None)[source]#

Score the stored series of this run again, on any window, after the fact.

No model is run: the series come from timeseries.parquet and are paired as the seal pairs them, a simulated stamp closing its period.

Parameters:
  • windows (Mapping[str, tuple[Any, Any]] | Sequence[DateWindow] | None) – {name: (start, end)} with ISO dates, either bound None for open, or a list of DateWindow. None scores the [metrics] window of the seal.

  • metrics (Sequence[str] | None) – Names of the metric table. None means every metric a series pair can give. A network metric is refused, and so is a metric that needs consecutive days when months is set.

  • months (Sequence[int] | None) – Calendar months, 1 to 12, that the paired periods must fall in.

  • station (str | None) – Score only this station. None scores every observed station the run simulates.

Returns:

pandas.DataFrame – One row per station, variable, metric and window: sim_id, run, station, variable, metric, window_name, window_start, window_end, months, value, n_samples, n_sim_nan.

Return type:

DataFrame

Run.score_network(output=None, window=None)[source]#

Score the stream-network criterion of this run again, as its trial scored it.

No model is run. The release field, the mesh, the maps and the criterion recharge come from the store, and the settings from the network output the run sealed, or the defaults of that output when it sealed none. The value is the one a calibration trial gives at the same parameters and window.

Parameters:
  • output (str | None) – The sealed network output to read. None reads the only one, or the defaults.

  • window (tuple[Any, Any] | Mapping[str, tuple[Any, Any]] | None) – (start, end) or {name: (start, end)}, ISO dates, either bound None for open. It picks the complete years of the two-bound mode. None reads the window the run was scored with, else every year. One state reads no window.

Returns:

pandas.DataFrame – One row per quantity: sim_id, run, output, mode (one_state or two_bounds), window_name, window_start, window_end, bound (minimal, maximal, a validation map, or empty), year (empty for the climatological value), quantity (J_signed, D_so, D_os, D_optim, r_optim_valid, n_years_scored, …) and value.

Return type:

DataFrame

Run.stations(variable, *, source='simulated')[source]#

Return the sorted station ids carrying one variable, simulated by default.

Lets a caller enumerate multi-station families (one reach_id station per SFR reach, gauge ids, …) before fetching each series with timeseries(). source="observed" lists the gauges that measure it.

property Run.time_index: DatetimeIndex#

Datetime index aligned with the simulation’s stress periods.

Length matches run.n_timesteps. Each stamp is the END of its period, as the solvers write it. The solver’s CF /time axis is read first; without it the stamps are rebuilt from the period_start, period_end and time_unit the run states about itself. A steady run without [simulation.time] records no step count and holds one state: its index is the one stamp the solver wrote on its axis, a clock with no calendar that starts at 1970-01-01, so every reader gets one stamp per stored state. Raises if the bounds are missing or a transient simulation has no timesteps.

Run.timeseries(
variable,
*,
station=None,
period=None,
downsample=None,
n_out=None,
source='simulated',
)[source]#

Return one time series, simulated unless source says otherwise.

Parameters:
  • variable (str) – Catalog variable name, such as "discharge" or "head".

  • station (str | None) – Station id stored in the timeseries table. Left None, it is the only station of the variable, or the whole catchment when it has one. A run with several observed piezometers or lakes stores a series for each, and the catchment has none for a head or a stage, so those reads need station; the error lists the ids.

  • period (tuple | str | None) – Optional window, (start, end) or a year as text ("2002"). It keeps the stress periods it overlaps, as a field or a CSV export reads it: a simulated value by its stamp, (lo, hi], an observation by its date, [lo, hi). One date reads the period that date reads.

  • downsample (str | None) – Optional decimation strategy. "lttb" runs Largest Triangle Three Buckets on the series; "auto" enables LTTB only when the series exceeds 50_000 points; None (default) returns the untouched full-resolution series.

  • n_out (int | None) – Target sample count for downsample="lttb" or "auto". Defaults to 5000.

  • source (str) – "simulated", the default, or "observed" for the measurement of the same variable.

Returns:

pandas.Series – Time-indexed values with timezone-normalized UTC timestamps.

Raises:

KeyError – Raised when no matching time series exists.

Return type:

Series

Hydrographic network#

Run.available_hydrographic_network_roles()[source]#

Return the canonical hydrographic-network roles this run can serve.

Run.has_hydrographic_network(role='generated')[source]#

Return true when the requested hydrographic-network role exists.

Run.hydrographic_network(role='generated')[source]#

Return one hydrographic network by canonical role.

Run.hydrographic_network_comparison(
*,
reference_role='reference',
candidate_role='generated',
tolerance_m=50.0,
)[source]#

Return one tolerance-based geometric comparison between two stored networks.

Run.hydrographic_network_comparison_metrics(
*,
reference_role='reference',
candidate_role='generated',
tolerance_m=50.0,
**metadata,
)[source]#

Return one flat metrics record for the stored hydrographic-network comparison.

Run.hydrographic_network_naming(role='generated')[source]#

Return canonical naming hints for one hydrographic-network role.