Verify physical route clearance and board containment

This commit is contained in:
Jan Petykiewicz 2026-11-27 14:12:40 -08:00
commit c200d0f7c1
17 changed files with 210 additions and 173 deletions

View file

@ -32,7 +32,7 @@ The near-port attempt uses up to 100 nodes per search and two congestion iterati
## Geometry and refinement ## Geometry and refinement
Search proxies approximate the shape of a move for collision checks. Verification uses physical polygons for static keepout checks and self-collisions. For conflicts between nets, it compares the checked path's clearance-expanded physical polygons with the other routes' installed, clearance-expanded proxies. Automatic and bundle modes also check that the physical polygons fit within the board. Search uses proxies to check moves and estimate congestion. Verification checks the physical polygons against keepouts, other nets, and the board rectangle in every routing mode. It uses the distance between physical polygons to check spacing between nets. 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).

View file

@ -42,7 +42,7 @@ Enable the `DiagnosticsOptions` flag for the question you want to answer.
1. Enable `capture_conflict_trace` in `DiagnosticsOptions`. In `run.conflict_trace`, choose the entry with `stage="final"` to inspect the returned paths. 1. Enable `capture_conflict_trace` in `DiagnosticsOptions`. In `run.conflict_trace`, choose the entry with `stage="final"` to inspect the returned paths.
2. Find the two net IDs in `conflict_edges`. In the matching `nets` entry, read `component_conflicts` for `self_component_index`, `other_net_id`, and `other_component_index`. 2. Find the two net IDs in `conflict_edges`. In the matching `nets` entry, read `component_conflicts` for `self_component_index`, `other_net_id`, and `other_component_index`.
3. Use those zero-based indices to look up components in each net's `path` in `run.results_by_net`. Plot their physical shapes to see where they approach each other. If their physical spacing looks sufficient, compare the installed proxy used by the [dynamic clearance check](architecture.md#geometry-and-refinement). 3. Use those zero-based indices to look up components in each net's `path` in `run.results_by_net`. Plot their physical shapes and compare the distance between them with the [required clearance](architecture.md#geometry-and-refinement).
An earlier entry such as `restored_best` indexes the paths at that stage. Use the paths from the same stage for a geometry comparison. If verification failed with an empty conflict edge list, check the net's report for a keepout conflict, self-collision, or board boundary violation. An earlier entry such as `restored_best` indexes the paths at that stage. Use the paths from the same stage for a geometry comparison. If verification failed with an empty conflict edge list, check the net's report for a keepout conflict, self-collision, or board boundary violation.

View file

@ -24,7 +24,7 @@ The fields below appear in constructor order. Use one layout unit for coordinate
| Field | Default | Meaning | | Field | Default | Meaning |
| --- | --- | --- | | --- | --- | --- |
| `bounds` | Required | Board rectangle as `(xmin, ymin, xmax, ymax)`. | | `bounds` | Required | Board rectangle as `(xmin, ymin, xmax, ymax)`. |
| `nets` | `()` | Sequence of `NetSpec` objects with unique IDs. | | `nets` | `()` | Sequence of `NetSpec` objects with unique IDs. Duplicate IDs raise `ValueError`. |
| `static_obstacles` | `()` | Shapely polygons that define keepouts. | | `static_obstacles` | `()` | Shapely polygons that define keepouts. |
| `initial_paths` | Empty mapping | Net IDs mapped to `PathSeed` objects. | | `initial_paths` | Empty mapping | Net IDs mapped to `PathSeed` objects. |
| `clearance` | `2.0` | Required spacing between physical shapes. | | `clearance` | `2.0` | Required spacing between physical shapes. |
@ -42,7 +42,7 @@ The fields below appear in constructor order. Use one layout unit for coordinate
| `RoutingResult.is_valid` and `outcome` | `is_valid` is true when the outcome is `completed`. Read `outcome` to distinguish success, a failed geometry check (`colliding`), a path that stopped short (`partial`), or an empty path (`unroutable`). | | `RoutingResult.is_valid` and `outcome` | `is_valid` is true when the outcome is `completed`. Read `outcome` to distinguish success, a failed geometry check (`colliding`), a path that stopped short (`partial`), or an empty path (`unroutable`). |
| `RoutingResult.path` | Ordered path components from the source to the last reached state. An unroutable result has an empty path. | | `RoutingResult.path` | Ordered path components from the source to the last reached state. An unroutable result has an empty path. |
| `RoutingResult.reached_target` | Whether the path reached the target position and heading. With heading inference, the check uses the chosen heading. Read `is_valid` for the result of geometry verification. | | `RoutingResult.reached_target` | Whether the path reached the target position and heading. With heading inference, the check uses the chosen heading. Read `is_valid` for the result of geometry verification. |
| `RoutingResult.report` | `total_length` in layout units plus static, dynamic, and self-collision counts. `out_of_bounds` records a board containment failure when checked. | | `RoutingResult.report` | `total_length` in layout units plus static, dynamic, and self-collision counts. `out_of_bounds` indicates that physical geometry extends outside the board rectangle. |
| `RoutingResult.locked_geometry` and `as_seed()` | Physical polygons and the sequence of moves, respectively. Check validity before exporting polygons or using them as keepouts. | | `RoutingResult.locked_geometry` and `as_seed()` | Physical polygons and the sequence of moves, respectively. Check validity before exporting polygons or using them as keepouts. |
| `RoutingRunResult.automatic` | In automatic mode, the selected planner, verified IDs, stage history, and any capacity or port-conflict bound. `None` for explicit modes. | | `RoutingRunResult.automatic` | In automatic mode, the selected planner, verified IDs, stage history, and any capacity or port-conflict bound. `None` for explicit modes. |
| `RoutingRunResult.topology` and `metrics` | Corridor counts and seed work when reported by the selected worker, plus work counters across the run. | | `RoutingRunResult.topology` and `metrics` | Corridor counts and seed work when reported by the selected worker, plus work counters across the run. |

View file

@ -7,11 +7,11 @@ Start with `run.results_by_net[net_id].outcome`. It distinguishes a path that st
| `result.outcome` | What to inspect | | `result.outcome` | What to inspect |
| --- | --- | | --- | --- |
| `completed` | The path reached its target and passed verification. Read its length in `report.total_length` and follow the [geometry export steps](route-a-layout.md#export-verified-geometry). | | `completed` | The path reached its target and passed verification. Read its length in `report.total_length` and follow the [geometry export steps](route-a-layout.md#export-verified-geometry). |
| `colliding` | The path reached its target and failed verification. Check `result.report` for keepout clearance, conflicts with another route, or self-overlap. In automatic mode, also check `report.out_of_bounds`. | | `colliding` | The path reached its target and failed verification. Check `result.report` for keepout clearance, conflicts with another route, self-overlap, or geometry outside the board. |
| `partial` | Read the position and heading of `result.path[-1].end_port`. Check room for the path to continue from that heading. If the next turn fits, compare search limits. | | `partial` | Read the position and heading of `result.path[-1].end_port`. Check room for the path to continue from that heading. If the next turn fits, compare search limits. |
| `unroutable` | The path is empty. Check the launch heading and room for the first straight or bend. | | `unroutable` | The path is empty. Check the launch heading and room for the first straight or bend. |
Check `is_valid` before exporting. With explicit `off`, `guide`, or `seed` mode, also check that the physical polygons fit the board if your export requires containment. Automatic mode includes that check in candidate verification. Check `is_valid` before exporting. Every routing mode checks that the physical polygons fit within the board.
## Why a net stopped short ## Why a net stopped short

View file

@ -7,6 +7,7 @@ import numpy
from shapely.geometry import LineString, box from shapely.geometry import LineString, box
from inire.geometry.component_overlap import components_overlap from inire.geometry.component_overlap import components_overlap
from inire.geometry.components import path_within_board
from inire.geometry.dynamic_path_index import DynamicPathIndex from inire.geometry.dynamic_path_index import DynamicPathIndex
from inire.geometry.index_helpers import grid_cell_span from inire.geometry.index_helpers import grid_cell_span
from inire.results import RoutingReport from inire.results import RoutingReport
@ -84,6 +85,7 @@ class RoutingWorld:
__slots__ = ( __slots__ = (
"clearance", "clearance",
"safety_zone_radius", "safety_zone_radius",
"board",
"grid_cell_size", "grid_cell_size",
"metrics", "metrics",
"_dynamic_paths", "_dynamic_paths",
@ -94,9 +96,12 @@ class RoutingWorld:
self, self,
clearance: float, clearance: float,
safety_zone_radius: float = 0.0021, safety_zone_radius: float = 0.0021,
*,
board: Polygon | None = None,
) -> None: ) -> None:
self.clearance = clearance self.clearance = clearance
self.safety_zone_radius = safety_zone_radius self.safety_zone_radius = safety_zone_radius
self.board = board
self.grid_cell_size = 50.0 self.grid_cell_size = 50.0
self.metrics = None self.metrics = None
@ -148,14 +153,27 @@ class RoutingWorld:
geometry: Sequence[Polygon], geometry: Sequence[Polygon],
dilated_geometry: Sequence[Polygon], dilated_geometry: Sequence[Polygon],
component_indexes: Sequence[int] | None = None, component_indexes: Sequence[int] | None = None,
*,
physical_geometry: Sequence[tuple[int, Polygon]] | None = None,
) -> None: ) -> None:
self._dynamic_paths.add_path( self._dynamic_paths.add_path(
net_id, net_id,
geometry, geometry,
dilated_geometry=dilated_geometry, dilated_geometry=dilated_geometry,
component_indexes=component_indexes, component_indexes=component_indexes,
physical_geometry=physical_geometry,
) )
def install_path(self, net_id: str, path: Sequence[ComponentResult]) -> None:
proxies: list[Polygon] = []
dilated_proxies: list[Polygon] = []
physical_geometry: list[tuple[int, Polygon]] = []
for component_index, component in enumerate(path):
proxies.extend(component.collision_geometry)
dilated_proxies.extend(component.dilated_collision_geometry)
physical_geometry.extend((component_index, polygon) for polygon in component.physical_geometry)
self.add_path(net_id, proxies, dilated_proxies, physical_geometry=physical_geometry)
def remove_path(self, net_id: str) -> None: def remove_path(self, net_id: str) -> None:
self._dynamic_paths.remove_path(net_id) self._dynamic_paths.remove_path(net_id)
@ -578,37 +596,6 @@ class RoutingWorld:
if _bounds_overlap(bounds, dynamic_paths.net_envelopes[other_net_id]) if _bounds_overlap(bounds, dynamic_paths.net_envelopes[other_net_id])
) )
def _get_verify_net_envelope_candidates(
self,
bounds: tuple[float, float, float, float],
net_id: str,
) -> tuple[str, ...]:
dynamic_paths = self._dynamic_paths
candidate_net_ids: list[str] = []
for obj_id in dynamic_paths.net_envelope_index.intersection(bounds):
other_net_id = dynamic_paths.net_envelope_obj_to_net[obj_id]
if other_net_id == net_id:
continue
if not _bounds_overlap(bounds, dynamic_paths.net_envelopes[other_net_id]):
continue
candidate_net_ids.append(other_net_id)
if self.metrics is not None:
self.metrics.total_verify_dynamic_candidate_nets += len(candidate_net_ids)
return tuple(candidate_net_ids)
def _get_verify_grid_span_obj_ids(
self,
bounds: tuple[float, float, float, float],
other_net_id: str,
) -> tuple[int, ...]:
dynamic_paths = self._dynamic_paths
gx_min, gy_min, gx_max, gy_max = grid_cell_span(bounds, self.grid_cell_size)
obj_ids: set[int] = set()
for gx in range(gx_min, gx_max + 1):
for gy in range(gy_min, gy_max + 1):
obj_ids.update(dynamic_paths.grid_net_obj_ids.get((gx, gy), {}).get(other_net_id, ()))
return tuple(sorted(obj_ids))
def check_move_congestion( def check_move_congestion(
self, self,
result: ComponentResult, result: ComponentResult,
@ -698,34 +685,30 @@ class RoutingWorld:
if not self._is_in_safety_zone(polygon, obj_id, None, None): if not self._is_in_safety_zone(polygon, obj_id, None, None):
static_collision_count += 1 static_collision_count += 1
if dynamic_paths.dilated: if dynamic_paths.has_physical_paths():
clearance = max(0.0, self.clearance)
for component_index, component in enumerate(components): for component_index, component in enumerate(components):
test_geometries = component.dilated_physical_geometry component_hits: set[str] = set()
component_hits = [] for polygon in component.physical_geometry:
for new_geometry in test_geometries: minx, miny, maxx, maxy = polygon.bounds
for hit_net_id in self._get_verify_net_envelope_candidates(new_geometry.bounds, str(net_id)): bounds = (minx - clearance, miny - clearance, maxx + clearance, maxy + clearance)
for obj_id in self._get_verify_grid_span_obj_ids(new_geometry.bounds, hit_net_id): candidates = dynamic_paths.physical_candidates(str(net_id), bounds)
if not _bounds_overlap(new_geometry.bounds, dynamic_paths.dilated_bounds[obj_id]): if self.metrics is not None:
self.metrics.total_verify_dynamic_candidate_nets += len({candidate[0] for candidate in candidates})
polygon_hits: set[str] = set()
for hit_net_id, hit_component_index, other in candidates:
if hit_net_id in polygon_hits:
continue continue
if self.metrics is not None: if self.metrics is not None:
self.metrics.total_verify_dynamic_exact_pair_checks += 1 self.metrics.total_verify_dynamic_exact_pair_checks += 1
tree_geometry = dynamic_paths.dilated[obj_id] overlaps = polygon.distance(other) < clearance if clearance > 0 else _has_non_touching_overlap(polygon, other)
if _has_non_touching_overlap(new_geometry, tree_geometry): if overlaps:
component_hits.append(hit_net_id) polygon_hits.add(hit_net_id)
if capture_component_conflicts: if capture_component_conflicts:
component_conflicts.add( component_conflicts.add((component_index, hit_net_id, hit_component_index))
( component_hits.update(polygon_hits)
component_index, dynamic_collision_count += len(component_hits)
hit_net_id, conflicting_net_ids.update(component_hits)
dynamic_paths.component_indexes[obj_id],
)
)
break
if component_hits:
unique_hits = tuple(sorted(set(component_hits)))
dynamic_collision_count += len(unique_hits)
conflicting_net_ids.update(unique_hits)
for index, component in enumerate(components): for index, component in enumerate(components):
for other_index in range(index + 2, len(components)): for other_index in range(index + 2, len(components)):
@ -738,6 +721,7 @@ class RoutingWorld:
dynamic_collision_count=dynamic_collision_count, dynamic_collision_count=dynamic_collision_count,
self_collision_count=self_collision_count, self_collision_count=self_collision_count,
total_length=total_length, total_length=total_length,
out_of_bounds=self.board is not None and not path_within_board(components, self.board),
), ),
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

