diff --git a/test/io/test_ugrid_coordinates.py b/test/io/test_ugrid_coordinates.py new file mode 100644 index 000000000..0c5e2d733 --- /dev/null +++ b/test/io/test_ugrid_coordinates.py @@ -0,0 +1,186 @@ +import numpy as np +import pytest +import xarray as xr + +import uxarray as ux + + +def _mesh(): + return xr.Dataset( + { + "mesh": ((), 0, { + "cf_role": "mesh_topology", "topology_dimension": 2, + "node_coordinates": "x y", "face_node_connectivity": "faces", + }), + "x": ("nodes", [0.0, 1.0, 0.0]), + "y": ("nodes", [0.0, 0.0, 1.0]), + "faces": (("cells", "corners"), [[0, 1, 2]], {"start_index": 0}), + } + ) + + +@pytest.mark.parametrize("chunks", [None, {}]) +def test_geographic_coordinates_selected_by_standard_name(tmp_path, chunks): + ds = _mesh() + ds.x.attrs["standard_name"] = "longitude" + ds.y.attrs["standard_name"] = "latitude" + ds.mesh.attrs["node_coordinates"] = "y x" + ds["center_x"] = ("cells", [0.33], {"standard_name": "longitude"}) + ds["center_y"] = ("cells", [0.33], {"standard_name": "latitude"}) + ds.mesh.attrs["face_coordinates"] = "center_y center_x" + path = tmp_path / "geographic.nc" + ds.to_netcdf(path) + grid = ux.open_grid(path, chunks=chunks) + np.testing.assert_array_equal(grid.node_lon.values, ds.x.values) + np.testing.assert_array_equal(grid.node_lat.values, ds.y.values) + np.testing.assert_array_equal(grid.face_lon.values, ds.center_x.values) + assert "x" in ds and "node_lon" not in ds + if chunks is not None: + assert grid.node_lon.chunks is not None + + +@pytest.mark.parametrize("metadata", ["standard_name", "m", "feet", "km", "mapping"]) +def test_projected_nodes_load_with_warning(tmp_path, metadata): + ds = _mesh() + # 360 m apart, so reading meters as degrees would merge the nodes. + ds.x.values[:] = [500000, 500360, 500000] + ds.y.values[:] = [4000000, 4000000, 4000360] + if metadata == "standard_name": + ds.x.attrs[metadata] = "projection_x_coordinate" + ds.y.attrs[metadata] = "projection_y_coordinate" + elif metadata == "mapping": + ds["crs"] = ((), 0, {"grid_mapping_name": "lambert_conformal_conic"}) + ds.x.attrs["grid_mapping"] = ds.y.attrs["grid_mapping"] = "crs" + else: + ds.x.attrs["units"] = ds.y.attrs["units"] = metadata + path = tmp_path / "utm.nc" + ds.to_netcdf(path) + for source in (ds, path): + with pytest.warns(UserWarning, match="Projected"): + grid = ux.open_grid(source) + grid.node_lon # noqa: B018 + np.testing.assert_array_equal(grid.node_lon.values, ds.x.values) + np.testing.assert_array_equal(grid.face_node_connectivity.values, [[0, 1, 2]]) + grid.get_dual() # raised "Duplicate nodes found" when meters were read as degrees + + +def test_projected_coordinates_retained_with_geographic_nodes(): + ds = _mesh() + ds = ds.rename(x="node_x", y="node_y") + ds.node_x.attrs = {"standard_name": "projection_x_coordinate", "units": "m"} + ds.node_y.attrs = {"standard_name": "projection_y_coordinate", "units": "m"} + ds["lon"] = ("nodes", [0.0, 1.0, 0.0], {"standard_name": "longitude"}) + ds["lat"] = ("nodes", [0.0, 0.0, 1.0], {"standard_name": "latitude"}) + ds.mesh.attrs["node_coordinates"] = "node_x node_y lat lon" + ds["face_x"] = ("cells", [500000.0], {"standard_name": "projection_x_coordinate"}) + ds["face_y"] = ("cells", [4000000.0], {"standard_name": "projection_y_coordinate"}) + ds.mesh.attrs["face_coordinates"] = "face_x face_y" + grid = ux.open_grid(ds) + np.testing.assert_array_equal(grid._ds.node_x_projected.values, ds.node_x.values) + np.testing.assert_array_equal(grid._ds.face_x_projected.values, ds.face_x.values) + assert "node_x" not in grid._ds and "face_x" not in grid._ds + assert np.isfinite(grid.face_areas.values).all() + assert 0 < grid.node_x.values.max() <= 1 + assert 0 < grid.face_lon.values[0] < 1 + + +def test_legacy_geographic_coordinates_without_metadata(): + ds = _mesh() + grid = ux.open_grid(ds) + np.testing.assert_array_equal(grid.node_lon.values, ds.x.values) + np.testing.assert_array_equal(grid.node_lat.values, ds.y.values) + + +@pytest.mark.parametrize("units", ["deg", "degrees", "degree_east", "radians", "rad"]) +@pytest.mark.parametrize("chunks", [None, {}]) +def test_angular_units_are_accepted_and_radians_converted(units, chunks, tmp_path): + ds = _mesh() + ds.x.attrs["units"] = ds.y.attrs["units"] = units + expected = ds.x.values.copy() + if units in ("radians", "rad"): + ds.x.values[:] = np.deg2rad(ds.x.values) + ds.y.values[:] = np.deg2rad(ds.y.values) + path = tmp_path / "angular.nc" + ds.to_netcdf(path) + grid = ux.open_grid(path, chunks=chunks) + np.testing.assert_allclose(grid.node_lon.values, expected) + np.testing.assert_allclose(grid.node_lat.values, ds.y.values if units not in ("radians", "rad") else np.rad2deg(ds.y.values)) + if chunks is not None: + assert grid.node_lon.chunks is not None + + +def test_partial_geographic_metadata_uses_positional_fallback(): + ds = _mesh() + ds.x.attrs["standard_name"] = "longitude" + ds.y.attrs["units"] = "degrees_north" + grid = ux.open_grid(ds) + np.testing.assert_array_equal(grid.node_lon.values, ds.x.values) + np.testing.assert_array_equal(grid.node_lat.values, ds.y.values) + + +def test_projected_face_coordinates_do_not_break_face_centers(): + ds = _mesh() + ds["face_x"] = ("cells", [500000.0], {"standard_name": "projection_x_coordinate"}) + ds["face_y"] = ("cells", [4000000.0], {"standard_name": "projection_y_coordinate"}) + ds.mesh.attrs["face_coordinates"] = "face_x face_y" + grid = ux.open_grid(ds) + assert 0 < grid.face_lon.values[0] < 1 + + +@pytest.mark.parametrize( + "units, used", [("deg", True), ("degrees_east", True), ("m", False)] +) +def test_face_coordinates_used_only_when_geographic(units, used): + ds = _mesh() + ds["cx"] = ("cells", [0.3], {"units": units}) + ds["cy"] = ("cells", [0.3], {"units": units}) + ds.mesh.attrs["face_coordinates"] = "cx cy" + grid = ux.open_grid(ds) + assert (grid.face_lon.values[0] == 0.3) == used + + +def test_coordinates_selected_by_cf_units(): + ds = _mesh() + ds.x.attrs["units"] = "degrees_east" + ds.y.attrs["units"] = "degrees_north" + ds.mesh.attrs["node_coordinates"] = "y x" + grid = ux.open_grid(ds) + np.testing.assert_array_equal(grid.node_lon.values, ds.x.values) + np.testing.assert_array_equal(grid.node_lat.values, ds.y.values) + + +def test_single_identified_coordinate_orders_positional_pair(): + ds = _mesh() + ds.y.attrs["units"] = "degrees_north" + ds.mesh.attrs["node_coordinates"] = "y x" + grid = ux.open_grid(ds) + np.testing.assert_array_equal(grid.node_lat.values, ds.y.values) + + +def test_non_string_units_are_ignored(): + ds = _mesh() + ds.x.attrs["units"] = ds.y.attrs["units"] = 1 + grid = ux.open_grid(ds) + np.testing.assert_array_equal(grid.node_lon.values, ds.x.values) + + +@pytest.mark.parametrize("chunks", [None, {}]) +def test_radian_face_and_edge_coordinates_converted(tmp_path, chunks): + ds = _mesh() + ds["edges"] = (("edg", "two"), [[0, 1], [1, 2], [2, 0]], {"start_index": 0}) + ds["cx"] = ("cells", [np.pi / 4], {"units": "radians"}) + ds["cy"] = ("cells", [np.pi / 2], {"units": "radians"}) + ds["ex"] = ("edg", [np.pi / 2] * 3, {"units": "rad"}) + ds["ey"] = ("edg", [np.pi / 2] * 3, {"units": "rad"}) + ds.mesh.attrs.update( + face_coordinates="cx cy", edge_coordinates="ex ey", edge_node_connectivity="edges" + ) + path = tmp_path / "radians.nc" + ds.to_netcdf(path) + grid = ux.open_grid(path, chunks=chunks) + if chunks is not None: + assert grid._ds.face_lat.chunks is not None + np.testing.assert_allclose(grid.face_lon.values, [45.0]) + np.testing.assert_allclose(grid.face_lat.values, [90.0]) + np.testing.assert_allclose(grid.edge_lat.values, [90.0] * 3) + assert grid.face_lat.attrs["units"] == grid.edge_lon.attrs["units"] == "degrees" diff --git a/uxarray/grid/coordinates.py b/uxarray/grid/coordinates.py index 7a97f3b0b..118fd8e48 100644 --- a/uxarray/grid/coordinates.py +++ b/uxarray/grid/coordinates.py @@ -671,6 +671,30 @@ def _construct_edge_centroids(node_x, node_y, node_z, edge_node_conn): return _normalize_xyz(centroid_x, centroid_y, centroid_z) +# CF 1.11 4.1/4.2 units for latitude and longitude, lowercased for comparison. +_LON_UNITS = { + "degrees_east", + "degree_east", + "degree_e", + "degrees_e", + "degreee", + "degreese", +} +_LAT_UNITS = { + "degrees_north", + "degree_north", + "degree_n", + "degrees_n", + "degreen", + "degreesn", +} +_ANGULAR_UNITS = ( + _LON_UNITS | _LAT_UNITS | {"degrees", "degree", "deg", "rad", "radian", "radians"} +) +_RADIAN_UNITS = {"rad", "radian", "radians"} +_LENGTH_UNITS = {"m", "km", "meter", "meters", "metre", "metres", "ft", "feet"} + + def _is_projected_grid(uxgrid) -> bool: """Return True if the grid uses projected (non-spherical) coordinates. @@ -687,11 +711,15 @@ def _is_projected_grid(uxgrid) -> bool: Falls back to ``False`` (geographic) when no signal is found, preserving backward compatibility with all existing geographic UGRID files. """ - if "node_lon" not in uxgrid._ds: + return _is_projected_ds(uxgrid._ds) + + +def _is_projected_ds(ds) -> bool: + """``_is_projected_grid`` for a raw grid dataset, before it is wrapped.""" + if "node_lon" not in ds: return False - da = uxgrid._ds["node_lon"] - attrs = da.attrs + attrs = ds["node_lon"].attrs # 1. standard_name stdname = attrs.get("standard_name", "") or "" @@ -704,17 +732,6 @@ def _is_projected_grid(uxgrid) -> bool: # Guard against non-string values (e.g. None) before calling .lower(). raw_units = attrs.get("units", "") units = raw_units.lower().strip() if isinstance(raw_units, str) else "" - _ANGULAR_UNITS = { - "degrees_east", - "degree_east", - "degree_e", - "degrees", - "degree", - "deg", - "rad", - "radians", - } - _LENGTH_UNITS = {"m", "km", "meter", "meters", "metre", "metres", "ft", "feet"} if units in _LENGTH_UNITS: return True if units in _ANGULAR_UNITS: @@ -722,8 +739,8 @@ def _is_projected_grid(uxgrid) -> bool: # 3. grid_mapping variable gm_name = attrs.get("grid_mapping", "") or "" - if gm_name and gm_name in uxgrid._ds: - gm_attrs = uxgrid._ds[gm_name].attrs + if gm_name and gm_name in ds: + gm_attrs = ds[gm_name].attrs gm_name_val = gm_attrs.get("grid_mapping_name", "latitude_longitude") if gm_name_val != "latitude_longitude": return True diff --git a/uxarray/grid/grid.py b/uxarray/grid/grid.py index b5e5909bb..d9bd1f777 100644 --- a/uxarray/grid/grid.py +++ b/uxarray/grid/grid.py @@ -41,6 +41,7 @@ _spec_guarantees_unique_nodes, ) from uxarray.grid.coordinates import ( + _is_projected_ds, _populate_edge_centroids, _populate_face_centerpoints, _populate_face_centroids, @@ -196,7 +197,11 @@ def __init__( # Internally generated formats known to have unique vertices skip the # search. File-backed formats are checked regardless of their usual layout. duplicate_node_map = None - if merge_coincident_nodes: + # The search reads node_lon/node_lat as degrees, so on projected + # coordinates it would report nodes that are not coincident. + if _is_projected_ds(grid_ds): + duplicate_node_map = {} + elif merge_coincident_nodes: if _spec_guarantees_unique_nodes(source_grid_spec): duplicate_node_map = {} else: diff --git a/uxarray/io/_ugrid.py b/uxarray/io/_ugrid.py index a44e25306..d5ab141dc 100644 --- a/uxarray/io/_ugrid.py +++ b/uxarray/io/_ugrid.py @@ -5,6 +5,37 @@ from uxarray.conventions import ugrid from uxarray.errors import GridInvalidError from uxarray.grid.connectivity import _replace_fill_values +from uxarray.grid.coordinates import ( + _ANGULAR_UNITS, + _LAT_UNITS, + _LON_UNITS, + _RADIAN_UNITS, +) + + +def _units(attrs): + units = attrs.get("units", "") + return units.strip().lower() if isinstance(units, str) else "" + + +def _cf_role(attrs): + """'lon', 'lat' or None. CF 1.11 4.1/4.2 identify latitude and longitude by + their units; standard_name is an optional extra.""" + if attrs.get("standard_name") == "longitude" or _units(attrs) in _LON_UNITS: + return "lon" + if attrs.get("standard_name") == "latitude" or _units(attrs) in _LAT_UNITS: + return "lat" + return None + + +def _is_geographic(ds, names): + """Whether coordinates carry no projection metadata (projected standard + names or length units), so they can be read as longitude and latitude.""" + return all( + not str(ds[name].attrs.get("standard_name", "")).startswith("projection_") + and _units(ds[name].attrs) in _ANGULAR_UNITS | {""} + for name in names + ) def _read_ugrid(ds): @@ -15,31 +46,52 @@ def _read_ugrid(ds): grid_topology_name = next(iter(ds.filter_by_attrs(cf_role="mesh_topology").keys())) ds = ds.rename({grid_topology_name: "grid_topology"}) - # get the names of node_lon and node_lat - node_lon_name, node_lat_name = ds["grid_topology"].node_coordinates.split() - coord_dict = { - node_lon_name: ugrid.NODE_COORDINATES[0], - node_lat_name: ugrid.NODE_COORDINATES[1], + coord_dict = {} + projected_dict = {} + reserved = { + *ugrid.CARTESIAN_NODE_COORDINATES, + *ugrid.CARTESIAN_EDGE_COORDINATES, + *ugrid.CARTESIAN_FACE_COORDINATES, } - if ( - "edge_lon" in ds - and "edge_lat" in ds - and "edge_coordinates" in ds["grid_topology"].attrs - ): - # get the names of edge_lon and edge_lat, if they exist - edge_lon_name, edge_lat_name = ds["grid_topology"].edge_coordinates.split() - coord_dict[edge_lon_name] = ugrid.EDGE_COORDINATES[0] - coord_dict[edge_lat_name] = ugrid.EDGE_COORDINATES[1] - if ( - "face_lon" in ds - and "face_lat" in ds - and "face_coordinates" in ds["grid_topology"].attrs - ): - # get the names of face_lon and face_lat, if they exist - face_lon_name, face_lat_name = ds["grid_topology"].face_coordinates.split() - coord_dict[face_lon_name] = ugrid.FACE_COORDINATES[0] - coord_dict[face_lat_name] = ugrid.FACE_COORDINATES[1] - + for location in ("node", "edge", "face"): + attribute = f"{location}_coordinates" + if attribute not in ds["grid_topology"].attrs: + continue + names = ds["grid_topology"].attrs[attribute].split() + roles = {name: _cf_role(ds[name].attrs) for name in names} + lons = [name for name in names if roles[name] == "lon"] + lats = [name for name in names if roles[name] == "lat"] + if len(lons) == 1 and len(lats) == 1: + lon_name, lat_name = lons[0], lats[0] + elif len(names) == 2 and (location == "node" or _is_geographic(ds, names)): + # Positional, unless the one coordinate that is identified says + # otherwise. Projected nodes stay on this path so Grid can warn. + if lats == [names[0]] or lons == [names[1]]: + lat_name, lon_name = names + else: + lon_name, lat_name = names + elif location == "node": + raise GridInvalidError( + "UGRID node_coordinates must identify one longitude and one latitude " + "(standard_name 'longitude'/'latitude' or units such as " + "'degrees_east'/'degrees_north'), or name exactly two coordinates." + ) + else: + lon_name = lat_name = None + for name in names: + if name not in (lon_name, lat_name) and name in reserved: + projected_dict[name] = f"{name}_projected" + if lon_name is None: + continue + for name in (lon_name, lat_name): + if _units(ds[name].attrs) in _RADIAN_UNITS: + ds[name] = np.rad2deg(ds[name]).assign_attrs( + {**ds[name].attrs, "units": "degrees"} + ) + coord_dict[lon_name] = f"{location}_lon" + coord_dict[lat_name] = f"{location}_lat" + + coord_dict.update(projected_dict) ds = ds.rename(coord_dict) conn_dict = {}