Catalog#
| Member | Kind | What it is |
|---|---|---|
| Open a catalog Constructors, the paths a catalog owns, and the handle itself. | ||
backend | property | The storage backend port driving the SQL reads. |
catalog_path | property | Path of the index database. |
close | method | Close the open field stores and the connection. |
closed | property | True once close ran. |
connection | property | The read-only DuckDB connection, for ad-hoc SQL. |
fields_path_for | method | Return the Zarr directory store of a run. |
from_workspace | method | Open the index of the project a workspace names by its project_root. |
project_path | property | Alias of workspace_path. |
read_config | property | The function the runs of this catalog validate a sealed snapshot with. |
reads_the_published_index | property | True while the file this handle reads is still the published index. |
render | property | The function the runs of this catalog draw a figure with, or None. |
run_dir_for | method | Return the directory of a run. |
runs_dir | property | Directory holding one sub-directory per run. |
tables_dir_for | method | Return the Parquet payload directory of a run. |
workspace_path | property | The project directory that owns this index. |
| Find runs Resolve a reference, list runs, and pick the best, worst or latest. | ||
best | method | Return the completed run with the best value of metric under its rule. |
diff | method | Compare two runs' parameters and metrics. |
find | method | Return the runs that match every filter, newest first. |
frame | property | Every sealed run as one DataFrame row (alias of list_simulations). |
latest | method | Return the most recently created completed run. |
list_simulations | method | Return one DataFrame row per sealed run matching filters. |
rank | method | Return up to n completed runs ranked on metric under their metric rule. |
rel_dir_of | method | Return the relative directory the index holds for sim_id. |
resolve | method | Resolve a user reference to a simulation UUID. |
simulations | property | Every sealed run of the project, newest first, as a DataFrame. |
worst | method | Return the completed run with the worst value of metric under its rule. |
| Read results Fields, time series, budgets, features and provenance of a run. | ||
attempts | method | Return every attempt of one case, by attempt number. |
calibration_phases | method | Return the phases of one session, by rank. |
cases | property | Every result directory of the project, one row each, through v_cases. |
get_provenance | method | Return where the input data of a run came from. |
list_geographic_features | method | Return the names of the vector layers a run stored, in name order. |
list_tracked_files | method | Return the files a run recorded with their digest. |
load_dataset | method | Return one xr.Dataset joining scalars and Zarr fields. |
open_zarr | method | Open the field store of a run for reading. |
query_budget | method | Return the water budget rows of a run. |
query_field | method | Read one stored period of a field as an array. |
query_mass_balance | method | Return the mass-balance rows of a run, one per timestep, in time order. |
query_timeseries | method | Read one series of a run at one station. |
read | method | Read variable for the run referenced by ref, as hydromodpy.read does. |
read_geographic_feature | method | Read one vector layer of a run, the GeoParquet file of its tables directory. |
read_geographic_metadata | method | Return the catchment metadata of a run as a key -> value map. |
sites | property | The 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_tag | method | Return the sim_ids carrying tag as a set of strings. |
| Calibration sessions The sessions a calibration leaves in the catalog and their iterations. | ||
calibration_iterations | method | Return the trials of one session, one row per trial and case, by trial number. |
calibration_sessions | property | Return every calibration session row as a DataFrame. |
| Inspect the index Tables, columns, metrics and stations of the index, and plain SQL. | ||
columns | method | Column names of table. |
describe | method | Return a human-readable summary of the catalog content. |
metrics | method | Distinct metric names recorded in the catalog. |
sql | method | Run an arbitrary SQL query against the catalog DuckDB store. |
stations | method | Distinct station ids referenced by metrics or timeseries. |
tables | method | Tables and views available to sql. |
variables | method | Readable 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_configis refused. A catalog opened byhmp.openor by aProjectcarries 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,
figureis refused. It ishydromodpy.project.show.render()for a catalog opened by aProject.
- 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.RunPer-simulation view returned by catalog queries.
hydromodpy.results.run.group.RunSetMulti-run view returned by cohort queries.
Open a catalog#
Constructors, the paths a catalog owns, and the handle itself.
- property Catalog.connection: DuckDBPyConnection[source]#
The read-only DuckDB connection, for ad-hoc SQL.
- classmethod Catalog.from_workspace(workspace)[source]#
Open the index of the project a workspace names by its
project_root.workspaceis 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.
Nonewhen the opener passed none: the runs read their raw configuration snapshot, andRun.hydromodpy_configis 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.
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
metricunder its rule.Best follows the direction of the metric: the highest
nse, the lowestrmse, thepbiasclosest to zero. A metric with no declared direction raisesUnrankedMetricError. Runs scored under different rules (station, variable, window or rule version) are not comparable: they raiseMixedWindowsErrorunlessmixed_windowsis true.
- Catalog.diff(ref_a, ref_b, *, project=None)[source]#
Compare two runs’ parameters and metrics.
Returns
{"a", "b", "params", "metrics"}.paramsmaps each differing(name, zone)to(value_a, value_b).metricsmaps 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 isNonewhen 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(orcrs): exact value of that run column.solver,solver_category,status,flow_regime,mesh_topology: their code, for examplesolver="modflow6"orstatus="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 examplense_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 raiseMixedWindowsError.
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>_gtstyle bound meets runs scored under different rules andmixed_windowsis false.
- Return type:
Examples
>>> good = cat.find( ... site="basin_a", status="completed", nse_gt=0.7 ... ) >>> good.best("nse")
- Catalog.latest(project=None, *, site=None)[source]#
Return the most recently created completed run.
- Parameters:
- Returns:
Run – The newest run whose status is
completed.- Raises:
KeyError – If no run is completed in that scope.
- Return type:
Examples
>>> run = hmp.open("~/ws/projects/my_project").latest()
- Catalog.list_simulations(**filters)[source]#
Return one DataFrame row per sealed run matching
filters.order_byaccepts only whitelisted simulation columns, with an optionalASCorDESCdirection.
-
Catalog.rank(
)[source]#project,metric='nse',*,ascending=None,n=1,best_first=True,site=None,mixed_windows=False,
Return up to
ncompleted runs ranked onmetricunder their metric rule.Without
ascendingthe runs come best first (best_first=True) or worst first, following the direction of the metric.ascendingorders 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 raiseMixedWindowsError, unlessmixed_windowsis 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 fromcases, 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:
@-selectors:@last,@last~N(N-th newest completed),@best:METRIC/@worst:METRIC(the metric scored under the run’s metric rule; add@STATIONto read another station),@running.sitenarrows a selector to the runs of one site. Best follows the direction of the metric: highestnse, lowestrmse,pbiasclosest to zero (seeMETRIC_SENSE).@bestand@worstrank scores, so the runs they rank must share one rule (station, variable, window, rule version; with@STATION, all but the station): otherwise they raiseMixedWindowsError, unlessmixed_windowsis true.A relative directory:
runs/<name>,sessions/<name>,sessions/<name>/trials/<nnnn>.Full UUID (36 chars with dashes).
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 raisesAmbiguousReferenceError.
Raises
SimulationNotFoundErrorwhen 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.
Read results#
Fields, time series, budgets, features and provenance of a run.
- 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.
- 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_bytesandportable(whether the file travels with an exported package).- Return type:
DataFrame
-
Catalog.load_dataset(
)[source]#filters=None,*,fields=None,include_params=True,include_metrics=True,include_env=True,
Return one
xr.Datasetjoining 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 whengcremoved 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:
- Returns:
pandas.DataFrame – One row per term, zone and timestep, as stored in the
budgetstable.- 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:
- 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:
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(
)[source]#sim_id,station_id,variable,period=None,*,source='simulated',
Read one series of a run at one station.
- Parameters:
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, asRun.timeseriesreads it.Nonereads 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(
)[source]#ref,variable,*,time=None,layer=None,sel=None,bbox=None,
Read
variablefor the run referenced byref, ashydromodpy.read()does.refis resolved throughresolve().timetakes whathydromodpy.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 -> valuemap.What the run recorded about its catchment and grid:
epsg,catch_area,dem_res, the outlet (x_outlet,y_outletand their snapped values),nrow,ncol. Every value is text.Examples
>>> float(cat.read_geographic_metadata(run.sim_id)["catch_area"])
Calibration sessions#
The sessions a calibration leaves in the catalog and their iterations.
Inspect the index#
Tables, columns, metrics and stations of the index, and plain SQL.
- 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.