@ -15,11 +15,12 @@ if TYPE_CHECKING:
class DynamicPathIndex: class DynamicPathIndex:
"""Index search proxies and physical polygons for installed paths."""
__slots__ = ( __slots__ = (
"engine", "engine",
"index", "index",
"geometries", "geometries",
"component_indexes",
"dilated", "dilated",
"dilated_bounds", "dilated_bounds",
"net_envelope_index", "net_envelope_index",
@ -30,13 +31,16 @@ class DynamicPathIndex:
"obj_cells", "obj_cells",
"net_to_obj_ids", "net_to_obj_ids",
"id_counter", "id_counter",
"_physical_index",
"_physical_objects",
"_physical_ids_by_net",
"_physical_id_counter",
) )
def __init__(self, engine: RoutingWorld) -> None: def __init__(self, engine: RoutingWorld) -> None:
self.engine = engine self.engine = engine
self.index = rtree.index.Index() self.index = rtree.index.Index()
self.geometries: dict[int, tuple[str, Polygon]] = {} self.geometries: dict[int, tuple[str, Polygon]] = {}
self.component_indexes: dict[int, int] = {}
self.dilated: dict[int, Polygon] = {} self.dilated: dict[int, Polygon] = {}
self.dilated_bounds: dict[int, tuple[float, float, float, float]] = {} self.dilated_bounds: dict[int, tuple[float, float, float, float]] = {}
self.net_envelope_index = rtree.index.Index() self.net_envelope_index = rtree.index.Index()
@ -47,6 +51,10 @@ class DynamicPathIndex:
self.obj_cells: dict[int, tuple[tuple[int, int], ...]] = {} self.obj_cells: dict[int, tuple[tuple[int, int], ...]] = {}
self.net_to_obj_ids: dict[str, set[int]] = {} self.net_to_obj_ids: dict[str, set[int]] = {}
self.id_counter = 0 self.id_counter = 0
self._physical_index = rtree.index.Index()
self._physical_objects: dict[int, tuple[str, int, Polygon]] = {}
self._physical_ids_by_net: dict[str, list[tuple[int, tuple[float, float, float, float]]]] = {}
self._physical_id_counter = 0
def _combine_net_bounds(self, obj_ids: set[int]) -> tuple[float, float, float, float]: def _combine_net_bounds(self, obj_ids: set[int]) -> tuple[float, float, float, float]:
first_obj_id = next(iter(obj_ids)) first_obj_id = next(iter(obj_ids))
@ -118,6 +126,8 @@ class DynamicPathIndex:
geometry: Sequence[Polygon], geometry: Sequence[Polygon],
dilated_geometry: Sequence[Polygon], dilated_geometry: Sequence[Polygon],
component_indexes: Sequence[int] | None = None, component_indexes: Sequence[int] | None = None,
*,
physical_geometry: Sequence[tuple[int, Polygon]] | None = None,
) -> None: ) -> None:
if self.engine.metrics is not None: if self.engine.metrics is not None:
self.engine.metrics.total_dynamic_path_objects_added += len(geometry) self.engine.metrics.total_dynamic_path_objects_added += len(geometry)
@ -128,38 +138,51 @@ class DynamicPathIndex:
dilated = dilated_geometry[index] dilated = dilated_geometry[index]
dilated_bounds = dilated.bounds dilated_bounds = dilated.bounds
self.geometries[obj_id] = (net_id, polygon) self.geometries[obj_id] = (net_id, polygon)
self.component_indexes[obj_id] = index if component_indexes is None else component_indexes[index]
self.dilated[obj_id] = dilated self.dilated[obj_id] = dilated
self.dilated_bounds[obj_id] = dilated_bounds self.dilated_bounds[obj_id] = dilated_bounds
self.index.insert(obj_id, dilated_bounds) self.index.insert(obj_id, dilated_bounds)
self.net_to_obj_ids.setdefault(net_id, set()).add(obj_id) self.net_to_obj_ids.setdefault(net_id, set()).add(obj_id)
self._register_grid_membership(obj_id, net_id, dilated_bounds, cell_size=cell_size) self._register_grid_membership(obj_id, net_id, dilated_bounds, cell_size=cell_size)
self._refresh_net_envelope(net_id) self._refresh_net_envelope(net_id)
if physical_geometry is None:
physical_geometry = [
(index if component_indexes is None else component_indexes[index], polygon)
for index, polygon in enumerate(geometry)
]
physical_ids = self._physical_ids_by_net.setdefault(net_id, [])
for component_index, polygon in physical_geometry:
obj_id = self._physical_id_counter
self._physical_id_counter += 1
bounds = polygon.bounds
self._physical_index.insert(obj_id, bounds)
self._physical_objects[obj_id] = (net_id, component_index, polygon)
physical_ids.append((obj_id, bounds))
def remove_path(self, net_id: str) -> None: def remove_path(self, net_id: str) -> None:
to_remove = list(self.net_to_obj_ids.get(net_id, ())) obj_ids = self.net_to_obj_ids.pop(net_id, ())
self.remove_obj_ids(to_remove)
def remove_obj_ids(self, obj_ids: list[int]) -> None:
if not obj_ids:
return
if self.engine.metrics is not None: if self.engine.metrics is not None:
self.engine.metrics.total_dynamic_path_objects_removed += len(obj_ids) self.engine.metrics.total_dynamic_path_objects_removed += len(obj_ids)
affected_nets: set[str] = set()
for obj_id in obj_ids: for obj_id in obj_ids:
net_id, _ = self.geometries[obj_id]
affected_nets.add(net_id)
self._unregister_grid_membership(obj_id, net_id) self._unregister_grid_membership(obj_id, net_id)
self.index.delete(obj_id, self.dilated_bounds[obj_id]) self.index.delete(obj_id, self.dilated_bounds[obj_id])
del self.geometries[obj_id] del self.geometries[obj_id]
del self.component_indexes[obj_id]
del self.dilated[obj_id] del self.dilated[obj_id]
del self.dilated_bounds[obj_id] del self.dilated_bounds[obj_id]
obj_id_set = self.net_to_obj_ids.get(net_id) self._clear_net_envelope(net_id)
if obj_id_set is not None: for obj_id, bounds in self._physical_ids_by_net.pop(net_id, ()):
obj_id_set.discard(obj_id) self._physical_index.delete(obj_id, bounds)
if not obj_id_set: del self._physical_objects[obj_id]
self.net_to_obj_ids.pop(net_id, None)
for net_id in affected_nets: def has_physical_paths(self) -> bool:
self._refresh_net_envelope(net_id) return bool(self._physical_objects)
def physical_candidates(
self, net_id: str, bounds: tuple[float, float, float, float]
) -> list[tuple[str, int, Polygon]]:
candidates = []
for obj_id in sorted(self._physical_index.intersection(bounds)):
candidate = self._physical_objects[obj_id]
if candidate[0] != net_id:
candidates.append(candidate)
return candidates

