Skip to content
Open
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
91 changes: 91 additions & 0 deletions autotest/test_cellbudgetfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -1299,3 +1299,94 @@ def test_cellbudgetfile_write_preserves_aux_vars(dis_sim, function_tmpdir):
assert np.allclose(spdis_orig[i][field], spdis_rewritten[i][field]), (
f"Field {field} mismatch at timestep {i}"
)


def test_match_names_prefers_exact():
from flopy.utils.binaryfile import _match_name, _match_names

texts = [
b" FLOW-JA-FACE",
b" UZF-GWRCH",
b" RCHA",
b" RCH",
]
# exact match wins over earlier substring matches, any case/padding
for name in ["RCH", "rch", " RCH ", b"RCH", "RCH".rjust(16)]:
assert _match_names(name, texts) == [b" RCH"]
assert _match_name("rcha", texts) == b" RCHA"
# without an exact match, fall back to substring matching
assert _match_name("flow", texts) == b" FLOW-JA-FACE"
assert _match_names("gwrc", texts) == [b" UZF-GWRCH"]
assert _match_name("nope", texts) is None

paknams = [b"RCH_10 ", b"RCH_1 "]
assert _match_name("rch_1", paknams) == b"RCH_1 "
assert _match_name("rch_", paknams) == b"RCH_10 "


@pytest.mark.requires_exe("mf6")
def test_cellbudgetfile_text_paknam_prefer_exact_match(function_tmpdir):
from flopy.mf6 import (
ModflowGwf,
ModflowGwfchd,
ModflowGwfdis,
ModflowGwfic,
ModflowGwfnpf,
ModflowGwfoc,
ModflowGwfrch,
ModflowGwfrcha,
ModflowIms,
ModflowTdis,
)

name = "rchmix"
sim = MFSimulation(sim_name=name, sim_ws=function_tmpdir, exe_name="mf6")
ModflowTdis(sim, nper=1)
ModflowIms(sim)
gwf = ModflowGwf(sim, modelname=name, save_flows=True)
ModflowGwfdis(gwf, nlay=1, nrow=3, ncol=3, top=10.0, botm=0.0)
ModflowGwfnpf(gwf)
ModflowGwfic(gwf, strt=5.0)
ModflowGwfchd(gwf, stress_period_data=[((0, 0, 0), 5.0)])
# array-based recharge (budget text RCHA) listed before the
# list-based recharge packages (budget text RCH), and a package
# name (RCH_10) containing another (RCH_1) listed first
ModflowGwfrcha(gwf, recharge=1e-3, pname="rcha_0", filename=f"{name}.rcha")
ModflowGwfrch(
gwf,
stress_period_data=[((0, 2, 2), 2.0)],
pname="rch_10",
filename=f"{name}_10.rch",
)
ModflowGwfrch(
gwf,
stress_period_data=[((0, 1, 1), 1.0)],
pname="rch_1",
filename=f"{name}_1.rch",
)
ModflowGwfoc(gwf, budget_filerecord=f"{name}.cbc", saverecord=[("BUDGET", "ALL")])
sim.write_simulation(silent=True)
success, _ = sim.run_simulation(silent=True)
assert success

cbc = gwf.output.budget()
totim = cbc.get_times()[-1]

rch = cbc.get_data(totim=totim, text="rch")
assert len(rch) == 2
assert all(r.dtype.names == ("node", "node2", "q") for r in rch)
assert sorted(float(r["q"][0]) for r in rch) == [1.0, 2.0]

rcha = cbc.get_data(totim=totim, text="rcha")
assert len(rcha) == 1

rch_1 = cbc.get_data(totim=totim, text="rch", paknam2="rch_1")
assert len(rch_1) == 1 and float(rch_1[0]["q"][0]) == 1.0
rch_10 = cbc.get_data(totim=totim, text="rch", paknam2="rch_10")
assert len(rch_10) == 1 and float(rch_10[0]["q"][0]) == 2.0

# export with text="RCH" should not pick up RCHA records
out = function_tmpdir / "rch_only.cbc"
cbc.export(out, text="RCH")
exported = CellBudgetFile(out)
assert [t.strip() for t in exported.textlist] == [b"RCH"]
71 changes: 49 additions & 22 deletions flopy/utils/binaryfile/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,52 @@
from ..gridutil import get_lni


def _match_names(name, names):
"""
Find the names in a binary file matching a user-specified name.

Matching is case-insensitive and ignores surrounding whitespace. An exact
match is preferred: if one exists, only it is returned. Otherwise, all
names containing the given name as a substring are returned, in order.
This keeps abbreviations like ``"spdis"`` working while making sure that,
for example, ``"RCH"`` selects ``RCH`` records and not ``RCHA`` or
``UZF-GWRCH`` records.

Parameters
----------
name : str or bytes
The name to look for.
names : sequence of bytes
The names in the file (e.g. budget text or package names).

Returns
-------
list of bytes
The matching names, as they appear in ``names``.
"""
if isinstance(name, bytes):
name = name.decode()
key = name.strip().upper()
exact = [n for n in names if n.decode().strip().upper() == key]
if exact:
return exact
return [n for n in names if key in n.decode().strip().upper()]


def _match_name(name, names):
"""
Find the name in a binary file best matching a user-specified name,
preferring an exact match over a substring match. See `_match_names`.

Returns
-------
bytes or None
The best matching name, or None if there is no match.
"""
matches = _match_names(name, names)
return matches[0] if matches else None


def _pad_text_to_16(text):
"""
Pad text to exactly 16 bytes, left-justified (MODFLOW standard).
Expand Down Expand Up @@ -2668,14 +2714,7 @@ def _find_text(self, text):
# check and make sure that text is in file
text16 = None
if text is not None:
if isinstance(text, bytes):
ttext = text.decode()
else:
ttext = text
for t in self.textlist:
if ttext.upper() in t.decode():
text16 = t
break
text16 = _match_name(text, self.textlist)
if text16 is None:
raise ValueError("The specified text string is not in the budget file")
return text16
Expand All @@ -2688,14 +2727,7 @@ def _find_paknam(self, paknam, to=False):
# check and make sure that text is in file
paknam16 = None
if paknam is not None:
if isinstance(paknam, bytes):
tpaknam = paknam.decode()
else:
tpaknam = paknam
for t in self._unique_package_names(to):
if tpaknam.upper() in t.decode():
paknam16 = t
break
paknam16 = _match_name(paknam, self._unique_package_names(to))
if paknam16 is None:
raise ValueError(
"The specified package name string is not in the budget file"
Expand Down Expand Up @@ -3702,12 +3734,7 @@ def export(

text_mapping = {}
for txt in textlist:
txt_str = txt.decode().strip() if isinstance(txt, bytes) else txt.strip()
txt_upper = txt_str.upper()
matching_records = [
t for t in self.textlist if txt_upper in t.decode().strip().upper()
]
text_mapping[txt] = matching_records
text_mapping[txt] = _match_names(txt, self.textlist)

nlay = self.nlay if self.nlay > 0 else None
nrow = self.nrow if self.nrow > 0 else None
Expand Down
Loading