Verify physical bend joins and preserve fine-grid arc accuracy

This commit is contained in:
Jan Petykiewicz 2026-11-28 20:01:29 -08:00
commit a86e0a4f5a
9 changed files with 521 additions and 36 deletions

View file

@ -82,7 +82,9 @@ To read a route's polygons and write them to a test file, follow the [geometry e
A custom S-bend outline uses local coordinates. Its input face is centered at `(0, 0)`, its output face at `(span, offset)`, and both ports face east. Use the same grid span as `SBendSeed(offset, radius)`, including any tangent extension to reach the output face. For example, an offset of `40` with radius `50` has its output at `(80, 40)`. The router rotates and translates the entire outline and uses it for collision checks and export. Supply a separate outline to customize the opposite offset. Unmatched moves use the circular S-bend, and matching moves use the same nominal length as that circular bend for scoring. Automatic mode uses lattice search when custom outlines are supplied. Bundle mode requires circular bends. A custom S-bend outline uses local coordinates. Its input face is centered at `(0, 0)`, its output face at `(span, offset)`, and both ports face east. Use the same grid span as `SBendSeed(offset, radius)`, including any tangent extension to reach the output face. For example, an offset of `40` with radius `50` has its output at `(80, 40)`. The router rotates and translates the entire outline and uses it for collision checks and export. Supply a separate outline to customize the opposite offset. Unmatched moves use the circular S-bend, and matching moves use the same nominal length as that circular bend for scoring. Automatic mode uses lattice search when custom outlines are supplied. Bundle mode requires circular bends.
When migrating a half-arc template, supply the complete outline through `sbend_outlines` and keep `bend_physical_geometry` for custom 90-degree bends. Replay an `SBendSeed` with the same outlines and bend settings to recover its physical geometry. When migrating a half-arc template, supply the complete outline through `sbend_outlines` and keep `bend_physical_geometry` for custom 90-degree bends. Both terminal faces of each custom polygon must be centered on their ports and match the routed width. A custom 90-degree template is shared across nets, so it can only be used by nets whose width matches its faces. Replay an `SBendSeed` with the same outlines and bend settings to recover its physical geometry.
Circular bends approximate the outer edge within a sagitta of 0.01 layout units. The router also sizes the subdivision for the outer edge of a clearance-expanded circular proxy.
### ObjectiveWeights ### ObjectiveWeights

View file

@ -7,6 +7,7 @@ from shapely.geometry import box
from shapely.strtree import STRtree from shapely.strtree import STRtree
from inire.constants import TOLERANCE_LINEAR from inire.constants import TOLERANCE_LINEAR
from inire.geometry.components import components_join
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Sequence from collections.abc import Sequence
@ -43,22 +44,48 @@ def components_overlap(
): ):
return False return False
if at_join:
port_a, port_b = component_a.end_port, component_b.start_port
axis = 0 if port_a.r % 180 == 0 else 1
normal, lateral = (port_a.x, port_a.y) if axis == 0 else (port_a.y, port_a.x)
face_a = _face_span(component_a, arrival=True)
face_b = _face_span(component_b, arrival=False)
if port_a != port_b or face_a is None or face_b is None:
at_join = False
else:
lo = lateral + max(face_a[0], face_b[0])
hi = lateral + min(face_a[1], face_b[1])
for polygon_a in polygons_a: for polygon_a in polygons_a:
for polygon_b in polygons_b: for polygon_b in polygons_b:
if at_join: if at_join:
# Sampling a bend can leave sub-tolerance slivers at its shared face. # Sampling a bend can leave sub-tolerance slivers at its shared face.
overlap = polygon_a.intersection(polygon_b) overlap = polygon_a.intersection(polygon_b)
if not overlap.is_empty: if not overlap.is_empty:
port = component_a.end_port
axis, position = (0, port.x) if port.r % 180 == 0 else (1, port.y)
bounds = overlap.bounds bounds = overlap.bounds
if bounds[axis] < position - TOLERANCE_LINEAR or bounds[axis + 2] > position + TOLERANCE_LINEAR: if (
bounds[axis] < normal - TOLERANCE_LINEAR
or bounds[axis + 2] > normal + TOLERANCE_LINEAR
or bounds[1 - axis] < lo - TOLERANCE_LINEAR
or bounds[3 - axis] > hi + TOLERANCE_LINEAR
):
return True return True
elif polygon_a.intersects(polygon_b) and (prefer_actual or not polygon_a.touches(polygon_b)): elif polygon_a.intersects(polygon_b) and (prefer_actual or not polygon_a.touches(polygon_b)):
return True return True
return False return False
def _face_span(component: ComponentResult, *, arrival: bool) -> tuple[float, float] | None:
if component.standard_faces and component.width is not None:
return -component.width / 2, component.width / 2
face = component.port_faces[int(arrival)]
return (face[0], face[1]) if face is not None else None
def invalid_component_join(left: ComponentResult, right: ComponentResult) -> bool:
return not components_join(left, right) or components_overlap(left, right, prefer_actual=True, at_join=True)
def count_path_self_collisions(components: Sequence[ComponentResult]) -> int: def count_path_self_collisions(components: Sequence[ComponentResult]) -> int:
internal_collisions = 0 internal_collisions = 0
for component in components: for component in components:

View file

