Trim verification work and plan independent channels before search

This commit is contained in:
Jan Petykiewicz 2026-11-30 15:24:14 -08:00
commit d64c70c68f
9 changed files with 85 additions and 48 deletions

View file

@ -117,6 +117,7 @@ class RoutingWorld:
*, *,
board: Polygon | None = None, board: Polygon | None = None,
self_clearance: float = 0.0, self_clearance: float = 0.0,
use_dynamic_grid: bool = True,
) -> None: ) -> None:
self.clearance = clearance self.clearance = clearance
self.self_clearance = self_clearance self.self_clearance = self_clearance
@ -126,15 +127,16 @@ class RoutingWorld:
self.grid_cell_size = 50.0 self.grid_cell_size = 50.0
self.metrics = None self.metrics = None
self._static_obstacles = StaticObstacleIndex(self) self._static_obstacles = StaticObstacleIndex(self)
self._dynamic_paths = DynamicPathIndex(self) self._dynamic_paths = DynamicPathIndex(self, use_grid=use_dynamic_grid)
@classmethod @classmethod
def from_problem(cls, problem: RoutingProblem, *, board: Polygon | None = None) -> RoutingWorld: def from_problem(cls, problem: RoutingProblem, *, board: Polygon | None = None, use_dynamic_grid: bool = True) -> RoutingWorld:
world = cls( world = cls(
clearance=problem.clearance, clearance=problem.clearance,
safety_zone_radius=problem.safety_zone_radius, safety_zone_radius=problem.safety_zone_radius,
board=box(*problem.bounds) if board is None else board, board=box(*problem.bounds) if board is None else board,
self_clearance=problem.self_clearance, self_clearance=problem.self_clearance,
use_dynamic_grid=use_dynamic_grid,
) )
for obstacle in problem.static_obstacles: for obstacle in problem.static_obstacles:
world.add_static_obstacle(obstacle) world.add_static_obstacle(obstacle)
@ -697,15 +699,16 @@ class RoutingWorld:
raw_geometries = static_obstacles.raw_tree.geometries raw_geometries = static_obstacles.raw_tree.geometries
for component in components: for component in components:
for polygon in component.physical_geometry: for polygon in component.physical_geometry:
if self.metrics is not None: query = polygon
self.metrics.total_verify_static_buffer_ops += 1 if self.clearance > 0:
buffered = polygon.buffer(self.clearance, join_style="mitre") x0, y0, x1, y1 = polygon.bounds
hits = static_obstacles.raw_tree.query(buffered, predicate="intersects") margin = self.clearance
query = box(x0 - margin, y0 - margin, x1 + margin, y1 + margin)
hits = static_obstacles.raw_tree.query(query)
for hit_idx in hits: for hit_idx in hits:
obstacle = raw_geometries[hit_idx] obstacle = raw_geometries[hit_idx]
# A mitre may extend past the physical clearance # Padded bounds only screen candidates. Use the physical
# radius at a component corner. Check the distance # polygons for clearance and zero-clearance contact rules.
# before counting an overlap with that broad phase.
violates = _violates_net_clearance if static_obstacles.raw_owners[hit_idx] is not None else _violates_clearance violates = _violates_net_clearance if static_obstacles.raw_owners[hit_idx] is not None else _violates_clearance
if violates(polygon, obstacle, self.clearance): if violates(polygon, obstacle, self.clearance):
static_collision_count += 1 static_collision_count += 1

View file

