Reject invalid path reservations and improve seeded routing

This commit is contained in:
Jan Petykiewicz 2026-11-28 00:09:11 -08:00
commit e0f5543578
16 changed files with 265 additions and 84 deletions

View file

@ -26,21 +26,21 @@ The near-port attempt uses up to 100 nodes per search and two congestion iterati
## Detailed search and congestion ## Detailed search and congestion
- **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) - **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. A long lead can use consecutive straights when a single forward scan cannot cover it. 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.** 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) - **Recheck the installed set.** Paths that reach their targets and pass geometry checks against themselves, the board, and keepouts participate in congestion. Partial and geometrically invalid paths remain available 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#L99)
- **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). - **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).
## Geometry and refinement ## Geometry and refinement
Search uses proxies to check moves and estimate congestion. Verification rejects invalid polygons and checks each port for a finite-width face with material on the correct side. It checks for overlap within and between components, and checks the route against keepouts, other nets, and the board rectangle in every routing mode. Refinement uses the same configured bend geometry as search and seed materialization. A circular S-bend with a fractional forward span ends with a short tangent extension to the next grid point, keeping the requested radius. Boundary contact with the board is allowed. Search uses proxies to check moves and estimate congestion. Verification rejects invalid polygons and checks each port for a finite-width face with material on the correct side. It checks for overlap within components and unintended contact between components, and checks the route against keepouts, other nets, and the board rectangle in every routing mode. Refinement uses the same configured bend geometry as search and seed materialization. A circular S-bend with a fractional forward span ends with a short tangent extension to the next grid point, keeping the requested radius. Boundary contact with the board is allowed.
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). 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).
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. 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. Refinement tries replacing sections of routes with at least four 90-degree bends. It indexes endpoints by heading and forward position to find eligible sections, then 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 eligible 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.
## Validate a change ## Validate a change

View file

@ -85,7 +85,7 @@ For a multi-net layout, apply the validity check to every net you intend to expo
## Reuse an existing route ## Reuse an existing route
- **Give the router a route it can move.** Put `result.as_seed()` in `initial_paths` under the net's ID. A seed uses the current start port, width, and geometry settings. A partial seed can suggest an approach. To build a hint from turns and straights, see the [path seed reference](api-reference.md#path-seeds). - **Give the router a route it can move.** Put `result.as_seed()` in `initial_paths` under the net's ID. A seed uses the current start port, width, and geometry settings. Search can follow a partial seed from the first iteration and can leave it to find another approach. To build a hint from turns and straights, see the [path seed reference](api-reference.md#path-seeds).
- **Hold a route fixed.** Check `result.is_valid`, then add `result.locked_geometry` to `static_obstacles` while routing other nets. The next run applies its own clearance to those polygons. - **Hold a route fixed.** Check `result.is_valid`, then add `result.locked_geometry` to `static_obstacles` while routing other nets. The next run applies its own clearance to those polygons.
Route a straight net, then use its polygons as keepouts in a second routing problem. The second net has to detour around one end of the fixed route. Route a straight net, then use its polygons as keepouts in a second routing problem. The second net has to detour around one end of the fixed route.

View file

@ -1,6 +1,6 @@
from __future__ import annotations from __future__ import annotations
from dataclasses import dataclass from dataclasses import dataclass, replace
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
import numpy import numpy
@ -611,6 +611,7 @@ class RoutingWorld:
components: Sequence[ComponentResult], components: Sequence[ComponentResult],
*, *,
capture_component_conflicts: bool = False, capture_component_conflicts: bool = False,
include_invalid_dynamic: bool = True,
) -> PathVerificationDetail: ) -> PathVerificationDetail:
if self.metrics is not None: if self.metrics is not None:
self.metrics.total_verify_path_report_calls += 1 self.metrics.total_verify_path_report_calls += 1
@ -643,7 +644,14 @@ class RoutingWorld:
if _violates_clearance(polygon, obstacle, self.clearance): if _violates_clearance(polygon, obstacle, self.clearance):
static_collision_count += 1 static_collision_count += 1
if dynamic_paths.has_physical_paths(): report = RoutingReport(
static_collision_count=static_collision_count,
self_collision_count=count_path_self_collisions(components),
total_length=total_length,
out_of_bounds=self.board is not None and not path_within_board(components, self.board),
discontinuous=not continuous,
)
if (include_invalid_dynamic or not report.intrinsic_collision_count) and dynamic_paths.has_physical_paths():
clearance = max(0.0, self.clearance) clearance = max(0.0, self.clearance)
for component_index, component in enumerate(components): for component_index, component in enumerate(components):
component_hits: set[str] = set() component_hits: set[str] = set()
@ -668,14 +676,7 @@ class RoutingWorld:
conflicting_net_ids.update(component_hits) conflicting_net_ids.update(component_hits)
return PathVerificationDetail( return PathVerificationDetail(
report=RoutingReport( report=replace(report, dynamic_collision_count=dynamic_collision_count) if dynamic_collision_count else report,
static_collision_count=static_collision_count,
dynamic_collision_count=dynamic_collision_count,
self_collision_count=count_path_self_collisions(components),
total_length=total_length,
out_of_bounds=self.board is not None and not path_within_board(components, self.board),
discontinuous=not continuous,
),
conflicting_net_ids=tuple(sorted(conflicting_net_ids)), conflicting_net_ids=tuple(sorted(conflicting_net_ids)),
component_conflicts=tuple(sorted(component_conflicts)), component_conflicts=tuple(sorted(component_conflicts)),
) )

