Simplify pair repair targets and avoid redundant index restores

This commit is contained in:
Jan Petykiewicz 2026-11-27 00:34:49 -08:00
commit d95eab6963
2 changed files with 76 additions and 22 deletions

View file

@ -75,11 +75,6 @@ class _RoutingState:
return len(self.best_review.conflict_edges) if self.best_review is not None else 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) @dataclass(frozen=True, slots=True)
class _PrePairCandidate: class _PrePairCandidate:
iteration: int iteration: int
@ -666,20 +661,17 @@ class PathFinder:
return candidate_length < incumbent_length return candidate_length < incumbent_length
return False 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( def _collect_pair_local_targets(
self, self,
state: _RoutingState, state: _RoutingState,
results: dict[str, RoutingResult], results: dict[str, RoutingResult],
review: _IterationReview, review: _IterationReview,
) -> list[_PairLocalTarget]: ) -> list[tuple[str, str]]:
if not review.conflict_edges: if not review.conflict_edges:
return [] return []
order_index = {net_id: idx for idx, net_id in enumerate(state.ordered_net_ids)} order_index = {net_id: idx for idx, net_id in enumerate(state.ordered_net_ids)}
seen_net_ids: set[str] = set() seen_net_ids: set[str] = set()
targets: list[_PairLocalTarget] = [] targets: list[tuple[str, str]] = []
for left_net_id, right_net_id in sorted(review.conflict_edges): 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: if left_net_id in seen_net_ids or right_net_id in seen_net_ids:
return [] return []
@ -693,8 +685,8 @@ class PathFinder:
): ):
continue continue
seen_net_ids.update((left_net_id, right_net_id)) seen_net_ids.update((left_net_id, right_net_id))
targets.append(_PairLocalTarget(net_ids=(left_net_id, right_net_id))) targets.append((left_net_id, right_net_id))
targets.sort(key=lambda target: min(order_index[target.net_ids[0]], order_index[target.net_ids[1]])) targets.sort(key=lambda pair: min(order_index[pair[0]], order_index[pair[1]]))
return targets return targets
def _materialize_pre_pair_frontier_trace( def _materialize_pre_pair_frontier_trace(
@ -772,10 +764,10 @@ class PathFinder:
incumbent_review: _IterationReview, incumbent_review: _IterationReview,
) -> tuple[bool, _IterationReview]: ) -> tuple[bool, _IterationReview]:
self._replace_installed_paths(state, candidate_results) self._replace_installed_paths(state, candidate_results)
candidate_results, _candidate_details_by_net, candidate_review = self._analyze_results( candidate_results, _, candidate_review = self._analyze_results(
state.ordered_net_ids, state.ordered_net_ids,
candidate_results, candidate_results,
capture_component_conflicts=True, capture_component_conflicts=False,
count_iteration_metrics=False, count_iteration_metrics=False,
) )
if self._whole_set_is_better( if self._whole_set_is_better(
@ -794,14 +786,13 @@ class PathFinder:
def _run_pair_local_target( def _run_pair_local_target(
self, self,
state: _RoutingState, state: _RoutingState,
target: _PairLocalTarget, target: tuple[str, str],
review: _IterationReview, review: _IterationReview,
) -> _IterationReview: ) -> _IterationReview:
incumbent_results = dict(state.results) incumbent_results = state.results
incumbent_review = review
ordered_nets = tuple(state.net_specs[net_id] for net_id in state.ordered_net_ids) 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 self.metrics.total_pair_local_search_pairs_considered += 1
for pair_order in self._pair_local_attempt_orders(target): for pair_order in (target, (target[1], target[0])):
self.metrics.total_pair_local_search_attempts += 1 self.metrics.total_pair_local_search_attempts += 1
candidate = search_pair_candidate( candidate = search_pair_candidate(
self.context, self.context,
@ -819,14 +810,12 @@ class PathFinder:
state, state,
{**incumbent_results, **replacements}, {**incumbent_results, **replacements},
incumbent_results, incumbent_results,
incumbent_review, review,
) )
if accepted: if accepted:
return next_review return next_review
state.results = incumbent_results return review
self._replace_installed_paths(state, incumbent_results)
return incumbent_review
def _run_pair_local_search(self, state: _RoutingState, review: _IterationReview) -> None: def _run_pair_local_search(self, state: _RoutingState, review: _IterationReview) -> None:
targets = self._collect_pair_local_targets(state, state.results, review) targets = self._collect_pair_local_targets(state, state.results, review)

View file

@ -785,6 +785,71 @@ def test_first_iteration_and_pair_length_tie_break() -> None:
assert finder._whole_set_is_better(results(10.0 - 2e-6), review, incumbent, review) assert finder._whole_set_is_better(results(10.0 - 2e-6), review, incumbent, review)
def test_pair_repair_limits_disjoint_targets_in_routing_order(monkeypatch: pytest.MonkeyPatch) -> None:
problem = RoutingProblem(
bounds=(0, 0, 100, 100),
nets=tuple(NetSpec(net_id, Port(10, i * 10, 0), Port(90, i * 10, 0)) for i, net_id in enumerate("cdbaef", 1)),
)
options = RoutingOptions(congestion=CongestionOptions(warm_start_enabled=False), topology=TopologyOptions(mode="off"))
world = RoutingWorld(clearance=problem.clearance)
finder = PathFinder(AStarContext(CostEvaluator(world, DangerMap(bounds=problem.bounds)), problem, options))
state = finder._prepare_state()
state.results = {net_id: RoutingResult(net_id, (), reached_target=True) for net_id in state.ordered_net_ids}
review = _IterationReview(set(state.ordered_net_ids), {("a", "b"), ("c", "d"), ("e", "f")}, set(), 6)
visited = []
def repair(_finder, _state, pair, current_review):
visited.append(pair)
return current_review
monkeypatch.setattr(PathFinder, "_run_pair_local_target", repair)
finder._run_pair_local_search(state, review)
assert visited == [("c", "d"), ("a", "b")]
visited.clear()
review.conflict_edges.add(("b", "c"))
finder._run_pair_local_search(state, review)
assert not visited
@pytest.mark.parametrize("candidate_reaches_live_check", [False, True])
def test_rejected_pair_keeps_original_index_for_reverse_attempt(monkeypatch: pytest.MonkeyPatch, candidate_reaches_live_check: bool) -> None:
problem = RoutingProblem(
bounds=(0, 0, 100, 100),
nets=(NetSpec("a", Port(10, 20, 0), Port(90, 20, 0)), NetSpec("b", Port(10, 40, 0), Port(90, 40, 0))),
)
options = RoutingOptions(congestion=CongestionOptions(warm_start_enabled=False), topology=TopologyOptions(mode="off"))
world = RoutingWorld(clearance=problem.clearance)
finder = PathFinder(AStarContext(CostEvaluator(world, DangerMap(bounds=problem.bounds)), problem, options))
state = finder._prepare_state()
for net in problem.nets:
path = (Straight.generate(net.start, 80, net.width, dilation=1.0),)
finder._install_path(net.net_id, path)
state.results[net.net_id] = RoutingResult(net.net_id, path, reached_target=True, report=world.verify_path_report(net.net_id, path))
initial_bounds = sorted(world.iter_dynamic_path_bounds(problem.bounds))
incumbent = dict(state.results)
review = _IterationReview(set(), set(), {"a", "b"}, 0)
attempted = []
def search(_context, _ordered, _results, pair_order, **_kwargs):
attempted.append(pair_order)
assert sorted(world.iter_dynamic_path_bounds(problem.bounds)) == initial_bounds
if candidate_reaches_live_check and pair_order == ("a", "b"):
return {"a": RoutingResult("a", incumbent["b"].path, reached_target=True)}, 0
return None
monkeypatch.setattr(router_module, "search_pair_candidate", search)
assert finder._run_pair_local_target(state, ("a", "b"), review) is review
assert attempted == [("a", "b"), ("b", "a")]
assert state.results == incumbent
assert sorted(world.iter_dynamic_path_bounds(problem.bounds)) == initial_bounds
assert all(world.verify_path_report(net_id, result.path) == result.report for net_id, result in incumbent.items())
metrics = finder.metrics.snapshot()
assert metrics.dynamic_path_objects_added == 2 + 4 * candidate_reaches_live_check
assert metrics.dynamic_path_objects_removed == 4 * candidate_reaches_live_check
def test_route_all_restores_best_iteration_snapshot_on_timeout(monkeypatch: pytest.MonkeyPatch) -> None: def test_route_all_restores_best_iteration_snapshot_on_timeout(monkeypatch: pytest.MonkeyPatch) -> None:
problem = RoutingProblem( problem = RoutingProblem(
bounds=(0, 0, 100, 100), bounds=(0, 0, 100, 100),