hydro_topmodel/lib.rs
1//! TOPMODEL(Beven & Kirkby 1979;1995 Fortran 版)——忠实分布式实现。
2//!
3//! Clean-room 从 R `topmodel` 包 v0.7.5 的 C 数值核心(`core_topmodel.c`/`get_f.c`/
4//! `param_init.c`/`misc.c`)移植:算法(Beven 公式)不可版权,C 源仅作行为 oracle。
5//! 11 参数 + TWI 直方图 + 河道延迟;单位 mm / hour(与 R 参考一致,便于 bit-exact 校验)。
6//! 交叉验证:`tests/topmodel_crosscheck.rs`(待加)vs R `topmodel` on huagrahuma 数据集。
7//!
8//! 关键方程(eq 号同 Beven HESS 2021 / R 源注释):
9//! - 基流退水 `qs = qss·exp(-S_mean/m)`(eq 6.33),`qss = exp(lnTe + ln(dt) - λ)`
10//! - 局部亏缺 `S[j] = S_mean + m·(λ - atb[j])`(eq 18.8)
11//! - 非饱和排水 `qv = Suz/(S·td)·dt`(eq 6.26)
12//! - 下渗 Green-Ampt/Morel-Seytoux(Newton-Raphson,`get_f`)
13//! - 路由:河道延迟 `Qt[k] += qt·Ad[j]`,k = i + j + ndelay
14//!
15//! # English summary
16//!
17//! TOPMODEL (Beven & Kirkby 1979; 1995 Fortran release) — faithful distributed
18//! implementation. Hydrological quantities are kept in mm per hour to match the
19//! R reference numerically and enable bit-exact regression.
20//!
21//! **Clean-room statement:** this Rust implementation is a clean-room port of
22//! the C numerical core of the R [`topmodel`] package v0.7.5
23//! (`core_topmodel.c` / `get_f.c` / `param_init.c` / `misc.c`). The underlying
24//! algorithm (Beven's published equations) is not copyrightable; the C source
25//! was used only as a behaviour oracle for cross-verification. No R/C source
26//! code is reproduced here.
27//!
28//! [`topmodel`]: https://cran.r-project.org/package=topmodel
29//!
30//! The model takes 11 scalar parameters plus a topographic wetness index (TWI)
31//! histogram and an optional channel-delay histogram, and produces per-step
32//! output series (outflow, baseflow, saturation-excess runoff, mean saturation
33//! deficit, infiltration, infiltration excess, actual ET).
34//!
35//! Key equations (equation numbers follow Beven, *Hydrological Processes*
36//! / R source comments):
37//! - Baseflow recession `qs = qss · exp(−S_mean / m)` (eq 6.33), where
38//! `qss = exp(lnTe + ln(dt) − λ)`.
39//! - Local deficit `S[j] = S_mean + m · (λ − atb[j])` (eq 18.8).
40//! - Unsaturated drainage `qv = Suz / (S · td) · dt` (eq 6.26).
41//! - Infiltration: Green–Ampt / Morel-Seytoux solved by Newton-Raphson
42//! (the crate-internal `Infiltration::get_f`).
43//! - Routing: channel delay `Qt[k] += qt · Ad[j]`, with `k = i + j + ndelay`.
44//!
45//! Cross-verification: `tests/topmodel_crosscheck.rs` against R `topmodel` on
46//! the **huagrahuma** dataset (available from the R `topmodel` package).
47//!
48//! Implements [`hydro_core::HydroModel`] so the model can be orchestrated by
49//! `hydro-platform`. With default parameters the model degrades to a lumped
50//! single-TWI-class configuration; supply a real `topidx` histogram for
51//! distributed runs.
52
53// Lint suppressions: struct/field names (qs0, lnTe, Sr0, Srmax, K0, CD, S_mean,
54// Aatb_r, Ad_r, Qt, Ea, ...) intentionally match the R `topmodel` v0.7.5 C-core
55// identifiers used by the bit-exact crosscheck in tests/topmodel_crosscheck.rs;
56// renaming would break the oracle alignment and the public API.
57#![allow(non_snake_case, unused_variables, unused_assignments)]
58
59use hydro_core::{Forcing, HydroModel};
60use serde::{Deserialize, Serialize};
61
62const ZERO: f64 = 0.0000001;
63
64// ── 流域几何(TWI 直方图 + 河道延迟)──
65
66/// TWI (topographic wetness index) histogram, the distributed input that
67/// partitions the basin into saturation classes.
68///
69/// Chinese: TWI 直方图 —— `atb` = ln(a/tanβ) 值(**降序**),`Aatb_r` = 累积面积比例(到该类下限)。
70#[derive(Clone, Debug, Serialize, Deserialize, Default)]
71pub struct TopidxHistogram {
72 /// `ln(a/tanβ)` values for each TWI class, sorted in **descending** order
73 /// (highest wetness first). Required for the local-deficit equation
74 /// `S[j] = S_mean + m·(λ − atb[j])` (Beven eq 18.8) to produce physically
75 /// ordered saturation states.
76 pub atb: Vec<f64>,
77 /// Cumulative area fraction at the lower bound of each class (i.e. the
78 /// fraction of the basin with TWI ≥ `atb[i]`). Values run from the first
79 /// class fraction up to 1.0; differences between adjacent entries give the
80 /// per-class area weights used inside [`run_topmodel_full`].
81 pub Aatb_r: Vec<f64>,
82}
83
84/// Channel-delay histogram describing how long it takes water to travel to the
85/// outlet from each distance class.
86///
87/// Chinese: 河道延迟 —— `d` = 河道距离(增序),`Ad_r` = 对应累积面积比例。
88#[derive(Clone, Debug, Serialize, Deserialize, Default)]
89pub struct ChannelDelay {
90 /// Channel distances (m) in **ascending** order, one entry per reach
91 /// class. Combined with the wave velocities `vch` / `vr` in
92 /// [`TopmodelParams`] to compute travel times `tch[i]`.
93 pub d: Vec<f64>,
94 /// Cumulative drained-area fraction corresponding to each distance class
95 /// (`Ad_r[i]` = fraction of basin area within channel distance `d[i]` of
96 /// the outlet). Used to build the per-reach area weights `Ad` that
97 /// distribute each step's lateral inflow `qt` across the delay lags.
98 pub Ad_r: Vec<f64>,
99}
100
101/// TOPMODEL parameters: 11 scalar model parameters plus the basin TWI
102/// histogram, the optional channel-delay histogram, and the basin area used
103/// to convert mm/Δt to m³/s.
104///
105/// Defaults give a lumped configuration (single TWI class at `atb = 0`,
106/// `Aatb_r = 1.0`); this is what [`TopmodelModel::new`] uses out of the box
107/// and what the [`run_topmodel_full`] regression tests assume. Real distributed
108/// runs require a real `topidx` histogram (and usually a `channel` delay
109/// histogram) computed from the basin DEM.
110///
111/// Chinese: TOPMODEL 11 参数 + 流域几何。默认值退化成集总(单 TWI 类),供平台多模型
112/// 对比;真实分布式运行必须提供 `topidx`(通常还需 `channel`)。
113#[derive(Clone, Debug, Serialize, Deserialize)]
114pub struct TopmodelParams {
115 /// Initial baseflow per unit area (`qs0`, m/h). Combined with `qss`
116 /// (derived from `lnTe`, `dt`, `λ`) to seed `S_mean[0] = −m · ln(qs0·dt / qss)`
117 /// in [`run_topmodel_full`]. Drives the eq 6.33 baseflow recession
118 /// `qs = qss · exp(−S_mean / m)` throughout the run.
119 pub qs0: f64,
120 /// Areal average of `ln(T₀)` (effective saturated transmissivity at soil
121 /// saturation, m²/h). Enters `qss = exp(lnTe + ln(dt) − λ)` and therefore
122 /// the baseflow recession magnitude.
123 pub lnTe: f64,
124 /// Exponential recession parameter (m). Controls how fast baseflow decays
125 /// as the basin-mean saturation deficit `S_mean` grows; appears as the
126 /// `1/m` scale in eq 6.33 and as the spatial redistribution slope in the
127 /// local-deficit equation eq 18.8.
128 pub m: f64,
129 /// Initial root-zone storage deficit (m). Per-class root-zone state
130 /// `srz[j]` is initialised to `Sr0` and then depleted by infiltration
131 /// before excess water reaches the unsaturated store `suz[j]`.
132 pub Sr0: f64,
133 /// Maximum root-zone storage deficit (m). Bounds the per-class `srz[j]`
134 /// state and limits actual ET (`Ea` extraction stops when `srz[j]`
135 /// reaches `Srmax`).
136 pub Srmax: f64,
137 /// Unsaturated-zone time delay per unit deficit (h/m). Scales the
138 /// unsaturated drainage `qv = suz[j] / (s · td) · dt` (eq 6.26): larger
139 /// `td` → slower drainage from `suz` into the saturated store.
140 pub td: f64,
141 /// Channel wave velocity (m/h). Used in [`ChannelDelay`] routing to set
142 /// the time to the outlet of the first reach, `tch[0] = d[0] / (vch·dt)`.
143 pub vch: f64,
144 /// Overland / hillslope wave velocity (m/h). Used for reaches beyond the
145 /// first: `tch[i] = tch[0] + (d[i] − d[0]) / (vr·dt)`.
146 pub vr: f64,
147 /// Saturated hydraulic conductivity `K₀` (m/h). Enters the Green–Ampt /
148 /// Morel-Seytoux infiltration solved by Newton-Raphson inside the model.
149 pub K0: f64,
150 /// Capillary drive `CD` (m) at the wetting front. Surface-water depth
151 /// head parameter used by the infiltration solver together with `K₀` and
152 /// `m`.
153 pub CD: f64,
154 /// Time step `dt` (h). TOPMODEL's internal time step; the same value is
155 /// used for infiltration, baseflow recession, unsaturated drainage and
156 /// routing. When run via [`TopmodelModel::step`], the caller-supplied
157 /// `dt_h` is used only for the mm/Δt → m³/s conversion.
158 pub dt: f64,
159 /// Optional basin TWI histogram. `None` (or a single-class `[0.0]`/`[1.0]`
160 /// histogram) degrades the model to a lumped single-class configuration.
161 /// Real distributed runs must supply a real histogram from a DEM.
162 #[serde(default)]
163 pub topidx: Option<TopidxHistogram>,
164 /// Optional channel-delay histogram. `None` produces instant outflow
165 /// (each step's lateral inflow `qt` is added to `Qt[i]` directly); a
166 /// populated histogram routes `qt` across lags via the kinematic
167 /// wave-velocity scheme described under [`ChannelDelay`].
168 #[serde(default)]
169 pub channel: Option<ChannelDelay>,
170 /// Basin area (km²). Used only by the [`TopmodelModel`] wrapper to convert
171 /// the model's mm-per-step output into outlet discharge (m³/s) via
172 /// `Q = mm · area_km2 / (dt_h · 3.6)`. Does not affect `run_topmodel_full`
173 /// output, which stays in mm.
174 #[serde(default = "default_area")]
175 pub area_km2: f64,
176}
177
178fn default_area() -> f64 { 1000.0 }
179
180impl Default for TopmodelParams {
181 fn default() -> Self {
182 // 默认:单类 TWI 直方图(集总退化,供平台多模型对比;真实运行需提供 topidx)。
183 Self {
184 qs0: 0.001, lnTe: 5.0, m: 0.01, Sr0: 0.0, Srmax: 0.05,
185 td: 30.0, vch: 100.0, vr: 100.0, K0: 3.0, CD: 1.0, dt: 1.0,
186 topidx: Some(TopidxHistogram { atb: vec![0.0], Aatb_r: vec![1.0] }),
187 channel: None,
188 area_km2: 1000.0,
189 }
190 }
191}
192
193/// Full per-step output of [`run_topmodel_full`], all in mm per `dt` step.
194/// Each `Vec` has one entry per input time step, suitable for direct
195/// variable-by-variable comparison against the R `topmodel` oracle.
196///
197/// Chinese: 完整运行输出(逐时步序列,mm;供 oracle 逐变量比对)。
198#[derive(Clone, Debug, Default)]
199pub struct TopmodelOutput {
200 /// Total outlet outflow after routing (mm per step). This is the routed
201 /// quantity `Qt[k]` summed over contributing reaches.
202 pub Qt: Vec<f64>,
203 /// Baseflow `qs = qss · exp(−S_mean / m)` (Beven eq 6.33), per step.
204 pub qs: Vec<f64>,
205 /// Surface runoff (mm per step): saturation-excess return flow plus
206 /// infiltration excess `fex`.
207 pub qo: Vec<f64>,
208 /// Basin-mean saturation deficit `S_mean` (mm). Drives the eq 6.33
209 /// baseflow recession; updated each step as `S_mean += qs − qv_total`.
210 pub S_mean: Vec<f64>,
211 /// Infiltration `f` (mm per step) from the Green–Ampt / Morel-Seytoux
212 /// solver. Goes into the root-zone store first; any excess fills the
213 /// unsaturated store `suz`.
214 pub f: Vec<f64>,
215 /// Infiltration excess `fex = rain − f` (mm per step). Becomes direct
216 /// surface runoff (Hortonian) and is added into `qo`.
217 pub fex: Vec<f64>,
218 /// Area-mean actual evapotranspiration `Ea` (mm per step), extracted from
219 /// the root-zone store with reduction `Ea = PET · (1 − srz/Srmax)`.
220 pub Ea: Vec<f64>,
221}
222
223// ── 下渗:Green-Ampt/Morel-Seytoux(Newton-Raphson;跨时步状态)──
224
225/// 下渗计算器(对应 get_f.c 的 static 变量 cumf/f_/pt/cnst/ponding)。
226#[derive(Clone)]
227struct Infiltration {
228 cumf: f64,
229 f_: f64,
230 pt: f64,
231 cnst: f64,
232 ponding: bool,
233}
234
235impl Infiltration {
236 fn new() -> Self {
237 Self { cumf: 0.0, f_: 0.0, pt: 0.0, cnst: 0.0, ponding: false }
238 }
239 fn reset(&mut self) {
240 self.cumf = 0.0; self.f_ = 0.0; self.pt = 0.0; self.cnst = 0.0; self.ponding = false;
241 }
242
243 /// 对应 get_f(t, R, C, K0, m, dt)。R = 雨强 [m/h],t = 累计时间 [h]。
244 fn get_f(&mut self, t: f64, r: f64, c: f64, k0: f64, m: f64, dt: f64) -> f64 {
245 const TOLERANCE: f64 = 0.00001;
246 const MAXITER: usize = 2000;
247 const NTERMS: usize = 10;
248
249 if t / dt == 1.0 {
250 self.reset();
251 }
252 if r <= 0.0 {
253 self.cumf = 0.0; self.ponding = false; self.f_ = 0.0; self.pt = 0.0;
254 return 0.0;
255 }
256
257 let mut f1 = 0.0;
258 if !self.ponding {
259 if self.cumf > 0.0 {
260 f1 = self.cumf;
261 let mut r2 = -k0 / m * (c + f1) / (1.0 - (f1 / m).exp());
262 if r > r2 {
263 self.f_ = self.cumf;
264 self.pt = t - dt;
265 self.ponding = true;
266 // goto cont1
267 self.cnst = Self::compute_cnst(self.f_, c, m);
268 self.f_ += r * (t - self.pt) / 2.0;
269 // fall through to Newton-Raphson below
270 } else {
271 // no ponding path continues below
272 let f2 = self.cumf + r * dt;
273 r2 = -k0 / m * (c + f2) / (1.0 - (f2 / m).exp());
274 if f2 == 0.0 || r < r2 {
275 let f = r;
276 self.cumf += f * dt;
277 self.ponding = false;
278 return f;
279 }
280 self.f_ = self.cumf + r2 * dt;
281 let mut f2m = f2;
282 let mut f1m = f1;
283 let mut i = 0;
284 while i < MAXITER {
285 r2 = -k0 / m * (c + self.f_) / (1.0 - (self.f_ / m).exp());
286 let diff;
287 if r2 > r {
288 f1m = self.f_;
289 self.f_ = (self.f_ + f2m) / 2.0;
290 diff = self.f_ - f1m;
291 } else {
292 f2m = self.f_;
293 self.f_ = (self.f_ + f1m) / 2.0;
294 diff = self.f_ - f2m;
295 }
296 if diff.abs() < TOLERANCE { break; }
297 i += 1;
298 }
299 if i == MAXITER { return -9999.0; }
300 self.pt = t - dt + (self.f_ - self.cumf) / r;
301 if self.pt > t {
302 let f = r;
303 self.cumf += f * dt;
304 self.ponding = false;
305 return f;
306 }
307 self.cnst = Self::compute_cnst(self.f_, c, m);
308 self.f_ += r * (t - self.pt) / 2.0;
309 self.ponding = true;
310 }
311 } else {
312 // cumf == 0 path
313 let f2 = self.cumf + r * dt;
314 let r2 = -k0 / m * (c + f2) / (1.0 - (f2 / m).exp());
315 if f2 == 0.0 || r < r2 {
316 let f = r;
317 self.cumf += f * dt;
318 self.ponding = false;
319 return f;
320 }
321 self.f_ = self.cumf + r2 * dt;
322 let mut f2m = f2;
323 let mut f1m = f1;
324 let mut i = 0;
325 while i < MAXITER {
326 let r2 = -k0 / m * (c + self.f_) / (1.0 - (self.f_ / m).exp());
327 let diff;
328 if r2 > r {
329 f1m = self.f_;
330 self.f_ = (self.f_ + f2m) / 2.0;
331 diff = self.f_ - f1m;
332 } else {
333 f2m = self.f_;
334 self.f_ = (self.f_ + f1m) / 2.0;
335 diff = self.f_ - f2m;
336 }
337 if diff.abs() < TOLERANCE { break; }
338 i += 1;
339 }
340 if i == MAXITER { return -9999.0; }
341 self.pt = t - dt + (self.f_ - self.cumf) / r;
342 if self.pt > t {
343 let f = r;
344 self.cumf += f * dt;
345 self.ponding = false;
346 return f;
347 }
348 self.cnst = Self::compute_cnst(self.f_, c, m);
349 self.f_ += r * (t - self.pt) / 2.0;
350 self.ponding = true;
351 }
352 }
353
354 // Newton-Raphson(ponding 发生后)
355 let mut i = 0;
356 while i < MAXITER {
357 let fc = self.f_ + c;
358 let mut sum = 0.0;
359 let mut factorial = 1.0;
360 for j in 1..=NTERMS {
361 factorial *= j as f64;
362 sum += (fc / m).powi(j as i32) / (j as f64 * factorial);
363 }
364 let g1 = -((fc.ln() - (fc.ln() + sum) / (c / m).exp() - self.cnst) / (k0 / m)) - (t - self.pt);
365 let g2 = ((self.f_ / m).exp() - 1.0) / (fc * k0 / m);
366 let diff = -g1 / g2;
367 self.f_ += diff;
368 if diff.abs() < TOLERANCE { break; }
369 i += 1;
370 }
371 if i == MAXITER { return -9999.0; }
372
373 if self.f_ - self.cumf < r * dt {
374 let f = (self.f_ - self.cumf) / dt;
375 self.cumf = self.f_;
376 self.f_ += f * dt;
377 f
378 } else {
379 let f = r;
380 self.cumf += f * dt;
381 self.ponding = false;
382 self.pt = 0.0;
383 f
384 }
385 }
386}
387
388impl Infiltration {
389 fn compute_cnst(f_: f64, c: f64, m: f64) -> f64 {
390 const NTERMS: usize = 10;
391 let fc = f_ + c;
392 let mut cnst = 0.0;
393 let mut factorial = 1.0;
394 for j in 1..=NTERMS {
395 factorial *= j as f64;
396 cnst += (fc / m).powi(j as i32) / (j as f64 * factorial);
397 }
398 fc.ln() - (fc.ln() + cnst) / (c / m).exp()
399 }
400}
401
402// ── 派生量:λ(地形指数面平均)+ Ad(河道延迟面积分布)──
403
404/// λ = areal integral of ln(a/tanβ) = Σ Aatb_r[i]·(atb[i]+atb[i-1])/2(对应 get_lambda)。
405fn get_lambda(atb: &[f64], aatb_r: &[f64]) -> f64 {
406 let n = atb.len().min(aatb_r.len());
407 let mut ret = 0.0;
408 for i in 1..n {
409 ret += aatb_r[i] * (atb[i] + atb[i - 1]) / 2.0;
410 }
411 ret
412}
413
414/// 河道延迟 → (tch, ndelay, nreach, Ad)。对应 get_Ad。
415fn compute_ad(d: &[f64], ad_r: &[f64], vch_dt: f64, vr_dt: f64) -> (Vec<f64>, usize, usize, Vec<f64>) {
416 let nch = d.len().min(ad_r.len());
417 if nch == 0 {
418 return (Vec::new(), 0, 0, Vec::new());
419 }
420 let mut tch = vec![0.0; nch];
421 tch[0] = d[0] / vch_dt;
422 for i in 1..nch {
423 tch[i] = tch[0] + (d[i] - d[0]) / vr_dt;
424 }
425 let mut nreach = tch[nch - 1] as usize;
426 if (nreach as f64) < tch[nch - 1] { nreach += 1; }
427 let ndelay = tch[0] as usize;
428 nreach = nreach.saturating_sub(ndelay);
429 if nreach == 0 {
430 return (tch, ndelay, 0, Vec::new());
431 }
432 let mut ad = vec![0.0; nreach];
433 for i in 0..nreach {
434 let t = (ndelay + i + 1) as f64;
435 if t > tch[nch - 1] {
436 ad[i] = 1.0;
437 } else {
438 for j in 1..nch {
439 if t <= tch[j] {
440 ad[i] = ad_r[j - 1] + (ad_r[j] - ad_r[j - 1]) * (t - tch[j - 1]) / (tch[j] - tch[j - 1]);
441 break;
442 }
443 }
444 }
445 }
446 // 差分:累积 → 单步
447 let mut a1 = ad[0];
448 for i in 1..nreach {
449 let a2 = ad[i];
450 ad[i] = a2 - a1;
451 a1 = a2;
452 }
453 (tch, ndelay, nreach, ad)
454}
455
456// ── 派生状态(对应 param_init)──
457
458struct Derived {
459 lambda: f64,
460 qss: f64,
461 ndelay: usize,
462 nreach: usize,
463 ad: Vec<f64>,
464 nidxclass: usize,
465 atb: Vec<f64>,
466 aatb_r: Vec<f64>,
467}
468
469impl Derived {
470 fn from_params(p: &TopmodelParams) -> Self {
471 let (atb, aatb_r) = match &p.topidx {
472 Some(h) if !h.atb.is_empty() => (h.atb.clone(), h.Aatb_r.clone()),
473 _ => (vec![0.0], vec![1.0]),
474 };
475 let nidxclass = atb.len();
476 let lambda = get_lambda(&atb, &aatb_r);
477 let ln_te_dt = p.lnTe + p.dt.ln();
478 let qss = (ln_te_dt - lambda).exp();
479 let (ndelay, nreach, ad) = match &p.channel {
480 Some(ch) if !ch.d.is_empty() => {
481 let vch_dt = p.vch * p.dt;
482 let vr_dt = p.vr * p.dt;
483 let (_tch, nd, nr, ad) = compute_ad(&ch.d, &ch.Ad_r, vch_dt, vr_dt);
484 (nd, nr, ad)
485 }
486 _ => (0, 0, Vec::new()),
487 };
488 Self { lambda, qss, ndelay, nreach, ad, nidxclass, atb, aatb_r }
489 }
490}
491
492// ── 忠实批量核心:run_topmodel_full(供 oracle 比对)──
493
494/// Run the full TOPMODEL loop step-by-step, mirroring the R `topmodel` run
495/// sequence (`param_init` → per-step production + routing). All inputs and
496/// outputs are in mm per `dt` step so the result can be compared
497/// variable-by-variable against the R reference.
498///
499/// Per step the function runs: Green–Ampt infiltration (`get_f`), eq 6.33
500/// baseflow recession, eq 18.8 local-deficit saturation-excess production,
501/// eq 6.26 unsaturated drainage, root-zone actual ET, and finally the
502/// kinematic channel routing that distributes each step's lateral inflow
503/// `qt = qs + qo` across the delay lags defined by the channel histogram.
504///
505/// Use this function (rather than the [`TopmodelModel`] trait wrapper) for
506/// oracle-verified regression: the wrapper adds an mm → m³/s conversion.
507///
508/// Chinese: 完整运行 TOPMODEL(逐时步循环,对应 R 的 run_topmodel 调用序列)。
509/// 输入:参数 + 雨量(mm/时步)+ ETp(mm/时步);输出:全序列(mm)。
510pub fn run_topmodel_full(p: &TopmodelParams, rain: &[f64], etp: &[f64]) -> TopmodelOutput {
511 let n = rain.len().max(etp.len());
512 let d = Derived::from_params(p);
513 let qs0_dt = p.qs0 * p.dt;
514
515 let mut out = TopmodelOutput {
516 Qt: vec![0.0; n], qs: vec![0.0; n], qo: vec![0.0; n],
517 S_mean: vec![0.0; n], f: vec![0.0; n], fex: vec![0.0; n], Ea: vec![0.0; n],
518 };
519 let mut srz = vec![p.Sr0; d.nidxclass]; // 根区亏缺
520 let mut suz = vec![0.0; d.nidxclass]; // 非饱和蓄水
521 let mut infl = Infiltration::new();
522
523 // S_mean[0] = -m·log(qs0_dt/qss)(对应 param_init)
524 out.S_mean[0] = if d.qss > 0.0 && qs0_dt > 0.0 {
525 -p.m * (qs0_dt / d.qss).ln()
526 } else { 0.0 };
527
528 // Qt 初值(对应 param_init):Qt[0..ndelay]=qs0;reach 段退水 qs0·(1-ΣAd)
529 for i in 0..n.min(d.ndelay) {
530 out.Qt[i] = qs0_dt;
531 }
532 {
533 let mut a = 0.0;
534 for i in 0..d.nreach {
535 a += d.ad[i];
536 let k = d.ndelay + i;
537 if k < n { out.Qt[k] = qs0_dt * (1.0 - a); }
538 }
539 }
540
541 for i in 0..n {
542 let r = rain.get(i).copied().unwrap_or(0.0);
543 let e = etp.get(i).copied().unwrap_or(0.0);
544
545 // 下渗 + 超渗
546 let t = (i as f64 + 1.0) * p.dt;
547 let mut fi = p.dt * infl.get_f(t, r / p.dt, p.CD, p.K0, p.m, p.dt);
548 if fi < 0.0 { fi = r; }
549 out.f[i] = fi;
550 out.fex[i] = r - fi;
551
552 // 基流
553 out.qs[i] = d.qss * (-out.S_mean[i] / p.m).exp();
554
555 let mut qo_total = 0.0;
556 let mut qv_total = 0.0;
557 let mut ea_total = 0.0;
558 let mut ex_prev = 0.0;
559
560 for j in 0..d.nidxclass {
561 let aatb_local = (d.aatb_r[j]
562 + if j < d.nidxclass - 1 { d.aatb_r[j + 1] } else { 0.0 }) / 2.0;
563
564 // 局部亏缺 eq 18.8
565 let mut s = out.S_mean[i] + p.m * (d.lambda - d.atb[j]);
566 if s < 0.0 { s = 0.0; }
567
568 // 根区:雨进根区(亏减少),溢出补非饱和
569 srz[j] -= fi;
570 if srz[j] < 0.0 {
571 suz[j] -= srz[j];
572 srz[j] = 0.0;
573 }
574
575 // 饱和溢流 ex(Suz 超过 S)
576 let mut ex = 0.0;
577 if suz[j] > s {
578 ex = suz[j] - s;
579 suz[j] = s;
580 }
581
582 // 非饱和排水 eq 6.26
583 let mut qv = 0.0;
584 if s > 0.0 {
585 qv = suz[j] / (s * p.td) * p.dt;
586 if qv > suz[j] { qv = suz[j]; }
587 suz[j] -= qv;
588 if suz[j] < ZERO { suz[j] = 0.0; }
589 qv *= aatb_local;
590 }
591 qv_total += qv;
592
593 // ET eq 6.27(从根区抽取,亏缺增加)
594 let mut ea = 0.0;
595 if e > 0.0 {
596 ea = e * (1.0 - srz[j] / p.Srmax);
597 if ea > p.Srmax - srz[j] { ea = p.Srmax - srz[j]; }
598 }
599 srz[j] += ea;
600 ea_total += aatb_local * ea;
601
602 // 饱和面产流 qo(相邻类 ex;分支1用原始 Aatb_r[j],分支2用 local)
603 if j > 0 {
604 let qo = if ex > 0.0 {
605 d.aatb_r[j] * (ex_prev + ex) / 2.0
606 } else if ex_prev > 0.0 {
607 aatb_local * ex_prev / (ex_prev - ex) * ex_prev / 2.0
608 } else { 0.0 };
609 qo_total += qo;
610 }
611 ex_prev = ex;
612 }
613
614 out.qo[i] = qo_total + out.fex[i];
615 let qt = out.qo[i] + out.qs[i];
616
617 // S_mean 更新(qs 出、qv 入)
618 out.S_mean[i] += out.qs[i] - qv_total;
619 if i + 1 < n { out.S_mean[i + 1] = out.S_mean[i]; }
620 out.Ea[i] = ea_total;
621
622 // 路由:Qt[k] += qt·Ad[j]
623 if d.nreach > 0 {
624 for j in 0..d.nreach {
625 let k = i + j + d.ndelay;
626 if k > n - 1 { break; }
627 out.Qt[k] += qt * d.ad[j];
628 }
629 } else {
630 // 无河道延迟:即时出流
631 out.Qt[i] += qt;
632 }
633 }
634 out
635}
636
637
638// ── HydroModel trait 包装(平台集成;逐时步)──
639
640/// [`hydro_core::HydroModel`] wrapper that runs TOPMODEL one step at a time.
641///
642/// Construct with [`TopmodelModel::new`] from a [`TopmodelParams`] value; each
643/// call to [`HydroModel::step`] advances the
644/// internal state (per-class root-zone deficit `srz`, unsaturated store `suz`,
645/// the Green–Ampt infiltration solver, the basin-mean saturation deficit
646/// `S_mean`, and a routed outflow buffer) and updates the outlet discharge
647/// in m³/s returned by [`HydroModel::discharge`].
648///
649/// The same parameters can be run in batch via [`run_topmodel_full`] to
650/// inspect the per-step internal variables in mm (no mm → m³/s conversion).
651/// Default parameters (single TWI class at `atb = 0`) give a lumped run; for
652/// a real distributed run supply a populated `topidx` (and usually `channel`).
653///
654/// [`HydroModel`]: hydro_core::HydroModel
655pub struct TopmodelModel {
656 params: TopmodelParams,
657 derived: Derived,
658 srz: Vec<f64>,
659 suz: Vec<f64>,
660 infl: Infiltration,
661 s_mean: f64,
662 qt_buf: Vec<f64>, // 路由缓冲(Qt[i])
663 step_i: usize,
664 discharge_m3s: f64,
665}
666
667fn mm_to_m3s(mm: f64, area_km2: f64, dt_h: f64) -> f64 {
668 mm * area_km2 / (dt_h * 3.6)
669}
670
671impl HydroModel for TopmodelModel {
672 type Params = TopmodelParams;
673
674 fn new(params: Self::Params) -> Self {
675 let derived = Derived::from_params(¶ms);
676 let qs0_dt = params.qs0 * params.dt;
677 let s_mean0 = if derived.qss > 0.0 && qs0_dt > 0.0 {
678 -params.m * (qs0_dt / derived.qss).ln()
679 } else { 0.0 };
680 Self {
681 srz: vec![params.Sr0; derived.nidxclass],
682 suz: vec![0.0; derived.nidxclass],
683 infl: Infiltration::new(),
684 s_mean: s_mean0,
685 derived,
686 params,
687 qt_buf: Vec::new(),
688 step_i: 0,
689 discharge_m3s: 0.0,
690 }
691 }
692
693 fn step(&mut self, f: &Forcing, dt_h: f64) {
694 let p = &self.params;
695 let i = self.step_i;
696 let r = f.p_mm.max(0.0);
697 let e = f.pet_mm.max(0.0);
698 let nidx = self.derived.nidxclass;
699
700 let t = (i as f64 + 1.0) * p.dt;
701 let mut fi = p.dt * self.infl.get_f(t, r / p.dt, p.CD, p.K0, p.m, p.dt);
702 if fi < 0.0 { fi = r; }
703 let fex = r - fi;
704
705 let qs = self.derived.qss * (-self.s_mean / p.m).exp();
706
707 let mut qo_total = 0.0;
708 let mut qv_total = 0.0;
709 let mut ea_total = 0.0;
710 let mut ex_prev = 0.0;
711
712 for j in 0..nidx {
713 let aatb_local = (self.derived.aatb_r[j]
714 + if j < nidx - 1 { self.derived.aatb_r[j + 1] } else { 0.0 }) / 2.0;
715 let mut s = self.s_mean + p.m * (self.derived.lambda - self.derived.atb[j]);
716 if s < 0.0 { s = 0.0; }
717
718 self.srz[j] -= fi;
719 if self.srz[j] < 0.0 {
720 self.suz[j] -= self.srz[j];
721 self.srz[j] = 0.0;
722 }
723 let mut ex = 0.0;
724 if self.suz[j] > s {
725 ex = self.suz[j] - s;
726 self.suz[j] = s;
727 }
728 let mut qv = 0.0;
729 if s > 0.0 {
730 qv = self.suz[j] / (s * p.td) * p.dt;
731 if qv > self.suz[j] { qv = self.suz[j]; }
732 self.suz[j] -= qv;
733 if self.suz[j] < ZERO { self.suz[j] = 0.0; }
734 qv *= aatb_local;
735 }
736 qv_total += qv;
737
738 let mut ea = 0.0;
739 if e > 0.0 {
740 ea = e * (1.0 - self.srz[j] / p.Srmax);
741 if ea > p.Srmax - self.srz[j] { ea = p.Srmax - self.srz[j]; }
742 }
743 self.srz[j] += ea;
744 ea_total += aatb_local * ea;
745
746 // 饱和面产流 qo(相邻类 ex)
747 if j > 0 {
748 let qo = if ex > 0.0 {
749 self.derived.aatb_r[j] * (ex_prev + ex) / 2.0
750 } else if ex_prev > 0.0 {
751 aatb_local * ex_prev / (ex_prev - ex) * ex_prev / 2.0
752 } else { 0.0 };
753 qo_total += qo;
754 }
755 ex_prev = ex;
756 }
757
758 qo_total += fex;
759 let qt = qo_total + qs;
760 self.s_mean += qs - qv_total;
761
762 // 路由到 Qt 缓冲
763 if self.derived.nreach > 0 {
764 for j in 0..self.derived.nreach {
765 let k = i + j + self.derived.ndelay;
766 if k >= self.qt_buf.len() { self.qt_buf.resize(k + 1, 0.0); }
767 self.qt_buf[k] += qt * self.derived.ad[j];
768 }
769 } else {
770 if i >= self.qt_buf.len() { self.qt_buf.resize(i + 1, 0.0); }
771 self.qt_buf[i] += qt;
772 }
773
774 let qt_i = self.qt_buf.get(i).copied().unwrap_or(0.0);
775 self.discharge_m3s = mm_to_m3s(qt_i, p.area_km2, dt_h);
776 self.step_i += 1;
777 }
778
779 fn discharge(&self) -> f64 { self.discharge_m3s }
780 fn state(&self) -> serde_json::Value {
781 serde_json::json!({ "S_mean": self.s_mean, "step": self.step_i })
782 }
783 fn reset(&mut self) {
784 let p = self.params.clone();
785 *self = Self::new(p);
786 }
787 fn name(&self) -> &'static str { "TOPMODEL" }
788 fn params(&self) -> &Self::Params { &self.params }
789 fn params_mut(&mut self) -> &mut Self::Params { &mut self.params }
790}
791
792#[cfg(test)]
793mod tests {
794 use super::*;
795
796 #[test]
797 fn lambda_single_class() {
798 // 单类 atb=[0], Aatb_r=[1] → λ=0(get_lambda 从 i=1 起,无项)
799 assert!(get_lambda(&[0.0], &[1.0]).abs() < 1e-12);
800 }
801
802 #[test]
803 fn lambda_two_class() {
804 // atb=[2,0], Aatb_r=[0.3,1.0] → λ = Aatb_r[1]*(atb[1]+atb[0])/2 = 1.0*(0+2)/2 = 1.0
805 let l = get_lambda(&[2.0, 0.0], &[0.3, 1.0]);
806 assert!((l - 1.0).abs() < 1e-12, "λ={}", l);
807 }
808
809 #[test]
810 fn rain_produces_flow() {
811 let mut p = TopmodelParams::default();
812 p.m = 0.01; p.lnTe = (5.0_f64).ln(); p.qs0 = 0.01; p.Srmax = 0.05; p.Sr0 = 0.0;
813 p.K0 = 0.0; p.CD = 0.0; p.dt = 1.0;
814 let mut m = TopmodelModel::new(p);
815 for _ in 0..10 { m.step(&Forcing { p_mm: 30.0, pet_mm: 0.0, t_c: 20.0 }, 1.0); }
816 assert!(m.discharge() > 0.0, "rain should produce flow: {}", m.discharge());
817 }
818
819 #[test]
820 fn no_mass_creation_constant_rain() {
821 let params = TopmodelParams::default();
822 let area = params.area_km2;
823 let mut m = TopmodelModel::new(params);
824 let n = 200;
825 let mut sum_q_mm = 0.0;
826 for _ in 0..n {
827 m.step(&Forcing { p_mm: 5.0, pet_mm: 0.0, t_c: 20.0 }, 1.0);
828 sum_q_mm += m.discharge() * 1.0 * 3.6 / area;
829 }
830 let sum_rain = 5.0 * n as f64;
831 assert!(sum_q_mm <= sum_rain * 1.05, "出流>降雨(质量凭空):{:.1}>{:.1}", sum_q_mm, sum_rain);
832 }
833
834 #[test]
835 fn dyn_dispatch() {
836 let mut m: Box<dyn hydro_core::DynHydroModel> = Box::new(TopmodelModel::new(TopmodelParams::default()));
837 m.step(&Forcing { p_mm: 50.0, pet_mm: 1.0, t_c: 20.0 }, 1.0);
838 assert!(m.discharge() >= 0.0);
839 assert_eq!(m.name(), "TOPMODEL");
840 }
841}