Skip to content

Commit 7f1467a

Browse files
authored
feat: add validation for vertices in GridFromPolygon (#242)
1 parent 4ae4c6f commit 7f1467a

2 files changed

Lines changed: 15 additions & 2 deletions

File tree

src/useq/_grid.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -458,12 +458,18 @@ class GridFromPolygon(_GridPlan[AbsolutePosition]):
458458
def is_relative(self) -> bool:
459459
return False
460460

461+
@field_validator("vertices", mode="after")
462+
def validate_vertices(
463+
cls, value: list[tuple[float, float]]
464+
) -> list[tuple[float, float]]:
465+
if not Polygon(value).is_valid:
466+
raise ValueError("Invalid or self-intersecting polygon.")
467+
return value
468+
461469
@property
462470
def poly(self) -> Polygon:
463471
"""Return the processed polygon vertices as a shapely Polygon."""
464472
poly = Polygon(self.vertices)
465-
if not poly.is_valid:
466-
raise ValueError("Invalid or self-intersecting polygon.")
467473

468474
# Apply offset if specified
469475
if self.offset is not None:

tests/test_grid_and_points_plans.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -354,3 +354,10 @@ def test_grid_from_polygon_with_convex_hull() -> None:
354354
overlap=0,
355355
)
356356
assert grid_with_hull.num_positions() == 9
357+
358+
359+
def test_invalid_poly() -> None:
360+
"""Test that self-intersecting polygons are invalid."""
361+
vertices = [(0, 0), (2, 2), (0, 2), (2, 0)]
362+
with pytest.raises(ValueError, match="Invalid or self-intersecting polygon"):
363+
useq.GridFromPolygon(vertices=vertices, fov_width=1, fov_height=1)

0 commit comments

Comments
 (0)