Skip to content

Commit 66ebd83

Browse files
committed
Add XGrid from_dataset helper with default to drop Field data
It's not necessary for us to have the Field data on the XGrid/xgcm.Grid object itself. It doesn't make a big difference in the end, but dropping the field data on grid ingestion would allow us to keep things logically separate.
1 parent adaa43f commit 66ebd83

1 file changed

Lines changed: 22 additions & 0 deletions

File tree

parcels/xgrid.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
_XGCM_AXIS_DIRECTION = Literal["X", "Y", "Z", "T"]
1717
_XGCM_AXIS_POSITION = Literal["center", "left", "right", "inner", "outer"]
1818
_XGCM_AXES = Mapping[_XGCM_AXIS_DIRECTION, xgcm.Axis]
19+
_DEFAULT_XGCM_KWARGS = {"periodic": False}
1920

2021

2122
def get_cell_count_along_dim(axis: xgcm.Axis) -> int:
@@ -34,6 +35,15 @@ def _get_xgrid_axes(grid: xgcm.Grid) -> list[_XGRID_AXES]:
3435
return sorted(spatial_axes, key=_XGRID_AXES_ORDERING.index)
3536

3637

38+
def drop_field_data(ds: xr.Dataset) -> xr.Dataset:
39+
"""
40+
Removes DataArrays from the dataset that are associated with field data so that
41+
when passed to the XGCM grid, the object only functions as an in memory representation
42+
of the grid.
43+
"""
44+
return ds.drop_vars(ds.data_vars)
45+
46+
3747
class XGrid(BaseGrid):
3848
"""
3949
Class to represent a structured grid in Parcels. Wraps a xgcm-like Grid object (we use a trimmed down version of the xgcm.Grid class that is vendored with Parcels).
@@ -53,6 +63,18 @@ def __init__(self, grid: xgcm.Grid, mesh="flat"):
5363
if len(set(grid.axes) & {"X", "Y", "Z"}) > 0: # Only if spatial grid is >0D (see #2054 for further development)
5464
assert_valid_lat_lon(ds["lat"], ds["lon"], grid.axes)
5565

66+
@classmethod
67+
def from_dataset(cls, ds: xr.Dataset, mesh="flat", xgcm_kwargs=None):
68+
"""WARNING: unstable API, subject to change in future versions."""
69+
if xgcm_kwargs is None:
70+
xgcm_kwargs = {}
71+
72+
xgcm_kwargs = {**_DEFAULT_XGCM_KWARGS, **xgcm_kwargs}
73+
74+
ds = drop_field_data(ds)
75+
grid = xgcm.Grid(ds, **xgcm_kwargs)
76+
return cls(grid, mesh=mesh)
77+
5678
@property
5779
def axes(self) -> list[_XGRID_AXES]:
5880
return _get_xgrid_axes(self.xgcm_grid)

0 commit comments

Comments
 (0)