Skip to content
Merged
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
131 changes: 122 additions & 9 deletions autotest/test_cellbudgetfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -1439,18 +1439,39 @@ def test_cellbudgetfile_export_multiple_packages_kstpkper_subset(


@pytest.mark.parametrize(
"relpath,kstpkper",
"relpath",
[
# imeth 1 and 2 (compact list without aux)
"freyberg_multilayer_transient/freyberg.cbc",
# imeth 5 (compact list with naux + 1 = 1)
"preserve_unitnums/testsfr2.ghb.cbc",
# imeth 1, 2 and 5
"mfusg_test/03_conduit_confined/output/ex3.cbb",
# CLN records whose ncol differs from the file-level ncol
"mfusg_test/03A_conduit_unconfined/output/ex3A.cln.cbb",
],
)
def test_cellbudgetfile_export_mf2005_compact_unchanged(
example_data_path, function_tmpdir, relpath
):
"""Exporting a whole MF2005 compact file reproduces it byte for byte."""
src = example_data_path / relpath
out = function_tmpdir / "out.cbc"
CellBudgetFile(src).export(out)
assert src.read_bytes() == out.read_bytes()


@pytest.mark.parametrize(
"relpath,kstpkper",
[
("freyberg_multilayer_transient/freyberg.cbc", [(1, 1), (1, 2)]),
# imeth 5 (compact list with aux)
("preserve_unitnums/testsfr2.ghb.cbc", None),
("mfusg_test/03_conduit_confined/output/ex3.cbb", 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."""
"""MF2005 compact records keep their imeth, and list records their fields."""
cbc = CellBudgetFile(example_data_path / relpath)
out = function_tmpdir / "out.cbc"
cbc.export(out, kstpkper=kstpkper)
Expand All @@ -1467,14 +1488,106 @@ def test_cellbudgetfile_export_mf2005_compact_lists(
for j, i in enumerate(idx):
hdr = cbc.recordarray[i]
exp_hdr = exported.recordarray[j]
for field in ["kstp", "kper", "text"]:
for field in ["kstp", "kper", "text", "ncol", "nrow", "nlay", "imeth"]:
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
assert b.dtype.names == a.dtype.names
for name in a.dtype.names:
assert np.allclose(a[name], b[name]), name
assert np.array_equal(a[name], b[name]), name
else:
assert exp_hdr["imeth"] == hdr["imeth"]
assert np.allclose(a, b)
assert np.array_equal(a, b, equal_nan=True)


def _write_mf2005_compact_cbc(path, precision):
"""Write a compact budget file with imeth 2, 3, 4 and 5 records."""
realtype = np.float32 if precision == "single" else np.float64
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", realtype), ("pertim", realtype), ("totim", realtype)]
)

def header(f, text, imeth):
np.array([(1, 1, text, ncol, nrow, -nlay)], h1).tofile(f)
np.array([(imeth, 1.0, 1.0, 1.0)], h2).tofile(f)

with open(path, "wb") as f:
header(f, b" WELLS", 2)
np.array([2], np.int32).tofile(f)
np.array([(3, -1.5), (10, -2.5)], [("node", "i4"), ("q", realtype)]).tofile(f)

header(f, b" ET", 3)
np.array([[1, 2], [3, 1]], np.int32).tofile(f)
np.array([[1.0, 2.0], [3.0, 4.0]], realtype).tofile(f)

header(f, b" RECHARGE", 4)
np.array([[5.0, 6.0], [7.0, 8.0]], realtype).tofile(f)

header(f, b" HEAD DEP BOUNDS", 5)
np.array([2], np.int32).tofile(f) # naux + 1
f.write(b"IFACE ")
np.array([2], np.int32).tofile(f)
np.array(
[(4, 0.5, 6.0), (11, 0.25, 0.0)],
[("node", "i4"), ("q", realtype), ("IFACE", realtype)],
).tofile(f)


@pytest.mark.parametrize("precision", ["single", "double"])
def test_cellbudgetfile_export_imeth_2_to_5(function_tmpdir, precision):
"""imeth 2-5 records, including aux names, are written unchanged."""
src = function_tmpdir / "mf2005.cbc"
_write_mf2005_compact_cbc(src, precision)
cbc = CellBudgetFile(src, precision=precision)
assert list(cbc.recordarray["imeth"]) == [2, 3, 4, 5]

out = function_tmpdir / "out.cbc"
cbc.export(out)
assert src.read_bytes() == out.read_bytes()

# subset
out = function_tmpdir / "subset.cbc"
cbc.export(out, text=["ET", "HEAD DEP BOUNDS"])
exported = CellBudgetFile(out, precision=precision)
assert list(exported.recordarray["imeth"]) == [3, 5]
ilayer, et = exported.get_data(idx=0)[0]
assert ilayer.tolist() == [[1, 2], [3, 1]]
assert et.tolist() == [[1.0, 2.0], [3.0, 4.0]]
ghb = exported.get_data(idx=1)[0]
assert ghb.dtype.names == ("node", "q", "IFACE")
assert ghb["IFACE"].tolist() == [6.0, 0.0]


def test_cellbudgetfile_export_imeth_2_to_5_precision(function_tmpdir):
"""imeth 2-5 real fields are converted to the requested precision."""
src = function_tmpdir / "mf2005.cbc"
_write_mf2005_compact_cbc(src, "single")
cbc = CellBudgetFile(src, precision="single")
out = function_tmpdir / "out.cbc"
cbc.export(out, precision="double")

expected = function_tmpdir / "expected.cbc"
_write_mf2005_compact_cbc(expected, "double")
assert out.read_bytes() == expected.read_bytes()


def test_cellbudgetfile_export_auto_precision(example_data_path, function_tmpdir):
"""With precision detected automatically, export keeps the file's precision."""
src = example_data_path / "freyberg_multilayer_transient" / "freyberg.cbc"
cbc = CellBudgetFile(src)
assert cbc.realtype == np.float32
out = function_tmpdir / "out.cbc"
cbc.export(out, kstpkper=[(1, 1)])
exported = CellBudgetFile(out)
assert exported.realtype == np.float32
97 changes: 49 additions & 48 deletions flopy/utils/binaryfile/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3649,6 +3649,13 @@ def export(
- precision : str, 'single' or 'double' (default is the file's precision)
- verbose : bool, print progress messages

Notes
-----
The output is a subset of the file in its own format, not a
conversion. Headers are always compact, and each record keeps its
imeth, except imeth 0 (non-compact full array), which is written
as the equivalent imeth 1.

Examples
--------
>>> cbc = CellBudgetFile('input.cbc')
Expand All @@ -3675,8 +3682,13 @@ def export(
textlist = [_pad_text_to_16(t) for t in text]

verbose = kwargs.get("verbose", False)
precision = kwargs.get("precision", self.precision)
realtype = np.float32 if precision == "single" else np.float64
# default to the file's precision, as detected if it was "auto"
precision = kwargs.get("precision")
if precision in (None, "auto"):
realtype = self.realtype
precision = "single" if realtype == np.float32 else "double"
else:
realtype = np.float32 if precision == "single" else np.float64

# header dtypes
h1dt = np.dtype(
Expand Down Expand Up @@ -3710,17 +3722,9 @@ def export(
# 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
ncol = self.ncol if self.ncol > 0 else None

if verbose:
print(f"Writing binary budget file: {filename}")
print(f" Precision: {precision}")
if nlay is not None and nrow is not None and ncol is not None:
print(f" Grid shape: {nlay} layers x {nrow} rows x {ncol} cols")
else:
print(" Grid shape not specified")

with open(filename, "wb") as f:
# iterate over records in file order, so that each record's
Expand All @@ -3735,20 +3739,14 @@ def export(
if (kstp, kper) not in selected_kstpkper:
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-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
# output is always compact, and records keep their
# imeth, except imeth 0 (non-compact array), which is
# equivalent to imeth 1.
imeth = int(header["imeth"])
data = self.get_data(idx=idx)[0]
if imeth in (0, 3, 4):
if imeth == 0:
imeth = 1
elif imeth in (2, 5):
imeth = 6
elif imeth not in (1, 6):
elif imeth not in range(1, 7):
raise ValueError(f"Invalid imeth={imeth} in budget file")

# copy text as-is to preserve its justification
Expand All @@ -3761,25 +3759,12 @@ def export(
if verbose:
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}"
)
# negative nlay -> compact format
ndim1, ndim2, ndim3 = ncol, nrow, -nlay
# copy the record's own dimensions, which can differ
# from the grid's (e.g. FLOW-JA-FACE, MFUSG CLN flows).
# negative nlay -> compact format
ndim1 = int(header["ncol"])
ndim2 = int(header["nrow"])
ndim3 = -abs(int(header["nlay"]))

header1 = np.array(
[(kstp, kper, text_bytes, ndim1, ndim2, ndim3)],
Expand All @@ -3791,15 +3776,31 @@ def export(
header2.tofile(f)

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)
np.asarray(data, dtype=realtype).tofile(f)

arr.tofile(f)
elif imeth in (2, 5):
# imeth 5 has aux names before the list; imeth 2 has
# no aux and no naux
auxtxt = [n for n in data.dtype.names if n not in ("node", "q")]
if imeth == 5:
np.array([len(auxtxt) + 1], dtype=np.int32).tofile(f)
for auxname in auxtxt:
f.write(_pad_text_to_16(auxname))
np.array([len(data)], dtype=np.int32).tofile(f)
dt_list = [("node", np.int32), ("q", realtype)]
dt_list += [(name, realtype) for name in auxtxt]
output_data = np.empty(len(data), dtype=np.dtype(dt_list))
for field in output_data.dtype.names:
output_data[field] = data[field]
output_data.tofile(f)

elif imeth == 3:
ilayer, arr = data
np.asarray(ilayer, dtype=np.int32).tofile(f)
np.asarray(arr, dtype=realtype).tofile(f)

elif imeth == 4:
np.asarray(data, dtype=realtype).tofile(f)

elif imeth == 6:
# write model and package names
Expand Down
Loading