From 2449ea36af20b73f97e466af36ec6d655e44f3de Mon Sep 17 00:00:00 2001 From: Bas des Tombe Date: Wed, 22 Jul 2026 09:42:58 +0200 Subject: [PATCH 1/2] Aggregate lake pieces per cell in lake_from_gdf; tolerate float-noise strt A lake commonly intersects a grid cell in multiple polygon pieces (e.g. straight from nlmod.grid.gdf_to_grid). lake_from_gdf turned each row into its own VERTICAL connection over the full cell area with bedleak = 1/clake, multiply-counting the lake-aquifer exchange. Pieces of one lake within a cell now collapse to a single connection with clake = cell_area / sum(piece_area / clake), the same area-weighted aggregation nlmod.gwf.surface_water.aggregate applies to RIV and DRN celldata. Numeric per-lake settings are now compared with np.allclose(rtol=1e-8) so aggregated inputs carrying float-level noise (e.g. area-weighted stages) are not rejected by the single-value check. Both regression tests fail on unchanged dev: three connections with bedleak 0.1 instead of two with area-weighted bedleak, and an AssertionError on a 1e-12 strt difference. --- nlmod/gwf/lake.py | 36 +++++++++++++++ tests/test_013_surface_water.py | 81 +++++++++++++++++++++++++++++++++ 2 files changed, 117 insertions(+) diff --git a/nlmod/gwf/lake.py b/nlmod/gwf/lake.py index c0258819..706d6384 100644 --- a/nlmod/gwf/lake.py +++ b/nlmod/gwf/lake.py @@ -62,6 +62,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 lake may have multiple rows (polygon pieces) per cellid, 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 @@ -158,6 +163,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") @@ -349,10 +356,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( + "found multiple rows per cell for one lake; provide polygon " + "geometries so the pieces can be area-weighted into one connection" + ) + 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 diff --git a/tests/test_013_surface_water.py b/tests/test_013_surface_water.py index 43f01b94..f8577d64 100644 --- a/tests/test_013_surface_water.py +++ b/tests/test_013_surface_water.py @@ -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 @@ -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) From 07d6d528d49cf5f550654915f62aa10e4a87b707 Mon Sep 17 00:00:00 2001 From: Bas des Tombe Date: Thu, 24 Sep 2026 16:50:24 +0200 Subject: [PATCH 2/2] Apply review suggestions: clearer lake piece wording and error message --- nlmod/gwf/lake.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/nlmod/gwf/lake.py b/nlmod/gwf/lake.py index 78925407..88fbc4d2 100644 --- a/nlmod/gwf/lake.py +++ b/nlmod/gwf/lake.py @@ -71,8 +71,8 @@ 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 lake may have multiple rows (polygon pieces) per cellid, e.g. straight - from nlmod.grid.gdf_to_grid. Pieces are combined into one lake-GWF + 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. @@ -435,8 +435,8 @@ def _aggregate_connections_per_cell(lake_gdf, ds): """ if "geometry" not in lake_gdf.columns or lake_gdf.geometry.isna().any(): raise ValueError( - "found multiple rows per cell for one lake; provide polygon " - "geometries so the pieces can be area-weighted into one connection" + "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()