diff --git a/README.md b/README.md
index db8e725..c609e27 100644
--- a/README.md
+++ b/README.md
@@ -31,22 +31,22 @@ else:
print(result.outcome)
```
-
+
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).
diff --git a/archive/routing/README.md b/archive/routing/README.md
index e72197d..9d3009d 100644
--- a/archive/routing/README.md
+++ b/archive/routing/README.md
@@ -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.
diff --git a/archive/routing/routing-refactor-plan.md b/archive/routing/routing-refactor-plan.md
index 5764183..26c1c5b 100644
--- a/archive/routing/routing-refactor-plan.md
+++ b/archive/routing/routing-refactor-plan.md
@@ -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)
diff --git a/docs/architecture.md b/docs/architecture.md
index fb6925c..4f3b083 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -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
diff --git a/docs/benchmark-fixtures.md b/docs/benchmark-fixtures.md
index 95c27cf..ed24852 100644
--- a/docs/benchmark-fixtures.md
+++ b/docs/benchmark-fixtures.md
@@ -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`.
diff --git a/docs/routing-diagnostics.md b/docs/routing-diagnostics.md
index db8ff2f..8b87785 100644
--- a/docs/routing-diagnostics.md
+++ b/docs/routing-diagnostics.md
@@ -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). |
diff --git a/docs/topological-routing.md b/docs/topological-routing.md
index 321a2ee..3e505d5 100644
--- a/docs/topological-routing.md
+++ b/docs/topological-routing.md
@@ -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 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).
diff --git a/docs/user/tune-and-troubleshoot.md b/docs/user/tune-and-troubleshoot.md
index a4d04ea..cdce9dd 100644
--- a/docs/user/tune-and-troubleshoot.md
+++ b/docs/user/tune-and-troubleshoot.md
@@ -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
diff --git a/inire/__init__.py b/inire/__init__.py
index 2911e17..ccef84e 100644
--- a/inire/__init__.py
+++ b/inire/__init__.py
@@ -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,
diff --git a/inire/geometry/collision.py b/inire/geometry/collision.py
index 33a1e8b..b7681f0 100644
--- a/inire/geometry/collision.py
+++ b/inire/geometry/collision.py
@@ -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):
diff --git a/inire/geometry/components.py b/inire/geometry/components.py
index 662643b..5c6b1e4 100644
--- a/inire/geometry/components.py
+++ b/inire/geometry/components.py
@@ -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
+ ),
)
diff --git a/inire/geometry/static_obstacle_index.py b/inire/geometry/static_obstacle_index.py
index 99fd153..2585d17 100644
--- a/inire/geometry/static_obstacle_index.py
+++ b/inire/geometry/static_obstacle_index.py
@@ -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:
diff --git a/inire/results.py b/inire/results.py
index 9e2cc47..3446b5e 100644
--- a/inire/results.py
+++ b/inire/results.py
@@ -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:
diff --git a/inire/router/_astar_admission.py b/inire/router/_astar_admission.py
index 463f6bd..c782cb6 100644
--- a/inire/router/_astar_admission.py
+++ b/inire/router/_astar_admission.py
@@ -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:
diff --git a/inire/router/_congestion_policy.py b/inire/router/_congestion_policy.py
index cf8c9f1..835e4f1 100644
--- a/inire/router/_congestion_policy.py
+++ b/inire/router/_congestion_policy.py
@@ -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
diff --git a/inire/router/_pair_local.py b/inire/router/_pair_local.py
index 74650a5..a6e1e6a 100644
--- a/inire/router/_pair_local.py
+++ b/inire/router/_pair_local.py
@@ -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:
diff --git a/inire/router/_router.py b/inire/router/_router.py
index 4c394f1..94bddbb 100644
--- a/inire/router/_router.py
+++ b/inire/router/_router.py
@@ -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
diff --git a/inire/router/_routing_policy.py b/inire/router/_routing_policy.py
index e05865b..2459584 100644
--- a/inire/router/_routing_policy.py
+++ b/inire/router/_routing_policy.py
@@ -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):
diff --git a/inire/router/_stack.py b/inire/router/_stack.py
index e5ec67b..4463f54 100644
--- a/inire/router/_stack.py
+++ b/inire/router/_stack.py
@@ -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}")
diff --git a/inire/router/_topology.py b/inire/router/_topology.py
index 663f5c9..48d6867 100644
--- a/inire/router/_topology.py
+++ b/inire/router/_topology.py
@@ -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]
diff --git a/inire/router/refiner.py b/inire/router/refiner.py
index 761ff5d..87ea5b1 100644
--- a/inire/router/refiner.py
+++ b/inire/router/refiner.py
@@ -19,7 +19,7 @@ from inire.geometry.primitives import port_local_coordinates
from inire.model import resolve_bend_geometry
if TYPE_CHECKING:
- from collections.abc import Iterator, Sequence
+ from collections.abc import Callable, Iterator, Sequence
from inire.geometry.collision import RoutingWorld
from inire.geometry.components import ComponentResult, MoveKind
@@ -360,6 +360,8 @@ class PathRefiner:
end_idx: int,
best_cost: float,
incumbent_valid: bool,
+ *,
+ expired: Callable[[], bool] | None = None,
) -> tuple[list[ComponentResult], float] | None:
ports = self._path_ports(start, path)
window_start = ports[start_idx]
@@ -377,10 +379,14 @@ class PathRefiner:
custom_danger_map = self.context.cost_evaluator.danger_map if isinstance(physical, Polygon) else None
components: dict[tuple[Port, MoveKind, tuple], ComponentResult] = {}
for radius in search.bend_radii:
+ if expired is not None and expired():
+ break
if circular_bend and not bend_fits_width(radius, net_width):
continue
side_extents = self._candidate_side_extents(window_start, window_end, window_path, net_width, radius)
for side_extent in dict.fromkeys(map(round, side_extents)):
+ if expired is not None and expired():
+ return (best_path, best_candidate_cost) if best_path is not None else None
moves = self._dogleg_moves(window_start, window_end, radius, side_extent)
if moves is None:
continue
@@ -426,8 +432,10 @@ class PathRefiner:
start: Port,
net_width: float,
path: Sequence[ComponentResult],
+ *,
+ expired: Callable[[], bool] | None = None,
) -> list[ComponentResult]:
- if not self.has_refinement_bends(path):
+ if not self.has_refinement_bends(path) or (expired is not None and expired()):
return list(path)
best_path = list(path)
@@ -438,12 +446,16 @@ class PathRefiner:
for _ in range(3):
improved = False
for start_idx, end_idx in self._iter_refinement_windows(start, best_path):
+ if expired is not None and expired():
+ return best_path
if incumbent_valid is None:
incumbent_valid = self.collision_engine.verify_path_report(net_id, best_path).is_valid
if remaining is not None:
remaining -= 1
self.context.metrics.total_refinement_windows_considered += 1
- refined = self._try_refine_window(net_id, start, net_width, best_path, start_idx, end_idx, best_cost, incumbent_valid)
+ refined = self._try_refine_window(
+ net_id, start, net_width, best_path, start_idx, end_idx, best_cost, incumbent_valid, expired=expired,
+ )
if refined is not None:
best_path, best_cost = refined
incumbent_valid = True
diff --git a/inire/router/visibility.py b/inire/router/visibility.py
index 3cd1ca4..9744706 100644
--- a/inire/router/visibility.py
+++ b/inire/router/visibility.py
@@ -67,7 +67,8 @@ class VisibilityManager:
return
seen = set()
- for x, y in raw_corners:
+ for point in raw_corners:
+ x, y = point[0], point[1]
sx, sy = round(x, 3), round(y, 3)
if (sx, sy) not in seen:
seen.add((sx, sy))
diff --git a/inire/tests/example_scenarios.py b/inire/tests/example_scenarios.py
index aa94f4d..692dcd9 100644
--- a/inire/tests/example_scenarios.py
+++ b/inire/tests/example_scenarios.py
@@ -28,7 +28,7 @@ from inire.tests.routing_corpus import SNAPSHOT_CASES, profile_options
from inire.tests.terminal_bench_scenario import terminal_bench_options, terminal_bench_problem
if TYPE_CHECKING:
- from collections.abc import Iterable
+ from collections.abc import Collection, Iterable
from inire.router._astar_types import AStarMetrics
from inire.router._router import PathFinder
@@ -498,9 +498,19 @@ def capture_scenario_snapshots(
selected_scenarios: Iterable[str] | None = None,
*,
include_performance_only: bool = False,
+ baseline_scenarios: Collection[str] = (),
) -> tuple[ScenarioSnapshot, ...]:
+ allowed = None if selected_scenarios is None else set(selected_scenarios)
+ if allowed is not None:
+ regular = dict(SCENARIO_SNAPSHOTS)
+ performance_only = dict(PERFORMANCE_SCENARIO_SNAPSHOTS)
+ unknown = allowed.difference(regular, performance_only, baseline_scenarios)
+ if unknown:
+ raise ValueError(f"Unknown performance scenario(s): {', '.join(sorted(unknown))}")
+ disabled = allowed.intersection(performance_only).difference(regular)
+ if disabled and not include_performance_only:
+ raise ValueError(f"Scenario(s) require --include-performance-only: {', '.join(sorted(disabled))}")
registry = SCENARIO_SNAPSHOTS
if include_performance_only:
registry += PERFORMANCE_SCENARIO_SNAPSHOTS
- allowed = None if selected_scenarios is None else set(selected_scenarios)
return tuple(capture() for name, capture in registry if allowed is None or name in allowed)
diff --git a/inire/tests/routing_expanded_benchmarks.py b/inire/tests/routing_expanded_benchmarks.py
index 6337859..39d4c9e 100644
--- a/inire/tests/routing_expanded_benchmarks.py
+++ b/inire/tests/routing_expanded_benchmarks.py
@@ -71,7 +71,7 @@ def _on_grid(case: BenchmarkCase, grid_nm: int) -> BenchmarkCase:
objective=replace(
options.objective,
bend_penalty=options.objective.bend_penalty * factor**1.5,
- sbend_penalty=options.objective.sbend_penalty * factor**1.5,
+ sbend_penalty=options.objective.sbend_penalty * factor,
),
congestion=replace(options.congestion, base_penalty=options.congestion.base_penalty * factor),
)
diff --git a/inire/tests/routing_external_benchmarks.py b/inire/tests/routing_external_benchmarks.py
index 77ae861..5028b0d 100644
--- a/inire/tests/routing_external_benchmarks.py
+++ b/inire/tests/routing_external_benchmarks.py
@@ -13,7 +13,9 @@ from inire.tests.routing_benchmark_case import BenchmarkCase, benchmark_options
def _external_benchmarks() -> tuple[BenchmarkCase, ...]:
fixture = Path(__file__).with_name("data") / "external_routing_benchmarks.json"
cases = []
- for row in loads(fixture.read_text(encoding="utf-8"))["cases"]:
+ payload = loads(fixture.read_text(encoding="utf-8"))
+ grid_nm = 1000 // payload["units_per_micron"]
+ for row in payload["cases"]:
problem = RoutingProblem(
tuple(row["bounds"]),
tuple(NetSpec(net["id"], Port(*net["start"]), Port(*net["target"]), width=net["width"]) for net in row["nets"]),
@@ -32,6 +34,7 @@ def _external_benchmarks() -> tuple[BenchmarkCase, ...]:
problem,
options,
expected_routed=row.get("expected_routed"),
+ grid_nm=grid_nm,
))
return tuple(cases)
diff --git a/inire/tests/test_api.py b/inire/tests/test_api.py
index 6cbb8a1..c9affbc 100644
--- a/inire/tests/test_api.py
+++ b/inire/tests/test_api.py
@@ -35,7 +35,7 @@ from inire.geometry.collision import RoutingWorld
from inire.results import ComponentConflictTrace, RoutingReport, RoutingResult
from inire.router._astar_types import AStarContext
from inire.router._router import PathFinder, _IterationReview
-from inire.router._stack import RoutingAttempts
+from inire.router._stack import RoutingAttempts, build_routing_stack
from inire.router.cost import CostEvaluator
from inire.router.danger_map import DangerMap
@@ -956,7 +956,7 @@ def test_default_router_escalates_only_within_the_configured_node_limit(monkeypa
assert run.results_by_net["turn"].is_valid == (ceiling > 500)
-def test_capture_frontier_trace_preserves_route_outputs() -> None:
+def test_capture_frontier_trace_preserves_route_outputs(monkeypatch: pytest.MonkeyPatch) -> None:
problem = RoutingProblem(
bounds=(0, 0, 100, 100),
nets=(
@@ -981,6 +981,117 @@ def test_capture_frontier_trace_preserves_route_outputs() -> None:
assert {trace.net_id for trace in run_with_trace.frontier_trace} == {"horizontal", "vertical"}
assert run_with_trace.metrics.verify_path_report_calls == run_without_trace.metrics.verify_path_report_calls
+ search = replace(base_options.search, node_limit=60, bend_radii=(), sbend_radii=())
+ options = replace(base_options, search=search, diagnostics=DiagnosticsOptions(capture_frontier_trace=True))
+ control = route(problem, options=options)
+ clock = [0.0]
+ monkeypatch.setattr(router_module.time, "monotonic", lambda: clock[0])
+ route_astar = router_module.route_astar
+ diagnostic_work = []
+
+ def expire_in_frontier(*args, config, metrics, **kwargs):
+ if config.frontier_trace is None:
+ return route_astar(*args, config=config, metrics=metrics, **kwargs)
+ clock[0] = 61.0
+ path = route_astar(*args, config=config, metrics=metrics, **kwargs)
+ diagnostic_work.append(metrics.total_nodes_expanded)
+ return path
+
+ monkeypatch.setattr(router_module, "route_astar", expire_in_frontier)
+ expired = route(problem, options=options)
+ assert diagnostic_work == [0]
+ assert expired.metrics.timeout_events == 0
+ assert expired.metrics.diagnostic_timeout_events == 1
+ assert expired.metrics.nodes_expanded == control.metrics.nodes_expanded
+ assert expired.results_by_net == control.results_by_net
+
+ clock[0] = 0.0
+ callback_times = []
+ detail_calls = []
+ verify_details = RoutingWorld.verify_path_details
+
+ def expire_during_component_details(self, net_id, path, **kwargs):
+ if kwargs.get("capture_component_conflicts"):
+ detail_calls.append(net_id)
+ clock[0] = 61.0
+ return verify_details(self, net_id, path, **kwargs)
+
+ monkeypatch.setattr(RoutingWorld, "verify_path_details", expire_during_component_details)
+ replay = route(
+ problem, options=replace(options, search=base_options.search),
+ iteration_callback=lambda index, _: callback_times.append((index, clock[0])),
+ )
+ assert callback_times == [(0, 0.0)]
+ assert len(detail_calls) == 1
+ assert replay.metrics.timeout_events == 0
+ assert replay.metrics.diagnostic_timeout_events == 1
+ assert replay.results_by_net == run_without_trace.results_by_net
+
+
+def test_pre_pair_trace_uses_restored_layout_after_repair(monkeypatch: pytest.MonkeyPatch) -> None:
+ nets = (
+ NetSpec("horizontal", Port(40, 100, 0), Port(160, 100, 0)),
+ NetSpec("vertical", Port(100, 40, 90), Port(100, 160, 90)),
+ )
+ seeds = {net.net_id: PathSeed((StraightSeed(120),)) for net in nets}
+ problem = RoutingProblem((0, 0, 200, 200), nets, clearance=1, initial_paths=seeds)
+ options = RoutingOptions(
+ search=SearchOptions(node_limit=3000, bend_radii=(10,), sbend_radii=()),
+ objective=ObjectiveWeights(danger_weight=0),
+ congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False),
+ refinement=RefinementOptions(enabled=False),
+ topology=TopologyOptions(mode="off"),
+ )
+ control = route(problem, options=options)
+ assert all(result.is_valid for result in control.results_by_net.values())
+ assert control.metrics.pair_local_search_accepts == 1
+ clock = [0.0]
+ monkeypatch.setattr(router_module.time, "monotonic", lambda: clock[0])
+ capture = PathFinder._capture_single_frontier_trace
+ replayed = []
+
+ def expire_in_pre_pair(self, state, net_id, result, hotspot_bounds):
+ if hotspot_bounds:
+ assert self.metrics.total_pair_local_search_accepts == 1
+ assert result.as_seed() == seeds[net_id]
+ assert all(state.results[key].as_seed() == seed for key, seed in seeds.items())
+ replayed.append(net_id)
+ clock[0] = 61.0
+ return capture(self, state, net_id, result, hotspot_bounds)
+
+ monkeypatch.setattr(PathFinder, "_capture_single_frontier_trace", expire_in_pre_pair)
+ traced = replace(options, diagnostics=DiagnosticsOptions(capture_pre_pair_frontier_trace=True))
+ stack = build_routing_stack(problem, traced)
+ results = stack.finder.route_all()
+ metrics = stack.finder.metrics.snapshot()
+ assert len(replayed) == 1
+ assert results == control.results_by_net
+ assert metrics.nodes_expanded == control.metrics.nodes_expanded
+ assert metrics.pair_local_search_attempts == control.metrics.pair_local_search_attempts
+ assert metrics.dynamic_path_objects_added == control.metrics.dynamic_path_objects_added
+ assert metrics.dynamic_path_objects_removed == control.metrics.dynamic_path_objects_removed
+ assert metrics.timeout_events == 0
+ assert metrics.diagnostic_timeout_events == 1
+ assert all(stack.world.verify_path_report(key, result.path).is_valid for key, result in results.items())
+
+ clock[0] = 0.0
+ verified = []
+ verify_details = RoutingWorld.verify_path_details
+
+ def expire_during_pre_pair_details(self, net_id, path, **kwargs):
+ if kwargs.get("capture_component_conflicts"):
+ verified.append(net_id)
+ clock[0] = 61.0
+ return verify_details(self, net_id, path, **kwargs)
+
+ monkeypatch.setattr(RoutingWorld, "verify_path_details", expire_during_pre_pair_details)
+ expired = route(problem, options=traced)
+ assert len(verified) == 1
+ assert len(replayed) == 1
+ assert expired.results_by_net == control.results_by_net
+ assert expired.metrics.timeout_events == 0
+ assert expired.metrics.diagnostic_timeout_events == 1
+
def test_reverify_iterations_limit_late_reroutes_to_conflicting_nets(monkeypatch: pytest.MonkeyPatch) -> None:
problem = RoutingProblem(
@@ -1097,8 +1208,8 @@ def test_rejected_pair_keeps_original_index_for_reverse_attempt(monkeypatch) ->
attempted.append(pair_order)
assert sorted(world.iter_dynamic_path_bounds(problem.bounds)) == initial_bounds
if pair_order == ("a", "b"):
- return {"a": RoutingResult("a", incumbent["b"].path, reached_target=True), "b": incumbent["b"]}, 0
- return None
+ return {"a": RoutingResult("a", incumbent["b"].path, reached_target=True), "b": incumbent["b"]}, 3
+ return None, 5
monkeypatch.setattr(router_module, "search_pair_candidate", search)
assert finder._run_pair_local_target(state, ("a", "b"), review) is review
@@ -1108,6 +1219,7 @@ def test_rejected_pair_keeps_original_index_for_reverse_attempt(monkeypatch) ->
assert sorted(world.iter_dynamic_path_bounds(problem.bounds)) == initial_bounds
assert all(world.verify_path_report(net_id, result.path) == result.report for net_id, result in incumbent.items())
metrics = finder.metrics.snapshot()
+ assert metrics.nodes_expanded == metrics.pair_local_search_nodes_expanded == 8
assert metrics.dynamic_path_objects_added == 7
assert metrics.dynamic_path_objects_removed == 4
@@ -1157,6 +1269,28 @@ def test_route_all_restores_best_iteration_snapshot_on_timeout(monkeypatch: pyte
assert evaluator.collision_engine.has_dynamic_paths()
+def test_equal_rank_keeps_clear_partial_progress_and_completed_geometry() -> None:
+ problem = RoutingProblem(
+ (0, 0, 100, 100),
+ (NetSpec("line", Port(10, 25, 0), Port(90, 25, 0)), NetSpec("peer", Port(50, 15, 90), Port(50, 40, 90))),
+ (box(70, 24, 72, 26),),
+ )
+ finder = build_routing_stack(problem, RoutingOptions(topology=TopologyOptions(mode="off"))).finder
+ state = finder._prepare_state()
+ peer = RoutingResult("peer", (Straight.generate(problem.nets[1].start, 25, 2),), reached_target=True)
+ review = _IterationReview(set(), set(), {"peer"}, 0)
+ state.results = {"peer": peer, "line": RoutingResult("line", ())}
+ assert finder._update_best_iteration(state, review)
+ for length, saved_length in ((20, 20), (30, 30), (45, 30), (70, 30), (10, 30)):
+ state.results = {
+ "peer": replace(peer, path=(Straight.generate(Port(85, 15, 90), 25, 2),)),
+ "line": RoutingResult("line", (Straight.generate(problem.nets[0].start, length, 2),)),
+ }
+ assert not finder._update_best_iteration(state, review)
+ assert state.best_results["line"].path[-1].length == saved_length
+ assert state.best_results["peer"] is peer
+
+
def test_iteration_prefers_shorter_paths_at_equal_coverage() -> None:
problem = RoutingProblem(bounds=(0, 0, 100, 100))
options = RoutingOptions(topology=TopologyOptions(mode="off"))
diff --git a/inire/tests/test_collision.py b/inire/tests/test_collision.py
index 8569235..bc98869 100644
--- a/inire/tests/test_collision.py
+++ b/inire/tests/test_collision.py
@@ -7,7 +7,7 @@ from shapely.geometry import Polygon, box
import inire.geometry.component_overlap as overlap_module
from inire.geometry.collision import RoutingWorld
-from inire.geometry.components import ComponentResult
+from inire.geometry.components import Bend90, ComponentResult
from inire.geometry.components import Straight
from inire.geometry.primitives import Port
from inire.model import RoutingProblem
@@ -329,3 +329,16 @@ def test_move_admission_rejects_keepout_overlap_near_an_endpoint() -> None:
assert engine.terminal_issue(move.start_port, 2) is None
assert engine.check_move_static(move)
assert engine.verify_path_report("line", (move,)).static_collision_count == 1
+
+
+def test_bend_admission_checks_the_outline_outside_the_proxy() -> None:
+ for proxy, margin in (("arc", None), ("clipped_bbox", 5), (box(0, -1, 1, 0), None)):
+ bend = Bend90.generate(Port(0, 0, 0), 10, 2, "CCW", collision_type=proxy, clip_margin=margin).translate(70, 20)
+ world = RoutingWorld(clearance=1)
+ hit = world.add_static_obstacle(box(77.3, 22.3, 77.7, 22.7))
+ assert world.check_move_static(bend)
+ assert world.verify_path_report("bend", (bend,)).static_collision_count == 1
+ world.remove_static_obstacle(hit)
+ world.add_static_obstacle(box(82, 27, 84, 32))
+ assert not world.check_move_static(bend)
+ assert world.verify_path_report("bend", (bend,)).is_valid
diff --git a/inire/tests/test_congestion_policy.py b/inire/tests/test_congestion_policy.py
index 71b8d3a..6eb6752 100644
--- a/inire/tests/test_congestion_policy.py
+++ b/inire/tests/test_congestion_policy.py
@@ -6,8 +6,6 @@ from inire.router._congestion_policy import (
IterationReview,
next_reroute_net_ids,
ordered_nets,
- reached_pair_local_plateau,
- repeated_conflict_count,
reroute_plan,
)
@@ -56,12 +54,3 @@ def test_next_reroute_nets_respect_reached_targets_and_corridors() -> None:
assert next_reroute_net_ids(ordered, review, all_reached_target=True, has_corridors=False) == {"a", "b", "c"}
assert next_reroute_net_ids(ordered, review, all_reached_target=False, has_corridors=True) == {"a", "b", "c"}
assert next_reroute_net_ids(ordered, review, all_reached_target=False, has_corridors=False) == set(ordered)
-
-
-def test_stopping_rules_track_plateau_and_repeated_conflict_count() -> None:
- assert reached_pair_local_plateau(improved=False, all_reached_target=True, best_conflict_edges=2)
- assert not reached_pair_local_plateau(improved=True, all_reached_target=True, best_conflict_edges=2)
- assert not reached_pair_local_plateau(improved=False, all_reached_target=True, best_conflict_edges=3)
- assert repeated_conflict_count(2, 2, 1) == 2
- assert repeated_conflict_count(3, 2, 1) == 0
- assert repeated_conflict_count(0, 0, 1) == 0
diff --git a/inire/tests/test_example_performance.py b/inire/tests/test_example_performance.py
index eed1355..0c1982b 100644
--- a/inire/tests/test_example_performance.py
+++ b/inire/tests/test_example_performance.py
@@ -70,7 +70,7 @@ def test_example_07_no_warm_start_outcome_and_optional_runtime() -> None:
assert snapshot.metrics.warm_start_paths_used == 0
assert snapshot.metrics.pair_local_search_pairs_considered >= 1
assert snapshot.metrics.pair_local_search_accepts >= 1
- assert snapshot.metrics.pair_local_search_nodes_expanded <= 128
+ assert 0 < snapshot.metrics.pair_local_search_nodes_expanded <= 750
assert snapshot.metrics.nodes_expanded <= 2500
assert snapshot.metrics.congestion_check_calls <= 6000
if RUN_PERFORMANCE:
diff --git a/inire/tests/test_example_regressions.py b/inire/tests/test_example_regressions.py
index 30c768a..2b60419 100644
--- a/inire/tests/test_example_regressions.py
+++ b/inire/tests/test_example_regressions.py
@@ -22,6 +22,13 @@ def test_example_07_no_warm_start_trace_finishes_without_conflict_edges(example_
assert run.metrics.pair_local_search_pairs_considered >= 1
assert run.metrics.pair_local_search_accepts >= 1
assert run.pre_pair_frontier_trace is not None
+ restored = next(entry for entry in run.conflict_trace if entry.stage == "restored_best")
+ pre_pair = run.pre_pair_frontier_trace
+ attempt = next(entry for entry in run.iteration_trace if entry.iteration == pre_pair.iteration)
+ assert pre_pair.conflict_edges == restored.conflict_edges
+ assert pre_pair.routed_net_ids == attempt.routed_net_ids
+ work = {net.net_id: net.nodes_expanded for net in attempt.net_attempts}
+ assert all(net.nodes_expanded == work.get(net.net_id, 0) for net in pre_pair.nets)
final_entry = run.conflict_trace[-1]
assert final_entry.stage == "final"
diff --git a/inire/tests/test_performance_reporting.py b/inire/tests/test_performance_reporting.py
index 0e74b93..79049c5 100644
--- a/inire/tests/test_performance_reporting.py
+++ b/inire/tests/test_performance_reporting.py
@@ -31,6 +31,20 @@ def test_performance_baseline_can_be_recorded_and_diffed_with_an_added_scenario(
assert [entry["name"] for entry in payload["scenarios"]] == ["example_01_simple_route"]
assert (tmp_path / "performance.md").exists()
+ retired = "example_retired"
+ baseline_path = tmp_path / "performance_baseline.json"
+ payload["scenarios"].append({**payload["scenarios"][0], "name": retired})
+ baseline_path.write_text(json.dumps(payload))
+ saved_files = {path: path.read_bytes() for path in tmp_path.iterdir()}
+ invalid = subprocess.run(
+ [sys.executable, str(script_path), "--output-dir", str(tmp_path),
+ "--scenario", "example_01_simple_route", "--scenario", "example_01_simple_rote"],
+ capture_output=True, text=True, check=False,
+ )
+ assert invalid.returncode == 2
+ assert "Unknown performance scenario(s): example_01_simple_rote" in invalid.stderr
+ assert {path: path.read_bytes() for path in tmp_path.iterdir()} == saved_files
+
output = tmp_path / "diff.md"
log = tmp_path / "optimization.md"
subprocess.run(
@@ -44,6 +58,8 @@ def test_performance_baseline_can_be_recorded_and_diffed_with_an_added_scenario(
"example_01_simple_route",
"--scenario",
"example_07_large_scale_routing_no_warm_start",
+ "--scenario",
+ retired,
"--metric",
"duration_s",
"--metric",
@@ -67,6 +83,7 @@ def test_performance_baseline_can_be_recorded_and_diffed_with_an_added_scenario(
assert "| example_01_simple_route | visibility_corner_index_builds |" in report
assert "| example_07_large_scale_routing_no_warm_start | duration_s | - |" in report
assert "| example_07_large_scale_routing_no_warm_start | nodes_expanded | - |" in report
+ assert f"| {retired} | missing | - | - | - |" in report
entry = log.read_text()
assert "Step 0 - Baseline" in entry
assert "Tooling smoke test." in entry
diff --git a/inire/tests/test_refinements.py b/inire/tests/test_refinements.py
index 7fa3cbb..b851d36 100644
--- a/inire/tests/test_refinements.py
+++ b/inire/tests/test_refinements.py
@@ -3,6 +3,7 @@ from dataclasses import replace
import pytest
from shapely.geometry import Polygon, box
+from inire.router import _router
from inire import CongestionOptions, ObjectiveWeights, RefinementOptions, RoutingOptions, RoutingProblem, SearchOptions, TopologyOptions, route
from inire import DiagnosticsOptions, PathSeed, StraightSeed
from inire.geometry.collision import RoutingWorld
@@ -74,6 +75,26 @@ def test_refinement_handles_both_signs_of_the_lateral_offset() -> None:
assert paths[0].report.total_length == pytest.approx(paths[1].report.total_length)
+def test_refinement_stops_between_candidates_when_worker_expires(monkeypatch: pytest.MonkeyPatch) -> None:
+ clock = [0.0]
+ monkeypatch.setattr(_router.time, "monotonic", lambda: clock[0])
+ dogleg_moves = _router.PathRefiner._dogleg_moves
+ candidates = []
+
+ def expire_at_first_candidate(*args, **kwargs):
+ candidates.append(clock[0])
+ clock[0] = 61.0
+ return dogleg_moves(*args, **kwargs)
+
+ monkeypatch.setattr(_router.PathRefiner, "_dogleg_moves", expire_at_first_candidate)
+ problem = _seeded_foldback()
+ options = replace(_REFINEMENT_OPTIONS, refinement=RefinementOptions(max_windows_per_net=None))
+ run = route(problem, options=options)
+ assert candidates == [0.0]
+ assert run.metrics.timeout_events == run.metrics.refinement_windows_considered == 1
+ assert run.results_by_net["foldback"].is_valid
+
+
def test_automatic_refinement_rechecks_retained_partial_paths() -> None:
base = _seeded_foldback()
blocked = NetSpec("blocked", Port(150, 120, 90), Port(150, 210, 90))
diff --git a/inire/tests/test_routing_benchmarks.py b/inire/tests/test_routing_benchmarks.py
index e515565..1732962 100644
--- a/inire/tests/test_routing_benchmarks.py
+++ b/inire/tests/test_routing_benchmarks.py
@@ -6,7 +6,8 @@ import pytest
from shapely.geometry import box, shape
from inire import (
- CongestionOptions, NetSpec, PathSeed, Port, RoutingOptions, RoutingProblem, RoutingResult, RoutingRunResult,
+ Bend90Seed, CongestionOptions, NetSpec, ObjectiveWeights, PathSeed, Port, RefinementOptions, RoutingOptions, RoutingProblem,
+ RoutingResult, RoutingRunResult, SBendSeed,
SearchOptions, StraightSeed, TopologyOptions, route,
)
from inire.router import _automatic, _compact
@@ -21,6 +22,7 @@ from inire.tests.routing_benchmarks import (
CROSSING_BENCHMARK_CASES,
)
from inire.tests.routing_corpus import CASE_GROUPS, automatic_options, profile_options
+from inire.tests.routing_expanded_benchmarks import _on_grid
from scripts.benchmark_retry_order import _measure as _measure_retry
from scripts.compare_topological_routing import (
_direct_trials,
@@ -171,9 +173,9 @@ def test_retry_experiment_records_worker_expansions() -> None:
sample = _measure_retry(case, "public-defaults", "lattice-500")
[attempt] = sample["retry_attempts"]
- [stage] = [stage for stage in sample["stages"] if stage["policy"] == "early-bounded-lattice"]
+ stage_work = sum(stage["nodes_expanded"] for stage in sample["stages"] if stage["policy"] == "early-bounded-lattice")
assert attempt["policy"] == "bounded-lattice"
- assert 0 < attempt["nodes_expanded"] == stage["nodes_expanded"] <= sample["nodes_expanded"]
+ assert 0 < attempt["nodes_expanded"] == stage_work <= sample["nodes_expanded"]
assert len(sample["verified"]) == case.routing_bound
@@ -265,6 +267,24 @@ def test_benchmark_native_cost_uses_configured_proximity_range() -> None:
assert wider.native_valid_costs["a"] > default.native_valid_costs["a"]
+def test_benchmark_native_cost_scales_with_grid_for_straights_and_bends() -> None:
+ problem = RoutingProblem((0, 0, 80, 80), (NetSpec("a", Port(10, 10, 0), Port(32, 36, 90)),))
+ options = RoutingOptions(
+ search=SearchOptions(node_limit=0, bend_radii=(10,), sbend_radii=(10,)),
+ objective=ObjectiveWeights(danger_weight=0),
+ refinement=RefinementOptions(enabled=False),
+ )
+ seed = PathSeed((StraightSeed(20), Bend90Seed(10, "CCW"), SBendSeed(8, 10)))
+ case = BenchmarkCase("grid-cost", "Straight, quarter-turn, and S-bend", problem, options, reference_paths=(("a", seed),))
+ normalized = []
+ for nm in (1000, 500, 250, 100, 10):
+ scaled = _on_grid(case, nm)
+ replay = replace(scaled, problem=replace(scaled.problem, initial_paths=dict(scaled.reference_paths)))
+ sample = _measure(replay, replay.options, "off")
+ normalized.append(sample.native_valid_costs["a"] * nm / 1000)
+ assert normalized == pytest.approx([normalized[0]] * len(normalized))
+
+
def test_connectivity_screen_checks_each_net_width_and_leaves_unknown_ports_for_search() -> None:
problem = RoutingProblem(
bounds=(0, 0, 400, 160),
diff --git a/inire/tests/test_terminal_bench.py b/inire/tests/test_terminal_bench.py
index f22c834..5f52332 100644
--- a/inire/tests/test_terminal_bench.py
+++ b/inire/tests/test_terminal_bench.py
@@ -7,8 +7,9 @@ from shapely import union_all
from shapely.affinity import translate
from shapely.geometry import box
-from inire import Bend90Seed, DiagnosticsOptions, Port, SBendSeed, TopologyOptions, route
+from inire import Bend90Seed, DiagnosticsOptions, PathSeed, Port, SBendSeed, StraightSeed, TopologyOptions, route
from inire.constants import TOLERANCE_LINEAR
+from inire.router import _bundle, _router
from inire.router._waypoints import export_waypoints
from inire.tests.terminal_bench_lane_plan import terminal_bench_lane_problem
from inire.tests.terminal_bench_scenario import (
@@ -168,3 +169,40 @@ def test_bundle_replays_with_resolved_ports_without_building_a_mesh(monkeypatch:
assert result.effective_net == original.effective_net
assert result.as_seed() == seeds[key]
assert result.locked_geometry == original.locked_geometry
+
+
+def test_automatic_preserves_headings_for_supplied_nonempty_seeds() -> None:
+ problem = terminal_bench_problem()
+ options = terminal_bench_options(node_limit=20, max_iterations=1)
+ options = replace(
+ options,
+ topology=TopologyOptions(infer_terminal_headings=True),
+ congestion=replace(options.congestion, warm_start_enabled=False),
+ refinement=replace(options.refinement, enabled=False),
+ )
+ for move in (StraightSeed(5), Bend90Seed(1000, "CW")):
+ run = route(replace(problem, initial_paths={"net_00": PathSeed((move,))}), options=options)
+ assert all(result.is_valid and result.requested_net == result.effective_net for result in run.results_by_net.values())
+ assert run.automatic.selected_planner == "bundle-turnaround"
+ assert bool(run.results_by_net["net_00"].report.seed_error) == isinstance(move, Bend90Seed)
+
+ empty = route(replace(problem, initial_paths={"net_00": PathSeed(())}), options=options)
+ assert empty.results_by_net["net_08"].effective_net.target.r == 180
+
+
+def test_zero_iterations_skip_bundle_planning_and_seed_materialization(monkeypatch: pytest.MonkeyPatch) -> None:
+ problem = terminal_bench_problem()
+ seeded = replace(problem, initial_paths={"net_00": PathSeed((StraightSeed(5),))})
+ options = terminal_bench_options(node_limit=20, max_iterations=0)
+
+ def fail_if_prepared(*_args, **_kwargs):
+ pytest.fail("A run with zero iterations prepared routes")
+
+ monkeypatch.setattr(_bundle, "plan_ordered_bundle", fail_if_prepared)
+ monkeypatch.setattr(_router, "materialize_path_seed", fail_if_prepared)
+ for mode in ("off", "automatic", "bundle"):
+ for candidate in (problem, seeded):
+ run = route(candidate, options=replace(options, topology=TopologyOptions(mode=mode, infer_terminal_headings=True)))
+ assert run.metrics.route_iterations == run.metrics.nodes_expanded == 0
+ assert len(run.results_by_net) == len(problem.nets)
+ assert all(result.outcome == "unroutable" and result.requested_net == result.effective_net for result in run.results_by_net.values())
diff --git a/inire/tests/test_topology.py b/inire/tests/test_topology.py
index 37521d0..0966df6 100644
--- a/inire/tests/test_topology.py
+++ b/inire/tests/test_topology.py
@@ -1,12 +1,15 @@
from dataclasses import replace
import pytest
+import shapely
from shapely.geometry import LineString, Polygon, box
from inire import (
CongestionOptions, DiagnosticsOptions, NetSpec, ObjectiveWeights, PathSeed, Port, RefinementOptions,
RoutingOptions, RoutingProblem, SBendSeed, SearchOptions, StraightSeed, TopologyOptions, route,
)
+from inire.geometry.collision import RoutingWorld
+from inire.router import _router, _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.tests.routing_benchmark_case import BenchmarkCase
@@ -112,7 +115,7 @@ def test_rounded_keepout_guidance_preserves_acute_aperture() -> None:
assert route(problem, options=options).results_by_net["opening"].is_valid
-def test_guidance_retry_can_change_an_incumbent_in_an_offset_gate() -> None:
+def test_guidance_retry_can_change_an_incumbent_in_an_offset_gate(monkeypatch: pytest.MonkeyPatch) -> None:
mode = 'seed'
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))
@@ -125,6 +128,21 @@ def test_guidance_retry_can_change_an_incumbent_in_an_offset_gate() -> None:
topology=TopologyOptions(mode=mode),
diagnostics=DiagnosticsOptions(capture_iteration_trace=True, capture_conflict_trace=True),
)
+ unmodified = route(problem, options=options)
+ assert all(result.is_valid for result in unmodified.results_by_net.values())
+
+ route_once = _stack.route_once
+
+ def limit_guided_attempt(problem, *, options, **kwargs):
+ if options.topology.guide_strength:
+ options = replace(
+ options,
+ search=replace(options.search, node_limit=1),
+ topology=replace(options.topology, seed_node_limit=1),
+ )
+ return route_once(problem, options=options, **kwargs)
+
+ monkeypatch.setattr(_stack, "route_once", limit_guided_attempt)
snapshots = []
run = route(
problem, options=options,
@@ -132,7 +150,7 @@ def test_guidance_retry_can_change_an_incumbent_in_an_offset_gate() -> None:
)
assert all(result.is_valid for result in run.results_by_net.values())
- assert snapshots == [(0, 1), (1, 1), (2, 2)]
+ assert snapshots == [(0, 0), (1, 0), (2, 2)]
assert [(entry.iteration, entry.completed_nets) for entry in run.iteration_trace] == [(2, 2)]
assert [entry.iteration for entry in run.conflict_trace if entry.stage == "iteration"] == [2]
assert run.conflict_trace[-1].iteration is None
@@ -144,6 +162,47 @@ def test_guidance_retry_can_change_an_incumbent_in_an_offset_gate() -> None:
assert [attempt.topology.guide_strength for attempt in sample.attempt_options] == [0.75, 0.0]
assert sample.selected_attempt == 1
+ clock = [0.0]
+ capture = _router.PathFinder._capture_frontier_trace
+
+ def expire_after_guided_search(self, state, results, details):
+ if self.context.options.topology.guide_strength:
+ clock[0] = state.start_time + state.timeout_s + 1
+ return capture(self, state, results, details)
+
+ monkeypatch.setattr(_router.time, "monotonic", lambda: clock[0])
+ monkeypatch.setattr(_router.PathFinder, "_capture_frontier_trace", expire_after_guided_search)
+ traced_options = replace(options, diagnostics=replace(options.diagnostics, capture_frontier_trace=True))
+ traced_run = route(problem, options=traced_options)
+ assert traced_run.results_by_net == run.results_by_net
+ assert traced_run.iteration_trace == run.iteration_trace
+ assert traced_run.metrics.route_iterations == run.metrics.route_iterations
+ assert traced_run.metrics.nodes_expanded == run.metrics.nodes_expanded
+ assert traced_run.metrics.timeout_events == 0
+ assert traced_run.metrics.diagnostic_timeout_events == 1
+
+ clock[0] = 0.0
+ monkeypatch.setattr(_router.PathFinder, "_capture_frontier_trace", capture)
+ verify_details = RoutingWorld.verify_path_details
+
+ def expire_during_component_details(self, net_id, path, **kwargs):
+ if kwargs.get("capture_component_conflicts"):
+ clock[0] = 61.0
+ return verify_details(self, net_id, path, **kwargs)
+
+ def limit_guided_before_retry(problem, *, options, **kwargs):
+ if options.topology.guide_strength:
+ options = replace(options, search=replace(options.search, node_limit=500), topology=replace(options.topology, seed_node_limit=500))
+ return route_once(problem, options=options, **kwargs)
+
+ monkeypatch.setattr(RoutingWorld, "verify_path_details", expire_during_component_details)
+ monkeypatch.setattr(_stack, "route_once", limit_guided_before_retry)
+ frontier_only = replace(options, diagnostics=DiagnosticsOptions(capture_frontier_trace=True))
+ traced = route(problem, options=frontier_only)
+ assert traced.results_by_net == run.results_by_net
+ assert traced.metrics.timeout_events == 0
+ assert traced.metrics.route_iterations == 3
+
def test_lane_assignment_keeps_mesh_path_order_on_equal_costs(monkeypatch: pytest.MonkeyPatch) -> None:
problem = DETOUR.problem
@@ -171,7 +230,58 @@ def test_topological_planner_finds_both_sides_of_an_obstacle() -> None:
assert crossing_heights[1] >= 437
-def test_seed_mode_respects_user_paths_on_repeated_runs() -> None:
+def test_small_offsets_on_a_mixed_width_board_share_the_widest_mesh(monkeypatch: pytest.MonkeyPatch) -> None:
+ triangulate = shapely.constrained_delaunay_triangles
+ meshes = []
+
+ def record_mesh(free):
+ meshes.append(free)
+ return triangulate(free)
+
+ monkeypatch.setattr(shapely, "constrained_delaunay_triangles", record_mesh)
+ nets = tuple(NetSpec(str(i), Port(20, 80 + 15 * i, 0), Port(200, 81 + 15 * i, 0), 2 + i / 10) for i in range(8))
+ keepouts = (box(40, 10, 55, 30), box(80, 10, 95, 30))
+ guides = plan_corridors((0, 0, 240, 220), keepouts, nets, clearance=2, bend_radius=10, limit=2)
+ assert guides.keys() == {net.net_id for net in nets}
+ assert len(meshes) == 1
+
+
+def test_seed_mode_recovers_a_narrow_guide_after_a_reserved_route_blocks_the_shared_guide(monkeypatch: pytest.MonkeyPatch) -> None:
+ problem = RoutingProblem(
+ (0, 0, 240, 200),
+ (NetSpec("wide", Port(120, 60, 90), Port(120, 139, 90), 24), NetSpec("narrow", Port(40, 100, 0), Port(200, 101, 0), 2)),
+ (box(110, 17, 130, 59), box(110, 140, 130, 200)), clearance=1, initial_paths={"wide": PathSeed((StraightSeed(79),))},
+ )
+ options = RoutingOptions(
+ search=SearchOptions(node_limit=2000, bend_radii=(10,), sbend_radii=(10,), sbend_offsets=(1,)),
+ congestion=CongestionOptions(max_iterations=2, warm_start_enabled=False),
+ objective=ObjectiveWeights(danger_weight=0, bend_penalty=20, sbend_penalty=20),
+ refinement=RefinementOptions(enabled=False),
+ topology=TopologyOptions(mode="seed", max_corridors=3, seed_node_limit=2000),
+ )
+ triangulate = shapely.constrained_delaunay_triangles
+ route_astar = _router.route_astar
+ events = []
+
+ def record_mesh(free):
+ events.append("mesh")
+ return triangulate(free)
+
+ def record_search(*args, config, **kwargs):
+ if config.restrict_to_corridor:
+ events.append("seed")
+ return route_astar(*args, config=config, **kwargs)
+
+ monkeypatch.setattr(shapely, "constrained_delaunay_triangles", record_mesh)
+ monkeypatch.setattr(_router, "route_astar", record_search)
+ run = route(problem, options=options)
+ assert all(result.is_valid for result in run.results_by_net.values())
+ assert run.results_by_net["wide"].as_seed() == problem.initial_paths["wide"]
+ assert run.topology.seeded_net_ids == ("narrow",)
+ assert dict(run.topology.corridor_counts)["narrow"] == 2
+ assert events[-3:] == ["seed", "mesh", "seed"]
+
+def test_seed_mode_respects_user_paths_on_repeated_runs(monkeypatch: pytest.MonkeyPatch) -> None:
existing = PathSeed((StraightSeed(140),))
problem = RoutingProblem(
bounds=(0, 0, 180, 100),
@@ -190,6 +300,22 @@ def test_seed_mode_respects_user_paths_on_repeated_runs() -> None:
assert stack.finder.topology_report.seeded_net_ids == ("new",)
assert list(stack.world.iter_static_dilated_geometries()) == []
+ completed = replace(problem, initial_paths={"existing": existing, "new": existing})
+
+ def fail_on_mesh(*_args, **_kwargs):
+ pytest.fail("Complete verified seeds should skip corridor planning")
+
+ monkeypatch.setattr("inire.router._topology.plan_corridors", fail_on_mesh)
+ for mode in ("guide", "seed"):
+ callbacks = []
+ run = route(
+ completed, options=RoutingOptions(topology=TopologyOptions(mode=mode)),
+ iteration_callback=lambda index, results, callbacks=callbacks: callbacks.append((index, results)),
+ )
+ assert run.metrics.nodes_expanded == 0
+ assert [(index, all(result.is_valid for result in results.values())) for index, results in callbacks] == [(0, True)]
+ assert all(result.is_valid and result.as_seed() == existing for result in run.results_by_net.values())
+
def test_narrow_net_recovers_corridors_with_a_wide_peer() -> None:
mode = 'seed'
diff --git a/inire/tests/test_visibility.py b/inire/tests/test_visibility.py
index a2cbd2f..b301c9e 100644
--- a/inire/tests/test_visibility.py
+++ b/inire/tests/test_visibility.py
@@ -1,4 +1,5 @@
-from shapely.geometry import box
+from shapely import force_3d
+from shapely.geometry import Polygon, box
from inire.geometry.collision import RoutingWorld
from inire.geometry.primitives import Port
@@ -42,6 +43,21 @@ def test_exact_corner_visibility_accepts_only_endpoint_contact_and_scales_to_lar
assert (0, 15) not in {(x, y) for x, y, _ in blocked}
+def test_corner_index_projects_exterior_and_hole_vertices_to_xy() -> None:
+ polygon = Polygon(box(30, 40, 60, 60).exterior.coords, (box(35, 45, 55, 55).exterior.coords,))
+ for clearance in (0, 2):
+ for owner in (None, "fixed"):
+ corners = []
+ for obstacle in (polygon, force_3d(polygon, z=5)):
+ world = RoutingWorld(clearance=clearance)
+ world.add_static_obstacle(obstacle, owner=owner)
+ visibility = VisibilityManager(world)
+ visibility._build_corner_index()
+ corners.append(visibility.corners)
+ assert corners[0] == corners[1]
+ assert len(corners[0]) == 8
+
+
def test_clear_cache_invalidates_without_rebuilding_and_static_change_rebuilds_lazily() -> None:
engine = RoutingWorld(clearance=0.0)
engine.metrics = AStarMetrics()
diff --git a/plans/routing-follow-up-review.md b/plans/routing-follow-up-review.md
new file mode 100644
index 0000000..6dc5aee
--- /dev/null
+++ b/plans/routing-follow-up-review.md
@@ -0,0 +1,228 @@
+# Routing follow-up review
+
+Review baseline `f6e7bac`. This plan follows the [full project review](full-project-review.md) and the subsequent changes to routing, dependency requirements, and benchmark reporting. All 20 items were implemented. The reproductions below describe the baseline.
+
+## Implementation verification
+
+- The performance-enabled test suite passed all 395 tests. The topology, terminal, visibility, and refinement tests also passed on Python 3.11 with NumPy 1.26 and on Python 3.14 with Shapely 2.2 and GEOS 3.15. Ruff and the offline lockfile check passed.
+- All 152 corpus and holdout boards reached their routing bounds under `matched-budget`, `public-defaults`, and `corpus-regression`. Each profile verified 2,245 nets. Verified IDs and per-net physical route lengths matched the baseline in all three profiles. Independent Shapely checks and zero-node seed replay confirmed board containment, clearance, and replayed geometry.
+- The fixed-budget lattice runs verified four nets instead of three on `holdout-staggered-opposed` and two instead of zero on `lidar-clements-8x8`. Guided runs on `blocking-turn-room` verified both nets instead of one in both modes, using 25 guide expansions and 32 seed expansions. The equal-rank partial for `lane_1` on `search-comb-3x4` advanced from x=240 to x=237 in both modes.
+- The ten-net fan-out retained all ten routes. Its counters now show 624 pair-local expansions and 1,703 total expansions. With shuffle seeds 42, 44, and 45, the pre-pair trace matched the restored iteration's conflict edges and component indices. A fake-clock test stopped diagnostic replay before its first expansion while keeping the same verified results and routing work. Historical captures retain the metric definitions used at capture time, which are recorded in the [archive guide](../archive/routing/README.md#compare-performance-or-diagnose-a-trace).
+- The 200-net mixed-width board retained 400 guides with one triangulation and routed all 200 nets in 400 lattice expansions. The exact-width ray-tree cache retained eight entries. The residual connectivity probe constructed one union for 120 residual widths and again found no disconnected nets. Distinct widths still receive their own mesh when they need recovery.
+- Guide and seed each verified the 240 supplied paths on `scale-bank-240-with-keepouts` with zero triangulations and zero expansions. The returned seeds matched the supplied paths.
+- The imported fixture comparison reports a 100 nm grid. The grid-cost test checks the normalized objective at all five authored resolutions. The wheel and source distribution carry matching project URLs and README content. All eight README targets, including the illustration and three heading anchors, resolved from outside the checkout.
+
+### Fixes from the implementation review
+
+- The pre-pair trace saves the restored layout and replays it after repair and final verification. Under a controlled deadline, both crossing nets now verify with tracing enabled, using the same 608 expansions and one repair attempt as the untraced run.
+- A frontier replay that expires increments `diagnostic_timeout_events`. The offset-gate retry still verifies both nets when the guided worker's trace expires. A verification-only worker still delivers its callback.
+- The 40-net board with 144 keepouts and a one-grid-unit offset uses one triangulation and retains 80 guides. The earlier implementation built 40 triangulations. Guide and seed modes each verified all 40 nets with one triangulation. Narrower meshes still recover missing corridors and passages near obstacles or board edges.
+- All 397 tests passed with performance checks enabled. An independent rerun of all three benchmark profiles verified the same 2,245 net IDs and per-net lengths in each profile. Expansion totals also matched the implementation before these review fixes.
+
+### Fixes from the second implementation review
+
+- Frontier-only conflict collection uses verified reports and runs after routing, final verification, and the replay callback. In the dense two-net replay, the callback still fired at 31.6 seconds of controlled work with tracing enabled. The diagnostic pass reached the deadline separately. The offset-gate retry still verified both nets.
+- Deferred pre-pair tracing collects component conflicts only for colliding nets. On the 22-net board, expiry during the first optional check stopped further checks and kept all 22 verified routes.
+- Failed shared guides can recover narrower alternatives when reservations obstruct the shared space. The width-24 seeded blocker and width-2 offset repro now verifies both nets in 1,792 expansions. The clear 40-net offset board still verifies 40/40 with one triangulation in guide and seed modes.
+- The performance-enabled suite passed 398 tests. All three corpus profiles reached every routing bound and matched the prior verified IDs, per-net lengths, and expansion totals.
+
+## 1. Catch physical keepout collisions missed by bend proxies — High
+
+Use a `120 × 120` board, a width-2 net from `(10, 20, 0)` to `(80, 80, 90)`, clearance 1, and a keepout from `(77.3, 22.3)` to `(77.7, 22.7)`. Set lattice mode, a 200-node budget, a single 90-degree radius of 10, no S-bends, zero proximity cost, three iterations, and disable warm start and refinement. With `bend_collision_type="clipped_bbox"` and `bend_clip_margin=5`, search repeatedly picks a one-bend path that fails final verification. Standard arc admission finds a valid three-bend detour in 37 expansions. A probe that checks the physical clearance of each proposed bend also finds the detour in 37 expansions with the original clipped proxy settings.
+
+Check static clearance against the physical outline when a bend proxy may understate it. Query the physical bounds in that case. Reuse the cached move-admission decision and preserve the fast path for standard geometry. Exercise a shrunken built-in proxy, a custom polygon proxy with an arc outline, and an exact-clearance control. Require unchanged coverage across the corpus and check work and runtime for standard arc routing. [Static move admission](../inire/geometry/collision.py#L299)
+
+## 2. Count all pair-local search expansions — Medium
+
+In `example_07_large_scale_routing_no_warm_start`, the router verifies 10/10 nets and reports 1,079 total expansions and 42 pair-local expansions. Instrumenting the actual `route_astar` calls in pair repair records 624 expansions over three pair attempts. The failed order spends 582 expansions before returning no candidate. All 624 expansions are absent from the top-level `nodes_expanded` field. The current diagnostics guide documents the narrower meaning of the pair-specific counter.
+
+Return expansion work even when a pair attempt fails and add it to both counters. Keep metrics from diagnostic replay isolated. Update the metric documentation and reconcile the expansion guardrails and saved baselines that use the older definitions. Compare the selected routes, attempt order, and verified coverage independently of the counter changes. [Pair search](../inire/router/_pair_local.py#L67) · [Counter update](../inire/router/_router.py#L851) · [Metric guide](../docs/routing-diagnostics.md#route-metrics)
+
+## 3. Skip planning and seed materialization with zero iterations — Medium
+
+With `max_iterations=0`, the point-terminal bundle fixture returns nine unroutable results with zero iterations in `off` and `automatic` modes. In `bundle` mode the router builds a schedule, performs zero routing iterations, and raises `Bundle schedule failed geometric verification for net_00`. The lattice worker also materializes supplied seeds before discovering that it will run zero iterations.
+
+Make the disabled-iteration outcome consistent across modes. Skip bundle planning and unused seed materialization while preserving public input checks and per-net diagnostics. Exercise a supported bundle, a bundle-shaped layout rejected by the planner when enabled, and seeded input. Keep zero-node replay with positive iterations available. [Bundle setup](../inire/router/_stack.py#L32) · [Bundle result check](../inire/router/_stack.py#L98) · [Seed preparation](../inire/router/_router.py#L337)
+
+## 4. Read visibility corners in XY at zero clearance — High
+
+A `100 × 80` board with a straight width-2 net from `(10, 20, 0)` to `(80, 20, 0)` and a keepout above it is enough to reproduce an exception. Use a polygon with exterior `box(30, 40, 60, 60)`, a hole `box(35, 45, 55, 55)`, and set every vertex's Z coordinate to 5. At zero clearance, both `tangent_corner` and `exact_corner` raise `ValueError: too many values to unpack` in lattice mode. The same input completes when visibility is off. The exception also occurs when the polygon is supplied as a fixed route. At clearance 2 the buffer yields XY coordinates and the search completes in each case.
+
+Read XY coordinates from each exterior and interior ring before indexing corners. Keep the original polygons available for returned geometry. Exercise XY and XYZ keepouts and fixed routes in both visibility modes and at zero and positive clearance. Compare the paths and the corner counts. [Visibility corner extraction](../inire/router/visibility.py#L55) · [Obstacle buffering](../inire/geometry/static_obstacle_index.py#L62)
+
+## 5. Keep routing when the conflict count stalls but the layout can improve — High
+
+Under matched-budget fixture settings with `mode="off"`, a 90-node search limit, seven iterations, warm start off, and refinement off, `holdout-staggered-opposed` stops after four iterations and verifies 3/9 nets. Its conflict edge counts are `[4, 1, 1, 1]`. Disabling only the repeated-count stop yields `[4, 1, 1, 1, 0, 0, 0]` and verifies 4/9. The same change improves `lidar-clements-8x8` from 0/6 to 2/6, against a bound of three. In both cases the edge identities also repeat before a later iteration improves coverage. Of 60 boards checked under these settings, five met the repeat-stop condition and two gained coverage when it was disabled.
+
+Remove the count-only early exit or replace it with a stopping rule that accounts for the changing congestion penalties. Keep the iteration and time limits. Compare the verified net IDs, check the progression of conflicts and penalties, and measure runtime on the boards that keep searching. Retain the path to pair-local repair while checking that it still triggers where it improves coverage. [Iteration stop](../inire/router/_router.py#L1166) · [Repeated-count rule](../inire/router/_congestion_policy.py#L117)
+
+## 6. Bound the cost of width-specific corridor meshes — Medium
+
+On a `1000 × 1000` board with 144 rectangular keepouts below 40 straight nets, corridor planning builds one mesh at uniform width 2 and 40 meshes when widths increase from 2 by 0.01 per net. Both runs guide all 40 nets. The measured planning times were 2.42 seconds and 5.43 seconds in the same process. Every width below the maximum gets a mesh even when the widest mesh has already supplied passages.
+
+A `1400 × 2400` board with 200 nets and 240 rectangular keepouts scales from one to 200 meshes, with two corridors per net in both runs. Planning took about 54 and 68 seconds in the same process. To reproduce it, place keepouts at `box(20 + 48*x, 18 + 48*y, 31 + 48*x, 30 + 48*y)` for `x` from 0 through 19 and `y` from 0 through 11. Give net `i` east-facing ports at `(5, 620 + 8*i)` and `(45, 620 + 8*i)`. Compare width 2 with `2 + 0.005*i` using clearance 2, bend radius 10, and two corridors per net. Use the mesh count as the primary comparison because the wall times vary with load.
+
+Keep width-specific recovery for missing corridors and passages that are genuinely too narrow in the shared mesh. Reuse a conservative mesh or defer narrower alternatives until the shared candidates fail. Verify both the mixed-width narrow-aperture fixtures and the case where a wide-mesh corridor exists but the narrower net needs a different passage. Compare triangulation counts and routing coverage on a large mixed-width layout before replacing the eager passes. [Width-specific planning](../inire/router/_topology.py#L384) · [Narrow corridor coverage](../inire/tests/test_topology.py)
+
+## 7. Update the corridor walkthrough after the retry removals — Low
+
+The corridor walkthrough still says that a joint retry can move lanes for several nets. The automatic planner removed that retry and its alternate-lane permutation in `7476209`. The architecture overview also describes lattice fallback in terms of planning being unavailable. The current flow requires triangulation and uses lattice when the geometry calls for it or earlier planners leave unresolved nets.
+
+Describe the shared portal assignment, width-specific recovery, and remaining lattice retries in the active guides. Check the walkthrough links and benchmark command against the current output. Keep the historical review and experiment records tied to their revisions. [Corridor walkthrough](../docs/topological-routing.md#corridor-planning-and-realization) · [Automatic architecture](../docs/architecture.md#automatic-routing)
+
+The bundle guide also says the smallest 90-degree radius must be a positive integer shared with `sbend_radii`. The planner tries the usable common integer radii. The point-terminal fixture verifies all nine nets with 90-degree radii `(10.5, 50)` and S-bend radii `(50,)`. Describe the eligibility of the common radius and retain the existing layout and geometry requirements. [Mode requirements](../docs/user/tune-and-troubleshoot.md#choose-a-routing-mode) · [Bundle radius selection](../inire/router/_bundle.py#L222)
+
+Restore the link from the archived refactor plan to the current corpus command. It points to `#run-the-full-regression-corpus`, while the current heading uses `#run-the-full-benchmark-corpus`. The historical results can stay tied to the original corpus. [Archived link](../archive/routing/routing-refactor-plan.md#verification) · [Current corpus command](../docs/benchmarks.md#run-the-full-benchmark-corpus)
+
+## 8. Hand off to pair repair only when the saved layout has a repairable pair — High
+
+Run `blocking-turn-room` with matched-budget options, an 85-node limit, five congestion iterations, zero guidance cost, and warm start and refinement off. Both guide and seed modes reach one verified net in iteration 0. In iteration 1 both nets reach their targets but conflict, and the router stops to hand off to pair repair. It restores iteration 0, whose partial path has no conflict edges, so pair repair tries no pairs. Bypassing only the pair-local handoff lets iteration 2 verify both nets. The guide run rises from 10 to 25 expansions and the seed run from 17 to 32. The repeated-count rule in item 5 stays enabled for this reproduction.
+
+Base the handoff on the saved layout the repair will receive. Require an eligible conflict pair before skipping the remaining congestion iterations. Cover the zero-edge saved layout and retain the early handoff on the fan-out fixture where pair repair succeeds. A control requiring at least one saved conflict edge retained all 10 fan-out routes and all three pair-search attempts. Evaluate coverage and work jointly with item 5. [Pair-local handoff](../inire/router/_router.py#L1163) · [Pair eligibility](../inire/router/_router.py#L727) · [Plateau rule](../inire/router/_congestion_policy.py#L111)
+
+## 9. Preserve useful partial paths when congestion iterations tie — Low
+
+With the same settings on `search-comb-3x4`, guide and seed each finish five iterations with no completed nets or conflict edges. The final path for `lane_1` ends at `(240, 150, 180)`. Every callback after iteration 0 shows that net ending at `(237, 150, 180)`, closer to its target at `(15, 150, 180)`. The equal layout rank always keeps the first iteration, even when a later iteration advances a partial path.
+
+Both partial paths fit the board and meet static clearance. On ties in completed net IDs and conflict rank, prefer more useful partial results using the existing target-distance ordering. Check the geometry of any candidate partial path used for this comparison. Preserve completed geometry and keep conflict trace indices aligned with the selected paths. Include an empty-to-partial case and a control where a closer endpoint belongs to a colliding path. [Layout selection](../inire/router/_router.py#L459) · [Search progress](../inire/router/_search.py#L41)
+
+## 10. Bound the width-specific ray indexes in lattice search — Medium
+
+Route the 200-net board from item 6 in lattice mode at four nodes per net and one iteration. Turn off bends, visibility, proximity cost, warm start, and refinement. Both width distributions verify 200/200 in 400 expansions. The uniform-width run retains one ray index with 240 buffered obstacles. The mixed-width run retains 200 indexes and 48,000 buffered obstacles. In fresh processes on the same core, the probes took about 0.35 and 2.05 seconds, with peak memory about 78 and 103 MiB.
+
+Bound retention while preserving exact-width geometry. Compare a size-limited index cache with a shared raw index that buffers only candidates for each query. Keep the tree for commonly reused widths if it saves work. Check exact-clearance behavior, repeated-width interleaving, a large mixed-width layout, and the normal lattice coverage and runtime baselines. [Width-specific index](../inire/geometry/static_obstacle_index.py#L106) · [Ray query](../inire/geometry/collision.py#L886)
+
+## 11. Verify complete seed layouts before planning corridors — Medium
+
+Use the reference paths in `scale-bank-240-with-keepouts` as `initial_paths`, with matched-budget options, one iteration, and warm start and refinement off. Guide and seed each verify 240/240 with zero expansions, after building corridors for all 240 nets. In one local run per mode, corridor planning took about 208 seconds in guide and 210 seconds in seed. A probe bypassing just `plan_corridors` returned identical verified placements in about 0.12 seconds per mode. A 40-net, 144-keepout control reproduced placement parity, with about 2.5 seconds of planning per mode.
+
+With a controlled clock, a plan that consumes the worker deadline returns an empty, unroutable result for an otherwise valid straight seed in both modes. This isolates the ordering problem without relying on host load.
+
+When every net has a seed that reaches its target, check the complete seeded layout before building guides. Take the fast path only if the seeds verify together. Exercise partial, incompatible, overlapping, and missing seeds that still need the normal search. Reuse verification work and retain the requested refinement and callback behavior. [Setup before the first iteration](../inire/router/_router.py#L315) · [Corridor planning](../inire/router/_router.py#L282)
+
+## 12. Scale the flat S-bend surcharge linearly with the benchmark grid — Medium
+
+The expanded fixture converter multiplies both bend surcharges by the grid scale raised to the power of 1.5. That compensates for the radius adjustment on 90-degree bends. An S-bend has a flat surcharge, so the same physical route is valued differently when expressed in finer grid units. A width-2 µm S-bend with radius 10 µm, offset 8 µm, and an exact 16 µm span has length 18.546 µm at both 1,000 nm and 10 nm grids. With proximity cost off and the default 500-unit surcharge before conversion, normalized native cost changes from 518.546 to 5,018.546.
+
+Scale the S-bend surcharge by the grid factor. Check normalized costs for a straight, a quarter turn, and an exact-span S-bend across the authored grids. With a corrected surcharge on 24 fine-grid expanded cases that allow S-bends, automatic regression coverage, verified paths, and expansion counts stayed the same. In a lattice control limited to 200 nodes per net and one iteration, `complex-column-5x2` retained the same verified net but changed its path and used 842 expansions instead of 992. Reconcile affected benchmark baselines and update the fixture guide, which still lists 72 expanded cases and eight search challenges. The current groups have 75 and 11 respectively. [Grid conversion](../inire/tests/routing_expanded_benchmarks.py#L59) · [Component radius](../inire/geometry/components.py#L197) · [Native surcharge](../inire/router/cost.py#L234) · [Fixture guide](../docs/benchmark-fixtures.md#micron-scale-routing-cases)
+
+Propagate the imported grid into the same comparison records. The converted fixtures declare ten layout units per micron, but the loader discards that scale. A JSON comparison of `lidar-toy-example` emits `"grid_nm": null`. The known scale for all six imported boards is 100 nm. Test that the comparison output carries the scale from the fixture data. [Imported fixture loader](../inire/tests/routing_external_benchmarks.py#L13) · [Comparison export](../scripts/compare_topological_routing.py#L413)
+
+## 13. Make the guidance retry regression independent of corridor candidates — Medium
+
+The two-net offset-gate test expects the guided attempt to verify one net in each of its first two iterations and the retry without a guidance cost to verify both nets. This holds on the lockfile environment with Shapely 2.1.2 and GEOS 3.13.1. With the local Shapely 2.2.0 distribution and GEOS 3.15.0, the planner generates different corridor centerlines and the first guided iteration verifies both nets. The worker skips the retry and reports selected attempt 0, and the test fails on the hard-coded callback sequence.
+
+Decouple the retry and attempt-index assertions from the particular corridor candidates this layout receives. Keep the real layout as a coverage control and use a deterministic first-attempt outcome to exercise retry selection and diagnostic indices. Verify the control on both dependency combinations and retain the check that both nets route. [Offset-gate regression](../inire/tests/test_topology.py#L115) · [Explicit retry and selection](../inire/router/_stack.py#L161)
+
+## 14. Observe the worker deadline during refinement and frontier replay — Medium
+
+On a `100 × 100` board, replay two perpendicular width-2 straights through the center, from `(10, 50, 0)` to `(90, 50, 0)` and from `(50, 10, 90)` to `(50, 90, 90)`. Use lattice mode, a 60-node limit, one iteration, no bends, warm start off, refinement off, and `capture_frontier_trace=True`. Advance a controlled clock from zero to 61 seconds as the first frontier replay starts. Both diagnostic searches still expand three nodes each past the 60-second worker deadline. The run reports zero timeouts. The same replay routine is used for pre-pair traces.
+
+On the seeded foldback control with unlimited refinement windows, advance the clock at the first window. A second window starts after expiration, and the timeout is counted only after refinement returns. The worker currently checks once before refining each net.
+
+Pass the worker's expiry check through frontier A* replay and check it between diagnostic replays and at refinement windows and bounded candidate checkpoints. Keep final verification and the latest verified geometry available after expiration. Exercise expiry before and during a diagnostic search, expiry during a refinement window, and an uninterrupted run with the same results and stable work counters. [Frontier replay](../inire/router/_router.py#L567) · [Worker deadline](../inire/router/_router.py#L382) · [Refinement loop](../inire/router/refiner.py#L423) · [Foldback control](../inire/tests/test_refinements.py#L21)
+
+## 15. Keep pre-pair counters and frontier geometry on the same layout — Medium
+
+Run the ten-net fan-out using `_trace_example_07_variant(warm_start_enabled=False, seed=44)`. Iteration 6 verifies six nets and leaves one conflict, `net_06`–`net_07`. Iteration 7 verifies four nets and has four conflict edges, none matching that pair. The worker restores iteration 6 and sends `net_06`–`net_07` to pair repair. The pre-pair trace reports iteration 7's edges, reroute order, and work, while replaying the restored iteration 6 geometry. Four routed paths differ between those layouts. The guide presents this trace as a record of the handoff into pair repair.
+
+With seed 45, both iterations verify seven nets with one conflict. The trace lists `net_02`–`net_03`, and pair repair receives `net_08`–`net_09`. A comparison of counts alone misses the attribution error. [Fan-out trace fixture](../inire/tests/example_scenarios.py#L367)
+
+Keep the attempt metadata associated with the saved layout and use it for the trace after restoring that layout. Include carries and any missing per-net attempt data consistently. The iteration trace already records the discarded iteration. Add a control where the conflict identities change and an earlier layout is restored, and check that the pre-pair conflict edges match the pair-repair input and that hotspot geometry refers to that same layout. Preserve coverage and search selection with diagnostics enabled. [Saved-layout restoration](../inire/router/_router.py#L430) · [Pre-pair trace assembly](../inire/router/_router.py#L755) · [Trace guide](../docs/routing-diagnostics.md#traces)
+
+## 16. Reject unknown performance scenarios before writing reports — Medium
+
+Run `scripts.record_performance_baseline --scenario example_01_simple_rote --output-dir ` using the documented module invocation. It exits successfully and writes an empty `scenarios` list and a Markdown baseline with no measurements. With the default output directory, those writes replace the committed baseline files. The diff tool accepts the same misspelling and emits an empty comparison. The shared snapshot selector simply drops unknown names.
+
+Validate all explicitly requested scenario names before measuring or writing files. Distinguish unknown names from performance-only names that need the existing flag. Keep the diff tool's support for a scenario newly present in the current run or present only in the baseline. Exercise a misspelling alongside an existing output file, a mixed valid and invalid selection, and a valid performance-only selection. [Snapshot selection](../inire/tests/example_scenarios.py#L497) · [Baseline recorder](../scripts/record_performance_baseline.py#L100) · [Baseline comparison](../scripts/diff_performance_baseline.py#L200)
+
+## 17. Resolve heading inference from the caller's seeded request — High
+
+Use `terminal-bench-point-terminals` in automatic mode with inference enabled, 20 search nodes, one congestion iteration, warm start off, and refinement off. Give `net_00` a radius-1000 quarter-turn seed while only radius 50 is configured. The public wrapper rejects the seed and the automatic planner now sees an unseeded request. It verifies 9/9 after changing `net_08` from the requested east-facing arrival to west-facing. The API describes caller headings as fixed when initial paths are supplied.
+
+Replace the rejected seed with a compatible `StraightSeed(5)` prefix on `net_00`. All headings stay fixed, but the automatic planner skips the fixed-heading bundle turnaround because it checks the configured inference flag. The run verifies 1/9. Turning inference off while keeping the same prefix and budget verifies 9/9 using the bundle turnaround.
+
+Resolve whether inference is active at the public boundary, where the original seeds and options are both available, and use that decision for selecting the compatible constructive planner. Preserve diagnostics for rejected seeds and the unseeded inference behavior. Cover a valid prefix, an unusable nonempty seed, and a fully seeded replay. Verify requested and effective poses as well as counts. [Seed filtering](../inire/__init__.py#L141) · [Bundle selection](../inire/router/_automatic.py#L225) · [Inference gate](../inire/router/_automatic.py#L762) · [Heading contract](../docs/user/api-reference.md#topologyoptions)
+
+## 18. Make the project links usable in release artifacts — Low
+
+The project and repository URLs are present as top-level keys in `[project]`, but the built wheel has neither a `Home-page` nor a `Project-URL` header. The README is copied into the wheel and into its long description with seven checkout-relative documentation links. The wheel contains none of those targets. One example is `docs/user/route-a-layout.md#define-the-inputs`, which resolves from the repository root and fails from the installed README.
+
+Declare the links in `[project.urls]` and give the released long description and installed README resolvable documentation links. Verify the wheel and source distribution metadata from fresh builds and check the links from outside the checkout. Keep the repository README's documentation useful when browsing the source. [Package metadata](../pyproject.toml#L1) · [Repository README](../README.md)
+
+## 19. Reuse connectivity work across residual net widths — Medium
+
+On a `1400 × 2800` board, use the 240 keepouts from item 6. Place 240 width-2 nets from `(5, 630 + 9*i, 0)` to `(45, 630 + 9*i + int(i >= 120), 0)`, with clearance 2. Direct planning locks the first 120 straights. The connectivity check finds no disconnected nets among the 120 remaining shifts. With uniform widths, it buffers 360 polygons and builds one union. Change the width of residual net `i` to `2 + 0.005*(i - 120)`. The test still finds no disconnected nets, while preparing 120 unions from 43,200 buffered polygons. Local interleaved probes took roughly 0.06 seconds and 6.8 seconds respectively.
+
+A separate 24-net automatic control with twelve straight locks and twelve mixed-width quarter turns reached this check twice and verified all 24 nets. Screen narrower nets against the widest residual width's free-space regions. Terminals already in one shared region can skip the narrower calculation. Keep the exact-width check where the shared result leaves connectivity unresolved. Compare disconnected IDs, lock selection, and coverage on mixed-width apertures and the corpus. [Connectivity check](../inire/router/_routing_policy.py#L117) · [Lock planning](../inire/router/_routing_policy.py#L155)
+
+## 20. Keep seed guidance from increasing the cost of free moves — Medium
+
+On a `120 × 100` board with no obstacles and zero clearance, use a width-2 net from `(10, 45, 0)` to `(100, 5, 270)`. Set lattice mode, eight expansion nodes, radius-10 quarter turns, no S-bends, visibility off, warm start off, one iteration, and refinement off. Set all four objective weights to zero. Supply `PathSeed((StraightSeed(80), Bend90Seed(10, "CW")))`. A matching move with computed cost zero receives a cost of 0.001 at the discount floor. The returned path stops after a straight at `(100, 45, 0)`.
+
+An in-memory probe capped the discounted cost at the original cost. On the same budget it verified the supplied prefix followed by a length-30 straight. Keep the discount nonincreasing while preserving its floor for moves whose original cost already exceeds the floor. Exercise zero and small positive original costs, seeded and unseeded search, and the low-length-cost benchmarks. [Guidance scoring](../inire/router/_astar_admission.py#L199)
+
+## Implementation order
+
+1. Fix bend admission, visibility coordinates, zero-iteration handling, and heading inference for seeded requests. Add targeted reproductions and run the timing-enabled suite. Enforce the worker deadline inside optional refinement and diagnostics.
+2. Evaluate the two congestion stopping rules independently. Check the reproduced coverage gains, preserve successful pair repairs, and measure the runtime cost of continuing through a plateau. Handle tied partial outcomes after the coverage changes.
+3. Correct pre-pair trace attribution separately from route selection. Update the expansion counters in a separate change so the metric baselines and any affected guardrails can be reconciled with measured work.
+4. Change seed verification order, mesh scheduling, ray-index retention, and lock connectivity independently after the correctness fixes. Use the large uniform- and mixed-width layouts, the seeded 240-net board, and narrow passages to check the tradeoffs. Update the walkthrough once the retained routing paths are clear.
+5. Correct the fixture unit conversion and compare old and new scores and paths separately from runtime router changes. Decouple the retry regression from the geometry planner's choice of candidates. Check the guidance discount against zero-cost and low-cost search.
+6. Validate performance scenario selection and update release metadata. Verify the report and distribution artifacts in scratch directories.
+
+For each routing change, compare verified net IDs across the corpus and holdout under all three profiles. Preserve coverage, validate changed routes against obstacles, fixed routes, peers, and board bounds, and report length and runtime changes over the common verified nets. Use the full timing-enabled suite before combining changes.
+
+## Baseline verification
+
+- All 389 tests passed with performance checks enabled. Ruff passed. The local environment used Python 3.13.18, Shapely 2.1.2, and GEOS 3.13.1.
+- All 152 corpus and retry-holdout boards were checked with `matched-budget`, `public-defaults`, and `corpus-regression`. Each profile produced 2,245 verified routes. Independent geometry checks agreed with the reports, and zero-node seed replays reproduced endpoint poses, lengths, and polygon outlines.
+- The geometry sweeps covered 96 legal primitive seed replays, 384 active searches across four routing modes, 500 generated corridor plans, 4,320 physical-index comparisons, and 1,077 ray-intersection comparisons. They produced no additional findings.
+- Five benchmark cases matched on geometry, counters, and traces across two Python hash seeds, with and without callbacks. The package archives passed content checks and the extracted wheel routed a guide case in the local environment. The documented `offset-gates` comparison also ran successfully with the current command.
+- A follow-up sweep across 75 boards and three modes checked iteration handoff and selected partial geometry. Four of the 225 runs stopped at the pair-repair handoff before the configured iteration limit. Bypassing only that condition improved coverage in two runs, both on `blocking-turn-room`.
+- The follow-up baseline again passed all 389 timing-enabled tests and Ruff. Another 144 rotated uniform- and mixed-width layouts verified from seed and agreed with the capacity and port-spacing checks.
+- In 18 benchmark CLI mode and policy runs, verified outcomes agreed with the selected stages and reported cost entries. Four retry samples on `stress-refine-return-shelf` each verified all four nets and reported placement data for those same net IDs.
+
+## Previous closing review
+
+The next full review pass after items 12 and 13 found no additional issues.
+
+- Independently checked all 152 corpus and holdout boards under each of the three profiles on both Python 3.13.18 with Shapely 2.1.2 and GEOS 3.13.1, and Python 3.14.10 with Shapely 2.2.0 and GEOS 3.15.0. Each environment and profile verified 2,245 routes. Checked endpoint poses, polygon validity and clearance, and geometry and lengths after replay.
+- On each dependency combination, 648 generated compound paths replayed from seeds and 96 active mixed-width gate layouts met their bounds and clearances. Callbacks, traces, and final reports agreed. The active control layouts returned equal paths and work counts with diagnostics enabled.
+- Built the wheel and source archive and matched all 40 runtime modules in the wheel against the checkout. Exercised automatic, off, guide, and seed routing from the extracted wheel on both environments. All 12 advanced examples verified, the fixture export and five documentation figures regenerated byte for byte, and the local file links across the 15 active documentation pages resolved.
+- All 389 timing-enabled tests and Ruff passed in the lockfile environment. The Python 3.14 suite passed 387 tests, skipped the opt-in performance test, and reproduced the one retry assertion failure in item 13.
+
+## Additional review of deadlines and diagnostics
+
+- All 389 timing-enabled tests and Ruff passed again. Across 128 seeded foldback controls with varied orientation, radius, width, spacing, and routing mode, refinement preserved endpoint poses, clearance, and route validity. All 128 changed placement without increasing the configured path cost.
+- The deadline probes in item 14 exercised real frontier searches and refinement with a controlled clock. A sweep of 225 bounded runs produced one pre-pair trace, whose metadata matched the saved layout. The fan-out with seed 44 and a separate three-net control both reproduced the attribution issue in item 15.
+
+## Full-codebase review passes
+
+The expanded review took its scope from the 190 tracked files at `f6e7bac`, including 110 Python files. It covered library modules, tests and fixtures, reporting and import/export commands, examples and visualizations, documentation and archived reports, and packaging and dependency configuration. The first full-codebase pass added items 16–18 and found the imported grid omission in item 12. The release and link checks then added the missing installed-documentation targets in item 18 and the archived link in item 7.
+
+| Area | Evidence gathered in the follow-up passes |
+| --- | --- |
+| Public API, geometry, and collision state | 648 compound seed replays exercised terminal poses, clearance, snapshots, and callbacks. An independent oracle agreed with 1,920 physical-index queries after insertions, removals, and replacements. All 36 concurrent routing calls matched serial placements and coverage. |
+| Search, constructive planners, congestion, and refinement | Independent clearance and seed-replay checks covered all 152 corpus and holdout boards under the three profiles on Python 3.11, 3.13, and 3.14. Each profile verified 2,245 routes in each environment. Another 96 mixed-width gate controls preserved paths and search work with diagnostics enabled. The earlier 128 refinement controls covered rotated and mirrored paths with several widths and spacings. A same-core check of the slower splitter-tree fixture recorded the same 15,653 expansions and the same verified IDs on Python 3.11 and 3.13. |
+| Tests and diagnostics | The lockfile suite passed all 389 tests with performance checks enabled and Ruff passed. The Python 3.11 suite passed 388 tests with the opt-in timing test skipped. A branch-instrumented Python 3.14 run passed 377 tests with performance gates and the known item 13 assertion deselected. The deadline and pre-pair counterexamples were checked against the saved layouts. |
+| Benchmarks, scripts, and data | All 16 script entry points accepted `--help`. Exercised benchmark comparisons, two-worker retries, parity snapshots, performance reports, four trace exports, and both waypoint entry points. All 27 exported paths replayed and independently met clearance. The external importer reproduced the checked-in data byte for byte from the two pinned archives. |
+| Examples, visualization, and documentation | Executed the user-guide Python snippets with their documented inputs, ran nine numbered examples, and regenerated 24 documentation and gallery figures. Fifteen figures matched byte for byte. The changed gallery placements retained verified coverage and matched the accompanying descriptions. Checked 388 local links across 30 distinct tracked Markdown pages, including the archive and historical plans. The broken archive fragment is recorded in item 7. |
+| Build and dependency compatibility | The lockfile check passed offline. Built the wheel and source archive and rebuilt the wheel from the unpacked archive. The 40 runtime Python files matched the checkout. The installed wheel routed in four modes and serialized results on Python 3.11.11 with Shapely 2.1.0, GEOS 3.13.1, and NumPy 1.26.4 and 2.2.6. The four plotting helpers produced PNGs on the minimum Python and Shapely versions. The unpacked source distribution ran the waypoint export to 9/9. |
+
+The final full-codebase pass after documenting those findings found no additional issues. It reran the suite, independent corpus verification, replay and index controls, command and data round-trips, source and installed documentation checks, and release builds. The numbered findings record the fixes identified at that review baseline.
+
+## Additional review of lock connectivity and guidance costs
+
+The next requested pass added items 19 and 20. A two-width aperture control classified the wide net as disconnected and retained the narrow net. The valid eight-node control path also verified independently in seed replay.
+
+All 389 timing-enabled tests passed and Ruff passed. The offline lockfile check, wheel and source archive rebuild, and a smoke test of all 16 command entry points passed again. Benchmark, retry, parity, waypoint, and diagnostics commands produced their artifacts in scratch directories.
+
+## Review pass after items 19 and 20
+
+This pass found no additional issues at `f6e7bac`. It covered the routing and geometry modules, public results, benchmark and diagnostic commands, fixture data, documentation and generated figures, and release artifacts.
+
+- All 389 tests passed with performance checks enabled, Ruff passed, and the offline lockfile check passed. Independent geometry and seed-replay checks verified 2,245 routes per profile across all 152 corpus and holdout boards.
+- Search-time and final same-net collision checks agreed on 1,008 generated paths, including 244 with overlaps. Across 240 bounded search configurations, traced and ordinary routing agreed on paths and work counts. All 96 verified placements in that matrix met clearance and bounds. Compound replay, mixed-width gate, physical index mutation, and concurrent placement controls passed again.
+- The review checked all 16 script entry points. Selected coverage agreed with reported costs and placement data in 18 comparison records and eight retry samples. Both pinned archive imports regenerated the external fixture data byte for byte. The twelve core documentation figures also regenerated byte for byte.
+- The wheel and source archive rebuilt successfully and all 40 runtime modules matched. The extracted wheel passed routing in the four search modes and result serialization on Python 3.11 with Shapely 2.1.0.
diff --git a/pyproject.toml b/pyproject.toml
index e442040..3871a0b 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -7,8 +7,6 @@ license = { file = "LICENSE.md" }
authors = [
{ name="Jan Petykiewicz", email="jan@mpxd.net" },
]
-homepage = "https://mpxd.net/code/jan/inire"
-repository = "https://mpxd.net/code/jan/inire"
classifiers = [
"Programming Language :: Python :: 3",
"Development Status :: 4 - Beta",
@@ -28,6 +26,11 @@ dependencies = [
"matplotlib",
]
+[project.urls]
+Homepage = "https://mpxd.net/code/jan/inire"
+Repository = "https://mpxd.net/code/jan/inire"
+Documentation = "https://mpxd.net/code/jan/inire/src/branch/topo/DOCS.md"
+
[dependency-groups]
dev = [
"hypothesis>=6.151.9",
diff --git a/scripts/diff_performance_baseline.py b/scripts/diff_performance_baseline.py
index 4fd9eff..e51ef89 100644
--- a/scripts/diff_performance_baseline.py
+++ b/scripts/diff_performance_baseline.py
@@ -40,8 +40,11 @@ def _current_snapshots(
selected_scenarios: tuple[str, ...] | None,
*,
include_performance_only: bool,
+ baseline: dict[str, dict[str, object]],
) -> dict[str, dict[str, object]]:
- snapshots = capture_scenario_snapshots(selected_scenarios, include_performance_only=include_performance_only)
+ snapshots = capture_scenario_snapshots(
+ selected_scenarios, include_performance_only=include_performance_only, baseline_scenarios=baseline.keys(),
+ )
return {snapshot.name: asdict(snapshot) for snapshot in snapshots}
@@ -201,7 +204,10 @@ def main() -> None:
metrics = tuple(args.metrics) if args.metrics else SUMMARY_KEYS
_validate_metrics(metrics)
baseline = _load_baseline(args.baseline, selected)
- current = _current_snapshots(selected, include_performance_only=args.include_performance_only)
+ try:
+ current = _current_snapshots(selected, include_performance_only=args.include_performance_only, baseline=baseline)
+ except ValueError as exc:
+ parser.error(str(exc))
report = _render_report(baseline, current, metrics)
if args.output is not None:
diff --git a/scripts/record_performance_baseline.py b/scripts/record_performance_baseline.py
index 3df56c0..3cedbe9 100644
--- a/scripts/record_performance_baseline.py
+++ b/scripts/record_performance_baseline.py
@@ -99,10 +99,12 @@ def main() -> None:
repo_root = Path(__file__).resolve().parents[1]
output_dir = repo_root / "archive" / "routing" if args.output_dir is None else args.output_dir.resolve()
- output_dir.mkdir(parents=True, exist_ok=True)
-
selected = tuple(args.scenarios) if args.scenarios else None
- payload = _build_payload(selected, include_performance_only=args.include_performance_only)
+ try:
+ payload = _build_payload(selected, include_performance_only=args.include_performance_only)
+ except ValueError as exc:
+ parser.error(str(exc))
+ output_dir.mkdir(parents=True, exist_ok=True)
json_path = output_dir / "performance_baseline.json"
markdown_path = output_dir / "performance.md"