Build traces on demand and share routing fixture setup

This commit is contained in:
Jan Petykiewicz 2026-11-26 23:00:23 -08:00
commit 6608e18ef5

View file

@ -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: