inire/inire/router/_stack.py
2026-12-02 20:35:06 -08:00

184 lines
7.3 KiB
Python

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" and options.congestion.max_iterations:
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)
# Replay and one-node attempts can rely on the indexes already used for verification.
world = RoutingWorld.from_problem(problem, use_dynamic_grid=options.search.node_limit > 1)
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,
attempt_callback: Callable[[RoutingOptions], None] | None = None,
) -> 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")
if attempt_callback is not None:
attempt_callback(options)
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" and options.congestion.max_iterations:
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,
*,
attempt_callback: Callable[[RoutingOptions], None] | None = None,
) -> None:
self.callback = callback
self.attempt_callback = attempt_callback
self.iterations = 0
self.samples: list[RouteMetrics] = []
def run(
self,
problem: RoutingProblem,
*,
options: RoutingOptions,
phase_timer: PhaseTimer | None = None,
) -> RoutingRunResult:
result = route_once(
problem, options=options, iteration_callback=self.callback, phase_timer=phase_timer,
iteration_offset=self.iterations, attempt_callback=self.attempt_callback,
)
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,
attempt_callback: Callable[[RoutingOptions], None] | None = None,
selected_attempt_callback: Callable[[int], None] | None = None,
) -> RoutingRunResult:
attempts = RoutingAttempts(iteration_callback, attempt_callback=attempt_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())
):
if selected_attempt_callback is not None:
selected_attempt_callback(0)
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())
retry_won = new_count > old_count
if selected_attempt_callback is not None:
selected_attempt_callback(int(retry_won))
selected = without_guidance if retry_won else with_guidance
return replace(selected, metrics=attempts.metrics())