hydro-platform 0.1.0

Multi-model hydrology platform: scenario orchestration, comparison, and metrics
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
//! hydro-platform: multi-model orchestration for the hydrology platform.
//!
//! Runs multiple hydrological models (新安江 / TOPMODEL / SWAT / API-CONT) on
//! the same basin + forcing, collects discharge hydrographs, and computes
//! comparison metrics (NSE / KGE / RMSE / PBIAS / R²) plus ensemble
//! probabilistic verification (CRPS / Brier / POD-FAR-CSI / Talagrand rank
//! histogram) and GB/T 22482-2008 flood-forecast qualification.
//!
//! ## Re-exports
//!
//! `hydro-platform` is the orchestration layer of the `hydro-suite` crates and
//! pulls the rest of the suite in as dependencies. From this one crate you get,
//! via re-export:
//!
//! - From [`hydro_core`]: the `HydroModel` / `DynHydroModel` traits, forcing
//!   types (`Forcing`, `BasinInfo`, `Outlet`), the `ModelType` enum, the
//!   full metrics toolkit (`compute_metrics`, `compute_metrics_gbt`,
//!   `crps`, `brier`, `pod_far_csi`, `rank_histogram`, …), and the
//!   GB/T 22482 qualification types.
//! - From [`hydro_calib`]: the [`calibrate`] entry point, [`ParamSpec`],
//!   [`Objective`], [`Method`], [`SceConfig`], [`CalibResult`].
//! - The four model crates themselves ([`hydro_xinanjiang`],
//!   [`hydro_topmodel`], [`hydro_swat`], [`hydro_apicont`]) are *dependencies*
//!   of `hydro-platform` and used internally by [`create_model`] /
//!   [`run_scenario`]; reach into them directly
//!   (`use hydro_xinanjiang::XinanjiangParams;`) when you need to construct
//!   parameter structs.
//!
//! ## Workflow
//!
//! 1. Build a [`Scenario`] (basin, forcing, dt_h, selected models, optional
//!    observation, optional per-model parameter overrides).
//! 2. Call [`run_scenario`] to get a [`ComparisonResult`] — one
//!    [`ModelResult`] per selected model (discharge series + optional
//!    metrics when an observation was supplied).
//! 3. Inspect per-model hydrographs, call [`ComparisonResult::best_nse`] for
//!    the best-fitting model, or feed the result into [`ensemble_stats`] /
//!    [`ensemble_probabilistic`] / [`ensemble_rank_histogram`] for
//!    multi-model ensemble verification.

pub use hydro_core::{
    Forcing, BasinInfo, Outlet, ModelType, MetricsReport, DynHydroModel, HydroModel,
    compute_metrics, compute_metrics_gbt,
    GbtEventErrors, QualificationTolerance, QualificationReport,
    event_errors, event_qualified, qualified_rate, qualification_grade, scheme_grade,
    ProbabilisticReport, crps, brier, pod_far_csi, ensemble_exceedance, compute_probabilistic,
    rank_histogram,
};

pub use hydro_calib::{calibrate, ParamSpec, Objective, Method, CalibResult, SceConfig};

use hydro_xinanjiang::{XinanjiangModel, XinanjiangParams};
use hydro_topmodel::{TopmodelModel, TopmodelParams};
use hydro_swat::{SwatModel, SwatParams};
use hydro_apicont::{ApicontModel, ApicontParams};

use serde::{Serialize, Deserialize};

/// A single model run result: discharge hydrograph + optional evaluation
/// metrics.
///
/// Produced by [`run_scenario`] for each model in the scenario's `models`
/// list. The `discharge` series has one entry per forcing time-step
/// (m³/s, identical length to `Scenario::forcing`); `metrics` is `Some(..)`
/// only when the scenario carried an `observed` series of matching length,
/// in which case it holds NSE / KGE / RMSE / PBIAS / R² + GB/T 22482
/// qualification computed via [`compute_metrics_gbt`].
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ModelResult {
    /// Which model produced this result (one of `Xinanjiang` / `Topmodel` /
    /// `Swat` / `Apicont`).
    pub model_type: ModelType,
    /// Human-readable model name (matches `ModelType::name()` — e.g.
    /// `"新安江"`, `"TOPMODEL"`, `"SWAT"`, `"API-CONT"`).
    pub name: String,
    /// Discharge hydrograph, m³/s per time-step. Length =
    /// `Scenario::forcing.len()`.
    pub discharge: Vec<f64>,       // m³/s per time-step
    /// Per-metric evaluation report. `None` when no `observed` series was
    /// supplied or its length did not match `discharge.len()`.
    pub metrics: Option<MetricsReport>,
}

