From e683a75ed251d7a3f7ce6134d56652ca12ac7445 Mon Sep 17 00:00:00 2001 From: Talley Lambert Date: Fri, 15 Aug 2025 16:11:20 -0400 Subject: [PATCH] feat: add validation for vertices in GridFromPolygon --- src/useq/_grid.py | 10 ++++++++-- tests/test_grid_and_points_plans.py | 7 +++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/src/useq/_grid.py b/src/useq/_grid.py index fc35592e..2ad9ebe8 100644 --- a/src/useq/_grid.py +++ b/src/useq/_grid.py @@ -458,12 +458,18 @@ class GridFromPolygon(_GridPlan[AbsolutePosition]): def is_relative(self) -> bool: return False + @field_validator("vertices", mode="after") + def validate_vertices( + cls, value: list[tuple[float, float]] + ) -> list[tuple[float, float]]: + if not Polygon(value).is_valid: + raise ValueError("Invalid or self-intersecting polygon.") + return value + @property def poly(self) -> Polygon: """Return the processed polygon vertices as a shapely Polygon.""" poly = Polygon(self.vertices) - if not poly.is_valid: - raise ValueError("Invalid or self-intersecting polygon.") # Apply offset if specified if self.offset is not None: diff --git a/tests/test_grid_and_points_plans.py b/tests/test_grid_and_points_plans.py index 55c21841..8c6844a2 100644 --- a/tests/test_grid_and_points_plans.py +++ b/tests/test_grid_and_points_plans.py @@ -354,3 +354,10 @@ def test_grid_from_polygon_with_convex_hull() -> None: overlap=0, ) assert grid_with_hull.num_positions() == 9 + + +def test_invalid_poly() -> None: + """Test that self-intersecting polygons are invalid.""" + vertices = [(0, 0), (2, 2), (0, 2), (2, 0)] + with pytest.raises(ValueError, match="Invalid or self-intersecting polygon"): + useq.GridFromPolygon(vertices=vertices, fov_width=1, fov_height=1)