inire/inire/router/_catalog_verify.py

279 lines
12 KiB
Python

"""Geometry verification shared by catalog replay and routing."""
from __future__ import annotations
from dataclasses import dataclass
from itertools import accumulate, combinations
from math import hypot, isfinite, isnan, ulp
from typing import TYPE_CHECKING
from shapely.affinity import affine_transform
from shapely.geometry import LineString, Polygon, box
from shapely.strtree import STRtree
from inire._catalog import HEADING_STEPS, face_endpoints
from inire.geometry.collision import _violates_clearance, _violates_net_clearance
if TYPE_CHECKING:
from collections.abc import Iterable, Sequence
from shapely.geometry.base import BaseGeometry
from inire._catalog import Evaluation, Move, MoveEvaluator, Pose
@dataclass(frozen=True, slots=True)
class Attachment:
"""Permission to meet a specific fixed obstacle at one terminal."""
obstacle: BaseGeometry
region: Polygon
actual_shapes: tuple[Polygon, ...] = ()
def validate_attachment(
evaluator: MoveEvaluator,
attachment: Attachment,
pose: Pose,
keepouts: Sequence[BaseGeometry],
face_tolerance: float,
*,
source: bool,
) -> None:
if not any(attachment.obstacle is obstacle for obstacle in keepouts):
raise ValueError("An attachment must identify a registered keepout")
if attachment.region.is_empty or not attachment.region.is_valid or not attachment.region.covers(
face_reservation(pose, evaluator.catalog.profiles[pose.profile].width, 0),
):
raise ValueError("An attachment region must be valid and cover the entire terminal face")
if any(
shape.is_empty or not shape.is_valid or not attachment.obstacle.covers(shape)
for shape in attachment.actual_shapes
):
raise ValueError("Fixed attachment shapes must be valid and inside the registered keepout")
actual = attachment.actual_shapes or (attachment.obstacle,)
width = evaluator.catalog.profiles[pose.profile].width
if not _matches_face(actual, pose, width, face_tolerance, arrival=source):
raise ValueError("Fixed attachment geometry does not meet its declared port face")
def wholly_in_attachment(move: Evaluation, attachment: Attachment) -> bool:
return all(attachment.region.covers(shape) for shape in move.footprints)
def meets_attachment_clearance(
move: Evaluation,
obstacle: BaseGeometry,
permissions: Sequence[tuple[Attachment, BaseGeometry]],
clearance: float,
) -> bool:
for shape in move.footprints:
outside = shape
for attachment, _ in permissions:
if outside.intersects(attachment.region):
outside = outside.difference(attachment.region)
if not outside.is_empty and _violates_clearance(outside, obstacle, clearance):
return False
for attachment, seam in permissions:
for shape in move.port_shapes or move.footprints:
if not shape.intersects(attachment.region):
continue
inside = shape.intersection(attachment.region)
for fixed in attachment.actual_shapes or (obstacle,):
if inside.relate_pattern(fixed, "2********") and not _seam_covers(seam, inside.intersection(fixed)):
return False
return True
def face_reservation(pose: Pose, width: float, tolerance: float) -> BaseGeometry:
"""The finite face and its allowed normal displacement, in layout coordinates."""
left, right = face_endpoints(pose, width)
if tolerance == 0:
return LineString((left, right))
dx, dy = HEADING_STEPS[pose.heading]
scale = tolerance / hypot(dx, dy)
x, y = dx * scale, dy * scale
return Polygon((
(left[0] - x, left[1] - y), (right[0] - x, right[1] - y),
(right[0] + x, right[1] + y), (left[0] + x, left[1] + y),
))
def _seam_covers(seam: BaseGeometry, overlap: BaseGeometry) -> bool:
if seam.covers(overlap):
return True
roundoff = 8 * ulp(max(abs(value) for value in seam.bounds))
return seam.buffer(roundoff).covers(overlap)
def _lateral_intervals(geometry: BaseGeometry) -> Iterable[tuple[float, float]]:
if geometry.is_empty:
return
if hasattr(geometry, "geoms"):
for part in geometry.geoms:
yield from _lateral_intervals(part)
else:
yield geometry.bounds[1], geometry.bounds[3]
def _matches_face(
footprints: Sequence[BaseGeometry], pose: Pose, width: float, tolerance: float, *, arrival: bool,
) -> bool:
dx, dy = HEADING_STEPS[pose.heading]
norm = hypot(dx, dy)
x, y = dx / norm, dy / norm
# Transform the face to x=0 without rotating any stored geometry.
frame = (x, y, -y, x, -(pose.x * x + pose.y * y), pose.x * y - pose.y * x)
half_width = width / 2
# Allow roundoff from projecting the footprint along a diagonal normal.
roundoff = 8 * ulp(max(abs(pose.x), abs(pose.y), width, tolerance))
local = tuple(affine_transform(shape, frame) for shape in footprints)
def covers_face(depth: float) -> bool:
reach = half_width + depth
patch = box(-depth if arrival else 0, -reach, 0 if arrival else depth, reach)
intervals = sorted(interval for shape in local for interval in _lateral_intervals(shape.intersection(patch)))
if not intervals or abs(intervals[0][0] + half_width) > roundoff:
return False
covered = intervals[0][1]
for lo, hi in intervals[1:]:
if lo > covered + roundoff:
return False
covered = max(covered, hi)
return abs(covered - half_width) <= roundoff
return covers_face(roundoff) or (tolerance > 0 and covers_face(tolerance + roundoff))
def compatible_join(left: Evaluation, right: Evaluation, width: float, tolerance: float) -> bool:
if left.end != right.start:
return False
seam = face_reservation(left.end, width, tolerance)
for first in left.port_shapes or left.footprints:
for second in right.port_shapes or right.footprints:
if first.relate_pattern(second, "2********") and not _seam_covers(seam, first.intersection(second)):
return False
return True
def _internal_edges(path: Sequence[Evaluation], clearance: float) -> Iterable[tuple[int, int, float]]:
distances = tuple(accumulate((move.length or 0.0 for move in path), initial=0.0))
unknowns = tuple(accumulate((move.length is None for move in path), initial=0))
for i, j in combinations(range(len(path)), 2):
if j > i + 1:
separation = distances[j] - distances[i + 1]
uncertain = unknowns[j] != unknowns[i + 1]
yield i, j, clearance if uncertain or separation >= clearance else 0.0
def _colliders(tree: STRtree, shapes: Sequence[BaseGeometry], clearance: float) -> tuple[BaseGeometry, ...]:
if not len(tree) or not shapes:
return ()
bounds = [extent for shape in shapes if not isnan((extent := shape.bounds)[0])]
if not bounds:
return ()
area = box(
min(b[0] for b in bounds) - clearance, min(b[1] for b in bounds) - clearance,
max(b[2] for b in bounds) + clearance, max(b[3] for b in bounds) + clearance,
)
return tuple(tree.geometries[index] for index in tree.query(area))
def verify_move(
evaluator: MoveEvaluator,
move: Evaluation,
board: Polygon,
keepouts: Sequence[BaseGeometry],
occupied: Sequence[BaseGeometry],
clearance: float,
face_tolerance: float,
) -> str | None:
profiles = evaluator.catalog.profiles
for pose, arrival in ((move.start, False), (move.end, True)):
if not _matches_face(move.port_shapes or move.footprints, pose, profiles[pose.profile].width, face_tolerance, arrival=arrival):
return "port_face"
if any(not board.covers(shape) for shape in move.footprints):
return "board_bounds"
if any(_violates_clearance(shape, keepout, clearance) for shape in move.footprints for keepout in keepouts):
return "keepout"
if any(_violates_net_clearance(shape, other, clearance) for shape in move.footprints for other in occupied):
return "occupied"
return None
def verify_path(
evaluator: MoveEvaluator,
path: Sequence[Evaluation],
start: Pose,
target: Pose,
*,
board: Polygon,
keepouts: Sequence[BaseGeometry] = (),
occupied: Sequence[BaseGeometry] = (),
clearance: float = 0.0,
self_clearance: float = 0.0,
face_tolerance: float = 0.0,
source_attachment: Attachment | None = None,
destination_attachment: Attachment | None = None,
) -> str | None:
"""Verify a catalog path and return the first reason it cannot be placed."""
if any(value < 0 or not isfinite(value) for value in (clearance, self_clearance, face_tolerance)):
raise ValueError("Clearance and face tolerance must be finite and nonnegative")
if not path or path[0].start != start or path[-1].end != target:
return "terminal_pose"
attachments = ((source_attachment, start, True), (destination_attachment, target, False))
attached = {id(item.obstacle): item.obstacle for item, _, _ in attachments if item is not None}
ordinary_keepouts = STRtree([obstacle for obstacle in keepouts if id(obstacle) not in attached])
installed = STRtree(occupied)
permissions: dict[tuple[int, int], list[tuple[Attachment, BaseGeometry]]] = {}
for attachment, pose, source in attachments:
if attachment is None:
continue
validate_attachment(evaluator, attachment, pose, keepouts, face_tolerance, source=source)
seam = face_reservation(pose, evaluator.catalog.profiles[pose.profile].width, face_tolerance)
if any(_violates_net_clearance(seam, shape, clearance) for shape in _colliders(installed, (seam,), clearance)):
return "occupied_seam"
ordered = range(len(path)) if source else reversed(range(len(path)))
for index in ordered:
permissions.setdefault((index, id(attachment.obstacle)), []).append((attachment, seam))
if not wholly_in_attachment(path[index], attachment):
break
for index, move in enumerate(path):
for key, obstacle in attached.items():
if not meets_attachment_clearance(move, obstacle, permissions.get((index, key), ()), clearance):
return "fixed_attachment"
profiles = evaluator.catalog.profiles
for move in path:
if error := verify_move(
evaluator, move, board,
_colliders(ordinary_keepouts, move.footprints, clearance), _colliders(installed, move.footprints, clearance),
clearance, face_tolerance,
):
return error
for left, right in zip(path[:-1], path[1:], strict=True):
width = profiles[left.end.profile].width
if not compatible_join(left, right, width, face_tolerance):
return "join"
seam = face_reservation(left.end, width, face_tolerance)
if any(_violates_net_clearance(seam, other, clearance) for other in occupied):
return "occupied_seam"
for i, j, spacing in _internal_edges(path, self_clearance):
if any(_violates_net_clearance(a, b, spacing) for a in path[i].footprints for b in path[j].footprints):
return "self_clearance"
return None
def replay_moves(
evaluator: MoveEvaluator,
start: Pose,
moves: Sequence[Move],
) -> tuple[Evaluation, ...] | None:
"""Materialize a sequence without proposing alternatives."""
current = start
placements = []
for move in moves:
evaluated = evaluator.evaluate(move, current)
if evaluated is None:
return None
placements.append(evaluated)
current = evaluated.end
return tuple(placements)