From 7ac4b60e84dcbcf5f95d3a5962dd639b3bfb2a74 Mon Sep 17 00:00:00 2001 From: wpbonelli Date: Mon, 16 Nov 2026 12:32:35 -0800 Subject: [PATCH 1/4] fix(binaryfile): export all records in CellBudgetFile.export() export() wrote only the first record per budget text per time step, so budget files with multiple packages of the same type (e.g. several RCH packages) lost all but the first package's records. Records were also written grouped by the requested text order rather than in file order, and imeth was inferred from the data type rather than taken from the header. Iterate over records in file order, as reverse() does, and write each record from its own header and data. Copy text and package names from the header verbatim, preserving their justification. Raise NotImplementedError for imeth values other than 0, 1 and 6 instead of writing them incorrectly. Co-Authored-By: Claude Opus 5.5 --- autotest/test_cellbudgetfile.py | 132 ++++++++++++++++ flopy/utils/binaryfile/__init__.py | 240 +++++++++++++---------------- 2 files changed, 242 insertions(+), 130 deletions(-) diff --git a/autotest/test_cellbudgetfile.py b/autotest/test_cellbudgetfile.py index e01d598f0..3f77bc8f0 100644 --- a/autotest/test_cellbudgetfile.py +++ b/autotest/test_cellbudgetfile.py @@ -1299,3 +1299,135 @@ 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}" ) + + +@pytest.fixture +def multi_rch_sim(function_tmpdir): + """ + MF6 model with two list-based RCH packages, so the budget file + has two RCH records per time step, and two stress periods. + """ + from flopy.mf6 import ( + ModflowGwf, + ModflowGwfchd, + ModflowGwfdis, + ModflowGwfic, + ModflowGwfnpf, + ModflowGwfoc, + ModflowGwfrch, + ModflowIms, + ModflowTdis, + ) + + name = "multirch" + sim = MFSimulation(sim_name=name, sim_ws=function_tmpdir, exe_name="mf6") + ModflowTdis(sim, nper=2, perioddata=[(1.0, 1, 1.0), (1.0, 1, 1.0)]) + 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, save_specific_discharge=True) + ModflowGwfic(gwf, strt=5.0) + ModflowGwfchd(gwf, stress_period_data=[((0, 0, 0), 5.0)]) + ModflowGwfrch( + gwf, + stress_period_data={0: [((0, 2, 2), 2.0)], 1: [((0, 2, 2), 4.0)]}, + pname="rch_10", + filename=f"{name}_10.rch", + ) + ModflowGwfrch( + gwf, + stress_period_data={0: [((0, 1, 1), 1.0)], 1: [((0, 1, 1), 3.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 + return sim + + +def _assert_records_equal(cbc, exported, idx_orig, idx_exported=None): + if idx_exported is None: + idx_exported = idx_orig + fields = ["kstp", "kper", "text", "imeth", "paknam2"] + orig_ra = cbc.recordarray[idx_orig] + exp_ra = exported.recordarray[idx_exported] + assert len(orig_ra) == len(exp_ra) + for field in fields: + assert np.array_equal(orig_ra[field], exp_ra[field]), field + for i, j in zip(idx_orig, idx_exported): + a = cbc.get_data(idx=int(i))[0] + b = exported.get_data(idx=int(j))[0] + if a.dtype.names: + assert a.dtype.names == b.dtype.names + for name in a.dtype.names: + assert np.allclose(a[name], b[name]), (i, name) + else: + assert np.allclose(a, b), i + + +@pytest.mark.requires_exe("mf6") +def test_cellbudgetfile_export_multiple_packages(multi_rch_sim, function_tmpdir): + cbc = multi_rch_sim.get_model().output.budget() + rch = cbc.get_data(text="RCH") + assert len(rch) == 4 # 2 packages x 2 stress periods + + out = function_tmpdir / "all.cbc" + cbc.export(out) + exported = CellBudgetFile(out) + all_idx = np.arange(len(cbc.recordarray)) + assert len(exported.recordarray) == len(cbc.recordarray) + _assert_records_equal(cbc, exported, all_idx) + assert len(exported.get_data(text="RCH")) == 4 + + # the export should be the same size as the original. it is not + # byte-identical because MF6 right-justifies auxiliary variable names + # (e.g. DATA-SPDIS qx, qy, qz), which flopy strips when reading. + assert out.stat().st_size == os.path.getsize(cbc.filename) + + +@pytest.mark.requires_exe("mf6") +def test_cellbudgetfile_export_multiple_packages_text_subset( + multi_rch_sim, function_tmpdir +): + cbc = multi_rch_sim.get_model().output.budget() + out = function_tmpdir / "rch.cbc" + cbc.export(out, text="RCH") + exported = CellBudgetFile(out) + assert [t.strip() for t in exported.textlist] == [b"RCH"] + assert [p.strip() for p in exported.recordarray["paknam2"]] == [ + b"RCH_10", + b"RCH_1", + b"RCH_10", + b"RCH_1", + ] + rch_idx = np.flatnonzero(cbc.recordarray["text"] == exported.textlist[0]) + _assert_records_equal(cbc, exported, rch_idx, np.arange(len(rch_idx))) + + # text given as a list in a different order than in the file + # should still produce records in file order + out = function_tmpdir / "rch_spdis.cbc" + cbc.export(out, text=["DATA-SPDIS", "RCH"]) + exported = CellBudgetFile(out) + mask = np.isin(cbc.recordarray["text"], exported.textlist) + idx = np.flatnonzero(mask) + assert len(idx) == 6 + _assert_records_equal(cbc, exported, idx, np.arange(len(idx))) + + +@pytest.mark.requires_exe("mf6") +def test_cellbudgetfile_export_multiple_packages_kstpkper_subset( + multi_rch_sim, function_tmpdir +): + cbc = multi_rch_sim.get_model().output.budget() + assert cbc.kstpkper == [(1, 1), (1, 2)] + out = function_tmpdir / "sp2.cbc" + cbc.export(out, kstpkper=[(1, 2)]) + exported = CellBudgetFile(out) + assert exported.kstpkper == [(1, 2)] + idx = np.flatnonzero(cbc.recordarray["kper"] == 2) + _assert_records_equal(cbc, exported, idx, np.arange(len(idx))) + rch = exported.get_data(text="RCH") + assert len(rch) == 2 + assert [float(r["q"][0]) for r in rch] == [4.0, 3.0] diff --git a/flopy/utils/binaryfile/__init__.py b/flopy/utils/binaryfile/__init__.py index fc349eeb5..eeb54ec54 100644 --- a/flopy/utils/binaryfile/__init__.py +++ b/flopy/utils/binaryfile/__init__.py @@ -3698,16 +3698,17 @@ def export( ] ) - sorted_kstpkper = sorted(kstpkper, key=lambda x: (int(x[0]), int(x[1]))) - - text_mapping = {} + # budget text names in the file selected for export + selected_texts = set() for txt in textlist: txt_str = txt.decode().strip() if isinstance(txt, bytes) else txt.strip() txt_upper = txt_str.upper() - matching_records = [ + selected_texts.update( t for t in self.textlist if txt_upper in t.decode().strip().upper() - ] - text_mapping[txt] = matching_records + ) + + # time steps selected for export (1-based) + selected_kstpkper = {(int(k), int(p)) for k, p in kstpkper} nlay = self.nlay if self.nlay > 0 else None nrow = self.nrow if self.nrow > 0 else None @@ -3722,142 +3723,121 @@ def export( print(" Grid shape not specified") with open(filename, "wb") as f: - for ksp in sorted_kstpkper: - kstp = int(ksp[0]) - kper = int(ksp[1]) + # iterate over records in file order, so that each record's + # header and data come from the same place, and so that all + # records with the same text (e.g. multiple packages of the + # same type) are exported + for idx, header in enumerate(self.recordarray): + if header["text"] not in selected_texts: + continue + kstp = int(header["kstp"]) + kper = int(header["kper"]) + if (kstp, kper) not in selected_kstpkper: + continue - # get_data() expects 0-based but kstpkper is 1-based - ksp_0based = (kstp - 1, kper - 1) + # take imeth from the record's header. records from + # non-compact files are indexed with imeth 0, which is + # written as the equivalent imeth 1 in the compact output. + imeth = int(header["imeth"]) + if imeth == 0: + imeth = 1 + if imeth not in (1, 6): + raise NotImplementedError( + f"Exporting imeth={imeth} records is not supported, " + "expected imeth=0 or 1 (array) or imeth=6 (list)" + ) + data = self.get_data(idx=idx)[0] + + # copy text as-is to preserve its justification + text_bytes = _pad_text_to_16(header["text"]) + text_str = text_bytes.decode().strip() + delt = float(header["delt"]) + pertim = float(header["pertim"]) + totim = float(header["totim"]) if verbose: - print(f"\n Writing kstp={kstp}, kper={kper}") - - for txt in textlist: - for file_txt in text_mapping[txt]: - data_list = self.get_data(kstpkper=ksp_0based, text=file_txt) - if not data_list: - continue - data = data_list[0] - mask = ( - (self.recordarray["kstp"] == kstp) - & (self.recordarray["kper"] == kper) - & (self.recordarray["text"] == file_txt) + print(f" Writing {text_str}: imeth={imeth}") + + is_flowja = text_str.upper() == "FLOW-JA-FACE" + + # Determine dimensions based on data type + if is_flowja and imeth == 1: + # keep FLOW-JA-FACE flat/size NJA + nja = np.asarray(data).size + ndim1, ndim2, ndim3 = nja, 1, -1 + else: + # Regular budget term: use grid dimensions + if nlay is None or nrow is None or ncol is None: + raise ValueError( + f"Grid dimensions (nlay, nrow, ncol) " + f"required for non-FLOW-JA-FACE " + f"budget term '{text_str}'. " + f"Provided: nlay={nlay}, nrow={nrow}, " + f"ncol={ncol}" ) - records = self.recordarray[mask] - if len(records) == 0: - continue + # negative nlay -> compact format + ndim1, ndim2, ndim3 = ncol, nrow, -nlay - record = records[0] + header1 = np.array( + [(kstp, kper, text_bytes, ndim1, ndim2, ndim3)], + dtype=h1dt, + ) + header1.tofile(f) - if isinstance(data, np.recarray): - imeth = 6 # list - else: - imeth = 1 # array + header2 = np.array([(imeth, delt, pertim, totim)], dtype=h2dt) + header2.tofile(f) - text_str = file_txt.decode().strip() - text_bytes = _pad_text_to_16(text_str) - delt = float(record["delt"]) - pertim = float(record["pertim"]) - totim = float(record["totim"]) + if imeth == 1: + arr = np.asarray(data, dtype=realtype) + # keep FLOW-JA-FACE flat/size NJA. + # reshape other variables to grid. + if is_flowja and arr.ndim != 1: + arr = arr.flatten() + elif arr.ndim == 1: + arr = arr.reshape(nlay, nrow, ncol) - if verbose: - print(f" Writing {text_str}: imeth={imeth}") + arr.tofile(f) + + elif imeth == 6: + # write model and package names + for name in ["modelnam", "paknam", "modelnam2", "paknam2"]: + f.write(_pad_text_to_16(header[name])) - is_flowja = text_str.upper() == "FLOW-JA-FACE" + # write naux and aux var names + standard_fields = {"node", "node2", "q"} + auxtxt = [ + name for name in data.dtype.names if name not in standard_fields + ] + naux = len(auxtxt) + np.array([naux + 1], dtype=np.int32).tofile(f) + for auxname in auxtxt: + f.write(_pad_text_to_16(auxname)) - # Determine dimensions based on data type - if is_flowja and imeth in [0, 1]: - # keep FLOW-JA-FACE flat/size NJA - nja = np.asarray(data).size - ndim1, ndim2, ndim3 = nja, 1, -1 - else: - # Regular budget term: use grid dimensions - if nlay is None or nrow is None or ncol is None: - raise ValueError( - f"Grid dimensions (nlay, nrow, ncol) " - f"required for non-FLOW-JA-FACE " - f"budget term '{text_str}'. " - f"Provided: nlay={nlay}, nrow={nrow}, " - f"ncol={ncol}" - ) - # negative nlay -> compact format - ndim1, ndim2, ndim3 = ncol, nrow, -nlay - - header1 = np.array( - [(kstp, kper, text_bytes, ndim1, ndim2, ndim3)], - dtype=h1dt, + if not (isinstance(data, np.ndarray) and data.dtype.names): + raise ValueError( + "For imeth=6, data must be a numpy recarray " + "with fields: node, node2, q, and optional " + "auxiliary fields" ) - header1.tofile(f) - - header2 = np.array([(imeth, delt, pertim, totim)], dtype=h2dt) - header2.tofile(f) - - if imeth in [0, 1]: - arr = np.asarray(data, dtype=realtype) - # keep FLOW-JA-FACE flat/size NJA. - # reshape other variables to grid. - if is_flowja and arr.ndim != 1: - arr = arr.flatten() - elif arr.ndim == 1: - arr = arr.reshape(nlay, nrow, ncol) - - arr.tofile(f) - - elif imeth == 6: - # write model and package names - modelnam = record["modelnam"].decode().strip() - paknam = record["paknam"].decode().strip() - modelnam2 = record["modelnam2"].decode().strip() - paknam2 = record["paknam2"].decode().strip() - - for name in [modelnam, paknam, modelnam2, paknam2]: - name_bytes = _pad_text_to_16(name) - f.write(name_bytes) - - # write naux and aux var names - standard_fields = {"node", "node2", "q"} - auxtxt = [ - name - for name in data.dtype.names - if name not in standard_fields - ] - naux = len(auxtxt) - np.array([naux + 1], dtype=np.int32).tofile(f) - for auxname in auxtxt: - f.write(_pad_text_to_16(auxname)) - - if not (isinstance(data, np.ndarray) and data.dtype.names): - raise ValueError( - "For imeth=6, data must be a numpy recarray " - "with fields: node, node2, q, and optional " - "auxiliary fields" - ) - - # nrite nlist and list data - nlist = len(data) - np.array([nlist], dtype=np.int32).tofile(f) - dt_list = [ - ("node", np.int32), - ("node2", np.int32), - ("q", realtype), - ] - for auxname in auxtxt: - dt_list.append((auxname, realtype)) - - output_dt = np.dtype(dt_list) - output_data = np.zeros(nlist, dtype=output_dt) - for field in output_dt.names: - if field in data.dtype.names: - output_data[field] = data[field].astype( - output_dt[field] - ) - - output_data.tofile(f) - else: - raise NotImplementedError( - "Expected imeth=1 (array) or imeth=6 (list)" - ) + # write nlist and list data + nlist = len(data) + np.array([nlist], dtype=np.int32).tofile(f) + dt_list = [ + ("node", np.int32), + ("node2", np.int32), + ("q", realtype), + ] + for auxname in auxtxt: + dt_list.append((auxname, realtype)) + + output_dt = np.dtype(dt_list) + output_data = np.zeros(nlist, dtype=output_dt) + for field in output_dt.names: + if field in data.dtype.names: + output_data[field] = data[field].astype(output_dt[field]) + + output_data.tofile(f) if verbose: print(f"\nSuccessfully wrote {filename}") From 1cf37432a369ce7b649d85a0e02af887dc6adf19 Mon Sep 17 00:00:00 2001 From: wpbonelli Date: Mon, 16 Nov 2026 12:55:40 -0800 Subject: [PATCH 2/4] fix(binaryfile): export MF2005 compact imeth 2-5 records The previous commit raised NotImplementedError for imeth values other than 0, 1 and 6, which broke exporting MF2005/MFUSG compact budget files with list-based packages (imeth 2 and 5). These were previously exported as imeth 6, and still are. imeth 3 and 4 records, which were previously written incorrectly, are now expanded to full 3D arrays and written as imeth 1. Co-Authored-By: Claude Opus 5.5 --- autotest/test_cellbudgetfile.py | 91 ++++++++++++++++++++++++++++++ flopy/utils/binaryfile/__init__.py | 31 +++++++--- 2 files changed, 113 insertions(+), 9 deletions(-) diff --git a/autotest/test_cellbudgetfile.py b/autotest/test_cellbudgetfile.py index 3f77bc8f0..f587c222f 100644 --- a/autotest/test_cellbudgetfile.py +++ b/autotest/test_cellbudgetfile.py @@ -1431,3 +1431,94 @@ def test_cellbudgetfile_export_multiple_packages_kstpkper_subset( rch = exported.get_data(text="RCH") assert len(rch) == 2 assert [float(r["q"][0]) for r in rch] == [4.0, 3.0] + + +@pytest.mark.parametrize( + "relpath,kstpkper", + [ + # imeth 1 and 2 (compact list without aux) + ("freyberg_multilayer_transient/freyberg.cbc", [(1, 1), (1, 2)]), + # imeth 5 (compact list with aux) + ("preserve_unitnums/testsfr2.ghb.cbc", None), + ], +) +def test_cellbudgetfile_export_mf2005_compact_lists( + example_data_path, function_tmpdir, relpath, kstpkper +): + """MF2005 compact list records (imeth 2 and 5) are exported as imeth 6.""" + cbc = CellBudgetFile(example_data_path / relpath) + out = function_tmpdir / "out.cbc" + cbc.export(out, kstpkper=kstpkper) + exported = CellBudgetFile(out) + + if kstpkper is None: + kstpkper = cbc.kstpkper + kk = [ + (int(k), int(p)) + for k, p in zip(cbc.recordarray["kstp"], cbc.recordarray["kper"]) + ] + idx = [i for i, ksp in enumerate(kk) if ksp in set(kstpkper)] + assert len(exported.recordarray) == len(idx) + for j, i in enumerate(idx): + hdr = cbc.recordarray[i] + exp_hdr = exported.recordarray[j] + for field in ["kstp", "kper", "text"]: + assert hdr[field] == exp_hdr[field] + a = cbc.get_data(idx=i)[0] + b = exported.get_data(idx=j)[0] + if hdr["imeth"] in (2, 5): + assert exp_hdr["imeth"] == 6 + for name in a.dtype.names: + assert np.allclose(a[name], b[name]), name + else: + assert exp_hdr["imeth"] == hdr["imeth"] + assert np.allclose(a, b) + + +def test_cellbudgetfile_export_imeth_3_4(function_tmpdir): + """imeth 3 and 4 records are expanded to full 3D arrays (imeth 1).""" + nlay, nrow, ncol = 3, 2, 2 + h1 = np.dtype( + [ + ("kstp", "i4"), + ("kper", "i4"), + ("text", "S16"), + ("ncol", "i4"), + ("nrow", "i4"), + ("nlay", "i4"), + ] + ) + h2 = np.dtype([("imeth", "i4"), ("delt", "f4"), ("pertim", "f4"), ("totim", "f4")]) + ilayer = np.array([[1, 2], [3, 1]], dtype=np.int32) + et = np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float32) + rch = np.array([[5.0, 6.0], [7.0, 8.0]], dtype=np.float32) + + src = function_tmpdir / "imeth34.cbc" + with open(src, "wb") as f: + np.array([(1, 1, b" ET", ncol, nrow, -nlay)], h1).tofile(f) + np.array([(3, 1.0, 1.0, 1.0)], h2).tofile(f) + ilayer.tofile(f) + et.tofile(f) + np.array([(1, 1, b" RECHARGE", ncol, nrow, -nlay)], h1).tofile(f) + np.array([(4, 1.0, 1.0, 1.0)], h2).tofile(f) + rch.tofile(f) + + cbc = CellBudgetFile(src, precision="single") + assert list(cbc.recordarray["imeth"]) == [3, 4] + out = function_tmpdir / "out.cbc" + cbc.export(out) + exported = CellBudgetFile(out, precision="single") + assert list(exported.recordarray["imeth"]) == [1, 1] + assert list(exported.recordarray["text"]) == list(cbc.recordarray["text"]) + + et3d = exported.get_data(idx=0)[0] + expected = np.zeros((nlay, nrow, ncol), dtype=np.float32) + for r in range(nrow): + for c in range(ncol): + expected[ilayer[r, c] - 1, r, c] = et[r, c] + assert np.array_equal(et3d, expected) + + rch3d = exported.get_data(idx=1)[0] + expected = np.zeros((nlay, nrow, ncol), dtype=np.float32) + expected[0] = rch + assert np.array_equal(rch3d, expected) diff --git a/flopy/utils/binaryfile/__init__.py b/flopy/utils/binaryfile/__init__.py index eeb54ec54..02d7faa6f 100644 --- a/flopy/utils/binaryfile/__init__.py +++ b/flopy/utils/binaryfile/__init__.py @@ -3735,18 +3735,31 @@ def export( if (kstp, kper) not in selected_kstpkper: continue - # take imeth from the record's header. records from - # non-compact files are indexed with imeth 0, which is - # written as the equivalent imeth 1 in the compact output. + # output is always compact, with array records written + # as imeth 1 and list records as imeth 6: + # - imeth 0 (non-compact) is equivalent to imeth 1 + # - imeth 2 and 5 (MF2005 lists) are written as imeth 6, + # with blank model and package names + # - imeth 3 (layer indicator + 2D array) and imeth 4 (2D + # array for layer 1) are expanded to full 3D arrays imeth = int(header["imeth"]) + data = self.get_data(idx=idx)[0] if imeth == 0: imeth = 1 - if imeth not in (1, 6): - raise NotImplementedError( - f"Exporting imeth={imeth} records is not supported, " - "expected imeth=0 or 1 (array) or imeth=6 (list)" - ) - data = self.get_data(idx=idx)[0] + elif imeth in (2, 5): + imeth = 6 + elif imeth in (3, 4): + arr3d = np.zeros((nlay, nrow, ncol), dtype=realtype) + if imeth == 3: + ilayer, values = data + rows, cols = np.indices((nrow, ncol)) + arr3d[ilayer - 1, rows, cols] = values + else: + arr3d[0] = data + data = arr3d + imeth = 1 + elif imeth not in (1, 6): + raise ValueError(f"Invalid imeth={imeth} in budget file") # copy text as-is to preserve its justification text_bytes = _pad_text_to_16(header["text"]) From d1ea4c08aa65553b729c1fb70efd48a3a6709d5b Mon Sep 17 00:00:00 2001 From: wpbonelli Date: Mon, 16 Nov 2026 13:25:31 -0800 Subject: [PATCH 3/4] fix(binaryfile): keep previous handling of imeth 3 and 4 in export() Leave imeth 3 and 4 records as they were exported before, as imeth 1, so this change stays limited to exporting multiple packages. Writing MF2005 compact records (imeth 2-5) unchanged is left for a follow-up. Co-Authored-By: Claude Opus 5.5 --- autotest/test_cellbudgetfile.py | 49 ------------------------------ flopy/utils/binaryfile/__init__.py | 24 +++++---------- 2 files changed, 7 insertions(+), 66 deletions(-) diff --git a/autotest/test_cellbudgetfile.py b/autotest/test_cellbudgetfile.py index f587c222f..35f5b21a9 100644 --- a/autotest/test_cellbudgetfile.py +++ b/autotest/test_cellbudgetfile.py @@ -1473,52 +1473,3 @@ def test_cellbudgetfile_export_mf2005_compact_lists( else: assert exp_hdr["imeth"] == hdr["imeth"] assert np.allclose(a, b) - - -def test_cellbudgetfile_export_imeth_3_4(function_tmpdir): - """imeth 3 and 4 records are expanded to full 3D arrays (imeth 1).""" - nlay, nrow, ncol = 3, 2, 2 - h1 = np.dtype( - [ - ("kstp", "i4"), - ("kper", "i4"), - ("text", "S16"), - ("ncol", "i4"), - ("nrow", "i4"), - ("nlay", "i4"), - ] - ) - h2 = np.dtype([("imeth", "i4"), ("delt", "f4"), ("pertim", "f4"), ("totim", "f4")]) - ilayer = np.array([[1, 2], [3, 1]], dtype=np.int32) - et = np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float32) - rch = np.array([[5.0, 6.0], [7.0, 8.0]], dtype=np.float32) - - src = function_tmpdir / "imeth34.cbc" - with open(src, "wb") as f: - np.array([(1, 1, b" ET", ncol, nrow, -nlay)], h1).tofile(f) - np.array([(3, 1.0, 1.0, 1.0)], h2).tofile(f) - ilayer.tofile(f) - et.tofile(f) - np.array([(1, 1, b" RECHARGE", ncol, nrow, -nlay)], h1).tofile(f) - np.array([(4, 1.0, 1.0, 1.0)], h2).tofile(f) - rch.tofile(f) - - cbc = CellBudgetFile(src, precision="single") - assert list(cbc.recordarray["imeth"]) == [3, 4] - out = function_tmpdir / "out.cbc" - cbc.export(out) - exported = CellBudgetFile(out, precision="single") - assert list(exported.recordarray["imeth"]) == [1, 1] - assert list(exported.recordarray["text"]) == list(cbc.recordarray["text"]) - - et3d = exported.get_data(idx=0)[0] - expected = np.zeros((nlay, nrow, ncol), dtype=np.float32) - for r in range(nrow): - for c in range(ncol): - expected[ilayer[r, c] - 1, r, c] = et[r, c] - assert np.array_equal(et3d, expected) - - rch3d = exported.get_data(idx=1)[0] - expected = np.zeros((nlay, nrow, ncol), dtype=np.float32) - expected[0] = rch - assert np.array_equal(rch3d, expected) diff --git a/flopy/utils/binaryfile/__init__.py b/flopy/utils/binaryfile/__init__.py index 02d7faa6f..3f9640541 100644 --- a/flopy/utils/binaryfile/__init__.py +++ b/flopy/utils/binaryfile/__init__.py @@ -3736,28 +3736,18 @@ def export( continue # output is always compact, with array records written - # as imeth 1 and list records as imeth 6: - # - imeth 0 (non-compact) is equivalent to imeth 1 - # - imeth 2 and 5 (MF2005 lists) are written as imeth 6, - # with blank model and package names - # - imeth 3 (layer indicator + 2D array) and imeth 4 (2D - # array for layer 1) are expanded to full 3D arrays + # as imeth 1 and list records as imeth 6. imeth 0 + # (non-compact) is equivalent to imeth 1. imeth 2-5 + # (MF2005 compact) are converted as before: lists + # (2, 5) to imeth 6 with blank model/package names, + # arrays (3, 4) to imeth 1. + # TODO: write imeth 2-5 records unchanged instead imeth = int(header["imeth"]) data = self.get_data(idx=idx)[0] - if imeth == 0: + if imeth in (0, 3, 4): imeth = 1 elif imeth in (2, 5): imeth = 6 - elif imeth in (3, 4): - arr3d = np.zeros((nlay, nrow, ncol), dtype=realtype) - if imeth == 3: - ilayer, values = data - rows, cols = np.indices((nrow, ncol)) - arr3d[ilayer - 1, rows, cols] = values - else: - arr3d[0] = data - data = arr3d - imeth = 1 elif imeth not in (1, 6): raise ValueError(f"Invalid imeth={imeth} in budget file") From 027c1cd9e22f25626070cc07fec1559da2b309b6 Mon Sep 17 00:00:00 2001 From: wpbonelli Date: Mon, 16 Nov 2026 13:31:19 -0800 Subject: [PATCH 4/4] test(binaryfile): check export() reorders text given out of file order The text subset test passed text in file order, so it didn't check that records are written in file order regardless of the order of text. Co-Authored-By: Claude Opus 5.5 --- autotest/test_cellbudgetfile.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/autotest/test_cellbudgetfile.py b/autotest/test_cellbudgetfile.py index 35f5b21a9..67b070371 100644 --- a/autotest/test_cellbudgetfile.py +++ b/autotest/test_cellbudgetfile.py @@ -1408,8 +1408,13 @@ def test_cellbudgetfile_export_multiple_packages_text_subset( # text given as a list in a different order than in the file # should still produce records in file order out = function_tmpdir / "rch_spdis.cbc" - cbc.export(out, text=["DATA-SPDIS", "RCH"]) + cbc.export(out, text=["RCH", "DATA-SPDIS"]) exported = CellBudgetFile(out) + assert [t.strip() for t in exported.recordarray["text"]] == [ + b"DATA-SPDIS", + b"RCH", + b"RCH", + ] * 2 mask = np.isin(cbc.recordarray["text"], exported.textlist) idx = np.flatnonzero(mask) assert len(idx) == 6