diff --git a/docs/architecture.md b/docs/architecture.md index b7d594b..b7de2d9 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,6 +1,6 @@ # Router architecture -An explicit routing mode runs one worker with that mode's settings. Automatic routing can run several workers with different obstacles, locks, or starting paths, then select a result. To see what a single worker receives and returns, start at [`route_once()`](../inire/router/_stack.py#L71). +An explicit mode starts one worker with that mode’s settings. Guide and seed can retry with zero guidance cost. Automatic routing can try several combinations of obstacles, locks, and starting paths. All modes use the same worker and assign iteration indices across attempts. See [`route_once()`](../inire/router/_stack.py#L65). Follow one complete run from board input through planning, verification, and plotting in [Complex-routing example 1](complex-routing-example-1.md). @@ -14,9 +14,9 @@ Follow the left column down while the number of verified nets is below the targe 2. **Try constructive planners.** Bundles assign ordered tracks through barriers. Column schedules place turns between openings. Compact planners fit short connections between constrained ports. Each produces seeds whose physical geometry the worker checks. 3. **Start with a small search budget.** Lock verified straight links and search for the remaining nets. A different lock order or a small unlocked probe can free room for a turn. Promising guide and column attempts can run first. 4. **Decide what to keep fixed.** If the remaining ports are connected, route around the locked geometry. If the locks disconnect them, pass the previously verified paths as seeds that can move. A joint retry can assign different lanes through a shared opening. If recovery stalls, seed and lattice attempts can search the whole layout. The final lattice retry can use the caller's full node limit. -5. **Select a verified layout.** Prefer more verified nets and compare cost when the verified net IDs match. A completed `incumbent-residual` trial or an improving `joint-portal-lanes` trial must pass another check with the original keepouts before it can win. Refinement can replace the selected layout only if it preserves the verified net IDs. See [the refinement handoff](../inire/router/_automatic.py#L584). +5. **Select a verified layout.** Prefer more verified nets and compare cost when the verified net IDs match. A completed `incumbent-residual` trial or an improving `joint-portal-lanes` trial must pass another check with the original keepouts before it can win. Refinement can replace the selected layout only if it preserves the verified net IDs. See [the refinement handoff](../inire/router/_automatic.py#L609). -The near-port attempt uses up to 100 nodes per search and two congestion iterations with the arc proxy. Alternate proxies use the configured iteration limit because a later shallow iteration can find a cheaper path. Wider lookahead uses up to 500 nodes per search and the configured iteration limit. Follow the caps and early exits in [the initial search trials](../inire/router/_automatic.py#L483). +The near-port attempt uses up to 100 nodes per search and two congestion iterations with the arc proxy. Alternate proxies use the configured iteration limit because a later shallow iteration can find a cheaper path. Wider lookahead uses up to 500 nodes per search and the configured iteration limit. Follow the caps and early exits in [the initial search trials](../inire/router/_automatic.py#L508). ### Example of a poor lock @@ -34,6 +34,10 @@ The near-port attempt uses up to 100 nodes per search and two congestion iterati ## Geometry and refinement +A result carries the requested and effective net specs so export can check the original width and terminal contract after heading inference. Fixed routes carry their owner and physical polygons into the same collision world used by search and verification. The world applies distinct-net clearance to fixed geometry, and planners see fixed routes alongside keepouts. [Route reuse and export](user/route-a-layout.md#reuse-an-existing-route) + +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. + 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/routing-diagnostics.md b/docs/routing-diagnostics.md index 823f960..a176866 100644 --- a/docs/routing-diagnostics.md +++ b/docs/routing-diagnostics.md @@ -30,7 +30,7 @@ Search bounds the two move caches by entries and polygon coordinates. It drops t Enable the `DiagnosticsOptions` flag for the question you want to answer. -When explicit guide or seed mode retries without guidance cost, the returned traces describe the selected attempt. Iteration numbers use the same indices as the progress callback. Work counters include both attempts. +Returned traces describe the selected attempt. Numbered entries use the same run-wide indices as progress callbacks. A timed-out iteration can consume an index without calling back. Work counters include all attempts. Reroute scheduling tracks its own effort from node expansions and uncached congestion queries. | Question | Flag and result | | --- | --- | diff --git a/docs/user/api-reference.md b/docs/user/api-reference.md index fa2b42b..93c03d2 100644 --- a/docs/user/api-reference.md +++ b/docs/user/api-reference.md @@ -8,7 +8,7 @@ Import these types from `inire`. To see how the inputs fit together in a runnabl 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. Automatic mode keeps increasing the index across attempts and 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. +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. ## Layout inputs diff --git a/inire/router/_astar_admission.py b/inire/router/_astar_admission.py index 757c461..5e2fc2f 100644 --- a/inire/router/_astar_admission.py +++ b/inire/router/_astar_admission.py @@ -235,6 +235,7 @@ def add_node( if not config.skip_congestion and ce.has_dynamic_paths(): if config.hard_congestion or not ce.clearance: if cache_key not in congestion.overlaps: + metrics.reroute_work += 1 congestion.overlaps[cache_key] = ce.check_physical_move_congestion(result, net_id).soft_overlap_count total_overlaps = congestion.overlaps[cache_key] elif ce.has_possible_move_congestion(result, net_id, congestion.presence): @@ -250,6 +251,7 @@ def add_node( total_overlaps = congestion.overlaps[cache_key] else: context.metrics.total_congestion_cache_misses += 1 + metrics.reroute_work += 1 total_overlaps = ce.check_move_congestion( result, net_id, diff --git a/inire/router/_astar_types.py b/inire/router/_astar_types.py index d32723c..c649be8 100644 --- a/inire/router/_astar_types.py +++ b/inire/router/_astar_types.py @@ -197,13 +197,14 @@ _READ_TOTALS = attrgetter(*(name for name, _ in _TOTAL_COUNTERS)) class AStarMetrics: - __slots__ = (*(name for name, _ in _TOTAL_COUNTERS), *_PER_SEARCH_COUNTERS, "last_expanded_nodes") + __slots__ = (*(name for name, _ in _TOTAL_COUNTERS), *_PER_SEARCH_COUNTERS, "last_expanded_nodes", "reroute_work") def __init__(self) -> None: self.reset_totals() self.reset_per_route() def reset_totals(self) -> None: + self.reroute_work = 0 for name, default in _TOTAL_COUNTERS: setattr(self, name, default) diff --git a/inire/router/_automatic.py b/inire/router/_automatic.py index 33c4055..1296ece 100644 --- a/inire/router/_automatic.py +++ b/inire/router/_automatic.py @@ -15,7 +15,7 @@ from shapely.geometry import box from inire.constants import TOLERANCE_LINEAR from inire.geometry.collision import RoutingWorld from inire.model import resolve_bend_geometry -from inire.results import AutomaticRoutingReport, RoutingStage, RoutingTiming, _planner_for_mode, _sum_route_metrics +from inire.results import AutomaticRoutingReport, RoutingStage, RoutingTiming, _planner_for_mode from inire.router._bundle import ordered_bundle_terminal_headings, plan_ordered_bundle from inire.router._capacity import cut_capacity, port_conflicts from inire.router._columns import column_jog_candidates, column_seed_candidates @@ -40,7 +40,7 @@ from inire.router._routing_policy import ( _trial, ) from inire.router._seed_materialization import materialize_path_seed, seed_preparation_error -from inire.router._stack import route_once +from inire.router._stack import RoutingAttempts from inire.router._topology import constrained_triangulation_available, plan_corridors from inire.router.cost import build_native_cost_evaluator, weighted_path_length from inire.seeds import SBendSeed @@ -52,7 +52,7 @@ if TYPE_CHECKING: from shapely.geometry.base import BaseGeometry from inire.model import NetSpec, RoutingOptions, RoutingProblem - from inire.results import RouteMetrics, RoutingOperation, RoutingResult, RoutingRunResult + from inire.results import RoutingOperation, RoutingResult, RoutingRunResult from inire.router._routing_policy import Trial from inire.router._topology import Corridor from inire.router.cost import CostEvaluator @@ -90,10 +90,8 @@ class _AutomaticRun: self.problem = problem self.options = options self.board = box(*problem.bounds) - self.metrics: list[RouteMetrics] = [] + self.attempts = RoutingAttempts(iteration_callback) self.timings: list[RoutingTiming] = [] - self.iteration_callback = iteration_callback - self.callback_index = 0 self.cost_pass_performed = False self.evaluator: CostEvaluator | None = None weights = options.topology.automatic_length_weights @@ -130,23 +128,15 @@ class _AutomaticRun: policy: str | None = None, corridors: dict[str, tuple[Corridor, ...]] | None = None, ) -> RoutingRunResult: - def notify(_iteration: int, results: dict[str, RoutingResult]) -> None: - assert self.iteration_callback is not None - self.iteration_callback(self.callback_index, results) - self.callback_index += 1 - mode = options.topology.mode time_operation = partial(self._time, planner=planner or _planner_for_mode(mode), mode=mode, policy=policy) with time_operation(operation): - run = route_once( + return self.attempts.run( problem, options=options, - iteration_callback=notify if self.iteration_callback else None, phase_timer=time_operation, corridors=corridors, ) - self.metrics.append(run.metrics) - return run def _selection_cost(self, result: RoutingResult) -> float: if not self.options.search.node_limit: @@ -684,7 +674,7 @@ class _AutomaticRun: self._lattice_fallback(trials, worker, "Constrained triangulation is unavailable") refinement_choice = self._refine(trials) best = refinement_choice or _best_trial(trials) - metrics = _sum_route_metrics(self.metrics) + metrics = self.attempts.metrics() report = AutomaticRoutingReport( tuple(trial.stage for trial in trials), next(i for i, trial in enumerate(trials) if trial is best), diff --git a/inire/router/_router.py b/inire/router/_router.py index 3e64bb7..02a5a8b 100644 --- a/inire/router/_router.py +++ b/inire/router/_router.py @@ -115,6 +115,7 @@ class PathFinder: "pre_pair_frontier_trace", "iteration_trace", "topology_report", + "iteration_offset", ) def __init__( @@ -135,6 +136,7 @@ class PathFinder: 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}")) @@ -1008,6 +1010,7 @@ class PathFinder: 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, @@ -1028,7 +1031,7 @@ class PathFinder: if self._expired(state): break - work_before = self.metrics.total_nodes_expanded + self.metrics.total_congestion_check_calls + work_before = self.metrics.reroute_work if capture_attempts: attempt_before = self._capture_metric_totals(_ATTEMPT_TRACE_TOTALS) node_limit_override = None @@ -1044,7 +1047,7 @@ class PathFinder: incumbent_fallback=incumbent_fallback, ) state.results[net_id] = result - work_after = self.metrics.total_nodes_expanded + self.metrics.total_congestion_check_calls + 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) @@ -1060,7 +1063,7 @@ class PathFinder: if diagnostics.capture_pre_pair_frontier_trace: self._update_pre_pair_candidate( state, - iteration=iteration, + iteration=trace_iteration, reroute_net_ids=reroute_net_ids, routed_net_ids=routed_net_ids, attempt_traces=attempt_traces, @@ -1070,11 +1073,11 @@ class PathFinder: 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) + iteration_trace_entry(trace_iteration, iteration_penalty, routed_net_ids, review, deltas, attempt_traces) ) if iteration_callback and not state.timed_out: - iteration_callback(iteration, dict(state.results)) + iteration_callback(trace_iteration, dict(state.results)) return review def _reverify_iteration_results(self, state: _RoutingState) -> _IterationReview: @@ -1087,7 +1090,7 @@ class PathFinder: self._capture_conflict_trace_entry( state, stage="iteration", - iteration=self.metrics.total_route_iterations - 1, + iteration=self.iteration_offset + self.metrics.total_route_iterations - 1, results=state.results, details_by_net=details_by_net, review=review, @@ -1219,7 +1222,9 @@ class PathFinder: 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 = [] diff --git a/inire/router/_search.py b/inire/router/_search.py index 68a919f..c0a9650 100644 --- a/inire/router/_search.py +++ b/inire/router/_search.py @@ -129,6 +129,7 @@ def route_astar( nodes_expanded += 1 metrics.total_nodes_expanded += 1 + metrics.reroute_work += 1 metrics.nodes_expanded += 1 if current.port == target: diff --git a/inire/router/_stack.py b/inire/router/_stack.py index f9fbc76..21f1d7d 100644 --- a/inire/router/_stack.py +++ b/inire/router/_stack.py @@ -14,7 +14,7 @@ if TYPE_CHECKING: from collections.abc import Callable from inire.model import RoutingOptions, RoutingProblem - from inire.results import RoutingResult + from inire.results import RouteMetrics, RoutingResult from inire.router._router import PhaseTimer from inire.router._topology import Corridor from inire.router.danger_map import DangerMap @@ -69,6 +69,7 @@ def route_once( iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None = None, phase_timer: PhaseTimer | None = None, corridors: dict[str, tuple[Corridor, ...]] | None = None, + iteration_offset: int = 0, ) -> RoutingRunResult: """Run one explicitly selected routing mode and capture its diagnostics.""" if options.topology.mode == "automatic": @@ -86,7 +87,9 @@ def route_once( iteration_callback(iteration, attach_effective(results)) callback = notify if iteration_callback is not None else None - results = finder.route_all(iteration_callback=callback, phase_timer=phase_timer, corridors=corridors, started_at=started_at) + results = finder.route_all( + iteration_callback=callback, phase_timer=phase_timer, corridors=corridors, started_at=started_at, iteration_offset=iteration_offset, + ) results = attach_effective(results) if options.topology.mode == "bundle": for result in results.values(): @@ -109,13 +112,42 @@ def collect_worker_result(finder: PathFinder, results: dict[str, RoutingResult]) ) +class RoutingAttempts: + """Coordinate workers without retaining diagnostic data from discarded runs.""" + + def __init__(self, callback: Callable[[int, dict[str, RoutingResult]], None] | None) -> None: + self.callback = callback + self.iterations = 0 + self.samples: list[RouteMetrics] = [] + + def run( + self, + problem: RoutingProblem, + *, + options: RoutingOptions, + phase_timer: PhaseTimer | None = None, + corridors: dict[str, tuple[Corridor, ...]] | None = None, + ) -> RoutingRunResult: + result = route_once( + problem, options=options, iteration_callback=self.callback, phase_timer=phase_timer, + corridors=corridors, iteration_offset=self.iterations, + ) + self.iterations += result.metrics.route_iterations + self.samples.append(result.metrics) + return result + + def metrics(self) -> RouteMetrics: + return _sum_route_metrics(self.samples) + + def route_explicit( problem: RoutingProblem, *, options: RoutingOptions, iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None = None, ) -> RoutingRunResult: - with_guidance = route_once(problem, options=options, iteration_callback=iteration_callback) + attempts = RoutingAttempts(iteration_callback) + with_guidance = attempts.run(problem, options=options) topology = options.topology if ( topology.mode not in ("guide", "seed") or not topology.guide_strength @@ -129,26 +161,8 @@ def route_explicit( options, topology=replace(topology, guide_strength=0.0), congestion=replace(options.congestion, max_iterations=1), ) - offset = with_guidance.metrics.route_iterations - - def notify(iteration: int, results: dict[str, RoutingResult]) -> None: - assert iteration_callback is not None - iteration_callback(offset + iteration, results) - - without_guidance = route_once(problem, options=retry, iteration_callback=notify if iteration_callback is not None else None) + without_guidance = attempts.run(problem, options=retry) old_count = sum(result.is_valid for result in with_guidance.results_by_net.values()) new_count = sum(result.is_valid for result in without_guidance.results_by_net.values()) - metrics = _sum_route_metrics((with_guidance.metrics, without_guidance.metrics)) - if new_count <= old_count: - return replace(with_guidance, metrics=metrics) - - pre_pair = without_guidance.pre_pair_frontier_trace - return replace( - without_guidance, metrics=metrics, - iteration_trace=tuple(replace(entry, iteration=entry.iteration + offset) for entry in without_guidance.iteration_trace), - conflict_trace=tuple( - replace(entry, iteration=entry.iteration + offset) if entry.iteration is not None else entry - for entry in without_guidance.conflict_trace - ), - pre_pair_frontier_trace=replace(pre_pair, iteration=pre_pair.iteration + offset) if pre_pair is not None else None, - ) + selected = without_guidance if new_count > old_count else with_guidance + return replace(selected, metrics=attempts.metrics()) diff --git a/inire/tests/test_api.py b/inire/tests/test_api.py index b70b955..59c001b 100644 --- a/inire/tests/test_api.py +++ b/inire/tests/test_api.py @@ -33,6 +33,7 @@ from inire.geometry.collision import RoutingWorld from inire.results import RoutingReport, RoutingResult from inire.router._astar_types import AStarContext from inire.router._router import PathFinder, _IterationReview +from inire.router._stack import RoutingAttempts from inire.router.cost import CostEvaluator from inire.router.danger_map import DangerMap def test_root_module_exports_only_stable_surface() -> None: @@ -1659,6 +1660,37 @@ def test_reverify_iterations_limit_late_reroutes_to_conflicting_nets(monkeypatch assert results["netC"].reached_target +def test_routing_attempts_reserve_an_index_for_a_timed_out_worker(monkeypatch) -> None: + net = NetSpec("track", Port(10, 20, 0), Port(90, 20, 0)) + problem = RoutingProblem( + (0, 0, 100, 50), (net,), initial_paths={net.net_id: PathSeed((StraightSeed(80),))}, + ) + options = RoutingOptions( + search=SearchOptions(node_limit=0), + topology=TopologyOptions(mode="off"), + diagnostics=DiagnosticsOptions(capture_iteration_trace=True, capture_conflict_trace=True), + ) + callbacks = [] + + def expired(finder, state): + if finder.metrics.total_route_iterations: + state.timed_out = True + finder.metrics.total_timeout_events = 1 + return state.timed_out + + attempts = RoutingAttempts(lambda index, _: callbacks.append(index)) + with monkeypatch.context() as patch: + patch.setattr(PathFinder, "_expired", expired) + timed_out = attempts.run(problem, options=options) + selected = attempts.run(problem, options=options) + + assert timed_out.metrics.timeout_events == 1 + assert attempts.metrics().route_iterations == 2 + assert callbacks == [1] + assert [entry.iteration for entry in selected.iteration_trace] == [1] + assert [entry.iteration for entry in selected.conflict_trace if entry.stage == "iteration"] == [1] + + def test_run_iteration_orders_subset_reroutes_by_recent_work(monkeypatch: pytest.MonkeyPatch) -> None: problem = RoutingProblem( bounds=(0, 0, 100, 100), @@ -1679,10 +1711,11 @@ def test_run_iteration_orders_subset_reroutes_by_recent_work(monkeypatch: pytest route_order: list[str] = [] def fake_route_net_once(self, state, iteration, net_id, *, node_limit_override=None, incumbent_fallback=None): - _ = self _ = state _ = iteration route_order.append(net_id) + self.metrics.reroute_work += 200 if net_id == "netA" else 20 + self.metrics.total_congestion_check_calls += 1000 if net_id == "netB" else 0 assert node_limit_override is None assert incumbent_fallback is None return RoutingResult(net_id=net_id, path=(), reached_target=False), False @@ -1704,6 +1737,9 @@ def test_run_iteration_orders_subset_reroutes_by_recent_work(monkeypatch: pytest assert review is not None assert route_order == ["netB", "netA"] + assert state.recent_attempt_work == {"netA": 200, "netB": 20} + pathfinder._run_iteration(state, 2, {"netA", "netB"}, None) + assert route_order == ["netB", "netA", "netB", "netA"] def test_run_iteration_caps_two_heaviest_late_phase_nets(monkeypatch: pytest.MonkeyPatch) -> None: diff --git a/inire/tests/test_terminal_bench.py b/inire/tests/test_terminal_bench.py index efd68af..841999e 100644 --- a/inire/tests/test_terminal_bench.py +++ b/inire/tests/test_terminal_bench.py @@ -7,7 +7,7 @@ from shapely import union_all from shapely.affinity import translate from shapely.geometry import box -from inire import Bend90Seed, Port, SBendSeed, TopologyOptions, route +from inire import Bend90Seed, DiagnosticsOptions, Port, SBendSeed, TopologyOptions, route from inire.constants import TOLERANCE_LINEAR from inire.layout import _check_export_net from inire.router._waypoints import export_waypoints @@ -142,9 +142,13 @@ def test_automatic_constructs_bundle_without_triangulation(unsupported, monkeypa else: monkeypatch.setattr(shapely, "geos_version", (3, 9, 0)) base = terminal_bench_options(node_limit=100, max_iterations=1) - options = replace(base, topology=TopologyOptions(infer_terminal_headings=True)) - - run = route(terminal_bench_problem(), options=options) + options = replace( + base, topology=TopologyOptions(infer_terminal_headings=True), diagnostics=DiagnosticsOptions(capture_iteration_trace=True), + ) + callbacks = [] + run = route(terminal_bench_problem(), options=options, iteration_callback=lambda index, _: callbacks.append(index)) + assert len(callbacks) >= 2 + assert [entry.iteration for entry in run.iteration_trace] == callbacks[-1:] assert run.automatic is not None assert len(run.automatic.verified_net_ids) == 9