Preserve routing coverage and verify release and example regressions

This commit is contained in:
Jan Petykiewicz 2026-11-28 20:57:22 -08:00
commit 8f6a917f51
26 changed files with 206 additions and 91 deletions

Binary file not shown.

Before

Width:  |  Height:  |  Size: 32 KiB

After

Width:  |  Height:  |  Size: 32 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 45 KiB

After

Width:  |  Height:  |  Size: 45 KiB

Before After
Before After

View file

@ -82,6 +82,7 @@ To read a route's polygons and write them to a test file, follow the [geometry e
| `sbend_outlines` | `()` | Complete custom S-bend polygons, supplied as `SBendOutline(offset, radius, width, polygon)` entries. Each entry applies to its signed offset, radius, and net width. |
| `proximity_range` | `10.0` | Obstacle proximity scoring range in layout units. Scale it with the coordinates when changing units. Large perimeters use an exact boundary index once the sample budget is reached. |
| `bend_physical_length` | `None` | Optional authored centerline length for the shared custom 90-degree template, including tangent extensions. Search, refinement, and reports use it when supplied. |
| `distance_heuristic_weight` | `1.0` | Finite, nonnegative multiplier for the remaining-distance term only. Increase it to favor progress toward the target relative to estimated turn penalties. The routed path's objective stays the same. |
A custom S-bend outline uses local coordinates. Its input face is centered at `(0, 0)`, its output face at `(span, offset)`, and both ports face east. Use the same grid span as `SBendSeed(offset, radius)`, including any tangent extension to reach the output face. For example, an offset of `40` with radius `50` has its output at `(80, 40)`. The router rotates and translates the entire outline and uses it for collision checks and export. Supply a separate outline to customize the opposite offset. Width matching allows a relative difference of `1e-12` to account for floating-point conversions. An ambiguous match raises an error. Unmatched moves use the circular S-bend. Set `SBendOutline.length` to use a process-specific centerline length for scoring, refinement, and reporting. The default is the nominal circular length. Automatic mode uses lattice search when a registered outline matches a net width. Bundle mode requires circular bends for its nets.

View file

