diff --git a/docs/architecture.md b/docs/architecture.md index dfef92c..3581157 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -28,7 +28,7 @@ The near-port attempt uses up to 100 nodes per search and two congestion iterati - **Build and admit moves.** Weighted A* searches snapped positions and headings. Rays, visible corners, and corridor waypoints propose straight endpoints. If a ray blocks a launch, a flat-ended trace scan checks for room to move. An aligned target goes directly to admission, which checks the straight's rectangular footprint for clearance. S-bends can follow each other when the configured moves permit it. Admission also checks cost and state dominance. [Move generation](../inire/router/_astar_moves.py) -- **Recheck the installed set.** The driver raises the overlap penalty when successive routes collide. After an iteration it verifies the installed paths, since a later route can collide with one completed earlier. It ranks snapshots by completed nets, then by conflicts and dynamic collisions. A narrowed retry includes every net that still fails verification. [`next_reroute_net_ids()`](../inire/router/_congestion_policy.py#L93) +- **Recheck the installed set.** Paths that reach their targets participate in congestion checks. Partial paths remain available in the results for diagnosis. After an iteration the driver verifies the installed paths, since a later route can collide with one completed earlier. It ranks snapshots by completed nets, then by conflicts and dynamic collisions. A narrowed retry includes every net that still fails verification. [`next_reroute_net_ids()`](../inire/router/_congestion_policy.py#L93) - **Repair a small conflict set.** The driver returns to the best iteration and can reuse its verification when those paths are still installed and restored-stage traces are disabled. If the conflicts form separate pairs, the router can try repairing up to two of them. It holds the other paths fixed, tries both routing orders as needed, and checks proposed replacements against the installed layout. For a worked trace, [follow a late conflict](routing-diagnostics.md#follow-a-late-conflict-into-pair-local-repair). @@ -38,7 +38,7 @@ Search uses proxies to check moves and estimate congestion. Verification rejects At a keepout corner, a mitred clearance buffer can reach farther than the specified clearance. Verification checks the actual distance before counting these hits as collisions. For an example with a corner close to the required clearance, see the [mitred-corner test](../inire/tests/test_collision.py#L146). -When expansion counts are similar but routing time rises, inspect ray casts for repeated visibility queries and exact pair checks for an overly broad dynamic lookup. The [metrics guide](routing-diagnostics.md#route-metrics) maps those questions to counters. +Dynamic congestion queries use a grid for small spans and an R-tree for large spans. When expansion counts are similar but routing time rises, inspect ray casts for repeated visibility queries and exact pair checks for an overly broad dynamic lookup. The [metrics guide](routing-diagnostics.md#route-metrics) maps those questions to counters. Refinement tries replacing sections of routes with at least four 90-degree bends. It scores proposed detours before constructing their polygons. With a finite budget above one, it tries sections with bends at both ends first. With a budget of one or no window limit, it starts with the longest section by component count. It can check just the replacement when the original route is valid against the installed geometry. Final verification checks the entire updated route. diff --git a/docs/topological-routing.md b/docs/topological-routing.md index 8f3dcf9..e027d6c 100644 --- a/docs/topological-routing.md +++ b/docs/topological-routing.md @@ -10,7 +10,7 @@ Guide mode suggests where a path can pass through free space and lets detailed s In the offset-gates example, the two openings are at different heights. The top panel highlights the proposed sequence of triangle edges to cross. In the middle panel, the dashed line joins suggested crossing points. In the bottom panel, the solid route uses an S-bend to change height between the openings. -1. **Find connected space for centerlines.** Inset the board by half the widest guide's width and expand obstacles by that half-width plus clearance. To connect a port to the mesh, try a short straight along its departure or arrival heading, or use the port position itself. The common padding can exclude openings that a narrower net can still use in lattice search. +1. **Find connected space for centerlines.** Inset the board by half the widest guide's width and expand obstacles by that half-width plus clearance. To connect a port to the mesh, try a short straight along its departure or arrival heading, or use the port position itself. If the shared mesh finds no passage for a narrower net, retry with padding for its width. diff --git a/inire/geometry/collision.py b/inire/geometry/collision.py index d4994e1..f8bfd8f 100644 --- a/inire/geometry/collision.py +++ b/inire/geometry/collision.py @@ -360,8 +360,13 @@ class RoutingWorld: bounds: tuple[float, float, float, float], net_id: str, ) -> bool: - gx_min, gy_min, gx_max, gy_max = grid_cell_span(bounds, self.grid_cell_size) - cells = self._dynamic_paths.grid_net_obj_ids + span = grid_cell_span(bounds, self.grid_cell_size) + dynamic_paths = self._dynamic_paths + if dynamic_paths.uses_tree_for_span(span): + span_bounds = _span_to_bounds(*span, self.grid_cell_size) + return next(dynamic_paths.tree_candidates(net_id, span_bounds), None) is not None + gx_min, gy_min, gx_max, gy_max = span + cells = dynamic_paths.grid_net_obj_ids if gx_min == gx_max and gy_min == gy_max: members = cells.get((gx_min, gy_min)) @@ -453,8 +458,8 @@ class RoutingWorld: net_id: str, broad_phase_cache: dict[tuple[str, int, int, int, int], dict[str, tuple[int, ...]]] | None, ) -> dict[str, tuple[int, ...]]: - gx_min, gy_min, gx_max, gy_max = grid_cell_span(bounds, self.grid_cell_size) - cache_key = (net_id, gx_min, gy_min, gx_max, gy_max) + span = grid_cell_span(bounds, self.grid_cell_size) + cache_key = (net_id, *span) if broad_phase_cache is not None and cache_key in broad_phase_cache: if self.metrics is not None: self.metrics.total_congestion_grid_span_cache_hits += 1 @@ -465,12 +470,18 @@ class RoutingWorld: dynamic_paths = self._dynamic_paths candidates_by_net: dict[str, set[int]] = {} - for gx in range(gx_min, gx_max + 1): - for gy in range(gy_min, gy_max + 1): - for other_net_id, obj_ids in dynamic_paths.grid_net_obj_ids.get((gx, gy), {}).items(): - if other_net_id == net_id: - continue - candidates_by_net.setdefault(other_net_id, set()).update(obj_ids) + if dynamic_paths.uses_tree_for_span(span): + span_bounds = _span_to_bounds(*span, self.grid_cell_size) + for other_net_id, obj_id in dynamic_paths.tree_candidates(net_id, span_bounds): + candidates_by_net.setdefault(other_net_id, set()).add(obj_id) + else: + gx_min, gy_min, gx_max, gy_max = span + for gx in range(gx_min, gx_max + 1): + for gy in range(gy_min, gy_max + 1): + for other_net_id, obj_ids in dynamic_paths.grid_net_obj_ids.get((gx, gy), {}).items(): + if other_net_id == net_id: + continue + candidates_by_net.setdefault(other_net_id, set()).update(obj_ids) frozen = { other_net_id: tuple(sorted(obj_ids)) @@ -486,8 +497,8 @@ class RoutingWorld: net_id: str, grid_net_cache: dict[tuple[str, int, int, int, int], tuple[str, ...]] | None, ) -> tuple[str, ...]: - gx_min, gy_min, gx_max, gy_max = grid_cell_span(bounds, self.grid_cell_size) - cache_key = (net_id, gx_min, gy_min, gx_max, gy_max) + span = grid_cell_span(bounds, self.grid_cell_size) + cache_key = (net_id, *span) if grid_net_cache is not None and cache_key in grid_net_cache: if self.metrics is not None: self.metrics.total_congestion_grid_net_cache_hits += 1 @@ -497,12 +508,17 @@ class RoutingWorld: self.metrics.total_congestion_grid_net_cache_misses += 1 dynamic_paths = self._dynamic_paths - candidate_net_ids: set[str] = set() - for gx in range(gx_min, gx_max + 1): - for gy in range(gy_min, gy_max + 1): - for other_net_id in dynamic_paths.grid_net_obj_ids.get((gx, gy), {}): - if other_net_id != net_id: - candidate_net_ids.add(other_net_id) + if dynamic_paths.uses_tree_for_span(span): + span_bounds = _span_to_bounds(*span, self.grid_cell_size) + candidate_net_ids = {other_net_id for other_net_id, _ in dynamic_paths.tree_candidates(net_id, span_bounds)} + else: + gx_min, gy_min, gx_max, gy_max = span + candidate_net_ids = set() + for gx in range(gx_min, gx_max + 1): + for gy in range(gy_min, gy_max + 1): + for other_net_id in dynamic_paths.grid_net_obj_ids.get((gx, gy), {}): + if other_net_id != net_id: + candidate_net_ids.add(other_net_id) frozen = tuple(sorted(candidate_net_ids)) if grid_net_cache is not None: diff --git a/inire/geometry/dynamic_path_index.py b/inire/geometry/dynamic_path_index.py index 7ba78a6..2faee6b 100644 --- a/inire/geometry/dynamic_path_index.py +++ b/inire/geometry/dynamic_path_index.py @@ -4,16 +4,19 @@ from typing import TYPE_CHECKING import rtree -from inire.geometry.index_helpers import iter_grid_cells +from inire.geometry.index_helpers import grid_cell_count, grid_cell_span, iter_grid_cells if TYPE_CHECKING: - from collections.abc import Sequence + from collections.abc import Iterator, Sequence from shapely.geometry import Polygon from inire.geometry.collision import RoutingWorld +_MAX_GRID_CELLS = 1024 + + class DynamicPathIndex: """Index search proxies and physical polygons for installed paths.""" @@ -105,13 +108,16 @@ class DynamicPathIndex: *, cell_size: float, ) -> None: - cells = tuple(iter_grid_cells(bounds, cell_size)) + span = grid_cell_span(bounds, cell_size) + if grid_cell_count(span) > _MAX_GRID_CELLS: + return + cells = tuple(iter_grid_cells(span)) self.obj_cells[obj_id] = cells for cell in cells: self.grid_net_obj_ids.setdefault(cell, {}).setdefault(net_id, set()).add(obj_id) def _unregister_grid_membership(self, obj_id: int, net_id: str) -> None: - for cell in self.obj_cells.pop(obj_id): + for cell in self.obj_cells.pop(obj_id, ()): net_obj_ids = self.grid_net_obj_ids[cell] member_ids = net_obj_ids[net_id] member_ids.remove(obj_id) @@ -120,6 +126,15 @@ class DynamicPathIndex: if not net_obj_ids: del self.grid_net_obj_ids[cell] + def uses_tree_for_span(self, span: tuple[int, int, int, int]) -> bool: + return len(self.obj_cells) != len(self.dilated) or grid_cell_count(span) > _MAX_GRID_CELLS + + def tree_candidates(self, net_id: str, bounds: tuple[float, float, float, float]) -> Iterator[tuple[str, int]]: + for obj_id in self.index.intersection(bounds): + other_net_id = self.geometries[obj_id][0] + if other_net_id != net_id: + yield other_net_id, obj_id + def add_path( self, net_id: str, diff --git a/inire/geometry/index_helpers.py b/inire/geometry/index_helpers.py index 201dafe..3372c1a 100644 --- a/inire/geometry/index_helpers.py +++ b/inire/geometry/index_helpers.py @@ -33,11 +33,13 @@ def grid_cell_span( ) -def iter_grid_cells( - bounds: tuple[float, float, float, float], - cell_size: float, -) -> Iterator[tuple[int, int]]: - gx_min, gy_min, gx_max, gy_max = grid_cell_span(bounds, cell_size) +def grid_cell_count(span: tuple[int, int, int, int]) -> int: + gx_min, gy_min, gx_max, gy_max = span + return (gx_max - gx_min + 1) * (gy_max - gy_min + 1) + + +def iter_grid_cells(span: tuple[int, int, int, int]) -> Iterator[tuple[int, int]]: + gx_min, gy_min, gx_max, gy_max = span for gx in range(gx_min, gx_max + 1): for gy in range(gy_min, gy_max + 1): yield (gx, gy) diff --git a/inire/router/_astar_moves.py b/inire/router/_astar_moves.py index 131d1ef..2141e8d 100644 --- a/inire/router/_astar_moves.py +++ b/inire/router/_astar_moves.py @@ -207,7 +207,7 @@ def expand_moves( net_width=net_width, caller="expand_forward", ) - if current.parent is None and max_reach < search_options.min_straight_length: + if current.parent is None and max_reach < max(1, math.ceil(search_options.min_straight_length)): # Radius around the ray can block a launch at an otherwise clear port face. reach = collision.straight_reach(cp, search_options.max_straight_length, net_width) max_reach = max(max_reach, math.floor(reach + TOLERANCE_LINEAR)) diff --git a/inire/router/_pair_local.py b/inire/router/_pair_local.py index 08a5d88..2a078ce 100644 --- a/inire/router/_pair_local.py +++ b/inire/router/_pair_local.py @@ -23,8 +23,6 @@ def _build_pair_local_context( ordered_nets: tuple[NetSpec, ...], incumbent_results: Mapping[str, RoutingResult], pair_order: tuple[str, str], - *, - lock_partial_paths: bool, ) -> AStarContext: problem = context.problem live_world = context.cost_evaluator.collision_engine @@ -36,7 +34,7 @@ def _build_pair_local_context( if net.net_id in pair_order: continue result = incumbent_results.get(net.net_id) - if result is None or not result.path or (not lock_partial_paths and not result.reached_target): + if result is None or not result.reached_target: continue for component in result.path: for polygon in component.physical_geometry: @@ -72,10 +70,9 @@ def search_pair_candidate( pair_order: tuple[str, str], *, needs_self_collision_check: Set[str], - lock_partial_paths: bool, ) -> tuple[dict[str, RoutingResult], int] | None: """Return both locally verified replacements and their search work.""" - local = _build_pair_local_context(context, ordered_nets, incumbent_results, pair_order, lock_partial_paths=lock_partial_paths) + local = _build_pair_local_context(context, ordered_nets, incumbent_results, pair_order) world = local.cost_evaluator.collision_engine options = local.options nets = {net.net_id: net for net in ordered_nets} diff --git a/inire/router/_router.py b/inire/router/_router.py index 2994c5c..eb958e2 100644 --- a/inire/router/_router.py +++ b/inire/router/_router.py @@ -359,7 +359,7 @@ class PathFinder: self.context.cost_evaluator.collision_engine.remove_path(net_id) for net_id in ordered_net_ids: result = results.get(net_id) - if result and result.path and (result.reached_target or not state.corridors): + if result and result.path and result.reached_target: self._install_path(net_id, result.path) def _review_restored_best(self, state: _RoutingState) -> _IterationReview: @@ -526,7 +526,8 @@ class PathFinder: ) net = state.net_specs[net_id] - with self._frontier_replay(net_id, result.path) as scratch_metrics: + installed_path = result.path if result.reached_target else () + with self._frontier_replay(net_id, installed_path) as scratch_metrics: route_astar( net.start, net.target, @@ -792,7 +793,6 @@ class PathFinder: incumbent_results, pair_order, needs_self_collision_check=state.needs_self_collision_check, - lock_partial_paths=not state.corridors, ) if candidate is None: continue @@ -891,12 +891,10 @@ class PathFinder: reached_target = path[-1].end_port == net.target if not reached_target and self._has_incumbent_fallback(incumbent_fallback): return self._restore_incumbent_fallback(net_id, incumbent_fallback, guidance_seed_present) + report = None if reached_target: self.metrics.total_nets_reached_target += 1 - report = None - if reached_target or not state.corridors: self._install_path(net_id, path) - if reached_target: report = self.context.cost_evaluator.collision_engine.verify_path_report(net_id, path) if report.self_collision_count > 0: state.needs_self_collision_check.add(net_id) diff --git a/inire/router/_topology.py b/inire/router/_topology.py index add32d4..ccc0256 100644 --- a/inire/router/_topology.py +++ b/inire/router/_topology.py @@ -414,9 +414,26 @@ def plan_corridors( return {} board = box(*bounds) - mesh = _Mesh(board, obstacles, max(net.width for net in nets) / 2, clearance) - endpoints, leads = _endpoint_access(mesh, nets, bend_radius) - assignments = _plan_lane_assignments( - mesh, nets, endpoints, leads, bend_radius=bend_radius, limit=limit, joint_net_ids=joint_net_ids - ) - return _build_corridors(mesh, board, nets, assignments, bend_radius) + keepouts = tuple(obstacles) + + def plan_group(group: Sequence[NetSpec], width: float) -> dict[str, tuple[Corridor, ...]]: + mesh = _Mesh(board, keepouts, width / 2, clearance) + endpoints, leads = _endpoint_access(mesh, group, bend_radius) + assignments = _plan_lane_assignments( + mesh, group, endpoints, leads, bend_radius=bend_radius, limit=limit, joint_net_ids=joint_net_ids + ) + return _build_corridors(mesh, board, group, assignments, bend_radius) + + widest = max(net.width for net in nets) + guides = plan_group(nets, widest) + if joint_net_ids: + return guides + + # Keep shared lane assignments and recover passages closed by the widest net's padding. + missing_by_width: dict[float, list[NetSpec]] = {} + for net in nets: + if net.width < widest and net.net_id not in guides: + missing_by_width.setdefault(net.width, []).append(net) + for width, group in missing_by_width.items(): + guides.update(plan_group(group, width)) + return {net.net_id: guides[net.net_id] for net in nets if net.net_id in guides} diff --git a/inire/tests/test_api.py b/inire/tests/test_api.py index dfb720e..94864a3 100644 --- a/inire/tests/test_api.py +++ b/inire/tests/test_api.py @@ -472,11 +472,12 @@ def test_lattice_straight_uses_flat_port_faces_for_clearance(mode, obstacle, val assert route(problem, options=options).results_by_net["line"].is_valid is valid -def test_lattice_can_launch_a_straight_before_a_bend_from_flat_port_face() -> None: +@pytest.mark.parametrize("min_length", [0, 0.5, 5]) +def test_lattice_can_launch_a_straight_before_a_bend_from_flat_port_face(min_length) -> None: net = NetSpec("turn", Port(10, 20, 0), Port(50, 30, 90)) - problem = RoutingProblem((0, 0, 90, 90), (net,), (box(4, 16, 8, 24),), clearance=2) + problem = RoutingProblem((0, 15, 60, 32), (net,), (box(4, 16, 8, 24),), clearance=2) options = RoutingOptions( - search=SearchOptions(node_limit=100, bend_radii=(10,), sbend_radii=()), + search=SearchOptions(node_limit=100, min_straight_length=min_length, bend_radii=(10,), sbend_radii=()), congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), topology=TopologyOptions(mode="off"), ) @@ -487,6 +488,26 @@ def test_lattice_can_launch_a_straight_before_a_bend_from_flat_port_face() -> No assert result.as_seed() == PathSeed((StraightSeed(30), Bend90Seed(10, "CCW"))) +def test_lattice_partial_path_leaves_crossing_net_valid() -> None: + blocked = NetSpec("blocked", Port(10, 100, 0), Port(170, 100, 0)) + through = NetSpec("through", Port(80, 40, 90), Port(80, 160, 90)) + problem = RoutingProblem((0, 0, 200, 200), (blocked, through), (box(125, 94, 145, 106),)) + options = RoutingOptions( + search=SearchOptions(node_limit=100, bend_radii=(), sbend_radii=()), + congestion=CongestionOptions(max_iterations=3, warm_start_enabled=False), + diagnostics=DiagnosticsOptions(capture_conflict_trace=True), + topology=TopologyOptions(mode="off"), + ) + + run = route(problem, options=options) + partial, complete = run.results_by_net["blocked"], run.results_by_net["through"] + + assert partial.outcome == "partial" + assert partial.locked_geometry[0].intersects(complete.locked_geometry[0]) + assert complete.is_valid + assert all(entry.conflict_edges == () for entry in run.conflict_trace) + + @pytest.mark.parametrize("mode", ["off", "guide", "seed", "automatic"]) def test_search_can_find_consecutive_sbends(mode) -> None: net = NetSpec("double", Port(20, 20, 0), Port(48, 30, 0)) diff --git a/inire/tests/test_astar.py b/inire/tests/test_astar.py index e87a883..a9b3c0e 100644 --- a/inire/tests/test_astar.py +++ b/inire/tests/test_astar.py @@ -266,7 +266,7 @@ def test_pair_local_context_clones_live_static_obstacles() -> None: ) context = AStarContext(evaluator, problem, RoutingOptions()) - local_context = _build_pair_local_context(context, problem.nets, {}, ("pair_a", "pair_b"), lock_partial_paths=True) + local_context = _build_pair_local_context(context, problem.nets, {}, ("pair_a", "pair_b")) assert context.problem.static_obstacles == () assert len(local_context.problem.static_obstacles) == 1 @@ -287,7 +287,7 @@ def test_worker_samples_proximity_only_for_objectives_it_uses(search_danger, ref refinement=RefinementOptions(enabled=refinement_enabled, objective=ObjectiveWeights(danger_weight=1.0)), ) stack = build_routing_stack(problem, options) - local = _build_pair_local_context(stack.context, problem.nets, {}, ("pair_a", "pair_b"), lock_partial_paths=True) + local = _build_pair_local_context(stack.context, problem.nets, {}, ("pair_a", "pair_b")) assert (stack.danger_map.tree is not None) == expected_tree assert (local.cost_evaluator.danger_map.tree is not None) == bool(search_danger) diff --git a/inire/tests/test_collision.py b/inire/tests/test_collision.py index 2ab0485..c5d3ef8 100644 --- a/inire/tests/test_collision.py +++ b/inire/tests/test_collision.py @@ -425,6 +425,28 @@ def test_dynamic_grid_updates_incrementally_on_add_and_remove() -> None: assert "netB" in dynamic_paths.grid_net_obj_ids.get((0, 0), {}) +@pytest.mark.parametrize("large_install", [True, False]) +def test_large_dynamic_spans_use_tree_for_congestion(large_install) -> None: + engine = RoutingWorld(clearance=2) + installed = Straight.generate(Port(0, 0, 0), 100_000 if large_install else 20, width=2, dilation=1) + query = Straight.generate(Port(10, -10, 90), 20 if large_install else 100_000, width=2, dilation=1) + engine.install_path("peer", (installed,)) + index = engine._dynamic_paths + + assert bool(index.grid_net_obj_ids) is (not large_install) + assert engine.has_possible_move_congestion(query, "query") + assert engine.has_candidate_move_congestion(query, "query") + assert engine.check_move_congestion(query, "query") == 1 + assert engine.verify_path_report("query", (query,)).dynamic_collision_count == 1 + assert engine.check_move_congestion(query, "peer") == 0 + + engine.remove_path("peer") + + assert not engine.has_possible_move_congestion(query, "query") + assert engine.check_move_congestion(query, "query") == 0 + assert not index.grid_net_obj_ids + + def test_dynamic_net_envelopes_update_incrementally_on_add_and_remove() -> None: engine = RoutingWorld(clearance=2.0) engine.metrics = AStarMetrics() diff --git a/inire/tests/test_failed_net_congestion.py b/inire/tests/test_failed_net_congestion.py index 4e09f82..38d7815 100644 --- a/inire/tests/test_failed_net_congestion.py +++ b/inire/tests/test_failed_net_congestion.py @@ -1,77 +1,24 @@ from shapely.geometry import box -from inire import CongestionOptions, RoutingOptions, RoutingProblem -from inire.geometry.primitives import Port -from inire.geometry.collision import RoutingWorld -from inire.model import NetSpec -from inire.router._astar_types import AStarContext -from inire.router._router import PathFinder -from inire.router.cost import CostEvaluator -from inire.router.danger_map import DangerMap +from inire import CongestionOptions, NetSpec, Port, RoutingOptions, RoutingProblem, SearchOptions, TopologyOptions +from inire.router._stack import build_routing_stack -def test_failed_net_visibility() -> None: - """ - Verifies that nets that fail to reach their target (return partial paths) - ARE added to the collision engine, making them visible to other nets - for negotiated congestion. - """ - # 1. Setup - engine = RoutingWorld(clearance=2.0) - # Create a simple danger map (bounds 0-100) - # We don't strictly need obstacles in it for this test. - dm = DangerMap(bounds=(0, 0, 100, 100)) - - evaluator = CostEvaluator(engine, dm) - - # 2. Configure Router with low limit to FORCE failure - # node_limit=10 is extremely low, likely allowing only a few moves. - # Start (0,0) -> Target (100,0) is 100um away. - - # Let's add a static obstacle that blocks the direct path. - obstacle = box(40, -10, 60, 10) # Wall at x=50 - engine.add_static_obstacle(obstacle) - - # With obstacle, direct jump fails. A* must search around. - # Limit=10 should be enough to fail to find a path around. - netlist = { - "net1": (Port(0, 0, 0), Port(100, 0, 0)) - } - net_widths = {"net1": 1.0} - pf = PathFinder( - AStarContext( - evaluator, - RoutingProblem( - bounds=(0, 0, 100, 100), - 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() - ), - ), - RoutingOptions( - search=RoutingOptions().search.__class__(node_limit=10), - congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), - ), - ), +def test_partial_path_is_returned_without_installing_it() -> None: + problem = RoutingProblem( + bounds=(0, 0, 100, 100), + nets=(NetSpec("blocked", Port(0, 50, 0), Port(100, 50, 0)),), + static_obstacles=(box(40, 40, 60, 60),), ) + options = RoutingOptions( + search=SearchOptions(node_limit=10, bend_radii=(), sbend_radii=()), + congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), + topology=TopologyOptions(mode="off"), + ) + stack = build_routing_stack(problem, options) - # 4. Route - print("\nStarting Route...") - results = pf.route_all() + result = stack.finder.route_all()["blocked"] - res = results["net1"] - print(f"Result: is_valid={res.is_valid}, reached={res.reached_target}, path_len={len(res.path)}") - - # 5. Verify Failure Condition - # We expect reached_target to be False because of node_limit + obstacle - assert not res.reached_target, "Test setup failed: Net reached target despite low limit!" - assert len(res.path) > 0, "Test setup failed: No partial path returned!" - - # 6. Verify Visibility - # Check if net1 is in the collision engine - found_nets = {net_id for net_id, _ in engine._dynamic_paths.geometries.values()} - - print(f"Nets found in engine: {found_nets}") - - # The FIX Expectation: "net1" SHOULD be present - assert "net1" in found_nets, "Bug present: Net1 is invisible despite having partial path!" + assert result.outcome == "partial" + assert result.path + assert not stack.world.has_dynamic_paths() diff --git a/inire/tests/test_topology.py b/inire/tests/test_topology.py index 81b92b2..cf615ac 100644 --- a/inire/tests/test_topology.py +++ b/inire/tests/test_topology.py @@ -74,6 +74,27 @@ def test_seed_mode_respects_user_paths_on_repeated_runs() -> None: assert list(stack.world.iter_static_dilated_geometries()) == [] +@pytest.mark.parametrize("mode", ["guide", "seed"]) +def test_narrow_net_recovers_corridors_with_a_wide_peer(mode) -> None: + wide = NetSpec("wide", Port(12, 200, 0), Port(30, 200, 0), width=180) + problem = replace(DETOUR.problem, nets=(*DETOUR.problem.nets, wide)) + options = replace( + DETOUR.options, + search=replace(DETOUR.options.search, node_limit=100), + congestion=replace(DETOUR.options.congestion, max_iterations=1, warm_start_enabled=False), + topology=TopologyOptions(mode=mode), + ) + + run = route(problem, options=options) + + assert run.topology is not None + assert run.topology.corridor_counts == (("detour", 2),) + assert run.results_by_net["wide"].is_valid + if mode == "seed": + assert run.topology.seeded_net_ids == ("detour",) + assert run.results_by_net["detour"].is_valid + + def test_topological_routing_falls_back_for_ports_outside_the_inset_mesh() -> None: problem = RoutingProblem(bounds=(0, 0, 100, 100), nets=(NetSpec("edge", Port(0, 50, 0), Port(100, 50, 0)),)) options = RoutingOptions(