Catalog#

MemberKindWhat it is
Open a catalog Constructors, the paths a catalog owns, and the handle itself.
backendpropertyThe storage backend port driving the SQL reads.
catalog_pathpropertyPath of the index database.
closemethodClose the open field stores and the connection.
closedpropertyTrue once close ran.
connectionpropertyThe read-only DuckDB connection, for ad-hoc SQL.
fields_path_formethodReturn the Zarr directory store of a run.
from_workspacemethodOpen the index of the project a workspace names by its project_root.
project_pathpropertyAlias of workspace_path.
read_configpropertyThe function the runs of this catalog validate a sealed snapshot with.
reads_the_published_indexpropertyTrue while the file this handle reads is still the published index.
renderpropertyThe function the runs of this catalog draw a figure with, or None.
run_dir_formethodReturn the directory of a run.
runs_dirpropertyDirectory holding one sub-directory per run.
tables_dir_formethodReturn the Parquet payload directory of a run.
workspace_pathpropertyThe project directory that owns this index.
Find runs Resolve a reference, list runs, and pick the best, worst or latest.
bestmethodReturn the completed run with the best value of metric under its rule.
diffmethodCompare two runs' parameters and metrics.
findmethodReturn the runs that match every filter, newest first.
framepropertyEvery sealed run as one DataFrame row (alias of list_simulations).
latestmethodReturn the most recently created completed run.
list_simulationsmethodReturn one DataFrame row per sealed run matching filters.
rankmethodReturn up to n completed runs ranked on metric under their metric rule.
rel_dir_ofmethodReturn the relative directory the index holds for sim_id.
resolvemethodResolve a user reference to a simulation UUID.
simulationspropertyEvery sealed run of the project, newest first, as a DataFrame.
worstmethodReturn the completed run with the worst value of metric under its rule.
Read results Fields, time series, budgets, features and provenance of a run.
attemptsmethodReturn every attempt of one case, by attempt number.
calibration_phasesmethodReturn the phases of one session, by rank.
casespropertyEvery result directory of the project, one row each, through v_cases.
get_provenancemethodReturn where the input data of a run came from.
list_geographic_featuresmethodReturn the names of the vector layers a run stored, in name order.
list_tracked_filesmethodReturn the files a run recorded with their digest.
load_datasetmethodReturn one xr.Dataset joining scalars and Zarr fields.
open_zarrmethodOpen the field store of a run for reading.
query_budgetmethodReturn the water budget rows of a run.
query_fieldmethodRead one stored period of a field as an array.
query_mass_balancemethodReturn the mass-balance rows of a run, one per timestep, in time order.
query_timeseriesmethodRead one series of a run at one station.
readmethodRead variable for the run referenced by ref, as hydromodpy.read does.
read_geographic_featuremethodRead one vector layer of a run, the GeoParquet file of its tables directory.
read_geographic_metadatamethodReturn the catchment metadata of a run as a key -> value map.
sitespropertyThe sites named by the runs and sessions of the project, with their counts.
Tags and notes Label a run, annotate it, rename it.
sims_with_tagmethodReturn the sim_ids carrying tag as a set of strings.
Calibration sessions The sessions a calibration leaves in the catalog and their iterations.
calibration_iterationsmethodReturn the trials of one session, one row per trial and case, by trial number.
calibration_sessionspropertyReturn every calibration session row as a DataFrame.
Inspect the index Tables, columns, metrics and stations of the index, and plain SQL.
columnsmethodColumn names of table.
describemethodReturn a human-readable summary of the catalog content.
metricsmethodDistinct metric names recorded in the catalog.
sqlmethodRun an arbitrary SQL query against the catalog DuckDB store.
stationsmethodDistinct station ids referenced by metrics or timeseries.
tablesmethodTables and views available to sql.
variablesmethodReadable variable names (Zarr fields + timeseries + features).
class Catalog(project_root, *, read_config=None, render=None)[source]#

Read-only view of a project index.

Parameters:
  • project_root (Path | str) – The project directory, the one holding runs/ and .hmp/.

  • read_config (Callable[[Mapping[str, Any]], BaseModel] | None) – The function that validates a sealed configuration snapshot, handed to every run this catalog builds. Without one, run.hydromodpy_config is refused. A catalog opened by hmp.open or by a Project carries it.

  • render (Renderer | None) – The function that draws a figure or writes a report for a run, a session or a set of runs, handed on like read_config to every object this catalog builds. Without one, figure is refused. It is hydromodpy.project.show.render() for a catalog opened by a Project.

