Check physical separation within and between routed nets

This commit is contained in:
Jan Petykiewicz 2026-11-28 20:16:29 -08:00
commit d02dbb872f
12 changed files with 199 additions and 35 deletions

View file

@ -27,7 +27,8 @@ The fields below appear in constructor order. Use one layout unit for coordinate
| `nets` | `()` | Sequence of `NetSpec` objects with unique IDs. Duplicate IDs raise `ValueError`. |
| `static_obstacles` | `()` | Valid, nonempty Shapely `Polygon` objects that define keepouts. |
| `initial_paths` | Empty mapping | Net IDs mapped to `PathSeed` objects. |
| `clearance` | `2.0` | Finite, nonnegative spacing required between physical shapes. |
| `clearance` | `2.0` | Finite, nonnegative spacing required between distinct nets and between a net and a keepout. At zero clearance, distinct nets must still be disjoint, including at vertices. Boundary contact with a keepout is allowed. |
| `self_clearance` | `0.0` | Optional spacing within one net. Applies between components when the intervening centerline is at least this long. Adjacent joins and components immediately on either side of one bend are exempt. Unintended contact is always checked. |
| `safety_zone_radius` | `0.0021` | Tolerance for small obstacle intersections at a move's endpoints during search. |
## Path seeds

View file

