basinledger 0.10.0__py3-none-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. basinledger/__init__.py +7 -0
  2. basinledger/__main__.py +106 -0
  3. basinledger/_lib/MODFLOW6.md +10 -0
  4. basinledger/_lib/libmf6.dll +4 -0
  5. basinledger/analysis.py +86 -0
  6. basinledger/analytic.py +73 -0
  7. basinledger/balance.py +202 -0
  8. basinledger/calibration.py +587 -0
  9. basinledger/chain.py +106 -0
  10. basinledger/config.py +459 -0
  11. basinledger/coupling/__init__.py +0 -0
  12. basinledger/coupling/exchange.py +705 -0
  13. basinledger/coupling/existing.py +361 -0
  14. basinledger/coupling/gwsoil.py +270 -0
  15. basinledger/coupling/irrigation.py +147 -0
  16. basinledger/coupling/lakes.py +324 -0
  17. basinledger/coupling/modflow6.py +645 -0
  18. basinledger/coupling/mover.py +165 -0
  19. basinledger/coupling/nextgen.py +189 -0
  20. basinledger/coupling/recharge.py +84 -0
  21. basinledger/coupling/sfr.py +158 -0
  22. basinledger/coupling/swatplus.py +360 -0
  23. basinledger/coupling/timesteps.py +310 -0
  24. basinledger/coupling/transport.py +290 -0
  25. basinledger/driver.py +1449 -0
  26. basinledger/forcing.py +128 -0
  27. basinledger/generic.py +85 -0
  28. basinledger/gridmaps.py +398 -0
  29. basinledger/hydrofabric.py +26 -0
  30. basinledger/ledger.py +92 -0
  31. basinledger/mapping.py +175 -0
  32. basinledger/routes.py +140 -0
  33. basinledger/rules.py +87 -0
  34. basinledger/scenarios.py +75 -0
  35. basinledger/temperature.py +352 -0
  36. basinledger/testing.py +200 -0
  37. basinledger/units.py +35 -0
  38. basinledger/users.py +253 -0
  39. basinledger/weather.py +293 -0
  40. basinledger-0.10.0.dist-info/METADATA +390 -0
  41. basinledger-0.10.0.dist-info/RECORD +45 -0
  42. basinledger-0.10.0.dist-info/WHEEL +4 -0
  43. basinledger-0.10.0.dist-info/entry_points.txt +2 -0
  44. basinledger-0.10.0.dist-info/licenses/LICENSE +28 -0
  45. basinledger-0.10.0.dist-info/licenses/LICENSES/MODFLOW6.md +10 -0
