inire/inire/router/_columns.py

830 lines
35 KiB
Python

"""Construct ordered routes through nonoverlapping columns of rectangles."""
from __future__ import annotations
from collections import defaultdict
from dataclasses import dataclass, replace
from functools import cache, lru_cache
from heapq import heappop, heappush, merge
from itertools import combinations_with_replacement, islice, pairwise, product
from math import acos, ceil, comb, cos, floor, gcd, isfinite, pi, sin
from typing import TYPE_CHECKING
from shapely import total_bounds
from shapely.geometry import LineString, box
from inire.geometry.components import bend90_uses_circular_geometry, bend_fits_width
from inire.geometry.intervals import Gap, open_intervals
from inire.geometry.sbend import ExactSBendScanLimitError, exact_sbend_spans
from inire.model import resolve_bend_geometry
from inire.router._waypoints import compile_waypoints
from inire.seeds import PathSeed, SBendSeed, StraightSeed
if TYPE_CHECKING:
from collections.abc import Callable, Iterator, Mapping
from shapely.geometry import Polygon
from inire.geometry.primitives import Port
from inire.model import NetSpec, RoutingProblem, SearchOptions
from inire.router._waypoints import XY
from inire.seeds import PathSegmentSeed
Profile = tuple[int, ...]
Window = tuple[int, int]
JogPivots = tuple[int | None, ...]
JogSchedule = tuple[float, tuple[Profile, ...], tuple[JogPivots, ...]]
_MAX_COLUMN_PARTITIONS = 4096
_MAX_COLUMN_PROFILES = 140
@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 _ColumnLayout:
tracks: tuple[_Track, ...]
columns: tuple[_Column, ...]
spans: tuple[Window, ...]
launch: Profile
arrival: Profile
widths: tuple[float, ...]
preferences: tuple[tuple[float, ...], ...]
@dataclass(frozen=True, slots=True)
class _BendSequence:
offsets: tuple[int, ...]
span: int
cost: float
@dataclass(frozen=True, slots=True, repr=False, eq=False)
class _BendState:
offset: int
previous: _BendState | None
span: int
cost: float
length: int
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._blocking_polygons:
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 _partition_budget_exceeded(tracks: tuple[_Track, ...], columns: tuple[_Column, ...]) -> bool:
return any(
comb(len(tracks) + len(column.openings) - 1, len(column.openings) - 1) > _MAX_COLUMN_PARTITIONS for column in columns
)
def _track_columns(problem: RoutingProblem, tracks: tuple[_Track, ...]) -> tuple[int, int, tuple[_Column, ...]]:
start = max(int(track.left.x) for track in tracks)
finish = min(int(track.right.x) for track in tracks)
return start, finish, _columns(problem, start, finish)
def column_partition_budget_exceeded(problem: RoutingProblem) -> bool:
tracks = _ordered_tracks(problem)
return bool(tracks) and _partition_budget_exceeded(tracks, _track_columns(problem, tracks)[2])
def _column_layout(problem: RoutingProblem, *, min_tracks: int = 3) -> _ColumnLayout | None:
tracks = _ordered_tracks(problem)
if len(tracks) < min_tracks or any(not isfinite(track.net.width) or track.net.width <= 0 for track in tracks):
return None
start, finish, columns = _track_columns(problem, tracks)
if not columns or _partition_budget_exceeded(tracks, columns):
return None
launch = tuple(int(track.left.y) for track in tracks)
arrival = tuple(int(track.right.y) for track in tracks)
spans = ((start, start), *(column.span for column in columns), (finish, finish))
preferences = []
for column in columns:
fraction = (sum(column.span) / 2 - start) / (finish - start)
preferences.append(tuple(a + fraction * (b - a) for a, b in zip(launch, arrival, strict=True)))
return _ColumnLayout(tracks, columns, spans, launch, arrival, tuple(track.net.width for track in tracks), tuple(preferences))
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, ...], ...] = (),
*,
combinations_limit: int | None = None,
) -> list[Profile]:
@cache
def band_profiles(opening: Gap, left: int, right: int) -> tuple[Profile, ...]:
return _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),
)
if combinations_limit is None:
return _best_column_profiles(column.openings, desired, band_profiles)
profiles = set()
n = len(widths)
for cuts in combinations_with_replacement(range(n + 1), len(column.openings) - 1):
groups = [
band_profiles(opening, left, right)
for opening, (left, right) in zip(column.openings, pairwise((0, *cuts, n)), strict=True)
]
for chosen in islice(product(*groups), combinations_limit):
profiles.add(tuple(y for group in chosen for y in group))
combinations_limit -= 1
if combinations_limit == 0:
break
return sorted(profiles, key=lambda row: (sum(abs(a - b) for a, b in zip(row, desired, strict=True)), row))[:_MAX_COLUMN_PROFILES]
def _best_column_profiles(
openings: tuple[Gap, ...],
desired: tuple[float, ...],
band_profiles: Callable[[Gap, int, int], tuple[Profile, ...]],
) -> list[Profile]:
# Sum deviations exactly so adding a band preserves the order of tied prefixes.
ratios = tuple(y.as_integer_ratio() for y in desired)
scale = max((denominator for _, denominator in ratios), default=1)
scaled_targets = tuple(numerator * (scale // denominator) for numerator, denominator in ratios)
def extend(prefixes: list[tuple[int, Profile]], band: Profile, deviation: int) -> Iterator[tuple[int, Profile]]:
return ((cost + deviation, prefix + band) for cost, prefix in prefixes)
# Prefixes that have placed the same number of tracks can use the same
# remaining bands. Each extension preserves the order by deviation and row.
# Disjoint bands make each row correspond to a unique track assignment.
prefixes: dict[int, list[tuple[int, Profile]]] = {0: [(0, ())]}
count = len(desired)
for index, opening in enumerate(openings, start=1):
next_prefixes = {}
for right in ((count,) if index == len(openings) else range(count + 1)):
streams = []
for left, ranked in prefixes.items():
if left > right:
continue
targets = scaled_targets[left:right]
for band in band_profiles(opening, left, right):
deviation = sum(abs(y * scale - target) for y, target in zip(band, targets, strict=True))
streams.append(extend(ranked, band, deviation))
if streams:
next_prefixes[right] = list(islice(merge(*streams), _MAX_COLUMN_PROFILES))
if not next_prefixes:
return []
prefixes = next_prefixes
return [row for _, row in prefixes.get(count, ())]
def _bend_sequences(
spans: dict[int, int],
radius: int,
weights: Mapping[str, float],
*,
max_usable: int,
weighted: bool,
sbend_penalty: float,
allowed_offsets: frozenset[float] | None = None,
) -> Callable[[int, int], _BendSequence | None]:
if allowed_offsets is not None:
positive = {d: span for d, span in spans.items() if d in allowed_offsets}
negative = {d: span for d, span in spans.items() if -d in allowed_offsets}
if positive != negative:
choose_up = _bend_sequences(positive, radius, weights, max_usable=max_usable, weighted=weighted, sbend_penalty=sbend_penalty)
choose_down = _bend_sequences(negative, radius, weights, max_usable=max_usable, weighted=weighted, sbend_penalty=sbend_penalty)
def choose_signed(delta: int, usable: int) -> _BendSequence | None:
return (choose_down if delta < 0 else choose_up)(delta, usable)
return choose_signed
spans = positive
# Each S-bend replaces a straight of its forward span in this window.
bends = [
(d, span, sbend_penalty + weights["sbend"] * 2 * radius * acos(1 - d / (2 * radius)) - weights["straight"] * span)
for d, span in spans.items()
if span <= max_usable
]
sequences = {0: (_BendState(0, None, 0, 0.0, 0),)}
upcoming = sorted(offset for offset, _, _ in bends)
stride = gcd(*upcoming) or 1
queued = set(upcoming)
@lru_cache(maxsize=4096)
def choose(delta: int, usable: int) -> _BendSequence | None:
magnitude = abs(delta)
# A circular S-bend advances at least as far as it shifts.
if magnitude > usable or magnitude % stride:
return None
while upcoming and upcoming[0] <= magnitude:
height = heappop(upcoming)
queued.remove(height)
candidates = [
_BendState(offset, prefix, span + prefix.span, cost + prefix.cost, prefix.length + 1)
for offset, span, cost in bends
for prefix in sequences.get(height - offset, ())
if span + prefix.span <= max_usable
]
# For each leading offset and span, at most one predecessor survives.
candidates.sort(
key=lambda candidate: (
candidate.span,
candidate.cost if weighted else candidate.length,
-candidate.offset,
)
)
frontier: list[_BendState] = []
for candidate in candidates:
if not frontier or (weighted and candidate.cost < frontier[-1].cost - 1e-9):
frontier.append(candidate)
sequences[height] = tuple(frontier)
# The shortest prefix determines whether a successor can fit.
remaining = max_usable - frontier[0].span
for offset, span, _ in bends:
next_height = height + offset
if span <= remaining and next_height not in queued:
heappush(upcoming, next_height)
queued.add(next_height)
best = next((state for state in reversed(sequences.get(magnitude, ())) if state.span <= usable), None)
if best is None:
return None
sign = -1 if delta < 0 else 1
offsets = []
state = best
while state.previous is not None:
offsets.append(sign * state.offset)
state = state.previous
return _BendSequence(tuple(offsets), best.span, best.cost)
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,
allowed_offsets: frozenset[float] | None = None,
) -> Iterator[tuple[tuple[Profile, ...], tuple[tuple[_BendSequence, ...], ...]]]:
max_usable = max(before - after - 4 for (_, after), (before, _) in pairwise(windows))
choose = _bend_sequences(
spans, radius, weights, max_usable=max_usable, weighted=weighted, sbend_penalty=sbend_penalty, allowed_offsets=allowed_offsets,
)
needs = tuple((a + b) / 2 + clearance for a, b in pairwise(widths))
straight_tracks = tuple(i for i, width in enumerate(widths) if not bend_fits_width(radius, width))
# 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))
if straight_tracks and any(offsets[i] for i in straight_tracks):
continue
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_sbend_schedules(
problem: RoutingProblem,
layout: _ColumnLayout,
radius: int,
spans: dict[int, int],
weights: Mapping[str, float],
*,
weighted: bool,
sbend_penalty: float,
allowed_offsets: frozenset[float] | None,
) -> Iterator[tuple[tuple[_BendSequence, ...], ...]]:
modulus = gcd(*spans)
launch, arrival = layout.launch, layout.arrival
residues = tuple(y % modulus for y in launch)
if tuple(y % modulus for y in arrival) != residues:
return
columns, widths, windows, preferences = layout.columns, layout.widths, layout.spans, layout.preferences
# 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 = (min(2 * radius - 1, ceil(radius * frac)) for frac in (0.8, 0.4, 1.44))
span_sets = dict.fromkeys(tuple((d, span) for d, span in spans.items() if d <= maximum) for maximum in limits)
active_span_sets = tuple(dict(span_set) for span_set in span_sets if span_set)
# Keep the base and extra-spacing profiles for the current slack setting.
@lru_cache(maxsize=2 * len(columns))
def profiles_for(column_index: int, spacing_slack: int, wall_slack: int) -> list[Profile]:
return _column_profiles(
problem, columns[column_index], widths, residues, preferences[column_index], spacing_slack, wall_slack, modulus,
)
seen = set()
for spacing_slack, wall_slack, active_spans in product((5, 3, 2, 1, 0, 7), (1, 0), active_span_sets):
interior = [profiles_for(i, spacing_slack, wall_slack) for i in range(len(columns))]
if weighted:
adjacent = [[launch], *interior, [arrival]]
reachable_offsets = (0, *(
d for offset in active_spans for d in (-offset, offset) if allowed_offsets is None or d in allowed_offsets
))
return_offsets = tuple(-d for d in reachable_offsets)
for i, (column, preference) in enumerate(zip(columns, preferences, strict=True)):
anchors = [(anchor, reachable_offsets) for anchor in adjacent[i][:2]]
anchors.extend((anchor, return_offsets) for anchor in adjacent[i + 2][:2])
reachable = tuple(tuple(tuple(y + d for d in offsets) for y in anchor) for anchor, offsets 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 in enumerate(columns):
if column.openings[0][0] == problem.bounds[1] or column.openings[-1][1] == problem.bounds[3]:
roomier = profiles_for(i, spacing_slack + 5, wall_slack)
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, allowed_offsets=allowed_offsets,
):
signature = rows, moves
if signature not in seen:
seen.add(signature)
yield moves
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)
if problem.initial_paths or physical_geometry != "arc":
return
radii = sorted({int(r) for r in search.sbend_radii if isfinite(r) and r > 0 and r == int(r)})
if not radii:
return
layout = _column_layout(problem)
if layout is None:
return
max_span = max(before - after - 4 for (_, after), (before, _) in pairwise(layout.spans))
max_offset = floor(problem.bounds[3]) - ceil(problem.bounds[1])
shifting_width = max((w for a, b, w in zip(layout.launch, layout.arrival, layout.widths, strict=True) if a != b), default=0.0)
allowed_offsets = None if search.sbend_offsets is None else frozenset(search.sbend_offsets)
for radius in radii:
if not bend_fits_width(radius, shifting_width):
continue
try:
spans = exact_sbend_spans(radius, max_span=max_span, max_offset=max_offset, offsets=search.sbend_offsets)
except ExactSBendScanLimitError:
continue
if not spans:
continue
for moves in _column_sbend_schedules(
problem, layout, radius, spans, weights, weighted=weighted, sbend_penalty=sbend_penalty, allowed_offsets=allowed_offsets,
):
seeds = _seeds(layout.tracks, layout.spans, moves, radius)
if all(search.seed_geometry_error(seed) is None for seed in seeds.values()):
yield seeds
def _jog_pivots(
left: Profile,
right: Profile,
window: Window,
widths: tuple[float, ...],
clearance: float,
radius: int,
minimum: float,
) -> JogPivots | None:
# For an upward shift, move the upper tracks first. For a downward
# shift, move the lower tracks first. Opposite shifts have disjoint
# lateral sweeps when both endpoint rows preserve track order.
upward = [i for i in reversed(range(len(left))) if left[i] < right[i]]
downward = [i for i in range(len(left)) if right[i] < left[i]]
pivots: list[int | None] = [None] * len(left)
scheduled: list[int] = []
for i in (*upward, *downward):
low, high = sorted((left[i], right[i]))
straight = high - low - 2 * radius
if straight < 0 or 0 < straight < minimum:
return None
margin = ceil(radius + max(minimum, clearance + widths[i] / 2))
pivot = window[0] + margin
for j in scheduled:
pitch = clearance + (widths[i] + widths[j]) / 2
other_low, other_high = sorted((left[j], right[j]))
if min(high, other_high) + pitch > max(low, other_low):
previous = pivots[j]
assert previous is not None
pivot = max(pivot, previous + ceil(2 * radius + max(minimum, pitch)))
if pivot > window[1] - margin:
return None
pivots[i] = pivot
scheduled.append(i)
return tuple(pivots)
def _jog_schedules(
profiles: list[list[Profile]],
windows: tuple[Window, ...],
widths: tuple[float, ...],
clearance: float,
radius: int,
minimum: float,
) -> list[JogSchedule]:
start = profiles[0][0]
approaches: dict[Profile, list[JogSchedule]] = {start: [(0.0, (start,), ())]}
for window, rows in zip(windows, profiles[1:], strict=True):
after = {}
for row in rows:
proposals = []
for previous, histories in approaches.items():
pivots = _jog_pivots(previous, row, window, widths, clearance, radius, minimum)
if pivots is None:
continue
length = sum(abs(a - b) for a, b in zip(previous, row, strict=True))
length += sum(pivot is not None for pivot in pivots) * (pi - 2) * radius
proposals.extend((score + length, (*history, row), (*moves, pivots)) for score, history, moves in histories)
if proposals:
after[row] = sorted(proposals, key=lambda proposal: (proposal[0], proposal[1]))[:3]
approaches = after
if not approaches:
break
return approaches.get(profiles[-1][0], [])
def _jog_seeds(
tracks: tuple[_Track, ...], rows: tuple[Profile, ...], moves: tuple[JogPivots, ...], radius: int, minimum: float,
) -> dict[str, PathSeed] | None:
seeds = {}
for i, track in enumerate(tracks):
points: list[XY] = [(int(track.left.x), int(track.left.y))]
for (left, right), pivots in zip(pairwise(rows), moves, strict=True):
pivot = pivots[i]
if pivot is not None:
points.extend(((pivot, left[i]), (pivot, right[i])))
points.append((int(track.right.x), int(track.right.y)))
if track.westbound:
points.reverse()
seed, end = compile_waypoints(tuple(points), track.net.start, radius)
if end != track.net.target or any(isinstance(move, StraightSeed) and move.length < minimum for move in seed.segments):
return None
seeds[track.net.net_id] = seed
return seeds
def _column_jog_schedules(
problem: RoutingProblem,
layout: _ColumnLayout,
radii: list[int],
minimum: float,
profiles_for_slack: Callable[[int], list[list[Profile]]],
*,
circular: bool,
) -> Iterator[tuple[int, tuple[Profile, ...], tuple[JogPivots, ...]]]:
radius_choices = []
for radius in radii:
# Tracks that cannot bend must stay on their launch rows in every column.
straight_rows = tuple((i, layout.launch[i]) for i, width in enumerate(layout.widths) if circular and not bend_fits_width(radius, width))
if all(layout.arrival[i] == y for i, y in straight_rows):
radius_choices.append((radius, straight_rows))
if not radius_choices:
return
windows = tuple((after, before) for (_, after), (before, _) in pairwise(layout.spans))
for slack in (1, 0):
profiles = profiles_for_slack(slack)
for radius, straight_rows in radius_choices:
eligible = profiles
if straight_rows:
eligible = [[row for row in rows if all(row[i] == y for i, y in straight_rows)] for rows in profiles]
if not all(eligible):
continue
schedules = _jog_schedules(eligible, windows, layout.widths, problem.clearance, radius, minimum)
for _, rows, moves in schedules:
yield radius, rows, moves
def column_jog_candidates(
problem: RoutingProblem, search: SearchOptions, *, limit_per_pass: int | None = None, recovery: bool = False,
) -> Iterator[dict[str, PathSeed]]:
"""Allocate tracks through ordered apertures using staggered 90-degree jogs."""
if problem.initial_paths:
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
layout = _column_layout(problem, min_tracks=1 if recovery else 3)
if layout is None:
return
circular = bend90_uses_circular_geometry(*resolve_bend_geometry(search))
@cache
def profiles_for_slack(slack: int) -> list[list[Profile]]:
widths = layout.widths
# Modulus one allows any integer track level.
residues = (0,) * len(widths)
interior = [
_column_profiles(problem, column, widths, residues, desired, slack, slack, 1, combinations_limit=8192)
for column, desired in zip(layout.columns, layout.preferences, strict=True)
]
if recovery:
# Terminal rows can carry through a column without a jog. They also
# give later turns room when the interpolated rows hug aperture edges.
anchors = dict.fromkeys((layout.launch, layout.arrival))
for i, column in enumerate(layout.columns):
rows = set(interior[i])
for anchor in anchors:
rows.update(_column_profiles(problem, column, widths, residues, anchor, slack, slack, 1))
interior[i] = sorted(rows)
return [[layout.launch], *interior, [layout.arrival]]
seen: set[tuple[tuple[str, PathSeed], ...]] = set()
def seed_pass(minimum: float) -> Iterator[dict[str, PathSeed]]:
for radius, rows, moves in _column_jog_schedules(problem, layout, radii, minimum, profiles_for_slack, circular=circular):
seeds = _jog_seeds(layout.tracks, rows, moves, radius, minimum)
if seeds is None:
continue
signature = tuple(seeds.items())
if signature in seen:
continue
seen.add(signature)
yield seeds
for minimum in dict.fromkeys((search.min_straight_length, 0.0)):
yield from islice(seed_pass(minimum), limit_per_pass)
def column_recovery_subproblems(problem: RoutingProblem) -> tuple[RoutingProblem, ...]:
"""Use full-width keepouts to isolate independent horizontal channels."""
xmin, ymin, xmax, ymax = problem.bounds
dividers = []
for shape in problem.static_obstacles:
left, bottom, right, top = shape.bounds
if left <= xmin and right >= xmax and ymin < top and bottom < ymax and shape.equals(box(left, bottom, right, top)):
dividers.append((bottom, top))
if not dividers:
return (problem,)
clearance = problem.clearance
def nearby(shapes: tuple[Polygon, ...], lower: float, upper: float) -> tuple[Polygon, ...]:
return tuple(shape for shape in shapes if shape.bounds[3] > lower - clearance and shape.bounds[1] < upper + clearance)
groups = []
for bottom, top in open_intervals(dividers, ymin, ymax):
lower = bottom + clearance if bottom != ymin else bottom
upper = top - clearance if top != ymax else top
if lower >= upper:
continue
nets = tuple(net for net in problem.nets if lower <= net.start.y <= upper and lower <= net.target.y <= upper)
if not nets:
continue
fixed_routes = []
for fixed in problem.fixed_routes:
polygons = nearby(fixed.polygons, lower, upper)
if polygons:
fixed_routes.append(replace(fixed, polygons=polygons))
groups.append(replace(
problem, bounds=(xmin, lower, xmax, upper), nets=nets,
static_obstacles=nearby(problem.static_obstacles, lower, upper), fixed_routes=tuple(fixed_routes),
))
return tuple(groups) if sum(len(group.nets) for group in groups) == len(problem.nets) else ()
def column_recovery_candidates(problem: RoutingProblem, search: SearchOptions) -> Iterator[dict[str, PathSeed]]:
"""Try individual apertures and a shared bypass outside the keepout field."""
yield from column_jog_candidates(problem, search, limit_per_pass=8, recovery=True)
obstacles = problem._blocking_polygons
if len(obstacles) < 2:
return
# Covering every keepout with one box offers a cheap option when planning
# individual columns has too many aperture assignments. Verify on the real board.
envelope = replace(problem, static_obstacles=(box(*total_bounds(obstacles)),), fixed_routes=())
yield from column_jog_candidates(envelope, search, limit_per_pass=8, recovery=True)