/// Comparison output from running every model in a [`Scenario`].
///
/// Wraps a `Vec<ModelResult>` (one entry per requested model, in the order
/// given by `Scenario::models`) together with the shared `time_steps` count
/// (= `Scenario::forcing.len()`). Pass it to [`ensemble_stats`] /
/// [`ensemble_probabilistic`] / [`ensemble_rank_histogram`] for multi-model
/// ensemble diagnostics, or call [`best_nse`](Self::best_nse) to pick the
/// best-fitting member when metrics are populated.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ComparisonResult {
    /// One [`ModelResult`] per model in `Scenario::models`, same order.
    pub results: Vec<ModelResult>,
    /// Number of time-steps in every member's `discharge` series.
    pub time_steps: usize,
}

impl ComparisonResult {
    /// Return the [`ModelResult`] with the highest NSE, or `None` if no
    /// member has metrics attached.
    ///
    /// Selection is by `MetricsReport::nse` only; ties resolve to the
    /// earlier member (stable `max_by`). Use this after a
    /// scenario run with an observation to pick the best-fitting model.
    pub fn best_nse(&self) -> Option<&ModelResult> {
        self.results.iter()
            .filter_map(|r| r.metrics.as_ref().map(|m| (r, m.nse)))
            .max_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal))
            .map(|(r, _)| r)
    }
}

// ── 多模型集合统计 + 概率验证 ──

/// Per-time-step ensemble statistics across all members of a
/// [`ComparisonResult`].
///
/// Every `Vec<f64>` field has length `time_steps`. At each step the values
/// are computed over the set `{r.discharge[step] : r in results}` — i.e.
/// the model outputs at that time-step form the ensemble. [`ensemble_stats`]
/// is the constructor.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct EnsembleStats {
    /// Arithmetic mean of member discharges at each step (m³/s).
    pub mean: Vec<f64>,
    /// Median (50th percentile, linear-interpolated) at each step (m³/s).
    pub median: Vec<f64>,
    /// Minimum member discharge at each step (m³/s).
    pub min: Vec<f64>,
    /// Maximum member discharge at each step (m³/s).
    pub max: Vec<f64>,
    /// 25th percentile (linear-interpolated) at each step (m³/s).
    pub p25: Vec<f64>,
    /// 75th percentile (linear-interpolated) at each step (m³/s).
    pub p75: Vec<f64>,
}

/// Linear-interpolated quantile of an ascending-sorted slice at probability
/// `q ∈ [0, 1]`. Empty input returns `0.0`; a single-element slice returns
/// that element.
fn quantile(sorted: &[f64], q: f64) -> f64 {
    if sorted.is_empty() {
        return 0.0;
    }
    if sorted.len() == 1 {
        return sorted[0];
    }
    let pos = q * (sorted.len() - 1) as f64;
    let lo = pos.floor() as usize;
    let hi = (lo + 1).min(sorted.len() - 1);
    let frac = pos - lo as f64;
    sorted[lo] + (sorted[hi] - sorted[lo]) * frac
}