@@ -0,0 +1,7 @@
1
+ """Basin Ledger: a basin's water, quantity and quality, balanced day by day across coupled models.
2
+
3
+ SWAT+ (through swatplus-bmi), MODFLOW 6 (through libmf6 and modflowapi) and water-user components (from
4
+ waterledger-models) are stepped one day at a time by one Python driver, on NextGen geography. See docs/design.md.
5
+ """
6
+
7
+ __version__ = "0.10.0"
@@ -0,0 +1,106 @@
1
+ """The command line.
2
+
3
+ python -m basinledger run basin.toml [--run NAME] [--days N] [--baseline] [--out DIR]
4
+ [--save-at DAY --save DIR] [--restart DIR]
5
+ python -m basinledger status basin.toml
6
+ python -m basinledger check basin.toml [--baseline]
7
+ python -m basinledger forward basin.toml parameters.csv observations.csv simulated.csv [--run-folder DIR]
8
+
9
+ ``run`` steps the example's models through its period (or ``--days``), checking the ledger every day, and writes
10
+ ledger.csv, series.csv and summary.json to the run's outputs folder. ``--baseline`` runs it without its water users.
11
+ ``--save-at`` stops after that day and saves the state to ``--save``; ``--restart`` carries on from a saved state.
12
+ ``status`` prints whether the example is calibrated or a screening run. ``check`` starts the example's models without
13
+ running a day, prints MODFLOW 6's units and the factors that convert them at every link, lists MODFLOW 6's packages
14
+ with what Basin Ledger takes over in each and what it leaves as the model's (coupling/existing.py), and lists every
15
+ problem its start-up finds (``Basin.check``); it exits with 1 if there are any. ``forward`` is the forward model PEST++
16
+ runs (calibration.py): the parameter set applied, the example run, and its value at each observation written;
17
+ ``--run-folder`` puts the run's files there instead of the example's run folder.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import json
24
+ import sys
25
+
26
+ from . import config as C
27
+ from .driver import Basin
28
+
29
+
30
+ def main(argv=None) -> int:
31
+ ap = argparse.ArgumentParser(prog="basinledger", description="Basin Ledger: coupled basin water accounting.")
32
+ sub = ap.add_subparsers(dest="cmd", required=True)
33
+ r = sub.add_parser("run", help="run an example")
34
+ r.add_argument("config")
35
+ r.add_argument("--run", default=None, help="run name (default: base, or baseline with --baseline)")
36
+ r.add_argument("--days", type=int, default=None)
37
+ r.add_argument("--baseline", action="store_true", help="without the example's water users")
38
+ r.add_argument("--out", default=None, help="outputs folder (default: <run folder>/outputs)")
39
+ r.add_argument("--save-at", type=int, default=None, help="stop after this many days and save the state")
40
+ r.add_argument("--save", default=None, help="folder for the saved state")
41
+ r.add_argument("--restart", default=None, help="carry on from a saved state")
42
+ s = sub.add_parser("status", help="calibrated or screening run")
43
+ s.add_argument("config")
44
+ k = sub.add_parser("check", help="every problem the start-up finds, without running a day")
45
+ k.add_argument("config")
46
+ k.add_argument("--baseline", action="store_true", help="without the example's water users")
47
+ f = sub.add_parser("forward", help="the forward model for PEST++")
48
+ for name in ("config", "parameters", "observations", "out"):
49
+ f.add_argument(name)
50
+ f.add_argument("--run-folder", default=None, help="where the run's files go (default: the example's)")
51
+ a = ap.parse_args(argv)
52
+
53
+ if a.cmd == "check":
54
+ cfg = C.load(a.config)
55
+ takeover, units = [], []
56
+ problems, notes = Basin.check(cfg, users=not a.baseline, takeover=takeover, units=units)
57
+ for u in units:
58
+ print(f"MODFLOW 6's units: {u}")
59
+ notes = [n for n in notes if u not in n]
60
+ if takeover:
61
+ from .coupling.existing import table
62
+ print("MODFLOW 6's packages:")
63
+ print(" " + table(takeover).replace("\n", "\n "))
64
+ for n in notes:
65
+ print(f"note: {n}")
66
+ if problems:
67
+ print(f"{cfg.name}: {len(problems)} problem{'s' if len(problems) > 1 else ''}")
68
+ for x in problems:
69
+ print("- " + x.replace("\n", "\n "))
70
+ return 1
71
+ print(f"{cfg.name}: no problems found")
72
+ return 0
73
+
74
+ if a.cmd == "forward":
75
+ from .calibration import run_forward_model
76
+ run_forward_model(a.config, a.parameters, a.observations, a.out, run_folder=a.run_folder)
77
+ return 0
78
+
79
+ if a.cmd == "status":
80
+ cfg = C.load(a.config)
81
+ print(f"{cfg.name}: {cfg.calibration_status}")
82
+ return 0
83
+
84
+ if (a.save_at is None) != (a.save is None):
85
+ ap.error("--save-at and --save go together")
86
+ run = a.run or ("baseline" if a.baseline else "base")
87
+ b = Basin.from_config(a.config, run=run, users=not a.baseline, days=a.days, restart=a.restart)
88
+ try:
89
+ if a.save_at is not None:
90
+ b.run(a.save_at - b.day)
91
+ b.save(a.save)
92
+ else:
93
+ b.run()
94
+ out = b.write_outputs(a.out)
95
+ finally:
96
+ b.finalize()
97
+ summary = json.loads((out / "summary.json").read_text())
98
+ print(f"{summary['example']} ({summary['status']}): {summary['days']} days, ledger closed every day")
99
+ print(f"outputs: {out}")
100
+ if summary["status_note"]:
101
+ print("note: " + summary["status_note"])
102
+ return 0
103
+
104
+
105
+ if __name__ == "__main__":
106
+ sys.exit(main())
@@ -0,0 +1,10 @@
1
+ # MODFLOW 6
2
+
3
+ The platform wheels of Basin Ledger carry MODFLOW 6's shared library (`libmf6.dylib`, `libmf6.so` or `libmf6.dll`),
4
+ unchanged, from the U.S. Geological Survey's release of MODFLOW 6, fetched with flopy's `get-modflow` when the wheel
5
+ is built.
6
+
7
+ MODFLOW 6 is U.S. Geological Survey software. Its source, release notes and license are at
8
+ https://github.com/MODFLOW-ORG/modflow6 (the license is in `LICENSE.md` there). Cite it as the USGS asks there.
9
+
10
+ Basin Ledger's own code is under the BSD 3-Clause license (`LICENSE`).
@@ -0,0 +1,4 @@
1
+ [diffend] Oversized file quarantined before diffing.
2
+ name: basinledger/_lib/libmf6.dll
3
+ size: 50723328 bytes
4
+ sha256: 7eade913c76e399599f9de114a14bc38563281347edf52b9b315d24ae9968fb6
@@ -0,0 +1,86 @@
1
+ """What a scenario did, from its ledger and a baseline's: where a well's water came from, and what a return does to a
2
+ stream's concentrations.
3
+
4
+ Both work on ledger tables (``Ledger.table()``, or ``ledger.csv`` read back with ``read_ledger``) of runs over the
5
+ same days.
6
+
7
+ **Capture** (``capture``). MODFLOW 6's budget closes each day, and every term of it is a ledger account:
8
+ recharge received, boundary flows in (``groundwater:boundary:*``), the release from storage, the exchange with the
9
+ coupled streams (``exchange:*:to_stream``, rivers and drains) and the wells (``route:well:*:delivered``). So between
10
+ a run with a user and the same run without it, the extra pumping must equal the extra release from storage, the
11
+ water the streams lose (less discharge, more leakage) and the extra boundary inflow, plus any change in recharge
12
+ (none in two-way mode, where SWAT+'s recharge doesn't depend on the aquifer). ``capture`` returns each part and the
13
+ residual, which a test holds to zero.
14
+
15
+ **Concentration change** (``concentration_change``). A user's return carries dissolved mass (``user:<u>:<c>:kg``).
16
+ At the reach receiving it, the day's concentration is the stream's own water at its background concentration plus
17
+ the return's mass, over the day's flow there in the run with the user. The percent change is against the
18
+ background. It needs the background concentration [A], and the receiving reach's flow, which already has the
19
+ depletion and the return in it.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import csv
25
+ from pathlib import Path
26
+
27
+ import numpy as np
28
+
29
+
30
+ def read_ledger(path: str | Path) -> dict[str, np.ndarray]:
31
+ """``ledger.csv`` back to a table: account -> daily values (m3 unless the account says otherwise)."""
32
+ with open(path, newline="") as f:
33
+ rows = list(csv.DictReader(f))
34
+ return {k: np.array([float(r[k]) if r[k] not in ("", "nan") else np.nan for r in rows])
35
+ for k in rows[0] if k not in ("day", "date")}
36
+
37
+
38
+ def _sum(t: dict, start: str = "", end: str = "") -> np.ndarray:
39
+ keys = [k for k in t if k.startswith(start) and k.endswith(end)]
40
+ n = len(next(iter(t.values())))
41
+ return np.nansum([t[k] for k in keys], axis=0) if keys else np.zeros(n)
42
+
43
+
44
+ def groundwater_terms(t: dict) -> dict[str, np.ndarray]:
45
+ """One run's daily groundwater budget from its ledger, m3, positive into the aquifer except the outflows named."""
46
+ return {
47
+ "recharge": _sum(t, "recharge:received"),
48
+ "boundary": _sum(t, "groundwater:boundary:"),
49
+ "storage_release": _sum(t, "groundwater:storage_release"),
50
+ "to_streams": _sum(t, "exchange:", ":to_stream"),
51
+ "pumping": _sum(t, "route:well:", ":delivered"),
52
+ "to_soil": _sum(t, "gw_soil:sent"),
53
+ }
54
+
55
+
56
+ def capture(base: dict, case: dict) -> dict:
57
+ """Where a case's extra pumping came from, against a baseline over the same days. Returns daily arrays (m3) and
58
+ totals: ``pumping`` (extra), ``from_storage``, ``from_streams`` (less discharge and more leakage),
59
+ ``from_boundary``, ``from_recharge``, ``from_soil`` (less water up into the soil, where the water table rises
60
+ into it) and ``residual`` (pumping less the rest), and each part's share."""
61
+ b, c = groundwater_terms(base), groundwater_terms(case)
62
+ if len(b["pumping"]) != len(c["pumping"]):
63
+ raise ValueError("the runs cover different days")
64
+ parts = {
65
+ "pumping": c["pumping"] - b["pumping"],
66
+ "from_storage": c["storage_release"] - b["storage_release"],
67
+ "from_streams": b["to_streams"] - c["to_streams"],
68
+ "from_boundary": c["boundary"] - b["boundary"],
69
+ "from_recharge": c["recharge"] - b["recharge"],
70
+ "from_soil": b["to_soil"] - c["to_soil"],
71
+ }
72
+ parts["residual"] = parts["pumping"] - sum(v for k, v in parts.items() if k.startswith("from_"))
73
+ total = {k: float(np.sum(v)) for k, v in parts.items()}
74
+ share = {k: total[k] / total["pumping"] if total["pumping"] else float("nan") for k in total if k != "pumping"}
75
+ return {"daily": parts, "total": total, "share": share}
76
+
77
+
78
+ def concentration_change(flow_m3: np.ndarray, return_m3: np.ndarray, return_kg: np.ndarray,
79
+ background_kg_m3: float) -> dict:
80
+ """At the receiving reach, each day: the concentration with the return (kg/m3) and its change against the
81
+ background, percent. ``flow_m3`` is the reach's flow that day in the run with the return (so the return and
82
+ any depletion are in it); the stream's own water, ``flow - return``, is at the background concentration."""
83
+ q = np.asarray(flow_m3, float)
84
+ own = np.clip(q - np.asarray(return_m3, float), 0.0, None)
85
+ conc = np.where(q > 0, (background_kg_m3 * own + np.asarray(return_kg, float)) / np.where(q > 0, q, 1.0), np.nan)
86
+ return {"concentration_kg_m3": conc, "change_percent": 100.0 * (conc / background_kg_m3 - 1.0)}
@@ -0,0 +1,73 @@
1
+ """Analytical solutions, for comparison with the coupled models: stream depletion and one-dimensional transport.
2
+
3
+ Glover and Balmer (1954): a well at distance d from a straight, fully penetrating stream in a uniform, infinite
4
+ aquifer of transmissivity T and storativity S. After pumping at a constant rate starts, the share of the pumping the
5
+ stream supplies at time t is
6
+
7
+ q(t) / Q = erfc( sqrt( d^2 S / (4 T t) ) ).
8
+
9
+ A varying pumping series is handled by superposition: each step's pumping change starts its own response. This is
10
+ the method nextgen-michigan uses for wells, and the one Michigan's Water Withdrawal Assessment Tool's depletion is
11
+ built on. Its assumptions (one straight stream, no streambed resistance, a uniform aquifer, no other boundaries) are
12
+ what a coupled groundwater model relaxes.
13
+
14
+ Ogata and Banks (1961): a solute carried at a uniform velocity v with longitudinal dispersion D through a
15
+ semi-infinite column, initially free of it, with the concentration at x = 0 held at C0 from t = 0:
16
+
17
+ C(x, t) / C0 = 1/2 [ erfc( (x - v t) / (2 sqrt(D t)) ) + exp(v x / D) erfc( (x + v t) / (2 sqrt(D t)) ) ].
18
+
19
+ Glover, R.E., Balmer, G.G., 1954. River depletion resulting from pumping a well near a river. Eos Trans. AGU 35(3),
20
+ 468-470. https://doi.org/10.1029/TR035i003p00468
21
+
22
+ Ogata, A., Banks, R.B., 1961. A solution of the differential equation of longitudinal dispersion in porous media.
23
+ U.S. Geological Survey Professional Paper 411-A. https://doi.org/10.3133/pp411A
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import math
29
+
30
+ import numpy as np
31
+
32
+
33
+ def glover_share(t_days: np.ndarray, distance_m: float, transmissivity_m2_d: float, storativity: float) -> np.ndarray:
34
+ """The share of a constant pumping rate the stream supplies t days after it starts (0 at t <= 0)."""
35
+ t = np.asarray(t_days, float)
36
+ out = np.zeros_like(t)
37
+ pos = t > 0
38
+ u = np.sqrt(distance_m ** 2 * storativity / (4.0 * transmissivity_m2_d * t[pos]))
39
+ out[pos] = np.array([math.erfc(x) for x in u])
40
+ return out
41
+
42
+
43
+ def glover_depletion(pumping: np.ndarray, distance_m: float, transmissivity_m2_d: float, storativity: float,
44
+ dt_days: float = 1.0) -> np.ndarray:
45
+ """Daily stream depletion (same units as ``pumping``) for a pumping series of one value per step, by
46
+ superposition of step changes. Each step's pumping is taken as starting at the step's beginning; the depletion
47
+ reported for a step is at its end."""
48
+ p = np.asarray(pumping, float)
49
+ n = len(p)
50
+ share = glover_share(dt_days * np.arange(1, n + 1), distance_m, transmissivity_m2_d, storativity)
51
+ dp = np.diff(np.r_[0.0, p])
52
+ return np.convolve(dp, share)[:n]
53
+
54
+
55
+ def _erfcx(b: float) -> float:
56
+ """exp(b^2) erfc(b), the scaled complementary error function, for b >= 0: directly below 25, and above by its
57
+ asymptotic series (four terms; relative error below 1e-10 there)."""
58
+ if b < 25.0:
59
+ return math.exp(b * b) * math.erfc(b)
60
+ u = 1.0 / (2.0 * b * b)
61
+ return (1.0 - u + 3.0 * u * u - 15.0 * u ** 3) / (b * math.sqrt(math.pi))
62
+
63
+
64
+ def ogata_banks(x_m: np.ndarray, t_days: float, velocity_m_d: float, dispersion_m2_d: float) -> np.ndarray:
65
+ """C / C0 at distances x >= 0 (m) downstream of the held concentration, t days after it starts. The second term
66
+ is computed as exp(v x / D - b^2) erfcx(b), b = (x + v t) / (2 sqrt(D t)), which can't overflow: the exponent is
67
+ -(x - v t)^2 / (4 D t)."""
68
+ x = np.asarray(x_m, float)
69
+ v, D, t = velocity_m_d, dispersion_m2_d, float(t_days)
70
+ s = 2.0 * math.sqrt(D * t)
71
+ first = np.array([math.erfc(a) for a in (x - v * t) / s])
72
+ second = np.array([math.exp(-(xi - v * t) ** 2 / (4.0 * D * t)) * _erfcx((xi + v * t) / s) for xi in x])
73
+ return 0.5 * (first + second)
basinledger/balance.py ADDED
@@ -0,0 +1,202 @@
1
+ """The whole basin over a coupled run (testing G3): SWAT+'s own budgets, the links and MODFLOW 6's, in m3.
2
+
3
+ Over the area the surface model covers:
4
+
5
+ - **land** (SWAT+'s ``basin_wb_day``, summed over the run): precipitation + irrigation + groundwater into the soil
6
+ (``gwsoilq``) = ET + runoff to the channels + percolation + the gain in soil water and snow + a residual, which is SWAT+'s own (wetland storage, for one, isn't
7
+ in it). Irrigation is counted as water from outside [A]: where a project irrigates from its own channels or
8
+ aquifers, that is a transfer inside the basin, and the example should say so;
9
+ - **the link** (the ledger): what SWAT+'s aquifers recharged, what MODFLOW 6 received, and what the map added;
10
+ - **groundwater** (the ledger): recharge + boundary inflow + release from storage = discharge to the coupled streams
11
+ + pumping + water up into the soil (``gw_soil:sent``), which closes by MODFLOW 6's budget;
12
+ - **channels and lakes**: runoff + groundwater SWAT+'s channels received (the exchange as applied, gains less
13
+ losses) + precipitation on lakes and channels + water users' returns to the streams + inflow from elsewhere =
14
+ evaporation from lakes and channels + withdrawals from the streams + outflow at the outlet + the gain in lake and
15
+ channel storage + a residual. Precipitation, evaporation and storage come from the lakes' and channels' daily
16
+ files (else the average annual ones times the run's years, with no storage term). Inflow from elsewhere is what
17
+ SWAT+'s channels report taking in beyond their upstream channels, the lakes' releases, the land's runoff, the
18
+ groundwater they gained and Basin Ledger's returns: the project's own point sources (recall objects), for one,
19
+ which are water from outside. A channel's loss to the aquifer comes out of its outflow after routing (SWAT+'s
20
+ seepage), not its inflow.
21
+
22
+ An example asks for it with ``[outputs] balance = "<outlet channel>"``: SWAT+ then prints ``basin_wb``,
23
+ ``channel_sd`` and ``reservoir`` daily.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ from pathlib import Path
29
+
30
+ import numpy as np
31
+
32
+ from .analysis import _sum, read_ledger
33
+
34
+
35
+ def _table(path: Path) -> tuple[list[str], list[list[str]]]:
36
+ lines = path.read_text().splitlines()
37
+ head = lines[1].split()
38
+ rows = [ln.split() for ln in lines[2:] if ln.split() and ln.split()[0].lstrip("-").isdigit()]
39
+ return head, rows
40
+
41
+
42
+ def _aa(path: Path) -> dict[str, float]:
43
+ if not path.exists():
44
+ return {}
45
+ head, rows = _table(path)
46
+ return {k: float(v) for k, v in zip(head, rows[-1]) if _num(v)} if rows else {}
47
+
48
+
49
+ def _num(v: str) -> bool:
50
+ try:
51
+ float(v)
52
+ return True
53
+ except ValueError:
54
+ return False
55
+
56
+
57
+ def basin_balance(run: str | Path, outlet: str) -> dict[str, float]:
58
+ """The run's balance in m3 (``run`` holds ``swatplus/`` and ``outputs/``), with the residual of each part."""
59
+ run = Path(run)
60
+ sw = run / "swatplus"
61
+ land = sum(float(r[2]) for r in _table_skip(sw / "ls_unit.def")) * 1e4
62
+ head, rows = _table(sw / "basin_wb_day.txt")
63
+ col = {k: head.index(k) for k in head}
64
+ mm = lambda k: sum(float(r[col[k]]) for r in rows) # noqa: E731
65
+ d_sw = sum(float(r[col["sw_final"]]) - float(r[col["sw_init"]]) for r in rows)
66
+ d_sno = sum(float(r[col["sno_final"]]) - float(r[col["sno_init"]]) for r in rows)
67
+ aa = _aa(sw / "basin_wb_aa.txt")
68
+ years = mm("precip") / aa["precip"] if aa.get("precip") else len(rows) / 365.25
69
+ res, cha = _aa(sw / "basin_res_aa.txt"), _aa(sw / "basin_sd_cha_aa.txt")
70
+ if not (sw / "reservoir.con").exists():
71
+ res = {}
72
+ t = read_ledger(run / "outputs" / "ledger.csv")
73
+ import csv
74
+ with open(run / "outputs" / "series.csv", newline="") as f:
75
+ out_gage = sum(float(r[f"flow:{outlet}"]) for r in csv.DictReader(f)) * 86400.0
76
+ to_m3 = lambda x: x / 1000.0 * land # noqa: E731 mm over the land
77
+ b = {
78
+ "years": years, "land_m2": land,
79
+ "precipitation_land": to_m3(mm("precip")),
80
+ "et_land": to_m3(mm("et")),
81
+ "runoff_to_channels": to_m3(mm("surq_gen") + mm("latq")),
82
+ "percolation": to_m3(mm("perc")),
83
+ "soil_water_gain": to_m3(d_sw), "snow_gain": to_m3(d_sno),
84
+ "precipitation_lakes": _daily_sum(sw / "reservoir_day.txt", "precip", res.get("precip", 0.0) * years),
85
+ "evaporation_lakes": _daily_sum(sw / "reservoir_day.txt", "evap", res.get("evap", 0.0) * years),
86
+ "precipitation_channels": _daily_sum(sw / "channel_sd_day.txt", "precip", cha.get("precip", 0.0) * years),
87
+ "evaporation_channels": _daily_sum(sw / "channel_sd_day.txt", "evap", cha.get("evap", 0.0) * years),
88
+ "recharge_made": float(np.nansum(_sum(t, "recharge:made"))),
89
+ "recharge_received": float(np.nansum(_sum(t, "recharge:received"))),
90
+ "recharge_by_the_map": float(np.nansum(_sum(t, "recharge:by_the_map"))),
91
+ "groundwater_boundary_in": float(np.nansum(_sum(t, "groundwater:boundary:"))),
92
+ "groundwater_storage_release": float(np.nansum(_sum(t, "groundwater:storage_release"))),
93
+ "groundwater_to_streams": float(np.nansum(_sum(t, "exchange:", ":to_stream"))),
94
+ "groundwater_into_channels": float(np.nansum(_sum(t, "exchange:", ":applied"))),
95
+ "pumping": float(np.nansum(_sum(t, "route:well:", ":delivered"))),
96
+ "returns_to_streams": float(np.nansum(_sum(t, "route:swat:point_source:", ":delivered"))),
97
+ "withdrawals_from_streams": float(np.nansum(_sum(t, "route:swat:place_of_use:", ":delivered"))),
98
+ "irrigation": to_m3(mm("irr")) if "irr" in col else 0.0,
99
+ "groundwater_into_soil": to_m3(mm("gwsoilq")) if "gwsoilq" in col else 0.0,
100
+ "groundwater_to_soil_sent": float(np.nansum(_sum(t, "gw_soil:sent"))),
101
+ "inflow_from_elsewhere": _other_inflow(sw, t),
102
+ "outflow": out_gage,
103
+ "max_daily_closure_share": float(np.nanmax(np.abs(t.get("groundwater:closure_share", np.zeros(1))))),
104
+ }
105
+ # with the exchange's point sources (swatplus-bmi before 0.2.0), the exchange is in the routes; don't count twice
106
+ b["returns_to_streams"] -= float(np.nansum(_sum(t, "route:swat:point_source:gw_", ":delivered")))
107
+ b["withdrawals_from_streams"] -= float(np.nansum(_sum(t, "route:swat:place_of_use:seep_", ":delivered")))
108
+ b["land_residual"] = (b["precipitation_land"] + b["irrigation"] + b["groundwater_into_soil"] - b["et_land"] - b["runoff_to_channels"] - b["percolation"]
109
+ - b["soil_water_gain"] - b["snow_gain"])
110
+ b["groundwater_residual"] = (b["recharge_received"] + b["groundwater_boundary_in"]
111
+ + b["groundwater_storage_release"] - b["groundwater_to_streams"] - b["pumping"]
112
+ - b["groundwater_to_soil_sent"])
113
+ b["lake_storage_gain"] = _storage_gain(sw / "reservoir_day.txt")
114
+ b["channel_storage_gain"] = _storage_gain(sw / "channel_sd_day.txt")
115
+ b["channels_residual"] = (- b["lake_storage_gain"] - b["channel_storage_gain"]
116
+ + b["runoff_to_channels"] + b["groundwater_into_channels"] + b["precipitation_lakes"]
117
+ + b["precipitation_channels"] + b["returns_to_streams"]
118
+ + b["inflow_from_elsewhere"] - b["evaporation_lakes"]
119
+ - b["evaporation_channels"] - b["withdrawals_from_streams"] - b["outflow"])
120
+ return b
121
+
122
+
123
+ def _storage_gain(path: Path) -> float:
124
+ """The change in storage (``flo_stor``, m3) over the run, summed over the objects of a SWAT+ daily file: each
125
+ object's last day less its first (the first day's start isn't printed) [A]."""
126
+ if not path.exists():
127
+ return 0.0
128
+ head, rows = _table(path)
129
+ i, n = head.index("flo_stor"), head.index("name")
130
+ first, last = {}, {}
131
+ for r in rows:
132
+ first.setdefault(r[n], float(r[i]))
133
+ last[r[n]] = float(r[i])
134
+ return sum(last[k] - first[k] for k in last)
135
+
136
+
137
+ def _daily_sum(path: Path, column: str, otherwise: float) -> float:
138
+ """A column of a SWAT+ daily file summed over the run (m3), or ``otherwise`` (from the average annual file)."""
139
+ if not path.exists():
140
+ return otherwise
141
+ head, rows = _table(path)
142
+ return sum(float(r[head.index(column)]) for r in rows) if rows else otherwise
143
+
144
+
145
+ def _other_inflow(sw: Path, t: dict) -> float:
146
+ """m3 SWAT+'s channels took in over the run from anything the balance doesn't otherwise count (channel_sd_day and
147
+ reservoir_day, printed daily for it): each channel's inflow less its upstream channels' and lakes' outflow, less
148
+ the land's runoff into it, the groundwater it received and Basin Ledger's point sources into it."""
149
+ path = sw / "channel_sd_day.txt"
150
+ if not path.exists():
151
+ return float("nan")
152
+ head, rows = _table(path)
153
+ i_name, i_in, i_out = head.index("name"), head.index("flo_in"), head.index("flo_out")
154
+ flo_in = sum(float(r[i_in]) for r in rows) * 86400.0
155
+ out = {}
156
+ for r in rows:
157
+ out[r[i_name]] = out.get(r[i_name], 0.0) + float(r[i_out]) * 86400.0
158
+ down = {}
159
+ for f in ("chandeg.con", "reservoir.con"):
160
+ p = sw / f
161
+ if p.exists():
162
+ for r in [ln.split() for ln in p.read_text().splitlines()[2:] if ln.split()]:
163
+ down[r[1]] = {"sdc": f"cha{int(r[-3]):03d}", "res": f"res{int(r[-3]):03d}"}.get(r[-4])
164
+ from_channels = sum(v for c, v in out.items() if down.get(c, "") and down[c].startswith("cha"))
165
+ from_lakes = 0.0
166
+ rp = sw / "reservoir_day.txt"
167
+ if rp.exists():
168
+ h2, r2 = _table(rp)
169
+ j_name, j_out = h2.index("name"), h2.index("flo_out")
170
+ from_lakes = sum(float(r[j_out]) for r in r2 if down.get(r[j_name], "").startswith("cha"))
171
+ # a channel's inflow holds the groundwater it gained; a loss comes out of its outflow after routing (SWAT+'s
172
+ # seepage), so only the gains come off here
173
+ gw = float(sum(np.nansum(np.clip(v, 0.0, None)) for k, v in t.items()
174
+ if k.startswith("exchange:") and k.endswith(":applied")))
175
+ returns = float(np.nansum(_sum(t, "route:swat:point_source:", ":delivered")))
176
+ wb_head, wb = _table(sw / "basin_wb_day.txt")
177
+ lsu = sum(float(r[2]) for r in _table_skip(sw / "ls_unit.def")) * 1e4
178
+ runoff = sum(float(r[wb_head.index("surq_cha")]) + float(r[wb_head.index("latq_cha")]) for r in wb) / 1000 * lsu
179
+ return flo_in - from_channels - from_lakes - runoff - gw - returns
180
+
181
+
182
+ def _table_skip(path: Path) -> list[list[str]]:
183
+ """ls_unit.def: title, count, header, then rows (id, name, area ha, ...)."""
184
+ if not path.exists():
185
+ return []
186
+ lines = path.read_text().splitlines()
187
+ return [ln.split() for ln in lines[3:] if ln.split() and ln.split()[0].isdigit()]
188
+
189
+
190
+ def soil_water_trend(swat_dir: str | Path, days: int = 365) -> dict[str, float]:
191
+ """SWAT+'s basin soil water over the last ``days`` days its ``basin_wb_day.txt`` prints (all of them if fewer):
192
+ the change (mm, final less initial), the precipitation (mm) and the change as a share of the precipitation. A
193
+ warm-up whose soil water still changes by a sizable share of its last year's precipitation hasn't settled
194
+ (``scenarios.warm_up``)."""
195
+ head, rows = _table(Path(swat_dir) / "basin_wb_day.txt")
196
+ col = {k: head.index(k) for k in head}
197
+ rows = rows[-days:]
198
+ change = float(rows[-1][col["sw_final"]]) - float(rows[0][col["sw_init"]])
199
+ precip = sum(float(r[col["precip"]]) for r in rows)
200
+ return {"days": len(rows), "soil_water_change_mm": change, "precipitation_mm": precip,
201
+ "share": abs(change) / precip if precip > 0 else float("nan"),
202
+ "soil_water_final_mm": float(rows[-1][col["sw_final"]])}