inire/inire/geometry/index_helpers.py
Jan Petykiewicz 23d0a140c1 Use physical clearance for fixed routes and terminal bounds
Use the same physical clearance rule for fixed-route admission and verification. Preserve imported vertices while clearing GEOS precision metadata. Count touching terminal faces as conflicts at zero clearance.
2026-11-29 16:36:54 -08:00

60 lines
1.9 KiB
Python

from __future__ import annotations
import math
from typing import TYPE_CHECKING
import numpy
from shapely import get_precision, set_precision
if TYPE_CHECKING:
from collections.abc import Iterator, Mapping
from shapely.geometry import Polygon
from shapely.geometry.base import BaseGeometry
def floating_polygon(polygon: Polygon) -> Polygon:
"""Clear the GEOS precision model without moving any vertices."""
if get_precision(polygon):
return set_precision(polygon, 0, mode="pointwise")
return polygon
def build_index_payload(
geometries: Mapping[int, BaseGeometry],
) -> tuple[list[int], list[BaseGeometry], numpy.ndarray]:
obj_ids = sorted(geometries)
ordered_geometries = [geometries[obj_id] for obj_id in obj_ids]
bounds_array = numpy.array([geometry.bounds for geometry in ordered_geometries], dtype=numpy.float64)
if not ordered_geometries:
bounds_array = bounds_array.reshape(0, 4)
return obj_ids, ordered_geometries, bounds_array
def grid_cell_span(
bounds: tuple[float, float, float, float],
cell_size: float,
) -> tuple[int, int, int, int]:
return (
math.floor(bounds[0] / cell_size),
math.floor(bounds[1] / cell_size),
math.floor(bounds[2] / cell_size),
math.floor(bounds[3] / cell_size),
)
def grid_cell_count(span: tuple[int, int, int, int]) -> int:
gx_min, gy_min, gx_max, gy_max = span
return (gx_max - gx_min + 1) * (gy_max - gy_min + 1)
def iter_grid_cells(span: tuple[int, int, int, int]) -> Iterator[tuple[int, int]]:
gx_min, gy_min, gx_max, gy_max = span
for gx in range(gx_min, gx_max + 1):
for gy in range(gy_min, gy_max + 1):
yield (gx, gy)
def is_axis_aligned_rect(geometry: BaseGeometry, *, tolerance: float = 1e-4) -> bool:
bounds = geometry.bounds
area = (bounds[2] - bounds[0]) * (bounds[3] - bounds[1])
return abs(geometry.area - area) < tolerance