Improve automatic routing retries and reuse component geometry
Try verified perimeter construction early and reuse probe routes as movable hints during lookahead. Batch collision checks and cache component generation for repeated placement and refinement candidates.
This commit is contained in:
parent
9e41c1abf8
commit
ed52ea6ffd
8 changed files with 160 additions and 55 deletions
|
|
@ -4,7 +4,9 @@ from dataclasses import dataclass, replace
|
|||
from typing import TYPE_CHECKING
|
||||
|
||||
import numpy
|
||||
from shapely.geometry import LineString, box
|
||||
from shapely import bounds as geometry_bounds
|
||||
from shapely import box, distance
|
||||
from shapely.geometry import LineString
|
||||
|
||||
from inire.constants import TOLERANCE_LINEAR
|
||||
from inire.geometry.component_overlap import count_path_self_collisions
|
||||
|
|
@ -705,35 +707,44 @@ class RoutingWorld:
|
|||
frozen_net_ids=frozen_net_ids,
|
||||
)
|
||||
|
||||
def _count_static_path_collisions(self, components: Sequence[ComponentResult]) -> int:
|
||||
static_obstacles = self._static_obstacles
|
||||
self._ensure_static_raw_tree()
|
||||
tree = static_obstacles.raw_tree
|
||||
if tree is None:
|
||||
return 0
|
||||
clearance = self.clearance
|
||||
polygons = [polygon for component in components for polygon in component.physical_geometry]
|
||||
if clearance > 0 and 4 <= len(polygons) <= 64:
|
||||
# Use padded bounds for the broad phase, then measure the physical
|
||||
# polygons. Keepouts and fixed routes use the same positive clearance.
|
||||
# Stream longer paths below to bound the number of retained pairs.
|
||||
shapes = numpy.asarray(polygons, dtype=object)
|
||||
queries = box(*(geometry_bounds(shapes) + (-clearance, -clearance, clearance, clearance)).T)
|
||||
left, right = tree.query(queries)
|
||||
if not len(left):
|
||||
return 0
|
||||
return int(numpy.count_nonzero(distance(shapes[left], tree.geometries[right]) < _clearance_limit(clearance)))
|
||||
|
||||
count = 0
|
||||
for polygon in polygons:
|
||||
query = polygon
|
||||
if clearance > 0:
|
||||
x0, y0, x1, y1 = polygon.bounds
|
||||
query = box(x0 - clearance, y0 - clearance, x1 + clearance, y1 + clearance)
|
||||
for hit in tree.query(query):
|
||||
violates = _violates_net_clearance if static_obstacles.raw_owners[hit] is not None else _violates_clearance
|
||||
count += violates(polygon, tree.geometries[hit], clearance)
|
||||
return count
|
||||
|
||||
def verify_path_geometry(self, components: Sequence[ComponentResult]) -> RoutingReport:
|
||||
"""Check polygon validity, self-spacing, the board, and static obstacles."""
|
||||
static_collision_count = 0
|
||||
total_length = sum(component.length for component in components)
|
||||
if any(not component.physical_geometry_valid for component in components):
|
||||
return RoutingReport(total_length=total_length, invalid_geometry=True)
|
||||
|
||||
static_obstacles = self._static_obstacles
|
||||
self._ensure_static_raw_tree()
|
||||
if static_obstacles.raw_tree is not None:
|
||||
raw_geometries = static_obstacles.raw_tree.geometries
|
||||
for component in components:
|
||||
for polygon in component.physical_geometry:
|
||||
query = polygon
|
||||
if self.clearance > 0:
|
||||
x0, y0, x1, y1 = polygon.bounds
|
||||
margin = self.clearance
|
||||
query = box(x0 - margin, y0 - margin, x1 + margin, y1 + margin)
|
||||
hits = static_obstacles.raw_tree.query(query)
|
||||
for hit_idx in hits:
|
||||
obstacle = raw_geometries[hit_idx]
|
||||
# Padded bounds only screen candidates. Use the physical
|
||||
# polygons for clearance and zero-clearance contact rules.
|
||||
violates = _violates_net_clearance if static_obstacles.raw_owners[hit_idx] is not None else _violates_clearance
|
||||
if violates(polygon, obstacle, self.clearance):
|
||||
static_collision_count += 1
|
||||
|
||||
return RoutingReport(
|
||||
static_collision_count=static_collision_count,
|
||||
static_collision_count=self._count_static_path_collisions(components),
|
||||
self_collision_count=count_path_self_collisions(components, self.self_clearance),
|
||||
total_length=total_length,
|
||||
out_of_bounds=self._board is not None and not all(self.board_covers_component(component) for component in components),
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ from __future__ import annotations
|
|||
from itertools import accumulate, combinations
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from shapely.geometry import box
|
||||
from shapely import box
|
||||
from shapely.strtree import STRtree
|
||||
|
||||
from inire.constants import TOLERANCE_LINEAR
|
||||
|
|
@ -125,7 +125,12 @@ def count_path_self_collisions(components: Sequence[ComponentResult], clearance:
|
|||
x0, y0, x1, y1 = components[i].total_physical_bounds
|
||||
return box(x0 - clearance, y0 - clearance, x1 + clearance, y1 + clearance)
|
||||
|
||||
pairs = ((i, other) for i in range(len(components)) for other in index.query(envelope_with_clearance(i)) if other > i)
|
||||
if len(components) <= 64:
|
||||
queries = [envelope_with_clearance(i) for i in range(len(components))] if clearance else envelopes
|
||||
left, right = index.query(queries)
|
||||
pairs = ((i, other) for i, other in zip(left, right, strict=True) if other > i)
|
||||
else:
|
||||
pairs = ((i, other) for i in range(len(components)) for other in index.query(envelope_with_clearance(i)) if other > i)
|
||||
return internal_collisions + sum(
|
||||
components_overlap(components[i], components[other], prefer_actual=True, at_join=other == i + 1, clearance=spacing(i, other))
|
||||
for i, other in pairs
|
||||
|
|
|
|||
|
|
@ -44,6 +44,7 @@ from inire.router._seed_materialization import materialize_path_seed, seed_prepa
|
|||
from inire.router._stack import RoutingAttempts
|
||||
from inire.router._topology import constrained_triangulation_available, plan_corridors
|
||||
from inire.router.cost import build_native_cost_evaluator, weighted_path_length
|
||||
from inire.router.refiner import PathRefiner
|
||||
from inire.seeds import SBendSeed
|
||||
|
||||
if TYPE_CHECKING:
|
||||
|
|
@ -370,10 +371,10 @@ class _AutomaticRun:
|
|||
return
|
||||
trials[-1] = replace(trial, selection="incomplete-layout")
|
||||
|
||||
def _perimeter_trials(self, options: RoutingOptions) -> list[Trial]:
|
||||
def _perimeter_trials(self, options: RoutingOptions, *, try_pair: bool = True) -> list[Trial]:
|
||||
problem = self.problem
|
||||
trials = []
|
||||
if len(problem.nets) == 2:
|
||||
if try_pair and len(problem.nets) == 2:
|
||||
with self._time("plan", planner="paired-perimeter"):
|
||||
self._paired_perimeter(trials)
|
||||
if trials and len(trials[-1].valid_costs) == len(problem.nets):
|
||||
|
|
@ -486,17 +487,51 @@ class _AutomaticRun:
|
|||
return trial
|
||||
return None
|
||||
|
||||
def _direct(self, options: RoutingOptions, policy: str) -> list[Trial]:
|
||||
def _direct(self, options: RoutingOptions, policy: str, *, hints: dict[str, PathSeed] | None = None) -> list[Trial]:
|
||||
def run(problem: RoutingProblem, *, options: RoutingOptions) -> RoutingRunResult:
|
||||
if hints:
|
||||
# Add internal hints after direct locks are chosen so search can move them.
|
||||
active_hints = {net.net_id: hints[net.net_id] for net in problem.nets if net.net_id in hints}
|
||||
if active_hints:
|
||||
problem = replace(problem, initial_paths={**active_hints, **problem.initial_paths})
|
||||
options = replace(options, congestion=replace(options.congestion, warm_start_enabled=False))
|
||||
return self._run(problem, options=options, policy=policy)
|
||||
|
||||
with self._time("plan", planner="direct", policy=policy):
|
||||
return _direct_trials(
|
||||
self.problem,
|
||||
self.board,
|
||||
options,
|
||||
policy,
|
||||
run_route=partial(self._run, policy=policy),
|
||||
run_route=run,
|
||||
check_trial=self._trial,
|
||||
)
|
||||
|
||||
def _try_hinted_lookahead(self, options: RoutingOptions, trials: list[Trial], incumbent: Trial, target: int) -> bool:
|
||||
if (
|
||||
self.problem.initial_paths or target != len(self.problem.nets)
|
||||
or not 2 <= len(incumbent.valid_costs) < target - 1
|
||||
or options.search.node_limit <= _NEAR_PORT_NODE_LIMIT
|
||||
or options.congestion.max_iterations <= 1 or options.congestion.shuffle_nets or not options.congestion.warm_start_enabled
|
||||
):
|
||||
return False
|
||||
retained = [incumbent.run.results_by_net[net_id] for net_id in incumbent.valid_costs]
|
||||
if all(len(result.path) == 1 and result.path[0].move_type == "straight" for result in retained):
|
||||
return False
|
||||
|
||||
hints = {result.net_id: result.as_seed() for result in retained}
|
||||
attempts = self._direct(options, "direct-lookahead-hinted", hints=hints)
|
||||
best = _best_trial(attempts)
|
||||
if len(incumbent.valid_costs) < len(best.valid_costs) < target:
|
||||
seeded = replace(options, topology=replace(options.topology, mode="seed"))
|
||||
attempts.extend(self._incumbent_trials(seeded, best, target))
|
||||
if len(_best_trial(attempts).valid_costs) >= target:
|
||||
trials.extend(attempts)
|
||||
return True
|
||||
# The ordinary retry starts from its original incumbents if hints fall short.
|
||||
trials.extend(replace(trial, selection="incomplete-layout") for trial in attempts)
|
||||
return False
|
||||
|
||||
def _early_guide(self, options: RoutingOptions) -> Trial | None:
|
||||
problem = self.problem
|
||||
if (
|
||||
|
|
@ -594,6 +629,27 @@ class _AutomaticRun:
|
|||
if self._try_column_recovery(options, trials, groups):
|
||||
return True
|
||||
groups = ()
|
||||
max_shift = 2 * max(options.search.sbend_radii, default=0)
|
||||
early_perimeter = (
|
||||
try_construction_early and target == len(problem.nets) <= 2 and not problem.initial_paths
|
||||
and options.search.node_limit > 1 and options.search.bend_radii and problem._blocking_polygons
|
||||
and all(net.start.r == net.target.r == 0 and not _is_short_shift(net, max_shift) for net in problem.nets)
|
||||
and (target == 2 or problem.nets[0].start.x > problem.nets[0].target.x)
|
||||
)
|
||||
if early_perimeter:
|
||||
# For a small, fixed-heading layout, try verified construction
|
||||
# before searching. Defer the perimeter's residual A* to its usual turn.
|
||||
with self._time("plan", planner="perimeter"):
|
||||
perimeter = []
|
||||
if target == 2:
|
||||
with self._time("plan", planner="paired-perimeter"):
|
||||
self._paired_perimeter(perimeter)
|
||||
else:
|
||||
perimeter = self._perimeter_trials(options)
|
||||
trials.extend(perimeter)
|
||||
if perimeter and len(perimeter[-1].valid_costs) == target:
|
||||
return True
|
||||
|
||||
probe_iterations = options.congestion.max_iterations
|
||||
proxy, _ = resolve_bend_geometry(options.search)
|
||||
# Clipped proxies can find cheaper routes in later probe iterations than in the wider retry.
|
||||
|
|
@ -618,9 +674,9 @@ class _AutomaticRun:
|
|||
trials.append(construction)
|
||||
return True
|
||||
|
||||
if len(problem.nets) <= 2:
|
||||
if len(problem.nets) <= 2 and (not early_perimeter or target == 2):
|
||||
with self._time("plan", planner="perimeter"):
|
||||
trials.extend(self._perimeter_trials(options))
|
||||
trials.extend(self._perimeter_trials(options, try_pair=not early_perimeter))
|
||||
if len(_best_trial(trials).valid_costs) >= target:
|
||||
return True
|
||||
|
||||
|
|
@ -630,6 +686,8 @@ class _AutomaticRun:
|
|||
# Every short shift has lateral displacement, so the direct retry cannot lock
|
||||
# any straight paths. It would run the same guide with the same budget.
|
||||
if early is None or early.run.metrics.timeout_events:
|
||||
if self._try_hinted_lookahead(options, trials, _best_trial(probe), target):
|
||||
return True
|
||||
trials.extend(self._direct(options, "direct-lookahead-retry"))
|
||||
return len(_best_trial(trials).valid_costs) >= target
|
||||
|
||||
|
|
@ -695,7 +753,9 @@ class _AutomaticRun:
|
|||
|
||||
def _refine(self, trials: list[Trial]) -> Trial | None:
|
||||
best = _best_trial(trials)
|
||||
if not self.options.refinement.enabled or not best.valid_costs:
|
||||
if not self.options.refinement.enabled or not any(
|
||||
PathRefiner.has_refinement_bends(best.run.results_by_net[net_id].path) for net_id in best.valid_costs
|
||||
):
|
||||
return None
|
||||
has_unresolved_paths = any(result.path and not result.is_valid for result in best.run.results_by_net.values())
|
||||
run, stage = self._seeded_attempt(
|
||||
|
|
|
|||
|
|
@ -10,8 +10,8 @@ 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 shapely import linestrings, total_bounds
|
||||
from shapely.geometry import box
|
||||
|
||||
from inire.geometry.components import bend90_uses_circular_geometry, bend_fits_width
|
||||
from inire.geometry.intervals import Gap, open_intervals
|
||||
|
|
@ -23,7 +23,7 @@ from inire.seeds import PathSeed, SBendSeed, StraightSeed
|
|||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable, Iterator, Mapping
|
||||
|
||||
from shapely.geometry import Polygon
|
||||
from shapely.geometry import LineString, Polygon
|
||||
|
||||
from inire.geometry.primitives import Port
|
||||
from inire.model import NetSpec, RoutingProblem, SearchOptions
|
||||
|
|
@ -394,23 +394,26 @@ def _bend_sequences(
|
|||
return choose
|
||||
|
||||
|
||||
@lru_cache(maxsize=256)
|
||||
def _arc_samples(radius: int, shift: int) -> tuple[tuple[float, float], ...]:
|
||||
theta = acos(1 - abs(shift) / (2 * radius))
|
||||
signed_radius = radius if shift > 0 else -radius
|
||||
angles = (theta * i / 12 for i in range(13))
|
||||
return tuple((radius * sin(angle), signed_radius * (1 - cos(angle))) for angle in angles)
|
||||
|
||||
|
||||
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
|
||||
samples = _arc_samples(radius, shift)
|
||||
points.extend((x + dx, y + dy) for dx, dy in samples[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.extend((x - dx, y - dy) for dx, dy in reversed(samples[:-1]))
|
||||
points.append((window, y))
|
||||
return LineString(points)
|
||||
return linestrings(points)
|
||||
|
||||
|
||||
def _schedules(
|
||||
|
|
|
|||
|
|
@ -25,6 +25,7 @@ if TYPE_CHECKING:
|
|||
from shapely.geometry.base import BaseGeometry
|
||||
|
||||
from inire.geometry.components import ComponentResult, MoveKind
|
||||
from inire.geometry.primitives import Port
|
||||
from inire.model import NetSpec, RoutingProblem, SearchOptions
|
||||
from inire.router._routing_policy import Scorer
|
||||
from inire.seeds import PathSegmentSeed
|
||||
|
|
@ -148,8 +149,12 @@ def _verified_candidates(
|
|||
seeds: Iterable[PathSeed],
|
||||
) -> Iterator[tuple[PathSeed, BaseGeometry, tuple[ComponentResult, ...]]]:
|
||||
bounds = board.bounds
|
||||
component_cache: dict[tuple[Port, PathSegmentSeed], ComponentResult] = {}
|
||||
for seed in seeds:
|
||||
path = materialize_path_seed(seed, start=net.start, net_width=net.width, search=search, clearance=world.clearance, bounds=bounds)
|
||||
path = materialize_path_seed(
|
||||
seed, start=net.start, net_width=net.width, search=search, clearance=world.clearance, bounds=bounds,
|
||||
component_cache=component_cache,
|
||||
)
|
||||
if not path or path[-1].end_port != net.target or not world.verify_path_report(net.net_id, path).is_valid:
|
||||
continue
|
||||
footprint = union_all([polygon for component in path for polygon in component.physical_geometry])
|
||||
|
|
|
|||
|
|
@ -54,7 +54,9 @@ def materialize_path_seed(
|
|||
clearance: float,
|
||||
bounds: tuple[float, float, float, float] | None = None,
|
||||
diagnostic: bool = False,
|
||||
component_cache: dict[tuple[Port, PathSegmentSeed], ComponentResult] | None = None,
|
||||
) -> tuple[ComponentResult, ...] | None:
|
||||
"""Materialize a seed, optionally reusing moves with the same geometry settings."""
|
||||
if diagnostic:
|
||||
error = seed_preparation_error(seed, start=start, net_width=net_width, search=search, clearance=clearance)
|
||||
if error is not None:
|
||||
|
|
@ -67,6 +69,13 @@ def materialize_path_seed(
|
|||
bend_clip_margin = search.bend_clip_margin
|
||||
|
||||
for index, segment in enumerate(seed.segments, start=1):
|
||||
if component_cache is not None:
|
||||
key = (current, segment)
|
||||
cached = component_cache.get(key)
|
||||
if cached is not None:
|
||||
path.append(cached)
|
||||
current = cached.end_port
|
||||
continue
|
||||
kind, parameters = seed_move(segment)
|
||||
try:
|
||||
template = search.sbend_template(segment.offset, segment.radius, net_width) if isinstance(segment, SBendSeed) else None
|
||||
|
|
@ -87,6 +96,8 @@ def materialize_path_seed(
|
|||
if diagnostic:
|
||||
raise SeedMaterializationError(f"segment {index} ({type(segment).__name__}) {exc}") from exc
|
||||
return None
|
||||
if component_cache is not None and len(component_cache) < 256:
|
||||
component_cache[key] = component
|
||||
path.append(component)
|
||||
current = component.end_port
|
||||
return tuple(path)
|
||||
|
|
|
|||
|
|
@ -262,7 +262,10 @@ class PathRefiner:
|
|||
moves.append(_DoglegMove(curr, length, "straight"))
|
||||
return moves if curr == target else None
|
||||
|
||||
def _build_dogleg(self, start: Port, width: float, radius: float, moves: list[_DoglegMove]) -> list[ComponentResult]:
|
||||
def _build_dogleg(
|
||||
self, start: Port, width: float, radius: float, moves: list[_DoglegMove],
|
||||
components: dict[tuple[Port, MoveKind, tuple], ComponentResult],
|
||||
) -> list[ComponentResult]:
|
||||
search = self.context.options.search
|
||||
proxy, physical = resolve_bend_geometry(search)
|
||||
dilation = self.collision_engine.clearance / 2.0
|
||||
|
|
@ -272,11 +275,16 @@ class PathRefiner:
|
|||
bounds = None if board is None else board.bounds
|
||||
for move in moves:
|
||||
parameters = (move.length,) if move.direction is None else (radius, move.direction)
|
||||
component = build_component(
|
||||
port, width, move.move_type, parameters,
|
||||
collision_type=proxy, physical_geometry_type=physical, clip_margin=search.bend_clip_margin, dilation=dilation,
|
||||
physical_length=search.bend_physical_length if move.move_type == "bend90" else None, bounds=bounds,
|
||||
)
|
||||
key = (port, move.move_type, parameters)
|
||||
component = components.get(key)
|
||||
if component is None:
|
||||
component = build_component(
|
||||
port, width, move.move_type, parameters,
|
||||
collision_type=proxy, physical_geometry_type=physical, clip_margin=search.bend_clip_margin, dilation=dilation,
|
||||
physical_length=search.bend_physical_length if move.move_type == "bend90" else None, bounds=bounds,
|
||||
)
|
||||
if len(components) < 256:
|
||||
components[key] = component
|
||||
path.append(component)
|
||||
port = component.end_port
|
||||
return path
|
||||
|
|
@ -367,11 +375,12 @@ class PathRefiner:
|
|||
proxy, physical = resolve_bend_geometry(search)
|
||||
circular_bend = bend90_uses_circular_geometry(proxy, physical)
|
||||
custom_danger_map = self.context.cost_evaluator.danger_map if isinstance(physical, Polygon) else None
|
||||
components: dict[tuple[Port, MoveKind, tuple], ComponentResult] = {}
|
||||
for radius in search.bend_radii:
|
||||
if circular_bend and not bend_fits_width(radius, net_width):
|
||||
continue
|
||||
side_extents = self._candidate_side_extents(window_start, window_end, window_path, net_width, radius)
|
||||
for side_extent in side_extents:
|
||||
for side_extent in dict.fromkeys(map(round, side_extents)):
|
||||
moves = self._dogleg_moves(window_start, window_end, radius, side_extent)
|
||||
if moves is None:
|
||||
continue
|
||||
|
|
@ -383,7 +392,7 @@ class PathRefiner:
|
|||
if not outside and not self.score_path(scoring_start, [*prefix, *moves, *suffix]) + 1e-6 < best_candidate_cost:
|
||||
continue
|
||||
try:
|
||||
replacement = self._build_dogleg(window_start, net_width, radius, moves)
|
||||
replacement = self._build_dogleg(window_start, net_width, radius, moves, components)
|
||||
except (ComponentPreparationError, OverflowError):
|
||||
continue
|
||||
self.context.metrics.total_refinement_candidates_built += 1
|
||||
|
|
|
|||
|
|
@ -31,6 +31,7 @@ if TYPE_CHECKING:
|
|||
from inire.model import RoutingOptions, RoutingProblem
|
||||
from inire.results import RoutingResult
|
||||
from inire.router._routing_policy import Trial
|
||||
from inire.seeds import PathSeed
|
||||
from inire.tests.routing_benchmark_case import BenchmarkCase
|
||||
|
||||
|
||||
|
|
@ -85,14 +86,14 @@ class _RetryExperiment(_AutomaticRun):
|
|||
options = replace(self.options, refinement=replace(self.options.refinement, enabled=False))
|
||||
trials.extend(self._widen_residual(options, retained, limit, target, policy="late-bounded-residual", check_connectivity=True))
|
||||
|
||||
def _direct(self, options: RoutingOptions, policy: str) -> list[Trial]:
|
||||
def _direct(self, options: RoutingOptions, policy: str, *, hints: dict[str, PathSeed] | None = None) -> list[Trial]:
|
||||
cap = self.retry_policy.probe_iterations
|
||||
if policy == "direct-probe-near-port" and cap is not None:
|
||||
configured = self.options.congestion.max_iterations
|
||||
iterations = configured if cap == "configured" else min(configured, cap)
|
||||
if iterations != options.congestion.max_iterations:
|
||||
options = replace(options, congestion=replace(options.congestion, max_iterations=iterations))
|
||||
return super()._direct(options, policy)
|
||||
return super()._direct(options, policy, hints=hints)
|
||||
|
||||
def _seed_recovery_trials(self, options: RoutingOptions, trials: list[Trial], target: int) -> None:
|
||||
limit = self.retry_policy.lattice_limit
|
||||
|
|
|
|||
Loading…
Reference in a new issue