Implement typed and octagonal catalog routing

This commit is contained in:
Jan Petykiewicz 2026-12-04 09:30:14 -08:00
commit 7616b398e9
25 changed files with 5544 additions and 85 deletions

View file

@ -41,3 +41,71 @@ For a mode comparison, use the same problem and options in each call to `route()
1. **Coverage and bounds.** Check which nets verified and whether their count reached the expected bound. The tests also verify known reference routes where available.
2. **Cost on matching net sets.** Benchmark-weighted length weights physical straights, 90-degree bends, and S-bends by 1, 4, and 13. Native objective cost uses the run's configured objective.
3. **Search and time.** Compare expansions and repeated wall times at the same settings. Constructive stages can spend time planning and verifying even with zero expansions. Inspect the [automatic reports](routing-diagnostics.md#automatic-reports) to find which stage performed the work.
## Capture legacy parity
Run `PYTHONPATH=. python scripts/capture_legacy_routing.py /tmp/inire-parity.json --repeat 3` from the checkout under test. Compare against revision `3b3d1c7` to measure the change to the move evaluator. To capture a Git archive, run the same script by absolute path from the extracted source tree and pass `--revision 3b3d1c7`. The capture records the effective ports, ordered moves, lengths, physical polygons, work counters, options, dependencies, and elapsed time. Use the same dependencies and compare route and work fields independently of elapsed time. The comparison covered 154 cases and modes with three repetitions per checkout and used Python 3.13.18, GEOS 3.13.1, NumPy 2.4.2, SciPy 1.17.1, Shapely 2.1.2, and Rtree 1.4.1. All recorded outcomes, routes, polygons, and deterministic work counters agreed. The sum of the per-case median times was 21.87 s at the reference revision and 21.88 s with the evaluation boundary.
## Catalog scale benchmarks
Use the aligned case for long-range profile changes. Use the constrained case for an obstacle detour among 40 connections on the same 5 × 5 mm board at 100 nm pitch. The script verifies the frozen reference routes independently before timing unseeded search.
```sh
PYTHONPATH=. python scripts/benchmark_catalog_routing.py --case constrained --mode native
PYTHONPATH=. python scripts/benchmark_catalog_routing.py --case constrained --mode manhattan
PYTHONPATH=. python scripts/benchmark_catalog_routing.py --case constrained --mode typed
PYTHONPATH=. python scripts/benchmark_catalog_routing.py --case constrained --mode typed --no-refinement
PYTHONPATH=. python scripts/benchmark_catalog_routing.py --case constrained --mode octagonal
```
Native uses the existing Manhattan API. Manhattan uses the catalog evaluator with a single profile and cardinal turns. Typed adds the centered transition. Octagonal also admits 45° bends. The diagonal-savings case keeps cardinal terminals and gives the octagonal search a shorter two-turn path. The diagonal case has a native diagonal terminal pair.
Use `--guide-pitch 1000` and `--guide-pitch 10000` to compare coarse guidance against explicit routing. The off-coarse case exercises a displaced transition at 1 nm layout precision. On the same case `--auto-pitch 1000` selects 200 nm and verifies the same terminal poses. For a bounded failure control, use `--node-limit 0`. Use `--geometry` to retain the ordered moves and physical polygons with each report.
The report includes repeated wall times, peak resident memory from the operating system, and per-net cost and physical length. Compare costs on the intersection of the completed net sets. Catalog reports also include work from discarded search attempts and budgeted retries.
### Representative measurements
The following constrained-case runs used an AMD Ryzen 9 5900X and a 1000-node detailed-search limit. Times are medians of three runs. The catalog Manhattan and typed configurations completed all 40 requests. Native Manhattan verified 39 within the same node limit.
| Configuration | Verified | Time | Catalog cost |
| --- | ---: | ---: | ---: |
| Native Manhattan, refinement disabled | 39 | 1.96 s | 17.9400 |
| Catalog Manhattan, refinement disabled | 40 | 0.54 s | 18.4426 |
| Typed, refinement disabled | 40 | 2.06 s | 10.2136 |
| Typed, refinement enabled | 40 | 2.24 s | 10.0140 |
| Octagonal, refinement disabled | 40 | 6.15 s | 10.2136 |
| Typed, 1 µm guidance, refinement disabled | 40 | 2.47 s | 10.2136 |
| Typed, 10 µm guidance, refinement disabled | 40 | 2.02 s | 10.2136 |
On the 39 routes verified by native Manhattan, the typed run without refinement cost 9.711. At both guidance pitches, 39 fine routes verified inside their first corridor and one completed after the explicit retry. The diagonal-savings case lowered the planted route from 591.416 µm and cost 0.076 to 481.982 µm and cost 0.06663. Profiling the octagonal run identified geometry admission and straight-span proposals as the largest search costs. Checking the output pose and cost lower bound before geometry evaluation brought the median over all 40 nets to 1.79 s.
The `corpus-open-lanes` and `corpus-lanes` cases reuse twelve lanes from the existing scale banks. The open lanes all switched profiles and reduced the total catalog cost from 0.648 to 0.552. With the corpus keepouts present, all twelve routed and the total stayed at 0.648 because the wider guide would violate clearance.
The constrained run with a zero-node budget verified and completed zero routes and reported `node_limit` for all 40. Native Manhattan used 115 MiB peak resident memory on the constrained board. The refined typed run used 90 MiB.
## Delay and independent-net retry
```sh
PYTHONPATH=. python scripts/benchmark_catalog_routing.py --case tuning --no-refinement
PYTHONPATH=. python scripts/benchmark_catalog_routing.py --case retry --no-refinement
PYTHONPATH=. python scripts/benchmark_catalog_routing.py --case retry --no-refinement --no-independent-retry
```
The tuning case measures a four-turn detour inside a caller-supplied window. The retry case shows whether the released reservation lets an independent net complete. Compare the verified and completed sets, group skew, straight spans intersecting active tuning windows, checked replacements, and time spent tuning or retrying.
On the same machine the tuning case matched both routes at zero residual skew in a median of 1.59 s with the shared tuning and retry budget. The first pass examined 1334 proposals, with 524 verified replacements from one eligible span. The released-reservation case completed one independent route with retry and zero with retry disabled, at 1.17 s and 1.15 s median respectively.
## Catalog acceptance checks
Run the catalog fixtures with Masque 4.0a3 importable to include layout placement and terminal checks.
```sh
python -m pytest -q inire/tests/test_catalog_*.py
```
- The [device set](../inire/tests/catalog_device_set.py) records the three profiles, authored transitions, generated bend settings, and fixed delays. [Device checks](../inire/tests/test_catalog_device_set.py)
- The [move and placement checks](../inire/tests/test_catalog_moves.py) cover exact lattice membership, grid-compatible leads, profile transitions, attachments, replay, physical placement, and partial placement.
- The [small search oracles](../inire/tests/test_catalog_search_oracle.py) enumerate complete histories and compare them with production proposal and pruning rules.
- The [timing checks](../inire/tests/test_catalog_timing_cases.py) cover direction-aware and wavelength-aware delay, matching budgets, window containment, and final verification of the chosen layout.

View file

@ -25,6 +25,45 @@ result = route(problem).results_by_net["input"]
- [Bend radius settings](api-reference.md#searchoptions)
- [Layout input types and defaults](api-reference.md#routingproblem)
## Route a typed Masque layout
The preview adapter lives in `inire.masque`. The integration fixtures exercise Masque 4.0a3. Define named ports on the top-level pattern, using Masque's port mappings to expose ports from preplaced cells. Assign each endpoint its canonical routing profile. The adapter rounds resolved positions to the nearest layout unit before Inire checks exact membership on the routing lattice. Dimensions in the grid, shapes, and catalog use that common layout unit.
```python
from math import pi
from masque import Pattern, Port
from shapely.geometry import box
from inire.masque import Catalog, Connection, Endpoint, Grid, Profile, StraightVariant, route_and_place
layout = Pattern(ports={
"source": Port((10_000, 20_000), rotation=pi),
"destination": Port((90_000, 20_000), rotation=0),
})
catalog = Catalog("process-a", {"ridge-4": Profile("ridge", width=4000)}, {
"ridge-straight": StraightVariant("ridge-4", cost_per_cm=1),
})
result = route_and_place(
layout,
{},
(Connection("input", Endpoint("source", "ridge-4"), Endpoint("destination", "ridge-4")),),
catalog=catalog,
grid=Grid(origin=(0, 0), pitch=100, meters_per_unit=1e-9),
board=box(0, 0, 100_000, 80_000),
layer=1,
)
assert result.placed == ("input",)
```
Pass a mapping from cell names to Masque patterns for fixed variants. Include blocking polygons from the placed layout in `keepouts`. An endpoint can carry an `Attachment` for one of those polygons when its route must join at the fixed port. Both endpoint names are consumed for each placed connection. A fixed cell can omit its physical centerline length. Nonadjacent pieces separated by a cell with unknown length must meet ordinary self-clearance. With `require_complete=True`, every requested connection and active match group must complete before placement begins.
To experiment with lattice selection, pass `AutomaticGrid(preferred_pitch=1000, meters_per_unit=1e-9)`. It uses a divisor of the preferred pitch that fits the rounded terminals and the authored fixed-cell displacements. Read the selected grid from the placement result. Pass `CoarseGuidance(pitch=1000)` to propose routes inside coarse corridors while still placing and verifying moves on the selected routing grid. The fine search can retry outside a corridor within the remaining node budget.
The placement result reports the catalog revision, evaluated routes, consumed terminals, and placement outcome. Each verified route exposes its catalog cost and physical length in layout units when the lengths of all constituent moves are known. Inspect `unavailable_variants` for grid-fit and realization diagnostics.
Give each `MatchGroup` its member offsets, wavelength in meters, and tolerance. Express offsets and tolerance in group optical length in layout units or in seconds. Supply a `DelayModel` for the process indices and characterized cell delays. To enable a tuning detour, supply that net's polygon in `tuning_windows`. A fixed contribution can be a characterized constant, a function of wavelength, or `None` for missing delay data. Bend lead costs use the profile's lowest declared straight rate by default. Set a bend's `lead_cost_per_cm=0` to include the leads in its placement charge.
<a id="connect-a-preplaced-crossing"></a>
## Route between placed crossings

679
inire/_catalog.py Normal file
View file

@ -0,0 +1,679 @@
"""Evaluate catalog moves in layout coordinates, independently of search and timing."""
from __future__ import annotations
from dataclasses import dataclass
from math import ceil, floor, fsum, hypot, isfinite, radians, sqrt, ulp
from numbers import Integral
from typing import TYPE_CHECKING
import numpy as np
from shapely.affinity import affine_transform, translate
from shapely.geometry import Polygon
from inire._snapshot import snapshot
from inire.geometry.catalog_curve import CurveSection, bend_curve, sample_section, sbend_curve, world_sections
if TYPE_CHECKING:
from collections.abc import Mapping
HEADING_STEPS = {
0: (1, 0), 45: (1, 1), 90: (0, 1), 135: (-1, 1),
180: (-1, 0), 225: (-1, -1), 270: (0, -1), 315: (1, -1),
}
def _require_integer(value: int) -> None:
if isinstance(value, bool) or not isinstance(value, Integral):
raise TypeError(f"Expected an integer layout coordinate or heading, got {value!r}")
def _require_positive(name: str, value: float) -> None:
if not isfinite(value) or value <= 0:
raise ValueError(f"{name} must be finite and positive")
def _require_nonnegative(name: str, value: float) -> None:
if not isfinite(value) or value < 0:
raise ValueError(f"{name} must be finite and nonnegative")
@dataclass(frozen=True, slots=True)
class Grid:
"""A square routing lattice in the adapter's integer layout units."""
origin: tuple[int, int]
pitch: int
meters_per_unit: float
def __post_init__(self) -> None:
for coordinate in (*self.origin, self.pitch):
_require_integer(coordinate)
_require_positive("Grid pitch", self.pitch)
_require_positive("Physical layout scale", self.meters_per_unit)
def lattice_position(self, x: int, y: int) -> tuple[int, int] | None:
_require_integer(x)
_require_integer(y)
col, rx = divmod(int(x) - int(self.origin[0]), int(self.pitch))
row, ry = divmod(int(y) - int(self.origin[1]), int(self.pitch))
return (col, row) if rx == ry == 0 else None
@dataclass(frozen=True, slots=True)
class Pose:
"""A layout position, heading in degrees, and canonical routing profile ID."""
x: int
y: int
heading: int
profile: str
def __post_init__(self) -> None:
for value in (self.x, self.y, self.heading):
_require_integer(value)
if self.heading not in HEADING_STEPS:
raise ValueError(f"Unsupported routing heading {self.heading}")
if not self.profile:
raise ValueError("A routing pose needs a profile ID")
# Exact arithmetic after transforms, including for numpy integer inputs.
object.__setattr__(self, "x", int(self.x))
object.__setattr__(self, "y", int(self.y))
object.__setattr__(self, "heading", int(self.heading))
def shifted(self, dx: int, dy: int) -> Pose:
return Pose(self.x + dx, self.y + dy, self.heading, self.profile)
def reversed(self) -> Pose:
return Pose(self.x, self.y, (self.heading + 180) % 360, self.profile)
@dataclass(frozen=True, slots=True)
class Profile:
waveguide_type: str
width: float
def __post_init__(self) -> None:
if not self.waveguide_type:
raise ValueError("A routing profile needs a waveguide type")
_require_positive("Profile width", self.width)
@dataclass(frozen=True, slots=True)
class Orientation:
"""Reflect about the local x-axis, then rotate about the origin."""
rotation: int = 0
reflected: bool = False
def __post_init__(self) -> None:
_require_integer(self.rotation)
if self.rotation not in (0, 90, 180, 270):
raise ValueError("Fixed-cell rotations must be declared quarter turns")
def matrix(self) -> tuple[int, int, int, int]:
x, y = HEADING_STEPS[self.rotation]
sign = -1 if self.reflected else 1
return x, -y * sign, y, x * sign
def port(self, port: Pose) -> Pose:
a, b, d, e = self.matrix()
heading = -port.heading if self.reflected else port.heading
return Pose(a * port.x + b * port.y, d * port.x + e * port.y, (heading + self.rotation) % 360, port.profile)
@dataclass(frozen=True, slots=True)
class Placement:
orientation: Orientation
x: int
y: int
@dataclass(frozen=True, slots=True)
class FixedVariant:
"""A two-port cell with named inward-facing authored ports."""
cell: str
ports: Mapping[str, Pose]
footprints: tuple[Polygon, ...]
traversals: tuple[tuple[str, str], ...]
orientations: tuple[Orientation, ...]
cost: float
length: float | None = None
port_shapes: tuple[Polygon, ...] = ()
def __post_init__(self) -> None:
if not self.cell or len(self.ports) != 2 or not all(self.ports):
raise ValueError("A fixed variant needs a cell and two distinct named ports")
if not self.footprints or any(
not isinstance(shape, Polygon) or shape.is_empty or not shape.is_valid or shape.has_z
or not isfinite(shape.area) or shape.area <= 0 for shape in (*self.footprints, *self.port_shapes)
):
raise ValueError("Fixed variant footprints must be nonempty valid planar polygons")
if (
not self.traversals or len(set(self.traversals)) != len(self.traversals)
or any(a == b or a not in self.ports or b not in self.ports for a, b in self.traversals)
):
raise ValueError("A fixed variant needs distinct directed traversals between its named ports")
if not self.orientations or len(set(self.orientations)) != len(self.orientations):
raise ValueError("A fixed variant needs distinct declared orientations")
_require_nonnegative("Fixed placement cost", self.cost)
if self.length is not None:
_require_positive("Fixed physical length", self.length)
object.__setattr__(self, "ports", snapshot(self.ports))
@dataclass(frozen=True, slots=True)
class StraightVariant:
profile: str
cost_per_cm: float
def __post_init__(self) -> None:
_require_nonnegative("Straight cost per centimeter", self.cost_per_cm)
@dataclass(frozen=True, slots=True)
class TaperVariant:
input_profile: str
output_profile: str
minimum_length: float
cost: float
max_stretch: float = 0.05
def __post_init__(self) -> None:
if self.input_profile == self.output_profile:
raise ValueError("A taper traversal must change profiles")
_require_positive("Taper minimum length", self.minimum_length)
_require_nonnegative("Taper cost", self.cost)
_require_nonnegative("Taper stretch limit", self.max_stretch)
@dataclass(frozen=True, slots=True)
class BendVariant:
profile: str
turn: int # signed degrees
radius: float
cost: float
minimum_radius: float = 0.0
euler_fraction: float | None = None
max_lead: float = 0.0
lead_cost_per_cm: float | None = None
sagitta: float = 0.01
def __post_init__(self) -> None:
_require_integer(self.turn)
if abs(self.turn) not in (45, 90, 135, 180):
raise ValueError("Generated bends must turn by 45°, 90°, 135°, or 180°")
_require_positive("Circular-equivalent radius", self.radius)
_require_positive("Bend sampling sagitta", self.sagitta)
_require_nonnegative("Minimum curvature radius", self.minimum_radius)
_require_nonnegative("Bend cost", self.cost)
_require_nonnegative("Tangent lead cap", self.max_lead)
if self.lead_cost_per_cm is not None:
_require_nonnegative("Lead cost per centimeter", self.lead_cost_per_cm)
if self.euler_fraction is not None and not 0 <= self.euler_fraction <= 1:
raise ValueError("An explicit Euler fraction must be in [0, 1]")
@dataclass(frozen=True, slots=True)
class SBendVariant:
profile: str
radius: float
cost: float
projections: tuple[tuple[int, int], ...]
minimum_radius: float = 0.0
euler_fraction: float | None = None
sagitta: float = 0.01
def __post_init__(self) -> None:
_require_positive("S-bend circular-equivalent radius", self.radius)
_require_positive("S-bend sampling sagitta", self.sagitta)
_require_nonnegative("S-bend minimum curvature radius", self.minimum_radius)
_require_nonnegative("S-bend cost", self.cost)
if self.euler_fraction is not None and not 0 <= self.euler_fraction <= 1:
raise ValueError("An explicit Euler fraction must be in [0, 1]")
if not self.projections or len(set(self.projections)) != len(self.projections):
raise ValueError("An S-bend needs distinct forward/lateral projection choices")
for forward, lateral in self.projections:
_require_integer(forward)
_require_integer(lateral)
if forward <= 0 or lateral == 0:
raise ValueError("S-bend projections require forward motion and nonzero lateral offset")
Variant = FixedVariant | StraightVariant | TaperVariant | BendVariant | SBendVariant
@dataclass(frozen=True, slots=True)
class Catalog:
revision: str
profiles: Mapping[str, Profile]
variants: Mapping[str, Variant]
def __post_init__(self) -> None:
if not self.revision or not all(self.profiles) or not all(self.variants):
raise ValueError("Catalog revision and IDs must be nonempty")
for name, variant in self.variants.items():
if isinstance(variant, FixedVariant):
profiles = tuple(port.profile for port in variant.ports.values())
elif isinstance(variant, TaperVariant):
profiles = (variant.input_profile, variant.output_profile)
else:
profiles = (variant.profile,)
if any(profile not in self.profiles for profile in profiles):
raise ValueError(f"Variant {name!r} uses an unknown profile")
object.__setattr__(self, "profiles", snapshot(self.profiles))
object.__setattr__(self, "variants", snapshot(self.variants))
@dataclass(frozen=True, slots=True)
class Move:
"""Selected parameters within one catalog revision."""
variant: str
steps: int | None = None
traversal: tuple[str, str] | None = None
orientation: Orientation = Orientation()
displacement: tuple[int, int] | None = None
leads: tuple[float, float] = (0.0, 0.0)
@dataclass(frozen=True, slots=True)
class Evaluation:
move: Move
start: Pose
end: Pose
footprints: tuple[Polygon, ...]
length: float | None # layout units
cost: float
placement: Placement | None = None
curve_sections: tuple[CurveSection, ...] = ()
minimum_radius: float | None = None
euler_fraction: float | None = None
port_shapes: tuple[Polygon, ...] = ()
def face_endpoints(pose: Pose, width: float) -> tuple[tuple[float, float], tuple[float, float]]:
"""Construct the same finite face for both sides of a direct join."""
dx, dy = HEADING_STEPS[pose.heading]
half_width = width / (2 * hypot(dx, dy))
nx, ny = -dy * half_width, dx * half_width
return (pose.x + nx, pose.y + ny), (pose.x - nx, pose.y - ny)
def unit_direction(heading: int) -> tuple[float, float]:
x, y = HEADING_STEPS[heading]
length = hypot(x, y)
return x / length, y / length
def _bend_port_displacement(variant: BendVariant, heading: int) -> tuple[float, float]:
turn_cos, turn_sin = unit_direction(abs(variant.turn))
forward = variant.radius * turn_sin
lateral = (1 if variant.turn > 0 else -1) * variant.radius * (1 - turn_cos)
x, y = unit_direction(heading)
return forward * x - lateral * y, forward * y + lateral * x
def _euler_setting(variant: BendVariant | SBendVariant) -> float | None:
if variant.euler_fraction is None and not variant.minimum_radius:
return 0.0
return variant.euler_fraction
def curve_polygon(
sections: tuple[CurveSection, ...], start: Pose, end: Pose, width: float, sagitta: float,
) -> Polygon:
left_edges, right_edges = [], []
current = (float(start.x), float(start.y))
for section in sections:
positions, normals = sample_section(section, current, sagitta)
offsets = normals * width / 2
left_edges.append(positions[:-1] + offsets[:-1])
right_edges.append(positions[:-1] - offsets[:-1])
current = tuple(positions[-1])
left_start, right_start = face_endpoints(start, width)
left_end, right_end = face_endpoints(end, width)
left = np.vstack((*left_edges, left_end))
right = np.vstack((*right_edges, right_end))
left[0], right[0] = left_start, right_start
return Polygon(np.concatenate((left, right[::-1])))
@dataclass(frozen=True, slots=True)
class _LocalFixed:
entry: Pose
exit: Pose
footprints: tuple[Polygon, ...]
port_shapes: tuple[Polygon, ...]
@dataclass(frozen=True, slots=True)
class VariantDiagnostic:
move: Move
entry_heading: int
reason: str
projections: tuple[int, int] | None = None
class MoveEvaluator:
"""Evaluate known move parameters with a request-local fixed geometry cache."""
def __init__(self, grid: Grid, catalog: Catalog) -> None:
self.grid = grid
self.catalog = catalog
self._fixed: dict[Move, _LocalFixed] = {}
self._bend_moves: dict[tuple[str, int], tuple[Move, ...]] = {}
self._bend_shapes: dict[tuple[Move, int], Evaluation] = {}
self._local_moves: dict[tuple[str, int], tuple[tuple[Move, Pose], ...]] = {}
self._sbend_shapes: dict[tuple[Move, int], Evaluation | None] = {}
self._unavailable: dict[tuple[Move, int, tuple[int, int] | None], VariantDiagnostic] = {}
@property
def unavailable(self) -> tuple[VariantDiagnostic, ...]:
return tuple(self._unavailable.values())
def _diagnose(self, move: Move, heading: int, reason: str, projections: tuple[int, int] | None = None) -> None:
self._unavailable.setdefault((move, heading, projections), VariantDiagnostic(move, heading, reason, projections))
def coverage_catalog(self, profile: str, *, cardinal: bool) -> Catalog:
"""Keep the profile's own primitives for a bounded coverage retry."""
variants = {}
for name, variant in self.catalog.variants.items():
if isinstance(variant, FixedVariant):
eligible = all(port.profile == profile and (not cardinal or port.heading % 90 == 0) for port in variant.ports.values())
elif isinstance(variant, TaperVariant):
eligible = False
else:
eligible = variant.profile == profile and (not cardinal or not isinstance(variant, BendVariant) or variant.turn % 90 == 0)
if eligible:
variants[name] = variant
return Catalog(self.catalog.revision, {profile: self.catalog.profiles[profile]}, variants)
def _local_fixed(self, move: Move, variant: FixedVariant) -> _LocalFixed:
if (
move.steps is not None or move.displacement is not None or move.leads != (0.0, 0.0)
or move.traversal not in variant.traversals or move.orientation not in variant.orientations
):
raise ValueError(f"Undeclared traversal or transform for fixed variant {move.variant!r}")
cached = self._fixed.get(move)
if cached is None:
assert move.traversal is not None
input_port, output_port = (variant.ports[name] for name in move.traversal)
orientation = move.orientation
cached = _LocalFixed(
orientation.port(input_port), orientation.port(output_port).reversed(),
tuple(affine_transform(shape, (*orientation.matrix(), 0, 0)) for shape in variant.footprints),
tuple(affine_transform(shape, (*orientation.matrix(), 0, 0)) for shape in variant.port_shapes),
)
self._fixed[move] = cached
return cached
def fixed_exit(self, move: Move, start: Pose, variant: FixedVariant) -> Pose | None:
"""Compute compatible fixed-cell displacement before translating polygons."""
local = self._local_fixed(move, variant)
if (start.profile, start.heading) != (local.entry.profile, local.entry.heading):
return None
end = local.exit.shifted(start.x - local.entry.x, start.y - local.entry.y)
if self.grid.lattice_position(end.x, end.y) is None:
self._diagnose(move, start.heading, "off_grid_output")
return None
return end
def local_moves(self, profile: str, heading: int) -> tuple[tuple[Move, Pose], ...]:
"""Finite compatible moves and their port displacement from the start."""
key = (profile, heading)
if key not in self._local_moves:
ox, oy = self.grid.origin
origin = Pose(ox, oy, heading, profile)
variants = self.catalog.variants
steps = []
for name, variant in variants.items():
if isinstance(variant, FixedVariant):
for traversal in variant.traversals:
for orientation in variant.orientations:
move = Move(name, traversal=traversal, orientation=orientation)
if end := self.fixed_exit(move, origin, variant):
steps.append((move, end.shifted(-ox, -oy)))
elif isinstance(variant, BendVariant) and variant.profile == profile:
for move in self.bend_moves(name, heading, variant):
assert move.displacement is not None
x, y = move.displacement
steps.append((move, Pose(x, y, (heading + variant.turn) % 360, profile)))
elif isinstance(variant, SBendVariant) and variant.profile == profile:
for move in self._sbend_specs(name, heading, variant):
if sbend := self._local_sbend(move, heading, variant):
steps.append((move, sbend.end))
elif isinstance(variant, TaperVariant):
move = Move(name)
result = self.evaluate(move, origin)
if result is not None:
steps.append((move, result.end.shifted(-ox, -oy)))
self._local_moves[key] = tuple(steps)
return self._local_moves[key]
def bend_moves(self, name: str, heading: int, variant: BendVariant) -> tuple[Move, ...]:
"""Return bounded grid-compatible lead choices in stable order."""
key = (name, heading)
if key not in self._bend_moves:
self._bend_moves[key] = self._bend_choices(name, heading, variant)
return self._bend_moves[key]
def _bend_choices(self, name: str, heading: int, variant: BendVariant) -> tuple[Move, ...]:
angle = radians(abs(variant.turn))
curve = bend_curve(variant.radius, angle, variant.minimum_radius, _euler_setting(variant))
if curve is None or curve.radius <= self.catalog.profiles[variant.profile].width / 2:
self._diagnose(Move(name), heading, "curvature_radius")
return ()
ux, uy = unit_direction(heading)
vx, vy = unit_direction((heading + variant.turn) % 360)
bare_x, bare_y = _bend_port_displacement(variant, heading)
cap = variant.max_lead
pitch = int(self.grid.pitch)
residual = 16 * ulp(max(variant.radius, cap, pitch))
det = ux * vy - uy * vx
# Enumerate the lattice points in the reachable lead box. Keep a
# bounded neighborhood of the bare port for each proposed variant.
start_x = ceil((bare_x + min(0, cap * ux) + min(0, cap * vx) - residual) / pitch)
end_x = floor((bare_x + max(0, cap * ux) + max(0, cap * vx) + residual) / pitch)
start_y = ceil((bare_y + min(0, cap * uy) + min(0, cap * vy) - residual) / pitch)
end_y = floor((bare_y + max(0, cap * uy) + max(0, cap * vy) + residual) / pitch)
def near(lo: int, hi: int, center: float) -> range:
mid = round(center / pitch)
return range(max(lo, mid - 8), min(hi, mid + 8) + 1)
moves = []
for ix in near(start_x, end_x, bare_x):
for iy in near(start_y, end_y, bare_y):
dx, dy = ix * pitch - bare_x, iy * pitch - bare_y
if abs(variant.turn) == 180:
if abs(ux * dy - uy * dx) > residual:
continue
difference = ux * dx + uy * dy
lead_pairs = ((max(0.0, difference), max(0.0, -difference)),)
if cap:
lead_pairs += ((cap + min(0.0, difference), cap - max(0.0, difference)),)
else:
lead_pairs = (((dx * vy - dy * vx) / det, (ux * dy - uy * dx) / det),)
for first, last in lead_pairs:
if not (-residual <= first <= cap + residual and -residual <= last <= cap + residual):
continue
leads = (max(0.0, min(cap, first)), max(0.0, min(cap, last)))
move = Move(name, displacement=(ix * pitch, iy * pitch), leads=leads)
if move not in moves:
moves.append(move)
if not moves:
self._diagnose(Move(name), heading, "no_grid_fit_within_lead_limit")
return tuple(sorted(moves, key=lambda item: (*item.leads, item.displacement)))
def _generated_bend(self, move: Move, start: Pose, variant: BendVariant) -> Evaluation | None:
if start.profile != variant.profile:
return None
if move.displacement is None or any(not isfinite(lead) or not 0 <= lead <= variant.max_lead for lead in move.leads):
self._diagnose(move, start.heading, "invalid_tangent_leads")
return None
key = (move, start.heading)
local = self._bend_shapes.get(key)
if local is None:
dx, dy = move.displacement
end_heading = (start.heading + variant.turn) % 360
local_start = Pose(0, 0, start.heading, start.profile)
local_end = Pose(dx, dy, end_heading, start.profile)
first, last = move.leads
ux, uy = unit_direction(start.heading)
vx, vy = unit_direction(end_heading)
bare_x, bare_y = _bend_port_displacement(variant, start.heading)
residual = 16 * ulp(max(variant.radius, variant.max_lead, self.grid.pitch))
expected_x, expected_y = bare_x + first * ux + last * vx, bare_y + first * uy + last * vy
if dx % self.grid.pitch or dy % self.grid.pitch or max(abs(expected_x - dx), abs(expected_y - dy)) > residual:
self._diagnose(move, start.heading, "off_grid_output")
return None
heading = radians(start.heading)
sign = 1 if variant.turn > 0 else -1
width = self.catalog.profiles[start.profile].width
curve = bend_curve(variant.radius, radians(abs(variant.turn)), variant.minimum_radius, _euler_setting(variant))
if curve is None or curve.radius <= width / 2:
self._diagnose(move, start.heading, "curvature_radius")
return None
sections = world_sections(curve, heading, sign)
if first:
sections = (CurveSection(first, heading), *sections)
if last:
sections = (*sections, CurveSection(last, heading + radians(variant.turn)))
polygon = curve_polygon(sections, local_start, local_end, width, variant.sagitta)
if not polygon.is_valid:
self._diagnose(move, start.heading, "invalid_footprint")
return None
lead_rate = variant.lead_cost_per_cm
if lead_rate is None:
lead_rate = min(
(
item.cost_per_cm for item in self.catalog.variants.values()
if isinstance(item, StraightVariant) and item.profile == start.profile
),
default=0.0,
)
cost = variant.cost + (first + last) * self.grid.meters_per_unit * 100 * lead_rate
local = Evaluation(
move, local_start, local_end, (polygon,), fsum(s.length for s in sections), cost,
curve_sections=sections, minimum_radius=curve.radius, euler_fraction=curve.fraction,
)
self._bend_shapes[key] = local
return Evaluation(
move, start, local.end.shifted(start.x, start.y), tuple(translate(shape, start.x, start.y) for shape in local.footprints),
local.length, local.cost, curve_sections=local.curve_sections,
minimum_radius=local.minimum_radius, euler_fraction=local.euler_fraction,
)
def _sbend_specs(self, name: str, heading: int, variant: SBendVariant) -> tuple[Move, ...]:
dx, dy = HEADING_STEPS[heading]
denominator = dx * dx + dy * dy
pitch = int(self.grid.pitch)
specs = []
for forward, lateral in variant.projections:
x, rx = divmod(dx * int(forward) - dy * int(lateral), denominator)
y, ry = divmod(dy * int(forward) + dx * int(lateral), denominator)
if rx == ry == 0:
specs.append(Move(name, displacement=(x * pitch, y * pitch)))
else:
self._diagnose(Move(name), heading, "off_grid_projections", (forward, lateral))
return tuple(specs)
def _local_sbend(self, move: Move, heading: int, variant: SBendVariant) -> Evaluation | None:
key = (move, heading)
if key not in self._sbend_shapes:
self._sbend_shapes[key] = None
if move in self._sbend_specs(move.variant, heading, variant):
assert move.displacement is not None
x, y = move.displacement
dx, dy = unit_direction(heading)
curve = sbend_curve(
x * dx + y * dy, y * dx - x * dy, variant.radius, variant.minimum_radius, _euler_setting(variant), radians(heading),
)
width = self.catalog.profiles[variant.profile].width
if curve is not None and curve.radius > width / 2:
origin, end = Pose(0, 0, heading, variant.profile), Pose(x, y, heading, variant.profile)
polygon = curve_polygon(curve.sections, origin, end, width, variant.sagitta)
if polygon.is_valid:
self._sbend_shapes[key] = Evaluation(
move, origin, end, (polygon,), fsum(section.length for section in curve.sections), variant.cost,
curve_sections=curve.sections, minimum_radius=curve.radius, euler_fraction=curve.fraction,
)
else:
self._diagnose(move, heading, "invalid_footprint")
else:
self._diagnose(move, heading, "sbend_curvature_or_span")
return self._sbend_shapes[key]
def evaluate(self, move: Move, start: Pose) -> Evaluation | None:
"""Return an evaluated placement, or None when its pose is unavailable."""
if self.grid.lattice_position(start.x, start.y) is None:
raise ValueError("Move starts off the routing lattice")
variant = self.catalog.variants[move.variant]
if isinstance(variant, FixedVariant):
end = self.fixed_exit(move, start, variant)
if end is None:
return None
local = self._fixed[move]
x, y = start.x - local.entry.x, start.y - local.entry.y
return Evaluation(
move, start, end, tuple(translate(shape, x, y) for shape in local.footprints),
variant.length, variant.cost, Placement(move.orientation, x, y),
port_shapes=tuple(translate(shape, x, y) for shape in local.port_shapes),
)
if move.traversal is not None or move.orientation != Orientation():
raise ValueError(f"Unexpected traversal or transform for generated variant {move.variant!r}")
if isinstance(variant, BendVariant):
if move.steps is not None:
raise ValueError("A bend uses a displacement and two leads")
return self._generated_bend(move, start, variant)
if isinstance(variant, SBendVariant):
if move.steps is not None or move.leads != (0.0, 0.0):
raise ValueError("An S-bend uses a displacement")
if start.profile != variant.profile:
return None
local = self._local_sbend(move, start.heading, variant)
if local is None:
return None
return Evaluation(
move, start, local.end.shifted(start.x, start.y), tuple(translate(shape, start.x, start.y) for shape in local.footprints),
local.length, local.cost, curve_sections=local.curve_sections,
minimum_radius=local.minimum_radius, euler_fraction=local.euler_fraction,
)
if move.displacement is not None or move.leads != (0.0, 0.0):
raise ValueError("Straight and taper moves cannot specify bend parameters")
dx, dy = HEADING_STEPS[start.heading]
pitch = int(self.grid.pitch)
step_length = pitch * (sqrt(2) if dx and dy else 1.0)
if isinstance(variant, StraightVariant):
if move.steps is None:
raise ValueError("A straight requires a step count")
_require_integer(move.steps)
if move.steps <= 0:
raise ValueError("A straight requires a positive step count")
if variant.profile != start.profile:
return None
steps = int(move.steps)
length = steps * step_length
cost = length * self.grid.meters_per_unit * 100 * variant.cost_per_cm
profile = variant.profile
else:
if move.steps is not None:
raise ValueError("Taper length is determined by its minimum length and heading")
if variant.input_profile != start.profile:
return None
steps = ceil(variant.minimum_length / step_length)
length = steps * step_length
if length > variant.minimum_length * (1 + variant.max_stretch):
self._diagnose(move, start.heading, "taper_stretch")
return None
cost = variant.cost
profile = variant.output_profile
end = Pose(start.x + steps * dx * pitch, start.y + steps * dy * pitch, start.heading, profile)
start_left, start_right = face_endpoints(start, self.catalog.profiles[start.profile].width)
end_left, end_right = face_endpoints(end, self.catalog.profiles[end.profile].width)
shape = Polygon((start_left, end_left, end_right, start_right))
return Evaluation(move, start, end, (shape,), length, cost)

155
inire/_catalog_timing.py Normal file
View file

@ -0,0 +1,155 @@
"""Timing evaluation of selected catalog geometry."""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass, field
from math import cos, fsum, isfinite, radians, sin, tau
from typing import TYPE_CHECKING
from scipy.integrate import quad
from inire._catalog import StraightVariant, _require_nonnegative, _require_positive
from inire._snapshot import snapshot
if TYPE_CHECKING:
from collections.abc import Mapping, Sequence
from inire._catalog import Evaluation, MoveEvaluator
from inire.geometry.catalog_curve import CurveSection
FixedDelay = float | Callable[[float], float | None] | None
class _UnavailableDelay(Exception):
"""Characterization is unavailable at this wavelength or tangent."""
@dataclass(frozen=True, slots=True)
class UniaxialGroupIndex:
parallel: float
perpendicular: float
def __post_init__(self) -> None:
_require_positive("Parallel group index", self.parallel)
_require_positive("Perpendicular group index", self.perpendicular)
def __call__(self, _wavelength: float, angle: float) -> float:
return self.parallel * cos(angle) ** 2 + self.perpendicular * sin(angle) ** 2
@dataclass(frozen=True, slots=True)
class DelayModel:
"""Optical length in layout units at a wavelength in meters.
Group-index callbacks receive (wavelength, travel angle relative to the
process axis in radians). Characterized variants receive their evaluated
placement and the wavelength. Fixed contributions can be constants,
wavelength callbacks, or None for a known missing contribution.
"""
wavelength: float
process_angle: float = 0.0
group_indices: Mapping[str, float | Callable[[float, float], float | None]] = field(default_factory=dict)
variant_delays: Mapping[str, float | Callable[[Evaluation, float], float | None]] = field(default_factory=dict)
fixed_contributions: Mapping[str, tuple[FixedDelay, ...]] = field(default_factory=dict)
bend_group_indices: Mapping[str, float | Callable[[float, float], float | None]] = field(default_factory=dict)
integration_tolerance: float = 1e-5
def __post_init__(self) -> None:
_require_positive("Timing wavelength", self.wavelength)
if not isfinite(self.process_angle):
raise ValueError("The process axis angle must be finite")
_require_positive("Delay integration tolerance", self.integration_tolerance)
for group_index in (*self.group_indices.values(), *self.bend_group_indices.values()):
if not callable(group_index):
_require_positive("Group index", group_index)
for delay in self.variant_delays.values():
if not callable(delay):
_require_nonnegative("Characterized delay", delay)
for contributions in self.fixed_contributions.values():
for contribution in contributions:
if contribution is not None and not callable(contribution):
_require_nonnegative("Fixed delay contribution", contribution)
object.__setattr__(self, "group_indices", snapshot(self.group_indices))
object.__setattr__(self, "variant_delays", snapshot(self.variant_delays))
object.__setattr__(self, "fixed_contributions", snapshot(self.fixed_contributions))
object.__setattr__(self, "bend_group_indices", snapshot(self.bend_group_indices))
@dataclass(frozen=True, slots=True)
class Delay:
optical_length: float
seconds: float
def _integrated_delay(move: Evaluation, model: DelayModel) -> float:
contributions = []
base_index = model.group_indices.get(move.start.profile)
for section in move.curve_sections:
curved = section.entry_curvature != 0 or section.exit_curvature != 0
group_index = model.bend_group_indices.get(move.move.variant, base_index) if curved else base_index
if group_index is None:
raise _UnavailableDelay
if not callable(group_index):
contributions.append(group_index * section.length)
continue
def integrand(
fraction: float,
*,
section: CurveSection = section,
group_index: Callable[[float, float], float | None] = group_index,
) -> float:
index = group_index(model.wavelength, (section.angle(fraction) - model.process_angle) % tau)
if index is None:
raise _UnavailableDelay
_require_positive("Evaluated group index", index)
return index
tolerance = model.integration_tolerance / (len(move.curve_sections) * section.length)
averaged = quad(integrand, 0, 1, epsabs=tolerance, epsrel=0)[0] if curved else integrand(0)
contributions.append(averaged * section.length)
return fsum(contributions)
def evaluate_delay(
evaluator: MoveEvaluator, path: Sequence[Evaluation], model: DelayModel, *, net_id: str,
) -> Delay | None:
"""Evaluate the placed route and its declared fixed contributions."""
contributions = []
for contribution in model.fixed_contributions.get(net_id, ()):
delay = contribution(model.wavelength) if callable(contribution) else contribution
if delay is None:
return None
_require_nonnegative("Evaluated fixed delay", delay)
contributions.append(delay)
for move in path:
spec = evaluator.catalog.variants[move.move.variant]
characterized = model.variant_delays.get(move.move.variant)
if characterized is not None:
optical_length = characterized(move, model.wavelength) if callable(characterized) else characterized
elif move.curve_sections:
try:
optical_length = _integrated_delay(move, model)
except _UnavailableDelay:
return None
elif isinstance(spec, StraightVariant):
angle = (radians(move.start.heading) - model.process_angle) % tau
group_index = model.group_indices.get(move.start.profile)
if callable(group_index):
group_index = group_index(model.wavelength, angle)
if group_index is None:
return None
_require_positive("Evaluated group index", group_index)
assert move.length is not None
optical_length = group_index * move.length
else:
return None
if optical_length is None:
return None
_require_nonnegative("Evaluated delay", optical_length)
contributions.append(optical_length)
length = fsum(contributions)
return Delay(length, length * evaluator.grid.meters_per_unit / 299_792_458)

View file

@ -0,0 +1,147 @@
"""Circular and partial Euler centerlines for evaluated catalog geometry."""
from __future__ import annotations
from dataclasses import dataclass
from functools import lru_cache
from math import acos, atan2, ceil, cos, hypot, pi, sin, sqrt, ulp
import numpy as np
from scipy.integrate import quad
from scipy.optimize import brentq
@dataclass(frozen=True, slots=True)
class CurveSection:
"""A tangent angle and a linear curvature ramp over a known arclength."""
length: float
heading: float
entry_curvature: float = 0.0
exit_curvature: float = 0.0
def angle(self, fraction: float) -> float:
return self.heading + self.length * fraction * (
self.entry_curvature + fraction * (self.exit_curvature - self.entry_curvature) / 2
)
@dataclass(frozen=True, slots=True)
class BendCurve:
radius: float
fraction: float
sections: tuple[CurveSection, ...]
def _normalized_sections(angle: float, fraction: float) -> tuple[CurveSection, ...]:
ramp = angle * fraction
plateau = angle * (1 - fraction)
candidates = (
CurveSection(ramp, 0, 0, 1),
CurveSection(plateau, ramp / 2, 1, 1),
CurveSection(ramp, angle - ramp / 2, 1, 0),
)
return tuple(section for section in candidates if section.length > 0)
def _minimum_radius(equivalent_radius: float, angle: float, fraction: float) -> float:
if fraction == 0:
return equivalent_radius
# The curve is symmetric about its mid-tangent. Its chord points in
# that direction, so a scalar integral gives the chord length.
normalized_chord = sum(
section.length * quad(lambda t, section=section: cos(section.angle(t) - angle / 2), 0, 1, epsabs=1e-12)[0]
for section in _normalized_sections(angle, fraction)
)
return 2 * equivalent_radius * sin(angle / 2) / normalized_chord
@lru_cache(maxsize=128)
def bend_curve(
equivalent_radius: float, angle: float, minimum_radius: float, fraction: float | None,
) -> BendCurve | None:
"""Scale a symmetric unit-curvature bend to the circular endpoint chord."""
if minimum_radius > equivalent_radius:
return None
if fraction is None:
if _minimum_radius(equivalent_radius, angle, 1.0) >= minimum_radius:
fraction = 1.0
elif minimum_radius == equivalent_radius:
fraction = 0.0
else:
fraction = brentq(lambda f: _minimum_radius(equivalent_radius, angle, f) - minimum_radius, 0, 1, xtol=1e-12)
radius = _minimum_radius(equivalent_radius, angle, fraction)
if radius < minimum_radius * (1 - 1e-12):
return None
return BendCurve(radius, fraction, tuple(
CurveSection(section.length * radius, section.heading, section.entry_curvature / radius, section.exit_curvature / radius)
for section in _normalized_sections(angle, fraction)
))
def world_sections(curve: BendCurve, heading: float, sign: int) -> tuple[CurveSection, ...]:
return tuple(
CurveSection(
section.length, heading + sign * section.heading, sign * section.entry_curvature, sign * section.exit_curvature,
) for section in curve.sections
)
def sbend_curve(
forward: float,
lateral: float,
radius: float,
minimum_radius: float,
fraction: float | None,
heading: float,
) -> BendCurve | None:
"""Fit two opposed lobes and an optional straight at their shared tangent."""
offset = abs(lateral)
distance = hypot(forward, 2 * radius - offset)
roundoff = 16 * ulp(max(forward, offset, radius))
if distance < 2 * radius - roundoff:
return None
angle = atan2(forward, 2 * radius - offset) - acos(min(1.0, 2 * radius / distance))
if not 0 < angle <= pi / 2:
return None
straight = (forward - 2 * radius * sin(angle)) * cos(angle) + (offset - 2 * radius * (1 - cos(angle))) * sin(angle)
if straight < -roundoff:
return None
lobe = bend_curve(radius, angle, minimum_radius, fraction)
if lobe is None:
return None
sign = 1 if lateral > 0 else -1
middle_heading = heading + sign * angle
middle = (CurveSection(straight, middle_heading),) if straight > roundoff else ()
return BendCurve(lobe.radius, lobe.fraction, (
*world_sections(lobe, heading, sign), *middle, *world_sections(lobe, middle_heading, -sign),
))
_QUADRATURE_NODES, _QUADRATURE_WEIGHTS = np.polynomial.legendre.leggauss(8)
def sample_section(
section: CurveSection, start: tuple[float, float], sagitta: float,
) -> tuple[np.ndarray, np.ndarray]:
"""Sample a curvature section and its normals using bounded angular segments."""
curvature = max(abs(section.entry_curvature), abs(section.exit_curvature))
if curvature:
angle_limit = min(pi / 12, 2 * acos(max(-1.0, 1 - curvature * sagitta)))
# The small-sagitta limit of the expression avoids cancellation at 1.
if not angle_limit:
angle_limit = sqrt(8 * curvature * sagitta)
segments = ceil(section.length * curvature / angle_limit)
else:
segments = 1
if segments > 100_000:
raise ValueError("Curve sampling requires more than 100000 segments")
ends = np.linspace(0.0, 1.0, segments + 1)
fractions = (ends[:-1, None] + (_QUADRATURE_NODES + 1) / (2 * segments))
headings = section.angle(fractions)
step = section.length / (2 * segments)
delta = step * np.column_stack((np.cos(headings) @ _QUADRATURE_WEIGHTS, np.sin(headings) @ _QUADRATURE_WEIGHTS))
positions = np.vstack((start, np.cumsum(delta, axis=0) + start))
endpoint_headings = section.angle(ends)
normals = np.column_stack((-np.sin(endpoint_headings), np.cos(endpoint_headings)))
return positions, normals

227
inire/masque.py Normal file
View file

@ -0,0 +1,227 @@
"""Route named Masque ports and place the catalog moves selected by Inire."""
from __future__ import annotations
from dataclasses import dataclass, field, replace
from math import degrees, isfinite, radians
from typing import TYPE_CHECKING, Literal
from shapely import union_all
from shapely.geometry import Polygon
from inire._catalog import (
BendVariant, Catalog, FixedVariant, Grid, Move, MoveEvaluator, Orientation, Pose, Profile, SBendVariant, StraightVariant, TaperVariant,
)
from inire._catalog_timing import DelayModel, UniaxialGroupIndex
from inire.router._catalog_guidance import AutomaticGrid, CoarseGuidance
from inire.router._catalog_layout import CatalogNet, LayoutSettings, route_layout
from inire.router._catalog_matching import MatchGroup
from inire.router._catalog_search import SearchBias
from inire.router._catalog_verify import Attachment, _matches_face
if TYPE_CHECKING:
from collections.abc import Mapping, Sequence
from masque import Pattern, Port
from shapely.geometry.base import BaseGeometry
from inire._catalog import VariantDiagnostic
from inire._catalog_timing import Delay
from inire.router._catalog_layout import LayoutAttempt
from inire.router._catalog_matching import MatchResult
from inire.router._catalog_search import SearchResult
__all__ = [
"Attachment",
"AutomaticGrid",
"BendVariant",
"Catalog",
"CoarseGuidance",
"Connection",
"DelayModel",
"Endpoint",
"FixedVariant",
"Grid",
"MatchGroup",
"Move",
"Orientation",
"PlacementResult",
"Pose",
"Profile",
"SBendVariant",
"SearchBias",
"StraightVariant",
"TaperVariant",
"UniaxialGroupIndex",
"route_and_place",
]
@dataclass(frozen=True, slots=True)
class Endpoint:
port: str
profile: str
attachment: Attachment | None = None
@dataclass(frozen=True, slots=True)
class Connection:
net_id: str
source: Endpoint
destination: Endpoint
seed: tuple[Move, ...] = ()
@dataclass(frozen=True, slots=True)
class PlacementResult:
"""Ordered route results and IDs whose terminals were consumed."""
catalog_revision: str
routes: Mapping[str, SearchResult]
placed: tuple[str, ...]
delays: Mapping[str, Delay | None] = field(default_factory=dict)
matching: Mapping[str, MatchResult] = field(default_factory=dict)
grid: Grid | None = None
attempts: tuple[LayoutAttempt, ...] = ()
unavailable_variants: tuple[VariantDiagnostic, ...] = ()
outcome: Literal["complete", "partial", "withheld"] = "complete"
def _port_pose(port: Port, profile: str, heading_tolerance: float) -> Pose:
if port.rotation is None or not isfinite(port.rotation) or not all(isfinite(value) for value in port.offset):
raise ValueError("Masque routing ports require a finite position and orientation")
angle = degrees(port.rotation)
heading = round(angle / 45) * 45
if abs(angle - heading) > heading_tolerance:
raise ValueError(f"Masque routing port heading {angle}° is outside the supported headings")
return Pose(round(port.x), round(port.y), heading % 360, profile)
def _resolve_connections(
layout: Pattern, connections: Sequence[Connection], catalog: Catalog, heading_tolerance: float,
) -> dict[str, CatalogNet]:
resolved = {}
terminals = set()
for connection in connections:
if not connection.net_id or connection.net_id in resolved:
raise ValueError(f"Duplicate or empty routing net ID {connection.net_id!r}")
poses = []
for endpoint in (connection.source, connection.destination):
if endpoint.port in terminals:
raise ValueError(f"Duplicate routing terminal {endpoint.port!r}")
if endpoint.port not in layout.ports or endpoint.profile not in catalog.profiles:
raise ValueError(f"Unknown Masque routing port or profile for {endpoint!r}")
pose = _port_pose(layout.ports[endpoint.port], endpoint.profile, heading_tolerance)
poses.append(pose)
terminals.add(endpoint.port)
resolved[connection.net_id] = CatalogNet(
poses[0].reversed(), poses[1], connection.source.attachment, connection.destination.attachment, connection.seed,
)
return resolved
def _resolve_cells(
cells: Mapping[str, Pattern],
catalog: Catalog,
layer: int | tuple[int, int] | str,
heading_tolerance: float,
face_tolerance: float,
) -> Catalog:
actual = {}
variants = dict(catalog.variants)
for variant, spec in catalog.variants.items():
if not isinstance(spec, FixedVariant):
continue
if spec.cell not in cells:
raise ValueError(f"Missing Masque routing cell {spec.cell!r}")
cell = cells[spec.cell]
if spec.cell not in actual:
actual[spec.cell] = tuple(Polygon(shape.vertices + shape.offset) for shape in cell.layer_as_polygons(layer, library=cells))
shapes = actual[spec.cell]
if not shapes or not union_all(spec.footprints).covers(union_all(shapes)):
raise ValueError(f"Masque cell {spec.cell!r} has missing geometry or material outside its footprint on this layer")
for name, pose in spec.ports.items():
port = cell.ports.get(name)
if port is None or _port_pose(port, pose.profile, heading_tolerance) != pose:
raise ValueError(f"Masque cell {spec.cell!r} has an incompatible routing port {name!r}")
if not _matches_face(shapes, pose, catalog.profiles[pose.profile].width, face_tolerance, arrival=False):
raise ValueError(f"Masque cell {spec.cell!r} has an incompatible physical face at {name!r}")
variants[variant] = replace(spec, port_shapes=shapes)
return replace(catalog, variants=variants)
def route_and_place(
layout: Pattern,
cells: Mapping[str, Pattern],
connections: Sequence[Connection],
*,
catalog: Catalog,
grid: Grid | AutomaticGrid,
board: Polygon,
layer: int | tuple[int, int] | str,
keepouts: Sequence[BaseGeometry] = (),
clearance: float = 0.0,
self_clearance: float = 0.0,
face_tolerance: float = 0.0,
heading_tolerance: float = 1e-6,
node_limit: int = 1000,
require_complete: bool = False,
timing: DelayModel | None = None,
match_groups: Sequence[MatchGroup] = (),
tuning_windows: Mapping[str, Polygon] | None = None,
tuning_proposal_limit: int = 2000,
refinement: bool = True,
guidance: CoarseGuidance | None = None,
refinement_node_limit: int = 64,
retry_independent: bool = True,
search_bias: SearchBias | None = None,
) -> PlacementResult:
"""Route in the Pattern's layout units and consume both named ports for each placed net."""
if not isfinite(heading_tolerance) or not 0 <= heading_tolerance < 22.5:
raise ValueError("Heading tolerance must be finite and in [0°, 22.5°)")
catalog = _resolve_cells(cells, catalog, layer, heading_tolerance, face_tolerance)
resolved = _resolve_connections(layout, connections, catalog, heading_tolerance)
if isinstance(grid, AutomaticGrid):
grid = grid.select(tuple(pose for net in resolved.values() for pose in (net.start, net.target)), catalog)
evaluator = MoveEvaluator(grid, catalog)
result = route_layout(
evaluator, resolved,
LayoutSettings(
board, keepouts, clearance, self_clearance, face_tolerance, node_limit,
tuning_proposal_limit, refinement, guidance, refinement_node_limit, retry_independent, search_bias,
),
timing=timing, groups=match_groups, windows=tuning_windows, require_complete=require_complete,
)
if require_complete and len(result.completed) != len(connections):
return PlacementResult(
catalog.revision, result.routes, (), result.delays, result.matching, grid, result.attempts, evaluator.unavailable, "withheld",
)
completed = set(result.completed)
placed = []
for connection in connections:
if connection.net_id not in completed:
continue
path = result.routes[connection.net_id].path
assert path is not None
for move in path:
if move.placement is None:
for shape in move.footprints:
layout.polygon(layer, vertices=shape.exterior.coords[:-1])
else:
spec = catalog.variants[move.move.variant]
assert isinstance(spec, FixedVariant)
placement = move.placement
layout.ref(
spec.cell, offset=(placement.x, placement.y), rotation=radians(placement.orientation.rotation),
mirrored=placement.orientation.reflected,
)
del layout.ports[connection.source.port]
del layout.ports[connection.destination.port]
placed.append(connection.net_id)
return PlacementResult(
catalog.revision, result.routes, tuple(placed), result.delays, result.matching, grid, result.attempts, evaluator.unavailable,
"complete" if len(placed) == len(connections) else "partial",
)

View file

@ -3,11 +3,9 @@ from __future__ import annotations
import heapq
from typing import TYPE_CHECKING
from shapely.geometry import Polygon
from inire.constants import TOLERANCE_LINEAR
from inire.geometry.component_overlap import components_overlap
from inire.geometry.components import build_component, check_component_endpoint, uses_custom_outline
from inire.geometry.components import check_component_endpoint, uses_custom_outline
from inire.geometry.primitives import Port
from inire.router.refiner import component_hits_ancestor_chain
@ -33,11 +31,7 @@ def process_move(
params: tuple,
) -> None:
cp = parent.port
coll_type = config.bend_collision_type
coll_key = id(coll_type) if isinstance(coll_type, Polygon) else coll_type
physical_type = config.bend_physical_geometry
physical_key = id(physical_type) if isinstance(physical_type, Polygon) else physical_type
search = context.options.search
evaluator = config.evaluator
template = None
if move_class == "sbend" and config.sbend_templates:
template = config.sbend_templates.get(params)
@ -46,32 +40,17 @@ def process_move(
outline = template.polygon if template else None
self_dilation = context.cost_evaluator.collision_engine.clearance / 2.0
abs_key = (
cp.as_tuple(),
move_class,
params,
net_width,
coll_key,
physical_key,
id(outline) if outline is not None else None,
self_dilation,
local_settings = (
move_class, params, net_width, *evaluator.cache_settings(),
id(outline) if outline is not None else None, template.length if template is not None else None, self_dilation,
)
abs_key = (cp.as_tuple(), *local_settings)
if abs_key in context.move_cache_abs:
context.metrics.total_move_cache_abs_hits += 1
res = context.move_cache_abs[abs_key]
else:
context.metrics.total_move_cache_abs_misses += 1
base_port = Port(0, 0, cp.r)
rel_key = (
cp.r,
move_class,
params,
net_width,
coll_key,
physical_key,
id(outline) if outline is not None else None,
self_dilation,
)
rel_key = (cp.r, *local_settings)
if rel_key in context.move_cache_rel:
context.metrics.total_move_cache_rel_hits += 1
res_rel = context.move_cache_rel[rel_key]
@ -80,20 +59,9 @@ def process_move(
try:
board = context.cost_evaluator.collision_engine.board
# Reject generated bends that overshoot before tessellating them.
if board is not None and move_class != "straight" and not uses_custom_outline(move_class, physical_type, outline):
if board is not None and move_class != "straight" and not uses_custom_outline(move_class, evaluator.physical_geometry, outline):
check_component_endpoint(cp, move_class, params, board.bounds)
res_rel = build_component(
base_port,
net_width,
move_class,
params,
collision_type=coll_type,
physical_geometry_type=physical_type,
clip_margin=config.bend_clip_margin,
dilation=self_dilation,
sbend_outline=outline,
physical_length=search.bend_physical_length if move_class == "bend90" else (template.length if template else None),
)
res_rel = evaluator.evaluate(Port(0, 0, cp.r), net_width, move_class, params, self_dilation, template)
except ValueError:
return
context.cache_move(rel_key, res_rel, relative=True)

View file

@ -308,7 +308,7 @@ def expand_moves(
angle_to_target = float((round((180.0 / math.pi) * math.atan2(dy_t, dx_t)) + 360.0) % 360.0)
prefer_toward_target = deferred_turns is not None and not config.restrict_to_corridor and dist_sq >= 150 * 150
circular_bend = bend90_uses_circular_geometry(config.bend_collision_type, config.bend_physical_geometry)
circular_bend = bend90_uses_circular_geometry(config.evaluator.collision_type, config.evaluator.physical_geometry)
for radius in search_options.bend_radii:
if circular_bend and not bend_fits_width(radius, net_width):
continue

View file

@ -5,14 +5,15 @@ from dataclasses import dataclass, field
from operator import attrgetter
from typing import TYPE_CHECKING, get_type_hints
from inire.model import resolve_bend_geometry
from inire.results import RouteMetrics
from inire.router.visibility import VisibilityManager
from ._move_evaluation import LegacyMoveEvaluator
if TYPE_CHECKING:
from collections.abc import Callable
from inire.geometry.components import BendCollisionModel, BendPhysicalGeometry, ComponentResult
from inire.geometry.components import BendCollisionModel, ComponentResult
from inire.geometry.primitives import Port
from inire.model import RoutingOptions, RoutingProblem, SBendOutline
from inire.router._topology import Corridor
@ -81,9 +82,7 @@ class CongestionCaches:
@dataclass(frozen=True, slots=True)
class SearchRunConfig:
bend_collision_type: BendCollisionModel
bend_physical_geometry: BendPhysicalGeometry
bend_clip_margin: float | None
evaluator: LegacyMoveEvaluator
node_limit: int
guidance_seed: tuple[PathSegmentSeed, ...] | None = None
guidance_bonus: float = 0.0
@ -133,14 +132,8 @@ class SearchRunConfig:
expired: Callable[[], bool] | None = None,
) -> SearchRunConfig:
search = options.search
bend_collision_type, bend_physical_geometry = resolve_bend_geometry(
search,
bend_collision_override=bend_collision_type,
)
return cls(
bend_collision_type=bend_collision_type,
bend_physical_geometry=bend_physical_geometry,
bend_clip_margin=search.bend_clip_margin,
evaluator=LegacyMoveEvaluator.from_options(search, collision_override=bend_collision_type),
node_limit=search.node_limit if node_limit is None else node_limit,
guidance_seed=guidance_seed,
guidance_bonus=float(guidance_bonus),

View file

@ -0,0 +1,142 @@
"""Sparse coarse corridors and exact grid selection for catalog routing."""
from __future__ import annotations
from dataclasses import dataclass
from heapq import heappop, heappush
from itertools import count
from math import gcd, hypot, inf
from typing import TYPE_CHECKING
from shapely.geometry import LineString, Point, box
from shapely.strtree import STRtree
from inire._catalog import HEADING_STEPS, FixedVariant, Grid, _require_integer, _require_positive
from inire.geometry.collision import _violates_clearance
if TYPE_CHECKING:
from collections.abc import Sequence
from shapely.geometry.base import BaseGeometry
from inire._catalog import Catalog, Pose
@dataclass(frozen=True, slots=True)
class AutomaticGrid:
"""Select a compatible divisor of a preferred routing pitch in layout units."""
preferred_pitch: int
meters_per_unit: float
def __post_init__(self) -> None:
_require_integer(self.preferred_pitch)
_require_positive("Preferred grid pitch", self.preferred_pitch)
_require_positive("Layout unit in meters", self.meters_per_unit)
def select(self, terminals: Sequence[Pose], catalog: Catalog) -> Grid:
origin = (terminals[0].x, terminals[0].y) if terminals else (0, 0)
pitch = int(self.preferred_pitch)
for pose in terminals:
pitch = gcd(pitch, pose.x - origin[0], pose.y - origin[1])
for variant in catalog.variants.values():
if isinstance(variant, FixedVariant):
a, b = variant.ports.values()
# Accepted fixed orientations swap or negate the axis differences.
pitch = gcd(pitch, a.x - b.x, a.y - b.y)
return Grid(origin, pitch, self.meters_per_unit)
@dataclass(frozen=True, slots=True)
class CoarseGuidance:
"""Coarse corridor search budget, independent of the realization pitch."""
pitch: int
node_limit: int = 4000
def __post_init__(self) -> None:
_require_integer(self.pitch)
_require_integer(self.node_limit)
_require_positive("Coarse guidance pitch", self.pitch)
if self.node_limit < 0:
raise ValueError("Coarse guidance node limit must be nonnegative")
@dataclass(frozen=True, slots=True)
class Corridor:
points: tuple[tuple[int, int], ...]
region: BaseGeometry
def admits(self, pose: Pose) -> bool:
return self.region.covers(Point(pose.x, pose.y))
def find_corridor(
start: Pose, target: Pose, settings: CoarseGuidance, *,
board: BaseGeometry, obstacles: Sequence[BaseGeometry], margin: float,
) -> tuple[Corridor | None, int]:
"""Guide on a coarse positional graph, with exact terminals as its endpoints."""
if not settings.node_limit:
return None, 0
pitch = int(settings.pitch)
start_xy, target_xy = (start.x, start.y), (target.x, target.y)
blockers = STRtree(obstacles)
def visible(a: tuple[int, int], b: tuple[int, int]) -> bool:
segment = LineString((a, b)) if a != b else Point(a)
if not board.covers(segment):
return False
x0, y0, x1, y1 = segment.bounds
nearby = blockers.query(box(x0 - margin, y0 - margin, x1 + margin, y1 + margin))
return not any(_violates_clearance(segment, blockers.geometries[index], margin) for index in nearby)
def corridor(points: Sequence[tuple[int, int]]) -> Corridor:
line = LineString(points) if len(set(points)) > 1 else Point(points[0])
return Corridor(tuple(points), line.buffer(2 * pitch + margin))
if visible(start_xy, target_xy):
return corridor((start_xy, target_xy)), 0
directions = tuple(HEADING_STEPS.values())
snapped = ((start.x + pitch // 2) // pitch) * pitch, ((start.y + pitch // 2) // pitch) * pitch
# Link the exact source to its surrounding coarse positions. The target's
# final connection is another visibility edge in this positional graph.
origins = [snapped, *((snapped[0] + dx * pitch, snapped[1] + dy * pitch) for dx, dy in directions)]
order = count()
queue = []
distances = {}
parents: dict[tuple[int, int], tuple[int, int] | None] = {}
for xy in origins:
if visible(start_xy, xy):
cost = hypot(xy[0] - start.x, xy[1] - start.y)
distances[xy], parents[xy] = cost, None
heappush(queue, (cost + hypot(xy[0] - target.x, xy[1] - target.y), next(order), cost, xy))
expanded = 0
while queue and expanded < settings.node_limit:
_, _, cost, current = heappop(queue)
if cost != distances[current]:
continue
expanded += 1
if visible(current, target_xy):
reverse = [target_xy]
ancestor = current
while ancestor is not None:
reverse.append(ancestor)
ancestor = parents[ancestor]
route = [start_xy, *reversed(reverse)]
simplified = [route[0]]
index = 0
while index < len(route) - 1:
following = next(i for i in range(len(route) - 1, index, -1) if visible(route[index], route[i]))
if route[following] != simplified[-1]:
simplified.append(route[following])
index = following
return corridor(simplified), expanded
for dx, dy in directions:
peer = current[0] + dx * pitch, current[1] + dy * pitch
estimate = cost + pitch * hypot(dx, dy)
if estimate < distances.get(peer, inf) and visible(current, peer):
distances[peer], parents[peer] = estimate, current
heappush(queue, (estimate + hypot(peer[0] - target.x, peer[1] - target.y), next(order), estimate, peer))
return None, expanded

View file

@ -0,0 +1,562 @@
"""Catalog layout search, tuning, and final placement verification."""
from __future__ import annotations
from dataclasses import dataclass, field, replace
from itertools import combinations
from math import fsum, inf, isfinite
from time import perf_counter
from typing import TYPE_CHECKING
from shapely.geometry import LineString, Polygon, box
from inire._catalog import HEADING_STEPS, MoveEvaluator, _require_integer
from inire._catalog_timing import evaluate_delay
from inire._snapshot import snapshot
from inire.geometry.collision import _violates_net_clearance
from ._catalog_guidance import Corridor, find_corridor
from ._catalog_matching import DelayChoice, choose_match
from ._catalog_search import COST_TOLERANCE, SearchResult, path_recipe, search_path
from ._catalog_tuning import tune_group
from ._catalog_verify import face_reservation, replay_moves, validate_attachment, verify_path
if TYPE_CHECKING:
from collections.abc import Mapping, Sequence
from shapely.geometry.base import BaseGeometry
from inire._catalog import Evaluation, Move, Pose
from inire._catalog_timing import Delay, DelayModel
from ._catalog_guidance import CoarseGuidance
from ._catalog_matching import MatchGroup, MatchResult
from ._catalog_search import SearchBias
from ._catalog_verify import Attachment
@dataclass(frozen=True, slots=True)
class CatalogNet:
start: Pose
target: Pose
source_attachment: Attachment | None = None
destination_attachment: Attachment | None = None
seed: tuple[Move, ...] = ()
@dataclass(frozen=True, slots=True)
class LayoutSettings:
board: Polygon
keepouts: Sequence[BaseGeometry] = ()
clearance: float = 0.0
self_clearance: float = 0.0
face_tolerance: float = 0.0
node_limit: int = 1000
tuning_proposal_limit: int = 2000
refinement: bool = True
guidance: CoarseGuidance | None = None
refinement_node_limit: int = 64
retry_independent: bool = True
search_bias: SearchBias | None = None
def __post_init__(self) -> None:
if not isinstance(self.board, Polygon) or self.board.is_empty or not self.board.is_valid:
raise ValueError("Routing board must be a valid nonempty polygon")
if any(shape.is_empty or not shape.is_valid for shape in self.keepouts):
raise ValueError("Keepouts must be valid nonempty geometries")
if any(not isfinite(value) or value < 0 for value in (self.clearance, self.self_clearance, self.face_tolerance)):
raise ValueError("Clearance and face tolerance must be finite and nonnegative")
for limit in (self.node_limit, self.tuning_proposal_limit, self.refinement_node_limit):
_require_integer(limit)
if min(self.node_limit, self.tuning_proposal_limit, self.refinement_node_limit) < 0:
raise ValueError("Routing and tuning limits must be nonnegative")
@dataclass(frozen=True, slots=True)
class LayoutAttempt:
order: tuple[str, ...]
covered_at: float | None
cost_at_coverage: float | None
elapsed: float
completed: tuple[str, ...]
expanded: int
proposed: int
coarse_expanded: int
geometry_checks: int
geometry_cache_hits: int
geometry_cache_entries: int
pair_repairs: int
tuning_seconds: float
independent_retry_seconds: float
independent_retries: int
@dataclass(frozen=True, slots=True)
class LayoutResult:
routes: Mapping[str, SearchResult]
completed: tuple[str, ...]
delays: Mapping[str, Delay | None] = field(default_factory=dict)
matching: Mapping[str, MatchResult] = field(default_factory=dict)
attempts: tuple[LayoutAttempt, ...] = ()
class _LayoutSearch:
def __init__(
self, evaluator: MoveEvaluator, nets: Mapping[str, CatalogNet], settings: LayoutSettings, windows: Mapping[str, Polygon],
) -> None:
self.evaluator = evaluator
self.nets = nets
self.settings = settings
self.windows = dict(windows)
self.routes: dict[str, SearchResult] = {}
self.installed: dict[str, tuple[BaseGeometry, ...]] = {}
self.installed_paths: dict[str, tuple[Evaluation, ...]] = {}
self.pair_repairs = 0
self._coverage_evaluators: dict[tuple[str, bool], MoveEvaluator] = {}
def _geometry_settings(self, name: str) -> dict:
net = self.nets[name]
settings = self.settings
return {
"board": settings.board,
"keepouts": (*settings.keepouts, *(shape for owner, shape in self.windows.items() if owner != name)),
"occupied": tuple(shape for owner, shapes in self.installed.items() if owner != name for shape in shapes),
"clearance": settings.clearance,
"self_clearance": settings.self_clearance,
"face_tolerance": settings.face_tolerance,
"source_attachment": net.source_attachment,
"destination_attachment": net.destination_attachment,
}
def _install(self, name: str, path: tuple[Evaluation, ...]) -> None:
net = self.nets[name]
profiles = self.evaluator.catalog.profiles
poses = [move.end for move in path[:-1]]
if net.source_attachment is not None:
poses.append(net.start)
if net.destination_attachment is not None:
poses.append(net.target)
self.installed_paths[name] = path
self.installed[name] = (
*(shape for move in path for shape in move.footprints),
*(face_reservation(pose, profiles[pose.profile].width, self.settings.face_tolerance) for pose in poses),
)
def verify(self, name: str, path: tuple[Evaluation, ...]) -> bool:
net = self.nets[name]
return verify_path(self.evaluator, path, net.start, net.target, **self._geometry_settings(name)) is None
def _search(self, name: str) -> SearchResult:
net = self.nets[name]
settings = {**self._geometry_settings(name), "bias": self.settings.search_bias}
node_limit = self.settings.node_limit
guidance = self.settings.guidance
coarse_expanded = 0
guided = None
guide_attempted = guidance is not None and node_limit > 1
if guide_attempted:
assert guidance is not None
attached = (net.source_attachment, net.destination_attachment)
obstacles = tuple(
shape for shape in (*settings["keepouts"], *settings["occupied"])
if all(attachment is None or shape is not attachment.obstacle for attachment in attached)
)
margin = self.settings.clearance + min(self.evaluator.catalog.profiles[pose.profile].width for pose in (net.start, net.target)) / 2
corridor, coarse_expanded = find_corridor(
net.start, net.target, guidance, board=self.settings.board, obstacles=obstacles, margin=margin,
)
if corridor is not None:
guided = search_path(
self.evaluator, net.start, net.target, node_limit=max(1, node_limit // 3), corridor=corridor, **settings,
)
if guided.path is not None:
return replace(guided, coarse_expanded=coarse_expanded, used_guidance=True)
node_limit -= guided.expanded
coverage = self._coverage_evaluator(net)
reserve = node_limit * 2 // 5 if coverage is not self.evaluator else node_limit // 4
explicit = search_path(self.evaluator, net.start, net.target, node_limit=node_limit - reserve, **settings)
remaining = node_limit - explicit.expanded
if explicit.path is None and remaining > 0 and coverage is not self.evaluator:
fallback = search_path(coverage, net.start, net.target, node_limit=remaining, **settings)
remaining -= fallback.expanded
explicit = replace(fallback.including_work(explicit), profile_fallback=True)
if explicit.path is None and remaining > 0:
scanned = search_path(self.evaluator, net.start, net.target, node_limit=remaining, scan_steps=True, **settings)
explicit = replace(scanned.including_work(explicit), profile_fallback=explicit.profile_fallback)
if guided is not None:
explicit = explicit.including_work(guided)
return replace(explicit, coarse_expanded=coarse_expanded, guide_fallback=guide_attempted)
def _coverage_evaluator(self, net: CatalogNet) -> MoveEvaluator:
if net.start.profile != net.target.profile:
return self.evaluator
key = net.start.profile, net.start.heading % 90 == net.target.heading % 90 == 0
if key not in self._coverage_evaluators:
restricted = self.evaluator.coverage_catalog(key[0], cardinal=key[1])
self._coverage_evaluators[key] = (
MoveEvaluator(self.evaluator.grid, restricted) if restricted.variants.keys() < self.evaluator.catalog.variants.keys()
else self.evaluator
)
return self._coverage_evaluators[key]
def search(self, name: str) -> None:
net = self.nets[name]
seed = replay_moves(self.evaluator, net.start, net.seed) if net.seed else None
incumbent = seed if seed is not None and self.verify(name, seed) else None
if incumbent is not None:
result = SearchResult(incumbent, "verified", 0, 0)
else:
result = self._search(name) if self.settings.node_limit else SearchResult(None, "node_limit", 0, 0)
if name in self.routes:
result = result.including_work(self.routes[name])
self.routes[name] = result
if result.path is not None:
self._install(name, result.path)
def repair(self, name: str, group_members: Mapping[str, str]) -> None:
"""Try to add one independent route and move at most one verified peer."""
limit = min(self.settings.node_limit // 2, self.settings.refinement_node_limit)
if not limit or not self.installed:
return
net = self.nets[name]
settings = {**self._geometry_settings(name), "occupied": ()}
candidate = search_path(self.evaluator, net.start, net.target, node_limit=limit, **settings)
self.routes[name] = self.routes[name].including_work(candidate)
if candidate.path is None:
return
bounds = self.evaluator.catalog.profiles
pieces = [shape for move in candidate.path for shape in move.footprints]
pieces.extend(
face_reservation(move.end, bounds[move.end.profile].width, self.settings.face_tolerance) for move in candidate.path[:-1]
)
blockers = [
peer for peer, shapes in self.installed.items()
if any(_violates_net_clearance(shape, occupied, self.settings.clearance) for shape in pieces for occupied in shapes)
]
if not blockers:
if self._verify_replacements({name: candidate.path}):
self.routes[name] = replace(self.routes[name], path=candidate.path, outcome="verified")
self._install(name, candidate.path)
return
if len(blockers) != 1 or blockers[0] in group_members:
return
[peer] = blockers
old_shapes = self.installed.pop(peer)
old_path = self.installed_paths.pop(peer)
self._install(name, candidate.path)
try:
displaced = self.nets[peer]
trial = search_path(self.evaluator, displaced.start, displaced.target, node_limit=limit, **self._geometry_settings(peer))
self.routes[peer] = self.routes[peer].including_work(trial)
if trial.path is None or not self._verify_replacements({name: candidate.path, peer: trial.path}):
return
finally:
self.installed.pop(name)
self.installed_paths.pop(name)
self.installed[peer], self.installed_paths[peer] = old_shapes, old_path
self.routes[name] = replace(self.routes[name], path=candidate.path, outcome="verified")
self.routes[peer] = replace(self.routes[peer], path=trial.path, outcome="verified")
self._install(name, candidate.path)
self._install(peer, trial.path)
self.pair_repairs += 1
def refine(self, name: str, group: MatchGroup | None, report: MatchResult | None, timing: DelayModel | None) -> MatchResult | None:
result = self.routes[name]
path = result.path
assert path is not None
budget = min(self.settings.refinement_node_limit, self.settings.node_limit)
dx, dy = HEADING_STEPS[path[0].start.heading]
collinear = all(
move.start.heading == move.end.heading == path[0].start.heading
and dx * (move.end.y - move.start.y) == dy * (move.end.x - move.start.x)
for move in path
)
# The initial catalog search already priced unobstructed collinear
# sequences. Revisit those only if a seed, timing, or a retry shaped the result.
if not budget or (collinear and not self.nets[name].seed and group is None and not result.profile_fallback and not result.used_guidance):
return report
# Try the most expensive pieces first. Include their nearest neighbors
# so a replacement can move a transition or shorten a corner setback.
windows = sorted(
{(max(0, i - 1), min(len(path), i + 2)) for i in range(len(path))},
key=lambda pair: (-fsum(move.cost for move in path[pair[0]:pair[1]]), *pair),
)
for begin, end in windows[:3]:
original = path[begin:end]
cost = fsum(move.cost for move in original)
if cost <= COST_TOLERANCE:
continue
start, target = original[0].start, original[-1].end
shapes = [shape.bounds for move in original for shape in move.footprints]
left, bottom = min(shape[0] for shape in shapes), min(shape[1] for shape in shapes)
right, top = max(shape[2] for shape in shapes), max(shape[3] for shape in shapes)
margin = max(
2 * self.evaluator.grid.pitch,
self.evaluator.catalog.profiles[start.profile].width,
self.evaluator.catalog.profiles[target.profile].width,
)
corridor = Corridor(((start.x, start.y), (target.x, target.y)), box(left - margin, bottom - margin, right + margin, top + margin))
settings = self._geometry_settings(name)
if begin:
settings["source_attachment"] = None
if end != len(path):
settings["destination_attachment"] = None
trial = search_path(
self.evaluator, start, target, node_limit=budget, max_cost=cost - 2 * COST_TOLERANCE, corridor=corridor, **settings,
)
budget -= trial.expanded
result = result.including_work(trial)
self.routes[name] = result
if trial.path is not None and fsum(move.cost for move in trial.path) < cost - COST_TOLERANCE:
proposed = (*path[:begin], *trial.path, *path[end:])
if self.verify(name, proposed):
updated = self._refined_match(name, proposed, group, report, timing)
if group is None or updated is not None:
self.routes[name] = replace(result, path=proposed)
self._install(name, proposed)
return updated
if not budget:
break
return report
def _refined_match(
self, name: str, path: tuple[Evaluation, ...], group: MatchGroup | None, report: MatchResult | None, timing: DelayModel | None,
) -> MatchResult | None:
if group is None or report is None or timing is None:
return report
delay = evaluate_delay(self.evaluator, path, replace(timing, wavelength=group.wavelength), net_id=name)
if delay is None:
return None
delays = {**report.delays, name: delay}
_, skew, fits = choose_match(group, {member: (DelayChoice((), value),) for member, value in delays.items()})
return replace(report, delays=snapshot(delays), skew=skew) if fits else None
def _verify_replacements(self, replacements: Mapping[str, tuple[Evaluation, ...]]) -> bool:
if not replacements:
return True
incumbent = self.installed.copy()
paths = self.installed_paths.copy()
try:
for name, path in replacements.items():
self._install(name, path)
return all(self.verify(name, path) for name, path in self.installed_paths.items())
finally:
self.installed = incumbent
self.installed_paths = paths
def tune(
self, group: MatchGroup, timing: DelayModel,
) -> MatchResult:
baselines = {name: self.routes[name].path for name in group.offsets}
alternative_limit = self.settings.node_limit // 2
total_proposals = self.settings.tuning_proposal_limit
initial_proposals = total_proposals - total_proposals // 3 if alternative_limit else total_proposals
report, replacements = tune_group(
self.evaluator, group, timing, baselines, self.windows, self.verify,
proposal_limit=initial_proposals,
)
proposed = report.proposed_replacements
verified = report.verified_replacements
eligible = report.eligible_spans
exhausted = report.budget_exhausted
found = report.tuning_space_found
if not self._verify_replacements(replacements):
report, _ = tune_group(self.evaluator, group, timing, baselines, {}, self.verify, proposal_limit=0)
replacements = {}
# Use a separate bounded search when the baseline geometry cannot
# match. Holding the other routes fixed preserves their verified spans.
if not report.complete and alternative_limit:
def rank(candidate: MatchResult, changed: Mapping[str, tuple[Evaluation, ...]]) -> tuple[bool, float, float]:
return (
not candidate.complete, 0.0 if candidate.complete else (candidate.skew if candidate.skew is not None else inf),
fsum(move.cost for name, base in baselines.items() for move in changed.get(name, base or ())),
)
best = rank(report, replacements)
for index, (name, baseline) in enumerate(baselines.items()):
net = self.nets[name]
excluded = () if baseline is None else (path_recipe(baseline),)
trial = search_path(
self.evaluator, net.start, net.target, node_limit=alternative_limit,
excluded_paths=excluded, **self._geometry_settings(name),
)
original = self.routes[name]
self.routes[name] = original.including_work(trial)
if trial.path is None:
continue
searched = dict(baselines)
searched[name] = trial.path
candidate, adjusted = tune_group(
self.evaluator, group, timing, searched, self.windows, self.verify,
proposal_limit=(total_proposals - proposed) // (len(baselines) - index),
)
proposed += candidate.proposed_replacements
verified += candidate.verified_replacements
eligible += candidate.eligible_spans
exhausted |= candidate.budget_exhausted
found |= candidate.tuning_space_found
adjusted.setdefault(name, trial.path)
if (score := rank(candidate, adjusted)) < best and self._verify_replacements(adjusted):
best, report, replacements = score, candidate, adjusted
for name, path in replacements.items():
self.routes[name] = replace(self.routes[name], path=path, outcome="verified")
if report.complete:
self._install(name, path)
return replace(
report, proposed_replacements=proposed, verified_replacements=verified, eligible_spans=eligible,
budget_exhausted=exhausted, tuning_space_found=found,
)
def _match_members(
nets: Mapping[str, CatalogNet], groups: Sequence[MatchGroup], windows: Mapping[str, Polygon],
) -> dict[str, str]:
members = {}
group_ids = set()
for group in groups:
if group.group_id in group_ids:
raise ValueError(f"Duplicate match group ID {group.group_id!r}")
group_ids.add(group.group_id)
for name in group.offsets:
if name not in nets or name in members:
raise ValueError(f"Match member {name!r} is unknown or belongs to multiple groups")
members[name] = group.group_id
for owner, window in windows.items():
if owner in members and (window.is_empty or not window.is_valid or window.area <= 0):
raise ValueError(f"Invalid tuning window for {owner!r}")
active = [(name, window) for name, window in windows.items() if name in members]
for (left, a), (right, b) in combinations(active, 2):
if a.relate_pattern(b, "2********"):
raise ValueError(f"Tuning windows intersect for {left!r} and {right!r}")
return members
def route_layout(
evaluator: MoveEvaluator,
nets: Mapping[str, CatalogNet],
settings: LayoutSettings,
*,
timing: DelayModel | None = None,
groups: Sequence[MatchGroup] = (),
windows: Mapping[str, Polygon] | None = None,
require_complete: bool = False,
) -> LayoutResult:
if groups and timing is None:
raise ValueError("Active match groups require a timing model")
windows = {} if windows is None else windows
members = _match_members(nets, groups, windows)
active_windows = {name: window for name, window in windows.items() if name in members}
for name, net in nets.items():
for pose in (net.start, net.target):
if pose.profile not in evaluator.catalog.profiles or evaluator.grid.lattice_position(pose.x, pose.y) is None:
raise ValueError(f"Net {name!r} has an invalid terminal {pose!r}")
for attachment, pose, source in ((net.source_attachment, net.start, True), (net.destination_attachment, net.target, False)):
if attachment is not None:
validate_attachment(evaluator, attachment, pose, settings.keepouts, settings.face_tolerance, source=source)
order = tuple(nets)
first = _route_attempt(evaluator, nets, settings, timing, groups, members, active_windows, order, require_complete)
if settings.refinement and len(order) > 1 and (
len(first.completed) < len(order) or _routes_compete(first, nets, evaluator, settings.clearance)
):
second = _route_attempt(evaluator, nets, settings, timing, groups, members, active_windows, tuple(reversed(order)), require_complete)
best = second if _layout_rank(second) < _layout_rank(first) else first
return replace(best, attempts=(*first.attempts, *second.attempts))
return first
def _routes_compete(
result: LayoutResult, nets: Mapping[str, CatalogNet], evaluator: MoveEvaluator, clearance: float,
) -> bool:
"""Only reorder a full layout when a peer may be forcing a detour."""
placements = {name: tuple(shape for move in (result.routes[name].path or ()) for shape in move.footprints) for name in result.completed}
for name in result.completed:
route = result.routes[name].path
if route is None or len(route) < 2:
continue
net = nets[name]
margin = clearance + max(evaluator.catalog.profiles[net.start.profile].width, evaluator.catalog.profiles[net.target.profile].width) / 2
direct = LineString(((net.start.x, net.start.y), (net.target.x, net.target.y)))
for peer, shapes in placements.items():
if peer != name and any(direct.distance(shape) < margin for shape in shapes):
return True
return False
def _layout_rank(result: LayoutResult) -> tuple[int, int, float]:
return (
-len(result.completed),
-sum(report.complete for report in result.matching.values()),
fsum(move.cost for name in result.completed for move in (result.routes[name].path or ())),
)
def _route_attempt(
evaluator: MoveEvaluator,
nets: Mapping[str, CatalogNet],
settings: LayoutSettings,
timing: DelayModel | None,
groups: Sequence[MatchGroup],
members: Mapping[str, str],
windows: Mapping[str, Polygon],
order: Sequence[str],
require_complete: bool,
) -> LayoutResult:
began = perf_counter()
routing = _LayoutSearch(evaluator, nets, settings, windows)
for name in order:
routing.search(name)
covered_at = perf_counter() - began if len(routing.installed) == len(nets) else None
cost_at_coverage = (
fsum(move.cost for route in routing.routes.values() for move in (route.path or ())) if covered_at is not None else None
)
tuning_start = perf_counter()
reports = {group.group_id: routing.tune(group, timing) for group in groups} if timing is not None else {}
tuning_seconds = perf_counter() - tuning_start if groups else 0.0
retry_start = perf_counter()
retries = 0
failed = {name for name, group in members.items() if not reports[group].complete}
if failed and not require_complete:
for name in failed:
routing.installed.pop(name, None)
routing.installed_paths.pop(name, None)
routing.windows.pop(name, None)
if settings.retry_independent:
for name in nets:
if name not in members and routing.routes[name].path is None:
retries += 1
routing.search(name)
retry_seconds = perf_counter() - retry_start if retries else 0.0
if settings.refinement and (not failed or not require_complete):
pending = [name for name in nets if name not in members and routing.routes[name].path is None]
for name in pending[:2]:
routing.repair(name, members)
completed = tuple(name for name in nets if name not in failed and routing.routes[name].path is not None)
if settings.refinement:
group_by_id = {group.group_id: group for group in groups}
for name in completed:
group_id = members.get(name)
report = routing.refine(name, group_by_id.get(group_id), reports.get(group_id), timing)
if group_id is not None and report is not None:
reports[group_id] = report
for name in completed:
path = routing.routes[name].path
assert path is not None
if not routing.verify(name, path):
raise RuntimeError(f"Final catalog layout verification failed for {name!r}")
delays = {}
if timing is not None:
for name, route in routing.routes.items():
if name in members:
delays[name] = reports[members[name]].delays.get(name)
elif route.path is not None:
delays[name] = evaluate_delay(evaluator, route.path, timing, net_id=name)
work = routing.routes.values()
attempt = LayoutAttempt(
tuple(order), covered_at, cost_at_coverage, perf_counter() - began, completed,
sum(route.expanded for route in work), sum(route.proposed for route in work), sum(route.coarse_expanded for route in work),
sum(route.geometry_checks for route in work), sum(route.geometry_cache_hits for route in work),
sum(route.geometry_cache_entries for route in work), routing.pair_repairs, tuning_seconds, retry_seconds, retries,
)
return LayoutResult(snapshot({name: routing.routes[name] for name in nets}), completed, snapshot(delays), snapshot(reports), (attempt,))

View file

@ -0,0 +1,125 @@
"""Select verified delay choices for one catalog match group."""
from __future__ import annotations
from bisect import bisect_left
from dataclasses import dataclass
from math import fsum, isfinite, ulp
from typing import TYPE_CHECKING, Literal
from inire._snapshot import snapshot
if TYPE_CHECKING:
from collections.abc import Mapping, Sequence
from inire._catalog import Evaluation
from inire._catalog_timing import Delay
TimingUnits = Literal["optical_length", "seconds"]
@dataclass(frozen=True, slots=True)
class MatchGroup:
group_id: str
offsets: Mapping[str, float]
wavelength: float
tolerance: float
units: TimingUnits = "optical_length"
def __post_init__(self) -> None:
if not self.group_id or not self.offsets or not all(self.offsets):
raise ValueError("A match group needs an ID and member net IDs")
if not isfinite(self.wavelength) or self.wavelength <= 0:
raise ValueError("A match group needs a positive finite wavelength")
if not isfinite(self.tolerance) or self.tolerance < 0 or any(not isfinite(offset) for offset in self.offsets.values()):
raise ValueError("Match offsets must be finite and tolerance must be finite and nonnegative")
if self.units not in ("optical_length", "seconds"):
raise ValueError("Match units must be optical_length or seconds")
object.__setattr__(self, "offsets", snapshot(self.offsets))
@dataclass(frozen=True, slots=True)
class DelayChoice:
path: tuple[Evaluation, ...]
delay: Delay
@property
def cost(self) -> float:
return fsum(move.cost for move in self.path)
@dataclass(frozen=True, slots=True)
class MatchResult:
group_id: str
status: Literal["matched", "unmatched", "unrouted", "missing_delay"]
delays: Mapping[str, Delay]
skew: float | None
budget_exhausted: bool = False
tuning_space_found: bool = False
proposed_replacements: int = 0
verified_replacements: int = 0
eligible_spans: int = 0
@property
def complete(self) -> bool:
return self.status == "matched"
def _within(spread: float, tolerance: float, low: float, high: float) -> bool:
# Adjusted times can be very small. Use the rounding scale of the
# compared values so the same interval works in either timing unit.
return spread <= tolerance + 4 * max(ulp(low), ulp(high), ulp(tolerance))
def choose_match(
group: MatchGroup, choices: Mapping[str, Sequence[DelayChoice]],
) -> tuple[dict[str, DelayChoice], float, bool]:
"""Minimize skew until tolerance is achievable, then minimize cost."""
layers = {}
for net, offset in group.offsets.items():
layers[net] = sorted(
(
(getattr(choice.delay, group.units) - offset, order, choice.cost, choice)
for order, choice in enumerate(choices[net])
),
key=lambda item: (item[0], item[1]),
)
if any(not layer for layer in layers.values()):
raise ValueError("Every match member needs at least one verified timing choice")
starts = sorted({option[0] for layer in layers.values() for option in layer})
skew_roundoff = 4 * max(ulp(value) for value in starts)
best_pick: tuple[tuple[float, int, float, DelayChoice], ...] | None = None
best_rank: tuple[bool, float, float, tuple[int, ...]] | None = None
best_skew = 0.0
for low in starts:
first = [bisect_left(layer, low, key=lambda option: option[0]) for layer in layers.values()]
if any(index == len(layer) for index, layer in zip(first, layers.values(), strict=True)):
break
attainable_high = max(layer[index][0] for index, layer in zip(first, layers.values(), strict=True))
fits = _within(attainable_high - low, group.tolerance, low, attainable_high)
limit = group.tolerance if fits else attainable_high - low
selected = []
for index, layer in zip(first, layers.values(), strict=True):
best = layer[index]
for option in layer[index + 1:]:
if not _within(option[0] - low, limit, low, option[0]):
break
if (option[2], option[1]) < (best[2], best[1]):
best = option
selected.append(best)
skew = max(item[0] for item in selected) - min(item[0] for item in selected)
rank = (not fits, 0.0 if fits else skew, fsum(item[2] for item in selected), tuple(item[1] for item in selected))
comparable = rank
if best_rank is not None and rank[0] == best_rank[0] and abs(rank[1] - best_rank[1]) <= skew_roundoff:
comparable = (rank[0], best_rank[1], rank[2], rank[3])
if best_rank is None or comparable < best_rank:
best_rank, best_pick, best_skew = rank, tuple(selected), skew
assert best_pick is not None
assert best_rank is not None
return (
{net: selected[3] for net, selected in zip(layers, best_pick, strict=True)},
best_skew,
not best_rank[0],
)

View file

@ -0,0 +1,617 @@
"""Bounded detailed search over evaluated catalog moves."""
from __future__ import annotations
from dataclasses import dataclass, replace
from heapq import heappop, heappush
from itertools import count, islice
from math import ceil, floor, fsum, hypot, inf, isfinite
from typing import TYPE_CHECKING, Literal
from shapely import box
from shapely.geometry import LineString, Point
from shapely.strtree import STRtree
from inire._catalog import HEADING_STEPS, Move, Pose, StraightVariant, _require_integer
from inire.geometry.collision import _violates_net_clearance
from ._catalog_verify import (
compatible_join, face_reservation, meets_attachment_clearance, replay_moves, validate_attachment,
verify_move, verify_path, wholly_in_attachment,
)
if TYPE_CHECKING:
from collections.abc import Iterator, Sequence
from shapely.geometry import Polygon
from shapely.geometry.base import BaseGeometry
from inire._catalog import Evaluation, MoveEvaluator
from ._catalog_guidance import Corridor
from ._catalog_verify import Attachment
@dataclass(frozen=True, slots=True)
class SearchBias:
"""Optional queue penalties in catalog cost units for nearby geometry."""
range: float = 1.0
proximity: float = 0.0
congestion: float = 0.0
guide: float = 0.0
def __post_init__(self) -> None:
if not isfinite(self.range) or self.range <= 0:
raise ValueError("Search bias range must be finite and positive")
if any(not isfinite(value) or value < 0 for value in (self.proximity, self.congestion, self.guide)):
raise ValueError("Search bias weights must be finite and nonnegative")
@dataclass(frozen=True, slots=True)
class SearchResult:
path: tuple[Evaluation, ...] | None
outcome: Literal["verified", "exhausted", "node_limit"]
expanded: int
proposed: int
coarse_expanded: int = 0
used_guidance: bool = False
guide_fallback: bool = False
profile_fallback: bool = False
geometry_checks: int = 0
geometry_cache_hits: int = 0
geometry_cache_entries: int = 0
budget_exhausted: bool = False
@property
def length(self) -> float | None:
if self.path is None or any(move.length is None for move in self.path):
return None
return fsum(move.length for move in self.path if move.length is not None)
@property
def cost(self) -> float | None:
return None if self.path is None else fsum(move.cost for move in self.path)
def including_work(self, earlier: SearchResult) -> SearchResult:
return replace(
self, expanded=self.expanded + earlier.expanded, proposed=self.proposed + earlier.proposed,
coarse_expanded=self.coarse_expanded + earlier.coarse_expanded,
geometry_checks=self.geometry_checks + earlier.geometry_checks,
geometry_cache_hits=self.geometry_cache_hits + earlier.geometry_cache_hits,
geometry_cache_entries=self.geometry_cache_entries + earlier.geometry_cache_entries,
)
@dataclass(frozen=True, slots=True)
class _Arrival:
move: Evaluation
previous: _Arrival | None
cost: float
length: float
unknown_lengths: int
source_can_attach: bool
priority_penalty: float = 0.0
def _placed_path(arrival: _Arrival | None) -> tuple[Evaluation, ...]:
path = []
while arrival is not None:
path.append(arrival.move)
arrival = arrival.previous
return tuple(reversed(path))
def path_recipe(path: Sequence[Evaluation]) -> tuple[Move, ...]:
"""Identify the same run of straight material regardless of its segmentation."""
recipe: list[Move] = []
for part in path:
move = part.move
if recipe and move.steps is not None and recipe[-1].variant == move.variant and recipe[-1].steps is not None:
previous = recipe.pop()
assert previous.steps is not None
recipe.append(Move(move.variant, steps=previous.steps + move.steps))
else:
recipe.append(move)
return tuple(recipe)
COST_TOLERANCE = 1e-12
_TravelState = tuple[str, int]
def _reverse_distances(
target: _TravelState, incoming: dict[_TravelState, list[tuple[_TravelState, float]]],
) -> dict[_TravelState, float]:
distances = {target: 0.0}
queue = [(0.0, target)]
while queue:
distance, state = heappop(queue)
if distance > distances[state]:
continue
for previous, change in incoming.get(state, ()):
estimate = distance + change
if estimate < distances.get(previous, inf):
distances[previous] = estimate
heappush(queue, (estimate, previous))
return distances
def _colliders(tree: STRtree, shapes: Sequence[BaseGeometry], clearance: float) -> tuple[BaseGeometry, ...]:
if not len(tree) or not shapes:
return ()
bounds = [shape.bounds for shape in shapes]
area = box(
min(b[0] for b in bounds) - clearance, min(b[1] for b in bounds) - clearance,
max(b[2] for b in bounds) + clearance, max(b[3] for b in bounds) + clearance,
)
return tuple(tree.geometries[index] for index in tree.query(area))
def _geometry_bias(move: Evaluation, blockers: STRtree, radius: float, weight: float, length_factor: float) -> float:
if not weight:
return 0.0
nearby = _colliders(blockers, move.footprints, radius)
if not nearby:
return 0.0
distance = min(shape.distance(other) for shape in move.footprints for other in nearby)
return weight * length_factor * max(0.0, 1 - distance / radius)
class _Proposals:
def __init__(
self, evaluator: MoveEvaluator, start: Pose, target: Pose, blockers: Sequence[BaseGeometry], clearance: float,
corridor: Corridor | None = None,
scan_steps: bool = False,
) -> None:
self.evaluator = evaluator
self.target = target
self.clearance = clearance
self.guide_points = corridor.points if corridor is not None else ()
self.scan_steps = scan_steps
self.blocker_bounds = tuple(shape.bounds for shape in blockers)
self._forward_only: dict[tuple[str, int], bool] = {}
profiles = evaluator.catalog.profiles
self._straights: dict[str, list[str]] = {profile: [] for profile in profiles}
self._straight_prices: dict[str, float] = {}
for name, variant in evaluator.catalog.variants.items():
if isinstance(variant, StraightVariant):
self._straights[variant.profile].append(name)
self._straight_prices[name] = variant.cost_per_cm
self._direction = (
(target.x > start.x) - (target.x < start.x),
(target.y > start.y) - (target.y < start.y),
)
# Relax the problem to heading/profile changes and a linear distance
# term. The latter telescopes across a route regardless of detours.
incoming: dict[_TravelState, list[tuple[_TravelState, float, int, int]]] = {}
self._fixed_offsets: dict[_TravelState, dict[Move, tuple[Pose, float]]] = {}
for profile in profiles:
for heading in HEADING_STEPS:
offsets = self._fixed_offsets.setdefault((profile, heading), {})
for move, end in evaluator.local_moves(profile, heading):
variant = evaluator.catalog.variants[move.variant]
assert not isinstance(variant, StraightVariant)
offsets[move] = end, variant.cost
incoming.setdefault((end.profile, end.heading), []).append(
((profile, heading), variant.cost, end.x, end.y),
)
target_key = (target.profile, target.heading)
reachable = {target_key}
pending = [target_key]
while pending:
for previous, *_ in incoming.get(pending.pop(), ()):
if previous not in reachable:
reachable.add(previous)
pending.append(previous)
ratios = []
for state in sorted(reachable):
for _, cost, x, y in incoming.get(state, ()):
distance = self._projection(x, y)
if distance > 0:
ratios.append(cost / distance)
profile, heading = state
dx, dy = HEADING_STEPS[heading]
progress = self._projection(dx, dy)
if progress > 0:
for name in self._straights[profile]:
variant = evaluator.catalog.variants[name]
assert isinstance(variant, StraightVariant)
ratios.append(variant.cost_per_cm * evaluator.grid.meters_per_unit * 100 * hypot(dx, dy) / progress)
self.cost_per_unit = min(ratios, default=0.0)
self.residual_cost = _reverse_distances(target_key, {
state: [(previous, max(0.0, cost - self.cost_per_unit * self._projection(x, y))) for previous, cost, x, y in edges]
for state, edges in incoming.items()
})
self.minimum_progress: list[tuple[int, int, dict[_TravelState, float]]] = []
for axis in (0, 1):
for sign in (-1, 1):
if any(sign * HEADING_STEPS[heading][axis] < 0 for profile, heading in reachable if self._straights[profile]):
continue
progress = {
state: [(previous, sign * (x, y)[axis]) for previous, _, x, y in incoming.get(state, ())]
for state in reachable
}
if any(distance < 0 for edges in progress.values() for _, distance in edges):
continue
self.minimum_progress.append((axis, sign, _reverse_distances(target_key, progress)))
def _projection(self, x: int, y: int) -> int:
dx, dy = self._direction
return dx * x + dy * y
def lower_bound(self, pose: Pose) -> float:
residual = self.residual_cost.get((pose.profile, pose.heading), inf)
dx, dy = HEADING_STEPS[pose.heading]
tx, ty = self.target.x - pose.x, self.target.y - pose.y
if any(sign * (tx, ty)[axis] < distances.get((pose.profile, pose.heading), inf)
for axis, sign, distances in self.minimum_progress):
return inf
if self._is_forward_only(pose) and (dx * ty != dy * tx or dx * tx + dy * ty < 0):
return inf
return max(0.0, residual + self._projection(tx, ty) * self.cost_per_unit)
def _is_forward_only(self, pose: Pose) -> bool:
key = (pose.profile, pose.heading)
if key not in self._forward_only:
dx, dy = HEADING_STEPS[pose.heading]
profiles = {pose.profile}
pending = [pose.profile]
while pending:
profile = pending.pop()
for _, end in self.evaluator.local_moves(profile, pose.heading):
if (end.profile, end.heading) not in self.residual_cost:
continue
if end.heading != pose.heading or dx * end.y != dy * end.x or dx * end.x + dy * end.y < 0:
self._forward_only[key] = False
return False
if end.profile not in profiles:
profiles.add(end.profile)
pending.append(end.profile)
self._forward_only[key] = True
return self._forward_only[key]
def destination_bound(self, start: Pose, move: Move) -> tuple[Pose, float] | None:
"""Return the exact output pose and an inexpensive lower bound on move cost."""
if move.steps is not None:
dx, dy = HEADING_STEPS[start.heading]
span = int(self.evaluator.grid.pitch) * move.steps
price = self._straight_prices[move.variant] * span * hypot(dx, dy) * self.evaluator.grid.meters_per_unit * 100
return start.shifted(dx * span, dy * span), price
local = self._fixed_offsets[(start.profile, start.heading)].get(move)
return (local[0].shifted(start.x, start.y), local[1]) if local is not None else None
def two_turn_recipes(self, start: Pose) -> Iterator[tuple[Move, ...]]:
"""Solve the straight spans of a two-turn route between parallel terminals."""
target = self.target
if target.heading != start.heading:
return
ux, uy = HEADING_STEPS[start.heading]
tx, ty = target.x - start.x, target.y - start.y
if ux * ty == uy * tx:
return
pitch = int(self.evaluator.grid.pitch)
denominator = pitch * (ux * ux + uy * uy)
cheapest = {
key: min(names, key=self._straight_prices.__getitem__)
for key, names in self._straights.items() if names
}
if start.profile not in cheapest or target.profile not in cheapest:
return
candidates = []
for first, turn in self.evaluator.local_moves(start.profile, start.heading):
vx, vy = HEADING_STEPS[turn.heading]
divisor = pitch * (ux * vy - uy * vx)
if not divisor or turn.profile not in cheapest:
continue
for second, exit_pose in self.evaluator.local_moves(turn.profile, turn.heading):
if (exit_pose.heading, exit_pose.profile) != (target.heading, target.profile):
continue
x, y = tx - turn.x - exit_pose.x, ty - turn.y - exit_pose.y
across, remainder = divmod(ux * y - uy * x, divisor)
if remainder or across < 0:
continue
x -= across * pitch * vx
y -= across * pitch * vy
parallel, remainder = divmod(ux * x + uy * y, denominator)
if remainder or parallel < 0:
continue
before_id, middle_id, after_id = (cheapest[profile] for profile in (start.profile, turn.profile, target.profile))
for before, after in dict.fromkeys(((0, parallel), (parallel, 0), (parallel // 2, parallel - parallel // 2))):
recipe = (
*((Move(before_id, steps=before),) if before else ()), first,
*((Move(middle_id, steps=across),) if across else ()), second,
*((Move(after_id, steps=after),) if after else ()),
)
legs = ((before_id, before, ux, uy), (middle_id, across, vx, vy), (after_id, after, ux, uy))
price = fsum(self._straight_prices[name] * steps * hypot(dx, dy) for name, steps, dx, dy in legs)
price *= pitch * self.evaluator.grid.meters_per_unit * 100
for move in (first, second):
variant = self.evaluator.catalog.variants[move.variant]
assert not isinstance(variant, StraightVariant)
price += variant.cost
candidates.append((price, recipe))
for _, recipe in sorted(candidates, key=lambda item: item[0]):
yield recipe
def from_pose(self, start: Pose, board_bounds: tuple[float, float, float, float]) -> Iterator[Move]:
fixed = self.evaluator.local_moves(start.profile, start.heading)
runs = self._straights[start.profile]
if not fixed:
dx, dy = HEADING_STEPS[start.heading]
tx, ty = self.target.x - start.x, self.target.y - start.y
if (start.heading, start.profile) == (self.target.heading, self.target.profile) and dx * ty == dy * tx:
steps = (dx * tx + dy * ty) // (int(self.evaluator.grid.pitch) * (dx * dx + dy * dy))
if steps > 0:
for name in runs:
yield Move(name, steps=steps)
return
if runs:
targets = self._straight_steps(start, fixed, board_bounds)
for steps in targets:
for name in runs:
yield Move(name, steps=steps)
for move, _ in fixed:
yield move
def _straight_steps(
self, start: Pose, fixed: Sequence[tuple[Move, Pose]], board_bounds: tuple[float, float, float, float],
) -> list[int]:
dx, dy = HEADING_STEPS[start.heading]
pitch = int(self.evaluator.grid.pitch)
x0, y0, x1, y1 = board_bounds
distance_x = (x1 - start.x) if dx > 0 else (start.x - x0) if dx < 0 else inf
distance_y = (y1 - start.y) if dy > 0 else (start.y - y0) if dy < 0 else inf
limit = floor(min(distance_x, distance_y) / pitch)
magnitude = dx * dx + dy * dy
tx, ty = self.target.x - start.x, self.target.y - start.y
steps = {limit}
def add_projection(x: float, y: float) -> None:
projected = (dx * x + dy * y) / (pitch * magnitude)
steps.update((floor(projected), ceil(projected)))
add_projection(tx, ty)
for x, y in self.guide_points:
add_projection(x - start.x, y - start.y)
for _, end in fixed:
add_projection(x - start.x - end.x, y - start.y - end.y)
def align_exit(end: Pose) -> None:
rx, ry = tx - end.x, ty - end.y
ex, ey = HEADING_STEPS[end.heading]
divisor = pitch * (dx * ey - dy * ex)
if divisor:
n, remainder = divmod(rx * ey - ry * ex, divisor)
if not remainder:
steps.add(n)
else:
add_projection(rx, ry)
for _, end in fixed:
align_exit(end)
for _, following in self.evaluator.local_moves(end.profile, end.heading):
align_exit(following.shifted(end.x, end.y))
# Obstacle edges and the inverse displacement of fixed cells create
# interior launch points even when a long straight has clear reach.
margin = self.clearance + self.evaluator.catalog.profiles[start.profile].width / 2
# This only influences proposals. Admission still checks the full
# footprints against the spatial index.
side_reach = margin * magnitude + max((abs(dx * end.y - dy * end.x) for _, end in fixed), default=0)
relevant = False
for bx0, by0, bx1, by1 in self.blocker_bounds:
side = tuple(dx * (y - start.y) - dy * (x - start.x) for x in (bx0, bx1) for y in (by0, by1))
if min(side) > side_reach or max(side) < -side_reach:
continue
relevant = True
for x in (bx0 - margin, bx0, bx1, bx1 + margin):
for y in (by0 - margin, by0, by1, by1 + margin):
px, py = x - start.x, y - start.y
add_projection(px, py)
for _, end in fixed:
add_projection(px - end.x, py - end.y)
if self.scan_steps and (relevant or not self._is_forward_only(start)):
steps.add(1)
return sorted((n for n in steps if 0 < n <= limit), reverse=True)
def _continues(
evaluator: MoveEvaluator,
parent: _Arrival | None,
move: Evaluation,
occupied: STRtree,
clearance: float,
self_clearance: float,
face_tolerance: float,
) -> bool:
if parent is None:
return True
width = evaluator.catalog.profiles[move.start.profile].width
if not compatible_join(parent.move, move, width, face_tolerance):
return False
if len(occupied):
seam = face_reservation(move.start, width, face_tolerance)
if any(_violates_net_clearance(seam, other, clearance) for other in _colliders(occupied, (seam,), clearance)):
return False
earlier = parent.previous
while earlier is not None:
uncertain = parent.unknown_lengths != earlier.unknown_lengths
spacing = self_clearance if uncertain or parent.length - earlier.length >= self_clearance else 0.0
if any(_violates_net_clearance(a, b, spacing) for a in earlier.move.footprints for b in move.footprints):
return False
earlier = earlier.previous
return True
def search_path(
evaluator: MoveEvaluator,
start: Pose,
target: Pose,
*,
board: Polygon,
keepouts: Sequence[BaseGeometry] = (),
occupied: Sequence[BaseGeometry] = (),
clearance: float = 0.0,
self_clearance: float = 0.0,
face_tolerance: float = 0.0,
node_limit: int = 1000,
arrivals_per_pose: int = 3,
source_attachment: Attachment | None = None,
destination_attachment: Attachment | None = None,
excluded_paths: Sequence[tuple[Move, ...]] = (),
max_cost: float = inf,
corridor: Corridor | None = None,
scan_steps: bool = False,
bias: SearchBias | None = None,
) -> SearchResult:
"""Search physical paths while retaining a bounded number of distinct arrival histories."""
_require_integer(node_limit)
_require_integer(arrivals_per_pose)
if node_limit < 0 or arrivals_per_pose < 1:
raise ValueError("Search requires a nonnegative node limit and positive arrival limit")
if any(value < 0 or not isfinite(value) for value in (clearance, self_clearance, face_tolerance)):
raise ValueError("Clearance and face tolerance must be finite and nonnegative")
for port in (start, target):
if evaluator.grid.lattice_position(port.x, port.y) is None or port.profile not in evaluator.catalog.profiles:
raise ValueError(f"Invalid catalog terminal {port!r}")
attached = {}
end_permissions = []
for attachment, pose, source in ((source_attachment, start, True), (destination_attachment, target, False)):
if attachment is not None:
validate_attachment(evaluator, attachment, pose, keepouts, face_tolerance, source=source)
attached[id(attachment.obstacle)] = attachment.obstacle
seam = face_reservation(pose, evaluator.catalog.profiles[pose.profile].width, face_tolerance)
end_permissions.append((attachment, seam, source))
ordinary_keepouts = STRtree([obstacle for obstacle in keepouts if id(obstacle) not in attached])
installed = STRtree(occupied)
guide_axis = LineString(corridor.points) if bias is not None and bias.guide and corridor is not None and len(corridor.points) > 1 else None
proposals = _Proposals(evaluator, start, target, (*keepouts, *occupied), clearance, corridor, scan_steps)
initial_bound = proposals.lower_bound(start)
if initial_bound == inf or initial_bound > max_cost + COST_TOLERANCE:
return SearchResult(None, "exhausted", 0, 0)
incumbent = None
macro_trials = macro_checks = 0
for recipe in islice(proposals.two_turn_recipes(start), min(node_limit // 2, 48)):
macro_trials += 1
if recipe in excluded_paths:
continue
path = replay_moves(evaluator, start, recipe)
if path is None or (corridor is not None and any(not corridor.admits(move.end) for move in path)):
continue
cost = fsum(move.cost for move in path)
if cost >= max_cost:
continue
macro_checks += 1
if verify_path(
evaluator, path, start, target, board=board, keepouts=keepouts, occupied=occupied, clearance=clearance,
self_clearance=self_clearance, face_tolerance=face_tolerance,
source_attachment=source_attachment, destination_attachment=destination_attachment,
) is None:
incumbent = path
max_cost = cost
order = count()
queue: list[tuple[float, float, int, Pose, _Arrival | None]] = [(initial_bound, initial_bound, next(order), start, None)]
expanded = cache_hits = 0
proposed, geometry_checks = macro_trials, macro_checks
visits: dict[Pose, int] = {}
evaluated: dict[tuple[Pose, Move], Evaluation | None] = {}
while queue and expanded < node_limit:
_, _, _, pose, parent = heappop(queue)
prior = visits.get(pose, 0)
if prior >= arrivals_per_pose:
continue
visits[pose] = prior + 1
expanded += 1
if parent is not None and pose == target:
path = _placed_path(parent)
if (incumbent is None or fsum(move.cost for move in path) < max_cost - COST_TOLERANCE) and (
path_recipe(path) not in excluded_paths
) and verify_path(
evaluator, path, start, target, board=board, keepouts=keepouts, occupied=occupied,
clearance=clearance, self_clearance=self_clearance, face_tolerance=face_tolerance,
source_attachment=source_attachment, destination_attachment=destination_attachment,
) is None:
return SearchResult(
path, "verified", expanded, proposed, geometry_checks=geometry_checks,
geometry_cache_hits=cache_hits, geometry_cache_entries=len(evaluated),
)
source_can_attach = parent is None or parent.source_can_attach
allowed = {
key: tuple(
(attachment, seam) for attachment, seam, source in end_permissions
if id(attachment.obstacle) == key and (not source or source_can_attach)
)
for key in attached
}
for spec in proposals.from_pose(pose, board.bounds):
if parent is not None and spec.steps is not None:
previous = parent.move.move
if previous.variant == spec.variant and previous.steps is not None:
combined = Move(spec.variant, steps=previous.steps + spec.steps)
if evaluated.get((parent.move.start, combined)) is not None:
continue
proposed += 1
preview = proposals.destination_bound(pose, spec)
if preview is None:
continue
expected, base_cost = preview
if visits.get(expected, 0) >= arrivals_per_pose:
continue
distance_cost = proposals.lower_bound(expected)
prefix_cost = parent.cost if parent is not None else 0.0
if distance_cost == inf or prefix_cost + base_cost + distance_cost > max_cost + COST_TOLERANCE:
continue
key = (pose, spec)
if key not in evaluated:
move = evaluator.evaluate(spec, pose)
if move is not None and corridor is not None and not corridor.admits(move.end):
move = None
if move is not None:
geometry_checks += 1
if verify_move(
evaluator, move, board,
_colliders(ordinary_keepouts, move.footprints, clearance), _colliders(installed, move.footprints, clearance),
clearance, face_tolerance,
):
move = None
evaluated[key] = move
else:
cache_hits += 1
move = evaluated[key]
if move is None or visits.get(move.end, 0) >= arrivals_per_pose:
continue
# Source permission depends on the arrival history. Destination
# permission is provisional until final verification checks the suffix.
if any(not meets_attachment_clearance(move, obstacle, allowed[key], clearance) for key, obstacle in attached.items()):
continue
if not _continues(evaluator, parent, move, installed, clearance, self_clearance, face_tolerance):
continue
step_length = move.length if move.length is not None else hypot(move.end.x - move.start.x, move.end.y - move.start.y)
penalty = parent.priority_penalty if parent is not None else 0.0
if bias is not None:
length_factor = step_length / bias.range
penalty += _geometry_bias(move, ordinary_keepouts, bias.range, bias.proximity, length_factor)
penalty += _geometry_bias(move, installed, bias.range, bias.congestion, length_factor)
if guide_axis is not None:
penalty += bias.guide * length_factor * guide_axis.distance(Point(move.end.x, move.end.y)) / bias.range
arrival = _Arrival(
move, parent, prefix_cost + move.cost,
(parent.length if parent is not None else 0) + (move.length or 0.0),
(parent.unknown_lengths if parent is not None else 0) + (move.length is None),
source_can_attach and source_attachment is not None and wholly_in_attachment(move, source_attachment),
penalty,
)
if arrival.cost + distance_cost > max_cost + COST_TOLERANCE:
continue
heappush(queue, (round(arrival.cost + distance_cost + penalty, 12), distance_cost, next(order), move.end, arrival))
return SearchResult(
incumbent, "verified" if incumbent is not None else ("node_limit" if queue else "exhausted"),
expanded, proposed, geometry_checks=geometry_checks, geometry_cache_hits=cache_hits,
geometry_cache_entries=len(evaluated), budget_exhausted=bool(queue),
)

View file

@ -0,0 +1,183 @@
"""Propose four-turn replacements inside supplied tuning windows."""
from __future__ import annotations
from collections import deque
from dataclasses import replace
from itertools import product
from math import ceil, floor
from typing import TYPE_CHECKING
from shapely import get_parts
from shapely.geometry import LineString
from inire._catalog import HEADING_STEPS, Move, StraightVariant
from inire._catalog_timing import evaluate_delay
from inire._snapshot import snapshot
from ._catalog_matching import DelayChoice, MatchResult, choose_match
from ._catalog_verify import replay_moves
if TYPE_CHECKING:
from collections.abc import Callable, Iterator, Mapping, Sequence
from shapely.geometry import Polygon
from inire._catalog import Evaluation, MoveEvaluator
from inire._catalog_timing import DelayModel
from ._catalog_matching import MatchGroup
def _eligible_spans(
evaluator: MoveEvaluator, path: Sequence[Evaluation], window: Polygon,
) -> Iterator[tuple[int, Evaluation, int, int]]:
pitch = int(evaluator.grid.pitch)
for index, straight in enumerate(path):
if not isinstance(evaluator.catalog.variants[straight.move.variant], StraightVariant):
continue
steps = straight.move.steps
assert steps is not None
dx, dy = HEADING_STEPS[straight.start.heading]
norm_squared = dx * dx + dy * dy
section = LineString(((straight.start.x, straight.start.y), (straight.end.x, straight.end.y)))
for part in get_parts(section.intersection(window)):
if not isinstance(part, LineString) or part.is_empty:
continue
positions = [((x - straight.start.x) * dx + (y - straight.start.y) * dy) / (pitch * norm_squared) for x, y in part.coords]
first = max(0, ceil(min(positions) - 1e-10))
last = min(steps, floor(max(positions) + 1e-10))
if first < last:
yield index, straight, first, last
def window_replacements(
evaluator: MoveEvaluator, path: Sequence[Evaluation], window: Polygon,
) -> Iterator[tuple[Evaluation, ...] | None]:
"""Yield bounded-grid detour proposals, including rejected evaluations for budget accounting."""
for index, straight, first, last in _eligible_spans(evaluator, path, window):
inset = max(1, (last - first) // 8)
spans = ((first, last), (first + inset, last), (first, last - inset), (first + inset, last - inset))
pending = deque(
_doglegs(evaluator, straight, window, a, b, sign)
for a, b in spans if a < b for sign in (1, -1)
)
while pending:
generator = pending.popleft()
try:
proposal = next(generator)
except StopIteration:
continue
pending.append(generator)
if proposal is None:
yield None
else:
yield (*path[:index], *proposal, *path[index + 1:])
def _doglegs(
evaluator: MoveEvaluator, straight: Evaluation, window: Polygon, first: int, last: int, sign: int,
) -> Iterator[tuple[Evaluation, ...] | None]:
start = straight.start
steps = straight.move.steps
assert steps is not None
pitch = int(evaluator.grid.pitch)
dx, dy = HEADING_STEPS[start.heading]
denom = pitch * (dx * dx + dy * dy)
x0, y0, x1, y1 = window.bounds
width_limit = ceil((abs(dy) * (x1 - x0) + abs(dx) * (y1 - y0)) / denom)
straight_name = straight.move.variant
turn = sign * 90
headings = (start.heading, (start.heading + turn) % 360, start.heading, (start.heading - turn) % 360, start.heading)
catalog_turns = [
tuple(
(move, end) for move, end in evaluator.local_moves(start.profile, entry)
if end.heading == exit and end.profile == start.profile
)
for entry, exit in zip(headings[:-1], headings[1:], strict=True)
]
for turns in product(*catalog_turns):
offsets_x = sum(end.x for _, end in turns)
offsets_y = sum(end.y for _, end in turns)
along, remainder = divmod(dx * offsets_x + dy * offsets_y, denom)
sideways, lateral_remainder = divmod(sign * (-dy * offsets_x + dx * offsets_y), denom)
forward = last - first - along
if remainder or lateral_remainder or forward < 0:
yield None
continue
begin = start.shifted(first * dx * pitch, first * dy * pitch)
for height in range(max(0, -sideways), width_limit + 1):
return_height = height + sideways
legs = (height, forward, return_height, 0)
replacement = []
for (turn_move, _), leg in zip(turns, legs, strict=True):
replacement.append(turn_move)
if leg:
replacement.append(Move(straight_name, steps=leg))
trial = replay_moves(evaluator, begin, replacement)
if trial is None or any(not window.covers(shape) for move in trial for shape in move.footprints):
yield None
continue
prefix = ()
suffix = ()
if first:
prefix = replay_moves(evaluator, start, (Move(straight_name, steps=first),))
assert prefix is not None
if last < steps:
suffix = replay_moves(evaluator, trial[-1].end, (Move(straight_name, steps=steps - last),))
assert suffix is not None
yield (*prefix, *trial, *suffix)
def tune_group(
evaluator: MoveEvaluator,
group: MatchGroup,
models: DelayModel,
baselines: Mapping[str, tuple[Evaluation, ...] | None],
windows: Mapping[str, Polygon],
verifies: Callable[[str, tuple[Evaluation, ...]], bool],
*,
proposal_limit: int,
) -> tuple[MatchResult, dict[str, tuple[Evaluation, ...]]]:
if proposal_limit < 0:
raise ValueError("Tuning proposal limit must be nonnegative")
model = replace(models, wavelength=group.wavelength)
delays = {}
choices: dict[str, list[DelayChoice]] = {}
for net in group.offsets:
path = baselines[net]
if path is not None and (delay := evaluate_delay(evaluator, path, model, net_id=net)) is not None:
delays[net] = delay
choices[net] = [DelayChoice(path, delay)]
if len(choices) != len(group.offsets):
status = "unrouted" if any(baselines[net] is None for net in group.offsets) else "missing_delay"
return MatchResult(group.group_id, status, snapshot(delays), None), {}
selected, skew, matched = choose_match(group, choices)
if matched:
return MatchResult(group.group_id, "matched", snapshot(delays), skew), {}
active = tuple((net, choices[net][0].path, windows[net]) for net in group.offsets if net in windows)
eligible_spans = sum(1 for _, path, window in active for _ in _eligible_spans(evaluator, path, window))
pending = deque((net, window_replacements(evaluator, path, window)) for net, path, window in active)
proposed = accepted = 0
while pending and proposed < proposal_limit:
net, generator = pending.popleft()
try:
path = next(generator)
except StopIteration:
continue
pending.append((net, generator))
proposed += 1
if path is None or not verifies(net, path):
continue
accepted += 1
delay = evaluate_delay(evaluator, path, model, net_id=net)
if delay is not None and delay.optical_length > choices[net][0].delay.optical_length:
choices[net].append(DelayChoice(path, delay))
exhausted = bool(pending)
selected, skew, matched = choose_match(group, choices)
delays = {net: option.delay for net, option in selected.items()}
modified = {net: option.path for net, option in selected.items() if option is not choices[net][0]}
return MatchResult(
group.group_id, "matched" if matched else "unmatched", snapshot(delays), skew, exhausted, accepted > 0,
proposed, accepted, eligible_spans,
), modified

View file

@ -0,0 +1,260 @@
"""Geometry verification shared by catalog replay and routing."""
from __future__ import annotations
from dataclasses import dataclass
from itertools import accumulate, combinations
from math import hypot, isfinite, ulp
from typing import TYPE_CHECKING
from shapely.affinity import affine_transform
from shapely.geometry import LineString, Polygon, box
from inire._catalog import HEADING_STEPS, face_endpoints
from inire.geometry.collision import _violates_clearance, _violates_net_clearance
if TYPE_CHECKING:
from collections.abc import Iterable, Sequence
from shapely.geometry.base import BaseGeometry
from inire._catalog import Evaluation, Move, MoveEvaluator, Pose
@dataclass(frozen=True, slots=True)
class Attachment:
"""Permission to meet a specific fixed obstacle at one terminal."""
obstacle: BaseGeometry
region: Polygon
actual_shapes: tuple[Polygon, ...] = ()
def validate_attachment(
evaluator: MoveEvaluator,
attachment: Attachment,
pose: Pose,
keepouts: Sequence[BaseGeometry],
face_tolerance: float,
*,
source: bool,
) -> None:
if not any(attachment.obstacle is obstacle for obstacle in keepouts):
raise ValueError("An attachment must identify a registered keepout")
if attachment.region.is_empty or not attachment.region.is_valid or not attachment.region.covers(
face_reservation(pose, evaluator.catalog.profiles[pose.profile].width, 0),
):
raise ValueError("An attachment region must be valid and cover the entire terminal face")
if any(
shape.is_empty or not shape.is_valid or not attachment.obstacle.covers(shape)
for shape in attachment.actual_shapes
):
raise ValueError("Fixed attachment shapes must be valid and inside the registered keepout")
actual = attachment.actual_shapes or (attachment.obstacle,)
width = evaluator.catalog.profiles[pose.profile].width
if not _matches_face(actual, pose, width, face_tolerance, arrival=source):
raise ValueError("Fixed attachment geometry does not meet its declared port face")
def wholly_in_attachment(move: Evaluation, attachment: Attachment) -> bool:
return all(attachment.region.covers(shape) for shape in move.footprints)
def meets_attachment_clearance(
move: Evaluation,
obstacle: BaseGeometry,
permissions: Sequence[tuple[Attachment, BaseGeometry]],
clearance: float,
) -> bool:
for shape in move.footprints:
outside = shape
for attachment, _ in permissions:
if outside.intersects(attachment.region):
outside = outside.difference(attachment.region)
if not outside.is_empty and _violates_clearance(outside, obstacle, clearance):
return False
for attachment, seam in permissions:
for shape in move.port_shapes or move.footprints:
if not shape.intersects(attachment.region):
continue
inside = shape.intersection(attachment.region)
for fixed in attachment.actual_shapes or (obstacle,):
if inside.relate_pattern(fixed, "2********") and not _seam_covers(seam, inside.intersection(fixed)):
return False
return True
def face_reservation(pose: Pose, width: float, tolerance: float) -> BaseGeometry:
"""The finite face and its allowed normal displacement, in layout coordinates."""
left, right = face_endpoints(pose, width)
if tolerance == 0:
return LineString((left, right))
dx, dy = HEADING_STEPS[pose.heading]
scale = tolerance / hypot(dx, dy)
x, y = dx * scale, dy * scale
return Polygon((
(left[0] - x, left[1] - y), (right[0] - x, right[1] - y),
(right[0] + x, right[1] + y), (left[0] + x, left[1] + y),
))
def _seam_covers(seam: BaseGeometry, overlap: BaseGeometry) -> bool:
if seam.covers(overlap):
return True
roundoff = 8 * ulp(max(abs(value) for value in seam.bounds))
return seam.buffer(roundoff).covers(overlap)
def _lateral_intervals(geometry: BaseGeometry) -> Iterable[tuple[float, float]]:
if geometry.is_empty:
return
if hasattr(geometry, "geoms"):
for part in geometry.geoms:
yield from _lateral_intervals(part)
else:
yield geometry.bounds[1], geometry.bounds[3]
def _matches_face(
footprints: Sequence[BaseGeometry], pose: Pose, width: float, tolerance: float, *, arrival: bool,
) -> bool:
dx, dy = HEADING_STEPS[pose.heading]
norm = hypot(dx, dy)
x, y = dx / norm, dy / norm
# Transform the face to x=0 without rotating any stored geometry.
frame = (x, y, -y, x, -(pose.x * x + pose.y * y), pose.x * y - pose.y * x)
half_width = width / 2
# Allow roundoff from projecting the footprint along a diagonal normal.
roundoff = 8 * ulp(max(abs(pose.x), abs(pose.y), width, tolerance))
local = tuple(affine_transform(shape, frame) for shape in footprints)
def covers_face(depth: float) -> bool:
reach = half_width + depth
patch = box(-depth if arrival else 0, -reach, 0 if arrival else depth, reach)
intervals = sorted(interval for shape in local for interval in _lateral_intervals(shape.intersection(patch)))
if not intervals or abs(intervals[0][0] + half_width) > roundoff:
return False
covered = intervals[0][1]
for lo, hi in intervals[1:]:
if lo > covered + roundoff:
return False
covered = max(covered, hi)
return abs(covered - half_width) <= roundoff
return covers_face(roundoff) or (tolerance > 0 and covers_face(tolerance + roundoff))
def compatible_join(left: Evaluation, right: Evaluation, width: float, tolerance: float) -> bool:
if left.end != right.start:
return False
seam = face_reservation(left.end, width, tolerance)
for first in left.port_shapes or left.footprints:
for second in right.port_shapes or right.footprints:
if first.relate_pattern(second, "2********") and not _seam_covers(seam, first.intersection(second)):
return False
return True
def _internal_edges(path: Sequence[Evaluation], clearance: float) -> Iterable[tuple[int, int, float]]:
distances = tuple(accumulate((move.length or 0.0 for move in path), initial=0.0))
unknowns = tuple(accumulate((move.length is None for move in path), initial=0))
for i, j in combinations(range(len(path)), 2):
if j > i + 1:
separation = distances[j] - distances[i + 1]
uncertain = unknowns[j] != unknowns[i + 1]
yield i, j, clearance if uncertain or separation >= clearance else 0.0
def verify_move(
evaluator: MoveEvaluator,
move: Evaluation,
board: Polygon,
keepouts: Sequence[BaseGeometry],
occupied: Sequence[BaseGeometry],
clearance: float,
face_tolerance: float,
) -> str | None:
profiles = evaluator.catalog.profiles
for pose, arrival in ((move.start, False), (move.end, True)):
if not _matches_face(move.port_shapes or move.footprints, pose, profiles[pose.profile].width, face_tolerance, arrival=arrival):
return "port_face"
if any(not board.covers(shape) for shape in move.footprints):
return "board_bounds"
if any(_violates_clearance(shape, keepout, clearance) for shape in move.footprints for keepout in keepouts):
return "keepout"
if any(_violates_net_clearance(shape, other, clearance) for shape in move.footprints for other in occupied):
return "occupied"
return None
def verify_path(
evaluator: MoveEvaluator,
path: Sequence[Evaluation],
start: Pose,
target: Pose,
*,
board: Polygon,
keepouts: Sequence[BaseGeometry] = (),
occupied: Sequence[BaseGeometry] = (),
clearance: float = 0.0,
self_clearance: float = 0.0,
face_tolerance: float = 0.0,
source_attachment: Attachment | None = None,
destination_attachment: Attachment | None = None,
) -> str | None:
"""Verify a catalog path and return the first reason it cannot be placed."""
if any(value < 0 or not isfinite(value) for value in (clearance, self_clearance, face_tolerance)):
raise ValueError("Clearance and face tolerance must be finite and nonnegative")
if not path or path[0].start != start or path[-1].end != target:
return "terminal_pose"
attachments = ((source_attachment, start, True), (destination_attachment, target, False))
attached = {id(item.obstacle): item.obstacle for item, _, _ in attachments if item is not None}
ordinary_keepouts = tuple(obstacle for obstacle in keepouts if id(obstacle) not in attached)
permissions: dict[tuple[int, int], list[tuple[Attachment, BaseGeometry]]] = {}
for attachment, pose, source in attachments:
if attachment is None:
continue
validate_attachment(evaluator, attachment, pose, keepouts, face_tolerance, source=source)
seam = face_reservation(pose, evaluator.catalog.profiles[pose.profile].width, face_tolerance)
if any(_violates_net_clearance(seam, shape, clearance) for shape in occupied):
return "occupied_seam"
ordered = range(len(path)) if source else reversed(range(len(path)))
for index in ordered:
permissions.setdefault((index, id(attachment.obstacle)), []).append((attachment, seam))
if not wholly_in_attachment(path[index], attachment):
break
for index, move in enumerate(path):
for key, obstacle in attached.items():
if not meets_attachment_clearance(move, obstacle, permissions.get((index, key), ()), clearance):
return "fixed_attachment"
profiles = evaluator.catalog.profiles
for move in path:
if error := verify_move(evaluator, move, board, ordinary_keepouts, occupied, clearance, face_tolerance):
return error
for left, right in zip(path[:-1], path[1:], strict=True):
width = profiles[left.end.profile].width
if not compatible_join(left, right, width, face_tolerance):
return "join"
seam = face_reservation(left.end, width, face_tolerance)
if any(_violates_net_clearance(seam, other, clearance) for other in occupied):
return "occupied_seam"
for i, j, spacing in _internal_edges(path, self_clearance):
if any(_violates_net_clearance(a, b, spacing) for a in path[i].footprints for b in path[j].footprints):
return "self_clearance"
return None
def replay_moves(
evaluator: MoveEvaluator,
start: Pose,
moves: Sequence[Move],
) -> tuple[Evaluation, ...] | None:
"""Materialize a sequence without proposing alternatives."""
current = start
placements = []
for move in moves:
evaluated = evaluator.evaluate(move, current)
if evaluated is None:
return None
placements.append(evaluated)
current = evaluated.end
return tuple(placements)

View file

@ -0,0 +1,71 @@
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING
from shapely.geometry import Polygon
from inire.geometry.components import build_component, component_endpoint, prepare_component_sampling
from inire.model import resolve_bend_geometry
if TYPE_CHECKING:
from inire.geometry.components import BendCollisionModel, BendPhysicalGeometry, ComponentResult, MoveKind
from inire.geometry.primitives import Port
from inire.model import SBendOutline, SearchOptions
@dataclass(frozen=True, slots=True)
class LegacyMoveEvaluator:
"""Evaluate a chosen Manhattan move using the existing primitive geometry."""
collision_type: BendCollisionModel
physical_geometry: BendPhysicalGeometry
clip_margin: float | None
bend_length: float | None
@classmethod
def from_options(
cls, search: SearchOptions, *, collision_override: BendCollisionModel | None = None,
) -> LegacyMoveEvaluator:
proxy, physical = resolve_bend_geometry(search, bend_collision_override=collision_override)
return cls(proxy, physical, search.bend_clip_margin, search.bend_physical_length)
def validate(
self, start: Port, width: float, kind: MoveKind, parameters: tuple, dilation: float, template: SBendOutline | None = None,
) -> Port:
"""Check a seed's endpoint and sampling requirements before allocating geometry."""
end = component_endpoint(start, kind, parameters)
prepare_component_sampling(
kind, parameters, width, collision_type=self.collision_type, physical_geometry_type=self.physical_geometry,
dilation=dilation, sbend_outline=template.polygon if template is not None else None,
)
return end
def evaluate(
self,
start: Port,
width: float,
kind: MoveKind,
parameters: tuple,
dilation: float,
template: SBendOutline | None = None,
*,
bounds: tuple[float, float, float, float] | None = None,
) -> ComponentResult:
return build_component(
start, width, kind, parameters,
collision_type=self.collision_type, physical_geometry_type=self.physical_geometry,
clip_margin=self.clip_margin, dilation=dilation,
sbend_outline=template.polygon if template is not None else None,
physical_length=self.bend_length if kind == "bend90" else (template.length if template is not None else None),
bounds=bounds,
)
def cache_settings(self) -> tuple:
"""Key for geometry caches owned by a routing context that retains the options."""
return (
id(self.collision_type) if isinstance(self.collision_type, Polygon) else self.collision_type,
id(self.physical_geometry) if isinstance(self.physical_geometry, Polygon) else self.physical_geometry,
self.clip_margin,
self.bend_length,
)

View file

@ -2,12 +2,12 @@ from __future__ import annotations
from typing import TYPE_CHECKING
from inire.geometry.components import (
ComponentPreparationError, build_component, component_endpoint, prepare_component_sampling,
)
from inire.model import _AmbiguousSBendOutlineError, resolve_bend_geometry
from inire.geometry.components import ComponentPreparationError
from inire.model import _AmbiguousSBendOutlineError
from inire.seeds import Bend90Seed, SBendSeed, StraightSeed
from ._move_evaluation import LegacyMoveEvaluator
if TYPE_CHECKING:
from inire.geometry.components import ComponentResult, MoveKind
from inire.geometry.primitives import Port
@ -26,16 +26,12 @@ def seed_move(segment: PathSegmentSeed) -> tuple[MoveKind, tuple]:
def seed_preparation_error(seed: PathSeed, *, start: Port, net_width: float, search: SearchOptions, clearance: float) -> str | None:
proxy, physical = resolve_bend_geometry(search)
evaluator = LegacyMoveEvaluator.from_options(search)
for index, segment in enumerate(seed.segments, start=1):
kind, parameters = seed_move(segment)
try:
template = search.sbend_template(segment.offset, segment.radius, net_width) if isinstance(segment, SBendSeed) else None
start = component_endpoint(start, kind, parameters)
prepare_component_sampling(
kind, parameters, net_width, collision_type=proxy, physical_geometry_type=physical,
dilation=clearance / 2, sbend_outline=template.polygon if template is not None else None,
)
start = evaluator.validate(start, net_width, kind, parameters, clearance / 2, template)
except (ComponentPreparationError, OverflowError, _AmbiguousSBendOutlineError) as exc:
return f"segment {index} ({type(segment).__name__}) {exc}"
return None
@ -65,8 +61,7 @@ def materialize_path_seed(
path: list[ComponentResult] = []
current = start
dilation = clearance / 2.0
bend_collision_type, bend_physical_geometry = resolve_bend_geometry(search)
bend_clip_margin = search.bend_clip_margin
evaluator = LegacyMoveEvaluator.from_options(search)
for index, segment in enumerate(seed.segments, start=1):
if component_cache is not None:
@ -79,18 +74,8 @@ def materialize_path_seed(
kind, parameters = seed_move(segment)
try:
template = search.sbend_template(segment.offset, segment.radius, net_width) if isinstance(segment, SBendSeed) else None
component = build_component(
current,
net_width,
kind,
parameters,
collision_type=bend_collision_type,
physical_geometry_type=bend_physical_geometry,
clip_margin=bend_clip_margin,
dilation=dilation,
sbend_outline=template.polygon if template is not None else None,
bounds=None if diagnostic else bounds,
physical_length=search.bend_physical_length if kind == "bend90" else (template.length if template else None),
component = evaluator.evaluate(
current, net_width, kind, parameters, dilation, template, bounds=None if diagnostic else bounds,
)
except (ComponentPreparationError, OverflowError, _AmbiguousSBendOutlineError) as exc:
if diagnostic:

View file

@ -12,12 +12,14 @@ from shapely.geometry import Polygon
from inire.constants import TOLERANCE_LINEAR
from inire.geometry.component_overlap import components_overlap
from inire.geometry.components import (
_bend90_length, bend_fits_width, bend90_grid_span, bend90_uses_circular_geometry, build_component, component_endpoint,
_bend90_length, bend_fits_width, bend90_grid_span, bend90_uses_circular_geometry, component_endpoint,
ComponentPreparationError,
)
from inire.geometry.primitives import port_local_coordinates
from inire.model import resolve_bend_geometry
from ._move_evaluation import LegacyMoveEvaluator
if TYPE_CHECKING:
from collections.abc import Callable, Iterator, Sequence
@ -267,7 +269,7 @@ class PathRefiner:
components: dict[tuple[Port, MoveKind, tuple], ComponentResult],
) -> list[ComponentResult]:
search = self.context.options.search
proxy, physical = resolve_bend_geometry(search)
evaluator = LegacyMoveEvaluator.from_options(search)
dilation = self.collision_engine.clearance / 2.0
path = []
port = start
@ -278,11 +280,7 @@ class PathRefiner:
key = (port, move.move_type, parameters)
component = components.get(key)
if component is None:
component = build_component(
port, width, move.move_type, parameters,
collision_type=proxy, physical_geometry_type=physical, clip_margin=search.bend_clip_margin, dilation=dilation,
physical_length=search.bend_physical_length if move.move_type == "bend90" else None, bounds=bounds,
)
component = evaluator.evaluate(port, width, move.move_type, parameters, dilation, bounds=bounds)
if len(components) < 256:
components[key] = component
path.append(component)

View file

@ -0,0 +1,44 @@
"""The synthetic 4, 5, and 8 µm waveguide technology in the routing plan."""
from shapely.geometry import Polygon, box
from inire._catalog import BendVariant, Catalog, FixedVariant, Grid, Orientation, Pose, Profile, SBendVariant, StraightVariant, Variant
from inire._catalog_timing import DelayModel
GRID = Grid((0, 0), 100, 1e-9)
WAVELENGTH = 1.55e-6
ORIENTATIONS = tuple(Orientation(angle, reflected) for angle in (0, 90, 180, 270) for reflected in (False, True))
TRAVERSALS = (("a", "b"), ("b", "a"))
def synthetic_device_set() -> tuple[Catalog, DelayModel]:
variants: dict[str, Variant] = {
"straight-4": StraightVariant("4", 1.0),
"straight-5": StraightVariant("5", 0.5),
"straight-8": StraightVariant("8", 0.2),
}
for profile, radius, quarter_cost in (("4", 10_000, 0.01), ("8", 100_000, 0.1)):
for turns in (45, 90, 135, 180):
for sign in (-1, 1):
angle = turns * sign
variants[f"bend-{profile}-{angle}"] = BendVariant(
profile, angle, radius, quarter_cost * (2 if turns >= 135 else 1),
max_lead=200, sagitta=10,
)
span, shift = 4 * radius // GRID.pitch, radius // (2 * GRID.pitch)
variants[f"sbend-{profile}"] = SBendVariant(profile, radius, 2 * quarter_cost, ((span, shift), (span, -shift)), sagitta=10)
a = Pose(0, 0, 0, "4")
variants["4-to-5"] = FixedVariant(
"4-to-5", {"a": a, "b": Pose(10_000, 0, 180, "5")},
(Polygon(((0, -2000), (10_000, -2500), (10_000, 2500), (0, 2000))),),
TRAVERSALS, ORIENTATIONS, 0.01, 10_000,
)
variants["4-to-8"] = FixedVariant(
"4-to-8", {"a": a, "b": Pose(100_000, 200, 180, "8")}, (box(0, -5000, 100_000, 5000),),
TRAVERSALS, ORIENTATIONS, 0.2, 100_010,
(Polygon(((0, -2000), (100_000, -3800), (100_000, 4200), (0, 2000))),),
)
profiles = {name: Profile(f"ridge-{name}", int(name) * 1000) for name in ("4", "5", "8")}
timing = DelayModel(WAVELENGTH, group_indices={"4": 4, "5": 4, "8": 2}, variant_delays={"4-to-5": 40_000, "4-to-8": 300_030})
return Catalog("synthetic-4-5-8", profiles, variants), timing

View file

@ -0,0 +1,58 @@
from dataclasses import replace
from math import pi, sqrt
import pytest
from inire._catalog import Move, MoveEvaluator, Pose
from inire._catalog_timing import evaluate_delay
from inire.tests.catalog_device_set import GRID, synthetic_device_set
def test_synthetic_device_set_has_the_expected_rate_radius_and_delay() -> None:
catalog, timing = synthetic_device_set()
evaluator = MoveEvaluator(GRID, catalog)
for name, cost in (("4", 0.1), ("5", 0.05), ("8", 0.02)):
cardinal = evaluator.evaluate(Move(f"straight-{name}", steps=10_000), Pose(0, 0, 0, name))
diagonal = evaluator.evaluate(Move(f"straight-{name}", steps=10_000), Pose(0, 0, 45, name))
assert cardinal is not None
assert diagonal is not None
assert cardinal.cost == pytest.approx(cost)
assert diagonal.cost == pytest.approx(cost * sqrt(2))
for name, radius, cost in (("4", 10_000, 0.01), ("8", 100_000, 0.1)):
for sign in (-1, 1):
spec = Move(f"bend-{name}-{sign * 90}", displacement=(radius, sign * radius))
bend = evaluator.evaluate(spec, Pose(0, 0, 0, name))
assert bend is not None
assert bend.length == pytest.approx(radius * pi / 2)
assert bend.cost == pytest.approx(cost)
shift = evaluator.evaluate(Move(f"sbend-{name}", displacement=(4 * radius, radius // 2)), Pose(0, 0, 0, name))
assert shift is not None
assert shift.cost == pytest.approx(2 * cost)
assert {move.variant for move, _ in evaluator.local_moves("5", 0)} == {"4-to-5"}
for name, other, displacement, length, cost, optical_length in (
("4-to-5", "5", (10_000, 0), 10_000, 0.01, 40_000),
("4-to-8", "8", (100_000, 200), 100_010, 0.2, 300_030),
):
a = Pose(0, 0, 0, "4")
b = Pose(*displacement, 0, other)
for traversal, start, end in ((("a", "b"), a, b), (("b", "a"), b.reversed(), a.reversed())):
piece = evaluator.evaluate(Move(name, traversal=traversal), start)
assert piece is not None
assert piece.end == end
assert piece.length == length
assert piece.cost == cost
delay = evaluate_delay(evaluator, (piece,), timing, net_id=name)
assert delay is not None
assert delay.optical_length == optical_length
displaced = catalog.variants["4-to-8"]
unknown = replace(catalog, variants={**catalog.variants, "4-to-8": replace(displaced, length=None)})
uncharacterized = MoveEvaluator(GRID, unknown)
piece = uncharacterized.evaluate(Move("4-to-8", traversal=("a", "b")), Pose(0, 0, 0, "4"))
assert piece is not None
assert piece.length is None
delay = evaluate_delay(uncharacterized, (piece,), timing, net_id="4-to-8")
assert delay is not None
assert delay.optical_length == 300_030

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