Skip to main content

hydro_core/
metrics.rs

1//! Evaluation metrics for hydrological model comparison.
2//!
3//! Three families:
4//! - **Deterministic single-series scores** — [`nse`] (equivalent to the
5//!   deterministic coefficient DC in the Chinese standard), [`kge`], [`rmse`],
6//!   [`pbias`], [`r2`] — with [`dc_grade`] mapping DC to the GB/T 22482-2008
7//!   甲 / 乙 / 丙 / 不合格 grade band.
8//! - **GB/T 22482-2008 flood-event qualification** — [`event_errors`],
9//!   [`event_qualified`], [`qualified_rate`], [`qualification_grade`],
10//!   [`scheme_grade`] — bundled by [`compute_metrics_gbt`] for one-shot
11//!   scoring.
12//! - **Ensemble probabilistic verification** — fair [`crps`], [`brier`],
13//!   [`pod_far_csi`] contingency, [`ensemble_exceedance`], and the Talagrand
14//!   [`rank_histogram`], collected by [`compute_probabilistic`].
15
16use serde::{Serialize, Deserialize};
17
18/// Nash–Sutcliffe Efficiency (NSE), equal to the deterministic coefficient
19/// DC (确定性系数) in the Chinese standard.
20///
21/// Formula: `NSE = 1 − Σᵢ(oᵢ − sᵢ)² / Σᵢ(oᵢ − ō)²`, where `ō` is the
22/// observed mean.
23///
24/// Range: `(−∞, 1]`. `1.0` is a perfect simulation; `0.0` means the
25/// simulation is exactly as informative as predicting the observed mean;
26/// values `< 0` mean the observed mean is a better predictor. Returns
27/// `NaN` for empty / mismatched slices or a constant observed series
28/// (zero denominator).
29pub fn nse(obs: &[f64], sim: &[f64]) -> f64 {
30    if obs.is_empty() || obs.len() != sim.len() {
31        return f64::NAN;
32    }
33    let mean_o = obs.iter().sum::<f64>() / obs.len() as f64;
34    let ss_res: f64 = obs.iter().zip(sim).map(|(o, s)| (o - s).powi(2)).sum();
35    let ss_tot: f64 = obs.iter().map(|o| (o - mean_o).powi(2)).sum();
36    if ss_tot < 1e-12 {
37        return f64::NAN;
38    }
39    1.0 - ss_res / ss_tot
40}
41
42/// Kling–Gupta Efficiency (Gupta et al. 2009).
43///
44/// Decomposes simulation error into three components and combines them:
45/// `KGE = 1 − √( (r−1)² + (α−1)² + (β−1)² )`, where `r` is the Pearson
46/// correlation, `α = σ_s / σ_o` the variability ratio, and `β = μ_s / μ_o`
47/// the bias ratio.
48///
49/// Range: `(−∞, 1]`, with `1.0` perfect. Compared to NSE, KGE penalises
50/// bias and variability mismatch explicitly, so it is less likely to
51/// reward mean-tracking simulations. Returns `NaN` for slices shorter
52/// than 2, mismatched lengths, or zero variance in either series.
53pub fn kge(obs: &[f64], sim: &[f64]) -> f64 {
54    if obs.len() < 2 || obs.len() != sim.len() {
55        return f64::NAN;
56    }
57    let n = obs.len() as f64;
58    let mean_o = obs.iter().sum::<f64>() / n;
59    let mean_s = sim.iter().sum::<f64>() / n;
60    let std_o = (obs.iter().map(|o| (o - mean_o).powi(2)).sum::<f64>() / n).sqrt();
61    let std_s = (sim.iter().map(|s| (s - mean_s).powi(2)).sum::<f64>() / n).sqrt();
62    if std_o < 1e-12 || std_s < 1e-12 {
63        return f64::NAN;
64    }
65    // Pearson correlation
66    let cov: f64 = obs.iter().zip(sim)
67        .map(|(o, s)| (o - mean_o) * (s - mean_s))
68        .sum::<f64>() / n;
69    let r = cov / (std_o * std_s);
70    let alpha = std_s / std_o;
71    let beta = mean_s / mean_o;
72    let ed = (r - 1.0).powi(2) + (alpha - 1.0).powi(2) + (beta - 1.0).powi(2);
73    1.0 - ed.sqrt()
74}
75
76/// Root-Mean-Square Error.
77///
78/// Formula: `RMSE = √( (1/N) Σᵢ(oᵢ − sᵢ)² )`.
79///
80/// Same units as the input series (typically m³/s). Lower is better;
81/// `0.0` is perfect. Returns `NaN` for empty / mismatched slices.
82pub fn rmse(obs: &[f64], sim: &[f64]) -> f64 {
83    if obs.is_empty() || obs.len() != sim.len() {
84        return f64::NAN;
85    }
86    let ssq: f64 = obs.iter().zip(sim).map(|(o, s)| (o - s).powi(2)).sum();
87    (ssq / obs.len() as f64).sqrt()
88}
89
90/// Percent Bias, `PBIAS = 100 · (Σs − Σo) / Σo` (%).
91///
92/// Positive means overprediction, negative means underprediction.
93/// `0.0` is perfect. Returns `NaN` when the observed sum is ~zero.
94pub fn pbias(obs: &[f64], sim: &[f64]) -> f64 {
95    let sum_o: f64 = obs.iter().sum();
96    if sum_o.abs() < 1e-12 {
97        return f64::NAN;
98    }
99    let sum_s: f64 = sim.iter().sum();
100    100.0 * (sum_s - sum_o) / sum_o
101}
102
103/// Coefficient of Determination, R² = (cov(o, s) / (σ_o · σ_s))².
104///
105/// Range: `[0, 1]`, with `1.0` a perfect linear relationship. Captures
106/// phase/amplitude agreement only after linear scaling, so it should be
107/// reported alongside PBIAS. Returns `NaN` for slices shorter than 2,
108/// mismatched lengths, or zero variance in either series.
109pub fn r2(obs: &[f64], sim: &[f64]) -> f64 {
110    if obs.len() < 2 || obs.len() != sim.len() {
111        return f64::NAN;
112    }
113    let n = obs.len() as f64;
114    let mean_o = obs.iter().sum::<f64>() / n;
115    let mean_s = sim.iter().sum::<f64>() / n;
116    let ss_oo: f64 = obs.iter().map(|o| (o - mean_o).powi(2)).sum();
117    let ss_ss: f64 = sim.iter().map(|s| (s - mean_s).powi(2)).sum();
118    let ss_os: f64 = obs.iter().zip(sim).map(|(o, s)| (o - mean_o) * (s - mean_s)).sum();
119    if ss_oo < 1e-12 || ss_ss < 1e-12 {
120        return f64::NAN;
121    }
122    (ss_os / (ss_oo * ss_ss).sqrt()).powi(2)
123}
124
125/// Map a DC (= NSE) value to its GB/T 22482-2008 accuracy grade.
126///
127/// Bands: `甲 (excellent) ≥ 0.90`, `乙 (good) ≥ 0.70`, `丙 (acceptable) ≥ 0.50`,
128/// otherwise `不合格 (failed)`. 丙 is the minimum grade acceptable for
129/// operational flood-forecast services.
130pub fn dc_grade(dc: f64) -> &'static str {
131    if dc >= 0.90 { "甲" }
132    else if dc >= 0.70 { "乙" }
133    else if dc >= 0.50 { "丙" }
134    else { "不合格" }
135}
136
137// ── GB/T 22482-2008 event errors + qualification rate ────────────────
138
139/// Per-event GB/T 22482-2008 flood-forecast errors (relative errors in %,
140/// peak-timing error in time-steps).
141#[derive(Clone, Debug, Serialize, Deserialize, Default)]
142pub struct GbtEventErrors {
143    /// Peak-discharge relative error, `100 · (Qpk_sim − Qpk_obs) / Qpk_obs` (%).
144    pub peak_rel_err_pct: f64,
145    /// Peak-timing error in time-steps, `argmax(sim) − argmax(obs)`.
146    /// Positive means the simulated peak is late (lagging); negative means early.
147    pub time_to_peak_err_steps: i64,
148    /// Runoff-depth relative error, `100 · (D_sim − D_obs) / D_obs` (%).
149    /// `D` (mm) is converted from discharge volume via
150    /// `D = ΣQ · dt_h · 3.6 / area_km2` (Q in m³/s, dt_h in hours).
151    pub runoff_depth_rel_err_pct: f64,
152}
153
154/// GB/T 22482-2008 qualification tolerance for a single flood event.
155///
156/// A forecast is 合格 (qualified) when all three errors fall within the
157/// corresponding absolute bounds.
158#[derive(Clone, Debug, Serialize, Deserialize)]
159pub struct QualificationTolerance {
160    /// Maximum allowed absolute peak-discharge relative error (%).
161    pub peak_rel_pct: f64,
162    /// Maximum allowed absolute peak-timing error (in time-steps).
163    pub time_to_peak_steps: i64,
164    /// Maximum allowed absolute runoff-depth relative error (%).
165    pub runoff_depth_rel_pct: f64,
166}
167
168impl Default for QualificationTolerance {
169    /// Default tolerance per GB/T 22482 practice: peak ±20%, peak timing
170    /// ±1 time-step, runoff depth ±20%.
171    fn default() -> Self {
172        Self { peak_rel_pct: 20.0, time_to_peak_steps: 1, runoff_depth_rel_pct: 20.0 }
173    }
174}
175
176/// Compute the GB/T 22482-2008 event errors for one flood.
177///
178/// `area_km2` is the basin drainage area; `dt_h` the time-step in hours.
179/// Both are needed to convert the discharge hydrograph to runoff depth (mm).
180/// Returns zeros (the `Default` value) when any input is empty or non-positive.
181pub fn event_errors(obs: &[f64], sim: &[f64], area_km2: f64, dt_h: f64) -> GbtEventErrors {
182    let mut e = GbtEventErrors::default();
183    if obs.is_empty() || sim.is_empty() || area_km2 <= 0.0 || dt_h <= 0.0 {
184        return e;
185    }
186    let (obs_pk, obs_idx) = argmax(obs);
187    let (sim_pk, sim_idx) = argmax(sim);
188    if obs_pk.abs() > 1e-9 {
189        e.peak_rel_err_pct = 100.0 * (sim_pk - obs_pk) / obs_pk;
190    }
191    e.time_to_peak_err_steps = sim_idx as i64 - obs_idx as i64;
192    let d_obs = runoff_depth_mm(obs, area_km2, dt_h);
193    let d_sim = runoff_depth_mm(sim, area_km2, dt_h);
194    if d_obs.abs() > 1e-9 {
195        e.runoff_depth_rel_err_pct = 100.0 * (d_sim - d_obs) / d_obs;
196    }
197    e
198}
199
200/// Decide whether a single event is 合格 (qualified) under the given tolerance:
201/// all three errors (peak, peak timing, runoff depth) must be within bounds.
202pub fn event_qualified(e: &GbtEventErrors, tol: &QualificationTolerance) -> bool {
203    e.peak_rel_err_pct.abs() <= tol.peak_rel_pct
204        && e.time_to_peak_err_steps.abs() <= tol.time_to_peak_steps
205        && e.runoff_depth_rel_err_pct.abs() <= tol.runoff_depth_rel_pct
206}
207
208/// Aggregated qualification report across many flood events.
209#[derive(Clone, Debug, Serialize, Deserialize, Default)]
210pub struct QualificationReport {
211    /// Total number of events evaluated.
212    pub total: usize,
213    /// Number of events that were 合格 (qualified).
214    pub qualified: usize,
215    /// Qualification rate, `100 · qualified / total` (%).
216    pub rate_pct: f64,
217    /// Grade label (甲 / 乙 / 丙 / 不合格) derived from `rate_pct` by
218    /// [`qualification_grade`].
219    pub grade: String,
220}
221
222/// Aggregate per-event qualified flags into a [`QualificationReport`].
223///
224/// `rate_pct = 100 · qualified / total`, with `rate_pct = 0` when the input
225/// is empty.
226pub fn qualified_rate(qualified_flags: &[bool]) -> QualificationReport {
227    let total = qualified_flags.len();
228    let qualified = qualified_flags.iter().filter(|&&q| q).count();
229    let rate_pct = if total == 0 {
230        0.0
231    } else {
232        100.0 * qualified as f64 / total as f64
233    };
234    QualificationReport {
235        total,
236        qualified,
237        rate_pct,
238        grade: qualification_grade(rate_pct).to_string(),
239    }
240}
241
242/// GB/T 22482-2008 grade for the qualification rate.
243///
244/// Bands: 甲 ≥ 85%, 乙 70–85%, 丙 60–70%, otherwise 不合格.
245pub fn qualification_grade(rate_pct: f64) -> &'static str {
246    if rate_pct >= 85.0 { "甲" }
247    else if rate_pct >= 70.0 { "乙" }
248    else if rate_pct >= 60.0 { "丙" }
249    else { "不合格" }
250}
251
252/// Overall scheme grade = the lower of the DC grade and the qualification-rate
253/// grade. 丙 is the minimum grade acceptable for operational flood-forecast
254/// services.
255pub fn scheme_grade(dc_grade: &str, qual_grade: &str) -> &'static str {
256    let rank = |g: &str| -> i32 {
257        match g { "甲" => 3, "乙" => 2, "丙" => 1, _ => 0 }
258    };
259    match rank(dc_grade).min(rank(qual_grade)) {
260        3 => "甲",
261        2 => "乙",
262        1 => "丙",
263        _ => "不合格",
264    }
265}
266
267/// Full metrics report for one model's simulation vs observation.
268///
269/// `gbt` and `qualified` are populated only when the caller supplies basin
270/// area and time-step (via [`compute_metrics_gbt`]); they are `None` from
271/// [`compute_metrics`].
272#[derive(Clone, Debug, Serialize, Deserialize, Default)]
273pub struct MetricsReport {
274    /// Nash–Sutcliffe Efficiency (= DC 确定性系数). Range `(−∞, 1]`.
275    pub nse: f64,
276    /// Kling–Gupta Efficiency. Range `(−∞, 1]`.
277    pub kge: f64,
278    /// Root-mean-square error (same units as input, typically m³/s).
279    pub rmse: f64,
280    /// Percent bias (%). Positive = overprediction.
281    pub pbias: f64,
282    /// Coefficient of determination R². Range `[0, 1]`.
283    pub r2: f64,
284    /// DC grade label (甲 / 乙 / 丙 / 不合格) from [`dc_grade`] on `nse`.
285    pub grade: String,
286    /// GB/T 22482-2008 event errors. `None` unless area/dt were supplied.
287    pub gbt: Option<GbtEventErrors>,
288    /// Whether the event is 合格 under the supplied tolerance. `None` unless
289    /// area/dt were supplied.
290    pub qualified: Option<bool>,
291}
292
293/// Compute all deterministic scores at once. `gbt` and `qualified` are
294/// left as `None` (use [`compute_metrics_gbt`] to populate them).
295pub fn compute_metrics(obs: &[f64], sim: &[f64]) -> MetricsReport {
296    let n = nse(obs, sim);
297    MetricsReport {
298        nse: n,
299        kge: kge(obs, sim),
300        rmse: rmse(obs, sim),
301        pbias: pbias(obs, sim),
302        r2: r2(obs, sim),
303        grade: dc_grade(n).to_string(),
304        gbt: None,
305        qualified: None,
306    }
307}
308
309/// Compute all deterministic scores plus GB/T 22482-2008 event errors and
310/// qualification under the supplied tolerance.
311///
312/// `area_km2` converts discharge volume to runoff depth; `dt_h` is the
313/// time-step in hours.
314pub fn compute_metrics_gbt(
315    obs: &[f64],
316    sim: &[f64],
317    area_km2: f64,
318    dt_h: f64,
319    tol: &QualificationTolerance,
320) -> MetricsReport {
321    let mut m = compute_metrics(obs, sim);
322    let e = event_errors(obs, sim, area_km2, dt_h);
323    m.qualified = Some(event_qualified(&e, tol));
324    m.gbt = Some(e);
325    m
326}
327
328// ── Probabilistic / ensemble scores (CRPS / POD-FAR-CSI / Brier) ──────
329
330/// Ensemble probabilistic verification report.
331#[derive(Clone, Debug, Serialize, Deserialize, Default)]
332pub struct ProbabilisticReport {
333    /// Fair Continuous Ranked Probability Score (CRPS), averaged over
334    /// time-steps. Lower is better; `0.0` for a perfect ensemble (every
335    /// member equals the observation).
336    pub crps: f64,
337    /// Brier score for the threshold-exceedance probability. Range `[0, 1]`;
338    /// `0.0` perfect, `1.0` worst.
339    pub brier: f64,
340    /// Probability of Detection, `POD = hits / (hits + misses)`. Range
341    /// `[0, 1]`, `1.0` perfect. `NaN` when there are no observed exceedances.
342    pub pod: f64,
343    /// False-Alarm Ratio, `FAR = false_alarms / (hits + false_alarms)`. Range
344    /// `[0, 1]`, `0.0` perfect. `NaN` when there are no forecast exceedances.
345    pub far: f64,
346    /// Critical Success Index, `CSI = hits / (hits + misses + false_alarms)`.
347    /// Range `[0, 1]`, `1.0` perfect. `NaN` when all three counts are zero.
348    pub csi: f64,
349}
350
351/// Per time-step exceedance probability, `|{m : m[t] > threshold}| / M`.
352///
353/// Ensemble members shorter than `M` are treated as non-exceeding at the
354/// missing time-steps. Returns an empty `Vec` when the ensemble is empty.
355pub fn ensemble_exceedance(ensemble: &[Vec<f64>], threshold: f64) -> Vec<f64> {
356    if ensemble.is_empty() {
357        return Vec::new();
358    }
359    let n_t = ensemble.iter().map(|m| m.len()).max().unwrap_or(0);
360    let m = ensemble.len() as f64;
361    (0..n_t)
362        .map(|t| {
363            let cnt = ensemble.iter()
364                .filter(|mem| mem.get(t).map_or(false, |v| *v > threshold))
365                .count() as f64;
366            cnt / m
367        })
368        .collect()
369}
370
371/// Fair Continuous Ranked Probability Score (Gneiting & Raftery 2007;
372/// Ferro 2017), averaged over time-steps.
373///
374/// Per step: `CRPS_t = (1/M) Σₘ |xₘ − y| − (1/(2M²)) Σₘ Σₙ |xₘ − xₙ|`.
375///
376/// The second term is the ensemble-mean absolute pairwise spread; removing
377/// the standard `(1/(2M))` self-term bias yields the *fair* CRPS, which
378/// approaches the score of a deterministic forecast (`MAE`) as `M → 1`.
379/// Time-steps where any member is missing are skipped. Returns `NaN` if
380/// no time-step can be evaluated.
381pub fn crps(ensemble: &[Vec<f64>], observed: &[f64]) -> f64 {
382    if ensemble.is_empty() || observed.is_empty() {
383        return f64::NAN;
384    }
385    let m = ensemble.len();
386    let mf = m as f64;
387    let mut sum = 0.0;
388    let mut count = 0usize;
389    for (t, &y) in observed.iter().enumerate() {
390        let vals: Vec<f64> = ensemble.iter().filter_map(|mem| mem.get(t).copied()).collect();
391        if vals.len() != m {
392            continue; // 该时步成员不全,跳过
393        }
394        let mae: f64 = vals.iter().map(|x| (x - y).abs()).sum::<f64>() / mf;
395        let mut pair = 0.0;
396        for i in 0..m {
397            for j in 0..m {
398                pair += (vals[i] - vals[j]).abs();
399            }
400        }
401        let spread = pair / (2.0 * mf * mf);
402        sum += (mae - spread).max(0.0);
403        count += 1;
404    }
405    if count == 0 { f64::NAN } else { sum / count as f64 }
406}
407
408/// Brier score for the threshold-exceedance probability.
409///
410/// Formula: `BS = (1/N) Σᵢ (pᵢ − oᵢ)²`, with `oᵢ ∈ {0, 1}` the observed
411/// exceedance indicator. Range `[0, 1]`; `0.0` perfect, `1.0` worst.
412/// Returns `NaN` for empty / mismatched slices.
413pub fn brier(prob_exceed: &[f64], observed_exceed: &[bool]) -> f64 {
414    if prob_exceed.is_empty() || prob_exceed.len() != observed_exceed.len() {
415        return f64::NAN;
416    }
417    let n = prob_exceed.len() as f64;
418    prob_exceed.iter().zip(observed_exceed.iter())
419        .map(|(p, o)| (p - if *o { 1.0 } else { 0.0 }).powi(2))
420        .sum::<f64>() / n
421}
422
423/// Threshold-exceedance contingency table → `(POD, FAR, CSI)`.
424///
425/// Counts: `hits = a` (forecast exceed ∧ observed exceed),
426/// `misses = b` (forecast no ∧ observed yes),
427/// `false_alarms = c` (forecast yes ∧ observed no). Then
428/// `POD = a / (a + b)`, `FAR = c / (a + c)`,
429/// `CSI = a / (a + b + c)`. Each ratio is `NaN` when its denominator is zero.
430pub fn pod_far_csi(forecast_exceed: &[bool], observed_exceed: &[bool]) -> (f64, f64, f64) {
431    let mut hits = 0.0;         // a: 预报超 ∧ 观测超
432    let mut misses = 0.0;       // b: 预报未超 ∧ 观测超
433    let mut false_alarms = 0.0; // c: 预报超 ∧ 观测未超
434    for (f, o) in forecast_exceed.iter().zip(observed_exceed.iter()) {
435        match (*f, *o) {
436            (true, true) => hits += 1.0,
437            (false, true) => misses += 1.0,
438            (true, false) => false_alarms += 1.0,
439            (false, false) => {} // 正确拒绝
440        }
441    }
442    let pod = if hits + misses > 0.0 { hits / (hits + misses) } else { f64::NAN };
443    let far = if hits + false_alarms > 0.0 { false_alarms / (hits + false_alarms) } else { f64::NAN };
444    let csi = if hits + misses + false_alarms > 0.0 {
445        hits / (hits + misses + false_alarms)
446    } else { f64::NAN };
447    (pod, far, csi)
448}
449
450/// All-in-one ensemble probabilistic verification.
451///
452/// Forecast exceedance = ensemble exceedance probability `> 0.5`;
453/// observed exceedance = `observed > threshold`. The two boolean series are
454/// aligned to the shorter length (the minimum of `observed.len()` and the
455/// ensemble's longest member length).
456pub fn compute_probabilistic(
457    ensemble: &[Vec<f64>],
458    observed: &[f64],
459    threshold: f64,
460) -> ProbabilisticReport {
461    let prob = ensemble_exceedance(ensemble, threshold);
462    let n = observed.len().min(prob.len());
463    let prob_aligned: Vec<f64> = prob.iter().take(n).copied().collect();
464    let obs_exceed: Vec<bool> = observed[..n].iter().map(|&q| q > threshold).collect();
465    let fcst_exceed: Vec<bool> = prob_aligned.iter().map(|&p| p > 0.5).collect();
466    let (pod, far, csi) = pod_far_csi(&fcst_exceed, &obs_exceed);
467    ProbabilisticReport {
468        crps: crps(ensemble, observed),
469        brier: brier(&prob_aligned, &obs_exceed),
470        pod, far, csi,
471    }
472}
473
474/// Talagrand rank histogram (verification rank histogram).
475///
476/// For each time-step, counts how many ensemble members rank below the
477/// observation (strictly smaller) and increments the corresponding bin of
478/// size `M + 1`. Time-steps with any missing member are skipped.
479///
480/// Interpretation: a flat histogram indicates a reliable ensemble; a U-shape
481/// indicates under-dispersion (overconfidence); a dome-shape indicates
482/// over-dispersion. Returns an empty `Vec` for empty inputs.
483pub fn rank_histogram(ensemble: &[Vec<f64>], observed: &[f64]) -> Vec<usize> {
484    if ensemble.is_empty() || observed.is_empty() {
485        return Vec::new();
486    }
487    let m = ensemble.len();
488    let mut hist = vec![0usize; m + 1];
489    for (t, &y) in observed.iter().enumerate() {
490        let vals: Vec<f64> = ensemble.iter().filter_map(|mem| mem.get(t).copied()).collect();
491        if vals.len() != m {
492            continue;
493        }
494        // rank = 严格小于观测的成员数(观测落在该秩区间)
495        let rank = vals.iter().filter(|&&x| x < y).count();
496        hist[rank] += 1;
497    }
498    hist
499}
500
501// ── helpers ──
502
503fn argmax(xs: &[f64]) -> (f64, usize) {
504    let mut best = f64::NEG_INFINITY;
505    let mut idx = 0;
506    for (i, &v) in xs.iter().enumerate() {
507        if v > best {
508            best = v;
509            idx = i;
510        }
511    }
512    (best, idx)
513}
514
515/// 径流深(mm)= ΣQ·dt_h·3.6 / area_km2(Q m³/s, dt_h 小时, area km²)。
516fn runoff_depth_mm(q: &[f64], area_km2: f64, dt_h: f64) -> f64 {
517    let sum_q: f64 = q.iter().sum();
518    sum_q * dt_h * 3.6 / area_km2
519}
520
521#[cfg(test)]
522mod tests {
523    use super::*;
524
525    #[test]
526    fn test_nse_perfect() {
527        let obs = vec![1.0, 2.0, 3.0, 4.0, 5.0];
528        assert!((nse(&obs, &obs) - 1.0).abs() < 1e-10);
529    }
530
531    #[test]
532    fn test_nse_mean_prediction() {
533        let obs = vec![1.0, 2.0, 3.0, 4.0, 5.0];
534        let sim = vec![3.0; 5]; // mean
535        assert!((nse(&obs, &sim) - 0.0).abs() < 1e-10);
536    }
537
538    #[test]
539    fn test_kge_perfect() {
540        let obs = vec![10.0, 20.0, 30.0, 40.0];
541        assert!((kge(&obs, &obs) - 1.0).abs() < 1e-10);
542    }
543
544    #[test]
545    fn test_rmse() {
546        let obs = vec![1.0, 2.0, 3.0];
547        let sim = vec![1.0, 2.0, 4.0];
548        // RMSE = sqrt((0+0+1)/3) = sqrt(1/3) ≈ 0.577
549        assert!((rmse(&obs, &sim) - (1.0_f64 / 3.0).sqrt()).abs() < 1e-10);
550    }
551
552    #[test]
553    fn test_pbias() {
554        let obs = vec![100.0, 200.0];
555        let sim = vec![110.0, 220.0];
556        // PBIAS = 100*(330-300)/300 = 10%
557        assert!((pbias(&obs, &sim) - 10.0).abs() < 1e-10);
558    }
559
560    #[test]
561    fn test_r2_perfect() {
562        let obs = vec![1.0, 2.0, 3.0, 4.0, 5.0];
563        assert!((r2(&obs, &obs) - 1.0).abs() < 1e-10);
564    }
565
566    #[test]
567    fn test_dc_grade() {
568        assert_eq!(dc_grade(0.95), "甲");
569        assert_eq!(dc_grade(0.85), "乙");
570        assert_eq!(dc_grade(0.60), "丙");
571        assert_eq!(dc_grade(0.30), "不合格");
572    }
573
574    #[test]
575    fn test_compute_metrics() {
576        let obs = vec![10.0, 20.0, 30.0, 40.0, 50.0];
577        let m = compute_metrics(&obs, &obs);
578        assert!((m.nse - 1.0).abs() < 1e-10);
579        assert_eq!(m.grade, "甲");
580        assert!(m.gbt.is_none() && m.qualified.is_none(), "compute_metrics 不应填 GB/T");
581    }
582
583    #[test]
584    fn test_event_errors_perfect() {
585        // obs==sim → 三项误差全 0;径流深 = ΣQ·1·3.6/1000 = 150·3.6/1000 = 0.54 mm
586        let obs = vec![10.0, 20.0, 30.0, 40.0, 50.0];
587        let e = event_errors(&obs, &obs, 1000.0, 1.0);
588        assert!(e.peak_rel_err_pct.abs() < 1e-9);
589        assert_eq!(e.time_to_peak_err_steps, 0);
590        assert!(e.runoff_depth_rel_err_pct.abs() < 1e-9);
591    }
592
593    #[test]
594    fn test_event_errors_peak_and_timing() {
595        // obs 峰在第 4 步=50;sim 峰在第 2 步=45(超前 2 步,峰值偏小 10%)
596        let obs = vec![10.0, 20.0, 30.0, 40.0, 50.0];
597        let sim = vec![10.0, 20.0, 45.0, 30.0, 10.0];
598        let e = event_errors(&obs, &sim, 1000.0, 1.0);
599        assert!((e.peak_rel_err_pct - (-10.0)).abs() < 1e-6, "峰偏 -10%, 得 {}", e.peak_rel_err_pct);
600        assert_eq!(e.time_to_peak_err_steps, -2, "超前 2 步");
601    }
602
603    #[test]
604    fn test_event_qualified_boundary() {
605        let tol = QualificationTolerance::default();
606        // 三项都在限内 → 合格
607        let ok = GbtEventErrors { peak_rel_err_pct: 19.0, time_to_peak_err_steps: 1, runoff_depth_rel_err_pct: -15.0 };
608        assert!(event_qualified(&ok, &tol));
609        // 峰超限 → 不合格
610        let bad = GbtEventErrors { peak_rel_err_pct: 21.0, time_to_peak_err_steps: 0, runoff_depth_rel_err_pct: 0.0 };
611        assert!(!event_qualified(&bad, &tol));
612    }
613
614    #[test]
615    fn test_qualified_rate_and_grade() {
616        // 9/10 合格 = 90% → 甲
617        let flags = vec![true; 9].into_iter().chain(std::iter::once(false)).collect::<Vec<_>>();
618        let r = qualified_rate(&flags);
619        assert_eq!(r.total, 10);
620        assert_eq!(r.qualified, 9);
621        assert!((r.rate_pct - 90.0).abs() < 1e-9);
622        assert_eq!(r.grade, "甲");
623        assert_eq!(qualification_grade(75.0), "乙");
624        assert_eq!(qualification_grade(65.0), "丙");
625        assert_eq!(qualification_grade(50.0), "不合格");
626    }
627
628    #[test]
629    fn test_scheme_grade_takes_lower() {
630        assert_eq!(scheme_grade("甲", "乙"), "乙"); // 取低
631        assert_eq!(scheme_grade("丙", "甲"), "丙");
632        assert_eq!(scheme_grade("甲", "甲"), "甲");
633        assert_eq!(scheme_grade("乙", "不合格"), "不合格");
634    }
635
636    #[test]
637    fn test_compute_metrics_gbt_qualified() {
638        let obs = vec![10.0, 20.0, 30.0, 40.0, 50.0];
639        // sim 完全一致 → 合格
640        let m = compute_metrics_gbt(&obs, &obs, 1000.0, 1.0, &Default::default());
641        assert_eq!(m.qualified, Some(true));
642        assert!(m.gbt.is_some());
643    }
644
645    #[test]
646    fn test_crps_perfect_ensemble_zero() {
647        // 成员全 = obs → CRPS = 0
648        let obs = vec![10.0, 20.0, 30.0];
649        let ens = vec![obs.clone(), obs.clone(), obs.clone()];
650        assert!(crps(&ens, &obs).abs() < 1e-9);
651    }
652
653    #[test]
654    fn test_crps_single_member_is_mae_and_spread_lowers() {
655        let obs = vec![0.0];
656        // 单成员 [10] → CRPS = MAE = 10(spread 项=0)
657        assert!((crps(&[vec![10.0]], &obs) - 10.0).abs() < 1e-9);
658        // 双成员 [0,10]:mae=(0+10)/2=5;spread=(1/8)·20=2.5 → CRPS=2.5
659        assert!((crps(&[vec![0.0], vec![10.0]], &obs) - 2.5).abs() < 1e-9);
660    }
661
662    #[test]
663    fn test_brier_perfect_and_worst() {
664        let obs = vec![true, false, true];
665        assert!(brier(&[1.0, 0.0, 1.0], &obs).abs() < 1e-9); // 完美
666        assert!((brier(&[0.0, 1.0, 0.0], &obs) - 1.0).abs() < 1e-9); // 最差
667    }
668
669    #[test]
670    fn test_pod_far_csi_contingency() {
671        // 3 命中 + 1 漏报 + 2 误报(+ 2 正确拒绝)
672        let fcst = vec![true, true, true, false, true, true, false, false];
673        let obs = vec![true, true, true, true, false, false, false, false];
674        let (pod, far, csi) = pod_far_csi(&fcst, &obs);
675        assert!((pod - 0.75).abs() < 1e-9, "POD=3/4, got {}", pod);
676        assert!((far - 0.4).abs() < 1e-9, "FAR=2/5, got {}", far);
677        assert!((csi - 0.5).abs() < 1e-9, "CSI=3/6, got {}", csi);
678    }
679
680    #[test]
681    fn test_ensemble_exceedance_fraction() {
682        let ens = vec![vec![10.0, 20.0, 5.0], vec![15.0, 5.0, 5.0], vec![20.0, 25.0, 5.0]];
683        let prob = ensemble_exceedance(&ens, 12.0);
684        // t0:{10,15,20}→2/3; t1:{20,5,25}→2/3; t2:{5,5,5}→0
685        assert!((prob[0] - 2.0 / 3.0).abs() < 1e-9);
686        assert!((prob[1] - 2.0 / 3.0).abs() < 1e-9);
687        assert!(prob[2].abs() < 1e-9);
688    }
689
690    #[test]
691    fn test_compute_probabilistic_end_to_end() {
692        // 2 成员,obs=[10,30];阈值=20。成员1=[12,28],成员2=[8,32]
693        let ens = vec![vec![12.0, 28.0], vec![8.0, 32.0]];
694        let obs = vec![10.0, 30.0];
695        let r = compute_probabilistic(&ens, &obs, 20.0);
696        // 超限概率:t0={12,8}→0(都≤20); t1={28,32}→1(都>20)
697        // fcst 超限(>0.5):[false,true]; obs 超限(>20):[false,true] → 完美:POD=1,FAR=0,CSI=1
698        assert!((r.pod - 1.0).abs() < 1e-9);
699        assert!(r.far.abs() < 1e-9);
700        assert!((r.csi - 1.0).abs() < 1e-9);
701        // Brier:prob=[0,1],obs指示=[0,1] → 0
702        assert!(r.brier.abs() < 1e-9);
703    }
704
705    #[test]
706    fn test_rank_histogram_bins() {
707        // 2 成员,t0:成员[1,3] obs=2 → rank=1(只有1<2);t1:成员[2,4] obs=3 → rank=1(只有2<3)
708        let ens = vec![vec![1.0, 2.0], vec![3.0, 4.0]];
709        let obs = vec![2.0, 3.0];
710        let h = rank_histogram(&ens, &obs);
711        assert_eq!(h, vec![0, 2, 0], "两步都落 bin1, got {:?}", h);
712        // 观测恒低于所有成员 → 全落 bin0
713        let h2 = rank_histogram(&vec![vec![10.0], vec![20.0]], &[5.0]);
714        assert_eq!(h2, vec![1, 0, 0]);
715    }
716}