diff --git a/flopy4/mf6/netcdf.py b/flopy4/mf6/netcdf.py index 1397b40b..3a3b37f6 100644 --- a/flopy4/mf6/netcdf.py +++ b/flopy4/mf6/netcdf.py @@ -18,8 +18,7 @@ from flopy4.mf6.enums import NetCDFFormat from flopy4.mf6.model import Model from flopy4.mf6.package import _DTYPE_MAP as _PKG_DTYPE_MAP -from flopy4.mf6.package import Package, period_shape -from flopy4.mf6.period_state import aux_names, period_states +from flopy4.mf6.package import Package from flopy4.mf6.spec import to_field_type from flopy4.version import __version__ @@ -98,29 +97,18 @@ def _input_packages(model: Model): yield sub, f"{prefix}{stype}{counts[stype]}" -def _package_states(package: Package, nper: int, model: Model) -> "dict | None": - """The values a package's period arrays hold in each period (see - `flopy4.mf6.period_state`), or None if it has none.""" - fields = [ - f +def _package_states(package: Package, nper: int) -> "dict | None": + """The values a package's exported period arrays hold in each period + (see `Package.period_states`), or None if it has none.""" + names = [ + f.name for f in attrs.fields(type(package)) if f.metadata.get("netcdf") and f.metadata.get("fill_forward") and f.metadata.get("block") == "period" and f.metadata.get("reader") != "readarray" ] - if not fields: - return None - shapes: dict[str, Any] = {} - for f in fields: - shape = period_shape(package, f) # type: ignore[arg-type] - if shape is None: - raise ValueError(f"{package.dfn_name}: {f.name}'s period shape isn't known") - shapes["aux" if f.metadata.get("fk") else f.name] = shape - dis = getattr(model, "dis", None) - idomain = getattr(dis, "idomain", None) if dis is not None else None - active = None if idomain is None else np.asarray(idomain).ravel() > 0 - return period_states(package, nper, fields, shapes, active=active) + return package.period_states(names, nper) if names else None def _tdis_start_text(model: Model, time: "Time") -> str | None: @@ -136,11 +124,6 @@ def _tdis_start_text(model: Model, time: "Time") -> str | None: return str(text).strip() if same else None -def _stack(periods: list, dtype: Any) -> np.ndarray: - """Stack per-period arrays.""" - return np.stack([np.asarray(a, dtype=dtype) for a in periods]) - - def _pkgclass(package_name: str) -> Package: import flopy4 @@ -355,7 +338,7 @@ def from_model( else: _nodes = d.get("nodes", _nlay) - states = _package_states(package, _nper, model) + states = _package_states(package, _nper) for f in _attrs.fields(type(package)): if not f.metadata.get("netcdf"): @@ -374,7 +357,9 @@ def from_model( elif f.metadata.get("fk") and states is not None: # dynamically named arrays (RCHA's aux): one param per # auxiliary name, holding its values in each period - if not (names := aux_names(package)): + aux = getattr(package, "auxiliary", None) + names = [] if aux is None else [str(n).lower() for n in np.atleast_1d(aux)] + if not names: continue p["auxiliary"] = names for n, name in enumerate(names): @@ -382,7 +367,7 @@ def from_model( { "name": f.name, "attrs": {"modflow_iaux": n + 1}, - "data": _stack(states[f"aux:{name}"], np.float64), + "data": states[f"aux:{name}"].astype(np.float64), } ) elif ( @@ -397,9 +382,9 @@ def from_model( # period arrays: the values held in each period; an # index array is integer, 1-based in the file if f.metadata.get("index"): - arr = _stack(states[f.name], np.int32) + 1 + arr = states[f.name].astype(np.int32) + 1 else: - arr = _stack(states[f.name], np.float64) + arr = states[f.name].astype(np.float64) p["params"].append({"name": f.name, "data": arr}) if len(p["params"]) > 0: diff --git a/flopy4/mf6/package.py b/flopy4/mf6/package.py index d32a5393..8e5e7b54 100644 --- a/flopy4/mf6/package.py +++ b/flopy4/mf6/package.py @@ -43,6 +43,7 @@ to_named_period_dict, to_period_dict, ) +from flopy4.mf6.period_state import period_mode, period_states from flopy4.mf6.spec import to_field_type from flopy4.mf6.write_context import WriteContext from flopy4.spec import is_array @@ -1004,15 +1005,70 @@ def _period_dict(self, f) -> Optional[dict]: value = self.__dict__.get(f.name) return to_named_period_dict(value) if f.metadata.get("fk") else to_period_dict(value) + def _default_nper(self, fields: list) -> int: + # a package's periods are its period blocks, over all fields + given = {k for g in fields for k in (self._period_dict(g) or {})} + return self.resolve_dims("nper").get("nper") or max(given, default=-1) + 1 + + def _active_cells(self) -> Optional[np.ndarray]: + """The model's active cells, flat by user node, if it has a grid.""" + dis = getattr(self._parent, "dis", None) + idomain = getattr(dis, "idomain", None) + return None if idomain is None else np.asarray(idomain).ravel() > 0 + + def period_states( + self, names: Optional[list[str]] = None, nper: Optional[int] = None + ) -> dict[str, np.ndarray]: + """The values the period array fields ``names`` (all with a shape, by + default) hold in each period, as MF6 holds them (see + `flopy4.mf6.period_state`): ``{tag: (nper, ...)}``, a field's tag its + name, and an aux field's ``aux:`` for each auxiliary name. + ``nper`` defaults as in `period_array`. Raises if a field asked for, + or given, can't be sized.""" + fields = self._period_array_fields() + selected = [ + f for f in fields if (f.name in names if names is not None else f.metadata.get("shape")) + ] + if nper is None: + nper = self._default_nper(fields) + blocks: dict[int, dict[str, Any]] = {} + shapes: dict[str, tuple[int, ...]] = {} + index = None + for f in selected: + periods = self._period_dict(f) or {} + shape = period_shape(self, f) or _given_shape(f, periods) + if shape is None: + if names is not None or periods: + raise ValueError(f"{self.dfn_name}: {f.name}'s period shape isn't known") + continue # not asked for, not given, and no grid to size it + if f.metadata.get("fk"): + aux = getattr(self, "auxiliary", None) + for n in [] if aux is None else np.atleast_1d(aux): + shapes[f"aux:{str(n).lower()}"] = shape + for kper, arrays in periods.items(): + for n, a in arrays.items(): + blocks.setdefault(kper, {})[f"aux:{str(n).lower()}"] = a + else: + shapes[f.name] = shape + if f.metadata.get("index"): + index = f.name + for kper, a in periods.items(): + blocks.setdefault(kper, {})[f.name] = a + return period_states( + blocks, period_mode(type(self)), nper, shapes, self._active_cells(), index + ) + def period_array( self, name: str, nper: Optional[int] = None, fill_forward: bool = True ) -> "np.ndarray | dict[str, np.ndarray] | None": """A period array field as a dense ``(nper, ...)`` array. With ``fill_forward`` (the default), each period holds the values in - effect then. Without it, periods the field doesn't give are filled - with ``FILL_DNODATA`` (floats) or ``FILL_INT64`` (integers). Each - field fills forward on its own, in grid packages too. + effect then, as MF6 holds them (see `period_states`): in a grid + package, an array a block doesn't give is held at that block's + boundary cells, and an empty block clears every array. Without it, + periods the field doesn't give are filled with ``FILL_DNODATA`` + (floats) or ``FILL_INT64`` (integers). Dynamically named arrays (aux) give ``{name: (nper, ...)}``. ``nper`` defaults to the simulation's, else to one past the last period any of @@ -1026,18 +1082,30 @@ def period_array( if not periods: return None if nper is None: - # a package's periods are its period blocks, over all fields - given = {k for g in fields for k in (self._period_dict(g) or {})} - nper = self.resolve_dims("nper").get("nper") or max(given) + 1 + nper = self._default_nper(fields) + if fill_forward: + if refs := split_tas(periods)[1]: + raise ValueError( + f"periods {sorted(refs)} come from a time-array series, " + "which can't be made dense yet" + ) + # a grid block's arrays share its boundary cells; layer arrays + # stand alone + grid = period_mode(type(self)) == "grid" + states = self.period_states(names=None if grid else [name], nper=nper) + if not f.metadata.get("fk"): + return states[name] + given = dict.fromkeys(str(n).lower() for arrays in periods.values() for n in arrays) + return {n: states[f"aux:{n}"] for n in given} shape = period_shape(self, f) if not f.metadata.get("fk"): - return dense(periods, nper, fill_forward, shape=shape) + return dense(periods, nper, fill_forward=False, shape=shape) names = list(dict.fromkeys(n for arrays in periods.values() for n in arrays)) return { n: dense( {k: arrays[n] for k, arrays in periods.items() if n in arrays}, nper, - fill_forward, + fill_forward=False, shape=shape, ) for n in names @@ -1190,6 +1258,23 @@ def from_xarray(self, ds: xr.Dataset) -> None: setattr(self, spd.name, period_lists.from_dataset(self, ds)) +def _given_shape(f: attrs.Attribute, periods: dict) -> tuple[int, ...] | None: + """A period array's shape in one period from the arrays given, for a + package whose grid isn't known; None if none is given.""" + values = ( + [a for arrays in periods.values() for a in arrays.values()] + if f.metadata.get("fk") + else list(periods.values()) + ) + full = next((a for a in values if a is not None and np.ndim(a) > 0), None) + if full is None and any(isinstance(a, np.ndarray) for a in values): + raise ValueError( + f"{f.name}: no array gives the shape: give an array, attach the " + "package to a model, or pass its dims" + ) + return None if full is None else tuple(np.shape(full)) + + def period_shape(package: Package, f: attrs.Attribute) -> tuple[int, ...] | None: """A period array field's shape in one period, from its DFN shape and the grid's dims (``package``'s), or None if they aren't known.""" diff --git a/flopy4/mf6/period_state.py b/flopy4/mf6/period_state.py index 23aa7bb0..7d61fdf0 100644 --- a/flopy4/mf6/period_state.py +++ b/flopy4/mf6/period_state.py @@ -1,14 +1,20 @@ -"""The values a package's period arrays hold in each stress period, as MF6 -holds them in its input context, for export (NetCDF). See -``flopy4.mf6.period_arrays`` for how period arrays are given. +"""The values period arrays hold in each stress period, as MF6 holds them in +its input context. See ``flopy4.mf6.period_arrays`` for how period arrays +are given. -How a period block changes the values depends on how MF6 reads the package: +This module knows nothing of packages: it takes period blocks, ``{kper: +{tag: value}}``, and returns ``{tag: (nper, ...) array}``. A tag names one +array (a stress field, or one auxiliary variable); the caller picks them. +`Package.period_states` and the NetCDF export both go through here. -- Layer arrays (RCHA, EVTA; READASARRAYS): an array given holds its values +How a period block changes the values depends on how MF6 reads the package +(`period_mode`): + +- ``"layer"`` (RCHA, EVTA; READASARRAYS): an array given holds its values until given again. An array given as a time-array series holds no values - (fill) while linked. The layer index array (IRCH, IEVT) holds 1 until - given. -- Grid arrays (CHDG, WELG, ...; READARRAYGRID): the first array given in a + (fill) while linked. The layer index array (IRCH, IEVT) holds 0 (1 in the + file) until given. +- ``"grid"`` (CHDG, WELG, ...; READARRAYGRID): the first array given in a block, stress or aux, sets the block's boundary cells, the active cells where it has a value. MF6 stores each array by position in that list of cells, so an array not given keeps its values by position, at the new @@ -20,129 +26,120 @@ """ import warnings -from typing import Any, Optional +from collections.abc import Mapping +from typing import Any, Literal, Optional import attrs import numpy as np from flopy4.mf6._types import TimeArraySeriesRef from flopy4.mf6.constants import FILL_DNODATA +from flopy4.mf6.period_arrays import is_grid_package - -def aux_names(package: Any) -> list[str]: - """A package's auxiliary variable names, lowercase.""" - aux = getattr(package, "auxiliary", None) - return [] if aux is None else [str(n).lower() for n in np.atleast_1d(aux)] +Mode = Literal["layer", "grid"] -def _mode(cls: type) -> str: - fields = attrs.fields_dict(cls) - if "readarraygrid" not in fields: +def period_mode(cls: type) -> Mode: + """How MF6 reads a package class's period blocks.""" + if not is_grid_package(cls): return "layer" - if "maxbound" not in fields: + if "maxbound" not in attrs.fields_dict(cls): raise NotImplementedError(f"{cls.__name__}: full-grid period arrays (no MAXBOUND)") return "grid" +def _active(active: Optional[np.ndarray], size: int) -> np.ndarray: + if active is None: + return np.ones(size, dtype=bool) + act = np.ravel(active) + if act.size == 1: + return np.broadcast_to(act, size) + if act.size != size: + raise ValueError(f"idomain has {act.size} cells, period arrays {size}") + return act + + def _grid_states( - blocks: dict[int, dict[str, Any]], - tags: list[str], + blocks: Mapping[int, Mapping[str, Any]], + shapes: Mapping[str, tuple[int, ...]], nper: int, - shape: Any, active: Optional[np.ndarray], -) -> dict[str, list[np.ndarray]]: +) -> dict[str, np.ndarray]: """Grid arrays' values in each period, read as MF6's grid-array loader reads them (Mf6FileGridArray.f90): by position in the block's list of boundary cells.""" - size = int(np.prod(shape(tags[0]))) if tags else 0 - if active is None: - act = np.ones(size, dtype=bool) - else: - act = np.ravel(active) - if act.size == 1: - act = np.broadcast_to(act, size) - elif act.size != size: - raise ValueError(f"idomain has {act.size} cells, period arrays {size}") + out = {t: np.full((nper, *s), FILL_DNODATA) for t, s in shapes.items()} + if not shapes: + return out + size = int(np.prod(next(iter(shapes.values())))) + act = _active(active, size) cells = np.zeros(0, dtype=np.int64) # boundary cells, by position - stored = {t: np.zeros(size) for t in tags} + stored = {t: np.zeros(size) for t in shapes} given: set[str] = set() - out: dict[str, list[np.ndarray]] = {t: [] for t in tags} for kper in range(nper): if (blk := blocks.get(kper)) is not None: first = True cells = np.zeros(0, dtype=np.int64) - # in the order written: stress arrays as declared, then aux - for tag, v in blk.items(): + for tag, v in blk.items(): # in the order written if v is None: continue if isinstance(v, TimeArraySeriesRef): raise NotImplementedError(f"{tag}: time-array series grid arrays") - a = np.broadcast_to(np.asarray(v, dtype=float), shape(tag)).ravel() + a = np.broadcast_to(np.asarray(v, dtype=float), shapes[tag]).ravel() if first: cells = np.flatnonzero((a != FILL_DNODATA) & act) first = False stored[tag][: cells.size] = a[cells] given.add(tag) - for tag in tags: - a = np.full(size, FILL_DNODATA) - if tag in given: - a[cells] = stored[tag][: cells.size] - out[tag].append(a.reshape(shape(tag))) + for tag in given: + out[tag][kper].reshape(-1)[cells] = stored[tag][: cells.size] return out -def period_states( - package: Any, +def _layer_states( + blocks: Mapping[int, Mapping[str, Any]], + shapes: Mapping[str, tuple[int, ...]], nper: int, - fields: list, - shapes: dict[str, tuple[int, ...]], - active: Optional[np.ndarray] = None, -) -> dict[str, list[np.ndarray]]: - """The values each period array holds in each period: ``{tag: - [array per period]}``, ``FILL_DNODATA`` where it holds no values. `fields` - are the package's period array fields; tags are their names, and an aux - field's are ``aux:`` for each auxiliary name. `shapes` gives each - field's period shape; `active` (flat, by user node) marks active cells - for grid arrays.""" - mode = _mode(type(package)) - - blocks: dict[int, dict[str, Any]] = {} - tags: list[str] = [] - index = None - for f in fields: - value = package.__dict__.get(f.name) or {} - if f.metadata.get("fk"): - names = aux_names(package) - tags += [f"aux:{n}" for n in names] - for kper, arrays in value.items(): - for n, a in arrays.items(): - blocks.setdefault(kper, {})[f"aux:{str(n).lower()}"] = a - else: - tags.append(f.name) - if f.metadata.get("index"): - index = f.name - for kper, a in value.items(): - blocks.setdefault(kper, {})[f.name] = a - - if past := sorted(k for k in blocks if k >= nper): - warnings.warn(f"periods {past} are past NPER ({nper}), dropped", stacklevel=3) - - def shape(tag: str) -> tuple[int, ...]: - return shapes["aux" if tag.startswith("aux:") else tag] - - if mode == "grid": - return _grid_states(blocks, tags, nper, shape, active) - - state: dict[str, Optional[np.ndarray]] = dict.fromkeys(tags) - if index is not None: - state[index] = np.zeros(shape(index), dtype=np.int64) - out: dict[str, list[np.ndarray]] = {t: [] for t in tags} + index: Optional[str], +) -> dict[str, np.ndarray]: + """Layer arrays' values in each period: each array holds what it was + last given.""" + out = { + t: np.zeros((nper, *s), dtype=np.int64) if t == index else np.full((nper, *s), FILL_DNODATA) + for t, s in shapes.items() + } + held: dict[str, Any] = {} for kper in range(nper): for tag, v in (blocks.get(kper) or {}).items(): # a series-linked array holds no values - linked = isinstance(v, TimeArraySeriesRef) - state[tag] = None if linked else np.broadcast_to(np.asarray(v), shape(tag)) - for tag in tags: - a = state[tag] - out[tag].append(np.full(shape(tag), FILL_DNODATA) if a is None else a) + held[tag] = None if isinstance(v, TimeArraySeriesRef) else v + for tag, v in held.items(): + out[tag][kper] = FILL_DNODATA if v is None else np.broadcast_to(v, shapes[tag]) return out + + +def period_states( + blocks: Mapping[int, Mapping[str, Any]], + mode: Mode, + nper: int, + shapes: Mapping[str, tuple[int, ...]], + active: Optional[np.ndarray] = None, + index: Optional[str] = None, +) -> dict[str, np.ndarray]: + """The values each array holds in each period, ``{tag: (nper, ...) + array}``, ``FILL_DNODATA`` where it holds none. + + ``blocks`` holds the period blocks as written, ``{kper: {tag: value}}``, + each block's tags in the order they're written (in a grid block, the + first array sets the boundary cells). ``shapes`` gives the shape of + every tag in one period, including tags no block gives. ``active`` + (flat, by user node) marks the active cells, for grid arrays. ``index`` + is the tag of a layer package's layer index array, if any. + """ + if past := sorted(k for k in blocks if k >= nper): + warnings.warn(f"periods {past} are past NPER ({nper}), dropped", stacklevel=2) + if unknown := {t for b in blocks.values() for t in b} - set(shapes): + raise ValueError(f"no shape for {sorted(unknown)}") + if mode == "grid": + return _grid_states(blocks, shapes, nper, active) + return _layer_states(blocks, shapes, nper, index) diff --git a/test/mf6/test_mf6_period_state.py b/test/mf6/test_mf6_period_state.py index dd79e3ce..aa5e9e9f 100644 --- a/test/mf6/test_mf6_period_state.py +++ b/test/mf6/test_mf6_period_state.py @@ -9,7 +9,7 @@ from flopy4.mf6.constants import FILL_DNODATA as NO from flopy4.mf6.gwf import Dis, Gwf, Rcha, Rivg, Welg from flopy4.mf6.netcdf import NetCDFModel -from flopy4.mf6.period_state import period_states +from flopy4.mf6.period_state import period_mode, period_states from flopy4.mf6.simulation import Simulation from flopy4.mf6.utils.time import Time @@ -158,4 +158,43 @@ class FullGrid: readarraygrid: bool = True with pytest.raises(NotImplementedError, match="full-grid"): - period_states(FullGrid(), NPER, [], {}) + period_mode(FullGrid) + + +def test_period_states_from_blocks(): + """period_states works on period blocks alone, no package: an aux-only + grid block sets the boundary, and q is held there by position.""" + blocks = { + 0: {"q": np.array([-1.0, -2.0, NO, NO]), "aux:m": np.array([1.0, 2.0, NO, NO])}, + 1: {"aux:m": np.array([NO, 5.0, 6.0, NO])}, + } + shapes = {"q": (4,), "aux:m": (4,)} + out = period_states(blocks, "grid", 3, shapes, active=np.array([1, 1, 1, 0]) > 0) + np.testing.assert_array_equal( + out["q"], [[-1.0, -2.0, NO, NO], [NO, -1.0, -2.0, NO], [NO, -1.0, -2.0, NO]] + ) + np.testing.assert_array_equal(out["aux:m"][2], [NO, 5.0, 6.0, NO]) + + +def test_period_array_follows_grid_regime(): + """Package.period_array goes through period_states, so it agrees with + the export: an empty block clears aux too, though no block gives it.""" + gwf = _model() + welg = Welg( + parent=gwf, + auxiliary=["m"], + q={0: np.array([-1.0, -2.0, NO, NO]), 2: None}, + aux={0: {"m": np.array([1.0, 2.0, NO, NO])}}, + ) + ds = NetCDFModel.from_model(gwf).to_xarray() + m = welg.period_array("aux")["m"] + np.testing.assert_array_equal(m, _periods(ds, "wel-1_m")) + np.testing.assert_array_equal(m[:, 0], [1.0, 1.0, NO, NO]) + + +def test_period_states_unknown_shape_raises(): + """A field asked for that neither the grid nor its values can size is + an error, not a missing key.""" + welg = Welg() + with pytest.raises(ValueError, match="period shape isn't known"): + welg.period_states(["q"], nper=1)