@ -2,7 +2,7 @@ from __future__ import annotations
from dataclasses import dataclass, field from dataclasses import dataclass, field
from itertools import pairwise from itertools import pairwise
from math import ceil, pi from math import asin, ceil, pi, radians, sqrt
from typing import TYPE_CHECKING, Literal from typing import TYPE_CHECKING, Literal
import numpy import numpy
@ -34,24 +34,45 @@ def path_within_board(path: Iterable[ComponentResult], board: Polygon) -> bool:
return all(board.covers(shape) for component in path for shape in component.physical_geometry) return all(board.covers(shape) for component in path for shape in component.physical_geometry)
def _has_port_face(polygon: Polygon, port: Port, *, arrival: bool) -> bool: PortFace = tuple[float, float, float, float]
def _port_face(polygon: Polygon, port: Port, *, arrival: bool) -> PortFace | None:
"""Find a centered port face with material on the required side.""" """Find a centered port face with material on the required side."""
axis = 0 if port.r % 180 == 0 else 1 axis = 0 if port.r % 180 == 0 else 1
position = (port.x, port.y) position = (port.x, port.y)
exterior = polygon.exterior exterior = polygon.exterior
coordinates = numpy.asarray(exterior.coords) coordinates = numpy.asarray(exterior.coords)
on_plane = numpy.abs(coordinates[:, axis] - position[axis]) <= TOLERANCE_LINEAR normal = coordinates[:, axis] - position[axis]
on_plane = numpy.abs(normal) <= TOLERANCE_LINEAR
lateral = coordinates[:, 1 - axis] - position[1 - axis] lateral = coordinates[:, 1 - axis] - position[1 - axis]
lower = numpy.minimum(lateral[:-1], lateral[1:]) lower = numpy.minimum(lateral[:-1], lateral[1:])
upper = numpy.maximum(lateral[:-1], lateral[1:]) upper = numpy.maximum(lateral[:-1], lateral[1:])
at_port = on_plane[:-1] & on_plane[1:] & (lower <= TOLERANCE_LINEAR) & (upper >= -TOLERANCE_LINEAR)
# The interior is left of a counterclockwise exterior edge. # The interior is left of a counterclockwise exterior edge.
forward = 1 if port.r < 180 else -1 forward = 1 if port.r < 180 else -1
inward = forward if not arrival else -forward inward = forward if not arrival else -forward
left = (lateral[1:] - lateral[:-1]) * (1 if axis == 1 else -1) left = (lateral[1:] - lateral[:-1]) * (1 if axis == 1 else -1)
interior = left if exterior.is_ccw else -left interior = left if exterior.is_ccw else -left
at_port &= interior * inward > 0 edges = numpy.flatnonzero(on_plane[:-1] & on_plane[1:] & (interior * inward > 0))
return bool(numpy.any(at_port & (lower < 0)) and numpy.any(at_port & (upper > 0))) intervals = sorted((lower[i], upper[i], min(normal[i:i + 2]), max(normal[i:i + 2])) for i in edges)
spans: list[PortFace] = []
for lo, hi, near, far in intervals:
if spans and lo <= spans[-1][1]:
prev_lo, prev_hi, prev_near, prev_far = spans[-1]
spans[-1] = prev_lo, max(prev_hi, hi), min(prev_near, near), max(prev_far, far)
else:
spans.append((lo, hi, near, far))
return next((span for span in spans if span[0] < 0 < span[1]), None)
def _face_matches_width(face: PortFace | None, width: float | None) -> bool:
return face is not None and (
width is None or max(abs(face[0] + width / 2), abs(face[1] - width / 2)) <= TOLERANCE_LINEAR
)
def _has_port_face(polygon: Polygon, port: Port, *, arrival: bool, width: float) -> bool:
return _face_matches_width(_port_face(polygon, port, arrival=arrival), width)
def _shares_face(left: Polygon, right: Polygon) -> bool: def _shares_face(left: Polygon, right: Polygon) -> bool:
@ -64,13 +85,28 @@ def _shares_face(left: Polygon, right: Polygon) -> bool:
def check_path_geometry(path: Sequence[ComponentResult]) -> tuple[bool, bool]: def check_path_geometry(path: Sequence[ComponentResult]) -> tuple[bool, bool]:
"""Return polygon validity and physical continuity for a path.""" """Return polygon validity and physical continuity for a path."""
continuous = all(a.end_port == b.start_port for a, b in pairwise(path)) continuous = True
for component in path: for component in path:
valid, connected = component.physical_checks valid, connected = component.physical_checks
if not valid: if not valid:
return False, False return False, False
continuous = continuous and connected continuous = continuous and connected
return True, continuous return True, continuous and all(components_join(a, b) for a, b in pairwise(path))
def components_join(left: ComponentResult, right: ComponentResult) -> bool:
if left.end_port != right.start_port:
return False
if left.standard_faces and right.standard_faces:
return True
a, b = left.port_faces[1], right.port_faces[0]
return (
_face_matches_width(a, left.width)
and _face_matches_width(b, right.width)
and a is not None and b is not None
and min(a[1], b[1]) > max(a[0], b[0])
and max(abs(a[2] - b[3]), abs(a[3] - b[2])) <= TOLERANCE_LINEAR
)
def bend_fits_width(radius: float, width: float) -> bool: def bend_fits_width(radius: float, width: float) -> bool:
@ -106,12 +142,15 @@ class ComponentResult:
physical_geometry: Sequence[Polygon] physical_geometry: Sequence[Polygon]
dilated_collision_geometry: Sequence[Polygon] dilated_collision_geometry: Sequence[Polygon]
dilated_physical_geometry: Sequence[Polygon] dilated_physical_geometry: Sequence[Polygon]
width: float | None = None
standard_faces: bool = False
_bounds: tuple[tuple[float, float, float, float], ...] = field(init=False, repr=False) _bounds: tuple[tuple[float, float, float, float], ...] = field(init=False, repr=False)
_total_bounds: tuple[float, float, float, float] = field(init=False, repr=False) _total_bounds: tuple[float, float, float, float] = field(init=False, repr=False)
_dilated_bounds: tuple[tuple[float, float, float, float], ...] = field(init=False, repr=False) _dilated_bounds: tuple[tuple[float, float, float, float], ...] = field(init=False, repr=False)
_total_dilated_bounds: tuple[float, float, float, float] = field(init=False, repr=False) _total_dilated_bounds: tuple[float, float, float, float] = field(init=False, repr=False)
_total_physical_bounds: tuple[float, float, float, float] | None = field(init=False, repr=False, compare=False, default=None) _total_physical_bounds: tuple[float, float, float, float] | None = field(init=False, repr=False, compare=False, default=None)
_physical_checks: tuple[bool, bool] | None = field(init=False, repr=False, compare=False, default=None) _physical_checks: tuple[bool, bool] | None = field(init=False, repr=False, compare=False, default=None)
_port_faces: tuple[PortFace | None, PortFace | None] | None = field(init=False, repr=False, compare=False, default=None)
def __post_init__(self) -> None: def __post_init__(self) -> None:
collision_geometry = tuple(self.collision_geometry) collision_geometry = tuple(self.collision_geometry)
@ -162,6 +201,18 @@ class ComponentResult:
def bend_radius(self) -> float | None: def bend_radius(self) -> float | None:
return self.move_spec.radius if isinstance(self.move_spec, Bend90Seed) else None return self.move_spec.radius if isinstance(self.move_spec, Bend90Seed) else None
@property
def port_faces(self) -> tuple[PortFace | None, PortFace | None]:
if self._port_faces is None:
shapes = self.physical_geometry
faces = (
_port_face(shapes[0], self.start_port, arrival=False),
_port_face(shapes[-1], self.end_port, arrival=True),
) if shapes else (None, None)
object.__setattr__(self, "_port_faces", faces)
return faces
return self._port_faces
@property @property
def physical_checks(self) -> tuple[bool, bool]: def physical_checks(self) -> tuple[bool, bool]:
if self._physical_checks is None: if self._physical_checks is None:
@ -169,8 +220,7 @@ class ComponentResult:
valid = bool(shapes) and all(not shape.is_empty and shape.is_valid for shape in shapes) valid = bool(shapes) and all(not shape.is_empty and shape.is_valid for shape in shapes)
connected = ( connected = (
valid valid
and _has_port_face(shapes[0], self.start_port, arrival=False) and (self.standard_faces or all(_face_matches_width(face, self.width) for face in self.port_faces))
and _has_port_face(shapes[-1], self.end_port, arrival=True)
and all(_shares_face(a, b) for a, b in pairwise(shapes)) and all(_shares_face(a, b) for a, b in pairwise(shapes))
) )
object.__setattr__(self, "_physical_checks", (valid, connected)) object.__setattr__(self, "_physical_checks", (valid, connected))
@ -202,6 +252,8 @@ class ComponentResult:
physical_geometry=translate_geometry(self.physical_geometry), physical_geometry=translate_geometry(self.physical_geometry),
dilated_collision_geometry=translate_geometry(self.dilated_collision_geometry), dilated_collision_geometry=translate_geometry(self.dilated_collision_geometry),
dilated_physical_geometry=translate_geometry(self.dilated_physical_geometry), dilated_physical_geometry=translate_geometry(self.dilated_physical_geometry),
width=self.width,
standard_faces=self.standard_faces,
) )
@ -218,12 +270,10 @@ def _combine_bounds(bounds_list: list[tuple[float, float, float, float]]) -> tup
def _get_num_segments(radius: float, angle_deg: float, sagitta: float = 0.01) -> int: def _get_num_segments(radius: float, angle_deg: float, sagitta: float = 0.01) -> int:
if radius <= 0: if radius <= 0:
return 1 return 1
ratio = max(0.0, min(1.0, 1.0 - sagitta / radius)) if not numpy.isfinite(sagitta) or sagitta <= 0:
theta_max = 2.0 * numpy.arccos(ratio) raise ValueError("Arc sagitta must be finite and positive")
if theta_max < TOLERANCE_ANGULAR: theta_max = 4 * asin(min(1.0, sqrt(sagitta) / sqrt(radius) / sqrt(2.0)))
return 16 return max(8, ceil(radians(abs(angle_deg)) / theta_max))
num = int(numpy.ceil(numpy.radians(abs(angle_deg)) / theta_max))
return max(8, num)
def _get_arc_polygons( def _get_arc_polygons(
@ -237,12 +287,11 @@ def _get_arc_polygons(
port_faces: tuple[Port, Port] | None = None, port_faces: tuple[Port, Port] | None = None,
) -> list[Polygon]: ) -> list[Polygon]:
t_start, t_end = numpy.radians(ts[0]), numpy.radians(ts[1]) t_start, t_end = numpy.radians(ts[0]), numpy.radians(ts[1])
num_segments = _get_num_segments(radius, abs(ts[1] - ts[0]), sagitta)
angles = numpy.linspace(t_start, t_end, num_segments + 1)
cx, cy = cxy cx, cy = cxy
inner_radius = radius - width / 2.0 - dilation inner_radius = radius - width / 2.0 - dilation
outer_radius = radius + width / 2.0 + dilation outer_radius = radius + width / 2.0 + dilation
num_segments = _get_num_segments(outer_radius, abs(ts[1] - ts[0]), sagitta)
angles = numpy.linspace(t_start, t_end, num_segments + 1)
cos_a = numpy.cos(angles) cos_a = numpy.cos(angles)
sin_a = numpy.sin(angles) sin_a = numpy.sin(angles)
@ -400,6 +449,8 @@ class Straight:
physical_geometry=geometry, physical_geometry=geometry,
dilated_collision_geometry=dilated_geometry, dilated_collision_geometry=dilated_geometry,
dilated_physical_geometry=dilated_geometry, dilated_physical_geometry=dilated_geometry,
width=width,
standard_faces=length_f > 0 and length_f.is_integer(),
) )
@ -487,6 +538,8 @@ class Bend90:
physical_geometry=physical_geometry, physical_geometry=physical_geometry,
dilated_collision_geometry=dilated_collision_geometry, dilated_collision_geometry=dilated_collision_geometry,
dilated_physical_geometry=dilated_physical_geometry, dilated_physical_geometry=dilated_physical_geometry,
width=width,
standard_faces=physical_geometry is arc_polys,
) )
@ -506,7 +559,7 @@ class SBend:
# Reflect the first arc about the midpoint and reverse it to get the # Reflect the first arc about the midpoint and reverse it to get the
# second arc. Reuse the midpoint and its normal for both polygons. # second arc. Reuse the midpoint and its normal for both polygons.
sign = 1 if offset > 0 else -1 sign = 1 if offset > 0 else -1
angles = numpy.linspace(0, theta, _get_num_segments(radius, float(numpy.degrees(theta)), sagitta) + 1) angles = numpy.linspace(0, theta, _get_num_segments(radius + width / 2, float(numpy.degrees(theta)), sagitta) + 1)
sin, cos = numpy.sin(angles), numpy.cos(angles) sin, cos = numpy.sin(angles), numpy.cos(angles)
first = numpy.column_stack((radius * sin, sign * radius * (1 - cos))) first = numpy.column_stack((radius * sin, sign * radius * (1 - cos)))
first[-1] = (span / 2, offset / 2) first[-1] = (span / 2, offset / 2)
@ -548,7 +601,7 @@ class SBend:
raise ValueError("Bend radius must be at least half the net width") raise ValueError("Bend radius must be at least half the net width")
sign = 1 if offset >= 0 else -1 sign = 1 if offset >= 0 else -1
theta = numpy.arccos(1.0 - abs(offset) / (2.0 * radius)) theta = 2 * asin(sqrt(abs(offset) / radius) / 2)
dx = sbend_span(offset, radius) dx = sbend_span(offset, radius)
grid_span = sbend_grid_span(offset, radius) grid_span = sbend_grid_span(offset, radius)
tail = grid_span - dx tail = grid_span - dx
@ -601,6 +654,8 @@ class SBend:
physical_geometry=physical_geometry, physical_geometry=physical_geometry,
dilated_collision_geometry=dilated_collision_geometry, dilated_collision_geometry=dilated_collision_geometry,
dilated_physical_geometry=dilated_physical_geometry, dilated_physical_geometry=dilated_physical_geometry,
width=width,
standard_faces=outline is None,
) )

View file

@ -56,8 +56,10 @@ class SBendOutline:
if not isinstance(self.polygon, Polygon) or self.polygon.is_empty or not self.polygon.is_valid: if not isinstance(self.polygon, Polygon) or self.polygon.is_empty or not self.polygon.is_valid:
raise ValueError("S-bend outline must be a valid, nonempty Polygon") raise ValueError("S-bend outline must be a valid, nonempty Polygon")
end = Port(sbend_grid_span(seed.offset, seed.radius), seed.offset, 0) end = Port(sbend_grid_span(seed.offset, seed.radius), seed.offset, 0)
if not _has_port_face(self.polygon, Port(0, 0, 0), arrival=False) or not _has_port_face(self.polygon, end, arrival=True): if not _has_port_face(self.polygon, Port(0, 0, 0), arrival=False, width=self.width) or not _has_port_face(
raise ValueError(f"S-bend outline needs east-facing port faces at (0, 0) and ({end.x}, {end.y})") self.polygon, end, arrival=True, width=self.width,
):
raise ValueError(f"S-bend outline needs east-facing port faces of width {self.width} at (0, 0) and ({end.x}, {end.y})")
object.__setattr__(self, "offset", seed.offset) object.__setattr__(self, "offset", seed.offset)
object.__setattr__(self, "radius", seed.radius) object.__setattr__(self, "radius", seed.radius)

View file

@ -6,6 +6,7 @@ from typing import TYPE_CHECKING
from shapely.geometry import Polygon from shapely.geometry import Polygon
from inire.constants import TOLERANCE_LINEAR from inire.constants import TOLERANCE_LINEAR
from inire.geometry.component_overlap import invalid_component_join
from inire.geometry.components import build_component, path_within_board from inire.geometry.components import build_component, path_within_board
from inire.geometry.primitives import Port from inire.geometry.primitives import Port
from inire.router.refiner import component_hits_ancestor_chain from inire.router.refiner import component_hits_ancestor_chain
@ -160,7 +161,16 @@ def add_node(
return return
context.static_safe_cache.add(cache_key) context.static_safe_cache.add(cache_key)
if config.self_collision_check and component_hits_ancestor_chain(result, parent): predecessor = parent.component_result
if (
(not result.standard_faces and not all(result.physical_checks))
or (config.self_collision_check and component_hits_ancestor_chain(result, parent))
or (
not config.self_collision_check and predecessor is not None
and not (predecessor.standard_faces and result.standard_faces)
and invalid_component_join(predecessor, result)
)
):
if frontier_trace is not None: if frontier_trace is not None:
frontier_trace.record("self_collision", move_type, parent.port.as_tuple(), state, result.total_dilated_bounds) frontier_trace.record("self_collision", move_type, parent.port.as_tuple(), state, result.total_dilated_bounds)
return return

View file

@ -7,7 +7,7 @@ from itertools import accumulate, chain
from math import inf from math import inf
from typing import TYPE_CHECKING, Any from typing import TYPE_CHECKING, Any
from inire.geometry.component_overlap import components_overlap from inire.geometry.component_overlap import components_overlap, invalid_component_join
from inire.geometry.components import _advance_port, _bend90_length, bend_fits_width, bend90_grid_span, build_component from inire.geometry.components import _advance_port, _bend90_length, bend_fits_width, bend90_grid_span, build_component
from inire.geometry.primitives import port_local_coordinates, rotation_matrix2 from inire.geometry.primitives import port_local_coordinates, rotation_matrix2
from inire.model import resolve_bend_geometry from inire.model import resolve_bend_geometry
@ -70,8 +70,12 @@ def component_hits_ancestor_chain(component: ComponentResult, parent_node: Any)
current = parent_node current = parent_node
while current and current.parent: while current and current.parent:
ancestor_component = current.component_result ancestor_component = current.component_result
if ancestor_component and components_overlap(ancestor_component, component, prefer_actual=True, at_join=current is parent_node): if ancestor_component:
return True if current is parent_node:
if invalid_component_join(ancestor_component, component):
return True
elif components_overlap(ancestor_component, component, prefer_actual=True):
return True
current = current.parent current = current.parent
return False return False
@ -270,9 +274,9 @@ class PathRefiner:
) -> bool: ) -> bool:
if not self.collision_engine.verify_path_report(net_id, replacement).is_valid: if not self.collision_engine.verify_path_report(net_id, replacement).is_valid:
return False return False
if prefix and components_overlap(prefix[-1], replacement[0], prefer_actual=True, at_join=True): if prefix and invalid_component_join(prefix[-1], replacement[0]):
return False return False
if suffix and components_overlap(replacement[-1], suffix[0], prefer_actual=True, at_join=True): if suffix and invalid_component_join(replacement[-1], suffix[0]):
return False return False
# The verified incumbent's prefix and suffix remain separated by # The verified incumbent's prefix and suffix remain separated by
# several components. Only pairs involving a replacement can change. # several components. Only pairs involving a replacement can change.

