Skip to content

Commit 09b5701

Browse files
authored
Include UGRID topology vars when subsetting with .cf (#648)
1 parent 730f59d commit 09b5701

4 files changed

Lines changed: 120 additions & 2 deletions

File tree

‎cf_xarray/accessor.py‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@
5555
from re import match as regex_match # type: ignore[no-redef]
5656

5757

58-
from . import parametric, sgrid
58+
from . import parametric, sgrid, ugrid
5959
from .criteria import (
6060
_DSG_ROLES,
6161
_GEOMETRY_TYPES,
@@ -2235,6 +2235,7 @@ def get_associated_variable_names(
22352235
4. "coordinates"
22362236
5. "grid_mapping"
22372237
6. "grid"
2238+
7. "mesh"
22382239
22392240
Parameters
22402241
----------
@@ -2247,7 +2248,7 @@ def get_associated_variable_names(
22472248
-------
22482249
names : dict
22492250
Dictionary with keys "ancillary_variables", "cell_measures", "coordinates", "bounds",
2250-
"grid_mapping", "grid".
2251+
"grid_mapping", "grid", "mesh".
22512252
"""
22522253
keys = [
22532254
"ancillary_variables",
@@ -2256,6 +2257,7 @@ def get_associated_variable_names(
22562257
"bounds",
22572258
"grid_mapping",
22582259
"grid",
2260+
"mesh",
22592261
"geometry",
22602262
]
22612263

@@ -2300,6 +2302,13 @@ def get_associated_variable_names(
23002302
if isinstance(self._obj, Dataset):
23012303
coords["coordinates"].extend(sgrid.get_topology_coords(self._obj, grid))
23022304

2305+
if mesh := attrs_or_encoding.get("mesh", None):
2306+
coords["mesh"] = [mesh]
2307+
if isinstance(self._obj, Dataset):
2308+
connectivity, mesh_coords = ugrid.get_mesh_variables(self._obj, mesh)
2309+
coords["mesh"].extend(connectivity)
2310+
coords["coordinates"].extend(mesh_coords)
2311+
23032312
if grid_mapping_attr := attrs_or_encoding.get("grid_mapping", None):
23042313
# Parse grid mapping variables and their coordinates
23052314
grid_mapping_dict = _parse_grid_mapping_attribute(grid_mapping_attr)

‎cf_xarray/tests/test_accessor.py‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2434,6 +2434,58 @@ def test_grid_topology() -> None:
24342434
assert "T" in ds.cf.axes
24352435

24362436

2437+
def test_ugrid_includes_topology_variables() -> None:
2438+
"""The mesh_topology variable, its connectivity, and its coordinate
2439+
variables should be pulled in by ds.cf[[var]] for a UGRID data variable."""
2440+
ds = xr.Dataset(
2441+
data_vars={
2442+
"h": (
2443+
"face",
2444+
np.zeros(2),
2445+
{"mesh": "mesh", "location": "face"},
2446+
),
2447+
},
2448+
coords={
2449+
"mesh": (
2450+
tuple(),
2451+
1,
2452+
{
2453+
"cf_role": "mesh_topology",
2454+
"topology_dimension": 2,
2455+
"node_coordinates": "node_lon node_lat",
2456+
"face_node_connectivity": "face_nodes",
2457+
"edge_node_connectivity": "edge_nodes",
2458+
"face_coordinates": "face_lon face_lat",
2459+
},
2460+
),
2461+
"node_lon": ("node", np.zeros(4)),
2462+
"node_lat": ("node", np.zeros(4)),
2463+
"face_lon": ("face", np.zeros(2)),
2464+
"face_lat": ("face", np.zeros(2)),
2465+
"face_nodes": (("face", "nvertex"), np.zeros((2, 3))),
2466+
"edge_nodes": (("edge", "two"), np.zeros((3, 2))),
2467+
},
2468+
)
2469+
2470+
assoc = ds.cf.get_associated_variable_names("h")
2471+
assert {"mesh", "face_nodes", "edge_nodes"}.issubset(set(assoc["mesh"]))
2472+
assert {"node_lon", "node_lat", "face_lon", "face_lat"}.issubset(
2473+
set(assoc["coordinates"])
2474+
)
2475+
2476+
expected = {
2477+
"mesh",
2478+
"face_nodes",
2479+
"edge_nodes",
2480+
"node_lon",
2481+
"node_lat",
2482+
"face_lon",
2483+
"face_lat",
2484+
}
2485+
subset = ds.cf[["h"]]
2486+
assert expected.issubset(set(subset.variables))
2487+
2488+
24372489
@requires_scipy
24382490
def test_curvefit() -> None:
24392491
from cf_xarray.datasets import airds

‎cf_xarray/ugrid.py‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# Connectivity attributes on a UGRID ``mesh_topology`` variable.
2+
UGRID_CONNECTIVITY_ATTRS = [
3+
"face_node_connectivity",
4+
"edge_node_connectivity",
5+
"face_edge_connectivity",
6+
"face_face_connectivity",
7+
"edge_face_connectivity",
8+
"boundary_node_connectivity",
9+
]
10+
11+
# Coordinate-variable attributes on a UGRID ``mesh_topology`` variable.
12+
UGRID_COORD_ATTRS = [
13+
"node_coordinates",
14+
"edge_coordinates",
15+
"face_coordinates",
16+
]
17+
18+
19+
def get_mesh_variables(ds, mesh_var_name):
20+
"""Return variables referenced by a UGRID ``mesh_topology`` variable.
21+
22+
Reads the connectivity attributes (``face_node_connectivity``,
23+
``edge_node_connectivity``, ...) and the coordinate attributes
24+
(``node_coordinates``, ``edge_coordinates``, ``face_coordinates``) from the
25+
mesh topology variable's attrs.
26+
27+
Returns a ``(connectivity, coordinates)`` tuple of variable-name lists,
28+
each filtered to names actually present in ``ds``.
29+
"""
30+
if mesh_var_name not in ds.variables:
31+
return [], []
32+
mesh_attrs = ds[mesh_var_name].attrs
33+
connectivity: list = []
34+
for attr_name in UGRID_CONNECTIVITY_ATTRS:
35+
if conn_str := mesh_attrs.get(attr_name):
36+
connectivity.extend(n for n in conn_str.split() if n in ds.variables)
37+
coordinates: list = []
38+
for attr_name in UGRID_COORD_ATTRS:
39+
if coord_str := mesh_attrs.get(attr_name):
40+
coordinates.extend(n for n in coord_str.split() if n in ds.variables)
41+
return connectivity, coordinates

‎doc/sgrid_ugrid.md‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,22 @@ appear as coords on `u`.
8484

8585
`cf_xarray` supports identifying the `mesh_topology` variable using the `cf_role` attribute.
8686

87+
### Connectivity and coordinate variables
88+
89+
When a data variable references a `mesh_topology` variable through its `mesh`
90+
attribute, `cf_xarray` follows that attribute when subsetting with `.cf`. The
91+
mesh topology variable, its connectivity variables (`face_node_connectivity`,
92+
`edge_node_connectivity`, `face_edge_connectivity`, `face_face_connectivity`,
93+
`edge_face_connectivity`, `boundary_node_connectivity`), and its coordinate
94+
variables (`node_coordinates`, `edge_coordinates`, `face_coordinates`) are
95+
pulled in alongside the data variable:
96+
97+
```python
98+
ds.cf[["h"]] # includes `mesh`, face_nodes, node_lon/node_lat, ...
99+
```
100+
101+
Only names actually present in the dataset are propagated.
102+
87103
## More?
88104

89105
Further support for interpreting the SGRID and UGRID conventions can be added. Contributions are welcome!

0 commit comments

Comments
 (0)