/// Compute per-time-step ensemble statistics across all members of `res`.
///
/// All members are assumed to share length `time_steps`; members with a
/// shorter `discharge` series contribute `None` at the missing steps and are
/// skipped at those steps. Returns mean / median / min / max / p25 / p75,
/// each of length `time_steps`.
pub fn ensemble_stats(res: &ComparisonResult) -> EnsembleStats {
    let t = res.time_steps;
    let mut mean = vec![0.0_f64; t];
    let mut median = Vec::with_capacity(t);
    let mut minv = Vec::with_capacity(t);
    let mut maxv = Vec::with_capacity(t);
    let mut p25 = Vec::with_capacity(t);
    let mut p75 = Vec::with_capacity(t);
    for step in 0..t {
        let mut vals: Vec<f64> = res.results.iter()
            .filter_map(|r| r.discharge.get(step).copied())
            .collect();
        if vals.is_empty() {
            median.push(0.0); minv.push(0.0); maxv.push(0.0); p25.push(0.0); p75.push(0.0);
            continue;
        }
        let n = vals.len();
        mean[step] = vals.iter().sum::<f64>() / n as f64;
        minv.push(vals.iter().cloned().fold(f64::INFINITY, f64::min));
        maxv.push(vals.iter().cloned().fold(f64::NEG_INFINITY, f64::max));
        vals.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
        median.push(quantile(&vals, 0.5));
        p25.push(quantile(&vals, 0.25));
        p75.push(quantile(&vals, 0.75));
    }
    EnsembleStats { mean, median, min: minv, max: maxv, p25, p75 }
}

/// Ensemble probabilistic verification against an observed series at a
/// discharge `threshold`.
///
/// Stacks the members' `discharge` series into `Vec<Vec<f64>>` and delegates
/// to [`hydro_core::compute_probabilistic`], which returns fair CRPS, Brier
/// score, POD / FAR / CSI, and exceedance probabilities. `observed.len()`
/// must equal `time_steps`. Threshold is in the same units as discharge
/// (m³/s).
pub fn ensemble_probabilistic(
    res: &ComparisonResult,
    observed: &[f64],
    threshold: f64,
) -> ProbabilisticReport {
    let ensemble: Vec<Vec<f64>> = res.results.iter().map(|r| r.discharge.clone()).collect();
    compute_probabilistic(&ensemble, observed, threshold)
}

/// Talagrand rank histogram (ensemble reliability) for the multi-model
/// ensemble vs an observed series.
///
/// Returns `M + 1` bins (where `M = results.len()`); bin `i` counts the
/// steps at which the observation ranks between the `i`-th and `(i+1)`-th
/// ordered member. A flat histogram indicates a reliable ensemble; U-shape
/// suggests under-dispersion, dome-shape over-dispersion. Delegates to
/// [`hydro_core::rank_histogram`]. `observed.len()` must equal `time_steps`.
pub fn ensemble_rank_histogram(res: &ComparisonResult, observed: &[f64]) -> Vec<usize> {
    let ensemble: Vec<Vec<f64>> = res.results.iter().map(|r| r.discharge.clone()).collect();
    rank_histogram(&ensemble, observed)
}

// ── M3:事件单位线预报(事件制,独立于 HydroModel 连续 trait)──

/// Event-based unit-hydrograph forecast: rainfall hyetograph `rain_mm`
/// (per time-step) convolved with a unit hydrograph `uh` (a normalised
/// kernel, `Σ uh = 1`) → outlet discharge hydrograph in m³/s.
///
/// The depth-to-discharge conversion factor is
/// `area_km2 · 1000 / (dt_h · 3600)` (i.e. `mm · km² → m³/s`). With `uh =
/// [1.0]` the convolution degenerates to direct inflow (no delay). This
/// function is event-based and independent of the continuous `HydroModel`
/// trait — useful for design-storm routing when no state needs to be
/// carried between events.
///
/// # Arguments
///
/// * `rain_mm` — rainfall depth per time-step (mm).
/// * `uh` — unit hydrograph kernel; should sum to 1 for mass conservation.
///   Length `L` spreads each pulse over `L` subsequent steps.
/// * `area_km2` — basin area used in the depth → discharge conversion.
/// * `dt_h` — time-step length in hours.
///
/// # Returns
///
/// Discharge hydrograph in m³/s, length `rain_mm.len()`.
pub fn event_uh_forecast(rain_mm: &[f64], uh: &[f64], area_km2: f64, dt_h: f64) -> Vec<f64> {
    let coef = area_km2 * 1000.0 / (dt_h * 3600.0); // mm·km² → m³/s
    let n = rain_mm.len();
    let mut q = vec![0.0; n];
    for t in 0..n {
        let kmax = uh.len().min(t + 1);
        let mut s = 0.0;
        for k in 0..kmax {
            s += uh[k] * rain_mm[t - k];
        }
        q[t] = s * coef;
    }
    q
}

