Skip to content

basic index working #114

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 24, 2025
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
6 changes: 5 additions & 1 deletion flopy4/mf6/gwf/dis.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@
from xattree import array, dim, field, xattree

from flopy4.mf6.converters import convert_array
from flopy4.mf6.indexes import grid_index
from flopy4.mf6.package import Package


@xattree
@xattree(index=grid_index, index_scope="gwf")
class Dis(Package):
length_units: str = field(
default=None,
Expand All @@ -21,20 +22,23 @@ class Dis(Package):
default=False, metadata={"block": "options"}
)
nlay: int = dim(
coord=False,
scope="gwf",
default=1,
metadata={
"block": "dimensions",
},
)
ncol: int = dim(
coord=False,
scope="gwf",
default=2,
metadata={
"block": "dimensions",
},
)
nrow: int = dim(
coord=False,
scope="gwf",
default=2,
metadata={
Expand Down
51 changes: 51 additions & 0 deletions flopy4/mf6/indexes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import pandas as pd
import xarray as xr
from xarray.core.indexes import Index, PandasIndex
from xarray.core.indexing import merge_sel_results


def alias(dataset: xr.Dataset, old_name: str, new_name: str) -> PandasIndex:
"""Alias a dimension coordinate to a coordinate with a different name."""
try:
size = dataset.sizes[old_name]
except KeyError:
try:
size = dataset.dims[old_name]
except KeyError:
size = dataset.attrs[old_name]
return PandasIndex(pd.RangeIndex(size, name=new_name), dim=old_name)


class GridIndex(Index):
def __init__(self, indices):
self._indices = indices

@classmethod
def from_variables(cls, variables):
return {
k: PandasIndex.from_variables({k: v}) for k, v in variables.items()
}

def create_variables(self, variables=None):
idx_vars = {}
for index in self._indices.values():
idx_vars.update(index.create_variables(variables))
return idx_vars

def sel(self, labels):
results = []
for k, index in self._indices.items():
if k in labels:
results.append(index.sel({k: labels[k]}))
return merge_sel_results(results)


def grid_index(dataset: xr.Dataset) -> GridIndex:
return GridIndex(
{
# k collides with npf.k so use "lay"
"lay": alias(dataset, "nlay", "lay"),
"col": alias(dataset, "ncol", "col"),
"row": alias(dataset, "nrow", "row"),
}
)
Loading
Loading