View file

@ -35,11 +35,11 @@ def components_overlap(
bounds_a = component_a.total_bounds bounds_a = component_a.total_bounds
bounds_b = component_b.total_bounds bounds_b = component_b.total_bounds
if not ( if (
bounds_a[0] < bounds_b[2] bounds_a[0] > bounds_b[2]
and bounds_a[2] > bounds_b[0] or bounds_a[2] < bounds_b[0]
and bounds_a[1] < bounds_b[3] or bounds_a[1] > bounds_b[3]
and bounds_a[3] > bounds_b[1] or bounds_a[3] < bounds_b[1]
): ):
return False return False
@ -48,13 +48,13 @@ def components_overlap(
if at_join: if at_join:
# Sampling a bend can leave sub-tolerance slivers at its shared face. # Sampling a bend can leave sub-tolerance slivers at its shared face.
overlap = polygon_a.intersection(polygon_b) overlap = polygon_a.intersection(polygon_b)
if overlap.area > 0: if not overlap.is_empty:
port = component_a.end_port port = component_a.end_port
axis, position = (0, port.x) if port.r % 180 == 0 else (1, port.y) axis, position = (0, port.x) if port.r % 180 == 0 else (1, port.y)
bounds = overlap.bounds bounds = overlap.bounds
if bounds[axis] < position - TOLERANCE_LINEAR or bounds[axis + 2] > position + TOLERANCE_LINEAR: if bounds[axis] < position - TOLERANCE_LINEAR or bounds[axis + 2] > position + TOLERANCE_LINEAR:
return True return True
elif polygon_a.intersects(polygon_b) and not polygon_a.touches(polygon_b): elif polygon_a.intersects(polygon_b) and (prefer_actual or not polygon_a.touches(polygon_b)):
return True return True
return False return False

View file

@ -29,12 +29,16 @@ class RoutingReport:
invalid_geometry: bool = False invalid_geometry: bool = False
@property @property
def collision_count(self) -> int: def intrinsic_collision_count(self) -> int:
return ( return (
self.static_collision_count + self.dynamic_collision_count + self.self_collision_count self.static_collision_count + self.self_collision_count
+ int(self.out_of_bounds) + int(self.discontinuous) + int(self.invalid_geometry) + int(self.out_of_bounds) + int(self.discontinuous) + int(self.invalid_geometry)
) )
@property
def collision_count(self) -> int:
return self.intrinsic_collision_count + self.dynamic_collision_count
@property @property
def is_valid(self) -> bool: def is_valid(self) -> bool:
return self.collision_count == 0 return self.collision_count == 0

View file

@ -8,6 +8,7 @@ from inire.geometry.components import bend_fits_width, bend90_grid_span
from inire.geometry.sbend import sbend_grid_span from inire.geometry.sbend import sbend_grid_span
from ._astar_admission import process_move from ._astar_admission import process_move
from ._seed_materialization import seed_move
if TYPE_CHECKING: if TYPE_CHECKING:
from inire.geometry.primitives import Port from inire.geometry.primitives import Port
@ -159,9 +160,16 @@ def expand_moves(
config: SearchRunConfig, config: SearchRunConfig,
) -> None: ) -> None:
search_options = context.options.search search_options = context.options.search
scan_limit = search_options.max_straight_length
cp = current.port cp = current.port
previous = current.component_result previous = current.component_result
prev_straight_length = previous.length if previous is not None and previous.move_type == "straight" else None seed_index = current.seed_index if config.propose_guidance_moves else None
prev_straight_length = previous.length if seed_index is None and previous is not None and previous.move_type == "straight" else None
seed = config.guidance_seed
if seed is not None and seed_index is not None and seed_index < len(seed):
kind, parameters = seed_move(seed[seed_index])
process_move(current, target, net_width, net_id, open_set, closed_set, context, metrics, congestion, config, kind, parameters)
dx_t = target.x - cp.x dx_t = target.x - cp.x
dy_t = target.y - cp.y dy_t = target.y - cp.y
dist_sq = dx_t * dx_t + dy_t * dy_t dist_sq = dx_t * dx_t + dy_t * dy_t
@ -183,7 +191,11 @@ def expand_moves(
collision = context.cost_evaluator.collision_engine collision = context.cost_evaluator.collision_engine
if ( if (
proj_t > 0 and abs(perp_t) < TOLERANCE_LINEAR and cp.r == target.r proj_t > 0 and abs(perp_t) < TOLERANCE_LINEAR and cp.r == target.r
and (prev_straight_length is None or proj_t < prev_straight_length - TOLERANCE_LINEAR) and (
prev_straight_length is None
or proj_t < prev_straight_length - TOLERANCE_LINEAR
or prev_straight_length + proj_t > scan_limit + TOLERANCE_LINEAR
)
): ):
process_move( process_move(
current, current,
@ -203,13 +215,13 @@ def expand_moves(
max_reach = collision.ray_cast( max_reach = collision.ray_cast(
cp, cp,
cp.r, cp.r,
search_options.max_straight_length, scan_limit,
net_width=net_width, net_width=net_width,
caller="expand_forward", caller="expand_forward",
) )
if current.parent is None and max_reach < max(1, math.ceil(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. # 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) reach = collision.straight_reach(cp, scan_limit, net_width)
max_reach = max(max_reach, math.floor(reach + TOLERANCE_LINEAR)) max_reach = max(max_reach, math.floor(reach + TOLERANCE_LINEAR))
if _should_cap_straights_to_bounds(context): if _should_cap_straights_to_bounds(context):
max_reach = min(max_reach, _distance_to_bounds_in_heading(cp, context.problem.bounds)) max_reach = min(max_reach, _distance_to_bounds_in_heading(cp, context.problem.bounds))
@ -261,7 +273,11 @@ def expand_moves(
for length in _quantized_lengths(candidate_lengths, max_reach): for length in _quantized_lengths(candidate_lengths, max_reach):
if length < search_options.min_straight_length: if length < search_options.min_straight_length:
continue continue
if prev_straight_length is not None and length >= prev_straight_length - TOLERANCE_LINEAR: if (
prev_straight_length is not None
and length >= prev_straight_length - TOLERANCE_LINEAR
and prev_straight_length + length <= scan_limit + TOLERANCE_LINEAR
):
continue continue
process_move( process_move(
current, current,

View file

@ -94,6 +94,7 @@ class SearchRunConfig:
corridor_strength: float = 0.0 corridor_strength: float = 0.0
restrict_to_corridor: bool = False restrict_to_corridor: bool = False
hard_congestion: bool = False hard_congestion: bool = False
propose_guidance_moves: bool = False
def estimate_remaining_cost(self, current: Port, target: Port, context: AStarContext) -> float: def estimate_remaining_cost(self, current: Port, target: Port, context: AStarContext) -> float:
evaluator = context.cost_evaluator evaluator = context.cost_evaluator
@ -121,6 +122,7 @@ class SearchRunConfig:
corridor_strength: float = 0.0, corridor_strength: float = 0.0,
restrict_to_corridor: bool = False, restrict_to_corridor: bool = False,
hard_congestion: bool = False, hard_congestion: bool = False,
propose_guidance_moves: bool = False,
) -> SearchRunConfig: ) -> SearchRunConfig:
search = options.search search = options.search
bend_collision_type, bend_physical_geometry = resolve_bend_geometry( bend_collision_type, bend_physical_geometry = resolve_bend_geometry(
@ -144,6 +146,7 @@ class SearchRunConfig:
corridor_strength=corridor_strength, corridor_strength=corridor_strength,
restrict_to_corridor=restrict_to_corridor, restrict_to_corridor=restrict_to_corridor,
hard_congestion=hard_congestion, hard_congestion=hard_congestion,
propose_guidance_moves=propose_guidance_moves,
) )

View file

@ -3,7 +3,7 @@
from __future__ import annotations from __future__ import annotations
from dataclasses import dataclass from dataclasses import dataclass
from typing import TYPE_CHECKING from typing import TYPE_CHECKING, TypeGuard
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Iterable, Mapping, Sequence, Set from collections.abc import Iterable, Mapping, Sequence, Set
@ -64,6 +64,10 @@ def all_results_reached_target(ordered_net_ids: Sequence[str], results: Mapping[
return len(results) == len(ordered_net_ids) and all(result.reached_target for result in results.values()) return len(results) == len(ordered_net_ids) and all(result.reached_target for result in results.values())
def can_reserve(result: RoutingResult | None) -> TypeGuard[RoutingResult]:
return bool(result and result.path and result.reached_target and not result.report.intrinsic_collision_count)
def reroute_plan( def reroute_plan(
ordered_net_ids: Sequence[str], ordered_net_ids: Sequence[str],
reroute_net_ids: Set[str], reroute_net_ids: Set[str],
@ -87,7 +91,9 @@ def reroute_plan(
return routed_net_ids, set() return routed_net_ids, set()
heaviest = sorted(routed_net_ids, key=lambda net_id: (-recent_attempt_work.get(net_id, 0), order_index[net_id]))[:2] heaviest = sorted(routed_net_ids, key=lambda net_id: (-recent_attempt_work.get(net_id, 0), order_index[net_id]))[:2]
return routed_net_ids, {net_id for net_id in heaviest if recent_attempt_work.get(net_id, 0) >= 200} return routed_net_ids, {
net_id for net_id in heaviest if recent_attempt_work.get(net_id, 0) >= 200 and not results[net_id].report.intrinsic_collision_count
}
def next_reroute_net_ids( def next_reroute_net_ids(

View file

@ -8,6 +8,7 @@ from inire.geometry.collision import RoutingWorld
from inire.model import RoutingProblem from inire.model import RoutingProblem
from inire.results import RoutingResult from inire.results import RoutingResult
from inire.router._astar_types import AStarContext, AStarMetrics, SearchRunConfig from inire.router._astar_types import AStarContext, AStarMetrics, SearchRunConfig
from inire.router._congestion_policy import can_reserve
from inire.router._search import incumbent_guidance, route_astar from inire.router._search import incumbent_guidance, route_astar
from inire.router.cost import CostEvaluator from inire.router.cost import CostEvaluator
from inire.router.danger_map import DangerMap from inire.router.danger_map import DangerMap
@ -34,7 +35,7 @@ def _build_pair_local_context(
if net.net_id in pair_order: if net.net_id in pair_order:
continue continue
result = incumbent_results.get(net.net_id) result = incumbent_results.get(net.net_id)
if result is None or not result.reached_target: if not can_reserve(result):
continue continue
for component in result.path: for component in result.path:
for polygon in component.physical_geometry: for polygon in component.physical_geometry:

View file

@ -25,6 +25,7 @@ from inire.router._astar_types import AStarContext, AStarMetrics, FrontierTraceC
from inire.router._congestion_policy import ( from inire.router._congestion_policy import (
IterationReview as _IterationReview, IterationReview as _IterationReview,
all_results_reached_target, all_results_reached_target,
can_reserve,
next_reroute_net_ids, next_reroute_net_ids,
ordered_nets, ordered_nets,
reached_pair_local_plateau, reached_pair_local_plateau,
@ -34,7 +35,7 @@ from inire.router._congestion_policy import (
) )
from inire.router._pair_local import search_pair_candidate from inire.router._pair_local import search_pair_candidate
from inire.router._route_traces import conflict_trace_entry, iteration_trace_entry, net_attempt_trace from inire.router._route_traces import conflict_trace_entry, iteration_trace_entry, net_attempt_trace
from inire.router._search import incumbent_guidance, route_astar from inire.router._search import incumbent_guidance, path_guidance, route_astar
from inire.router._seed_materialization import materialize_path_seed from inire.router._seed_materialization import materialize_path_seed
from inire.router.refiner import PathRefiner from inire.router.refiner import PathRefiner
@ -140,9 +141,6 @@ class PathFinder:
def _metric_deltas(self, before: dict[str, int], after: dict[str, int]) -> dict[str, int]: def _metric_deltas(self, before: dict[str, int], after: dict[str, int]) -> dict[str, int]:
return {metric_name: after[metric_name] - before[metric_name] for metric_name in before} return {metric_name: after[metric_name] - before[metric_name] for metric_name in before}
def _has_incumbent_fallback(self, result: RoutingResult | None) -> bool:
return bool(result and result.reached_target and result.path)
def _restore_incumbent_fallback( def _restore_incumbent_fallback(
self, self,
net_id: str, net_id: str,
@ -179,6 +177,7 @@ class PathFinder:
) -> dict[str, tuple[ComponentResult, ...]]: ) -> dict[str, tuple[ComponentResult, ...]]:
greedy_paths: dict[str, tuple[ComponentResult, ...]] = {} greedy_paths: dict[str, tuple[ComponentResult, ...]] = {}
greedy_node_limit = min(self.context.options.search.node_limit, 2000) greedy_node_limit = min(self.context.options.search.node_limit, 2000)
world = self.context.cost_evaluator.collision_engine
with self._temporary_path_reservations() as reserve: with self._temporary_path_reservations() as reserve:
for net_id in state.ordered_net_ids: for net_id in state.ordered_net_ids:
net = state.net_specs[net_id] net = state.net_specs[net_id]
@ -207,7 +206,7 @@ class PathFinder:
net_id=net_id, net_id=net_id,
config=run_config, config=run_config,
) )
if not path: if not path or world.verify_path_report(net_id, path).intrinsic_collision_count:
continue continue
self.metrics.total_warm_start_paths_built += 1 self.metrics.total_warm_start_paths_built += 1
greedy_paths[net_id] = tuple(path) greedy_paths[net_id] = tuple(path)
@ -359,7 +358,7 @@ class PathFinder:
self.context.cost_evaluator.collision_engine.remove_path(net_id) self.context.cost_evaluator.collision_engine.remove_path(net_id)
for net_id in ordered_net_ids: for net_id in ordered_net_ids:
result = results.get(net_id) result = results.get(net_id)
if result and result.path and result.reached_target: if can_reserve(result):
self._install_path(net_id, result.path) self._install_path(net_id, result.path)
def _review_restored_best(self, state: _RoutingState) -> _IterationReview: def _review_restored_best(self, state: _RoutingState) -> _IterationReview:
@ -526,7 +525,7 @@ class PathFinder:
) )
net = state.net_specs[net_id] net = state.net_specs[net_id]
installed_path = result.path if result.reached_target else () installed_path = result.path if can_reserve(result) else ()
with self._frontier_replay(net_id, installed_path) as scratch_metrics: with self._frontier_replay(net_id, installed_path) as scratch_metrics:
route_astar( route_astar(
net.start, net.start,
@ -581,6 +580,7 @@ class PathFinder:
net_id, net_id,
result.path, result.path,
capture_component_conflicts=capture_component_conflicts, capture_component_conflicts=capture_component_conflicts,
include_invalid_dynamic=False,
) )
details_by_net[net_id] = detail details_by_net[net_id] = detail
analyzed_results[net_id] = RoutingResult( analyzed_results[net_id] = RoutingResult(
@ -835,9 +835,11 @@ class PathFinder:
self.context.cost_evaluator.collision_engine.remove_path(net_id) self.context.cost_evaluator.collision_engine.remove_path(net_id)
guidance_seed_present = False guidance_seed_present = False
if iteration == 0 and state.initial_paths and net_id in state.initial_paths: initial_path = state.initial_paths.get(net_id) if state.initial_paths else None
initial_arrives = bool(initial_path and initial_path[-1].end_port == net.target)
if iteration == 0 and initial_path is not None and (initial_arrives or search.node_limit <= 0):
self.metrics.total_warm_start_paths_used += 1 self.metrics.total_warm_start_paths_used += 1
path: Sequence[ComponentResult] | None = state.initial_paths[net_id] path: Sequence[ComponentResult] | None = initial_path
else: else:
coll_model, _ = resolve_bend_geometry(search) coll_model, _ = resolve_bend_geometry(search)
skip_congestion = False skip_congestion = False
@ -846,13 +848,18 @@ class PathFinder:
skip_congestion = True skip_congestion = True
if coll_model == "arc": if coll_model == "arc":
coll_model = "clipped_bbox" coll_model = "clipped_bbox"
elif iteration > 0: if iteration > 0:
guidance_seed, guidance_bonus = incumbent_guidance( guidance_seed, guidance_bonus = incumbent_guidance(
state.results.get(net_id), self.context.options.objective.bend_penalty state.results.get(net_id), self.context.options.objective.bend_penalty
) )
guidance_seed_present = guidance_seed is not None use_prefix = not guidance_seed and bool(initial_path and not initial_arrives)
if use_prefix and initial_path:
guidance_seed, guidance_bonus = path_guidance(initial_path, self.context.options.objective.bend_penalty)
if iteration == 0:
self.metrics.total_warm_start_paths_used += 1
guidance_seed_present = guidance_seed is not None
if node_limit_override is not None and self._has_incumbent_fallback(incumbent_fallback): if node_limit_override is not None and can_reserve(incumbent_fallback):
return self._restore_incumbent_fallback(net_id, incumbent_fallback, guidance_seed_present) return self._restore_incumbent_fallback(net_id, incumbent_fallback, guidance_seed_present)
corridors = state.corridors.get(net_id, ()) corridors = state.corridors.get(net_id, ())
@ -863,6 +870,7 @@ class PathFinder:
store_expanded=diagnostics.capture_expanded, store_expanded=diagnostics.capture_expanded,
guidance_seed=guidance_seed, guidance_seed=guidance_seed,
guidance_bonus=guidance_bonus, guidance_bonus=guidance_bonus,
propose_guidance_moves=use_prefix,
skip_congestion=skip_congestion, skip_congestion=skip_congestion,
self_collision_check=(net_id in state.needs_self_collision_check), self_collision_check=(net_id in state.needs_self_collision_check),
node_limit=search.node_limit if node_limit_override is None else node_limit_override, node_limit=search.node_limit if node_limit_override is None else node_limit_override,
@ -882,20 +890,23 @@ class PathFinder:
if diagnostics.capture_expanded and self.metrics.last_expanded_nodes: if diagnostics.capture_expanded and self.metrics.last_expanded_nodes:
state.accumulated_expanded_nodes.extend(self.metrics.last_expanded_nodes) state.accumulated_expanded_nodes.extend(self.metrics.last_expanded_nodes)
if not path and use_prefix:
path = initial_path
if not path: if not path:
if self._has_incumbent_fallback(incumbent_fallback): if can_reserve(incumbent_fallback):
return self._restore_incumbent_fallback(net_id, incumbent_fallback, guidance_seed_present) return self._restore_incumbent_fallback(net_id, incumbent_fallback, guidance_seed_present)
return RoutingResult(net_id=net_id, path=(), reached_target=False), guidance_seed_present return RoutingResult(net_id=net_id, path=(), reached_target=False), guidance_seed_present
reached_target = path[-1].end_port == net.target reached_target = path[-1].end_port == net.target
if not reached_target and self._has_incumbent_fallback(incumbent_fallback): if not reached_target and can_reserve(incumbent_fallback):
return self._restore_incumbent_fallback(net_id, incumbent_fallback, guidance_seed_present) return self._restore_incumbent_fallback(net_id, incumbent_fallback, guidance_seed_present)
report = None report = None
if reached_target: if reached_target:
self.metrics.total_nets_reached_target += 1 self.metrics.total_nets_reached_target += 1
self._install_path(net_id, path) report = self.context.cost_evaluator.collision_engine.verify_path_details(net_id, path, include_invalid_dynamic=False).report
report = self.context.cost_evaluator.collision_engine.verify_path_report(net_id, path) if not report.intrinsic_collision_count:
self._install_path(net_id, path)
if report.self_collision_count > 0: if report.self_collision_count > 0:
state.needs_self_collision_check.add(net_id) state.needs_self_collision_check.add(net_id)
@ -1084,6 +1095,7 @@ class PathFinder:
net.net_id, net.net_id,
result.path, result.path,
capture_component_conflicts=capture_conflicts, capture_component_conflicts=capture_conflicts,
include_invalid_dynamic=False,
) )
details_by_net[net.net_id] = detail details_by_net[net.net_id] = detail
final_results[net.net_id] = RoutingResult( final_results[net.net_id] = RoutingResult(

View file

@ -9,6 +9,8 @@ from ._astar_moves import expand_moves as _expand_moves
from ._astar_types import AStarContext, AStarMetrics, AStarNode as _AStarNode, CongestionCaches, SearchRunConfig from ._astar_types import AStarContext, AStarMetrics, AStarNode as _AStarNode, CongestionCaches, SearchRunConfig
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Sequence
from inire.geometry.components import ComponentResult from inire.geometry.components import ComponentResult
from inire.geometry.primitives import Port from inire.geometry.primitives import Port
from inire.results import RoutingResult from inire.results import RoutingResult
@ -21,7 +23,11 @@ def incumbent_guidance(
) -> tuple[tuple[PathSegmentSeed, ...] | None, float]: ) -> tuple[tuple[PathSegmentSeed, ...] | None, float]:
if result is None or not result.reached_target or not result.path: if result is None or not result.reached_target or not result.path:
return None, 0.0 return None, 0.0
return result.as_seed().segments, max(10.0, bend_penalty * 0.25) return path_guidance(result.path, bend_penalty)
def path_guidance(path: Sequence[ComponentResult], bend_penalty: float) -> tuple[tuple[PathSegmentSeed, ...], float]:
return tuple(component.move_spec for component in path), max(10.0, bend_penalty * 0.25)
def _reconstruct_path(end_node: _AStarNode) -> list[ComponentResult]: def _reconstruct_path(end_node: _AStarNode) -> list[ComponentResult]:

View file

@ -7,10 +7,20 @@ from inire.model import resolve_bend_geometry
from inire.seeds import Bend90Seed, SBendSeed, StraightSeed from inire.seeds import Bend90Seed, SBendSeed, StraightSeed
if TYPE_CHECKING: if TYPE_CHECKING:
from inire.geometry.components import ComponentResult from inire.geometry.components import ComponentResult, MoveKind
from inire.geometry.primitives import Port from inire.geometry.primitives import Port
from inire.model import SearchOptions from inire.model import SearchOptions
from inire.seeds import PathSeed from inire.seeds import PathSeed, PathSegmentSeed
def seed_move(segment: PathSegmentSeed) -> tuple[MoveKind, tuple]:
if isinstance(segment, StraightSeed):
return "straight", (max(1, round(segment.length)),)
if isinstance(segment, Bend90Seed):
return "bend90", (segment.radius, segment.direction)
if isinstance(segment, SBendSeed):
return "sbend", (segment.offset, segment.radius)
raise TypeError(f"Unsupported seed segment: {type(segment)!r}")
def materialize_path_seed( def materialize_path_seed(
@ -31,14 +41,7 @@ def materialize_path_seed(
bend_clip_margin = search.bend_clip_margin bend_clip_margin = search.bend_clip_margin
for segment in seed.segments: for segment in seed.segments:
if isinstance(segment, StraightSeed): kind, parameters = seed_move(segment)
kind, parameters = "straight", (max(1, round(segment.length)),)
elif isinstance(segment, Bend90Seed):
kind, parameters = "bend90", (segment.radius, segment.direction)
elif isinstance(segment, SBendSeed):
kind, parameters = "sbend", (segment.offset, segment.radius)
else:
raise TypeError(f"Unsupported seed segment: {type(segment)!r}")
component = build_component( component = build_component(
current, current,
net_width, net_width,

View file

@ -1,7 +1,10 @@
from __future__ import annotations from __future__ import annotations
from bisect import bisect_left
from dataclasses import dataclass from dataclasses import dataclass
from heapq import merge
from itertools import accumulate, chain from itertools import accumulate, chain
from math import inf
from typing import TYPE_CHECKING, Any from typing import TYPE_CHECKING, Any
from inire.geometry.component_overlap import components_overlap from inire.geometry.component_overlap import components_overlap
@ -29,11 +32,45 @@ class _DoglegMove:
bend_radius: float | None = None bend_radius: float | None = None
def _forward_position(port: Port) -> float:
axis = port.y if port.r % 180 else port.x
return axis if port.r < 180 else -axis
class _WindowEnds:
"""Find the last sufficiently forward endpoint in a prefix of the path."""
def __init__(self, indices: list[int], ports: Sequence[Port]) -> None:
self.indices = indices
self._size = 1 << (len(indices) - 1).bit_length()
self._maxima = [-inf] * (2 * self._size)
self._maxima[self._size : self._size + len(indices)] = [_forward_position(ports[index]) for index in indices]
for node in range(self._size - 1, 0, -1):
self._maxima[node] = max(self._maxima[2 * node], self._maxima[2 * node + 1])
def rightmost(self, stop: int, minimum: float) -> int | None:
if not stop:
return None
node = self._size + stop - 1
if self._maxima[node] >= minimum:
return stop - 1
# Earlier leaves lie in left siblings of the path back to the root.
while node > 1:
if node % 2 and self._maxima[node - 1] >= minimum:
node -= 1
while node < self._size:
right = 2 * node + 1
node = right if self._maxima[right] >= minimum else right - 1
return node - self._size
node //= 2
return None
def component_hits_ancestor_chain(component: ComponentResult, parent_node: Any) -> bool: def component_hits_ancestor_chain(component: ComponentResult, parent_node: Any) -> bool:
current = parent_node current = parent_node
while current and current.parent: while current and current.parent:
ancestor_component = current.component_result ancestor_component = current.component_result
if ancestor_component and components_overlap(component, ancestor_component): if ancestor_component and components_overlap(ancestor_component, component, prefer_actual=True, at_join=current is parent_node):
return True return True
current = current.parent current = current.parent
return False return False
@ -248,28 +285,40 @@ class PathRefiner:
def _iter_refinement_windows(self, start: Port, path: Sequence[ComponentResult]) -> Iterator[tuple[int, int]]: def _iter_refinement_windows(self, start: Port, path: Sequence[ComponentResult]) -> Iterator[tuple[int, int]]:
ports = self._path_ports(start, path) ports = self._path_ports(start, path)
min_bend_span = bend90_grid_span(min(self.context.options.search.bend_radii, default=0.0)) min_forward = 4 * bend90_grid_span(min(self.context.options.search.bend_radii, default=0.0))
bends = [component.move_type == "bend90" for component in path] bends = [component.move_type == "bend90" for component in path]
bend_counts = tuple(accumulate(bends, initial=0)) bend_counts = tuple(accumulate(bends, initial=0))
limit = self.context.options.refinement.max_windows_per_net limit = self.context.options.refinement.max_windows_per_net
# Keep the original order for a single attempt and for unlimited refinement. # Keep the original order for a single attempt and for unlimited refinement.
edge_counts = (2, 1, 0) if limit is not None and limit > 1 else (None,) prioritize_bend_edges = limit is not None and limit > 1
edge_counts = (2, 1, 0) if prioritize_bend_edges else (None,)
by_heading: dict[tuple[int | float, int | None], list[int]] = {}
for end, port in enumerate(ports[1:], start=1):
if bend_counts[end] >= 4:
edge = int(bends[end - 1]) if prioritize_bend_edges else None
by_heading.setdefault((port.r, edge), []).append(end)
candidates = {key: _WindowEnds(indices, ports) for key, indices in by_heading.items()}
def from_start(index: int, edge_count: int | None) -> Iterator[tuple[int, int, int]]:
end_edge = edge_count - int(bends[index]) if edge_count is not None else None
ends = candidates.get((ports[index].r, end_edge))
if ends is None:
return
minimum_end = bisect_left(bend_counts, bend_counts[index] + 4)
minimum_position = _forward_position(ports[index]) + min_forward
stop = len(ends.indices)
while (slot := ends.rightmost(stop, minimum_position)) is not None:
end = ends.indices[slot]
if end < minimum_end:
break
yield index - end, index, end
stop = slot
for edge_count in edge_counts: for edge_count in edge_counts:
for window_size in range(len(path), 3, -1): windows = (from_start(index, edge_count) for index, count in enumerate(bend_counts[:-1]) if count <= bend_counts[-1] - 4)
for start_idx in range(len(path) - window_size + 1): # Each stream is longest-first, so the merge only needs one pending window per start.
end_idx = start_idx + window_size for _, start_idx, end_idx in merge(*windows):
if bend_counts[end_idx] - bend_counts[start_idx] < 4: yield start_idx, end_idx
continue
if edge_count is not None and bends[start_idx] + bends[end_idx - 1] != edge_count:
continue
window_start = ports[start_idx]
window_end = ports[end_idx]
if window_start.r != window_end.r:
continue
local_dx, _ = port_local_coordinates(window_start, window_end.x, window_end.y)
if local_dx >= 4 * min_bend_span:
yield start_idx, end_idx
def _try_refine_window( def _try_refine_window(
self, self,

View file

@ -296,6 +296,25 @@ def test_custom_sbend_reports_overlap_inside_the_component() -> None:
assert not result.report.discontinuous assert not result.report.discontinuous
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
assert not result.report.discontinuous
@pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"]) @pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"])
@pytest.mark.parametrize(("seed_length", "grid_length"), [(0.2, 1), (19.5, 20), (19.75, 20), (20.49, 20)]) @pytest.mark.parametrize(("seed_length", "grid_length"), [(0.2, 1), (19.5, 20), (19.75, 20), (20.49, 20)])
def test_fractional_straight_seed_uses_grid_length(mode, seed_length, grid_length) -> None: def test_fractional_straight_seed_uses_grid_length(mode, seed_length, grid_length) -> None:
@ -508,6 +527,42 @@ def test_lattice_partial_path_leaves_crossing_net_valid() -> None:
assert all(entry.conflict_edges == () for entry in run.conflict_trace) assert all(entry.conflict_edges == () for entry in run.conflict_trace)
@pytest.mark.parametrize("reverse", [False, True])
def test_invalid_seed_leaves_crossing_peer_valid(reverse) -> None:
blocked = NetSpec("blocked", Port(10, 100, 0), Port(170, 100, 0))
through = NetSpec("through", Port(80, 40, 90), Port(80, 160, 90))
nets = (through, blocked) if reverse else (blocked, through)
seeds = {"blocked": PathSeed((StraightSeed(160),)), "through": PathSeed((StraightSeed(120),))}
problem = RoutingProblem((0, 0, 200, 200), nets, (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_lattice_can_chain_straights_before_a_bend_under_scan_limit() -> None:
net = NetSpec("lead", Port(10, 20, 0), Port(80, 30, 90))
problem = RoutingProblem((0, 15, 95, 32), (net,))
options = RoutingOptions(
search=SearchOptions(node_limit=100, max_straight_length=10, bend_radii=(10,), sbend_radii=()),
congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False),
topology=TopologyOptions(mode="off"),
)
result = route(problem, options=options).results_by_net["lead"]
assert result.is_valid
assert result.as_seed() == PathSeed((*(StraightSeed(10),) * 6, Bend90Seed(10, "CCW")))
@pytest.mark.parametrize("mode", ["off", "guide", "seed", "automatic"]) @pytest.mark.parametrize("mode", ["off", "guide", "seed", "automatic"])
def test_search_can_find_consecutive_sbends(mode) -> None: def test_search_can_find_consecutive_sbends(mode) -> None:
net = NetSpec("double", Port(20, 20, 0), Port(48, 30, 0)) net = NetSpec("double", Port(20, 20, 0), Port(48, 30, 0))
@ -635,7 +690,8 @@ def test_route_verification_detects_physical_bend_overlap(mode, proxy) -> None:
seed = PathSeed((Bend90Seed(10, "CCW"),)) seed = PathSeed((Bend90Seed(10, "CCW"),))
problem = RoutingProblem((0, 0, 120, 120), nets, initial_paths={net.net_id: seed for net in nets}) problem = RoutingProblem((0, 0, 120, 120), nets, initial_paths={net.net_id: seed for net in nets})
bend_proxy = box(0, -11, 11, 0) bend_proxy = box(0, -11, 11, 0)
physical_bend = bend_proxy.union(box(-13, -11, 1, -9)).union(box(-13, -11, -11, 15)) 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))
search = SearchOptions(node_limit=20, bend_radii=(10,), bend_proxy_geometry=bend_proxy, bend_physical_geometry=physical_bend) search = SearchOptions(node_limit=20, bend_radii=(10,), bend_proxy_geometry=bend_proxy, bend_physical_geometry=physical_bend)
options = RoutingOptions( options = RoutingOptions(
search=search, search=search,

View file

@ -7,9 +7,11 @@ from inire import CongestionOptions, ObjectiveWeights, RefinementOptions, Routin
from inire.geometry.collision import RoutingWorld from inire.geometry.collision import RoutingWorld
from inire.geometry.components import Bend90 from inire.geometry.components import Bend90
from inire.geometry.primitives import Port from inire.geometry.primitives import Port
from inire.geometry.primitives import port_local_coordinates
from inire.model import NetSpec from inire.model import NetSpec
from inire.router._astar_types import AStarContext from inire.router._astar_types import AStarContext
from inire.router._router import PathFinder 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._waypoints import compile_waypoints
from inire.router.cost import CostEvaluator from inire.router.cost import CostEvaluator
from inire.router.danger_map import DangerMap from inire.router.danger_map import DangerMap
@ -33,6 +35,27 @@ _REFINEMENT_OPTIONS = RoutingOptions(
) )
@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]) @pytest.mark.parametrize("radius", [10, 10.25])
def test_refinement_handles_both_signs_of_the_lateral_offset(radius) -> None: def test_refinement_handles_both_signs_of_the_lateral_offset(radius) -> None:
options = replace(_REFINEMENT_OPTIONS, search=replace(_REFINEMENT_OPTIONS.search, bend_radii=(radius,))) options = replace(_REFINEMENT_OPTIONS, search=replace(_REFINEMENT_OPTIONS.search, bend_radii=(radius,)))

View file

@ -182,13 +182,13 @@ def test_route_uses_complete_initial_paths_without_rerouting() -> None:
assert result.as_seed() == initial_seed assert result.as_seed() == initial_seed
def test_route_retries_partial_initial_paths_across_iterations() -> None: def test_route_uses_a_partial_initial_path_on_the_first_iteration() -> None:
iterations: list[int] = [] iterations: list[int] = []
partial_seed = PathSeed((StraightSeed(length=5.0),)) partial_seed = PathSeed((StraightSeed(length=7.0),))
run = _route_problem( run = _route_problem(
netlist={"net": (Port(0, 0, 0), Port(10, 0, 0))}, netlist={"net": (Port(0, 0, 0), Port(20, 0, 0))},
net_widths={"net": 2.0}, net_widths={"net": 2.0},
max_iterations=2, max_iterations=1,
warm_start_enabled=False, warm_start_enabled=False,
capture_expanded=True, capture_expanded=True,
initial_paths={"net": partial_seed}, initial_paths={"net": partial_seed},
@ -197,12 +197,13 @@ def test_route_retries_partial_initial_paths_across_iterations() -> None:
) )
result = run.results_by_net["net"] result = run.results_by_net["net"]
assert iterations == [0, 1] assert iterations == [0]
assert result.is_valid assert result.is_valid
assert result.reached_target assert result.reached_target
assert result.outcome == "completed" assert result.outcome == "completed"
assert result.as_seed() != partial_seed assert result.as_seed().segments == (*partial_seed.segments, StraightSeed(13))
assert run.expanded_nodes assert run.expanded_nodes
assert run.metrics.guidance_match_moves > 0
def test_route_negotiated_congestion_resolution() -> None: def test_route_negotiated_congestion_resolution() -> None: