"""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, islice, pairwise, product from math import acos, ceil, comb, cos, floor, gcd, isfinite, pi, sin from typing import TYPE_CHECKING from shapely.geometry import LineString from inire.geometry.intervals import Gap, open_intervals from inire.geometry.sbend import 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 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, ...]] @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 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 _column_layout(problem: RoutingProblem) -> _ColumnLayout | None: 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 None start = max(int(track.left.x) for track in tracks) finish = min(int(track.right.x) for track in tracks) columns = _columns(problem, start, finish) if not 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]: 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]) combinations = product(*groups) if combinations_limit is None: profiles.update(tuple(y for group in chosen for y in group) for chosen in combinations) else: for chosen in islice(combinations, 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))[:140] 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_sbend_schedules( problem: RoutingProblem, layout: _ColumnLayout, radius: int, spans: dict[int, int], weights: Mapping[str, float], *, weighted: bool, sbend_penalty: float, ) -> 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 = 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 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) 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 radius = int(bend) spans = {d: span for d, span in exact_sbend_spans(radius).items() if search.allows_sbend_offset(d) or search.allows_sbend_offset(-d)} if not spans: return layout = _column_layout(problem) if layout is None: return for moves in _column_sbend_schedules(problem, layout, radius, spans, weights, weighted=weighted, sbend_penalty=sbend_penalty): 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, search: SearchOptions ) -> 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 not search.min_straight_length <= move.length <= search.max_straight_length 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, ) -> Iterator[tuple[int, tuple[Profile, ...], tuple[JogPivots, ...]]]: columns, widths, preferences = layout.columns, layout.widths, layout.preferences launch, arrival = layout.launch, layout.arrival windows = tuple((after, before) for (_, after), (before, _) in pairwise(layout.spans)) for slack in (1, 0): # Modulus one allows any integer track level, independent of the # set of exact S-bend spans. interior = [ _column_profiles(problem, column, widths, (0,) * len(widths), desired, slack, slack, 1, combinations_limit=8192) for column, desired in zip(columns, preferences, strict=True) ] for radius in radii: schedules = _jog_schedules( [[launch], *interior, [arrival]], windows, widths, problem.clearance, radius, minimum ) for _, rows, moves in schedules: yield radius, rows, moves def column_jog_candidates(problem: RoutingProblem, search: SearchOptions) -> 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) if layout is None or any( comb(len(layout.tracks) + len(column.openings) - 1, len(column.openings) - 1) > 4096 for column in layout.columns ): return for radius, rows, moves in _column_jog_schedules(problem, layout, radii, search.min_straight_length): seeds = _jog_seeds(layout.tracks, rows, moves, radius, search) if seeds is not None: yield seeds