@ -58,6 +58,10 @@ def _violates_clearance(left: BaseGeometry, right: BaseGeometry, clearance: floa
return left.distance(right) < clearance - tolerance
def _violates_net_clearance(left: BaseGeometry, right: BaseGeometry, clearance: float) -> bool:
return _violates_clearance(left, right, clearance) if clearance else left.intersects(right)
def _span_to_bounds(
gx_min: int,
gy_min: int,
@ -93,10 +97,13 @@ class RoutingWorld:
__slots__ = (
"clearance",
"self_clearance",
"safety_zone_radius",
"board",
"grid_cell_size",
"metrics",
"_reserved_obstacles",
"_reserved_geometry_ids",
"_dynamic_paths",
"_static_obstacles",
)
@ -107,13 +114,17 @@ class RoutingWorld:
safety_zone_radius: float = 0.0021,
*,
board: Polygon | None = None,
self_clearance: float = 0.0,
) -> None:
self.clearance = clearance
self.self_clearance = self_clearance
self.safety_zone_radius = safety_zone_radius
self.board = board
self.grid_cell_size = 50.0
self.metrics = None
self._reserved_obstacles: dict[int, int] = {}
self._reserved_geometry_ids: set[int] = set()
self._static_obstacles = StaticObstacleIndex(self)
self._dynamic_paths = DynamicPathIndex(self)
@ -141,10 +152,17 @@ class RoutingWorld:
for obj_id in self._dynamic_paths.index.intersection(query_bounds):
yield self._dynamic_paths.geometries[obj_id][1].bounds
def add_static_obstacle(self, polygon: Polygon, dilated_geometry: Polygon | None = None) -> int:
return self._static_obstacles.add_obstacle(polygon, dilated_geometry=dilated_geometry)
def add_static_obstacle(self, polygon: Polygon, dilated_geometry: Polygon | None = None, *, reserved: bool = False) -> int:
obstacle_id = self._static_obstacles.add_obstacle(polygon, dilated_geometry=dilated_geometry)
if reserved and not self.clearance:
self._reserved_obstacles[obstacle_id] = id(polygon)
self._reserved_geometry_ids.add(id(polygon))
return obstacle_id
def remove_static_obstacle(self, obj_id: int) -> None:
polygon_id = self._reserved_obstacles.pop(obj_id, None)
if polygon_id is not None and polygon_id not in self._reserved_obstacles.values():
self._reserved_geometry_ids.discard(polygon_id)
self._static_obstacles.remove_obstacle(obj_id)
def _ensure_static_tree(self) -> None:
@ -257,11 +275,19 @@ class RoutingWorld:
clearance = self.clearance
left, bottom, right, top = result.total_bounds
reserved = self._reserved_geometry_ids
if reserved:
x0, y0, x1, y1 = result.total_physical_bounds
left, bottom, right, top = min(left, x0), min(bottom, y0), max(right, x1), max(top, y1)
# Expand the whole proxy envelope, including the tangent faces of an arc.
hits = tree.query(box(left - clearance, bottom - clearance, right + clearance, top + clearance))
obstacles = tree.geometries
for hit_idx in hits:
obstacle = obstacles[hit_idx]
if reserved and id(obstacle) in reserved:
if any(polygon.intersects(obstacle) for polygon in result.physical_geometry):
return True
continue
for polygon in result.collision_geometry:
if _violates_clearance(polygon, obstacle, clearance) and not self._is_in_safety_zone(polygon, obstacle, start_port, end_port):
return True
@ -304,6 +330,30 @@ class RoutingWorld:
return DynamicCongestionDetail(soft_overlap_count=real_hits_count)
def check_physical_move_congestion(
self,
result: ComponentResult,
net_id: str,
*,
frozen_net_ids: frozenset[str] = frozenset(),
) -> DynamicCongestionDetail:
"""Use physical clearance when admitting a move with a hard obstacle."""
hits = set()
for polygon in result.physical_geometry:
for other_net_id, _index, other in self._physical_candidates(net_id, polygon):
if other_net_id in hits or not _violates_net_clearance(polygon, other, self.clearance):
continue
if other_net_id in frozen_net_ids:
return DynamicCongestionDetail(soft_overlap_count=len(hits), hits_frozen_net=True)
hits.add(other_net_id)
return DynamicCongestionDetail(soft_overlap_count=len(hits))
def _physical_candidates(self, net_id: str, polygon: Polygon) -> list[tuple[str, int, Polygon]]:
minx, miny, maxx, maxy = polygon.bounds
clearance = self.clearance
bounds = (minx - clearance, miny - clearance, maxx + clearance, maxy + clearance)
return self._dynamic_paths.physical_candidates(net_id, bounds)
def _collect_congestion_candidates(
self,
result: ComponentResult,
@ -598,6 +648,8 @@ class RoutingWorld:
dynamic_paths = self._dynamic_paths
if not dynamic_paths.geometries:
return DynamicCongestionDetail()
if not self.clearance or frozen_net_ids:
return self.check_physical_move_congestion(result, net_id, frozen_net_ids=frozen_net_ids)
candidates_by_net = self._collect_congestion_candidates(
result,
@ -639,6 +691,7 @@ class RoutingWorld:
self._ensure_static_raw_tree()
if static_obstacles.raw_tree is not None:
raw_geometries = static_obstacles.raw_tree.geometries
reserved = self._reserved_geometry_ids
for component in components:
for polygon in component.physical_geometry:
if self.metrics is not None:
@ -650,24 +703,21 @@ class RoutingWorld:
# A mitre may extend past the physical clearance
# radius at a component corner. Check the distance
# before counting an overlap with that broad phase.
if _violates_clearance(polygon, obstacle, self.clearance):
if (reserved and id(obstacle) in reserved) or _violates_clearance(polygon, obstacle, self.clearance):
static_collision_count += 1
report = RoutingReport(
static_collision_count=static_collision_count,
self_collision_count=count_path_self_collisions(components),
self_collision_count=count_path_self_collisions(components, self.self_clearance),
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)
for component_index, component in enumerate(components):
component_hits: set[str] = set()
for polygon in component.physical_geometry:
minx, miny, maxx, maxy = polygon.bounds
bounds = (minx - clearance, miny - clearance, maxx + clearance, maxy + clearance)
candidates = dynamic_paths.physical_candidates(str(net_id), bounds)
candidates = self._physical_candidates(net_id, polygon)
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()
@ -676,7 +726,7 @@ class RoutingWorld:
continue
if self.metrics is not None:
self.metrics.total_verify_dynamic_exact_pair_checks += 1
if _violates_clearance(polygon, other, clearance):
if _violates_net_clearance(polygon, other, self.clearance):
polygon_hits.add(hit_net_id)
if capture_component_conflicts:
component_conflicts.add((component_index, hit_net_id, hit_component_index))

View file

@ -1,6 +1,6 @@
from __future__ import annotations
from itertools import combinations
from itertools import accumulate, combinations
from typing import TYPE_CHECKING
from shapely.geometry import box
@ -22,6 +22,7 @@ def components_overlap(
prefer_actual: bool = False,
*,
at_join: bool = False,
clearance: float = 0.0,
) -> bool:
polygons_a: Sequence[Polygon]
polygons_b: Sequence[Polygon]
@ -37,10 +38,10 @@ def components_overlap(
bounds_b = component_b.total_bounds
if (
bounds_a[0] > bounds_b[2]
or bounds_a[2] < bounds_b[0]
or bounds_a[1] > bounds_b[3]
or bounds_a[3] < bounds_b[1]
bounds_a[0] > bounds_b[2] + clearance
or bounds_a[2] + clearance < bounds_b[0]
or bounds_a[1] > bounds_b[3] + clearance
or bounds_a[3] + clearance < bounds_b[1]
):
return False
@ -70,7 +71,10 @@ def components_overlap(
or bounds[3 - axis] > hi + TOLERANCE_LINEAR
):
return True
elif polygon_a.intersects(polygon_b) and (prefer_actual or not polygon_a.touches(polygon_b)):
elif (
(polygon_a.intersects(polygon_b) and (prefer_actual or not polygon_a.touches(polygon_b)))
or (clearance and polygon_a.distance(polygon_b) < clearance - TOLERANCE_LINEAR * min(1.0, clearance))
):
return True
return False
@ -86,7 +90,7 @@ def invalid_component_join(left: ComponentResult, right: ComponentResult) -> boo
return not components_join(left, right) or components_overlap(left, right, prefer_actual=True, at_join=True)
def count_path_self_collisions(components: Sequence[ComponentResult]) -> int:
def count_path_self_collisions(components: Sequence[ComponentResult], clearance: float = 0.0) -> int:
internal_collisions = 0
for component in components:
for left, right in combinations(component.physical_geometry, 2):
@ -101,9 +105,24 @@ def count_path_self_collisions(components: Sequence[ComponentResult]) -> int:
for component in components
]
index = STRtree(envelopes)
distances = list(accumulate((component.length for component in components), initial=0.0)) if clearance else ()
def envelope_with_clearance(i: int) -> Polygon:
if not clearance:
return envelopes[i]
x0, y0, x1, y1 = components[i].total_physical_bounds
return box(x0 - clearance, y0 - clearance, x1 + clearance, y1 + clearance)
def spacing(i: int, other: int) -> float:
if not distances or distances[other] - distances[i + 1] < clearance - TOLERANCE_LINEAR:
return 0.0
if other == i + 2 and components[i + 1].move_type != "straight":
return 0.0 # Keep the geometry local to one continuous bend together.
return clearance
return internal_collisions + sum(
components_overlap(component, components[other], prefer_actual=True, at_join=other == i + 1)
for i, (component, envelope) in enumerate(zip(components, envelopes, strict=True))
for other in index.query(envelope)
components_overlap(component, components[other], prefer_actual=True, at_join=other == i + 1, clearance=spacing(i, other))
for i, component in enumerate(components)
for other in index.query(envelope_with_clearance(i))
if other > i
)

View file

@ -281,6 +281,8 @@ class RoutingProblem:
initial_paths: dict[str, PathSeed] = field(default_factory=dict)
clearance: float = 2.0
safety_zone_radius: float = 0.0021
self_clearance: float = 0.0
_reserved_obstacles: tuple[Polygon, ...] = field(default=(), repr=False)
def __post_init__(self) -> None:
bounds = tuple(self.bounds)
@ -288,6 +290,7 @@ class RoutingProblem:
raise ValueError("Routing bounds must be finite with minimums below maximums")
if not isfinite(self.clearance) or self.clearance < 0:
raise ValueError("Routing clearance must be finite and nonnegative")
_require_nonnegative("self_clearance", self.self_clearance)
object.__setattr__(self, "bounds", bounds)
nets = tuple(self.nets)
seen: set[str] = set()

View file

@ -164,11 +164,12 @@ def add_node(
context.static_safe_cache.add(cache_key)
predecessor = parent.component_result
self_clearance = context.cost_evaluator.collision_engine.self_clearance
if (
(not result.standard_faces and not all(result.physical_checks))
or (config.self_collision_check and component_hits_ancestor_chain(result, parent))
or ((config.self_collision_check or self_clearance) and component_hits_ancestor_chain(result, parent, self_clearance))
or (
not config.self_collision_check and predecessor is not None
not (config.self_collision_check or self_clearance) and predecessor is not None
and not (predecessor.standard_faces and result.standard_faces)
and invalid_component_join(predecessor, result)
)
@ -222,9 +223,13 @@ def add_node(
return
total_overlaps = 0
if not config.skip_congestion and context.cost_evaluator.collision_engine.has_dynamic_paths():
ce = context.cost_evaluator.collision_engine
if ce.has_possible_move_congestion(result, net_id, congestion.presence):
if not config.skip_congestion and ce.has_dynamic_paths():
if config.hard_congestion or not ce.clearance:
if cache_key not in congestion.overlaps:
congestion.overlaps[cache_key] = ce.check_physical_move_congestion(result, net_id).soft_overlap_count
total_overlaps = congestion.overlaps[cache_key]
elif ce.has_possible_move_congestion(result, net_id, congestion.presence):
if ce.has_candidate_move_congestion(
result,
net_id,

View file

@ -28,9 +28,13 @@ def _build_pair_local_context(
problem = context.problem
live_world = context.cost_evaluator.collision_engine
static_obstacles = tuple(live_world.iter_static_geometries())
world = RoutingWorld(clearance=live_world.clearance, safety_zone_radius=live_world.safety_zone_radius, board=live_world.board)
world = RoutingWorld(
clearance=live_world.clearance, safety_zone_radius=live_world.safety_zone_radius, board=live_world.board,
self_clearance=live_world.self_clearance,
)
reserved_ids = {id(polygon) for polygon in problem._reserved_obstacles}
for obstacle in static_obstacles:
world.add_static_obstacle(obstacle)
world.add_static_obstacle(obstacle, reserved=id(obstacle) in reserved_ids)
for net in ordered_nets:
if net.net_id in pair_order:
continue
@ -39,7 +43,7 @@ def _build_pair_local_context(
continue
for component in result.path:
for polygon in component.physical_geometry:
world.add_static_obstacle(polygon)
world.add_static_obstacle(polygon, reserved=True)
danger_map = DangerMap(bounds=problem.bounds)
if context.options.objective.danger_weight:
@ -108,7 +112,7 @@ def search_pair_candidate(
replacements[net_id] = RoutingResult(net_id, tuple(path), reached_target=True, report=report)
for component in path:
for polygon in component.physical_geometry:
world.add_static_obstacle(polygon)
world.add_static_obstacle(polygon, reserved=True)
local.clear_static_caches()
return replacements, local.metrics.total_nodes_expanded

View file

@ -163,7 +163,7 @@ class PathFinder:
def reserve(path: Sequence[ComponentResult]) -> None:
for component in path:
for shape in component.physical_geometry:
temporary.append(world.add_static_obstacle(shape))
temporary.append(world.add_static_obstacle(shape, reserved=True))
try:
yield reserve

View file

@ -192,7 +192,10 @@ def _residual_problem(problem: RoutingProblem, locks: LockPlan) -> RoutingProble
return problem
residual = tuple(net for net in problem.nets if net.net_id not in locks.direct and net.net_id not in locks.disconnected)
locked = tuple(shape for result in locks.direct.values() for shape in result.locked_geometry)
return replace(problem, nets=residual, static_obstacles=problem.static_obstacles + locked)
return replace(
problem, nets=residual, static_obstacles=problem.static_obstacles + locked,
_reserved_obstacles=problem._reserved_obstacles + locked,
)
def _route_residual(

View file

@ -40,9 +40,11 @@ def build_routing_stack(problem: RoutingProblem, options: RoutingOptions) -> Rou
clearance=problem.clearance,
safety_zone_radius=problem.safety_zone_radius,
board=box(*problem.bounds),
self_clearance=problem.self_clearance,
)
reserved_ids = {id(polygon) for polygon in problem._reserved_obstacles}
for obstacle in problem.static_obstacles:
world.add_static_obstacle(obstacle)
world.add_static_obstacle(obstacle, reserved=id(obstacle) in reserved_ids)
danger_map = DangerMap(bounds=problem.bounds)
refinement = options.refinement

View file

@ -7,6 +7,7 @@ from itertools import accumulate, chain
from math import inf
from typing import TYPE_CHECKING, Any
from inire.constants import TOLERANCE_LINEAR
from inire.geometry.component_overlap import components_overlap, invalid_component_join
from inire.geometry.components import _advance_port, _bend90_length, bend_fits_width, bend90_grid_span, build_component
from inire.geometry.primitives import port_local_coordinates, rotation_matrix2
@ -66,16 +67,22 @@ class _WindowEnds:
return None
def component_hits_ancestor_chain(component: ComponentResult, parent_node: Any) -> bool:
def component_hits_ancestor_chain(component: ComponentResult, parent_node: Any, clearance: float = 0.0) -> bool:
current = parent_node
between = 0.0
previous_move = parent_node.component_result if parent_node else None
while current and current.parent:
ancestor_component = current.component_result
if ancestor_component:
if current is parent_node:
if invalid_component_join(ancestor_component, component):
return True
elif components_overlap(ancestor_component, component, prefer_actual=True):
else:
single_bend = current is parent_node.parent and previous_move is not None and previous_move.move_type != "straight"
spacing = clearance if not single_bend and between >= clearance - TOLERANCE_LINEAR else 0.0
if components_overlap(ancestor_component, component, prefer_actual=True, clearance=spacing):
return True
between += ancestor_component.length
current = current.parent
return False
@ -272,6 +279,8 @@ class PathRefiner:
prefix: list[ComponentResult],
suffix: list[ComponentResult],
) -> bool:
if self.collision_engine.self_clearance:
return self.collision_engine.verify_path_report(net_id, (*prefix, *replacement, *suffix)).is_valid
if not self.collision_engine.verify_path_report(net_id, replacement).is_valid:
return False
if prefix and invalid_component_join(prefix[-1], replacement[0]):

View file

@ -638,6 +638,72 @@ def test_partial_path_tracks_geometric_progress_without_cost_heuristic(heuristic
assert run.results_by_net["across"].outcome == "partial"
@pytest.mark.parametrize(("radius", "spacing", "valid"), [(2, 0, True), (2, 4, False), (3, 4, True)])
def test_same_net_clearance_preserves_join_and_checks_separated_path(radius, spacing, valid) -> None:
net = NetSpec("fold", Port(10, 20, 0), Port(10, 20 + 2 * radius, 180))
seed = PathSeed((StraightSeed(25), Bend90Seed(radius, "CCW"), Bend90Seed(radius, "CCW"), StraightSeed(25)))
problem = RoutingProblem((0, 0, 100, 50), (net,), initial_paths={"fold": seed}, self_clearance=spacing)
options = RoutingOptions(search=SearchOptions(node_limit=0, bend_radii=(radius,)))
result = route(problem, options=options).results_by_net["fold"]
assert result.is_valid is valid
assert not result.report.discontinuous
if not valid:
assert result.report.self_collision_count > 0
@pytest.mark.parametrize(("start_x", "y", "collides"), [(10, 22, True), (40, 22, True), (40, 23, False)])
def test_zero_clearance_forbids_inter_net_contact_but_allows_keepout_edges(start_x, y, collides) -> None:
nets = (
NetSpec("first", Port(10, 20, 0), Port(40, 20, 0)),
NetSpec("second", Port(start_x, y, 0), Port(90, y, 0)),
)
seeds = {"first": PathSeed((StraightSeed(30),)), "second": PathSeed((StraightSeed(90 - start_x),))}
problem = RoutingProblem((0, 0, 100, 50), nets, (box(10, 15, 40, 19),), initial_paths=seeds, clearance=0)
results = route(problem, options=RoutingOptions(search=SearchOptions(node_limit=0))).results_by_net
assert [result.report.static_collision_count for result in results.values()] == [0, 0]
assert [result.report.dynamic_collision_count for result in results.values()] == [int(collides), int(collides)]
def test_automatic_residual_cannot_touch_a_locked_distinct_net_at_zero_clearance() -> None:
nets = (
NetSpec("first", Port(10, 20, 0), Port(80, 20, 0)),
NetSpec("second", Port(10, 22, 0), Port(80, 22, 0)),
)
problem = RoutingProblem((0, 0, 100, 50), nets, clearance=0)
options = RoutingOptions(
search=SearchOptions(node_limit=30, bend_radii=(), sbend_radii=()),
refinement=RefinementOptions(enabled=False),
)
results = route(problem, options=options).results_by_net
assert sum(result.is_valid for result in results.values()) == 1
@pytest.mark.parametrize(("second_x", "y", "valid"), [(53, 25, True), (52, 25, False), (50, 26, True)])
def test_guide_admits_moves_using_physical_inter_net_clearance(second_x, y, valid) -> None:
nets = (
NetSpec("first", Port(10, 20, 0), Port(50, 20, 0)),
NetSpec("second", Port(second_x, y, 0), Port(90, y, 0)),
)
problem = RoutingProblem((0, 0, 100, 50), nets, clearance=4)
options = RoutingOptions(
search=SearchOptions(node_limit=50, bend_radii=(), sbend_radii=(), visibility_guidance="off"),
congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False, use_tiered_strategy=False),
refinement=RefinementOptions(enabled=False),
topology=TopologyOptions(mode="guide"),
)
results = route(problem, options=options).results_by_net
assert results["first"].is_valid
assert results["second"].is_valid is valid
def test_automatic_falls_back_to_lattice_when_corridor_search_is_unavailable(monkeypatch) -> None:
monkeypatch.delattr(shapely, "constrained_delaunay_triangles", raising=False)
net = NetSpec("line", Port(10, 50, 0), Port(90, 50, 0))

View file

@ -30,6 +30,8 @@ Implemented items 25 and 36 use cardinal heading vectors and consistent length u
Implemented items 7, 8, 9, and 10 cover endpoint-aware corner visibility with a local fallback, hole-aware plots, indexed terminal-bank checks, and removal of unused private A* node fields. The seven complex-routing walkthrough figures still render byte for byte. The 4,000-net capacity probe took about 0.11 s for a clear bank and 0.04 s for a densely overlapping bank.
Implemented items 23 and 38 expose optional same-net spacing and reject edge and vertex shorts between different nets at zero clearance, including automatic reservations. Hard corridor congestion now uses exact physical spacing with exact-fit and diagonal controls.
| Batch | Work | Acceptance gate |
| --- | --- | --- |
| Physical verification | 1, 2, 17, 23, and 38 | Reject the faulty geometry and keep legal joins valid in search and seed replay. Check circular bend accuracy, folded-route spacing, and isolation between different nets. |