from __future__ import annotations import time from dataclasses import dataclass, replace from typing import TYPE_CHECKING from inire.geometry.collision import RoutingWorld from inire.results import RoutingRunResult, _sum_route_metrics from inire.router._astar_types import AStarContext from inire.router._router import PathFinder from inire.router.cost import CostEvaluator, proximity_map if TYPE_CHECKING: from collections.abc import Callable from inire.model import RoutingOptions, RoutingProblem 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 @dataclass(frozen=True, slots=True) class RoutingStack: world: RoutingWorld danger_map: DangerMap evaluator: CostEvaluator context: AStarContext finder: PathFinder def build_routing_stack(problem: RoutingProblem, options: RoutingOptions) -> RoutingStack: if options.topology.mode == "bundle": from inire.router._bundle import plan_ordered_bundle # noqa: PLC0415 problem = plan_ordered_bundle(problem, options.search, infer_terminal_headings=options.topology.infer_terminal_headings) world = RoutingWorld.from_problem(problem) danger_map = proximity_map(problem, options.search.proximity_range) refinement = options.refinement if options.search.node_limit > 0 and options.congestion.max_iterations > 0 and ( options.objective.danger_weight or (refinement.enabled and refinement.objective is not None and refinement.objective.danger_weight) ): danger_map.precompute(problem._blocking_polygons) evaluator = CostEvaluator.from_objective( world, danger_map, options.objective, greedy_h_weight=options.search.greedy_h_weight, distance_heuristic_weight=options.search.distance_heuristic_weight, ) context = AStarContext(evaluator, problem, options) finder = PathFinder(context) return RoutingStack( world=world, danger_map=danger_map, evaluator=evaluator, context=context, finder=finder, ) def route_once( problem: RoutingProblem, *, options: RoutingOptions, 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": raise ValueError("A single routing attempt requires an explicit planner mode") started_at = time.monotonic() finder = build_routing_stack(problem, options).finder effective = {net.net_id: net for net in finder.context.problem.nets} def attach_effective(results: dict[str, RoutingResult]) -> dict[str, RoutingResult]: return {key: replace(result, effective_net=effective[key]) for key, result in results.items()} def notify(iteration: int, results: dict[str, RoutingResult]) -> None: assert iteration_callback is not None 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, iteration_offset=iteration_offset, ) results = attach_effective(results) if options.topology.mode == "bundle": for result in results.values(): if not result.is_valid: raise ValueError(f"Bundle schedule failed geometric verification for {result.net_id}") return collect_worker_result(finder, results) def collect_worker_result(finder: PathFinder, results: dict[str, RoutingResult]) -> RoutingRunResult: return RoutingRunResult( results_by_net=results, metrics=finder.metrics.snapshot(), expanded_nodes=tuple(finder.accumulated_expanded_nodes), conflict_trace=tuple(finder.conflict_trace), frontier_trace=tuple(finder.frontier_trace), pre_pair_frontier_trace=finder.pre_pair_frontier_trace, iteration_trace=tuple(finder.iteration_trace), topology=finder.topology_report, ) 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: 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 or not options.search.node_limit or options.congestion.max_iterations < 2 or with_guidance.metrics.timeout_events or not with_guidance.topology or not with_guidance.topology.corridor_counts or all(result.is_valid for result in with_guidance.results_by_net.values()) ): return with_guidance retry = replace( options, topology=replace(topology, guide_strength=0.0), congestion=replace(options.congestion, max_iterations=1), ) 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()) selected = without_guidance if new_count > old_count else with_guidance return replace(selected, metrics=attempts.metrics())