Check a replayed route against itself and fixed geometry before adding it to the collision index. Add cross-net conflicts once the index is populated, then share reports across review, traces, and the callback. Recheck changed geometry after refinement.
280 lines
11 KiB
Python
280 lines
11 KiB
Python
from dataclasses import replace
|
|
|
|
import pytest
|
|
from shapely.geometry import Polygon, box
|
|
|
|
from inire import CongestionOptions, ObjectiveWeights, RefinementOptions, RoutingOptions, RoutingProblem, SearchOptions, TopologyOptions, route
|
|
from inire import DiagnosticsOptions, PathSeed, StraightSeed
|
|
from inire.geometry.collision import RoutingWorld
|
|
from inire.geometry.components import Bend90
|
|
from inire.geometry.primitives import Port
|
|
from inire.geometry.primitives import port_local_coordinates
|
|
from inire.model import NetSpec
|
|
from inire.router._astar_types import AStarContext
|
|
from inire.router._router import PathFinder
|
|
from inire.router._seed_materialization import materialize_path_seed
|
|
from inire.router._waypoints import compile_waypoints
|
|
from inire.router.cost import CostEvaluator
|
|
from inire.router.danger_map import DangerMap
|
|
|
|
|
|
_FOLDBACK = ((20, 80), (60, 80), (60, 150), (120, 150), (120, 100), (180, 100), (180, 150), (240, 150), (240, 70), (280, 70))
|
|
|
|
|
|
def _seeded_foldback(*, reflected: bool = False, radius: float = 10) -> RoutingProblem:
|
|
points = tuple((x, 220 - y) for x, y in _FOLDBACK) if reflected else _FOLDBACK
|
|
start = Port(*points[0], 0)
|
|
seed, target = compile_waypoints(points, start, radius)
|
|
return RoutingProblem((0, 0, 320, 220), (NetSpec("foldback", start, target),), initial_paths={"foldback": seed})
|
|
|
|
|
|
_REFINEMENT_OPTIONS = RoutingOptions(
|
|
search=SearchOptions(node_limit=1, bend_radii=(10,)),
|
|
objective=ObjectiveWeights(danger_weight=0),
|
|
congestion=CongestionOptions(max_iterations=1),
|
|
topology=TopologyOptions(mode="off"),
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize("limit", [None, 1, 4])
|
|
def test_refinement_window_order_matches_exhaustive_search(limit) -> None:
|
|
problem = _seeded_foldback()
|
|
options = replace(_REFINEMENT_OPTIONS, refinement=RefinementOptions(max_windows_per_net=limit))
|
|
start = problem.nets[0].start
|
|
path = materialize_path_seed(problem.initial_paths["foldback"], start=start, net_width=2, search=options.search, clearance=2)
|
|
assert path is not None
|
|
finder = PathFinder(AStarContext(CostEvaluator(RoutingWorld(clearance=2), DangerMap(problem.bounds)), problem, options))
|
|
ports = [start, *(move.end_port for move in path)]
|
|
eligible = []
|
|
for left, source in enumerate(ports[:-1]):
|
|
for right, target in enumerate(ports[left + 1 :], start=left + 1):
|
|
bends = [move.move_type == "bend90" for move in path[left:right]]
|
|
forward, _ = port_local_coordinates(source, target.x, target.y)
|
|
if sum(bends) >= 4 and source.r == target.r and forward >= 40:
|
|
priority = -sum((bends[0], bends[-1])) if limit == 4 else 0
|
|
eligible.append((priority, left - right, left, right))
|
|
|
|
assert list(finder.refiner._iter_refinement_windows(start, path)) == [(left, right) for _, _, left, right in sorted(eligible)]
|
|
|
|
|
|
@pytest.mark.parametrize("radius", [10, 10.25])
|
|
def test_refinement_handles_both_signs_of_the_lateral_offset(radius) -> None:
|
|
options = replace(_REFINEMENT_OPTIONS, search=replace(_REFINEMENT_OPTIONS.search, bend_radii=(radius,)))
|
|
paths = [
|
|
route(_seeded_foldback(reflected=reflected, radius=radius), options=options).results_by_net["foldback"]
|
|
for reflected in (False, True)
|
|
]
|
|
|
|
assert all(path.is_valid and sum(move.move_type == "bend90" for move in path.path) == 4 for path in paths)
|
|
assert paths[0].report.total_length == pytest.approx(paths[1].report.total_length)
|
|
|
|
|
|
def test_automatic_refinement_rechecks_retained_partial_paths() -> None:
|
|
base = _seeded_foldback()
|
|
blocked = NetSpec("blocked", Port(150, 120, 90), Port(150, 210, 90))
|
|
problem = replace(
|
|
base,
|
|
nets=(*base.nets, blocked),
|
|
static_obstacles=(box(70, 180, 260, 220),),
|
|
initial_paths={**base.initial_paths, "blocked": PathSeed((StraightSeed(50),))},
|
|
)
|
|
options = replace(
|
|
_REFINEMENT_OPTIONS,
|
|
search=replace(_REFINEMENT_OPTIONS.search, node_limit=15),
|
|
congestion=replace(_REFINEMENT_OPTIONS.congestion, warm_start_enabled=False),
|
|
diagnostics=DiagnosticsOptions(capture_conflict_trace=True),
|
|
topology=TopologyOptions(mode="automatic"),
|
|
)
|
|
|
|
run = route(problem, options=options)
|
|
|
|
assert run.automatic is not None
|
|
assert run.automatic.stages[run.automatic.selected_stage].operation == "refine"
|
|
assert run.results_by_net["foldback"].is_valid
|
|
partial = run.results_by_net["blocked"]
|
|
assert partial.outcome == "partial"
|
|
assert partial.report.dynamic_collision_count == 1
|
|
final = run.conflict_trace[-1]
|
|
assert final.stage == "final"
|
|
traced = next(net for net in final.nets if net.net_id == "blocked")
|
|
assert traced.report == partial.report
|
|
assert traced.conflicting_net_ids == ("foldback",)
|
|
|
|
|
|
@pytest.mark.parametrize("weights", [None, (0, 0, 0)])
|
|
def test_automatic_selects_refinement_using_its_explicit_objective(weights) -> None:
|
|
problem = _seeded_foldback()
|
|
lattice_options = replace(
|
|
_REFINEMENT_OPTIONS,
|
|
search=replace(_REFINEMENT_OPTIONS.search, node_limit=100),
|
|
objective=ObjectiveWeights(0, 0, 0, 0),
|
|
refinement=RefinementOptions(objective=ObjectiveWeights(danger_weight=0)),
|
|
)
|
|
automatic_options = replace(
|
|
lattice_options, topology=TopologyOptions(mode="automatic", automatic_length_weights=weights),
|
|
)
|
|
expected = route(problem, options=lattice_options).results_by_net["foldback"]
|
|
run = route(problem, options=automatic_options)
|
|
actual = run.results_by_net["foldback"]
|
|
|
|
assert actual.is_valid
|
|
assert len(actual.path) == 9
|
|
assert actual.as_seed() == expected.as_seed()
|
|
assert run.automatic.stages[run.automatic.selected_stage].operation == "refine"
|
|
|
|
|
|
def test_seeded_refinement_builds_proximity_map_at_zero_search_budget(monkeypatch) -> None:
|
|
problem = replace(_seeded_foldback(), static_obstacles=(box(0, 0, 10, 10),))
|
|
options = replace(
|
|
_REFINEMENT_OPTIONS,
|
|
search=replace(_REFINEMENT_OPTIONS.search, node_limit=0),
|
|
refinement=RefinementOptions(objective=ObjectiveWeights()),
|
|
)
|
|
calls = []
|
|
precompute = DangerMap.precompute
|
|
|
|
def track(self, obstacles):
|
|
calls.append(tuple(obstacles))
|
|
precompute(self, obstacles)
|
|
|
|
monkeypatch.setattr(DangerMap, "precompute", track)
|
|
callbacks = []
|
|
run = route(problem, options=options, iteration_callback=lambda _, results: callbacks.append(results["foldback"]))
|
|
|
|
result = run.results_by_net["foldback"]
|
|
assert result.is_valid
|
|
assert run.metrics.refinement_candidates_accepted > 0
|
|
assert calls == [problem.static_obstacles]
|
|
assert result.as_seed() != problem.initial_paths["foldback"]
|
|
assert result.report.total_length == pytest.approx(sum(component.length for component in result.path))
|
|
assert callbacks == [result]
|
|
|
|
|
|
@pytest.mark.parametrize("mode", ["automatic", "off"])
|
|
def test_refinement_preserves_custom_bend_geometry_on_seed_replay(mode) -> None:
|
|
outline = Polygon([(0, -11), (11, -11), (11, 0), (9, 0), (9, -9), (0, -9)])
|
|
options = replace(
|
|
_REFINEMENT_OPTIONS,
|
|
search=replace(_REFINEMENT_OPTIONS.search, bend_physical_geometry=outline),
|
|
topology=TopologyOptions(mode=mode),
|
|
)
|
|
problem = _seeded_foldback()
|
|
run = route(problem, options=options)
|
|
result = run.results_by_net["foldback"]
|
|
replay = route(
|
|
replace(problem, initial_paths={"foldback": result.as_seed()}),
|
|
options=replace(options, refinement=RefinementOptions(enabled=False)),
|
|
).results_by_net["foldback"]
|
|
|
|
assert run.metrics.refinement_candidates_accepted > 0
|
|
assert result.is_valid
|
|
assert replay.is_valid
|
|
assert all(a.equals(b) for a, b in zip(result.locked_geometry, replay.locked_geometry, strict=True))
|
|
|
|
|
|
def _build_pathfinder(
|
|
evaluator: CostEvaluator,
|
|
*,
|
|
bounds: tuple[float, float, float, float],
|
|
netlist: dict[str, tuple[Port, Port]],
|
|
net_widths: dict[str, float],
|
|
search: SearchOptions | None = None,
|
|
) -> PathFinder:
|
|
nets = tuple(
|
|
NetSpec(net_id=net_id, start=start, target=target, width=net_widths.get(net_id, 2.0))
|
|
for net_id, (start, target) in netlist.items()
|
|
)
|
|
return PathFinder(
|
|
AStarContext(
|
|
evaluator,
|
|
RoutingProblem(bounds=bounds, nets=nets),
|
|
RoutingOptions(search=SearchOptions() if search is None else search),
|
|
),
|
|
)
|
|
|
|
|
|
def test_arc_resolution_sagitta() -> None:
|
|
start = Port(0, 0, 0)
|
|
# R=10, 90 deg bend.
|
|
# High tolerance (0.5um) -> few segments
|
|
res_coarse = Bend90.generate(start, radius=10.0, width=2.0, direction="CCW", sagitta=0.5)
|
|
# Low tolerance (1nm) -> many segments
|
|
res_fine = Bend90.generate(start, radius=10.0, width=2.0, direction="CCW", sagitta=0.001)
|
|
|
|
|
|
# Check number of points in the polygon exterior
|
|
# (num_segments + 1) * 2 points usually
|
|
pts_coarse = len(res_coarse.collision_geometry[0].exterior.coords)
|
|
pts_fine = len(res_fine.collision_geometry[0].exterior.coords)
|
|
|
|
assert pts_fine > pts_coarse
|
|
|
|
|
|
@pytest.mark.parametrize(("offset", "move_type"), [(0, "straight"), (5, "sbend")])
|
|
def test_refinement_leaves_simple_paths_installed(offset: int, move_type: str) -> None:
|
|
problem = RoutingProblem(
|
|
bounds=(0, 0, 120, 120),
|
|
nets=(NetSpec("out", Port(10, 50, 0), Port(110, 50 + offset, 0)),),
|
|
)
|
|
options = RoutingOptions(
|
|
search=SearchOptions(bend_radii=(10.0,), sbend_radii=(10.0,)),
|
|
congestion=CongestionOptions(warm_start_enabled=False),
|
|
topology=TopologyOptions(mode="off"),
|
|
)
|
|
|
|
run = route(problem, options=options)
|
|
|
|
assert run.results_by_net["out"].is_valid
|
|
assert run.results_by_net["out"].path[-1].move_type == move_type
|
|
assert run.metrics.refine_path_calls == 0
|
|
assert run.metrics.dynamic_path_objects_removed == 0
|
|
|
|
|
|
def test_locked_routes() -> None:
|
|
engine = RoutingWorld(clearance=2.0)
|
|
danger_map = DangerMap(bounds=(0, -50, 100, 50))
|
|
danger_map.precompute([])
|
|
evaluator = CostEvaluator(engine, danger_map)
|
|
|
|
# 1. Route Net A
|
|
netlist_a = {"netA": (Port(0, 0, 0), Port(50, 0, 0))}
|
|
results_a = _build_pathfinder(
|
|
evaluator,
|
|
bounds=(0, -50, 100, 50),
|
|
netlist=netlist_a,
|
|
net_widths={"netA": 2.0},
|
|
search=SearchOptions(bend_radii=(5.0, 10.0)),
|
|
).route_all()
|
|
assert results_a["netA"].is_valid
|
|
|
|
# 2. Treat Net A as locked geometry in the next run.
|
|
for polygon in results_a["netA"].locked_geometry:
|
|
engine.add_static_obstacle(polygon)
|
|
|
|
# 3. Route Net B through the same space. It should detour or fail.
|
|
# We'll place Net B's start/target such that it MUST cross Net A's physical path.
|
|
netlist_b = {"netB": (Port(0, -5, 0), Port(50, 5, 0))}
|
|
|
|
# Route Net B
|
|
results_b = _build_pathfinder(
|
|
evaluator,
|
|
bounds=(0, -50, 100, 50),
|
|
netlist=netlist_b,
|
|
net_widths={"netB": 2.0},
|
|
search=SearchOptions(bend_radii=(5.0, 10.0)),
|
|
).route_all()
|
|
|
|
# Net B should be is_valid (it detoured) or at least not have collisions
|
|
# with Net A in the dynamic set (because netA is now static).
|
|
# Since netA is static, netB will see it as a HARD collision if it tries to cross.
|
|
|
|
# Our A* will find a detour around the static obstacle.
|
|
assert results_b["netB"].is_valid
|
|
|
|
# Verify geometry doesn't intersect locked netA (physical check)
|
|
poly_a = [p.physical_geometry[0] for p in results_a["netA"].path]
|
|
poly_b = [p.physical_geometry[0] for p in results_b["netB"].path]
|
|
|
|
for pa in poly_a:
|
|
for pb in poly_b:
|
|
assert not pa.intersects(pb)
|