/// SCS-style dimensionless unit hydrograph, simplified to a triangular UH:
/// linear rise to the peak at index `peak_t`, linear recession to zero at
/// index `base_t - 1`, then normalised so `Σ uh = 1`.
///
/// Use it as the `uh` input to [`event_uh_forecast`] when no measured
/// unit hydrograph is available. Returns an empty `Vec` when `base_t == 0`.
///
/// # Arguments
///
/// * `peak_t` — index of the peak ordinate (`0..base_t`); clamped to
///   `base_t - 1` if larger.
/// * `base_t` — total base length (number of ordinates).
pub fn scs_unit_hydrograph(peak_t: usize, base_t: usize) -> Vec<f64> {
    if base_t == 0 {
        return Vec::new();
    }
    let p = peak_t.min(base_t.saturating_sub(1));
    let mut uh = vec![0.0_f64; base_t];
    for t in 0..base_t {
        uh[t] = if t <= p {
            t as f64 / p.max(1) as f64
        } else {
            (base_t - t) as f64 / (base_t - p).max(1) as f64
        };
    }
    let sum: f64 = uh.iter().sum();
    if sum > 0.0 {
        for v in uh.iter_mut() {
            *v /= sum;
        }
    }
    uh
}

/// A forecast scenario: basin + forcing + selected models + optional
/// observation + optional per-model parameter overrides.
///
/// Pass to [`run_scenario`] to execute every selected model on the same
/// forcing and collect a [`ComparisonResult`]. Field defaults (via struct
/// literal in tests / examples) are typically `observed: None` and
/// `params_overrides: None`; supply `Some(obs)` to enable per-model
/// metrics, and `Some(overrides)` keyed by [`ModelType::name`] to swap in
/// non-default parameters per model.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Scenario {
    /// Basin descriptor (area used for depth→discharge conversion +
    /// GB/T 22482 runoff-depth error).
    pub basin: BasinInfo,
    /// Forcing series (P / PET / T) — shared by all selected models.
    pub forcing: Vec<Forcing>,
    /// Time-step length in hours. Must match the time-step implicit in
    /// `forcing` (e.g. `1.0` for hourly forcing, `24.0` for daily SWAT+).
    pub dt_h: f64,
    /// Which models to run on this scenario. Order is preserved in the
    /// returned `ComparisonResult::results`.
    pub models: Vec<ModelType>,
    /// Optional observed discharge series. When supplied and of the same
    /// length as `forcing`, each `ModelResult::metrics` is populated.
    pub observed: Option<Vec<f64>>,
    /// Per-model parameter overrides (JSON keyed by `ModelType::name()`).
    /// Missing → use model defaults.
    pub params_overrides: Option<serde_json::Map<String, serde_json::Value>>,
}

/// Factory: create a boxed [`DynHydroModel`] from a [`ModelType`] tag + a
/// JSON params blob.
///
/// The params JSON is deserialised into the model's `Params` struct; if
/// deserialisation fails (unknown field / wrong type), the model's
/// `Params::default()` is used as a fallback so a malformed override never
/// panics the run. This is the single dispatch point that lets
/// [`run_scenario`] treat all four models uniformly behind the
/// `DynHydroModel` trait.
pub fn create_model(mt: ModelType, params: &serde_json::Value) -> Box<dyn DynHydroModel> {
    match mt {
        ModelType::Xinanjiang => Box::new(XinanjiangModel::new(
            serde_json::from_value(params.clone()).unwrap_or_default(),
        )),
        ModelType::Topmodel => Box::new(TopmodelModel::new(
            serde_json::from_value(params.clone()).unwrap_or_default(),
        )),
        ModelType::Swat => Box::new(SwatModel::new(
            serde_json::from_value(params.clone()).unwrap_or_default(),
        )),
        ModelType::Apicont => Box::new(ApicontModel::new(
            serde_json::from_value(params.clone()).unwrap_or_default(),
        )),
    }
}

/// Get the default params for a model type as a JSON `Value`.
///
/// Convenience for scenarios that start from defaults and patch a few
/// fields, and for [`run_model_default`] / [`run_scenario`].
pub fn default_params(mt: ModelType) -> serde_json::Value {
    match mt {
        ModelType::Xinanjiang => serde_json::to_value(XinanjiangParams::default()).unwrap(),
        ModelType::Topmodel => serde_json::to_value(TopmodelParams::default()).unwrap(),
        ModelType::Swat => serde_json::to_value(SwatParams::default()).unwrap(),
        ModelType::Apicont => serde_json::to_value(ApicontParams::default()).unwrap(),
    }
}