Raises:
  • FileNotFoundError – If the directory is not a project.

  • hydromodpy.core.exceptions.WriteConflictError – If the index had to be built and another process keeps its lock.

  • hydromodpy.core.exceptions.SchemaVersionMismatchError – If the index was written under another schema version.

  • hydromodpy.core.exceptions.CatalogUnreadableError – If the index file exists but DuckDB cannot open it.

Examples

>>> import hydromodpy as hmp
>>> catalog = hmp.open("~/hmp_workspace/projects/nancon")
>>> catalog.latest().summary()

See also

hydromodpy.results.run.view.Run

Per-simulation view returned by catalog queries.

hydromodpy.results.run.group.RunSet

Multi-run view returned by cohort queries.

Open a catalog#

Constructors, the paths a catalog owns, and the handle itself.

property Catalog.backend: DuckDBBackend[source]#

The storage backend port driving the SQL reads.

property Catalog.catalog_path: Path[source]#

Path of the index database.

Catalog.close()[source]#

Close the open field stores and the connection.

property Catalog.closed: bool[source]#

True once close() ran.

property Catalog.connection: DuckDBPyConnection[source]#

The read-only DuckDB connection, for ad-hoc SQL.

Catalog.fields_path_for(sim_id)[source]#

Return the Zarr directory store of a run.

classmethod Catalog.from_workspace(workspace)[source]#

Open the index of the project a workspace names by its project_root.

workspace is a [workspace] configuration or a runtime workspace object: both carry the project directory.

property Catalog.project_path: Path[source]#

Alias of workspace_path.

property Catalog.read_config: Callable[[Mapping[str, Any]], BaseModel] | None[source]#

The function the runs of this catalog validate a sealed snapshot with.

None when the opener passed none: the runs read their raw configuration snapshot, and Run.hydromodpy_config is refused.

property Catalog.reads_the_published_index: bool[source]#

True while the file this handle reads is still the published index.

A rebuild publishes a new file by rename, and an open handle keeps reading the file it opened. Its owner then opens the index again.

property Catalog.render: Renderer | None[source]#

The function the runs of this catalog draw a figure with, or None.

With None, run.figure and run.show(what="figure") are refused and say to open the run with hmp.open.

Catalog.run_dir_for(sim_id)[source]#

Return the directory of a run.

property Catalog.runs_dir: Path[source]#

Directory holding one sub-directory per run.

Catalog.tables_dir_for(sim_id)[source]#

Return the Parquet payload directory of a run.

property Catalog.workspace_path: Path[source]#

The project directory that owns this index.

Find runs#

Resolve a reference, list runs, and pick the best, worst or latest.

Catalog.best(project, metric='nse', *, site=None, mixed_windows=False)[source]#

Return the completed run with the best value of metric under its rule.

Best follows the direction of the metric: the highest nse, the lowest rmse, the pbias closest to zero. A metric with no declared direction raises UnrankedMetricError. Runs scored under different rules (station, variable, window or rule version) are not comparable: they raise MixedWindowsError unless mixed_windows is true.

Catalog.diff(ref_a, ref_b, *, project=None)[source]#

Compare two runs’ parameters and metrics.

Returns {"a", "b", "params", "metrics"}. params maps each differing (name, zone) to (value_a, value_b). metrics maps each differing (metric, station, variable) to one entry per run, {"value", "window_start", "window_end", "n"}: the score and the window and samples it was computed on. An entry is None when the run holds no such score.

Catalog.find(*, mixed_windows=False, **filters)[source]#

Return the runs that match every filter, newest first.

Parameters:
  • **filters –

    Each keyword narrows the set:

    • project, site, site_fingerprint, case_id, recipe, rel_dir, name, name_stem, solution_key, request_id, crs_wkt (or crs): exact value of that run column.

    • solver, solver_category, status, flow_regime, mesh_topology: their code, for example solver="modflow6" or status="completed".

    • mesh_engine: the engine that built the mesh, for example "voronoi", read from the stored configuration.

    • tags: one tag the run carries.

    • <metric>_gt, <metric>_gte, <metric>_lt, <metric>_lte: bound on a metric scored under the run’s metric rule, for example nse_gt=0.7. A bound reads every score against one number, so the runs it is applied to must share one rule (station, variable, window, rule version): runs that carry the metric under different rules raise MixedWindowsError.

  • mixed_windows (bool) – Apply the bounds although the runs were scored under different rules. Refused by default.

Returns:

RunSet – The matching runs. It is empty when nothing matches.

Raises:
  • ValueError – If a keyword is none of the above, or names a metric the catalog does not know (a retired spelling is refused with the name to write). The message lists them.

  • MixedWindowsError – If a <metric>_gt style bound meets runs scored under different rules and mixed_windows is false.

