Run#
| Member | Kind | What it is |
|---|---|---|
| The run itself | ||
checks | property | What the seal measured: budget, convergence, coverage, calibration. |
config_snapshot | property | Raw config payload stored in the catalog as a dict. |
delete | method | Move this run to trash/ (reversible). Raises if protected or running. |
deliveries | property | Latest delivery line of each file and destination, in the order they first appear. |
dir | property | Directory of this run, runs/<name> or a trial of a session. |
export | method | Export data of this run to files; return the files written. |
exports | property | Files under exports/ that exports/index.json records, by path. |
figure | method | Draw the variable or preset *name* of this run. |
figures | property | Figures under figures/ that figures/index.json records, by path. |
flow_regime | property | Flow regime recorded by the workflow, such as steady or transient. |
hydromodpy_config | property | Validated HydroModPyConfig rebuilt from the stored snapshot. |
inputs | property | Every input this run loaded, as inputs.json lists it. |
label | method | Return the label of this run today, with its rule version and reasons. |
n_cells | property | Number of active cells or faces in the persisted simulation mesh. |
n_layers | property | Number of vertical layers in the persisted simulation mesh. |
n_timesteps | property | Number of persisted timesteps when the workflow is time-dependent. |
name | property | Optional human-readable run name. |
note | method | Append a timestamped note to annotations.json of this run. Returns self. |
project | property | Project label associated with this run. |
read | method | Read a variable of this run, one type for each nature of variable. |
record | property | The seal of this run, read from its directory, never from the index. |
show | method | Read one thing of this run: table, field, series, profile, figure or report. |
sim_id | property | Simulation UUID persisted in the catalog. |
site | property | Name of the site this run was computed on, None on a synthetic domain. |
solver | property | Flow solver name recorded for this run. |
status | property | Run status stored in the catalog. |
steps | property | Pipeline steps this run has done, in order: all of them once it is sealed. |
table | method | Return the sealed table *name* of this run. |
tag | method | Add (+tag or bare) or remove (-tag) tags. Returns self. |
tags | property | Optional tags attached to this simulation. |
| Fields, rasters and mesh | ||
catchment_mask | property | Boolean mask of the catchment: the basin of D at the catchment outlet. |
dem | property | DEM as float64 with the source nodata sentinel replaced by NaN. |
field | method | Read one period of one field, persisted or recomputed on the fly, as an array. |
geographic | method | Return a persisted geographic feature for this run. |
geographic_raster | method | Return one geographic raster persisted for this run. |
grid | property | Scalar grid metadata: cell_size, shape, extent, CRS, area. |
has_field | method | Return true when a field is available for this run. |
mesh | property | Unstructured simulation mesh used by field arrays. |
outlet | property | Outlet coordinates (x, y) in the simulation CRS. |
| Tables and time series | ||
budget | method | Return water budget rows for this simulation. |
has_table | method | Return True when the run holds at least one row of table. |
mass_balance | property | Mass-balance diagnostics ordered by timestep. |
metrics | property | Every score the seal of this run records, read from manifest.json. |
observed | method | Return observed timeseries ingested for this simulation. |
parameters | property | Calibratable parameters persisted for this run. |
recharge_forcing | method | Input recharge rate of the model domain per stress period, in m/s. |
score | method | Score the stored series of this run again, on any window, after the fact. |
score_network | method | Score the stream-network criterion of this run again, as its trial scored it. |
stations | method | Return the sorted station ids carrying one variable, simulated by default. |
time_index | property | Datetime index aligned with the simulation's stress periods. |
timeseries | method | Return one time series, simulated unless source says otherwise. |
| Hydrographic network | ||
available_hydrographic_network_roles | method | Return the canonical hydrographic-network roles this run can serve. |
has_hydrographic_network | method | Return true when the requested hydrographic-network role exists. |
hydrographic_network | method | Return one hydrographic network by canonical role. |
hydrographic_network_comparison | method | Return one tolerance-based geometric comparison between two stored networks. |
hydrographic_network_comparison_metrics | method | Return one flat metrics record for the stored hydrographic-network comparison. |
hydrographic_network_naming | method | Return 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.
Runis a lightweight view over one row in thesimulationstable. 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:
- Raises:
hydromodpy.results.errors.RunNotFoundError – On first attribute access if
sim_idis 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.CatalogWorkspace-level catalog that creates
Runinstances.hydromodpy.results.run.group.RunSetCollection view for many runs.
The run itself#
- property Run.checks: Checks[source]#
budget, convergence, coverage, calibration.
Raises
RunNotSealedErrorfor 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. Usehydromodpy_configfor a validated Pydantic instance.
- property Run.deliveries: tuple[PublishedLine, ...][source]#
Latest delivery line of each file and destination, in the order they first appear.
-
Run.export(
)[source]#variable,*,time=None,period=None,format=None,folder=None,file=None,crs=None,resolution=None,layer=None,nodata=-9999.0,
Export data of this run to files; return the files written.
The words of an
[[export]]block:variablesays what (a name, a list, or"all"),timeorperiodwhen,folderorfilewhere. The format follows the data unlessformator the extension offilenames 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 inruns/<run>/exports/; a relativefolderorfileis read from there. Each file carries the identity of the run and is recorded inexports/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/thatexports/index.jsonrecords, by path.
-
Run.figure(
)[source]#name=None,*,request=None,draw=None,save=None,dpi=None,theme=None,engine=None,time=None,data=False,**options,
Draw the variable or preset name of this run.
The run’s
[display]is not applied.requestis a request written as a mapping, as one[[display.figure]]table.drawis a Python functiondraw(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.
Nonetakes 150.theme (str | None) – A theme of the request path.
Nonetakes the one of the run.engine (str | None) – The engine of the request path,
staticorinteractive.time (str | None) – The instant a figure that draws one shows: a date,
"first"or"last".Noneleaves the figure its own default.data (bool) – With it the tables behind the figure come back, keyed
a,banda:<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.openor 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/thatfigures/index.jsonrecords, 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
HydroModPyConfigrebuilt from the stored snapshot.The run reads it through the
read_configfunction its opener passed: a run opened byhmp.openor by aProjectcarries the one that validates a sealed snapshot, migration included. RaisesConfigErrorwhen this handle carries none: open the run throughhmp.openor passread_config, the validation ofHydroModPyConfig.from_snapshot(run.config_snapshot). With a function, a snapshot this version no longer validates raisesValueErrorandconfig_snapshotstill gives the raw mapping.
- property Run.inputs: list[InputEntry][source]#
Every input this run loaded, as
inputs.jsonlists it.Raises
RunNotSealedErrorfor 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.
- 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.DataArraywith the dimensionstime,layerandcellit has. One period intimeremovestime.a time series gives a
pandas.Seriesindexed by date. It takesseland notime.a geographic feature gives a
geopandas.GeoDataFrame, one row per shape. It takes notime."particles"gives apandas.DataFrame, one row per recorded position. It takes notime.
Every field the run reports through
has_fieldreads 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, andtimeis ignored for a field without a time axis.- Parameters:
variable (str) – Name resolved against the field registry, then the
timeseriestable, 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 asliceof indexes.Nonekeeps 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
timenames a date outside the run, or is given for a series or a feature.IndexError – If
timeis 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.siteis the basin (Noneon a synthetic domain),record.run.case_idthe case,record.lineagewhere the run comes from,record.checkswhat the seal measured,record.inputsevery input it loaded (inputs.json),record.metricsandrecord.scoreits scores under the metric rule. RaisesRunNotSealedErrorfor a run that never completed.
- Run.show(what, **options)[source]#
Read one thing of this run:
table,field,series,profile,figureorreport.It is the method of what
hydromodpy.showreads for a run:nameis the table, variable or figure,time,layer,selandbboxsteer a field, andpreset,stationandstrictsteer a report.
- property Run.site: str | None[source]#
Name of the site this run was computed on,
Noneon a synthetic domain.The whole site block (gauge, outlet, fingerprint) is
record.site.
- 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.
metricsis the score table of the seal andparametersthe parameter table.calibrationis 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 oftables.parquet/in the run directory. A name the run does not hold is refused with the names it does hold.
Fields, rasters and mesh#
- property Run.catchment_mask: ndarray#
the basin of D at the catchment outlet.
One value per mesh face, read-only,
Truefor the faces of the basin stored asmesh/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,Truewhere the DEM has a valid positive elevation; its shape isrun.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, ishydromodpy.results.derive.views.catchment_weights(run).- Type:
Boolean mask of the catchment
- property Run.dem: ndarray#
DEM as
float64with 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 toCatalog.query_field, which falls back to the virtual derivations (watertable elevation/depth, seepage mask, drain outflow) when the field is not persisted. This keepshas_fieldhonest: a variable it reports as available always reads back as an array. Each call opens the store: many steps read throughfield_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 toNaN(for float dtypes) or0(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:
- 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
RuntimeErrorwhen 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.
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, astimeseries()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.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,valueand the window each score was computed on (window_start,window_end,n_samples,metric_rule_version), thenn_clipped, the negative values a log-scale score clipped to zero (0 onnse_logwhen none, empty on a metric that never clips), andn_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
timeseriestable of the run withsource = observed(seehydromodpy.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 forvariableis returned.period (tuple, optional) – Window
(start, end), read astimeseries()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
DataFrameindexed byparam_name(or by the(param_name, zone_id)MultiIndex when a parameter is zonal) with columnsvalue,unit,parameterization. Homogeneous scalars are trivially looked up viarun.parameters.loc["thickness", "value"].
- 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.parquetand 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 boundNonefor open, or a list ofDateWindow.Nonescores the[metrics]window of the seal.metrics (Sequence[str] | None) – Names of the metric table.
Nonemeans every metric a series pair can give. A network metric is refused, and so is a metric that needs consecutive days whenmonthsis set.months (Sequence[int] | None) – Calendar months, 1 to 12, that the paired periods must fall in.
station (str | None) – Score only this station.
Nonescores 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.
Nonereads 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 boundNonefor open. It picks the complete years of the two-bound mode.Nonereads 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_stateortwo_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, …) andvalue.- 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_idstation per SFR reach, gauge ids, …) before fetching each series withtimeseries().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/timeaxis is read first; without it the stamps are rebuilt from theperiod_start,period_endandtime_unitthe 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(
)[source]#variable,*,station=None,period=None,downsample=None,n_out=None,source='simulated',
Return one time series, simulated unless
sourcesays 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 needstation; 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 to5000.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(
)[source]#*,reference_role='reference',candidate_role='generated',tolerance_m=50.0,
Return one tolerance-based geometric comparison between two stored networks.