from contextlib import nullcontext from dataclasses import replace import pytest import shapely from shapely.affinity import translate from shapely.geometry import Polygon, box import inire.geometry.components as components_module import inire.router._router as router_module import inire.router._search as search_module from inire import ( Bend90Seed, CongestionOptions, DiagnosticsOptions, FixedRoute, NetSpec, ObjectiveWeights, PathSeed, Port, RefinementOptions, RoutingOptions, RoutingProblem, SBendOutline, SBendSeed, SearchOptions, StraightSeed, TopologyOptions, route, ) from inire.geometry.components import SBend, Straight from inire.geometry.collision import RoutingWorld from inire.results import ComponentConflictTrace, RoutingReport, RoutingResult from inire.router._astar_types import AStarContext from inire.router._router import PathFinder, _IterationReview from inire.router._stack import RoutingAttempts from inire.router.cost import CostEvaluator from inire.router.danger_map import DangerMap def test_routing_problem_rejects_duplicate_net_ids() -> None: nets = ( NetSpec("shared", Port(10, 20, 0), Port(90, 20, 0)), NetSpec("shared", Port(10, 70, 0), Port(90, 70, 0)), ) with pytest.raises(ValueError, match="Duplicate net ID: 'shared'"): RoutingProblem(bounds=(0, 0, 100, 100), nets=nets) fixed = FixedRoute("shared", (box(10, 40, 90, 42),)) with pytest.raises(ValueError, match="Duplicate active or fixed net ID: 'shared'"): RoutingProblem(bounds=(0, 0, 100, 100), nets=nets[:1], fixed_routes=(fixed,)) def test_routing_problem_requires_typed_geometry_inputs() -> None: bounds = (0, 0, 100, 100) with pytest.raises(TypeError, match="must be a Shapely Polygon"): RoutingProblem(bounds, static_obstacles=(box(20, 20, 30, 30).boundary,)) with pytest.raises(TypeError, match="initial_paths values must be PathSeed"): RoutingProblem(bounds, initial_paths={"line": (StraightSeed(50),)}) def test_net_width_must_be_finite_and_positive() -> None: for width in (0, float("nan")): with pytest.raises(ValueError, match="width must be finite and positive"): NetSpec("net", Port(10, 20, 0), Port(90, 20, 0), width=width) def test_routing_clearance_must_be_finite_and_nonnegative() -> None: for clearance in (-1.0, float("inf")): with pytest.raises(ValueError, match="clearance must be finite and nonnegative"): RoutingProblem((0, 0, 100, 100), clearance=clearance) def test_routing_bounds_require_a_finite_positive_rectangle() -> None: for bounds in ((100, 0, 0, 100), (0, 0, 100, float("nan"))): with pytest.raises(ValueError, match="bounds must be finite"): RoutingProblem(bounds) def test_routing_keepout_must_be_nonempty_and_valid() -> None: keepout = Polygon([(0, 0), (10, 10), (0, 10), (10, 0)]) with pytest.raises(ValueError, match=r"static_obstacles\[1\].*nonempty and valid"): RoutingProblem((0, 0, 100, 100), static_obstacles=(box(20, 20, 30, 30), keepout)) def test_search_distances_and_radii_require_finite_values() -> None: with pytest.raises(ValueError, match="bend_radii"): SearchOptions(bend_radii=(float("inf"),)) with pytest.raises(ValueError, match="min_straight_length"): SearchOptions(min_straight_length=-1) with pytest.raises(ValueError, match="max_straight_length"): SearchOptions(max_straight_length=0) with pytest.raises(ValueError, match="bend_proxy_geometry"): SearchOptions(bend_proxy_geometry="clipped-bbox") def test_route_does_not_generate_bends_wider_than_their_diameter() -> None: nets = ( NetSpec("turn", Port(20, 25, 0), Port(30, 35, 90), width=25), NetSpec("shift", Port(20, 85, 0), Port(35, 91, 0), width=25), ) seeds = { "turn": PathSeed((Bend90Seed(10, "CCW"),)), "shift": PathSeed((SBendSeed(6, 10),)), } problem = RoutingProblem((0, 0, 100, 120), nets, initial_paths=seeds) options = RoutingOptions( search=SearchOptions(bend_radii=(10,), sbend_radii=(10,), node_limit=100), congestion=CongestionOptions(max_iterations=1), ) run = route(problem, options=options) assert set(run.results_by_net) == set(seeds) for result in run.results_by_net.values(): assert not result.is_valid assert all(isinstance(move, StraightSeed) for move in result.as_seed().segments) def test_seed_parameters_must_describe_a_forward_usable_move() -> None: with pytest.raises(ValueError, match="seed"): StraightSeed(-10) with pytest.raises(ValueError, match="seed"): Bend90Seed(0, "CW") with pytest.raises(ValueError, match="seed"): SBendSeed(20, 10) with pytest.raises(ValueError, match="seed"): SBendSeed(3.5, 10) def test_search_skips_sbends_when_the_offset_list_is_empty() -> None: problem = RoutingProblem((0, 0, 90, 70), (NetSpec("shift", Port(10, 20, 0), Port(60, 24, 0)),)) options = RoutingOptions( search=SearchOptions(node_limit=100, bend_radii=(), sbend_radii=(10,), sbend_offsets=()), topology=TopologyOptions(mode="off"), congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), ) result = route(problem, options=options).results_by_net["shift"] assert not result.is_valid assert not any(isinstance(move, SBendSeed) for move in result.as_seed().segments) def test_initial_path_must_respect_explicit_sbend_offsets() -> None: net = NetSpec("shift", Port(10, 20, 0), Port(41, 23, 0)) seed = PathSeed((SBendSeed(3, 10), StraightSeed(20))) problem = RoutingProblem((0, 0, 90, 70), (net,), initial_paths={"shift": seed}) rejected = route(problem, options=RoutingOptions(search=SearchOptions(node_limit=0, sbend_offsets=(4,)))).results_by_net[net.net_id] assert rejected.outcome == "unroutable" assert rejected.report.seed_error == "Initial path for 'shift' uses an S-bend offset outside sbend_offsets" result = route(problem, options=RoutingOptions(search=SearchOptions(sbend_offsets=(3,)))).results_by_net["shift"] assert result.is_valid assert result.as_seed() == seed def test_replay_reports_incompatible_seed_segments_and_verifies_peers() -> None: cases = ( (NetSpec("unsupported_turn", Port(20, 20, 0), Port(25, 25, 90)), Bend90Seed(5, "CCW"), "uses radius 5 outside bend_radii"), (NetSpec("unsupported_sbend", Port(20, 60, 0), Port(35, 63, 0)), SBendSeed(3, 20), "uses radius 20 outside sbend_radii"), (NetSpec("overwide_turn", Port(20, 100, 0), Port(30, 110, 90), width=30), Bend90Seed(10, "CCW"), "segment 1 (Bend90Seed) needs radius at least 15, got 10"), (NetSpec("overwide_sbend", Port(20, 150, 0), Port(35, 156, 0), width=30), SBendSeed(6, 10), "segment 1 (SBendSeed) needs radius at least 15, got 10"), ) peer = NetSpec("peer", Port(20, 190, 0), Port(70, 190, 0)) seeds = {net.net_id: PathSeed((segment,)) for net, segment, _ in cases} seeds[peer.net_id] = PathSeed((StraightSeed(50),)) problem = RoutingProblem((0, 0, 100, 220), (*(net for net, _, _ in cases), peer), initial_paths=seeds) options = RoutingOptions( search=SearchOptions(node_limit=0, bend_radii=(10,), sbend_radii=(10,)), topology=TopologyOptions(mode="off"), diagnostics=DiagnosticsOptions(capture_conflict_trace=True), ) callbacks = [] run = route(problem, options=options, iteration_callback=lambda _, results: callbacks.append(results)) assert run.results_by_net[peer.net_id].is_valid assert run.metrics.nodes_expanded == 0 assert callbacks == [run.results_by_net] traced_reports = {net.net_id: net.report for net in run.conflict_trace[-1].nets} for net, _, error in cases: rejected = run.results_by_net[net.net_id] assert rejected.outcome == "unroutable" assert rejected.report.seed_error == f"Initial path for {net.net_id!r} {error}" assert rejected.report.invalid_geometry assert traced_reports[net.net_id] == rejected.report @pytest.mark.parametrize(("clearance", "valid"), [(0, True), (0.001, False)]) def test_search_checks_physical_clearance_after_a_local_proxy_intersection(clearance, valid) -> None: physical = box(0, -11, 11, -9).union(box(9, -11, 11, 0)) proxy = physical.union(box(-0.0015, -10.0005, 0.0002, -9.9995)) net = NetSpec("corner", Port(20, 20, 0), Port(30, 30, 90)) keepout = box(19.999, 19.9999, 19.9995, 20.0001) problem = RoutingProblem((0, 0, 45, 45), (net,), (keepout,), clearance=clearance) options = RoutingOptions( search=SearchOptions(node_limit=25, bend_radii=(10,), sbend_radii=(), bend_physical_geometry=physical, bend_proxy_geometry=proxy), congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), refinement=RefinementOptions(enabled=False), topology=TopologyOptions(mode="off"), ) result = route(problem, options=options).results_by_net[net.net_id] assert result.is_valid is valid assert result.reached_target is valid if valid: assert result.as_seed() == PathSeed((Bend90Seed(10, "CCW"),)) assert result.locked_geometry[0].distance(keepout) == pytest.approx(0.0005) def test_lattice_search_repairs_a_seed_that_verification_retains() -> None: net = NetSpec("line", Port(20, 20, 0), Port(120, 20, 0)) up, down = Bend90Seed(10, "CCW"), Bend90Seed(10, "CW") detour = PathSeed((up, down, StraightSeed(60), down, up)) problem = RoutingProblem( (0, 0, 150, 70), (net,), (box(60, 38, 80, 42),), initial_paths={net.net_id: detour}, clearance=1, ) options = RoutingOptions( search=SearchOptions(node_limit=0, bend_radii=(10,), sbend_radii=()), congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), refinement=RefinementOptions(enabled=False), topology=TopologyOptions(mode="off"), ) verified = route(problem, options=options) retained = verified.results_by_net[net.net_id] repaired = route(problem, options=replace(options, search=replace(options.search, node_limit=50))) replacement = repaired.results_by_net[net.net_id] assert verified.metrics.nodes_expanded == 0 assert retained.reached_target assert retained.outcome == "colliding" assert retained.report.static_collision_count == 1 assert retained.as_seed() == detour assert repaired.metrics.nodes_expanded > 0 assert replacement.reached_target assert replacement.is_valid assert replacement.as_seed() == PathSeed((StraightSeed(100),)) def test_search_and_congestion_reject_invalid_budgets() -> None: for budget in (True, -1, 1.5): with pytest.raises(ValueError, match="node_limit must be a nonnegative integer"): SearchOptions(node_limit=budget) with pytest.raises(ValueError, match="max_iterations must be a nonnegative integer"): CongestionOptions(max_iterations=budget) def test_cost_options_require_finite_nonnegative_values() -> None: with pytest.raises(ValueError, match="unit_length_cost"): ObjectiveWeights(unit_length_cost=float("nan")) with pytest.raises(ValueError, match="greedy_h_weight"): SearchOptions(greedy_h_weight=-1) with pytest.raises(ValueError, match="base_penalty"): CongestionOptions(base_penalty=float("nan")) with pytest.raises(ValueError, match="multiplier"): CongestionOptions(multiplier=-1) def test_public_inputs_reject_invalid_ids_and_named_options() -> None: with pytest.raises(TypeError, match="Net ID must be a string"): NetSpec(7, Port(0, 0, 0), Port(10, 0, 0)) with pytest.raises(ValueError, match="net_order"): CongestionOptions(net_order="longesst") with pytest.raises(ValueError, match="visibility_guidance"): SearchOptions(visibility_guidance="exact") def _sbend_strip(offset, half_width=1): centerline = [(0, 0), (20, offset / 10), (50, 3 * offset / 4), (80, offset)] return Polygon( [(x, y - half_width) for x, y in centerline] + [(x, y + half_width) for x, y in reversed(centerline)], ) def test_custom_sbend_board_admission_agrees_with_replay_and_net_order() -> None: polygon = Polygon([(0, -1), (79.5, 39), (79.5, 41), (0, 1)]) with pytest.warns(UserWarning, match="port faces"): outline = SBendOutline(40, 50, 2, polygon) edge = NetSpec("edge", Port(10, 10, 0), Port(90, 50, 0)) peer = NetSpec("peer", Port(5, 70, 0), Port(85, 110, 0)) problem = RoutingProblem((0, 0, 89.75, 115), (edge,), clearance=0) options = RoutingOptions( search=SearchOptions(node_limit=10, min_straight_length=100, bend_radii=(), sbend_radii=(50,), sbend_offsets=(40,), sbend_outlines=(outline,)), congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), topology=TopologyOptions(mode="off"), ) seed = PathSeed((SBendSeed(40, 50),)) replay_options = replace(options, search=replace(options.search, node_limit=0)) seeded = replace(problem, initial_paths={edge.net_id: seed}) replay = route(seeded, options=replay_options).results_by_net[edge.net_id] assert replay.is_valid for nets in ((edge,), (edge, peer), (peer, edge)): results = route(replace(problem, nets=nets), options=options).results_by_net assert all(result.is_valid for result in results.values()) assert results[edge.net_id].as_seed() == seed assert results[edge.net_id].locked_geometry == replay.locked_geometry smaller_board = (0, 0, 89.25, 115) assert not route(replace(problem, bounds=smaller_board), options=options).results_by_net[edge.net_id].reached_target assert route(replace(seeded, bounds=smaller_board), options=replay_options).results_by_net[edge.net_id].report.out_of_bounds def test_custom_sbend_matches_float_width_in_search_and_replay() -> None: outline = SBendOutline(40, 50, 0.3, _sbend_strip(40, half_width=0.15)) nets = ( NetSpec("matching", Port(10, 10, 0), Port(90, 50, 0), 0.1 + 0.2), NetSpec("fallback", Port(10, 70, 0), Port(90, 110, 0), 0.31), ) problem = RoutingProblem((0, 0, 100, 125), nets, clearance=0) search = SearchOptions(node_limit=30, sbend_outlines=(outline,), bend_radii=(), sbend_radii=(50,)) options = RoutingOptions(search=search, topology=TopologyOptions(mode="off")) active = route(problem, options=options).results_by_net seeds = {net.net_id: PathSeed((SBendSeed(40, 50),)) for net in nets} replay = route( replace(problem, initial_paths=seeds), options=replace(options, search=replace(search, node_limit=0)), ).results_by_net for net_id, polygon_count in (("matching", 1), ("fallback", 2)): assert active[net_id].is_valid assert replay[net_id].is_valid assert len(active[net_id].locked_geometry) == polygon_count assert active[net_id].locked_geometry == replay[net_id].locked_geometry def test_search_and_seed_replay_check_materialized_sbend_faces() -> None: clearance = 0.1 # The nominal face fails clearance. The supplied outline is within the face tolerance. keepout = box(0, 7, 10 - clearance + 0.4e-6, 13) polygon = Polygon([(0.8e-6 if x == 0 else x, y) for x, y in _sbend_strip(40).exterior.coords]) outline = SBendOutline(40, 50, 2, polygon) net = NetSpec("shift", Port(10, 10, 0), Port(90, 50, 0), width=2) problem = RoutingProblem( (0, 0, 100, 100), (net,), (keepout,), initial_paths={net.net_id: PathSeed((SBendSeed(40, 50),))}, clearance=clearance, ) options = RoutingOptions( search=SearchOptions(node_limit=0, bend_radii=(), sbend_radii=(50,), sbend_outlines=(outline,)), topology=TopologyOptions(mode="off"), ) callbacks = [] run = route(problem, options=options, iteration_callback=lambda _, results: callbacks.append(results[net.net_id])) result = run.results_by_net[net.net_id] assert result.locked_geometry[0].distance(keepout) > clearance assert result.is_valid assert result.report.terminal_error is None assert len(callbacks) == 1 assert callbacks[0].report == result.report active_options = replace(options, search=replace(options.search, node_limit=30)) active = route(replace(problem, initial_paths={}), options=active_options).results_by_net[net.net_id] assert active.is_valid assert active.as_seed() == result.as_seed() assert active.locked_geometry == result.locked_geometry def _nearby_sbend_outlines() -> tuple[SBendOutline, SBendOutline]: outline = SBendOutline(40, 50, 0.3, _sbend_strip(40, half_width=0.15)) return outline, replace(outline, width=0.3 * (1 + 1.5e-12)) def test_custom_sbend_outline_rejects_duplicate_and_ambiguous_widths() -> None: outline, other = _nearby_sbend_outlines() with pytest.raises(ValueError, match="Duplicate S-bend outline"): SearchOptions(sbend_radii=(50,), sbend_outlines=(outline, replace(outline, width=0.1 + 0.2))) options = SearchOptions(sbend_radii=(50,), sbend_outlines=(outline, other)) with pytest.raises(ValueError, match="Ambiguous S-bend outlines"): options.sbend_outline(40, 50, (outline.width + other.width) / 2) @pytest.mark.parametrize(('mode', 'node_limit'), [('automatic', 0), ('off', 20)]) def test_ambiguous_sbend_outline_is_skipped_in_search_and_seed_replay(mode, node_limit) -> None: outline, other = _nearby_sbend_outlines() width = (outline.width + other.width) / 2 shift = NetSpec("shift", Port(10, 10, 0), Port(90, 50, 0), width=width) peer = NetSpec("peer", Port(10, 70, 0), Port(90, 110, 0), width=outline.width) seed = PathSeed((SBendSeed(40, 50),)) paths = {} if node_limit else {net.net_id: seed for net in (shift, peer)} problem = RoutingProblem((0, 0, 100, 120), (shift, peer), initial_paths=paths, clearance=0) options = RoutingOptions( search=SearchOptions(node_limit=node_limit, bend_radii=(), sbend_radii=(50,), sbend_offsets=(40,), sbend_outlines=(outline, other)), congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), topology=TopologyOptions(mode=mode), ) results = route(problem, options=options).results_by_net assert not results["shift"].is_valid assert not any(isinstance(component.move_spec, SBendSeed) for component in results["shift"].path) assert results["peer"].is_valid assert results["peer"].path[0].physical_geometry[0].equals(translate(outline.polygon, 10, 70)) if not node_limit: assert "segment 1 (SBendSeed) Ambiguous S-bend outlines" in results["shift"].report.seed_error @pytest.mark.parametrize( ('contact', 'heading'), [ ('gap', 0), ('face', 90), ('overlap', 90), ], ) def test_custom_sbend_join_allows_boundary_contact_and_rejects_area_overlap(contact, heading) -> None: left, right = _sbend_strip(40), _sbend_strip(-40) if contact == "gap": left, right = translate(left, -0.75), translate(right, 0.75) elif contact == "overlap": right = translate(right, -0.5) start = Port(20, 30, 0) if heading == 0 else Port(100, 20, 90) finish = Port(180, 30, 0) if heading == 0 else Port(100, 180, 90) net = NetSpec("shift", start, finish) seed = PathSeed((SBendSeed(40, 50), SBendSeed(-40, 50))) problem = RoutingProblem((0, 0, 220, 220), (net,), initial_paths={"shift": seed}, clearance=0) warning = pytest.warns(UserWarning, match="port faces") if contact in ("gap", "overlap") else nullcontext() with warning: options = RoutingOptions(search=SearchOptions( node_limit=0, sbend_radii=(50,), sbend_outlines=(SBendOutline(40, 50, 2, left), SBendOutline(-40, 50, 2, right)), )) result = route(problem, options=options).results_by_net["shift"] assert result.reached_target first, second = result.locked_geometry if contact == "gap": assert first.distance(second) > 0 elif contact == "face": assert first.intersection(second).length == pytest.approx(2) assert (first.intersection(second).area > 0) == (contact == "overlap") assert result.report.self_collision_count == int(contact == "overlap") assert result.is_valid == (contact != "overlap") def test_custom_sbend_can_exceed_the_circular_width_limit() -> None: polygon = Polygon([(0, -6), (8, -2), (8, 10), (0, 6)]) outline = SBendOutline(4, 5, 12, polygon) net = NetSpec("wide", Port(10, 10, 0), Port(18, 14, 0), width=12) seed = PathSeed((SBendSeed(4, 5),)) problem = RoutingProblem((0, 0, 50, 50), (net,), clearance=0) options = RoutingOptions(search=SearchOptions(node_limit=40, bend_radii=(), sbend_radii=(5,), sbend_outlines=(outline,))) result = route(problem, options=options).results_by_net[net.net_id] assert result.is_valid assert result.as_seed() == seed assert result.locked_geometry == (translate(polygon, 10, 10),) @pytest.mark.parametrize( ('node_limit', 'circular_proxy'), [ (40, False), (0, True), ], ) def test_custom_quarter_turn_width_depends_on_whether_it_uses_a_circular_proxy(node_limit, circular_proxy) -> None: polygon = box(0, -5, 5, -3).union(box(3, -5, 5, 0)) net = NetSpec("wide", Port(20, 20, 0), Port(24, 24, 90), width=10) seed = PathSeed((Bend90Seed(4, "CCW"),)) problem = RoutingProblem( (0, 0, 50, 50), (net,), initial_paths={} if node_limit else {net.net_id: seed}, clearance=0, ) options = RoutingOptions(search=SearchOptions( node_limit=node_limit, bend_radii=(4,), sbend_radii=(), bend_physical_geometry=polygon, bend_proxy_geometry="bbox" if circular_proxy else None, )) warning = nullcontext() if circular_proxy else pytest.warns(UserWarning, match="declared port faces of width 10") with warning: result = route(problem, options=options).results_by_net[net.net_id] if circular_proxy: assert result.report.invalid_geometry assert "needs radius at least 5, got 4" in result.report.seed_error else: assert result.is_valid assert result.as_seed() == seed assert result.locked_geometry == (translate(polygon, 20, 24),) def test_custom_quarter_turn_warns_when_its_faces_do_not_match_the_width() -> None: outline = box(0, -11, 11, -9).union(box(9, -11, 11, 0)) net = NetSpec("bend", Port(10, 20, 0), Port(30, 40, 90), width=4) seed = PathSeed((StraightSeed(10), Bend90Seed(10, "CCW"), StraightSeed(10))) problem = RoutingProblem((0, 0, 100, 100), (net,), clearance=0) options = RoutingOptions( search=SearchOptions(node_limit=100, bend_radii=(10,), sbend_radii=(), bend_physical_geometry=outline), congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), topology=TopologyOptions(mode="off"), ) with pytest.warns(UserWarning, match="declared port faces of width 4"): result = route(problem, options=options).results_by_net["bend"] assert result.is_valid assert result.as_seed() == seed def test_route_verification_rejects_self_contact_away_from_a_join() -> None: net = NetSpec("fold", Port(10, 10, 0), Port(10, 12, 180)) turn = Bend90Seed(1, "CCW") seed = PathSeed((StraightSeed(20), turn, turn, StraightSeed(20))) problem = RoutingProblem((0, 0, 100, 100), (net,), initial_paths={"fold": seed}, clearance=0) options = RoutingOptions( search=SearchOptions(node_limit=0, bend_radii=(1,)), congestion=CongestionOptions(max_iterations=1), ) result = route(problem, options=options).results_by_net["fold"] assert result.locked_geometry[0].intersection(result.locked_geometry[-1]).length == 20 assert result.reached_target assert result.outcome == "colliding" assert result.report.self_collision_count > 0 def test_fractional_straight_seeds_use_grid_lengths() -> None: lengths = ((0.2, 1, 1), (19.5, 19.5, 20), (20.49, 20.49, 20)) nets = tuple( NetSpec(str(y), Port(10, y, 0), Port(10 + target_distance, y, 0)) for y, (_, target_distance, _) in zip((20, 40, 60), lengths, strict=True) ) seeds = { net.net_id: PathSeed((StraightSeed(seed_length),)) for net, (seed_length, _, _) in zip(nets, lengths, strict=True) } problem = RoutingProblem((0, 0, 100, 100), nets, initial_paths=seeds) options = RoutingOptions(congestion=CongestionOptions(max_iterations=1)) run = route(problem, options=options) assert run.metrics.nodes_expanded == 0 for net, (_, _, grid_length) in zip(nets, lengths, strict=True): result = run.results_by_net[net.net_id] assert result.is_valid assert result.report.total_length == grid_length assert result.as_seed() == PathSeed((StraightSeed(grid_length),)) assert result.path[-1].end_port == Port(10 + grid_length, net.start.y, 0) def test_verify_only_retains_colliding_seeds_and_final_trace(monkeypatch) -> None: nets = ( NetSpec("horizontal", Port(10, 50, 0), Port(90, 50, 0)), NetSpec("vertical", Port(50, 10, 90), Port(50, 90, 90)), NetSpec("partial", Port(10, 80, 0), Port(90, 80, 0)), NetSpec("unseeded", Port(10, 90, 0), Port(90, 90, 0)), ) seeds = {net.net_id: PathSeed((StraightSeed(80),)) for net in nets[:2]} seeds["partial"] = PathSeed((StraightSeed(40),)) problem = RoutingProblem((0, 0, 100, 100), nets, (box(20, 77, 25, 82),), initial_paths=seeds) options = RoutingOptions( search=SearchOptions(node_limit=0), congestion=CongestionOptions(max_iterations=10), diagnostics=DiagnosticsOptions(capture_conflict_trace=True), refinement=RefinementOptions(enabled=False), ) def fail_on_proximity(*_args): pytest.fail("Geometry-only verification built a proximity map") monkeypatch.setattr(DangerMap, "precompute", fail_on_proximity) monkeypatch.delattr(shapely, "constrained_delaunay_triangles", raising=False) callbacks = [] run = route(problem, options=options) with_callback = route(problem, options=options, iteration_callback=lambda index, results: callbacks.append((index, results))) for net in nets[:2]: result = run.results_by_net[net.net_id] assert result.as_seed() == seeds[net.net_id] assert result.outcome == "colliding" assert result.report.dynamic_collision_count == 1 assert run.results_by_net["partial"].outcome == "partial" assert run.results_by_net["partial"].report.total_length == 40 assert run.results_by_net["partial"].report.static_collision_count == 1 assert run.results_by_net["unseeded"].outcome == "unroutable" iteration, restored, final = run.conflict_trace assert (iteration.stage, restored.stage, final.stage) == ("iteration", "restored_best", "final") assert iteration.conflict_edges == restored.conflict_edges == final.conflict_edges == (("horizontal", "vertical"),) for traced_net, other_net in zip(final.nets[:2], ("vertical", "horizontal"), strict=True): assert traced_net.component_conflicts == (ComponentConflictTrace(other_net, 0, 0),) assert traced_net == next(net for net in iteration.nets if net.net_id == traced_net.net_id) assert traced_net == next(net for net in restored.nets if net.net_id == traced_net.net_id) assert run.metrics.nodes_expanded == 0 assert run.metrics.route_iterations == 1 assert run.metrics.verify_path_report_calls == 3 assert run.metrics.verify_static_buffer_ops == 0 assert run.metrics.verify_dynamic_exact_pair_checks == 2 assert callbacks == [(0, run.results_by_net)] assert with_callback.results_by_net == run.results_by_net assert with_callback.metrics.verify_path_report_calls == run.metrics.verify_path_report_calls def test_lattice_length_cost_units_preserve_search_order() -> None: net = NetSpec("turn", Port(15, 40, 0), Port(165, 80, 0)) problem = RoutingProblem((0, 0, 190, 100), (net,), (box(63, 7, 85, 55),)) options = RoutingOptions( search=SearchOptions(node_limit=32, min_straight_length=2, bend_radii=(10,), sbend_radii=()), diagnostics=DiagnosticsOptions(capture_expanded=True), congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False, use_tiered_strategy=False), refinement=RefinementOptions(enabled=False), topology=TopologyOptions(mode="off"), ) small = route(problem, options=replace(options, objective=ObjectiveWeights(0.001, 0, 0, 0))) large = route(problem, options=replace(options, objective=ObjectiveWeights(1e12, 0, 0, 0))) assert small.results_by_net["turn"].is_valid assert large.results_by_net["turn"].is_valid assert small.results_by_net["turn"].as_seed() == large.results_by_net["turn"].as_seed() assert small.expanded_nodes assert small.expanded_nodes == large.expanded_nodes assert small.metrics.nodes_expanded == large.metrics.nodes_expanded def test_partial_path_tracks_geometric_progress_without_cost_heuristic() -> None: heuristic = 1.5 price = 0 net = NetSpec("across", Port(5, 20, 0), Port(90, 20, 0)) problem = RoutingProblem((0, 0, 100, 40), (net,), (box(45, 0, 55, 40),)) options = RoutingOptions( search=SearchOptions(node_limit=5, greedy_h_weight=heuristic, bend_radii=(), sbend_radii=()), objective=ObjectiveWeights(price, 0, 0, 0), congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False, use_tiered_strategy=False), refinement=RefinementOptions(enabled=False), topology=TopologyOptions(mode="off"), ) run = route(problem, options=options) assert run.results_by_net["across"].outcome == "partial" def test_coincident_ports_are_reported_without_blocking_the_batch() -> None: net = NetSpec("abutting", Port(30, 20, 0), Port(30.4, 20.4, 0)) peer = NetSpec("peer", Port(10, 60, 0), Port(70, 60, 0)) seeds = {net.net_id: PathSeed((Bend90Seed(41, "CCW"),)), peer.net_id: PathSeed((StraightSeed(60),))} problem = RoutingProblem((0, 0, 100, 100), (net, peer), initial_paths=seeds) options = RoutingOptions( search=SearchOptions(node_limit=0), topology=TopologyOptions(mode="seed"), diagnostics=DiagnosticsOptions(capture_conflict_trace=True), ) callbacks = [] run = route(problem, options=options, iteration_callback=lambda _, results: callbacks.append(results)) assert tuple(run.results_by_net) == (net.net_id, peer.net_id) rejected = run.results_by_net[net.net_id] assert rejected.outcome == "unroutable" assert rejected.path == () assert rejected.requested_net == net assert rejected.effective_net == net assert rejected.report.terminal_error == f"start and target ports {net.start.as_tuple()} coincide after grid snapping" assert run.results_by_net[peer.net_id].is_valid assert callbacks assert all(results[net.net_id] == rejected for results in callbacks) assert next(trace.report for trace in run.conflict_trace[-1].nets if trace.net_id == net.net_id) == rejected.report def test_invalid_terminal_faces_are_reported_without_search() -> None: nets = ( NetSpec("outside", Port(10, 40, 0), Port(302, 40, 0)), NetSpec("blocked", Port(10, 80, 0), Port(280, 80, 0)), NetSpec("flush", Port(10, 120, 0), Port(300, 120, 0)), ) problem = RoutingProblem((0, 0, 300, 160), nets, (box(275, 75, 285, 85),)) options = RoutingOptions( search=SearchOptions(node_limit=600, bend_radii=(20,)), congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), refinement=RefinementOptions(enabled=False), ) run = route(problem, options=options) outside, blocked, flush = (run.results_by_net[net.net_id] for net in nets) assert not outside.is_valid assert outside.report.terminal_error == "target port (302, 40, 0) face extends outside the routing board" assert not blocked.is_valid assert blocked.report.terminal_error == "target port (280, 80, 0) face violates keepout clearance" assert flush.is_valid assert flush.report.terminal_error is None assert run.metrics.nodes_expanded < 10 def test_same_net_clearance_preserves_join_and_checks_separated_path() -> None: folds = (("tight", 20, 2), ("clear", 60, 3)) nets = tuple(NetSpec(name, Port(10, y, 0), Port(10, y + 2 * radius, 180)) for name, y, radius in folds) seeds = { name: PathSeed((StraightSeed(25), Bend90Seed(radius, "CCW"), Bend90Seed(radius, "CCW"), StraightSeed(25))) for name, _, radius in folds } problem = RoutingProblem((0, 0, 100, 100), nets, initial_paths=seeds, self_clearance=4) options = RoutingOptions(search=SearchOptions(node_limit=0, bend_radii=(2, 3))) spaced = route(problem, options=options).results_by_net unspaced = route(replace(problem, self_clearance=0), options=options).results_by_net assert not spaced["tight"].is_valid assert spaced["tight"].report.self_collision_count > 0 assert spaced["clear"].is_valid assert all(result.is_valid for result in unspaced.values()) def test_zero_clearance_forbids_inter_net_contact_but_allows_keepout_edges() -> None: nets = ( NetSpec("first", Port(10, 20, 0), Port(40, 20, 0)), NetSpec("touching", Port(40, 22, 0), Port(90, 22, 0)), NetSpec("separate", Port(40, 25, 0), Port(90, 25, 0)), ) seeds = {net.net_id: PathSeed((StraightSeed(net.target.x - net.start.x),)) for net in nets} problem = RoutingProblem((0, 0, 100, 50), nets, (box(10, 15, 40, 19),), initial_paths=seeds, clearance=0) results = route(problem, options=RoutingOptions(search=SearchOptions(node_limit=0))).results_by_net assert all(result.report.static_collision_count == 0 for result in results.values()) assert results["first"].report.dynamic_collision_count == 1 assert results["touching"].report.dynamic_collision_count == 1 assert results["separate"].is_valid def test_unsafe_seeds_report_segments_without_allocating_geometry(monkeypatch: pytest.MonkeyPatch) -> None: def unexpected_tessellation(*_args, **_kwargs): pytest.fail("Oversized seed reached the tessellator") monkeypatch.setattr(components_module, "_get_arc_polygons", unexpected_tessellation) monkeypatch.setattr(SBend, "_arcs", unexpected_tessellation) nets = ( NetSpec("turn", Port(10, 20, 0), Port(90, 20, 0)), NetSpec("shift", Port(10, 40, 0), Port(90, 40, 0)), ) moves = {"turn": Bend90Seed(1e11, "CCW"), "shift": SBendSeed(1e11, 1e11)} problem = RoutingProblem( (0, 0, 100, 60), nets, initial_paths={net_id: PathSeed((move,)) for net_id, move in moves.items()}, ) options = RoutingOptions( search=SearchOptions(node_limit=0, bend_radii=(1e11,), sbend_radii=(1e11,), sbend_offsets=(1e11,)), refinement=RefinementOptions(enabled=False), diagnostics=DiagnosticsOptions(capture_conflict_trace=True), ) run = route(problem, options=options) traced = {net.net_id: net.report for net in run.conflict_trace[-1].nets} for net_id, move in moves.items(): result = run.results_by_net[net_id] assert not result.is_valid assert result.report.seed_error == ( f"Initial path for {net_id!r} segment 1 ({type(move).__name__}) exceeds 250,000 subdivisions for one circular arc" ) assert traced[net_id].seed_error == result.report.seed_error def test_automatic_falls_back_to_lattice_when_corridor_search_is_unavailable(monkeypatch) -> None: monkeypatch.delattr(shapely, "constrained_delaunay_triangles", raising=False) net = NetSpec("line", Port(10, 50, 0), Port(90, 50, 0)) problem = RoutingProblem((0, 0, 100, 100), (net,)) options = RoutingOptions(search=SearchOptions(bend_radii=(), sbend_radii=()), refinement=RefinementOptions(enabled=False)) run = route(problem, options=options) assert run.results_by_net["line"].is_valid assert run.automatic is not None assert run.automatic.stages[run.automatic.selected_stage].kind == "lattice-fallback" def test_routes_report_boundary_violations_in_results_and_diagnostics() -> None: mode = 'automatic' problem = RoutingProblem( bounds=(0, 0, 100, 100), nets=( NetSpec("edge", Port(10, 0, 0), Port(90, 0, 0)), NetSpec("flush", Port(0, 50, 0), Port(100, 50, 0)), ), initial_paths={"edge": PathSeed((StraightSeed(80),))}, ) options = RoutingOptions( search=SearchOptions(node_limit=100), topology=TopologyOptions(mode=mode), diagnostics=DiagnosticsOptions(capture_conflict_trace=True), ) run = route(problem, options=options) valid_ids = tuple(net_id for net_id, result in run.results_by_net.items() if result.is_valid) assert valid_ids == ("flush",) if mode == "automatic": assert run.automatic is not None assert run.automatic.verified_net_ids == valid_ids selected = run.automatic.stages[run.automatic.selected_stage] assert selected.out_of_bounds_net_ids == ("edge",) edge = run.results_by_net["edge"] assert edge.reached_target assert edge.outcome == "colliding" assert edge.report.out_of_bounds assert edge.collisions == 1 assert not edge.report.is_valid final = run.conflict_trace[-1] assert final.stage == "final" assert "edge" not in final.completed_net_ids traced_edge = next(net for net in final.nets if net.net_id == "edge") assert traced_edge.outcome == edge.outcome assert traced_edge.report == edge.report def test_lattice_straight_uses_flat_port_faces_for_clearance() -> None: nets = ( NetSpec("touching", Port(10, 20, 0), Port(30, 20, 0)), NetSpec("blocked", Port(10, 45, 0), Port(30, 45, 0)), ) obstacles = (box(32, 16, 36, 24), box(31.9, 41, 36, 49)) problem = RoutingProblem((0, 0, 60, 60), nets, obstacles, clearance=2) options = RoutingOptions( search=SearchOptions(node_limit=100, bend_radii=(), sbend_radii=()), congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), topology=TopologyOptions(mode="off"), ) results = route(problem, options=options).results_by_net assert results["touching"].is_valid assert not results["blocked"].is_valid def test_invalid_seed_leaves_crossing_peer_valid() -> None: blocked = NetSpec("blocked", Port(10, 100, 0), Port(170, 100, 0)) through = NetSpec("through", Port(80, 40, 90), Port(80, 160, 90)) seeds = {"blocked": PathSeed((StraightSeed(160),)), "through": PathSeed((StraightSeed(120),))} problem = RoutingProblem((0, 0, 200, 200), (blocked, through), (box(125, 94, 145, 106),), initial_paths=seeds) options = RoutingOptions( search=SearchOptions(node_limit=0), congestion=CongestionOptions(max_iterations=1), diagnostics=DiagnosticsOptions(capture_conflict_trace=True), topology=TopologyOptions(mode="off"), ) run = route(problem, options=options) assert run.results_by_net["blocked"].report.static_collision_count == 1 assert run.results_by_net["through"].is_valid assert all(entry.conflict_edges == () for entry in run.conflict_trace) def test_congestion_retry_includes_keepout_collision_alongside_peer_conflicts() -> None: static = NetSpec("static", Port(20, 40, 0), Port(230, 40, 0)) horizontal = NetSpec("horizontal", Port(20, 150, 0), Port(230, 150, 0)) vertical = NetSpec("vertical", Port(140, 105, 90), Port(140, 235, 90)) problem = RoutingProblem( (0, 0, 260, 260), (static, horizontal, vertical), (box(80, 20, 100, 60),), clearance=0, initial_paths={ "static": PathSeed((StraightSeed(210),)), "horizontal": PathSeed((StraightSeed(210),)), "vertical": PathSeed((StraightSeed(130),)), }, ) options = RoutingOptions( search=SearchOptions(bend_radii=(5, 10), sbend_radii=(), node_limit=50), congestion=CongestionOptions(max_iterations=2, warm_start_enabled=False), refinement=RefinementOptions(enabled=False), diagnostics=DiagnosticsOptions(capture_iteration_trace=True), topology=TopologyOptions(mode="off"), ) run = route(problem, options=options) assert run.iteration_trace[0].conflict_edges == 1 assert "static" in run.iteration_trace[0].routed_net_ids assert "static" in run.iteration_trace[1].routed_net_ids assert run.results_by_net["static"].report.static_collision_count == 1 def test_first_lattice_pass_accepts_fractional_turn_with_keepout_inside_its_bounding_box() -> None: problem = RoutingProblem( (0, 0, 100, 100), nets=(NetSpec("bend", Port(20, 20, 0), Port(31, 31, 90)),), static_obstacles=(box(20, 28, 24, 30),), clearance=0, ) options = RoutingOptions( search=SearchOptions(bend_radii=(10.25,), sbend_radii=(), node_limit=100), congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), refinement=RefinementOptions(enabled=False), topology=TopologyOptions(mode="off"), ) result = route(problem, options=options).results_by_net["bend"] assert result.is_valid assert result.as_seed() == PathSeed((Bend90Seed(10.25, "CCW"),)) def test_route_verification_detects_physical_bend_overlap() -> None: nets = ( NetSpec("a", Port(50, 50, 0), Port(60, 60, 90)), NetSpec("b", Port(50, 65, 0), Port(60, 75, 90)), ) seed = PathSeed((Bend90Seed(10, "CCW"),)) problem = RoutingProblem((0, 0, 120, 120), nets, initial_paths={net.net_id: seed for net in nets}) bend_proxy = box(0, -11, 11, 0) outline = Polygon([(0, -11), (11, -11), (11, 0), (9, 0), (9, -9), (0, -9)]) physical_bend = outline.union(box(10, -8, 13, -6)).union(box(12, -8, 14, 9)) options = RoutingOptions( search=SearchOptions(node_limit=0, bend_radii=(10,), bend_proxy_geometry=bend_proxy, bend_physical_geometry=physical_bend), congestion=CongestionOptions(max_iterations=1), diagnostics=DiagnosticsOptions(capture_conflict_trace=True), topology=TopologyOptions(mode="off"), ) run = route(problem, options=options) left = run.results_by_net["a"] right = run.results_by_net["b"] assert left.locked_geometry[0].intersection(right.locked_geometry[0]).area > 0 for result in (left, right): assert result.outcome == "colliding" assert result.report.dynamic_collision_count == 1 assert run.conflict_trace[-1].conflict_edges == (("a", "b"),) @pytest.mark.parametrize( 'node_limit', [ 40, 500, 700, ], ids=['tight', 'initial', 'higher'], ) def test_default_router_escalates_only_within_the_configured_node_limit(monkeypatch, node_limit) -> None: problem = RoutingProblem((0, 0, 200, 200), (NetSpec("turn", Port(20, 20, 0), Port(180, 160, 90)),)) route_astar = router_module.route_astar attempted_limits = [] def route_with_budget(*args, config, **kwargs): attempted_limits.append(config.node_limit) if config.node_limit <= 500: return None return route_astar(*args, config=config, **kwargs) monkeypatch.setattr(router_module, "route_astar", route_with_budget) options = None if node_limit is None else RoutingOptions(search=SearchOptions(node_limit=node_limit)) run = route(problem, options=options) assert run.automatic is not None ceiling = SearchOptions().node_limit if node_limit is None else node_limit assert attempted_limits assert max(attempted_limits) <= ceiling limits = [stage.node_limit for stage in run.automatic.stages] assert min(500, ceiling) in limits assert [limit for limit in limits if limit > 500] == ([ceiling] if ceiling > 500 else []) assert run.results_by_net["turn"].is_valid == (ceiling > 500) def test_capture_frontier_trace_preserves_route_outputs() -> None: problem = RoutingProblem( bounds=(0, 0, 100, 100), nets=( NetSpec("horizontal", Port(10, 50, 0), Port(90, 50, 0), width=2.0), NetSpec("vertical", Port(50, 10, 90), Port(50, 90, 90), width=2.0), ), ) problem = replace(problem, initial_paths={net.net_id: PathSeed((StraightSeed(80),)) for net in problem.nets}) base_options = RoutingOptions( search=SearchOptions(node_limit=0), congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), refinement=RefinementOptions(enabled=False), topology=TopologyOptions(mode="off"), ) run_without_trace = route(problem, options=base_options) run_with_trace = route( problem, options=replace(base_options, diagnostics=DiagnosticsOptions(capture_frontier_trace=True)), ) assert run_without_trace.results_by_net == run_with_trace.results_by_net assert {trace.net_id for trace in run_with_trace.frontier_trace} == {"horizontal", "vertical"} assert run_with_trace.metrics.verify_path_report_calls == run_without_trace.metrics.verify_path_report_calls def test_reverify_iterations_limit_late_reroutes_to_conflicting_nets(monkeypatch: pytest.MonkeyPatch) -> None: problem = RoutingProblem( bounds=(0, 0, 100, 100), nets=( NetSpec("netA", Port(10, 50, 0), Port(90, 50, 0), width=2.0), NetSpec("netB", Port(50, 10, 90), Port(50, 90, 90), width=2.0), NetSpec("netC", Port(10, 20, 0), Port(90, 20, 0), width=2.0), ), ) options = RoutingOptions( congestion=CongestionOptions(max_iterations=10, warm_start_enabled=False), refinement=RefinementOptions(enabled=False), ) evaluator = CostEvaluator(RoutingWorld(clearance=2.0), DangerMap(bounds=problem.bounds)) pathfinder = PathFinder(AStarContext(evaluator, problem, options)) colliding_a = RoutingResult( net_id="netA", path=(Straight.generate(Port(10, 50, 0), 80.0, 2.0, dilation=1.0),), reached_target=True, report=RoutingReport(dynamic_collision_count=1, total_length=80.0), ) colliding_b = RoutingResult( net_id="netB", path=(Straight.generate(Port(50, 10, 90), 80.0, 2.0, dilation=1.0),), reached_target=True, report=RoutingReport(dynamic_collision_count=1, total_length=80.0), ) completed_c = RoutingResult( net_id="netC", path=(Straight.generate(Port(10, 20, 0), 80.0, 2.0, dilation=1.0),), reached_target=True, report=RoutingReport(total_length=80.0), ) iterations_seen: list[int] = [] reroute_sets: list[set[str]] = [] def fake_run_iteration(self, state, iteration, reroute_net_ids, iteration_callback): _ = self _ = iteration_callback iterations_seen.append(iteration) reroute_sets.append(set(reroute_net_ids)) state.results = {"netA": colliding_a, "netB": colliding_b, "netC": completed_c} return _IterationReview( conflicting_nets={"netA", "netB"}, conflict_edges={("netA", "netB")}, completed_net_ids={"netC"}, total_dynamic_collisions=2, ) monkeypatch.setattr(PathFinder, "_run_iteration", fake_run_iteration) monkeypatch.setattr(PathFinder, "_verify_results", lambda self, state: (dict(state.results), {})) monkeypatch.setattr(PathFinder, "_run_pair_local_search", lambda self, state, review: None) results = pathfinder.route_all() assert iterations_seen == [0, 1] assert reroute_sets == [{"netA", "netB", "netC"}, {"netA", "netB"}] assert results["netA"].outcome == "colliding" assert results["netB"].outcome == "colliding" assert results["netC"].reached_target def test_routing_attempts_reserve_an_index_for_a_timed_out_worker(monkeypatch) -> None: net = NetSpec("track", Port(10, 20, 0), Port(90, 20, 0)) problem = RoutingProblem( (0, 0, 100, 50), (net,), initial_paths={net.net_id: PathSeed((StraightSeed(80),))}, ) options = RoutingOptions( search=SearchOptions(node_limit=0), topology=TopologyOptions(mode="off"), diagnostics=DiagnosticsOptions(capture_iteration_trace=True, capture_conflict_trace=True), ) callbacks = [] def expired(finder, state): if finder.metrics.total_route_iterations: state.timed_out = True finder.metrics.total_timeout_events = 1 return state.timed_out attempts = RoutingAttempts(lambda index, _: callbacks.append(index)) with monkeypatch.context() as patch: patch.setattr(PathFinder, "_expired", expired) timed_out = attempts.run(problem, options=options) selected = attempts.run(problem, options=options) assert timed_out.metrics.timeout_events == 1 assert attempts.metrics().route_iterations == 2 assert callbacks == [1] assert [entry.iteration for entry in selected.iteration_trace] == [1] assert [entry.iteration for entry in selected.conflict_trace if entry.stage == "iteration"] == [1] def test_rejected_pair_keeps_original_index_for_reverse_attempt(monkeypatch) -> None: problem = RoutingProblem( bounds=(0, 0, 100, 100), nets=tuple(NetSpec(net_id, Port(10, y, 0), Port(90, y, 0)) for net_id, y in (("a", 20), ("b", 40), ("c", 60))), ) options = RoutingOptions(congestion=CongestionOptions(warm_start_enabled=False), topology=TopologyOptions(mode="off")) world = RoutingWorld(clearance=problem.clearance) finder = PathFinder(AStarContext(CostEvaluator(world, DangerMap(bounds=problem.bounds)), problem, options)) state = finder._prepare_state() for net in problem.nets: path = (Straight.generate(net.start, 80, net.width, dilation=1.0),) finder._add_route(net.net_id, path) state.results[net.net_id] = RoutingResult(net.net_id, path, reached_target=True, report=world.verify_path_report(net.net_id, path)) initial_bounds = sorted(world.iter_dynamic_path_bounds(problem.bounds)) incumbent = dict(state.results) review = _IterationReview(set(), set(), set(incumbent), 0) attempted = [] def search(_context, _ordered, _results, pair_order, **_kwargs): attempted.append(pair_order) assert sorted(world.iter_dynamic_path_bounds(problem.bounds)) == initial_bounds if pair_order == ("a", "b"): return {"a": RoutingResult("a", incumbent["b"].path, reached_target=True), "b": incumbent["b"]}, 0 return None monkeypatch.setattr(router_module, "search_pair_candidate", search) assert finder._run_pair_local_target(state, ("a", "b"), review) is review assert attempted == [("a", "b"), ("b", "a")] assert state.results == incumbent assert sorted(world.iter_dynamic_path_bounds(problem.bounds)) == initial_bounds assert all(world.verify_path_report(net_id, result.path) == result.report for net_id, result in incumbent.items()) metrics = finder.metrics.snapshot() assert metrics.dynamic_path_objects_added == 7 assert metrics.dynamic_path_objects_removed == 4 def test_route_all_restores_best_iteration_snapshot_on_timeout(monkeypatch: pytest.MonkeyPatch) -> None: problem = RoutingProblem( bounds=(0, 0, 100, 100), nets=(NetSpec("netA", Port(10, 50, 0), Port(90, 50, 0), width=2.0),), ) options = RoutingOptions( congestion=CongestionOptions(max_iterations=2, warm_start_enabled=False), refinement=RefinementOptions(enabled=False), ) evaluator = CostEvaluator(RoutingWorld(clearance=2.0), DangerMap(bounds=problem.bounds)) pathfinder = PathFinder(AStarContext(evaluator, problem, options)) best_result = RoutingResult( net_id="netA", path=(Straight.generate(Port(10, 50, 0), 80.0, 2.0, dilation=1.0),), reached_target=True, report=RoutingReport(), ) worse_result = RoutingResult(net_id="netA", path=(), reached_target=False) def fake_run_iterations(self, state, iteration_callback): _ = iteration_callback _ = self state.results = {"netA": best_result} pathfinder._update_best_iteration( state, _IterationReview( conflicting_nets=set(), conflict_edges=set(), completed_net_ids={"netA"}, total_dynamic_collisions=0, ), ) state.best_is_indexed = True state.results = {"netA": worse_result} return True monkeypatch.setattr(PathFinder, "_run_iterations", fake_run_iterations) monkeypatch.setattr(PathFinder, "_verify_results", lambda self, state: (dict(state.results), {})) results = pathfinder.route_all() assert results["netA"].outcome == "completed" assert evaluator.collision_engine.has_dynamic_paths() def test_iteration_prefers_shorter_paths_at_equal_coverage() -> None: problem = RoutingProblem(bounds=(0, 0, 100, 100)) options = RoutingOptions(topology=TopologyOptions(mode="off")) world = RoutingWorld(clearance=problem.clearance) finder = PathFinder(AStarContext(CostEvaluator(world, DangerMap(bounds=problem.bounds)), problem, options)) review = _IterationReview(set(), set(), {"line"}, 0) def completed(length): segment = Straight.generate(Port(10, 10, 0), length, 2.0) return {"line": RoutingResult("line", (segment,), reached_target=True, report=RoutingReport(total_length=length))} incumbent = completed(20) assert finder._whole_set_is_better(completed(10), review, incumbent, review) assert not finder._whole_set_is_better(completed(20), review, incumbent, review) @pytest.mark.parametrize("during", ["preparation", "search"]) def test_worker_checks_timeout_inside_single_net_attempt(monkeypatch, during) -> None: clock = [0.0] monkeypatch.setattr(router_module.time, "monotonic", lambda: clock[0]) problem = RoutingProblem((0, 0, 100, 100), (NetSpec("line", Port(10, 50, 0), Port(90, 50, 0)),)) options = RoutingOptions( search=SearchOptions(node_limit=100), congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), refinement=RefinementOptions(enabled=False), topology=TopologyOptions(mode="off"), ) if during == "preparation": def expire_during_preparation(*_args): clock[0] = 61.0 monkeypatch.setattr(PathFinder, "_prepare_topology", expire_during_preparation) else: original_expand = search_module._expand_moves def expire_during_search(*args, **kwargs): original_expand(*args, **kwargs) clock[0] = 61.0 monkeypatch.setattr(search_module, "_expand_moves", expire_during_search) result = route(problem, options=options) assert result.metrics.timeout_events == 1 assert result.metrics.nodes_expanded == int(during == "search") assert not result.results_by_net["line"].is_valid def test_locked_routes_enable_incremental_requests_without_sessions() -> None: problem_a = RoutingProblem( bounds=(0, -50, 100, 50), nets=(NetSpec("netA", Port(10, 0, 0), Port(90, 0, 0), width=2.0),), ) options = RoutingOptions(search=SearchOptions(bend_radii=(10.0,))) results_a = route(problem_a, options=options) assert results_a.results_by_net["netA"].is_valid problem_b = RoutingProblem( bounds=(0, -50, 100, 50), nets=(NetSpec("netB", Port(50, -20, 90), Port(50, 20, 90), width=2.0),), static_obstacles=results_a.results_by_net["netA"].locked_geometry, ) results_b = route(problem_b, options=options) assert results_b.results_by_net["netB"].is_valid def test_close_net_widths_use_distinct_keepout_trees() -> None: narrow = NetSpec("narrow", Port(10, 20, 0), Port(90, 20, 0), width=2.00001) wide = NetSpec("wide", Port(10, 60, 0), Port(90, 60, 0), width=2.00004) problem = RoutingProblem((0, 0, 100, 100), (narrow, wide), (box(28, 21.00001, 75, 31),), clearance=0) options = RoutingOptions( search=SearchOptions(node_limit=40, bend_radii=(), sbend_radii=()), congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), topology=TopologyOptions(mode="off"), ) for candidate in (problem, replace(problem, nets=(wide, narrow))): run = route(candidate, options=options) assert all(result.is_valid for result in run.results_by_net.values()) assert run.metrics.static_net_tree_rebuilds == 2