hydro_core/lib.rs
1//! hydro-core: shared types, the `HydroModel` trait, and evaluation metrics
2//! for the multi-model hydrology platform (新安江 / TOPMODEL / SWAT /
3//! API-CONT).
4//!
5//! Each model crate (`hydro-xinanjiang`, `hydro-topmodel`, `hydro-swat`,
6//! `hydro-apicont`) depends only on this crate and implements `HydroModel`.
7//! The platform crate (`hydro-platform`) uses `DynHydroModel` for
8//! heterogeneous comparison of all four models on the same basin.
9//!
10//! # Evaluation metrics
11//!
12//! [`metrics`] provides:
13//! - **Deterministic single-series scores** — NSE (= DC 确定性系数), KGE,
14//! RMSE, PBIAS, R² — with `dc_grade` mapping DC to the GB/T 22482-2008
15//! 甲 / 乙 / 丙 / 不合格 grade band.
16//! - **GB/T 22482-2008 flood-forecast qualification** — event errors
17//! (peak / peak-timing / runoff-depth), event qualification, 合格率, and
18//! overall scheme grade.
19//! - **Ensemble probabilistic verification** — fair CRPS, Brier score,
20//! POD/FAR/CSI contingency, exceedance probabilities, and the Talagrand
21//! rank histogram.
22
23pub mod forcing;
24pub mod metrics;
25
26pub use forcing::{Forcing, BasinInfo, Outlet};
27pub use metrics::{
28 MetricsReport, nse, kge, rmse, pbias, r2, dc_grade, compute_metrics,
29 GbtEventErrors, QualificationTolerance, QualificationReport,
30 event_errors, event_qualified, qualified_rate, qualification_grade, scheme_grade,
31 compute_metrics_gbt,
32 ProbabilisticReport, crps, brier, pod_far_csi, ensemble_exceedance, compute_probabilistic,
33 rank_histogram,
34};
35
36use serde::{Serialize, Deserialize};
37
38/// Identifier for the four distributed hydrology models orchestrated by the
39/// platform crate.
40///
41/// Used as a machine-friendly tag in scenario configs and parameter
42/// overrides; for the human-readable label, see [`ModelType::name`] or
43/// [`HydroModel::name`].
44#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, Hash)]
45pub enum ModelType {
46 /// Xinanjiang model (三水源, saturation-excess + unit-hydrograph routing).
47 Xinanjiang,
48 /// TOPMODEL (Beven & Kirkby 1979, saturation-excess, TWI-based).
49 Topmodel,
50 /// SWAT+ LTE (USDA-ARS, daily, hydrology-only subset).
51 Swat,
52 /// API-CONT (antecedent precipitation index continuous baseline).
53 Apicont,
54}
55
56impl ModelType {
57 /// Human-readable display name in conventional Chinese/English
58 /// (`"新安江"`, `"TOPMODEL"`, `"SWAT"`, `"API-CONT"`), suitable for UI
59 /// tables and reports.
60 pub fn name(&self) -> &'static str {
61 match self {
62 ModelType::Xinanjiang => "新安江",
63 ModelType::Topmodel => "TOPMODEL",
64 ModelType::Swat => "SWAT",
65 ModelType::Apicont => "API-CONT",
66 }
67 }
68}
69
70/// The core trait every distributed hydrological model implements.
71///
72/// Each model owns its parameter struct (associated type [`Params`](HydroModel::Params))
73/// and its internal state. The platform calls
74/// [`step`](HydroModel::step) once per time-step and reads
75/// [`discharge`](HydroModel::discharge) for the outlet hydrograph in m³/s.
76/// Implementations are expected to be deterministic given (params, state,
77/// forcing) so that calibration can rely on reproducibility.
78pub trait HydroModel: Send {
79 /// Model-specific parameters, serializable so calibrated configs can be
80 /// persisted as JSON and overrides can be applied at runtime by the
81 /// platform.
82 type Params: Serialize + for<'de> Deserialize<'de> + Clone + Send;
83
84 /// Construct a model instance with the given parameters and default
85 /// (cold-start) state.
86 fn new(params: Self::Params) -> Self;
87
88 /// Advance the model by one time-step of length `dt_h` (hours), given the
89 /// meteorological [`Forcing`] for that step. Updates internal state in
90 /// place; the resulting outlet discharge is read via
91 /// [`discharge`](HydroModel::discharge).
92 fn step(&mut self, forcing: &Forcing, dt_h: f64);
93
94 /// Current discharge at the basin outlet, in m³/s. Read after each
95 /// [`step`](HydroModel::step) to assemble the hydrograph.
96 fn discharge(&self) -> f64;
97
98 /// Serialize the internal state (soil moisture, storages, …) as JSON for
99 /// warm-restart across events or runs.
100 fn state(&self) -> serde_json::Value;
101
102 /// Reset internal state to its default cold-start values.
103 fn reset(&mut self);
104
105 /// Model display name (e.g. `"新安江"`, `"TOPMODEL"`) — see also
106 /// [`ModelType::name`].
107 fn name(&self) -> &'static str;
108
109 /// Read-only access to the parameter struct.
110 fn params(&self) -> &Self::Params;
111
112 /// Mutable access to the parameter struct (used by calibrators to apply
113 /// a new candidate vector between runs).
114 fn params_mut(&mut self) -> &mut Self::Params;
115}
116
117/// Object-safe wrapper so the platform can hold `Vec<Box<dyn DynHydroModel>>`
118/// for heterogeneous multi-model comparison.
119///
120/// Each method mirrors the corresponding `HydroModel` method, but parameters
121/// are passed as `serde_json::Value` so all four models share a single trait
122/// object. Any `HydroModel` is automatically a `DynHydroModel` via the
123/// blanket impl below — you never implement this trait manually.
124pub trait DynHydroModel: Send {
125 /// Advance one time-step. See [`HydroModel::step`].
126 fn step(&mut self, forcing: &Forcing, dt_h: f64);
127 /// Current outlet discharge (m³/s). See [`HydroModel::discharge`].
128 fn discharge(&self) -> f64;
129 /// Display name. See [`HydroModel::name`].
130 fn name(&self) -> &'static str;
131 /// Snapshot the model's parameters as JSON (e.g. to save a calibrated
132 /// config or to diff two models).
133 fn params_json(&self) -> serde_json::Value;
134 /// Replace parameters from a JSON value. Silently ignored if the value
135 /// does not deserialize into the model's `Params` struct.
136 fn set_params_json(&mut self, v: &serde_json::Value);
137 /// Reset internal state to defaults (cold start). See [`HydroModel::reset`].
138 fn reset(&mut self);
139}
140
141/// Blanket impl: every `HydroModel` is automatically a `DynHydroModel`.
142impl<M: HydroModel> DynHydroModel for M {
143 fn step(&mut self, forcing: &Forcing, dt_h: f64) {
144 HydroModel::step(self, forcing, dt_h);
145 }
146 fn discharge(&self) -> f64 {
147 HydroModel::discharge(self)
148 }
149 fn name(&self) -> &'static str {
150 HydroModel::name(self)
151 }
152 fn params_json(&self) -> serde_json::Value {
153 serde_json::to_value(self.params()).unwrap_or(serde_json::Value::Null)
154 }
155 fn set_params_json(&mut self, v: &serde_json::Value) {
156 if let Ok(p) = serde_json::from_value::<M::Params>(v.clone()) {
157 *self.params_mut() = p;
158 }
159 }
160 fn reset(&mut self) {
161 HydroModel::reset(self);
162 }
163}