Return type:

RunSet

Examples

>>> good = cat.find(
...     site="basin_a", status="completed", nse_gt=0.7
... )
>>> good.best("nse")
property Catalog.frame[source]#

Every sealed run as one DataFrame row (alias of list_simulations).

Catalog.latest(project=None, *, site=None)[source]#

Return the most recently created completed run.

Parameters:
  • project (str | None) – Look only at the runs of this project. None looks at the whole catalog.

  • site (str | None) – Look only at the runs of this site.

Returns:

Run – The newest run whose status is completed.

Raises:

KeyError – If no run is completed in that scope.

Return type:

Run

Examples

>>> run = hmp.open("~/ws/projects/my_project").latest()
Catalog.list_simulations(**filters)[source]#

Return one DataFrame row per sealed run matching filters.

order_by accepts only whitelisted simulation columns, with an optional ASC or DESC direction.

Catalog.rank(
project,
metric='nse',
*,
ascending=None,
n=1,
best_first=True,
site=None,
mixed_windows=False,
)[source]#

Return up to n completed runs ranked on metric under their metric rule.

Without ascending the runs come best first (best_first=True) or worst first, following the direction of the metric. ascending orders on the raw value instead, for a metric with no direction. The scores must share one rule: runs scored at different stations, on different variables, windows or rule versions raise MixedWindowsError, unless mixed_windows is true.

Catalog.rel_dir_of(sim_id)[source]#

Return the relative directory the index holds for sim_id.

A sealed run answers from simulations; a case still running answers from cases, where its attempt recorded the id.

Catalog.resolve(ref, *, project=None, site=None, mixed_windows=False)[source]#

Resolve a user reference to a simulation UUID.

Accepted forms, tried in order:

  1. @-selectors: @last, @last~N (N-th newest completed), @best:METRIC / @worst:METRIC (the metric scored under the run’s metric rule; add @STATION to read another station), @running. site narrows a selector to the runs of one site. Best follows the direction of the metric: highest nse, lowest rmse, pbias closest to zero (see METRIC_SENSE). @best and @worst rank scores, so the runs they rank must share one rule (station, variable, window, rule version; with @STATION, all but the station): otherwise they raise MixedWindowsError, unless mixed_windows is true.

  2. A relative directory: runs/<name>, sessions/<name>, sessions/<name>/trials/<nnnn>.

  3. Full UUID (36 chars with dashes).

  4. UUID prefix of >= 4 hex characters, or the run directory name <name> (runs/<name>). A hex word that is both a prefix and a name of two different runs raises AmbiguousReferenceError.

Raises SimulationNotFoundError when nothing matches, with the closest directory names suggested.

property Catalog.simulations: DataFrame[source]#

Every sealed run of the project, newest first, as a DataFrame.

The same columns as list_simulations(), without a filter.

Catalog.worst(
project,
metric='nse',
*,
site=None,
mixed_windows=False,
)[source]#

Return the completed run with the worst value of metric under its rule.

The mirror of best(), with the same refusal of mixed rules.

Read results#

Fields, time series, budgets, features and provenance of a run.

Catalog.attempts(rel_dir)[source]#

Return every attempt of one case, by attempt number.

Catalog.calibration_phases(session_id)[source]#

Return the phases of one session, by rank.

property Catalog.cases: DataFrame[source]#

Every result directory of the project, one row each, through v_cases.

A sealed run carries its label and its headline metric; a running, failed or aborted attempt carries the status its outcome says. The status and the pulse of a live case are read on the disk, because the index is not written again at each pulse.

Catalog.get_provenance(sim_id, variable=None)[source]#

Return where the input data of a run came from.

One row per input variable: the source type (an HTTP API, a user file, a data manager, a derived product or the cache), the source reference, the SHA-256 digests and the loader that read it.

Parameters:
  • sim_id (str | UUID) – Id of the run.

  • variable (str | None) – Keep only this input variable, for example "dem".

Returns:

pandas.DataFrame – The rows of the provenance table for that run.

Return type:

DataFrame

Catalog.list_geographic_features(sim_id)[source]#

Return the names of the vector layers a run stored, in name order.

Each name reads back with read_geographic_feature().

Catalog.list_tracked_files(sim_id)[source]#

Return the files a run recorded with their digest.

Returns:

pandas.DataFrame – One row per file: role, category, original_path, canonical_path, sha256, size_bytes and portable (whether the file travels with an exported package).

Return type:

DataFrame

Catalog.load_dataset(
filters=None,
*,
fields=None,
include_params=True,
include_metrics=True,
include_env=True,
)[source]#

Return one xr.Dataset joining scalars and Zarr fields.

