Report coincident terminals and unusable seeds per net, update custom bend handling and verification, and cover the revised behavior with regression tests. Shorten the user and developer guides around reader tasks and keep the illustrated routing walkthrough and reference links easy to find.
1307 lines
57 KiB
Python
1307 lines
57 KiB
Python
from __future__ import annotations
|
|
|
|
import random
|
|
import time
|
|
from contextlib import contextmanager, nullcontext
|
|
from dataclasses import dataclass, field, replace
|
|
from functools import partial
|
|
from typing import TYPE_CHECKING
|
|
|
|
from shapely import shortest_line
|
|
|
|
from inire.geometry.components import bend_fits_width, bend90_uses_circular_geometry
|
|
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,
|
|
can_reserve,
|
|
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, path_guidance, route_astar
|
|
from inire.router._seed_materialization import materialize_path_seed, SeedMaterializationError
|
|
from inire.router.refiner import PathRefiner
|
|
|
|
if TYPE_CHECKING:
|
|
from collections.abc import Callable, Iterator, Sequence
|
|
from contextlib import AbstractContextManager
|
|
|
|
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_indexed: 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)
|
|
seed_errors: dict[str, str] = field(default_factory=dict)
|
|
terminal_errors: dict[str, str] = field(default_factory=dict)
|
|
replay_details: dict[str, PathVerificationDetail] | None = None
|
|
timed_out: bool = False
|
|
|
|
@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 _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",
|
|
"iteration_offset",
|
|
)
|
|
|
|
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
|
|
self.iteration_offset = 0
|
|
|
|
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 _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._add_route(net_id, result.path)
|
|
return result, guidance_seed_present
|
|
|
|
def _add_route(self, net_id: str, path: Sequence[ComponentResult]) -> None:
|
|
self.context.cost_evaluator.collision_engine.add_route(net_id, path)
|
|
|
|
@contextmanager
|
|
def _temporary_path_reservations(self) -> Iterator[Callable[[str, Sequence[ComponentResult]], None]]:
|
|
world = self.context.cost_evaluator.collision_engine
|
|
temporary: list[int] = []
|
|
|
|
def reserve(net_id: str, path: Sequence[ComponentResult]) -> None:
|
|
for component in path:
|
|
for shape in component.physical_geometry:
|
|
temporary.append(world.add_static_obstacle(shape, owner=net_id))
|
|
|
|
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)
|
|
world = self.context.cost_evaluator.collision_engine
|
|
existing = state.initial_paths or {}
|
|
expired = partial(self._expired, state)
|
|
with self._temporary_path_reservations() as reserve:
|
|
for net_id, path in existing.items():
|
|
if path[-1].end_port == state.net_specs[net_id].target and world.verify_path_report(net_id, path).is_valid:
|
|
reserve(net_id, path)
|
|
if existing:
|
|
self.context.clear_static_caches()
|
|
for net_id in state.ordered_net_ids:
|
|
if expired():
|
|
break
|
|
if net_id in existing or net_id in state.terminal_errors:
|
|
continue
|
|
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,
|
|
expired=expired,
|
|
)
|
|
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 or world.verify_path_report(net_id, path).intrinsic_collision_count:
|
|
continue
|
|
self.metrics.total_warm_start_paths_built += 1
|
|
greedy_paths[net_id] = tuple(path)
|
|
reserve(net_id, 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, ...]] = {}
|
|
preserved = set()
|
|
expired = partial(self._expired, state)
|
|
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(net_id, path)
|
|
preserved.add(net_id)
|
|
for net_id in state.ordered_net_ids:
|
|
if expired():
|
|
break
|
|
if net_id in preserved or net_id in state.terminal_errors:
|
|
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,
|
|
expired=expired,
|
|
)
|
|
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(net_id, 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 if net_id not in state.terminal_errors],
|
|
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, *, started_at: float | None = None) -> _RoutingState:
|
|
problem = self.context.problem
|
|
congestion = self.context.options.congestion
|
|
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() if started_at is None else started_at,
|
|
timeout_s=max(60.0, 10.0 * num_nets * congestion.max_iterations),
|
|
initial_paths=None,
|
|
accumulated_expanded_nodes=[],
|
|
best_results={},
|
|
best_is_indexed=False,
|
|
best_review=None,
|
|
last_conflict_edge_count=0,
|
|
repeated_conflict_count=0,
|
|
recent_attempt_work={},
|
|
pre_pair_candidate=None,
|
|
)
|
|
self._materialize_problem_initial_paths(state)
|
|
if congestion.max_iterations:
|
|
world = self.context.cost_evaluator.collision_engine
|
|
search = self.context.options.search
|
|
proxy, physical_bend = resolve_bend_geometry(search)
|
|
circular_bend = bend90_uses_circular_geometry(proxy, physical_bend)
|
|
custom_bend_radius = max(search.bend_radii, default=0.0) if physical_bend != "arc" else 0.0
|
|
initial_paths = state.initial_paths or {}
|
|
for net_id, net in net_specs.items():
|
|
# Custom moves can have faces offset from the nominal port plane.
|
|
custom_bend = custom_bend_radius > 0 and (not circular_bend or bend_fits_width(custom_bend_radius, net.width))
|
|
if search.node_limit and (custom_bend or search.has_applicable_sbend_outline((net.width,))):
|
|
continue
|
|
path = initial_paths.get(net_id)
|
|
materialized_ports = (path[0].start_port, path[-1].end_port) if path else ()
|
|
for name, port in (("start", net.start), ("target", net.target)):
|
|
# Verification checks the actual polygons of a materialized seed.
|
|
if port in materialized_ports:
|
|
continue
|
|
issue = world.terminal_issue(port, net.width)
|
|
if issue is not None:
|
|
state.terminal_errors[net_id] = f"{name} port {port.as_tuple()} {issue}"
|
|
break
|
|
if congestion.max_iterations <= 0 or (self.context.options.search.node_limit <= 0 and self.context.options.topology.mode != "bundle"):
|
|
return state
|
|
if self._expired(state):
|
|
return state
|
|
self._prepare_topology(state, corridors)
|
|
if self._expired(state):
|
|
return state
|
|
if congestion.warm_start_enabled and len(state.initial_paths or ()) < len(net_specs):
|
|
greedy = self._build_greedy_warm_start_paths(state)
|
|
if greedy:
|
|
state.initial_paths = {**(state.initial_paths or {}), **greedy}
|
|
if state.corridors and state.initial_paths:
|
|
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._add_route(net_id, path)
|
|
state.results[net_id] = RoutingResult(net_id, path, reached_target=True, report=report)
|
|
return state
|
|
|
|
def _expired(self, state: _RoutingState) -> bool:
|
|
if not state.timed_out and time.monotonic() - state.start_time >= state.timeout_s:
|
|
state.timed_out = True
|
|
self.metrics.total_timeout_events += 1
|
|
return state.timed_out
|
|
|
|
def _materialize_problem_initial_paths(self, state: _RoutingState) -> None:
|
|
if not self.context.problem.initial_paths:
|
|
return
|
|
|
|
search = self.context.options.search
|
|
initial_paths: dict[str, tuple[ComponentResult, ...]] = {}
|
|
for net_id, seed in self.context.problem.initial_paths.items():
|
|
if net_id not in state.net_specs:
|
|
raise ValueError(f"Initial path provided for unknown net: {net_id}")
|
|
error = search.seed_geometry_error(seed)
|
|
if error is not None:
|
|
state.seed_errors[net_id] = f"Initial path for {net_id!r} {error}"
|
|
continue
|
|
net = state.net_specs[net_id]
|
|
try:
|
|
path = materialize_path_seed(
|
|
seed,
|
|
start=net.start,
|
|
net_width=net.width,
|
|
search=search,
|
|
diagnostic=True,
|
|
clearance=self.context.cost_evaluator.collision_engine.clearance,
|
|
)
|
|
except SeedMaterializationError as exc:
|
|
state.seed_errors[net_id] = f"Initial path for {net_id!r} {exc}"
|
|
continue
|
|
if path:
|
|
initial_paths[net_id] = path
|
|
state.initial_paths = initial_paths or None
|
|
|
|
def _replace_indexed_routes(
|
|
self, state: _RoutingState, results: dict[str, RoutingResult], *, net_ids: Sequence[str] | None = None
|
|
) -> None:
|
|
state.replay_details = None
|
|
ordered_net_ids = state.ordered_net_ids if net_ids is None else net_ids
|
|
for net_id in ordered_net_ids:
|
|
self.context.cost_evaluator.collision_engine.remove_path(net_id)
|
|
for net_id in ordered_net_ids:
|
|
result = results.get(net_id)
|
|
if can_reserve(result):
|
|
self._add_route(net_id, result.path)
|
|
|
|
def _review_restored_best(self, state: _RoutingState) -> _IterationReview:
|
|
diagnostics = self.context.options.diagnostics
|
|
details_by_net = state.replay_details
|
|
if details_by_net is None:
|
|
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,
|
|
)
|
|
else:
|
|
review = review_verified_results(state.results, details_by_net)
|
|
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_indexed_routes(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
|
|
|
|
# A clearance violation can occur between the flat ends of two bend polygons.
|
|
gap = min(
|
|
(shortest_line(left, right) for left in left_component.physical_geometry for right in right_component.physical_geometry),
|
|
key=lambda line: line.length,
|
|
)
|
|
minx, miny, maxx, maxy = gap.bounds
|
|
buffered = (minx - margin, miny - margin, maxx + margin, maxy + 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._add_route(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, guidance_bonus = incumbent_guidance(result, self.context.options.objective.bend_penalty)
|
|
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]
|
|
installed_path = result.path if can_reserve(result) else ()
|
|
with self._frontier_replay(net_id, installed_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] = {}
|
|
replay = self.context.options.search.node_limit == 0
|
|
|
|
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,
|
|
include_invalid_dynamic=False,
|
|
geometry_report=result.report if replay else None,
|
|
)
|
|
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 _collect_pair_local_targets(
|
|
self,
|
|
state: _RoutingState,
|
|
results: dict[str, RoutingResult],
|
|
review: _IterationReview,
|
|
) -> list[tuple[str, str]]:
|
|
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[tuple[str, str]] = []
|
|
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((left_net_id, right_net_id))
|
|
targets.sort(key=lambda pair: min(order_index[pair[0]], order_index[pair[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,
|
|
replacements: dict[str, RoutingResult],
|
|
incumbent_review: _IterationReview,
|
|
) -> tuple[bool, _IterationReview]:
|
|
incumbent_results = state.results
|
|
candidate_results = {**incumbent_results, **replacements}
|
|
changed_net_ids = [net_id for net_id in state.ordered_net_ids if net_id in replacements]
|
|
self._replace_indexed_routes(state, candidate_results, net_ids=changed_net_ids)
|
|
candidate_results, _, candidate_review = self._analyze_results(
|
|
state.ordered_net_ids,
|
|
candidate_results,
|
|
capture_component_conflicts=False,
|
|
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_indexed_routes(state, incumbent_results, net_ids=changed_net_ids)
|
|
return False, incumbent_review
|
|
|
|
def _run_pair_local_target(
|
|
self,
|
|
state: _RoutingState,
|
|
target: tuple[str, str],
|
|
review: _IterationReview,
|
|
) -> _IterationReview:
|
|
incumbent_results = state.results
|
|
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 (target, (target[1], target[0])):
|
|
if self._expired(state):
|
|
break
|
|
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,
|
|
expired=partial(self._expired, state),
|
|
)
|
|
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,
|
|
replacements,
|
|
review,
|
|
)
|
|
if accepted:
|
|
return next_review
|
|
|
|
return review
|
|
|
|
def _run_pair_local_search(self, state: _RoutingState, review: _IterationReview) -> None:
|
|
if not self.context.options.search.node_limit:
|
|
return
|
|
targets = self._collect_pair_local_targets(state, state.results, review)
|
|
if not targets:
|
|
return
|
|
|
|
initial_edges = len(review.conflict_edges)
|
|
for target in targets[:2]:
|
|
review = self._run_pair_local_target(state, target, review)
|
|
if len(targets) > 2 and len(review.conflict_edges) == initial_edges - 2:
|
|
self._run_pair_local_target(state, targets[2], 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
|
|
world = self.context.cost_evaluator.collision_engine
|
|
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
|
|
world.remove_path(net_id)
|
|
guidance_seed_present = False
|
|
|
|
terminal_error = state.terminal_errors.get(net_id)
|
|
initial_path = state.initial_paths.get(net_id) if state.initial_paths else None
|
|
initial_arrives = bool(initial_path and initial_path[-1].end_port == net.target)
|
|
initial_report = None
|
|
if iteration == 0 and search.node_limit and initial_path and initial_arrives:
|
|
initial_report = world.verify_path_geometry(initial_path)
|
|
seed_intrinsic_ok = initial_report is not None and not initial_report.intrinsic_collision_count
|
|
if terminal_error:
|
|
path: Sequence[ComponentResult] | None = initial_path
|
|
elif iteration == 0 and initial_path is not None and (seed_intrinsic_ok or search.node_limit <= 0):
|
|
self.metrics.total_warm_start_paths_used += 1
|
|
path = initial_path
|
|
elif search.node_limit == 0:
|
|
path = None
|
|
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"
|
|
if iteration > 0:
|
|
guidance_seed, guidance_bonus = incumbent_guidance(
|
|
state.results.get(net_id), self.context.options.objective.bend_penalty
|
|
)
|
|
use_prefix = not guidance_seed and bool(initial_path and not initial_arrives)
|
|
if use_prefix and initial_path:
|
|
guidance_seed, guidance_bonus = path_guidance(initial_path, self.context.options.objective.bend_penalty)
|
|
if iteration == 0:
|
|
self.metrics.total_warm_start_paths_used += 1
|
|
guidance_seed_present = guidance_seed is not None
|
|
|
|
if node_limit_override is not None and can_reserve(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,
|
|
propose_guidance_moves=use_prefix,
|
|
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,
|
|
expired=partial(self._expired, state),
|
|
)
|
|
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 (
|
|
(initial_arrives and iteration == 0 and (not path or path[-1].end_port != net.target))
|
|
or (not path and use_prefix)
|
|
):
|
|
path = initial_path
|
|
|
|
if not path:
|
|
if can_reserve(incumbent_fallback):
|
|
return self._restore_incumbent_fallback(net_id, incumbent_fallback, guidance_seed_present)
|
|
return RoutingResult(net_id=net_id, path=(), report=RoutingReport(terminal_error=terminal_error)), guidance_seed_present
|
|
|
|
reached_target = path[-1].end_port == net.target
|
|
if not reached_target and can_reserve(incumbent_fallback):
|
|
return self._restore_incumbent_fallback(net_id, incumbent_fallback, guidance_seed_present)
|
|
if reached_target:
|
|
self.metrics.total_nets_reached_target += 1
|
|
if search.node_limit:
|
|
report = world.verify_path_details(
|
|
net_id, path, include_invalid_dynamic=False,
|
|
geometry_report=initial_report if path is initial_path else None,
|
|
).report
|
|
else:
|
|
report = world.verify_path_geometry(path)
|
|
if not report.intrinsic_collision_count:
|
|
self._add_route(net_id, path)
|
|
if report.self_collision_count > 0:
|
|
state.needs_self_collision_check.add(net_id)
|
|
else:
|
|
report = RoutingReport(terminal_error=terminal_error)
|
|
|
|
return (
|
|
RoutingResult(
|
|
net_id=net_id,
|
|
path=tuple(path),
|
|
reached_target=reached_target,
|
|
report=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)
|
|
|
|
trace_iteration = self.iteration_offset + iteration
|
|
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 self._expired(state):
|
|
break
|
|
|
|
work_before = self.metrics.reroute_work
|
|
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.reroute_work
|
|
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)
|
|
)
|
|
|
|
if self._expired(state) and not state.results:
|
|
return None
|
|
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=trace_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(trace_iteration, iteration_penalty, routed_net_ids, review, deltas, attempt_traces)
|
|
)
|
|
|
|
if iteration_callback and not state.timed_out:
|
|
iteration_callback(trace_iteration, dict(state.results))
|
|
return review
|
|
|
|
def _reverify_iteration_results(self, state: _RoutingState) -> _IterationReview:
|
|
diagnostics = self.context.options.diagnostics
|
|
replay = self.context.options.search.node_limit == 0 and not state.timed_out
|
|
capture_conflicts = diagnostics.capture_conflict_trace or (
|
|
replay and (diagnostics.capture_frontier_trace or diagnostics.capture_pre_pair_frontier_trace)
|
|
)
|
|
state.results, details_by_net, review = self._analyze_results(
|
|
state.ordered_net_ids,
|
|
state.results,
|
|
capture_component_conflicts=capture_conflicts,
|
|
count_iteration_metrics=True,
|
|
)
|
|
if replay:
|
|
# Replay has one iteration. These details describe the whole indexed layout.
|
|
state.replay_details = details_by_net
|
|
self._capture_conflict_trace_entry(
|
|
state,
|
|
stage="iteration",
|
|
iteration=self.iteration_offset + 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)
|
|
rounds = congestion.max_iterations if self.context.options.search.node_limit else min(1, congestion.max_iterations)
|
|
for iteration in range(rounds):
|
|
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_indexed = improved
|
|
if state.timed_out:
|
|
return True
|
|
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:
|
|
options = self.context.options
|
|
if not options.refinement.enabled or not state.results:
|
|
return
|
|
|
|
replay = options.search.node_limit == 0
|
|
proximity_ready = not replay
|
|
world = self.context.cost_evaluator.collision_engine
|
|
for net_id in state.ordered_net_ids:
|
|
if self._expired(state):
|
|
break
|
|
result = state.results.get(net_id)
|
|
if not result or not result.is_valid or not self.refiner.has_refinement_bends(result.path):
|
|
continue
|
|
if not proximity_ready:
|
|
evaluator = self.context.cost_evaluator
|
|
weights = options.refinement.objective or options.objective
|
|
if evaluator.danger_map is not None and weights.danger_weight:
|
|
evaluator.danger_map.precompute(self.context.problem._blocking_polygons)
|
|
proximity_ready = True
|
|
net = state.net_specs[net_id]
|
|
self.metrics.total_refine_path_calls += 1
|
|
world.remove_path(net_id)
|
|
refined_path = tuple(self.refiner.refine_path(net_id, net.start, net.width, result.path))
|
|
self._add_route(net_id, refined_path)
|
|
report = result.report
|
|
if replay and refined_path != result.path:
|
|
state.replay_details = None
|
|
report = world.verify_path_geometry(refined_path)
|
|
state.results[net_id] = RoutingResult(
|
|
net_id=net_id,
|
|
path=refined_path,
|
|
reached_target=result.reached_target,
|
|
report=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] = {}
|
|
replay = self.context.options.search.node_limit == 0
|
|
replay_details = state.replay_details or {}
|
|
for net in self.context.problem.nets:
|
|
result = state.results.get(net.net_id)
|
|
seed_error = state.seed_errors.get(net.net_id) if self.context.options.congestion.max_iterations else None
|
|
terminal_error = state.terminal_errors.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,
|
|
report=RoutingReport(invalid_geometry=seed_error is not None, seed_error=seed_error, terminal_error=terminal_error),
|
|
)
|
|
continue
|
|
detail = replay_details.get(net.net_id)
|
|
if detail is None:
|
|
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,
|
|
include_invalid_dynamic=False,
|
|
geometry_report=result.report if replay and result.reached_target else None,
|
|
)
|
|
report = detail.report
|
|
if seed_error or terminal_error:
|
|
report = replace(report, seed_error=seed_error, terminal_error=terminal_error)
|
|
detail = replace(detail, report=report)
|
|
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=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,
|
|
started_at: float | None = None,
|
|
iteration_offset: int = 0,
|
|
) -> dict[str, RoutingResult]:
|
|
self.iteration_offset = iteration_offset
|
|
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, started_at=started_at)
|
|
replay = self.context.options.search.node_limit == 0
|
|
timed_out = self._run_iterations(state, None if replay else iteration_callback)
|
|
self.accumulated_expanded_nodes = list(state.accumulated_expanded_nodes)
|
|
# A partial iteration can leave the index out of sync with the saved results.
|
|
best_is_live = not timed_out and state.best_is_indexed
|
|
if not best_is_live:
|
|
self._restore_best_iteration(state)
|
|
|
|
diagnostics = self.context.options.diagnostics
|
|
capture_restored = diagnostics.capture_conflict_trace or diagnostics.capture_pre_pair_frontier_trace
|
|
if not timed_out or capture_restored:
|
|
review = state.best_review if best_is_live and not capture_restored else None
|
|
if review is None:
|
|
review = self._review_restored_best(state)
|
|
if not timed_out:
|
|
self._run_pair_local_search(state, review)
|
|
if not timed_out and not self._expired(state):
|
|
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)
|
|
if not self._expired(state):
|
|
self._capture_frontier_trace(state, final_results, details_by_net)
|
|
if replay and iteration_callback is not None and not timed_out and self.metrics.total_route_iterations:
|
|
iteration_callback(self.iteration_offset, {net_id: final_results[net_id] for net_id in state.ordered_net_ids})
|
|
return final_results
|