View file

@ -166,7 +166,13 @@ class RoutingProblem:
safety_zone_radius: float = 0.0021 safety_zone_radius: float = 0.0021
def __post_init__(self) -> None: def __post_init__(self) -> None:
object.__setattr__(self, "nets", tuple(self.nets)) nets = tuple(self.nets)
seen: set[str] = set()
for net in nets:
if net.net_id in seen:
raise ValueError(f"Duplicate net ID: {net.net_id!r}")
seen.add(net.net_id)
object.__setattr__(self, "nets", nets)
object.__setattr__(self, "static_obstacles", tuple(self.static_obstacles)) object.__setattr__(self, "static_obstacles", tuple(self.static_obstacles))
initial_paths = dict(self.initial_paths) initial_paths = dict(self.initial_paths)
if any(not isinstance(seed, PathSeed) for seed in initial_paths.values()): if any(not isinstance(seed, PathSeed) for seed in initial_paths.values()):

View file

@ -154,7 +154,7 @@ class _AutomaticRun:
def _trial(self, run: RoutingRunResult, stage: RoutingStage) -> Trial: def _trial(self, run: RoutingRunResult, stage: RoutingStage) -> Trial:
with self._time("verify", planner=stage.planner, mode=stage.mode, policy=stage.policy): with self._time("verify", planner=stage.planner, mode=stage.mode, policy=stage.policy):
return _trial(run, stage, self.board, score=self._selection_cost) return _trial(run, stage, score=self._selection_cost)
def _seeded_problem(self, trial: Trial) -> RoutingProblem: def _seeded_problem(self, trial: Trial) -> RoutingProblem:
seeds = {net_id: trial.run.results_by_net[net_id].as_seed() for net_id in trial.valid_costs} seeds = {net_id: trial.run.results_by_net[net_id].as_seed() for net_id in trial.valid_costs}
@ -267,7 +267,7 @@ class _AutomaticRun:
problem, options = self.problem, self.options problem, options = self.problem, self.options
if len(problem.nets) != 2: if len(problem.nets) != 2:
return return
world = RoutingWorld(clearance=problem.clearance, safety_zone_radius=problem.safety_zone_radius) world = RoutingWorld(clearance=problem.clearance, safety_zone_radius=problem.safety_zone_radius, board=self.board)
for obstacle in problem.static_obstacles: for obstacle in problem.static_obstacles:
world.add_static_obstacle(obstacle) world.add_static_obstacle(obstacle)
@ -278,7 +278,6 @@ class _AutomaticRun:
if not path or path[-1].end_port != net.target or not world.verify_path_report(net.net_id, path).is_valid: if not path or path[-1].end_port != net.target or not world.verify_path_report(net.net_id, path).is_valid:
continue continue
footprint = shapely.union_all([shape for component in path for shape in component.physical_geometry]) footprint = shapely.union_all([shape for component in path for shape in component.physical_geometry])
if self.board.covers(footprint):
choices.append((seed, footprint)) choices.append((seed, footprint))
return choices return choices
@ -589,7 +588,7 @@ class _AutomaticRun:
policy=best.stage.policy, policy=best.stage.policy,
operation="refine", operation="refine",
) )
# Audit the merged result so the stage still reports unresolved routes outside the board. # Keep reports for unresolved routes when merging the refined subset.
results = {**best.run.results_by_net, **run.results_by_net} results = {**best.run.results_by_net, **run.results_by_net}
refined = self._trial(replace(run, results_by_net=results), stage) refined = self._trial(replace(run, results_by_net=results), stage)
# Only a whole verified replacement of the incumbent can win. # Only a whole verified replacement of the incumbent can win.

