diff --git a/flopy4/mf6/__init__.py b/flopy4/mf6/__init__.py index 08763545..e713a8cf 100644 --- a/flopy4/mf6/__init__.py +++ b/flopy4/mf6/__init__.py @@ -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 @@ -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). diff --git a/flopy4/mf6/component.py b/flopy4/mf6/component.py index 3b2304c2..b87a0152 100644 --- a/flopy4/mf6/component.py +++ b/flopy4/mf6/component.py @@ -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 @@ -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: @@ -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 @@ -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) diff --git a/flopy4/mf6/context.py b/flopy4/mf6/context.py deleted file mode 100644 index 1fb65c7a..00000000 --- a/flopy4/mf6/context.py +++ /dev/null @@ -1,35 +0,0 @@ -from abc import ABC -from pathlib import Path - -import attrs - -from flopy4.mf6.component import Component -from flopy4.utils import to_path - - -@attrs.define(kw_only=True, slots=False) -class Context(Component, ABC): - workspace: Path = attrs.field(default=None, converter=to_path) - """The directory the context'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 context 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) diff --git a/flopy4/mf6/converter/__init__.py b/flopy4/mf6/converter/__init__.py index 8f0b6b6d..271aeb8a 100644 --- a/flopy4/mf6/converter/__init__.py +++ b/flopy4/mf6/converter/__init__.py @@ -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, ) @@ -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 diff --git a/flopy4/mf6/converter/egress/unstructure.py b/flopy4/mf6/converter/egress/unstructure.py index 41f540d9..b0e519ba 100644 --- a/flopy4/mf6/converter/egress/unstructure.py +++ b/flopy4/mf6/converter/egress/unstructure.py @@ -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 ( @@ -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 @@ -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 diff --git a/flopy4/mf6/model.py b/flopy4/mf6/model.py index f31a6767..3cc503b3 100644 --- a/flopy4/mf6/model.py +++ b/flopy4/mf6/model.py @@ -3,12 +3,12 @@ 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 @@ -16,7 +16,7 @@ def workspace(self) -> Path: 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] @@ -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" diff --git a/flopy4/mf6/simulation.py b/flopy4/mf6/simulation.py index 48516a57..217e7a35 100644 --- a/flopy4/mf6/simulation.py +++ b/flopy4/mf6/simulation.py @@ -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 @@ -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( diff --git a/flopy4/mf6/simulation_methods.py b/flopy4/mf6/simulation_methods.py index 556c5280..57826874 100644 --- a/flopy4/mf6/simulation_methods.py +++ b/flopy4/mf6/simulation_methods.py @@ -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 @@ -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( diff --git a/flopy4/mf6/utils/codegen/make.py b/flopy4/mf6/utils/codegen/make.py index 5c72a683..4f9d977c 100644 --- a/flopy4/mf6/utils/codegen/make.py +++ b/flopy4/mf6/utils/codegen/make.py @@ -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", } @@ -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: diff --git a/test/mf6/test_mf6_codegen.py b/test/mf6/test_mf6_codegen.py index 98b88c93..e05654fd 100644 --- a/test/mf6/test_mf6_codegen.py +++ b/test/mf6/test_mf6_codegen.py @@ -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} diff --git a/test/mf6/test_mf6_component.py b/test/mf6/test_mf6_component.py index d80013d9..a186b06a 100644 --- a/test/mf6/test_mf6_component.py +++ b/test/mf6/test_mf6_component.py @@ -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")