@ -3,10 +3,15 @@ import time
from shapely.geometry import box
from inire import (
CongestionOptions,
DiagnosticsOptions,
NetSpec,
ObjectiveWeights,
Port,
RoutingOptions,
RoutingProblem,
RoutingResult,
SearchOptions,
)
from inire.router._stack import build_routing_stack
from inire.utils.visualization import plot_expanded_nodes, plot_routing_results
@ -40,8 +45,6 @@ def main() -> None:
static_obstacles=tuple(obstacles),
clearance=6.0,
)
from inire import CongestionOptions, DiagnosticsOptions, ObjectiveWeights, RoutingOptions, SearchOptions
options = RoutingOptions(
search=SearchOptions(
node_limit=2_000_000,
@ -49,6 +52,7 @@ def main() -> None:
sbend_radii=(50.0,),
greedy_h_weight=1.5,
bend_clip_margin=10.0,
distance_heuristic_weight=10.0,
),
objective=ObjectiveWeights(
unit_length_cost=0.1,

View file

@ -6,7 +6,7 @@ from math import asin, ceil, pi, radians, sqrt
from typing import TYPE_CHECKING, Literal
import numpy
from shapely import get_num_coordinates, snap
from shapely import get_num_coordinates, snap, transform
from shapely.affinity import rotate as shapely_rotate
from shapely.affinity import scale as shapely_scale
from shapely.affinity import translate as shapely_translate
@ -243,18 +243,23 @@ class ComponentResult:
def translate(self, dx: int | float, dy: int | float) -> ComponentResult:
# The collision and physical views often reference the same polygons.
translated: dict[int, Polygon] = {}
polygons = {
id(polygon): polygon
for geometry in (
self.collision_geometry, self.physical_geometry,
self.dilated_collision_geometry, self.dilated_physical_geometry,
)
for polygon in geometry
}
if len(polygons) > 1 and (self.standard_faces or all(not polygon.has_z for polygon in polygons.values())):
offset = numpy.array((dx, dy))
shifted = transform(list(polygons.values()), lambda coordinates: coordinates + offset)
translated = dict(zip(polygons, shifted, strict=True))
else:
translated = {key: shapely_translate(polygon, dx, dy) for key, polygon in polygons.items()}
def translate_geometry(polygons: Sequence[Polygon]) -> tuple[Polygon, ...]:
geometry = []
for polygon in polygons:
key = id(polygon)
shifted = translated.get(key)
if shifted is None:
shifted = shapely_translate(polygon, dx, dy)
translated[key] = shifted
geometry.append(shifted)
return tuple(geometry)
return tuple(translated[id(polygon)] for polygon in polygons)
result = ComponentResult(
start_port=self.start_port.translate(dx, dy),
@ -274,6 +279,8 @@ class ComponentResult:
def _combine_bounds(bounds_list: list[tuple[float, float, float, float]]) -> tuple[float, float, float, float]:
if len(bounds_list) == 1:
return bounds_list[0]
arr = numpy.asarray(bounds_list, dtype=numpy.float64)
return (
float(arr[:, 0].min()),

View file

@ -111,8 +111,7 @@ class StaticObstacleIndex:
for obj_id in sorted(self.geometries.keys()):
polygon = self.geometries[obj_id]
style = "mitre" if is_axis_aligned_rect(polygon) else "round"
dilated = polygon.buffer(total_dilation, join_style=style)
dilated = polygon.buffer(total_dilation, join_style="mitre")
geometries.append(dilated)
bounds_list.append(dilated.bounds)
is_rect_list.append(is_axis_aligned_rect(dilated))

View file

@ -59,13 +59,19 @@ def verify_export_grid(
"""Round vertices to the export grid and check the geometry the writer will receive."""
if not isfinite(grid) or grid <= 0:
raise ValueError("Export grid must be finite and positive")
net_ids = {net.net_id for net in problem.nets}
nets = {net.net_id: net for net in problem.nets}
paths: dict[str, tuple[ComponentResult, ...]] = {}
for net_id, result in results.items():
if net_id not in net_ids or net_id != result.net_id:
net = nets.get(net_id)
if net is None or net_id != result.net_id:
raise ValueError(f"Export result {net_id!r} has no matching routing net")
if not result.is_valid:
raise ValueError(f"Export result {net_id!r} must already be verified")
if (
result.path[0].start_port.as_tuple()[:2] != net.start.as_tuple()[:2]
or result.path[-1].end_port.as_tuple()[:2] != net.target.as_tuple()[:2]
):
raise ValueError(f"Export result {net_id!r} has different terminal positions")
paths[net_id] = tuple(_round_component(component, grid) for component in result.path)
world = RoutingWorld.from_problem(problem)
@ -149,6 +155,8 @@ def route_profiles(
assigned = [net_id for net_ids, _ in groups for net_id in net_ids]
if len(set(assigned)) != len(assigned) or set(assigned) != net_by_id.keys():
raise ValueError("Process profiles must assign every net to exactly one group")
if unknown := problem.initial_paths.keys() - net_by_id.keys():
raise ValueError(f"Initial paths provided for unknown nets: {', '.join(sorted(unknown))}")
results: dict[str, RoutingResult] = {}
reservations: list[Polygon] = []

View file

@ -108,10 +108,12 @@ class SearchOptions:
sbend_outlines: tuple[SBendOutline, ...] = ()
proximity_range: float = 10.0
bend_physical_length: float | None = None
distance_heuristic_weight: float = 1.0
def __post_init__(self) -> None:
_require_budget("node_limit", self.node_limit)
_require_nonnegative("greedy_h_weight", self.greedy_h_weight)
_require_nonnegative("distance_heuristic_weight", self.distance_heuristic_weight)
if not isfinite(self.proximity_range) or self.proximity_range <= 0:
raise ValueError("proximity_range must be finite and positive")
if self.bend_physical_length is not None:

View file

@ -43,7 +43,7 @@ class RoutingReport:
@property
def is_valid(self) -> bool:
return self.collision_count == 0
return self.collision_count == 0 and self.terminal_error is None
@dataclass(frozen=True, slots=True)
@ -275,7 +275,7 @@ class RoutingResult:
return "unroutable"
if not self.reached_target:
return "partial"
if self.report.collision_count > 0 or self.report.terminal_error is not None:
if not self.report.is_valid:
return "colliding"
return "completed"

View file

@ -221,7 +221,9 @@ def expand_moves(
net_width=net_width,
caller="expand_forward",
)
if (previous is None or previous.move_type != "straight") and max_reach < max(1, math.ceil(search_options.min_straight_length)):
short_launch = (previous is None or previous.move_type != "straight") and max_reach < max(1, math.ceil(search_options.min_straight_length))
sbend_only = not search_options.bend_radii and bool(search_options.sbend_radii)
if short_launch or (sbend_only and max_reach < scan_limit):
# Radius around the ray can block a launch at an otherwise clear port face.
reach = collision.straight_reach(cp, scan_limit, net_width)
max_reach = max(max_reach, math.floor(reach + TOLERANCE_LINEAR))

View file

@ -104,7 +104,8 @@ class SearchRunConfig:
evaluator = context.cost_evaluator
cost = evaluator.h_manhattan(current, target, min_bend_radius=context.min_bend_radius)
if self.restrict_to_corridor and self.corridor is not None and current != target:
distance_cost = self.corridor.remaining(current) * evaluator.default_weights.unit_length_cost
distance_weight = evaluator.default_weights.unit_length_cost * evaluator.distance_heuristic_weight
distance_cost = self.corridor.remaining(current) * distance_weight
return 0.4 * cost + 0.6 * evaluator.greedy_h_weight * distance_cost
return cost

View file

@ -52,6 +52,7 @@ def _build_pair_local_context(
danger_map,
context.options.objective,
greedy_h_weight=context.cost_evaluator.greedy_h_weight,
distance_heuristic_weight=context.cost_evaluator.distance_heuristic_weight,
)
return AStarContext(
evaluator,

View file

@ -308,7 +308,7 @@ class PathFinder:
seed_nodes_expanded=self.metrics.total_nodes_expanded - before,
)
def _prepare_state(self, corridors: dict[str, tuple[Corridor, ...]] | None = None) -> _RoutingState:
def _prepare_state(self, corridors: dict[str, tuple[Corridor, ...]] | None = None, *, started_at: float | None = None) -> _RoutingState:
problem = self.context.problem
congestion = self.context.options.congestion
net_specs = {net.net_id: net for net in problem.nets}
@ -318,7 +318,7 @@ class PathFinder:
ordered_net_ids=[net.net_id for net in ordered_nets(net_specs.values(), congestion.net_order)],
results={},
needs_self_collision_check=set(),
start_time=time.monotonic(),
start_time=time.monotonic() if started_at is None else started_at,
timeout_s=max(60.0, 10.0 * num_nets * congestion.max_iterations),
initial_paths=None,
accumulated_expanded_nodes=[],
@ -1213,6 +1213,7 @@ class PathFinder:
iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None = None,
phase_timer: PhaseTimer | None = None,
corridors: dict[str, tuple[Corridor, ...]] | None = None,
started_at: float | None = None,
) -> dict[str, RoutingResult]:
self.context.congestion_penalty = self.context.options.congestion.base_penalty
self.accumulated_expanded_nodes = []
@ -1224,7 +1225,7 @@ class PathFinder:
self.metrics.reset_totals()
self.metrics.reset_per_route()
state = self._prepare_state(corridors)
state = self._prepare_state(corridors, started_at=started_at)
timed_out = self._run_iterations(state, iteration_callback)
self.accumulated_expanded_nodes = list(state.accumulated_expanded_nodes)
# A partial iteration can leave the index out of sync with the saved results.
@ -1240,10 +1241,11 @@ class PathFinder:
review = self._review_restored_best(state)
if not timed_out:
self._run_pair_local_search(state, review)
if not timed_out:
if not timed_out and not self._expired(state):
with phase_timer("refine") if phase_timer is not None and self.context.options.refinement.enabled else nullcontext():
self._refine_results(state)
with phase_timer("verify") if phase_timer is not None else nullcontext():
final_results, details_by_net = self._verify_results(state)
self._capture_frontier_trace(state, final_results, details_by_net)
if not self._expired(state):
self._capture_frontier_trace(state, final_results, details_by_net)
return final_results

View file

@ -77,9 +77,11 @@ def route_astar(
best_node = start_node
best_distance = _distance_to_terminal(start, target)
nodes_expanded = 0
# Small bounded probes need the full move set early. For larger attempts
# leave room for the preferred frontier before widening an expensive search.
release_turns_at = min(32, config.node_limit // 20) if config.node_limit <= 1_000 else min(100_000, config.node_limit * 3 // 4)
# A short forward scan has to piece together progress one local move at a
# time. Give the preferred frontier more room when long straights are available.
scan_spans = context.options.search.max_straight_length / max(1.0, context.min_bend_radius)
preferred = 2 * min(scan_spans, config.node_limit) ** 2
release_turns_at = min(config.node_limit, max(config.node_limit // 20, preferred))
while open_set or deferred_turns:
if nodes_expanded >= config.node_limit or (config.expired is not None and nodes_expanded % 32 == 0 and config.expired()):

View file

@ -1,5 +1,6 @@
from __future__ import annotations
import time
from dataclasses import dataclass, replace
from typing import TYPE_CHECKING
@ -48,6 +49,7 @@ def build_routing_stack(problem: RoutingProblem, options: RoutingOptions) -> Rou
danger_map,
options.objective,
greedy_h_weight=options.search.greedy_h_weight,
distance_heuristic_weight=options.search.distance_heuristic_weight,
)
context = AStarContext(evaluator, problem, options)
finder = PathFinder(context)
@ -72,8 +74,9 @@ def route_once(
if options.topology.mode == "automatic":
raise ValueError("A single routing attempt requires an explicit planner mode")
started_at = time.monotonic()
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, started_at=started_at)
if options.topology.mode == "bundle":
for result in results.values():
if not result.is_valid:

View file

@ -98,7 +98,9 @@ def constrained_triangulation_available() -> bool:
class _Mesh:
def __init__(self, board: Polygon, obstacles: Iterable[Polygon], margin: float, clearance: float, *, relief: float = 0.0) -> None:
def __init__(
self, board: Polygon, obstacles: Iterable[Polygon], margin: float, clearance: float, *, relief: float = 0.0, round_joins: bool = False,
) -> None:
if not constrained_triangulation_available():
raise RuntimeError("Topological routing requires Shapely 2.1 and GEOS 3.10 or newer")
@ -109,7 +111,7 @@ class _Mesh:
self.keepouts = shapely.STRtree(tuple(obstacles))
padding = max(0.0, margin + clearance - relief)
padded = shapely.union_all([
shape.buffer(padding, join_style="mitre" if is_axis_aligned_rect(shape) else "round")
shape.buffer(padding, join_style="round" if round_joins and not is_axis_aligned_rect(shape) else "mitre")
for shape in self.keepouts.geometries
])
self.inset = board.buffer(-margin)
@ -452,8 +454,8 @@ def plan_corridors(
board = box(*bounds)
keepouts = tuple(obstacles)
def plan_group(group: Sequence[NetSpec], width: float, *, relief: float = 0.0) -> tuple[dict[str, tuple[Corridor, ...]], BaseGeometry]:
mesh = _Mesh(board, keepouts, width / 2, clearance, relief=relief)
def plan_group(group: Sequence[NetSpec], width: float, *, recover: bool = False) -> tuple[dict[str, tuple[Corridor, ...]], BaseGeometry]:
mesh = _Mesh(board, keepouts, width / 2, clearance, relief=8 * TOLERANCE_LINEAR if recover else 0.0, round_joins=recover)
endpoints, leads = _endpoint_access(mesh, group, bend_radius)
assignments = _plan_lane_assignments(
mesh, group, endpoints, leads, bend_radius=bend_radius, limit=limit, joint_net_ids=joint_net_ids
@ -487,6 +489,6 @@ def plan_corridors(
if missing and keepouts:
# Exact-clearance passages can collapse to a line before triangulation.
# This affects only candidate guidance. Move admission checks the original shapes.
recovered, _ = plan_group(missing, width, relief=8 * TOLERANCE_LINEAR)
recovered, _ = plan_group(missing, width, recover=True)
guides.update(recovered)
return {net.net_id: guides[net.net_id] for net in nets if net.net_id in guides}

View file

@ -38,6 +38,7 @@ class CostEvaluator:
"danger_map",
"_search_weights",
"_greedy_h_weight",
"distance_heuristic_weight",
"_target_x",
"_target_y",
"_target_r",
@ -54,6 +55,7 @@ class CostEvaluator:
bend_penalty: float = 250.0,
sbend_penalty: float | None = None,
danger_weight: float = 1.0,
distance_heuristic_weight: float = 1.0,
) -> None:
actual_sbend_penalty = 2.0 * bend_penalty if sbend_penalty is None else sbend_penalty
self.collision_engine = collision_engine
@ -65,6 +67,7 @@ class CostEvaluator:
danger_weight=danger_weight,
)
self._greedy_h_weight = float(greedy_h_weight)
self.distance_heuristic_weight = distance_heuristic_weight
self._target_x = 0.0
self._target_y = 0.0
self._target_r = 0
@ -79,6 +82,7 @@ class CostEvaluator:
objective: ObjectiveWeights,
*,
greedy_h_weight: float = 1.5,
distance_heuristic_weight: float = 1.0,
) -> CostEvaluator:
return cls(
world,
@ -88,6 +92,7 @@ class CostEvaluator:
bend_penalty=objective.bend_penalty,
sbend_penalty=objective.sbend_penalty,
danger_weight=objective.danger_weight,
distance_heuristic_weight=distance_heuristic_weight,
)
@property
@ -148,7 +153,8 @@ class CostEvaluator:
if diff == 0 and perp_dist > 0:
penalty += 2 * bp
return self._greedy_h_weight * (dist * self._search_weights.unit_length_cost + penalty)
distance_cost = dist * (self._search_weights.unit_length_cost * self.distance_heuristic_weight)
return self._greedy_h_weight * (distance_cost + penalty)
def score_component(
self,

View file

@ -289,6 +289,7 @@ def _build_example_07_variant_stack(
sbend_radii=(50.0,),
greedy_h_weight=1.5,
bend_clip_margin=10.0,
distance_heuristic_weight=10.0,
),
objective=ObjectiveWeights(
unit_length_cost=0.1,

View file

@ -105,12 +105,13 @@ def test_translate_reuses_shared_polygons_and_preserves_each_geometry_view(
) -> None:
component = SBend.generate(Port(0, 0, 90), -5.0, 10.0, 2.0, collision_type=collision_type, dilation=1.0)
calls = []
transform = components_module.transform
def translate(polygon, dx, dy):
calls.append(id(polygon))
return shapely_translate(polygon, dx, dy)
def record(polygons, operation):
calls.extend(map(id, polygons))
return transform(polygons, operation)
monkeypatch.setattr(components_module, "shapely_translate", translate)
monkeypatch.setattr(components_module, "transform", record)
dx, dy = 81.25, -31.5
shifted = component.translate(dx, dy)

View file

@ -1,3 +1,5 @@
from dataclasses import replace
import pytest
from shapely.geometry import Polygon, box
@ -90,7 +92,7 @@ def test_example_07_no_warm_start_trace_finishes_without_conflict_edges() -> Non
assert final_entry.conflict_edges == ()
def test_example_06_clipped_bbox_margin_restores_legacy_seed() -> None:
def test_example_06_clipped_bbox_margin_keeps_legacy_seed_replayable() -> None:
bounds = (-20, -20, 170, 170)
obstacles = (
Polygon([(40, 110), (60, 110), (60, 130), (40, 130)]),
@ -116,22 +118,7 @@ def test_example_06_clipped_bbox_margin_restores_legacy_seed() -> None:
**common_kwargs,
),
).results_by_net["clipped_model"]
legacy_margin = route(
problem,
options=RoutingOptions(
search=SearchOptions(
bend_radii=(10.0,),
bend_collision_type="clipped_bbox",
bend_clip_margin=1.0,
),
**common_kwargs,
),
).results_by_net["clipped_model"]
assert no_margin.is_valid
assert legacy_margin.is_valid
assert legacy_margin.as_seed() != no_margin.as_seed()
assert legacy_margin.as_seed() == PathSeed(
legacy_seed = PathSeed(
(
StraightSeed(5.0),
Bend90Seed(10.0, "CW"),
@ -141,6 +128,16 @@ def test_example_06_clipped_bbox_margin_restores_legacy_seed() -> None:
StraightSeed(30.0),
)
)
simulation = replace(problem, initial_paths={"clipped_model": legacy_seed})
legacy_options = RoutingOptions(
search=SearchOptions(node_limit=0, bend_radii=(10.0,), bend_collision_type="clipped_bbox", bend_clip_margin=1.0),
**common_kwargs,
)
legacy = route(simulation, options=legacy_options).results_by_net["clipped_model"]
assert no_margin.is_valid
assert legacy.is_valid
assert legacy.as_seed() == legacy_seed
def test_example_07_reduced_bottleneck_uses_adaptive_greedy_callback() -> None:

Some files were not shown because too many files have changed in this diff Show more