Use verified terminal and column constructions, cheaper straight profiles, and tighter cost bounds to reduce routing work. Reuse geometry in clearance checks and tuning while retaining verified coverage and timing constraints. Report median routing time times squared cost in the benchmark tools and record the comparisons and regression coverage.
403 lines
19 KiB
Python
403 lines
19 KiB
Python
"""Perimeter detours and fixed-heading returns for ordered bundles."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from dataclasses import replace
|
|
from functools import lru_cache
|
|
from itertools import chain, combinations, islice, pairwise, product
|
|
from math import ceil, floor, isfinite
|
|
from typing import TYPE_CHECKING
|
|
|
|
from inire.geometry.collision import RoutingWorld
|
|
from inire.geometry.components import Straight, bend90_grid_span, bend90_uses_circular_geometry, bend_fits_width
|
|
from inire.geometry.primitives import Port, rotate_cardinal
|
|
from inire.model import resolve_bend_geometry
|
|
from inire.router._jog import detour_lane_offsets, jog_launch_steps
|
|
from inire.router._seed_materialization import materialize_path_seed
|
|
from inire.router._waypoints import _direction, compile_waypoints, export_waypoints
|
|
from inire.seeds import Bend90Seed, PathSeed, StraightSeed
|
|
|
|
if TYPE_CHECKING:
|
|
from collections.abc import Callable, Iterator
|
|
|
|
from inire.geometry.components import ComponentResult
|
|
from inire.model import NetSpec, RoutingProblem, SearchOptions
|
|
from inire.router._waypoints import XY
|
|
|
|
|
|
def residual_dogleg_candidates(problem: RoutingProblem, search: SearchOptions, *, limit_per_pass: int | None = None) -> Iterator[PathSeed]:
|
|
"""Try four-turn routes through interior gaps with the incumbent geometry locked."""
|
|
if len(problem.nets) != 1 or problem.initial_paths:
|
|
return
|
|
(net,) = problem.nets
|
|
if net.start.r != net.target.r:
|
|
return
|
|
heading = int(net.start.r)
|
|
|
|
def project(x: float, y: float) -> tuple[float, float]:
|
|
return rotate_cardinal(x, y, -heading)
|
|
|
|
def physical(x: int, y: int) -> XY:
|
|
return rotate_cardinal(x, y, heading)
|
|
|
|
def extent(bounds: tuple[float, float, float, float]) -> tuple[float, float, float, float]:
|
|
x0, y0, x1, y1 = bounds
|
|
a, b = project(x0, y0), project(x1, y1)
|
|
return min(a[0], b[0]), min(a[1], b[1]), max(a[0], b[0]), max(a[1], b[1])
|
|
|
|
start_x, start_y = map(int, project(net.start.x, net.start.y))
|
|
end_x, end_y = map(int, project(net.target.x, net.target.y))
|
|
if end_x <= start_x:
|
|
return
|
|
circular = bend90_uses_circular_geometry(*resolve_bend_geometry(search))
|
|
radii = sorted({int(r) for r in search.bend_radii if isfinite(r) and r > 0 and r == int(r)})
|
|
if circular:
|
|
radii = [r for r in radii if bend_fits_width(r, net.width)]
|
|
if not radii:
|
|
return
|
|
half_width = net.width / 2
|
|
pad = problem.clearance + half_width
|
|
_, floor_y, _, ceiling_y = extent(problem.bounds)
|
|
obstacles = []
|
|
for shape in problem._blocking_polygons:
|
|
if shape.is_empty:
|
|
continue
|
|
a, b, c, d = extent(shape.bounds)
|
|
if c + pad >= start_x and a - pad <= end_x:
|
|
obstacles.append((a - pad, b - pad, c + pad, d + pad))
|
|
|
|
world: RoutingWorld | None = None
|
|
|
|
@lru_cache(maxsize=4096)
|
|
def straight_clear(a: int, b: int, c: int, d: int) -> bool:
|
|
nonlocal world
|
|
length = abs(c - a) + abs(d - b)
|
|
if not length:
|
|
return True
|
|
left, right = sorted((a, c))
|
|
bottom, top = sorted((b, d))
|
|
if all(right < x0 or left > x1 or top < y0 or bottom > y1 for x0, y0, x1, y1 in obstacles):
|
|
return True
|
|
if world is None:
|
|
world = RoutingWorld.from_problem(problem)
|
|
start, end = physical(a, b), physical(c, d)
|
|
direction = _direction(start, end)
|
|
assert direction is not None
|
|
straight = Straight.generate(Port(*start, direction), length, net.width)
|
|
return not world.check_move_static(straight)
|
|
|
|
lanes = {ceil(floor_y + half_width), floor(ceiling_y - half_width)}
|
|
for _, bottom, _, top in obstacles:
|
|
lanes.update((floor(bottom), ceil(top)))
|
|
lanes = {y for y in lanes if floor_y + half_width <= y <= ceiling_y - half_width}
|
|
ordered_lanes = sorted(lanes, key=lambda y: (abs(y - start_y) + abs(y - end_y), y))
|
|
seen: set[PathSeed] = set()
|
|
|
|
def seed_pass(minimum: float) -> Iterator[PathSeed]:
|
|
remaining = 16384
|
|
for radius in radii:
|
|
first, last = ceil(start_x + radius + minimum), floor(end_x - radius - minimum)
|
|
if last - first < 2 * radius:
|
|
continue
|
|
pivots = {first, last}
|
|
for left, _, right, _ in obstacles:
|
|
pivots.update((floor(left - radius), ceil(right + radius)))
|
|
ordered_pivots = sorted(x for x in pivots if first <= x <= last)
|
|
entrances = [x for x in ordered_pivots if straight_clear(start_x, start_y, x - radius, start_y)]
|
|
exits = [x for x in reversed(ordered_pivots) if straight_clear(x + radius, end_y, end_x, end_y)]
|
|
for y in ordered_lanes:
|
|
rises = [sorted((port_y, y)) for port_y in (start_y, end_y)]
|
|
if any(high - low < 2 * radius + minimum for low, high in rises):
|
|
continue
|
|
lower, upper = rises
|
|
departures = [x for x in entrances if straight_clear(x, lower[0] + radius, x, lower[1] - radius)]
|
|
arrivals = [x for x in exits if straight_clear(x, upper[0] + radius, x, upper[1] - radius)]
|
|
for a, b in product(departures, arrivals):
|
|
if not remaining:
|
|
return
|
|
remaining -= 1
|
|
if b - a < 2 * radius + minimum or not straight_clear(a + radius, y, b - radius, y):
|
|
continue
|
|
local_points = ((start_x, start_y), (a, start_y), (a, y), (b, y), (b, end_y), (end_x, end_y))
|
|
seed, end = compile_waypoints(tuple(physical(x, h) for x, h in local_points), net.start, radius)
|
|
if end == net.target and seed not in seen and all(
|
|
not isinstance(move, StraightSeed) or minimum <= move.length for move in seed.segments
|
|
):
|
|
seen.add(seed)
|
|
yield seed
|
|
|
|
for minimum in dict.fromkeys((search.min_straight_length, 0.0)):
|
|
yield from islice(seed_pass(minimum), limit_per_pass)
|
|
|
|
|
|
def bundle_turnaround_candidates(
|
|
problem: RoutingProblem,
|
|
proposal: RoutingProblem,
|
|
search: SearchOptions,
|
|
) -> Iterator[RoutingProblem]:
|
|
"""Fit a final turnaround below the shelf without changing terminal headings."""
|
|
if len(problem.nets) != len(proposal.nets) or not problem.nets:
|
|
return
|
|
mismatches = [
|
|
(fixed, inferred)
|
|
for fixed, inferred in zip(problem.nets, proposal.nets, strict=True)
|
|
if (fixed.start, fixed.target) != (inferred.start, inferred.target)
|
|
]
|
|
if len(mismatches) != 1:
|
|
return
|
|
returning, inferred = mismatches[0]
|
|
if returning.start != inferred.start or returning.target.r != 0 or inferred.target.r != 180:
|
|
return
|
|
radius = next((int(move.radius) for move in proposal.initial_paths[returning.net_id].segments if isinstance(move, Bend90Seed)), None)
|
|
if radius is None:
|
|
return
|
|
farthest = max(net.target.x for net in problem.nets)
|
|
shelf = max((net for net in problem.nets if net.target.x == farthest), key=lambda net: net.target.y)
|
|
if shelf == returning:
|
|
return
|
|
|
|
def points_for(net: NetSpec) -> tuple[XY, ...]:
|
|
path = materialize_path_seed(
|
|
proposal.initial_paths[net.net_id], start=net.start, net_width=net.width, search=search, clearance=problem.clearance,
|
|
bounds=problem.bounds,
|
|
)
|
|
return tuple((round(x), round(y)) for x, y in export_waypoints(path or ()))
|
|
|
|
shelf_points, return_points = points_for(shelf), points_for(returning)
|
|
horizontals = [i for i, (a, b) in enumerate(pairwise(shelf_points)) if a[1] == b[1]]
|
|
if len(return_points) != 6 or not horizontals:
|
|
return
|
|
launch = max(horizontals, key=lambda i: shelf_points[i][1])
|
|
drop = launch + 1
|
|
bends = [(a, b) for a, b in pairwise(shelf_points[drop:]) if a[0] != b[0] and a[1] != b[1]]
|
|
if len(bends) != 1 or drop + 1 >= len(shelf_points):
|
|
return
|
|
(left_x, left_y), (right_x, right_y) = bends[0]
|
|
drop_offset = left_y - right_y
|
|
if not 0 < drop_offset < 2 * radius:
|
|
return
|
|
min_gap = problem.clearance + (returning.width + shelf.width) / 2
|
|
# Parallel S-bends approach each other most at their largest tangent angle.
|
|
inner_gap = ceil(min_gap / (1 - drop_offset / (2 * radius)))
|
|
top = floor(problem.bounds[3] - shelf.width / 2)
|
|
first_drop = max(shelf_points[drop][0], ceil(returning.target.x + radius + min_gap))
|
|
for descent_x, gap, lead in product(
|
|
(first_drop, first_drop + radius // 2, first_drop + radius),
|
|
range(inner_gap, inner_gap + 5),
|
|
(0, 2, 4, 8),
|
|
):
|
|
shelf_candidate = list(shelf_points)
|
|
shelf_candidate[launch] = (shelf_points[launch][0], top)
|
|
shelf_candidate[drop] = (descent_x, top)
|
|
shelf_candidate[drop + 1] = (descent_x, shelf_points[drop + 1][1])
|
|
x_turn = returning.target.x - radius - lead
|
|
turn_points = (
|
|
*return_points[:4],
|
|
(return_points[4][0], right_y - gap),
|
|
(right_x, right_y - gap),
|
|
(left_x, left_y - gap),
|
|
(x_turn, left_y - gap),
|
|
(x_turn, returning.target.y),
|
|
(returning.target.x, returning.target.y),
|
|
)
|
|
try:
|
|
shelf_seed, shelf_end = compile_waypoints(tuple(shelf_candidate), shelf.start, radius)
|
|
return_seed, return_end = compile_waypoints(turn_points, returning.start, radius)
|
|
except ValueError:
|
|
continue
|
|
if shelf_end == shelf.target and return_end == returning.target:
|
|
seeds = {**proposal.initial_paths, shelf.net_id: shelf_seed, returning.net_id: return_seed}
|
|
yield replace(problem, initial_paths=seeds)
|
|
|
|
|
|
def terminal_link_seed(net: NetSpec, search: SearchOptions) -> PathSeed | None:
|
|
"""Connect aligned terminals with a straight or a single tangent bend."""
|
|
start, target = net.start, net.target
|
|
a, b = (start.x, start.y), (target.x, target.y)
|
|
if a == b:
|
|
return None
|
|
if start.r == target.r == _direction(a, b):
|
|
return PathSeed((StraightSeed(abs(b[0] - a[0]) + abs(b[1] - a[1])),))
|
|
if start.r % 180 == target.r % 180:
|
|
return None
|
|
corner = (b[0], a[1]) if start.r % 180 == 0 else (a[0], b[1])
|
|
if corner in (a, b) or _direction(a, corner) != start.r or _direction(corner, b) != target.r:
|
|
return None
|
|
proxy, physical = resolve_bend_geometry(search)
|
|
circular = bend90_uses_circular_geometry(proxy, physical)
|
|
available = min(abs(b[0] - a[0]), abs(b[1] - a[1]))
|
|
radius = min((r for r in search.bend_radii if r <= available and (not circular or bend_fits_width(r, net.width))), default=0.0)
|
|
if not radius:
|
|
return None
|
|
seed, end = compile_waypoints((a, corner, b), start, radius)
|
|
return seed if end == target else None
|
|
|
|
|
|
def terminal_offset_seeds(net: NetSpec, search: SearchOptions, world: RoutingWorld) -> Iterator[PathSeed]:
|
|
sx, sy, heading = net.start.as_tuple()
|
|
tx, ty, target_heading = net.target.as_tuple()
|
|
if heading != target_heading or not bend90_uses_circular_geometry(*resolve_bend_geometry(search)):
|
|
return
|
|
forward, lateral = map(int, rotate_cardinal(tx - sx, ty - sy, -heading))
|
|
if forward <= 0:
|
|
return
|
|
dx, dy = map(int, rotate_cardinal(1, 0, heading))
|
|
margin = world.clearance + net.width / 2
|
|
bounds = min(sx, tx) - margin, min(sy, ty) - margin, max(sx, tx) + margin, max(sy, ty) + margin
|
|
blockers = (*world.iter_static_obstacle_bounds(bounds), *world.iter_dynamic_path_bounds(bounds))
|
|
if lateral == 0:
|
|
lanes = detour_lane_offsets((sx, sy), (dx, dy), forward, 1, margin, blockers)
|
|
if lanes:
|
|
yield from _terminal_detours(net, search, forward, lanes)
|
|
return
|
|
for radius in sorted(set(search.bend_radii)):
|
|
span = bend90_grid_span(radius)
|
|
if min(forward, abs(lateral)) < 2 * span or not bend_fits_width(radius, net.width):
|
|
continue
|
|
for lead in jog_launch_steps((sx, sy), (dx, dy), lateral, 2 * span, forward - 2 * span, 1, margin, blockers):
|
|
x = lead + span
|
|
ax, ay = rotate_cardinal(x, 0, heading)
|
|
bx, by = rotate_cardinal(x, lateral, heading)
|
|
points = ((sx, sy), (sx + int(ax), sy + int(ay)), (sx + int(bx), sy + int(by)), (tx, ty))
|
|
seed, end = compile_waypoints(points, net.start, radius)
|
|
if end == net.target:
|
|
yield seed
|
|
|
|
|
|
def _terminal_detours(net: NetSpec, search: SearchOptions, forward: int, lanes: set[int]) -> Iterator[PathSeed]:
|
|
sx, sy, heading = net.start.as_tuple()
|
|
for radius in sorted(set(search.bend_radii)):
|
|
span = bend90_grid_span(radius)
|
|
if forward < 4 * span or not bend_fits_width(radius, net.width):
|
|
continue
|
|
offsets = {max(lane, 2 * span) if lane >= 0 else min(lane, -2 * span) for lane in lanes}
|
|
for lateral in sorted(offsets, key=lambda offset: (abs(offset), offset)):
|
|
midpoints = ((span, 0), (span, lateral), (forward - span, lateral), (forward - span, 0))
|
|
points = [(sx, sy)]
|
|
for x, y in midpoints:
|
|
rx, ry = rotate_cardinal(x, y, heading)
|
|
points.append((sx + int(rx), sy + int(ry)))
|
|
points.append((int(net.target.x), int(net.target.y)))
|
|
seed, end = compile_waypoints(tuple(points), net.start, radius)
|
|
if end == net.target:
|
|
yield seed
|
|
|
|
|
|
def terminal_constructive_path(
|
|
net: NetSpec, search: SearchOptions, world: RoutingWorld, *, expired: Callable[[], bool],
|
|
) -> tuple[ComponentResult, ...] | None:
|
|
"""Try verified terminal links and detours before native search."""
|
|
link = terminal_link_seed(net, search)
|
|
offsets = islice(terminal_offset_seeds(net, search, world), search.terminal_jog_limit)
|
|
for seed in chain((link,) if link else (), offsets):
|
|
if expired():
|
|
break
|
|
path = materialize_path_seed(seed, start=net.start, net_width=net.width, search=search, clearance=world.clearance)
|
|
if path and path[-1].end_port == net.target and world.verify_path_report(net.net_id, path).is_valid:
|
|
return path
|
|
return None
|
|
|
|
|
|
def _return_detours(
|
|
problem: RoutingProblem,
|
|
net: NetSpec,
|
|
obstacles: tuple[tuple[float, float, float, float], ...],
|
|
radius: int,
|
|
) -> Iterator[PathSeed]:
|
|
xmin, ymin, xmax, ymax = problem.bounds
|
|
half_width = net.width / 2
|
|
margin = ceil(problem.clearance + half_width + 1)
|
|
start, target = net.start, net.target
|
|
low = min(start.y, target.y) - 2 * radius
|
|
high = max(start.y, target.y) + 2 * radius
|
|
bottom = min(low, min((floor(bottom - margin) for _, bottom, _, _ in obstacles), default=low))
|
|
top = max(high, max((ceil(top + margin) for _, _, _, top in obstacles), default=high))
|
|
lanes = tuple(y for y in dict.fromkeys((bottom, top, low, high)) if ymin + half_width <= y <= ymax - half_width)
|
|
if not lanes:
|
|
return
|
|
left_edge = ceil(xmin + half_width)
|
|
right_edge = floor(xmax - half_width)
|
|
min_departure = start.x + radius
|
|
max_arrival = target.x - radius
|
|
pivots = {left_edge, right_edge, min_departure + 1, max_arrival - 1}
|
|
for left, _, right, _ in obstacles:
|
|
pivots.update((floor(left - margin), ceil(right + margin)))
|
|
departures = sorted(x for x in pivots if min_departure <= x <= right_edge)
|
|
arrivals = sorted((x for x in pivots if left_edge <= x <= max_arrival), reverse=True)
|
|
# Keep the first pivot pair and try bends that meet the ports directly next.
|
|
if min_departure <= right_edge and min_departure not in departures:
|
|
departures.insert(1, min_departure)
|
|
if left_edge <= max_arrival and max_arrival not in arrivals:
|
|
arrivals.insert(1, max_arrival)
|
|
# Try each lane for a pivot pair before spending the budget on more pivots.
|
|
for first, last, y in product(departures, arrivals, lanes):
|
|
points = ((start.x, start.y), (first, start.y), (first, y), (last, y), (last, target.y), (target.x, target.y))
|
|
seed, end = compile_waypoints(points, start, radius)
|
|
if end == target:
|
|
yield seed
|
|
|
|
|
|
def perimeter_detour_candidates(problem: RoutingProblem, search: SearchOptions) -> Iterator[tuple[NetSpec, PathSeed]]:
|
|
"""Try four-turn detours around obstacles or behind east-facing ports."""
|
|
_, physical_geometry = resolve_bend_geometry(search)
|
|
if problem.initial_paths or physical_geometry != "arc":
|
|
return
|
|
radii = sorted({int(r) for r in search.bend_radii if isfinite(r) and r > 0 and r == int(r)})
|
|
if not radii:
|
|
return
|
|
obstacles = tuple(shape.bounds for shape in problem._blocking_polygons if not shape.is_empty)
|
|
for net in problem.nets:
|
|
if net.start.r != 0 or net.target.r != 0:
|
|
continue
|
|
radius = next((r for r in radii if bend_fits_width(r, net.width)), None)
|
|
if radius is None:
|
|
continue
|
|
if net.start.x > net.target.x:
|
|
yield from ((net, seed) for seed in _return_detours(problem, net, obstacles, radius))
|
|
continue
|
|
# The two outer tangencies take one radius each, and the middle leg takes two.
|
|
spare = net.target.x - net.start.x - 4 * radius
|
|
if spare < 0 or not obstacles:
|
|
continue
|
|
padding = problem.clearance + net.width / 2
|
|
nearby = tuple(bounds for bounds in obstacles if bounds[0] <= net.target.x + padding and bounds[2] >= net.start.x - padding)
|
|
low, high = sorted((net.start.y, net.target.y))
|
|
if all(bottom > high + padding or top < low - padding for _, bottom, _, top in nearby):
|
|
continue
|
|
margin = ceil(padding + 1)
|
|
top = max(ceil(top + margin) for _, _, _, top in nearby)
|
|
bottom = min(floor(bottom - margin) for _, bottom, _, _ in nearby)
|
|
y_floor = problem.bounds[1] + net.width / 2
|
|
y_ceiling = problem.bounds[3] - net.width / 2
|
|
lanes, fallback_lanes = [], []
|
|
for y, fallback in ((top, high + 2 * radius), (bottom, low - 2 * radius)):
|
|
if y_floor <= y <= y_ceiling and min(abs(y - low), abs(y - high)) >= 2 * radius:
|
|
lanes.append(y)
|
|
elif y_floor <= fallback <= y_ceiling:
|
|
fallback_lanes.append(fallback)
|
|
lanes.extend(fallback_lanes)
|
|
if not lanes:
|
|
continue
|
|
end_slack = 1 if spare >= 2 else 0
|
|
pivots = {net.start.x + radius + end_slack, net.target.x - radius - end_slack}
|
|
pivots.update(
|
|
x
|
|
for left, _, right, _ in nearby
|
|
for x in (floor(left - radius - margin), ceil(right + radius + margin))
|
|
if net.start.x + radius <= x <= net.target.x - radius
|
|
)
|
|
for first, last in combinations(sorted(pivots), 2):
|
|
if last - first < 2 * radius:
|
|
continue
|
|
for y in lanes:
|
|
points = (
|
|
(net.start.x, net.start.y),
|
|
(first, net.start.y),
|
|
(first, y),
|
|
(last, y),
|
|
(last, net.target.y),
|
|
(net.target.x, net.target.y),
|
|
)
|
|
seed, end = compile_waypoints(points, net.start, radius)
|
|
if end == net.target:
|
|
yield net, seed
|