Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions nlmod/gwf/lake.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,11 @@ def lake_from_gdf(
lakeno : with the number of the lake
strt : with the starting head of the lake
clake : with the bed resistance of the lake
A single lake may have multiple elements (polygon pieces) in one cell, e.g.
straight from nlmod.grid.gdf_to_grid. Pieces are combined into one lake-GWF
connection per cell with an area-weighted bed resistance (see
_aggregate_connections_per_cell), like nlmod.gwf.surface_water.aggregate
already does for RIV/DRN celldata.
optional columns are 'STATUS', 'STAGE', 'RAINFALL', 'EVAPORATION',
'RUNOFF', 'INFLOW', 'WITHDRAWAL', 'AUXILIARY', 'RATE', 'INVERT',
'WIDTH', 'SLOPE', 'ROUGH'. These columns should contain the name
Expand Down Expand Up @@ -173,6 +178,8 @@ def lake_from_gdf(
gdf = add_lakeno_to_gdf(gdf, boundname_column)

for lakeno, lake_gdf in gdf.groupby("lakeno"):
if lake_gdf.index.duplicated().any():
lake_gdf = _aggregate_connections_per_cell(lake_gdf, ds)
nlakeconn = lake_gdf.shape[0]
if "strt" in lake_gdf:
strt = _get_and_check_single_value(lake_gdf, "strt")
Expand Down Expand Up @@ -413,10 +420,39 @@ def lake_from_gdf(
return lak


def _aggregate_connections_per_cell(lake_gdf, ds):
"""Combine multiple pieces of one lake within a grid cell into one connection.

A lake polygon commonly intersects a grid cell in more than one piece (e.g.
after nlmod.grid.gdf_to_grid). MODFLOW 6 applies each VERTICAL lake-GWF
connection over the full cell area, so per-piece rows would multiply-count the
exchange. Each piece therefore contributes conductance for its own area: the
combined bed resistance is clake = cell_area / sum(piece_area / clake), so
that the connection conductance cell_area / clake equals the summed piece
conductance — the same area-weighted aggregation nlmod.gwf.surface_water
.aggregate applies to RIV/DRN celldata. All other columns take the value of
the first piece per cell.
"""
if "geometry" not in lake_gdf.columns or lake_gdf.geometry.isna().any():
raise ValueError(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I had a bit of trouble reading the error message. Is this a good alternative:

"found multiple elements of one lake in a single cell; provide polygon "
"geometries of the lake to aggregate these elements"

"found multiple elements of one lake in a single cell; provide polygon "
"geometries of the lake to aggregate these elements"
)
cond = (lake_gdf.geometry.area / lake_gdf["clake"]).groupby(level=0).sum()
agg = lake_gdf.groupby(level=0).first()
agg["clake"] = ds["area"].data[agg.index] / cond
return agg


def _get_and_check_single_value(lake_gdf, column):
value = lake_gdf[column].iloc[0]
if lake_gdf[column].isna().all() or lake_gdf[column].eq("").all():
return value
if pd.api.types.is_numeric_dtype(lake_gdf[column]):
# aggregated inputs (e.g. area-weighted stages) carry float-level noise
if not np.allclose(lake_gdf[column], value, rtol=1e-8, atol=0.0):
raise AssertionError(f"A single lake should have a single {column}")
return value
if not (lake_gdf[column] == value).all():
raise (AssertionError(f"A single lake should have a single {column}"))
return value
Expand Down
81 changes: 81 additions & 0 deletions tests/test_013_surface_water.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
import geopandas as gpd
import numpy as np
import pandas as pd
import pytest
import util
from shapely.geometry import box

import nlmod

Expand Down Expand Up @@ -133,3 +135,82 @@ def test_aggregate():
assert not celldata.isna().any(axis=None)
riv_spd = nlmod.gwf.surface_water.build_spd(celldata, "RIV", ds)
flopy.mf6.ModflowGwfriv(gwf, stress_period_data=riv_spd)


def _get_lake_model(model_name):
model_ws = os.path.join(util.get_model_data_dir(), model_name)
ds = nlmod.get_ds(
[170000, 171000, 550000, 551000], model_ws=model_ws, model_name=model_name
)
ds = nlmod.time.set_ds_time(ds, time=[1], start=pd.Timestamp.today())
ds = nlmod.dims.refine(ds)

sim = nlmod.sim.sim(ds)
nlmod.sim.tdis(ds, sim)
nlmod.sim.ims(sim)
gwf = nlmod.gwf.gwf(ds, sim)
nlmod.gwf.dis(ds, gwf)
return ds, gwf


def test_lake_from_gdf_aggregates_pieces_per_cell():
"""Multiple pieces of a lake in one cell merge into a single connection.

A lake commonly intersects a grid cell in multiple polygon pieces (e.g. after
nlmod.grid.gdf_to_grid). Each piece should contribute conductance for its own
area, and the pieces should collapse to a single lake-GWF connection per cell,
like nlmod.gwf.surface_water.aggregate already does for RIV/DRN celldata.
"""
ds, gwf = _get_lake_model("lp")

# lake_0 covers cell 14 with two pieces (6000 m2 at clake=10 and 2000 m2 at
# clake=20) and cell 15 with one piece (10000 m2, the full cell, at clake=10)
gdf_lake = gpd.GeoDataFrame(
{
"name": ["lake_0", "lake_0", "lake_0"],
"strt": [1.0, 1.0, 1.0],
"clake": [10.0, 20.0, 10.0],
},
geometry=[
box(0, 0, 100, 60),
box(0, 60, 50, 100),
box(100, 0, 200, 100),
],
index=[14, 14, 15],
)

lak = nlmod.gwf.lake_from_gdf(gwf, gdf_lake, ds, boundname_column="name")

conns = lak.connectiondata.array
assert len(conns) == 2, "pieces within a cell should merge to one connection"
bedleak = {
cellid[-1]: bl
for (_, _, cellid, *_), bl in zip(
conns.tolist(), conns["bedleak"], strict=False
)
}
# bedleak * cell_area == sum(piece_area / clake), cell area is 10000 m2
assert bedleak[14] == pytest.approx((6000.0 / 10.0 + 2000.0 / 20.0) / 10000.0)
assert bedleak[15] == pytest.approx((10000.0 / 10.0) / 10000.0)
assert lak.packagedata.array[0][2] == 2 # nlakeconn counts cells, not pieces


def test_lake_from_gdf_accepts_floating_point_strt_noise():
"""Float-level noise in per-cell strt values is accepted as a single value.

Aggregated inputs (e.g. area-weighted stages per cell) carry float-level noise;
a single-value check with exact equality rejects them for no physical reason.
"""
ds, gwf = _get_lake_model("ln")

gdf_lake = gpd.GeoDataFrame(
{
"name": ["lake_0", "lake_0"],
"strt": [1.0, 1.0 + 1e-12],
"clake": [10.0, 10.0],
},
index=[14, 15],
)

lak = nlmod.gwf.lake_from_gdf(gwf, gdf_lake, ds, boundname_column="name")
assert lak.packagedata.array[0][1] == pytest.approx(1.0)
Loading