inire/inire/router/_router.py

1164 lines
49 KiB
Python

from __future__ import annotations
import random
import time
from contextlib import contextmanager, nullcontext
from dataclasses import dataclass, field
from typing import TYPE_CHECKING
from inire.model import resolve_bend_geometry
from inire.results import (
ConflictTraceEntry,
FrontierPruneSample,
IterationNetAttemptTrace,
IterationTraceEntry,
NetFrontierTrace,
PrePairFrontierTraceEntry,
PrePairNetTrace,
RoutingReport,
RoutingResult,
TopologyReport,
)
from inire.router._astar_types import AStarContext, AStarMetrics, FrontierTraceCollector, SearchRunConfig
from inire.router._congestion_policy import (
IterationReview as _IterationReview,
all_results_reached_target,
next_reroute_net_ids,
ordered_nets,
reached_pair_local_plateau,
repeated_conflict_count,
reroute_plan,
review_verified_results,
)
from inire.router._pair_local import search_pair_candidate
from inire.router._route_traces import conflict_trace_entry, iteration_trace_entry, net_attempt_trace
from inire.router._search import incumbent_guidance, route_astar
from inire.router._seed_materialization import materialize_path_seed
from inire.router.refiner import PathRefiner
if TYPE_CHECKING:
from collections.abc import Callable, Iterator, Sequence
from contextlib import AbstractContextManager
from shapely.geometry import Polygon
from inire.geometry.collision import PathVerificationDetail
from inire.geometry.components import ComponentResult
from inire.model import NetSpec
from inire.results import ConflictTraceStage, RoutingOperation
from inire.router._topology import Corridor
PhaseTimer = Callable[[RoutingOperation], AbstractContextManager[None]]
@dataclass(slots=True)
class _RoutingState:
net_specs: dict[str, NetSpec]
ordered_net_ids: list[str]
results: dict[str, RoutingResult]
needs_self_collision_check: set[str]
start_time: float
timeout_s: float
initial_paths: dict[str, tuple[ComponentResult, ...]] | None
accumulated_expanded_nodes: list[tuple[int, int, int]]
best_results: dict[str, RoutingResult]
best_is_installed: bool
best_review: _IterationReview | None
last_conflict_edge_count: int
repeated_conflict_count: int
recent_attempt_work: dict[str, int]
pre_pair_candidate: _PrePairCandidate | None
corridors: dict[str, tuple[Corridor, ...]] = field(default_factory=dict)
@property
def best_conflict_edges(self) -> int | None:
return len(self.best_review.conflict_edges) if self.best_review is not None else None
@dataclass(frozen=True, slots=True)
class _PairLocalTarget:
net_ids: tuple[str, str]
@dataclass(frozen=True, slots=True)
class _PrePairCandidate:
iteration: int
routed_net_ids: tuple[str, ...]
conflict_edges: tuple[tuple[str, str], ...]
net_attempts: tuple[IterationNetAttemptTrace, ...]
_ITERATION_TRACE_TOTALS = (
"nodes_expanded",
"congestion_check_calls",
"congestion_candidate_ids",
"congestion_exact_pair_checks",
)
_ATTEMPT_TRACE_TOTALS = (
"nodes_expanded",
"congestion_check_calls",
"pruned_closed_set",
"pruned_cost",
"pruned_hard_collision",
)
class PathFinder:
__slots__ = (
"context",
"metrics",
"refiner",
"accumulated_expanded_nodes",
"conflict_trace",
"frontier_trace",
"pre_pair_frontier_trace",
"iteration_trace",
"topology_report",
)
def __init__(
self,
context: AStarContext,
metrics: AStarMetrics | None = None,
) -> None:
self.context = context
self.metrics = self.context.metrics if metrics is None else metrics
self.context.metrics = self.metrics
self.context.cost_evaluator.collision_engine.metrics = self.metrics
if self.context.cost_evaluator.danger_map is not None:
self.context.cost_evaluator.danger_map.metrics = self.metrics
self.refiner = PathRefiner(self.context)
self.accumulated_expanded_nodes: list[tuple[int, int, int]] = []
self.conflict_trace: list[ConflictTraceEntry] = []
self.frontier_trace: list[NetFrontierTrace] = []
self.pre_pair_frontier_trace: PrePairFrontierTraceEntry | None = None
self.iteration_trace: list[IterationTraceEntry] = []
self.topology_report: TopologyReport | None = None
def _metric_total(self, metric_name: str) -> int:
return int(getattr(self.metrics, f"total_{metric_name}"))
def _capture_metric_totals(self, metric_names: tuple[str, ...]) -> dict[str, int]:
return {metric_name: self._metric_total(metric_name) for metric_name in metric_names}
def _metric_deltas(self, before: dict[str, int], after: dict[str, int]) -> dict[str, int]:
return {metric_name: after[metric_name] - before[metric_name] for metric_name in before}
def _has_incumbent_fallback(self, result: RoutingResult | None) -> bool:
return bool(result and result.reached_target and result.path)
def _restore_incumbent_fallback(
self,
net_id: str,
result: RoutingResult,
guidance_seed_present: bool,
) -> tuple[RoutingResult, bool]:
self.metrics.total_late_phase_capped_fallbacks += 1
self._install_path(net_id, result.path)
return result, guidance_seed_present
def _install_path(self, net_id: str, path: Sequence[ComponentResult]) -> None:
all_geoms: list[Polygon] = []
all_dilated: list[Polygon] = []
component_indexes: list[int] = []
for component_index, result in enumerate(path):
all_geoms.extend(result.collision_geometry)
all_dilated.extend(result.dilated_collision_geometry)
component_indexes.extend([component_index] * len(result.collision_geometry))
self.context.cost_evaluator.collision_engine.add_path(
net_id,
all_geoms,
dilated_geometry=all_dilated,
component_indexes=component_indexes,
)
@contextmanager
def _temporary_path_reservations(self) -> Iterator[Callable[[Sequence[ComponentResult]], None]]:
world = self.context.cost_evaluator.collision_engine
temporary: list[int] = []
def reserve(path: Sequence[ComponentResult]) -> None:
for component in path:
for shape in component.physical_geometry:
temporary.append(world.add_static_obstacle(shape))
try:
yield reserve
finally:
for obstacle in temporary:
world.remove_static_obstacle(obstacle)
self.context.clear_static_caches()
def _build_greedy_warm_start_paths(
self,
state: _RoutingState,
) -> dict[str, tuple[ComponentResult, ...]]:
greedy_paths: dict[str, tuple[ComponentResult, ...]] = {}
greedy_node_limit = min(self.context.options.search.node_limit, 2000)
with self._temporary_path_reservations() as reserve:
for net_id in state.ordered_net_ids:
net = state.net_specs[net_id]
h_start = self.context.cost_evaluator.h_manhattan(
net.start,
net.target,
min_bend_radius=self.context.min_bend_radius,
)
max_cost_limit = max(h_start * 3.0, 2000.0)
candidates = state.corridors.get(net_id, ())
run_config = SearchRunConfig.from_options(
self.context.options,
skip_congestion=True,
max_cost=max_cost_limit,
self_collision_check=True,
node_limit=greedy_node_limit,
corridor=candidates[0] if candidates else None,
corridor_strength=self.context.options.topology.guide_strength,
)
path = route_astar(
net.start,
net.target,
net.width,
context=self.context,
metrics=self.metrics,
net_id=net_id,
config=run_config,
)
if not path:
continue
self.metrics.total_warm_start_paths_built += 1
greedy_paths[net_id] = tuple(path)
reserve(path)
self.context.clear_static_caches()
return greedy_paths
def _build_corridor_seeds(self, state: _RoutingState) -> dict[str, tuple[ComponentResult, ...]]:
topology = self.context.options.topology
world = self.context.cost_evaluator.collision_engine
existing = state.initial_paths or {}
seeds: dict[str, tuple[ComponentResult, ...]] = {}
with self._temporary_path_reservations() as reserve:
for net_id, path in existing.items():
if path and path[-1].end_port == state.net_specs[net_id].target and world.verify_path_report(net_id, path).is_valid:
reserve(path)
for net_id in state.ordered_net_ids:
if net_id in existing:
continue
net = state.net_specs[net_id]
candidates = state.corridors.get(net_id, ())
remaining = min(topology.seed_node_limit, self.context.options.search.node_limit)
for index, corridor in enumerate(candidates):
if remaining <= 0:
break
searches_left = len(candidates) - index
budget = max(1, remaining // searches_left)
if index == 0 and searches_left > 1:
budget = max(budget, (remaining + 1) // 2)
config = SearchRunConfig.from_options(
self.context.options,
node_limit=budget,
skip_congestion=True,
self_collision_check=True,
corridor=corridor,
restrict_to_corridor=True,
)
path = route_astar(net.start, net.target, net.width, self.context, metrics=self.metrics, net_id=net_id, config=config)
remaining -= self.metrics.nodes_expanded
if path and path[-1].end_port == net.target and world.verify_path_report(net_id, path).is_valid:
seeds[net_id] = tuple(path)
self.metrics.total_warm_start_paths_built += 1
reserve(path)
break
return seeds
def _prepare_topology(self, state: _RoutingState, corridors: dict[str, tuple[Corridor, ...]] | None) -> None:
topology = self.context.options.topology
if topology.mode == "bundle":
self.topology_report = TopologyReport(seeded_net_ids=tuple(self.context.problem.initial_paths))
return
if topology.mode not in ("guide", "seed"):
return
from inire.router._topology import plan_corridors # noqa: PLC0415
world = self.context.cost_evaluator.collision_engine
for net_id in state.ordered_net_ids:
world.remove_path(net_id)
if corridors is None:
corridors = plan_corridors(
self.context.problem.bounds,
world.iter_static_geometries(),
[state.net_specs[net_id] for net_id in state.ordered_net_ids],
clearance=world.clearance,
bend_radius=min(self.context.options.search.bend_radii, default=0.0),
limit=topology.max_corridors,
)
state.corridors = corridors
before = self.metrics.total_nodes_expanded
seeds = self._build_corridor_seeds(state) if topology.mode == "seed" and state.corridors else {}
if seeds:
state.initial_paths = {**(state.initial_paths or {}), **seeds}
self.topology_report = TopologyReport(
corridor_counts=tuple((net_id, len(candidates)) for net_id, candidates in state.corridors.items()),
seeded_net_ids=tuple(seeds),
seed_nodes_expanded=self.metrics.total_nodes_expanded - before,
)
def _prepare_state(self, corridors: dict[str, tuple[Corridor, ...]] | None = None) -> _RoutingState:
problem = self.context.problem
congestion = self.context.options.congestion
initial_paths = self._materialize_problem_initial_paths()
net_specs = {net.net_id: net for net in problem.nets}
num_nets = len(net_specs)
state = _RoutingState(
net_specs=net_specs,
ordered_net_ids=[net.net_id for net in ordered_nets(net_specs.values(), congestion.net_order)],
results={},
needs_self_collision_check=set(),
start_time=time.monotonic(),
timeout_s=max(60.0, 10.0 * num_nets * congestion.max_iterations),
initial_paths=initial_paths,
accumulated_expanded_nodes=[],
best_results={},
best_is_installed=False,
best_review=None,
last_conflict_edge_count=0,
repeated_conflict_count=0,
recent_attempt_work={},
pre_pair_candidate=None,
)
self._prepare_topology(state, corridors)
if state.initial_paths is None and congestion.warm_start_enabled:
state.initial_paths = self._build_greedy_warm_start_paths(state)
if state.corridors and state.initial_paths and congestion.max_iterations > 0:
world = self.context.cost_evaluator.collision_engine
for net_id, path in state.initial_paths.items():
if not path or path[-1].end_port != net_specs[net_id].target:
continue
report = world.verify_path_report(net_id, path)
if report.is_valid:
self._install_path(net_id, path)
state.results[net_id] = RoutingResult(net_id, path, reached_target=True, report=report)
return state
def _materialize_problem_initial_paths(self) -> dict[str, tuple[ComponentResult, ...]] | None:
if not self.context.problem.initial_paths:
return None
search = self.context.options.search
net_specs = {net.net_id: net for net in self.context.problem.nets}
initial_paths: dict[str, tuple[ComponentResult, ...]] = {}
for net_id, seed in self.context.problem.initial_paths.items():
if net_id not in net_specs:
raise ValueError(f"Initial path provided for unknown net: {net_id}")
net = net_specs[net_id]
initial_paths[net_id] = materialize_path_seed(
seed,
start=net.start,
net_width=net.width,
search=search,
clearance=self.context.cost_evaluator.collision_engine.clearance,
)
return initial_paths
def _replace_installed_paths(self, state: _RoutingState, results: dict[str, RoutingResult]) -> None:
for net_id in state.ordered_net_ids:
self.context.cost_evaluator.collision_engine.remove_path(net_id)
for net_id in state.ordered_net_ids:
result = results.get(net_id)
if result and result.path and (result.reached_target or not state.corridors):
self._install_path(net_id, result.path)
def _review_restored_best(self, state: _RoutingState) -> _IterationReview:
diagnostics = self.context.options.diagnostics
state.results, details_by_net, review = self._analyze_results(
state.ordered_net_ids,
state.results,
capture_component_conflicts=diagnostics.capture_conflict_trace or diagnostics.capture_pre_pair_frontier_trace,
count_iteration_metrics=False,
)
if diagnostics.capture_conflict_trace:
self._capture_conflict_trace_entry(
state,
stage="restored_best",
iteration=None,
results=state.results,
details_by_net=details_by_net,
review=review,
)
if diagnostics.capture_pre_pair_frontier_trace:
self.pre_pair_frontier_trace = self._materialize_pre_pair_frontier_trace(
state,
state.results,
details_by_net,
)
return review
def _update_best_iteration(self, state: _RoutingState, review: _IterationReview) -> bool:
if state.best_review is not None and review.rank >= state.best_review.rank:
return False
state.best_results = dict(state.results)
state.best_review = review
return True
def _restore_best_iteration(self, state: _RoutingState) -> None:
if not state.best_results:
return
state.results = dict(state.best_results)
self._replace_installed_paths(state, state.results)
def _capture_conflict_trace_entry(
self,
state: _RoutingState,
*,
stage: ConflictTraceStage,
iteration: int | None,
results: dict[str, RoutingResult],
details_by_net: dict[str, PathVerificationDetail],
review: _IterationReview,
) -> None:
if not self.context.options.diagnostics.capture_conflict_trace:
return
self.conflict_trace.append(
conflict_trace_entry(state.ordered_net_ids, results, details_by_net, review, stage=stage, iteration=iteration)
)
def _build_frontier_hotspot_bounds(
self,
state: _RoutingState,
net_id: str,
details_by_net: dict[str, PathVerificationDetail],
) -> tuple[tuple[float, float, float, float], ...]:
result = state.results.get(net_id)
detail = details_by_net.get(net_id)
if result is None or detail is None or not result.path:
return ()
hotspot_bounds: list[tuple[float, float, float, float]] = []
seen: set[tuple[float, float, float, float]] = set()
margin = max(5.0, self.context.cost_evaluator.collision_engine.clearance * 2.0)
for self_component_index, other_net_id, other_component_index in detail.component_conflicts:
other_result = state.results.get(other_net_id)
if other_result is None or not other_result.path:
continue
if self_component_index >= len(result.path) or other_component_index >= len(other_result.path):
continue
left_component = result.path[self_component_index]
right_component = other_result.path[other_component_index]
overlap_found = False
for left_poly in left_component.dilated_physical_geometry:
for right_poly in right_component.dilated_physical_geometry:
if not left_poly.intersects(right_poly) or left_poly.touches(right_poly):
continue
overlap = left_poly.intersection(right_poly)
if overlap.is_empty:
continue
buffered = overlap.buffer(margin, join_style="mitre").bounds
if buffered not in seen:
seen.add(buffered)
hotspot_bounds.append(buffered)
overlap_found = True
if overlap_found:
continue
left_bounds = left_component.total_dilated_bounds
right_bounds = right_component.total_dilated_bounds
if (
left_bounds[0] < right_bounds[2]
and left_bounds[2] > right_bounds[0]
and left_bounds[1] < right_bounds[3]
and left_bounds[3] > right_bounds[1]
):
buffered = (
max(left_bounds[0], right_bounds[0]) - margin,
max(left_bounds[1], right_bounds[1]) - margin,
min(left_bounds[2], right_bounds[2]) + margin,
min(left_bounds[3], right_bounds[3]) + margin,
)
if buffered not in seen:
seen.add(buffered)
hotspot_bounds.append(buffered)
return tuple(hotspot_bounds)
@contextmanager
def _frontier_replay(self, net_id: str, path: tuple[ComponentResult, ...]) -> Iterator[AStarMetrics]:
"""Use scratch counters while replaying a net with its path temporarily removed."""
context = self.context
world = context.cost_evaluator.collision_engine
danger_map = context.cost_evaluator.danger_map
context_metrics, world_metrics = context.metrics, world.metrics
danger_metrics = danger_map.metrics if danger_map is not None else None
scratch_metrics = AStarMetrics()
try:
context.metrics = world.metrics = scratch_metrics
if danger_map is not None:
danger_map.metrics = scratch_metrics
world.remove_path(net_id)
try:
yield scratch_metrics
finally:
if path:
self._install_path(net_id, path)
finally:
context.metrics, world.metrics = context_metrics, world_metrics
if danger_map is not None:
danger_map.metrics = danger_metrics
def _capture_single_frontier_trace(
self,
state: _RoutingState,
net_id: str,
result: RoutingResult,
hotspot_bounds: tuple[tuple[float, float, float, float], ...],
) -> NetFrontierTrace:
if not hotspot_bounds:
return NetFrontierTrace(
net_id=net_id,
hotspot_bounds=(),
pruned_closed_set=0,
pruned_hard_collision=0,
pruned_self_collision=0,
pruned_cost=0,
)
guidance_seed = result.as_seed().segments if result.path else None
guidance_bonus = max(10.0, self.context.options.objective.bend_penalty * 0.25) if guidance_seed else 0.0
collector = FrontierTraceCollector(hotspot_bounds=hotspot_bounds)
run_config = SearchRunConfig.from_options(
self.context.options,
return_partial=True,
store_expanded=False,
guidance_seed=guidance_seed,
guidance_bonus=guidance_bonus,
frontier_trace=collector,
self_collision_check=(net_id in state.needs_self_collision_check),
node_limit=self.context.options.search.node_limit,
)
net = state.net_specs[net_id]
with self._frontier_replay(net_id, result.path) as scratch_metrics:
route_astar(
net.start,
net.target,
net.width,
context=self.context,
metrics=scratch_metrics,
net_id=net_id,
config=run_config,
)
return NetFrontierTrace(
net_id=net_id,
hotspot_bounds=hotspot_bounds,
pruned_closed_set=collector.pruned_closed_set,
pruned_hard_collision=collector.pruned_hard_collision,
pruned_self_collision=collector.pruned_self_collision,
pruned_cost=collector.pruned_cost,
samples=tuple(
FrontierPruneSample(
reason=reason, # type: ignore[arg-type]
move_type=move_type,
hotspot_index=hotspot_index,
parent_state=parent_state,
end_state=end_state,
)
for reason, move_type, hotspot_index, parent_state, end_state in collector.samples
),
)
def _analyze_results(
self,
ordered_net_ids: Sequence[str],
results: dict[str, RoutingResult],
*,
capture_component_conflicts: bool,
count_iteration_metrics: bool,
) -> tuple[dict[str, RoutingResult], dict[str, PathVerificationDetail], _IterationReview]:
if count_iteration_metrics:
self.metrics.total_iteration_reverify_calls += 1
analyzed_results = dict(results)
details_by_net: dict[str, PathVerificationDetail] = {}
for net_id in ordered_net_ids:
result = results.get(net_id)
if not result or not result.path or not result.reached_target:
continue
if count_iteration_metrics:
self.metrics.total_iteration_reverified_nets += 1
detail = self.context.cost_evaluator.collision_engine.verify_path_details(
net_id,
result.path,
capture_component_conflicts=capture_component_conflicts,
)
details_by_net[net_id] = detail
analyzed_results[net_id] = RoutingResult(
net_id=net_id,
path=result.path,
reached_target=result.reached_target,
report=detail.report,
)
review = review_verified_results(analyzed_results, details_by_net)
if count_iteration_metrics:
self.metrics.total_iteration_conflicting_nets += len(review.conflicting_nets)
self.metrics.total_iteration_conflict_edges += len(review.conflict_edges)
return analyzed_results, details_by_net, review
def _capture_frontier_trace(
self,
state: _RoutingState,
final_results: dict[str, RoutingResult],
details_by_net: dict[str, PathVerificationDetail],
) -> None:
if not self.context.options.diagnostics.capture_frontier_trace:
return
self.frontier_trace = []
state.results = dict(final_results)
for net_id in state.ordered_net_ids:
result = state.results.get(net_id)
detail = details_by_net.get(net_id)
if result is None or detail is None or not result.reached_target:
continue
if detail.report.dynamic_collision_count == 0 or not detail.component_conflicts:
continue
hotspot_bounds = self._build_frontier_hotspot_bounds(state, net_id, details_by_net)
if not hotspot_bounds:
continue
self.frontier_trace.append(
self._capture_single_frontier_trace(
state,
net_id,
result,
hotspot_bounds,
)
)
def _whole_set_is_better(
self,
candidate_results: dict[str, RoutingResult],
candidate_review: _IterationReview,
incumbent_results: dict[str, RoutingResult],
incumbent_review: _IterationReview,
) -> bool:
candidate_rank, incumbent_rank = candidate_review.rank, incumbent_review.rank
if candidate_rank != incumbent_rank:
return candidate_rank < incumbent_rank
candidate_length = sum(
result.report.total_length
for result in candidate_results.values()
if result.reached_target
)
incumbent_length = sum(
result.report.total_length
for result in incumbent_results.values()
if result.reached_target
)
if abs(candidate_length - incumbent_length) > 1e-6:
return candidate_length < incumbent_length
return False
def _pair_local_attempt_orders(self, target: _PairLocalTarget) -> tuple[tuple[str, str], tuple[str, str]]:
return target.net_ids, target.net_ids[::-1]
def _collect_pair_local_targets(
self,
state: _RoutingState,
results: dict[str, RoutingResult],
review: _IterationReview,
) -> list[_PairLocalTarget]:
if not review.conflict_edges:
return []
order_index = {net_id: idx for idx, net_id in enumerate(state.ordered_net_ids)}
seen_net_ids: set[str] = set()
targets: list[_PairLocalTarget] = []
for left_net_id, right_net_id in sorted(review.conflict_edges):
if left_net_id in seen_net_ids or right_net_id in seen_net_ids:
return []
left_result = results.get(left_net_id)
right_result = results.get(right_net_id)
if (
left_result is None
or right_result is None
or not left_result.reached_target
or not right_result.reached_target
):
continue
seen_net_ids.update((left_net_id, right_net_id))
targets.append(_PairLocalTarget(net_ids=(left_net_id, right_net_id)))
targets.sort(key=lambda target: min(order_index[target.net_ids[0]], order_index[target.net_ids[1]]))
return targets
def _materialize_pre_pair_frontier_trace(
self,
state: _RoutingState,
results: dict[str, RoutingResult],
details_by_net: dict[str, PathVerificationDetail],
) -> PrePairFrontierTraceEntry | None:
candidate = state.pre_pair_candidate
if candidate is None:
return None
result_by_net = dict(results)
detail_by_net = dict(details_by_net)
nets: list[PrePairNetTrace] = []
attempt_by_net = {attempt.net_id: attempt for attempt in candidate.net_attempts}
for net_id in candidate.routed_net_ids:
attempt = attempt_by_net.get(net_id)
result = result_by_net.get(net_id)
detail = detail_by_net.get(net_id)
if attempt is None or result is None or detail is None or not result.reached_target:
continue
hotspot_bounds = self._build_frontier_hotspot_bounds(state, net_id, detail_by_net)
nets.append(
PrePairNetTrace(
net_id=net_id,
nodes_expanded=attempt.nodes_expanded,
congestion_check_calls=attempt.congestion_check_calls,
pruned_closed_set=attempt.pruned_closed_set,
pruned_cost=attempt.pruned_cost,
pruned_hard_collision=attempt.pruned_hard_collision,
guidance_seed_present=attempt.guidance_seed_present,
frontier=self._capture_single_frontier_trace(state, net_id, result, hotspot_bounds),
)
)
if not nets:
return None
return PrePairFrontierTraceEntry(
iteration=candidate.iteration,
routed_net_ids=candidate.routed_net_ids,
conflict_edges=candidate.conflict_edges,
nets=tuple(nets),
)
def _update_pre_pair_candidate(
self,
state: _RoutingState,
*,
iteration: int,
reroute_net_ids: set[str],
routed_net_ids: list[str],
attempt_traces: list[IterationNetAttemptTrace],
review: _IterationReview,
) -> None:
if (
len(reroute_net_ids) < len(state.ordered_net_ids)
and review.conflict_edges
and all_results_reached_target(state.ordered_net_ids, state.results)
):
state.pre_pair_candidate = _PrePairCandidate(
iteration=iteration,
routed_net_ids=tuple(routed_net_ids),
conflict_edges=tuple(sorted(review.conflict_edges)),
net_attempts=tuple(attempt_traces),
)
return
state.pre_pair_candidate = None
def _apply_pair_local_candidate(
self,
state: _RoutingState,
candidate_results: dict[str, RoutingResult],
incumbent_results: dict[str, RoutingResult],
incumbent_review: _IterationReview,
) -> tuple[bool, _IterationReview]:
self._replace_installed_paths(state, candidate_results)
candidate_results, _candidate_details_by_net, candidate_review = self._analyze_results(
state.ordered_net_ids,
candidate_results,
capture_component_conflicts=True,
count_iteration_metrics=False,
)
if self._whole_set_is_better(
candidate_results,
candidate_review,
incumbent_results,
incumbent_review,
):
self.metrics.total_pair_local_search_accepts += 1
state.results = candidate_results
return True, candidate_review
self._replace_installed_paths(state, incumbent_results)
return False, incumbent_review
def _run_pair_local_target(
self,
state: _RoutingState,
target: _PairLocalTarget,
review: _IterationReview,
) -> _IterationReview:
incumbent_results = dict(state.results)
incumbent_review = review
ordered_nets = tuple(state.net_specs[net_id] for net_id in state.ordered_net_ids)
self.metrics.total_pair_local_search_pairs_considered += 1
for pair_order in self._pair_local_attempt_orders(target):
self.metrics.total_pair_local_search_attempts += 1
candidate = search_pair_candidate(
self.context,
ordered_nets,
incumbent_results,
pair_order,
needs_self_collision_check=state.needs_self_collision_check,
lock_partial_paths=not state.corridors,
)
if candidate is None:
continue
replacements, nodes_expanded = candidate
self.metrics.total_pair_local_search_nodes_expanded += nodes_expanded
accepted, next_review = self._apply_pair_local_candidate(
state,
{**incumbent_results, **replacements},
incumbent_results,
incumbent_review,
)
if accepted:
return next_review
state.results = incumbent_results
self._replace_installed_paths(state, incumbent_results)
return incumbent_review
def _run_pair_local_search(self, state: _RoutingState, review: _IterationReview) -> None:
targets = self._collect_pair_local_targets(state, state.results, review)
if not targets:
return
for target in targets[:2]:
review = self._run_pair_local_target(state, target, review)
def _route_net_once(
self,
state: _RoutingState,
iteration: int,
net_id: str,
*,
node_limit_override: int | None = None,
incumbent_fallback: RoutingResult | None = None,
) -> tuple[RoutingResult, bool]:
search = self.context.options.search
congestion = self.context.options.congestion
diagnostics = self.context.options.diagnostics
net = state.net_specs[net_id]
self.metrics.total_nets_routed += 1
if node_limit_override is not None:
self.metrics.total_late_phase_capped_nets += 1
self.context.cost_evaluator.collision_engine.remove_path(net_id)
guidance_seed_present = False
if iteration == 0 and state.initial_paths and net_id in state.initial_paths:
self.metrics.total_warm_start_paths_used += 1
path: Sequence[ComponentResult] | None = state.initial_paths[net_id]
else:
coll_model, _ = resolve_bend_geometry(search)
skip_congestion = False
guidance_seed, guidance_bonus = None, 0.0
if congestion.use_tiered_strategy and iteration == 0 and not state.corridors:
skip_congestion = True
if coll_model == "arc":
coll_model = "clipped_bbox"
elif iteration > 0:
guidance_seed, guidance_bonus = incumbent_guidance(
state.results.get(net_id), self.context.options.objective.bend_penalty
)
guidance_seed_present = guidance_seed is not None
if node_limit_override is not None and self._has_incumbent_fallback(incumbent_fallback):
return self._restore_incumbent_fallback(net_id, incumbent_fallback, guidance_seed_present)
corridors = state.corridors.get(net_id, ())
run_config = SearchRunConfig.from_options(
self.context.options,
bend_collision_type=coll_model,
return_partial=True,
store_expanded=diagnostics.capture_expanded,
guidance_seed=guidance_seed,
guidance_bonus=guidance_bonus,
skip_congestion=skip_congestion,
self_collision_check=(net_id in state.needs_self_collision_check),
node_limit=search.node_limit if node_limit_override is None else node_limit_override,
corridor=corridors[iteration] if iteration < len(corridors) else None,
corridor_strength=self.context.options.topology.guide_strength / (iteration + 1),
hard_congestion=bool(state.corridors) and iteration == 0,
)
path = route_astar(
net.start,
net.target,
net.width,
context=self.context,
metrics=self.metrics,
net_id=net_id,
config=run_config,
)
if diagnostics.capture_expanded and self.metrics.last_expanded_nodes:
state.accumulated_expanded_nodes.extend(self.metrics.last_expanded_nodes)
if not path:
if self._has_incumbent_fallback(incumbent_fallback):
return self._restore_incumbent_fallback(net_id, incumbent_fallback, guidance_seed_present)
return RoutingResult(net_id=net_id, path=(), reached_target=False), guidance_seed_present
reached_target = path[-1].end_port == net.target
if not reached_target and self._has_incumbent_fallback(incumbent_fallback):
return self._restore_incumbent_fallback(net_id, incumbent_fallback, guidance_seed_present)
if reached_target:
self.metrics.total_nets_reached_target += 1
report = None
if reached_target or not state.corridors:
self._install_path(net_id, path)
if reached_target:
report = self.context.cost_evaluator.collision_engine.verify_path_report(net_id, path)
if report.self_collision_count > 0:
state.needs_self_collision_check.add(net_id)
return (
RoutingResult(
net_id=net_id,
path=tuple(path),
reached_target=reached_target,
report=RoutingReport() if report is None else report,
),
guidance_seed_present,
)
def _run_iteration(
self,
state: _RoutingState,
iteration: int,
reroute_net_ids: set[str],
iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None,
) -> _IterationReview | None:
congestion = self.context.options.congestion
diagnostics = self.context.options.diagnostics
self.metrics.total_route_iterations += 1
self.metrics.reset_per_route()
if congestion.shuffle_nets and (iteration > 0 or state.initial_paths is None):
iteration_seed = (congestion.seed + iteration) if congestion.seed is not None else None
random.Random(iteration_seed).shuffle(state.ordered_net_ids)
iteration_penalty = self.context.congestion_penalty
routed_net_ids, capped_net_ids = reroute_plan(
state.ordered_net_ids,
reroute_net_ids,
state.recent_attempt_work,
best_conflict_edges=state.best_conflict_edges,
results=state.results,
)
self.metrics.total_nets_carried_forward += len(state.ordered_net_ids) - len(routed_net_ids)
iteration_before = {}
attempt_traces: list[IterationNetAttemptTrace] = []
attempt_work: dict[str, int] = {}
capture_attempts = diagnostics.capture_iteration_trace or diagnostics.capture_pre_pair_frontier_trace
if diagnostics.capture_iteration_trace:
iteration_before = self._capture_metric_totals(_ITERATION_TRACE_TOTALS)
for net_id in routed_net_ids:
if time.monotonic() - state.start_time > state.timeout_s:
self.metrics.total_timeout_events += 1
return None
work_before = self.metrics.total_nodes_expanded + self.metrics.total_congestion_check_calls
if capture_attempts:
attempt_before = self._capture_metric_totals(_ATTEMPT_TRACE_TOTALS)
node_limit_override = None
incumbent_fallback = None
if net_id in capped_net_ids:
node_limit_override = min(self.context.options.search.node_limit, 1)
incumbent_fallback = state.results.get(net_id)
result, guidance_seed_present = self._route_net_once(
state,
iteration,
net_id,
node_limit_override=node_limit_override,
incumbent_fallback=incumbent_fallback,
)
state.results[net_id] = result
work_after = self.metrics.total_nodes_expanded + self.metrics.total_congestion_check_calls
attempt_work[net_id] = work_after - work_before
if capture_attempts:
attempt_after = self._capture_metric_totals(_ATTEMPT_TRACE_TOTALS)
deltas = self._metric_deltas(attempt_before, attempt_after)
attempt_traces.append(
net_attempt_trace(net_id, deltas, reached_target=result.reached_target, guidance_seed_present=guidance_seed_present)
)
state.recent_attempt_work = attempt_work
review = self._reverify_iteration_results(state)
if diagnostics.capture_pre_pair_frontier_trace:
self._update_pre_pair_candidate(
state,
iteration=iteration,
reroute_net_ids=reroute_net_ids,
routed_net_ids=routed_net_ids,
attempt_traces=attempt_traces,
review=review,
)
if diagnostics.capture_iteration_trace:
iteration_after = self._capture_metric_totals(_ITERATION_TRACE_TOTALS)
deltas = self._metric_deltas(iteration_before, iteration_after)
self.iteration_trace.append(
iteration_trace_entry(iteration, iteration_penalty, routed_net_ids, review, deltas, attempt_traces)
)
if iteration_callback:
iteration_callback(iteration, state.results)
return review
def _reverify_iteration_results(self, state: _RoutingState) -> _IterationReview:
state.results, details_by_net, review = self._analyze_results(
state.ordered_net_ids,
state.results,
capture_component_conflicts=self.context.options.diagnostics.capture_conflict_trace,
count_iteration_metrics=True,
)
self._capture_conflict_trace_entry(
state,
stage="iteration",
iteration=self.metrics.total_route_iterations - 1,
results=state.results,
details_by_net=details_by_net,
review=review,
)
return review
def _run_iterations(
self,
state: _RoutingState,
iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None,
) -> bool:
congestion = self.context.options.congestion
reroute_net_ids = set(state.ordered_net_ids)
for iteration in range(congestion.max_iterations):
review = self._run_iteration(
state,
iteration,
reroute_net_ids,
iteration_callback,
)
if review is None:
return True
improved = self._update_best_iteration(state, review)
state.best_is_installed = improved
if not any(
result.outcome in {"colliding", "partial", "unroutable"}
for result in state.results.values()
):
return False
all_reached = all_results_reached_target(state.ordered_net_ids, state.results)
reroute_net_ids = next_reroute_net_ids(
state.ordered_net_ids, review, all_reached_target=all_reached, has_corridors=bool(state.corridors)
)
if reached_pair_local_plateau(improved=improved, all_reached_target=all_reached, best_conflict_edges=state.best_conflict_edges):
return False
edge_count = len(review.conflict_edges)
state.repeated_conflict_count = repeated_conflict_count(edge_count, state.last_conflict_edge_count, state.repeated_conflict_count)
state.last_conflict_edge_count = edge_count
if state.repeated_conflict_count >= 2:
return False
self.context.congestion_penalty *= congestion.multiplier
return False
def _refine_results(self, state: _RoutingState) -> None:
if not self.context.options.refinement.enabled or not state.results:
return
for net_id in state.ordered_net_ids:
result = state.results.get(net_id)
if not result or not result.path or result.outcome in {"colliding", "partial", "unroutable"}:
continue
net = state.net_specs[net_id]
self.metrics.total_refine_path_calls += 1
self.context.cost_evaluator.collision_engine.remove_path(net_id)
refined_path = self.refiner.refine_path(net_id, net.start, net.width, result.path)
self._install_path(net_id, refined_path)
# Defer full verification until _verify_results() so we do not
# verify the same refined path twice in one route_all() call.
state.results[net_id] = RoutingResult(
net_id=net_id,
path=tuple(refined_path),
reached_target=result.reached_target,
report=result.report,
)
def _verify_results(self, state: _RoutingState) -> tuple[dict[str, RoutingResult], dict[str, PathVerificationDetail]]:
diagnostics = self.context.options.diagnostics
final_results: dict[str, RoutingResult] = {}
details_by_net: dict[str, PathVerificationDetail] = {}
for net in self.context.problem.nets:
result = state.results.get(net.net_id)
if not result or not result.path:
final_results[net.net_id] = RoutingResult(net_id=net.net_id, path=(), reached_target=False)
continue
capture_conflicts = diagnostics.capture_conflict_trace or (diagnostics.capture_frontier_trace and result.reached_target)
detail = self.context.cost_evaluator.collision_engine.verify_path_details(
net.net_id,
result.path,
capture_component_conflicts=capture_conflicts,
)
details_by_net[net.net_id] = detail
final_results[net.net_id] = RoutingResult(
net_id=net.net_id,
path=result.path,
reached_target=result.reached_target,
report=detail.report,
)
if diagnostics.capture_conflict_trace:
review = review_verified_results(final_results, details_by_net)
self._capture_conflict_trace_entry(
state,
stage="final",
iteration=None,
results=final_results,
details_by_net=details_by_net,
review=review,
)
return final_results, details_by_net
def route_all(
self,
*,
iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None = None,
phase_timer: PhaseTimer | None = None,
corridors: dict[str, tuple[Corridor, ...]] | None = None,
) -> dict[str, RoutingResult]:
self.context.congestion_penalty = self.context.options.congestion.base_penalty
self.accumulated_expanded_nodes = []
self.conflict_trace = []
self.frontier_trace = []
self.pre_pair_frontier_trace = None
self.iteration_trace = []
self.topology_report = None
self.metrics.reset_totals()
self.metrics.reset_per_route()
state = self._prepare_state(corridors)
timed_out = self._run_iterations(state, iteration_callback)
self.accumulated_expanded_nodes = list(state.accumulated_expanded_nodes)
# A partial iteration or a callback can leave the index out of sync with the saved results.
if timed_out or iteration_callback is not None or not state.best_is_installed:
self._restore_best_iteration(state)
diagnostics = self.context.options.diagnostics
if not timed_out or diagnostics.capture_conflict_trace or diagnostics.capture_pre_pair_frontier_trace:
review = self._review_restored_best(state)
if not timed_out:
self._run_pair_local_search(state, review)
if not timed_out:
with phase_timer("refine") if phase_timer is not None and self.context.options.refinement.enabled else nullcontext():
self._refine_results(state)
with phase_timer("verify") if phase_timer is not None else nullcontext():
final_results, details_by_net = self._verify_results(state)
self._capture_frontier_trace(state, final_results, details_by_net)
return final_results