Fix routing correctness and bound optional routing work

Check physical keepout clearance, retain useful partial paths, and account for all pair repair searches. Verify complete seeds early and recover narrower corridors when shared guides are blocked.

Keep frontier diagnostics outside routing decisions and bound their work by the worker deadline. Correct benchmark scaling and scenario validation, and update the guides and release metadata.
This commit is contained in:
Jan Petykiewicz 2026-12-02 17:16:34 -08:00
commit 63acb94642
40 changed files with 1073 additions and 199 deletions

View file

@ -31,22 +31,22 @@ else:
print(result.outcome)
```
![A short solid waveguide connects the start at (50, 100) and target at (250, 100). Both port arrows point east.](docs/figures/first-route.png)
![A short solid waveguide connects the start at (50, 100) and target at (250, 100). Both port arrows point east.](https://mpxd.net/code/jan/inire/raw/branch/topo/docs/figures/first-route.png)
The example prints `200.0`. Heading `0` is east at both ports.
## Route your own layout
- [Layout inputs](docs/user/route-a-layout.md#define-the-inputs)
- [Partial routes](docs/user/tune-and-troubleshoot.md#why-a-net-stopped-short)
- [Placement recipes](docs/user/route-a-layout.md#save-a-placement-recipe)
- [User guide](DOCS.md)
- [Layout inputs](https://mpxd.net/code/jan/inire/src/branch/topo/docs/user/route-a-layout.md#user-content-define-the-inputs)
- [Partial routes](https://mpxd.net/code/jan/inire/src/branch/topo/docs/user/tune-and-troubleshoot.md#user-content-why-a-net-stopped-short)
- [Placement recipes](https://mpxd.net/code/jan/inire/src/branch/topo/docs/user/route-a-layout.md#user-content-save-a-placement-recipe)
- [User guide](https://mpxd.net/code/jan/inire/src/branch/topo/DOCS.md)
## Develop Inire
- [Developer guide](docs/development.md)
- [Routing benchmarks](docs/benchmarks.md)
- [Developer guide](https://mpxd.net/code/jan/inire/src/branch/topo/docs/development.md)
- [Routing benchmarks](https://mpxd.net/code/jan/inire/src/branch/topo/docs/benchmarks.md)
## License
Inire is distributed under the [GNU Affero General Public License v3](LICENSE.md).
Inire is distributed under the [GNU Affero General Public License v3](https://mpxd.net/code/jan/inire/src/branch/topo/LICENSE.md).

View file

@ -28,3 +28,5 @@ Use these records to recover the rationale for a routing decision or compare a f
| Reroute order and work immediately before repair | [Pre-pair frontier trace](pre_pair_frontier_trace.md). |
Each trace report has a companion JSON file with the same basename. The baseline comparison tool reads `performance_baseline.json` from this directory by default. For a fresh trace, set `--output-dir` to keep the capture separate from the archived record. See the [fan-out capture command](../../docs/routing-diagnostics.md#follow-a-late-conflict-into-pair-local-repair).
In the archived traces and pair-local characterization, `nodes_expanded` excludes pair-local search. The archived `pair_local_search_nodes_expanded` counts only attempts that produced a locally valid pair. Neither convention affects the nine scenarios in the saved performance baseline, which used no pair-local search. Fresh captures count every pair-local search in both counters.

View file

@ -42,7 +42,7 @@ Use this record to recover the original refactor scope and the reason for each p
## Verification
Use the current 67-board corpus as the regression baseline for routing changes. The `corpus-regression` and `public-defaults` profiles reach every board's routing bound and verify 433 of 437 nets each. For behavior-preserving changes, compare exact paths, per-net costs, bounds, planner stage order and metadata, and relevant callback and trace payloads. For changes that intentionally eliminate work, such as item 13, record the expected counter differences while checking route and trace parity. [Corpus reproduction](../../docs/benchmarks.md#run-the-full-regression-corpus)
Use the current 67-board corpus as the regression baseline for routing changes. The `corpus-regression` and `public-defaults` profiles reach every board's routing bound and verify 433 of 437 nets each. For behavior-preserving changes, compare exact paths, per-net costs, bounds, planner stage order and metadata, and relevant callback and trace payloads. For changes that intentionally eliminate work, such as item 13, record the expected counter differences while checking route and trace parity. [Corpus reproduction](../../docs/benchmarks.md#run-the-full-benchmark-corpus)
Capture the same cases and options at both revisions. The parity command defaults to the `corpus-regression` and `public-defaults` profiles. [Parity commands](../../docs/routing-diagnostics.md#reproduce-and-compare)

View file

@ -10,7 +10,7 @@ Follow the left column while coverage is below the target. Reaching the target s
1. **Set a coverage target.** Conflicting aligned port faces and [track capacity](../inire/router/_capacity.py#L29) at rectangular cuts can bound how many nets fit.
2. **Try constructive plans.** Bundles assign ordered tracks, columns schedule turns, and compact planners fit short links. Each plan supplies seeds for the worker to verify.
3. **Search for missing routes.** Early attempts use small budgets and can hold verified routes fixed. When a column plan stalls, try separated channels or a shared bypass around the keepouts. If the locks cut off a port, retry with movable seeds or different lanes. With one net left, try a verified detour around the locked paths, including incumbents found by the seed fallback. Lattice search handles custom outlines or proxies and is the fallback when corridor planning is unavailable.
3. **Search for missing routes.** Early attempts use small budgets and can hold verified routes fixed. When a column plan stalls, try separated channels or a shared bypass around the keepouts. If the locks cut off a port, retry with movable seeds or different lanes. With one net left, try a verified detour around the locked paths, including incumbents found by the seed fallback. Lattice search handles custom outlines and proxies and can retry unresolved nets after corridor-guided attempts.
4. **Select and refine.** Prefer higher verified coverage. Compare cost on matching verified net IDs. Refinement can replace the selected layout only if those IDs remain verified.
### Example of a poor lock

View file

@ -5,16 +5,16 @@
## Micron-scale routing cases
The `expanded` group adds 72 deterministic, unseeded boards with independently constructed reference routes. The authored grid units are 10, 100, 250, 500, and 1000 nm. Bend radii span 10–100 µm and trace widths span 1–20 µm. The comparison script records `grid_nm` for these boards. Convert benchmark-weighted lengths to microns by multiplying by `grid_nm / 1000`.
The `expanded` group adds 75 deterministic, unseeded boards with independently constructed reference routes. The authored grid units are 10, 100, 250, 500, and 1000 nm. Bend radii span 10–100 µm and trace widths span 1–20 µm. The comparison script records `grid_nm` for these boards and the imported fixtures. Convert benchmark-weighted lengths to microns by multiplying by `grid_nm / 1000`.
| Group | Boards | Coverage |
| --- | ---: | --- |
| `geometry-corners` | 32 | Exact four-bend spans, tight returns and paired routes, exact-span S-bend slots, mixed widths, and saturated or overloaded apertures. |
| `complex-layouts` | 24 | Serial aperture banks with opposing tracks, concave and fixed-route keepouts, and staggered crossing arrays. |
| `search-challenges` | 8 | Alternating comb walls that force repeated turns and exercise search-budget exhaustion. |
| `search-challenges` | 11 | Alternating comb walls and other tight passages that require repeated turns or exercise search-budget exhaustion. |
| `scaling` | 8 | Banks and crossing arrays of up to 256 nets, obstacle fields with up to 320 keepouts, and a 240-net board with 240 keepouts and four blocked approaches. |
Pytest verifies the 72 reference layouts and checks that unseeded routing reaches the known bound on every board. Use `--case search-challenges` or `--case scaling` with an explicit budget to compare routing policies on the harder boards. For scaling comparisons, use the same grid, mode, and budget and collect repeated timings with `--repeat`.
Pytest verifies the 75 reference layouts and checks that unseeded routing reaches the known bound on every board. Use `--case search-challenges` or `--case scaling` with an explicit budget to compare routing policies on the harder boards. For scaling comparisons, use the same grid, mode, and budget and collect repeated timings with `--repeat`.
To exercise the low-budget fallbacks on tight geometry, run `--case geometry-corners --profile corpus-regression --mode automatic --nodes 1 --seed-nodes 1 --iterations 1`.

View file

@ -22,10 +22,12 @@ Use repeated wall times to check whether counter changes affect runtime.
| Similar expansions, more search time | Check `ray_cast_calls*` and `ray_cast_exact_geometry_checks` for visibility work. Compare dynamic `congestion_candidate_ids` with `congestion_exact_pair_checks` to see how much candidate geometry reaches exact tests. |
| Verification dominates | Compare `verify_path_report_calls` with `verify_static_buffer_ops` and `verify_dynamic_exact_pair_checks`. This can distinguish repeated path checks from expensive checks of the same paths. |
| Refinement takes longer | Compare `refinement_windows_considered`, `refinement_candidates_verified`, and `refinement_candidates_accepted`. Check whether the added windows buy a better path before enlarging the default budget. |
| Attempts reach targets while verified coverage stays flat | Compare `iteration_conflict_edges` and `nets_carried_forward`. After congestion iterations finish, check how many pair repairs were tried and how many were installed. `pair_local_search_nodes_expanded` counts expansions from searches that produced a locally valid pair. Use `pair_local_search_attempts` to count every try. |
| Attempts reach targets while verified coverage stays flat | Compare `iteration_conflict_edges` and `nets_carried_forward`. After congestion iterations finish, check how many pair repairs were tried and how many were installed. `pair_local_search_nodes_expanded` counts expansions from every pair-local search and is included in `nodes_expanded`. Use `pair_local_search_attempts` to count every try. |
`nets_routed` and `nets_reached_target` count attempts. Use `result.is_valid` or `verified_net_ids` for final successes.
`timeout_events` counts routing workers that reached their deadline. Frontier diagnostics use the time left after routing and final verification. They gather component details for colliding nets and check the deadline during that work and during frontier replay. `diagnostic_timeout_events` counts workers where the deadline stopped or skipped frontier diagnostics. A diagnostic timeout leaves the routing result, retry decisions, and replay callback intact.
- [Full metrics field list](../inire/results.py)
Exact corner visibility uses cached local queries. Track them with `visibility_corner_queries_exact` and `visibility_point_cache_hits`. The legacy graph counters `visibility_builds` and `visibility_corner_pairs_checked` report zero, as do `ray_cast_calls_visibility_build` and `ray_cast_calls_visibility_query`.
@ -43,7 +45,7 @@ Returned traces describe the selected attempt. Numbered entries use the same run
| Which net consumed an iteration's budget? | `capture_iteration_trace` records `iteration_trace`. Inspect per-net `net_attempts` for expansions, pruning, congestion calls, and seed usage. |
| Which routes have a clearance conflict? | `capture_conflict_trace` records the conflicting net IDs and the component indices in `conflict_trace`. |
| Which candidate moves were pruned near the conflict? | `capture_frontier_trace` records `frontier_trace` for routes that reached their targets and still conflict with other nets. The trace samples moves and their prune reasons during a replay. |
| What did the last unresolved iteration hand to pair-local repair? | `capture_pre_pair_frontier_trace` records `pre_pair_frontier_trace`. Check reroute order, conflict edges, and per-net attempt work immediately before repair. |
| What layout did the worker restore for pair-local repair? | `capture_pre_pair_frontier_trace` records the selected congestion iteration, its reroute order, conflict edges, and work. The worker saves that layout and replays it after repair and verification. A conflicting net carried from an earlier iteration has zero attempt work for the selected iteration. |
| Where did detailed search explore? | `capture_expanded` records positions and headings from the detailed routing iterations in `expanded_nodes`. Use `plot_expanded_nodes()` as in the [fan-out script](../examples/07_large_scale_routing.py). |
<a id="find-overlapping-components"></a>

View file

@ -10,17 +10,17 @@
Read the panels from top to bottom. Follow the crossed triangle edges, the suggested crossing points, then the S-bend in the verified route.
1. **Find space for centerlines.** Inset the board by half the widest guide's width. Expand obstacles by that amount plus clearance. Try a straight port lead to reach the mesh, or use the port itself. A flush port can reach the inset mesh via a lead whose flat end fits on the board. If a narrow net has no passage, retry with its own width.
1. **Find space for centerlines.** Inset the board by half the widest guide's width. Expand obstacles by that amount plus clearance. Try a straight port lead to reach the mesh, or use the port itself. A flush port can reach the inset mesh via a lead whose flat end fits on the board. Nets can reuse shared corridors when the mesh has open space around both ports and the area between them. A narrower mesh can recover missing corridors and add passages near keepouts or board edges. If a shared guide fails and a reserved route occupies that shared space, the worker can build a narrower mesh on demand. A straight path that fits in the shared mesh can supply its own alternate guide.
<a id="design-background"></a>
A portal is an edge shared by adjacent free-space triangles. For an earlier representation of a route by its crossings of triangle edges, see Section III-A and Figure 1 of [Hama and Etoh's curvilinear detailed-routing paper](https://www.cecs.uci.edu/~papers/compendium94-03/papers/1998/aspdac98/pdffiles/06c_3.pdf).
2. **Choose a passage and a lane.** Rank passages by distance and competing nets. Place lanes on shared triangle edges according to turn room and reservations. A joint retry can move lanes for several nets.
2. **Choose a passage and a lane.** Rank passages by distance and competing nets. Assign lanes jointly by reserving space on shared triangle edges as each net is planned.
- [Lane scoring](../inire/router/_topology.py#L255)
3. **Turn the sketch into a path.** Guide mode suggests moves and adds a soft cost. Seed mode searches within a corridor and checks the resulting seed against obstacles and earlier seeds. With alternatives, it allocates at least half the seed budget to the first corridor.
3. **Turn the sketch into a path.** Guide mode suggests moves and adds a soft cost. Seed mode searches within a corridor and checks the resulting seed against obstacles and earlier seeds. With alternatives, it allocates at least half the seed budget to the first corridor. With at least two iterations and positive guidance strength, an explicit guided run that leaves unresolved nets can retry with the guidance cost disabled. Guide and seed modes can verify a complete supplied layout before building corridors.
A passage can be connected in the mesh and leave too little room to bend onto the target port's heading. For the bend-radius and port-alignment rules that constrain the physical route, see Section II-B of [LiDAR 2.0](https://arxiv.org/html/2505.17239v1#S2.SS2).

View file

@ -31,7 +31,7 @@ Set `TopologyOptions(mode=...)` and pass it as `topology` in `RoutingOptions`.
- **`off`.** Run lattice search directly to measure what search can do without corridor suggestions.
- **`guide`.** Suggest a passage through free space. Search can leave it to make a turn.
- **`seed`.** Try to build a valid starting path inside the suggested passage before the detailed search.
- **`bundle`.** Route supported ordered rectangular bundles with an empty `initial_paths` mapping. Use circular physical bends. The smallest 90-degree bend radius must be a positive integer and must also appear in `sbend_radii`. Unsupported layouts and invalid schedules raise `ValueError`.
- **`bundle`.** Route supported ordered rectangular bundles with an empty `initial_paths` mapping. Use circular physical bends and configure a usable positive integer radius in both `bend_radii` and `sbend_radii`. Unsupported layouts and invalid schedules raise `ValueError` when routing iterations are enabled.
### Mode requirements

View file

@ -147,6 +147,10 @@ def _route(
raise ValueError(f"Initial path provided for unknown net: {net_id}")
if net_id not in coincident and (error := search.seed_geometry_error(seed)) is not None:
seed_errors[net_id] = f"Initial path for {net_id!r} {error}"
if options.topology.mode == "automatic" and options.topology.infer_terminal_headings and any(
seed.segments and net_id not in coincident for net_id, seed in problem.initial_paths.items()
):
options = replace(options, topology=replace(options.topology, infer_terminal_headings=False))
if coincident or seed_errors:
problem = replace(
problem,

View file

@ -18,7 +18,7 @@ from inire.results import RoutingReport
from inire.geometry.static_obstacle_index import StaticObstacleIndex
if TYPE_CHECKING:
from collections.abc import Iterable, Sequence
from collections.abc import Callable, Iterable, Sequence
from shapely.geometry import Polygon
from shapely.geometry.base import BaseGeometry
@ -304,7 +304,7 @@ class RoutingWorld:
clearance = self.clearance
left, bottom, right, top = result.total_bounds
if self._static_obstacles.owners:
if self._static_obstacles.owners or result.check_physical_keepout:
x0, y0, x1, y1 = result.total_physical_bounds
left, bottom, right, top = min(left, x0), min(bottom, y0), max(right, x1), max(top, y1)
# The broad phase must include both the keepout proxy and the physical outline.
@ -317,6 +317,8 @@ class RoutingWorld:
if any(_violates_net_clearance(polygon, obstacle, clearance) for polygon in physical):
return True
continue
if result.check_physical_keepout and any(_violates_clearance(polygon, obstacle, clearance) for polygon in physical):
return True
for polygon in result.collision_geometry:
if not _violates_clearance(polygon, obstacle, clearance):
continue
@ -758,8 +760,11 @@ class RoutingWorld:
capture_component_conflicts: bool = False,
include_invalid_dynamic: bool = True,
geometry_report: RoutingReport | None = None,
diagnostic_expired: Callable[[], bool] | None = None,
) -> PathVerificationDetail:
"""Check the full path, optionally reusing its report against unchanged static geometry."""
"""Check a path, or collect component conflicts from an already verified report for diagnostics."""
if diagnostic_expired is not None and geometry_report is None:
raise ValueError("Diagnostic conflict collection needs a verified path report")
if self.metrics is not None:
self.metrics.total_verify_path_report_calls += 1
report = self.verify_path_geometry(components) if geometry_report is None else geometry_report
@ -772,7 +777,10 @@ class RoutingWorld:
and (include_invalid_dynamic or not report.intrinsic_collision_count)
and self._dynamic_paths.has_physical_paths()
):
comparisons = 0
for component_index, component in enumerate(components):
if diagnostic_expired is not None and diagnostic_expired():
return PathVerificationDetail(report=report)
component_hits: set[str] = set()
for polygon in component.physical_geometry:
candidates = self._physical_candidates(net_id, polygon)
@ -782,6 +790,10 @@ class RoutingWorld:
for hit_net_id, hit_component_index, other in candidates:
if hit_net_id in polygon_hits and not capture_component_conflicts:
continue
if diagnostic_expired is not None:
comparisons += 1
if comparisons % 32 == 0 and diagnostic_expired():
return PathVerificationDetail(report=report)
if self.metrics is not None:
self.metrics.total_verify_dynamic_exact_pair_checks += 1
if _violates_net_clearance(polygon, other, self.clearance):

View file

@ -1,6 +1,6 @@
from __future__ import annotations
from dataclasses import dataclass, field, replace
from dataclasses import dataclass, field, fields, replace
from math import asin, ceil, isfinite, pi, radians, sqrt
from typing import TYPE_CHECKING, Literal
@ -138,6 +138,13 @@ class ComponentResult:
_total_physical_bounds: tuple[float, float, float, float] | None = field(init=False, repr=False, compare=False, default=None)
_physical_geometry_valid: bool | None = field(init=False, repr=False, compare=False, default=None)
_coordinate_count: int | None = field(init=False, repr=False, compare=False, default=None)
check_physical_keepout: bool = field(default=False, repr=False, compare=False)
def __setstate__(self, state: list[object]) -> None:
for item, value in zip(fields(self), state, strict=False):
object.__setattr__(self, item.name, value)
if len(state) < len(fields(self)):
object.__setattr__(self, "check_physical_keepout", self.collision_geometry is not self.physical_geometry)
def __post_init__(self) -> None:
collision_geometry = tuple(self.collision_geometry)
@ -257,6 +264,7 @@ class ComponentResult:
dilated_physical_geometry=translate_geometry(self.dilated_physical_geometry),
width=self.width,
standard_faces=self.standard_faces,
check_physical_keepout=self.check_physical_keepout,
)
object.__setattr__(result, "_coordinate_count", self._coordinate_count)
return result
@ -565,6 +573,11 @@ class Bend90:
dilated_physical_geometry=dilated_physical_geometry,
width=width,
standard_faces=physical_geometry is arc_polys,
check_physical_keepout=(
custom_physical
or isinstance(collision_type, Polygon)
or (collision_type == "clipped_bbox" and clip_margin is not None and clip_margin > 0)
),
)
@ -682,6 +695,9 @@ class SBend:
dilated_physical_geometry=dilated_physical_geometry,
width=width,
standard_faces=outline is None,
check_physical_keepout=(
outline is None and collision_type == "clipped_bbox" and clip_margin is not None and clip_margin > 0
),
)

View file

@ -1,5 +1,6 @@
from __future__ import annotations
from collections import OrderedDict
from typing import TYPE_CHECKING
import numpy
@ -15,6 +16,9 @@ if TYPE_CHECKING:
from inire.geometry.collision import RoutingWorld
_NET_TREE_CACHE_SIZE = 8
class StaticObstacleIndex:
__slots__ = (
"engine",
@ -48,7 +52,7 @@ class StaticObstacleIndex:
self.raw_tree: STRtree | None = None
self.raw_owners: tuple[str | None, ...] = ()
self.owners: dict[int, str] = {}
self.net_specific_trees: dict[tuple[float, float], tuple[STRtree, numpy.ndarray, numpy.ndarray]] = {}
self.net_specific_trees: OrderedDict[tuple[float, float], tuple[STRtree, numpy.ndarray, numpy.ndarray]] = OrderedDict()
self.ray_cast_cache: dict[tuple[float, float, float, float, float | None, float, type, type, type, type], float] = {}
self.id_counter = 0
self.version = 0
@ -107,6 +111,7 @@ class StaticObstacleIndex:
width, clearance = float(net_width), float(self.engine.clearance)
key = (width, clearance)
if key in self.net_specific_trees:
self.net_specific_trees.move_to_end(key)
return self.net_specific_trees[key]
if self.engine.metrics is not None:
@ -127,6 +132,8 @@ class StaticObstacleIndex:
payload = (STRtree(geometries), numpy.array(is_rect_list, dtype=bool), numpy.array(bounds_list, dtype=numpy.float64))
self.net_specific_trees[key] = payload
if len(self.net_specific_trees) > _NET_TREE_CACHE_SIZE:
self.net_specific_trees.popitem(last=False)
return payload
def ensure_raw_tree(self) -> None:

View file

@ -256,6 +256,11 @@ class RouteMetrics:
pair_local_search_nodes_expanded: int
late_phase_capped_nets: int
late_phase_capped_fallbacks: int
diagnostic_timeout_events: int = 0
def __setstate__(self, state: list[object]) -> None:
for index, item in enumerate(fields(self)):
object.__setattr__(self, item.name, state[index] if index < len(state) else item.default)
def _sum_route_metrics(samples: Iterable[RouteMetrics]) -> RouteMetrics:

View file

@ -217,7 +217,7 @@ def add_node(
applied_bonus = config.guidance_bonus
context.metrics.total_guidance_bonus_applied_sbend += applied_bonus
context.metrics.total_guidance_bonus_applied += applied_bonus
move_cost = max(0.001, move_cost - applied_bonus)
move_cost = min(move_cost, max(0.001, move_cost - applied_bonus))
next_seed_index = parent.seed_index + 1
if corridor is not None and config.corridor_strength:

View file

@ -106,15 +106,3 @@ def next_reroute_net_ids(
if has_corridors or (all_reached_target and 0 < len(review.conflict_edges) <= 3):
return set(ordered_net_ids).difference(review.completed_net_ids)
return set(ordered_net_ids)
def reached_pair_local_plateau(*, improved: bool, all_reached_target: bool, best_conflict_edges: int | None) -> bool:
# A non-improving iteration with at most two remaining conflicts is
# enough to hand the reached-target layout to bounded pair-local repair.
return not improved and all_reached_target and best_conflict_edges is not None and best_conflict_edges <= 2
def repeated_conflict_count(current_edges: int, previous_edges: int, previous_repeats: int) -> int:
if current_edges and current_edges == previous_edges:
return previous_repeats + 1
return 0

View file

@ -72,8 +72,8 @@ def search_pair_candidate(
*,
needs_self_collision_check: Set[str],
expired: Callable[[], bool] | None = None,
) -> tuple[dict[str, RoutingResult], int] | None:
"""Return both locally verified replacements and their search work."""
) -> tuple[dict[str, RoutingResult] | None, int]:
"""Return search work and the locally verified replacements, if any."""
local = _build_pair_local_context(context, ordered_nets, incumbent_results, pair_order)
world = local.cost_evaluator.collision_engine
options = local.options
@ -102,11 +102,11 @@ def search_pair_candidate(
config=config,
)
if not path or path[-1].end_port != net.target:
return None
return None, local.metrics.total_nodes_expanded
report = world.verify_path_report(net_id, path)
if not report.is_valid:
return None
return None, local.metrics.total_nodes_expanded
replacements[net_id] = RoutingResult(net_id, tuple(path), reached_target=True, report=report)
for component in path:
for polygon in component.physical_geometry:

View file

@ -7,8 +7,9 @@ from dataclasses import dataclass, field, replace
from functools import partial
from typing import TYPE_CHECKING
from shapely import shortest_line
from shapely import STRtree, shortest_line
from inire.geometry.collision import _violates_net_clearance
from inire.geometry.components import bend_fits_width, bend90_uses_circular_geometry
from inire.model import resolve_bend_geometry
from inire.results import (
@ -30,14 +31,12 @@ from inire.router._congestion_policy import (
can_reserve,
next_reroute_net_ids,
ordered_nets,
reached_pair_local_plateau,
repeated_conflict_count,
reroute_plan,
review_verified_results,
)
from inire.router._pair_local import search_pair_candidate
from inire.router._route_traces import conflict_trace_entry, iteration_trace_entry, net_attempt_trace
from inire.router._search import incumbent_guidance, path_guidance, route_astar
from inire.router._search import _distance_to_terminal, incumbent_guidance, path_guidance, route_astar
from inire.router._seed_materialization import materialize_path_seed, SeedMaterializationError
from inire.router.refiner import PathRefiner
@ -49,7 +48,7 @@ if TYPE_CHECKING:
from inire.geometry.components import ComponentResult
from inire.model import NetSpec
from inire.results import ConflictTraceStage, RoutingOperation
from inire.router._topology import Corridor
from inire.router._topology import Corridor, DeferredCorridor
PhaseTimer = Callable[[RoutingOperation], AbstractContextManager[None]]
@ -67,11 +66,11 @@ class _RoutingState:
best_results: dict[str, RoutingResult]
best_is_indexed: bool
best_review: _IterationReview | None
last_conflict_edge_count: int
repeated_conflict_count: int
recent_attempt_work: dict[str, int]
pre_pair_candidate: _PrePairCandidate | None
pre_pair_candidate: _PrePairCandidate | None = None
best_pre_pair_candidate: _PrePairCandidate | None = None
corridors: dict[str, tuple[Corridor, ...]] = field(default_factory=dict)
deferred_corridors: dict[str, DeferredCorridor] = field(default_factory=dict)
seed_errors: dict[str, str] = field(default_factory=dict)
terminal_errors: dict[str, str] = field(default_factory=dict)
replay_details: dict[str, PathVerificationDetail] | None = None
@ -253,11 +252,19 @@ class PathFinder:
continue
net = state.net_specs[net_id]
candidates = state.corridors.get(net_id, ())
blocked_shared_space = self._shared_guide_blocked(state, net_id)
remaining = min(topology.seed_node_limit, self.context.options.search.node_limit)
for index, corridor in enumerate(candidates):
if remaining <= 0:
for index in range(topology.max_corridors):
if remaining <= 0 or expired():
break
if index == 1 and blocked_shared_space:
self._recover_corridor(state, net_id)
candidates = state.corridors[net_id]
if index >= len(candidates):
break
searches_left = len(candidates) - index
if index == 0 and blocked_shared_space:
searches_left = min(topology.max_corridors, searches_left + 1)
budget = max(1, remaining // searches_left)
if index == 0 and searches_left > 1:
budget = max(budget, (remaining + 1) // 2)
@ -266,7 +273,7 @@ class PathFinder:
node_limit=budget,
skip_congestion=True,
self_collision_check=True,
corridor=corridor,
corridor=candidates[index],
restrict_to_corridor=True,
expired=expired,
)
@ -279,6 +286,23 @@ class PathFinder:
break
return seeds
def _shared_guide_blocked(self, state: _RoutingState, net_id: str) -> bool:
deferred = state.deferred_corridors.get(net_id)
if deferred is None:
return False
world = self.context.cost_evaluator.collision_engine
return any(world.iter_static_obstacle_bounds(deferred.bounds)) or any(world.iter_dynamic_path_bounds(deferred.bounds))
def _recover_corridor(self, state: _RoutingState, net_id: str) -> Corridor | None:
deferred = state.deferred_corridors.pop(net_id)
if self._expired(state):
return None
alternate = deferred.recover()
if alternate is not None:
first, *rest = state.corridors[net_id]
state.corridors[net_id] = (first, alternate, *rest)[:self.context.options.topology.max_corridors]
return alternate
def _prepare_topology(self, state: _RoutingState, corridors: dict[str, tuple[Corridor, ...]] | None) -> None:
topology = self.context.options.topology
if topology.mode == "bundle":
@ -300,6 +324,7 @@ class PathFinder:
clearance=world.clearance,
bend_radius=min(self.context.options.search.bend_radii, default=0.0),
limit=topology.max_corridors,
deferred=state.deferred_corridors,
)
state.corridors = corridors
before = self.metrics.total_nodes_expanded
@ -329,13 +354,10 @@ class PathFinder:
best_results={},
best_is_indexed=False,
best_review=None,
last_conflict_edge_count=0,
repeated_conflict_count=0,
recent_attempt_work={},
pre_pair_candidate=None,
)
self._materialize_problem_initial_paths(state)
if congestion.max_iterations:
self._materialize_problem_initial_paths(state)
world = self.context.cost_evaluator.collision_engine
search = self.context.options.search
proxy, physical_bend = resolve_bend_geometry(search)
@ -361,6 +383,9 @@ class PathFinder:
return state
if self._expired(state):
return state
if self.context.options.topology.mode in ("guide", "seed") and self._verify_complete_seeds(state):
self.topology_report = TopologyReport()
return state
self._prepare_topology(state, corridors)
if self._expired(state):
return state
@ -379,12 +404,39 @@ class PathFinder:
state.results[net_id] = RoutingResult(net_id, path, reached_target=True, report=report)
return state
def _verify_complete_seeds(self, state: _RoutingState) -> bool:
paths = state.initial_paths
if not paths or len(paths) != len(state.net_specs) or any(
path[-1].end_port != state.net_specs[net_id].target for net_id, path in paths.items()
):
return False
seeded = {net_id: RoutingResult(net_id, path, reached_target=True) for net_id, path in paths.items()}
self._replace_indexed_routes(state, seeded)
results, details, review = self._analyze_results(
state.ordered_net_ids, seeded, capture_component_conflicts=False, count_iteration_metrics=False,
)
if len(review.completed_net_ids) != len(seeded):
self._replace_indexed_routes(state, {})
return False
state.results = results
state.replay_details = details
return True
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 _diagnostics_expired(self, state: _RoutingState) -> bool:
if self.metrics.total_diagnostic_timeout_events:
return True
if time.monotonic() - state.start_time >= state.timeout_s:
self.metrics.total_diagnostic_timeout_events += 1
return True
return False
def _materialize_problem_initial_paths(self, state: _RoutingState) -> None:
if not self.context.problem.initial_paths:
return
@ -434,7 +486,7 @@ class PathFinder:
state.results, details_by_net, review = self._analyze_results(
state.ordered_net_ids,
state.results,
capture_component_conflicts=diagnostics.capture_conflict_trace or diagnostics.capture_pre_pair_frontier_trace,
capture_component_conflicts=diagnostics.capture_conflict_trace,
count_iteration_metrics=False,
)
else:
@ -448,22 +500,54 @@ class PathFinder:
details_by_net=details_by_net,
review=review,
)
if diagnostics.capture_pre_pair_frontier_trace:
self.pre_pair_frontier_trace = self._materialize_pre_pair_frontier_trace(
state,
state.results,
details_by_net,
)
return review
def _update_best_iteration(self, state: _RoutingState, review: _IterationReview) -> bool:
if state.best_review is not None and review.rank >= state.best_review.rank:
if review.rank == state.best_review.rank and review.completed_net_ids == state.best_review.completed_net_ids and not state.timed_out:
self._keep_partial_progress(state)
return False
state.best_results = dict(state.results)
state.best_review = review
state.best_pre_pair_candidate = state.pre_pair_candidate
return True
def _keep_partial_progress(self, state: _RoutingState) -> None:
candidates = [
result for net_id, result in state.results.items()
if result.path and not result.reached_target
and (incumbent := state.best_results.get(net_id)) != result
and (incumbent is None or not incumbent.reached_target)
]
if not candidates:
return
world = self.context.cost_evaluator.collision_engine
reserved = STRtree([shape for result in state.best_results.values() if can_reserve(result) for shape in result.locked_geometry])
def is_clear(result: RoutingResult) -> bool:
return world.verify_path_geometry(result.path).is_valid and not any(
_violates_net_clearance(shape, reserved.geometries[hit], world.clearance)
for shape in result.locked_geometry
for hit in reserved.query(shape, predicate="dwithin", distance=world.clearance)
)
for candidate in candidates:
if self._expired(state):
break
net_id = candidate.net_id
incumbent = state.best_results.get(net_id)
if incumbent and incumbent.path:
target = state.net_specs[net_id].target
if (
_distance_to_terminal(candidate.path[-1].end_port, target) >= _distance_to_terminal(incumbent.path[-1].end_port, target)
and is_clear(incumbent)
):
continue
if is_clear(candidate):
state.best_results[net_id] = candidate
def _restore_best_iteration(self, state: _RoutingState) -> None:
if not state.best_results:
return
@ -490,19 +574,29 @@ class PathFinder:
def _build_frontier_hotspot_bounds(
self,
state: _RoutingState,
net_id: str,
details_by_net: dict[str, PathVerificationDetail],
result: RoutingResult,
detail: PathVerificationDetail | None = None,
) -> tuple[tuple[float, float, float, float], ...]:
result = state.results.get(net_id)
detail = details_by_net.get(net_id)
if result is None or detail is None or not result.path:
if not result.report.dynamic_collision_count or self._diagnostics_expired(state):
return ()
world = self.context.cost_evaluator.collision_engine
if detail is None or not detail.component_conflicts:
with self._scratch_diagnostics():
detail = world.verify_path_details(
result.net_id, result.path,
capture_component_conflicts=True,
include_invalid_dynamic=False,
geometry_report=result.report,
diagnostic_expired=partial(self._diagnostics_expired, state),
)
hotspot_bounds: list[tuple[float, float, float, float]] = []
seen: set[tuple[float, float, float, float]] = set()
margin = max(5.0, self.context.cost_evaluator.collision_engine.clearance * 2.0)
margin = max(5.0, world.clearance * 2.0)
for self_component_index, other_net_id, other_component_index in detail.component_conflicts:
if self._diagnostics_expired(state):
break
other_result = state.results.get(other_net_id)
if other_result is None or not other_result.path:
continue
@ -540,8 +634,8 @@ class PathFinder:
return tuple(hotspot_bounds)
@contextmanager
def _frontier_replay(self, net_id: str, path: tuple[ComponentResult, ...]) -> Iterator[AStarMetrics]:
"""Use scratch counters while replaying a net with its path temporarily removed."""
def _scratch_diagnostics(self) -> Iterator[AStarMetrics]:
"""Isolate the counters of optional geometry checks and frontier replays."""
context = self.context
world = context.cost_evaluator.collision_engine
danger_map = context.cost_evaluator.danger_map
@ -553,16 +647,22 @@ class PathFinder:
if danger_map is not None:
danger_map.metrics = scratch_metrics
yield scratch_metrics
finally:
context.metrics, world.metrics = context_metrics, world_metrics
if danger_map is not None:
danger_map.metrics = danger_metrics
@contextmanager
def _frontier_replay(self, net_id: str, path: tuple[ComponentResult, ...]) -> Iterator[AStarMetrics]:
world = self.context.cost_evaluator.collision_engine
with self._scratch_diagnostics() as scratch_metrics:
world.remove_path(net_id)
try:
yield scratch_metrics
finally:
if path:
self._add_route(net_id, path)
finally:
context.metrics, world.metrics = context_metrics, world_metrics
if danger_map is not None:
danger_map.metrics = danger_metrics
def _capture_single_frontier_trace(
self,
@ -571,7 +671,7 @@ class PathFinder:
result: RoutingResult,
hotspot_bounds: tuple[tuple[float, float, float, float], ...],
) -> NetFrontierTrace:
if not hotspot_bounds:
if not hotspot_bounds or self._diagnostics_expired(state):
return NetFrontierTrace(
net_id=net_id,
hotspot_bounds=(),
@ -592,6 +692,7 @@ class PathFinder:
frontier_trace=collector,
self_collision_check=(net_id in state.needs_self_collision_check),
node_limit=self.context.options.search.node_limit,
expired=partial(self._diagnostics_expired, state),
)
net = state.net_specs[net_id]
@ -673,7 +774,7 @@ class PathFinder:
final_results: dict[str, RoutingResult],
details_by_net: dict[str, PathVerificationDetail],
) -> None:
if not self.context.options.diagnostics.capture_frontier_trace:
if not self.context.options.diagnostics.capture_frontier_trace or self._diagnostics_expired(state):
return
self.frontier_trace = []
@ -683,10 +784,9 @@ class PathFinder:
detail = details_by_net.get(net_id)
if result is None or detail is None or not result.reached_target:
continue
if detail.report.dynamic_collision_count == 0 or not detail.component_conflicts:
continue
hotspot_bounds = self._build_frontier_hotspot_bounds(state, net_id, details_by_net)
hotspot_bounds = self._build_frontier_hotspot_bounds(state, result, detail)
if self._diagnostics_expired(state):
break
if not hotspot_bounds:
continue
@ -752,27 +852,39 @@ class PathFinder:
targets.sort(key=lambda pair: min(order_index[pair[0]], order_index[pair[1]]))
return targets
def _materialize_pre_pair_frontier_trace(
self,
state: _RoutingState,
results: dict[str, RoutingResult],
details_by_net: dict[str, PathVerificationDetail],
) -> PrePairFrontierTraceEntry | None:
candidate = state.pre_pair_candidate
def _capture_pre_pair_frontier_trace(self, state: _RoutingState, restored: dict[str, RoutingResult]) -> None:
if self._diagnostics_expired(state):
return
replay = replace(state, results=restored, replay_details=None)
changed = [net_id for net_id in state.ordered_net_ids if restored.get(net_id) != state.results.get(net_id)]
with self._scratch_diagnostics():
try:
self._replace_indexed_routes(replay, restored, net_ids=changed)
self.pre_pair_frontier_trace = self._materialize_pre_pair_frontier_trace(replay)
finally:
self._replace_indexed_routes(replay, state.results, net_ids=changed)
def _materialize_pre_pair_frontier_trace(self, state: _RoutingState) -> PrePairFrontierTraceEntry | None:
candidate = state.best_pre_pair_candidate
if candidate is None:
return None
result_by_net = dict(results)
detail_by_net = dict(details_by_net)
nets: list[PrePairNetTrace] = []
attempt_by_net = {attempt.net_id: attempt for attempt in candidate.net_attempts}
for net_id in candidate.routed_net_ids:
attempt = attempt_by_net.get(net_id)
result = result_by_net.get(net_id)
detail = detail_by_net.get(net_id)
if attempt is None or result is None or detail is None or not result.reached_target:
conflict_net_ids = {net_id for edge in candidate.conflict_edges for net_id in edge}
net_ids = dict.fromkeys((*candidate.routed_net_ids, *sorted(conflict_net_ids)))
for net_id in net_ids:
if self._diagnostics_expired(state):
break
result = state.results.get(net_id)
if result is None or not result.reached_target or not result.path:
continue
hotspot_bounds = self._build_frontier_hotspot_bounds(state, net_id, detail_by_net)
attempt = attempt_by_net.get(net_id)
if attempt is None:
attempt = net_attempt_trace(net_id, dict.fromkeys(_ATTEMPT_TRACE_TOTALS, 0), reached_target=True, guidance_seed_present=False)
hotspot_bounds = self._build_frontier_hotspot_bounds(state, result)
if self._diagnostics_expired(state):
break
nets.append(
PrePairNetTrace(
net_id=net_id,
@ -800,24 +912,15 @@ class PathFinder:
state: _RoutingState,
*,
iteration: int,
reroute_net_ids: set[str],
routed_net_ids: list[str],
attempt_traces: list[IterationNetAttemptTrace],
review: _IterationReview,
) -> None:
if (
len(reroute_net_ids) < len(state.ordered_net_ids)
and review.conflict_edges
and all_results_reached_target(state.ordered_net_ids, state.results)
):
state.pre_pair_candidate = _PrePairCandidate(
iteration=iteration,
routed_net_ids=tuple(routed_net_ids),
conflict_edges=tuple(sorted(review.conflict_edges)),
net_attempts=tuple(attempt_traces),
)
return
state.pre_pair_candidate = None
state.pre_pair_candidate = _PrePairCandidate(
iteration=iteration,
routed_net_ids=tuple(attempt.net_id for attempt in attempt_traces),
conflict_edges=tuple(sorted(review.conflict_edges)),
net_attempts=tuple(attempt_traces),
) if review.conflict_edges else None
def _apply_pair_local_candidate(
self,
@ -861,7 +964,7 @@ class PathFinder:
if self._expired(state):
break
self.metrics.total_pair_local_search_attempts += 1
candidate = search_pair_candidate(
replacements, nodes_expanded = search_pair_candidate(
self.context,
ordered_nets,
incumbent_results,
@ -869,10 +972,10 @@ class PathFinder:
needs_self_collision_check=state.needs_self_collision_check,
expired=partial(self._expired, state),
)
if candidate is None:
continue
replacements, nodes_expanded = candidate
self.metrics.total_pair_local_search_nodes_expanded += nodes_expanded
self.metrics.total_nodes_expanded += nodes_expanded
if replacements is None:
continue
accepted, next_review = self._apply_pair_local_candidate(
state,
replacements,
@ -911,6 +1014,10 @@ class PathFinder:
world = self.context.cost_evaluator.collision_engine
net = state.net_specs[net_id]
self.metrics.total_nets_routed += 1
if iteration == 0 and state.replay_details is not None:
self.metrics.total_warm_start_paths_used += 1
self.metrics.total_nets_reached_target += 1
return state.results[net_id], False
if node_limit_override is not None:
self.metrics.total_late_phase_capped_nets += 1
world.remove_path(net_id)
@ -952,7 +1059,9 @@ class PathFinder:
if node_limit_override is not None and can_reserve(incumbent_fallback):
return self._restore_incumbent_fallback(net_id, incumbent_fallback, guidance_seed_present)
alternate = self._recover_corridor(state, net_id) if iteration and self._shared_guide_blocked(state, net_id) else None
corridors = state.corridors.get(net_id, ())
corridor = alternate if alternate is not None else (corridors[iteration] if iteration < len(corridors) else None)
run_config = SearchRunConfig.from_options(
self.context.options,
bend_collision_type=coll_model,
@ -964,7 +1073,7 @@ class PathFinder:
skip_congestion=skip_congestion,
self_collision_check=(net_id in state.needs_self_collision_check),
node_limit=search.node_limit if node_limit_override is None else node_limit_override,
corridor=corridors[iteration] if iteration < len(corridors) else None,
corridor=corridor,
corridor_strength=self.context.options.topology.guide_strength / (iteration + 1),
hard_congestion=bool(state.corridors) and iteration == 0,
expired=partial(self._expired, state),
@ -1090,8 +1199,6 @@ class PathFinder:
self._update_pre_pair_candidate(
state,
iteration=trace_iteration,
reroute_net_ids=reroute_net_ids,
routed_net_ids=routed_net_ids,
attempt_traces=attempt_traces,
review=review,
)
@ -1109,15 +1216,18 @@ class PathFinder:
def _reverify_iteration_results(self, state: _RoutingState) -> _IterationReview:
diagnostics = self.context.options.diagnostics
replay = self.context.options.search.node_limit == 0 and not state.timed_out
capture_conflicts = diagnostics.capture_conflict_trace or (
replay and (diagnostics.capture_frontier_trace or diagnostics.capture_pre_pair_frontier_trace)
)
state.results, details_by_net, review = self._analyze_results(
state.ordered_net_ids,
state.results,
capture_component_conflicts=capture_conflicts,
count_iteration_metrics=True,
)
details_by_net = state.replay_details
if details_by_net is None:
state.results, details_by_net, review = self._analyze_results(
state.ordered_net_ids,
state.results,
capture_component_conflicts=diagnostics.capture_conflict_trace,
count_iteration_metrics=True,
)
else:
self.metrics.total_iteration_reverify_calls += 1
self.metrics.total_iteration_reverified_nets += len(details_by_net)
review = review_verified_results(state.results, details_by_net)
if replay:
# Replay has one iteration. These details describe the whole indexed layout.
state.replay_details = details_by_net
@ -1162,13 +1272,12 @@ class PathFinder:
reroute_net_ids = next_reroute_net_ids(
state.ordered_net_ids, review, all_reached_target=all_reached, has_corridors=bool(state.corridors)
)
if reached_pair_local_plateau(improved=improved, all_reached_target=all_reached, best_conflict_edges=state.best_conflict_edges):
return False
edge_count = len(review.conflict_edges)
state.repeated_conflict_count = repeated_conflict_count(edge_count, state.last_conflict_edge_count, state.repeated_conflict_count)
state.last_conflict_edge_count = edge_count
if state.repeated_conflict_count >= 2:
if (
not improved and self.context.options.search.node_limit and state.best_review is not None
and 0 < len(state.best_review.conflict_edges) <= 2
and all_results_reached_target(state.ordered_net_ids, state.best_results)
and self._collect_pair_local_targets(state, state.best_results, state.best_review)
):
return False
self.context.congestion_penalty *= congestion.multiplier
return False
@ -1196,12 +1305,13 @@ class PathFinder:
net = state.net_specs[net_id]
self.metrics.total_refine_path_calls += 1
world.remove_path(net_id)
refined_path = tuple(self.refiner.refine_path(net_id, net.start, net.width, result.path))
refined_path = tuple(self.refiner.refine_path(net_id, net.start, net.width, result.path, expired=partial(self._expired, state)))
self._add_route(net_id, refined_path)
report = result.report
if replay and refined_path != result.path:
if refined_path != result.path:
state.replay_details = None
report = world.verify_path_geometry(refined_path)
if replay:
report = world.verify_path_geometry(refined_path)
state.results[net_id] = RoutingResult(
net_id=net_id,
path=refined_path,
@ -1227,11 +1337,10 @@ class PathFinder:
continue
detail = replay_details.get(net.net_id)
if detail is None:
capture_conflicts = diagnostics.capture_conflict_trace or (diagnostics.capture_frontier_trace and result.reached_target)
detail = self.context.cost_evaluator.collision_engine.verify_path_details(
net.net_id,
result.path,
capture_component_conflicts=capture_conflicts,
capture_component_conflicts=diagnostics.capture_conflict_trace,
include_invalid_dynamic=False,
geometry_report=result.report if replay and result.reached_target else None,
)
@ -1281,6 +1390,10 @@ class PathFinder:
state = self._prepare_state(corridors, started_at=started_at)
replay = self.context.options.search.node_limit == 0
timed_out = self._run_iterations(state, None if replay else iteration_callback)
if self.topology_report is not None and state.corridors:
self.topology_report = replace(
self.topology_report, corridor_counts=tuple((net_id, len(candidates)) for net_id, candidates in state.corridors.items()),
)
self.accumulated_expanded_nodes = list(state.accumulated_expanded_nodes)
# A partial iteration can leave the index out of sync with the saved results.
best_is_live = not timed_out and state.best_is_indexed
@ -1288,20 +1401,30 @@ class PathFinder:
self._restore_best_iteration(state)
diagnostics = self.context.options.diagnostics
capture_restored = diagnostics.capture_conflict_trace or diagnostics.capture_pre_pair_frontier_trace
capture_restored = diagnostics.capture_conflict_trace
pre_pair_layout = None
if not timed_out or capture_restored:
review = state.best_review if best_is_live and not capture_restored else None
if review is None:
review = self._review_restored_best(state)
if not timed_out:
if not timed_out and not self._expired(state):
if (
diagnostics.capture_pre_pair_frontier_trace and state.best_pre_pair_candidate is not None
and self._collect_pair_local_targets(state, state.results, review)
):
pre_pair_layout = dict(state.results)
self._run_pair_local_search(state, review)
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)
if not self._expired(state):
self._capture_frontier_trace(state, final_results, details_by_net)
timed_out = timed_out or self._expired(state)
if replay and iteration_callback is not None and not timed_out and self.metrics.total_route_iterations:
iteration_callback(self.iteration_offset, {net_id: final_results[net_id] for net_id in state.ordered_net_ids})
if not timed_out and (pre_pair_layout is not None or diagnostics.capture_frontier_trace):
with phase_timer("verify") if phase_timer is not None else nullcontext():
if pre_pair_layout is not None:
self._capture_pre_pair_frontier_trace(state, pre_pair_layout)
self._capture_frontier_trace(state, final_results, details_by_net)
return final_results

View file

@ -132,19 +132,31 @@ def _disconnected_nets(
for net in residual:
by_width.setdefault(net.width, []).append(net)
disconnected = set()
for width, nets in by_width.items():
def free_regions(width: float) -> tuple[Polygon, ...]:
# Allow the whole board to centerlines, including flush ports. Rounded
# buffers and a small under-dilation keep this test optimistic.
padding = max(0.0, problem.clearance + width / 2 - max(problem.safety_zone_radius, TOLERANCE_LINEAR))
forbidden = shapely.union_all([shape.buffer(padding) for shape in obstacles])
regions = tuple(region for region in shapely.get_parts(board.difference(forbidden)) if region.area > 0)
if len(regions) < 2:
continue
for region in regions:
shapely.prepare(region)
return regions
widest = max(by_width)
shared_regions = free_regions(widest)
disconnected = set()
for width, nets in by_width.items():
if width == widest and len(shared_regions) < 2:
continue
regions = shared_regions if width == widest else None
for net in nets:
start, target = Point(net.start.x, net.start.y), Point(net.target.x, net.target.y)
if width != widest and any(region.covers(start) and region.covers(target) for region in shared_regions):
continue
if regions is None:
regions = free_regions(width)
if len(regions) < 2:
break
start_regions = {idx for idx, region in enumerate(regions) if region.covers(start)}
target_regions = {idx for idx, region in enumerate(regions) if region.covers(target)}
if start_regions and target_regions and start_regions.isdisjoint(target_regions):

View file

@ -30,7 +30,7 @@ class RoutingStack:
def build_routing_stack(problem: RoutingProblem, options: RoutingOptions) -> RoutingStack:
if options.topology.mode == "bundle":
if options.topology.mode == "bundle" and options.congestion.max_iterations:
from inire.router._bundle import plan_ordered_bundle # noqa: PLC0415
problem = plan_ordered_bundle(problem, options.search, infer_terminal_headings=options.topology.infer_terminal_headings)
@ -95,7 +95,7 @@ def route_once(
iteration_callback=callback, phase_timer=phase_timer, corridors=corridors, started_at=started_at, iteration_offset=iteration_offset,
)
results = attach_effective(results)
if options.topology.mode == "bundle":
if options.topology.mode == "bundle" and options.congestion.max_iterations:
for result in results.values():
if not result.is_valid:
raise ValueError(f"Bundle schedule failed geometric verification for {result.net_id}")

View file

@ -3,6 +3,7 @@
from __future__ import annotations
from dataclasses import dataclass, field
from functools import cache, partial
from heapq import heappop, heappush
from itertools import pairwise
from math import hypot, inf
@ -14,9 +15,10 @@ from shapely.geometry import LineString, Point, box
from inire.constants import TOLERANCE_LINEAR
from inire.geometry.collision import _violates_clearance
from inire.geometry.index_helpers import is_axis_aligned_rect
from inire.geometry.primitives import port_local_coordinates
if TYPE_CHECKING:
from collections.abc import Iterable, Sequence
from collections.abc import Callable, Iterable, Sequence
from shapely.geometry import Polygon
from shapely.geometry.base import BaseGeometry
@ -69,6 +71,12 @@ class Corridor:
return sorted(candidates, key=lambda xy: xy[0] + abs(xy[1]))[:4]
@dataclass(frozen=True, slots=True)
class DeferredCorridor:
bounds: tuple[float, float, float, float]
recover: Callable[[], Corridor | None]
@dataclass(frozen=True, slots=True)
class _Portal:
lanes: tuple[XY, ...]
@ -379,6 +387,7 @@ def plan_corridors(
clearance: float,
bend_radius: float,
limit: int,
deferred: dict[str, DeferredCorridor] | None = None,
) -> dict[str, tuple[Corridor, ...]]:
"""Plan clearance-aware corridor guides for the requested nets."""
if not nets:
@ -395,22 +404,70 @@ def plan_corridors(
widest = max(net.width for net in nets)
guides, shared_space = plan_group(nets, widest)
# Keep shared assignments and add routes through passages opened by the narrower margin.
if all(net.width == widest for net in nets) and len(guides) == len(nets):
return guides
pitch = max(1.0, widest + clearance)
turn_room = max(bend_radius, pitch)
def shared_straight(net: NetSpec) -> LineString | None:
forward, side = port_local_coordinates(net.start, net.target.x, net.target.y)
if net.start.r != net.target.r or side or forward <= 0:
return None
direct = LineString(((net.start.x, net.start.y), (net.target.x, net.target.y)))
return direct if shared_space.covers(direct) else None
def shared_guide_space(net: NetSpec) -> tuple[float, float, float, float] | None:
shared = guides.get(net.net_id)
if not shared:
return None
x0, x1 = sorted((net.start.x, net.target.x))
y0, y1 = sorted((net.start.y, net.target.y))
direct = shared_straight(net)
if direct is None:
# Allow room for approaching both port headings in the shared mesh.
# Nets close to a wall or board edge still get width-specific alternatives.
bounds = (x0 - turn_room, y0 - turn_room, x1 + turn_room, y1 + turn_room)
return bounds if shared_space.covers(box(*bounds)) else None
first, *rest = shared
if not first.footprint.covers(direct):
footprint = direct.buffer(pitch + net.width / 2).intersection(board)
shapely.prepare(footprint)
guides[net.net_id] = (first, Corridor(direct, footprint, turn_room), *rest)[:limit]
gap = net.width / 2 + clearance
return (x0 - gap, y0 - gap, x1 + gap, y1 + gap)
by_width: dict[float, list[NetSpec]] = {}
for net in nets:
by_width.setdefault(net.width, []).append(net)
@cache
def width_guides(width: float) -> dict[str, tuple[Corridor, ...]]:
return plan_group(by_width[width], width)[0]
def narrower_alternate(net_id: str, width: float) -> Corridor | None:
return next(
(c for c in width_guides(width).get(net_id, ()) if c.centerline.difference(shared_space).length > widest + 2 * clearance),
None,
)
# Keep shared assignments and add routes through passages opened by the narrower margin.
shapely.prepare(shared_space)
for width, group in by_width.items():
if width < widest:
narrow, _ = plan_group(group, width)
for net_id, corridors in narrow.items():
if net_id not in guides:
guides[net_id] = corridors
for net in group:
net_id = net.net_id
if limit == 1 and net_id in guides:
continue
alternate = next(
(c for c in corridors if c.centerline.difference(shared_space).length > widest + 2 * clearance),
None,
)
if alternate is not None:
if (shared_bounds := shared_guide_space(net)) is not None:
if deferred is not None:
deferred[net_id] = DeferredCorridor(shared_bounds, partial(narrower_alternate, net_id, width))
continue
if net_id not in guides:
if corridors := width_guides(width).get(net_id):
guides[net_id] = corridors
continue
if alternate := narrower_alternate(net_id, width):
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]

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