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
465
inire/router/_columns.py
Normal file
465
inire/router/_columns.py
Normal file
|
|
@ -0,0 +1,465 @@
|
|||
"""Construct ordered routes through nonoverlapping columns of rectangles."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
from functools import lru_cache
|
||||
from itertools import combinations_with_replacement, pairwise, product
|
||||
from math import acos, ceil, cos, floor, gcd, isfinite, isqrt, sin
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from shapely.geometry import LineString, box
|
||||
|
||||
from inire.model import resolve_bend_geometry
|
||||
from inire.seeds import PathSeed, SBendSeed, StraightSeed
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable, Iterator, Mapping
|
||||
|
||||
from inire.geometry.primitives import Port
|
||||
from inire.model import NetSpec, RoutingProblem, SearchOptions
|
||||
from inire.seeds import PathSegmentSeed
|
||||
|
||||
|
||||
Profile = tuple[int, ...]
|
||||
Gap = tuple[float, float]
|
||||
Window = tuple[int, int]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class _Track:
|
||||
net: NetSpec
|
||||
left: Port
|
||||
right: Port
|
||||
westbound: bool
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class _Column:
|
||||
span: Window
|
||||
openings: tuple[Gap, ...]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class _BendSequence:
|
||||
offsets: tuple[int, ...]
|
||||
span: int
|
||||
cost: float
|
||||
|
||||
|
||||
def rectangular_obstacle_bounds(problem: RoutingProblem) -> tuple[tuple[float, float, float, float], ...] | None:
|
||||
bounds = tuple(tuple(shape.bounds) for shape in problem.static_obstacles)
|
||||
if any(shape.is_empty or not shape.equals(box(*extent)) for shape, extent in zip(problem.static_obstacles, bounds, strict=True)):
|
||||
return None
|
||||
return bounds
|
||||
|
||||
|
||||
def open_intervals(solid: list[Gap], ymin: float, ymax: float) -> tuple[Gap, ...]:
|
||||
openings = []
|
||||
cursor = ymin
|
||||
for bottom, top in sorted(solid):
|
||||
if top <= ymin or bottom >= ymax:
|
||||
continue
|
||||
if cursor < bottom:
|
||||
openings.append((cursor, bottom))
|
||||
cursor = max(cursor, top)
|
||||
if cursor < ymax:
|
||||
openings.append((cursor, ymax))
|
||||
return tuple(openings)
|
||||
|
||||
|
||||
def _columns(problem: RoutingProblem, start: int, finish: int) -> tuple[_Column, ...]:
|
||||
# A bounding rectangle only reserves extra space in this candidate
|
||||
# planner. Capacity proofs still require the actual rectangular obstacles.
|
||||
extents: dict[Window, list[Gap]] = defaultdict(list)
|
||||
for obstacle in problem.static_obstacles:
|
||||
if obstacle.is_empty:
|
||||
continue
|
||||
left, bottom, right, top = obstacle.bounds
|
||||
lo, hi = floor(left), ceil(right)
|
||||
if lo < start or hi > finish:
|
||||
return ()
|
||||
extents[lo, hi].append((bottom, top))
|
||||
columns = []
|
||||
previous = start
|
||||
for (left, right), solid in sorted(extents.items()):
|
||||
if left <= previous:
|
||||
return ()
|
||||
openings = open_intervals(solid, problem.bounds[1], problem.bounds[3])
|
||||
if not openings:
|
||||
return ()
|
||||
columns.append(_Column((left, right), openings))
|
||||
previous = right
|
||||
return tuple(columns)
|
||||
|
||||
|
||||
def _ordered_tracks(problem: RoutingProblem) -> tuple[_Track, ...]:
|
||||
tracks = []
|
||||
for net in problem.nets:
|
||||
if net.start.r == net.target.r == 0 and net.start.x < net.target.x:
|
||||
tracks.append(_Track(net, net.start, net.target, False))
|
||||
elif net.start.r == net.target.r == 180 and net.start.x > net.target.x:
|
||||
tracks.append(_Track(net, net.target, net.start, True))
|
||||
else:
|
||||
return ()
|
||||
tracks.sort(key=lambda track: track.left.y)
|
||||
if any(a.left.y >= b.left.y or a.right.y >= b.right.y for a, b in pairwise(tracks)):
|
||||
return ()
|
||||
return tuple(tracks)
|
||||
|
||||
|
||||
def _round_up(y: float, residue: int, modulus: int) -> int:
|
||||
return ceil((y - residue) / modulus) * modulus + residue
|
||||
|
||||
|
||||
def _round_down(y: float, residue: int, modulus: int) -> int:
|
||||
return floor((y - residue) / modulus) * modulus + residue
|
||||
|
||||
|
||||
def _pack_forward(
|
||||
lower: list[int],
|
||||
upper: list[int],
|
||||
spacing: list[float],
|
||||
residues: Profile,
|
||||
desired: tuple[float, ...],
|
||||
modulus: int,
|
||||
reachable: tuple[Profile, ...] = (),
|
||||
) -> Profile:
|
||||
row = []
|
||||
for i, (band_bottom, high, residue, y) in enumerate(zip(lower, upper, residues, desired, strict=True)):
|
||||
low = band_bottom
|
||||
if row:
|
||||
low = max(low, _round_up(row[-1] + spacing[i - 1], residue, modulus))
|
||||
choice = min(high, max(low, round((y - residue) / modulus) * modulus + residue))
|
||||
if reachable:
|
||||
choice = min((v for v in reachable[i] if low <= v <= high), key=lambda v: (abs(v - y), v), default=choice)
|
||||
row.append(choice)
|
||||
return tuple(row)
|
||||
|
||||
|
||||
def _band_profiles(
|
||||
problem: RoutingProblem,
|
||||
opening: Gap,
|
||||
widths: tuple[float, ...],
|
||||
residues: Profile,
|
||||
desired: tuple[float, ...],
|
||||
spacing_slack: int,
|
||||
wall_slack: int,
|
||||
modulus: int,
|
||||
reachability: tuple[tuple[Profile, ...], ...],
|
||||
) -> tuple[Profile, ...]:
|
||||
if not widths:
|
||||
return ((),)
|
||||
bottom, top = opening
|
||||
bottom_wall = bottom != problem.bounds[1]
|
||||
top_wall = top != problem.bounds[3]
|
||||
margin = problem.clearance + wall_slack
|
||||
lower = [_round_up(bottom + w / 2 + (margin if bottom_wall else 0), m, modulus) for w, m in zip(widths, residues, strict=True)]
|
||||
upper = [_round_down(top - w / 2 - (margin if top_wall else 0), m, modulus) for w, m in zip(widths, residues, strict=True)]
|
||||
spacing = [(a + b) / 2 + problem.clearance + spacing_slack for a, b in pairwise(widths)]
|
||||
for i in range(1, len(lower)):
|
||||
lower[i] = max(lower[i], _round_up(lower[i - 1] + spacing[i - 1], residues[i], modulus))
|
||||
for i in range(len(upper) - 2, -1, -1):
|
||||
upper[i] = min(upper[i], _round_down(upper[i + 1] - spacing[i], residues[i], modulus))
|
||||
if any(low > high for low, high in zip(lower, upper, strict=True)):
|
||||
return ()
|
||||
|
||||
profiles = {_pack_forward(lower, upper, spacing, residues, desired, modulus)}
|
||||
# Reflect the band to project preferences from its upper boundary as well.
|
||||
reflected = _pack_forward(
|
||||
[-y for y in reversed(upper)],
|
||||
[-y for y in reversed(lower)],
|
||||
spacing[::-1],
|
||||
tuple(-m for m in reversed(residues)),
|
||||
tuple(-y for y in reversed(desired)),
|
||||
modulus,
|
||||
)
|
||||
profiles.add(tuple(-y for y in reversed(reflected)))
|
||||
if bottom_wall:
|
||||
profiles.add(tuple(lower))
|
||||
if top_wall:
|
||||
profiles.add(tuple(upper))
|
||||
if bottom_wall and top_wall:
|
||||
n = len(lower)
|
||||
spread = tuple(lower[0] + (upper[-1] - lower[0]) * i / max(1, n - 1) for i in range(n))
|
||||
if n == 1:
|
||||
spread = ((lower[0] + upper[0]) / 2,)
|
||||
profiles.add(_pack_forward(lower, upper, spacing, residues, spread, modulus))
|
||||
for reachable in reachability:
|
||||
profiles.add(_pack_forward(lower, upper, spacing, residues, desired, modulus, reachable))
|
||||
return tuple(sorted(profiles))
|
||||
|
||||
|
||||
def _column_profiles(
|
||||
problem: RoutingProblem,
|
||||
column: _Column,
|
||||
widths: tuple[float, ...],
|
||||
residues: Profile,
|
||||
desired: tuple[float, ...],
|
||||
spacing_slack: int,
|
||||
wall_slack: int,
|
||||
modulus: int,
|
||||
reachability: tuple[tuple[Profile, ...], ...] = (),
|
||||
) -> list[Profile]:
|
||||
profiles = set()
|
||||
n = len(widths)
|
||||
band_cache = {}
|
||||
for cuts in combinations_with_replacement(range(n + 1), len(column.openings) - 1):
|
||||
groups = []
|
||||
for opening, (left, right) in zip(column.openings, pairwise((0, *cuts, n)), strict=True):
|
||||
key = opening, left, right
|
||||
if key not in band_cache:
|
||||
band_cache[key] = _band_profiles(
|
||||
problem,
|
||||
opening,
|
||||
widths[left:right],
|
||||
residues[left:right],
|
||||
desired[left:right],
|
||||
spacing_slack,
|
||||
wall_slack,
|
||||
modulus,
|
||||
tuple(candidate[left:right] for candidate in reachability),
|
||||
)
|
||||
groups.append(band_cache[key])
|
||||
profiles.update(tuple(y for group in chosen for y in group) for chosen in product(*groups))
|
||||
return sorted(profiles, key=lambda row: (sum(abs(a - b) for a, b in zip(row, desired, strict=True)), row))[:140]
|
||||
|
||||
|
||||
def _exact_spans(radius: int) -> dict[int, int]:
|
||||
spans = {}
|
||||
for offset in range(1, 2 * radius):
|
||||
squared = offset * (4 * radius - offset)
|
||||
span = isqrt(squared)
|
||||
if span * span == squared:
|
||||
spans[offset] = span
|
||||
return spans
|
||||
|
||||
|
||||
def _bend_sequences(
|
||||
spans: dict[int, int],
|
||||
radius: int,
|
||||
weights: Mapping[str, float],
|
||||
*,
|
||||
weighted: bool,
|
||||
sbend_penalty: float,
|
||||
) -> Callable[[int, int], _BendSequence | None]:
|
||||
# Each S-bend replaces a straight of its forward span in this window.
|
||||
bend_costs = {
|
||||
d: sbend_penalty + weights["sbend"] * 2 * radius * acos(1 - d / (2 * radius)) - weights["straight"] * span for d, span in spans.items()
|
||||
}
|
||||
sequences: list[tuple[_BendSequence, ...]] = [(_BendSequence((), 0, 0.0),)]
|
||||
|
||||
@lru_cache(maxsize=4096)
|
||||
def choose(delta: int, usable: int) -> _BendSequence | None:
|
||||
magnitude = abs(delta)
|
||||
while len(sequences) <= magnitude:
|
||||
height = len(sequences)
|
||||
candidates = [
|
||||
_BendSequence((offset, *prefix.offsets), span + prefix.span, bend_costs[offset] + prefix.cost)
|
||||
for offset, span in spans.items()
|
||||
if offset <= height
|
||||
for prefix in sequences[height - offset]
|
||||
]
|
||||
candidates.sort(
|
||||
key=lambda candidate: (
|
||||
candidate.span,
|
||||
candidate.cost if weighted else len(candidate.offsets),
|
||||
tuple(-d for d in candidate.offsets),
|
||||
)
|
||||
)
|
||||
frontier = []
|
||||
for candidate in candidates:
|
||||
if not frontier or (weighted and candidate.cost < frontier[-1].cost - 1e-9):
|
||||
frontier.append(candidate)
|
||||
sequences.append(tuple(frontier))
|
||||
viable = [candidate for candidate in sequences[magnitude] if candidate.span <= usable]
|
||||
if not viable:
|
||||
return None
|
||||
best = viable[-1]
|
||||
if delta < 0:
|
||||
return _BendSequence(tuple(-offset for offset in best.offsets), best.span, best.cost)
|
||||
return best
|
||||
|
||||
return choose
|
||||
|
||||
|
||||
def _positions(radius: int, spans: dict[int, int], sequence: _BendSequence, window: int, y: int) -> LineString:
|
||||
x = (window - sequence.span) // 2
|
||||
points = [(0, y), (x, y)]
|
||||
for shift in sequence.offsets:
|
||||
theta = acos(1 - abs(shift) / (2 * radius))
|
||||
direction = 1 if shift > 0 else -1
|
||||
advance = spans[abs(shift)]
|
||||
for i in range(1, 13):
|
||||
angle = theta * i / 12
|
||||
points.append((x + radius * sin(angle), y + direction * radius * (1 - cos(angle))))
|
||||
for i in range(11, -1, -1):
|
||||
angle = theta * i / 12
|
||||
points.append((x + advance - radius * sin(angle), y + shift - direction * radius * (1 - cos(angle))))
|
||||
x += advance
|
||||
y += shift
|
||||
points.append((window, y))
|
||||
return LineString(points)
|
||||
|
||||
|
||||
def _schedules(
|
||||
windows: tuple[Window, ...],
|
||||
profiles: list[list[Profile]],
|
||||
widths: tuple[float, ...],
|
||||
clearance: float,
|
||||
radius: int,
|
||||
spans: dict[int, int],
|
||||
weights: Mapping[str, float],
|
||||
*,
|
||||
weighted: bool,
|
||||
sbend_penalty: float,
|
||||
) -> Iterator[tuple[tuple[Profile, ...], tuple[tuple[_BendSequence, ...], ...]]]:
|
||||
choose = _bend_sequences(spans, radius, weights, weighted=weighted, sbend_penalty=sbend_penalty)
|
||||
needs = tuple((a + b) / 2 + clearance for a, b in pairwise(widths))
|
||||
|
||||
# The track order allows a local check of each neighboring pair. The
|
||||
# final router still verifies the exact arcs and every pair of routes.
|
||||
@lru_cache(maxsize=65536)
|
||||
def pair_clear(window: int, gap: int, da: int, db: int, need: float) -> bool:
|
||||
if min(gap, gap + db - da) < need:
|
||||
return False
|
||||
if min(gap, gap + db) - max(0, da) >= need:
|
||||
return True
|
||||
lower, upper = choose(da, window - 4), choose(db, window - 4)
|
||||
assert lower is not None
|
||||
assert upper is not None
|
||||
# Cache the shapes via the local wrapper. The span map is fixed.
|
||||
return positions(lower, window, 0).distance(positions(upper, window, gap)) >= need + 0.025
|
||||
|
||||
@lru_cache(maxsize=8192)
|
||||
def positions(sequence: _BendSequence, window: int, y: int) -> LineString:
|
||||
return _positions(radius, spans, sequence, window, y)
|
||||
|
||||
start = profiles[0][0]
|
||||
approaches = {start: [(0.0, (start,))]}
|
||||
for ((_, after), (before, _)), rows in zip(pairwise(windows), profiles[1:], strict=True):
|
||||
window = before - after
|
||||
next_approaches = {}
|
||||
for row in rows:
|
||||
scores = []
|
||||
for previous, histories in approaches.items():
|
||||
offsets = tuple(b - a for a, b in zip(previous, row, strict=True))
|
||||
sequences = [choose(d, window - 4) for d in offsets]
|
||||
if any(sequence is None for sequence in sequences):
|
||||
continue
|
||||
if any(
|
||||
not pair_clear(window, b - a, da, db, need)
|
||||
for (a, b), (da, db), need in zip(pairwise(previous), pairwise(offsets), needs, strict=True)
|
||||
):
|
||||
continue
|
||||
if weighted:
|
||||
cost = sum(sequence.cost for sequence in sequences if sequence is not None)
|
||||
else:
|
||||
cost = sum(abs(d) for d in offsets) + 1.5 * max(abs(d) for d in offsets)
|
||||
cost += 0.02 * sum(sequence.span for sequence in sequences if sequence is not None)
|
||||
scores.extend((score + cost, (*history, row)) for score, history in histories)
|
||||
if scores:
|
||||
next_approaches[row] = sorted(scores)[:2]
|
||||
approaches = next_approaches
|
||||
if not approaches:
|
||||
return
|
||||
for _, rows in approaches.get(profiles[-1][0], ()):
|
||||
moves = []
|
||||
for ((_, after), (before, _)), (a, b) in zip(pairwise(windows), pairwise(rows), strict=True):
|
||||
sequences = tuple(choose(y1 - y0, before - after - 4) for y0, y1 in zip(a, b, strict=True))
|
||||
assert all(sequence is not None for sequence in sequences)
|
||||
moves.append(tuple(sequence for sequence in sequences if sequence is not None))
|
||||
yield rows, tuple(moves)
|
||||
|
||||
|
||||
def _seeds(
|
||||
tracks: tuple[_Track, ...],
|
||||
windows: tuple[Window, ...],
|
||||
moves: tuple[tuple[_BendSequence, ...], ...],
|
||||
radius: int,
|
||||
) -> dict[str, PathSeed]:
|
||||
seeds = {}
|
||||
for i, track in enumerate(tracks):
|
||||
x = track.left.x
|
||||
segments: list[PathSegmentSeed] = []
|
||||
for ((_, after), (before, _)), sequences in zip(pairwise(windows), moves, strict=True):
|
||||
sequence = sequences[i]
|
||||
if not sequence.offsets:
|
||||
continue
|
||||
entrance = (after + before - sequence.span) // 2
|
||||
segments.append(StraightSeed(entrance - x))
|
||||
segments.extend(SBendSeed(offset, radius) for offset in sequence.offsets)
|
||||
x = entrance + sequence.span
|
||||
segments.append(StraightSeed(track.right.x - x))
|
||||
seeds[track.net.net_id] = PathSeed(tuple(reversed(segments) if track.westbound else segments))
|
||||
return seeds
|
||||
|
||||
|
||||
def column_seed_candidates(
|
||||
problem: RoutingProblem,
|
||||
search: SearchOptions,
|
||||
weights: Mapping[str, float],
|
||||
*,
|
||||
weighted: bool,
|
||||
sbend_penalty: float = 0.0,
|
||||
) -> Iterator[dict[str, PathSeed]]:
|
||||
"""Yield candidate routes from configured circular bends and problem geometry."""
|
||||
_, physical_geometry = resolve_bend_geometry(search)
|
||||
bend = min(search.sbend_radii, default=0.0)
|
||||
if problem.initial_paths or physical_geometry != "arc" or not isfinite(bend) or bend <= 0 or bend != int(bend):
|
||||
return
|
||||
tracks = _ordered_tracks(problem)
|
||||
if len(tracks) < 3 or any(not isfinite(track.net.width) or track.net.width <= 0 for track in tracks):
|
||||
return
|
||||
start, finish = max(track.left.x for track in tracks), min(track.right.x for track in tracks)
|
||||
columns = _columns(problem, start, finish)
|
||||
if not columns:
|
||||
return
|
||||
radius = int(bend)
|
||||
spans = _exact_spans(radius)
|
||||
if not spans:
|
||||
return
|
||||
modulus = gcd(*spans)
|
||||
launch, arrival = tuple(track.left.y for track in tracks), tuple(track.right.y for track in tracks)
|
||||
residues = tuple(y % modulus for y in launch)
|
||||
if tuple(y % modulus for y in arrival) != residues:
|
||||
return
|
||||
widths = tuple(track.net.width for track in tracks)
|
||||
windows = ((start, start), *(column.span for column in columns), (finish, finish))
|
||||
preferences = []
|
||||
for column in columns:
|
||||
share = (sum(column.span) / 2 - start) / (finish - start)
|
||||
preferences.append(tuple(a + share * (b - a) for a, b in zip(launch, arrival, strict=True)))
|
||||
# The first pass uses moderate lateral shifts. Later passes relax the
|
||||
# spacing or try smaller or larger bends if a transition will not fit.
|
||||
limits = tuple(dict.fromkeys(min(2 * radius - 1, ceil(radius * frac)) for frac in (0.8, 0.4, 1.44)))
|
||||
seen = set()
|
||||
for spacing_slack, wall_slack, maximum in product((5, 3, 2, 1, 0, 7), (1, 0), limits):
|
||||
active_spans = {d: span for d, span in spans.items() if d <= maximum}
|
||||
if not active_spans:
|
||||
continue
|
||||
interior = [
|
||||
_column_profiles(problem, column, widths, residues, preference, spacing_slack, wall_slack, modulus)
|
||||
for column, preference in zip(columns, preferences, strict=True)
|
||||
]
|
||||
if weighted:
|
||||
adjacent = [[launch], *interior, [arrival]]
|
||||
reachable_offsets = (0, *(d for offset in active_spans for d in (-offset, offset)))
|
||||
for i, (column, preference) in enumerate(zip(columns, preferences, strict=True)):
|
||||
anchors = (*adjacent[i][:2], *adjacent[i + 2][:2])
|
||||
reachable = tuple(tuple(tuple(y + d for d in reachable_offsets) for y in anchor) for anchor in anchors)
|
||||
seeded = _column_profiles(problem, column, widths, residues, preference, spacing_slack, wall_slack, modulus, reachable)
|
||||
interior[i] = sorted(set(interior[i] + seeded))
|
||||
for i, (column, preference) in enumerate(zip(columns, preferences, strict=True)):
|
||||
if column.openings[0][0] == problem.bounds[1] or column.openings[-1][1] == problem.bounds[3]:
|
||||
roomier = _column_profiles(problem, column, widths, residues, preference, spacing_slack + 5, wall_slack, modulus)
|
||||
interior[i] = sorted(set(interior[i] + roomier[:45]))
|
||||
profiles = [[launch], *interior, [arrival]]
|
||||
for rows, moves in _schedules(
|
||||
windows, profiles, widths, problem.clearance, radius, active_spans, weights, weighted=weighted, sbend_penalty=sbend_penalty
|
||||
):
|
||||
signature = rows, moves
|
||||
if signature not in seen:
|
||||
seen.add(signature)
|
||||
yield _seeds(tracks, windows, moves, radius)
|
||||
Loading…
Reference in a new issue