See hydromodpy.results.catalog.dataset_loader.load_dataset().

Catalog.open_zarr(sim_id)[source]#

Open the field store of a run for reading.

The handle is tracked and closed by close().

Raises:

FileNotFoundError – If the run has no fields.zarr, with the purge date when gc removed it from a kept trial.

Catalog.query_budget(sim_id, zone_id=None, steps=None)[source]#

Return the water budget rows of a run.

Parameters:
  • sim_id (str | UUID) – Id of the run.

  • zone_id (str | None) – Keep only this budget zone. None keeps every zone.

  • steps (tuple[int, int] | None) – (first, last) period indexes, both included.

Returns:

pandas.DataFrame – One row per term, zone and timestep, as stored in the budgets table.

Return type:

DataFrame

Catalog.query_field(sim_id, variable, timestep, layer=None)[source]#

Read one stored period of a field as an array.

A field the run did not store but can rebuild (water-table depth, seepage mask, drain outflow) is computed from the stored ones.

Parameters:
  • sim_id (str | UUID) – Id of the run.

  • variable (str) – Field name, for example "head".

  • timestep (int) – Index of the stored period, 0 for the first.

  • layer (int | None) – Layer index of a three-dimensional field. None keeps every layer.

Returns:

numpy.ndarray – The values of that period, one per cell (and per layer).

Raises:

KeyError – If the run neither stores nor can rebuild variable.

Return type:

ndarray

Examples

>>> heads = cat.query_field(
...     run.sim_id, "head", timestep=0, layer=0
... )
Catalog.query_mass_balance(sim_id)[source]#

Return the mass-balance rows of a run, one per timestep, in time order.

Catalog.query_timeseries(
sim_id,
station_id,
variable,
period=None,
*,
source='simulated',
)[source]#

Read one series of a run at one station.

Parameters:
  • sim_id (str | UUID) – Id of the run.

  • station_id (str) – Station the series belongs to, for example "outlet".

  • variable (str) – Series name, for example "discharge".

  • period (tuple | None) – Window (start, end), or a year as text ("2002"). It keeps the stress periods it overlaps, as Run.timeseries reads it. None reads the whole series.

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

Returns:

pandas.Series – Values indexed by time (naive UTC timestamps), named variable.

Raises:

KeyError – If the run holds no such series.

Return type:

Series

Examples

>>> q = cat.query_timeseries(
...     run.sim_id, "outlet", "discharge", period="2002"
... )
Catalog.read(
ref,
variable,
*,
time=None,
layer=None,
sel=None,
bbox=None,
)[source]#

Read variable for the run referenced by ref, as hydromodpy.read() does.

ref is resolved through resolve(). time takes what hydromodpy.read() takes: a period index, a date, "first" or "last", or a slice of indexes.

Catalog.read_geographic_feature(sim_id, feature_name)[source]#

Read one vector layer of a run, the GeoParquet file of its tables directory.

Catalog.read_geographic_metadata(sim_id)[source]#

Return the catchment metadata of a run as a key -> value map.

What the run recorded about its catchment and grid: epsg, catch_area, dem_res, the outlet (x_outlet, y_outlet and their snapped values), nrow, ncol. Every value is text.

Examples

>>> float(cat.read_geographic_metadata(run.sim_id)["catch_area"])
property Catalog.sites: DataFrame[source]#

The sites named by the runs and sessions of the project, with their counts.

Tags and notes#

Label a run, annotate it, rename it.

Catalog.sims_with_tag(tag)[source]#

Return the sim_ids carrying tag as a set of strings.

Calibration sessions#

The sessions a calibration leaves in the catalog and their iterations.

Catalog.calibration_iterations(session_id)[source]#

Return the trials of one session, one row per trial and case, by trial number.

property Catalog.calibration_sessions: DataFrame[source]#

Return every calibration session row as a DataFrame.

Inspect the index#

Tables, columns, metrics and stations of the index, and plain SQL.

Catalog.columns(table='simulations')[source]#

Column names of table.

Catalog.describe()[source]#

Return a human-readable summary of the catalog content.

Catalog.metrics()[source]#

Distinct metric names recorded in the catalog.

Catalog.sql(query, params=None)[source]#

Run an arbitrary SQL query against the catalog DuckDB store.

Documented escape hatch for callers that need ad-hoc analytical queries beyond the typed catalog API. Returns the result as a pandas.DataFrame.

Catalog.stations()[source]#

Distinct station ids referenced by metrics or timeseries.

Catalog.tables()[source]#

Tables and views available to sql().

Catalog.variables()[source]#

Readable variable names (Zarr fields + timeseries + features).