From 0c059cc7d6135833356c8ca9d93f4acabe1e2469 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Fri, 27 Nov 2026 00:38:00 -0800 Subject: [PATCH] Share worker setup, residual preparation, and scenario capture --- inire/geometry/components.py | 7 +- inire/router/_automatic.py | 14 ++-- inire/router/_pair_local.py | 8 +- inire/router/_routing_policy.py | 20 ++++- inire/router/_stack.py | 15 ++-- inire/router/cost.py | 28 +++++-- inire/tests/example_scenarios.py | 101 ++++++------------------- scripts/diff_performance_baseline.py | 17 +---- scripts/record_performance_baseline.py | 29 +------ 9 files changed, 88 insertions(+), 151 deletions(-) diff --git a/inire/geometry/components.py b/inire/geometry/components.py index 031911c..958af15 100644 --- a/inire/geometry/components.py +++ b/inire/geometry/components.py @@ -14,7 +14,7 @@ from inire.seeds import Bend90Seed, PathSegmentSeed, SBendSeed, StraightSeed from .primitives import Port, rotation_matrix2 if TYPE_CHECKING: - from collections.abc import Sequence + from collections.abc import Iterable, Sequence from numpy.typing import NDArray @@ -25,6 +25,11 @@ BendCollisionModel = BendCollisionModelName | Polygon BendPhysicalGeometry = Literal["arc"] | Polygon +def path_within_board(path: Iterable[ComponentResult], board: Polygon) -> bool: + """Check containment of the physical geometry, including boundary contact.""" + return all(board.covers(shape) for component in path for shape in component.physical_geometry) + + def _normalize_length(value: float) -> float: return float(value) diff --git a/inire/router/_automatic.py b/inire/router/_automatic.py index 3cd0ba1..49a6c3b 100644 --- a/inire/router/_automatic.py +++ b/inire/router/_automatic.py @@ -34,7 +34,7 @@ from inire.router._routing_policy import ( _disconnected_nets, _is_short_shift, _residual_problem, - _route_residual, + _route_prepared_residual, _trial, ) from inire.router._seed_materialization import materialize_path_seed @@ -379,7 +379,8 @@ class _AutomaticRun: policy = "incumbent-residual" locks = LockPlan(retained) - run, stage = _route_residual(problem, options, locks, residual_mode="seed", run_route=partial(self._run, policy=policy)) + residual = _residual_problem(problem, locks) + run, stage = _route_prepared_residual(residual, options, locks, residual_mode="seed", run_route=partial(self._run, policy=policy)) stage = replace(stage, kind=policy, policy=policy, retry_reason="Residual terminals remain connected with the incumbents locked") trial = self._trial(run, stage) if len(trial.valid_costs) == len(problem.nets): @@ -389,7 +390,7 @@ class _AutomaticRun: dogleg = self._residual_dogleg_trial(options, _best_trial([best, trial])) if dogleg is not None: return [trial, dogleg] - joint = self._joint_lane_trial(options, locks, trial) + joint = self._joint_lane_trial(residual, options, locks, trial) if joint is not None: trials.append(replace(joint, selection="requires-layout-check")) if joint.improves_on(_best_trial([best, trial])): @@ -540,8 +541,7 @@ class _AutomaticRun: stage = RoutingStage("seed", (), run.metrics.nodes_expanded, options.search.node_limit, policy="seed-fallback") trials.append(self._trial(run, stage)) - def _joint_lane_trial(self, options: RoutingOptions, locks: LockPlan, previous: Trial) -> Trial | None: - residual = _residual_problem(self.problem, locks) + def _joint_lane_trial(self, residual: RoutingProblem, options: RoutingOptions, locks: LockPlan, previous: Trial) -> Trial | None: if len(residual.nets) < 2: return None policy = "joint-portal-lanes" @@ -560,8 +560,8 @@ class _AutomaticRun: if not corridors: return None retry = replace(options, congestion=replace(options.congestion, max_iterations=min(3, options.congestion.max_iterations))) - run, stage = _route_residual( - self.problem, retry, locks, residual_mode="seed", run_route=partial(self._run, policy=policy, corridors=corridors) + run, stage = _route_prepared_residual( + residual, retry, locks, residual_mode="seed", run_route=partial(self._run, policy=policy, corridors=corridors) ) stage = replace( stage, diff --git a/inire/router/_pair_local.py b/inire/router/_pair_local.py index 8fe23f3..11699ac 100644 --- a/inire/router/_pair_local.py +++ b/inire/router/_pair_local.py @@ -27,7 +27,6 @@ def _build_pair_local_context( lock_partial_paths: bool, ) -> AStarContext: problem = context.problem - objective = context.options.objective live_world = context.cost_evaluator.collision_engine static_obstacles = tuple(live_world.iter_static_geometries()) world = RoutingWorld(clearance=live_world.clearance, safety_zone_radius=live_world.safety_zone_radius) @@ -45,14 +44,11 @@ def _build_pair_local_context( danger_map = DangerMap(bounds=problem.bounds) danger_map.precompute(list(static_obstacles)) - evaluator = CostEvaluator( + evaluator = CostEvaluator.from_objective( world, danger_map, - unit_length_cost=objective.unit_length_cost, + context.options.objective, greedy_h_weight=context.cost_evaluator.greedy_h_weight, - bend_penalty=objective.bend_penalty, - sbend_penalty=objective.sbend_penalty, - danger_weight=objective.danger_weight, ) return AStarContext( evaluator, diff --git a/inire/router/_routing_policy.py b/inire/router/_routing_policy.py index a873ec0..2e49cb6 100644 --- a/inire/router/_routing_policy.py +++ b/inire/router/_routing_policy.py @@ -10,7 +10,7 @@ from shapely.geometry import Point from inire.constants import TOLERANCE_LINEAR from inire.geometry.collision import RoutingWorld -from inire.geometry.components import Straight +from inire.geometry.components import Straight, path_within_board from inire.geometry.primitives import port_local_coordinates from inire.model import resolve_bend_geometry from inire.results import RoutingResult, RoutingStage @@ -96,7 +96,7 @@ def _direct_paths( if net.start.r != net.target.r or forward <= 0 or lateral: continue component = Straight.generate(net.start, forward, net.width, dilation=problem.clearance / 2) - if any(not board.covers(shape) for shape in component.physical_geometry): + if not path_within_board((component,), board): continue report = world.verify_path_report(net.net_id, (component,)) if report.is_valid: @@ -204,9 +204,21 @@ def _route_residual( *, residual_mode: Literal["guide", "seed"] | None = None, run_route: RouteCall = route_once, +) -> tuple[RoutingRunResult, RoutingStage]: + return _route_prepared_residual( + _residual_problem(problem, locks), options, locks, residual_mode=residual_mode, run_route=run_route + ) + + +def _route_prepared_residual( + problem: RoutingProblem, + options: RoutingOptions, + locks: LockPlan, + *, + residual_mode: Literal["guide", "seed"] | None = None, + run_route: RouteCall = route_once, ) -> tuple[RoutingRunResult, RoutingStage]: direct = locks.direct - problem = _residual_problem(problem, locks) residual = problem.nets if not residual: mode = "off" @@ -234,7 +246,7 @@ def _trial(run: RoutingRunResult, stage: RoutingStage, board: Polygon, *, score: outside = tuple( net_id for net_id, result in run.results_by_net.items() - if result.report.out_of_bounds or any(not board.covers(shape) for shape in result.locked_geometry) + if result.report.out_of_bounds or not path_within_board(result.path, board) ) if outside: results = dict(run.results_by_net) diff --git a/inire/router/_stack.py b/inire/router/_stack.py index 69d75d4..5887e85 100644 --- a/inire/router/_stack.py +++ b/inire/router/_stack.py @@ -6,6 +6,7 @@ from typing import TYPE_CHECKING from shapely.geometry import box from inire.geometry.collision import RoutingWorld +from inire.geometry.components import path_within_board from inire.results import RoutingRunResult from inire.router._astar_types import AStarContext from inire.router._router import PathFinder @@ -46,15 +47,11 @@ def build_routing_stack(problem: RoutingProblem, options: RoutingOptions) -> Rou danger_map = DangerMap(bounds=problem.bounds) danger_map.precompute(list(problem.static_obstacles)) - objective = options.objective - evaluator = CostEvaluator( + evaluator = CostEvaluator.from_objective( world, danger_map, - unit_length_cost=objective.unit_length_cost, + options.objective, greedy_h_weight=options.search.greedy_h_weight, - bend_penalty=objective.bend_penalty, - sbend_penalty=objective.sbend_penalty, - danger_weight=objective.danger_weight, ) context = AStarContext(evaluator, problem, options) finder = PathFinder(context) @@ -84,9 +81,13 @@ def route_once( if options.topology.mode == "bundle": board = box(*problem.bounds) for result in results.values(): - if not result.is_valid or any(not board.covers(shape) for shape in result.locked_geometry): + if not result.is_valid or not path_within_board(result.path, board): 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(), diff --git a/inire/router/cost.py b/inire/router/cost.py index 1cece3b..f7f2ba0 100644 --- a/inire/router/cost.py +++ b/inire/router/cost.py @@ -70,6 +70,25 @@ class CostEvaluator: self._target_cos = 1.0 self._target_sin = 0.0 + @classmethod + def from_objective( + cls, + world: RoutingWorld, + danger_map: DangerMap | None, + objective: ObjectiveWeights, + *, + greedy_h_weight: float = 1.5, + ) -> CostEvaluator: + return cls( + world, + danger_map, + unit_length_cost=objective.unit_length_cost, + greedy_h_weight=greedy_h_weight, + bend_penalty=objective.bend_penalty, + sbend_penalty=objective.sbend_penalty, + danger_weight=objective.danger_weight, + ) + @property def default_weights(self) -> ObjectiveWeights: return self._search_weights @@ -228,11 +247,4 @@ def build_native_cost_evaluator(problem: RoutingProblem, objective: ObjectiveWei if objective.danger_weight and problem.static_obstacles: danger = DangerMap(bounds=problem.bounds) danger.precompute(list(problem.static_obstacles)) - return CostEvaluator( - RoutingWorld(clearance=problem.clearance), - danger, - unit_length_cost=objective.unit_length_cost, - bend_penalty=objective.bend_penalty, - sbend_penalty=objective.sbend_penalty, - danger_weight=objective.danger_weight, - ) + return CostEvaluator.from_objective(RoutingWorld(clearance=problem.clearance), danger, objective) diff --git a/inire/tests/example_scenarios.py b/inire/tests/example_scenarios.py index 50c811f..e28fd60 100644 --- a/inire/tests/example_scenarios.py +++ b/inire/tests/example_scenarios.py @@ -22,11 +22,13 @@ from inire import ( ) from inire.geometry.primitives import Port from inire.results import RouteMetrics, _sum_route_metrics -from inire.router._stack import build_routing_stack +from inire.router._stack import build_routing_stack, collect_worker_result from inire.tests.routing_corpus import SNAPSHOT_CASES, profile_options from inire.tests.terminal_bench_scenario import terminal_bench_options, terminal_bench_problem if TYPE_CHECKING: + from collections.abc import Iterable + from inire.router._astar_types import AStarMetrics from inire.router._router import PathFinder from inire.router.cost import CostEvaluator @@ -56,15 +58,6 @@ class ScenarioSnapshot: ) -def _summarize(results: dict[str, RoutingResult], duration_s: float) -> ScenarioOutcome: - return ( - duration_s, - len(results), - sum(1 for result in results.values() if result.is_valid), - sum(1 for result in results.values() if result.reached_target), - ) - - def _make_snapshot( name: str, results: dict[str, RoutingResult], @@ -81,21 +74,6 @@ def _make_snapshot( ) -def _make_run_result( - results: dict[str, RoutingResult], - pathfinder: PathFinder, -) -> RoutingRunResult: - return RoutingRunResult( - results_by_net=results, - metrics=pathfinder.metrics.snapshot(), - expanded_nodes=tuple(pathfinder.accumulated_expanded_nodes), - conflict_trace=tuple(pathfinder.conflict_trace), - frontier_trace=tuple(pathfinder.frontier_trace), - pre_pair_frontier_trace=pathfinder.pre_pair_frontier_trace, - iteration_trace=tuple(pathfinder.iteration_trace), - ) - - def _snapshot_worker(name: str, pathfinder: PathFinder) -> ScenarioSnapshot: start = perf_counter() results = pathfinder.route_all() @@ -111,10 +89,6 @@ def snapshot_example_01() -> ScenarioSnapshot: return _snapshot_worker("example_01_simple_route", build_routing_stack(problem, options).finder) -def run_example_01() -> ScenarioOutcome: - return snapshot_example_01().as_outcome() - - def snapshot_example_02() -> ScenarioSnapshot: problem = RoutingProblem( bounds=(0, 0, 100, 100), @@ -132,10 +106,6 @@ def snapshot_example_02() -> ScenarioSnapshot: return _snapshot_worker("example_02_congestion_resolution", build_routing_stack(problem, options).finder) -def run_example_02() -> ScenarioOutcome: - return snapshot_example_02().as_outcome() - - def snapshot_example_03() -> ScenarioSnapshot: problem_a = RoutingProblem( bounds=(0, -50, 100, 50), @@ -160,10 +130,6 @@ def snapshot_example_03() -> ScenarioSnapshot: return _make_snapshot("example_03_locked_paths", {**results_a, **results_b}, t1 - t0, combined_metrics) -def run_example_03() -> ScenarioOutcome: - return snapshot_example_03().as_outcome() - - def snapshot_example_04() -> ScenarioSnapshot: problem = RoutingProblem( bounds=(0, 0, 100, 100), @@ -179,10 +145,6 @@ def snapshot_example_04() -> ScenarioSnapshot: return _snapshot_worker("example_04_sbends_and_radii", build_routing_stack(problem, options).finder) -def run_example_04() -> ScenarioOutcome: - return snapshot_example_04().as_outcome() - - def _build_example_05_worker(diagnostics: DiagnosticsOptions) -> PathFinder: problem = RoutingProblem( bounds=(0, 0, 200, 200), @@ -204,14 +166,10 @@ def snapshot_example_05() -> ScenarioSnapshot: return _snapshot_worker("example_05_orientation_stress", _build_example_05_worker(DiagnosticsOptions())) -def run_example_05() -> ScenarioOutcome: - return snapshot_example_05().as_outcome() - - def trace_example_05() -> RoutingRunResult: pathfinder = _build_example_05_worker(DiagnosticsOptions(capture_conflict_trace=True, capture_frontier_trace=True)) results = pathfinder.route_all() - return _make_run_result(results, pathfinder) + return collect_worker_result(pathfinder, results) def snapshot_example_06() -> ScenarioSnapshot: @@ -258,10 +216,6 @@ def snapshot_example_06() -> ScenarioSnapshot: ) -def run_example_06() -> ScenarioOutcome: - return snapshot_example_06().as_outcome() - - def snapshot_example_07() -> ScenarioSnapshot: return _snapshot_example_07_variant( "example_07_large_scale_routing", @@ -389,7 +343,7 @@ def _run_example_07_variant( metrics.reset_per_route() results = pathfinder.route_all(iteration_callback=iteration_callback) - return _make_run_result(results, pathfinder) + return collect_worker_result(pathfinder, results) def _snapshot_example_07_variant( @@ -424,10 +378,6 @@ def _trace_example_07_variant( ) -def run_example_07() -> ScenarioOutcome: - return snapshot_example_07().as_outcome() - - def _build_example_08_workers() -> tuple[PathFinder, PathFinder]: net = NetSpec("standard_arc", Port(20, 20, 0), Port(100, 100, 90)) problem = RoutingProblem(bounds=(0, 0, 150, 150), nets=(net,)) @@ -460,10 +410,6 @@ def snapshot_example_08() -> ScenarioSnapshot: ) -def run_example_08() -> ScenarioOutcome: - return snapshot_example_08().as_outcome() - - def snapshot_example_09() -> ScenarioSnapshot: problem = RoutingProblem( bounds=(0, 0, 100, 100), @@ -478,10 +424,6 @@ def snapshot_example_09() -> ScenarioSnapshot: return _snapshot_worker("example_09_unroutable_best_effort", build_routing_stack(problem, options).finder) -def run_example_09() -> ScenarioOutcome: - return snapshot_example_09().as_outcome() - - def snapshot_terminal_bench_pr345() -> ScenarioSnapshot: problem = terminal_bench_problem() start = perf_counter() @@ -495,18 +437,6 @@ def _snapshot_routing_benchmark(case: BenchmarkCase) -> ScenarioSnapshot: return _make_snapshot(f"routing_benchmark_{case.name.replace('-', '_')}", run.results_by_net, perf_counter() - start, run.metrics) -SCENARIOS: tuple[tuple[str, ScenarioRun], ...] = ( - ("example_01_simple_route", run_example_01), - ("example_02_congestion_resolution", run_example_02), - ("example_03_locked_paths", run_example_03), - ("example_04_sbends_and_radii", run_example_04), - ("example_05_orientation_stress", run_example_05), - ("example_06_bend_collision_models", run_example_06), - ("example_07_large_scale_routing", run_example_07), - ("example_08_custom_bend_geometry", run_example_08), - ("example_09_unroutable_best_effort", run_example_09), -) - SCENARIO_SNAPSHOTS: tuple[tuple[str, ScenarioSnapshotRun], ...] = ( ("example_01_simple_route", snapshot_example_01), ("example_02_congestion_resolution", snapshot_example_02), @@ -519,6 +449,15 @@ SCENARIO_SNAPSHOTS: tuple[tuple[str, ScenarioSnapshotRun], ...] = ( ("example_09_unroutable_best_effort", snapshot_example_09), ) + +def _snapshot_outcome(capture: ScenarioSnapshotRun) -> ScenarioOutcome: + return capture().as_outcome() + + +SCENARIOS: tuple[tuple[str, ScenarioRun], ...] = tuple( + (name, partial(_snapshot_outcome, capture)) for name, capture in SCENARIO_SNAPSHOTS +) + PERFORMANCE_SCENARIO_SNAPSHOTS: tuple[tuple[str, ScenarioSnapshotRun], ...] = ( ("example_07_large_scale_routing_no_warm_start", snapshot_example_07_no_warm_start), ("example_07_large_scale_routing_no_warm_start_seed43", snapshot_example_07_no_warm_start_seed43), @@ -540,5 +479,13 @@ TRACE_PERFORMANCE_SCENARIO_RUNS: tuple[tuple[str, TraceScenarioRun], ...] = ( ) -def capture_all_scenario_snapshots() -> tuple[ScenarioSnapshot, ...]: - return tuple(run() for _, run in SCENARIO_SNAPSHOTS) +def capture_scenario_snapshots( + selected_scenarios: Iterable[str] | None = None, + *, + include_performance_only: bool = False, +) -> tuple[ScenarioSnapshot, ...]: + registry = SCENARIO_SNAPSHOTS + if include_performance_only: + registry += PERFORMANCE_SCENARIO_SNAPSHOTS + allowed = None if selected_scenarios is None else set(selected_scenarios) + return tuple(capture() for name, capture in registry if allowed is None or name in allowed) diff --git a/scripts/diff_performance_baseline.py b/scripts/diff_performance_baseline.py index f2b9cd6..4fd9eff 100644 --- a/scripts/diff_performance_baseline.py +++ b/scripts/diff_performance_baseline.py @@ -7,8 +7,8 @@ from dataclasses import asdict from datetime import datetime from pathlib import Path -from inire.tests.example_scenarios import PERFORMANCE_SCENARIO_SNAPSHOTS, SCENARIO_SNAPSHOTS from inire.results import RouteMetrics +from inire.tests.example_scenarios import capture_scenario_snapshots SUMMARY_KEYS = ( @@ -26,12 +26,6 @@ SUMMARY_KEYS = ( ) -def _snapshot_registry(include_performance_only: bool) -> tuple[tuple[str, object], ...]: - if not include_performance_only: - return SCENARIO_SNAPSHOTS - return SCENARIO_SNAPSHOTS + PERFORMANCE_SCENARIO_SNAPSHOTS - - def _available_metric_names() -> tuple[str, ...]: return ( "duration_s", @@ -47,13 +41,8 @@ def _current_snapshots( *, include_performance_only: bool, ) -> dict[str, dict[str, object]]: - allowed = None if selected_scenarios is None else set(selected_scenarios) - snapshots: dict[str, dict[str, object]] = {} - for name, run in _snapshot_registry(include_performance_only): - if allowed is not None and name not in allowed: - continue - snapshots[name] = asdict(run()) - return snapshots + snapshots = capture_scenario_snapshots(selected_scenarios, include_performance_only=include_performance_only) + return {snapshot.name: asdict(snapshot) for snapshot in snapshots} def _load_baseline(path: Path, selected_scenarios: tuple[str, ...] | None) -> dict[str, dict[str, object]]: diff --git a/scripts/record_performance_baseline.py b/scripts/record_performance_baseline.py index c8cb64a..6a01fcf 100644 --- a/scripts/record_performance_baseline.py +++ b/scripts/record_performance_baseline.py @@ -7,27 +7,7 @@ from dataclasses import asdict from datetime import date from pathlib import Path -from inire.tests.example_scenarios import PERFORMANCE_SCENARIO_SNAPSHOTS, SCENARIO_SNAPSHOTS - - -SUMMARY_METRICS = ( - "route_iterations", - "nets_routed", - "nodes_expanded", - "ray_cast_calls", - "moves_generated", - "moves_added", - "dynamic_tree_rebuilds", - "visibility_builds", - "congestion_check_calls", - "verify_path_report_calls", -) - - -def _snapshot_registry(include_performance_only: bool) -> tuple[tuple[str, object], ...]: - if not include_performance_only: - return SCENARIO_SNAPSHOTS - return SCENARIO_SNAPSHOTS + PERFORMANCE_SCENARIO_SNAPSHOTS +from inire.tests.example_scenarios import capture_scenario_snapshots def _build_payload( @@ -35,12 +15,7 @@ def _build_payload( *, include_performance_only: bool = False, ) -> dict[str, object]: - allowed = None if selected_scenarios is None else set(selected_scenarios) - snapshots = [] - for name, run in _snapshot_registry(include_performance_only): - if allowed is not None and name not in allowed: - continue - snapshots.append(run()) + snapshots = capture_scenario_snapshots(selected_scenarios, include_performance_only=include_performance_only) return { "generated_on": date.today().isoformat(), "generator": "scripts/record_performance_baseline.py",