Recover bounded routes around bends and through narrow corridors

This commit is contained in:
Jan Petykiewicz 2026-11-28 20:29:40 -08:00
commit af3ddfbb09
21 changed files with 616 additions and 73 deletions

View file

@ -15,7 +15,7 @@ Omitting `options` uses `RoutingOptions()`. To observe progress, pass a callable
### Ports and nets ### Ports and nets
- `Port(x, y, r)` rounds coordinates to integers. The heading `r` is in degrees, with 0 east, 90 north, 180 west, and 270 south. The rounded angle must be a multiple of 90 and is wrapped to the range 0–359. - `Port(x, y, r)` rounds coordinates to integers. The heading `r` is in degrees, with 0 east, 90 north, 180 west, and 270 south. The rounded angle must be a multiple of 90 and is wrapped to the range 0–359.
- `NetSpec(net_id, start, target, width=2.0)` uses a unique ID, two ports, and a finite positive width. Set the start heading to the direction of departure and the target heading to the direction of arrival. - `NetSpec(net_id, start, target, width=2.0)` uses a unique string ID, two ports, and a finite positive width. Set the start heading to the direction of departure and the target heading to the direction of arrival. If both snapped ports are identical, connect the placed ports directly and omit that net from the routing problem.
### RoutingProblem ### RoutingProblem
@ -28,8 +28,8 @@ The fields below appear in constructor order. Use one layout unit for coordinate
| `static_obstacles` | `()` | Valid, nonempty Shapely `Polygon` objects that define keepouts. | | `static_obstacles` | `()` | Valid, nonempty Shapely `Polygon` objects 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` | 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. | | `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. | | `safety_zone_radius` | `0.0021` | Tolerance for small obstacle intersections at a move's endpoints during search. |
| `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. |
## Path seeds ## Path seeds
@ -43,7 +43,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` flags geometry outside the board. `discontinuous` flags missing or point-only joins, including at terminal faces. `invalid_geometry` flags invalid or empty physical polygons. `seed_error` identifies a supplied bend that cannot carry the net's width. | | `RoutingResult.report` | `total_length` in layout units plus static, dynamic, and self-collision counts. `out_of_bounds` flags geometry outside the board. `discontinuous` flags missing or point-only joins, including at terminal faces. `invalid_geometry` flags invalid or empty physical polygons. `seed_error` identifies a supplied bend that cannot carry the net's width. `terminal_error` identifies an inaccessible start or target face. |
| `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. |
@ -129,7 +129,7 @@ For a layout that repeatedly stops short at an opening, `guide` can suggest a pa
| --- | --- | --- | | --- | --- | --- |
| `mode` | `"automatic"` | Select a [routing mode](tune-and-troubleshoot.md#choose-a-routing-mode). | | `mode` | `"automatic"` | Select a [routing mode](tune-and-troubleshoot.md#choose-a-routing-mode). |
| `max_corridors` | `3` | Maximum proposed passages per net. | | `max_corridors` | `3` | Maximum proposed passages per net. |
| `guide_strength` | `0.75` | Maximum added guidance cost per unit length. Zero keeps the suggested moves without adding cost. | | `guide_strength` | `0.75` | Maximum added guidance cost per unit length. Explicit guide and seed runs with at least two configured congestion iterations may try one additional iteration from the start with zero guidance cost. The retry retains corridor move proposals and wins only with higher verified coverage. |
| `seed_node_limit` | `600` | Total seed-search expansions per net, capped by the active search limit. | | `seed_node_limit` | `600` | Total seed-search expansions per net, capped by the active search limit. |
| `infer_terminal_headings` | `False` | Let automatic or bundle mode choose headings for supported layouts with flexible port directions. Automatic preserves caller headings when initial paths are supplied. | | `infer_terminal_headings` | `False` | Let automatic or bundle mode choose headings for supported layouts with flexible port directions. Automatic preserves caller headings when initial paths are supplied. |
| `automatic_cost` | `"selective"` | Try a second column-planning pass based on route cost when the first pass chains short S-bends. Use `"always"` to try both passes or `"never"` to plan by span alone. | | `automatic_cost` | `"selective"` | Try a second column-planning pass based on route cost when the first pass chains short S-bends. Use `"always"` to try both passes or `"never"` to plan by span alone. |

View file

@ -88,6 +88,37 @@ For a multi-net layout, apply the validity check to every net you intend to expo
- **Give the router a route it can move.** Put `result.as_seed()` in `initial_paths` under the net's ID. A seed uses the current start port, width, and geometry settings. Search can follow a partial seed from the first iteration and can leave it to find another approach. To build a hint from turns and straights, see the [path seed reference](api-reference.md#path-seeds). - **Give the router a route it can move.** Put `result.as_seed()` in `initial_paths` under the net's ID. A seed uses the current start port, width, and geometry settings. Search can follow a partial seed from the first iteration and can leave it to find another approach. To build a hint from turns and straights, see the [path seed reference](api-reference.md#path-seeds).
- **Hold a route fixed.** Check `result.is_valid`, then add `result.locked_geometry` to `static_obstacles` while routing other nets. The next run applies its own clearance to those polygons. - **Hold a route fixed.** Check `result.is_valid`, then add `result.locked_geometry` to `static_obstacles` while routing other nets. The next run applies its own clearance to those polygons.
When terminal headings are inferred, store the two selected ports alongside the seed, width, and geometry options. Use those exact ports to replay the route and export the same polygons.
```python
from dataclasses import replace
from inire import RefinementOptions, TopologyOptions, route
chosen = route(problem, options=options)
verified_nets = []
seeds = {}
for net in problem.nets:
result = chosen.results_by_net[net.net_id]
if result.is_valid:
verified_nets.append(replace(net, start=result.path[0].start_port, target=result.path[-1].end_port))
seeds[net.net_id] = result.as_seed()
replay = route(
replace(problem, nets=tuple(verified_nets), initial_paths=seeds),
options=replace(
options,
search=replace(options.search, node_limit=0),
topology=TopologyOptions(mode="off"),
refinement=RefinementOptions(enabled=False),
),
)
for net in verified_nets:
result = replay.results_by_net[net.net_id]
assert result.is_valid
assert result.locked_geometry == chosen.results_by_net[net.net_id].locked_geometry
```
Route a straight net, then use its polygons as keepouts in a second routing problem. The second net has to detour around one end of the fixed route. Route a straight net, then use its polygons as keepouts in a second routing problem. The second net has to detour around one end of the fixed route.
```python ```python

View file

@ -47,14 +47,25 @@ def route(
iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None = None, iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None = None,
) -> RoutingRunResult: ) -> RoutingRunResult:
resolved_options = RoutingOptions() if options is None else options resolved_options = RoutingOptions() if options is None else options
for net in problem.nets:
if net.start == net.target:
raise ValueError(f"Net {net.net_id!r} has coincident ports after grid snapping; connect the placed ports directly")
if problem.initial_paths:
net_ids = {net.net_id for net in problem.nets}
for net_id, seed in problem.initial_paths.items():
if net_id not in net_ids:
raise ValueError(f"Initial path provided for unknown net: {net_id}")
error = resolved_options.search.seed_geometry_error(seed)
if error is not None:
raise ValueError(f"Initial path for {net_id!r} {error}")
if resolved_options.topology.mode == "automatic": if resolved_options.topology.mode == "automatic":
from .router._automatic import route_automatic # noqa: PLC0415 from .router._automatic import route_automatic # noqa: PLC0415
return route_automatic(problem, resolved_options, iteration_callback) return route_automatic(problem, resolved_options, iteration_callback)
from .router._stack import route_once # noqa: PLC0415 from .router._stack import route_explicit # noqa: PLC0415
return route_once(problem, options=resolved_options, iteration_callback=iteration_callback) return route_explicit(problem, options=resolved_options, iteration_callback=iteration_callback)
__all__ = [ __all__ = [
"AutomaticRoutingReport", "AutomaticRoutingReport",

View file

@ -180,6 +180,30 @@ class RoutingWorld:
def _ensure_static_raw_tree(self) -> None: def _ensure_static_raw_tree(self) -> None:
self._static_obstacles.ensure_raw_tree() self._static_obstacles.ensure_raw_tree()
def terminal_issue(self, port: Port, width: float) -> str | None:
dx, dy = rotate_cardinal(0, width / 2, int(port.r))
bounds = (port.x - abs(dx), port.y - abs(dy), port.x + abs(dx), port.y + abs(dy))
if self.board is not None:
x0, y0, x1, y1 = self.board.bounds
if bounds[0] < x0 or bounds[1] < y0 or bounds[2] > x1 or bounds[3] > y1:
return "face extends outside the routing board"
self._ensure_static_raw_tree()
tree = self._static_obstacles.raw_tree
if tree is None:
return None
clearance = self.clearance
candidates = tree.query(box(bounds[0] - clearance, bounds[1] - clearance, bounds[2] + clearance, bounds[3] + clearance))
if not len(candidates):
return None
face = LineString(((port.x - dx, port.y - dy), (port.x + dx, port.y + dy)))
for index in candidates:
keepout = tree.geometries[index]
if (clearance or id(keepout) in self._reserved_geometry_ids) and _violates_net_clearance(face, keepout, clearance):
return "face violates keepout clearance"
if not clearance and not face.relate_pattern(keepout, "F**F*****"):
return "face enters a keepout"
return None
def add_path( def add_path(
self, self,
net_id: str, net_id: str,

View file

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

View file

@ -28,6 +28,7 @@ class RoutingReport:
discontinuous: bool = False discontinuous: bool = False
invalid_geometry: bool = False invalid_geometry: bool = False
seed_error: str | None = None seed_error: str | None = None
terminal_error: str | None = None
@property @property
def intrinsic_collision_count(self) -> int: def intrinsic_collision_count(self) -> int:
@ -272,7 +273,7 @@ class RoutingResult:
return "unroutable" return "unroutable"
if not self.reached_target: if not self.reached_target:
return "partial" return "partial"
if self.report.collision_count > 0: if self.report.collision_count > 0 or self.report.terminal_error is not None:
return "colliding" return "colliding"
return "completed" return "completed"

View file

@ -159,7 +159,7 @@ def expand_moves(
metrics: AStarMetrics, metrics: AStarMetrics,
congestion: CongestionCaches, congestion: CongestionCaches,
config: SearchRunConfig, config: SearchRunConfig,
deferred_turns: list[tuple[AStarNode, float, BendDirection]], deferred_turns: list[tuple[AStarNode, float, BendDirection]] | None,
) -> None: ) -> None:
search_options = context.options.search search_options = context.options.search
scan_limit = search_options.max_straight_length scan_limit = search_options.max_straight_length
@ -221,7 +221,7 @@ def expand_moves(
net_width=net_width, net_width=net_width,
caller="expand_forward", caller="expand_forward",
) )
if current.parent is None and max_reach < max(1, math.ceil(search_options.min_straight_length)): if (previous is None or previous.move_type != "straight") and max_reach < max(1, math.ceil(search_options.min_straight_length)):
# Radius around the ray can block a launch at an otherwise clear port face. # Radius around the ray can block a launch at an otherwise clear port face.
reach = collision.straight_reach(cp, scan_limit, net_width) reach = collision.straight_reach(cp, scan_limit, net_width)
max_reach = max(max_reach, math.floor(reach + TOLERANCE_LINEAR)) max_reach = max(max_reach, math.floor(reach + TOLERANCE_LINEAR))
@ -257,6 +257,8 @@ def expand_moves(
if sbend_span is None: if sbend_span is None:
continue continue
candidate_lengths.extend((dx_local - sbend_span, dx_local - 2.0 * sbend_span)) candidate_lengths.extend((dx_local - sbend_span, dx_local - 2.0 * sbend_span))
if not bend_spans:
candidate_lengths.append(max_reach - sbend_span)
guide_offsets: set[int] = set() guide_offsets: set[int] = set()
if config.corridor is not None: if config.corridor is not None:
@ -299,13 +301,13 @@ def expand_moves(
angle_to_target = 0.0 angle_to_target = 0.0
if dx_t != 0 or dy_t != 0: if dx_t != 0 or dy_t != 0:
angle_to_target = float((round((180.0 / math.pi) * math.atan2(dy_t, dx_t)) + 360.0) % 360.0) angle_to_target = float((round((180.0 / math.pi) * math.atan2(dy_t, dx_t)) + 360.0) % 360.0)
prefer_toward_target = not config.restrict_to_corridor and dist_sq >= 150 * 150 prefer_toward_target = deferred_turns is not None and not config.restrict_to_corridor and dist_sq >= 150 * 150
for radius in search_options.bend_radii: for radius in search_options.bend_radii:
if not bend_fits_width(radius, net_width): if not bend_fits_width(radius, net_width):
continue continue
for direction in ("CW", "CCW"): for direction in ("CW", "CCW"):
if prefer_toward_target: if prefer_toward_target and deferred_turns is not None:
heading = (cp.r + (90 if direction == "CCW" else -90)) % 360 heading = (cp.r + (90 if direction == "CCW" else -90)) % 360
difference = (angle_to_target - heading + 180.0) % 360.0 - 180.0 difference = (angle_to_target - heading + 180.0) % 360.0 - 180.0
if abs(difference) > 135.0: if abs(difference) > 135.0:
@ -334,8 +336,30 @@ def expand_moves(
offsets = set(explicit_offsets) if explicit_offsets is not None else guide_offsets offsets = set(explicit_offsets) if explicit_offsets is not None else guide_offsets
if search_options.sbend_outlines: if search_options.sbend_outlines:
offsets.update(outline.offset for outline in search_options.sbend_outlines_for_width(net_width)) offsets.update(outline.offset for outline in search_options.sbend_outlines_for_width(net_width))
if explicit_offsets is None and target.r == cp.r and 0 < dx_local <= 4 * max_sbend_r and 0 < abs(dy_local) < 2 * max_sbend_r: if explicit_offsets is None and target.r == cp.r and dx_local > 0 and dy_local:
if dx_local <= 4 * max_sbend_r and abs(dy_local) < 2 * max_sbend_r:
offsets.add(round(dy_local)) offsets.add(round(dy_local))
elif abs(dy_local) >= 2 * max_sbend_r:
for radius in search_options.sbend_radii:
max_offset = math.ceil(2 * radius) - 1
if max_offset <= 0 or not bend_fits_width(radius, net_width):
continue
count = math.ceil(abs(dy_local) / max_offset)
if count <= 4:
offset = round(dy_local / count)
span = _sbend_forward_span(offset, radius)
if span is not None and span * count <= dx_local + count - 1:
offsets.add(offset)
elif explicit_offsets is None and dx_local > 0 and (target.r - cp.r) % 180 == 90:
# Position just before the final quarter turn, including its two tangent spans.
turn = 1 if (target.r - cp.r) % 360 == 90 else -1
for span in bend_spans:
offset = round(dy_local - turn * span)
for radius in search_options.sbend_radii:
forward = _sbend_forward_span(offset, radius)
if forward is not None and forward <= dx_local - span:
offsets.add(offset)
break
for offset in sorted(offsets): for offset in sorted(offsets):
if offset == 0: if offset == 0:

View file

@ -9,6 +9,8 @@ from inire.results import RouteMetrics
from inire.router.visibility import VisibilityManager from inire.router.visibility import VisibilityManager
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Callable
from inire.geometry.components import BendCollisionModel, BendPhysicalGeometry, ComponentResult from inire.geometry.components import BendCollisionModel, BendPhysicalGeometry, ComponentResult
from inire.geometry.primitives import Port from inire.geometry.primitives import Port
from inire.model import RoutingOptions, RoutingProblem from inire.model import RoutingOptions, RoutingProblem
@ -95,6 +97,7 @@ class SearchRunConfig:
restrict_to_corridor: bool = False restrict_to_corridor: bool = False
hard_congestion: bool = False hard_congestion: bool = False
propose_guidance_moves: bool = False propose_guidance_moves: bool = False
expired: Callable[[], bool] | None = field(default=None, repr=False, compare=False)
def estimate_remaining_cost(self, current: Port, target: Port, context: AStarContext) -> float: def estimate_remaining_cost(self, current: Port, target: Port, context: AStarContext) -> float:
evaluator = context.cost_evaluator evaluator = context.cost_evaluator
@ -124,6 +127,7 @@ class SearchRunConfig:
restrict_to_corridor: bool = False, restrict_to_corridor: bool = False,
hard_congestion: bool = False, hard_congestion: bool = False,
propose_guidance_moves: bool = False, propose_guidance_moves: bool = False,
expired: Callable[[], bool] | None = None,
) -> SearchRunConfig: ) -> SearchRunConfig:
search = options.search search = options.search
bend_collision_type, bend_physical_geometry = resolve_bend_geometry( bend_collision_type, bend_physical_geometry = resolve_bend_geometry(
@ -148,6 +152,7 @@ class SearchRunConfig:
restrict_to_corridor=restrict_to_corridor, restrict_to_corridor=restrict_to_corridor,
hard_congestion=hard_congestion, hard_congestion=hard_congestion,
propose_guidance_moves=propose_guidance_moves, propose_guidance_moves=propose_guidance_moves,
expired=expired,
) )

View file

@ -84,6 +84,8 @@ class _AutomaticRun:
options: RoutingOptions, options: RoutingOptions,
iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None, iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None,
) -> None: ) -> None:
if any(not seed.segments for seed in problem.initial_paths.values()):
problem = replace(problem, initial_paths={net_id: seed for net_id, seed in problem.initial_paths.items() if seed.segments})
self.raw_problem = problem self.raw_problem = problem
self.problem = problem self.problem = problem
self.options = options self.options = options
@ -165,8 +167,16 @@ class _AutomaticRun:
net_id: result.as_seed() for net_id, result in trial.run.results_by_net.items() net_id: result.as_seed() for net_id, result in trial.run.results_by_net.items()
if result.path and (include_unresolved or net_id in trial.valid_costs) if result.path and (include_unresolved or net_id in trial.valid_costs)
} }
nets = tuple(net for net in self.problem.nets if net.net_id in seeds) nets = []
return replace(self.problem, nets=nets, initial_paths=seeds) for net in self.problem.nets:
if net.net_id not in seeds:
continue
result = trial.run.results_by_net[net.net_id]
nets.append(replace(
net, start=result.path[0].start_port,
target=result.path[-1].end_port if result.reached_target else net.target,
))
return replace(self.problem, nets=tuple(nets), initial_paths=seeds)
def _seeded_attempt( def _seeded_attempt(
self, self,
@ -182,6 +192,7 @@ class _AutomaticRun:
refinement = options.refinement refinement = options.refinement
if operation == "verify": if operation == "verify":
refinement = replace(refinement, enabled=False) refinement = replace(refinement, enabled=False)
node_limit = 0
worker = replace( worker = replace(
options, options,
search=replace(options.search, node_limit=node_limit), search=replace(options.search, node_limit=node_limit),
@ -202,29 +213,48 @@ class _AutomaticRun:
) )
return run, stage return run, stage
def _verify(self, problem: RoutingProblem, planner: str, *, kind: str | None = None, policy: str | None = None) -> Trial: def _verify(
run, stage = self._seeded_attempt(problem, planner, kind=kind or planner, policy=policy, operation="verify") self, problem: RoutingProblem, planner: str, *,
kind: str | None = None, policy: str | None = None, preserve_hints: bool = False,
) -> Trial:
def verify(candidate: RoutingProblem) -> Trial:
run, stage = self._seeded_attempt(candidate, planner, kind=kind or planner, policy=policy, operation="verify")
return self._trial(run, stage) return self._trial(run, stage)
if preserve_hints and self.problem.initial_paths:
active_ids = {net.net_id for net in problem.nets}
hints = {net_id: seed for net_id, seed in self.problem.initial_paths.items() if net_id in active_ids}
merged = {**problem.initial_paths, **hints}
if merged != problem.initial_paths:
incumbent = verify(replace(problem, initial_paths=merged))
if len(incumbent.valid_costs) == len(problem.nets):
return incumbent
candidate = verify(problem)
return candidate if candidate.improves_on(incumbent) else incumbent
return verify(problem)
def _constructive_trials(self) -> tuple[list[Trial], tuple[str, ...]]: def _constructive_trials(self) -> tuple[list[Trial], tuple[str, ...]]:
problem, options = self.problem, self.options options = self.options
problem = replace(self.problem, initial_paths={}) if self.problem.initial_paths else self.problem
verify = partial(self._verify, preserve_hints=True)
trials: list[Trial] = [] trials: list[Trial] = []
rejections = [] rejections = []
try: try:
with self._time("plan", planner="bundle"): with self._time("plan", planner="bundle"):
bundle = plan_ordered_bundle(self.raw_problem, options.search, infer_terminal_headings=True) raw = replace(self.raw_problem, initial_paths={}) if self.raw_problem.initial_paths else self.raw_problem
bundle = plan_ordered_bundle(raw, options.search, infer_terminal_headings=True)
except ValueError as exc: except ValueError as exc:
rejections.append(str(exc)) rejections.append(str(exc))
else: else:
if bundle.nets == problem.nets: if bundle.nets == problem.nets:
trials.append(self._verify(bundle, "bundle")) trials.append(verify(bundle, "bundle"))
if len(trials[-1].valid_costs) == len(problem.nets): if len(trials[-1].valid_costs) == len(problem.nets):
return trials, () return trials, ()
rejections.append("Bundle candidate failed geometric verification") rejections.append("Bundle candidate failed geometric verification")
elif not options.topology.infer_terminal_headings: elif not options.topology.infer_terminal_headings:
with self._time("plan", planner="bundle-turnaround"): with self._time("plan", planner="bundle-turnaround"):
for candidate in bundle_turnaround_candidates(problem, bundle, options.search): for candidate in bundle_turnaround_candidates(problem, bundle, options.search):
trials.append(self._verify(candidate, "bundle-turnaround")) trials.append(verify(candidate, "bundle-turnaround"))
if len(trials[-1].valid_costs) == len(problem.nets): if len(trials[-1].valid_costs) == len(problem.nets):
return trials, () return trials, ()
rejections.append("No geometrically verified turnaround matched the terminal headings") rejections.append("No geometrically verified turnaround matched the terminal headings")
@ -232,40 +262,40 @@ class _AutomaticRun:
with self._time("plan", planner="compact-port-jogs"): with self._time("plan", planner="compact-port-jogs"):
compact = compact_port_seed_set(problem, options.search) compact = compact_port_seed_set(problem, options.search)
if compact is not None: if compact is not None:
trials.append(self._verify(replace(problem, initial_paths=compact), "compact-port-jogs")) trials.append(verify(replace(problem, initial_paths=compact), "compact-port-jogs"))
if len(trials[-1].valid_costs) == len(problem.nets): if len(trials[-1].valid_costs) == len(problem.nets):
return trials, tuple(rejections) return trials, tuple(rejections)
span_trial = self._column_trial(False, trials) span_trial = self._column_trial(False, trials, problem=problem)
if span_trial is None: if span_trial is None:
rejections.append("Span scoring found no verified column layout") rejections.append("Span scoring found no verified column layout")
policy = options.topology.automatic_cost policy = options.topology.automatic_cost
if policy == "always" or (policy == "selective" and span_trial is not None and _has_fragmented_shifts(span_trial)): if policy == "always" or (policy == "selective" and span_trial is not None and _has_fragmented_shifts(span_trial)):
self.cost_pass_performed = True self.cost_pass_performed = True
if self._column_trial(True, trials) is None: if self._column_trial(True, trials, problem=problem) is None:
rejections.append("Cost scoring found no verified column layout") rejections.append("Cost scoring found no verified column layout")
if not trials or len(_best_trial(trials).valid_costs) < len(problem.nets): if not trials or len(_best_trial(trials).valid_costs) < len(problem.nets):
planner = "local-sbend" planner = "local-sbend"
with self._time("plan", planner=planner): with self._time("plan", planner=planner):
shifts = short_shift_seed_set(problem, options.search, self._selection_cost) shifts = short_shift_seed_set(problem, options.search, self._selection_cost)
if shifts is not None: if shifts is not None:
trial = self._verify(replace(problem, initial_paths=shifts), planner) trial = verify(replace(problem, initial_paths=shifts), planner)
complete = len(trial.valid_costs) == len(problem.nets) complete = len(trial.valid_costs) == len(problem.nets)
trials.append(trial if complete else replace(trial, selection="incomplete-layout")) trials.append(trial if complete else replace(trial, selection="incomplete-layout"))
if not complete: if not complete:
rejections.append("Local S-bend layout failed full verification") rejections.append("Local S-bend layout failed full verification")
return trials, tuple(rejections) return trials, tuple(rejections)
def _column_trial(self, weighted: bool, trials: list[Trial]) -> Trial | None: def _column_trial(self, weighted: bool, trials: list[Trial], *, problem: RoutingProblem) -> Trial | None:
objective = self.options.objective objective = self.options.objective
weights = self.length_weights or dict.fromkeys(("straight", "bend90", "sbend"), objective.unit_length_cost) weights = self.length_weights or dict.fromkeys(("straight", "bend90", "sbend"), objective.unit_length_cost)
penalty = 0.0 if self.length_weights is not None else objective.sbend_penalty penalty = 0.0 if self.length_weights is not None else objective.sbend_penalty
policy = "weighted" if weighted else "span" policy = "weighted" if weighted else "span"
kind = "column-cost" if weighted else "column-span" kind = "column-cost" if weighted else "column-span"
with self._time("plan", planner="column", policy=policy): with self._time("plan", planner="column", policy=policy):
candidates = column_seed_candidates(self.problem, self.options.search, weights, weighted=weighted, sbend_penalty=penalty) candidates = column_seed_candidates(problem, self.options.search, weights, weighted=weighted, sbend_penalty=penalty)
for seeds in islice(candidates, 8): for seeds in islice(candidates, 8):
trial = self._verify(replace(self.problem, initial_paths=seeds), "column", kind=kind, policy=policy) trial = self._verify(replace(problem, initial_paths=seeds), "column", kind=kind, policy=policy, preserve_hints=True)
trials.append(trial) trials.append(trial)
if len(trial.valid_costs) == len(self.problem.nets): if len(trial.valid_costs) == len(self.problem.nets):
return trial return trial

View file

@ -14,7 +14,7 @@ from inire.router.cost import CostEvaluator
from inire.router.danger_map import DangerMap from inire.router.danger_map import DangerMap
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Mapping, Set from collections.abc import Callable, Mapping, Set
from inire.model import NetSpec from inire.model import NetSpec
@ -75,6 +75,7 @@ def search_pair_candidate(
pair_order: tuple[str, str], pair_order: tuple[str, str],
*, *,
needs_self_collision_check: Set[str], needs_self_collision_check: Set[str],
expired: Callable[[], bool] | None = None,
) -> tuple[dict[str, RoutingResult], int] | None: ) -> tuple[dict[str, RoutingResult], int] | None:
"""Return both locally verified replacements and their search work.""" """Return both locally verified replacements and their search work."""
local = _build_pair_local_context(context, ordered_nets, incumbent_results, pair_order) local = _build_pair_local_context(context, ordered_nets, incumbent_results, pair_order)
@ -93,6 +94,7 @@ def search_pair_candidate(
guidance_seed=guidance_seed, guidance_seed=guidance_seed,
guidance_bonus=guidance_bonus, guidance_bonus=guidance_bonus,
node_limit=options.search.node_limit, node_limit=options.search.node_limit,
expired=expired,
) )
path = route_astar( path = route_astar(
net.start, net.start,

View file

@ -4,6 +4,7 @@ import random
import time import time
from contextlib import contextmanager, nullcontext from contextlib import contextmanager, nullcontext
from dataclasses import dataclass, field, replace from dataclasses import dataclass, field, replace
from functools import partial
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from shapely import shortest_line from shapely import shortest_line
@ -71,6 +72,8 @@ class _RoutingState:
pre_pair_candidate: _PrePairCandidate | None pre_pair_candidate: _PrePairCandidate | None
corridors: dict[str, tuple[Corridor, ...]] = field(default_factory=dict) corridors: dict[str, tuple[Corridor, ...]] = field(default_factory=dict)
seed_errors: dict[str, str] = field(default_factory=dict) seed_errors: dict[str, str] = field(default_factory=dict)
terminal_errors: dict[str, str] = field(default_factory=dict)
timed_out: bool = False
@property @property
def best_conflict_edges(self) -> int | None: def best_conflict_edges(self) -> int | None:
@ -179,8 +182,19 @@ class PathFinder:
greedy_paths: dict[str, tuple[ComponentResult, ...]] = {} greedy_paths: dict[str, tuple[ComponentResult, ...]] = {}
greedy_node_limit = min(self.context.options.search.node_limit, 2000) greedy_node_limit = min(self.context.options.search.node_limit, 2000)
world = self.context.cost_evaluator.collision_engine world = self.context.cost_evaluator.collision_engine
existing = state.initial_paths or {}
expired = partial(self._expired, state)
with self._temporary_path_reservations() as reserve: with self._temporary_path_reservations() as reserve:
for net_id, path in existing.items():
if path[-1].end_port == state.net_specs[net_id].target and world.verify_path_report(net_id, path).is_valid:
reserve(path)
if existing:
self.context.clear_static_caches()
for net_id in state.ordered_net_ids: for net_id in state.ordered_net_ids:
if expired():
break
if net_id in existing or net_id in state.terminal_errors:
continue
net = state.net_specs[net_id] net = state.net_specs[net_id]
h_start = self.context.cost_evaluator.h_manhattan( h_start = self.context.cost_evaluator.h_manhattan(
net.start, net.start,
@ -197,6 +211,7 @@ class PathFinder:
node_limit=greedy_node_limit, node_limit=greedy_node_limit,
corridor=candidates[0] if candidates else None, corridor=candidates[0] if candidates else None,
corridor_strength=self.context.options.topology.guide_strength, corridor_strength=self.context.options.topology.guide_strength,
expired=expired,
) )
path = route_astar( path = route_astar(
net.start, net.start,
@ -220,12 +235,17 @@ class PathFinder:
world = self.context.cost_evaluator.collision_engine world = self.context.cost_evaluator.collision_engine
existing = state.initial_paths or {} existing = state.initial_paths or {}
seeds: dict[str, tuple[ComponentResult, ...]] = {} seeds: dict[str, tuple[ComponentResult, ...]] = {}
preserved = set()
expired = partial(self._expired, state)
with self._temporary_path_reservations() as reserve: with self._temporary_path_reservations() as reserve:
for net_id, path in existing.items(): for net_id, path in existing.items():
if path and path[-1].end_port == state.net_specs[net_id].target and world.verify_path_report(net_id, path).is_valid: if path and path[-1].end_port == state.net_specs[net_id].target and world.verify_path_report(net_id, path).is_valid:
reserve(path) reserve(path)
preserved.add(net_id)
for net_id in state.ordered_net_ids: for net_id in state.ordered_net_ids:
if net_id in existing: if expired():
break
if net_id in preserved or net_id in state.terminal_errors:
continue continue
net = state.net_specs[net_id] net = state.net_specs[net_id]
candidates = state.corridors.get(net_id, ()) candidates = state.corridors.get(net_id, ())
@ -244,6 +264,7 @@ class PathFinder:
self_collision_check=True, self_collision_check=True,
corridor=corridor, corridor=corridor,
restrict_to_corridor=True, restrict_to_corridor=True,
expired=expired,
) )
path = route_astar(net.start, net.target, net.width, self.context, metrics=self.metrics, net_id=net_id, config=config) path = route_astar(net.start, net.target, net.width, self.context, metrics=self.metrics, net_id=net_id, config=config)
remaining -= self.metrics.nodes_expanded remaining -= self.metrics.nodes_expanded
@ -271,7 +292,7 @@ class PathFinder:
corridors = plan_corridors( corridors = plan_corridors(
self.context.problem.bounds, self.context.problem.bounds,
world.iter_static_geometries(), world.iter_static_geometries(),
[state.net_specs[net_id] for net_id in state.ordered_net_ids], [state.net_specs[net_id] for net_id in state.ordered_net_ids if net_id not in state.terminal_errors],
clearance=world.clearance, clearance=world.clearance,
bend_radius=min(self.context.options.search.bend_radii, default=0.0), bend_radius=min(self.context.options.search.bend_radii, default=0.0),
limit=topology.max_corridors, limit=topology.max_corridors,
@ -310,11 +331,25 @@ class PathFinder:
pre_pair_candidate=None, pre_pair_candidate=None,
) )
self._materialize_problem_initial_paths(state) self._materialize_problem_initial_paths(state)
if congestion.max_iterations:
world = self.context.cost_evaluator.collision_engine
for net_id, net in net_specs.items():
for name, port in (("start", net.start), ("target", net.target)):
issue = world.terminal_issue(port, net.width)
if issue is not None:
state.terminal_errors[net_id] = f"{name} port {port.as_tuple()} {issue}"
break
if congestion.max_iterations <= 0 or (self.context.options.search.node_limit <= 0 and self.context.options.topology.mode != "bundle"): if congestion.max_iterations <= 0 or (self.context.options.search.node_limit <= 0 and self.context.options.topology.mode != "bundle"):
return state return state
if self._expired(state):
return state
self._prepare_topology(state, corridors) self._prepare_topology(state, corridors)
if state.initial_paths is None and congestion.warm_start_enabled: if self._expired(state):
state.initial_paths = self._build_greedy_warm_start_paths(state) return state
if congestion.warm_start_enabled and len(state.initial_paths or ()) < len(net_specs):
greedy = self._build_greedy_warm_start_paths(state)
if greedy:
state.initial_paths = {**(state.initial_paths or {}), **greedy}
if state.corridors and state.initial_paths: if state.corridors and state.initial_paths:
world = self.context.cost_evaluator.collision_engine world = self.context.cost_evaluator.collision_engine
for net_id, path in state.initial_paths.items(): for net_id, path in state.initial_paths.items():
@ -326,6 +361,12 @@ class PathFinder:
state.results[net_id] = RoutingResult(net_id, path, reached_target=True, report=report) state.results[net_id] = RoutingResult(net_id, path, reached_target=True, report=report)
return state return state
def _expired(self, state: _RoutingState) -> bool:
if not state.timed_out and time.monotonic() - state.start_time >= state.timeout_s:
state.timed_out = True
self.metrics.total_timeout_events += 1
return state.timed_out
def _materialize_problem_initial_paths(self, state: _RoutingState) -> None: def _materialize_problem_initial_paths(self, state: _RoutingState) -> None:
if not self.context.problem.initial_paths: if not self.context.problem.initial_paths:
return return
@ -788,6 +829,8 @@ class PathFinder:
ordered_nets = tuple(state.net_specs[net_id] for net_id in state.ordered_net_ids) ordered_nets = tuple(state.net_specs[net_id] for net_id in state.ordered_net_ids)
self.metrics.total_pair_local_search_pairs_considered += 1 self.metrics.total_pair_local_search_pairs_considered += 1
for pair_order in (target, (target[1], target[0])): for pair_order in (target, (target[1], target[0])):
if self._expired(state):
break
self.metrics.total_pair_local_search_attempts += 1 self.metrics.total_pair_local_search_attempts += 1
candidate = search_pair_candidate( candidate = search_pair_candidate(
self.context, self.context,
@ -795,6 +838,7 @@ class PathFinder:
incumbent_results, incumbent_results,
pair_order, pair_order,
needs_self_collision_check=state.needs_self_collision_check, needs_self_collision_check=state.needs_self_collision_check,
expired=partial(self._expired, state),
) )
if candidate is None: if candidate is None:
continue continue
@ -817,8 +861,11 @@ class PathFinder:
if not targets: if not targets:
return return
initial_edges = len(review.conflict_edges)
for target in targets[:2]: for target in targets[:2]:
review = self._run_pair_local_target(state, target, review) review = self._run_pair_local_target(state, target, review)
if len(targets) > 2 and len(review.conflict_edges) == initial_edges - 2:
self._run_pair_local_target(state, targets[2], review)
def _route_net_once( def _route_net_once(
self, self,
@ -841,9 +888,20 @@ class PathFinder:
initial_path = state.initial_paths.get(net_id) if state.initial_paths else None initial_path = state.initial_paths.get(net_id) if state.initial_paths else None
initial_arrives = bool(initial_path and initial_path[-1].end_port == net.target) initial_arrives = bool(initial_path and initial_path[-1].end_port == net.target)
if iteration == 0 and initial_path is not None and (initial_arrives or search.node_limit <= 0): seed_intrinsic_ok = (
self.metrics.total_warm_start_paths_used += 1 initial_arrives and initial_path is not None
and (
not search.node_limit or self.context.options.topology.mode == "off"
or not self.context.cost_evaluator.collision_engine.verify_path_details(
net_id, initial_path, include_invalid_dynamic=False,
).report.intrinsic_collision_count
)
) if iteration == 0 else False
if net_id in state.terminal_errors:
path: Sequence[ComponentResult] | None = initial_path path: Sequence[ComponentResult] | None = initial_path
elif iteration == 0 and initial_path is not None and (seed_intrinsic_ok or search.node_limit <= 0):
self.metrics.total_warm_start_paths_used += 1
path = initial_path
elif search.node_limit == 0: elif search.node_limit == 0:
path = None path = None
else: else:
@ -883,6 +941,7 @@ class PathFinder:
corridor=corridors[iteration] if iteration < len(corridors) else None, corridor=corridors[iteration] if iteration < len(corridors) else None,
corridor_strength=self.context.options.topology.guide_strength / (iteration + 1), corridor_strength=self.context.options.topology.guide_strength / (iteration + 1),
hard_congestion=bool(state.corridors) and iteration == 0, hard_congestion=bool(state.corridors) and iteration == 0,
expired=partial(self._expired, state),
) )
path = route_astar( path = route_astar(
net.start, net.start,
@ -896,7 +955,10 @@ class PathFinder:
if diagnostics.capture_expanded and self.metrics.last_expanded_nodes: if diagnostics.capture_expanded and self.metrics.last_expanded_nodes:
state.accumulated_expanded_nodes.extend(self.metrics.last_expanded_nodes) state.accumulated_expanded_nodes.extend(self.metrics.last_expanded_nodes)
if not path and use_prefix: if (
(initial_arrives and iteration == 0 and (not path or path[-1].end_port != net.target))
or (not path and use_prefix)
):
path = initial_path path = initial_path
if not path: if not path:
@ -958,9 +1020,8 @@ class PathFinder:
iteration_before = self._capture_metric_totals(_ITERATION_TRACE_TOTALS) iteration_before = self._capture_metric_totals(_ITERATION_TRACE_TOTALS)
for net_id in routed_net_ids: for net_id in routed_net_ids:
if time.monotonic() - state.start_time > state.timeout_s: if self._expired(state):
self.metrics.total_timeout_events += 1 break
return None
work_before = self.metrics.total_nodes_expanded + self.metrics.total_congestion_check_calls work_before = self.metrics.total_nodes_expanded + self.metrics.total_congestion_check_calls
if capture_attempts: if capture_attempts:
@ -987,6 +1048,8 @@ class PathFinder:
net_attempt_trace(net_id, deltas, reached_target=result.reached_target, guidance_seed_present=guidance_seed_present) net_attempt_trace(net_id, deltas, reached_target=result.reached_target, guidance_seed_present=guidance_seed_present)
) )
if self._expired(state) and not state.results:
return None
state.recent_attempt_work = attempt_work state.recent_attempt_work = attempt_work
review = self._reverify_iteration_results(state) review = self._reverify_iteration_results(state)
if diagnostics.capture_pre_pair_frontier_trace: if diagnostics.capture_pre_pair_frontier_trace:
@ -1005,7 +1068,7 @@ class PathFinder:
iteration_trace_entry(iteration, iteration_penalty, routed_net_ids, review, deltas, attempt_traces) iteration_trace_entry(iteration, iteration_penalty, routed_net_ids, review, deltas, attempt_traces)
) )
if iteration_callback: if iteration_callback and not state.timed_out:
iteration_callback(iteration, dict(state.results)) iteration_callback(iteration, dict(state.results))
return review return review
@ -1045,6 +1108,8 @@ class PathFinder:
return True return True
improved = self._update_best_iteration(state, review) improved = self._update_best_iteration(state, review)
state.best_is_installed = improved state.best_is_installed = improved
if state.timed_out:
return True
if not any( if not any(
result.outcome in {"colliding", "partial", "unroutable"} result.outcome in {"colliding", "partial", "unroutable"}
for result in state.results.values() for result in state.results.values()
@ -1073,6 +1138,8 @@ class PathFinder:
proximity_ready = bool(options.search.node_limit) proximity_ready = bool(options.search.node_limit)
for net_id in state.ordered_net_ids: for net_id in state.ordered_net_ids:
if self._expired(state):
break
result = state.results.get(net_id) result = state.results.get(net_id)
if not result or not result.is_valid or not self.refiner.has_refinement_bends(result.path): if not result or not result.is_valid or not self.refiner.has_refinement_bends(result.path):
continue continue
@ -1103,10 +1170,11 @@ class PathFinder:
for net in self.context.problem.nets: for net in self.context.problem.nets:
result = state.results.get(net.net_id) result = state.results.get(net.net_id)
seed_error = state.seed_errors.get(net.net_id) if self.context.options.congestion.max_iterations else None seed_error = state.seed_errors.get(net.net_id) if self.context.options.congestion.max_iterations else None
terminal_error = state.terminal_errors.get(net.net_id)
if not result or not result.path: if not result or not result.path:
final_results[net.net_id] = RoutingResult( final_results[net.net_id] = RoutingResult(
net_id=net.net_id, path=(), reached_target=False, net_id=net.net_id, path=(), reached_target=False,
report=RoutingReport(invalid_geometry=seed_error is not None, seed_error=seed_error), report=RoutingReport(invalid_geometry=seed_error is not None, seed_error=seed_error, terminal_error=terminal_error),
) )
continue continue
capture_conflicts = diagnostics.capture_conflict_trace or (diagnostics.capture_frontier_trace and result.reached_target) capture_conflicts = diagnostics.capture_conflict_trace or (diagnostics.capture_frontier_trace and result.reached_target)
@ -1116,12 +1184,16 @@ class PathFinder:
capture_component_conflicts=capture_conflicts, capture_component_conflicts=capture_conflicts,
include_invalid_dynamic=False, include_invalid_dynamic=False,
) )
report = detail.report
if seed_error or terminal_error:
report = replace(report, seed_error=seed_error, terminal_error=terminal_error)
detail = replace(detail, report=report)
details_by_net[net.net_id] = detail details_by_net[net.net_id] = detail
final_results[net.net_id] = RoutingResult( final_results[net.net_id] = RoutingResult(
net_id=net.net_id, net_id=net.net_id,
path=result.path, path=result.path,
reached_target=result.reached_target, reached_target=result.reached_target,
report=detail.report if seed_error is None else replace(detail.report, seed_error=seed_error), report=report,
) )
if diagnostics.capture_conflict_trace: if diagnostics.capture_conflict_trace:
review = review_verified_results(final_results, details_by_net) review = review_verified_results(final_results, details_by_net)

View file

@ -15,6 +15,7 @@ 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
from inire.router._congestion_policy import ordered_nets from inire.router._congestion_policy import ordered_nets
from inire.router._seed_materialization import materialize_path_seed
from inire.router._stack import route_once from inire.router._stack import route_once
if TYPE_CHECKING: if TYPE_CHECKING:
@ -81,8 +82,6 @@ def _direct_paths(
*, *,
priority: frozenset[str] = frozenset(), priority: frozenset[str] = frozenset(),
) -> dict[str, RoutingResult]: ) -> dict[str, RoutingResult]:
if problem.initial_paths:
return {}
world = RoutingWorld(clearance=problem.clearance, safety_zone_radius=problem.safety_zone_radius, board=board) 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)
@ -92,6 +91,18 @@ def _direct_paths(
paths = {} paths = {}
for net in ordered: for net in ordered:
seed = problem.initial_paths.get(net.net_id)
if seed is None or options.search.seed_geometry_error(seed):
continue
path = materialize_path_seed(seed, start=net.start, net_width=net.width, search=options.search, clearance=problem.clearance)
if path and path[-1].end_port == net.target:
report = world.verify_path_report(net.net_id, path)
if report.is_valid:
paths[net.net_id] = RoutingResult(net.net_id, path, reached_target=True, report=report)
world.install_path(net.net_id, path)
for net in ordered:
if net.net_id in problem.initial_paths:
continue
forward, lateral = port_local_coordinates(net.start, net.target.x, net.target.y) forward, lateral = port_local_coordinates(net.start, net.target.x, net.target.y)
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
@ -192,8 +203,9 @@ def _residual_problem(problem: RoutingProblem, locks: LockPlan) -> RoutingProble
return problem 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) 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) locked = tuple(shape for result in locks.direct.values() for shape in result.locked_geometry)
initial_paths = {net.net_id: problem.initial_paths[net.net_id] for net in residual if net.net_id in problem.initial_paths}
return replace( return replace(
problem, nets=residual, static_obstacles=problem.static_obstacles + locked, problem, nets=residual, static_obstacles=problem.static_obstacles + locked, initial_paths=initial_paths,
_reserved_obstacles=problem._reserved_obstacles + locked, _reserved_obstacles=problem._reserved_obstacles + locked,
) )

View file

@ -76,13 +76,17 @@ def route_astar(
best_node = start_node best_node = start_node
best_distance = _distance_to_terminal(start, target) best_distance = _distance_to_terminal(start, target)
nodes_expanded = 0 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)
while open_set or deferred_turns: while open_set or deferred_turns:
if nodes_expanded >= config.node_limit: if nodes_expanded >= config.node_limit or (config.expired is not None and nodes_expanded % 32 == 0 and config.expired()):
return _reconstruct_path(best_node) if config.return_partial else None
if deferred_turns and (not open_set or nodes_expanded >= release_turns_at):
for index, (parent, radius, direction) in enumerate(deferred_turns):
if config.expired is not None and index % 32 == 0 and config.expired():
return _reconstruct_path(best_node) if config.return_partial else None return _reconstruct_path(best_node) if config.return_partial else None
if not open_set:
# Recover turns away from the target after exhausting the preferred frontier.
for parent, radius, direction in deferred_turns:
process_move( process_move(
parent, target, net_width, net_id, open_set, closed_set, context, metrics, congestion, config, "bend90", (radius, direction) parent, target, net_width, net_id, open_set, closed_set, context, metrics, congestion, config, "bend90", (radius, direction)
) )
@ -99,6 +103,8 @@ def route_astar(
state = current.port.as_tuple() state = current.port.as_tuple()
if state in closed_set and closed_set[state] <= current.g_cost + TOLERANCE_LINEAR: if state in closed_set and closed_set[state] <= current.g_cost + TOLERANCE_LINEAR:
continue continue
if current.port == target and config.expired is not None and config.expired():
return _reconstruct_path(best_node) if config.return_partial else None
closed_set[state] = current.g_cost closed_set[state] = current.g_cost
if config.return_partial: if config.return_partial:
distance = _distance_to_terminal(current.port, target) distance = _distance_to_terminal(current.port, target)
@ -126,7 +132,7 @@ def route_astar(
metrics, metrics,
congestion, congestion,
config=config, config=config,
deferred_turns=deferred_turns, deferred_turns=deferred_turns if nodes_expanded <= release_turns_at else None,
) )
return _reconstruct_path(best_node) if config.return_partial else None return _reconstruct_path(best_node) if config.return_partial else None

View file

@ -1,12 +1,12 @@
from __future__ import annotations from __future__ import annotations
from dataclasses import dataclass from dataclasses import dataclass, replace
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from shapely.geometry import box from shapely.geometry import box
from inire.geometry.collision import RoutingWorld from inire.geometry.collision import RoutingWorld
from inire.results import RoutingRunResult from inire.results import RoutingRunResult, _sum_route_metrics
from inire.router._astar_types import AStarContext from inire.router._astar_types import AStarContext
from inire.router._router import PathFinder from inire.router._router import PathFinder
from inire.router.cost import CostEvaluator from inire.router.cost import CostEvaluator
@ -103,3 +103,39 @@ def collect_worker_result(finder: PathFinder, results: dict[str, RoutingResult])
iteration_trace=tuple(finder.iteration_trace), iteration_trace=tuple(finder.iteration_trace),
topology=finder.topology_report, topology=finder.topology_report,
) )
def route_explicit(
problem: RoutingProblem,
*,
options: RoutingOptions,
iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None = None,
) -> RoutingRunResult:
start_index = 0
def notify(_iteration: int, results: dict[str, RoutingResult]) -> None:
nonlocal start_index
assert iteration_callback is not None
iteration_callback(start_index, results)
start_index += 1
callback = notify if iteration_callback is not None else None
with_guidance = route_once(problem, options=options, iteration_callback=callback)
topology = options.topology
if (
topology.mode not in ("guide", "seed") or not topology.guide_strength
or not options.search.node_limit or options.congestion.max_iterations < 2
or with_guidance.metrics.timeout_events or not with_guidance.topology or not with_guidance.topology.corridor_counts
or all(result.is_valid for result in with_guidance.results_by_net.values())
):
return with_guidance
retry = replace(
options, topology=replace(topology, guide_strength=0.0),
congestion=replace(options.congestion, max_iterations=1),
)
without_guidance = route_once(problem, options=retry, iteration_callback=callback)
old_count = sum(result.is_valid for result in with_guidance.results_by_net.values())
new_count = sum(result.is_valid for result in without_guidance.results_by_net.values())
chosen = without_guidance if new_count > old_count else with_guidance
return replace(chosen, metrics=_sum_route_metrics((with_guidance.metrics, without_guidance.metrics)))

View file

@ -11,7 +11,9 @@ from typing import TYPE_CHECKING
import shapely import shapely
from shapely.geometry import LineString, Point, box from shapely.geometry import LineString, Point, box
from inire.constants import TOLERANCE_LINEAR
from inire.geometry.collision import _violates_clearance from inire.geometry.collision import _violates_clearance
from inire.geometry.index_helpers import is_axis_aligned_rect
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Iterable, Sequence from collections.abc import Iterable, Sequence
@ -96,7 +98,7 @@ def constrained_triangulation_available() -> bool:
class _Mesh: class _Mesh:
def __init__(self, board: Polygon, obstacles: Iterable[Polygon], margin: float, clearance: float) -> None: def __init__(self, board: Polygon, obstacles: Iterable[Polygon], margin: float, clearance: float, *, relief: float = 0.0) -> None:
if not constrained_triangulation_available(): if not constrained_triangulation_available():
raise RuntimeError("Topological routing requires Shapely 2.1 and GEOS 3.10 or newer") raise RuntimeError("Topological routing requires Shapely 2.1 and GEOS 3.10 or newer")
@ -105,7 +107,11 @@ class _Mesh:
self.margin = margin self.margin = margin
self.clearance = clearance self.clearance = clearance
self.keepouts = shapely.STRtree(tuple(obstacles)) self.keepouts = shapely.STRtree(tuple(obstacles))
padded = shapely.union_all([shape.buffer(margin + clearance, join_style="mitre") for shape in self.keepouts.geometries]) 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")
for shape in self.keepouts.geometries
])
self.inset = board.buffer(-margin) self.inset = board.buffer(-margin)
self.free = self.inset.difference(padded) self.free = self.inset.difference(padded)
self.boundary = self.free.boundary self.boundary = self.free.boundary
@ -446,24 +452,41 @@ def plan_corridors(
board = box(*bounds) board = box(*bounds)
keepouts = tuple(obstacles) keepouts = tuple(obstacles)
def plan_group(group: Sequence[NetSpec], width: float) -> dict[str, tuple[Corridor, ...]]: 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) mesh = _Mesh(board, keepouts, width / 2, clearance, relief=relief)
endpoints, leads = _endpoint_access(mesh, group, bend_radius) endpoints, leads = _endpoint_access(mesh, group, bend_radius)
assignments = _plan_lane_assignments( assignments = _plan_lane_assignments(
mesh, group, endpoints, leads, bend_radius=bend_radius, limit=limit, joint_net_ids=joint_net_ids mesh, group, endpoints, leads, bend_radius=bend_radius, limit=limit, joint_net_ids=joint_net_ids
) )
return _build_corridors(mesh, board, group, assignments, bend_radius) return _build_corridors(mesh, board, group, assignments, bend_radius), mesh.free
widest = max(net.width for net in nets) widest = max(net.width for net in nets)
guides = plan_group(nets, widest) guides, shared_space = plan_group(nets, widest)
if joint_net_ids: if joint_net_ids:
return guides return guides
# Keep shared lane assignments and recover passages closed by the widest net's padding. # Keep shared assignments and add routes through passages opened by the narrower margin.
missing_by_width: dict[float, list[NetSpec]] = {} by_width: dict[float, list[NetSpec]] = {}
for net in nets: for net in nets:
if net.width < widest and net.net_id not in guides: by_width.setdefault(net.width, []).append(net)
missing_by_width.setdefault(net.width, []).append(net) for width, group in by_width.items():
for width, group in missing_by_width.items(): if width < widest:
guides.update(plan_group(group, width)) narrow, _ = plan_group(group, width)
for net_id, corridors in narrow.items():
if net_id not in guides:
guides[net_id] = corridors
continue
alternate = next(
(c for c in corridors if c.centerline.difference(shared_space).length > widest + 2 * clearance),
None,
)
if alternate is not None:
first, *rest = guides[net_id]
guides[net_id] = (first, alternate, *rest)[:limit]
missing = [net for net in group if net.net_id not in guides]
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)
guides.update(recovered)
return {net.net_id: guides[net.net_id] for net in nets if net.net_id in guides} return {net.net_id: guides[net.net_id] for net in nets if net.net_id in guides}

File diff suppressed because one or more lines are too long

View file

@ -8,6 +8,7 @@ from shapely.geometry import Polygon, box
import inire import inire
import inire.router._router as router_module import inire.router._router as router_module
import inire.router._search as search_module
from inire import ( from inire import (
Bend90Seed, Bend90Seed,
CongestionOptions, CongestionOptions,
@ -638,6 +639,58 @@ def test_partial_path_tracks_geometric_progress_without_cost_heuristic(heuristic
assert run.results_by_net["across"].outcome == "partial" assert run.results_by_net["across"].outcome == "partial"
@pytest.mark.parametrize("coordinates", [(30, 20), (30.4, 20.4), (101, 20)])
def test_coincident_ports_report_an_explicit_input_error(coordinates) -> None:
x, y = coordinates
net = NetSpec("abutting", Port(round(x), round(y), 0), Port(x, y, 0))
problem = RoutingProblem((0, 0, 100, 100), (net,))
with pytest.raises(ValueError, match="'abutting' has coincident ports"):
route(problem)
@pytest.mark.parametrize("mode", ["off", "automatic"])
@pytest.mark.parametrize(("target_x", "blocked", "message"), [
(302, False, "face extends outside the routing board"),
(280, True, "face violates keepout clearance"),
(300, False, None),
])
def test_invalid_terminal_faces_are_reported_without_search(mode, target_x, blocked, message) -> None:
nets = (
NetSpec("bad", Port(10, 80, 0), Port(target_x, 80, 0)),
NetSpec("peer", Port(10, 120, 0), Port(80, 120, 0)),
)
keepouts = (box(275, 75, 285, 85),) if blocked else ()
problem = RoutingProblem((0, 0, 300, 160), nets, keepouts)
options = RoutingOptions(
search=SearchOptions(node_limit=600, bend_radii=(20,)),
congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False),
refinement=RefinementOptions(enabled=False),
topology=TopologyOptions(mode=mode),
)
run = route(problem, options=options)
bad = run.results_by_net["bad"]
assert run.results_by_net["peer"].is_valid
assert bad.is_valid == (message is None)
assert run.metrics.nodes_expanded < 10
if message is None:
assert bad.report.terminal_error is None
else:
assert bad.report.terminal_error == f"target port {(target_x, 80, 0)} {message}"
def test_keepout_clearance_at_face_and_opposite_coincident_headings() -> None:
net = NetSpec("return", Port(50, 50, 0), Port(50, 50, 180))
problem = RoutingProblem((0, 0, 100, 100), (net,), (box(30, 53, 70, 60),))
options = RoutingOptions(search=SearchOptions(node_limit=0), topology=TopologyOptions(mode="off"))
result = route(problem, options=options).results_by_net["return"]
assert result.report.terminal_error is None
assert result.outcome == "unroutable"
@pytest.mark.parametrize(("radius", "spacing", "valid"), [(2, 0, True), (2, 4, False), (3, 4, True)]) @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: 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)) net = NetSpec("fold", Port(10, 20, 0), Port(10, 20 + 2 * radius, 180))
@ -1038,7 +1091,8 @@ def test_route_verification_detects_physical_bend_overlap(mode, proxy) -> None:
NetSpec("a", Port(50, 50, 0), Port(60, 60, 90)), NetSpec("a", Port(50, 50, 0), Port(60, 60, 90)),
NetSpec("b", Port(41, 54, 0), Port(51, 44, 270)), NetSpec("b", Port(41, 54, 0), Port(51, 44, 270)),
) )
problem = RoutingProblem((0, 0, 120, 120), nets) seeds = {"a": PathSeed((Bend90Seed(10, "CCW"),)), "b": PathSeed((Bend90Seed(10, "CW"),))}
problem = RoutingProblem((0, 0, 120, 120), nets, initial_paths=seeds)
search = SearchOptions(node_limit=100, bend_radii=(10,), bend_collision_type="clipped_bbox", bend_clip_margin=4) search = SearchOptions(node_limit=100, bend_radii=(10,), bend_collision_type="clipped_bbox", bend_clip_margin=4)
else: else:
nets = ( nets = (
@ -1052,7 +1106,7 @@ def test_route_verification_detects_physical_bend_overlap(mode, proxy) -> None:
physical_bend = outline.union(box(10, -8, 13, -6)).union(box(12, -8, 14, 9)) physical_bend = outline.union(box(10, -8, 13, -6)).union(box(12, -8, 14, 9))
search = SearchOptions(node_limit=20, bend_radii=(10,), bend_proxy_geometry=bend_proxy, bend_physical_geometry=physical_bend) search = SearchOptions(node_limit=20, bend_radii=(10,), bend_proxy_geometry=bend_proxy, bend_physical_geometry=physical_bend)
options = RoutingOptions( options = RoutingOptions(
search=search, search=replace(search, node_limit=0),
congestion=CongestionOptions(max_iterations=1), congestion=CongestionOptions(max_iterations=1),
diagnostics=DiagnosticsOptions(capture_conflict_trace=True), diagnostics=DiagnosticsOptions(capture_conflict_trace=True),
topology=TopologyOptions(mode=mode), topology=TopologyOptions(mode=mode),
@ -1874,6 +1928,38 @@ def test_route_all_restores_best_iteration_snapshot_on_timeout(monkeypatch: pyte
assert evaluator.collision_engine.has_dynamic_paths() assert evaluator.collision_engine.has_dynamic_paths()
@pytest.mark.parametrize("during", ["preparation", "search"])
def test_worker_checks_timeout_inside_single_net_attempt(during, monkeypatch) -> None:
clock = [0.0]
monkeypatch.setattr(router_module.time, "monotonic", lambda: clock[0])
problem = RoutingProblem((0, 0, 100, 100), (NetSpec("line", Port(10, 50, 0), Port(90, 50, 0)),))
options = RoutingOptions(
search=SearchOptions(node_limit=100),
congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False),
refinement=RefinementOptions(enabled=False),
topology=TopologyOptions(mode="off"),
)
if during == "preparation":
def expire_during_preparation(*_args):
clock[0] = 61.0
monkeypatch.setattr(PathFinder, "_prepare_topology", expire_during_preparation)
else:
original_expand = search_module._expand_moves
def expire_during_search(*args, **kwargs):
original_expand(*args, **kwargs)
clock[0] = 61.0
monkeypatch.setattr(search_module, "_expand_moves", expire_during_search)
result = route(problem, options=options)
assert result.metrics.timeout_events == 1
assert result.metrics.nodes_expanded == int(during == "search")
assert not result.results_by_net["line"].is_valid
def test_capture_conflict_trace_records_restored_best_stage(monkeypatch: pytest.MonkeyPatch) -> None: def test_capture_conflict_trace_records_restored_best_stage(monkeypatch: pytest.MonkeyPatch) -> None:
problem = RoutingProblem( problem = RoutingProblem(
bounds=(0, 0, 100, 100), bounds=(0, 0, 100, 100),

View file

@ -0,0 +1,31 @@
from json import loads
from pathlib import Path
import pytest
from shapely.geometry import Polygon
from inire import (
CongestionOptions, NetSpec, ObjectiveWeights, Port, RefinementOptions, RoutingOptions, RoutingProblem, SearchOptions, route,
)
_CASES = loads((Path(__file__).parent / "data" / "crow_launch_cases.json").read_text())["cases"]
@pytest.mark.parametrize("case", _CASES, ids=[str(case["id"]) for case in _CASES])
def test_original_crow_launch_direction_routes_at_the_review_budget(case) -> None:
net = NetSpec(str(case["id"]), Port(*case["start"]), Port(*case["target"]), case["width"])
problem = RoutingProblem(tuple(case["bounds"]), (net,), tuple(Polygon(*rings) for rings in case["keepouts"]), clearance=70)
options = RoutingOptions(
search=SearchOptions(
node_limit=225, bend_radii=(5000, 10000), sbend_radii=(5000, 10000), min_straight_length=500, max_straight_length=450_000,
),
congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False, use_tiered_strategy=False),
objective=ObjectiveWeights(danger_weight=0),
refinement=RefinementOptions(enabled=False),
)
run = route(problem, options=options)
assert run.results_by_net[net.net_id].is_valid
assert run.metrics.nodes_expanded <= 225

View file

@ -8,7 +8,8 @@ from shapely import union_all
from shapely.geometry import Point, Polygon, box, shape from shapely.geometry import Point, Polygon, box, shape
from inire import ( from inire import (
Bend90Seed, NetSpec, Port, RoutingOptions, RoutingProblem, SBendOutline, SBendSeed, SearchOptions, StraightSeed, TopologyOptions, route, Bend90Seed, NetSpec, PathSeed, Port, RoutingOptions, RoutingProblem, SBendOutline,
SBendSeed, SearchOptions, StraightSeed, TopologyOptions, route,
) )
from inire.constants import TOLERANCE_LINEAR from inire.constants import TOLERANCE_LINEAR
from inire.router._automatic import _AutomaticRun from inire.router._automatic import _AutomaticRun
@ -417,6 +418,45 @@ def test_unused_custom_outline_keeps_constructive_planning_available(name, mode)
assert all(path.is_valid for path in result.results_by_net.values()) assert all(path.is_valid for path in result.results_by_net.values())
@pytest.mark.parametrize("hint", [(), (StraightSeed(2400),)])
def test_automatic_plan_recovers_full_complex_board_with_one_supplied_hint(hint) -> None:
case = next(case for case in BENCHMARK_CASES if case.name == "terminal-bench")
problem = replace(case.problem, initial_paths={"net_04": PathSeed(hint)})
options = replace(
case.options,
search=replace(case.options.search, node_limit=100),
topology=replace(case.options.topology, mode="automatic"),
congestion=replace(case.options.congestion, max_iterations=1, warm_start_enabled=False),
refinement=replace(case.options.refinement, enabled=False),
)
result = route(problem, options=options)
assert len(result.results_by_net) == 9
assert all(path.is_valid for path in result.results_by_net.values())
def test_point_terminal_replay_preserves_the_selected_port_headings() -> None:
case = next(case for case in BENCHMARK_CASES if case.name == "terminal-bench-point-terminals")
a, *others = case.problem.nets
problem = replace(case.problem, nets=(replace(a, start=a.start.translate(rotation=180)), *others))
options = replace(case.options, topology=replace(case.options.topology, mode="automatic"))
chosen = route(problem, options=options)
paths = chosen.results_by_net
assert all(path.is_valid for path in paths.values())
rebuilt = tuple(
replace(net, start=paths[net.net_id].path[0].start_port, target=paths[net.net_id].path[-1].end_port) for net in problem.nets
)
assert rebuilt[0].start.r != problem.nets[0].start.r
assert [net.net_id for net in rebuilt if net.target.r == 180] == ["net_08"]
seeds = {net_id: result.as_seed() for net_id, result in paths.items()}
replay_options = replace(
options, search=replace(options.search, node_limit=0), refinement=replace(options.refinement, enabled=False),
)
replay = route(replace(problem, nets=rebuilt, initial_paths=seeds), options=replay_options)
assert all(result.is_valid and result.locked_geometry == paths[net_id].locked_geometry for net_id, result in replay.results_by_net.items())
def test_complex_benchmarks_are_distinct_unseeded_nine_net_problems() -> None: def test_complex_benchmarks_are_distinct_unseeded_nine_net_problems() -> None:
assert len({case.name for case in BENCHMARK_CASES}) == len(BENCHMARK_CASES) assert len({case.name for case in BENCHMARK_CASES}) == len(BENCHMARK_CASES)
assert len(COMPLEX_BENCHMARK_CASES) == 20 assert len(COMPLEX_BENCHMARK_CASES) == 20

View file

@ -1,14 +1,104 @@
from dataclasses import replace from dataclasses import replace
import pytest import pytest
from shapely.geometry import LineString, box from shapely.geometry import LineString, Polygon, box
from inire import CongestionOptions, NetSpec, PathSeed, Port, RoutingOptions, RoutingProblem, SearchOptions, StraightSeed, TopologyOptions, route from inire import (
CongestionOptions, NetSpec, ObjectiveWeights, PathSeed, Port, RefinementOptions,
RoutingOptions, RoutingProblem, SearchOptions, StraightSeed, TopologyOptions, route,
)
from inire.router._stack import build_routing_stack from inire.router._stack import build_routing_stack
from inire.router._topology import _Assignment, _endpoint_access, _Mesh, _plan_lane_assignments, plan_corridors from inire.router._topology import _Assignment, _endpoint_access, _Mesh, _plan_lane_assignments, plan_corridors
from inire.tests.routing_benchmarks import DETOUR from inire.tests.routing_benchmarks import DETOUR
@pytest.mark.parametrize("hint", [(), (StraightSeed(5),), (StraightSeed(680),)])
def test_seed_mode_realizes_corridor_with_incomplete_or_invalid_hint(hint) -> None:
problem = replace(DETOUR.problem, initial_paths={"detour": PathSeed(hint)})
options = replace(
DETOUR.options,
search=replace(DETOUR.options.search, node_limit=100),
congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False),
refinement=RefinementOptions(enabled=False),
topology=TopologyOptions(mode="seed"),
)
run = route(problem, options=options)
assert run.results_by_net["detour"].is_valid
assert 0 < run.metrics.nodes_expanded <= 100
@pytest.mark.parametrize("with_peer", [False, True])
def test_narrow_alternative_remains_available_with_a_shared_guide(with_peer) -> None:
narrow = NetSpec("narrow", Port(60, 110, 0), Port(740, 110, 0))
wide = NetSpec("wide", Port(100, 500, 0), Port(150, 500, 0), 100)
nets = (narrow, wide) if with_peer else (narrow,)
problem = RoutingProblem((0, 0, 800, 600), nets, (box(300, 50, 480, 350),), clearance=6)
options = RoutingOptions(
search=SearchOptions(node_limit=500, bend_radii=(20,), sbend_radii=()),
objective=ObjectiveWeights(danger_weight=0),
congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False),
refinement=RefinementOptions(enabled=False),
topology=TopologyOptions(mode="seed"),
)
run = route(problem, options=options)
assert all(result.is_valid for result in run.results_by_net.values())
@pytest.mark.parametrize("mode", ["off", "guide", "seed", "automatic"])
@pytest.mark.parametrize("narrow_by", [0, 0.001])
def test_offset_gate_search_uses_exact_clearance(mode, narrow_by) -> None:
walls = (
box(20, 0, 26, 5 + narrow_by), box(20, 9 - narrow_by, 26, 25),
box(43, 0, 49, 11 + narrow_by), box(43, 15 - narrow_by, 49, 25),
)
net = NetSpec("gate", Port(1, 7, 0), Port(60, 13, 0))
problem = RoutingProblem((0, 0, 62, 25), (net,), walls, clearance=1)
options = RoutingOptions(
search=SearchOptions(node_limit=250, min_straight_length=1, bend_radii=(), sbend_radii=(10,), sbend_offsets=(6,)),
objective=ObjectiveWeights(danger_weight=0),
congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False, use_tiered_strategy=False),
refinement=RefinementOptions(enabled=False),
topology=TopologyOptions(mode=mode),
)
assert route(problem, options=options).results_by_net["gate"].is_valid == (narrow_by == 0)
@pytest.mark.parametrize("mode", ["off", "guide", "seed", "automatic"])
def test_rounded_keepout_guidance_preserves_acute_aperture(mode) -> None:
keepouts = (Polygon([(35, 0), (65, 0), (50, 22.95)]), Polygon([(35, 50), (65, 50), (50, 27.05)]))
problem = RoutingProblem((0, 0, 100, 50), (NetSpec("opening", Port(7, 15, 0), Port(93, 35, 0)),), keepouts, clearance=1)
options = RoutingOptions(
search=SearchOptions(node_limit=200, bend_radii=(), sbend_radii=(10,), sbend_offsets=(10,)),
objective=ObjectiveWeights(danger_weight=0),
congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False, use_tiered_strategy=False),
refinement=RefinementOptions(enabled=False),
topology=TopologyOptions(mode=mode),
)
assert route(problem, options=options).results_by_net["opening"].is_valid
@pytest.mark.parametrize("mode", ["guide", "seed"])
def test_guidance_retry_can_change_an_incumbent_in_an_offset_gate(mode) -> None:
nets = (NetSpec("a", Port(16, 48, 0), Port(199, 82, 0), 4.5), NetSpec("b", Port(18, 59, 0), Port(197, 93, 0), 1.25))
walls = (box(60, 0, 67, 56.25), box(60, 74.125, 67, 118), box(125, 0, 132, 66.25), box(125, 84.125, 132, 118))
problem = RoutingProblem((0, 0, 219, 118), nets, walls, clearance=1)
options = RoutingOptions(
search=SearchOptions(node_limit=1000, bend_radii=(10,), sbend_radii=(10,), sbend_offsets=(10, 12)),
objective=ObjectiveWeights(danger_weight=0),
congestion=CongestionOptions(max_iterations=2),
refinement=RefinementOptions(enabled=False),
topology=TopologyOptions(mode=mode),
)
assert all(result.is_valid for result in route(problem, options=options).results_by_net.values())
def test_lane_assignment_keeps_mesh_path_order_on_equal_costs(monkeypatch: pytest.MonkeyPatch) -> None: def test_lane_assignment_keeps_mesh_path_order_on_equal_costs(monkeypatch: pytest.MonkeyPatch) -> None:
problem = DETOUR.problem problem = DETOUR.problem
mesh = _Mesh(box(*problem.bounds), problem.static_obstacles, problem.nets[0].width / 2, problem.clearance) mesh = _Mesh(box(*problem.bounds), problem.static_obstacles, problem.nets[0].width / 2, problem.clearance)

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