From 8b32d684962de454c65cc7f683abc4aa37851071 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Sun, 29 Nov 2026 19:13:44 -0800 Subject: [PATCH] Reuse geometry and conflict reports during seed replay Check a replayed route against itself and fixed geometry before adding it to the collision index. Add cross-net conflicts once the index is populated, then share reports across review, traces, and the callback. Recheck changed geometry after refinement. --- docs/architecture.md | 2 + docs/user/api-reference.md | 2 + inire/geometry/collision.py | 49 +++++++++++++-------- inire/router/_router.py | 78 +++++++++++++++++++++++---------- inire/tests/test_api.py | 38 +++++++++++----- inire/tests/test_collision.py | 5 +++ inire/tests/test_refinements.py | 9 +++- 7 files changed, 129 insertions(+), 54 deletions(-) diff --git a/docs/architecture.md b/docs/architecture.md index 9bd3acc..f1fde16 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -40,6 +40,8 @@ A result carries the requested and effective net specs. The effective net record Search, seed replay, and refinement share analytic endpoint and circular sampling calculations. Preparation rejects oversized sampling requests before allocating the outline. Verification uses the materialized polygons for exact containment and clearance. +Zero-node replay checks each complete path against the board, itself, and fixed geometry before adding eligible paths to the collision index. A second pass adds cross-net conflicts to those reports. Iteration review and final reporting reuse the results while the indexed routes stay the same. + Search uses proxies to check moves and estimate congestion. Verification rejects invalid polygons and checks each port for a finite-width face with material on the correct side. It checks for overlap within components and unintended contact between components, and checks the route against keepouts, other nets, and the board rectangle in every routing mode. Search and seed materialization use the same custom S-bend outline when one is configured. A circular S-bend with a fractional forward span ends with a short tangent extension to the next grid point, keeping the requested radius. Boundary contact with the board is allowed. At a keepout corner, a mitred clearance buffer can reach farther than the specified clearance. Verification checks the actual distance before counting these hits as collisions. For an example with a corner close to the required clearance, see the [mitred-corner test](../inire/tests/test_collision.py#L146). diff --git a/docs/user/api-reference.md b/docs/user/api-reference.md index 01ed672..8526bbd 100644 --- a/docs/user/api-reference.md +++ b/docs/user/api-reference.md @@ -10,6 +10,8 @@ route(problem, *, options=None, iteration_callback=None) -> RoutingRunResult Omitting `options` uses `RoutingOptions()`. To observe progress, pass a callable accepting `(index, results_by_net)`. Each call receives a snapshot of the nets in one completed congestion iteration. Indices increase across attempts. An iteration that times out can consume an index without calling back. Automatic mode uses the same planner order with or without a callback. Check the returned result for final coverage, including on runs that finish without a callback. +For a zero-node attempt that completes its replay iteration, the callback receives the verified results after any refinement. + ## Layout inputs ### Ports and nets diff --git a/inire/geometry/collision.py b/inire/geometry/collision.py index b888ca5..e3eee20 100644 --- a/inire/geometry/collision.py +++ b/inire/geometry/collision.py @@ -709,28 +709,15 @@ class RoutingWorld: frozen_net_ids=frozen_net_ids, ) - def verify_path_details( - self, - net_id: str, - components: Sequence[ComponentResult], - *, - capture_component_conflicts: bool = False, - include_invalid_dynamic: bool = True, - ) -> PathVerificationDetail: - if self.metrics is not None: - self.metrics.total_verify_path_report_calls += 1 + def verify_path_geometry(self, components: Sequence[ComponentResult]) -> RoutingReport: + """Check continuity, self-spacing, the board, and static obstacles.""" static_collision_count = 0 - dynamic_collision_count = 0 total_length = sum(component.length for component in components) valid_geometry, continuous = check_path_geometry(components) if not valid_geometry: - return PathVerificationDetail(RoutingReport(total_length=total_length, invalid_geometry=True)) - conflicting_net_ids: set[str] = set() - component_conflicts: set[tuple[int, str, int]] = set() + return RoutingReport(total_length=total_length, invalid_geometry=True) static_obstacles = self._static_obstacles - dynamic_paths = self._dynamic_paths - self._ensure_static_raw_tree() if static_obstacles.raw_tree is not None: raw_geometries = static_obstacles.raw_tree.geometries @@ -749,14 +736,36 @@ class RoutingWorld: if violates(polygon, obstacle, self.clearance): static_collision_count += 1 - report = RoutingReport( + return RoutingReport( static_collision_count=static_collision_count, self_collision_count=count_path_self_collisions(components, self.self_clearance), total_length=total_length, out_of_bounds=self.board is not None and not path_within_board(components, self.board), discontinuous=not continuous, ) - if (include_invalid_dynamic or not report.intrinsic_collision_count) and dynamic_paths.has_physical_paths(): + + def verify_path_details( + self, + net_id: str, + components: Sequence[ComponentResult], + *, + capture_component_conflicts: bool = False, + include_invalid_dynamic: bool = True, + geometry_report: RoutingReport | None = None, + ) -> PathVerificationDetail: + """Check the full path, optionally reusing its report against unchanged static geometry.""" + if self.metrics is not None: + self.metrics.total_verify_path_report_calls += 1 + report = self.verify_path_geometry(components) if geometry_report is None else geometry_report + dynamic_collision_count = 0 + conflicting_net_ids: set[str] = set() + component_conflicts: set[tuple[int, str, int]] = set() + + if ( + not report.invalid_geometry + and (include_invalid_dynamic or not report.intrinsic_collision_count) + and self._dynamic_paths.has_physical_paths() + ): for component_index, component in enumerate(components): component_hits: set[str] = set() for polygon in component.physical_geometry: @@ -777,8 +786,10 @@ class RoutingWorld: dynamic_collision_count += len(component_hits) conflicting_net_ids.update(component_hits) + if dynamic_collision_count != report.dynamic_collision_count: + report = replace(report, dynamic_collision_count=dynamic_collision_count) return PathVerificationDetail( - report=replace(report, dynamic_collision_count=dynamic_collision_count) if dynamic_collision_count else report, + report=report, conflicting_net_ids=tuple(sorted(conflicting_net_ids)), component_conflicts=tuple(sorted(component_conflicts)), ) diff --git a/inire/router/_router.py b/inire/router/_router.py index 4a993b5..90b830a 100644 --- a/inire/router/_router.py +++ b/inire/router/_router.py @@ -73,6 +73,7 @@ class _RoutingState: 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 @@ -415,6 +416,7 @@ class PathFinder: 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) @@ -425,12 +427,16 @@ class PathFinder: 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, - ) + 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, @@ -630,6 +636,7 @@ class PathFinder: 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) @@ -643,6 +650,7 @@ class PathFinder: 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( @@ -991,7 +999,11 @@ class PathFinder: return self._restore_incumbent_fallback(net_id, incumbent_fallback, guidance_seed_present) if reached_target: self.metrics.total_nets_reached_target += 1 - report = self.context.cost_evaluator.collision_engine.verify_path_details(net_id, path, include_invalid_dynamic=False).report + world = self.context.cost_evaluator.collision_engine + if search.node_limit: + report = world.verify_path_details(net_id, path, include_invalid_dynamic=False).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: @@ -1095,12 +1107,20 @@ class PathFinder: 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=self.context.options.diagnostics.capture_conflict_trace, + 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", @@ -1158,7 +1178,9 @@ class PathFinder: if not options.refinement.enabled or not state.results: return - proximity_ready = bool(options.search.node_limit) + 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 @@ -1173,22 +1195,26 @@ class PathFinder: proximity_ready = True 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) + 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) - # Defer full verification until _verify_results() so we do not - # verify the same refined path twice in one route_all() call. + 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=tuple(refined_path), + path=refined_path, reached_target=result.reached_target, - report=result.report, + 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 @@ -1199,13 +1225,16 @@ class PathFinder: report=RoutingReport(invalid_geometry=seed_error is not None, seed_error=seed_error, terminal_error=terminal_error), ) 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, - include_invalid_dynamic=False, - ) + 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) @@ -1250,7 +1279,8 @@ class PathFinder: self.metrics.reset_per_route() state = self._prepare_state(corridors, started_at=started_at) - timed_out = self._run_iterations(state, iteration_callback) + 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 @@ -1272,4 +1302,6 @@ class PathFinder: 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 diff --git a/inire/tests/test_api.py b/inire/tests/test_api.py index baed2f5..e8b0c21 100644 --- a/inire/tests/test_api.py +++ b/inire/tests/test_api.py @@ -565,6 +565,7 @@ def test_zero_search_budget_verifies_seeds_without_triangulation(mode, monkeypat assert run.results_by_net["line"].is_valid assert run.metrics.nodes_expanded == 0 + assert run.metrics.verify_path_report_calls == 1 @pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"]) @@ -578,7 +579,7 @@ def test_verify_only_retains_colliding_seeds_and_final_trace(mode, rounds, monke ) seeds = {net.net_id: PathSeed((StraightSeed(80),)) for net in nets[:2]} seeds["partial"] = PathSeed((StraightSeed(40),)) - problem = RoutingProblem((0, 0, 100, 100), nets, (box(5, 5, 8, 8),), initial_paths=seeds) + problem = RoutingProblem((0, 0, 100, 100), nets, (box(20, 77, 25, 82),), initial_paths=seeds) options = RoutingOptions( search=SearchOptions(node_limit=0), congestion=CongestionOptions(max_iterations=rounds), @@ -591,7 +592,9 @@ def test_verify_only_retains_colliding_seeds_and_final_trace(mode, rounds, monke pytest.fail("Geometry-only verification built a proximity map") monkeypatch.setattr(DangerMap, "precompute", fail_on_proximity) + callbacks = [] run = route(problem, options=options) + with_callback = route(problem, options=options, iteration_callback=lambda index, results: callbacks.append((index, results))) for net in nets[:2]: result = run.results_by_net[net.net_id] @@ -599,10 +602,24 @@ def test_verify_only_retains_colliding_seeds_and_final_trace(mode, rounds, monke assert result.outcome == "colliding" assert result.report.dynamic_collision_count == 1 assert run.results_by_net["partial"].outcome == "partial" + assert run.results_by_net["partial"].report.total_length == 40 + assert run.results_by_net["partial"].report.static_collision_count == 1 assert run.results_by_net["unseeded"].outcome == "unroutable" - assert run.conflict_trace[-1].conflict_edges == (("horizontal", "vertical"),) + iteration, restored, final = run.conflict_trace + assert (iteration.stage, restored.stage, final.stage) == ("iteration", "restored_best", "final") + assert iteration.conflict_edges == restored.conflict_edges == final.conflict_edges == (("horizontal", "vertical"),) + for traced_net in final.nets[:2]: + assert traced_net.component_conflicts + assert traced_net == next(net for net in iteration.nets if net.net_id == traced_net.net_id) + assert traced_net == next(net for net in restored.nets if net.net_id == traced_net.net_id) assert run.metrics.nodes_expanded == 0 assert run.metrics.route_iterations == 1 + assert run.metrics.verify_path_report_calls == 3 + assert run.metrics.verify_static_buffer_ops == 3 + assert run.metrics.verify_dynamic_exact_pair_checks == 2 + assert callbacks == [(0, run.results_by_net)] + assert with_callback.results_by_net == run.results_by_net + assert with_callback.metrics.verify_path_report_calls == run.metrics.verify_path_report_calls @pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"]) @@ -617,12 +634,14 @@ def test_verify_only_reports_width_incompatible_seed_segments(mode, move) -> Non topology=TopologyOptions(mode=mode), ) - results = route(problem, options=options).results_by_net + callbacks = [] + results = route(problem, options=options, iteration_callback=lambda _, current: callbacks.append(current["wide"].report)).results_by_net assert results["peer"].is_valid report = results["wide"].report assert report.invalid_geometry assert report.seed_error == f"Initial path for 'wide' segment 1 ({type(move).__name__}) needs radius at least 15, got 10" + assert callbacks == [report] def test_active_search_can_recover_from_width_incompatible_seed() -> None: @@ -1544,7 +1563,8 @@ def test_capture_conflict_trace_records_component_pairs() -> None: assert trace_by_net["vertical"].component_conflicts[0].other_component_index == 0 -def test_capture_frontier_trace_preserves_route_outputs() -> None: +@pytest.mark.parametrize("replay", [False, True]) +def test_capture_frontier_trace_preserves_route_outputs(replay) -> None: problem = RoutingProblem( bounds=(0, 0, 100, 100), nets=( @@ -1557,16 +1577,14 @@ def test_capture_frontier_trace_preserves_route_outputs() -> None: refinement=RefinementOptions(enabled=False), topology=TopologyOptions(mode="off"), ) + if replay: + problem = replace(problem, initial_paths={net.net_id: PathSeed((StraightSeed(80),)) for net in problem.nets}) + base_options = replace(base_options, search=replace(base_options.search, node_limit=0)) run_without_trace = route(problem, options=base_options) run_with_trace = route( problem, - options=RoutingOptions( - congestion=base_options.congestion, - refinement=base_options.refinement, - diagnostics=DiagnosticsOptions(capture_frontier_trace=True), - topology=base_options.topology, - ), + options=replace(base_options, diagnostics=DiagnosticsOptions(capture_frontier_trace=True)), ) assert {net_id: result.outcome for net_id, result in run_without_trace.results_by_net.items()} == { diff --git a/inire/tests/test_collision.py b/inire/tests/test_collision.py index 5d4e2c2..ee99707 100644 --- a/inire/tests/test_collision.py +++ b/inire/tests/test_collision.py @@ -332,6 +332,11 @@ def test_verify_path_details_returns_conflicting_net_ids() -> None: assert detail.report.dynamic_collision_count == 1 assert detail.conflicting_net_ids == ("netB",) + engine.remove_path("netB") + rechecked = engine.verify_path_details("netA", path_a, geometry_report=detail.report) + assert rechecked.report == engine.verify_path_geometry(path_a) + assert rechecked.conflicting_net_ids == () + def test_verify_path_details_reports_component_conflicts() -> None: engine = RoutingWorld(clearance=2.0) diff --git a/inire/tests/test_refinements.py b/inire/tests/test_refinements.py index d565eca..8832ee3 100644 --- a/inire/tests/test_refinements.py +++ b/inire/tests/test_refinements.py @@ -138,11 +138,16 @@ def test_seeded_refinement_builds_proximity_map_at_zero_search_budget(monkeypatc precompute(self, obstacles) monkeypatch.setattr(DangerMap, "precompute", track) - run = route(problem, options=options) + callbacks = [] + run = route(problem, options=options, iteration_callback=lambda _, results: callbacks.append(results["foldback"])) - assert run.results_by_net["foldback"].is_valid + result = run.results_by_net["foldback"] + assert result.is_valid assert run.metrics.refinement_candidates_accepted > 0 assert calls == [problem.static_obstacles] + assert result.as_seed() != problem.initial_paths["foldback"] + assert result.report.total_length == pytest.approx(sum(component.length for component in result.path)) + assert callbacks == [result] @pytest.mark.parametrize("mode", ["automatic", "off"])