inire/inire/router/_topology.py

386 lines
16 KiB
Python

"""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, permutations
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,
*,
forced_lane: tuple[Edge, XY] | None = None,
) -> _Assignment:
gates = [self.portals[_edge(a, b)].lanes for a, b in pairwise(cells)]
if forced_lane is not None:
edge, lane = forced_lane
gate = next(i for i, (a, b) in enumerate(pairwise(cells)) if _edge(a, b) == edge)
gates[gate] = (lane,)
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 _prepared_reservations(shapes_by_cell: dict[int, list[BaseGeometry]]) -> dict[int, BaseGeometry]:
reservations = {cell: shapely.union_all(shapes) for cell, shapes in shapes_by_cell.items() if shapes}
for reservation in reservations.values():
shapely.prepare(reservation)
return reservations
def _assign_shared_lanes(
mesh: _Mesh,
assignments: dict[str, list[_Assignment]],
endpoints: dict[str, tuple[_Endpoint, _Endpoint]],
users: dict[Edge, list[str]],
occupied: dict[int, list[tuple[str, BaseGeometry]]],
leads: dict[int, list[tuple[str, BaseGeometry]]],
unresolved: frozenset[str],
radius: float,
) -> bool:
shared = [
(edge, group)
for edge, group in users.items()
if 2 <= len(group) <= min(4, len(mesh.portals[edge].lanes)) and not unresolved.isdisjoint(group)
]
if not shared:
return False
edge, group = max(shared, key=lambda item: (len(item[1]) / len(mesh.portals[item[0]].lanes), len(item[1])))
lanes = mesh.portals[edge].lanes
choices = []
for net_id in group:
cells = assignments[net_id][0].cells
reservations = _prepared_reservations(
{
cell: [shape for owner, shape in occupied.get(cell, ()) if owner not in group]
+ [shape for owner, shape in leads.get(cell, ()) if owner != net_id]
for cell in cells
}
)
start, target = endpoints[net_id]
choices.append([mesh.assign_lanes(cells, start, target, reservations, radius, forced_lane=(edge, lane)) for lane in lanes])
# The selected portal has at most nine lanes and at most four users.
def cost(order: tuple[int, ...]) -> float:
return sum(candidates[lane].cost for candidates, lane in zip(choices, order, strict=True))
selected = min(permutations(range(len(lanes)), len(group)), key=cost)
changed = False
for net_id, candidates, lane in zip(group, choices, selected, strict=True):
proposal = candidates[lane]
if proposal.points != assignments[net_id][0].points:
assignments[net_id][0] = proposal
changed = True
return changed
def plan_corridors(
bounds: tuple[float, float, float, float],
obstacles: Iterable[Polygon],
nets: Sequence[NetSpec],
*,
clearance: float,
bend_radius: float,
limit: int,
joint_net_ids: frozenset[str] = frozenset(),
) -> dict[str, tuple[Corridor, ...]]:
"""Plan normal guides, or return a changed assignment for a targeted joint retry."""
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[tuple[str, BaseGeometry]]] = {}
demand: dict[Edge, int] = {}
users: dict[Edge, list[str]] = {}
assignments_by_net: dict[str, list[_Assignment]] = {}
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}
reservations = _prepared_reservations(
{
cell: [shape for _, shape in occupied.get(cell, ())]
+ [shape for owner, shape in leads.get(cell, ()) if owner != net.net_id]
for cell in candidate_cells
}
)
assignments = sorted(
(mesh.assign_lanes(cells, start, target, reservations, bend_radius) for cells in candidates),
key=lambda assignment: assignment.cost,
)
if not assignments:
continue
assignments_by_net[net.net_id] = assignments
best = assignments[0]
for a, b in pairwise(best.cells):
edge = _edge(a, b)
demand[edge] = demand.get(edge, 0) + 1
if joint_net_ids:
users.setdefault(edge, []).append(net.net_id)
reservation = LineString(best.points).buffer(mesh.pitch - 0.01)
for cell in mesh.index.query(reservation, predicate="intersects"):
occupied.setdefault(cell, []).append((net.net_id, reservation))
if joint_net_ids and not _assign_shared_lanes(mesh, assignments_by_net, endpoints, users, occupied, leads, joint_net_ids, bend_radius):
return {}
guides: dict[str, tuple[Corridor, ...]] = {}
for net in nets:
if net.net_id not in assignments_by_net:
continue
corridors = []
for assignment in assignments_by_net[net.net_id]:
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