@ -9,7 +9,7 @@ from shapely.strtree import STRtree
from inire.constants import TOLERANCE_LINEAR from inire.constants import TOLERANCE_LINEAR
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Sequence from collections.abc import Iterable, Sequence
from shapely.geometry import Polygon from shapely.geometry import Polygon
from inire.geometry.components import ComponentResult from inire.geometry.components import ComponentResult
@ -91,19 +91,8 @@ def count_path_self_collisions(components: Sequence[ComponentResult], clearance:
internal_collisions += 1 internal_collisions += 1
if len(components) < 2: if len(components) < 2:
return internal_collisions return internal_collisions
envelopes = [
component.physical_geometry[0] if len(component.physical_geometry) == 1 else box(*component.total_physical_bounds)
for component in components
]
index = STRtree(envelopes)
distances = list(accumulate((component.length for component in components), initial=0.0)) if clearance else () 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: def spacing(i: int, other: int) -> float:
if not distances or distances[other] - distances[i + 1] < clearance - TOLERANCE_LINEAR: if not distances or distances[other] - distances[i + 1] < clearance - TOLERANCE_LINEAR:
return 0.0 return 0.0
@ -111,9 +100,25 @@ def count_path_self_collisions(components: Sequence[ComponentResult], clearance:
return 0.0 # Keep the geometry local to one continuous bend together. return 0.0 # Keep the geometry local to one continuous bend together.
return clearance return clearance
pairs: Iterable[tuple[int, int]]
if len(components) <= 3:
# At most three pairs, each with its own bounds check.
pairs = combinations(range(len(components)), 2)
else:
envelopes = [
component.physical_geometry[0] if len(component.physical_geometry) == 1 else box(*component.total_physical_bounds)
for component in components
]
index = STRtree(envelopes)
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)
pairs = ((i, other) for i in range(len(components)) for other in index.query(envelope_with_clearance(i)) if other > i)
return internal_collisions + sum( return internal_collisions + sum(
components_overlap(component, components[other], prefer_actual=True, at_join=other == i + 1, clearance=spacing(i, other)) components_overlap(components[i], components[other], prefer_actual=True, at_join=other == i + 1, clearance=spacing(i, other))
for i, component in enumerate(components) for i, other in pairs
for other in index.query(envelope_with_clearance(i))
if other > i
) )

View file

@ -38,10 +38,12 @@ class DynamicPathIndex:
"_physical_objects", "_physical_objects",
"_physical_ids_by_net", "_physical_ids_by_net",
"_physical_id_counter", "_physical_id_counter",
"_use_grid",
) )
def __init__(self, engine: RoutingWorld) -> None: def __init__(self, engine: RoutingWorld, *, use_grid: bool = True) -> None:
self.engine = engine self.engine = engine
self._use_grid = use_grid
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.dilated: dict[int, Polygon] = {} self.dilated: dict[int, Polygon] = {}
@ -157,6 +159,7 @@ class DynamicPathIndex:
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)
if self._use_grid:
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: if physical_geometry is None:

View file