View file

@ -260,7 +260,10 @@ def test_route_verification_rejects_adjacent_component_overlap(wrong_side) -> No
if wrong_side: if wrong_side:
outline = shapely.union_all([box(-4, -11, 0, -9), box(-4, -10, -2, -4), box(-4, -6, 11, -4), box(9, -6, 11, 0)]) outline = shapely.union_all([box(-4, -11, 0, -9), box(-4, -10, -2, -4), box(-4, -6, 11, -4), box(9, -6, 11, 0)])
else: else:
outline = shapely.union_all([box(0, -11, 11, -9), box(9, -11, 11, 0), box(-4, -11, 2, -10.5)]) outline = shapely.union_all([
box(0, -11, 11, -9), box(9, -11, 11, 0),
box(2, -9.5, 3, -7), box(-4, -8, 3, -7), box(-4, -10, -3, -7),
])
net = NetSpec("bend", Port(20, 20, 0), Port(50, 30, 90)) net = NetSpec("bend", Port(20, 20, 0), Port(50, 30, 90))
seed = PathSeed((StraightSeed(20), Bend90Seed(10, "CCW"))) seed = PathSeed((StraightSeed(20), Bend90Seed(10, "CCW")))
problem = RoutingProblem((0, 0, 100, 100), (net,), initial_paths={"bend": seed}) problem = RoutingProblem((0, 0, 100, 100), (net,), initial_paths={"bend": seed})
@ -311,6 +314,70 @@ def test_sbend_outline_requires_both_port_faces() -> None:
SBendOutline(40, 50, 2, half) SBendOutline(40, 50, 2, half)
def _sbend_strip(offset, half_width=1):
centerline = [(0, 0), (20, offset / 10), (50, 3 * offset / 4), (80, offset)]
return Polygon(
[(x, y - half_width) for x, y in centerline] + [(x, y + half_width) for x, y in reversed(centerline)],
)
@pytest.mark.parametrize("contact", ["face", "rounding", "gap", "extra_edge", "extra_point"])
@pytest.mark.parametrize("heading", [0, 90])
def test_custom_sbend_join_checks_actual_centered_face(contact, heading) -> None:
left, right = _sbend_strip(40), _sbend_strip(-40)
if contact in ("rounding", "gap"):
shift = 0.25e-6 if contact == "rounding" else 0.75e-6
left, right = translate(left, -shift), translate(right, shift)
if contact in ("extra_edge", "extra_point"):
left = left.union(box(70, 36, 74, 51)).union(box(73, 49, 80, 51))
tip = box(0, 9, 7, 11) if contact == "extra_edge" else Polygon([(0, 50 - 40), (7, 9), (7, 11)])
right = right.union(box(6, -3, 8, 11)).union(tip)
start = Port(20, 30, 0) if heading == 0 else Port(100, 20, 90)
finish = Port(180, 30, 0) if heading == 0 else Port(100, 180, 90)
net = NetSpec("shift", start, finish)
seed = PathSeed((SBendSeed(40, 50), SBendSeed(-40, 50)))
problem = RoutingProblem((0, 0, 220, 220), (net,), initial_paths={"shift": seed}, clearance=0)
options = RoutingOptions(search=SearchOptions(
node_limit=0, sbend_radii=(50,),
sbend_outlines=(SBendOutline(40, 50, 2, left), SBendOutline(-40, 50, 2, right)),
))
result = route(problem, options=options).results_by_net["shift"]
assert result.reached_target
assert result.report.discontinuous == (contact == "gap")
assert result.report.self_collision_count == int(contact in ("extra_edge", "extra_point"))
assert result.is_valid == (contact in ("face", "rounding"))
def test_custom_sbend_width_is_measured_over_the_whole_port_face() -> None:
with pytest.raises(ValueError, match="port faces of width"):
SBendOutline(40, 50, 2, _sbend_strip(40, half_width=0.01))
outline = Polygon([(0, -1), (20, -2), (80, 39), (80, 40), (80, 41), (20, 5), (0, 1), (0, 0)])
assert SBendOutline(40, 50, 2, outline).polygon == outline
@pytest.mark.parametrize("width", [2, 4])
@pytest.mark.parametrize("node_limit", [0, 100])
def test_custom_quarter_turn_requires_the_net_width_at_its_faces(width, node_limit) -> None:
outline = box(0, -11, 11, -9).union(box(9, -11, 11, 0))
net = NetSpec("bend", Port(10, 20, 0), Port(30, 40, 90), width)
seed = PathSeed((StraightSeed(10), Bend90Seed(10, "CCW"), StraightSeed(10)))
problem = RoutingProblem((0, 0, 100, 100), (net,), initial_paths={} if node_limit else {"bend": seed}, clearance=0)
options = RoutingOptions(
search=SearchOptions(node_limit=node_limit, bend_radii=(10,), sbend_radii=(), bend_physical_geometry=outline),
congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False),
topology=TopologyOptions(mode="off"),
)
result = route(problem, options=options).results_by_net["bend"]
assert result.is_valid == (width == 2)
if node_limit == 0:
assert result.report.discontinuous == (width == 4)
def test_custom_quarter_turn_outline_leaves_circular_sbends_available() -> None: def test_custom_quarter_turn_outline_leaves_circular_sbends_available() -> None:
net = NetSpec("shift", Port(30, 50, 0), Port(110, 90, 0)) net = NetSpec("shift", Port(30, 50, 0), Port(110, 90, 0))
seed = PathSeed((SBendSeed(40, 50),)) seed = PathSeed((SBendSeed(40, 50),))

View file

@ -1,10 +1,10 @@
import pytest import pytest
from dataclasses import FrozenInstanceError from dataclasses import FrozenInstanceError
from math import pi, sqrt from math import asin, cos, pi, sin, sqrt
from shapely.affinity import rotate as shapely_rotate from shapely.affinity import rotate as shapely_rotate
from shapely.affinity import scale as shapely_scale from shapely.affinity import scale as shapely_scale
from shapely.affinity import translate as shapely_translate from shapely.affinity import translate as shapely_translate
from shapely.geometry import Polygon from shapely.geometry import Polygon, box
import inire.geometry.components as components_module import inire.geometry.components as components_module
from inire.geometry.components import Bend90, SBend, Straight from inire.geometry.components import Bend90, SBend, Straight
@ -299,6 +299,30 @@ def test_arc_sagitta_precision() -> None:
assert pts_fine > pts_coarse * 2 assert pts_fine > pts_coarse * 2
@pytest.mark.parametrize("radius", [100, 79999, 80001, 100000])
@pytest.mark.parametrize("offset", [None, 0.5])
def test_circular_bends_detect_keepouts_inside_the_outer_edge(radius, offset) -> None:
width = radius / 200
start = Port(0, 0, 0)
if offset is None:
component = Bend90.generate(start, radius, width, direction="CCW")
centers = [(0, radius, -pi / 2 + pi / 64)]
else:
lateral = round(offset * radius)
component = SBend.generate(start, lateral, radius, width)
theta = 2 * asin(sqrt(lateral / radius) / 2)
span = sqrt(lateral * (4 * radius - lateral))
centers = [(0, radius, -pi / 2 + theta / 32), (span, lateral - radius, pi / 2 + theta / 32)]
# These points are between the old 16-segment chord and the physical
# outer edge at fine scales. The keepouts lie entirely inside the arc.
outer_probe_radius = radius + width / 2 - max(0.03, width * 0.12)
for cx, cy, angle in centers:
x, y = cx + outer_probe_radius * cos(angle), cy + outer_probe_radius * sin(angle)
world = RoutingWorld(0)
world.add_static_obstacle(box(x - 0.005, y - 0.005, x + 0.005, y + 0.005))
assert world.verify_path_report("bend", (component,)).static_collision_count == 1
def test_component_transform_invariance() -> None: def test_component_transform_invariance() -> None:
# Verify that generating at (0,0) then transforming # Verify that generating at (0,0) then transforming
# is same as generating at the transformed port. # is same as generating at the transformed port.

View file

