inire/inire/router/_stack.py

131 lines
5.1 KiB
Python

from __future__ import annotations
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 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.static_obstacles)
evaluator = CostEvaluator.from_objective(
world,
danger_map,
options.objective,
greedy_h_weight=options.search.greedy_h_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,
) -> 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")
finder = build_routing_stack(problem, options).finder
results = finder.route_all(iteration_callback=iteration_callback, phase_timer=phase_timer, corridors=corridors)
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,
)
def route_explicit(
problem: RoutingProblem,
*,
options: RoutingOptions,
iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None = None,
) -> RoutingRunResult:
start_index = 0
def notify(_iteration: int, results: dict[str, RoutingResult]) -> None:
nonlocal start_index
assert iteration_callback is not None
iteration_callback(start_index, results)
start_index += 1
callback = notify if iteration_callback is not None else None
with_guidance = route_once(problem, options=options, iteration_callback=callback)
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 = route_once(problem, options=retry, iteration_callback=callback)
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())
chosen = without_guidance if new_count > old_count else with_guidance
return replace(chosen, metrics=_sum_route_metrics((with_guidance.metrics, without_guidance.metrics)))