Skip to content

Commit 87fa240

Browse files
authored
Include topology vars when subsetting with .cf (#640)
1 parent 192f107 commit 87fa240

4 files changed

Lines changed: 81 additions & 0 deletions

File tree

‎cf_xarray/accessor.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2269,6 +2269,8 @@ def get_associated_variable_names(
22692269

22702270
if grid := attrs_or_encoding.get("grid", None):
22712271
coords["grid"] = [grid]
2272+
if isinstance(self._obj, Dataset):
2273+
coords["coordinates"].extend(sgrid.get_topology_coords(self._obj, grid))
22722274

22732275
if grid_mapping_attr := attrs_or_encoding.get("grid_mapping", None):
22742276
# Parse grid mapping variables and their coordinates

‎cf_xarray/sgrid.py‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,31 @@
1111
# "edge3_dimensions",
1212
]
1313

14+
SGRID_COORD_ATTRS = [
15+
"node_coordinates",
16+
"face_coordinates",
17+
"edge1_coordinates",
18+
"edge2_coordinates",
19+
"volume_coordinates",
20+
]
21+
22+
23+
def get_topology_coords(ds, grid_var_name):
24+
"""Return coordinate variable names referenced by an SGRID topology variable.
25+
26+
Reads ``node_coordinates``, ``face_coordinates``, ``edge{1,2}_coordinates``,
27+
and ``volume_coordinates`` from the topology variable's attrs and filters
28+
to names that are actually present in ``ds``.
29+
"""
30+
if grid_var_name not in ds.variables:
31+
return []
32+
grid_attrs = ds[grid_var_name].attrs
33+
names: list[str] = []
34+
for attr_name in SGRID_COORD_ATTRS:
35+
if coord_str := grid_attrs.get(attr_name):
36+
names.extend(n for n in coord_str.split() if n in ds.variables)
37+
return names
38+
1439

1540
def parse_axes(ds):
1641
import re

‎cf_xarray/tests/test_accessor.py‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2484,6 +2484,43 @@ def test_sgrid():
24842484
}
24852485

24862486

2487+
def test_sgrid_includes_topology_coordinates():
2488+
"""Variables referenced in node/face/edge/volume_coordinates of the
2489+
grid_topology variable should be pulled in by ds.cf[[var]]."""
2490+
roms = sgrid_roms.copy()
2491+
for pos in ("psi", "rho", "u", "v"):
2492+
roms[f"lon_{pos}"] = ((f"xi_{pos}", f"eta_{pos}"), np.zeros((2, 2)))
2493+
roms[f"lat_{pos}"] = ((f"xi_{pos}", f"eta_{pos}"), np.zeros((2, 2)))
2494+
2495+
expected_coord_vars = {
2496+
"lon_psi",
2497+
"lat_psi",
2498+
"lon_rho",
2499+
"lat_rho",
2500+
"lon_u",
2501+
"lat_u",
2502+
"lon_v",
2503+
"lat_v",
2504+
}
2505+
assoc = roms.cf.get_associated_variable_names("u")
2506+
assert expected_coord_vars.issubset(set(assoc["coordinates"]))
2507+
2508+
subset = roms.cf[["u"]]
2509+
assert "grid" in subset.variables
2510+
assert expected_coord_vars.issubset(set(subset.variables))
2511+
2512+
# only dim-compatible coords attach to the DataArray form
2513+
u_da = roms.cf["u"]
2514+
assert {"lon_u", "lat_u"}.issubset(set(u_da.coords))
2515+
2516+
delft = sgrid_delft.copy()
2517+
delft["node_lon"] = (("inode", "jnode"), np.zeros((2, 2)))
2518+
delft["node_lat"] = (("inode", "jnode"), np.zeros((2, 2)))
2519+
delft["foo"] = (("icell", "jcell"), np.ones((2, 2)), {"grid": "grid"})
2520+
delft_subset = delft.cf[["foo"]]
2521+
assert {"grid", "node_lon", "node_lat"}.issubset(set(delft_subset.variables))
2522+
2523+
24872524
def test_ancillary_variables_extra_dim():
24882525
ds = xr.Dataset(
24892526
{

‎doc/sgrid_ugrid.md‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,23 @@ only `xi_u`, `eta_u` are listed in the repr even though the attributes on the `g
6161
variable `grid` list many more dimension names.
6262
```
6363

64+
### Coordinate variables
65+
66+
`cf_xarray` also follows the `node_coordinates`, `face_coordinates`,
67+
`edge1_coordinates`, `edge2_coordinates`, and `volume_coordinates` attributes
68+
on the `grid_topology` variable. When you select a data variable that
69+
references a `grid_topology` via its `grid` attribute, the referenced
70+
coordinate variables are pulled in alongside it:
71+
72+
```python
73+
ds.cf[["u"]] # includes `grid`, lon_psi/lat_psi, lon_rho/lat_rho, ...
74+
```
75+
76+
Only names actually present in the dataset are propagated. For the
77+
`DataArray` form (`ds.cf["u"]`) xarray only attaches coordinates whose
78+
dimensions are compatible with the variable, so e.g. only `lon_u`/`lat_u`
79+
appear as coords on `u`.
80+
6481
## UGRID
6582

6683
### Topology variable

0 commit comments

Comments
 (0)