@ -0,0 +1,294 @@
# Full project review and follow-up plan
Review baseline `3d7fc3a`. This pass covers public inputs and seed replay, physical geometry and collision checks, lattice and corridor routing, automatic planner selection, congestion and refinement, diagnostics, examples, and local developer checks. The earlier review fixes are in the baseline. See the [routing simplification plan](routing-simplification.md) for the prior prototypes and their parity requirements.
The full local run passed 592 tests with `INIRE_RUN_PERFORMANCE=1` on Python 3.13.18, Shapely 2.1.2, and GEOS 3.13.1. Ruff passed. Public defaults matched the prior verified net IDs on all 67 boards, for 433 verified nets. The three focused triangulation capability tests passed, and all seven complex-routing walkthrough figures regenerated byte for byte. All 15 active Markdown pages are within two links of the user or developer guide, and local file links resolve. [Developer checks](../docs/development.md#check-a-change) · [Walkthrough](../docs/complex-routing-example-1.md)
The follow-up pass independently verified every nonempty returned path on the 67 corpus boards under a 35-node, single-iteration automatic profile with warm start and refinement disabled. The resulting geometry reports matched the public results in that profile. Hatchling built the wheel and source distribution locally. The extracted wheel routed a public-API smoke case outside the checkout, and the unpacked source archive built a wheel and ran complex-routing example 1 to 9/9 with the benchmark CLI. All nine numbered examples ran from both the project directory and a clean export, producing nine images each time. [Automatic residual routing](../inire/router/_routing_policy.py#L211) · [Build configuration](../pyproject.toml#L39)
Project-directory compatibility checks with Shapely 2.0.0 and 2.0.7 confirmed the automatic lattice fallback on Shapely versions without triangulation, 9/9 coverage in complex-routing example 1, and the documented restrictions on active guide and seed searches. The Shapely 2.0.0 run used Python 3.11.11, GEOS 3.11.1, and NumPy 1.26.4. A 192-layout primitive matrix passed 768 seed verifications on each of three Shapely versions and 768 active searches on Shapely 2.1.2 and 384 each on 2.0.0 and 2.0.7. An independent rectangular geometry check agreed with all 1,728 route reports and the associated final conflict traces on each version. [Mode and dependency behavior](../docs/complex-routing-example-1.md#compare-all-routing-modes)
On Python 3.14.10 with the local Shapely build against GEOS 3.15.0, the full suite passed 581 tests and skipped the 11 opt-in performance checks. A fresh source archive built a wheel whose 39 production modules all matched the reviewed checkout. The extracted wheel routed a public smoke case on Python 3.13 and 3.14 from outside the checkout. [Local verification](../docs/development.md#check-a-change) · [Build configuration](../pyproject.toml#L39)
The six imported layouts regenerated byte for byte from the pinned upstream archives. The documented placed-device route survived a WKT export and readback as a connected polygon, and the locked-route example completed a second route around the exported geometry. A 72-call concurrent smoke test reproduced the sequential geometry of 36 simple layouts. A further 96 seed replays used rotated and translated serial-gate layouts. Their geometry reports were consistent under those transforms, and the erased collision diagnostics in one layout reduced to the crossing in item 30. Additional probes used nanometer-scale bends and keepouts, narrow apertures, seed reuse after heading inference, partial incumbent reuse, and dependency combinations outside the lockfile. [Fixture importer](../docs/benchmark-fixtures.md#regenerate-the-converted-inputs) · [Placed-device and export workflow](../docs/user/route-a-layout.md#route-between-placed-crossings)
Three fresh processes with different Python hash seeds produced identical per-net outcomes, move sequences, polygon WKB hashes, reports, selected stages, and work counters across 82 runs. These covered all 67 corpus boards in bounded automatic mode and five boards in lattice, guide, and seed modes with a fixed net-shuffle seed. [Benchmark options](../inire/tests/routing_corpus.py)
The independent fabrication pass used three openEBL 2025-02 submissions. KLayout 0.30.12 extracted the silicon polygons, port markers, and authored waveguide waypoints on the submissions' 1 nm grid. A fresh automatic search verified 9/18 links in the Raymond MZI array, 27/36 in the CROW MZI, and 2/4 in the contra-directional coupler with a 225-node limit per attempt. Each link was attempted separately, retaining neighboring authored silicon and opening its two intentional port joins in the keepouts. All 58 links verified when replayed from their authored waypoints with 5 µm circular bends. Reversing the search recovered the other nine CROW links, and lattice attempts with a 1,200-node limit completed the other two layouts. After replacing all 58 links across the three layouts and writing OASIS at 1 nm, the pinned EBeam deck reported exactly the same markers as the originals. The Raymond original, an export-only control, and the modified version all gave zero markers. These are checks against the published deck and the selected optical routes. [Pinned fabrication submissions](https://github.com/SiEPIC/openEBL-2025-02/tree/a887476a301db2a014be007717cd1821e111f58e/submissions) · [Pinned EBeam deck](https://github.com/SiEPIC/SiEPIC_EBeam_PDK/blob/363fbb52eefa8669100499ab531d3fe7befc4867/klayout/EBeam/drc/SiEPIC_EBeam.drc)
On the independent 5-by-3 mm CPW chip, KLayout confirmed that the published etch layer removes a 5 µm section from the feedline conductor. Routing the two conductor sections as separate connections and reconstructing their 6 µm gaps returned the same effective metal across the full chip after OASIS write and read at 1 nm. Routing one connection with the coupling mask omitted produced a continuous conductor across the intended break. [Published CPW chip and layout source](https://github.com/paulggin/klayout-cpw-design/tree/a38dc34cf6785ba0af41b27f43b6137fd2b69cc7)
## Implementation order
Implemented items 1, 2, and 17 cover missing joins, extra line or point contact on the join plane, custom port-face widths, and outer-edge arc accuracy. The focused geometry, API, collision, and refinement run passed 287 tests. The remaining items retain the acceptance checks below.
| Batch | Work | Acceptance gate |
| --- | --- | --- |
| Physical verification | 1, 2, 17, 23, and 38 | Reject the faulty geometry and keep legal joins valid in search and seed replay. Check circular bend accuracy, folded-route spacing, and isolation between different nets. |
| Routing coverage and selection | 3, 4, 5, 11, 15, 16, 18, 24, 25, 27, 28, 32, 36, and 41 | Recover each reported route at its existing budget, and apply objective units consistently. Reach the required bound on every corpus board. |
| Input, replay, and diagnostic accuracy | 6, 7, 8, 20, 21, 26, 30, and 37 | Diagnose invalid settings and impossible terminals early, preserve useful visibility on large layouts, render the actual free space, and replay the intended physical geometry. |
| Performance and cleanup | 9, 10, 12, 13, 19, and 29 | Compare runtimes and memory where the workload changes, and keep the best verified result if a worker times out. Require exact routing and trace parity for the private-state cleanup. |
| Release packaging | 14 and 22 | Build and smoke-test the runtime wheel independently of the checkout. Keep the source archive usable for development and verify the supported dependency combinations. |
| Fabrication workflow | 31, 33, 34, 35, 39, and 40 | Compare process-specific geometry and authored optical lengths before and after routing and export. Check port matching, the RF cross-section, per-net bend rules, export-grid clearance, and layer assignment. |
## 1. Detect extra contact on the join plane — High
Two adjacent custom S-bends can share their centered two-unit port face and another two-unit edge ten units away. The route verifies with zero self-collisions because both intersections lie on the same plane. The extra edge connects separated parts of the route. [Adjacent-component verification](../inire/geometry/component_overlap.py#L48)
Reproduce on bounds `(0, 0, 220, 120)` at zero clearance. Route from `(20, 30, 0)` to `(180, 30, 0)` using `SBendSeed(40, 50)` and `SBendSeed(-40, 50)` with width 2. Give both outlines their standard local endpoints. The base outline is the strip formed by adding and subtracting one from each y coordinate of `[(0, 0), (20, offset / 10), (50, 3 * offset / 4), (80, offset)]`. Union the positive outline with `box(70, 36, 74, 51)` and `box(73, 49, 80, 51)`. Union the negative outline with `box(6, -3, 8, 11)` and `box(0, 9, 7, 11)`. Seed-only verification reports two shared edges on `x = 100`, spanning `y = 69..71` and `y = 79..81`.
Determine the connected, centered face shared by the two components and confine the join tolerance to that face. Reuse the predicate in verification, A* ancestor checks, and refinement. Check the off-center edge and a point contact away from the face, ordinary straight and bend joins, and rotated custom joins that differ by rounding. [A* and refinement callers](../inire/router/refiner.py#L69)
## 2. Validate port-face width on custom bends — Medium
`SBendOutline(40, 50, 2, polygon)` accepts both terminals with faces only 0.02 units wide. Use the strip in item 1 with `offset=40` and a half-width of `0.01`. A route from `(10, 10, 0)` to `(110, 50, 0)` with a 10-unit width-2 straight on each side verifies with two abrupt width changes. The current check validates the face position, orientation, and finite extent. [Outline validation](../inire/model.py#L52) · [Port-face predicate](../inire/geometry/components.py#L33)
The same check affects custom 90-degree bends, where one configured polygon can apply to nets of different widths. Set `bend_radii=(10,)` and `bend_physical_geometry=box(0, -11, 11, -9).union(box(9, -11, 11, 0))`. On an empty 100-by-100 board at zero clearance, verify a net from `(10, 20, 0)` to `(30, 40, 90)` with `StraightSeed(10)`, `Bend90Seed(10, "CCW")`, and `StraightSeed(10)`. Lattice and automatic modes both report completion at widths 2 and 4. At width 4 the exported straight faces span 4 units and the bend faces span 2 units. [Custom quarter-turn geometry](../inire/geometry/components.py#L406)
Check the centered connected span against the declared width for S-bend outlines and the routed net width for custom quarter turns. Interior sections can still vary in width. Compare the face extent within a geometric tolerance so multiple collinear edges can form a single face. Reject the 0.02-unit S-bend outline and accept an asymmetric outline with full-width terminal faces. Verify the width-2 quarter turn and diagnose the width-4 mismatch in both search and seed replay. Describe how a custom quarter-turn template applies on mixed-width boards. [Custom geometry API](../docs/user/api-reference.md#searchoptions)
## 3. Keep automatic planning available with unused outlines — Medium
Complex-routing example 1 uses width-2 nets. Adding a single `SBendOutline(40, 50, 3, polygon)` dropped automatic coverage from 9/9 to 0/9 with a 100-node limit, one congestion iteration, warm start off, and refinement off. The width-3 outline matches no net. Automatic switches to lattice routing when the outline list is nonempty, and explicit bundle has the same unconditional restriction. [Automatic dispatch](../inire/router/_automatic.py#L603) · [Bundle checks](../inire/router/_bundle.py#L213)
Check whether any registered outline applies to a net before changing planner availability. Share the applicability rule between automatic and bundle. Keep the lattice fallback when an outline applies. With an unused width, require the fixed-heading example's 9/9 result and verify that the point-terminal bundle still runs. With a matching outline, verify the exported polygon and preserve the documented bundle error. [Mode comparison and fixture](../docs/complex-routing-example-1.md#compare-all-routing-modes)
## 4. Recover legal straight moves after a bend — Medium
On bounds `(38, 18, 54, 62)`, use start `(40, 20, 0)`, target `(40, 60, 180)`, width 2, clearance 2, and keepout `box(52.85, 25, 54, 27.2)`. Use radius-10 quarter turns, disable S-bends and warm start, and run lattice search for one iteration with a 200-node limit. Search stops after the first bend. The seed `CCW(10), straight(20), CCW(10)` verifies. An in-memory probe enabling the flat-ended footprint check at the intermediate port reached the target in five expansions. [Straight-move proposal](../inire/router/_astar_moves.py#L217) · [Flat-ended scan](../inire/geometry/collision.py#L729)
Preserve the conservative ray for ordinary move proposals. Recover a candidate when the ray blocks an otherwise legal straight at a component output. Try a deferred check if adding the exact scan to the main frontier changes bounded search order. Check all four rotations, an obstacle that genuinely blocks the next straight, and the splitter-tree benchmark, which is sensitive to changes in straight proposals.
## 5. Recover narrower passages when the shared mesh finds a different corridor — Medium
The width-specific retry covers nets with no shared corridor. If the shared mesh supplies a different corridor, the narrower net can still lose a usable passage. On an 800-by-600 board, place a keepout at `box(300, 50, 480, 350)`. The width-2 net runs east from `(60, 110, 0)` to `(740, 110, 0)` at clearance 6. Add an unrelated width-100 straight from `(100, 500, 0)` to `(150, 500, 0)`. With seed mode, radius 20, S-bends and warm start off, one iteration, and 500 nodes, the detour changes from completed with two corridors to partial with one corridor. The shared inset closes the lower opening. [Width-specific corridor fallback](../inire/router/_topology.py#L432)
Prototype a width-specific retry after the shared corridors fail to realize a route, or include an alternative through a passage absent from the shared mesh. Keep the shared lane assignment and the per-net expansion allowance intact. Require the width-2 route to complete with or without the unrelated wide net at the same budget. Check mixed-width portal contention and the existing shared-lane cases for coverage and cost changes.
## 6. Validate search and congestion settings at construction — Medium
`SearchOptions(node_limit=float('nan'))` is accepted and bypasses the normal expansion-limit comparison. `CongestionOptions(max_iterations=1.5)` is accepted and raises `TypeError` inside `range()` during routing. A misspelled `net_order='longesst'` silently selects shortest-first ordering. [Search and congestion options](../inire/model.py#L66) · [Expansion ceiling](../inire/router/_search.py#L74) · [Net ordering](../inire/router/_congestion_policy.py#L16)
`NetSpec` also accepts integer IDs even though the API type is `str`. On a 100-by-40 empty board with one width-2 net from `(5, 20, 0)` to `(90, 20, 0)`, replay `StraightSeed(85)` at zero search nodes and use integer ID `7`. Verification reports one dynamic conflict against the path itself because it queries the index with a string ID. Two overlapping paths with IDs `7` and `"7"` raise `TypeError` while comparing peers. Enforce string IDs at construction, or normalize IDs before uniqueness checks and seed-map validation. [Net model](../inire/model.py#L24) · [Verification index lookup](../inire/geometry/collision.py#L661)
Validate nonnegative integer budgets and enumerate allowed order names at construction. Keep zero-budget verification behavior and support the documented defaults. In the same change, decide and document which numerical objective and penalty values are supported. Reject nonfinite values before scoring or iteration. Test zero, valid positive values, rejected values, and identifiers loaded from serialized layouts through the public constructors.
## 7. Make exact-corner visibility useful on real corner states — Medium
With clearance zero, put two keepouts at `box(10, 20, 20, 30)` and `box(-10, 10, 0, 15)`. The segment from `(10, 20)` to `(0, 15)` touches the two keepouts only at its endpoints. The visibility ray returns reach zero because it counts the source corner itself as a hit. The exact-corner query returns no visible corner. In a separate probe with 200 indexed corners, adding one distant rectangle dropped the same local query from five visible corners to zero. Above 200 corners the graph builder skips construction and the exact query has no local fallback. [Corner graph](../inire/router/visibility.py#L93) · [Ray intersection](../inire/geometry/collision.py#L812) · [Visibility option](../docs/user/api-reference.md#searchoptions)
Give visibility rays endpoint-aware semantics and leave move admission responsible for physical clearance. Compute or cache local exact neighbors on demand when global precomputation is skipped. Check an outward ray, a ray entering the source keepout, a blocker strictly between corners, and a local query before and after adding distant corners. Confirm the default tangent mode keeps its existing coverage and work.
## 8. Show holes in keepouts and routed polygons — Low
The main route plot and the walkthrough polygon helper draw exterior rings only. For a keepout with exterior `box(20, 20, 80, 80)` and hole `box(30, 30, 70, 70)`, a net from `(35, 50, 0)` to `(65, 50, 0)` verifies inside the hole. Both renderers paint the hole as keepout. The same rendering path also omits holes in custom outlines. [Route visualization](../inire/utils/visualization.py#L49) · [Documentation figure helper](../scripts/render_documentation_figures.py#L45)
Share a hole-aware polygon renderer for the affected paths, including filled and outline-only geometry. Keep labels, proxy styling, and axis bounds. Verify a point in a hole stays unfilled in a headless rendering test. Regenerate the active walkthrough figures and inspect any visual changes.
## 9. Avoid quadratic scans of clear terminal banks — Low
The capacity check enumerates every pair of terminals on each aligned bank. With width-2 nets at `y = 5 * i` between `x = 5` and `x = 95` and clearance 2, every terminal pair is clear. The check took about 0.25, 0.75, and 2.62 seconds for 1,000, 2,000, and 4,000 nets on this machine. [Aligned port conflict check](../inire/router/_capacity.py#L62)
Index lateral intervals to find pairs that can actually conflict. Preserve the disjoint-net bound and compare deterministic pair selection on overlapping and mixed-width banks. Benchmark the clear bank and a dense bank separately. Use the existing capacity suite and automatic coverage checks before adopting a changed pair order.
## 10. Remove unused per-node search state — Low
`AStarNode.base_move_cost`, `cache_key`, and `congestion_resolved` have no readers or current constructor call sites that supply them. The public metrics still expose lazy-congestion counters and two ray-cast categories whose production callers have been removed. [Search node](../inire/router/_astar_types.py#L153) · [Public metrics](../inire/results.py#L216) · [Ray-cast labels](../inire/geometry/collision.py#L693)
Remove the three private node fields and their constructor arguments in a parity-only change. Keep exported counter names available for existing diagnostics and baseline files. Document retired counters separately if that helps interpret current reports. Compare selected paths and stage, iteration, and frontier traces exactly. [Parity procedure](../docs/routing-diagnostics.md#reproduce-and-compare)
## 11. Honor the explicit refinement objective in automatic mode — Medium
Use the seeded foldback fixture with a 100-node search limit, all search objective weights set to zero, and `RefinementOptions(objective=ObjectiveWeights(danger_weight=0))`. With identical geometry and congestion settings, explicit lattice mode returns a verified nine-component route of length 392.83. Automatic mode builds the same refinement but returns its 17-component, 475.66-unit incumbent because both layouts tie under the search objective. [Seeded foldback fixture](../inire/tests/test_refinements.py#L21) · [Refinement scoring](../inire/router/refiner.py#L100) · [Automatic selection](../inire/router/_automatic.py#L149)
Keep the search objective for ranking ordinary planner attempts. For a verified refinement that preserves the selected net IDs, apply the caller's explicit refinement objective consistently when deciding whether to keep the replacement. Define its interaction with `automatic_length_weights` in the API reference. Check the foldback in both modes, the default selection when no override is set, and the guard against losing verified nets. [Refinement handoff](../inire/router/_automatic.py#L584) · [Objective options](../docs/user/api-reference.md#refinementoptions)
## 12. Report and enforce the worker deadline during long attempts — Low
The worker checks its timeout before starting each net. A single search can cross the deadline, complete, and leave `timeout_events` at zero. In a fake-clock probe, a one-net lattice worker with warm start disabled completed a legal straight after the clock advanced from 0 to 61 seconds. Its 60-second deadline was never observed. Corridor preparation and warm-start work can also run past the deadline before the first between-net check. [Worker deadline](../inire/router/_router.py#L290) · [Between-net timeout check](../inire/router/_router.py#L955) · [A* expansion loop](../inire/router/_search.py#L74)
Define safe cancellation points for the worker. Check the deadline during long search loops and at phase transitions, count expiration once, and keep the best verified result and consistent collision indexes. Use a fake clock to cover a single long search, expiry during preparation, and a timeout after a previous iteration produced a verified layout. Check that tight loops retain their current runtime on the performance suite.
## 13. Skip proximity sampling in verification-only runs — Low
In explicit lattice mode with `node_limit=0`, one congestion iteration, and refinement disabled, the default danger weight still builds the proximity tree even though no moves are scored. On a 100,100-by-100,100 board with keepout `box(50, 80, 100050, 100080)`, verification of the straight seed from `(10, 20, 0)` to `(90, 20, 0)` built 80,000 samples and took about 34 ms. Setting the danger weight to zero produced the same verified result and took about 0.8 ms. Both runs expanded zero nodes. [Proximity setup](../inire/router/_stack.py#L47)
Build obstacle samples when search or enabled refinement actually needs proximity costs. Keep the board bounds available for geometric verification. Test an explicit verification-only run with the default weights and a seeded refinement with a nonzero danger weight. Check automatic candidate scoring separately, since automatic may still need proximity data for layout selection. [Automatic scoring](../inire/router/_automatic.py#L149)
## 14. Ship a self-contained runtime wheel — Low
The local wheel contained 41 entries under `inire/tests/`, including benchmark tests and fixtures. It contained no `scripts/` or `examples/` entries. The public routing smoke case passed from the extracted wheel with the checkout removed from the import path. Importing the shipped `inire.tests.test_routing_benchmarks` failed with `No module named 'scripts'`. [Build configuration](../pyproject.toml#L39) · [Benchmark test imports](../inire/tests/test_routing_benchmarks.py#L24)
Keep repository benchmark tests and their fixtures in the source distribution and exclude them from the runtime wheel. Build both artifacts locally, run the public-API smoke cases against the wheel with the checkout off the import path, and check that the unpacked source distribution can build the wheel and run its benchmark tooling.
## 15. Keep corridor seeding available for incomplete caller hints — Medium
On the existing detour fixture, use seed mode with a 100-node search limit, one congestion iteration, and warm start and refinement disabled. The unseeded run completes with a topology-generated seed in 41 expansions. Adding an empty `PathSeed`, or the legal prefix `PathSeed((StraightSeed(5),))`, consumes the detailed-search budget and returns a partial result. Adding a complete straight seed of length 680 through the obstacle returns a static collision with zero expansions. The corridor seed builder skips any net present in the caller's seed mapping. [Detour fixture](../inire/tests/routing_benchmarks.py) · [Corridor seed builder](../inire/router/_router.py#L216) · [Seed use during routing](../inire/router/_router.py#L838)
Preserve a complete verified caller seed. Treat an empty seed as an absent hint, and allow seed mode to realize a corridor when the caller's seed is incomplete or fails geometric checks. Reuse a legal prefix as guidance when possible. Keep the original diagnostic path when the verification-only budget is zero. Require the detour to complete under the same budget with no seed, an empty seed, and a legal prefix. Check the statically invalid complete hint in both search and verification-only runs, and retain the existing test for caller seeds across repeated runs. [Seed mode tests](../inire/tests/test_topology.py#L56)
## 16. Infer intermediate S-bend offsets for a multi-bend shift — Medium
Use an empty 100-by-100 board, width 2, clearance 0, start `(20, 20, 0)`, and target `(56, 40, 0)`. Disable quarter turns and set `sbend_radii=(10,)`, a 100-node budget, one congestion iteration, and warm start and refinement disabled. With `sbend_offsets=None`, lattice, guide, seed, and automatic all return partial. With `sbend_offsets=(10,)`, each mode verifies two consecutive 10-unit S-bends. The implicit target-offset logic only proposes that shift when a single configured bend can cover it. [S-bend move proposals](../inire/router/_astar_moves.py#L329) · [Public option](../docs/user/api-reference.md#searchoptions)
Propose bounded intermediate offsets when the target lies beyond one S-bend's lateral range, using the remaining forward room and the configured radii. Check both signs, valid fractional radii, and a budget that cannot realize the proposed shift. Preserve explicit signed offset lists and the empty-list setting that disables S-bends. Compare all four modes on the reproducer and review branch counts and coverage on the corpus.
## 17. Preserve circular bend accuracy in fine layout units — High
A 100 µm bend represented on a 1 nm grid uses 16 segments per arc. In a zero-budget quarter-turn replay at zero clearance, use bounds `(0, 0, 102000, 102000)`, a 500-unit net from `(1000, 1000, 0)` to `(101000, 101000, 90)`, and `Bend90Seed(100000, "CCW")`. Put a 10-unit square around the point at radius `100190` and angle `-π/2 + π/64` from the bend center `(1000, 101000)`. The entire square is inside the ideal circular guide. The exported polygon misses the keepout by 55.52 units and the result verifies. A circular `SBendSeed(50000, 100000)` also missed a keepout inside the first ideal arc. [Arc sampling](../inire/geometry/components.py#L218) · [S-bend sampling](../inire/geometry/components.py#L509) · [Coordinate units](../docs/user/route-a-layout.md#define-the-inputs)
The quarter turn uses 1,571 segments at radius 79,999 and drops to 16 at radius 80,001 because the sagitta-derived angle falls below the angular tolerance. Compute the number of segments with a numerically stable formula and keep the approximation error bounded as radius grows. Check quarter turns and both S-bend halves on either side of the threshold, compare several layout units for the same physical geometry, and verify keepouts near both arc boundaries against analytic distances. If a tessellation limit is necessary, give callers an explicit accuracy contract. [Bend option reference](../docs/user/api-reference.md#searchoptions)
## 18. Keep planning available for unseeded nets on a partially seeded layout — Medium
Complex-routing example 1 verifies 9/9 with automatic mode, a 100-node limit, one congestion iteration, and refinement disabled. Reuse its verified 2,400-unit straight for `net_04` through `initial_paths` and the same call verifies only that net. An empty `PathSeed` for `net_04` also drops coverage to 1/9. Holding that straight fixed as a keepout verifies one of the eight remaining routes. A nonempty seed mapping suppresses the bundle, column, compact, and direct planners for the whole layout. In the worker, one materialized path also suppresses greedy warm-start generation for every remaining net. [Bundle entry check](../inire/router/_bundle.py#L213) · [Direct paths](../inire/router/_routing_policy.py#L78) · [Worker preparation](../inire/router/_router.py#L289)
Treat empty paths as absent during planning. Make verified caller paths available as incumbents while retaining compatible construction and warm-start options for unseeded nets. For example, a candidate that already reproduces the caller's straight can use it with its existing geometry. Verify candidates on the whole board before selecting them. Recover 9/9 on this fixture with either hint at the same budget. Cover a caller seed that disagrees with a constructive candidate and preserve the precedence of fixed terminal headings. [Reuse workflow](../docs/user/route-a-layout.md#reuse-an-existing-route)
## 19. Bound proximity-map work on fine layout grids — Medium
The default proximity map samples every five layout units and sets its distance cutoff to ten units. Route a width-0.5 µm straight five micrometers below a 1 mm square keepout on a 1.5-by-1.6 mm board. With lattice mode and 20 search nodes, both micrometer and nanometer representations complete in two expansions. At 1 nm per unit, tree setup grows from 800 to 800,000 samples, from about 0.5 ms to 360 ms, and from about 71 MiB to 208 MiB peak process memory. The proximity cost at the same physical position changes from 0.04 to zero. This is active search, so skipping verification-only work in item 13 would leave the problem in place. [Proximity sampling](../inire/router/danger_map.py#L68) · [Automatic candidate scoring](../inire/router/cost.py#L243) · [Coordinate units](../docs/user/route-a-layout.md#define-the-inputs)
Bound setup work independently of the database unit and document how callers choose the physical range of proximity scoring. Compare an index of boundary segments with exposing a configurable sampling interval and sharing the index between attempts. Keep the default corpus route coverage and measure peak memory on identical one-micrometer, 0.1-micrometer, and one-nanometer layouts. Include a long keepout edge and a polygon with an interior opening.
## 20. Preserve routed headings when reusing inferred-terminal paths — Low
On the point-terminal variant of complex-routing example 1, automatic routing with heading inference verifies 9/9. Export the nine `as_seed()` values and replay them using the original `NetSpec` entries and zero search nodes. Only 8/9 verify because `net_08` arrived westbound and its original target heading points east. Replay with both endpoint ports from the chosen path and all nine verify. `PathSeed` stores only moves, so callers saving paths for reuse need the inferred terminal ports as well. [Result seed export](../inire/results.py#L284) · [Heading inference dispatch](../inire/router/_automatic.py#L618) · [Point-terminal walkthrough](../docs/complex-routing-example-1.md#compare-all-routing-modes)
Add a public example that stores both chosen ports alongside the seed, then rebuilds a zero-budget verification problem. Exercise a changed departure heading and a changed arrival heading, and compare the replayed physical polygons. Use the same port values in the example when exporting geometry and reusing its path. [Reuse workflow](../docs/user/route-a-layout.md#reuse-an-existing-route)
## 21. Match custom S-bend outlines across ordinary floating-point conversions — Medium
Register `SBendOutline(40, 50, 0.3, polygon)` and replay `SBendSeed(40, 50)` from `(10, 10, 0)` to `(90, 50, 0)`. Form the outline by taking the points `[(0, 0), (20, 0), (50, 25), (80, 40)]` and joining the upper and lower offsets at `±0.15` in y. At width `0.3` the route exports the registered outline as one polygon. At width `0.1 + 0.2` it exports two circular arc polygons. Both routes verify. Template lookup, move proposals, and planner eligibility require a consistent definition of a matching width. [Outline lookup and registration](../inire/model.py#L93) · [Move proposals](../inire/router/_astar_moves.py#L329)
Normalize equivalent values or use a narrowly bounded matching tolerance consistently across registration, search, seed replay, and planner eligibility. Detect ambiguous matches explicitly and keep genuinely distinct widths and radii independent. Test the two equivalent widths against the same outline and verify that a materially different width still receives the circular bend. Include values obtained by layout-unit conversion. [Custom outline API](../docs/user/api-reference.md#searchoptions)
## 22. Declare a runtime-compatible NumPy and Shapely range — Medium
The runtime requirements allow NumPy 2.2.6 with Shapely 2.0.0. Both wheels install on Python 3.11, but `import inire` fails with `ImportError: numpy.core.multiarray failed to import`. Shapely 2.0.0 imports and routes with NumPy 1.26.4. It emits intersection warnings on verified component joins in complex-routing example 1, which abort the example when runtime warnings are treated as errors. Shapely 2.0.4 introduced NumPy 2.0 wheel compatibility, and 2.0.6 fixed a further NumPy 2.1 compatibility issue. This can affect consumers with an older Shapely pin even when the project's current lockfile works. [Runtime requirements](../pyproject.toml#L23) · [Join verification](../inire/geometry/component_overlap.py#L48) · [Shapely 2.0 release notes](https://shapely.readthedocs.io/en/2.0.7/release/2.x.html)
Choose and document a compatible dependency floor. Test installation and public routing on Python 3.11 with the oldest supported Shapely and the supported NumPy major versions. Keep the automatic fallback available on a release without constrained triangulation. Include a current environment in the local release smoke checks.
## 23. Define the spacing requirement between separated parts of one net — Medium
The API describes `clearance` as required spacing between physical shapes. On an empty board, replay a width-2 route from `(10, 20, 0)` to `(10, 24, 180)` with a 25-unit straight, two consecutive radius-2 counterclockwise turns, and another 25-unit straight. The parallel straight sections are 2 units apart edge to edge. At clearance 4, verification still reports completion with zero self-collisions. The same-net check detects intersections, including unintended contact, and uses no spacing threshold. Close parallel runs can matter for optical coupling even when they belong to one connection. [Clearance API](../docs/user/api-reference.md#routingproblem) · [Self-collision verification](../inire/geometry/component_overlap.py#L63)
Document the existing inter-net and keepout rule explicitly. Define a separate rule for self-spacing if process clearance is expected between separated segments. Apply it to search, seed verification, and refinement with a local exemption for connected geometry near ordinary joins. Test the folded path, a connected bend with short adjoining straights, and a fold at exact spacing.
## 24. Propose an S-bend launch between two offset apertures in lattice mode — Medium
On bounds `(0, 0, 62, 25)` at clearance 1, use a width-2 net from `(1, 7, 0)` to `(60, 13, 0)`. Place one wall across `x = 20..26` with opening `y = 4.95..9.05` and another across `x = 43..49` with opening `y = 10.95..15.05`. Disable quarter turns, set `sbend_radii=(10,)`, `sbend_offsets=(6,)`, and a minimum straight length of 1. Disable danger weighting, warm start, and refinement. With one iteration and a 1,000-node limit, lattice search exhausts its frontier after 14 expansions. Any launch at integer `x = 26..29` can complete with the S-bend and a straight, yet lattice visits none of those states. Guide and seed modes verify the route in 22 and 14 expansions respectively. Automatic mode on Shapely 2.0.0 reproduces the 14-expansion failure. Across 63 generated versions of this two-aperture design, every reference path verified, and lattice missed 51 while the triangulation-capable modes completed all 63. [Straight proposals](../inire/router/_astar_moves.py#L228) · [Candidate generation around visible corners](../inire/router/_astar_moves.py#L52)
Derive straight candidates from transitions between offset apertures. Include S-bend reach in local obstacle guidance when quarter turns are disabled. Keep move admission responsible for the physical checks. Verify the same case in lattice mode and on Shapely 2.0, with both signs and all four input headings. Compare branch counts on open boards and narrow gates.
## 25. Make the heading heuristic consistent under cardinal rotation — Medium
On bounds `(0, 0, 120, 120)`, use a width-1.75 net from `(8, 60, 0)` to `(112, 101, 0)`, clearance 1.25, and keepouts `box(87, 48, 99, 71)` and `box(28, 84, 47, 107)`. Run lattice mode with radius-10 quarter turns, S-bends disabled, a 50-node limit, one congestion iteration, and danger weighting, warm start, tiered strategy, and refinement disabled. The original layout verifies in 17 expansions. Each of the three cardinal rotations reaches the 50-node limit without completing. The original seed verifies when replayed on all four layouts. The heuristic uses trigonometric values for the target heading and tests the perpendicular projection against zero. Tiny nonzero results on an aligned state incur a bend penalty. Replacing only those target vectors with exact cardinal values yielded completion in 17 expansions in every rotation. [Target heading and scoring](../inire/router/cost.py#L105) · [Cardinal rotation helper](../inire/geometry/primitives.py#L59)
Use the exact cardinal vector in the heuristic. Verify mirrored and rotated geometries with the same budget, including a case where the target genuinely requires an alignment penalty. Compare the selected paths and expansions on the corpus to identify any search-order changes.
## 26. Give coincident terminals an explicit result — Low
A connection between abutting cells can have identical arrival and departure ports. Distinct input coordinates can also collapse to the same port after grid snapping. On an empty 100-by-100 board, a net with both endpoints `(30, 20, 0)` produces an empty `unroutable` result with `reached_target=False` in lattice, guide, seed, and automatic modes. The search reaches its target at the initial state, and the worker then treats the empty path as a failure. This looks the same to applications as a failed geometric search. [Grid snapping](../docs/user/api-reference.md#ports-and-nets) · [Reached-target check](../inire/router/_search.py#L103) · [Empty-path result](../inire/router/_router.py#L895)
Define whether Inire should report a geometry-free connection or ask callers to remove it. If supported, distinguish it from an unroutable path and validate board and port compatibility before treating it as connected. If unsupported, give callers an input error that names the net and document how placed-cell workflows should handle the direct join. Exercise exact and snapped coincidences, opposite headings at the same position, and endpoints outside the board.
## 27. Keep acute-corner apertures open in the routing model — Medium
On bounds `(0, 0, 100, 50)` at clearance 1, route a width-2 net from `(7, 15, 0)` to `(93, 35, 0)`. Use keepout triangles `[(35, 0), (65, 0), (50, 22.95)]` and `[(35, 50), (65, 50), (50, 27.05)]`. The gap is 4.1 units at its tightest point. The seed `SBendSeed(10, 10), StraightSeed(50), SBendSeed(10, 10)` verifies. With quarter turns disabled, `sbend_radii=(10,)`, `sbend_offsets=(10,)`, 200 nodes, one iteration, and danger weighting, warm start, and refinement disabled, all four search modes return partial. The mesh reports zero corridors. Its mitered buffers merge across the gap, and the width-aware lattice ray casts against keepouts with the same corner extension. [Mesh padding](../inire/router/_topology.py#L106) · [Width-specific static ray geometry](../inire/geometry/static_obstacle_index.py#L94)
An in-memory probe using rounded corner padding for the mesh alone restored guide, seed, and automatic routing in 25 expansions. Applying it to the ray alone restored lattice routing in 15. Match the broad-phase geometry to Euclidean clearance, or use a local exact retry when corner padding closes a passage. Keep final move verification exact. Test acute and beveled shapes, a genuinely too-narrow aperture, and exact clearance in addition to the existing rectangular cases. [Physical clearance predicate](../inire/geometry/collision.py#L54)
## 28. Recover when the corridor cost steers search away from a working route — Medium
On bounds `(0, 0, 219, 118)` at clearance 1, route width 4.5 from `(16, 48, 0)` to `(199, 82, 0)` and width 1.25 from `(18, 59, 0)` to `(197, 93, 0)`. Use full-height walls across `x = 60..67` with opening `y = 56.25..74.125` and `x = 125..132` with opening `y = 66.25..84.125`. Set both bend radii to 10, S-bend offsets to `(10, 12)`, a 1,000-node search limit, and two congestion iterations. Leave warm start enabled and disable refinement and danger weighting. Lattice verifies both routes in 846 expansions. Default guide strength verifies one route in 3,678 expansions, and seed mode also verifies one. Setting guide strength to zero keeps the corridor proposals and verifies both in 1,488 expansions. Raising the node limit to 4,000 leaves default guide and seed at one route. [Corridor cost](../inire/router/_astar_admission.py#L187) · [Routing retry policy](../inire/router/_router.py#L869) · [Guide strength API](../docs/user/api-reference.md#topologyoptions)
Allow a bounded lower-strength retry when a corridor yields incomplete coverage. Keep useful corridor proposals and allow an incumbent to be reconsidered when it blocks another feasible route. Compare coverage and work on this board and on a case where the guidance cost helps. Preserve intentional caller settings and define when explicit guide and seed modes can use the retry.
## 29. Bound search memory on large failed attempts — Medium
On bounds `(0, 0, 2400, 1600)`, block the board with `box(1180, 0, 1220, 1600)` and route a width-2 net from `(150, 800, 0)` to `(2100, 780, 0)` at clearance 2. Use lattice mode, one congestion iteration, quarter-turn radii `(20, 45)`, S-bend radii `(15, 30)`, and offsets `(-18, -12, 12, 18)`. Turn off danger weighting, tiered strategy, refinement, and warm start. The worker returns a partial path at each configured budget. Peak process memory was about 109 MiB at 500 expansions, 294 MiB at 3,000, and 648 MiB at 8,000. At 8,000 expansions it retained 111,086 absolute move entries and the same number of static-admission keys between the two sets. Lowering the internal geometry-cache threshold to 5,000 entries reduced peak memory at 3,000 expansions to 216 MiB, with the same expansion count and outcome. The static-admission keys were still retained. [Search cache ownership and eviction](../inire/router/_astar_types.py#L229) · [Per-move cache use](../inire/router/_astar_admission.py#L44)
Measure the separate costs of the move caches, static-admission sets, and live frontier. Give long attempts a practical memory bound and retire stale collision keys with the geometry they describe. Reuse local component geometry where it actually reduces retention. Verify deterministic route and trace parity, check peak memory on the blocked board, and include a long attempt that succeeds.
## 30. Keep collision diagnostics in verification-only runs — Medium
On an empty 100-by-100 board, seed width-2 straights from `(10, 50, 0)` to `(90, 50, 0)` and `(50, 10, 90)` to `(50, 90, 90)`. Set the search budget to zero and disable refinement. With `max_iterations=1`, lattice, guide, seed, and automatic each report two colliding paths and one conflict edge. With `max_iterations=2` or its default of 10, the first iteration reports the same conflict. The next iteration replaces both paths with empty results, the layout ranking prefers the empty conflict graph, and the final report calls both paths unroutable. The final trace also loses the conflict edge. [Seed use and retries](../inire/router/_router.py#L838) · [Best-layout ranking](../inire/router/_congestion_policy.py#L31) · [Verification-only option](../docs/user/api-reference.md#searchoptions)
Verify supplied paths once when the search budget is zero and return the physical result and final conflict graph. Keep complete and incomplete seeds diagnosable alongside unseeded nets. Test both one and several congestion iterations in the four modes, and check whether enabled refinement needs a separate verified replacement rule. Retain the explicit zero-iteration behavior.
## 31. Preserve authored lengths when rerouting phase-sensitive connections — Medium
In the Raymond fabrication submission, the two `MZI9` arms carry authored length annotations of 286.770 µm (`Waveguide$10`) and 183.637 µm (`Waveguide$1`). Replacing the former with the automatic route from `(261120, -46270, 0)` to `(261120, -167770, 180)` on the 1 nm grid gives a 127.208 µm path, using two clockwise 5 µm quarter turns and a 111.5 µm straight. Both 500 nm port faces join the existing silicon, and the modified MZI array still passes the published EBeam deck. The signed arm-length difference changes from +103.133 µm to −56.429 µm. Even when the original waypoints and radius are replayed, the circular replacement's reported length can differ from the authored waveguide length. The EBeam 500 nm strip definition specifies Bézier bends, and the `Waveguide` cell's authored 156.137 µm becomes 154.948 µm with circular bends. [Raymond fabrication layout](https://github.com/SiEPIC/openEBL-2025-02/blob/a887476a301db2a014be007717cd1821e111f58e/submissions/EBeam_hannahraymond_MZIv21.gds) · [EBeam waveguide definitions](https://github.com/SiEPIC/SiEPIC_EBeam_PDK/blob/363fbb52eefa8669100499ab531d3fe7befc4867/klayout/EBeam/WAVEGUIDES.xml#L3-L15) · [Public results](../docs/user/api-reference.md#results)
Document which geometric and fabrication checks are covered and which circuit constraints callers must supply and check. Add a reuse example that compares a verified replacement with the authored length and preserves the incumbent when the length difference falls outside tolerance. Evaluate a per-net length target or pairwise length-difference constraint, and carry the actual process-specific bend length through search, refinement, and export when that model is supplied. Use both a length-sensitive MZI and an unconstrained connection as acceptance cases. [Export workflow](../docs/user/route-a-layout.md#export-verified-geometry)
## 32. Infer a launch S-bend before a final quarter turn — Medium
The CROW MZI fabrication submission has nine comparable lower connections that failed in their authored direction under the 225-node probe. All nine completed in 9 to 11 total expansions when the terminal order was reversed and both port headings were turned 180°. Each reversed route also verified when replayed in its original direction. For the `Waveguide$33` link, use a 500 nm width, 70 nm clearance, 5 and 10 µm radii, and the actual terminals `(49700, -267710, 270)` and `(50180, -308570, 180)` on the 1 nm grid. The reversed search realizes one quarter turn, a straight, and an S-bend into its target. The original direction can use the same sequence in reverse. With the original headings and `sbend_offsets=(5480,)`, automatic also completes at the same budget. The lattice's goal-derived S-bend proposal requires the current and target headings to match, so the original approach does not get the necessary S-bend proposal before the quarter turn. [CROW MZI fabrication layout](https://github.com/SiEPIC/openEBL-2025-02/blob/a887476a301db2a014be007717cd1821e111f58e/submissions/masihb_crow1_mzi_v1.gds) · [A* S-bend proposals](../inire/router/_astar_moves.py#L329)
Use the position before a supported terminal quarter turn to propose useful S-bend offsets, or add a bounded reverse probe for unresolved nets with reversible geometry. Verify any reversed seed in the requested direction. Fractional S-bends and asymmetric custom outlines need that check because their physical geometry can depend on the travel direction. Retest the nine links, both handednesses, and a connection that needs to take the turn before the S-bend. Measure expansion counts and keep the configured search budget intact.
## 33. Verify the RF cross-section before exporting a coplanar waveguide — Medium
The pinned QFoundry feedline defines a 15.5 µm signal trace with a 7 µm gap on each side. Replay two parallel, 200 µm straight connections on a 1 nm grid using `NetSpec.width=15500` and `clearance=3000`. At a 32 µm pitch Inire verifies both center conductors. Converting the paths to the negative lithography layer leaves a 2.5 µm ground strip between the two gap envelopes. The QFoundry deck reports one aluminum width violation. At 28 µm pitch the two envelopes merge and the center ground strip disappears. The deck reports no width violation because the intended strip no longer exists. Replaying the same paths at the 29.5 µm envelope width with 3 µm clearance rejects both pitches. A 36 µm control verifies the envelopes, leaves a 6.5 µm strip, and passes the deck. [RF routing scope](../README.md) · [QFoundry waveguide dimensions and layers](https://github.com/tii-qfoundry/PDK_QFoundry/blob/9c31db1d6879c96bd98460ee134181a865481d75/qfoundry/tech/waveguides.xml#L21-L48) · [QFoundry fabrication checks](https://github.com/tii-qfoundry/PDK_QFoundry/blob/9c31db1d6879c96bd98460ee134181a865481d75/qfoundry/tech/drc/drc.lydrc)
Add an RF example that routes against the gap envelope and reuses the verified centerline to emit the strip and gaps on the required process layers. Explain how to preserve the separate ground-clearance envelope and verify ground connectivity, since a width check cannot find an absent strip. At the 15 µm minimum flux-line bend radius, replay builds the 15.5 µm core and the 29.5 µm gap envelope, but rejects the 49.5 µm ground-clearance width because it exceeds the bend diameter. Build this wider exclusion as an offset of the local footprint that fills the inside of the bend. Keep the single-polygon optical workflow available. Check the three pitches and a bend using the published dimensions and process rules. [Geometry export](../docs/user/route-a-layout.md#export-verified-geometry)
Preserve intentional breaks during import and export. In the 5-by-3 mm reference chip, declare one connection on each side of the coupling capacitor, using the effective metal after applying the etch layer. Use the reconstructed mask as the passing control and deliberately omit the coupling mask to check that the independent connectivity test detects the short. [Published CPW chip](https://github.com/paulggin/klayout-cpw-design/blob/a38dc34cf6785ba0af41b27f43b6137fd2b69cc7/layouts/cpw_full_layout.gds)
## 34. Apply the bend rules for each geometry class on a mixed layout — Medium
The pinned QFoundry feedline and flux-line profiles have the same 15.5 µm trace width and 7 µm gaps, but their minimum bend radii are 50 µm and 15 µm respectively. On bounds `(0, 0, 150000, 55000)` at 1 nm per unit, route gap-envelope width 29500 from `(35000, 20000, 0)` to `(50000, 35000, 90)` for `flux` and from `(100000, 20000, 0)` to `(115000, 35000, 90)` for `feed`. With clearance 3000, no S-bends, and allowed radii `(15000, 50000)`, lattice completes both with a radius-15000 quarter turn. The feedline violates its process radius. Removing the smaller radius globally also removes the legal flux-line turn. A shared width cannot distinguish these two route profiles. [QFoundry bend profiles](https://github.com/tii-qfoundry/PDK_QFoundry/blob/9c31db1d6879c96bd98460ee134181a865481d75/qfoundry/tech/waveguides.xml#L42-L64) · [Net model](../inire/model.py#L24) · [Search options](../docs/user/api-reference.md#searchoptions)
Document how to route separately by process profile and preserve each verified group as keepouts. Evaluate a per-net permitted geometry profile for design flows that need joint routing. Use the same profile during search, seed replay, refinement, and final verification. Check this board and a second board with room for both legal turns.
## 35. Check the physical widths of placed optical ports — Medium
On a 1 nm grid, connect a 500 nm device port at `(10000, 10000, 0)` to a 3 µm device port at `(110000, 10000, 0)` with a width-500 net. With the documented port openings in the routing keepouts, Inire verifies a straight. On the assembled silicon, the independent EBeam deck reports one `SiEPIC-1a` marker at the target port. Route the 500 nm connection to `(70000, 10000, 0)` instead, and place the pinned 40 µm, 500-to-3000 nm EBeam taper from there to the target. The assembly passes the same deck. The API has port position and heading plus one width for the whole net. The widths of the attached devices live outside that model. [Placed-device workflow](../docs/user/route-a-layout.md#route-between-placed-crossings) · [Published EBeam taper](https://github.com/SiEPIC/SiEPIC_EBeam_PDK/blob/363fbb52eefa8669100499ab531d3fe7befc4867/klayout/EBeam/gds/EBeam/ebeam_routing_taper_te1550_w%3D500nm_to_w%3D3000nm_L%3D40um.gds) · [Pinned EBeam deck](https://github.com/SiEPIC/SiEPIC_EBeam_PDK/blob/363fbb52eefa8669100499ab531d3fe7befc4867/klayout/EBeam/drc/SiEPIC_EBeam.drc)
Show how to check both terminal widths and place explicit process tapers before routing. Have a layout adapter accept declared port widths and reject a direct join if the widths differ. Use the correctly placed taper, a deliberately omitted taper, and matched-width terminals rotated by 90° as acceptance cases.
## 36. Keep the search heuristic in the configured cost units — Medium
On bounds `(0, 0, 190, 100)`, route a width-2 net from `(15, 40, 0)` to `(165, 80, 0)` around `box(63, 7, 85, 55)` at clearance 2. Use lattice mode, a 32-node limit, radius-10 quarter turns, no S-bends, a minimum straight length of 2, and `greedy_h_weight=1.5`. Disable warm start, tiered strategy, and refinement, and use one congestion iteration. With only length in the search objective, `unit_length_cost=1` completes in 12 expansions. Changing the cost per unit to `0.001` or `1000` yields a partial route at 32 expansions. A cost-unit change should leave the pure-length objective ordered the same way. An in-memory probe scaling the Manhattan distance term by the configured length cost restored the original path at `0.001` in 12 expansions. [Search heuristic and move scoring](../inire/router/cost.py#L117) · [Corridor heuristic](../inire/router/_astar_types.py#L99) · [Cost options](../docs/user/api-reference.md#objectiveweights)
Use the configured length units for estimated remaining distance, including corridor distance. Keep the interpretation of `greedy_h_weight` consistent with the accumulated objective. Check the three cost scales in lattice search, a corridor-guided case, and explicit behavior at zero length cost.
## 37. Diagnose terminals whose physical ports cannot be reached — Medium
On bounds `(0, 0, 300, 160)`, route a width-2 net at clearance 2 from `(10, 80, 0)` to `(302, 80, 0)`. Use radius-20 quarter turns, radius-10 S-bends, a 600-node limit, one congestion iteration, and disable warm start, refinement, and danger weighting. Lattice uses all 600 expansions. Automatic uses 2,200 across attempts and returns a partial path with no diagnostic that identifies the off-board terminal. The same happens with target `(280, 80, 0)` inside `box(275, 75, 285, 85)`. As a control, target `(300, 80, 0)` is on the board edge and verifies with a flat end face. [Worker dispatch](../inire/router/_router.py#L838) · [Physical verification](../inire/geometry/collision.py#L608) · [Reported outcomes](../docs/user/api-reference.md#results)
Check terminal positions and the required physical end faces against the board and keepouts before starting an attempt. Report the specific invalid terminal and keep other nets routable. Preserve valid flush interfaces and port openings. Keep verification of a supplied partial path available for inspecting an infeasible connection, and test placements just inside and outside a boundary and at exact clearance.
## 38. Distinguish zero clearance from a short between different nets — Medium
On a 1 nm grid, replay two 8 µm straights with 500 nm width and y coordinates 2000 and 2500. At `clearance=0`, both routes verify without dynamic collisions. Their polygons share an 8 µm edge. After writing and reading the common silicon layer, KLayout merges them into one connected polygon. The published EBeam width and spacing deck produces no marker because it sees a single conductor. At positive clearance, Inire detects the contact. A control with 70 nm of actual gap verifies in both tools and retains two connected components. [Exact clearance predicate](../inire/geometry/collision.py#L48) · [Geometry export](../docs/user/route-a-layout.md#export-verified-geometry) · [Pinned EBeam deck](https://github.com/SiEPIC/SiEPIC_EBeam_PDK/blob/363fbb52eefa8669100499ab531d3fe7befc4867/klayout/EBeam/drc/SiEPIC_EBeam.drc)
Define and document whether distinct nets may share edges or vertices at zero clearance. For independent same-layer connections, report shared edges as shorts or require an explicit policy for intentional contact. Preserve normal adjacent moves of the same net and process boundaries represented as keepouts. Check a shared edge, an endpoint contact, a valid zero-clearance boundary, and separate exported conductors.
## 39. Verify clearance on the coordinates written to the layout file — Medium
On a 1 nm grid, replay concentric counterclockwise quarter turns about `(3000, 6070)`. The inner net is 490 nm wide with radius 2500 nm, from `(3000, 3570, 0)` to `(5500, 6070, 90)`. The outer is 509.94 nm wide with radius 3070 nm, from `(3000, 3000, 0)` to `(6070, 6070, 90)`. At clearance 70 nm both verify, with a minimum floating-point separation of 70.0208 nm. Rounding their polygon vertices to the original 1 nm grid reduces the gap to 68.9420 nm. KLayout reports 12 EBeam `Si_space` markers in the written OASIS file. A 0.1 nm export of the same polygons produces zero markers. The 1 nm control with a 3072 nm outer radius, the same widths, and corresponding endpoints also produces zero markers. [Public export workflow](../docs/user/route-a-layout.md#export-verified-geometry) · [Arc polygon coordinates](../inire/geometry/components.py#L235) · [Pinned EBeam spacing rule](https://github.com/SiEPIC/SiEPIC_EBeam_PDK/blob/363fbb52eefa8669100499ab531d3fe7befc4867/klayout/EBeam/drc/SiEPIC_EBeam.drc)
Document that snapping ports leaves bend polygons with fractional vertex coordinates. In a fabrication export adapter, verify the actual quantized geometries or allow an intentional clearance margin tied to the export grid. Test rounded bends near minimum clearance and check that the selected rounding policy preserves port faces and accepted joins.
## 40. Preserve layer identity in the routing and export workflow — Low
On a 1 nm grid, replay a 500 nm-wide silicon straight from `(1000, 10000, 0)` to `(19000, 10000, 0)` and a 750 nm-wide silicon nitride straight from `(10000, 1000, 90)` to `(10000, 19000, 90)`. A single Inire problem reports both as colliding. Each verifies in a separate problem. On the EBeam silicon `1/0` and silicon nitride `4/0` layers, KLayout retains both geometries separately despite their projected intersection, and the published fabrication deck reports zero markers. Exporting both on `1/0` instead produces one connected polygon, also with zero markers. Process layer identity determines which geometry overlaps are allowed. [Layout inputs](../docs/user/api-reference.md#layout-inputs) · [Pinned EBeam layer rules](https://github.com/SiEPIC/SiEPIC_EBeam_PDK/blob/363fbb52eefa8669100499ab531d3fe7befc4867/klayout/EBeam/drc/SiEPIC_EBeam.drc)
State that each routing problem represents one collision plane. Show how an adapter preserves layer identity, partitions independent layers into separate problems, and adds cross-layer keepouts where the process requires them. Keep placed transition devices in the circuit model. Check both layer assignments and verify connectivity separately from fabrication spacing.
## 41. Revisit legal turns away from the target before the budget runs out — Medium
Use bounds `(-25, -185, 230, 0)`, keepout `box(50, -185, 187, -37)`, width 2, clearance 1, and terminals `(190, -40, 270)` and `(20, -50, 0)`. The path must go east around the obstacle before traveling west to approach the target. Use lattice mode, radius-10 quarter turns, no S-bends, straight lengths from 2 to 40, a bend penalty of 10, and a 500-node limit. Use one congestion iteration and disable warm start, tiered strategy, refinement, and danger weighting. The current search returns partial at 500 expansions. An in-memory run admitting the turns immediately completes in 443. A geometric seed verifies as well. The distant-turn rule defers moves whose new headings point away from the target, and A* only releases those moves when the preferred queue empties. [Turn classification](../inire/router/_astar_moves.py#L298) · [Deferred queue](../inire/router/_search.py#L74)
Keep a bounded share of the search budget for deferred turns, or promote deferred moves when the preferred frontier stops improving. Compare the original budget on this board, a mirrored board, and cases where the detour is blocked. Measure the added search on boards whose best path turns toward the target immediately.
## Local verification for the batches
- Run `.venv/bin/ruff check --no-cache inire scripts` and focused regressions for each batch. Run `INIRE_RUN_PERFORMANCE=1 .venv/bin/pytest -q` before closing the plan. Tests run locally using the existing developer workflow. [Developer guide](../docs/development.md#check-a-change)
- Compare `public-defaults` and `corpus-regression` per board for verified IDs, work, and route cost. Use 433 verified nets across 67 boards as the prior public-defaults baseline. Investigate any coverage loss and record intended gains or path changes. Include the splitter-tree regression, mixed-width and crossing holdouts, and the fixed-heading and point-terminal variants of complex-routing example 1. [Benchmark profiles and fixtures](../docs/benchmarks.md#choose-a-profile)
- Exercise automatic, lattice, guide, seed, and bundle where each mode supports the fixture. Confirm the no-triangulation capability tests and run a smoke check using the minimum supported library versions when that environment is available. Replay supplied seeds with a zero search budget where specified. [Mode and dependency behavior](../docs/complex-routing-example-1.md#compare-all-routing-modes)
- Regenerate the walkthrough into a scratch directory. Keep active user and developer pages reachable within two links, with planning and archived materials outside that navigation check. [Figure regeneration](../docs/development.md#check-a-documentation-figure)
- For fabrication changes, compare the original, an export-only control, and the routed design in KLayout. Use the pinned decks above and compare marker types and coordinates. For optical checks, replace the original waveguide polygons on the silicon layer and retain the surrounding layout and port markers. Check circuit length metadata separately. For RF, retain the conductor and gap dimensions through negative-layer export and check ground continuity as well as widths.