View file

@ -29,7 +29,7 @@ def _build_pair_local_context(
problem = context.problem problem = context.problem
live_world = context.cost_evaluator.collision_engine live_world = context.cost_evaluator.collision_engine
static_obstacles = tuple(live_world.iter_static_geometries()) static_obstacles = tuple(live_world.iter_static_geometries())
world = RoutingWorld(clearance=live_world.clearance, safety_zone_radius=live_world.safety_zone_radius) world = RoutingWorld(clearance=live_world.clearance, safety_zone_radius=live_world.safety_zone_radius, board=live_world.board)
for obstacle in static_obstacles: for obstacle in static_obstacles:
world.add_static_obstacle(obstacle) world.add_static_obstacle(obstacle)
for net in ordered_nets: for net in ordered_nets:

View file

@ -6,6 +6,8 @@ from contextlib import contextmanager, nullcontext
from dataclasses import dataclass, field from dataclasses import dataclass, field
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from shapely import shortest_line
from inire.model import resolve_bend_geometry from inire.model import resolve_bend_geometry
from inire.results import ( from inire.results import (
ConflictTraceEntry, ConflictTraceEntry,
@ -40,8 +42,6 @@ if TYPE_CHECKING:
from collections.abc import Callable, Iterator, Sequence from collections.abc import Callable, Iterator, Sequence
from contextlib import AbstractContextManager from contextlib import AbstractContextManager
from shapely.geometry import Polygon
from inire.geometry.collision import PathVerificationDetail from inire.geometry.collision import PathVerificationDetail
from inire.geometry.components import ComponentResult from inire.geometry.components import ComponentResult
from inire.model import NetSpec from inire.model import NetSpec
@ -154,19 +154,7 @@ class PathFinder:
return result, guidance_seed_present return result, guidance_seed_present
def _install_path(self, net_id: str, path: Sequence[ComponentResult]) -> None: def _install_path(self, net_id: str, path: Sequence[ComponentResult]) -> None:
all_geoms: list[Polygon] = [] self.context.cost_evaluator.collision_engine.install_path(net_id, path)
all_dilated: list[Polygon] = []
component_indexes: list[int] = []
for component_index, result in enumerate(path):
all_geoms.extend(result.collision_geometry)
all_dilated.extend(result.dilated_collision_geometry)
component_indexes.extend([component_index] * len(result.collision_geometry))
self.context.cost_evaluator.collision_engine.add_path(
net_id,
all_geoms,
dilated_geometry=all_dilated,
component_indexes=component_indexes,
)
@contextmanager @contextmanager
def _temporary_path_reservations(self) -> Iterator[Callable[[Sequence[ComponentResult]], None]]: def _temporary_path_reservations(self) -> Iterator[Callable[[Sequence[ComponentResult]], None]]:
@ -462,20 +450,13 @@ class PathFinder:
if overlap_found: if overlap_found:
continue continue
left_bounds = left_component.total_dilated_bounds # A clearance violation can occur between the flat ends of two bend polygons.
right_bounds = right_component.total_dilated_bounds gap = min(
if ( (shortest_line(left, right) for left in left_component.physical_geometry for right in right_component.physical_geometry),
left_bounds[0] < right_bounds[2] key=lambda line: line.length,
and left_bounds[2] > right_bounds[0]
and left_bounds[1] < right_bounds[3]
and left_bounds[3] > right_bounds[1]
):
buffered = (
max(left_bounds[0], right_bounds[0]) - margin,
max(left_bounds[1], right_bounds[1]) - margin,
min(left_bounds[2], right_bounds[2]) + margin,
min(left_bounds[3], right_bounds[3]) + margin,
) )
minx, miny, maxx, maxy = gap.bounds
buffered = (minx - margin, miny - margin, maxx + margin, maxy + margin)
if buffered not in seen: if buffered not in seen:
seen.add(buffered) seen.add(buffered)
hotspot_bounds.append(buffered) hotspot_bounds.append(buffered)

View file

@ -10,7 +10,7 @@ from shapely.geometry import Point
from inire.constants import TOLERANCE_LINEAR from inire.constants import TOLERANCE_LINEAR
from inire.geometry.collision import RoutingWorld from inire.geometry.collision import RoutingWorld
from inire.geometry.components import Straight, path_within_board from inire.geometry.components import Straight
from inire.geometry.primitives import port_local_coordinates from inire.geometry.primitives import port_local_coordinates
from inire.model import resolve_bend_geometry from inire.model import resolve_bend_geometry
from inire.results import RoutingResult, RoutingStage from inire.results import RoutingResult, RoutingStage
@ -83,7 +83,7 @@ def _direct_paths(
) -> dict[str, RoutingResult]: ) -> dict[str, RoutingResult]:
if problem.initial_paths: if problem.initial_paths:
return {} return {}
world = RoutingWorld(clearance=problem.clearance, safety_zone_radius=problem.safety_zone_radius) world = RoutingWorld(clearance=problem.clearance, safety_zone_radius=problem.safety_zone_radius, board=board)
for obstacle in problem.static_obstacles: for obstacle in problem.static_obstacles:
world.add_static_obstacle(obstacle) world.add_static_obstacle(obstacle)
ordered = ordered_nets(problem.nets, options.congestion.net_order) ordered = ordered_nets(problem.nets, options.congestion.net_order)
@ -96,12 +96,10 @@ def _direct_paths(
if net.start.r != net.target.r or forward <= 0 or lateral: if net.start.r != net.target.r or forward <= 0 or lateral:
continue continue
component = Straight.generate(net.start, forward, net.width, dilation=problem.clearance / 2) component = Straight.generate(net.start, forward, net.width, dilation=problem.clearance / 2)
if not path_within_board((component,), board):
continue
report = world.verify_path_report(net.net_id, (component,)) report = world.verify_path_report(net.net_id, (component,))
if report.is_valid: if report.is_valid:
paths[net.net_id] = RoutingResult(net.net_id, (component,), reached_target=True, report=report) paths[net.net_id] = RoutingResult(net.net_id, (component,), reached_target=True, report=report)
world.add_path(net.net_id, component.collision_geometry, dilated_geometry=component.dilated_collision_geometry) world.install_path(net.net_id, (component,))
return paths return paths
@ -242,32 +240,8 @@ def _route_prepared_residual(
) )
def _trial(run: RoutingRunResult, stage: RoutingStage, board: Polygon, *, score: Scorer) -> Trial: def _trial(run: RoutingRunResult, stage: RoutingStage, *, score: Scorer) -> Trial:
outside = tuple( outside = tuple(net_id for net_id, result in run.results_by_net.items() if result.report.out_of_bounds)
net_id
for net_id, result in run.results_by_net.items()
if result.report.out_of_bounds or not path_within_board(result.path, board)
)
if outside:
results = dict(run.results_by_net)
for net_id in outside:
result = results[net_id]
if not result.report.out_of_bounds:
results[net_id] = replace(result, report=replace(result.report, out_of_bounds=True))
trace = run.conflict_trace
if trace and trace[-1].stage == "final":
final = trace[-1]
checked = replace(
final,
completed_net_ids=tuple(net_id for net_id in final.completed_net_ids if net_id not in outside),
nets=tuple(
replace(net, outcome=results[net.net_id].outcome, report=results[net.net_id].report) if net.net_id in outside else net
for net in final.nets
),
)
trace = (*trace[:-1], checked)
run = replace(run, results_by_net=results, conflict_trace=trace)
valid_costs = {net_id: score(result) for net_id, result in run.results_by_net.items() if result.is_valid} valid_costs = {net_id: score(result) for net_id, result in run.results_by_net.items() if result.is_valid}
stage = replace(stage, valid_net_ids=tuple(valid_costs), out_of_bounds_net_ids=outside) stage = replace(stage, valid_net_ids=tuple(valid_costs), out_of_bounds_net_ids=outside)
return Trial(run, stage, valid_costs) return Trial(run, stage, valid_costs)

View file

@ -6,7 +6,6 @@ from typing import TYPE_CHECKING
from shapely.geometry import box from shapely.geometry import box
from inire.geometry.collision import RoutingWorld from inire.geometry.collision import RoutingWorld
from inire.geometry.components import path_within_board
from inire.results import RoutingRunResult from inire.results import RoutingRunResult
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
@ -40,6 +39,7 @@ def build_routing_stack(problem: RoutingProblem, options: RoutingOptions) -> Rou
world = RoutingWorld( world = RoutingWorld(
clearance=problem.clearance, clearance=problem.clearance,
safety_zone_radius=problem.safety_zone_radius, safety_zone_radius=problem.safety_zone_radius,
board=box(*problem.bounds),
) )
for obstacle in problem.static_obstacles: for obstacle in problem.static_obstacles:
world.add_static_obstacle(obstacle) world.add_static_obstacle(obstacle)
@ -83,9 +83,8 @@ def route_once(
finder = build_routing_stack(problem, options).finder finder = build_routing_stack(problem, options).finder
results = finder.route_all(iteration_callback=iteration_callback, phase_timer=phase_timer, corridors=corridors) results = finder.route_all(iteration_callback=iteration_callback, phase_timer=phase_timer, corridors=corridors)
if options.topology.mode == "bundle": if options.topology.mode == "bundle":
board = box(*problem.bounds)
for result in results.values(): for result in results.values():
if not result.is_valid or not path_within_board(result.path, board): if not result.is_valid:
raise ValueError(f"Bundle schedule failed geometric verification for {result.net_id}") raise ValueError(f"Bundle schedule failed geometric verification for {result.net_id}")
return collect_worker_result(finder, results) return collect_worker_result(finder, results)

View file

@ -58,7 +58,7 @@ DIRECT_POLICIES = tuple(_EXPERIMENTS)
def direct_trials(problem: RoutingProblem, board: Polygon, options: RoutingOptions, strategy: str) -> list[Trial]: def direct_trials(problem: RoutingProblem, board: Polygon, options: RoutingOptions, strategy: str) -> list[Trial]:
experiment = _EXPERIMENTS[strategy] experiment = _EXPERIMENTS[strategy]
summarize = partial(_trial, board=board, score=benchmark_weighted_length) summarize = partial(_trial, score=benchmark_weighted_length)
if experiment is None: if experiment is None:
return _direct_trials(problem, board, options, strategy, check_trial=summarize) return _direct_trials(problem, board, options, strategy, check_trial=summarize)

View file

@ -7,10 +7,12 @@ from shapely.geometry import box
import inire import inire
import inire.router._router as router_module import inire.router._router as router_module
from inire import ( from inire import (
Bend90Seed,
CongestionOptions, CongestionOptions,
DiagnosticsOptions, DiagnosticsOptions,
NetSpec, NetSpec,
ObjectiveWeights, ObjectiveWeights,
PathSeed,
Port, Port,
RefinementOptions, RefinementOptions,
RoutingOptions, RoutingOptions,
@ -63,7 +65,18 @@ def test_route_problem_smoke() -> None:
assert run.iteration_trace == () assert run.iteration_trace == ()
def test_automatic_routes_report_boundary_violations_in_results_and_diagnostics() -> None: 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)
@pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"])
def test_routes_report_boundary_violations_in_results_and_diagnostics(mode) -> None:
problem = RoutingProblem( problem = RoutingProblem(
bounds=(0, 0, 100, 100), bounds=(0, 0, 100, 100),
nets=( nets=(
@ -71,13 +84,19 @@ def test_automatic_routes_report_boundary_violations_in_results_and_diagnostics(
NetSpec("flush", Port(0, 50, 0), Port(100, 50, 0)), NetSpec("flush", Port(0, 50, 0), Port(100, 50, 0)),
), ),
) )
options = RoutingOptions(search=SearchOptions(node_limit=100), diagnostics=DiagnosticsOptions(capture_conflict_trace=True)) options = RoutingOptions(
search=SearchOptions(node_limit=100),
topology=TopologyOptions(mode=mode),
diagnostics=DiagnosticsOptions(capture_conflict_trace=True),
)
run = route(problem, options=options) run = route(problem, options=options)
assert run.automatic is not None
valid_ids = tuple(net_id for net_id, result in run.results_by_net.items() if result.is_valid) valid_ids = tuple(net_id for net_id, result in run.results_by_net.items() if result.is_valid)
assert valid_ids == run.automatic.verified_net_ids == ("flush",) 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] selected = run.automatic.stages[run.automatic.selected_stage]
assert selected.out_of_bounds_net_ids == ("edge",) assert selected.out_of_bounds_net_ids == ("edge",)
@ -96,6 +115,46 @@ def test_automatic_routes_report_boundary_violations_in_results_and_diagnostics(
assert traced_edge.report == edge.report assert traced_edge.report == edge.report
@pytest.mark.parametrize("mode", ["automatic", "off"])
@pytest.mark.parametrize("proxy", ["clipped_bbox", "custom"])
def test_route_verification_detects_physical_bend_overlap(mode, proxy) -> None:
if proxy == "clipped_bbox":
nets = (
NetSpec("a", Port(50, 50, 0), Port(60, 60, 90)),
NetSpec("b", Port(41, 54, 0), Port(51, 44, 270)),
)
problem = RoutingProblem((0, 0, 120, 120), nets)
search = SearchOptions(node_limit=100, bend_radii=(10,), bend_collision_type="clipped_bbox", bend_clip_margin=4)
else:
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)
physical_bend = bend_proxy.union(box(-13, -11, 1, -9)).union(box(-13, -11, -11, 15))
search = SearchOptions(node_limit=20, bend_radii=(10,), bend_proxy_geometry=bend_proxy, bend_physical_geometry=physical_bend)
options = RoutingOptions(
search=search,
congestion=CongestionOptions(max_iterations=1),
diagnostics=DiagnosticsOptions(capture_conflict_trace=True),
topology=TopologyOptions(mode=mode),
)
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
if run.automatic is not None:
assert run.automatic.verified_net_ids == ()
assert run.conflict_trace[-1].conflict_edges == (("a", "b"),)
@pytest.mark.parametrize("node_limit", [40, 500, 700, None], ids=["tight", "initial", "higher", "default"]) @pytest.mark.parametrize("node_limit", [40, 500, 700, None], ids=["tight", "initial", "higher", "default"])
def test_default_router_escalates_only_within_the_configured_node_limit(monkeypatch, node_limit) -> None: 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)),)) problem = RoutingProblem((0, 0, 200, 200), (NetSpec("turn", Port(20, 20, 0), Port(180, 160, 90)),))