@ -506,28 +506,27 @@ class _AutomaticRun:
return True return True
return False return False
def _column_recovery_trial(self, options: RoutingOptions) -> Trial | None: def _try_column_recovery(self, options: RoutingOptions, trials: list[Trial], groups: tuple[RoutingProblem, ...]) -> bool:
problem = self.problem problem = self.problem
if problem.initial_paths or not options.search.bend_radii or not problem._blocking_polygons:
return None
planner = "column-recovery" planner = "column-recovery"
with self._time("plan", planner=planner): with self._time("plan", planner=planner):
groups = column_recovery_subproblems(problem)
if not groups:
return None
combined = {} combined = {}
for group in groups: for group in groups:
for seeds in column_recovery_candidates(group, options.search): for seeds in column_recovery_candidates(group, options.search):
trial = self._verify(replace(group, initial_paths=seeds), planner) trial = self._verify(replace(group, initial_paths=seeds), planner)
if len(trial.valid_costs) == len(group.nets): if len(trial.valid_costs) == len(group.nets):
if group is problem: if group is problem:
return trial trials.append(trial)
return True
combined.update(seeds) combined.update(seeds)
break break
else: else:
return None return False
trial = self._verify(replace(problem, initial_paths=combined), planner) trial = self._verify(replace(problem, initial_paths=combined), planner)
return trial if len(trial.valid_costs) == len(problem.nets) else None if len(trial.valid_costs) == len(problem.nets):
trials.append(trial)
return True
return False
def _search_trials(self, trials: list[Trial], target: int) -> None: def _search_trials(self, trials: list[Trial], target: int) -> None:
configured_search = self.options.search configured_search = self.options.search
@ -561,6 +560,17 @@ class _AutomaticRun:
try_construction_early = not options.congestion.shuffle_nets try_construction_early = not options.congestion.shuffle_nets
if try_construction_early and self._try_column_jogs(options, trials, target): if try_construction_early and self._try_column_jogs(options, trials, target):
return True return True
groups = ()
if (
try_construction_early and target == len(problem.nets) and not problem.initial_paths
and options.search.bend_radii and problem._blocking_polygons
):
with self._time("plan", planner="column-recovery"):
groups = column_recovery_subproblems(problem)
# With independent channels, try construction before spending search
# budget on each net. Keep the general bypass as a later fallback.
if len(groups) > 1 and self._try_column_recovery(options, trials, groups):
return True
probe_iterations = options.congestion.max_iterations probe_iterations = options.congestion.max_iterations
proxy, _ = resolve_bend_geometry(options.search) proxy, _ = resolve_bend_geometry(options.search)
# Clipped proxies can find cheaper routes in later probe iterations than in the wider retry. # Clipped proxies can find cheaper routes in later probe iterations than in the wider retry.
@ -591,10 +601,7 @@ class _AutomaticRun:
if len(_best_trial(trials).valid_costs) >= target: if len(_best_trial(trials).valid_costs) >= target:
return True return True
if target == len(problem.nets) and not options.congestion.shuffle_nets: if len(groups) == 1 and self._try_column_recovery(options, trials, groups):
recovery = self._column_recovery_trial(options)
if recovery is not None:
trials.append(recovery)
return True return True
# Every short shift has lateral displacement, so the direct retry cannot lock # Every short shift has lateral displacement, so the direct retry cannot lock

View file

@ -110,7 +110,7 @@ def _pack_routes(
clearance: float, clearance: float,
) -> dict[str, PathSeed] | None: ) -> dict[str, PathSeed] | None:
order = sorted(candidates, key=lambda net_id: len(candidates[net_id])) order = sorted(candidates, key=lambda net_id: len(candidates[net_id]))
chosen: dict[str, tuple[PathSeed, BaseGeometry]] = {} chosen: dict[str, tuple[PathSeed, BaseGeometry, tuple[float, float, float, float]]] = {}
remaining = 4096 remaining = 4096
choices = [iter(candidates[net_id]) for net_id in order] choices = [iter(candidates[net_id]) for net_id in order]
index = 0 index = 0
@ -122,9 +122,14 @@ def _pack_routes(
if remaining <= 0: if remaining <= 0:
return None return None
remaining -= 1 remaining -= 1
if any(_violates_net_clearance(footprint, other, clearance) for _, other in chosen.values()): left, bottom, right, top = bounds = footprint.bounds
if any(
not (right + clearance < x0 or left > x1 + clearance or top + clearance < y0 or bottom > y1 + clearance)
and _violates_net_clearance(footprint, other, clearance)
for _, other, (x0, y0, x1, y1) in chosen.values()
):
continue continue
chosen[net_id] = (seed, footprint) chosen[net_id] = (seed, footprint, bounds)
index += 1 index += 1
break break
else: else:
@ -141,8 +146,9 @@ def _verified_candidates(
search: SearchOptions, search: SearchOptions,
seeds: Iterable[PathSeed], seeds: Iterable[PathSeed],
) -> Iterator[tuple[PathSeed, BaseGeometry, tuple[ComponentResult, ...]]]: ) -> Iterator[tuple[PathSeed, BaseGeometry, tuple[ComponentResult, ...]]]:
bounds = board.bounds
for seed in seeds: for seed in seeds:
path = materialize_path_seed(seed, start=net.start, net_width=net.width, search=search, clearance=world.clearance, bounds=board.bounds) path = materialize_path_seed(seed, start=net.start, net_width=net.width, search=search, clearance=world.clearance, bounds=bounds)
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 = union_all([polygon for component in path for polygon in component.physical_geometry]) footprint = union_all([polygon for component in path for polygon in component.physical_geometry])

