Skip to main content

hydro_swat/
lib.rs

1//! SWAT+ LTE 简化驱动(水文核心)——忠实移植自 `swatplus/src/hru_lte_control.f90`。
2//!
3//! Clean-room 从 USDA-ARS SWAT+ (github.com/swat-model/swatplus, 公共领域) 算法移植。
4//! 单文件日驱动:SCS-CN 两阶段(日 CN 从土壤湿度→Q)+ 雪 + Hargreaves/PT PET + AET
5//! + 侧向流 + 暗管 + 渗漏 + 指数地下水退水。单位:mm / day(与 SWAT+ 一致)。
6//!
7//! 交叉验证:`tests/swat_crosscheck.rs`(待加)vs SWAT+ on Ames_sub1(12 HRU, 46 年)。
8//!
9//! # English summary
10//!
11//! SWAT+ LTE (Long-Term Evaluation) simplified driver — the daily hydrology
12//! core, faithful port of the algorithm in `swatplus/src/hru_lte_control.f90`.
13//! Single-file daily driver: two-stage SCS-CN (daily curve number updated from
14//! soil moisture, then runoff), snow accumulation/melt, Hargreaves or
15//! Priestley–Taylor potential ET, actual ET, lateral flow, tile drainage,
16//! percolation, and exponential groundwater recession. Units are mm/day to
17//! match SWAT+.
18//!
19//! **Clean-room statement:** this Rust implementation is a clean-room port of
20//! USDA-ARS SWAT+ ([`swatplus`]), which is public domain (US government work).
21//! The algorithm is not copyrighted; the Fortran source was used only as a
22//! behaviour oracle for cross-verification. No Fortran source code is
23//! reproduced here.
24//!
25//! [`swatplus`]: https://github.com/swat-model/swatplus
26//!
27//! For the full per-layer HRU module set (canopy interception, multi-layer
28//! percolation, plant phenology, soil temperature, Penman–Monteith PET, etc.)
29//! see the [`swat_hru`] submodule — a clean-room port of `hru_control.f90`'s
30//! hydrology subset, bit-exact against SWAT+ on the Ames_sub1 dataset (12 HRU,
31//! 46 years).
32//!
33//! Cross-verification: `tests/swat_crosscheck.rs` against SWAT+ on Ames_sub1
34//! (available from TAMU SWAT+ `Example_datasets`). Implements
35//! [`hydro_core::HydroModel`] so the model can be orchestrated by
36//! `hydro-platform`.
37
38// Lint suppressions: the SWAT+ LTE numerical core is a faithful clean-room
39// port of USDA-ARS SWAT+ (public domain) and is bit-exact-verified against
40// the Fortran reference. Some intermediate locals mirror the Fortran control
41// flow (assigned for clarity, not all read back); we keep them to preserve
42// the 1:1 correspondence with the source. None of these affect codegen.
43#![allow(unused_variables, unused_assignments, unused_mut)]
44
45use hydro_core::{Forcing, HydroModel};
46use serde::{Deserialize, Serialize};
47
48// ── PET 方法 ──
49
50/// Potential evapotranspiration method selector for the SWAT+ LTE driver.
51///
52/// Mirrors the PET method switch in `et_pot.f90`. Hargreaves needs only daily
53/// temperature extrema and extraterrestrial radiation; Priestley–Taylor uses
54/// net radiation and the slope-of-saturation-vapour-pressure curve.
55///
56/// Chinese: PET 方法选择(Hargreaves 仅需温度;Priestley–Taylor 需辐射)。
57#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
58pub enum PetMethod {
59    /// Hargreaves method (`et_pot.f90`, Hargreaves & Samani 1985).
60    /// `ramm = solradmx / (2.5 − 0.0022·tave)`;
61    /// `pet = 0.0032 · ramm · (tave + 17.8) · (tmax − tmin)^0.6` (mm/day).
62    Hargreaves,
63    /// Priestley–Taylor method (`et_pot.f90`, Priestley & Taylor 1972).
64    /// `d = exp(21.255 − 5304/tk) · 5304 / tk²`;
65    /// `gma = d / (d + 0.68)`; `ho = 23.9 · solrad · 0.77 / 58.3`;
66    /// `pet = 1.28 · ho · gma` (mm/day).
67    PriestleyTaylor,
68}
69
70impl Default for PetMethod {
71    fn default() -> Self { PetMethod::Hargreaves }
72}
73
74// ── LTE 参数(对应 hru_lte_control 的 hlt/hlt_db 字段)──
75
76/// SWAT+ LTE parameters — the lumped daily driver configuration consumed by
77/// [`run_swat_lte_full`] and [`SwatModel`].
78///
79/// Fields correspond 1:1 to entries in the `hru_lte` / `hru_lte_db` structures
80/// of `hru_lte_control.f90`, with curve-number shape parameters (`wrt1`,
81/// `wrt2`, `smx`) coming from the S-curve fit in `curno.f90` and `ascrv.f90`.
82/// All water quantities are in mm; the basin area in ha is used only to convert
83/// mm/day to m³/s for the [`HydroModel`] trait output.
84///
85/// Chinese: SWAT+ LTE 参数集 —— 对应 hru_lte_control 的 hlt/hlt_db 字段;
86/// CN 形状参数 wrt1/wrt2/smx 来自 curno.f90 + ascrv.f90 的 S 曲线拟合。
87#[derive(Clone, Debug, Serialize, Deserialize)]
88pub struct SwatParams {
89    // CN shape(对应 wrt1/wrt2/smx,from curno.f90)
90    /// S-curve intercept (`curno.f90` / `ascrv.f90`). Enters the daily retention
91    /// update as `xx = wrt1 − wrt2 · sw` then `r2 = smx · (1 − sw / (sw + exp(xx)))`.
92    /// Dimensionless.
93    pub wrt1: f64,
94    /// S-curve slope (`curno.f90` / `ascrv.f90`). Multiplies `sw` inside the
95    /// retention curve; larger magnitudes make daily CN more sensitive to soil
96    /// water. Dimensionless.
97    pub wrt2: f64,
98    /// `smx` — the maximum retention parameter (`curno.f90`). Used as the upper
99    /// bound of `r2 = smx · (1 − sw / (sw + exp(xx)))`; the daily CN follows as
100    /// `cn = 25400 / (r2 + 254)` (≈ 3 ≤ r2 ≤ smx). Dimensionless [mm-like].
101    pub smx: f64,
102    // 土壤
103    /// Plant-available water capacity of the single soil store (mm). Drives the
104    /// linear actual-ET factor `aet = pet · sw / awc`.
105    pub awc: f64,
106    /// Soil porosity (saturation storage) of the single store (mm). Caps the
107    /// lateral-flow saturation fraction `swf = (sw − awc) / (por − awc)`.
108    pub por: f64,
109    /// Initial soil water at simulation start (mm). Seeds `sw = sw0` in both
110    /// [`run_swat_lte_full`] and [`SwatModel::new`].
111    pub sw0: f64,
112    // ET
113    /// ET coefficient (`etco`, dimensionless). Scales potential ET before the
114    /// AET step: `pet_eff = etco · pet`. In `hru_lte_control.f90` it is also the
115    /// base of the growing-season AET scaler `b1`.
116    pub etco: f64,
117    /// PET method (Hargreaves or Priestley–Taylor). Selects which branch of
118    /// `et_pot.f90` is invoked for the daily PET computation.
119    pub pet_method: PetMethod,
120    // 渗漏/侧向/暗管
121    /// Percolation travel time constant (h) (`swr_percmicro.f90`). Drains the
122    /// soil store as `perc = sw_excess · (1 − exp(−24 / hk))`.
123    pub hk: f64,
124    /// Percolation coefficient (dimensionless). Scales the field-capacity target
125    /// inside `sw_excess = sw − awc · perco` before the percolation update.
126    pub perco: f64,
127    /// Tile-drainage travel time (h) (`tile_flow.f90`). Zero disables tile
128    /// drainage; otherwise `flow_tile = sw_excess · (1 − exp(−24 / tdrain))`,
129    /// capped at 10 mm/day.
130    pub tdrain: f64,
131    /// Lateral-flow slope class number (`latq_co` analogue, dimensionless).
132    /// Enters `flowlat = 0.024 · swf · sc · slope / slopelen`.
133    pub sc: f64,
134    /// Hillslope gradient (m/m). Used in the lateral-flow formula together with
135    /// `slopelen` and `sc`.
136    pub slope: f64,
137    /// Hillslope length (m). Used as the denominator of the lateral-flow
138    /// formula; clamped to ≥ 1e-6 to avoid divide-by-zero.
139    pub slopelen: f64,
140    // 地下水
141    /// Groundwater alpha recession factor (`alpha_bf`, dimensionless). Drives
142    /// the exponential baseflow update `gwflow = gwflow · abf + perc · (1 − abf)`.
143    pub abf: f64,
144    /// Deep-percolation fraction (`perco` deep, dimensionless). Splits the
145    /// shallow-aquifer recharge into `percdeep = perc · percc` routed to the
146    /// deep aquifer.
147    pub percc: f64,
148    /// Revap coefficient (`revap`, dimensionless). Fraction of actual ET
149    /// transferred back to the shallow aquifer: `revap = aet · revapc`.
150    pub revapc: f64,
151    /// Initial shallow groundwater storage (mm). Seeds `gw = gw0`.
152    pub gw0: f64,
153    // 位置(太阳辐射计算)
154    /// Latitude term `yls` (`sol_rad.f90`-related, stored precomputed). Used
155    /// for day-length / extraterrestrial-radiation lookup in SWAT+; in this LTE
156    /// driver it is carried for completeness and the default corresponds to
157    /// ~41.2°N (Ames, Iowa).
158    pub yls: f64,
159    /// Longitude term `ylc` (`sol_rad.f90`-related). Companion to `yls`; the
160    /// default corresponds to ~96.6°W (Ames, Iowa).
161    pub ylc: f64,
162    // 面积
163    /// HRU area (ha). Used only to convert daily outflow from mm/day to m³/s
164    /// via `Q = mm · ha · 10 / 86400` inside [`SwatModel::step`].
165    pub area_ha: f64,
166    // 生长季(影响 b1: AET 缩放系数;非生长 b1=etco-0.4,生长 b1=etco)
167    /// Growing-season flag. Selects the AET scaler `b1 = etco` (growing) or
168    /// `b1 = etco − 0.4` (dormant), matching `hru_lte_control.f90`.
169    pub growing: bool,
170}
171
172impl Default for SwatParams {
173    fn default() -> Self {
174        Self {
175            wrt1: 0.0, wrt2: 0.0, smx: 50.0,
176            awc: 100.0, por: 150.0, sw0: 50.0,
177            etco: 1.0, pet_method: PetMethod::Hargreaves,
178            hk: 24.0, perco: 1.0, tdrain: 0.0,
179            sc: 10.0, slope: 0.01, slopelen: 100.0,
180            abf: 0.95, percc: 0.05, revapc: 0.0,
181            gw0: 0.0,
182            yls: 0.72, ylc: -1.69, // ~41.2°N, -96.6°W(Ames)
183            area_ha: 100.0,
184            growing: false,
185        }
186    }
187}
188
189/// Daily weather forcing for the SWAT+ LTE driver (matches the per-day fields
190/// read from SWAT+ weather files). All radiation quantities are in MJ/m²/day,
191/// matching `et_pot.f90` conventions.
192///
193/// Chinese: 日天气输入 —— 对应 SWAT+ 天气文件逐日字段。
194#[derive(Clone, Debug, Default)]
195pub struct DailyWeather {
196    /// Daily precipitation (mm).
197    pub precip: f64,
198    /// Daily maximum temperature (°C).
199    pub tmax: f64,
200    /// Daily minimum temperature (°C).
201    pub tmin: f64,
202    /// Measured solar radiation (MJ/m²/day) (used by Priestley–Taylor PET).
203    pub solrad: f64,
204    /// Maximum possible (clear-sky) solar radiation (MJ/m²/day) (used by
205    /// Hargreaves PET to back-compute `ramm`).
206    pub solradmx: f64,
207}
208
209/// Daily water-balance output (one row per simulated day), corresponding to the
210/// SWAT+ `hltwb_d` output record from `hru_lte_control.f90`. All water
211/// quantities are in mm unless noted.
212///
213/// Chinese: 日输出 —— 对应 hltwb_d,逐日行(单位 mm)。
214#[derive(Clone, Debug, Default)]
215pub struct DailyOutput {
216    /// Daily precipitation (mm).
217    pub precip: f64,
218    /// Snowfall (water equivalent) (mm).
219    pub snowfall: f64,
220    /// Snowmelt (mm).
221    pub snowmelt: f64,
222    /// Surface runoff from SCS-CN (`surq`) (mm).
223    pub surq: f64,
224    /// Lateral flow plus groundwater outflow (`latq`) (mm).
225    pub latq: f64,
226    /// Total daily outflow = surface + lateral + tile + groundwater (`chflow`)
227    /// (mm).
228    pub wateryld: f64,
229    /// Percolation below the soil profile (`perc`) (mm).
230    pub perc: f64,
231    /// Actual ET (canopy + soil + snow sublimation) (mm).
232    pub et: f64,
233    /// Daily curve number computed from soil moisture (-).
234    pub cn: f64,
235    /// End-of-day soil water in the single store (mm).
236    pub sw: f64,
237    /// Potential ET for the day (mm).
238    pub pet: f64,
239    /// Tile drainage (`qtile`) (mm).
240    pub qtile: f64,
241    /// Groundwater outflow (`gwflow`) (mm).
242    pub gwflow: f64,
243}
244
245/// Batch output of [`run_swat_lte_full`]: a vector of daily records, one per
246/// input weather row.
247///
248/// Chinese: 批量输出 —— [`run_swat_lte_full`] 的逐日序列。
249#[derive(Clone, Debug, Default)]
250pub struct SwatOutput {
251    /// Daily water-balance records, in the same order as the input weather.
252    pub days: Vec<DailyOutput>,
253}
254
255// ── 忠实批量核心:run_swat_lte_full ──
256
257/// Run the full SWAT+ LTE daily driver (faithful to `hru_lte_control.f90`'s
258/// daily loop).
259///
260/// Drives the single-store daily water balance for `weather.len()` days:
261/// (1) daily CN from soil moisture via the S-curve in `curno.f90`/`ascrv.f90`;
262/// (2) snow accumulation/melt with degree-day factor;
263/// (3) SCS-CN runoff from `sq_daycn.f90`;
264/// (4) PET by Hargreaves or Priestley–Taylor (`et_pot.f90`);
265/// (5) linear actual ET with growing-season scaler `b1`;
266/// (6) lateral flow, (7) tile drainage, (8) percolation (`swr_percmicro.f90`);
267/// (9) exponential groundwater recession;
268/// (10) channel outflow = surface + lateral + tile + groundwater.
269///
270/// Inputs are the model parameters `p` and a slice of daily weather rows;
271/// output units are mm/day (matching SWAT+).
272pub fn run_swat_lte_full(p: &SwatParams, weather: &[DailyWeather]) -> SwatOutput {
273    let n = weather.len();
274    let mut days = Vec::with_capacity(n);
275    // 状态
276    let mut sw = p.sw0;
277    let mut snow = 0.0_f64;
278    let mut gw = p.gw0;
279    let mut gwdeep = 0.0_f64;
280    let mut gwflow = 0.0_f64;
281    // 常量(对应 Fortran a1=0.2, a2=0.8)
282    let a1 = 0.2_f64;
283    let a2 = 0.8_f64;
284    // b1: 生长季缩放(AET)
285    let b1 = if p.growing { p.etco } else { p.etco - 0.4_f64.max(0.0) - 0.0 };
286
287    for (iday, w) in weather.iter().enumerate() {
288        let precip = w.precip;
289        let tmax = w.tmax;
290        let tmin = w.tmin;
291        let tave = (tmax + tmin) / 2.0;
292
293        // ── 1) 日 CN(对应 sq_dailycn 逻辑,inline)──
294        let mut xx = p.wrt1 - p.wrt2 * sw;
295        if xx < -20.0 { xx = -20.0; }
296        if xx > 20.0 { xx = 20.0; }
297        let mut r2 = if sw + xx.exp() > 0.001 {
298            p.smx * (1.0 - sw / (sw + xx.exp()))
299        } else { p.smx };
300        if r2 < 3.0 { r2 = 3.0; }
301        let cn_sd = 25400.0 / (r2 + 254.0);
302
303        // ── 2) 雪 + 径流 ──
304        let mut snowfall = 0.0_f64;
305        let mut snowmelt = 0.0_f64;
306        let mut runoff = 0.0_f64;
307        let mut precipeff = 0.0_f64;
308
309        if tave < 0.0 {
310            snowfall = precip;
311            snow += precip;
312            // runoff = 0
313        } else {
314            snowmelt = 4.57 * tave;
315            if snowmelt > snow {
316                snowmelt = snow;
317                snow = 0.0;
318            } else {
319                snow -= snowmelt;
320            }
321            precipeff = precip + snowmelt;
322            xx = precipeff - a1 * r2;
323            if xx > 0.0 {
324                runoff = xx * xx / (precipeff + a2 * r2);
325            }
326            sw += precipeff - runoff;
327        }
328
329        // ── 3) PET(Hargreaves 或 Priestley-Taylor)──
330        let pet = match p.pet_method {
331            PetMethod::Hargreaves => {
332                let ramm = if (2.5 - 0.0022 * tave).abs() > 1e-12 {
333                    w.solradmx / (2.5 - 0.0022 * tave)
334                } else { 0.0 };
335                0.0032 * ramm * (tave + 17.8) * (tmax - tmin).max(0.0).powf(0.6)
336            }
337            PetMethod::PriestleyTaylor => {
338                let tk = tave + 273.0;
339                let d = (21.255 - 5304.0 / tk).exp() * 5304.0 / (tk * tk);
340                let gma = d / (d + 0.68);
341                let ho = 23.9 * w.solrad * (1.0 - 0.23) / 58.3;
342                1.28 * ho * gma
343            }
344        };
345        let pet = p.etco * pet;
346
347        // ── 4) AET(线性: pet·sw/awc;b1 缩放)──
348        let mut aet = if p.awc > 0.0 { pet * sw / p.awc } else { 0.0 };
349        aet = b1 * aet;
350
351        // ── 5) 侧向流 ──
352        let mut flowlat = 0.0_f64;
353        let sw_excess = sw - p.awc;
354        if sw_excess > 0.0 && (p.por - p.awc) > 0.0 {
355            let swf = (sw - p.awc) / (p.por - p.awc);
356            flowlat = 0.024 * swf * p.sc * p.slope / p.slopelen.max(1e-6);
357            if flowlat > sw { flowlat = sw; }
358            sw -= flowlat;
359        }
360
361        // ── 6) 暗管 ──
362        let mut flow_tile = 0.0_f64;
363        let sw_excess = sw - p.awc;
364        if sw_excess > 0.0 && p.tdrain > 0.0 {
365            flow_tile = sw_excess * (1.0 - (-24.0 / p.tdrain).exp());
366            if flow_tile > 10.0 { flow_tile = 10.0; }
367        }
368        if flow_tile > sw { flow_tile = sw; }
369        sw -= flow_tile;
370
371        // ── 7) 渗漏 ──
372        let mut perc = 0.0_f64;
373        let sw_excess = sw - p.awc * p.perco;
374        if sw_excess > 0.0 {
375            perc = sw_excess * (1.0 - (-24.0 / p.hk).exp());
376        }
377        if perc < 0.0 { perc = 0.0; }
378        if perc > sw { perc = sw; }
379        sw -= perc;
380
381        // ── 8) AET 提取(在渗漏后)──
382        if aet > sw { aet = sw; }
383        sw -= aet;
384
385        // ── 9) 地下水 ──
386        gw += perc;
387        let mut revap = aet * p.revapc;
388        let percdeep = perc * p.percc;
389        gwflow = gwflow * p.abf + perc * (1.0 - p.abf);
390        if gwflow > gw { gwflow = gw; }
391        gw -= gwflow;
392        if revap > gw { revap = gw; }
393        gw -= revap;
394        let mut percdeep_act = percdeep;
395        if percdeep_act > gw { percdeep_act = gw; }
396        gw -= percdeep_act;
397        gwdeep += percdeep_act;
398
399        // ── 10) 出流 ──
400        let chflow = runoff + flowlat + flow_tile + gwflow;
401        let latq = flowlat + gwflow;
402
403        days.push(DailyOutput {
404            precip, snowfall, snowmelt, surq: runoff, latq,
405            wateryld: chflow, perc, et: aet, cn: cn_sd, sw,
406            pet, qtile: flow_tile, gwflow,
407        });
408    }
409    SwatOutput { days }
410}
411
412// ── HydroModel trait 包装 ──
413
414/// [`hydro_core::HydroModel`] wrapper around [`SwatParams`] that steps the SWAT+
415/// LTE daily driver one day at a time and exposes the channel outflow in m³/s.
416///
417/// `step()` adapts the generic [`Forcing`] to the LTE single-store algorithm
418/// (using `pet_mm` directly as the Hargreaves PET estimate since the trait does
419/// not carry `tmax`/`tmin`/`solrad`). Forcing time step should be 24 h; the
420/// per-day state (soil water `sw`, snowpack `snow`, shallow groundwater `gw`,
421/// groundwater outflow `gwflow`) is held between calls.
422///
423/// Chinese: SWAT+ LTE 单步驱动 —— 包装为 [`HydroModel`] trait,
424/// 输出 chflow 经 mm/day → m³/s 转换(用 area_ha)。
425pub struct SwatModel {
426    params: SwatParams,
427    // 日驱动状态
428    sw: f64, snow: f64, gw: f64, gwdeep: f64, gwflow: f64,
429    discharge: f64, // m³/s
430}
431
432/// Convert a daily water depth (mm) over an area (ha) to a daily-average
433/// discharge (m³/s): `mm·ha·10 = m³`, divided by 86400 s.
434fn mm_to_m3s(mm: f64, area_ha: f64) -> f64 {
435    // mm·ha → m³/s over a day: mm·ha·10 = m³; /86400 = m³/s
436    mm * area_ha * 10.0 / 86400.0
437}
438
439impl HydroModel for SwatModel {
440    type Params = SwatParams;
441
442    fn new(params: Self::Params) -> Self {
443        Self {
444            sw: params.sw0, snow: 0.0, gw: params.gw0, gwdeep: 0.0, gwflow: 0.0,
445            discharge: 0.0, params,
446        }
447    }
448
449    fn step(&mut self, f: &Forcing, _dt_h: f64) {
450        let p = &self.params;
451        let a1 = 0.2_f64;
452        let a2 = 0.8_f64;
453        let b1 = if p.growing { p.etco } else { p.etco - 0.4 };
454        let tave = f.t_c;
455        let precip = f.p_mm.max(0.0);
456
457        // 日 CN
458        let mut xx = p.wrt1 - p.wrt2 * self.sw;
459        if xx < -20.0 { xx = -20.0; }
460        if xx > 20.0 { xx = 20.0; }
461        let mut r2 = if self.sw + xx.exp() > 0.001 {
462            p.smx * (1.0 - self.sw / (self.sw + xx.exp()))
463        } else { p.smx };
464        if r2 < 3.0 { r2 = 3.0; }
465
466        // 雪 + 径流
467        let mut runoff = 0.0_f64;
468        if tave < 0.0 {
469            self.snow += precip;
470        } else {
471            let mut snowmelt = 4.57 * tave;
472            if snowmelt > self.snow { snowmelt = self.snow; self.snow = 0.0; }
473            else { self.snow -= snowmelt; }
474            let pe = precip + snowmelt;
475            xx = pe - a1 * r2;
476            if xx > 0.0 { runoff = xx * xx / (pe + a2 * r2); }
477            self.sw += pe - runoff;
478        }
479
480        // PET(用 Forcing.pet_mm 作 Hargreaves 近似;真实需 tmax/tmin/solrad)
481        let pet = f.pet_mm.max(0.0);
482        let mut aet = if p.awc > 0.0 { pet * self.sw / p.awc } else { 0.0 };
483        aet = b1 * aet;
484
485        // 侧向流
486        let mut flowlat = 0.0_f64;
487        if self.sw - p.awc > 0.0 && (p.por - p.awc) > 0.0 {
488            let swf = (self.sw - p.awc) / (p.por - p.awc);
489            flowlat = 0.024 * swf * p.sc * p.slope / p.slopelen.max(1e-6);
490            if flowlat > self.sw { flowlat = self.sw; }
491            self.sw -= flowlat;
492        }
493
494        // 渗漏
495        let mut perc = 0.0_f64;
496        let sw_excess = self.sw - p.awc * p.perco;
497        if sw_excess > 0.0 { perc = sw_excess * (1.0 - (-24.0 / p.hk).exp()); }
498        if perc > self.sw { perc = self.sw; }
499        self.sw -= perc;
500
501        // AET 提取
502        if aet > self.sw { aet = self.sw; }
503        self.sw -= aet;
504
505        // GW
506        self.gw += perc;
507        self.gwflow = self.gwflow * p.abf + perc * (1.0 - p.abf);
508        if self.gwflow > self.gw { self.gwflow = self.gw; }
509        self.gw -= self.gwflow;
510
511        // 出流 → m³/s
512        let chflow = runoff + flowlat + self.gwflow;
513        self.discharge = mm_to_m3s(chflow, p.area_ha);
514    }
515
516    fn discharge(&self) -> f64 { self.discharge }
517    fn state(&self) -> serde_json::Value {
518        serde_json::json!({ "sw": self.sw, "snow": self.snow, "gw": self.gw })
519    }
520    fn reset(&mut self) {
521        self.sw = self.params.sw0; self.snow = 0.0; self.gw = self.params.gw0;
522        self.gwdeep = 0.0; self.gwflow = 0.0; self.discharge = 0.0;
523    }
524    fn name(&self) -> &'static str { "SWAT" }
525    fn params(&self) -> &Self::Params { &self.params }
526    fn params_mut(&mut self) -> &mut Self::Params { &mut self.params }
527}
528
529#[cfg(test)]
530mod tests {
531    use super::*;
532
533    #[test]
534    fn rain_produces_flow() {
535        let mut m = SwatModel::new(SwatParams::default());
536        for _ in 0..10 {
537            m.step(&Forcing { p_mm: 50.0, pet_mm: 2.0, t_c: 20.0 }, 24.0);
538        }
539        assert!(m.discharge() > 0.0, "rain should produce flow");
540    }
541
542    #[test]
543    fn drought_recedes() {
544        let mut m = SwatModel::new(SwatParams::default());
545        for _ in 0..30 {
546            m.step(&Forcing { p_mm: 50.0, pet_mm: 2.0, t_c: 20.0 }, 24.0);
547        }
548        let peak = m.discharge();
549        for _ in 0..200 {
550            m.step(&Forcing { p_mm: 0.0, pet_mm: 5.0, t_c: 25.0 }, 24.0);
551        }
552        assert!(m.discharge() < peak);
553    }
554
555    #[test]
556    fn snow_accumulates_and_melts() {
557        let mut p = SwatParams::default();
558        p.sw0 = 50.0; p.awc = 100.0; p.por = 200.0;
559        let w = vec![
560            DailyWeather { precip: 50.0, tmax: -5.0, tmin: -10.0, solrad: 10.0, solradmx: 20.0 },
561            DailyWeather { precip: 0.0, tmax: 10.0, tmin: 2.0, solrad: 15.0, solradmx: 25.0 },
562        ];
563        let out = run_swat_lte_full(&p, &w);
564        assert!((out.days[0].snowfall - 50.0).abs() < 1e-9, "snowfall=50");
565        assert!(out.days[0].surq.abs() < 1e-9, "no runoff when snowing");
566        assert!(out.days[1].snowmelt > 0.0, "snow melts on warm day");
567        assert!(out.days[1].surq > 0.0, "melt produces runoff");
568    }
569
570    #[test]
571    fn gw_exponential_recession() {
572        let mut p = SwatParams::default();
573        p.abf = 0.9; p.awc = 0.0; p.sw0 = 0.0; p.gw0 = 0.0;
574        // 先大雨充 gw + gwflow,再断雨看退水
575        let mut w = vec![DailyWeather { precip: 100.0, tmax: 20.0, tmin: 10.0, solrad: 10.0, solradmx: 20.0 }; 3];
576        w.extend(vec![DailyWeather { precip: 0.0, tmax: 25.0, tmin: 15.0, solrad: 15.0, solradmx: 25.0 }; 200]);
577        let out = run_swat_lte_full(&p, &w);
578        let peak_gwf = out.days.iter().map(|d| d.gwflow).fold(0.0_f64, f64::max);
579        let last_gwf = out.days.last().unwrap().gwflow;
580        assert!(peak_gwf > 0.0, "gwflow should be charged");
581        assert!(last_gwf < peak_gwf, "gwflow should recede: {} < {}", last_gwf, peak_gwf);
582    }
583
584    #[test]
585    fn no_mass_creation_constant_rain() {
586        let params = SwatParams::default();
587        let area_ha = params.area_ha;
588        let w = vec![DailyWeather { precip: 5.0, tmax: 20.0, tmin: 10.0, solrad: 10.0, solradmx: 20.0 }; 365];
589        let out = run_swat_lte_full(&params, &w);
590        let sum_rain = 5.0 * 365.0;
591        let sum_out: f64 = out.days.iter().map(|d| d.wateryld).sum();
592        // mm→m³: wateryld_mm · area_ha · 10 = m³; 但这里直接比 mm 总量
593        assert!(sum_out <= sum_rain * 1.02, "出流>降雨(质量凭空):{:.1}>{:.1}", sum_out, sum_rain);
594    }
595
596    #[test]
597    fn dyn_dispatch() {
598        let mut m: Box<dyn hydro_core::DynHydroModel> = Box::new(SwatModel::new(SwatParams::default()));
599        m.step(&Forcing { p_mm: 50.0, pet_mm: 2.0, t_c: 20.0 }, 24.0);
600        assert!(m.discharge() >= 0.0);
601        assert_eq!(m.name(), "SWAT");
602    }
603}
604pub mod swat_hru;