View file

@ -197,7 +197,7 @@ def test_verify_path_report_distinguishes_long_net_ids_with_shared_prefix() -> N
assert engine.metrics.total_verify_dynamic_candidate_nets == 1 assert engine.metrics.total_verify_dynamic_candidate_nets == 1
def test_verify_path_report_uses_net_envelopes_before_dynamic_object_scan() -> None: def test_verify_path_report_uses_physical_bounds_before_exact_checks() -> None:
engine = RoutingWorld(clearance=2.0) engine = RoutingWorld(clearance=2.0)
engine.metrics = AStarMetrics() engine.metrics = AStarMetrics()
path_a = [Straight.generate(Port(0, 0, 0), 20.0, width=2.0, dilation=1.0)] path_a = [Straight.generate(Port(0, 0, 0), 20.0, width=2.0, dilation=1.0)]
@ -222,6 +222,19 @@ def test_verify_path_report_uses_net_envelopes_before_dynamic_object_scan() -> N
assert engine.metrics.total_verify_dynamic_exact_pair_checks == 1 assert engine.metrics.total_verify_dynamic_exact_pair_checks == 1
@pytest.mark.parametrize(("clearance", "valid"), [(1.4, True), (1.5, False)])
def test_verify_path_report_uses_physical_distance_between_routes(clearance, valid) -> None:
engine = RoutingWorld(clearance=clearance)
existing = Straight.generate(Port(0, 0, 0), 10, width=2, dilation=clearance / 2)
query = Straight.generate(Port(12, 2, 90), 10, width=2, dilation=clearance / 2)
engine.install_path("existing", (existing,))
# The physical corners are one unit apart on each axis.
assert engine.verify_path_report("query", (query,)).is_valid is valid
engine.remove_path("existing")
assert engine.verify_path_report("query", (query,)).is_valid
def test_verify_path_details_returns_conflicting_net_ids() -> None: def test_verify_path_details_returns_conflicting_net_ids() -> None:
engine = RoutingWorld(clearance=2.0) engine = RoutingWorld(clearance=2.0)
engine.metrics = AStarMetrics() engine.metrics = AStarMetrics()

