From cb5e3a094dc063281a350d1336a4b698151265f2 Mon Sep 17 00:00:00 2001 From: wpbonelli Date: Mon, 16 Nov 2026 12:54:30 -0800 Subject: [PATCH] fix(binaryfile): skip non-matching records when indexing layer files BinaryLayerFile._build_index appended every header to recordarray but, for records whose text did not match (e.g. DRAWDOWN records in a file read as HEAD), skipped neither the data nor the iposarray entry. The next header was then read from the middle of the data block, so files mixing record types (as MODFLOW-2005 output control allows when heads and drawdown share a unit) failed to load or were indexed incorrectly. Skip non-matching records' data, index only matching headers, and raise a clear error when no record matches the requested text. Co-Authored-By: Claude Opus 5.5 --- autotest/test_binaryfile.py | 71 ++++++++++++++++++++++++++++++ flopy/utils/binaryfile/__init__.py | 27 +++++++----- 2 files changed, 88 insertions(+), 10 deletions(-) diff --git a/autotest/test_binaryfile.py b/autotest/test_binaryfile.py index c2616482c..7dbcade75 100644 --- a/autotest/test_binaryfile.py +++ b/autotest/test_binaryfile.py @@ -145,6 +145,77 @@ def test_headfile_build_index(example_data_path): ) +@pytest.mark.parametrize("precision", ["single", "double"]) +def test_headfile_build_index_mixed_text(function_tmpdir, precision): + # MODFLOW-2005 output control allows heads and drawdown to be saved + # to the same unit; each reader should only index its own records + nlay, nrow, ncol = 2, 3, 4 + dtype = np.float32 if precision == "single" else np.float64 + fpth = function_tmpdir / "mixed.hds" + + def value(text, kper, ilay): + return (100.0 if text == "HEAD" else -1.0) * kper + ilay + + with open(fpth, "wb") as f: + for kper in (1, 2, 3): + for text in ("HEAD", "DRAWDOWN"): + for ilay in range(1, nlay + 1): + header = BinaryHeader.create( + bintype="head", + precision=precision, + text=text, + kstp=1, + kper=kper, + pertim=1.0, + totim=float(kper), + ncol=ncol, + nrow=nrow, + ilay=ilay, + ) + header.tofile(f) + np.full((nrow, ncol), value(text, kper, ilay), dtype).tofile(f) + + for text in ("HEAD", "DRAWDOWN"): + with HeadFile(fpth, text=text.lower(), precision=precision) as hds: + assert len(hds) == 3 * nlay + assert hds.get_times() == [1.0, 2.0, 3.0] + assert hds.get_kstpkper() == [(0, 0), (0, 1), (0, 2)] + assert hds.nlay == nlay + assert all(t.strip() == text.encode() for t in hds.recordarray["text"]) + assert list(hds.headers["text"]) == [text] * (3 * nlay) + for kper in (1, 2, 3): + data = hds.get_data(totim=float(kper)) + assert data.shape == (nlay, nrow, ncol) + for ilay in range(1, nlay + 1): + np.testing.assert_allclose(data[ilay - 1], value(text, kper, ilay)) + ts = hds.get_ts((1, 2, 3)) + np.testing.assert_allclose(ts[:, 0], [1.0, 2.0, 3.0]) + np.testing.assert_allclose( + ts[:, 1], [value(text, kper, 2) for kper in (1, 2, 3)] + ) + + +def test_headfile_build_index_no_matching_text(function_tmpdir): + fpth = function_tmpdir / "drawdown_only.hds" + with open(fpth, "wb") as f: + header = BinaryHeader.create( + bintype="head", + precision="double", + text="DRAWDOWN", + kstp=1, + kper=1, + pertim=1.0, + totim=1.0, + ncol=4, + nrow=3, + ilay=1, + ) + header.tofile(f) + np.zeros((3, 4), np.float64).tofile(f) + with pytest.raises(ValueError, match="No records with text 'head'"): + HeadFile(fpth, precision="double") + + def test_concentration_build_index(example_data_path): # test low-level BinaryLayerFile._build_index() method with UCN file pth = example_data_path / "mt3d_test/mf2005mt3d/P07/MT3D001.UCN" diff --git a/flopy/utils/binaryfile/__init__.py b/flopy/utils/binaryfile/__init__.py index fc349eeb5..9a29be348 100644 --- a/flopy/utils/binaryfile/__init__.py +++ b/flopy/utils/binaryfile/__init__.py @@ -435,24 +435,31 @@ def _build_index(self): ipos = 0 while ipos < self.totalbytes: header = self._get_header() - self.recordarray.append(header) + databytes = self.get_databytes(header) if self.text.upper() not in header["text"]: + # the file may contain other record types (e.g. HEAD and + # DRAWDOWN saved to the same unit), skip over their data + self.file.seek(databytes, 1) + ipos = self.file.tell() continue - if ipos == 0: - self.times.append(header["totim"]) + self.recordarray.append(header) + totim = header["totim"] + if not self.times or totim != self.times[-1]: + self.times.append(totim) self.kstpkper.append((header["kstp"], header["kper"])) - else: - totim = header["totim"] - if totim != self.times[-1]: - self.times.append(totim) - self.kstpkper.append((header["kstp"], header["kper"])) ipos = self.file.tell() self.iposarray.append(ipos) - databytes = self.get_databytes(header) self.file.seek(databytes, 1) ipos = self.file.tell() - # self.recordarray contains a recordarray of all the headers. + if len(self.recordarray) == 0: + self.file.close() + raise ValueError( + f"No records with text '{self.text.decode().strip()}' " + f"found in {self.filename}" + ) + + # self.recordarray contains the headers of all records matching text. self.recordarray = np.array(self.recordarray, dtype=self.header_dtype) self.iposarray = np.array(self.iposarray, dtype=np.int64) self.nlay = np.max(self.recordarray["ilay"])