swmod 0.0.1__py3-none-any.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.
swmod/coupling.py ADDED
@@ -0,0 +1,2510 @@
1
+ """
2
+ Coupled Simulation Module
3
+
4
+ Handles the partitioned Picard coupling loop between MODFLOW 6 (via `modflowapi`)
5
+ and the standalone `SurfaceWaterNetwork`.
6
+ """
7
+
8
+ import json
9
+ import logging
10
+ import sqlite3
11
+ import subprocess
12
+ import sys
13
+ import time
14
+ from collections.abc import Callable
15
+ from copy import deepcopy
16
+ from pathlib import Path
17
+ from typing import Any, Literal
18
+
19
+ import modflowapi
20
+ import numpy as np
21
+ import pandas as pd
22
+
23
+ from swmod._logging import verbose_logging
24
+ from swmod.network import Connection, Node, SurfaceWaterNetwork
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+
29
+ class CoupledSimulation:
30
+ """
31
+ Manages partitioned Picard coupling between a MODFLOW 6 groundwater model
32
+ and a Surface Water Network model.
33
+
34
+ When a GWT (Groundwater Transport) model is present in the MODFLOW 6 simulation,
35
+ concentration tracking is automatically enabled on all surface water nodes to support
36
+ solute transport coupling (e.g., chloride intrusion, contaminant plumes). For
37
+ multiple GWT models, model-specific concentrations can be provided per node via
38
+ ``node.concentrations = {"GWT_1": c1, "GWT_2": c2, ...}``.
39
+
40
+ Parameters
41
+ ----------
42
+ dll_path : str or Path, optional
43
+ Path to the MODFLOW 6 shared library DLL (`libmf6.dll`, `libmf6.so`, etc.).
44
+ If None, automatically searches for `libmf6.dll` in `.bin/`, `../.bin/`, and `../../.bin/`.
45
+ sim_dir : str or Path, default 'sim_output'
46
+ Path to the MODFLOW 6 simulation working directory containing simulation files.
47
+ sw_network : SurfaceWaterNetwork
48
+ Surface water network model instance.
49
+ gwf_model_name : str, default 'GWF_1'
50
+ MODFLOW 6 GWF model name. If left as default, the name is auto-detected
51
+ from `mfsim.nam` when a single GWF model is defined there.
52
+ riv_pack_name : str, default 'RIV_1'
53
+ MODFLOW 6 RIV package name.
54
+ relaxation_factor : float, default 0.3
55
+ Base under-relaxation factor (0.0, 1.0] for updating node stages between Picard iterations.
56
+ max_coupling_iter : int, default 50
57
+ Maximum outer Picard coupling iterations per time step.
58
+ stage_tol : float, default 1e-3
59
+ Convergence tolerance for maximum node stage change [m] between coupling iterations (1.0 mm).
60
+ Enforced in both ``"modflow"`` (via ``sim.allow_convergence``) and ``"picard"`` coupling schemes.
61
+ flow_tol : float, optional, default None
62
+ Optional volumetric flow residual convergence tolerance [m^3/day].
63
+ If provided, Picard loop requires both max stage shift < stage_tol and max flow residual < flow_tol.
64
+ If None, Picard loop checks only stage convergence (default).
65
+ coupling_scheme : {"modflow", "picard"}, default "modflow"
66
+ Coupling strategy used in :meth:`run`.
67
+ - ``"modflow"``: MODFLOW callback-driven coupling loop.
68
+ - ``"picard"``: Explicit partitioned Picard outer loop in Python.
69
+ Parameters ``relaxation_factor``, ``max_coupling_iter``, and ``flow_tol``
70
+ are used primarily when ``coupling_scheme="picard"``.
71
+ max_stage_step : float or None, default 0.1
72
+ Maximum allowed surface-water stage change [m] per GWF outer iteration when
73
+ ``coupling_scheme="modflow"``. Limiting the per-iteration stage jump (combined
74
+ with sign-flip oscillation damping) prevents positive-feedback blowups when
75
+ groundwater heads overshoot across a high-conductance ``RIV`` bed bottom, while
76
+ remaining unrelaxed (zero lag) whenever the stage change is within the cap.
77
+ Set to ``None`` to disable per-iteration stage limiting.
78
+ verbose : bool, default False
79
+ Whether to temporarily enable verbose logging (DEBUG on ``swmod.coupling``)
80
+ for coupling progress and forward verbosity to ``modflowapi``.
81
+ allow_unsafe_gwt_run : bool, default False
82
+ If True, bypasses GWT preflight safety checks before `modflowapi` initialization.
83
+
84
+ Notes
85
+ -----
86
+ Concentration tracking is automatically enabled if GWT models are detected in the simulation.
87
+ Each node's concentration can be updated via :meth:`Node.update_concentration` during
88
+ simulation loops to model solute transport at the groundwater-surface water interface.
89
+ When possible, the coupling maps current SW concentrations to RIV auxiliary
90
+ concentration fields used by GWT/SSM. With multiple GWT models, each model is
91
+ mapped to its own AUX concentration column.
92
+ """
93
+
94
+ def __init__(
95
+ self,
96
+ dll_path: str | Path | None = None,
97
+ sim_dir: str | Path = "sim_output",
98
+ sw_network: SurfaceWaterNetwork | None = None,
99
+ gwf_model_name: str = "GWF_1",
100
+ riv_pack_name: str = "RIV_1",
101
+ relaxation_factor: float = 0.3,
102
+ max_coupling_iter: int = 50,
103
+ stage_tol: float = 1e-3,
104
+ flow_tol: float | None = None,
105
+ coupling_scheme: Literal["modflow", "picard"] = "modflow",
106
+ max_stage_step: float | None = 0.1,
107
+ verbose: bool = False,
108
+ allow_unsafe_gwt_run: bool = False,
109
+ ):
110
+ if dll_path is None:
111
+ possible_dll_paths = [
112
+ Path(".bin/libmf6.dll"),
113
+ Path("../.bin/libmf6.dll"),
114
+ Path("../../.bin/libmf6.dll"),
115
+ ]
116
+ found = next((p for p in possible_dll_paths if p.exists()), None)
117
+ if found is not None:
118
+ self.dll_path = found
119
+ else:
120
+ self.dll_path = Path(".bin/libmf6.dll")
121
+ else:
122
+ self.dll_path = Path(dll_path)
123
+
124
+ self.sim_dir = Path(sim_dir)
125
+ if sw_network is None:
126
+ raise ValueError(
127
+ "sw_network parameter must be provided to CoupledSimulation."
128
+ )
129
+ sw_network.validate()
130
+ self.sw_network = sw_network
131
+ self.gwf_model_name = gwf_model_name.upper()
132
+ self._gwf_model_name_user_specified = self.gwf_model_name != "GWF_1"
133
+ self.riv_pack_name = riv_pack_name.upper()
134
+ self.relaxation_factor = relaxation_factor
135
+ self.max_coupling_iter = max_coupling_iter
136
+ self.stage_tol = stage_tol
137
+ self.flow_tol = flow_tol
138
+ if coupling_scheme not in {"modflow", "picard"}:
139
+ raise ValueError(
140
+ "coupling_scheme must be either 'modflow' or 'picard'."
141
+ )
142
+ self.coupling_scheme = coupling_scheme
143
+ if max_stage_step is not None and float(max_stage_step) <= 0.0:
144
+ raise ValueError("max_stage_step must be positive or None.")
145
+ self.max_stage_step = (
146
+ None if max_stage_step is None else float(max_stage_step)
147
+ )
148
+ self.verbose = verbose
149
+ self.allow_unsafe_gwt_run = allow_unsafe_gwt_run
150
+
151
+ if not self.dll_path.exists():
152
+ raise FileNotFoundError(f"MODFLOW 6 DLL not found at: {self.dll_path}")
153
+
154
+ self.mf6 = modflowapi.ModflowApi(
155
+ str(self.dll_path), working_directory=str(self.sim_dir)
156
+ )
157
+ self.head_addr: str | None = None
158
+ self.stage_addr: str | None = None
159
+ self.rbot_addr: str | None = None
160
+ self.head: np.ndarray | None = None
161
+
162
+ self.initialize_history()
163
+
164
+ self._gwt_models: list[str] = []
165
+ self._riv_auxvar_addr: str | None = None
166
+ self._gwt_fmi_auxvar_addrs: dict[str, str] = {}
167
+ self._riv_conc_aux_indices: dict[str, int] = {}
168
+ self._riv_naux: int = 0
169
+ self._warned_aux_layout_assumption = False
170
+ self._riv_aux_configured = False
171
+ self._nodeuser_configured = False
172
+ self._nodeuser_zero_based: np.ndarray | None = None
173
+ self._nodesuser: int = 0
174
+ self._gwt_conc_addrs: dict[str, str] = {}
175
+ self._gwt_nodeuser_cache: dict[str, tuple[np.ndarray | None, int]] = {}
176
+ self._step_prev_stages: dict[int | str, float] | None = None
177
+ self._step_prev_concentrations: dict[str, dict[int | str, float]] = {}
178
+ self._iter_prev_stage_deltas: dict[int | str, float] = {}
179
+ self._iter_stage_alphas: dict[int | str, float] = {}
180
+ self._last_iter_stage_damped: bool = False
181
+ self._last_iter_max_stage_change: float = 0.0
182
+
183
+ # Detect GWT model for concentration tracking
184
+ self._enable_concentration_tracking()
185
+
186
+ def _get_providers(self) -> list[Callable[[], float]]:
187
+ """
188
+ Build stage provider functions in RIV package registration order.
189
+ Clamps stage to bed_bottom elevation (stage >= bed_bottom) to prevent unphysical
190
+ negative suction drainage in MODFLOW RIV cells when surface stage drops below bed.
191
+ """
192
+ providers: list[Callable[[], float]] = []
193
+ indexed_providers: list[tuple[int, Callable[[], float]]] = []
194
+ for node in self.sw_network.nodes.values():
195
+ if node.gw_cell_ids:
196
+ node_providers: list[Callable[[], float]] = []
197
+ for rbot in node.gw_bottoms:
198
+ node_providers.append(lambda n=node, b=rbot: max(n.stage, b))
199
+ providers.extend(node_providers)
200
+ if node.riv_row_indices:
201
+ indexed_providers.extend(
202
+ zip(node.riv_row_indices, node_providers, strict=False)
203
+ )
204
+ for conn in self.sw_network.connections.values():
205
+ if conn.gw_cell_ids:
206
+ conn_providers: list[Callable[[], float]] = []
207
+ for rbot, frac in zip(conn.gw_bottoms, conn.gw_fractions):
208
+ conn_providers.append(
209
+ lambda c=conn, f=frac, b=rbot: max(
210
+ (1.0 - f) * self.sw_network.nodes[c.node_from].stage
211
+ + f * self.sw_network.nodes[c.node_to].stage,
212
+ b,
213
+ )
214
+ )
215
+ providers.extend(conn_providers)
216
+ if conn.riv_row_indices:
217
+ indexed_providers.extend(
218
+ zip(conn.riv_row_indices, conn_providers, strict=False)
219
+ )
220
+ return self._order_providers_by_riv_rows(
221
+ providers, indexed_providers, value_name="stage"
222
+ )
223
+
224
+ def _order_providers_by_riv_rows(
225
+ self,
226
+ providers: list[Callable[[], float]],
227
+ indexed_providers: list[tuple[int, Callable[[], float]]],
228
+ value_name: str,
229
+ ) -> list[Callable[[], float]]:
230
+ """Reorder providers by explicit RIV row mapping when riv_row_indices are available."""
231
+ if not indexed_providers:
232
+ return providers
233
+
234
+ if len(indexed_providers) != len(providers):
235
+ raise ValueError(
236
+ "Partial riv_row_indices mapping detected: provide riv_row_indices "
237
+ f"for all coupled node/connection entries or for none when updating {value_name}."
238
+ )
239
+
240
+ row_ids = [int(ridx) for ridx, _ in indexed_providers]
241
+ if min(row_ids) < 0:
242
+ raise ValueError(
243
+ f"Invalid negative riv_row_indices found while mapping {value_name} providers."
244
+ )
245
+ if len(set(row_ids)) != len(row_ids):
246
+ raise ValueError(
247
+ f"Duplicate riv_row_indices found while mapping {value_name} providers."
248
+ )
249
+ expected = set(range(len(providers)))
250
+ missing = expected.difference(row_ids)
251
+ extra = set(row_ids).difference(expected)
252
+ if missing or extra:
253
+ raise ValueError(
254
+ "riv_row_indices must be a complete 0-based permutation of RIV rows for "
255
+ f"{value_name} updates. Missing: {sorted(missing)}, extra: {sorted(extra)}."
256
+ )
257
+
258
+ ordered: list[Callable[[], float] | None] = [None] * len(providers)
259
+ for ridx, provider in indexed_providers:
260
+ ordered[int(ridx)] = provider
261
+ return [p for p in ordered if p is not None]
262
+
263
+ def _get_node_concentration(self, node: Node, gwt_model_name: str) -> float:
264
+ """
265
+ Resolve node concentration for a specific GWT model.
266
+
267
+ Model-specific concentrations can be provided via ``node.concentrations`` dict.
268
+ If absent, falls back to scalar ``node.concentration``.
269
+ """
270
+ model_key = str(gwt_model_name).upper()
271
+
272
+ per_model = getattr(node, "concentrations", None)
273
+ if isinstance(per_model, dict):
274
+ for key, value in per_model.items():
275
+ if str(key).upper() == model_key:
276
+ return max(0.0, float(value))
277
+
278
+ conc = getattr(node, "concentration", 0.0)
279
+ if isinstance(conc, dict):
280
+ for key, value in conc.items():
281
+ if str(key).upper() == model_key:
282
+ return max(0.0, float(value))
283
+ return 0.0
284
+
285
+ return max(0.0, float(conc))
286
+
287
+ def _get_concentration_providers(
288
+ self, gwt_model_name: str
289
+ ) -> list[Callable[[], float]]:
290
+ """
291
+ Build concentration providers in RIV package registration order.
292
+
293
+ The order mirrors :meth:`_get_providers` so concentration values align with
294
+ the same RIV entries used for stage updates.
295
+ """
296
+ providers: list[Callable[[], float]] = []
297
+ indexed_providers: list[tuple[int, Callable[[], float]]] = []
298
+ for node in self.sw_network.nodes.values():
299
+ if node.gw_cell_ids:
300
+ node_providers: list[Callable[[], float]] = []
301
+ for _ in node.gw_bottoms:
302
+ node_providers.append(
303
+ lambda n=node, m=gwt_model_name: self._get_node_concentration(
304
+ n, m
305
+ )
306
+ )
307
+ providers.extend(node_providers)
308
+ if node.riv_row_indices:
309
+ indexed_providers.extend(
310
+ zip(node.riv_row_indices, node_providers, strict=False)
311
+ )
312
+ for conn in self.sw_network.connections.values():
313
+ if conn.gw_cell_ids:
314
+ conn_providers: list[Callable[[], float]] = []
315
+ for frac in conn.gw_fractions:
316
+ conn_providers.append(
317
+ lambda c=conn, f=frac, m=gwt_model_name: max(
318
+ 0.0,
319
+ (1.0 - f)
320
+ * self._get_node_concentration(
321
+ self.sw_network.nodes[c.node_from], m
322
+ )
323
+ + f
324
+ * self._get_node_concentration(
325
+ self.sw_network.nodes[c.node_to], m
326
+ ),
327
+ )
328
+ )
329
+ providers.extend(conn_providers)
330
+ if conn.riv_row_indices:
331
+ indexed_providers.extend(
332
+ zip(conn.riv_row_indices, conn_providers, strict=False)
333
+ )
334
+ return self._order_providers_by_riv_rows(
335
+ providers, indexed_providers, value_name="concentration"
336
+ )
337
+
338
+ def _enable_concentration_tracking(self) -> None:
339
+ """
340
+ Detect if GWT model(s) are present and enable concentration tracking on all nodes.
341
+
342
+ Concentration tracking is automatically enabled for GW-SW transport coupling
343
+ when the MODFLOW 6 simulation includes GWT models.
344
+ """
345
+ models_from_nam: list[tuple[str, str]] = []
346
+ nam_file = self.sim_dir / "mfsim.nam"
347
+ if nam_file.exists():
348
+ models_from_nam = self._read_models_from_nam(nam_file)
349
+
350
+ if not self._gwf_model_name_user_specified:
351
+ gwf_models = [
352
+ name for model_type, name in models_from_nam if model_type == "GWF6"
353
+ ]
354
+ if len(gwf_models) == 1:
355
+ self.gwf_model_name = gwf_models[0]
356
+
357
+ gwt_models: list[str] = []
358
+
359
+ if not gwt_models:
360
+ gwt_models = [
361
+ name for model_type, name in models_from_nam if model_type == "GWT6"
362
+ ]
363
+
364
+ self._gwt_models = gwt_models
365
+ if gwt_models:
366
+ with verbose_logging(
367
+ bool(getattr(self, "verbose", False)),
368
+ level=logging.INFO,
369
+ logger_name=logger.name,
370
+ ):
371
+ logger.info("GWT models detected: %s", gwt_models)
372
+ logger.info(
373
+ "Enabling concentration tracking on all surface water nodes."
374
+ )
375
+
376
+ for node in self.sw_network.nodes.values():
377
+ node.track_concentration = bool(gwt_models)
378
+
379
+ @staticmethod
380
+ def _read_models_from_nam(nam_path: Path) -> list[tuple[str, str]]:
381
+ """
382
+ Read model definitions from mfsim.nam MODELS section.
383
+
384
+ Returns list of (model_type, model_name), both upper-cased.
385
+ """
386
+ models: list[tuple[str, str]] = []
387
+ section: str | None = None
388
+
389
+ try:
390
+ lines = nam_path.read_text(encoding="utf-8").splitlines()
391
+ except OSError:
392
+ return models
393
+
394
+ for raw_line in lines:
395
+ line = raw_line.strip()
396
+ if not line or line.startswith("#"):
397
+ continue
398
+
399
+ upper = line.upper()
400
+ if upper.startswith("BEGIN "):
401
+ parts = upper.split()
402
+ section = parts[1] if len(parts) > 1 else None
403
+ continue
404
+ if upper.startswith("END "):
405
+ section = None
406
+ continue
407
+ if section != "MODELS":
408
+ continue
409
+
410
+ parts = line.split()
411
+ if len(parts) < 2:
412
+ continue
413
+
414
+ model_type = parts[0].upper()
415
+ model_name = None
416
+ if len(parts) >= 3 and not parts[2].lower().endswith(".nam"):
417
+ model_name = parts[2]
418
+ elif not parts[1].lower().endswith(".nam"):
419
+ model_name = parts[1]
420
+
421
+ if model_name:
422
+ models.append((model_type, model_name.upper()))
423
+
424
+ return models
425
+
426
+ def _validate_gwt_solutiongroup_order(self) -> None:
427
+ """
428
+ Validate GWF/GWT IMS ordering in mfsim.nam before native MF6 initialization.
429
+
430
+ MODFLOW 6 requires:
431
+ 1. GWF and GWT are solved by different IMS packages.
432
+ 2. The GWF IMS line appears before the GWT IMS line in the solutiongroup.
433
+ """
434
+ if not self._gwt_models:
435
+ return
436
+
437
+ nam_path = self.sim_dir / "mfsim.nam"
438
+ if not nam_path.exists():
439
+ return
440
+
441
+ model_types: dict[str, str] = {}
442
+ solutiongroups: list[dict[str, tuple[int, str]]] = []
443
+ current_group: dict[str, tuple[int, str]] | None = None
444
+ section: str | None = None
445
+ order = 0
446
+
447
+ try:
448
+ lines = nam_path.read_text(encoding="utf-8").splitlines()
449
+ except OSError:
450
+ return
451
+
452
+ for raw_line in lines:
453
+ line = raw_line.strip()
454
+ if not line or line.startswith("#"):
455
+ continue
456
+
457
+ upper = line.upper()
458
+ if upper.startswith("BEGIN "):
459
+ parts = upper.split()
460
+ section = parts[1] if len(parts) > 1 else None
461
+ if section == "SOLUTIONGROUP":
462
+ current_group = {}
463
+ order = 0
464
+ continue
465
+ if upper.startswith("END "):
466
+ if section == "SOLUTIONGROUP" and current_group is not None:
467
+ solutiongroups.append(current_group)
468
+ current_group = None
469
+ section = None
470
+ continue
471
+
472
+ parts = line.split()
473
+ if section == "MODELS" and len(parts) >= 3:
474
+ model_types[parts[2].upper()] = parts[0].upper()
475
+ elif (
476
+ section == "SOLUTIONGROUP"
477
+ and len(parts) >= 3
478
+ and current_group is not None
479
+ ):
480
+ if parts[0].upper() != "IMS6":
481
+ continue
482
+ ims_file = parts[1]
483
+ for model_name in parts[2:]:
484
+ current_group[model_name.upper()] = (order, ims_file)
485
+ order += 1
486
+
487
+ gwf_name = self.gwf_model_name.upper()
488
+ gwt_names = [m.upper() for m in self._gwt_models]
489
+ errors: list[str] = []
490
+
491
+ for gwt_name in gwt_names:
492
+ if model_types.get(gwt_name) != "GWT6":
493
+ continue
494
+
495
+ found = False
496
+ for group in solutiongroups:
497
+ if gwf_name not in group or gwt_name not in group:
498
+ continue
499
+ found = True
500
+ gwf_order, gwf_ims = group[gwf_name]
501
+ gwt_order, gwt_ims = group[gwt_name]
502
+ if gwf_ims == gwt_ims:
503
+ errors.append(
504
+ f"{gwf_name} and {gwt_name} use the same IMS file '{gwf_ims}'."
505
+ )
506
+ if gwf_order >= gwt_order:
507
+ errors.append(
508
+ f"{gwt_name} is listed before {gwf_name} in solutiongroup."
509
+ )
510
+ break
511
+ if not found:
512
+ errors.append(
513
+ f"Could not find {gwf_name} and {gwt_name} in the same solutiongroup."
514
+ )
515
+
516
+ if errors and not self.allow_unsafe_gwt_run:
517
+ err_text = "; ".join(errors)
518
+ raise RuntimeError(
519
+ "Invalid MODFLOW 6 GWF/GWT solution configuration: "
520
+ f"{err_text} "
521
+ "MF6 will terminate during initialization for this configuration "
522
+ "(often perceived as a kernel crash when using modflowapi). "
523
+ "Fix mfsim.nam so GWF uses a different IMS than GWT and the GWF IMS "
524
+ "line appears before the GWT IMS line."
525
+ )
526
+ if errors and self.allow_unsafe_gwt_run:
527
+ logger.warning(
528
+ "Proceeding despite invalid GWF/GWT solution configuration: %s",
529
+ "; ".join(errors),
530
+ )
531
+
532
+ def _get_solution_ids_for_run(self) -> list[int]:
533
+ """
534
+ Resolve MODFLOW solution IDs from mfsim.nam solutiongroup IMS entries.
535
+
536
+ Returns [1] when the name file cannot be parsed.
537
+ """
538
+ nam_path = self.sim_dir / "mfsim.nam"
539
+ if not nam_path.exists():
540
+ return [1]
541
+
542
+ try:
543
+ lines = nam_path.read_text(encoding="utf-8").splitlines()
544
+ except OSError:
545
+ return [1]
546
+
547
+ in_solutiongroup = False
548
+ ims_count = 0
549
+ for raw_line in lines:
550
+ line = raw_line.strip()
551
+ if not line or line.startswith("#"):
552
+ continue
553
+ upper = line.upper()
554
+ if upper.startswith("BEGIN SOLUTIONGROUP"):
555
+ in_solutiongroup = True
556
+ continue
557
+ if in_solutiongroup and upper.startswith("END SOLUTIONGROUP"):
558
+ break
559
+ if in_solutiongroup and upper.startswith("IMS6 "):
560
+ ims_count += 1
561
+
562
+ if ims_count <= 0:
563
+ return [1]
564
+ return list(range(1, ims_count + 1))
565
+
566
+ @staticmethod
567
+ def _normalize_aux_name(name: Any) -> str:
568
+ """Normalize MF6 aux-name entries to comparable uppercase text."""
569
+ if isinstance(name, bytes):
570
+ text = name.decode("ascii", errors="ignore")
571
+ elif isinstance(name, np.bytes_):
572
+ text = bytes(name).decode("ascii", errors="ignore")
573
+ else:
574
+ text = str(name)
575
+ return text.strip().strip("\x00").strip("'").strip('"').upper()
576
+
577
+ def _configure_riv_concentration_assignment(self) -> None:
578
+ """
579
+ Configure MF6 RIV aux-memory pointers for concentration assignment.
580
+
581
+ Requires a detected GWT model and an auxiliary variable named one of:
582
+ CONCENTRATION, RIV_SW, or CONC.
583
+ """
584
+ self._riv_auxvar_addr = None
585
+ self._gwt_fmi_auxvar_addrs = {}
586
+ self._riv_conc_aux_indices = {}
587
+ self._riv_naux = 0
588
+ self._riv_aux_configured = True
589
+
590
+ if not self._gwt_models:
591
+ return
592
+
593
+ try:
594
+ naux_addr = self.mf6.get_var_address(
595
+ "NAUX", self.gwf_model_name, self.riv_pack_name
596
+ )
597
+ naux_val = self.mf6.get_value(naux_addr)
598
+ if len(naux_val) == 0:
599
+ logger.warning(
600
+ "GWT model detected but RIV NAUX is empty; cannot assign RIV concentration auxiliary values."
601
+ )
602
+ return
603
+ self._riv_naux = int(naux_val[0])
604
+ except Exception:
605
+ logger.warning(
606
+ "GWT model detected, but unable to read RIV NAUX from MODFLOW API; "
607
+ "RIV concentration assignment is disabled."
608
+ )
609
+ return
610
+
611
+ if self._riv_naux <= 0:
612
+ logger.warning(
613
+ "GWT model detected, but RIV package has no AUX variables (NAUX=0); "
614
+ "RIV concentration assignment is disabled."
615
+ )
616
+ return
617
+
618
+ aux_names: list[str] = []
619
+ try:
620
+ aux_name_addr = self.mf6.get_var_address(
621
+ "AUXNAME_CST", self.gwf_model_name, self.riv_pack_name
622
+ )
623
+ raw_names = self.mf6.get_value(aux_name_addr)
624
+ aux_names = [self._normalize_aux_name(v) for v in raw_names]
625
+ except Exception:
626
+ aux_names = []
627
+
628
+ if not aux_names:
629
+ try:
630
+ aux_name_addr = self.mf6.get_var_address(
631
+ "AUXNAME", self.gwf_model_name, self.riv_pack_name
632
+ )
633
+ raw_names = self.mf6.get_value(aux_name_addr)
634
+ aux_names = [self._normalize_aux_name(v) for v in raw_names]
635
+ except Exception:
636
+ aux_names = []
637
+
638
+ if aux_names:
639
+ used_indices: set[int] = set()
640
+ for model in self._gwt_models:
641
+ m = str(model).upper()
642
+ candidates = [
643
+ f"CONCENTRATION_{m}",
644
+ f"RIV_SW_{m}",
645
+ f"CONC_{m}",
646
+ f"{m}_CONCENTRATION",
647
+ f"{m}_RIV_SW",
648
+ f"{m}_CONC",
649
+ m,
650
+ ]
651
+
652
+ found_idx: int | None = None
653
+ for candidate in candidates:
654
+ if candidate in aux_names:
655
+ cand_idx = aux_names.index(candidate)
656
+ if cand_idx not in used_indices:
657
+ found_idx = cand_idx
658
+ break
659
+
660
+ # Single-model fallback to generic names.
661
+ if found_idx is None and len(self._gwt_models) == 1:
662
+ for generic in ("CONCENTRATION", "RIV_SW", "CONC"):
663
+ if generic in aux_names:
664
+ cand_idx = aux_names.index(generic)
665
+ if cand_idx not in used_indices:
666
+ found_idx = cand_idx
667
+ break
668
+
669
+ if found_idx is not None:
670
+ self._riv_conc_aux_indices[m] = found_idx
671
+ used_indices.add(found_idx)
672
+ else:
673
+ logger.warning(
674
+ "GWT model '%s' detected, but no matching RIV AUX concentration column was found; "
675
+ "concentration assignment for this model is disabled.",
676
+ model,
677
+ )
678
+ elif self._riv_naux >= len(self._gwt_models):
679
+ for idx, model in enumerate(self._gwt_models):
680
+ self._riv_conc_aux_indices[str(model).upper()] = idx
681
+ logger.warning(
682
+ "GWT model(s) detected, but RIV AUX names are unavailable via MODFLOW API; "
683
+ "mapping concentrations to AUX columns by GWT model order."
684
+ )
685
+ else:
686
+ logger.warning(
687
+ "GWT model(s) detected, but RIV AUX names are unavailable and NAUX is smaller than "
688
+ "the number of GWT models; RIV concentration assignment is disabled."
689
+ )
690
+ return
691
+
692
+ if not self._riv_conc_aux_indices:
693
+ return
694
+
695
+ try:
696
+ self._riv_auxvar_addr = self.mf6.get_var_address(
697
+ "AUXVAR", self.gwf_model_name, self.riv_pack_name
698
+ )
699
+ except Exception:
700
+ self._riv_auxvar_addr = None
701
+ logger.warning(
702
+ "GWT model detected, but unable to locate RIV AUXVAR memory address; "
703
+ "RIV concentration assignment is disabled."
704
+ )
705
+ return
706
+
707
+ self._discover_gwt_fmi_auxvar_addrs()
708
+
709
+ def _discover_gwt_fmi_auxvar_addrs(self) -> None:
710
+ """
711
+ Locate MODFLOW 6 GWT FMI flow-term AUXVAR addresses corresponding to ``riv_pack_name``.
712
+
713
+ When a GWF6-GWT6 exchange is active, MODFLOW 6's GWT/SSM package reads package
714
+ auxiliary concentrations from ``<GWT>/FMI-FT<k>/AUXVAR`` rather than directly from
715
+ ``<GWF>/<RIV_PACK>/AUXVAR``. Because the exchange only refreshes FMI AUXVAR when the
716
+ GWF package reads new stress-period data from disk, swmod must write updated SW
717
+ concentrations to both GWF RIV AUXVAR and each GWT model's matching FMI-FT AUXVAR.
718
+ """
719
+ self._gwt_fmi_auxvar_addrs = {}
720
+ target_pack = self.riv_pack_name.upper()
721
+
722
+ input_vars: list[str] = []
723
+ if hasattr(self.mf6, "get_input_var_names"):
724
+ try:
725
+ input_vars = [str(v) for v in self.mf6.get_input_var_names()]
726
+ except Exception:
727
+ input_vars = []
728
+
729
+ for gwt_model in self._gwt_models:
730
+ m_key = str(gwt_model).upper()
731
+ ft_names: list[str] = []
732
+ if input_vars:
733
+ prefix = f"{m_key}/FMI-FT"
734
+ seen_ft: set[str] = set()
735
+ for var in input_vars:
736
+ upper_v = var.upper()
737
+ if upper_v.startswith(prefix) and upper_v.endswith("/NAME"):
738
+ parts = upper_v.split("/")
739
+ if len(parts) >= 3 and parts[1] not in seen_ft:
740
+ seen_ft.add(parts[1])
741
+ ft_names.append(parts[1])
742
+ else:
743
+ ft_names = [f"FMI-FT{k}" for k in range(1, 51)]
744
+
745
+ for ft_name in ft_names:
746
+ try:
747
+ name_addr = self.mf6.get_var_address("NAME", m_key, ft_name)
748
+ raw_val = self.mf6.get_value(name_addr)
749
+ except Exception:
750
+ if not input_vars:
751
+ break
752
+ continue
753
+
754
+ if isinstance(raw_val, (list, tuple, np.ndarray)):
755
+ names = [self._normalize_aux_name(v) for v in np.atleast_1d(raw_val)]
756
+ else:
757
+ names = [self._normalize_aux_name(raw_val)]
758
+
759
+ if target_pack in names:
760
+ try:
761
+ fmi_aux_addr = self.mf6.get_var_address("AUXVAR", m_key, ft_name)
762
+ # Verify address is readable before registering
763
+ self.mf6.get_value(fmi_aux_addr)
764
+ self._gwt_fmi_auxvar_addrs[m_key] = fmi_aux_addr
765
+ logger.debug(
766
+ "Mapped GWT model '%s' FMI AUXVAR for '%s' -> %s",
767
+ m_key,
768
+ target_pack,
769
+ fmi_aux_addr,
770
+ )
771
+ except Exception:
772
+ logger.warning(
773
+ "Found GWT FMI flow term '%s/%s' for '%s', but unable to access its AUXVAR.",
774
+ m_key,
775
+ ft_name,
776
+ target_pack,
777
+ )
778
+ break
779
+
780
+ def _write_auxvar_concentrations(
781
+ self,
782
+ auxvar_addr: str,
783
+ concentration_providers: dict[str, list[Callable[[], float]]],
784
+ ) -> None:
785
+ """Write SW concentrations into a single MODFLOW 6 AUXVAR memory array."""
786
+ aux = np.asarray(self.mf6.get_value(auxvar_addr))
787
+
788
+ if aux.ndim == 2:
789
+ if concentration_providers:
790
+ first_model = next(iter(concentration_providers))
791
+ n_entries = len(concentration_providers[first_model])
792
+ else:
793
+ n_entries = 0
794
+
795
+ if aux.shape[0] == n_entries:
796
+ for model, aux_idx in self._riv_conc_aux_indices.items():
797
+ providers = concentration_providers.get(model, [])
798
+ if aux_idx < aux.shape[1]:
799
+ for i, provider in enumerate(providers):
800
+ aux[i, aux_idx] = provider()
801
+ elif aux.shape[1] == n_entries:
802
+ for model, aux_idx in self._riv_conc_aux_indices.items():
803
+ providers = concentration_providers.get(model, [])
804
+ if aux_idx < aux.shape[0]:
805
+ for i, provider in enumerate(providers):
806
+ aux[aux_idx, i] = provider()
807
+ elif self._riv_naux > 0 and aux.shape[1] == self._riv_naux and aux.shape[0] >= n_entries:
808
+ for model, aux_idx in self._riv_conc_aux_indices.items():
809
+ providers = concentration_providers.get(model, [])
810
+ if aux_idx < aux.shape[1]:
811
+ for i, provider in enumerate(providers):
812
+ aux[i, aux_idx] = provider()
813
+ elif self._riv_naux > 0 and aux.shape[0] == self._riv_naux and aux.shape[1] >= n_entries:
814
+ for model, aux_idx in self._riv_conc_aux_indices.items():
815
+ providers = concentration_providers.get(model, [])
816
+ if aux_idx < aux.shape[0]:
817
+ for i, provider in enumerate(providers):
818
+ aux[aux_idx, i] = provider()
819
+ else:
820
+ logger.warning(
821
+ "RIV AUXVAR '%s' shape %s does not match %d providers; skipping concentration update.",
822
+ auxvar_addr,
823
+ aux.shape,
824
+ n_entries,
825
+ )
826
+ return
827
+ self.mf6.set_value(auxvar_addr, aux)
828
+ return
829
+
830
+ if aux.ndim == 1 and self._riv_naux > 0:
831
+ n_entries = len(aux) // self._riv_naux
832
+ for model, aux_idx in self._riv_conc_aux_indices.items():
833
+ providers = concentration_providers.get(model, [])
834
+ for i in range(min(n_entries, len(providers))):
835
+ flat_idx = i * self._riv_naux + aux_idx
836
+ if flat_idx < len(aux):
837
+ aux[flat_idx] = providers[i]()
838
+ if self._riv_naux > 1 and not self._warned_aux_layout_assumption:
839
+ logger.warning(
840
+ "RIV AUXVAR was returned as a 1-D vector; assuming entry-major flattened layout "
841
+ "for concentration assignment."
842
+ )
843
+ self._warned_aux_layout_assumption = True
844
+ self.mf6.set_value(auxvar_addr, aux)
845
+ return
846
+
847
+ logger.warning(
848
+ "Unsupported RIV AUXVAR '%s' shape %s; concentration assignment skipped for this step.",
849
+ auxvar_addr,
850
+ aux.shape,
851
+ )
852
+
853
+ def _update_riv_concentrations(
854
+ self, concentration_providers: dict[str, list[Callable[[], float]]]
855
+ ) -> None:
856
+ """
857
+ Push SW concentrations into MODFLOW 6 RIV AUXVAR and GWT FMI AUXVAR for GWT/SSM coupling.
858
+ """
859
+ if self._riv_auxvar_addr is None or not self._riv_conc_aux_indices:
860
+ return
861
+
862
+ self._write_auxvar_concentrations(self._riv_auxvar_addr, concentration_providers)
863
+ for fmi_addr in self._gwt_fmi_auxvar_addrs.values():
864
+ self._write_auxvar_concentrations(fmi_addr, concentration_providers)
865
+
866
+ def _get_connection_flow_series(
867
+ self, conn: Connection, n_steps: int
868
+ ) -> list[float]:
869
+ """Resolve stored flow history for a connection."""
870
+ key_candidates = []
871
+ for key in [
872
+ getattr(conn, "_history_key", None),
873
+ getattr(conn, "name", None),
874
+ f"{conn.node_from}->{conn.node_to}",
875
+ ]:
876
+ if key and key not in key_candidates:
877
+ key_candidates.append(key)
878
+
879
+ for key in key_candidates:
880
+ if key in self.history["flows"]:
881
+ return self.history["flows"][key]
882
+
883
+ return [0.0] * n_steps
884
+
885
+ def run(
886
+ self,
887
+ ext_flow_series: (dict[int | str, list[float]] | list[float]) | None = None,
888
+ precipitation_series: (dict[int | str, list[float]] | list[float])
889
+ | None = None,
890
+ evaporation_series: (dict[int | str, list[float]] | list[float]) | None = None,
891
+ verbose: bool | None = None,
892
+ ) -> dict[int | str, float]:
893
+ """
894
+ Execute coupled SW-GW simulation across all MODFLOW 6 time steps.
895
+
896
+ Parameters
897
+ ----------
898
+ ext_flow_series : dict or list of float, optional
899
+ Time-varying external volumetric node inflows [m^3/day] mapped by node name or uniform list for all nodes.
900
+ precipitation_series : dict or list of float, optional
901
+ Time-varying direct open-water precipitation rate [m/day] mapped by node name or uniform list for all nodes.
902
+ evaporation_series : dict or list of float, optional
903
+ Time-varying direct open-water evaporation rate [m/day] mapped by node name or uniform list for all nodes.
904
+ verbose : bool, optional
905
+ Whether to temporarily enable verbose logging (DEBUG on ``swmod.coupling``)
906
+ for coupling progress. If None, uses ``self.verbose`` specified during
907
+ initialization. For ``coupling_scheme="modflow"``, this flag is also passed
908
+ to MODFLOW API execution.
909
+
910
+ Returns
911
+ -------
912
+ dict of {int or str : float}
913
+ Map of node ID -> final solved stage elevation [m].
914
+ """
915
+ self.ext_flow_series = ext_flow_series
916
+ self.precipitation_series = precipitation_series
917
+ self.evaporation_series = evaporation_series
918
+ if verbose is None:
919
+ verbose = self.verbose
920
+
921
+ nam_path = self.sim_dir / "mfsim.nam"
922
+ if not nam_path.exists():
923
+ raise FileNotFoundError(
924
+ f"MODFLOW 6 simulation name file not found at '{nam_path}'. "
925
+ "Ensure the FloPy simulation is written before coupling.run(), "
926
+ "for example by calling sim.write_simulation()."
927
+ )
928
+
929
+ self._validate_gwt_solutiongroup_order()
930
+ self._preflight_native_initialize_if_unstructured()
931
+
932
+ self.mf6 = modflowapi.ModflowApi(
933
+ str(self.dll_path), working_directory=str(self.sim_dir)
934
+ )
935
+
936
+ self.head_addr = self.mf6.get_var_address("X", self.gwf_model_name)
937
+ self.stage_addr = self.mf6.get_var_address(
938
+ "STAGE", self.gwf_model_name, self.riv_pack_name
939
+ )
940
+ self.rbot_addr = self.mf6.get_var_address(
941
+ "RBOT", self.gwf_model_name, self.riv_pack_name
942
+ )
943
+
944
+ self.providers = self._get_providers()
945
+ self.concentration_providers = {
946
+ str(model).upper(): self._get_concentration_providers(str(model))
947
+ for model in self._gwt_models
948
+ }
949
+ self._riv_aux_configured = False
950
+ self._gwt_fmi_auxvar_addrs = {}
951
+ self._nodeuser_configured = False
952
+ self._nodeuser_zero_based = None
953
+ self._nodesuser = 0
954
+ self._gwt_conc_addrs = {
955
+ str(m).upper(): self.mf6.get_var_address("X", str(m).upper())
956
+ for m in self._gwt_models
957
+ }
958
+ self._gwt_nodeuser_cache = {}
959
+ self._step_prev_stages = None
960
+ self._step_prev_concentrations = {}
961
+
962
+ self.initialize_history()
963
+
964
+ t_start = time.perf_counter()
965
+
966
+ with verbose_logging(bool(verbose), level=logging.DEBUG, logger_name=logger.name):
967
+ if self.coupling_scheme == "modflow":
968
+ modflowapi.run_simulation(
969
+ self.dll_path, self.sim_dir, self.callback, verbose=verbose
970
+ )
971
+ self.elapsed_time = time.perf_counter() - t_start
972
+ logger.info(
973
+ "Coupled simulation completed in %.2f seconds.", self.elapsed_time
974
+ )
975
+ new_stages = self.sw_network.get_node_stages()
976
+ return new_stages
977
+
978
+ return self._run_picard(t_start=t_start)
979
+
980
+ def _run_picard(self, t_start: float) -> dict[int | str, float]:
981
+ self.mf6.initialize()
982
+ solution_ids = self._get_solution_ids_for_run()
983
+
984
+ kper = 0
985
+
986
+ logger.info("Starting coupled Picard iterations...")
987
+
988
+ while self.mf6.get_current_time() < self.mf6.get_end_time():
989
+ dt = self.mf6.get_time_step()
990
+ self.mf6.prepare_time_step(dt)
991
+
992
+ self._snapshot_step_start_state()
993
+ self._stress_period_start(kper)
994
+
995
+ prev_stages = {
996
+ nid: node.stage for nid, node in self.sw_network.nodes.items()
997
+ }
998
+ prev_diffs: dict[int | str, float] = {}
999
+ connected_nodes = {
1000
+ c.node_from for c in self.sw_network.connections.values()
1001
+ } | {c.node_to for c in self.sw_network.connections.values()}
1002
+ node_alphas: dict[int | str, float] = {
1003
+ nid: (1.0 if nid not in connected_nodes else self.relaxation_factor)
1004
+ for nid in self.sw_network.nodes
1005
+ }
1006
+ converged = False
1007
+
1008
+ for coup_iter in range(1, self.max_coupling_iter + 1):
1009
+ new_stages = self._iteration_start(dt)
1010
+
1011
+ # 2. Advance MODFLOW 6 solutions to full internal convergence for this Picard iteration.
1012
+ for sol_idx, sol_id in enumerate(solution_ids):
1013
+ if sol_idx > 0 and self._gwt_models:
1014
+ self._gwt_iteration_start(self._gwt_models, dt)
1015
+ self.mf6.prepare_solve(sol_id)
1016
+ max_inner_iter = 100
1017
+ try:
1018
+ mx_addr = self.mf6.get_var_address("MXITER", f"SLN_{sol_id}")
1019
+ max_inner_iter = int(self.mf6.get_value(mx_addr)[0])
1020
+ except Exception:
1021
+ pass
1022
+
1023
+ has_converged = False
1024
+ inner_it = 0
1025
+ while not has_converged and inner_it < max_inner_iter:
1026
+ inner_it += 1
1027
+ has_converged = bool(self.mf6.solve(sol_id))
1028
+
1029
+ self.mf6.finalize_solve(sol_id)
1030
+ if not has_converged:
1031
+ logger.warning(
1032
+ "MODFLOW 6 solution SLN_%d did not converge at stress period %d, "
1033
+ "Picard iteration %d (%d/%d inner solves).",
1034
+ sol_id,
1035
+ kper + 1,
1036
+ coup_iter,
1037
+ inner_it,
1038
+ max_inner_iter,
1039
+ )
1040
+ if self._gwt_models:
1041
+ self._gwt_iteration_start(self._gwt_models, dt)
1042
+
1043
+ # 5. Apply adaptive under-relaxation and step clamping to node stages
1044
+ max_diff = 0.0
1045
+ max_step = 1.0 # Clamp maximum single-iteration stage step [m]
1046
+ current_diffs: dict[int | str, float] = {}
1047
+
1048
+ for nid, new_s in new_stages.items():
1049
+ if not self.sw_network.nodes[nid].constant_stage:
1050
+ old_s = prev_stages[nid]
1051
+ diff_raw = new_s - old_s
1052
+
1053
+ # Detect numerical flip-flop oscillation (sign flip between iterations)
1054
+ if nid not in connected_nodes:
1055
+ node_alphas[nid] = 1.0
1056
+ elif nid in prev_diffs and (diff_raw * prev_diffs[nid]) < 0:
1057
+ node_alphas[nid] = max(0.05, node_alphas[nid] * 0.5)
1058
+ else:
1059
+ node_alphas[nid] = min(0.8, node_alphas[nid] * 1.2)
1060
+
1061
+ relaxed_s = old_s + node_alphas[nid] * diff_raw
1062
+
1063
+ # Clamp stage step to prevent numerical overshoot
1064
+ clamped_s = max(
1065
+ old_s - max_step, min(old_s + max_step, relaxed_s)
1066
+ )
1067
+
1068
+ self.sw_network.nodes[nid].stage = clamped_s
1069
+ diff = abs(clamped_s - old_s)
1070
+ max_diff = max(max_diff, diff)
1071
+ current_diffs[nid] = diff_raw
1072
+
1073
+ logger.debug(
1074
+ " [Step %d] Coupling Iter %2d: Max Stage Shift = %.6f m",
1075
+ kper + 1,
1076
+ coup_iter,
1077
+ max_diff,
1078
+ )
1079
+
1080
+ prev_diffs = current_diffs
1081
+ prev_stages = {
1082
+ nid: node.stage for nid, node in self.sw_network.nodes.items()
1083
+ }
1084
+
1085
+ if coup_iter >= 2 and max_diff < self.stage_tol:
1086
+ if self.flow_tol is not None:
1087
+ res_map = self.sw_network.calculate_residuals(
1088
+ head=self.head, dt=dt, is_steady_state=self.is_steady_state
1089
+ )
1090
+ max_res = (
1091
+ max(abs(r) for r in res_map.values()) if res_map else 0.0
1092
+ )
1093
+ if max_res < self.flow_tol:
1094
+ converged = True
1095
+ break
1096
+ else:
1097
+ converged = True
1098
+ break
1099
+
1100
+ if not converged:
1101
+ if self.flow_tol is not None:
1102
+ res_map = self.sw_network.calculate_residuals(
1103
+ head=self.head, dt=dt, is_steady_state=self.is_steady_state
1104
+ )
1105
+ max_res = max(abs(r) for r in res_map.values()) if res_map else 0.0
1106
+ flow_info = f", max flow residual = {max_res:.2f} m^3/d > flow_tol {self.flow_tol:.2f} m^3/d"
1107
+ else:
1108
+ flow_info = ""
1109
+ logger.warning(
1110
+ "Coupled Picard simulation did not converge at time step %d "
1111
+ "(current max stage shift = %.6f m > tolerance %.6f m%s). "
1112
+ "Consider increasing max_coupling_iter (currently %d) "
1113
+ "or adjusting relaxation_factor (currently %s).",
1114
+ kper + 1,
1115
+ max_diff,
1116
+ self.stage_tol,
1117
+ flow_info,
1118
+ self.max_coupling_iter,
1119
+ self.relaxation_factor,
1120
+ )
1121
+
1122
+ self._stress_period_end(dt=dt, kper=kper)
1123
+ if self._gwt_models:
1124
+ self._record_gwt_concentration_history(self._gwt_models, (kper, 0))
1125
+
1126
+ self.mf6.finalize_time_step()
1127
+ kper += 1
1128
+
1129
+ # Explicitly finalize MODFLOW 6 simulation to flush binary output files (.hds, .cbc) to disk
1130
+ self.mf6.finalize()
1131
+
1132
+ self.elapsed_time = time.perf_counter() - t_start
1133
+ logger.info("Coupled simulation completed in %.2f seconds.", self.elapsed_time)
1134
+
1135
+ return new_stages
1136
+
1137
+ def initialize_history(self):
1138
+ self.history: dict[str, Any] = {
1139
+ "time": [],
1140
+ "stages": {nid: [] for nid in self.sw_network.nodes},
1141
+ "gw_seepage": {nid: [] for nid in self.sw_network.nodes},
1142
+ "gw_infiltration": {nid: [] for nid in self.sw_network.nodes},
1143
+ "precipitation": {nid: [] for nid in self.sw_network.nodes},
1144
+ "evaporation": {nid: [] for nid in self.sw_network.nodes},
1145
+ "ext_flow": {nid: [] for nid in self.sw_network.nodes},
1146
+ "storage": {nid: [] for nid in self.sw_network.nodes},
1147
+ "flows": {},
1148
+ }
1149
+ self._initial_stages: dict[int | str, float] = {
1150
+ nid: float(node.stage) for nid, node in self.sw_network.nodes.items()
1151
+ }
1152
+ if getattr(self, "_gwt_models", None):
1153
+ self.history["concentrations"] = {
1154
+ str(m).upper(): {nid: [] for nid in self.sw_network.nodes}
1155
+ for m in self._gwt_models
1156
+ }
1157
+ self._assign_connection_history_keys(self.history["flows"], create_missing=True)
1158
+
1159
+ self.elapsed_time: float = 0.0
1160
+ self._last_sp_start_kper: int | None = None
1161
+ self._last_stress_period_end_step: tuple[int, int] | None = None
1162
+ self._last_gwt_sp_end_step: dict[str, tuple[int, int]] = {}
1163
+
1164
+ def _assign_connection_history_keys(
1165
+ self, flow_store: dict[str, list[float]], create_missing: bool
1166
+ ) -> None:
1167
+ for conn in self.sw_network.connections.values():
1168
+ description = f"{conn.node_from}->{conn.node_to}"
1169
+ raw_name = getattr(conn, "name", None)
1170
+ key = str(raw_name).strip() if raw_name is not None else ""
1171
+ if not key:
1172
+ key = description
1173
+ conn.name = description
1174
+ conn._history_key = key
1175
+ if create_missing and key not in flow_store:
1176
+ flow_store[key] = []
1177
+
1178
+ def history_to_dataframes(
1179
+ self,
1180
+ start: str | None = None,
1181
+ time_unit: str = "D",
1182
+ incluse_derived: bool = True,
1183
+ ) -> dict[str, pd.DataFrame]:
1184
+ """
1185
+ Convert coupling history to pandas DataFrames keyed like ``self.history``.
1186
+
1187
+ Returns
1188
+ -------
1189
+ dict[str, pandas.DataFrame]
1190
+ Dictionary with keys matching ``self.history`` except ``"time"``.
1191
+ Each DataFrame uses simulation time as index and node/connection ids as columns.
1192
+ start : str | None
1193
+ Optional start time for the simulation. If provided, the index of the DataFrames will be converted to timestamps starting from this time.
1194
+ time_unit : str
1195
+ Time unit for the simulation time index. Default is "D" (days).
1196
+ incluse_derived : bool
1197
+ Whether to include derived node-level ``"storage"`` and ``"net_residual"``
1198
+ tables in the output. Default is True.
1199
+ """
1200
+ times = list(self.history.get("time", []))
1201
+ n_steps = len(times)
1202
+ table_keys = [
1203
+ "stages",
1204
+ "gw_seepage",
1205
+ "gw_infiltration",
1206
+ "precipitation",
1207
+ "evaporation",
1208
+ "ext_flow",
1209
+ "flows",
1210
+ ]
1211
+ idx = pd.Index([float(t) for t in times], name="time")
1212
+ if start is not None:
1213
+ idx = pd.Timestamp(start) + pd.to_timedelta(idx, unit=time_unit)
1214
+ out: dict[str, pd.DataFrame] = {}
1215
+
1216
+ for table_key in table_keys:
1217
+ table_data = self.history.get(table_key, {})
1218
+ if not isinstance(table_data, dict):
1219
+ raise RuntimeError(
1220
+ f"History entry '{table_key}' must be a dictionary of series."
1221
+ )
1222
+
1223
+ ordered_columns = list(table_data.keys())
1224
+ frame_data: dict[Any, list[float]] = {}
1225
+ for col_key in ordered_columns:
1226
+ series = table_data[col_key]
1227
+ if len(series) != n_steps:
1228
+ raise RuntimeError(
1229
+ f"History series '{table_key}.{col_key}' has length {len(series)}; expected {n_steps}."
1230
+ )
1231
+ frame_data[col_key] = [float(v) for v in series]
1232
+
1233
+ out[table_key] = pd.DataFrame(frame_data, index=idx)
1234
+
1235
+ if incluse_derived:
1236
+ storage_data: dict[int | str, list[float]] = {}
1237
+ net_residual_data: dict[int | str, list[float]] = {}
1238
+ for nid in self.sw_network.nodes:
1239
+ wb = self.get_water_balance(nid, dates=idx)
1240
+ storage_data[nid] = [float(v) for v in wb["storage"].tolist()]
1241
+ net_residual_data[nid] = [
1242
+ float(v) for v in wb["net_residual"].tolist()
1243
+ ]
1244
+ out["storage"] = pd.DataFrame(storage_data, index=idx)
1245
+ out["net_residual"] = pd.DataFrame(net_residual_data, index=idx)
1246
+
1247
+ return out
1248
+
1249
+ def _set_history_from_dataframes(
1250
+ self, history_frames: dict[str, pd.DataFrame]
1251
+ ) -> None:
1252
+ required_keys = [
1253
+ "stages",
1254
+ "gw_seepage",
1255
+ "gw_infiltration",
1256
+ "precipitation",
1257
+ "evaporation",
1258
+ "ext_flow",
1259
+ "flows",
1260
+ ]
1261
+ missing = set(required_keys).difference(history_frames.keys())
1262
+ if missing:
1263
+ raise ValueError(
1264
+ f"History DataFrame dictionary is missing required keys: {sorted(missing)}"
1265
+ )
1266
+
1267
+ table_frames: dict[str, pd.DataFrame] = {}
1268
+ for key in required_keys:
1269
+ frame = history_frames[key]
1270
+ if not isinstance(frame, pd.DataFrame):
1271
+ raise ValueError(f"History entry '{key}' must be a pandas DataFrame.")
1272
+ if frame.index.name != "time":
1273
+ frame = frame.copy()
1274
+ frame.index.name = "time"
1275
+ table_frames[key] = frame
1276
+
1277
+ base_times = table_frames[required_keys[0]].index.tolist()
1278
+ for key in required_keys[1:]:
1279
+ times = table_frames[key].index.tolist()
1280
+ if times != base_times:
1281
+ raise ValueError(
1282
+ f"History DataFrame '{key}' has a different time index from '{required_keys[0]}'."
1283
+ )
1284
+
1285
+ times_float = [float(t) for t in base_times]
1286
+ rebuilt: dict[str, Any] = {"time": times_float}
1287
+ for key in required_keys:
1288
+ frame = table_frames[key]
1289
+ rebuilt[key] = {
1290
+ col: frame[col].astype(float).tolist() for col in frame.columns.tolist()
1291
+ }
1292
+
1293
+ self.history = rebuilt
1294
+ self._assign_connection_history_keys(
1295
+ self.history["flows"], create_missing=False
1296
+ )
1297
+
1298
+ def _to_jsonable(self, value: Any) -> Any:
1299
+ if value is None or isinstance(value, (bool, int, float, str)):
1300
+ return value
1301
+ if isinstance(value, Path):
1302
+ return {"__type__": "path", "value": str(value)}
1303
+ if isinstance(value, np.ndarray):
1304
+ return {"__type__": "ndarray", "value": value.tolist()}
1305
+ if isinstance(value, np.generic):
1306
+ return value.item()
1307
+ if isinstance(value, dict):
1308
+ return {
1309
+ "__type__": "dict",
1310
+ "items": [
1311
+ [self._to_jsonable(k), self._to_jsonable(v)]
1312
+ for k, v in value.items()
1313
+ ],
1314
+ }
1315
+ if isinstance(value, list):
1316
+ return {"__type__": "list", "items": [self._to_jsonable(v) for v in value]}
1317
+ if isinstance(value, tuple):
1318
+ return {
1319
+ "__type__": "tuple",
1320
+ "items": [self._to_jsonable(v) for v in value],
1321
+ }
1322
+ if isinstance(value, set):
1323
+ return {"__type__": "set", "items": [self._to_jsonable(v) for v in value]}
1324
+ if hasattr(value, "__dict__"):
1325
+ module = value.__class__.__module__
1326
+ if not module.startswith("swmod.network"):
1327
+ raise TypeError(
1328
+ f"Unsupported object type for JSON serialization: {value.__class__.__name__} from module {module}"
1329
+ )
1330
+ return {
1331
+ "__type__": "object",
1332
+ "module": module,
1333
+ "class": value.__class__.__name__,
1334
+ "attributes": {
1335
+ key: self._to_jsonable(val)
1336
+ for key, val in vars(value).items()
1337
+ if not str(key).startswith("_")
1338
+ },
1339
+ }
1340
+ raise TypeError(
1341
+ f"Unsupported value type for JSON serialization: {type(value).__name__}"
1342
+ )
1343
+
1344
+ def _from_jsonable(self, value: Any) -> Any:
1345
+ if not isinstance(value, dict) or "__type__" not in value:
1346
+ return value
1347
+ value_type = value["__type__"]
1348
+
1349
+ if value_type == "path":
1350
+ return Path(value["value"])
1351
+ if value_type == "ndarray":
1352
+ return np.asarray(value["value"])
1353
+ if value_type == "dict":
1354
+ return {
1355
+ self._from_jsonable(item[0]): self._from_jsonable(item[1])
1356
+ for item in value["items"]
1357
+ }
1358
+ if value_type == "list":
1359
+ return [self._from_jsonable(item) for item in value["items"]]
1360
+ if value_type == "tuple":
1361
+ return tuple(self._from_jsonable(item) for item in value["items"])
1362
+ if value_type == "set":
1363
+ return {self._from_jsonable(item) for item in value["items"]}
1364
+ if value_type == "object":
1365
+ module = str(value.get("module", ""))
1366
+ class_name = str(value.get("class", ""))
1367
+ if not module.startswith("swmod.network"):
1368
+ raise ValueError(
1369
+ f"Unsupported serialized object module '{module}' in sw_network.json."
1370
+ )
1371
+ network_module = __import__(module, fromlist=[class_name])
1372
+ cls_obj = getattr(network_module, class_name, None)
1373
+ if cls_obj is None:
1374
+ raise ValueError(
1375
+ f"Unknown serialized class '{class_name}' in module '{module}'."
1376
+ )
1377
+ obj = cls_obj.__new__(cls_obj)
1378
+ attrs = {
1379
+ key: self._from_jsonable(val)
1380
+ for key, val in value.get("attributes", {}).items()
1381
+ }
1382
+ obj.__dict__.update(attrs)
1383
+ return obj
1384
+ raise ValueError(f"Unsupported serialized value type '{value_type}'.")
1385
+
1386
+ def save_results(self, directory: str | Path) -> None:
1387
+ """
1388
+ Save model structure and coupling history to disk for postprocessing.
1389
+
1390
+ Parameters
1391
+ ----------
1392
+ directory : str or Path
1393
+ Output directory for persisted model and history files.
1394
+ """
1395
+ out_dir = Path(directory)
1396
+ out_dir.mkdir(parents=True, exist_ok=True)
1397
+
1398
+ dataframes = self.history_to_dataframes()
1399
+ history_db_path = out_dir / "history.sqlite"
1400
+ table_names = [
1401
+ "stages",
1402
+ "gw_seepage",
1403
+ "gw_infiltration",
1404
+ "precipitation",
1405
+ "evaporation",
1406
+ "ext_flow",
1407
+ "flows",
1408
+ ]
1409
+ with sqlite3.connect(history_db_path) as db:
1410
+ for table_name in table_names:
1411
+ dataframes[table_name].to_sql(
1412
+ table_name, db, if_exists="replace", index=True, index_label="time"
1413
+ )
1414
+ db.execute(
1415
+ f"CREATE INDEX IF NOT EXISTS idx_{table_name}_time ON {table_name} (time)"
1416
+ )
1417
+
1418
+ sw_network_payload = self._to_jsonable(self.sw_network)
1419
+ with (out_dir / "sw_network.json").open("w", encoding="utf-8") as f:
1420
+ json.dump(sw_network_payload, f, indent=2)
1421
+
1422
+ metadata = {
1423
+ "schema_version": 2,
1424
+ "elapsed_time": float(getattr(self, "elapsed_time", 0.0)),
1425
+ "dll_path": str(getattr(self, "dll_path", "")),
1426
+ "sim_dir": str(getattr(self, "sim_dir", "")),
1427
+ "gwf_model_name": str(getattr(self, "gwf_model_name", "GWF_1")),
1428
+ "riv_pack_name": str(getattr(self, "riv_pack_name", "RIV_1")),
1429
+ "relaxation_factor": float(getattr(self, "relaxation_factor", 0.3)),
1430
+ "max_coupling_iter": int(getattr(self, "max_coupling_iter", 50)),
1431
+ "stage_tol": float(getattr(self, "stage_tol", 1e-3)),
1432
+ "flow_tol": (
1433
+ None
1434
+ if getattr(self, "flow_tol", None) is None
1435
+ else float(self.flow_tol)
1436
+ ),
1437
+ "coupling_scheme": str(getattr(self, "coupling_scheme", "modflow")),
1438
+ "max_stage_step": (
1439
+ None
1440
+ if getattr(self, "max_stage_step", 0.1) is None
1441
+ else float(getattr(self, "max_stage_step", 0.1))
1442
+ ),
1443
+ "verbose": bool(getattr(self, "verbose", False)),
1444
+ "allow_unsafe_gwt_run": bool(getattr(self, "allow_unsafe_gwt_run", False)),
1445
+ "gwt_models": [str(m) for m in getattr(self, "_gwt_models", [])],
1446
+ }
1447
+ with (out_dir / "metadata.json").open("w", encoding="utf-8") as f:
1448
+ json.dump(metadata, f, indent=2)
1449
+
1450
+ @classmethod
1451
+ def load_results(cls, directory: str | Path) -> "CoupledSimulation":
1452
+ """
1453
+ Load a saved coupling model and history from disk.
1454
+
1455
+ Parameters
1456
+ ----------
1457
+ directory : str or Path
1458
+ Directory created by :meth:`save_results`.
1459
+ """
1460
+ in_dir = Path(directory)
1461
+ metadata_path = in_dir / "metadata.json"
1462
+ network_path = in_dir / "sw_network.json"
1463
+ history_db_path = in_dir / "history.sqlite"
1464
+
1465
+ for p in [metadata_path, network_path, history_db_path]:
1466
+ if not p.exists():
1467
+ raise FileNotFoundError(
1468
+ f"Saved coupling results are incomplete. Missing file: {p}"
1469
+ )
1470
+
1471
+ metadata = json.loads(metadata_path.read_text(encoding="utf-8"))
1472
+ sw_network_payload = json.loads(network_path.read_text(encoding="utf-8"))
1473
+
1474
+ decoder = cls.__new__(cls)
1475
+ sw_network = decoder._from_jsonable(sw_network_payload)
1476
+ if not isinstance(sw_network, SurfaceWaterNetwork):
1477
+ raise ValueError(
1478
+ "sw_network.json does not contain a valid SurfaceWaterNetwork object."
1479
+ )
1480
+
1481
+ table_names = [
1482
+ "stages",
1483
+ "gw_seepage",
1484
+ "gw_infiltration",
1485
+ "precipitation",
1486
+ "evaporation",
1487
+ "ext_flow",
1488
+ "flows",
1489
+ ]
1490
+ history_frames: dict[str, pd.DataFrame] = {}
1491
+ with sqlite3.connect(history_db_path) as db:
1492
+ for table_name in table_names:
1493
+ df_table = pd.read_sql_query(
1494
+ f"SELECT * FROM {table_name} ORDER BY time", db
1495
+ )
1496
+ if "time" not in df_table.columns:
1497
+ raise ValueError(
1498
+ f"History table '{table_name}' is missing required 'time' column."
1499
+ )
1500
+ df_table = df_table.set_index("time")
1501
+ df_table.index.name = "time"
1502
+ history_frames[table_name] = df_table
1503
+
1504
+ obj = cls.__new__(cls)
1505
+ obj.dll_path = Path(metadata.get("dll_path") or ".bin/libmf6.dll")
1506
+ obj.sim_dir = Path(metadata.get("sim_dir") or "sim_output")
1507
+ obj.sw_network = sw_network
1508
+ obj.gwf_model_name = str(metadata.get("gwf_model_name", "GWF_1")).upper()
1509
+ obj._gwf_model_name_user_specified = True
1510
+ obj.riv_pack_name = str(metadata.get("riv_pack_name", "RIV_1")).upper()
1511
+ obj.relaxation_factor = float(metadata.get("relaxation_factor", 0.3))
1512
+ obj.max_coupling_iter = int(metadata.get("max_coupling_iter", 50))
1513
+ obj.stage_tol = float(metadata.get("stage_tol", 1e-3))
1514
+ obj.flow_tol = metadata.get("flow_tol")
1515
+ obj.coupling_scheme = str(metadata.get("coupling_scheme", "modflow"))
1516
+ raw_max_step = metadata.get("max_stage_step", 0.1)
1517
+ obj.max_stage_step = None if raw_max_step is None else float(raw_max_step)
1518
+ obj.verbose = bool(metadata.get("verbose", False))
1519
+ obj.allow_unsafe_gwt_run = bool(metadata.get("allow_unsafe_gwt_run", False))
1520
+
1521
+ obj.mf6 = None
1522
+ obj.head_addr = None
1523
+ obj.stage_addr = None
1524
+ obj.rbot_addr = None
1525
+ obj.head = None
1526
+ obj.providers = []
1527
+ obj.concentration_providers = {}
1528
+ obj.ext_flow_series = None
1529
+ obj.precipitation_series = None
1530
+ obj.evaporation_series = None
1531
+ obj.is_steady_state = False
1532
+ obj._gwt_models = [str(m).upper() for m in metadata.get("gwt_models", [])]
1533
+ obj._riv_auxvar_addr = None
1534
+ obj._gwt_fmi_auxvar_addrs = {}
1535
+ obj._riv_conc_aux_indices = {}
1536
+ obj._riv_naux = 0
1537
+ obj._warned_aux_layout_assumption = False
1538
+ obj._riv_aux_configured = False
1539
+ obj._nodeuser_configured = False
1540
+ obj._nodeuser_zero_based = None
1541
+ obj._nodesuser = 0
1542
+
1543
+ obj._set_history_from_dataframes(history_frames)
1544
+ obj.elapsed_time = float(metadata.get("elapsed_time", 0.0))
1545
+ obj._last_sp_start_kper = None
1546
+ obj._last_stress_period_end_step = None
1547
+ return obj
1548
+
1549
+ def _get_callback_model_names(self, sim) -> list[str]:
1550
+ """Return uppercase model names belonging to the active modflowapi callback solution."""
1551
+ models = getattr(sim, "models", None)
1552
+ if not models:
1553
+ return []
1554
+ if isinstance(models, dict):
1555
+ return [str(k).upper() for k in models.keys()]
1556
+ return [str(getattr(m, "name", m)).upper() for m in models]
1557
+
1558
+ def _is_gwf_solution_callback(self, sim) -> bool:
1559
+ """Return True when the modflowapi callback belongs to the coupled GWF solution."""
1560
+ model_names = self._get_callback_model_names(sim)
1561
+ if not model_names:
1562
+ return True
1563
+ return self.gwf_model_name.upper() in model_names
1564
+
1565
+ def _get_gwt_models_in_callback(self, sim) -> list[str]:
1566
+ """Return uppercase GWT model names belonging to the active modflowapi callback solution."""
1567
+ if not self._gwt_models:
1568
+ return []
1569
+ model_names = set(self._get_callback_model_names(sim))
1570
+ return [str(m).upper() for m in self._gwt_models if str(m).upper() in model_names]
1571
+
1572
+ def _snapshot_step_start_state(self) -> None:
1573
+ """Snapshot start-of-timestep stages and concentrations for implicit storage mixing."""
1574
+ self._step_prev_stages = {
1575
+ nid: float(node.stage) for nid, node in self.sw_network.nodes.items()
1576
+ }
1577
+ for node in self.sw_network.nodes.values():
1578
+ node.prev_stage = float(node.stage)
1579
+ self._step_prev_concentrations = {
1580
+ str(m).upper(): {
1581
+ nid: self._get_node_concentration(node, str(m))
1582
+ for nid, node in self.sw_network.nodes.items()
1583
+ }
1584
+ for m in self._gwt_models
1585
+ }
1586
+ self._iter_prev_stage_deltas = {}
1587
+ self._iter_stage_alphas = {}
1588
+ self._last_iter_stage_damped = False
1589
+ self._last_iter_max_stage_change = 0.0
1590
+
1591
+ def _get_model_user_array(self, model_name: str, var_addr: str) -> np.ndarray:
1592
+ """Read a model's X array and expand reduced-node indexing via DIS/NODEUSER if needed."""
1593
+ model_key = str(model_name).upper()
1594
+ vec = np.asarray(self.mf6.get_value(var_addr), dtype=float)
1595
+ if model_key not in self._gwt_nodeuser_cache:
1596
+ nodeuser_zb: np.ndarray | None = None
1597
+ n_user = len(vec)
1598
+ for dis_name in ("DIS", "DISV", "DISU"):
1599
+ try:
1600
+ nu_addr = self.mf6.get_var_address("NODESUSER", model_key, dis_name)
1601
+ nu_val = self.mf6.get_value(nu_addr)
1602
+ if len(nu_val) == 0:
1603
+ continue
1604
+ cand_n = int(nu_val[0])
1605
+ if cand_n <= len(vec):
1606
+ break
1607
+ map_addr = self.mf6.get_var_address("NODEUSER", model_key, dis_name)
1608
+ map_1b = np.asarray(self.mf6.get_value(map_addr), dtype=int)
1609
+ if len(map_1b) == len(vec):
1610
+ nodeuser_zb = map_1b - 1
1611
+ n_user = cand_n
1612
+ break
1613
+ except Exception:
1614
+ continue
1615
+ self._gwt_nodeuser_cache[model_key] = (nodeuser_zb, n_user)
1616
+
1617
+ nodeuser_zb, n_user = self._gwt_nodeuser_cache[model_key]
1618
+ if nodeuser_zb is not None:
1619
+ full = np.full(n_user, np.nan, dtype=float)
1620
+ full[nodeuser_zb] = vec
1621
+ return full
1622
+ return vec
1623
+
1624
+ def _gwt_iteration_start(self, gwt_models: list[str], dt: float) -> None:
1625
+ """
1626
+ Update SW node concentrations from current GWT groundwater concentrations and
1627
+ push the updated concentrations into MODFLOW 6 RIV AUXVAR before solving GWT.
1628
+ """
1629
+ if not gwt_models:
1630
+ return
1631
+ for gwt_model in gwt_models:
1632
+ m_key = str(gwt_model).upper()
1633
+ conc_addr = self._gwt_conc_addrs.get(m_key)
1634
+ if conc_addr is None:
1635
+ conc_addr = self.mf6.get_var_address("X", m_key)
1636
+ self._gwt_conc_addrs[m_key] = conc_addr
1637
+ gw_conc = self._get_model_user_array(m_key, conc_addr)
1638
+ prev_concs = self._step_prev_concentrations.get(m_key)
1639
+ self.sw_network.solve_concentrations(
1640
+ gw_conc=gw_conc,
1641
+ head=self.head,
1642
+ dt=dt,
1643
+ is_steady_state=self.is_steady_state,
1644
+ prev_stages=self._step_prev_stages,
1645
+ prev_concentrations=prev_concs,
1646
+ gwt_model_name=m_key if len(self._gwt_models) > 1 else None,
1647
+ )
1648
+ self._update_riv_concentrations(self.concentration_providers)
1649
+
1650
+ def _check_mf6_convergence(self, sim) -> None:
1651
+ """Emit a logger.warning if any MODFLOW 6 solution in ``sim`` failed to converge."""
1652
+ solutions = getattr(sim, "solutions", None)
1653
+ if not solutions or self.mf6 is None:
1654
+ return
1655
+ kper = getattr(sim, "kper", None)
1656
+ kstp = getattr(sim, "kstp", None)
1657
+ sp_num = int(kper) + 1 if kper is not None else len(self.history.get("time", [])) + 1
1658
+ kstp_num = int(kstp) + 1 if kstp is not None else 1
1659
+ try:
1660
+ curr_time = float(self.mf6.get_current_time())
1661
+ except Exception:
1662
+ curr_time = float("nan")
1663
+ n_outer = getattr(sim, "iteration", None)
1664
+ n_outer_int = int(n_outer) + 1 if n_outer is not None else None
1665
+
1666
+ for sol_id, slnobj in sorted(solutions.items()):
1667
+ sln_name = f"SLN_{sol_id}"
1668
+ try:
1669
+ icnvg_addr = self.mf6.get_var_address("ICNVG", sln_name)
1670
+ icnvg_val = self.mf6.get_value(icnvg_addr)
1671
+ converged = bool(int(icnvg_val[0]) != 0) if len(icnvg_val) > 0 else True
1672
+ except Exception:
1673
+ continue
1674
+ if not converged:
1675
+ mxiter = getattr(slnobj, "mxiter", None)
1676
+ iter_info = (
1677
+ f", {n_outer_int}/{mxiter} outer iterations"
1678
+ if n_outer_int is not None and mxiter is not None
1679
+ else ""
1680
+ )
1681
+ logger.warning(
1682
+ "MODFLOW 6 solution %s did not converge at stress period %d, "
1683
+ "time step %d (t=%.2f d%s).",
1684
+ sln_name,
1685
+ sp_num,
1686
+ kstp_num,
1687
+ curr_time,
1688
+ iter_info,
1689
+ )
1690
+
1691
+ def callback(self, sim, callback_step):
1692
+ if callback_step == modflowapi.Callbacks.stress_period_start:
1693
+ # make sure the callback is not called multiple times, for each solution group
1694
+ if getattr(self, "_last_sp_start_kper", None) != sim.kper:
1695
+ self._last_sp_start_kper = sim.kper
1696
+ self._stress_period_start(sim.kper)
1697
+ elif callback_step == modflowapi.Callbacks.timestep_start:
1698
+ if self._is_gwf_solution_callback(sim):
1699
+ self._snapshot_step_start_state()
1700
+ elif callback_step == modflowapi.Callbacks.iteration_start:
1701
+ if self._is_gwf_solution_callback(sim):
1702
+ self._iteration_start(sim.delt)
1703
+ if hasattr(sim, "allow_convergence"):
1704
+ stage_tol = getattr(self, "stage_tol", None)
1705
+ stage_converged = (
1706
+ stage_tol is None
1707
+ or float(stage_tol) <= 0.0
1708
+ or self._last_iter_max_stage_change <= float(stage_tol)
1709
+ )
1710
+ sim.allow_convergence = (
1711
+ not self._last_iter_stage_damped and stage_converged
1712
+ )
1713
+ else:
1714
+ gwt_in_cb = self._get_gwt_models_in_callback(sim)
1715
+ if gwt_in_cb:
1716
+ self._gwt_iteration_start(gwt_in_cb, sim.delt)
1717
+ elif callback_step == modflowapi.Callbacks.timestep_end:
1718
+ self._check_mf6_convergence(sim)
1719
+ gwt_in_cb = self._get_gwt_models_in_callback(sim)
1720
+ if gwt_in_cb:
1721
+ # Re-evaluate final SW concentrations using converged GWT solution
1722
+ self._gwt_iteration_start(gwt_in_cb, sim.delt)
1723
+ elif callback_step == modflowapi.Callbacks.stress_period_end:
1724
+ step_key = (getattr(sim, "kper", None), getattr(sim, "kstp", None))
1725
+ if self._is_gwf_solution_callback(sim):
1726
+ if step_key != getattr(self, "_last_stress_period_end_step", None):
1727
+ self._last_stress_period_end_step = step_key
1728
+ self._stress_period_end(
1729
+ update_prev_stage=not bool(self._gwt_models),
1730
+ dt=getattr(sim, "delt", None),
1731
+ kper=getattr(sim, "kper", None),
1732
+ )
1733
+ else:
1734
+ gwt_in_cb = self._get_gwt_models_in_callback(sim)
1735
+ if gwt_in_cb:
1736
+ self._record_gwt_concentration_history(gwt_in_cb, step_key)
1737
+
1738
+ def _stress_period_start(self, kper):
1739
+ if not self._riv_aux_configured:
1740
+ self._configure_riv_concentration_assignment()
1741
+
1742
+ # Determine if current time step / stress period is steady-state
1743
+ self.is_steady_state = False
1744
+ iss_addr = self.mf6.get_var_address("ISS", self.gwf_model_name)
1745
+ iss_val = self.mf6.get_value(iss_addr)
1746
+ if len(iss_val) > 0 and iss_val[0] == 1:
1747
+ self.is_steady_state = True
1748
+
1749
+ # Update time-varying external point inflows if provided [m^3/day]
1750
+ if self.ext_flow_series:
1751
+ if isinstance(self.ext_flow_series, dict):
1752
+ for nid, series in self.ext_flow_series.items():
1753
+ if nid in self.sw_network.nodes and kper < len(series):
1754
+ self.sw_network.nodes[nid].ext_flow = float(series[kper])
1755
+ elif isinstance(
1756
+ self.ext_flow_series, (list, tuple, np.ndarray)
1757
+ ) and kper < len(self.ext_flow_series):
1758
+ val = float(self.ext_flow_series[kper])
1759
+ for node in self.sw_network.nodes.values():
1760
+ node.ext_flow = val
1761
+
1762
+ # Update time-varying open-water precipitation if provided [m/day]
1763
+ if self.precipitation_series:
1764
+ if isinstance(self.precipitation_series, dict):
1765
+ for nid, series in self.precipitation_series.items():
1766
+ if nid in self.sw_network.nodes and kper < len(series):
1767
+ self.sw_network.nodes[nid].precipitation = float(series[kper])
1768
+ elif isinstance(
1769
+ self.precipitation_series, (list, tuple, np.ndarray)
1770
+ ) and kper < len(self.precipitation_series):
1771
+ val = float(self.precipitation_series[kper])
1772
+ for node in self.sw_network.nodes.values():
1773
+ node.precipitation = val
1774
+
1775
+ # Update time-varying open-water evaporation if provided [m/day]
1776
+ if self.evaporation_series:
1777
+ if isinstance(self.evaporation_series, dict):
1778
+ for nid, series in self.evaporation_series.items():
1779
+ if nid in self.sw_network.nodes and kper < len(series):
1780
+ self.sw_network.nodes[nid].evaporation = float(series[kper])
1781
+ elif isinstance(
1782
+ self.evaporation_series, (list, tuple, np.ndarray)
1783
+ ) and kper < len(self.evaporation_series):
1784
+ val = float(self.evaporation_series[kper])
1785
+ for node in self.sw_network.nodes.values():
1786
+ node.evaporation = val
1787
+
1788
+ # Update time-varying connection control elevations (e.g. seasonal weir crests / culvert inverts / pump thresholds)
1789
+ for conn in self.sw_network.connections.values():
1790
+ for attr in (
1791
+ "crest_elevation",
1792
+ "invert_elevation",
1793
+ "min_stage_from",
1794
+ "max_stage_from",
1795
+ "min_stage_to",
1796
+ "max_stage_to",
1797
+ ):
1798
+ series = getattr(conn, f"{attr}_series", None)
1799
+ if series is not None and kper < len(series):
1800
+ setattr(conn, attr, float(series[kper]))
1801
+
1802
+ def _configure_reduced_node_mapping(self, heads_len: int) -> None:
1803
+ """
1804
+ Detect whether MODFLOW 6 uses reduced node indexing (when idomain <= 0 cells exist)
1805
+ and cache the 0-based NODEUSER mapping back to full user-grid cell indices.
1806
+ """
1807
+ self._nodeuser_configured = True
1808
+ self._nodeuser_zero_based = None
1809
+ self._nodesuser = heads_len
1810
+
1811
+ for dis_name in ("DIS", "DISV", "DISU"):
1812
+ try:
1813
+ nodesuser_addr = self.mf6.get_var_address(
1814
+ "NODESUSER", self.gwf_model_name, dis_name
1815
+ )
1816
+ nodesuser_val = self.mf6.get_value(nodesuser_addr)
1817
+ if len(nodesuser_val) == 0:
1818
+ continue
1819
+ n_user = int(nodesuser_val[0])
1820
+ if n_user <= heads_len:
1821
+ return
1822
+
1823
+ nodeuser_addr = self.mf6.get_var_address(
1824
+ "NODEUSER", self.gwf_model_name, dis_name
1825
+ )
1826
+ nodeuser_1based = np.asarray(
1827
+ self.mf6.get_value(nodeuser_addr), dtype=int
1828
+ )
1829
+ if len(nodeuser_1based) == heads_len:
1830
+ self._nodeuser_zero_based = nodeuser_1based - 1
1831
+ self._nodesuser = n_user
1832
+ return
1833
+ except Exception:
1834
+ continue
1835
+ self._nodeuser_zero_based = None
1836
+ self._nodesuser = heads_len
1837
+
1838
+ def _get_user_heads(self) -> np.ndarray:
1839
+ """
1840
+ Return groundwater heads indexed by 0-based user-grid node index.
1841
+ When MODFLOW 6 omits inactive/pass-through cells (idomain <= 0), expands the
1842
+ reduced X vector back to user-node indexing via DIS/NODEUSER.
1843
+ """
1844
+ heads_vec = np.asarray(self.mf6.get_value(self.head_addr), dtype=float)
1845
+ if not self._nodeuser_configured:
1846
+ self._configure_reduced_node_mapping(len(heads_vec))
1847
+
1848
+ if self._nodeuser_zero_based is not None:
1849
+ full_heads = np.full(self._nodesuser, np.nan, dtype=float)
1850
+ full_heads[self._nodeuser_zero_based] = heads_vec
1851
+ return full_heads
1852
+ return heads_vec
1853
+
1854
+ def _iteration_start(self, dt):
1855
+ # Query current groundwater heads from MODFLOW API memory
1856
+ self.head = self._get_user_heads()
1857
+
1858
+ prev_iter_stages = {
1859
+ nid: float(node.stage) for nid, node in self.sw_network.nodes.items()
1860
+ }
1861
+
1862
+ # Solve surface water network equilibrium using current GW heads
1863
+ solve_kwargs: dict[str, Any] = {
1864
+ "head": self.head,
1865
+ "dt": dt,
1866
+ "is_steady_state": self.is_steady_state,
1867
+ "warn_on_nonconvergence": False,
1868
+ }
1869
+ if self.flow_tol is not None:
1870
+ solve_kwargs["flow_tol"] = self.flow_tol
1871
+ new_stages = self.sw_network.solve(**solve_kwargs)
1872
+
1873
+ # In MODFLOW callback coupling, limit per-iteration stage jumps (and damp
1874
+ # sign-flip oscillations) so intermediate GWF Newton overshoots across RIV
1875
+ # bed bottoms cannot trigger positive-feedback blowups, while remaining
1876
+ # unrelaxed (zero lag) once |delta_stage| <= max_stage_step.
1877
+ self._last_iter_stage_damped = False
1878
+ max_step = getattr(self, "max_stage_step", None)
1879
+ if getattr(self, "coupling_scheme", "modflow") == "modflow" and max_step is not None:
1880
+ prev_deltas = getattr(self, "_iter_prev_stage_deltas", {})
1881
+ alphas = getattr(self, "_iter_stage_alphas", {})
1882
+ for nid, node in self.sw_network.nodes.items():
1883
+ if node.constant_stage:
1884
+ continue
1885
+ old_s = prev_iter_stages[nid]
1886
+ raw_delta = float(node.stage) - old_s
1887
+ alpha = alphas.get(nid, 1.0)
1888
+ if (
1889
+ nid in prev_deltas
1890
+ and abs(raw_delta) > 1e-4
1891
+ and (raw_delta * prev_deltas[nid]) < 0.0
1892
+ ):
1893
+ alpha = max(0.25, alpha * 0.5)
1894
+ else:
1895
+ alpha = min(1.0, alpha * 1.25)
1896
+ alphas[nid] = alpha
1897
+ prev_deltas[nid] = raw_delta
1898
+
1899
+ delta = alpha * raw_delta
1900
+ if delta > max_step:
1901
+ delta = max_step
1902
+ elif delta < -max_step:
1903
+ delta = -max_step
1904
+
1905
+ applied_s = old_s + delta
1906
+ bed = node.get_bed_elevation()
1907
+ if bed is not None and applied_s < bed:
1908
+ applied_s = float(bed)
1909
+ if abs(applied_s - float(node.stage)) > 1e-6:
1910
+ self._last_iter_stage_damped = True
1911
+ node.stage = applied_s
1912
+ new_stages[nid] = applied_s
1913
+ self._iter_prev_stage_deltas = prev_deltas
1914
+ self._iter_stage_alphas = alphas
1915
+
1916
+ # Track maximum applied stage shift across all non-constant SW nodes
1917
+ self._last_iter_max_stage_change = max(
1918
+ (
1919
+ abs(float(node.stage) - prev_iter_stages[nid])
1920
+ for nid, node in self.sw_network.nodes.items()
1921
+ if not node.constant_stage
1922
+ ),
1923
+ default=0.0,
1924
+ )
1925
+
1926
+ # Update RIV stages in MODFLOW 6 memory pointer
1927
+ riv_stages = self.mf6.get_value(self.stage_addr)
1928
+ for idx in range(len(riv_stages)):
1929
+ if idx < len(self.providers):
1930
+ riv_stages[idx] = self.providers[idx]()
1931
+ if getattr(self, "rbot_addr", None) is not None:
1932
+ try:
1933
+ riv_rbots = self.mf6.get_value(self.rbot_addr)
1934
+ if len(riv_rbots) == len(riv_stages):
1935
+ riv_stages = np.maximum(riv_stages, riv_rbots)
1936
+ except Exception:
1937
+ pass
1938
+ self.mf6.set_value(self.stage_addr, riv_stages)
1939
+ self._update_riv_concentrations(self.concentration_providers)
1940
+
1941
+ return new_stages
1942
+
1943
+ def _stress_period_end(
1944
+ self,
1945
+ update_prev_stage: bool = True,
1946
+ dt: float | None = None,
1947
+ kper: int | None = None,
1948
+ ):
1949
+ # Record time-series output history and update prev_stage
1950
+ # Store cumulative model time (days), not 1-based timestep number.
1951
+ prev_time = float(self.history["time"][-1]) if self.history["time"] else 0.0
1952
+ curr_time = float(self.mf6.get_current_time())
1953
+ step_dt = float(dt) if (dt is not None and dt > 0.0) else (curr_time - prev_time)
1954
+ if step_dt <= 0.0:
1955
+ step_dt = 1.0
1956
+ self.history["time"].append(curr_time)
1957
+
1958
+ if not getattr(self.sw_network, "last_solve_converged", True):
1959
+ sp_num = (
1960
+ int(kper) + 1
1961
+ if kper is not None
1962
+ else len(self.history["time"])
1963
+ )
1964
+ logger.warning(
1965
+ "Surface water solver did not converge at stress period %d (t=%.2f d): "
1966
+ "max residual = %.4g m^3/d at node '%s' (%d node(s) above flow_tol=%.4g m^3/d).",
1967
+ sp_num,
1968
+ curr_time,
1969
+ getattr(self.sw_network, "last_solve_max_residual", float("nan")),
1970
+ getattr(self.sw_network, "last_solve_worst_node", None),
1971
+ getattr(self.sw_network, "last_solve_exceeded_count", 0),
1972
+ getattr(self.sw_network, "last_solve_flow_tol", 0.05),
1973
+ )
1974
+ sto_hist = self.history.setdefault(
1975
+ "storage", {nid: [] for nid in self.sw_network.nodes}
1976
+ )
1977
+ for nid, node in self.sw_network.nodes.items():
1978
+ self.history["stages"][nid].append(node.stage)
1979
+ gw_seepage, gw_infiltration = node.calculate_gw_exchange_components()
1980
+ self.history["gw_seepage"][nid].append(gw_seepage)
1981
+ self.history["gw_infiltration"][nid].append(gw_infiltration)
1982
+ self.history["precipitation"][nid].append(node.precipitation)
1983
+ self.history["evaporation"][nid].append(
1984
+ node.calculate_actual_evaporation(node.stage)
1985
+ )
1986
+ self.history["ext_flow"][nid].append(
1987
+ node.calculate_actual_ext_flow(node.stage)
1988
+ )
1989
+ sto_hist.setdefault(nid, []).append(
1990
+ node.calculate_storage_flux(
1991
+ node.stage, dt=step_dt, is_steady_state=self.is_steady_state
1992
+ )
1993
+ )
1994
+ if update_prev_stage:
1995
+ node.prev_stage = node.stage
1996
+
1997
+ for conn in self.sw_network.connections.values():
1998
+ conn_key = getattr(
1999
+ conn, "_history_key", f"{conn.node_from}->{conn.node_to}"
2000
+ )
2001
+ if conn_key not in self.history["flows"]:
2002
+ self.history["flows"][conn_key] = []
2003
+ s_from = self.sw_network.nodes[conn.node_from].stage
2004
+ s_to = self.sw_network.nodes[conn.node_to].stage
2005
+ self.history["flows"][conn_key].append(conn.flow(s_from, s_to))
2006
+
2007
+ def _record_gwt_concentration_history(
2008
+ self, gwt_models: list[str], step_key: tuple[Any, Any]
2009
+ ) -> None:
2010
+ """Record converged SW node concentrations for GWT model(s) at stress period end."""
2011
+ conc_hist = self.history.setdefault(
2012
+ "concentrations",
2013
+ {
2014
+ str(m).upper(): {nid: [] for nid in self.sw_network.nodes}
2015
+ for m in self._gwt_models
2016
+ },
2017
+ )
2018
+ for m in gwt_models:
2019
+ m_key = str(m).upper()
2020
+ if self._last_gwt_sp_end_step.get(m_key) == step_key:
2021
+ continue
2022
+ self._last_gwt_sp_end_step[m_key] = step_key
2023
+ model_store = conc_hist.setdefault(
2024
+ m_key, {nid: [] for nid in self.sw_network.nodes}
2025
+ )
2026
+ for nid, node in self.sw_network.nodes.items():
2027
+ model_store[nid].append(self._get_node_concentration(node, m_key))
2028
+
2029
+ def _simulation_uses_unstructured_grid(self) -> bool:
2030
+ """
2031
+ Return True when any GWF model uses DISV or DISU discretization.
2032
+ """
2033
+ nam_path = self.sim_dir / "mfsim.nam"
2034
+ if not nam_path.exists():
2035
+ return False
2036
+
2037
+ models = self._read_models_from_nam(nam_path)
2038
+ gwf_model_names = [name for model_type, name in models if model_type == "GWF6"]
2039
+ if not gwf_model_names:
2040
+ return False
2041
+
2042
+ for model_name in gwf_model_names:
2043
+ model_nam_path = self.sim_dir / f"{model_name.lower()}.nam"
2044
+ if not model_nam_path.exists():
2045
+ continue
2046
+ try:
2047
+ lines = model_nam_path.read_text(encoding="utf-8").splitlines()
2048
+ except OSError:
2049
+ continue
2050
+ section = None
2051
+ for raw_line in lines:
2052
+ line = raw_line.strip()
2053
+ if not line or line.startswith("#"):
2054
+ continue
2055
+ upper = line.upper()
2056
+ if upper.startswith("BEGIN "):
2057
+ parts = upper.split()
2058
+ section = parts[1] if len(parts) > 1 else None
2059
+ continue
2060
+ if upper.startswith("END "):
2061
+ section = None
2062
+ continue
2063
+ if section != "PACKAGES":
2064
+ continue
2065
+ token = line.split()[0].upper()
2066
+ if token in {"DISV6", "DISU6"}:
2067
+ return True
2068
+ return False
2069
+
2070
+ def _preflight_native_initialize_if_unstructured(self) -> None:
2071
+ """
2072
+ Isolate potential native initialization crashes for DISV/DISU in a subprocess.
2073
+
2074
+ Some MF6/modflowapi builds can terminate the host process during initialize()
2075
+ for unstructured grids. This preflight keeps the main Python process safe and
2076
+ turns native termination into a clear RuntimeError.
2077
+ """
2078
+ if not self._simulation_uses_unstructured_grid():
2079
+ return
2080
+
2081
+ cmd = [
2082
+ sys.executable,
2083
+ "-c",
2084
+ (
2085
+ "import modflowapi; "
2086
+ f"mf6 = modflowapi.ModflowApi(r'{str(self.dll_path)}', "
2087
+ f"working_directory=r'{str(self.sim_dir)}'); "
2088
+ "mf6.initialize(); "
2089
+ "mf6.finalize()"
2090
+ ),
2091
+ ]
2092
+ proc = subprocess.run(
2093
+ cmd,
2094
+ capture_output=True,
2095
+ text=True,
2096
+ timeout=120,
2097
+ )
2098
+ if proc.returncode != 0:
2099
+ details = "\n".join(
2100
+ part for part in [proc.stdout.strip(), proc.stderr.strip()] if part
2101
+ )
2102
+ mf6_error_summary = self._read_mf6_error_summary()
2103
+ if mf6_error_summary:
2104
+ details = (
2105
+ f"{details}\n\nMF6 list-file error summary:\n{mf6_error_summary}"
2106
+ if details
2107
+ else f"MF6 list-file error summary:\n{mf6_error_summary}"
2108
+ )
2109
+ if details:
2110
+ details = f"\nPreflight output:\n{details}"
2111
+ raise RuntimeError(
2112
+ "Native MF6 initialization failed in preflight subprocess for this "
2113
+ "unstructured (DISV/DISU) simulation. This likely indicates an "
2114
+ "MF6/modflowapi runtime incompatibility in the current environment. "
2115
+ "The coupling run was aborted to avoid a host kernel crash."
2116
+ f"{details}"
2117
+ )
2118
+
2119
+ def _read_mf6_error_summary(self) -> str:
2120
+ """
2121
+ Read the most relevant diagnostics from mfsim.lst when available.
2122
+ """
2123
+ lst_path = self.sim_dir / "mfsim.lst"
2124
+ if not lst_path.exists():
2125
+ return ""
2126
+ try:
2127
+ lines = lst_path.read_text(encoding="utf-8", errors="ignore").splitlines()
2128
+ except OSError:
2129
+ return ""
2130
+
2131
+ error_idx = next(
2132
+ (
2133
+ i
2134
+ for i, line in enumerate(lines)
2135
+ if line.strip().upper() == "ERROR REPORT:"
2136
+ ),
2137
+ None,
2138
+ )
2139
+ if error_idx is not None:
2140
+ end_idx = next(
2141
+ (
2142
+ j
2143
+ for j in range(error_idx + 1, len(lines))
2144
+ if lines[j].strip().upper() == "UNIT ERROR REPORT:"
2145
+ ),
2146
+ min(error_idx + 25, len(lines)),
2147
+ )
2148
+ block = [ln.rstrip() for ln in lines[error_idx:end_idx]]
2149
+ return "\n".join(ln for ln in block if ln.strip())
2150
+
2151
+ tail = [ln.rstrip() for ln in lines[-30:] if ln.strip()]
2152
+ return "\n".join(tail)
2153
+
2154
+ def get_network_snapshot(
2155
+ self,
2156
+ kper: int | None = None,
2157
+ time: float | None = None,
2158
+ time_atol: float = 1e-9,
2159
+ ) -> SurfaceWaterNetwork:
2160
+ """
2161
+ Return a surface-water network snapshot at one history step.
2162
+
2163
+ Parameters
2164
+ ----------
2165
+ kper : int, optional
2166
+ 0-based history step index to extract.
2167
+ time : float, optional
2168
+ Simulation time value from ``self.history["time"]`` to extract.
2169
+ Exactly one of ``kper`` or ``time`` must be provided.
2170
+ time_atol : float, default 1e-9
2171
+ Absolute tolerance used when matching ``time`` against recorded history time.
2172
+
2173
+ Returns
2174
+ -------
2175
+ SurfaceWaterNetwork
2176
+ Deep-copied network with node states set to the selected step.
2177
+ """
2178
+ if (kper is None) == (time is None):
2179
+ raise ValueError("Provide exactly one of 'kper' or 'time'.")
2180
+
2181
+ times = list(self.history.get("time", []))
2182
+ n_steps = len(times)
2183
+ if n_steps == 0:
2184
+ raise RuntimeError(
2185
+ "Simulation has not been run yet. Call `coupling.run()` first."
2186
+ )
2187
+
2188
+ if kper is not None:
2189
+ step = int(kper)
2190
+ if step < 0 or step >= n_steps:
2191
+ raise ValueError(
2192
+ f"kper={kper} is out of range. Valid range is [0, {n_steps - 1}]."
2193
+ )
2194
+ else:
2195
+ target = float(time)
2196
+ time_values = np.array([float(t) for t in times], dtype=float)
2197
+ matches = np.where(np.isclose(time_values, target, atol=time_atol, rtol=0.0))[
2198
+ 0
2199
+ ]
2200
+ if len(matches) == 0:
2201
+ nearest_idx = int(np.argmin(np.abs(time_values - target)))
2202
+ nearest_time = float(time_values[nearest_idx])
2203
+ raise ValueError(
2204
+ f"time={target} was not found in history within atol={time_atol}. "
2205
+ f"Nearest recorded time is {nearest_time} at kper={nearest_idx}."
2206
+ )
2207
+ step = int(matches[0])
2208
+
2209
+ snapshot = deepcopy(self.sw_network)
2210
+
2211
+ for nid, node in snapshot.nodes.items():
2212
+ node.stage = float(self.history["stages"][nid][step])
2213
+ node.gw_seepage = float(self.history["gw_seepage"][nid][step])
2214
+ node.gw_infiltration = float(self.history["gw_infiltration"][nid][step])
2215
+ node.precipitation = float(self.history["precipitation"][nid][step])
2216
+ node.evaporation = float(self.history["evaporation"][nid][step])
2217
+ node.ext_flow = float(self.history["ext_flow"][nid][step])
2218
+ if step > 0:
2219
+ node.prev_stage = float(self.history["stages"][nid][step - 1])
2220
+ else:
2221
+ node.prev_stage = node.stage
2222
+ for conn in snapshot.connections.values():
2223
+ for attr in (
2224
+ "crest_elevation",
2225
+ "invert_elevation",
2226
+ "min_stage_from",
2227
+ "max_stage_from",
2228
+ "min_stage_to",
2229
+ "max_stage_to",
2230
+ ):
2231
+ series = getattr(conn, f"{attr}_series", None)
2232
+ if series is not None and step < len(series):
2233
+ setattr(conn, attr, float(series[step]))
2234
+ return snapshot
2235
+
2236
+ def get_water_balance(
2237
+ self,
2238
+ element: int | str | Node | Connection,
2239
+ kper: int | None = None,
2240
+ dates: Any | None = None,
2241
+ start: pd.Timestamp | str | None = None,
2242
+ ):
2243
+ """
2244
+ Retrieve water balance volumetric budget components [m^3/day] from coupled simulation results.
2245
+
2246
+ Parameters
2247
+ ----------
2248
+ element : int, str, Node, or Connection
2249
+ Target node identifier/instance, or connection identifier/instance.
2250
+ kper : int, optional
2251
+ 0-based stress period index. If provided, returns a single-row DataFrame for that step.
2252
+ If None, returns a full time-series DataFrame across all simulated time steps.
2253
+ dates : sequence of datetime-like or timestamps, optional
2254
+ Optional datetime index to assign to the time-series DataFrame (length must match number of steps).
2255
+ start : pd.Timestamp | str | None, optional
2256
+ Start time of the simulation, used to offset the time index if provided.
2257
+
2258
+ Returns
2259
+ -------
2260
+ pandas.DataFrame
2261
+ DataFrame of volumetric budget components [m^3/day] over time or for a specific step.
2262
+ """
2263
+ import pandas as pd
2264
+
2265
+ n_steps = len(self.history["time"])
2266
+ if n_steps == 0:
2267
+ raise RuntimeError(
2268
+ "Simulation has not been run yet. Call `coupling.run()` first."
2269
+ )
2270
+
2271
+ # Resolve element to Node or Connection
2272
+ target_node = None
2273
+ target_conn = None
2274
+
2275
+ if isinstance(element, Node):
2276
+ target_node = element
2277
+ elif isinstance(element, Connection):
2278
+ target_conn = self.sw_network.get_connection(element)
2279
+ elif element in self.sw_network.nodes:
2280
+ target_node = self.sw_network.nodes[element]
2281
+ else:
2282
+ target_conn = self.sw_network.get_connection(str(element))
2283
+
2284
+ if target_node is None and target_conn is None:
2285
+ raise ValueError(
2286
+ f"Element '{element}' not found as a Node or Connection in the Surface Water Network."
2287
+ )
2288
+
2289
+ if dates is not None and len(dates) == n_steps:
2290
+ idx = dates
2291
+ else:
2292
+ idx = self.history["time"]
2293
+ if start is not None:
2294
+ idx = pd.Timestamp(start) + pd.to_timedelta(idx, unit="D")
2295
+
2296
+ if target_node is not None:
2297
+ nid = target_node.name
2298
+ stages = self.history["stages"][nid]
2299
+ gw_seepage = self.history.get("gw_seepage", {}).get(nid, [])
2300
+ gw_infiltration = self.history.get("gw_infiltration", {}).get(nid, [])
2301
+ if len(gw_seepage) != n_steps or len(gw_infiltration) != n_steps:
2302
+ raise RuntimeError(
2303
+ "Coupling history does not contain complete gw_seepage/gw_infiltration series. "
2304
+ "Legacy gw_exchange-only history is not supported."
2305
+ )
2306
+ gw_ex = [gw_seepage[i] + gw_infiltration[i] for i in range(n_steps)]
2307
+ area = target_node.area
2308
+
2309
+ # Inflow/outflow connections
2310
+ up_conns = [
2311
+ c for c in self.sw_network.connections.values() if c.node_to == nid
2312
+ ]
2313
+ down_conns = [
2314
+ c for c in self.sw_network.connections.values() if c.node_from == nid
2315
+ ]
2316
+
2317
+ up_inflows = []
2318
+ down_outflows = []
2319
+
2320
+ for step in range(n_steps):
2321
+ u_sum = 0.0
2322
+ d_sum = 0.0
2323
+ for c in up_conns:
2324
+ fl = self._get_connection_flow_series(c, n_steps)[step]
2325
+ if fl > 0:
2326
+ u_sum += fl
2327
+ else:
2328
+ d_sum += fl
2329
+
2330
+ for c in down_conns:
2331
+ fl = self._get_connection_flow_series(c, n_steps)[step]
2332
+ if fl > 0:
2333
+ d_sum -= fl
2334
+ else:
2335
+ u_sum -= fl
2336
+
2337
+ up_inflows.append(u_sum)
2338
+ down_outflows.append(d_sum)
2339
+
2340
+ # Node time-varying parameters from history
2341
+ p_hist = self.history.get("precipitation", {}).get(
2342
+ nid, [target_node.precipitation] * n_steps
2343
+ )
2344
+ e_hist = self.history.get("evaporation", {}).get(
2345
+ nid,
2346
+ [target_node.calculate_actual_evaporation(target_node.stage)] * n_steps,
2347
+ )
2348
+ ext_hist = self.history.get("ext_flow", {}).get(
2349
+ nid,
2350
+ [target_node.calculate_actual_ext_flow(target_node.stage)] * n_steps,
2351
+ )
2352
+
2353
+ p_flux = [p_hist[i] * area for i in range(n_steps)]
2354
+ e_flux = [-e_hist[i] * area for i in range(n_steps)]
2355
+ ext_in = [max(0.0, ext_hist[i]) for i in range(n_steps)]
2356
+ ext_out = [min(0.0, ext_hist[i]) for i in range(n_steps)]
2357
+
2358
+ # Storage flux [m^3/day]
2359
+ recorded_sto = self.history.get("storage", {}).get(nid)
2360
+ if recorded_sto is not None and len(recorded_sto) == n_steps:
2361
+ sto_flux = [float(v) for v in recorded_sto]
2362
+ else:
2363
+ times = self.history["time"]
2364
+ init_stage = getattr(self, "_initial_stages", {}).get(
2365
+ nid, target_node.prev_stage
2366
+ )
2367
+ sto_flux = []
2368
+ for step in range(n_steps):
2369
+ if target_node.include_storage:
2370
+ s_curr = stages[step]
2371
+ s_prev = stages[step - 1] if step > 0 else init_stage
2372
+ dt_step = (
2373
+ float(times[step]) - float(times[step - 1])
2374
+ if step > 0
2375
+ else float(times[0])
2376
+ )
2377
+ if dt_step <= 0.0:
2378
+ dt_step = 1.0
2379
+ sto_flux.append(-area * (s_curr - s_prev) / dt_step)
2380
+ else:
2381
+ sto_flux.append(0.0)
2382
+
2383
+ # Residual
2384
+ net_res = [
2385
+ p_flux[i]
2386
+ + e_flux[i]
2387
+ + ext_in[i]
2388
+ + ext_out[i]
2389
+ + gw_ex[i]
2390
+ + sto_flux[i]
2391
+ + up_inflows[i]
2392
+ + down_outflows[i]
2393
+ for i in range(n_steps)
2394
+ ]
2395
+
2396
+ df_data = {
2397
+ "precipitation": p_flux,
2398
+ "evaporation": e_flux,
2399
+ "ext_inflow": ext_in,
2400
+ "ext_outflow": ext_out,
2401
+ "gw_seepage": gw_seepage,
2402
+ "gw_infiltration": gw_infiltration,
2403
+ "upstream_inflow": up_inflows,
2404
+ "downstream_outflow": down_outflows,
2405
+ "storage": sto_flux,
2406
+ "net_residual": net_res,
2407
+ }
2408
+ df = pd.DataFrame(df_data, index=idx)
2409
+
2410
+ if kper is not None:
2411
+ return df.iloc[[kper]]
2412
+ return df
2413
+
2414
+ else:
2415
+ q_series = self._get_connection_flow_series(target_conn, n_steps)
2416
+
2417
+ up_in = [max(0.0, q) for q in q_series]
2418
+ down_out = [-max(0.0, q) for q in q_series]
2419
+ gw_seepage = [0.0] * n_steps
2420
+ gw_infiltration = [0.0] * n_steps
2421
+ net_res = [
2422
+ up_in[i] + down_out[i] + gw_seepage[i] + gw_infiltration[i]
2423
+ for i in range(n_steps)
2424
+ ]
2425
+
2426
+ df_data = {
2427
+ "upstream_inflow": up_in,
2428
+ "downstream_outflow": down_out,
2429
+ "gw_seepage": gw_seepage,
2430
+ "gw_infiltration": gw_infiltration,
2431
+ "net_residual": net_res,
2432
+ }
2433
+ df = pd.DataFrame(df_data, index=idx)
2434
+
2435
+ if kper is not None:
2436
+ return df.iloc[[kper]]
2437
+ return df
2438
+
2439
+ def plot_water_balance(
2440
+ self,
2441
+ element: int | str | Node | Connection,
2442
+ kper: int | None = None,
2443
+ dates: Any | None = None,
2444
+ start: pd.Timestamp | str | None = None,
2445
+ ax: Any | None = None,
2446
+ figsize: tuple[float, float] = (10.0, 5.5),
2447
+ title: str | None = None,
2448
+ add_stage: bool = False,
2449
+ ymax: float | None = None,
2450
+ ):
2451
+ """
2452
+ Plot the volumetric water balance budget breakdown from coupled simulation results.
2453
+
2454
+ Parameters
2455
+ ----------
2456
+ element : int, str, Node, or Connection
2457
+ Target node identifier/instance, or connection identifier/instance.
2458
+ kper : int, optional
2459
+ Optional specific stress period index to plot as a single-period bar chart.
2460
+ If None, plots a stacked bar chart over the entire simulated time series.
2461
+ dates : sequence of datetime-like or timestamps, optional
2462
+ Optional datetime index for labeling the time axis.
2463
+ start : pd.Timestamp | str | None, optional
2464
+ Start time of the simulation, used to offset the time axis if provided.
2465
+ ax : matplotlib.axes.Axes, optional
2466
+ Matplotlib Axes instance. If None, creates a new figure and axes.
2467
+ figsize : tuple of (float, float), default (10.0, 5.5)
2468
+ Figure size when ax is None.
2469
+ title : str, optional
2470
+ Custom plot title.
2471
+ add_stage : bool, default False
2472
+ Whether to add the lake stage (water level) as a secondary y-axis.
2473
+ ymax : float, optional
2474
+ Maximum y-axis limit for the plot. If None, it will be determined automatically.
2475
+
2476
+ Returns
2477
+ -------
2478
+ tuple of (matplotlib.figure.Figure, matplotlib.axes.Axes)
2479
+ """
2480
+ from swmod.plotting import plot_water_balance
2481
+
2482
+ df_wb = self.get_water_balance(
2483
+ element=element,
2484
+ kper=kper,
2485
+ dates=dates,
2486
+ start=start,
2487
+ )
2488
+ elem_name = str(getattr(element, "name", None) or element)
2489
+ if add_stage:
2490
+ stage = pd.Series(self.history["stages"][element], index=df_wb.index)
2491
+ if not self.sw_network.nodes[element].include_storage:
2492
+ stage_s = stage.copy()
2493
+ if start is not None:
2494
+ stage_s.index = [pd.Timestamp(start)] + list(stage.index[:-1])
2495
+ else:
2496
+ stage_s.index = [0.0] + list(stage.index[:-1])
2497
+ stage = pd.concat((stage, stage_s)).sort_index(kind="mergesort")
2498
+ else:
2499
+ stage = None
2500
+
2501
+ return plot_water_balance(
2502
+ df_wb=df_wb,
2503
+ element_name=elem_name,
2504
+ ax=ax,
2505
+ figsize=figsize,
2506
+ title=title,
2507
+ start=start,
2508
+ stage=stage,
2509
+ ymax=ymax,
2510
+ )