Skip to content

Commit

Permalink
Add Ugrid2d.bounding_polygon
Browse files Browse the repository at this point in the history
  • Loading branch information
Huite committed Aug 12, 2023
1 parent ea4828d commit ebf78d1
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 0 deletions.
1 change: 1 addition & 0 deletions docs/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,7 @@ UGRID2D Topology
Ugrid2d.bounds
Ugrid2d.edge_bounds
Ugrid2d.face_bounds
Ugrid2d.polygon_bounds

Ugrid2d.node_node_connectivity
Ugrid2d.node_edge_connectivity
Expand Down
4 changes: 4 additions & 0 deletions docs/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ Added
- :meth:`xugrid.UgridDatasetAccessor.rename` and
:meth:`xugrid.UgridDataArrayAccessor.rename` to rename both topology and the
associated dimensions.
- :meth:`xugrid.Ugrid2d.polygon_bounds` has been added to get a polygon
describing the bounds of the grid.

Fixed
~~~~~
Expand All @@ -46,6 +48,8 @@ Fixed
reference system).
- :meth:`xugrid.UgridDatasetAccessor.to_geodataframe` will no longer error when
converting a UgridDataset that does not contain any variables.
- :meth:`xugrid.OverlapRegridder.regrid` will no longer give incorrect results
on repeated calls with the "mode" method.

Changed
~~~~~~~
Expand Down
7 changes: 7 additions & 0 deletions tests/test_ugrid2d.py
Original file line number Diff line number Diff line change
Expand Up @@ -901,6 +901,13 @@ def test_from_geodataframe():
assert isinstance(grid, xugrid.Ugrid2d)


def test_bounding_polygon():
grid = grid2d()
polygon = grid.bounding_polygon()
assert isinstance(polygon, shapely.Polygon)
assert np.allclose(grid.bounds, polygon.bounds)


def test_to_shapely():
grid = grid2d()

Expand Down
16 changes: 16 additions & 0 deletions xugrid/ugrid/ugrid2d.py
Original file line number Diff line number Diff line change
Expand Up @@ -1671,3 +1671,19 @@ def to_shapely(self, dim):
f"Dimension {dim} is not a face, node, or edge dimension of the"
" Ugrid2d topology."
)

def bounding_polygon(self) -> "shapely.Polygon": # type: ignore # noqa
"""
Construct the bounding polygon of the grid.
This polygon may include holes if the grid also contains holes.
"""
import shapely

def _bbox_area(bounds):
return (bounds[2] - bounds[0]) * (bounds[3] - bounds[1])

edges = self.node_coordinates[self.boundary_node_connectivity]
collection = shapely.polygonize(shapely.linestrings(edges))
polygon = max(collection.geoms, key=lambda x: _bbox_area(x.bounds))
return polygon

0 comments on commit ebf78d1

Please sign in to comment.