From 6608e18ef53d760396584d4eab346749c1faa9b1 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Thu, 26 Nov 2026 23:00:23 -0800 Subject: [PATCH] Build traces on demand and share routing fixture setup --- archive/routing/performance.md | 14 +- archive/routing/performance_baseline.json | 120 +++---- inire/router/_automatic.py | 18 +- inire/router/_router.py | 36 +- inire/router/cost.py | 21 +- inire/tests/example_scenarios.py | 392 +++++++--------------- inire/tests/routing_corpus.py | 19 +- inire/tests/test_api.py | 9 +- inire/tests/test_example_regressions.py | 37 +- 9 files changed, 237 insertions(+), 429 deletions(-) diff --git a/archive/routing/performance.md b/archive/routing/performance.md index 0a54430..c0673a0 100644 --- a/archive/routing/performance.md +++ b/archive/routing/performance.md @@ -8,13 +8,13 @@ Use `scripts/diff_performance_baseline.py` to compare a fresh run against that s | Scenario | Duration (s) | Total | Valid | Reached | Iter | Nets Routed | Nodes | Ray Casts | Moves Gen | Moves Added | Dyn Tree | Visibility Builds | Congestion Checks | Verify Calls | | :-- | --: | --: | --: | --: | --: | --: | --: | --: | --: | --: | --: | --: | --: | --: | | example_01_simple_route | 0.0043 | 1 | 1 | 1 | 1 | 1 | 2 | 10 | 11 | 7 | 0 | 0 | 0 | 4 | -| example_02_congestion_resolution | 0.2536 | 3 | 3 | 3 | 1 | 3 | 366 | 1164 | 1413 | 668 | 0 | 0 | 0 | 16 | -| example_03_locked_paths | 0.1450 | 2 | 2 | 2 | 2 | 2 | 191 | 657 | 904 | 307 | 0 | 0 | 0 | 10 | -| example_04_sbends_and_radii | 0.0217 | 2 | 2 | 2 | 1 | 2 | 15 | 70 | 123 | 65 | 0 | 0 | 0 | 8 | -| example_05_orientation_stress | 0.1859 | 3 | 3 | 3 | 2 | 5 | 297 | 1274 | 1680 | 689 | 0 | 0 | 146 | 17 | -| example_06_bend_collision_models | 0.1723 | 3 | 3 | 3 | 3 | 3 | 240 | 682 | 1026 | 629 | 0 | 0 | 0 | 12 | -| example_07_large_scale_routing | 0.1860 | 10 | 10 | 10 | 1 | 10 | 78 | 383 | 372 | 227 | 0 | 0 | 0 | 40 | -| example_08_custom_bend_geometry | 0.0152 | 2 | 2 | 2 | 2 | 2 | 18 | 56 | 78 | 56 | 0 | 0 | 0 | 8 | +| example_02_congestion_resolution | 0.2541 | 3 | 3 | 3 | 1 | 3 | 366 | 1164 | 1413 | 668 | 0 | 0 | 0 | 16 | +| example_03_locked_paths | 0.1476 | 2 | 2 | 2 | 2 | 2 | 191 | 657 | 904 | 307 | 0 | 0 | 0 | 10 | +| example_04_sbends_and_radii | 0.0222 | 2 | 2 | 2 | 1 | 2 | 15 | 70 | 123 | 65 | 0 | 0 | 0 | 8 | +| example_05_orientation_stress | 0.1878 | 3 | 3 | 3 | 2 | 5 | 284 | 1237 | 1617 | 673 | 0 | 0 | 151 | 17 | +| example_06_bend_collision_models | 0.1732 | 3 | 3 | 3 | 3 | 3 | 240 | 682 | 1026 | 629 | 0 | 0 | 0 | 12 | +| example_07_large_scale_routing | 0.1869 | 10 | 10 | 10 | 1 | 10 | 78 | 383 | 372 | 227 | 0 | 0 | 0 | 40 | +| example_08_custom_bend_geometry | 0.0154 | 2 | 2 | 2 | 2 | 2 | 18 | 56 | 78 | 56 | 0 | 0 | 0 | 8 | | example_09_unroutable_best_effort | 0.0053 | 1 | 0 | 0 | 1 | 1 | 3 | 13 | 16 | 10 | 0 | 0 | 0 | 1 | ## Full Counter Set diff --git a/archive/routing/performance_baseline.json b/archive/routing/performance_baseline.json index 7076989..698456a 100644 --- a/archive/routing/performance_baseline.json +++ b/archive/routing/performance_baseline.json @@ -3,7 +3,7 @@ "generator": "scripts/record_performance_baseline.py", "scenarios": [ { - "duration_s": 0.004315305966883898, + "duration_s": 0.004303620080463588, "metrics": { "congestion_cache_hits": 0, "congestion_cache_misses": 0, @@ -87,7 +87,7 @@ "refinement_windows_considered": 0, "route_iterations": 1, "score_component_calls": 11, - "score_component_total_ns": 19890, + "score_component_total_ns": 16362, "static_net_tree_rebuilds": 1, "static_raw_tree_rebuilds": 0, "static_safe_cache_hits": 1, @@ -117,7 +117,7 @@ "valid_results": 1 }, { - "duration_s": 0.25360398599877954, + "duration_s": 0.2540899380110204, "metrics": { "congestion_cache_hits": 0, "congestion_cache_misses": 0, @@ -201,7 +201,7 @@ "refinement_windows_considered": 4, "route_iterations": 1, "score_component_calls": 1088, - "score_component_total_ns": 1145758, + "score_component_total_ns": 1136950, "static_net_tree_rebuilds": 3, "static_raw_tree_rebuilds": 0, "static_safe_cache_hits": 1, @@ -231,7 +231,7 @@ "valid_results": 3 }, { - "duration_s": 0.14500006497837603, + "duration_s": 0.14755904604680836, "metrics": { "congestion_cache_hits": 0, "congestion_cache_misses": 0, @@ -310,19 +310,19 @@ "refinement_candidates_accepted": 1, "refinement_candidates_built": 1, "refinement_candidates_verified": 1, - "refinement_dynamic_bounds_checked": 2, + "refinement_dynamic_bounds_checked": 0, "refinement_static_bounds_checked": 2, "refinement_windows_considered": 2, "route_iterations": 2, "score_component_calls": 510, - "score_component_total_ns": 545847, + "score_component_total_ns": 550707, "static_net_tree_rebuilds": 2, "static_raw_tree_rebuilds": 1, "static_safe_cache_hits": 1, "static_tree_rebuilds": 1, "timeout_events": 0, - "verify_dynamic_candidate_nets": 8, - "verify_dynamic_exact_pair_checks": 8, + "verify_dynamic_candidate_nets": 0, + "verify_dynamic_exact_pair_checks": 0, "verify_path_report_calls": 10, "verify_static_buffer_ops": 48, "visibility_builds": 0, @@ -345,7 +345,7 @@ "valid_results": 2 }, { - "duration_s": 0.021677320008166134, + "duration_s": 0.022167235030792654, "metrics": { "congestion_cache_hits": 0, "congestion_cache_misses": 0, @@ -429,7 +429,7 @@ "refinement_windows_considered": 0, "route_iterations": 1, "score_component_calls": 90, - "score_component_total_ns": 94482, + "score_component_total_ns": 98717, "static_net_tree_rebuilds": 2, "static_raw_tree_rebuilds": 0, "static_safe_cache_hits": 1, @@ -459,28 +459,28 @@ "valid_results": 2 }, { - "duration_s": 0.18591969890985638, + "duration_s": 0.18780142499599606, "metrics": { - "congestion_cache_hits": 3, - "congestion_cache_misses": 146, - "congestion_candidate_ids": 32, - "congestion_candidate_nets": 23, - "congestion_candidate_precheck_hits": 129, - "congestion_candidate_precheck_misses": 20, + "congestion_cache_hits": 1, + "congestion_cache_misses": 151, + "congestion_candidate_ids": 19, + "congestion_candidate_nets": 15, + "congestion_candidate_precheck_hits": 133, + "congestion_candidate_precheck_misses": 19, "congestion_candidate_precheck_skips": 0, - "congestion_check_calls": 146, - "congestion_exact_pair_checks": 30, - "congestion_grid_net_cache_hits": 16, - "congestion_grid_net_cache_misses": 26, - "congestion_grid_span_cache_hits": 15, - "congestion_grid_span_cache_misses": 7, + "congestion_check_calls": 151, + "congestion_exact_pair_checks": 18, + "congestion_grid_net_cache_hits": 12, + "congestion_grid_net_cache_misses": 22, + "congestion_grid_span_cache_hits": 11, + "congestion_grid_span_cache_misses": 4, "congestion_lazy_requeues": 0, "congestion_lazy_resolutions": 0, - "congestion_net_envelope_cache_hits": 127, - "congestion_net_envelope_cache_misses": 39, - "congestion_presence_cache_hits": 196, - "congestion_presence_cache_misses": 27, - "congestion_presence_skips": 74, + "congestion_net_envelope_cache_hits": 133, + "congestion_net_envelope_cache_misses": 37, + "congestion_presence_cache_hits": 181, + "congestion_presence_cache_misses": 26, + "congestion_presence_skips": 55, "danger_map_cache_hits": 0, "danger_map_cache_misses": 0, "danger_map_lookup_calls": 0, @@ -490,12 +490,12 @@ "dynamic_path_objects_added": 48, "dynamic_path_objects_removed": 36, "dynamic_tree_rebuilds": 0, - "guidance_bonus_applied": 562.5, - "guidance_bonus_applied_bend90": 500.0, + "guidance_bonus_applied": 100.0, + "guidance_bonus_applied_bend90": 87.5, "guidance_bonus_applied_sbend": 0.0, - "guidance_bonus_applied_straight": 62.5, - "guidance_match_moves": 9, - "guidance_match_moves_bend90": 8, + "guidance_bonus_applied_straight": 12.5, + "guidance_match_moves": 8, + "guidance_match_moves_bend90": 7, "guidance_match_moves_sbend": 0, "guidance_match_moves_straight": 1, "hard_collision_cache_hits": 0, @@ -505,29 +505,29 @@ "iteration_reverify_calls": 2, "late_phase_capped_fallbacks": 0, "late_phase_capped_nets": 0, - "move_cache_abs_hits": 374, - "move_cache_abs_misses": 1306, - "move_cache_rel_hits": 1204, + "move_cache_abs_hits": 249, + "move_cache_abs_misses": 1368, + "move_cache_rel_hits": 1266, "move_cache_rel_misses": 102, - "moves_added": 689, - "moves_generated": 1680, + "moves_added": 673, + "moves_generated": 1617, "nets_carried_forward": 1, "nets_reached_target": 5, "nets_routed": 5, - "nodes_expanded": 297, + "nodes_expanded": 284, "pair_local_search_accepts": 0, "pair_local_search_attempts": 0, "pair_local_search_nodes_expanded": 0, "pair_local_search_pairs_considered": 0, "path_cost_calls": 2, - "pruned_closed_set": 159, - "pruned_cost": 533, + "pruned_closed_set": 140, + "pruned_cost": 505, "pruned_hard_collision": 14, - "ray_cast_calls": 1274, - "ray_cast_calls_expand_forward": 292, + "ray_cast_calls": 1237, + "ray_cast_calls_expand_forward": 279, "ray_cast_calls_expand_snap": 2, "ray_cast_calls_other": 0, - "ray_cast_calls_straight_static": 971, + "ray_cast_calls_straight_static": 947, "ray_cast_calls_visibility_build": 0, "ray_cast_calls_visibility_query": 0, "ray_cast_calls_visibility_tangent": 9, @@ -542,11 +542,11 @@ "refinement_static_bounds_checked": 0, "refinement_windows_considered": 0, "route_iterations": 2, - "score_component_calls": 1234, - "score_component_total_ns": 1189711, + "score_component_calls": 1190, + "score_component_total_ns": 1157917, "static_net_tree_rebuilds": 3, "static_raw_tree_rebuilds": 0, - "static_safe_cache_hits": 8, + "static_safe_cache_hits": 2, "static_tree_rebuilds": 1, "timeout_events": 0, "verify_dynamic_candidate_nets": 8, @@ -563,7 +563,7 @@ "visibility_point_queries": 0, "visibility_tangent_candidate_corner_checks": 70, "visibility_tangent_candidate_ray_tests": 9, - "visibility_tangent_candidate_scans": 292, + "visibility_tangent_candidate_scans": 279, "warm_start_paths_built": 2, "warm_start_paths_used": 2 }, @@ -573,7 +573,7 @@ "valid_results": 3 }, { - "duration_s": 0.1722618379862979, + "duration_s": 0.17324819299392402, "metrics": { "congestion_cache_hits": 0, "congestion_cache_misses": 0, @@ -599,7 +599,7 @@ "danger_map_cache_misses": 731, "danger_map_lookup_calls": 1914, "danger_map_query_calls": 731, - "danger_map_total_ns": 18541396, + "danger_map_total_ns": 18539700, "dynamic_grid_rebuilds": 0, "dynamic_path_objects_added": 54, "dynamic_path_objects_removed": 36, @@ -657,7 +657,7 @@ "refinement_windows_considered": 0, "route_iterations": 3, "score_component_calls": 842, - "score_component_total_ns": 20820878, + "score_component_total_ns": 20771160, "static_net_tree_rebuilds": 3, "static_raw_tree_rebuilds": 3, "static_safe_cache_hits": 141, @@ -687,7 +687,7 @@ "valid_results": 3 }, { - "duration_s": 0.18596431298647076, + "duration_s": 0.18685018795076758, "metrics": { "congestion_cache_hits": 0, "congestion_cache_misses": 0, @@ -713,7 +713,7 @@ "danger_map_cache_misses": 448, "danger_map_lookup_calls": 681, "danger_map_query_calls": 448, - "danger_map_total_ns": 10931551, + "danger_map_total_ns": 10856837, "dynamic_grid_rebuilds": 0, "dynamic_path_objects_added": 132, "dynamic_path_objects_removed": 88, @@ -771,7 +771,7 @@ "refinement_windows_considered": 0, "route_iterations": 1, "score_component_calls": 291, - "score_component_total_ns": 11785678, + "score_component_total_ns": 11698395, "static_net_tree_rebuilds": 10, "static_raw_tree_rebuilds": 1, "static_safe_cache_hits": 6, @@ -801,7 +801,7 @@ "valid_results": 10 }, { - "duration_s": 0.015218257089145482, + "duration_s": 0.0154108009301126, "metrics": { "congestion_cache_hits": 0, "congestion_cache_misses": 0, @@ -885,7 +885,7 @@ "refinement_windows_considered": 0, "route_iterations": 2, "score_component_calls": 72, - "score_component_total_ns": 84457, + "score_component_total_ns": 82036, "static_net_tree_rebuilds": 2, "static_raw_tree_rebuilds": 0, "static_safe_cache_hits": 2, @@ -915,7 +915,7 @@ "valid_results": 2 }, { - "duration_s": 0.005253698094747961, + "duration_s": 0.005300503107719123, "metrics": { "congestion_cache_hits": 0, "congestion_cache_misses": 0, @@ -941,7 +941,7 @@ "danger_map_cache_misses": 20, "danger_map_lookup_calls": 30, "danger_map_query_calls": 20, - "danger_map_total_ns": 504814, + "danger_map_total_ns": 510754, "dynamic_grid_rebuilds": 0, "dynamic_path_objects_added": 2, "dynamic_path_objects_removed": 1, @@ -999,7 +999,7 @@ "refinement_windows_considered": 0, "route_iterations": 1, "score_component_calls": 14, - "score_component_total_ns": 543596, + "score_component_total_ns": 551521, "static_net_tree_rebuilds": 1, "static_raw_tree_rebuilds": 1, "static_safe_cache_hits": 0, diff --git a/inire/router/_automatic.py b/inire/router/_automatic.py index 6002a22..5507b28 100644 --- a/inire/router/_automatic.py +++ b/inire/router/_automatic.py @@ -40,8 +40,7 @@ from inire.router._routing_policy import ( from inire.router._seed_materialization import materialize_path_seed from inire.router._stack import route_once from inire.router._topology import plan_corridors -from inire.router.cost import CostEvaluator, weighted_path_length -from inire.router.danger_map import DangerMap +from inire.router.cost import build_native_cost_evaluator, weighted_path_length from inire.seeds import SBendSeed if TYPE_CHECKING: @@ -54,6 +53,7 @@ if TYPE_CHECKING: from inire.results import RouteMetrics, RoutingOperation, RoutingResult, RoutingRunResult from inire.router._routing_policy import Trial from inire.router._topology import Corridor + from inire.router.cost import CostEvaluator from inire.seeds import PathSeed @@ -148,19 +148,7 @@ class _AutomaticRun: if self.length_weights is not None: return weighted_path_length(result.path, self.length_weights) if self.evaluator is None: - objective = self.options.objective - danger = None - if objective.danger_weight and self.problem.static_obstacles: - danger = DangerMap(bounds=self.problem.bounds) - danger.precompute(list(self.problem.static_obstacles)) - self.evaluator = CostEvaluator( - RoutingWorld(clearance=self.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, - ) + self.evaluator = build_native_cost_evaluator(self.problem, self.options.objective) return self.evaluator.path_cost(result.path[0].start_port, result.path) def _trial(self, run: RoutingRunResult, stage: RoutingStage) -> Trial: diff --git a/inire/router/_router.py b/inire/router/_router.py index 31bf5a0..617cff2 100644 --- a/inire/router/_router.py +++ b/inire/router/_router.py @@ -998,6 +998,7 @@ class PathFinder: iteration_before = {} attempt_traces: list[IterationNetAttemptTrace] = [] attempt_work: dict[str, int] = {} + capture_attempts = diagnostics.capture_iteration_trace or diagnostics.capture_pre_pair_frontier_trace if diagnostics.capture_iteration_trace: iteration_before = self._capture_metric_totals(_ITERATION_TRACE_TOTALS) @@ -1006,7 +1007,9 @@ class PathFinder: self.metrics.total_timeout_events += 1 return None - attempt_before = self._capture_metric_totals(_ATTEMPT_TRACE_TOTALS) + work_before = self.metrics.total_nodes_expanded + self.metrics.total_congestion_check_calls + if capture_attempts: + attempt_before = self._capture_metric_totals(_ATTEMPT_TRACE_TOTALS) node_limit_override = None incumbent_fallback = None if net_id in capped_net_ids: @@ -1020,23 +1023,26 @@ class PathFinder: incumbent_fallback=incumbent_fallback, ) state.results[net_id] = result - attempt_after = self._capture_metric_totals(_ATTEMPT_TRACE_TOTALS) - deltas = self._metric_deltas(attempt_before, attempt_after) - attempt_work[net_id] = deltas["nodes_expanded"] + deltas["congestion_check_calls"] - attempt_traces.append( - net_attempt_trace(net_id, deltas, reached_target=result.reached_target, guidance_seed_present=guidance_seed_present) - ) + work_after = self.metrics.total_nodes_expanded + self.metrics.total_congestion_check_calls + attempt_work[net_id] = work_after - work_before + if capture_attempts: + attempt_after = self._capture_metric_totals(_ATTEMPT_TRACE_TOTALS) + deltas = self._metric_deltas(attempt_before, attempt_after) + attempt_traces.append( + net_attempt_trace(net_id, deltas, reached_target=result.reached_target, guidance_seed_present=guidance_seed_present) + ) state.recent_attempt_work = attempt_work review = self._reverify_iteration_results(state) - self._update_pre_pair_candidate( - state, - iteration=iteration, - reroute_net_ids=reroute_net_ids, - routed_net_ids=routed_net_ids, - attempt_traces=attempt_traces, - review=review, - ) + if diagnostics.capture_pre_pair_frontier_trace: + self._update_pre_pair_candidate( + state, + iteration=iteration, + reroute_net_ids=reroute_net_ids, + routed_net_ids=routed_net_ids, + attempt_traces=attempt_traces, + review=review, + ) if diagnostics.capture_iteration_trace: iteration_after = self._capture_metric_totals(_ITERATION_TRACE_TOTALS) deltas = self._metric_deltas(iteration_before, iteration_after) diff --git a/inire/router/cost.py b/inire/router/cost.py index b18391d..1cece3b 100644 --- a/inire/router/cost.py +++ b/inire/router/cost.py @@ -6,16 +6,17 @@ from typing import TYPE_CHECKING import numpy as np from inire.constants import TOLERANCE_LINEAR +from inire.geometry.collision import RoutingWorld from inire.model import ObjectiveWeights +from inire.router.danger_map import DangerMap if TYPE_CHECKING: from collections.abc import Iterable, Mapping, Sequence from typing import Protocol - from inire.geometry.collision import RoutingWorld from inire.geometry.components import MoveKind from inire.geometry.primitives import Port - from inire.router.danger_map import DangerMap + from inire.model import RoutingProblem class ScoreableMove(Protocol): @property @@ -219,3 +220,19 @@ class CostEvaluator: ) current_port = component.end_port return total + + +def build_native_cost_evaluator(problem: RoutingProblem, objective: ObjectiveWeights) -> CostEvaluator: + """Score candidate paths using the original layout's obstacles and objective.""" + danger = None + 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, + ) diff --git a/inire/tests/example_scenarios.py b/inire/tests/example_scenarios.py index 32fea64..50c811f 100644 --- a/inire/tests/example_scenarios.py +++ b/inire/tests/example_scenarios.py @@ -1,6 +1,6 @@ from __future__ import annotations -from dataclasses import dataclass +from dataclasses import dataclass, replace from functools import partial from time import perf_counter from typing import TYPE_CHECKING @@ -13,7 +13,6 @@ from inire import ( DiagnosticsOptions, NetSpec, ObjectiveWeights, - RefinementOptions, RoutingOptions, RoutingProblem, RoutingResult, @@ -21,26 +20,18 @@ from inire import ( SearchOptions, route, ) -from inire.geometry.collision import RoutingWorld from inire.geometry.primitives import Port from inire.results import RouteMetrics, _sum_route_metrics -from inire.router._astar_types import AStarContext, AStarMetrics -from inire.router._router import PathFinder from inire.router._stack import build_routing_stack -from inire.router.cost import CostEvaluator -from inire.router.danger_map import DangerMap 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 inire.router._astar_types import AStarMetrics + from inire.router._router import PathFinder + from inire.router.cost import CostEvaluator from inire.tests.routing_benchmark_case import BenchmarkCase -_SEARCH_FIELDS = set(SearchOptions.__dataclass_fields__) -_CONGESTION_FIELDS = set(CongestionOptions.__dataclass_fields__) -_REFINEMENT_FIELDS = set(RefinementOptions.__dataclass_fields__) -_DIAGNOSTICS_FIELDS = set(DiagnosticsOptions.__dataclass_fields__) -_OBJECTIVE_FIELDS = set(ObjectiveWeights.__dataclass_fields__) - ScenarioOutcome = tuple[float, int, int, int] ScenarioRun = Callable[[], ScenarioOutcome] ScenarioSnapshotRun = Callable[[], "ScenarioSnapshot"] @@ -105,112 +96,19 @@ def _make_run_result( ) -def _build_evaluator( - bounds: tuple[float, float, float, float], - *, - clearance: float = 2.0, - obstacles: list[Polygon] | None = None, - bend_penalty: float = 50.0, - sbend_penalty: float = 150.0, -) -> CostEvaluator: - static_obstacles = obstacles or [] - engine = RoutingWorld(clearance=clearance) - for obstacle in static_obstacles: - engine.add_static_obstacle(obstacle) - - danger_map = DangerMap(bounds=bounds) - danger_map.precompute(static_obstacles) - return CostEvaluator(engine, danger_map, bend_penalty=bend_penalty, sbend_penalty=sbend_penalty) - - -def _net_specs( - netlist: dict[str, tuple[Port, Port]], - widths: dict[str, float], -) -> tuple[NetSpec, ...]: - return tuple( - NetSpec(net_id=net_id, start=start, target=target, width=widths.get(net_id, 2.0)) - for net_id, (start, target) in netlist.items() - ) - - -def _build_options(**overrides: object) -> RoutingOptions: - search_overrides = {key: value for key, value in overrides.items() if key in _SEARCH_FIELDS} - congestion_overrides = {key: value for key, value in overrides.items() if key in _CONGESTION_FIELDS} - refinement_overrides = {key: value for key, value in overrides.items() if key in _REFINEMENT_FIELDS} - diagnostics_overrides = {key: value for key, value in overrides.items() if key in _DIAGNOSTICS_FIELDS} - objective_overrides = {key: value for key, value in overrides.items() if key in _OBJECTIVE_FIELDS} - return RoutingOptions( - search=SearchOptions(**search_overrides), - congestion=CongestionOptions(**congestion_overrides), - refinement=RefinementOptions(**refinement_overrides), - diagnostics=DiagnosticsOptions(**diagnostics_overrides), - objective=ObjectiveWeights(**objective_overrides), - ) - - -def _build_pathfinder( - evaluator: CostEvaluator, - *, - bounds: tuple[float, float, float, float], - nets: tuple[NetSpec, ...], - metrics: AStarMetrics | None = None, - **request_kwargs: object, -) -> PathFinder: - resolved_metrics = AStarMetrics() if metrics is None else metrics - return PathFinder( - AStarContext( - evaluator, - RoutingProblem(bounds=bounds, nets=nets), - _build_options(**request_kwargs), - metrics=resolved_metrics, - ), - metrics=resolved_metrics, - ) - - -def _build_routing_stack( - *, - bounds: tuple[float, float, float, float], - netlist: dict[str, tuple[Port, Port]], - widths: dict[str, float], - clearance: float = 2.0, - obstacles: list[Polygon] | None = None, - evaluator_kwargs: dict[str, float] | None = None, - request_kwargs: dict[str, object] | None = None, -) -> tuple[RoutingWorld, CostEvaluator, AStarMetrics, object]: - static_obstacles = obstacles or [] - engine = RoutingWorld(clearance=clearance) - for obstacle in static_obstacles: - engine.add_static_obstacle(obstacle) - - danger_map = DangerMap(bounds=bounds) - danger_map.precompute(static_obstacles) - - evaluator = CostEvaluator(engine, danger_map, **(evaluator_kwargs or {})) - metrics = AStarMetrics() - pathfinder = _build_pathfinder( - evaluator, - bounds=bounds, - nets=_net_specs(netlist, widths), - metrics=metrics, - **(request_kwargs or {}), - ) - return engine, evaluator, metrics, pathfinder +def _snapshot_worker(name: str, pathfinder: PathFinder) -> ScenarioSnapshot: + start = perf_counter() + results = pathfinder.route_all() + return _make_snapshot(name, results, perf_counter() - start, pathfinder.metrics.snapshot()) def snapshot_example_01() -> ScenarioSnapshot: - netlist = {"net1": (Port(10, 50, 0), Port(90, 50, 0))} - widths = {"net1": 2.0} - _, _, _, pathfinder = _build_routing_stack( + problem = RoutingProblem( bounds=(0, 0, 100, 100), - netlist=netlist, - widths=widths, - request_kwargs={"bend_radii": [10.0]}, + nets=(NetSpec("net1", Port(10, 50, 0), Port(90, 50, 0)),), ) - t0 = perf_counter() - results = pathfinder.route_all() - t1 = perf_counter() - return _make_snapshot("example_01_simple_route", results, t1 - t0, pathfinder.metrics.snapshot()) + options = RoutingOptions(search=SearchOptions(bend_radii=(10.0,))) + return _snapshot_worker("example_01_simple_route", build_routing_stack(problem, options).finder) def run_example_01() -> ScenarioOutcome: @@ -218,31 +116,20 @@ def run_example_01() -> ScenarioOutcome: def snapshot_example_02() -> ScenarioSnapshot: - netlist = { - "horizontal": (Port(10, 50, 0), Port(90, 50, 0)), - "vertical_up": (Port(45, 10, 90), Port(45, 90, 90)), - "vertical_down": (Port(55, 90, 270), Port(55, 10, 270)), - } - widths = dict.fromkeys(netlist, 2.0) - _, _, _, pathfinder = _build_routing_stack( + problem = RoutingProblem( bounds=(0, 0, 100, 100), - netlist=netlist, - widths=widths, - evaluator_kwargs={ - "greedy_h_weight": 1.5, - "bend_penalty": 50.0, - "sbend_penalty": 150.0, - }, - request_kwargs={ - "bend_radii": [10.0], - "sbend_radii": [10.0], - "base_penalty": 1000.0, - }, + nets=( + NetSpec("horizontal", Port(10, 50, 0), Port(90, 50, 0)), + NetSpec("vertical_up", Port(45, 10, 90), Port(45, 90, 90)), + NetSpec("vertical_down", Port(55, 90, 270), Port(55, 10, 270)), + ), ) - t0 = perf_counter() - results = pathfinder.route_all() - t1 = perf_counter() - return _make_snapshot("example_02_congestion_resolution", results, t1 - t0, pathfinder.metrics.snapshot()) + options = RoutingOptions( + search=SearchOptions(bend_radii=(10.0,), sbend_radii=(10.0,)), + objective=ObjectiveWeights(bend_penalty=50.0, sbend_penalty=150.0), + congestion=CongestionOptions(base_penalty=1000.0), + ) + return _snapshot_worker("example_02_congestion_resolution", build_routing_stack(problem, options).finder) def run_example_02() -> ScenarioOutcome: @@ -250,28 +137,26 @@ def run_example_02() -> ScenarioOutcome: def snapshot_example_03() -> ScenarioSnapshot: - netlist_a = {"netA": (Port(10, 0, 0), Port(90, 0, 0))} - widths_a = {"netA": 2.0} - engine, evaluator, _, pathfinder = _build_routing_stack( + problem_a = RoutingProblem( bounds=(0, -50, 100, 50), - netlist=netlist_a, - widths=widths_a, - request_kwargs={"bend_radii": [10.0]}, + nets=(NetSpec("netA", Port(10, 0, 0), Port(90, 0, 0)),), ) + options = RoutingOptions( + search=SearchOptions(bend_radii=(10.0,)), + objective=ObjectiveWeights(danger_weight=0.0), + ) + finder_a = build_routing_stack(problem_a, options).finder t0 = perf_counter() - results_a = pathfinder.route_all() - metrics_a = pathfinder.metrics.snapshot() - for polygon in results_a["netA"].locked_geometry: - engine.add_static_obstacle(polygon) - pathfinder_b = _build_pathfinder( - evaluator, - bounds=(0, -50, 100, 50), - nets=_net_specs({"netB": (Port(50, -20, 90), Port(50, 20, 90))}, {"netB": 2.0}), - bend_radii=[10.0], + results_a = finder_a.route_all() + problem_b = RoutingProblem( + bounds=problem_a.bounds, + nets=(NetSpec("netB", Port(50, -20, 90), Port(50, 20, 90)),), + static_obstacles=results_a["netA"].locked_geometry, ) - results_b = pathfinder_b.route_all() + finder_b = build_routing_stack(problem_b, options).finder + results_b = finder_b.route_all() t1 = perf_counter() - combined_metrics = _sum_route_metrics((metrics_a, pathfinder_b.metrics.snapshot())) + combined_metrics = _sum_route_metrics((finder_a.metrics.snapshot(), finder_b.metrics.snapshot())) return _make_snapshot("example_03_locked_paths", {**results_a, **results_b}, t1 - t0, combined_metrics) @@ -280,54 +165,43 @@ def run_example_03() -> ScenarioOutcome: def snapshot_example_04() -> ScenarioSnapshot: - netlist = { - "sbend_only": (Port(10, 50, 0), Port(60, 55, 0)), - "multi_radii": (Port(10, 10, 0), Port(90, 90, 0)), - } - widths = {"sbend_only": 2.0, "multi_radii": 2.0} - _, _, _, pathfinder = _build_routing_stack( + problem = RoutingProblem( bounds=(0, 0, 100, 100), - netlist=netlist, - widths=widths, - evaluator_kwargs={ - "unit_length_cost": 1.0, - "bend_penalty": 10.0, - "sbend_penalty": 20.0, - }, - request_kwargs={ - "node_limit": 50000, - "bend_radii": [10.0, 30.0], - "sbend_offsets": [5.0], - }, + nets=( + NetSpec("sbend_only", Port(10, 50, 0), Port(60, 55, 0)), + NetSpec("multi_radii", Port(10, 10, 0), Port(90, 90, 0)), + ), ) - t0 = perf_counter() - results = pathfinder.route_all() - t1 = perf_counter() - return _make_snapshot("example_04_sbends_and_radii", results, t1 - t0, pathfinder.metrics.snapshot()) + options = RoutingOptions( + search=SearchOptions(node_limit=50_000, bend_radii=(10.0, 30.0), sbend_offsets=(5.0,)), + objective=ObjectiveWeights(bend_penalty=10.0, sbend_penalty=20.0), + ) + 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 snapshot_example_05() -> ScenarioSnapshot: - netlist = { - "u_turn": (Port(50, 50, 0), Port(50, 70, 180)), - "loop": (Port(100, 100, 90), Port(100, 80, 270)), - "zig_zag": (Port(20, 150, 0), Port(180, 150, 0)), - } - widths = dict.fromkeys(netlist, 2.0) - _, _, _, pathfinder = _build_routing_stack( +def _build_example_05_worker(diagnostics: DiagnosticsOptions) -> PathFinder: + problem = RoutingProblem( bounds=(0, 0, 200, 200), - netlist=netlist, - widths=widths, - evaluator_kwargs={"bend_penalty": 50.0}, - request_kwargs={"bend_radii": [20.0]}, + nets=( + NetSpec("u_turn", Port(50, 50, 0), Port(50, 70, 180)), + NetSpec("loop", Port(100, 100, 90), Port(100, 80, 270)), + NetSpec("zig_zag", Port(20, 150, 0), Port(180, 150, 0)), + ), ) - t0 = perf_counter() - results = pathfinder.route_all() - t1 = perf_counter() - return _make_snapshot("example_05_orientation_stress", results, t1 - t0, pathfinder.metrics.snapshot()) + options = RoutingOptions( + search=SearchOptions(bend_radii=(20.0,)), + objective=ObjectiveWeights(bend_penalty=50.0, sbend_penalty=100.0), + diagnostics=diagnostics, + ) + return build_routing_stack(problem, options).finder + + +def snapshot_example_05() -> ScenarioSnapshot: + return _snapshot_worker("example_05_orientation_stress", _build_example_05_worker(DiagnosticsOptions())) def run_example_05() -> ScenarioOutcome: @@ -335,67 +209,44 @@ def run_example_05() -> ScenarioOutcome: def trace_example_05() -> RoutingRunResult: - netlist = { - "u_turn": (Port(50, 50, 0), Port(50, 70, 180)), - "loop": (Port(100, 100, 90), Port(100, 80, 270)), - "zig_zag": (Port(20, 150, 0), Port(180, 150, 0)), - } - widths = dict.fromkeys(netlist, 2.0) - _, _, _, pathfinder = _build_routing_stack( - bounds=(0, 0, 200, 200), - netlist=netlist, - widths=widths, - evaluator_kwargs={"bend_penalty": 50.0}, - request_kwargs={"bend_radii": [20.0], "capture_conflict_trace": True, "capture_frontier_trace": True}, - ) + pathfinder = _build_example_05_worker(DiagnosticsOptions(capture_conflict_trace=True, capture_frontier_trace=True)) results = pathfinder.route_all() return _make_run_result(results, pathfinder) def snapshot_example_06() -> ScenarioSnapshot: bounds = (-20, -20, 170, 170) - obstacles = [ + obstacles = ( box(40, 110, 60, 130), box(40, 60, 60, 80), box(40, 10, 60, 30), - ] + ) custom_physical = Polygon([(0, -11), (11, -11), (11, 0), (9, 0), (9, -9), (0, -9)]) - scenarios = [ + search = SearchOptions(bend_radii=(10.0,)) + options = RoutingOptions( + objective=ObjectiveWeights(bend_penalty=50.0, sbend_penalty=150.0), + congestion=CongestionOptions(use_tiered_strategy=False), + ) + scenarios = ( + (NetSpec("arc_model", Port(10, 120, 0), Port(90, 140, 90)), search), + (NetSpec("bbox_model", Port(10, 70, 0), Port(90, 90, 90)), replace(search, bend_collision_type="bbox")), ( - _build_evaluator(bounds, obstacles=obstacles), - {"arc_model": (Port(10, 120, 0), Port(90, 140, 90))}, - {"arc_model": 2.0}, - {"bend_radii": [10.0], "bend_collision_type": "arc", "use_tiered_strategy": False}, - ), - ( - _build_evaluator(bounds, obstacles=obstacles), - {"bbox_model": (Port(10, 70, 0), Port(90, 90, 90))}, - {"bbox_model": 2.0}, - {"bend_radii": [10.0], "bend_collision_type": "bbox", "use_tiered_strategy": False}, - ), - ( - _build_evaluator(bounds, obstacles=obstacles), - {"custom_geometry": (Port(10, 20, 0), Port(90, 40, 90))}, - {"custom_geometry": 2.0}, - { - "bend_radii": [10.0], - "bend_physical_geometry": custom_physical, - "bend_proxy_geometry": custom_physical, - "use_tiered_strategy": False, - }, + NetSpec("custom_geometry", Port(10, 20, 0), Port(90, 40, 90)), + replace(search, bend_physical_geometry=custom_physical, bend_proxy_geometry=custom_physical), ), + ) + finders = [ + build_routing_stack( + RoutingProblem(bounds=bounds, nets=(net,), static_obstacles=obstacles), + replace(options, search=scenario_search), + ).finder + for net, scenario_search in scenarios ] t0 = perf_counter() combined_results: dict[str, RoutingResult] = {} route_metrics: list[RouteMetrics] = [] - for evaluator, netlist, net_widths, request_kwargs in scenarios: - pathfinder = _build_pathfinder( - evaluator, - bounds=bounds, - nets=_net_specs(netlist, net_widths), - **request_kwargs, - ) + for pathfinder in finders: combined_results.update(pathfinder.route_all()) route_metrics.append(pathfinder.metrics.snapshot()) t1 = perf_counter() @@ -577,37 +428,27 @@ def run_example_07() -> ScenarioOutcome: return snapshot_example_07().as_outcome() -def snapshot_example_08() -> ScenarioSnapshot: - bounds = (0, 0, 150, 150) - netlist = {"standard_arc": (Port(20, 20, 0), Port(100, 100, 90))} - widths = {"standard_arc": 2.0} +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,)) + options = RoutingOptions( + search=SearchOptions(bend_radii=(10.0,), sbend_radii=()), + objective=ObjectiveWeights(bend_penalty=50.0, sbend_penalty=150.0), + congestion=CongestionOptions(max_iterations=1, use_tiered_strategy=False), + ) custom_physical = Polygon([(0, -11), (11, -11), (11, 0), (9, 0), (9, -9), (0, -9)]) - custom_proxy = box(0, -11, 11, 0) + custom_problem = replace(problem, nets=(replace(net, net_id="custom_geometry_and_proxy"),)) + custom_options = replace( + options, + search=replace(options.search, bend_physical_geometry=custom_physical, bend_proxy_geometry=box(0, -11, 11, 0)), + ) + return build_routing_stack(problem, options).finder, build_routing_stack(custom_problem, custom_options).finder + +def snapshot_example_08() -> ScenarioSnapshot: t0 = perf_counter() - pathfinder_std = _build_pathfinder( - _build_evaluator(bounds), - bounds=bounds, - nets=_net_specs(netlist, widths), - bend_radii=[10.0], - sbend_radii=[], - max_iterations=1, - use_tiered_strategy=False, - metrics=AStarMetrics(), - ) + pathfinder_std, pathfinder_custom = _build_example_08_workers() results_std = pathfinder_std.route_all() - pathfinder_custom = _build_pathfinder( - _build_evaluator(bounds), - bounds=bounds, - nets=_net_specs({"custom_geometry_and_proxy": netlist["standard_arc"]}, {"custom_geometry_and_proxy": 2.0}), - bend_radii=[10.0], - bend_physical_geometry=custom_physical, - bend_proxy_geometry=custom_proxy, - sbend_radii=[], - max_iterations=1, - use_tiered_strategy=False, - metrics=AStarMetrics(), - ) results_custom = pathfinder_custom.route_all() t1 = perf_counter() combined_metrics = _sum_route_metrics((pathfinder_std.metrics.snapshot(), pathfinder_custom.metrics.snapshot())) @@ -624,24 +465,17 @@ def run_example_08() -> ScenarioOutcome: def snapshot_example_09() -> ScenarioSnapshot: - obstacles = [ - box(35, 35, 45, 65), - box(55, 35, 65, 65), - ] - netlist = {"budget_limited_net": (Port(10, 50, 0), Port(85, 60, 180))} - widths = {"budget_limited_net": 2.0} - _, _, _, pathfinder = _build_routing_stack( + problem = RoutingProblem( bounds=(0, 0, 100, 100), - netlist=netlist, - widths=widths, - obstacles=obstacles, - evaluator_kwargs={"bend_penalty": 50.0, "sbend_penalty": 150.0}, - request_kwargs={"node_limit": 3, "bend_radii": [10.0], "warm_start_enabled": False, "max_iterations": 1}, + nets=(NetSpec("budget_limited_net", Port(10, 50, 0), Port(85, 60, 180)),), + static_obstacles=(box(35, 35, 45, 65), box(55, 35, 65, 65)), ) - t0 = perf_counter() - results = pathfinder.route_all() - t1 = perf_counter() - return _make_snapshot("example_09_unroutable_best_effort", results, t1 - t0, pathfinder.metrics.snapshot()) + options = RoutingOptions( + search=SearchOptions(node_limit=3, bend_radii=(10.0,)), + objective=ObjectiveWeights(bend_penalty=50.0, sbend_penalty=150.0), + congestion=CongestionOptions(warm_start_enabled=False, max_iterations=1), + ) + return _snapshot_worker("example_09_unroutable_best_effort", build_routing_stack(problem, options).finder) def run_example_09() -> ScenarioOutcome: diff --git a/inire/tests/routing_corpus.py b/inire/tests/routing_corpus.py index 351f779..210aa5d 100644 --- a/inire/tests/routing_corpus.py +++ b/inire/tests/routing_corpus.py @@ -6,9 +6,7 @@ from dataclasses import replace from typing import TYPE_CHECKING from inire import RoutingOptions -from inire.geometry.collision import RoutingWorld -from inire.router.cost import CostEvaluator, weighted_path_length -from inire.router.danger_map import DangerMap +from inire.router.cost import build_native_cost_evaluator, weighted_path_length from inire.tests.retry_holdout_benchmarks import RETRY_HOLDOUT_CASES from inire.tests.routing_benchmarks import ( BENCHMARK_CASES, @@ -124,20 +122,7 @@ def native_verified_costs( results: dict[str, RoutingResult], verified_net_ids: Iterable[str], ) -> dict[str, float]: - objective = options.objective - problem = case.problem - danger = None - if objective.danger_weight and problem.static_obstacles: - danger = DangerMap(bounds=problem.bounds) - danger.precompute(list(problem.static_obstacles)) - scorer = 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, - ) + scorer = build_native_cost_evaluator(case.problem, options.objective) costs = {} for net_id in verified_net_ids: path = results[net_id].path diff --git a/inire/tests/test_api.py b/inire/tests/test_api.py index eece699..605a132 100644 --- a/inire/tests/test_api.py +++ b/inire/tests/test_api.py @@ -263,7 +263,7 @@ def test_capture_conflict_trace_preserves_route_outputs() -> None: assert [entry.stage for entry in run_with_trace.conflict_trace] == ["iteration", "restored_best", "final"] -def test_capture_iteration_trace_preserves_route_outputs() -> None: +def test_capture_iteration_trace_preserves_route_outputs(monkeypatch) -> None: problem = RoutingProblem( bounds=(0, 0, 100, 100), nets=( @@ -276,7 +276,12 @@ def test_capture_iteration_trace_preserves_route_outputs() -> None: refinement=RefinementOptions(enabled=False), ) - run_without_trace = route(problem, options=base_options) + def unexpected_attempt_trace(*_args, **_kwargs): + pytest.fail("Routing built an attempt trace with diagnostics disabled") + + with monkeypatch.context() as patch: + patch.setattr(router_module, "net_attempt_trace", unexpected_attempt_trace) + run_without_trace = route(problem, options=base_options) run_with_trace = route( problem, options=RoutingOptions( diff --git a/inire/tests/test_example_regressions.py b/inire/tests/test_example_regressions.py index 68ce4d4..6099783 100644 --- a/inire/tests/test_example_regressions.py +++ b/inire/tests/test_example_regressions.py @@ -16,11 +16,8 @@ from inire.router._stack import build_routing_stack from inire.seeds import Bend90Seed, PathSeed, StraightSeed from inire.tests.example_scenarios import ( SCENARIOS, - _build_evaluator, _build_example_07_variant_stack, - _build_pathfinder, - _net_specs, - AStarMetrics, + _build_example_08_workers, snapshot_example_05, snapshot_example_07_no_warm_start, trace_example_07_no_warm_start, @@ -272,34 +269,10 @@ def test_custom_proxy_without_physical_geometry_warns_and_keeps_arc_geometry() - def test_example_08_custom_geometry_runs_in_separate_sessions() -> None: - bounds = (0, 0, 150, 150) - netlist = {"standard_arc": (Port(20, 20, 0), Port(100, 100, 90))} - widths = {"standard_arc": 2.0} - custom_physical = Polygon([(0, -11), (11, -11), (11, 0), (9, 0), (9, -9), (0, -9)]) - custom_proxy = box(0, -11, 11, 0) - - standard = _build_pathfinder( - _build_evaluator(bounds), - bounds=bounds, - nets=_net_specs(netlist, widths), - bend_radii=[10.0], - sbend_radii=[], - max_iterations=1, - use_tiered_strategy=False, - metrics=AStarMetrics(), - ).route_all() - custom = _build_pathfinder( - _build_evaluator(bounds), - bounds=bounds, - nets=_net_specs({"custom_geometry_and_proxy": netlist["standard_arc"]}, {"custom_geometry_and_proxy": 2.0}), - bend_radii=[10.0], - bend_physical_geometry=custom_physical, - bend_proxy_geometry=custom_proxy, - sbend_radii=[], - max_iterations=1, - use_tiered_strategy=False, - metrics=AStarMetrics(), - ).route_all() + standard_worker, custom_worker = _build_example_08_workers() + assert standard_worker.context.cost_evaluator.collision_engine is not custom_worker.context.cost_evaluator.collision_engine + standard = standard_worker.route_all() + custom = custom_worker.route_all() assert standard["standard_arc"].is_valid assert standard["standard_arc"].reached_target