diff --git a/autotest/test_cellbudgetfile.py b/autotest/test_cellbudgetfile.py index e01d598f0..67b070371 100644 --- a/autotest/test_cellbudgetfile.py +++ b/autotest/test_cellbudgetfile.py @@ -1299,3 +1299,182 @@ 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=["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 + _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] + + +@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) diff --git a/flopy/utils/binaryfile/__init__.py b/flopy/utils/binaryfile/__init__.py index fc349eeb5..3f9640541 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,124 @@ 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) + # 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-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 in (0, 3, 4): + imeth = 1 + elif imeth in (2, 5): + imeth = 6 + 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"]) + 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) - is_flowja = text_str.upper() == "FLOW-JA-FACE" + elif imeth == 6: + # write model and package names + for name in ["modelnam", "paknam", "modelnam2", "paknam2"]: + f.write(_pad_text_to_16(header[name])) - # 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, + # 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" ) - 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}")