142 lines
5.6 KiB
Python
142 lines
5.6 KiB
Python
"""Sparse coarse corridors and exact grid selection for catalog routing."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass
|
|
from heapq import heappop, heappush
|
|
from itertools import count
|
|
from math import gcd, hypot, inf
|
|
from typing import TYPE_CHECKING
|
|
|
|
from shapely.geometry import LineString, Point, box
|
|
from shapely.strtree import STRtree
|
|
|
|
from inire._catalog import HEADING_STEPS, FixedVariant, Grid, _require_integer, _require_positive
|
|
from inire.geometry.collision import _violates_clearance
|
|
|
|
if TYPE_CHECKING:
|
|
from collections.abc import Sequence
|
|
|
|
from shapely.geometry.base import BaseGeometry
|
|
|
|
from inire._catalog import Catalog, Pose
|
|
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class AutomaticGrid:
|
|
"""Select a compatible divisor of a preferred routing pitch in layout units."""
|
|
|
|
preferred_pitch: int
|
|
meters_per_unit: float
|
|
|
|
def __post_init__(self) -> None:
|
|
_require_integer(self.preferred_pitch)
|
|
_require_positive("Preferred grid pitch", self.preferred_pitch)
|
|
_require_positive("Layout unit in meters", self.meters_per_unit)
|
|
|
|
def select(self, terminals: Sequence[Pose], catalog: Catalog) -> Grid:
|
|
origin = (terminals[0].x, terminals[0].y) if terminals else (0, 0)
|
|
pitch = int(self.preferred_pitch)
|
|
for pose in terminals:
|
|
pitch = gcd(pitch, pose.x - origin[0], pose.y - origin[1])
|
|
for variant in catalog.variants.values():
|
|
if isinstance(variant, FixedVariant):
|
|
a, b = variant.ports.values()
|
|
# Accepted fixed orientations swap or negate the axis differences.
|
|
pitch = gcd(pitch, a.x - b.x, a.y - b.y)
|
|
return Grid(origin, pitch, self.meters_per_unit)
|
|
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class CoarseGuidance:
|
|
"""Coarse corridor search budget, independent of the realization pitch."""
|
|
|
|
pitch: int
|
|
node_limit: int = 4000
|
|
|
|
def __post_init__(self) -> None:
|
|
_require_integer(self.pitch)
|
|
_require_integer(self.node_limit)
|
|
_require_positive("Coarse guidance pitch", self.pitch)
|
|
if self.node_limit < 0:
|
|
raise ValueError("Coarse guidance node limit must be nonnegative")
|
|
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class Corridor:
|
|
points: tuple[tuple[int, int], ...]
|
|
region: BaseGeometry
|
|
|
|
def admits(self, pose: Pose) -> bool:
|
|
return self.region.covers(Point(pose.x, pose.y))
|
|
|
|
|
|
def find_corridor(
|
|
start: Pose, target: Pose, settings: CoarseGuidance, *,
|
|
board: BaseGeometry, obstacles: Sequence[BaseGeometry], margin: float,
|
|
) -> tuple[Corridor | None, int]:
|
|
"""Guide on a coarse positional graph, with exact terminals as its endpoints."""
|
|
if not settings.node_limit:
|
|
return None, 0
|
|
pitch = int(settings.pitch)
|
|
start_xy, target_xy = (start.x, start.y), (target.x, target.y)
|
|
blockers = STRtree(obstacles)
|
|
|
|
def visible(a: tuple[int, int], b: tuple[int, int]) -> bool:
|
|
segment = LineString((a, b)) if a != b else Point(a)
|
|
if not board.covers(segment):
|
|
return False
|
|
x0, y0, x1, y1 = segment.bounds
|
|
nearby = blockers.query(box(x0 - margin, y0 - margin, x1 + margin, y1 + margin))
|
|
return not any(_violates_clearance(segment, blockers.geometries[index], margin) for index in nearby)
|
|
|
|
def corridor(points: Sequence[tuple[int, int]]) -> Corridor:
|
|
line = LineString(points) if len(set(points)) > 1 else Point(points[0])
|
|
return Corridor(tuple(points), line.buffer(2 * pitch + margin))
|
|
|
|
if visible(start_xy, target_xy):
|
|
return corridor((start_xy, target_xy)), 0
|
|
|
|
directions = tuple(HEADING_STEPS.values())
|
|
snapped = ((start.x + pitch // 2) // pitch) * pitch, ((start.y + pitch // 2) // pitch) * pitch
|
|
# Link the exact source to its surrounding coarse positions. The target's
|
|
# final connection is another visibility edge in this positional graph.
|
|
origins = [snapped, *((snapped[0] + dx * pitch, snapped[1] + dy * pitch) for dx, dy in directions)]
|
|
order = count()
|
|
queue = []
|
|
distances = {}
|
|
parents: dict[tuple[int, int], tuple[int, int] | None] = {}
|
|
for xy in origins:
|
|
if visible(start_xy, xy):
|
|
cost = hypot(xy[0] - start.x, xy[1] - start.y)
|
|
distances[xy], parents[xy] = cost, None
|
|
heappush(queue, (cost + hypot(xy[0] - target.x, xy[1] - target.y), next(order), cost, xy))
|
|
|
|
expanded = 0
|
|
while queue and expanded < settings.node_limit:
|
|
_, _, cost, current = heappop(queue)
|
|
if cost != distances[current]:
|
|
continue
|
|
expanded += 1
|
|
if visible(current, target_xy):
|
|
reverse = [target_xy]
|
|
ancestor = current
|
|
while ancestor is not None:
|
|
reverse.append(ancestor)
|
|
ancestor = parents[ancestor]
|
|
route = [start_xy, *reversed(reverse)]
|
|
simplified = [route[0]]
|
|
index = 0
|
|
while index < len(route) - 1:
|
|
following = next(i for i in range(len(route) - 1, index, -1) if visible(route[index], route[i]))
|
|
if route[following] != simplified[-1]:
|
|
simplified.append(route[following])
|
|
index = following
|
|
return corridor(simplified), expanded
|
|
for dx, dy in directions:
|
|
peer = current[0] + dx * pitch, current[1] + dy * pitch
|
|
estimate = cost + pitch * hypot(dx, dy)
|
|
if estimate < distances.get(peer, inf) and visible(current, peer):
|
|
distances[peer], parents[peer] = estimate, current
|
|
heappush(queue, (estimate + hypot(peer[0] - target.x, peer[1] - target.y), next(order), estimate, peer))
|
|
return None, expanded
|