/// Run a single model with default parameters and return its discharge
/// hydrograph (m³/s, one entry per forcing step).
///
/// Convenience for quick baseline runs and for generating a "synthetic
/// truth" hydrograph to feed back into calibration as the observed series.
/// Equivalent to `create_model(mt, &default_params(mt))` followed by a
/// step loop.
pub fn run_model_default(mt: ModelType, forcing: &[Forcing], dt_h: f64) -> Vec<f64> {
    let params = default_params(mt);
    let mut m = create_model(mt, &params);
    forcing.iter().map(|f| {
        m.step(f, dt_h);
        m.discharge()
    }).collect()
}

/// Run all selected models in `scenario` on the same forcing and collect
/// hydrographs + (optional) evaluation metrics.
///
/// For each `ModelType` in `scenario.models`:
///
/// 1. Resolve params — `params_overrides[mt.name()]` if present, else
///    [`default_params`].
/// 2. Build a model via [`create_model`] and step it through `forcing` with
///    `dt_h`, recording discharge at each step.
/// 3. If `observed` is `Some` and matches the forcing length, evaluate the
///    discharge series with [`compute_metrics_gbt`] (NSE / KGE / RMSE /
///    PBIAS / R² + GB/T 22482 event errors and qualification).
///
/// Returns a [`ComparisonResult`] whose `time_steps` equals
/// `scenario.forcing.len()` and whose `results` keeps the order of
/// `scenario.models`. Member models are independent — they do not share
/// state — so each call is repeatable.
pub fn run_scenario(scenario: &Scenario) -> ComparisonResult {
    let mut results = Vec::new();
    for mt in &scenario.models {
        let params = scenario.params_overrides.as_ref()
            .and_then(|m| m.get(mt.name()))
            .cloned()
            .unwrap_or_else(|| default_params(*mt));
        let mut model = create_model(*mt, &params);
        let mut discharge = Vec::with_capacity(scenario.forcing.len());
        for f in &scenario.forcing {
            model.step(f, scenario.dt_h);
            discharge.push(model.discharge());
        }
        let metrics = scenario.observed.as_ref()
            .filter(|obs| obs.len() == discharge.len())
            .map(|obs| {
                compute_metrics_gbt(
                    obs,
                    &discharge,
                    scenario.basin.area_km2,
                    scenario.dt_h,
                    &QualificationTolerance::default(),
                )
            });
        results.push(ModelResult {
            model_type: *mt,
            name: mt.name().to_string(),
            discharge,
            metrics,
        });
    }
    ComparisonResult { results, time_steps: scenario.forcing.len() }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    fn make_scenario(models: Vec<ModelType>) -> Scenario {
        let forcing: Vec<Forcing> = (0..48)
            .map(|i| Forcing {
                p_mm: if i < 6 { 25.0 } else { 0.0 },
                pet_mm: 2.0,
                t_c: 20.0,
            })
            .collect();
        Scenario {
            basin: BasinInfo {
                id: "test".into(), name: "Test Basin".into(),
                area_km2: 1000.0, outlet_lat: 30.0, outlet_lon: 120.0,
            },
            forcing, dt_h: 1.0, models,
            observed: None, params_overrides: None,
        }
    }

    #[test]
    fn test_run_all_three_models() {
        let s = make_scenario(vec![ModelType::Xinanjiang, ModelType::Topmodel, ModelType::Swat]);
        let result = run_scenario(&s);
        assert_eq!(result.results.len(), 3);
        assert_eq!(result.time_steps, 48);
        for r in &result.results {
            assert_eq!(r.discharge.len(), 48);
            // Peak discharge during rain period
            let peak = r.discharge.iter().cloned().fold(0.0_f64, f64::max);
            assert!(peak > 0.0, "{} should produce flow: peak={}", r.name, peak);
        }
    }

    #[test]
    fn test_comparison_with_observed() {
        // Run XAJ first to get "truth"
        let s1 = make_scenario(vec![ModelType::Xinanjiang]);
        let r1 = run_scenario(&s1);
        let observed = r1.results[0].discharge.clone();

        // Run all 3 with XAJ as observation
        let s2 = Scenario { observed: Some(observed), ..make_scenario(vec![
            ModelType::Xinanjiang, ModelType::Topmodel, ModelType::Swat,
        ]) };
        let r2 = run_scenario(&s2);

        // XAJ should have NSE ≈ 1.0 (obs == sim)
        let xaj = r2.results.iter().find(|r| r.model_type == ModelType::Xinanjiang).unwrap();
        let nse = xaj.metrics.as_ref().unwrap().nse;
        assert!(nse > 0.99, "XAJ NSE vs itself should be ~1: {}", nse);
    }

    #[test]
    fn test_default_params() {
        for mt in [ModelType::Xinanjiang, ModelType::Topmodel, ModelType::Swat] {
            let p = default_params(mt);
            assert!(p.is_object(), "default params for {:?} should be JSON object", mt);
        }
    }

    #[test]
    fn test_create_model_dyn() {
        let m = create_model(ModelType::Xinanjiang, &default_params(ModelType::Xinanjiang));
        assert_eq!(m.name(), "新安江");
        let m = create_model(ModelType::Topmodel, &default_params(ModelType::Topmodel));
        assert_eq!(m.name(), "TOPMODEL");
        let m = create_model(ModelType::Swat, &default_params(ModelType::Swat));
        assert_eq!(m.name(), "SWAT");
    }

    #[test]
    fn test_ensemble_stats_two_members() {
        let r = ComparisonResult {
            results: vec![
                ModelResult { model_type: ModelType::Xinanjiang, name: "A".into(),
                    discharge: vec![10.0, 20.0], metrics: None },
                ModelResult { model_type: ModelType::Topmodel, name: "B".into(),
                    discharge: vec![30.0, 40.0], metrics: None },
            ],
            time_steps: 2,
        };
        let s = ensemble_stats(&r);
        assert!((s.mean[0] - 20.0).abs() < 1e-9, "mean0=(10+30)/2");
        assert!((s.mean[1] - 30.0).abs() < 1e-9, "mean1=(20+40)/2");
        assert!((s.min[0] - 10.0).abs() < 1e-9);
        assert!((s.max[1] - 40.0).abs() < 1e-9);
        assert!((s.median[0] - 20.0).abs() < 1e-9, "median of 10/30 interp =20");
        assert_eq!(s.mean.len(), 2);
    }

    #[test]
    fn test_scs_unit_hydrograph_normalized() {
        let uh = scs_unit_hydrograph(2, 5);
        assert_eq!(uh.len(), 5);
        let sum: f64 = uh.iter().sum();
        assert!((sum - 1.0).abs() < 1e-9, "UH 应归一化 Σ=1, got {}", sum);
        // 峰在第 2 步(三角:0,0.5,1,0.67,0.33 归一化前 → 峰在 idx2)
        let peak_idx = uh.iter().enumerate()
            .max_by(|a, b| a.1.partial_cmp(b.1).unwrap()).unwrap().0;
        assert_eq!(peak_idx, 2);
    }

    #[test]
    fn test_event_uh_forecast_unit_pulse_and_lag() {
        // uh=[1.0](无延迟):恒定雨 → 稳态 q=rain·coef;coef=1000·1000/3600≈277.78
        let q = event_uh_forecast(&[10.0; 4], &[1.0], 1000.0, 1.0);
        let coef = 1000.0 * 1000.0 / 3600.0;
        for v in &q {
            assert!((v - 10.0 * coef).abs() < 1e-3, "稳态 q, got {}", v);
        }
        // uh=[0.5,0.5]:单脉冲雨 [10,0] → t0:0.5·10·coef; t1:0.5·10·coef(延迟)
        let q2 = event_uh_forecast(&[10.0, 0.0], &[0.5, 0.5], 1000.0, 1.0);
        assert!((q2[0] - 0.5 * 10.0 * coef).abs() < 1e-3, "t0 half, got {}", q2[0]);
        assert!((q2[1] - 0.5 * 10.0 * coef).abs() < 1e-3, "t1 delayed half, got {}", q2[1]);
    }
}