# Copyright 2025–2026 European Union
# Author: Bulgheroni Antonio (antonio.bulgheroni@ec.europa.eu)
# SPDX-License-Identifier: EUPL-1.2
"""
Module for polygon geometry operations.
This module provides functions for computing polygon properties such as signed area
and normalizing polygon vertex order. It is designed to work with NumPy arrays
representing polygon vertices.
"""
from __future__ import annotations
import numpy as np
[docs]
def polygon_signed_area(vertices: np.ndarray) -> float:
"""
Compute the signed area of a polygon using the shoelace formula.
This function calculates the signed area of a polygon defined by its vertices.
The sign indicates the orientation of the polygon: positive for counter-clockwise
ordering, negative for clockwise ordering.
:param vertices: Array of polygon vertices with shape (N, 2)
:type vertices: numpy.ndarray
:return: Signed area of the polygon
:rtype: float
:raises ValueError: if vertices array does not have the correct shape
"""
x = vertices[:, 0]
y = vertices[:, 1]
return float(0.5 * np.sum(x[:-1] * y[1:] - x[1:] * y[:-1]))
[docs]
def normalize_polygon_ccw(vertices: np.ndarray) -> np.ndarray:
"""
Normalize polygon vertices to be ordered counter-clockwise and closed.
This function ensures that polygon vertices are ordered in counter-clockwise
direction and that the polygon is closed (first and last vertices are identical).
:param vertices: Array of polygon vertices with shape (N, 2)
:type vertices: numpy.ndarray
:return: Vertices ordered CCW and closed
:rtype: numpy.ndarray
:raises ValueError: if vertices array does not have the correct shape
"""
if not np.allclose(vertices[0], vertices[-1]):
vertices = np.vstack([vertices, vertices[0]])
if polygon_signed_area(vertices) < 0:
vertices = vertices[::-1]
return vertices