Select and verify topological and constructive routing plans
This commit is contained in:
parent
d741456d6b
commit
be3222e5ae
1 changed files with 2868 additions and 68 deletions
313
inire/router/_topology.py
Normal file
313
inire/router/_topology.py
Normal file
|
|
@ -0,0 +1,313 @@
|
|||
"""Capacity-aware corridor planning in the triangulated centerline free space."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from heapq import heappop, heappush
|
||||
from itertools import pairwise
|
||||
from math import hypot, inf
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import shapely
|
||||
from shapely.geometry import LineString, Point, box
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterable, Sequence
|
||||
|
||||
from shapely.geometry import Polygon
|
||||
from shapely.geometry.base import BaseGeometry
|
||||
|
||||
from inire.geometry.primitives import Port
|
||||
from inire.model import NetSpec
|
||||
|
||||
|
||||
XY = tuple[float, float]
|
||||
Edge = tuple[int, int]
|
||||
HEADINGS = ((1, 0), (0, 1), (-1, 0), (0, -1))
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class Corridor:
|
||||
centerline: LineString
|
||||
footprint: BaseGeometry
|
||||
scale: float
|
||||
_distances: dict[tuple[float, float], float] = field(default_factory=dict)
|
||||
_remaining: dict[tuple[float, float], float] = field(default_factory=dict)
|
||||
_anchors: tuple[XY, ...] = field(init=False)
|
||||
_length: float = field(init=False)
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
self._anchors = tuple(dict.fromkeys(self.centerline.coords))
|
||||
self._length = self.centerline.length
|
||||
|
||||
def distance(self, port: Port) -> float:
|
||||
xy = (port.x, port.y)
|
||||
if xy not in self._distances:
|
||||
self._distances[xy] = min(1.0, self.centerline.distance(Point(xy)) / self.scale)
|
||||
return self._distances[xy]
|
||||
|
||||
def remaining(self, port: Port) -> float:
|
||||
xy = (port.x, port.y)
|
||||
if xy not in self._remaining:
|
||||
point = Point(xy)
|
||||
self._remaining[xy] = self._length - self.centerline.project(point) + self.centerline.distance(point)
|
||||
return self._remaining[xy]
|
||||
|
||||
def nearby_anchors(self, port: Port, forward_limit: float) -> list[tuple[float, float]]:
|
||||
"""Return nearby waypoints in the current port's forward/lateral frame."""
|
||||
dx, dy = HEADINGS[int(port.r) // 90]
|
||||
candidates = []
|
||||
for x, y in self._anchors:
|
||||
px, py = x - port.x, y - port.y
|
||||
forward, lateral = px * dx + py * dy, py * dx - px * dy
|
||||
if 0 < forward <= forward_limit:
|
||||
candidates.append((forward, lateral))
|
||||
return sorted(candidates, key=lambda xy: xy[0] + abs(xy[1]))[:4]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class _Portal:
|
||||
lanes: tuple[XY, ...]
|
||||
midpoint: XY
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class _Endpoint:
|
||||
port: XY
|
||||
lead: XY
|
||||
cell: int
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class _Assignment:
|
||||
cells: tuple[int, ...]
|
||||
points: tuple[XY, ...]
|
||||
cost: float
|
||||
|
||||
|
||||
def _edge(a: int, b: int) -> Edge:
|
||||
return (a, b) if a < b else (b, a)
|
||||
|
||||
|
||||
class _Mesh:
|
||||
def __init__(self, board: Polygon, obstacles: Iterable[Polygon], margin: float, clearance: float) -> None:
|
||||
triangulate = getattr(shapely, "constrained_delaunay_triangles", None)
|
||||
if triangulate is None:
|
||||
raise RuntimeError("Topological routing requires Shapely 2.1 and GEOS 3.10 or newer")
|
||||
|
||||
self.pitch = max(1.0, 2 * margin + clearance)
|
||||
obstacles = shapely.union_all([shape.buffer(margin + clearance, join_style="mitre") for shape in obstacles])
|
||||
self.free = board.buffer(-margin).difference(obstacles)
|
||||
self.boundary = self.free.boundary
|
||||
self.cells: tuple[Polygon, ...] = tuple(triangulate(self.free).geoms)
|
||||
self.index = shapely.STRtree(self.cells)
|
||||
self.portals: dict[Edge, _Portal] = {}
|
||||
self.neighbors: list[list[int]] = [[] for _ in self.cells]
|
||||
self.room: dict[XY, float] = {}
|
||||
|
||||
edges: dict[tuple[XY, XY], int] = {}
|
||||
for cell_id, cell in enumerate(self.cells):
|
||||
for a, b in pairwise(cell.exterior.coords):
|
||||
segment = (a, b) if a < b else (b, a)
|
||||
other = edges.get(segment)
|
||||
if other is None:
|
||||
edges[segment] = cell_id
|
||||
continue
|
||||
ax, ay = segment[0]
|
||||
bx, by = segment[1]
|
||||
length = hypot(bx - ax, by - ay)
|
||||
# Leave a small offset at wall vertices. Narrow passages keep a middle lane.
|
||||
usable = max(0.0, length - 0.2)
|
||||
count = min(9, 1 + int(usable / self.pitch))
|
||||
spacing = usable / max(1, count - 1)
|
||||
fractions = [0.5 + (i - (count - 1) / 2) * spacing / length for i in range(count)]
|
||||
lanes = tuple((ax + (bx - ax) * f, ay + (by - ay) * f) for f in fractions)
|
||||
self.portals[other, cell_id] = _Portal(lanes, ((ax + bx) / 2, (ay + by) / 2))
|
||||
self.neighbors[other].append(cell_id)
|
||||
self.neighbors[cell_id].append(other)
|
||||
|
||||
def endpoint(self, port: Port, direction: int, lead_length: float) -> _Endpoint | None:
|
||||
x, y, rotation = port.as_tuple()
|
||||
dx, dy = HEADINGS[rotation // 90]
|
||||
for length in (lead_length, lead_length / 2, 1.0, 0.0):
|
||||
lead = (x + dx * length * direction, y + dy * length * direction)
|
||||
if length and not self.free.covers(LineString(((x, y), lead))):
|
||||
continue
|
||||
cells = self.index.query(Point(lead), predicate="covered_by")
|
||||
if len(cells):
|
||||
return _Endpoint((x, y), lead, int(min(cells)))
|
||||
return None
|
||||
|
||||
def _crossing_cost(self, edge: Edge, demand: dict[Edge, int]) -> float:
|
||||
count = len(self.portals[edge].lanes)
|
||||
load = demand.get(edge, 0)
|
||||
return self.pitch * (load / count + 12 * max(0, load + 1 - count))
|
||||
|
||||
def shortest(
|
||||
self,
|
||||
start: _Endpoint,
|
||||
target: _Endpoint,
|
||||
demand: dict[Edge, int],
|
||||
prefix: tuple[int, ...],
|
||||
blocked: set[Edge],
|
||||
) -> tuple[float, tuple[int, ...]]:
|
||||
location = start.lead
|
||||
prefix_cost = 0.0
|
||||
for a, b in pairwise(prefix):
|
||||
edge = _edge(a, b)
|
||||
midpoint = self.portals[edge].midpoint
|
||||
prefix_cost += hypot(midpoint[0] - location[0], midpoint[1] - location[1]) + self._crossing_cost(edge, demand)
|
||||
location = midpoint
|
||||
|
||||
# In a triangle the straight line between two portal points stays in free space.
|
||||
# The entry portal is part of the state because it changes each exit cost.
|
||||
queue = [(prefix_cost + hypot(target.lead[0] - location[0], target.lead[1] - location[1]), prefix_cost, prefix, location)]
|
||||
cost_by_entry: dict[tuple[int, int], float] = {}
|
||||
while queue:
|
||||
estimate, cost, path, location = heappop(queue)
|
||||
cell = path[-1]
|
||||
if cell == target.cell:
|
||||
return estimate, path
|
||||
for neighbor in self.neighbors[cell]:
|
||||
edge = _edge(cell, neighbor)
|
||||
if neighbor in path or edge in blocked:
|
||||
continue
|
||||
midpoint = self.portals[edge].midpoint
|
||||
next_cost = cost + hypot(midpoint[0] - location[0], midpoint[1] - location[1]) + self._crossing_cost(edge, demand)
|
||||
if next_cost < cost_by_entry.get((cell, neighbor), inf):
|
||||
cost_by_entry[cell, neighbor] = next_cost
|
||||
remaining = hypot(target.lead[0] - midpoint[0], target.lead[1] - midpoint[1])
|
||||
heappush(queue, (next_cost + remaining, next_cost, (*path, neighbor), midpoint))
|
||||
return inf, ()
|
||||
|
||||
def alternatives(self, start: _Endpoint, target: _Endpoint, demand: dict[Edge, int], limit: int) -> list[tuple[int, ...]]:
|
||||
_, first = self.shortest(start, target, demand, (start.cell,), set())
|
||||
if not first:
|
||||
return []
|
||||
paths = [first]
|
||||
frontier: list[tuple[float, tuple[int, ...]]] = []
|
||||
seen = {first}
|
||||
while len(paths) < limit:
|
||||
for end in range(1, len(paths[-1])):
|
||||
prefix = paths[-1][:end]
|
||||
blocked = {_edge(path[end - 1], path[end]) for path in paths if path[:end] == prefix and len(path) > end}
|
||||
cost, candidate = self.shortest(start, target, demand, prefix, blocked)
|
||||
if candidate and candidate not in seen:
|
||||
seen.add(candidate)
|
||||
heappush(frontier, (cost, candidate))
|
||||
if not frontier:
|
||||
break
|
||||
paths.append(heappop(frontier)[1])
|
||||
return paths
|
||||
|
||||
def turn_cost(self, a: XY, b: XY, c: XY, radius: float) -> float:
|
||||
dx, dy = b[0] - a[0], b[1] - a[1]
|
||||
ex, ey = c[0] - b[0], c[1] - b[1]
|
||||
scale = hypot(dx, dy) * hypot(ex, ey)
|
||||
if not scale or not radius:
|
||||
return 0.0
|
||||
if b not in self.room:
|
||||
self.room[b] = self.boundary.distance(Point(b))
|
||||
angle_cost = 1 - max(-1.0, min(1.0, (dx * ex + dy * ey) / scale))
|
||||
return angle_cost * (radius / 2 + 3 * max(0, radius - self.room[b]))
|
||||
|
||||
def assign_lanes(
|
||||
self,
|
||||
cells: tuple[int, ...],
|
||||
start: _Endpoint,
|
||||
target: _Endpoint,
|
||||
reservations: dict[int, BaseGeometry],
|
||||
radius: float,
|
||||
) -> _Assignment:
|
||||
gates = [self.portals[_edge(a, b)].lanes for a, b in pairwise(cells)]
|
||||
gates.append((target.lead,))
|
||||
choices = [(0.0, (start.port, start.lead))]
|
||||
for cell, gate in zip(cells, gates, strict=True):
|
||||
next_choices = []
|
||||
for point in gate:
|
||||
best = (inf, ())
|
||||
for previous_cost, points in choices:
|
||||
a, b = points[-2:]
|
||||
distance = hypot(point[0] - b[0], point[1] - b[1])
|
||||
cost = previous_cost + distance + self.turn_cost(a, b, point, radius)
|
||||
buffered_routes = reservations.get(cell)
|
||||
if buffered_routes is not None and distance and buffered_routes.intersects(LineString((b, point))):
|
||||
cost += 12 * self.pitch + 4 * radius
|
||||
if cell == target.cell:
|
||||
cost += self.turn_cost(b, point, target.port, radius)
|
||||
if cost < best[0]:
|
||||
best = (cost, (*points, point))
|
||||
next_choices.append(best)
|
||||
choices = next_choices
|
||||
cost, points = choices[0]
|
||||
return _Assignment(cells, (*points, target.port), cost)
|
||||
|
||||
|
||||
def plan_corridors(
|
||||
bounds: tuple[float, float, float, float],
|
||||
obstacles: Iterable[Polygon],
|
||||
nets: Sequence[NetSpec],
|
||||
*,
|
||||
clearance: float,
|
||||
bend_radius: float,
|
||||
limit: int,
|
||||
) -> dict[str, tuple[Corridor, ...]]:
|
||||
if not nets:
|
||||
return {}
|
||||
|
||||
mesh = _Mesh(box(*bounds), obstacles, max(net.width for net in nets) / 2, clearance)
|
||||
board = box(*bounds)
|
||||
endpoints = {}
|
||||
leads: dict[int, list[tuple[str, BaseGeometry]]] = {}
|
||||
for net in nets:
|
||||
span = hypot(net.target.x - net.start.x, net.target.y - net.start.y)
|
||||
lead_length = min(max(bend_radius / 2, mesh.pitch), span / 4)
|
||||
start = mesh.endpoint(net.start, 1, lead_length)
|
||||
target = mesh.endpoint(net.target, -1, lead_length)
|
||||
if start is not None and target is not None and start.port != target.port:
|
||||
endpoints[net.net_id] = start, target
|
||||
for end in (start, target):
|
||||
if end.port == end.lead:
|
||||
continue
|
||||
shape = LineString((end.port, end.lead)).buffer(mesh.pitch - 0.01)
|
||||
for cell in mesh.index.query(shape, predicate="intersects"):
|
||||
leads.setdefault(cell, []).append((net.net_id, shape))
|
||||
|
||||
occupied: dict[int, list[BaseGeometry]] = {}
|
||||
demand: dict[Edge, int] = {}
|
||||
guides: dict[str, tuple[Corridor, ...]] = {}
|
||||
for net in nets:
|
||||
if net.net_id not in endpoints:
|
||||
continue
|
||||
start, target = endpoints[net.net_id]
|
||||
candidates = mesh.alternatives(start, target, demand, limit)
|
||||
candidate_cells = {cell for candidate in candidates for cell in candidate}
|
||||
overlapping = {
|
||||
cell: occupied.get(cell, []) + [shape for net_id, shape in leads.get(cell, ()) if net_id != net.net_id] for cell in candidate_cells
|
||||
}
|
||||
reservations = {cell: shapely.union_all(shapes) for cell, shapes in overlapping.items() if shapes}
|
||||
for reservation in reservations.values():
|
||||
shapely.prepare(reservation)
|
||||
assignments = sorted(
|
||||
(mesh.assign_lanes(cells, start, target, reservations, bend_radius) for cells in candidates),
|
||||
key=lambda assignment: assignment.cost,
|
||||
)
|
||||
if not assignments:
|
||||
continue
|
||||
best = assignments[0]
|
||||
for a, b in pairwise(best.cells):
|
||||
edge = _edge(a, b)
|
||||
demand[edge] = demand.get(edge, 0) + 1
|
||||
reservation = LineString(best.points).buffer(mesh.pitch - 0.01)
|
||||
for cell in mesh.index.query(reservation, predicate="intersects"):
|
||||
occupied.setdefault(cell, []).append(reservation)
|
||||
|
||||
corridors = []
|
||||
for assignment in assignments:
|
||||
line = LineString(assignment.points)
|
||||
region = shapely.union_all([mesh.cells[i] for i in assignment.cells] + [line])
|
||||
footprint = region.buffer(mesh.pitch + net.width / 2, join_style="mitre").intersection(board)
|
||||
shapely.prepare(footprint)
|
||||
corridors.append(Corridor(line, footprint, max(bend_radius, mesh.pitch)))
|
||||
guides[net.net_id] = tuple(corridors)
|
||||
return guides
|
||||
Loading…
Reference in a new issue