"""Constructive routing for ordered bundles with an outer return and paired barriers.""" from __future__ import annotations from collections import defaultdict from dataclasses import dataclass, replace from itertools import pairwise from math import ceil, floor, isfinite, isqrt, sqrt from typing import TYPE_CHECKING from shapely.geometry import box from inire.geometry.primitives import Port from inire.geometry.components import bend_fits_width from inire.geometry.sbend import exact_sbend_spans from inire.model import resolve_bend_geometry from inire.router._waypoints import XY, compile_waypoints if TYPE_CHECKING: from inire.model import NetSpec, RoutingProblem, SearchOptions Bounds = tuple[float, float, float, float] @dataclass(frozen=True, slots=True) class _Layout: first: tuple[Bounds, Bounds] last: tuple[Bounds, Bounds] north: Bounds south: Bounds tower: Bounds outer_return: NetSpec short: NetSpec lower: tuple[NetSpec, ...] upper: tuple[NetSpec, ...] @dataclass(frozen=True, slots=True) class _Shift: x: int y: int sbend: bool = False def _identify_layout(problem: RoutingProblem, margin: float) -> _Layout: columns: dict[tuple[float, float], list[Bounds]] = defaultdict(list) for obstacle in problem._blocking_polygons: if not obstacle.equals(box(*obstacle.bounds)): raise ValueError("Bundle routing requires axis-aligned rectangular obstacles") x0, y0, x1, y1 = obstacle.bounds columns[x0, x1].append((x0, y0, x1, y1)) paired = [tuple(sorted(column, key=lambda b: b[1])) for _, column in sorted(columns.items()) if len(column) == 2] singles = [column[0] for column in columns.values() if len(column) == 1] if len(paired) != 2 or len(singles) != 3 or len(columns) != 5: raise ValueError("Bundle routing requires two paired barriers and three interior obstacles") first, last = paired tower = min(singles, key=lambda b: b[1]) north = max(singles, key=lambda b: b[3]) if tower == north: raise ValueError("An ordered bundle needs separate north and tower obstacles") (south,) = (b for b in singles if b not in (tower, north)) if not first[0][2] < min(north[0], south[0]) < max(north[2], south[2]) < tower[0] < last[0][0]: raise ValueError("The paired barriers must enclose the north and south obstacles followed by the tower") nets = sorted(problem.nets, key=lambda net: net.start.y) if ( not nets or len({(net.start.x, net.start.r, net.width) for net in nets}) != 1 or len({net.start.y for net in nets}) != len(nets) or nets[0].start.r != 0 ): raise ValueError("Bundle routing requires equally wide eastbound launches on a common x coordinate") if nets[0].start.x >= first[0][0] or any(net.target.x <= net.start.x for net in nets): raise ValueError("Bundle routing requires launches before the first barrier and destinations to the east") right = max(net.target.x for net in nets) outer_return = nets[0] interior = [net for net in nets[1:] if net.target.x < right] if len(interior) != 1 or not north[2] < outer_return.target.x < tower[0]: raise ValueError("Bundle routing requires a short route and an outer return to the north shelf") short = interior[0] if not (first[0][3] + margin <= short.start.y <= first[1][1] - margin and short.target.x < north[0]): raise ValueError("The short route must leave through the first gap and end before the north obstacle") lower = tuple(net for net in nets[1:] if net.start.y < short.start.y) upper = tuple(net for net in nets if net.start.y > short.start.y) through = (*lower, *upper) if ( len(lower) < 2 or len(upper) < 3 or any(a.target.y >= b.target.y for a, b in pairwise(through)) or outer_return.target.y <= max(net.target.y for net in through) ): raise ValueError("The through nets must retain their launch order below the return") if not last[0][3] + margin <= upper[0].target.y <= last[1][1] - margin: raise ValueError("The lowest upper net must terminate opposite the second gap") return _Layout(first, last, north, south, tower, outer_return, short, lower, upper) def _eastbound_launches(problem: RoutingProblem) -> RoutingProblem: nets = tuple(replace(net, start=Port(net.start.x, net.start.y, 0)) for net in problem.nets) return replace(problem, nets=nets) def ordered_bundle_terminal_headings(problem: RoutingProblem) -> RoutingProblem: """Resolve terminal headings from the layout without assigning tracks.""" if not problem.nets: return problem problem = _eastbound_launches(problem) layout = _identify_layout(problem, problem.nets[0].width / 2 + problem.clearance) nets = tuple(replace(net, target=Port(net.target.x, net.target.y, 180 if net == layout.outer_return else 0)) for net in problem.nets) return replace(problem, nets=nets) def _assign_shifts( layout: _Layout, radius: int, margin: float, pitch: int, floor_lane: int, search: SearchOptions, ) -> tuple[dict[str, list[_Shift]], int]: short, lower, upper = layout.short, layout.lower, layout.upper middle, *ascending, shelf = upper north, south, tower = layout.north, layout.south, layout.tower last_lower, last_upper = layout.last stagger = max(pitch, radius // 2) launch = ceil(short.start.x) + 2 * radius shifts: dict[str, list[_Shift]] = {net.net_id: [] for net in (short, *lower, *upper)} # Account for the perimeter return first, then fill the remaining bottom tracks. bottom_capacity = 1 + floor((tower[1] - margin - 1 - floor_lane) / pitch) if bottom_capacity < 1: raise ValueError("The tower blocks the perimeter return") above_tower = lower[bottom_capacity - 1 :] for index, net in enumerate(lower, start=1): shifts[net.net_id].append(_Shift(launch + index * stagger, floor_lane + index * pitch)) upper_base = ceil(max(layout.first[1][3] + margin + 1, short.target.y + radius)) for index, net in enumerate(upper[:-1]): shifts[net.net_id].append(_Shift(launch + (len(upper) - 1 - index) * stagger, upper_base + index * pitch)) shelf_launch = ceil(max(north[3] + margin + 1, upper_base + (len(upper) - 1) * pitch)) shifts[shelf.net_id].append(_Shift(launch, shelf_launch)) shifts[short.net_id].append(_Shift(int(short.target.x) - 2 * radius, int(short.target.y))) # Pack descending tracks beside the short terminal. The limiting turn must # already be below the obstacle keepout when its arc reaches the left wall. drop = ceil(short.target.x + pitch) available = north[0] - margin - drop - (len(upper) - 2) * pitch if available <= 0: raise ValueError("The side of the north obstacle has insufficient track capacity") run = min(radius, available) max_y = floor(north[1] - margin - radius + sqrt(run * (2 * radius - run)) - 1) for index, net in enumerate(upper[:-1]): y = max_y - (len(upper) - 2 - index) * pitch shifts[net.net_id].append(_Shift(drop + index * pitch, y)) # The outermost eastbound track traverses above the north obstacle. Pick a # final shelf that can reach its destination with an exact lattice S-bend. first_top = ceil(last_upper[3] + margin + 0.1) top_lanes = [first_top + i * pitch for i in range(len(ascending))] offsets = tuple(exact_sbend_spans(radius)) shelf_options = [ int(shelf.target.y) + offset for offset in offsets if search.allows_sbend_offset(-offset) and top_lanes[-1] + pitch <= shelf.target.y + offset <= shelf_launch - 2 * radius ] if not shelf_options: raise ValueError("The north shelf has no exact S-bend to the outer eastbound target") shifts[shelf.net_id].append(_Shift(ceil(north[2] + margin + radius + 1), min(shelf_options))) side_rise = ceil(north[2] + margin + radius + pitch) for index, (net, y) in enumerate(zip(reversed(ascending), reversed(top_lanes), strict=True)): shifts[net.net_id].append(_Shift(side_rise + index * stagger, y)) tower_floor = ceil(tower[3] + margin + 1) tower_lanes = [tower_floor + i * pitch for i in range(len(above_tower))] middle_y = shifts[middle.net_id][-1].y middle_rise = side_rise + (len(ascending) - 1) * stagger middle_floor = tower_lanes[-1] + pitch if tower_lanes else tower_floor if middle_y < middle_floor: shift = next((d for d in offsets if search.allows_sbend_offset(d) and middle_y + d >= middle_floor), None) if shift is None: raise ValueError("The middle track cannot rise above the tower with a lattice S-bend") shifts[middle.net_id].append(_Shift(middle_rise, middle_y + shift, sbend=True)) middle_rise += isqrt(shift * (4 * radius - shift)) lower_rise = max(ceil(south[2] + margin + radius + 1), middle_rise) for index, (net, y) in enumerate(zip(reversed(above_tower), reversed(tower_lanes), strict=True)): shifts[net.net_id].append(_Shift(lower_rise + index * stagger, y)) lower_drop = ceil(tower[2] + margin + radius + 1) highest_lane = floor(last_lower[1] - margin - 1) lower_lanes = [] for net in reversed(above_tower): target_y = int(net.target.y) y = highest_lane # Align with the target if it fits below the barrier, or leave # two radii for the quarter turns on the final rise. if 0 < abs(target_y - y) < 2 * radius: y = target_y if target_y < y else target_y - 2 * radius if y < floor_lane + bottom_capacity * pitch: raise ValueError("The bottom lanes cannot leave room for the final turns") lower_lanes.append(y) highest_lane = y - pitch for index, (net, y) in enumerate(zip(above_tower, reversed(lower_lanes), strict=True)): shifts[net.net_id].append(_Shift(lower_drop + index * stagger, y)) shifts[middle.net_id].append(_Shift(lower_drop + len(above_tower) * stagger, int(middle.target.y))) finish = ceil(last_lower[2] + margin + radius + 1) for group in (reversed(lower), iter(ascending)): for index, net in enumerate(group): shifts[net.net_id].append(_Shift(finish + index * stagger, int(net.target.y))) shifts[shelf.net_id].append(_Shift(finish + len(ascending) * stagger, int(shelf.target.y), sbend=True)) return shifts, launch def plan_ordered_bundle(problem: RoutingProblem, search: SearchOptions, *, infer_terminal_headings: bool) -> RoutingProblem: """Generate path seeds from an ordered bundle layout for router verification.""" if problem.initial_paths: raise ValueError("Bundle routing requires an unseeded problem") if not problem.nets: return problem _, physical_geometry = resolve_bend_geometry(search) bend = min(search.bend_radii, default=0.0) if ( not isfinite(bend) or bend <= 0 or bend != int(bend) or bend not in search.sbend_radii or physical_geometry != "arc" or search.has_applicable_sbend_outline(net.width for net in problem.nets) ): raise ValueError("Bundle routing needs a common integer radius for circular bends and S-bends") radius = int(bend) width = problem.nets[0].width if not bend_fits_width(radius, width): raise ValueError("Bundle bend radius must be at least half the net width") margin = width / 2 + problem.clearance pitch = ceil(width + problem.clearance) + 1 floor_lane = ceil(problem.bounds[1] + width / 2) if infer_terminal_headings: # The supported arrangement puts every launch to the left of its # destination and of the first barrier, so the bundle launches east. problem = _eastbound_launches(problem) layout = _identify_layout(problem, margin) shifts, launch = _assign_shifts(layout, radius, margin, pitch, floor_lane, search) seeds = {} updated_nets = [] for net in problem.nets: start = int(net.start.x), int(net.start.y) target = int(net.target.x), int(net.target.y) if net == layout.outer_return: right_turn = ceil(max(n.target.x for n in problem.nets) + radius + pitch) points = [start, (launch, start[1]), (launch, floor_lane), (right_turn, floor_lane), (right_turn, target[1]), target] else: points: list[XY] = [start] y = start[1] for shift in shifts[net.net_id]: span = abs(shift.y - y) if not span: continue advance = isqrt(span * (4 * radius - span)) if shift.sbend else 0 points.extend(((shift.x, y), (shift.x + advance, shift.y))) y = shift.y points.append(target) seed, arrival = compile_waypoints(tuple(points), net.start, radius) if not infer_terminal_headings and arrival.r != net.target.r: raise ValueError(f"Bundle routing needs arrival heading {arrival.r} for {net.net_id}. Enable point-terminal inference to allow it.") seeds[net.net_id] = seed updated_nets.append(replace(net, target=arrival)) return replace(problem, nets=tuple(updated_nets), initial_paths=seeds)