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
5 changes: 2 additions & 3 deletions flopy4/mf6/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,7 @@
from flopy4.mf6._types import TimeArraySeriesRef, TimeSeriesRef
from flopy4.mf6.codec import dump as dump_mf6
from flopy4.mf6.codec import load as load_mf6
from flopy4.mf6.component import Component
from flopy4.mf6.context import Context
from flopy4.mf6.component import Component, WorkspaceComponent
from flopy4.mf6.converter import structure, unstructure
from flopy4.mf6.enums import NetCDFFormat
from flopy4.mf6.load_context import LoadContext
Expand Down Expand Up @@ -141,7 +140,7 @@ def _load_mf6(
with open(path, "r") as fp:
raw = load_mf6(fp)
instance = structure_component(raw, cls, context=context, name=name)
if isinstance(instance, Context):
if isinstance(instance, WorkspaceComponent):
instance.workspace = context.workspace
# The file's path as an input file would name it, relative to the
# simulation directory (gwf/m.nam).
Expand Down
34 changes: 31 additions & 3 deletions flopy4/mf6/component.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from flopy4.mf6.write_context import WriteContext
from flopy4.spec import is_reference, reference_names, referenced, resolve, retarget
from flopy4.uio import IO, Loader, Writer
from flopy4.utils import empty_if_none
from flopy4.utils import empty_if_none, to_path

if TYPE_CHECKING:
from flopy4.mf6.load_context import LoadContext
Expand Down Expand Up @@ -658,7 +658,7 @@ def _attach_to_parent_field(self, parent: "Component") -> None:
@classmethod
def __attrs_init_subclass__(cls):
# Only register classes that declare their own `dfn_name`.
# Abstract bases (Package, Context, Model, Exchange, Solution, ...)
# Abstract bases (Package, WorkspaceComponent, Model, Exchange, Solution, ...)
# have no `dfn_name` of their own and are silently skipped.
dfn_name = cls.__dict__.get("dfn_name")
if dfn_name is not None:
Expand Down Expand Up @@ -895,7 +895,7 @@ def to_dict(self, blocks: bool = False, strict: bool = False) -> dict[str, Any]:

if strict:
data.pop("_filename")
data.pop("workspace", None) # might be a Context
data.pop("workspace", None) # might be a WorkspaceComponent

if blocks:
blocks_ = {} # type: ignore
Expand Down Expand Up @@ -957,3 +957,31 @@ def _collect_child_griddata_datasets(self) -> dict:
except Exception:
pass
return result


@attrs.define(kw_only=True, slots=False)
class WorkspaceComponent(Component, ABC):
workspace: Path = attrs.field(default=None, converter=to_path)
"""The directory the component's files are written to and read from.
A model under a simulation has the simulation's (see
`Model.workspace`)."""

def __attrs_post_init__(self):
super().__attrs_post_init__()
if self.workspace is None:
self.workspace = Path.cwd()

@property
def path(self) -> Path:
return self.workspace / self.filename

def to_xarray(self):
"""DataTree for this component and its full child hierarchy.

Built directly from live attribute values via flopy4.attrs_xarray's
attrs_to_datatree. Each child node, leaf packages included, is
built from its own fields directly, so griddata appears natively.
"""
from flopy4.attrs_xarray import attrs_to_datatree

return attrs_to_datatree(self)
35 changes: 0 additions & 35 deletions flopy4/mf6/context.py

This file was deleted.

5 changes: 2 additions & 3 deletions flopy4/mf6/converter/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@
import cattr
from cattr import Converter

from flopy4.mf6.component import Component
from flopy4.mf6.context import Context
from flopy4.mf6.component import Component, WorkspaceComponent
from flopy4.mf6.converter.egress.unstructure import (
unstructure_component,
)
Expand All @@ -32,7 +31,7 @@ def _make_converter() -> Converter:

def structure(data: dict[str, Any], path: Path) -> Component:
component = COMPONENT_CONVERTER.structure(data, Component)
if isinstance(component, Context):
if isinstance(component, WorkspaceComponent):
component.workspace = path.parent
component.filename = Path(path.name)
return component
Expand Down
7 changes: 3 additions & 4 deletions flopy4/mf6/converter/egress/unstructure.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,8 @@
from flopy4.attrs_xarray import child_field_candidates
from flopy4.mf6._types import TimeArraySeriesRef
from flopy4.mf6.block import block_list_type
from flopy4.mf6.component import Component
from flopy4.mf6.component import Component, WorkspaceComponent
from flopy4.mf6.constants import FILL_DNODATA
from flopy4.mf6.context import Context
from flopy4.mf6.converter.binding import write_row
from flopy4.mf6.dims_provider_methods import DimsProviderMethods
from flopy4.mf6.item import (
Expand Down Expand Up @@ -66,7 +65,7 @@ def _put_child_file_records(block: dict, field: attrs.Attribute, value: Any) ->


def _make_binding_blocks(value: Component) -> dict[str, dict[str, list[tuple[str, ...]]]]:
if not isinstance(value, Context):
if not isinstance(value, WorkspaceComponent):
return {}

blocks = {} # type: ignore
Expand Down Expand Up @@ -506,7 +505,7 @@ def _unstructure_component(value: Component) -> dict[str, Any]:
# Skip child components already processed as bindings
field = fields_by_name.get(field_name)
if (
isinstance(value, Context)
isinstance(value, WorkspaceComponent)
and field is not None
and field.metadata.get("child")
and child_field_candidates(field) is not None
Expand Down
12 changes: 8 additions & 4 deletions flopy4/mf6/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,20 @@

import attrs

from flopy4.mf6.context import Context
from flopy4.mf6.component import WorkspaceComponent
from flopy4.utils import to_path


@attrs.define(kw_only=True, slots=False)
class Model(Context, ABC):
class Model(WorkspaceComponent, ABC):
@property # type: ignore[override]
def workspace(self) -> Path:
"""The simulation's workspace, or the model's own if it has no
simulation. MF6 resolves every path in every input file against
the simulation's directory, so a model's filenames are relative
to it too (`gwf/m.dis` for a model in a subdirectory)."""
parent = self.__dict__.get("_parent")
if isinstance(parent, Context):
if isinstance(parent, WorkspaceComponent):
return parent.workspace
return self.__dict__.get("_workspace") # type: ignore[return-value]

Expand All @@ -26,7 +26,11 @@ def workspace(self, value) -> None:
workspace is the simulation's: set that instead."""
value = to_path(value)
parent = self.__dict__.get("_parent")
if isinstance(parent, Context) and value is not None and value != parent.workspace:
if (
isinstance(parent, WorkspaceComponent)
and value is not None
and value != parent.workspace
):
raise ValueError(
f"{self.name}: a model's workspace is its simulation's " # type: ignore[attr-defined]
f"({parent.workspace}); set the simulation's workspace instead"
Expand Down
4 changes: 2 additions & 2 deletions flopy4/mf6/simulation.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

import attrs

from flopy4.mf6.context import Context
from flopy4.mf6.component import WorkspaceComponent
from flopy4.mf6.exchange import Exchange
from flopy4.mf6.model import Model
from flopy4.mf6.simulation_methods import SimulationMethods
Expand All @@ -14,7 +14,7 @@


@attrs.define(kw_only=True, slots=False)
class Simulation(SimulationMethods, Context):
class Simulation(SimulationMethods, WorkspaceComponent):
dfn_name: ClassVar[str] = "sim-nam"

continue_: bool = keyword(
Expand Down
4 changes: 2 additions & 2 deletions flopy4/mf6/simulation_methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from flopy4.dimensions import validate_dimension_resolution

if TYPE_CHECKING:
from flopy4.mf6.context import Context
from flopy4.mf6.component import WorkspaceComponent
from flopy4.mf6.simulation import Simulation
from flopy4.mf6.solution import Solution
from flopy4.mf6.utils.time import Time
Expand All @@ -22,7 +22,7 @@ def default_filename(self) -> str:

def __attrs_post_init__(self) -> None:
super().__attrs_post_init__() # type: ignore[misc]
sim: "Context" = self # type: ignore[assignment]
sim: "WorkspaceComponent" = self # type: ignore[assignment]
if sim._filename != Path("mfsim.nam"):
if sim._filename is not None:
warn(
Expand Down
4 changes: 2 additions & 2 deletions flopy4/mf6/utils/codegen/make.py
Original file line number Diff line number Diff line change
Expand Up @@ -998,7 +998,7 @@ def _generated_imports(
_base_imports = {
"Package": "from flopy4.mf6.package import Package",
"Solution": "from flopy4.mf6.solution import Solution",
"Context": "from flopy4.mf6.context import Context",
"WorkspaceComponent": "from flopy4.mf6.component import WorkspaceComponent",
"Exchange": "from flopy4.mf6.exchange import Exchange",
"Model": "from flopy4.mf6.model import Model",
}
Expand Down Expand Up @@ -1561,7 +1561,7 @@ def _model_package_specs(
def _base_class(component: Component) -> str:
"""Determine the Python base class for a component."""
if component.type == "simulation":
return "Context"
return "WorkspaceComponent"
if filters.is_model_nam(component.name):
return "Model"
if component.name.split("-")[0] == _SLN_PREFIX:
Expand Down
2 changes: 1 addition & 1 deletion test/mf6/test_mf6_codegen.py
Original file line number Diff line number Diff line change
Expand Up @@ -403,7 +403,7 @@ def test_simulation_spec(all_dfns):
root = Path("/fake/mf6")
spec = build_component_spec(all_dfns["sim-nam"], root=root, dfns=all_dfns)
assert spec.class_name == "Simulation"
assert spec.base_class == "Context"
assert spec.base_class == "WorkspaceComponent"
assert spec.mixins == ["SimulationMethods"]
assert spec.outpath == root / "simulation.py"
types = {f.py_name: f.type_annotation for f in spec.fields}
Expand Down
2 changes: 1 addition & 1 deletion test/mf6/test_mf6_component.py
Original file line number Diff line number Diff line change
Expand Up @@ -3218,7 +3218,7 @@ def test_explicit_parent_top_down():

def test_explicit_parent_bottom_up_non_package():
"""The bottom-up (`parent=`) half of _parent tracking works for a
non-Package component (Model/Context/Component's own chain), whose
non-Package component (Model/WorkspaceComponent/Component's own chain), whose
own __attrs_post_init__ chains to Component's."""
sim = Simulation()
gwf = Gwf(parent=sim, name="gwf")
Expand Down
Loading