Skip to main content

hydro_platform/
lib.rs

1//! hydro-platform: multi-model orchestration for the hydrology platform.
2//!
3//! Runs multiple hydrological models (新安江 / TOPMODEL / SWAT / API-CONT) on
4//! the same basin + forcing, collects discharge hydrographs, and computes
5//! comparison metrics (NSE / KGE / RMSE / PBIAS / R²) plus ensemble
6//! probabilistic verification (CRPS / Brier / POD-FAR-CSI / Talagrand rank
7//! histogram) and GB/T 22482-2008 flood-forecast qualification.
8//!
9//! ## Re-exports
10//!
11//! `hydro-platform` is the orchestration layer of the `hydro-suite` crates and
12//! pulls the rest of the suite in as dependencies. From this one crate you get,
13//! via re-export:
14//!
15//! - From [`hydro_core`]: the `HydroModel` / `DynHydroModel` traits, forcing
16//!   types (`Forcing`, `BasinInfo`, `Outlet`), the `ModelType` enum, the
17//!   full metrics toolkit (`compute_metrics`, `compute_metrics_gbt`,
18//!   `crps`, `brier`, `pod_far_csi`, `rank_histogram`, …), and the
19//!   GB/T 22482 qualification types.
20//! - From [`hydro_calib`]: the [`calibrate`] entry point, [`ParamSpec`],
21//!   [`Objective`], [`Method`], [`SceConfig`], [`CalibResult`].
22//! - The four model crates themselves ([`hydro_xinanjiang`],
23//!   [`hydro_topmodel`], [`hydro_swat`], [`hydro_apicont`]) are *dependencies*
24//!   of `hydro-platform` and used internally by [`create_model`] /
25//!   [`run_scenario`]; reach into them directly
26//!   (`use hydro_xinanjiang::XinanjiangParams;`) when you need to construct
27//!   parameter structs.
28//!
29//! ## Workflow
30//!
31//! 1. Build a [`Scenario`] (basin, forcing, dt_h, selected models, optional
32//!    observation, optional per-model parameter overrides).
33//! 2. Call [`run_scenario`] to get a [`ComparisonResult`] — one
34//!    [`ModelResult`] per selected model (discharge series + optional
35//!    metrics when an observation was supplied).
36//! 3. Inspect per-model hydrographs, call [`ComparisonResult::best_nse`] for
37//!    the best-fitting model, or feed the result into [`ensemble_stats`] /
38//!    [`ensemble_probabilistic`] / [`ensemble_rank_histogram`] for
39//!    multi-model ensemble verification.
40
41pub use hydro_core::{
42    Forcing, BasinInfo, Outlet, ModelType, MetricsReport, DynHydroModel, HydroModel,
43    compute_metrics, compute_metrics_gbt,
44    GbtEventErrors, QualificationTolerance, QualificationReport,
45    event_errors, event_qualified, qualified_rate, qualification_grade, scheme_grade,
46    ProbabilisticReport, crps, brier, pod_far_csi, ensemble_exceedance, compute_probabilistic,
47    rank_histogram,
48};
49
50pub use hydro_calib::{calibrate, ParamSpec, Objective, Method, CalibResult, SceConfig};
51
52use hydro_xinanjiang::{XinanjiangModel, XinanjiangParams};
53use hydro_topmodel::{TopmodelModel, TopmodelParams};
54use hydro_swat::{SwatModel, SwatParams};
55use hydro_apicont::{ApicontModel, ApicontParams};
56
57use serde::{Serialize, Deserialize};
58
59/// A single model run result: discharge hydrograph + optional evaluation
60/// metrics.
61///
62/// Produced by [`run_scenario`] for each model in the scenario's `models`
63/// list. The `discharge` series has one entry per forcing time-step
64/// (m³/s, identical length to `Scenario::forcing`); `metrics` is `Some(..)`
65/// only when the scenario carried an `observed` series of matching length,
66/// in which case it holds NSE / KGE / RMSE / PBIAS / R² + GB/T 22482
67/// qualification computed via [`compute_metrics_gbt`].
68#[derive(Clone, Debug, Serialize, Deserialize)]
69pub struct ModelResult {
70    /// Which model produced this result (one of `Xinanjiang` / `Topmodel` /
71    /// `Swat` / `Apicont`).
72    pub model_type: ModelType,
73    /// Human-readable model name (matches `ModelType::name()` — e.g.
74    /// `"新安江"`, `"TOPMODEL"`, `"SWAT"`, `"API-CONT"`).
75    pub name: String,
76    /// Discharge hydrograph, m³/s per time-step. Length =
77    /// `Scenario::forcing.len()`.
78    pub discharge: Vec<f64>,       // m³/s per time-step
79    /// Per-metric evaluation report. `None` when no `observed` series was
80    /// supplied or its length did not match `discharge.len()`.
81    pub metrics: Option<MetricsReport>,
82}
83
84/// Comparison output from running every model in a [`Scenario`].
85///
86/// Wraps a `Vec<ModelResult>` (one entry per requested model, in the order
87/// given by `Scenario::models`) together with the shared `time_steps` count
88/// (= `Scenario::forcing.len()`). Pass it to [`ensemble_stats`] /
89/// [`ensemble_probabilistic`] / [`ensemble_rank_histogram`] for multi-model
90/// ensemble diagnostics, or call [`best_nse`](Self::best_nse) to pick the
91/// best-fitting member when metrics are populated.
92#[derive(Clone, Debug, Serialize, Deserialize)]
93pub struct ComparisonResult {
94    /// One [`ModelResult`] per model in `Scenario::models`, same order.
95    pub results: Vec<ModelResult>,
96    /// Number of time-steps in every member's `discharge` series.
97    pub time_steps: usize,
98}
99
100impl ComparisonResult {
101    /// Return the [`ModelResult`] with the highest NSE, or `None` if no
102    /// member has metrics attached.
103    ///
104    /// Selection is by `MetricsReport::nse` only; ties resolve to the
105    /// earlier member (stable `max_by`). Use this after a
106    /// scenario run with an observation to pick the best-fitting model.
107    pub fn best_nse(&self) -> Option<&ModelResult> {
108        self.results.iter()
109            .filter_map(|r| r.metrics.as_ref().map(|m| (r, m.nse)))
110            .max_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal))
111            .map(|(r, _)| r)
112    }
113}
114
115// ── 多模型集合统计 + 概率验证 ──
116
117/// Per-time-step ensemble statistics across all members of a
118/// [`ComparisonResult`].
119///
120/// Every `Vec<f64>` field has length `time_steps`. At each step the values
121/// are computed over the set `{r.discharge[step] : r in results}` — i.e.
122/// the model outputs at that time-step form the ensemble. [`ensemble_stats`]
123/// is the constructor.
124#[derive(Clone, Debug, Serialize, Deserialize)]
125pub struct EnsembleStats {
126    /// Arithmetic mean of member discharges at each step (m³/s).
127    pub mean: Vec<f64>,
128    /// Median (50th percentile, linear-interpolated) at each step (m³/s).
129    pub median: Vec<f64>,
130    /// Minimum member discharge at each step (m³/s).
131    pub min: Vec<f64>,
132    /// Maximum member discharge at each step (m³/s).
133    pub max: Vec<f64>,
134    /// 25th percentile (linear-interpolated) at each step (m³/s).
135    pub p25: Vec<f64>,
136    /// 75th percentile (linear-interpolated) at each step (m³/s).
137    pub p75: Vec<f64>,
138}
139
140/// Linear-interpolated quantile of an ascending-sorted slice at probability
141/// `q ∈ [0, 1]`. Empty input returns `0.0`; a single-element slice returns
142/// that element.
143fn quantile(sorted: &[f64], q: f64) -> f64 {
144    if sorted.is_empty() {
145        return 0.0;
146    }
147    if sorted.len() == 1 {
148        return sorted[0];
149    }
150    let pos = q * (sorted.len() - 1) as f64;
151    let lo = pos.floor() as usize;
152    let hi = (lo + 1).min(sorted.len() - 1);
153    let frac = pos - lo as f64;
154    sorted[lo] + (sorted[hi] - sorted[lo]) * frac
155}
156
157/// Compute per-time-step ensemble statistics across all members of `res`.
158///
159/// All members are assumed to share length `time_steps`; members with a
160/// shorter `discharge` series contribute `None` at the missing steps and are
161/// skipped at those steps. Returns mean / median / min / max / p25 / p75,
162/// each of length `time_steps`.
163pub fn ensemble_stats(res: &ComparisonResult) -> EnsembleStats {
164    let t = res.time_steps;
165    let mut mean = vec![0.0_f64; t];
166    let mut median = Vec::with_capacity(t);
167    let mut minv = Vec::with_capacity(t);
168    let mut maxv = Vec::with_capacity(t);
169    let mut p25 = Vec::with_capacity(t);
170    let mut p75 = Vec::with_capacity(t);
171    for step in 0..t {
172        let mut vals: Vec<f64> = res.results.iter()
173            .filter_map(|r| r.discharge.get(step).copied())
174            .collect();
175        if vals.is_empty() {
176            median.push(0.0); minv.push(0.0); maxv.push(0.0); p25.push(0.0); p75.push(0.0);
177            continue;
178        }
179        let n = vals.len();
180        mean[step] = vals.iter().sum::<f64>() / n as f64;
181        minv.push(vals.iter().cloned().fold(f64::INFINITY, f64::min));
182        maxv.push(vals.iter().cloned().fold(f64::NEG_INFINITY, f64::max));
183        vals.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
184        median.push(quantile(&vals, 0.5));
185        p25.push(quantile(&vals, 0.25));
186        p75.push(quantile(&vals, 0.75));
187    }
188    EnsembleStats { mean, median, min: minv, max: maxv, p25, p75 }
189}
190
191/// Ensemble probabilistic verification against an observed series at a
192/// discharge `threshold`.
193///
194/// Stacks the members' `discharge` series into `Vec<Vec<f64>>` and delegates
195/// to [`hydro_core::compute_probabilistic`], which returns fair CRPS, Brier
196/// score, POD / FAR / CSI, and exceedance probabilities. `observed.len()`
197/// must equal `time_steps`. Threshold is in the same units as discharge
198/// (m³/s).
199pub fn ensemble_probabilistic(
200    res: &ComparisonResult,
201    observed: &[f64],
202    threshold: f64,
203) -> ProbabilisticReport {
204    let ensemble: Vec<Vec<f64>> = res.results.iter().map(|r| r.discharge.clone()).collect();
205    compute_probabilistic(&ensemble, observed, threshold)
206}
207
208/// Talagrand rank histogram (ensemble reliability) for the multi-model
209/// ensemble vs an observed series.
210///
211/// Returns `M + 1` bins (where `M = results.len()`); bin `i` counts the
212/// steps at which the observation ranks between the `i`-th and `(i+1)`-th
213/// ordered member. A flat histogram indicates a reliable ensemble; U-shape
214/// suggests under-dispersion, dome-shape over-dispersion. Delegates to
215/// [`hydro_core::rank_histogram`]. `observed.len()` must equal `time_steps`.
216pub fn ensemble_rank_histogram(res: &ComparisonResult, observed: &[f64]) -> Vec<usize> {
217    let ensemble: Vec<Vec<f64>> = res.results.iter().map(|r| r.discharge.clone()).collect();
218    rank_histogram(&ensemble, observed)
219}
220
221// ── M3:事件单位线预报(事件制,独立于 HydroModel 连续 trait)──
222
223/// Event-based unit-hydrograph forecast: rainfall hyetograph `rain_mm`
224/// (per time-step) convolved with a unit hydrograph `uh` (a normalised
225/// kernel, `Σ uh = 1`) → outlet discharge hydrograph in m³/s.
226///
227/// The depth-to-discharge conversion factor is
228/// `area_km2 · 1000 / (dt_h · 3600)` (i.e. `mm · km² → m³/s`). With `uh =
229/// [1.0]` the convolution degenerates to direct inflow (no delay). This
230/// function is event-based and independent of the continuous `HydroModel`
231/// trait — useful for design-storm routing when no state needs to be
232/// carried between events.
233///
234/// # Arguments
235///
236/// * `rain_mm` — rainfall depth per time-step (mm).
237/// * `uh` — unit hydrograph kernel; should sum to 1 for mass conservation.
238///   Length `L` spreads each pulse over `L` subsequent steps.
239/// * `area_km2` — basin area used in the depth → discharge conversion.
240/// * `dt_h` — time-step length in hours.
241///
242/// # Returns
243///
244/// Discharge hydrograph in m³/s, length `rain_mm.len()`.
245pub fn event_uh_forecast(rain_mm: &[f64], uh: &[f64], area_km2: f64, dt_h: f64) -> Vec<f64> {
246    let coef = area_km2 * 1000.0 / (dt_h * 3600.0); // mm·km² → m³/s
247    let n = rain_mm.len();
248    let mut q = vec![0.0; n];
249    for t in 0..n {
250        let kmax = uh.len().min(t + 1);
251        let mut s = 0.0;
252        for k in 0..kmax {
253            s += uh[k] * rain_mm[t - k];
254        }
255        q[t] = s * coef;
256    }
257    q
258}
259
260/// SCS-style dimensionless unit hydrograph, simplified to a triangular UH:
261/// linear rise to the peak at index `peak_t`, linear recession to zero at
262/// index `base_t - 1`, then normalised so `Σ uh = 1`.
263///
264/// Use it as the `uh` input to [`event_uh_forecast`] when no measured
265/// unit hydrograph is available. Returns an empty `Vec` when `base_t == 0`.
266///
267/// # Arguments
268///
269/// * `peak_t` — index of the peak ordinate (`0..base_t`); clamped to
270///   `base_t - 1` if larger.
271/// * `base_t` — total base length (number of ordinates).
272pub fn scs_unit_hydrograph(peak_t: usize, base_t: usize) -> Vec<f64> {
273    if base_t == 0 {
274        return Vec::new();
275    }
276    let p = peak_t.min(base_t.saturating_sub(1));
277    let mut uh = vec![0.0_f64; base_t];
278    for t in 0..base_t {
279        uh[t] = if t <= p {
280            t as f64 / p.max(1) as f64
281        } else {
282            (base_t - t) as f64 / (base_t - p).max(1) as f64
283        };
284    }
285    let sum: f64 = uh.iter().sum();
286    if sum > 0.0 {
287        for v in uh.iter_mut() {
288            *v /= sum;
289        }
290    }
291    uh
292}
293
294/// A forecast scenario: basin + forcing + selected models + optional
295/// observation + optional per-model parameter overrides.
296///
297/// Pass to [`run_scenario`] to execute every selected model on the same
298/// forcing and collect a [`ComparisonResult`]. Field defaults (via struct
299/// literal in tests / examples) are typically `observed: None` and
300/// `params_overrides: None`; supply `Some(obs)` to enable per-model
301/// metrics, and `Some(overrides)` keyed by [`ModelType::name`] to swap in
302/// non-default parameters per model.
303#[derive(Clone, Debug, Serialize, Deserialize)]
304pub struct Scenario {
305    /// Basin descriptor (area used for depth→discharge conversion +
306    /// GB/T 22482 runoff-depth error).
307    pub basin: BasinInfo,
308    /// Forcing series (P / PET / T) — shared by all selected models.
309    pub forcing: Vec<Forcing>,
310    /// Time-step length in hours. Must match the time-step implicit in
311    /// `forcing` (e.g. `1.0` for hourly forcing, `24.0` for daily SWAT+).
312    pub dt_h: f64,
313    /// Which models to run on this scenario. Order is preserved in the
314    /// returned `ComparisonResult::results`.
315    pub models: Vec<ModelType>,
316    /// Optional observed discharge series. When supplied and of the same
317    /// length as `forcing`, each `ModelResult::metrics` is populated.
318    pub observed: Option<Vec<f64>>,
319    /// Per-model parameter overrides (JSON keyed by `ModelType::name()`).
320    /// Missing → use model defaults.
321    pub params_overrides: Option<serde_json::Map<String, serde_json::Value>>,
322}
323
324/// Factory: create a boxed [`DynHydroModel`] from a [`ModelType`] tag + a
325/// JSON params blob.
326///
327/// The params JSON is deserialised into the model's `Params` struct; if
328/// deserialisation fails (unknown field / wrong type), the model's
329/// `Params::default()` is used as a fallback so a malformed override never
330/// panics the run. This is the single dispatch point that lets
331/// [`run_scenario`] treat all four models uniformly behind the
332/// `DynHydroModel` trait.
333pub fn create_model(mt: ModelType, params: &serde_json::Value) -> Box<dyn DynHydroModel> {
334    match mt {
335        ModelType::Xinanjiang => Box::new(XinanjiangModel::new(
336            serde_json::from_value(params.clone()).unwrap_or_default(),
337        )),
338        ModelType::Topmodel => Box::new(TopmodelModel::new(
339            serde_json::from_value(params.clone()).unwrap_or_default(),
340        )),
341        ModelType::Swat => Box::new(SwatModel::new(
342            serde_json::from_value(params.clone()).unwrap_or_default(),
343        )),
344        ModelType::Apicont => Box::new(ApicontModel::new(
345            serde_json::from_value(params.clone()).unwrap_or_default(),
346        )),
347    }
348}
349
350/// Get the default params for a model type as a JSON `Value`.
351///
352/// Convenience for scenarios that start from defaults and patch a few
353/// fields, and for [`run_model_default`] / [`run_scenario`].
354pub fn default_params(mt: ModelType) -> serde_json::Value {
355    match mt {
356        ModelType::Xinanjiang => serde_json::to_value(XinanjiangParams::default()).unwrap(),
357        ModelType::Topmodel => serde_json::to_value(TopmodelParams::default()).unwrap(),
358        ModelType::Swat => serde_json::to_value(SwatParams::default()).unwrap(),
359        ModelType::Apicont => serde_json::to_value(ApicontParams::default()).unwrap(),
360    }
361}
362
363/// Run a single model with default parameters and return its discharge
364/// hydrograph (m³/s, one entry per forcing step).
365///
366/// Convenience for quick baseline runs and for generating a "synthetic
367/// truth" hydrograph to feed back into calibration as the observed series.
368/// Equivalent to `create_model(mt, &default_params(mt))` followed by a
369/// step loop.
370pub fn run_model_default(mt: ModelType, forcing: &[Forcing], dt_h: f64) -> Vec<f64> {
371    let params = default_params(mt);
372    let mut m = create_model(mt, &params);
373    forcing.iter().map(|f| {
374        m.step(f, dt_h);
375        m.discharge()
376    }).collect()
377}
378
379/// Run all selected models in `scenario` on the same forcing and collect
380/// hydrographs + (optional) evaluation metrics.
381///
382/// For each `ModelType` in `scenario.models`:
383///
384/// 1. Resolve params — `params_overrides[mt.name()]` if present, else
385///    [`default_params`].
386/// 2. Build a model via [`create_model`] and step it through `forcing` with
387///    `dt_h`, recording discharge at each step.
388/// 3. If `observed` is `Some` and matches the forcing length, evaluate the
389///    discharge series with [`compute_metrics_gbt`] (NSE / KGE / RMSE /
390///    PBIAS / R² + GB/T 22482 event errors and qualification).
391///
392/// Returns a [`ComparisonResult`] whose `time_steps` equals
393/// `scenario.forcing.len()` and whose `results` keeps the order of
394/// `scenario.models`. Member models are independent — they do not share
395/// state — so each call is repeatable.
396pub fn run_scenario(scenario: &Scenario) -> ComparisonResult {
397    let mut results = Vec::new();
398    for mt in &scenario.models {
399        let params = scenario.params_overrides.as_ref()
400            .and_then(|m| m.get(mt.name()))
401            .cloned()
402            .unwrap_or_else(|| default_params(*mt));
403        let mut model = create_model(*mt, &params);
404        let mut discharge = Vec::with_capacity(scenario.forcing.len());
405        for f in &scenario.forcing {
406            model.step(f, scenario.dt_h);
407            discharge.push(model.discharge());
408        }
409        let metrics = scenario.observed.as_ref()
410            .filter(|obs| obs.len() == discharge.len())
411            .map(|obs| {
412                compute_metrics_gbt(
413                    obs,
414                    &discharge,
415                    scenario.basin.area_km2,
416                    scenario.dt_h,
417                    &QualificationTolerance::default(),
418                )
419            });
420        results.push(ModelResult {
421            model_type: *mt,
422            name: mt.name().to_string(),
423            discharge,
424            metrics,
425        });
426    }
427    ComparisonResult { results, time_steps: scenario.forcing.len() }
428}
429
430// ---------------------------------------------------------------------------
431// Tests
432// ---------------------------------------------------------------------------
433
434#[cfg(test)]
435mod tests {
436    use super::*;
437
438    fn make_scenario(models: Vec<ModelType>) -> Scenario {
439        let forcing: Vec<Forcing> = (0..48)
440            .map(|i| Forcing {
441                p_mm: if i < 6 { 25.0 } else { 0.0 },
442                pet_mm: 2.0,
443                t_c: 20.0,
444            })
445            .collect();
446        Scenario {
447            basin: BasinInfo {
448                id: "test".into(), name: "Test Basin".into(),
449                area_km2: 1000.0, outlet_lat: 30.0, outlet_lon: 120.0,
450            },
451            forcing, dt_h: 1.0, models,
452            observed: None, params_overrides: None,
453        }
454    }
455
456    #[test]
457    fn test_run_all_three_models() {
458        let s = make_scenario(vec![ModelType::Xinanjiang, ModelType::Topmodel, ModelType::Swat]);
459        let result = run_scenario(&s);
460        assert_eq!(result.results.len(), 3);
461        assert_eq!(result.time_steps, 48);
462        for r in &result.results {
463            assert_eq!(r.discharge.len(), 48);
464            // Peak discharge during rain period
465            let peak = r.discharge.iter().cloned().fold(0.0_f64, f64::max);
466            assert!(peak > 0.0, "{} should produce flow: peak={}", r.name, peak);
467        }
468    }
469
470    #[test]
471    fn test_comparison_with_observed() {
472        // Run XAJ first to get "truth"
473        let s1 = make_scenario(vec![ModelType::Xinanjiang]);
474        let r1 = run_scenario(&s1);
475        let observed = r1.results[0].discharge.clone();
476
477        // Run all 3 with XAJ as observation
478        let s2 = Scenario { observed: Some(observed), ..make_scenario(vec![
479            ModelType::Xinanjiang, ModelType::Topmodel, ModelType::Swat,
480        ]) };
481        let r2 = run_scenario(&s2);
482
483        // XAJ should have NSE ≈ 1.0 (obs == sim)
484        let xaj = r2.results.iter().find(|r| r.model_type == ModelType::Xinanjiang).unwrap();
485        let nse = xaj.metrics.as_ref().unwrap().nse;
486        assert!(nse > 0.99, "XAJ NSE vs itself should be ~1: {}", nse);
487    }
488
489    #[test]
490    fn test_default_params() {
491        for mt in [ModelType::Xinanjiang, ModelType::Topmodel, ModelType::Swat] {
492            let p = default_params(mt);
493            assert!(p.is_object(), "default params for {:?} should be JSON object", mt);
494        }
495    }
496
497    #[test]
498    fn test_create_model_dyn() {
499        let m = create_model(ModelType::Xinanjiang, &default_params(ModelType::Xinanjiang));
500        assert_eq!(m.name(), "新安江");
501        let m = create_model(ModelType::Topmodel, &default_params(ModelType::Topmodel));
502        assert_eq!(m.name(), "TOPMODEL");
503        let m = create_model(ModelType::Swat, &default_params(ModelType::Swat));
504        assert_eq!(m.name(), "SWAT");
505    }
506
507    #[test]
508    fn test_ensemble_stats_two_members() {
509        let r = ComparisonResult {
510            results: vec![
511                ModelResult { model_type: ModelType::Xinanjiang, name: "A".into(),
512                    discharge: vec![10.0, 20.0], metrics: None },
513                ModelResult { model_type: ModelType::Topmodel, name: "B".into(),
514                    discharge: vec![30.0, 40.0], metrics: None },
515            ],
516            time_steps: 2,
517        };
518        let s = ensemble_stats(&r);
519        assert!((s.mean[0] - 20.0).abs() < 1e-9, "mean0=(10+30)/2");
520        assert!((s.mean[1] - 30.0).abs() < 1e-9, "mean1=(20+40)/2");
521        assert!((s.min[0] - 10.0).abs() < 1e-9);
522        assert!((s.max[1] - 40.0).abs() < 1e-9);
523        assert!((s.median[0] - 20.0).abs() < 1e-9, "median of 10/30 interp =20");
524        assert_eq!(s.mean.len(), 2);
525    }
526
527    #[test]
528    fn test_scs_unit_hydrograph_normalized() {
529        let uh = scs_unit_hydrograph(2, 5);
530        assert_eq!(uh.len(), 5);
531        let sum: f64 = uh.iter().sum();
532        assert!((sum - 1.0).abs() < 1e-9, "UH 应归一化 Σ=1, got {}", sum);
533        // 峰在第 2 步(三角:0,0.5,1,0.67,0.33 归一化前 → 峰在 idx2)
534        let peak_idx = uh.iter().enumerate()
535            .max_by(|a, b| a.1.partial_cmp(b.1).unwrap()).unwrap().0;
536        assert_eq!(peak_idx, 2);
537    }
538
539    #[test]
540    fn test_event_uh_forecast_unit_pulse_and_lag() {
541        // uh=[1.0](无延迟):恒定雨 → 稳态 q=rain·coef;coef=1000·1000/3600≈277.78
542        let q = event_uh_forecast(&[10.0; 4], &[1.0], 1000.0, 1.0);
543        let coef = 1000.0 * 1000.0 / 3600.0;
544        for v in &q {
545            assert!((v - 10.0 * coef).abs() < 1e-3, "稳态 q, got {}", v);
546        }
547        // uh=[0.5,0.5]:单脉冲雨 [10,0] → t0:0.5·10·coef; t1:0.5·10·coef(延迟)
548        let q2 = event_uh_forecast(&[10.0, 0.0], &[0.5, 0.5], 1000.0, 1.0);
549        assert!((q2[0] - 0.5 * 10.0 * coef).abs() < 1e-3, "t0 half, got {}", q2[0]);
550        assert!((q2[1] - 0.5 * 10.0 * coef).abs() < 1e-3, "t1 delayed half, got {}", q2[1]);
551    }
552}