hydro_apicont/lib.rs
1//! API-CONT:前期降水指数连续基线模型(廉价,3 参数)。
2//!
3//! 单线性蓄水库 + 蒸发 + 线性水库汇流。蓄水量 `sm` 经指数退水 `(1−k)·sm` 排出为径流
4//! (即前期降水的指数记忆,API 的本质);再经 `cs` 线性水库演算到出口。
5//! 严格水量平衡:`rain = ET + drain + Δsm`。适合作为多模型对比中最廉价的连续基线。
6//!
7//! # English
8//!
9//! `hydro-apicont` is **API-CONT**, a cheap 3-parameter continuous baseline
10//! rainfall–runoff model built around the *antecedent precipitation index* (API).
11//! A single linear storage `sm` (mm) is filled by rain, drained by ET, and
12//! exponentially depleted to runoff via `(1 − k) · sm` each step — the classic
13//! exponential memory that gives API models their receding signature. A second
14//! linear-reservoir routing store with recession `cs` then advects that drained
15//! water to the basin outlet as discharge (m³/s).
16//!
17//! The model enforces a strict mass balance `rain = ET + drain + Δsm` every
18//! step (see the `no_mass_creation_constant_rain` test). With only `k`, `cs`,
19//! and `area_km2` to set, it is intended as the cheapest member of the
20//! multi-model ensemble orchestrated by `hydro-platform`, useful as a baseline
21//! against which the structurally richer Xinanjiang / TOPMODEL / SWAT+ LTE
22//! models can be scored.
23//!
24//! ## Mass balance
25//!
26//! For each step of length `dt_h` (hours):
27//!
28//! 1. Fill: `sm ← sm + max(P, 0)`
29//! 2. ET: `ea = min(PET, sm)`, `sm ← sm − ea`
30//! 3. Drain: `drain = (1 − k) · sm`, `sm ← sm − drain` (← API exponential memory)
31//! 4. Route: `Q ← cs · Q + (1 − cs) · mm_to_m3s(drain, area_km2, dt_h)`
32//!
33//! where `mm_to_m3s(mm, area_km2, dt_h) = mm · area_km2 · 1000 / (dt_h · 3600)`.
34//! Summed over a step, `P = ea + drain + Δsm` exactly — no mass is created.
35
36use hydro_core::{Forcing, HydroModel};
37use serde::{Deserialize, Serialize};
38
39/// API-CONT model parameters (3 scalars).
40///
41/// All three fields implement `Default` (via the struct-level impl) so the
42/// model can be constructed with `ApicontParams::default()` for a quick smoke
43/// run; real basins should override at least `area_km2`.
44///
45/// | Field | Unit | Meaning | Typical range |
46/// |------------|------|-----------------------------------------------|---------------|
47/// | `k` | — | Storage retention coefficient (`0.50–0.95`) | 0.85 |
48/// | `cs` | — | Routing linear-reservoir recession | 0.10–0.50 |
49/// | `area_km2` | km² | Basin area (mm/Δt → m³/s conversion) | basin-specific|
50#[derive(Clone, Debug, Serialize, Deserialize)]
51pub struct ApicontParams {
52 /// Storage retention coefficient `k` (dimensionless).
53 ///
54 /// Fraction of the antecedent store `sm` retained each step; the remainder
55 /// `(1 − k) · sm` drains as runoff. **Range 0.50–0.95**: higher = longer
56 /// memory and slower recession (the essence of the API exponential-decay
57 /// signature). Default `0.85`.
58 pub k: f64,
59
60 /// Routing recession coefficient `cs` (dimensionless, linear reservoir).
61 ///
62 /// Smoothing factor applied to the drained water on its way to the outlet:
63 /// `Q ← cs · Q + (1 − cs) · q_raw`. **Range 0.10–0.50**: higher = more
64 /// smoothing / longer lag. Default `0.25`.
65 pub cs: f64,
66
67 /// Basin area in km². Used to convert depth (mm per `dt_h`) into discharge
68 /// (m³/s) via `mm_to_m3s(mm, area_km2, dt_h)`. Basin-specific.
69 pub area_km2: f64,
70}
71
72impl Default for ApicontParams {
73 /// Sane defaults for a 1000 km² basin: `k = 0.85`, `cs = 0.25`.
74 fn default() -> Self {
75 Self { k: 0.85, cs: 0.25, area_km2: 1000.0 }
76 }
77}
78
79/// API-CONT continuous baseline model — single linear antecedent store +
80/// linear-reservoir routing.
81///
82/// Construct with [`ApicontModel::new`] from an [`ApicontParams`], then drive
83/// it step-by-step through the [`HydroModel`] trait (`step` → `discharge`).
84/// Internal state is the antecedent storage `sm` (mm) and the routed outlet
85/// discharge `Q` (m³/s). Use [`ApicontModel::reset`] to return to a dry store.
86///
87/// Implements the [`hydro_core::HydroModel`] / [`hydro_core::DynHydroModel`]
88/// traits, so it slots into `hydro-platform` scenario orchestration alongside
89/// the Xinanjiang / TOPMODEL / SWAT+ LTE models.
90pub struct ApicontModel {
91 params: ApicontParams,
92 sm: f64, // 前期降水蓄水量(mm)
93 discharge: f64,
94}
95
96/// Convert a depth in mm over a basin of `area_km2` in `dt_h` hours into m³/s.
97///
98/// `mm · area_km2 · 1000 / (dt_h · 3600)`. Private — used only by
99/// [`ApicontModel::step`].
100fn mm_to_m3s(mm: f64, area_km2: f64, dt_h: f64) -> f64 {
101 mm * area_km2 * 1000.0 / (dt_h * 3600.0)
102}
103
104impl HydroModel for ApicontModel {
105 type Params = ApicontParams;
106
107 /// Build a fresh model with an empty antecedent store (`sm = 0`) and zero
108 /// outlet discharge.
109 fn new(params: Self::Params) -> Self {
110 Self { params, sm: 0.0, discharge: 0.0 }
111 }
112
113 /// Advance one step of length `dt_h` (hours).
114 ///
115 /// Enforces strict mass balance `P = ea + drain + Δsm`:
116 /// fill → ET (`ea = min(PET, sm)`) → exponential API drain
117 /// (`drain = (1 − k) · sm`) → linear-reservoir routing
118 /// (`Q ← cs · Q + (1 − cs) · mm_to_m3s(drain, ...)`).
119 fn step(&mut self, f: &Forcing, dt_h: f64) {
120 let p = &self.params;
121 let rain = f.p_mm.max(0.0);
122 let pet = f.pet_mm.max(0.0);
123 // 蓄水填充
124 self.sm += rain;
125 // 蒸发(不超过蓄水)
126 let ea = pet.min(self.sm);
127 self.sm -= ea;
128 // 指数退水排出为径流(API 记忆)
129 let drain = (1.0 - p.k) * self.sm;
130 self.sm -= drain;
131 // 线性水库汇流
132 let q_raw = mm_to_m3s(drain, p.area_km2, dt_h);
133 self.discharge = self.discharge * p.cs + q_raw * (1.0 - p.cs);
134 }
135
136 /// Current outlet discharge (m³/s).
137 fn discharge(&self) -> f64 { self.discharge }
138
139 /// Snapshot of the internal state as `{ "sm": <mm> }`.
140 fn state(&self) -> serde_json::Value {
141 serde_json::json!({ "sm": self.sm })
142 }
143
144 /// Reset the store and discharge to zero (a dry, pre-storm initial
145 /// condition).
146 fn reset(&mut self) { self.sm = 0.0; self.discharge = 0.0; }
147
148 /// Static model name — `"API-CONT"`.
149 fn name(&self) -> &'static str { "API-CONT" }
150
151 /// Shared reference to the parameter struct.
152 fn params(&self) -> &Self::Params { &self.params }
153
154 /// Exclusive reference to the parameter struct (for online updates).
155 fn params_mut(&mut self) -> &mut Self::Params { &mut self.params }
156}
157
158#[cfg(test)]
159mod tests {
160 use super::*;
161
162 #[test]
163 fn rain_produces_flow() {
164 let mut m = ApicontModel::new(ApicontParams::default());
165 for _ in 0..10 { m.step(&Forcing { p_mm: 30.0, pet_mm: 0.0, t_c: 20.0 }, 1.0); }
166 assert!(m.discharge > 0.0);
167 }
168
169 #[test]
170 fn drought_recedes() {
171 let mut m = ApicontModel::new(ApicontParams::default());
172 for _ in 0..5 { m.step(&Forcing { p_mm: 50.0, pet_mm: 0.0, t_c: 20.0 }, 1.0); }
173 let peak = m.discharge;
174 for _ in 0..100 { m.step(&Forcing { p_mm: 0.0, pet_mm: 5.0, t_c: 25.0 }, 1.0); }
175 assert!(m.discharge < peak);
176 assert!(m.discharge < 5.0, "应退到低值, got {}", m.discharge);
177 }
178
179 /// 蓄水指数退水:断雨断蒸时 sm 按 k 几何衰减(drain=(1−k)·sm → sm ← k·sm)。
180 #[test]
181 fn store_decays_geometrically() {
182 let mut m = ApicontModel::new(ApicontParams::default());
183 m.sm = 100.0;
184 m.step(&Forcing { p_mm: 0.0, pet_mm: 0.0, t_c: 20.0 }, 1.0);
185 assert!((m.sm - 85.0).abs() < 1e-9, "sm=0.85·100=85, got {}", m.sm);
186 }
187
188 /// 水量守恒上界:累计出流(mm)≤ 累计降雨(杜绝质量凭空)。
189 #[test]
190 fn no_mass_creation_constant_rain() {
191 let params = ApicontParams::default();
192 let area = params.area_km2;
193 let mut m = ApicontModel::new(params);
194 let rain = 5.0;
195 let n = 200;
196 let mut sum_q_mm = 0.0;
197 for _ in 0..n {
198 m.step(&Forcing { p_mm: rain, pet_mm: 0.0, t_c: 20.0 }, 1.0);
199 sum_q_mm += m.discharge * 1.0 * 3.6 / area;
200 }
201 let sum_rain = rain * n as f64;
202 assert!(sum_q_mm <= sum_rain * 1.001, "出流>降雨(质量凭空):{:.1}>{:.1}", sum_q_mm, sum_rain);
203 }
204
205 #[test]
206 fn dyn_dispatch() {
207 let mut m: Box<dyn hydro_core::DynHydroModel> =
208 Box::new(ApicontModel::new(ApicontParams::default()));
209 m.step(&Forcing { p_mm: 50.0, pet_mm: 0.0, t_c: 20.0 }, 1.0);
210 assert!(m.discharge() >= 0.0);
211 assert_eq!(m.name(), "API-CONT");
212 }
213}