View file

@ -20,7 +20,7 @@ from inire import (
route, route,
) )
DEFAULT_BOUNDS = (0, 0, 100, 100) DEFAULT_BOUNDS = (0, -5, 100, 100)
_PROBLEM_FIELDS = set(RoutingProblem.__dataclass_fields__) - {"bounds", "nets", "static_obstacles"} _PROBLEM_FIELDS = set(RoutingProblem.__dataclass_fields__) - {"bounds", "nets", "static_obstacles"}
_SEARCH_FIELDS = set(SearchOptions.__dataclass_fields__) _SEARCH_FIELDS = set(SearchOptions.__dataclass_fields__)

View file

@ -33,7 +33,6 @@ from inire.tests.routing_corpus import (
) )
if TYPE_CHECKING: if TYPE_CHECKING:
from shapely.geometry import Polygon
from inire import CapacityLimit, RoutingProblem, RoutingTiming, TopologyReport from inire import CapacityLimit, RoutingProblem, RoutingTiming, TopologyReport
from inire.router._routing_policy import Trial from inire.router._routing_policy import Trial
from inire.tests.routing_benchmark_case import BenchmarkCase from inire.tests.routing_benchmark_case import BenchmarkCase
@ -76,13 +75,13 @@ def _mode_options(options: RoutingOptions, strategy: str, profile: str = "matche
return replace(options, topology=replace(options.topology, mode="off" if strategy in POLICIES else strategy)) return replace(options, topology=replace(options.topology, mode="off" if strategy in POLICIES else strategy))
def _order_trials(problem: RoutingProblem, board: Polygon, options: RoutingOptions, strategy: str) -> list[Trial]: def _order_trials(problem: RoutingProblem, options: RoutingOptions, strategy: str) -> list[Trial]:
limit = options.search.node_limit limit = options.search.node_limit
first_limit = max(1, limit // 2) first_limit = max(1, limit // 2)
first_order = options.congestion.net_order first_order = options.congestion.net_order
first_options = replace(options, search=replace(options.search, node_limit=first_limit), topology=replace(options.topology, mode="seed")) first_options = replace(options, search=replace(options.search, node_limit=first_limit), topology=replace(options.topology, mode="seed"))
run = route(problem, options=first_options) run = route(problem, options=first_options)
first = _trial(run, RoutingStage("seed", (), run.metrics.nodes_expanded, first_limit, net_order=first_order), board) first = _trial(run, RoutingStage("seed", (), run.metrics.nodes_expanded, first_limit, net_order=first_order))
if len(first.valid_costs) == len(problem.nets) or limit == 1: if len(first.valid_costs) == len(problem.nets) or limit == 1:
return [first] return [first]
@ -112,7 +111,7 @@ def _order_trials(problem: RoutingProblem, board: Polygon, options: RoutingOptio
if strategy == "seed-order-locked": if strategy == "seed-order-locked":
run = replace(run, results_by_net={**incumbents, **run.results_by_net}) run = replace(run, results_by_net={**incumbents, **run.results_by_net})
stage = RoutingStage("seed", (), run.metrics.nodes_expanded, second_limit, net_order=second_order, incumbent_net_ids=tuple(incumbents)) stage = RoutingStage("seed", (), run.metrics.nodes_expanded, second_limit, net_order=second_order, incumbent_net_ids=tuple(incumbents))
return [first, _trial(run, stage, board)] return [first, _trial(run, stage)]
def _measure(case: BenchmarkCase, options: RoutingOptions, strategy: str) -> RunSample: def _measure(case: BenchmarkCase, options: RoutingOptions, strategy: str) -> RunSample:
@ -161,16 +160,16 @@ def _measure(case: BenchmarkCase, options: RoutingOptions, strategy: str) -> Run
else: else:
bundle_duration = perf_counter() - started bundle_duration = perf_counter() - started
stage = RoutingStage("bundle", (), run.metrics.nodes_expanded, options.search.node_limit, kind="bundle") stage = RoutingStage("bundle", (), run.metrics.nodes_expanded, options.search.node_limit, kind="bundle")
trials = [_trial(run, stage, board)] trials = [_trial(run, stage)]
elif strategy in DIRECT_POLICIES: elif strategy in DIRECT_POLICIES:
problem = case.fixed_headings_problem() problem = case.fixed_headings_problem()
trials = _direct_trials(problem, board, options, strategy) trials = _direct_trials(problem, board, options, strategy)
elif strategy in ORDER_POLICIES: elif strategy in ORDER_POLICIES:
problem = case.fixed_headings_problem() problem = case.fixed_headings_problem()
trials = _order_trials(problem, board, options, strategy) trials = _order_trials(problem, options, strategy)
else: else:
run = route(case.fixed_headings_problem(), options=options) run = route(case.fixed_headings_problem(), options=options)
trials = [_trial(run, RoutingStage(strategy, (), run.metrics.nodes_expanded, options.search.node_limit), board)] trials = [_trial(run, RoutingStage(strategy, (), run.metrics.nodes_expanded, options.search.node_limit))]
best = _best_trial(trials) best = _best_trial(trials)
duration = perf_counter() - started duration = perf_counter() - started
run = best.run run = best.run