View file

@ -82,7 +82,7 @@ def _direct_paths(
*, *,
priority: frozenset[str] = frozenset(), priority: frozenset[str] = frozenset(),
) -> dict[str, RoutingResult]: ) -> dict[str, RoutingResult]:
world = RoutingWorld.from_problem(problem, board=board) world = RoutingWorld.from_problem(problem, board=board, use_dynamic_grid=False)
ordered = ordered_nets(problem.nets, options.congestion.net_order) ordered = ordered_nets(problem.nets, options.congestion.net_order)
if priority: if priority:
ordered.sort(key=lambda net: net.net_id not in priority) ordered.sort(key=lambda net: net.net_id not in priority)

View file

@ -35,7 +35,8 @@ def build_routing_stack(problem: RoutingProblem, options: RoutingOptions) -> Rou
problem = plan_ordered_bundle(problem, options.search, infer_terminal_headings=options.topology.infer_terminal_headings) problem = plan_ordered_bundle(problem, options.search, infer_terminal_headings=options.topology.infer_terminal_headings)
world = RoutingWorld.from_problem(problem) # Replay and one-node attempts can rely on the indexes already used for verification.
world = RoutingWorld.from_problem(problem, use_dynamic_grid=options.search.node_limit > 1)
danger_map = proximity_map(problem, options.search.proximity_range) danger_map = proximity_map(problem, options.search.proximity_range)
refinement = options.refinement refinement = options.refinement

View file

@ -934,7 +934,7 @@ def test_verify_only_retains_colliding_seeds_and_final_trace(mode, rounds, monke
assert run.metrics.nodes_expanded == 0 assert run.metrics.nodes_expanded == 0
assert run.metrics.route_iterations == 1 assert run.metrics.route_iterations == 1
assert run.metrics.verify_path_report_calls == 3 assert run.metrics.verify_path_report_calls == 3
assert run.metrics.verify_static_buffer_ops == 3 assert run.metrics.verify_static_buffer_ops == 0
assert run.metrics.verify_dynamic_exact_pair_checks == 2 assert run.metrics.verify_dynamic_exact_pair_checks == 2
assert callbacks == [(0, run.results_by_net)] assert callbacks == [(0, run.results_by_net)]
assert with_callback.results_by_net == run.results_by_net assert with_callback.results_by_net == run.results_by_net

View file

@ -75,6 +75,18 @@ def test_column_recovery_routes_with_a_one_node_search_budget(name) -> None:
assert all(result.is_valid for result in run.results_by_net.values()) assert all(result.is_valid for result in run.results_by_net.values())
def test_independent_column_channels_can_skip_the_search_probe() -> None:
(case,) = CASE_GROUPS["search-comb-3x4"]
options = automatic_options(profile_options(case, "corpus-regression"), "corpus-regression")
run = route(case.problem, options=options)
assert run.automatic is not None
assert run.automatic.selected_planner == "column-recovery"
assert len(run.automatic.verified_net_ids) == case.routing_bound
assert run.metrics.nodes_expanded == 0
@pytest.mark.parametrize("name", ["retry-holdout-stepped-roof", "retry-holdout-west-roof"]) @pytest.mark.parametrize("name", ["retry-holdout-stepped-roof", "retry-holdout-west-roof"])
def test_residual_perimeter_completes_a_return_with_straight_peers(name) -> None: def test_residual_perimeter_completes_a_return_with_straight_peers(name) -> None:
(case,) = CASE_GROUPS[name] (case,) = CASE_GROUPS[name]