"""Geometric upper bounds on automatic routing coverage.""" from __future__ import annotations from bisect import bisect_left, bisect_right from itertools import pairwise from math import floor, isfinite from typing import TYPE_CHECKING from shapely.geometry import box from shapely.strtree import STRtree from inire.constants import TOLERANCE_LINEAR from inire.geometry.collision import _clearance_limit from inire.geometry.intervals import open_intervals from inire.model import resolve_bend_geometry from inire.results import CapacityLimit if TYPE_CHECKING: from inire.geometry.intervals import Gap from inire.model import RoutingOptions, RoutingProblem def _rectangular_obstacle_bounds(problem: RoutingProblem) -> tuple[tuple[float, float, float, float], ...] | None: polygons = problem._blocking_polygons bounds = tuple(tuple(shape.bounds) for shape in polygons) if any(shape.is_empty or not shape.equals(box(*extent)) for shape, extent in zip(polygons, bounds, strict=True)): return None return bounds def cut_capacity(problem: RoutingProblem, options: RoutingOptions) -> CapacityLimit | None: """Bound routes across vertical cuts through truly rectangular obstacles.""" _, physical_geometry = resolve_bend_geometry(options.search) if physical_geometry != "arc" or not problem.nets: return None obstacles = _rectangular_obstacle_bounds(problem) if not obstacles: return None # The narrowest guide gives an optimistic upper bound for mixed widths. width = min(net.width for net in problem.nets) if not isfinite(width) or width <= 0 or problem.clearance < 0: return None clearance = problem.clearance half_width = width / 2 pitch = max(TOLERANCE_LINEAR, width + clearance - TOLERANCE_LINEAR) ymin, ymax = problem.bounds[1], problem.bounds[3] net_intervals = [] for net in problem.nets: left = min(net.start.x, net.target.x) + half_width right = max(net.start.x, net.target.x) - half_width if left < right: net_intervals.append((left, right)) net_starts = sorted(left for left, _ in net_intervals) net_ends = sorted(right for _, right in net_intervals) starts = sorted((left, index, (bottom, top)) for index, (left, bottom, _, top) in enumerate(obstacles)) ends = sorted((right, index) for index, (_, _, right, _) in enumerate(obstacles)) edges = sorted({left for left, _, _ in starts} | {right for right, _ in ends}) active: dict[int, Gap] = {} start = end = 0 limit = None for left, right in pairwise(edges): x = (left + right) / 2 # Match the strict containment test at each cut, including a midpoint rounded to an edge. while start < len(starts) and starts[start][0] < x: _, index, span = starts[start] active[index] = span start += 1 while end < len(ends) and ends[end][0] <= x: _, index = ends[end] active.pop(index, None) end += 1 if not active: continue crossing = bisect_left(net_starts, x) - bisect_right(net_ends, x) if not crossing: continue tracks = 0 for low, high in open_intervals(active.values(), ymin, ymax): bottom = low + half_width + (clearance if low != ymin else 0) top = high - half_width - (clearance if high != ymax else 0) room = top - bottom + 2 * TOLERANCE_LINEAR if room >= 0: tracks += 1 + floor(room / pitch) max_routed = len(problem.nets) - crossing + tracks if tracks < crossing and (limit is None or max_routed < limit.max_routed): limit = CapacityLimit(x, crossing, tracks, max_routed) return limit def port_conflicts(problem: RoutingProblem, options: RoutingOptions) -> tuple[tuple[str, str], ...]: """Find disjoint fixed-heading terminal pairs with insufficient optical clearance.""" _, physical_geometry = resolve_bend_geometry(options.search) if physical_geometry != "arc": return () aligned: dict[tuple[int, int], list[tuple[str, float, float]]] = {} for net in problem.nets: half_width = net.width / 2 for port in (net.start, net.target): axis = port.r % 180 longitudinal, lateral = (port.x, port.y) if axis == 0 else (port.y, port.x) aligned.setdefault((axis, longitudinal), []).append((net.net_id, lateral - half_width, lateral + half_width)) # Each disjoint conflict pair forces at least one route to be omitted. # A terminal's physical cross-section is fixed by its heading and width. pairs = [] matched = set() for bank in aligned.values(): ports = [port for port in bank if port[0] not in matched] if len(ports) < 2: continue pairs.extend(_match_bank(ports, problem.clearance, matched)) return tuple(pairs) def _match_bank(ports: list[tuple[str, float, float]], clearance: float, matched: set[str]) -> list[tuple[str, str]]: separation = _clearance_limit(clearance) padding = separation / 2 spans = [box(low - padding, 0, high + padding, 1) for _, low, high in ports] index = STRtree(spans) def conflicts(i: int, j: int) -> bool: a, low_a, high_a = ports[i] b, low_b, high_b = ports[j] if a == b or b in matched: return False gap = max(low_a, low_b) - min(high_a, high_b) # Distinct conductors cannot share a point even at zero clearance. return gap < separation if clearance else gap <= 0 pairs = [] for i, (a, _, _) in enumerate(ports): if a in matched: continue # Dense banks usually match consecutive terminals in input order. j = i + 1 if i + 1 < len(ports) and conflicts(i, i + 1) else min( (j for j in index.query(spans[i]) if j > i and conflicts(i, j)), default=None, ) if j is None: continue b = ports[j][0] pairs.append((a, b)) matched.update((a, b)) return pairs