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/__init__.py +51 -0
- swmod/_logging.py +94 -0
- swmod/builder.py +558 -0
- swmod/coupling.py +2510 -0
- swmod/network.py +3741 -0
- swmod/plotting.py +909 -0
- swmod/version.py +1 -0
- swmod-0.0.1.dist-info/METADATA +75 -0
- swmod-0.0.1.dist-info/RECORD +11 -0
- swmod-0.0.1.dist-info/WHEEL +4 -0
- swmod-0.0.1.dist-info/licenses/LICENSE +21 -0
swmod/__init__.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
from swmod.version import __version__
|
|
2
|
+
from swmod._logging import set_log_level
|
|
3
|
+
from swmod.network import (
|
|
4
|
+
Node,
|
|
5
|
+
Outfall,
|
|
6
|
+
Connection,
|
|
7
|
+
Reach,
|
|
8
|
+
Weir,
|
|
9
|
+
Culvert,
|
|
10
|
+
Pump,
|
|
11
|
+
SurfaceWaterNetwork,
|
|
12
|
+
CrossSection,
|
|
13
|
+
RectangularCrossSection,
|
|
14
|
+
TrapezoidalCrossSection,
|
|
15
|
+
TriangularCrossSection,
|
|
16
|
+
)
|
|
17
|
+
from swmod.coupling import CoupledSimulation
|
|
18
|
+
from swmod.builder import (
|
|
19
|
+
create_test_model,
|
|
20
|
+
create_natural_geometries,
|
|
21
|
+
create_complex_geometries,
|
|
22
|
+
add_surface_water,
|
|
23
|
+
)
|
|
24
|
+
from swmod.plotting import plot_coupled_map, plot_network, plot_water_balance
|
|
25
|
+
|
|
26
|
+
__all__ = [
|
|
27
|
+
"__version__",
|
|
28
|
+
"set_log_level",
|
|
29
|
+
"Node",
|
|
30
|
+
"Outfall",
|
|
31
|
+
"Connection",
|
|
32
|
+
"Reach",
|
|
33
|
+
"Weir",
|
|
34
|
+
"Culvert",
|
|
35
|
+
"Pump",
|
|
36
|
+
"SurfaceWaterNetwork",
|
|
37
|
+
"CrossSection",
|
|
38
|
+
"RectangularCrossSection",
|
|
39
|
+
"TrapezoidalCrossSection",
|
|
40
|
+
"TriangularCrossSection",
|
|
41
|
+
"CoupledSimulation",
|
|
42
|
+
"create_test_model",
|
|
43
|
+
"create_natural_geometries",
|
|
44
|
+
"create_complex_geometries",
|
|
45
|
+
"add_surface_water",
|
|
46
|
+
"plot_coupled_map",
|
|
47
|
+
"plot_network",
|
|
48
|
+
"plot_water_balance",
|
|
49
|
+
]
|
|
50
|
+
|
|
51
|
+
|
swmod/_logging.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""Internal logging helpers for swmod."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from collections.abc import Iterator
|
|
7
|
+
from contextlib import contextmanager
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _has_active_handler(target_logger: logging.Logger) -> bool:
|
|
11
|
+
"""Return True if ``target_logger`` or any propagated ancestor has a non-NullHandler."""
|
|
12
|
+
current: logging.Logger | None = target_logger
|
|
13
|
+
while current is not None:
|
|
14
|
+
if any(not isinstance(h, logging.NullHandler) for h in current.handlers):
|
|
15
|
+
return True
|
|
16
|
+
if not current.propagate:
|
|
17
|
+
break
|
|
18
|
+
current = current.parent
|
|
19
|
+
return False
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@contextmanager
|
|
23
|
+
def verbose_logging(
|
|
24
|
+
enabled: bool,
|
|
25
|
+
level: int = logging.DEBUG,
|
|
26
|
+
logger_name: str = "swmod",
|
|
27
|
+
) -> Iterator[None]:
|
|
28
|
+
"""
|
|
29
|
+
Temporarily ensure log records at ``level`` or higher from ``logger_name`` are emitted.
|
|
30
|
+
|
|
31
|
+
When ``enabled`` is False, this is a no-op so callers control verbosity solely through
|
|
32
|
+
Python's standard :mod:`logging` configuration. When ``enabled`` is True, the target
|
|
33
|
+
logger's level is temporarily lowered to ``level`` if needed, and a temporary
|
|
34
|
+
:class:`logging.StreamHandler` is attached only when no active handler exists on the
|
|
35
|
+
logger or its ancestors.
|
|
36
|
+
"""
|
|
37
|
+
if not enabled:
|
|
38
|
+
yield
|
|
39
|
+
return
|
|
40
|
+
|
|
41
|
+
target_logger = logging.getLogger(logger_name)
|
|
42
|
+
prev_level = target_logger.level
|
|
43
|
+
level_changed = target_logger.getEffectiveLevel() > level
|
|
44
|
+
if level_changed:
|
|
45
|
+
target_logger.setLevel(level)
|
|
46
|
+
|
|
47
|
+
temp_handler: logging.Handler | None = None
|
|
48
|
+
if not _has_active_handler(target_logger):
|
|
49
|
+
temp_handler = logging.StreamHandler()
|
|
50
|
+
temp_handler.setLevel(level)
|
|
51
|
+
temp_handler.setFormatter(
|
|
52
|
+
logging.Formatter("%(levelname)s:%(name)s:%(message)s")
|
|
53
|
+
)
|
|
54
|
+
target_logger.addHandler(temp_handler)
|
|
55
|
+
|
|
56
|
+
try:
|
|
57
|
+
yield
|
|
58
|
+
finally:
|
|
59
|
+
if temp_handler is not None:
|
|
60
|
+
target_logger.removeHandler(temp_handler)
|
|
61
|
+
if level_changed:
|
|
62
|
+
target_logger.setLevel(prev_level)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def set_log_level(level: int | str) -> logging.Logger:
|
|
66
|
+
"""
|
|
67
|
+
Configure the ``swmod`` package logger level.
|
|
68
|
+
|
|
69
|
+
If no active handler is configured on ``swmod`` or the root logger, a
|
|
70
|
+
:class:`logging.StreamHandler` is attached to the ``swmod`` logger so messages at
|
|
71
|
+
``level`` and above are immediately visible.
|
|
72
|
+
|
|
73
|
+
Parameters
|
|
74
|
+
----------
|
|
75
|
+
level : int or str
|
|
76
|
+
Logging level (e.g. ``logging.INFO``, ``logging.DEBUG``, ``"INFO"``, ``"WARNING"``).
|
|
77
|
+
|
|
78
|
+
Returns
|
|
79
|
+
-------
|
|
80
|
+
logging.Logger
|
|
81
|
+
The configured ``swmod`` package logger.
|
|
82
|
+
"""
|
|
83
|
+
pkg_logger = logging.getLogger("swmod")
|
|
84
|
+
resolved = (
|
|
85
|
+
getattr(logging, level.upper(), None) if isinstance(level, str) else level
|
|
86
|
+
)
|
|
87
|
+
if not isinstance(resolved, int):
|
|
88
|
+
raise ValueError(f"Invalid log level: {level!r}")
|
|
89
|
+
pkg_logger.setLevel(resolved)
|
|
90
|
+
if not _has_active_handler(pkg_logger):
|
|
91
|
+
handler = logging.StreamHandler()
|
|
92
|
+
handler.setFormatter(logging.Formatter("%(levelname)s:%(name)s:%(message)s"))
|
|
93
|
+
pkg_logger.addHandler(handler)
|
|
94
|
+
return pkg_logger
|
swmod/builder.py
ADDED
|
@@ -0,0 +1,558 @@
|
|
|
1
|
+
"""
|
|
2
|
+
MODFLOW 6 Model Builder Module
|
|
3
|
+
|
|
4
|
+
Generates FloPy grid models and GeoPandas GIS spatial features:
|
|
5
|
+
- Grid size: configurable (default 20x20, 100m x 100m cells).
|
|
6
|
+
- GeoPandas GeoDataFrame geometries for lakes, ponds, and river reaches.
|
|
7
|
+
- Automatic spatial intersection mapping of GIS vector features onto FloPy grid cell IDs.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
import flopy
|
|
14
|
+
import geopandas as gpd
|
|
15
|
+
import pandas as pd
|
|
16
|
+
from flopy.utils import GridIntersect
|
|
17
|
+
from shapely.geometry import LineString, Polygon
|
|
18
|
+
|
|
19
|
+
from swmod.network import Node, Reach, SurfaceWaterNetwork
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def create_natural_geometries() -> gpd.GeoDataFrame:
|
|
23
|
+
"""
|
|
24
|
+
Generate realistic natural GIS vector geometries for a 2000m x 2000m catchment.
|
|
25
|
+
|
|
26
|
+
Returns
|
|
27
|
+
-------
|
|
28
|
+
gpd.GeoDataFrame
|
|
29
|
+
GeoDataFrame containing vector geometries for:
|
|
30
|
+
- `upper_lake`: Natural irregular polygon in upper catchment.
|
|
31
|
+
- `lower_pond`: Natural irregular polygon in lower catchment.
|
|
32
|
+
- `reach`: S-curved meander LineString channel connecting lake to pond.
|
|
33
|
+
"""
|
|
34
|
+
lake_coords = [
|
|
35
|
+
(400.0, 1750.0),
|
|
36
|
+
(650.0, 1700.0),
|
|
37
|
+
(800.0, 1550.0),
|
|
38
|
+
(750.0, 1350.0),
|
|
39
|
+
(550.0, 1300.0),
|
|
40
|
+
(350.0, 1450.0),
|
|
41
|
+
(320.0, 1650.0),
|
|
42
|
+
]
|
|
43
|
+
poly_lake = Polygon(lake_coords)
|
|
44
|
+
|
|
45
|
+
pond_coords = [
|
|
46
|
+
(1200.0, 750.0),
|
|
47
|
+
(1450.0, 700.0),
|
|
48
|
+
(1600.0, 550.0),
|
|
49
|
+
(1500.0, 350.0),
|
|
50
|
+
(1300.0, 320.0),
|
|
51
|
+
(1150.0, 480.0),
|
|
52
|
+
]
|
|
53
|
+
poly_pond = Polygon(pond_coords)
|
|
54
|
+
|
|
55
|
+
reach_coords = [
|
|
56
|
+
(550.0, 1300.0),
|
|
57
|
+
(620.0, 1150.0),
|
|
58
|
+
(780.0, 1050.0),
|
|
59
|
+
(950.0, 980.0),
|
|
60
|
+
(1100.0, 880.0),
|
|
61
|
+
(1200.0, 750.0),
|
|
62
|
+
]
|
|
63
|
+
line_reach = LineString(reach_coords)
|
|
64
|
+
|
|
65
|
+
data = [
|
|
66
|
+
{
|
|
67
|
+
"name": "upper_lake",
|
|
68
|
+
"feature_type": "lake",
|
|
69
|
+
"c_bed": 5.0,
|
|
70
|
+
"reach_width": 0.0,
|
|
71
|
+
"initial_stage": 7.0,
|
|
72
|
+
"bed_bottom": 4.0,
|
|
73
|
+
"geometry": poly_lake,
|
|
74
|
+
},
|
|
75
|
+
{
|
|
76
|
+
"name": "lower_pond",
|
|
77
|
+
"feature_type": "pond",
|
|
78
|
+
"c_bed": 5.0,
|
|
79
|
+
"reach_width": 0.0,
|
|
80
|
+
"initial_stage": 5.0,
|
|
81
|
+
"bed_bottom": 3.0,
|
|
82
|
+
"geometry": poly_pond,
|
|
83
|
+
},
|
|
84
|
+
{
|
|
85
|
+
"name": "reach",
|
|
86
|
+
"feature_type": "reach",
|
|
87
|
+
"c_bed": 2.0,
|
|
88
|
+
"reach_width": 10.0,
|
|
89
|
+
"initial_stage": 6.0,
|
|
90
|
+
"bed_bottom": 3.5,
|
|
91
|
+
"geometry": line_reach,
|
|
92
|
+
},
|
|
93
|
+
]
|
|
94
|
+
|
|
95
|
+
return gpd.GeoDataFrame(data, crs="EPSG:32631")
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def create_complex_geometries() -> gpd.GeoDataFrame:
|
|
99
|
+
"""
|
|
100
|
+
Generate complex multi-reach natural GIS vector geometries for a 6-node network:
|
|
101
|
+
- Central Lake (Polygon)
|
|
102
|
+
- West Wetland (Polygon)
|
|
103
|
+
- West Reach (LineString)
|
|
104
|
+
- East Reach (LineString)
|
|
105
|
+
- East Bypass Reach (LineString)
|
|
106
|
+
"""
|
|
107
|
+
poly_central_lake = Polygon(
|
|
108
|
+
[
|
|
109
|
+
(700.0, 1600.0),
|
|
110
|
+
(1100.0, 1550.0),
|
|
111
|
+
(1200.0, 1350.0),
|
|
112
|
+
(1000.0, 1200.0),
|
|
113
|
+
(750.0, 1250.0),
|
|
114
|
+
(650.0, 1450.0),
|
|
115
|
+
]
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
poly_west_wetland = Polygon(
|
|
119
|
+
[
|
|
120
|
+
(300.0, 1000.0),
|
|
121
|
+
(550.0, 950.0),
|
|
122
|
+
(600.0, 750.0),
|
|
123
|
+
(450.0, 650.0),
|
|
124
|
+
(250.0, 800.0),
|
|
125
|
+
]
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
line_west_reach = LineString(
|
|
129
|
+
[(750.0, 1250.0), (600.0, 1150.0), (450.0, 1050.0), (450.0, 850.0)]
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
line_east_reach = LineString(
|
|
133
|
+
[(1000.0, 1200.0), (1250.0, 1100.0), (1450.0, 950.0), (1450.0, 800.0)]
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
line_east_bypass = LineString(
|
|
137
|
+
[(1450.0, 800.0), (1350.0, 600.0), (1150.0, 450.0), (1000.0, 350.0)]
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
data = [
|
|
141
|
+
{
|
|
142
|
+
"name": "central_lake",
|
|
143
|
+
"feature_type": "lake",
|
|
144
|
+
"c_bed": 5.0,
|
|
145
|
+
"reach_width": 0.0,
|
|
146
|
+
"initial_stage": 7.0,
|
|
147
|
+
"bed_bottom": 4.0,
|
|
148
|
+
"geometry": poly_central_lake,
|
|
149
|
+
},
|
|
150
|
+
{
|
|
151
|
+
"name": "west_wetland",
|
|
152
|
+
"feature_type": "wetland",
|
|
153
|
+
"c_bed": 5.0,
|
|
154
|
+
"reach_width": 0.0,
|
|
155
|
+
"initial_stage": 5.5,
|
|
156
|
+
"bed_bottom": 3.5,
|
|
157
|
+
"geometry": poly_west_wetland,
|
|
158
|
+
},
|
|
159
|
+
{
|
|
160
|
+
"name": "reach_west",
|
|
161
|
+
"feature_type": "reach",
|
|
162
|
+
"c_bed": 2.0,
|
|
163
|
+
"reach_width": 8.0,
|
|
164
|
+
"initial_stage": 6.2,
|
|
165
|
+
"bed_bottom": 3.8,
|
|
166
|
+
"geometry": line_west_reach,
|
|
167
|
+
},
|
|
168
|
+
{
|
|
169
|
+
"name": "reach_east",
|
|
170
|
+
"feature_type": "reach",
|
|
171
|
+
"c_bed": 2.0,
|
|
172
|
+
"reach_width": 6.0,
|
|
173
|
+
"initial_stage": 6.0,
|
|
174
|
+
"bed_bottom": 3.7,
|
|
175
|
+
"geometry": line_east_reach,
|
|
176
|
+
},
|
|
177
|
+
{
|
|
178
|
+
"name": "reach_bypass",
|
|
179
|
+
"feature_type": "reach",
|
|
180
|
+
"c_bed": 2.0,
|
|
181
|
+
"reach_width": 6.0,
|
|
182
|
+
"initial_stage": 4.8,
|
|
183
|
+
"bed_bottom": 3.2,
|
|
184
|
+
"geometry": line_east_bypass,
|
|
185
|
+
},
|
|
186
|
+
]
|
|
187
|
+
|
|
188
|
+
return gpd.GeoDataFrame(data, crs="EPSG:32631")
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def add_surface_water(
|
|
192
|
+
gwf: flopy.mf6.ModflowGwf,
|
|
193
|
+
sw_network: SurfaceWaterNetwork,
|
|
194
|
+
gdf_water: gpd.GeoDataFrame,
|
|
195
|
+
riv_pack_name: str = "RIV_1",
|
|
196
|
+
) -> flopy.mf6.ModflowGwfriv:
|
|
197
|
+
"""
|
|
198
|
+
Connect a SurfaceWaterNetwork and GIS vector geometries to an existing FloPy ModflowGwf model.
|
|
199
|
+
|
|
200
|
+
Intersects the GIS features with the groundwater model grid (structured, DISV, or DISU),
|
|
201
|
+
calculates cell IDs, conductances, and bed bottom elevations, populates `gw_cell_ids`,
|
|
202
|
+
`gw_conductances`, `gw_bottoms`, `gw_fractions`, and `riv_row_indices` on each
|
|
203
|
+
Node and Reach connection in `sw_network`,
|
|
204
|
+
and automatically attaches/updates a MODFLOW 6 RIV package on `gwf`.
|
|
205
|
+
|
|
206
|
+
Parameters
|
|
207
|
+
----------
|
|
208
|
+
gwf : flopy.mf6.ModflowGwf
|
|
209
|
+
FloPy Groundwater Flow model instance.
|
|
210
|
+
sw_network : SurfaceWaterNetwork
|
|
211
|
+
Surface water network model instance.
|
|
212
|
+
gdf_water : gpd.GeoDataFrame
|
|
213
|
+
GeoDataFrame containing spatial geometries for surface water features.
|
|
214
|
+
riv_pack_name : str, default 'RIV_1'
|
|
215
|
+
Name for the MODFLOW 6 RIV package.
|
|
216
|
+
|
|
217
|
+
Returns
|
|
218
|
+
-------
|
|
219
|
+
flopy.mf6.ModflowGwfriv
|
|
220
|
+
Configured FloPy RIV package attached to `gwf`.
|
|
221
|
+
"""
|
|
222
|
+
# Ensure nodes (lake/pond) are registered before reaches to match _get_providers order 100%
|
|
223
|
+
if "feature_type" in gdf_water.columns:
|
|
224
|
+
is_node = gdf_water["feature_type"].isin(
|
|
225
|
+
["lake", "pond", "upper_lake", "lower_pond", "wetland"]
|
|
226
|
+
)
|
|
227
|
+
node_df = gdf_water[is_node]
|
|
228
|
+
reach_df = gdf_water[~is_node]
|
|
229
|
+
gdf_water_sorted = pd.concat([node_df, reach_df], ignore_index=True)
|
|
230
|
+
else:
|
|
231
|
+
gdf_water_sorted = gdf_water.copy()
|
|
232
|
+
|
|
233
|
+
ix = GridIntersect(gwf.modelgrid)
|
|
234
|
+
ncol = getattr(gwf.modelgrid, "ncol", gwf.modelgrid.ncpl)
|
|
235
|
+
nper = (
|
|
236
|
+
gwf.simulation.tdis.nper.get_data()
|
|
237
|
+
if hasattr(gwf, "simulation") and hasattr(gwf.simulation, "tdis")
|
|
238
|
+
else 1
|
|
239
|
+
)
|
|
240
|
+
|
|
241
|
+
riv_data = []
|
|
242
|
+
for node in sw_network.nodes.values():
|
|
243
|
+
node.riv_row_indices = []
|
|
244
|
+
for conn in sw_network.connections.values():
|
|
245
|
+
conn.riv_row_indices = []
|
|
246
|
+
reaches_in_sw = [conn for conn in sw_network.connections.values() if isinstance(conn, Reach)]
|
|
247
|
+
unassigned_reaches = list(reaches_in_sw)
|
|
248
|
+
seen_targets: set[int] = set()
|
|
249
|
+
|
|
250
|
+
for _, row in gdf_water_sorted.iterrows():
|
|
251
|
+
name = str(row["name"])
|
|
252
|
+
f_type = str(row.get("feature_type", "node"))
|
|
253
|
+
c_bed = float(row.get("c_bed", 5.0))
|
|
254
|
+
bed_bot = float(row.get("bed_bottom", 3.0))
|
|
255
|
+
|
|
256
|
+
target_obj = None
|
|
257
|
+
|
|
258
|
+
if name in sw_network.nodes:
|
|
259
|
+
target_obj = sw_network.nodes[name]
|
|
260
|
+
w_reach = float(row.get("reach_width", 0.0))
|
|
261
|
+
init_stage = float(target_obj.stage)
|
|
262
|
+
else:
|
|
263
|
+
# Match reach connection
|
|
264
|
+
for conn in list(unassigned_reaches):
|
|
265
|
+
conn_name = f"{conn.node_from}->{conn.node_to}"
|
|
266
|
+
if name in [
|
|
267
|
+
conn_name,
|
|
268
|
+
getattr(conn, "name", ""),
|
|
269
|
+
conn.node_from,
|
|
270
|
+
conn.node_to,
|
|
271
|
+
] or name.startswith("reach"):
|
|
272
|
+
target_obj = conn
|
|
273
|
+
unassigned_reaches.remove(conn)
|
|
274
|
+
break
|
|
275
|
+
|
|
276
|
+
if target_obj is None and len(unassigned_reaches) > 0:
|
|
277
|
+
target_obj = unassigned_reaches.pop(0)
|
|
278
|
+
|
|
279
|
+
if target_obj is not None:
|
|
280
|
+
# Use reach width from cross_section if available
|
|
281
|
+
if hasattr(target_obj, "cross_section") and hasattr(
|
|
282
|
+
target_obj.cross_section, "width"
|
|
283
|
+
):
|
|
284
|
+
w_reach = float(target_obj.cross_section.width)
|
|
285
|
+
elif hasattr(target_obj, "cross_section") and hasattr(
|
|
286
|
+
target_obj.cross_section, "bottom_width"
|
|
287
|
+
):
|
|
288
|
+
w_reach = float(target_obj.cross_section.bottom_width)
|
|
289
|
+
else:
|
|
290
|
+
w_reach = float(row.get("reach_width", 5.0))
|
|
291
|
+
|
|
292
|
+
s_from = (
|
|
293
|
+
sw_network.nodes[target_obj.node_from].stage
|
|
294
|
+
if target_obj.node_from in sw_network.nodes
|
|
295
|
+
else 5.0
|
|
296
|
+
)
|
|
297
|
+
s_to = (
|
|
298
|
+
sw_network.nodes[target_obj.node_to].stage
|
|
299
|
+
if target_obj.node_to in sw_network.nodes
|
|
300
|
+
else 5.0
|
|
301
|
+
)
|
|
302
|
+
init_stage = float((s_from + s_to) / 2.0)
|
|
303
|
+
else:
|
|
304
|
+
w_reach = float(row.get("reach_width", 5.0))
|
|
305
|
+
init_stage = float(row.get("initial_stage", 5.0))
|
|
306
|
+
|
|
307
|
+
if target_obj is not None and id(target_obj) not in seen_targets:
|
|
308
|
+
target_obj.gw_cell_ids = []
|
|
309
|
+
target_obj.gw_conductances = []
|
|
310
|
+
target_obj.gw_bottoms = []
|
|
311
|
+
target_obj.gw_heads = []
|
|
312
|
+
target_obj.riv_row_indices = []
|
|
313
|
+
if isinstance(target_obj, Reach):
|
|
314
|
+
target_obj.gw_fractions = []
|
|
315
|
+
seen_targets.add(id(target_obj))
|
|
316
|
+
|
|
317
|
+
res = ix.intersect(row["geometry"], geo_dataframe=False)
|
|
318
|
+
if len(res) > 0:
|
|
319
|
+
if hasattr(gwf.modelgrid, "ncol"):
|
|
320
|
+
cids = [r * ncol + c for r, c in res["cellids"]]
|
|
321
|
+
else:
|
|
322
|
+
cids = list(res["cellids"])
|
|
323
|
+
|
|
324
|
+
if f_type == "reach" or row["geometry"].geom_type in [
|
|
325
|
+
"LineString",
|
|
326
|
+
"MultiLineString",
|
|
327
|
+
]:
|
|
328
|
+
lengths = list(res["lengths"])
|
|
329
|
+
areas = [float(l * w_reach) for l in lengths]
|
|
330
|
+
total_len = float(sum(lengths)) if len(lengths) > 0 else 1.0
|
|
331
|
+
cum_len = 0.0
|
|
332
|
+
fractions = []
|
|
333
|
+
for l in lengths:
|
|
334
|
+
cum_len += l / 2.0
|
|
335
|
+
fractions.append(float(cum_len / total_len))
|
|
336
|
+
cum_len += l / 2.0
|
|
337
|
+
else:
|
|
338
|
+
areas = list(res["areas"])
|
|
339
|
+
fractions = [0.0] * len(cids)
|
|
340
|
+
|
|
341
|
+
conds = [float(a / c_bed) for a in areas]
|
|
342
|
+
bots = [bed_bot] * len(cids)
|
|
343
|
+
|
|
344
|
+
row_indices = []
|
|
345
|
+
for cid, cond, bot in zip(cids, conds, bots):
|
|
346
|
+
if hasattr(gwf.modelgrid, "ncol"):
|
|
347
|
+
r, c = divmod(cid, ncol)
|
|
348
|
+
cell_tuple = (0, r, c)
|
|
349
|
+
else:
|
|
350
|
+
cell_tuple = (0, cid)
|
|
351
|
+
riv_data.append((cell_tuple, init_stage, cond, bot))
|
|
352
|
+
row_indices.append(len(riv_data) - 1)
|
|
353
|
+
|
|
354
|
+
# Populate SW network object attributes
|
|
355
|
+
if target_obj is not None:
|
|
356
|
+
target_obj.gw_cell_ids.extend(cids)
|
|
357
|
+
target_obj.gw_conductances.extend(conds)
|
|
358
|
+
target_obj.gw_bottoms.extend(bots)
|
|
359
|
+
target_obj.gw_heads.extend([float(init_stage)] * len(cids))
|
|
360
|
+
target_obj.riv_row_indices.extend(row_indices)
|
|
361
|
+
if isinstance(target_obj, Reach):
|
|
362
|
+
target_obj.gw_fractions.extend(fractions)
|
|
363
|
+
elif isinstance(target_obj, Node):
|
|
364
|
+
target_obj.bed_elevation = min(target_obj.gw_bottoms)
|
|
365
|
+
|
|
366
|
+
sw_network.validate()
|
|
367
|
+
|
|
368
|
+
riv = flopy.mf6.ModflowGwfriv(
|
|
369
|
+
gwf,
|
|
370
|
+
pname=riv_pack_name,
|
|
371
|
+
maxbound=len(riv_data),
|
|
372
|
+
stress_period_data={per: riv_data for per in range(nper)},
|
|
373
|
+
)
|
|
374
|
+
|
|
375
|
+
return riv
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def create_test_model(
|
|
379
|
+
sim_dir: str | Path = "sim_output",
|
|
380
|
+
sim_name: str = "mfsim",
|
|
381
|
+
model_name: str = "gwf_1",
|
|
382
|
+
riv_pack_name: str = "riv_1",
|
|
383
|
+
nrow: int = 20,
|
|
384
|
+
ncol: int = 20,
|
|
385
|
+
nlay: int = 1,
|
|
386
|
+
delr: float = 100.0,
|
|
387
|
+
delc: float = 100.0,
|
|
388
|
+
top: float = 10.0,
|
|
389
|
+
botm: float = -10.0,
|
|
390
|
+
k11: float = 10.0,
|
|
391
|
+
recharge: float = 0.0005,
|
|
392
|
+
nper: int = 1,
|
|
393
|
+
recharge_series: list[float] | None = None,
|
|
394
|
+
sy: float = 0.15,
|
|
395
|
+
ss: float | None = None,
|
|
396
|
+
gdf_water: gpd.GeoDataFrame | None = None,
|
|
397
|
+
) -> tuple[flopy.mf6.MFSimulation, dict[str, dict[str, Any]], gpd.GeoDataFrame]:
|
|
398
|
+
"""
|
|
399
|
+
Generate FloPy simulation files with spatial intersection mapping.
|
|
400
|
+
"""
|
|
401
|
+
sim_dir = Path(sim_dir)
|
|
402
|
+
sim_dir.mkdir(parents=True, exist_ok=True)
|
|
403
|
+
|
|
404
|
+
if gdf_water is None:
|
|
405
|
+
gdf_water = create_natural_geometries()
|
|
406
|
+
|
|
407
|
+
# Ensure nodes (lake/pond) are registered before reaches to match _get_providers order 100%
|
|
408
|
+
is_node = gdf_water["feature_type"].isin(
|
|
409
|
+
["lake", "pond", "upper_lake", "lower_pond", "wetland"]
|
|
410
|
+
)
|
|
411
|
+
node_df = gdf_water[is_node]
|
|
412
|
+
reach_df = gdf_water[~is_node]
|
|
413
|
+
gdf_water = pd.concat([node_df, reach_df], ignore_index=True)
|
|
414
|
+
|
|
415
|
+
sim = flopy.mf6.MFSimulation(
|
|
416
|
+
sim_name=sim_name,
|
|
417
|
+
version="mf6",
|
|
418
|
+
exe_name="mf6",
|
|
419
|
+
sim_ws=str(sim_dir),
|
|
420
|
+
)
|
|
421
|
+
|
|
422
|
+
perioddata = [(1.0, 1, 1.0)] * nper
|
|
423
|
+
flopy.mf6.ModflowTdis(
|
|
424
|
+
sim,
|
|
425
|
+
time_units="DAYS",
|
|
426
|
+
nper=nper,
|
|
427
|
+
perioddata=perioddata,
|
|
428
|
+
)
|
|
429
|
+
|
|
430
|
+
flopy.mf6.ModflowIms(
|
|
431
|
+
sim,
|
|
432
|
+
pname="ims",
|
|
433
|
+
complexity="MODERATE",
|
|
434
|
+
outer_maximum=200,
|
|
435
|
+
inner_maximum=100,
|
|
436
|
+
)
|
|
437
|
+
|
|
438
|
+
gwf = flopy.mf6.ModflowGwf(
|
|
439
|
+
sim,
|
|
440
|
+
modelname=model_name,
|
|
441
|
+
save_flows=True,
|
|
442
|
+
)
|
|
443
|
+
|
|
444
|
+
flopy.mf6.ModflowGwfdis(
|
|
445
|
+
gwf,
|
|
446
|
+
nlay=nlay,
|
|
447
|
+
nrow=nrow,
|
|
448
|
+
ncol=ncol,
|
|
449
|
+
delr=delr,
|
|
450
|
+
delc=delc,
|
|
451
|
+
top=top,
|
|
452
|
+
botm=botm,
|
|
453
|
+
)
|
|
454
|
+
|
|
455
|
+
flopy.mf6.ModflowGwfnpf(
|
|
456
|
+
gwf,
|
|
457
|
+
icelltype=0,
|
|
458
|
+
k=k11,
|
|
459
|
+
)
|
|
460
|
+
|
|
461
|
+
if nper > 1:
|
|
462
|
+
thickness = float(top - botm)
|
|
463
|
+
effective_ss = float(ss) if ss is not None else float(sy / thickness)
|
|
464
|
+
|
|
465
|
+
flopy.mf6.ModflowGwfsto(
|
|
466
|
+
gwf,
|
|
467
|
+
sy=sy,
|
|
468
|
+
ss=effective_ss,
|
|
469
|
+
iconvert=0,
|
|
470
|
+
steady_state={0: True},
|
|
471
|
+
transient={per: True for per in range(1, nper)},
|
|
472
|
+
)
|
|
473
|
+
|
|
474
|
+
flopy.mf6.ModflowGwfic(
|
|
475
|
+
gwf,
|
|
476
|
+
strt=6.0,
|
|
477
|
+
)
|
|
478
|
+
|
|
479
|
+
# Configure Recharge
|
|
480
|
+
if recharge_series is not None:
|
|
481
|
+
rch_period_data = {
|
|
482
|
+
per: [float(recharge_series[per])] for per in range(len(recharge_series))
|
|
483
|
+
}
|
|
484
|
+
flopy.mf6.ModflowGwfrcha(
|
|
485
|
+
gwf,
|
|
486
|
+
recharge=rch_period_data,
|
|
487
|
+
)
|
|
488
|
+
elif recharge > 0:
|
|
489
|
+
flopy.mf6.ModflowGwfrcha(
|
|
490
|
+
gwf,
|
|
491
|
+
recharge=recharge,
|
|
492
|
+
)
|
|
493
|
+
|
|
494
|
+
# Perform GIS spatial intersection with FloPy grid dynamically across all features
|
|
495
|
+
ix = GridIntersect(gwf.modelgrid)
|
|
496
|
+
riv_data = []
|
|
497
|
+
cell_mapping = {}
|
|
498
|
+
|
|
499
|
+
for _, row in gdf_water.iterrows():
|
|
500
|
+
name = str(row["name"])
|
|
501
|
+
f_type = str(row["feature_type"])
|
|
502
|
+
c_bed = float(row["c_bed"])
|
|
503
|
+
w_reach = float(row.get("reach_width", 0.0))
|
|
504
|
+
init_stage = float(row["initial_stage"])
|
|
505
|
+
bed_bot = float(row["bed_bottom"])
|
|
506
|
+
|
|
507
|
+
res = ix.intersect(row["geometry"], geo_dataframe=False)
|
|
508
|
+
if len(res) > 0:
|
|
509
|
+
cids = [r * ncol + c for r, c in res["cellids"]]
|
|
510
|
+
if f_type == "reach":
|
|
511
|
+
lengths = list(res["lengths"])
|
|
512
|
+
areas = [float(l * w_reach) for l in lengths]
|
|
513
|
+
else:
|
|
514
|
+
areas = list(res["areas"])
|
|
515
|
+
|
|
516
|
+
conds = [float(a / c_bed) for a in areas]
|
|
517
|
+
bots = [bed_bot] * len(cids)
|
|
518
|
+
|
|
519
|
+
for cid, cond, bot in zip(cids, conds, bots):
|
|
520
|
+
r, c = divmod(cid, ncol)
|
|
521
|
+
riv_data.append(((0, r, c), init_stage, cond, bot))
|
|
522
|
+
|
|
523
|
+
cell_mapping[name] = {
|
|
524
|
+
"cell_ids": cids,
|
|
525
|
+
"conductances": conds,
|
|
526
|
+
"bottoms": bots,
|
|
527
|
+
"areas": areas,
|
|
528
|
+
}
|
|
529
|
+
else:
|
|
530
|
+
cell_mapping[name] = {
|
|
531
|
+
"cell_ids": [],
|
|
532
|
+
"conductances": [],
|
|
533
|
+
"bottoms": [],
|
|
534
|
+
"areas": [],
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
# Backward compatibility aliases for default model
|
|
538
|
+
if "upper_lake" in cell_mapping and "lake1" not in cell_mapping:
|
|
539
|
+
cell_mapping["lake1"] = cell_mapping["upper_lake"]
|
|
540
|
+
if "lower_pond" in cell_mapping and "pond" not in cell_mapping:
|
|
541
|
+
cell_mapping["pond"] = cell_mapping["lower_pond"]
|
|
542
|
+
|
|
543
|
+
flopy.mf6.ModflowGwfriv(
|
|
544
|
+
gwf,
|
|
545
|
+
pname=riv_pack_name,
|
|
546
|
+
maxbound=len(riv_data),
|
|
547
|
+
stress_period_data={per: riv_data for per in range(nper)},
|
|
548
|
+
)
|
|
549
|
+
|
|
550
|
+
flopy.mf6.ModflowGwfoc(
|
|
551
|
+
gwf,
|
|
552
|
+
head_filerecord=f"{model_name}.hds",
|
|
553
|
+
budget_filerecord=f"{model_name}.cbc",
|
|
554
|
+
saverecord=[("HEAD", "ALL"), ("BUDGET", "ALL")],
|
|
555
|
+
)
|
|
556
|
+
|
|
557
|
+
sim.write_simulation()
|
|
558
|
+
return sim, cell_mapping, gdf_water
|