Keep ambiguous S-bend templates local to affected nets

This commit is contained in:
Jan Petykiewicz 2026-11-29 23:56:47 -08:00
commit 867aab8fa2
10 changed files with 123 additions and 22 deletions

View file

@ -40,7 +40,7 @@ The fields below appear in constructor order. Use one layout unit for coordinate
`PathSeed(segments)` holds an ordered tuple of `StraightSeed(length)`, `Bend90Seed(radius, direction)`, and `SBendSeed(offset, radius)` moves. Lengths and radii must be finite and positive. When routing a seed, straight lengths are rounded to the nearest grid unit, with ties rounded to even and a minimum of one unit. Bend directions are `"CW"` and `"CCW"`. S-bend offsets must be nonzero integers with magnitude less than twice the radius. A seed is materialized from the net's current start port using its width and the run's geometry options. Moves that use a generated circular outline or a proxy derived from one require a radius of at least half the net width.
A disabled radius or offset discards the seed and sets the net's `seed_error`. Active search can route the net from scratch. Zero-node replay still checks the other seeds. Unknown net IDs raise `ValueError`.
A disabled radius or offset or an ambiguous S-bend outline discards the seed and sets the net's `seed_error`. Active search can route the net from scratch. Zero-node replay still checks the other seeds. Unknown net IDs raise `ValueError`.
## Results
@ -51,7 +51,7 @@ A disabled radius or offset discards the seed and sets the net's `seed_error`. A
| `RoutingResult.requested_net` and `effective_net` | The net as supplied and the net used by the worker, including resolved headings. |
| `RoutingResult.path` | Ordered path components from the source to the last reached state. Each component carries its move specification and placed start and end ports. An unroutable result has an empty path. |
| `RoutingResult.reached_target` | Whether the path reached the target position and heading. With heading inference, the check uses the chosen heading. Read `is_valid` for the result of geometry verification. |
| `RoutingResult.report` | `total_length` in layout units plus static, dynamic, and self-collision counts. `out_of_bounds` flags geometry outside the board. `invalid_geometry` flags invalid polygons or a rejected seed that produced no path. `seed_error` describes a seed rejected by the configured move options or by geometry preparation. `terminal_error` identifies coincident ports or an inaccessible start or target face. |
| `RoutingResult.report` | `total_length` in layout units plus static, dynamic, and self-collision counts. `out_of_bounds` flags geometry outside the board. `invalid_geometry` flags invalid polygons or a rejected seed that produced no path. `seed_error` describes a seed rejected by the configured move options or by geometry preparation. `terminal_error` identifies coincident ports or an inaccessible start or target face. `sbend_template_error` identifies S-bend moves skipped because multiple outlines matched the net width. A route using other moves can still complete. |
| `RoutingResult.as_seed()` | The ordered moves for [saving a placement recipe](route-a-layout.md#save-a-placement-recipe) or replaying a path. |
| `RoutingResult.locked_geometry` | Physical polygons checked during routing. Use these to inspect the route or [reserve a completed net](route-a-layout.md#reuse-an-existing-route). |
| `RoutingRunResult.automatic` | In automatic mode, the selected planner, verified IDs, stage history, and any capacity or port-conflict bound. `None` for explicit modes. |
@ -95,7 +95,7 @@ For structured logging, `dataclasses.asdict(run)` preserves the per-net fields.
| `bend_physical_length` | `None` | Optional authored centerline length for the shared custom 90-degree template, including tangent extensions. Search, refinement, and reports use it when supplied. |
| `distance_heuristic_weight` | `1.0` | Finite, nonnegative multiplier for the remaining-distance term only. Increase it to favor progress toward the target relative to estimated turn penalties. The routed path's objective stays the same. |
A custom S-bend outline uses local coordinates. Its input face is centered at `(0, 0)`, its output face at `(span, offset)`, and both ports face east. Use the same grid span as `SBendSeed(offset, radius)`, including any tangent extension to reach the output face. For example, an offset of `40` with radius `50` has its output at `(80, 40)`. The router rotates and translates the entire outline and uses it for collision checks and seed replay. Supply a separate outline to customize the opposite offset. Width matching allows a relative difference of `1e-12` to account for floating-point conversions. An ambiguous match raises an error. Unmatched moves use the circular S-bend. Set `SBendOutline.length` to use a process-specific centerline length for scoring, refinement, and reporting. The default is the nominal circular length. Automatic mode uses lattice search when an enabled outline matches a net width. Bundle mode requires circular bends for its nets.
A custom S-bend outline uses local coordinates. Its input face is centered at `(0, 0)`, its output face at `(span, offset)`, and both ports face east. Use the same grid span as `SBendSeed(offset, radius)`, including any tangent extension to reach the output face. For example, an offset of `40` with radius `50` has its output at `(80, 40)`. The router rotates and translates the entire outline and uses it for collision checks and seed replay. Supply a separate outline to customize the opposite offset. Width matching allows a relative difference of `1e-12` to account for floating-point conversions. If multiple outlines apply to the same move, `route()` skips that move for the affected net and sets `sbend_template_error` in the final result and iteration callbacks. Direct calls to `SearchOptions.sbend_template()` and `sbend_outline()` raise `ValueError` for an ambiguous match. Moves with no matching outline use the circular S-bend. Set `SBendOutline.length` to use a process-specific centerline length for scoring, refinement, and reporting. The default is the nominal circular length. Automatic mode uses lattice search when an enabled outline matches a net width. Bundle mode requires circular bends for its nets.
Match custom outline faces to their declared ports and width. `SBendOutline` warns about a mismatch at construction. For a custom 90-degree outline used in a result, `route()` warns once per radius and net width. Replay an `SBendSeed` with the same outlines and bend settings.

View file

@ -79,6 +79,7 @@ def route(
iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None = None,
) -> RoutingRunResult:
resolved_options = RoutingOptions() if options is None else options
search = resolved_options.search
requested = {net.net_id: net for net in problem.nets}
coincident = {
net.net_id: RoutingResult(
@ -91,11 +92,18 @@ def route(
for net in problem.nets
if net.start == net.target
}
template_errors = {}
if search.sbend_outlines and search.active_sbend_outlines:
widths = dict.fromkeys(net.width for net in problem.nets)
errors_by_width = {width: search._sbend_template_error(width) for width in widths}
template_errors = {
net.net_id: error for net in problem.nets if (error := errors_by_width[net.width]) is not None
}
seed_errors = {}
for net_id, seed in problem.initial_paths.items():
if net_id not in requested:
raise ValueError(f"Initial path provided for unknown net: {net_id}")
if net_id not in coincident and (error := resolved_options.search.seed_geometry_error(seed)) is not None:
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 coincident or seed_errors:
problem = replace(
@ -117,6 +125,9 @@ def route(
report = replace(result.report, seed_error=error, invalid_geometry=result.report.invalid_geometry or not result.path)
attached[net_id] = replace(result, report=report)
attached.update(coincident)
for net_id, error in template_errors.items():
if (result := attached.get(net_id)) is not None:
attached[net_id] = replace(result, report=replace(result.report, sbend_template_error=error))
return attached
def notify(iteration: int, results: dict[str, RoutingResult]) -> None:
@ -135,11 +146,11 @@ def route(
results = attach_requested(run.results_by_net)
if coincident:
results = {net_id: results[net_id] for net_id in requested}
_, physical_bend = _resolve_bend_geometry(resolved_options.search)
_, physical_bend = _resolve_bend_geometry(search)
if isinstance(physical_bend, _Polygon):
_warn_bend_port_mismatches(results, requested)
run = replace(run, results_by_net=results)
if (coincident or seed_errors) and run.conflict_trace:
if (coincident or seed_errors or template_errors) and run.conflict_trace:
from .router._route_traces import complete_final_conflict_trace # noqa: PLC0415
run = complete_final_conflict_trace(run)

View file

@ -103,6 +103,10 @@ class _SearchOptionsCache:
_active_sbend_outlines: tuple[SBendOutline, ...]
class _AmbiguousSBendOutlineError(ValueError):
pass
@dataclass(frozen=True, slots=True)
class SearchOptions(_SearchOptionsCache):
node_limit: int = 1000000
@ -195,13 +199,29 @@ class SearchOptions(_SearchOptionsCache):
def sbend_outlines_for_width(self, width: float) -> Iterator[SBendOutline]:
return (outline for outline in self.active_sbend_outlines if _outline_width_matches(outline.width, width))
def _sbend_templates_for_width(self, width: float) -> dict[tuple[float, float], SBendOutline | None]:
# A key mapped to None is ambiguous. A missing key uses a circular S-bend.
templates: dict[tuple[float, float], SBendOutline | None] = {}
for outline in self.sbend_outlines_for_width(width):
key = outline.offset, outline.radius
templates[key] = None if key in templates else outline
return templates
def _sbend_template_error(self, width: float) -> str | None:
ambiguous = [
f"(offset {offset:g}, radius {radius:g})"
for (offset, radius), outline in self._sbend_templates_for_width(width).items()
if outline is None
]
return f"Ambiguous S-bend outlines for width {width!r} at {', '.join(ambiguous)}" if ambiguous else None
def has_applicable_sbend_outline(self, widths: Iterable[float]) -> bool:
return bool(self.active_sbend_outlines) and any(next(self.sbend_outlines_for_width(width), None) is not None for width in widths)
def sbend_template(self, offset: float, radius: float, width: float) -> SBendOutline | None:
matches = [outline for outline in self.sbend_outlines_for_width(width) if (outline.offset, outline.radius) == (offset, radius)]
if len(matches) > 1:
raise ValueError(f"Ambiguous S-bend outlines for offset {offset}, radius {radius}, width {width}")
raise _AmbiguousSBendOutlineError(f"Ambiguous S-bend outlines for offset {offset}, radius {radius}, width {width}")
return matches[0] if matches else None
def sbend_outline(self, offset: float, radius: float, width: float) -> Polygon | None:

View file

@ -31,6 +31,12 @@ class RoutingReport:
invalid_geometry: bool = False
seed_error: str | None = None
terminal_error: str | None = None
sbend_template_error: str | None = None
def __setstate__(self, state: list[object]) -> None:
# Reports pickled before the template diagnostic have one fewer field.
for index, item in enumerate(fields(self)):
object.__setattr__(self, item.name, state[index] if index < len(state) else item.default)
@property
def intrinsic_collision_count(self) -> int:

View file

@ -38,11 +38,11 @@ def process_move(
physical_type = config.bend_physical_geometry
physical_key = id(physical_type) if isinstance(physical_type, Polygon) else physical_type
search = context.options.search
template = (
search.sbend_template(params[0], params[1], net_width)
if move_class == "sbend" and search.sbend_outlines and search.active_sbend_outlines
else None
)
template = None
if move_class == "sbend" and config.sbend_templates:
template = config.sbend_templates.get(params)
if template is None and params in config.sbend_templates:
return
outline = template.polygon if template else None
self_dilation = context.cost_evaluator.collision_engine.clearance / 2.0

View file

@ -335,9 +335,9 @@ def expand_moves(
)
max_sbend_r = max(search_options.sbend_radii) if search_options.sbend_radii else 0.0
templates = config.sbend_templates
custom_sbends = (
{(outline.offset, outline.radius) for outline in search_options.sbend_outlines_for_width(net_width)}
if search_options.sbend_outlines and search_options.active_sbend_outlines else ()
{key for key, template in templates.items() if template is not None} if templates else ()
)
if not bend_fits_width(max_sbend_r, net_width) and not custom_sbends:
return

View file

@ -14,7 +14,7 @@ if TYPE_CHECKING:
from inire.geometry.components import BendCollisionModel, BendPhysicalGeometry, ComponentResult
from inire.geometry.primitives import Port
from inire.model import RoutingOptions, RoutingProblem
from inire.model import RoutingOptions, RoutingProblem, SBendOutline
from inire.router._topology import Corridor
from inire.router.cost import CostEvaluator
from inire.seeds import PathSegmentSeed
@ -99,6 +99,7 @@ class SearchRunConfig:
hard_congestion: bool = False
propose_guidance_moves: bool = False
expired: Callable[[], bool] | None = field(default=None, repr=False, compare=False)
sbend_templates: dict[tuple[float, float], SBendOutline | None] | None = None
def estimate_remaining_cost(self, current: Port, target: Port, context: AStarContext) -> float:
evaluator = context.cost_evaluator

View file

@ -1,6 +1,7 @@
from __future__ import annotations
import heapq
from dataclasses import replace
from math import inf
from typing import TYPE_CHECKING
@ -60,6 +61,10 @@ def route_astar(
metrics = AStarMetrics()
metrics.reset_per_route()
search = context.options.search
if search.sbend_outlines and search.active_sbend_outlines:
config = replace(config, sbend_templates=search._sbend_templates_for_width(net_width))
context.ensure_static_caches_current()
context.cost_evaluator.set_target(target)
open_set: list[_AStarNode] = []

View file

@ -5,7 +5,7 @@ from typing import TYPE_CHECKING
from inire.geometry.components import (
ComponentPreparationError, build_component, component_endpoint, prepare_component_sampling,
)
from inire.model import resolve_bend_geometry
from inire.model import _AmbiguousSBendOutlineError, resolve_bend_geometry
from inire.seeds import Bend90Seed, SBendSeed, StraightSeed
if TYPE_CHECKING:
@ -29,14 +29,14 @@ def seed_preparation_error(seed: PathSeed, *, start: Port, net_width: float, sea
proxy, physical = resolve_bend_geometry(search)
for index, segment in enumerate(seed.segments, start=1):
kind, parameters = seed_move(segment)
template = search.sbend_template(segment.offset, segment.radius, net_width) if isinstance(segment, SBendSeed) else None
try:
template = search.sbend_template(segment.offset, segment.radius, net_width) if isinstance(segment, SBendSeed) else None
start = component_endpoint(start, kind, parameters)
prepare_component_sampling(
kind, parameters, net_width, collision_type=proxy, physical_geometry_type=physical,
dilation=clearance / 2, sbend_outline=template.polygon if template is not None else None,
)
except (ComponentPreparationError, OverflowError) as exc:
except (ComponentPreparationError, OverflowError, _AmbiguousSBendOutlineError) as exc:
return f"segment {index} ({type(segment).__name__}) {exc}"
return None
@ -68,8 +68,8 @@ def materialize_path_seed(
for index, segment in enumerate(seed.segments, start=1):
kind, parameters = seed_move(segment)
template = search.sbend_template(segment.offset, segment.radius, net_width) if isinstance(segment, SBendSeed) else None
try:
template = search.sbend_template(segment.offset, segment.radius, net_width) if isinstance(segment, SBendSeed) else None
component = build_component(
current,
net_width,
@ -83,7 +83,7 @@ def materialize_path_seed(
bounds=None if diagnostic else bounds,
physical_length=search.bend_physical_length if kind == "bend90" else (template.length if template else None),
)
except (ComponentPreparationError, OverflowError) as exc:
except (ComponentPreparationError, OverflowError, _AmbiguousSBendOutlineError) as exc:
if diagnostic:
raise SeedMaterializationError(f"segment {index} ({type(segment).__name__}) {exc}") from exc
return None

View file

@ -629,16 +629,74 @@ def test_search_checks_materialized_quarter_turn_face() -> None:
assert result.as_seed() == PathSeed((Bend90Seed(20, "CCW"),))
def test_custom_sbend_outline_rejects_duplicate_and_ambiguous_widths() -> None:
def _nearby_sbend_outlines() -> tuple[SBendOutline, SBendOutline]:
outline = SBendOutline(40, 50, 0.3, _sbend_strip(40, half_width=0.15))
return outline, replace(outline, width=0.3 * (1 + 1.5e-12))
def test_custom_sbend_outline_rejects_duplicate_and_ambiguous_widths() -> None:
outline, other = _nearby_sbend_outlines()
with pytest.raises(ValueError, match="Duplicate S-bend outline"):
SearchOptions(sbend_radii=(50,), sbend_outlines=(outline, replace(outline, width=0.1 + 0.2)))
other = replace(outline, width=0.3 * (1 + 1.5e-12))
options = SearchOptions(sbend_radii=(50,), sbend_outlines=(outline, other))
with pytest.raises(ValueError, match="Ambiguous S-bend outlines"):
options.sbend_outline(40, 50, (outline.width + other.width) / 2)
@pytest.mark.parametrize("mode", ["automatic", "off", "guide", "seed"])
def test_ambiguous_sbend_outline_reports_the_affected_net_without_blocking_straights(mode) -> None:
outline, other = _nearby_sbend_outlines()
width = (outline.width + other.width) / 2
peer = NetSpec("peer", Port(10, 80, 0), Port(90, 80, 0), width=0.5)
line = NetSpec("line", Port(10, 10, 0), Port(50, 10, 0), width=width)
problem = RoutingProblem((0, 0, 100, 100), (peer, line), clearance=0)
options = RoutingOptions(
search=SearchOptions(node_limit=10, bend_radii=(), sbend_radii=(50,), sbend_outlines=(outline, other)),
congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False),
topology=TopologyOptions(mode=mode),
diagnostics=DiagnosticsOptions(capture_conflict_trace=True),
)
callbacks = []
run = route(problem, options=options, iteration_callback=lambda _, results: callbacks.append(results))
assert all(result.is_valid for result in run.results_by_net.values())
error = f"Ambiguous S-bend outlines for width {width!r} at (offset 40, radius 50)"
assert run.results_by_net["line"].report.sbend_template_error == error
assert run.results_by_net["peer"].report.sbend_template_error is None
assert callbacks
assert callbacks[-1]["line"].report.sbend_template_error == error
assert {net.net_id: net.report.sbend_template_error for net in run.conflict_trace[-1].nets} == {"peer": None, "line": error}
disabled = replace(options, search=replace(options.search, sbend_offsets=()))
assert route(problem, options=disabled).results_by_net["line"].report.sbend_template_error is None
@pytest.mark.parametrize("mode", ["automatic", "off"])
@pytest.mark.parametrize("node_limit", [0, 20])
def test_ambiguous_sbend_outline_is_skipped_in_search_and_seed_replay(mode, node_limit) -> None:
outline, other = _nearby_sbend_outlines()
width = (outline.width + other.width) / 2
shift = NetSpec("shift", Port(10, 10, 0), Port(90, 50, 0), width=width)
peer = NetSpec("peer", Port(10, 70, 0), Port(90, 110, 0), width=outline.width)
seed = PathSeed((SBendSeed(40, 50),))
paths = {} if node_limit else {net.net_id: seed for net in (shift, peer)}
problem = RoutingProblem((0, 0, 100, 120), (shift, peer), initial_paths=paths, clearance=0)
options = RoutingOptions(
search=SearchOptions(node_limit=node_limit, bend_radii=(), sbend_radii=(50,), sbend_offsets=(40,), sbend_outlines=(outline, other)),
congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False),
topology=TopologyOptions(mode=mode),
)
results = route(problem, options=options).results_by_net
assert not results["shift"].is_valid
assert not any(isinstance(component.move_spec, SBendSeed) for component in results["shift"].path)
assert results["peer"].is_valid
assert results["peer"].path[0].physical_geometry[0].equals(translate(outline.polygon, 10, 70))
if not node_limit:
assert "segment 1 (SBendSeed) Ambiguous S-bend outlines" in results["shift"].report.seed_error
@pytest.mark.parametrize("contact", ["face", "rounding", "gap", "extra_edge", "extra_point", "wide_face", "overlap"])
@pytest.mark.parametrize("heading", [0, 90])
def test_custom_sbend_join_allows_boundary_contact_and_rejects_area_overlap(contact, heading) -> None: