From 7616b398e9237eaafe2640d0cec637daaca6c6c3 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Fri, 4 Dec 2026 09:30:14 -0800 Subject: [PATCH] Implement typed and octagonal catalog routing --- docs/benchmarks.md | 68 ++ docs/user/route-a-layout.md | 39 + inire/_catalog.py | 679 +++++++++++ inire/_catalog_timing.py | 155 +++ inire/geometry/catalog_curve.py | 147 +++ inire/masque.py | 227 ++++ inire/router/_astar_admission.py | 50 +- inire/router/_astar_moves.py | 2 +- inire/router/_astar_types.py | 17 +- inire/router/_catalog_guidance.py | 142 +++ inire/router/_catalog_layout.py | 562 +++++++++ inire/router/_catalog_matching.py | 125 ++ inire/router/_catalog_search.py | 617 ++++++++++ inire/router/_catalog_tuning.py | 183 +++ inire/router/_catalog_verify.py | 260 ++++ inire/router/_move_evaluation.py | 71 ++ inire/router/_seed_materialization.py | 33 +- inire/router/refiner.py | 12 +- inire/tests/catalog_device_set.py | 44 + inire/tests/test_catalog_device_set.py | 58 + inire/tests/test_catalog_moves.py | 1315 +++++++++++++++++++++ inire/tests/test_catalog_search_oracle.py | 153 +++ inire/tests/test_catalog_timing_cases.py | 266 +++++ scripts/benchmark_catalog_routing.py | 312 +++++ scripts/capture_legacy_routing.py | 92 ++ 25 files changed, 5544 insertions(+), 85 deletions(-) create mode 100644 inire/_catalog.py create mode 100644 inire/_catalog_timing.py create mode 100644 inire/geometry/catalog_curve.py create mode 100644 inire/masque.py create mode 100644 inire/router/_catalog_guidance.py create mode 100644 inire/router/_catalog_layout.py create mode 100644 inire/router/_catalog_matching.py create mode 100644 inire/router/_catalog_search.py create mode 100644 inire/router/_catalog_tuning.py create mode 100644 inire/router/_catalog_verify.py create mode 100644 inire/router/_move_evaluation.py create mode 100644 inire/tests/catalog_device_set.py create mode 100644 inire/tests/test_catalog_device_set.py create mode 100644 inire/tests/test_catalog_moves.py create mode 100644 inire/tests/test_catalog_search_oracle.py create mode 100644 inire/tests/test_catalog_timing_cases.py create mode 100644 scripts/benchmark_catalog_routing.py create mode 100644 scripts/capture_legacy_routing.py diff --git a/docs/benchmarks.md b/docs/benchmarks.md index e5aaf11..0eed1ee 100644 --- a/docs/benchmarks.md +++ b/docs/benchmarks.md @@ -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. diff --git a/docs/user/route-a-layout.md b/docs/user/route-a-layout.md index 486daba..9adf02e 100644 --- a/docs/user/route-a-layout.md +++ b/docs/user/route-a-layout.md @@ -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. + ## Route between placed crossings diff --git a/inire/_catalog.py b/inire/_catalog.py new file mode 100644 index 0000000..c904128 --- /dev/null +++ b/inire/_catalog.py @@ -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) diff --git a/inire/_catalog_timing.py b/inire/_catalog_timing.py new file mode 100644 index 0000000..cefee3c --- /dev/null +++ b/inire/_catalog_timing.py @@ -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) diff --git a/inire/geometry/catalog_curve.py b/inire/geometry/catalog_curve.py new file mode 100644 index 0000000..ca0be7d --- /dev/null +++ b/inire/geometry/catalog_curve.py @@ -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 diff --git a/inire/masque.py b/inire/masque.py new file mode 100644 index 0000000..172f8eb --- /dev/null +++ b/inire/masque.py @@ -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", + ) diff --git a/inire/router/_astar_admission.py b/inire/router/_astar_admission.py index c782cb6..b5a8c37 100644 --- a/inire/router/_astar_admission.py +++ b/inire/router/_astar_admission.py @@ -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) diff --git a/inire/router/_astar_moves.py b/inire/router/_astar_moves.py index 593fff1..d74e2dc 100644 --- a/inire/router/_astar_moves.py +++ b/inire/router/_astar_moves.py @@ -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 diff --git a/inire/router/_astar_types.py b/inire/router/_astar_types.py index 1e6ee8c..473eb90 100644 --- a/inire/router/_astar_types.py +++ b/inire/router/_astar_types.py @@ -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), diff --git a/inire/router/_catalog_guidance.py b/inire/router/_catalog_guidance.py new file mode 100644 index 0000000..1a5673d --- /dev/null +++ b/inire/router/_catalog_guidance.py @@ -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 diff --git a/inire/router/_catalog_layout.py b/inire/router/_catalog_layout.py new file mode 100644 index 0000000..726c4df --- /dev/null +++ b/inire/router/_catalog_layout.py @@ -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,)) diff --git a/inire/router/_catalog_matching.py b/inire/router/_catalog_matching.py new file mode 100644 index 0000000..0fed67a --- /dev/null +++ b/inire/router/_catalog_matching.py @@ -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], + ) diff --git a/inire/router/_catalog_search.py b/inire/router/_catalog_search.py new file mode 100644 index 0000000..0fc6219 --- /dev/null +++ b/inire/router/_catalog_search.py @@ -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), + ) diff --git a/inire/router/_catalog_tuning.py b/inire/router/_catalog_tuning.py new file mode 100644 index 0000000..a960619 --- /dev/null +++ b/inire/router/_catalog_tuning.py @@ -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 diff --git a/inire/router/_catalog_verify.py b/inire/router/_catalog_verify.py new file mode 100644 index 0000000..f511f24 --- /dev/null +++ b/inire/router/_catalog_verify.py @@ -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) diff --git a/inire/router/_move_evaluation.py b/inire/router/_move_evaluation.py new file mode 100644 index 0000000..e6c33cf --- /dev/null +++ b/inire/router/_move_evaluation.py @@ -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, + ) diff --git a/inire/router/_seed_materialization.py b/inire/router/_seed_materialization.py index 8fa2ed1..c894b3e 100644 --- a/inire/router/_seed_materialization.py +++ b/inire/router/_seed_materialization.py @@ -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: diff --git a/inire/router/refiner.py b/inire/router/refiner.py index 87ea5b1..2601965 100644 --- a/inire/router/refiner.py +++ b/inire/router/refiner.py @@ -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) diff --git a/inire/tests/catalog_device_set.py b/inire/tests/catalog_device_set.py new file mode 100644 index 0000000..b737673 --- /dev/null +++ b/inire/tests/catalog_device_set.py @@ -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 diff --git a/inire/tests/test_catalog_device_set.py b/inire/tests/test_catalog_device_set.py new file mode 100644 index 0000000..371c7df --- /dev/null +++ b/inire/tests/test_catalog_device_set.py @@ -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 diff --git a/inire/tests/test_catalog_moves.py b/inire/tests/test_catalog_moves.py new file mode 100644 index 0000000..714d4cc --- /dev/null +++ b/inire/tests/test_catalog_moves.py @@ -0,0 +1,1315 @@ +from dataclasses import replace +from math import cos, hypot, pi, radians, sin, sqrt + +import pytest +from scipy.integrate import quad +from shapely.affinity import rotate, translate +from shapely.geometry import LineString, MultiPolygon, Polygon, box + +from inire._catalog import ( + BendVariant, Catalog, Evaluation, FixedVariant, Grid, Move, MoveEvaluator, Orientation, Placement, Pose, Profile, + SBendVariant, StraightVariant, TaperVariant, +) +from inire._catalog_timing import Delay, DelayModel, UniaxialGroupIndex, evaluate_delay +from inire.geometry.catalog_curve import bend_curve +from inire.geometry.components import Bend90 +from inire.geometry.primitives import Port +from inire.masque import Connection, Endpoint, route_and_place +from inire.router._catalog_guidance import AutomaticGrid, CoarseGuidance, find_corridor +from inire.router._catalog_layout import CatalogNet, LayoutSettings, route_layout +from inire.router._catalog_matching import DelayChoice, MatchGroup, choose_match +from inire.router._catalog_search import search_path +from inire.router._catalog_verify import Attachment, compatible_join, replay_moves, verify_path + + +def test_exact_grid_membership_in_adapter_units() -> None: + grid = Grid((30, -20), 100, 1e-9) + assert grid.lattice_position(330, 180) == (3, 2) + assert grid.lattice_position(331, 180) is None + with pytest.raises(TypeError, match="integer layout coordinate"): + grid.lattice_position(330.00000000000006, 180) + + +def test_replay_a_displaced_transition_in_both_directions() -> None: + transition = FixedVariant( + "displaced", {"a": Pose(0, 0, 0, "thin"), "b": Pose(100_000, 200, 180, "wide")}, + (box(0, -5000, 100_000, 5000),), + (("a", "b"), ("b", "a")), (Orientation(), Orientation(180, True)), 0.2, 100_010, + ) + catalog = Catalog("fixture", {"thin": Profile("4 µm", 4000), "wide": Profile("8 µm", 8000)}, { + "displaced": transition, "wide-straight": StraightVariant("wide", 0.2), + }) + evaluator = MoveEvaluator(Grid((0, 0), 100, 1e-9), catalog) + start = Pose(10_000, 20_000, 0, "thin") + moves = ( + Move("displaced", traversal=("a", "b")), + Move("wide-straight", steps=200), + Move("displaced", traversal=("b", "a"), orientation=Orientation(180, True)), + ) + path = replay_moves(evaluator, start, moves) + assert path is not None + first, straight, last = path + assert first.end == Pose(110_000, 20_200, 0, "wide") + assert straight.end == Pose(130_000, 20_200, 0, "wide") + assert last.end == Pose(230_000, 20_000, 0, "thin") + assert last.placement == Placement(Orientation(180, True), 230_000, 20_000) + assert last.footprints[0].equals(box(130_000, 15_000, 230_000, 25_000)) + assert sum(move.cost for move in path) == pytest.approx(0.4004) + + directed = replace(transition, traversals=(("a", "b"),)) + forward_only = MoveEvaluator(evaluator.grid, replace(catalog, variants={**catalog.variants, "displaced": directed})) + with pytest.raises(ValueError, match="Undeclared traversal"): + forward_only.evaluate(moves[-1], straight.end) + + +def test_off_origin_reflected_cell_preserves_ports_and_footprint() -> None: + orientation = Orientation(90, True) + bend = FixedVariant( + "quarter", {"in": Pose(2, 3, 0, "ridge"), "out": Pose(14, 11, 270, "ridge")}, + (box(2, 3, 14, 11),), (("in", "out"),), (orientation,), 2, + ) + evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog("fixture", {"ridge": Profile("ridge", 4)}, {"quarter": bend})) + result = evaluator.evaluate(Move("quarter", traversal=("in", "out"), orientation=orientation), Pose(43, 52, 90, "ridge")) + assert result is not None + assert result.end == Pose(51, 64, 0, "ridge") + assert result.placement == Placement(orientation, 40, 50) + assert result.footprints[0].equals(box(43, 52, 51, 64)) + + +def test_diagonal_straight_cost_and_taper_stretch() -> None: + evaluator = MoveEvaluator( + Grid((0, 0), 100, 1e-9), + Catalog("fixture", {"thin": Profile("ridge", 4000), "wide": Profile("ridge", 5000)}, { + "straight": StraightVariant("thin", 1), + "long": TaperVariant("thin", "wide", 10_000, 0.01), + "short": TaperVariant("thin", "wide", 2000, 0.01), + "characterized": TaperVariant("thin", "wide", 2000, 0.01, max_stretch=0.07), + }), + ) + start = Pose(0, 0, 45, "thin") + straight = evaluator.evaluate(Move("straight", steps=10_000), start) + assert straight is not None + assert straight.cost == pytest.approx(0.1 * sqrt(2)) + long_taper = evaluator.evaluate(Move("long"), straight.end) + assert long_taper is not None + assert long_taper.end == Pose(1_007_100, 1_007_100, 45, "wide") + assert evaluator.evaluate(Move("short"), start) is None + shorter = evaluator.evaluate(Move("characterized"), start) + assert shorter is not None + assert shorter.length == pytest.approx(1500 * sqrt(2)) + assert shorter.start.profile == "thin" + assert shorter.end.profile == "wide" + timing = DelayModel(1.55e-6, variant_delays={"characterized": 7000}) + delay = evaluate_delay(evaluator, (shorter,), timing, net_id="taper") + assert delay is not None + assert delay.optical_length == 7000 + assert verify_path(evaluator, (shorter,), start, shorter.end, board=box(-10_000, -10_000, 2e6, 2e6)) is None + assert verify_path(evaluator, (straight, long_taper), start, long_taper.end, board=box(-10_000, -10_000, 2e6, 2e6)) is None + + +def test_replay_checks_poses_and_reserves_the_finite_seam() -> None: + input_port = Pose(-2, 0, 0, "guide") + joint = Pose(0, 0, 0, "guide") + target = Pose(2, 0, 0, "guide") + evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog("fixture", {"guide": Profile("guide", 2)}, {})) + board = box(-3, -3, 3, 3) + first = Evaluation(Move("in"), input_port, joint, (box(-2, -1, -0.001, 1),), 2, 1) + second = Evaluation(Move("out"), joint, target, (box(0.001, -1, 2, 1),), 2, 1) + path = (first, second) + assert verify_path(evaluator, path, input_port, target, board=board, face_tolerance=0.002) is None + strip = box(-0.00025, -2, 0.00025, 2) + assert verify_path(evaluator, path, input_port, target, board=board, occupied=(strip,), face_tolerance=0.002) == "occupied_seam" + gap = (replace(first, footprints=(box(-2, -1, -0.004, 1),)), replace(second, footprints=(box(0.004, -1, 2, 1),))) + assert verify_path(evaluator, gap, input_port, target, board=board, face_tolerance=0.002) == "port_face" + assert not compatible_join(first, replace(second, start=joint.shifted(1, 0)), 2, 0.002) + + +@pytest.fixture +def asymmetric_fixture(): + grid = Grid((0, 0), 100, 1e-9) + transition = FixedVariant( + "transition", {"wide": Pose(0, 0, 0, "5"), "thin": Pose(10_000, 0, 180, "4")}, + (Polygon(((0, -2500), (10_000, -2000), (10_000, 2000), (0, 2500))),), + (("wide", "thin"), ("thin", "wide")), (Orientation(), Orientation(270)), 0.01, 10_000, + ) + thin_arc = Bend90.generate(Port(4000, 0, 0), 8000, 4000, "CCW", sagitta=2) + bend = FixedVariant( + "asymmetric", {"a": Pose(0, 0, 0, "4"), "b": Pose(12_000, 8000, 270, "4")}, + (box(0, -2000, 4000, 2000), *thin_arc.physical_geometry), + (("a", "b"),), (Orientation(),), 0.01, 4000 + 4000 * pi, + ) + evaluator = MoveEvaluator(grid, Catalog("fixture", {"4": Profile("4 µm", 4000), "5": Profile("5 µm", 5000)}, { + "4-straight": StraightVariant("4", 1), + "5-straight": StraightVariant("5", 0.5), + "bend": bend, + "transition": transition, + })) + start = Pose(20_000, 30_000, 0, "5") + target = Pose(70_000, 75_000, 90, "5") + kwargs = { + "board": box(0, 0, 100_000, 100_000), + "keepouts": (box(57_000, 37_000, 59_000, 39_000),), + "clearance": 1000, + "face_tolerance": 2, + } + return evaluator, start, target, kwargs + + +def test_search_proposes_a_straight_to_an_unequal_setback_bend(asymmetric_fixture) -> None: + evaluator, start, target, kwargs = asymmetric_fixture + known = replay_moves(evaluator, start, ( + Move("5-straight", steps=280), + Move("transition", traversal=("wide", "thin")), + Move("bend", traversal=("a", "b")), + Move("transition", traversal=("thin", "wide"), orientation=Orientation(270)), + Move("5-straight", steps=270), + )) + assert known is not None + assert verify_path(evaluator, known, start, target, **kwargs) is None + result = search_path(evaluator, start, target, **kwargs) + assert result.path is not None, result + [corner] = [part for part in result.path if part.move.variant == "bend"] + assert corner.start == Pose(58_000, 30_000, 0, "4") + assert corner.end == Pose(70_000, 38_000, 90, "4") + assert [part.move.traversal for part in result.path if part.move.variant == "transition"] == [("wide", "thin"), ("thin", "wide")] + assert verify_path(evaluator, result.path, start, target, **kwargs) is None + assert replay_moves(evaluator, start, tuple(part.move for part in result.path)) == result.path + + +def test_search_finds_only_legal_interior_launch_for_displaced_transition() -> None: + a = Pose(2, 4, 0, "a") + b = Pose(28, 8, 0, "b") + transition = FixedVariant( + "displaced", {"in": Pose(0, 0, 0, "a"), "out": Pose(8, 4, 180, "b")}, + (Polygon(((0, -1), (8, 3), (8, 5), (0, 1))),), + (("in", "out"),), (Orientation(),), 0.2, + ) + evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog( + "launch", {"a": Profile("ridge", 2), "b": Profile("ridge", 2)}, { + "a-straight": StraightVariant("a", 1), "b-straight": StraightVariant("b", 1), "transition": transition, + }, + )) + result = search_path( + evaluator, a, b, board=box(0, 0, 30, 12), keepouts=(box(0, 5, 10, 12), box(18, 0, 30, 7)), + node_limit=50, + ) + assert result.outcome == "verified" + assert result.path is not None + [change] = [part for part in result.path if part.move.variant == "transition"] + assert change.start == Pose(10, 4, 0, "a") + assert change.end == Pose(18, 8, 0, "b") + + +@pytest.mark.parametrize(("distance", "transition_cost", "reversible", "count", "cost"), [ + (370, 0.010, True, 0, 0.037), + (380, 0.010, True, None, 0.038), + (390, 0.010, True, 2, 0.0385), + (390, 0.012, True, 0, 0.039), + (390, 0.010, False, 0, 0.039), +]) +def test_search_uses_catalog_cost_for_profile_tradeoffs(distance, transition_cost, reversible, count, cost) -> None: + directions = (("in", "out"), ("out", "in")) if reversible else (("in", "out"),) + transition = FixedVariant( + "centered", {"in": Pose(0, 0, 0, "4"), "out": Pose(10_000, 0, 180, "5")}, + (Polygon(((0, -2000), (10_000, -2500), (10_000, 2500), (0, 2000))),), + directions, (Orientation(), Orientation(180)), transition_cost, 10_000, + ) + evaluator = MoveEvaluator(Grid((0, 0), 100, 1e-9), Catalog( + "cost", {"4": Profile("4 µm", 4000), "5": Profile("5 µm", 5000)}, { + "4-straight": StraightVariant("4", 1), "5-straight": StraightVariant("5", 0.5), "transition": transition, + }, + )) + start = Pose(10_000, 10_000, 0, "4") + end = Pose(start.x + distance * 1000, start.y, 0, "4") + result = search_path(evaluator, start, end, board=box(0, 0, 500_000, 20_000), node_limit=1000) + assert result.outcome == "verified" + assert result.path is not None + if count is not None: + assert sum(part.move.variant == "transition" for part in result.path) == count + assert sum(part.cost for part in result.path) == pytest.approx(cost) + + +@pytest.fixture +def masque_4a3(): + masque = pytest.importorskip("masque") + if masque.__version__ != "4.0a3": + pytest.skip("The Masque integration fixture uses 4.0a3") + return masque + + +def test_masque_route_places_verified_references_and_consumes_terminal_names(masque_4a3, asymmetric_fixture) -> None: + evaluator, start, target, kwargs = asymmetric_fixture + masque = masque_4a3 + layer = 7 + cells = {} + for variant in evaluator.catalog.variants.values(): + if isinstance(variant, FixedVariant): + pattern = masque.Pattern(ports={ + name: masque.Port((port.x, port.y), rotation=radians(port.heading)) + for name, port in variant.ports.items() + }) + for shape in variant.footprints: + pattern.polygon(layer, vertices=shape.exterior.coords[:-1]) + cells[variant.cell] = pattern + source = masque.Port((start.x, start.y), rotation=pi) + destination = masque.Port((target.x, target.y), rotation=pi / 2) + layout = masque.Pattern(ports={"source": source, "destination": destination, "other": source.copy()}) + request = (Connection("typed", Endpoint("source", "5"), Endpoint("destination", "5")),) + result = route_and_place(layout, cells, request, catalog=evaluator.catalog, grid=evaluator.grid, layer=layer, **kwargs) + assert result.placed == ("typed",) + assert tuple(layout.ports) == ("other",) + [bend] = layout.refs["asymmetric"] + assert tuple(bend.offset) == (58_000, 30_000) + assert bend.rotation == 0 + assert not bend.mirrored + assert len(layout.refs["transition"]) == 2 + assert result.routes["typed"].path is not None + generated = [part.footprints[0] for part in result.routes["typed"].path if part.placement is None] + assert len(layout.shapes[layer]) == len(generated) + for placed, expected in zip(layout.shapes[layer], generated, strict=True): + assert Polygon(placed.vertices + placed.offset).equals(expected) + + + blocked = masque.Pattern(ports={"source": source.copy(), "destination": destination.copy()}) + blocking_geometry = (*kwargs["keepouts"], box(62_000, 29_500, 62_500, 30_500)) + blocked_result = route_and_place( + blocked, cells, request, catalog=evaluator.catalog, grid=evaluator.grid, layer=layer, + **{**kwargs, "keepouts": blocking_geometry}, + ) + assert blocked_result.placed == () + assert tuple(blocked.ports) == ("source", "destination") + assert not blocked.shapes + assert not blocked.refs + + restricted = masque.Pattern(ports={"source": source.copy(), "destination": destination.copy()}) + variants = dict(evaluator.catalog.variants) + variants["transition"] = replace(variants["transition"], traversals=(("thin", "wide"),)) + restricted_result = route_and_place( + restricted, cells, request, catalog=replace(evaluator.catalog, variants=variants), grid=evaluator.grid, layer=layer, **kwargs, + ) + assert restricted_result.routes["typed"].path is None + assert restricted_result.outcome == "partial" + assert tuple(restricted.ports) == ("source", "destination") + + +@pytest.mark.parametrize("require_complete", [False, True]) +def test_masque_partial_placement_leaves_unrouted_port_names(masque_4a3, require_complete) -> None: + masque = masque_4a3 + layout = masque.Pattern(ports={ + "a": masque.Port((2, 4), rotation=pi), + "b": masque.Port((18, 4), rotation=0), + "c": masque.Port((2, 8), rotation=pi), + "d": masque.Port((18, 8), rotation=0), + }) + catalog = Catalog("placement", {"w": Profile("ridge", 2)}, {"straight": StraightVariant("w", 1)}) + routes = ( + Connection("clear", Endpoint("a", "w"), Endpoint("b", "w")), + Connection("blocked", Endpoint("c", "w"), Endpoint("d", "w")), + ) + result = route_and_place( + layout, {}, routes, catalog=catalog, grid=Grid((0, 0), 1, 1e-6), board=box(0, 0, 20, 12), + layer=1, keepouts=(box(9, 6, 11, 10),), require_complete=require_complete, + ) + assert result.routes["clear"].outcome == "verified" + assert result.routes["blocked"].outcome == "exhausted" + if require_complete: + assert tuple(layout.ports) == ("a", "b", "c", "d") + assert result.placed == () + assert not layout.shapes + else: + assert tuple(layout.ports) == ("c", "d") + assert result.placed == ("clear",) + assert len(layout.shapes[1]) == 1 + + +def test_fixed_attachment_accepts_split_approach_checks_clearance_and_rejects_shelf() -> None: + evaluator = MoveEvaluator(Grid((0, 0), 100, 1e-9), Catalog( + "attachment", {"4": Profile("ridge", 4000)}, {"s": StraightVariant("4", 1)}, + )) + start, target = Pose(0, 0, 0, "4"), Pose(10_000, 0, 0, "4") + bounds = box(-11_000, -10_000, 11_000, 10_000) + fixed = box(-10_000, -2000, 0, 2000) + region = box(-2000, -3000, 2000, 3000) + attachment = Attachment(fixed, region) + common = {"board": bounds, "clearance": 1000, "keepouts": (fixed,)} + full = replay_moves(evaluator, start, (Move("s", steps=100),)) + split = replay_moves(evaluator, start, tuple(Move("s", steps=n) for n in (5, 25, 70))) + assert full is not None + assert split is not None + assert verify_path(evaluator, full, start, target, **common) == "keepout" + assert search_path(evaluator, start, target, **common).outcome == "exhausted" + assert search_path(evaluator, start, target, source_attachment=attachment, **common).outcome == "verified" + assert verify_path(evaluator, full, start, target, source_attachment=attachment, **common) is None + assert verify_path(evaluator, split, start, target, source_attachment=attachment, self_clearance=3000, **common) is None + short = replace(attachment, region=box(-2000, -3000, 500, 3000)) + assert verify_path(evaluator, split, start, target, source_attachment=short, **common) == "fixed_attachment" + + shelving = MultiPolygon((fixed, box(300, 1500, 700, 2000))) + assert verify_path( + evaluator, full, start, target, board=bounds, clearance=1000, keepouts=(shelving,), + source_attachment=Attachment(shelving, region), + ) == "fixed_attachment" + reverse = search_path(evaluator, target.reversed(), start.reversed(), destination_attachment=attachment, **common) + assert reverse.outcome == "verified" + + +def test_delay_reporting_respects_actual_travel_direction_and_wavelength() -> None: + evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog( + "timing", {"guide": Profile("ridge", 4)}, {"s": StraightVariant("guide", 1)}, + )) + east = replay_moves(evaluator, Pose(0, 0, 0, "guide"), (Move("s", steps=20),)) + west = replay_moves(evaluator, Pose(20, 0, 180, "guide"), (Move("s", steps=20),)) + assert east is not None + assert west is not None + + def modal_index(wavelength, angle): + return (3 if wavelength == 1.55e-6 else 4) + 0.5 * cos(angle) + + model = DelayModel(1.55e-6, group_indices={"guide": modal_index}) + east_delay = evaluate_delay(evaluator, east, model, net_id="east") + west_delay = evaluate_delay(evaluator, west, model, net_id="west") + assert east_delay is not None + assert west_delay is not None + assert east_delay.optical_length == 70 + assert east_delay.seconds == pytest.approx(70e-6 / 299_792_458) + assert west_delay.optical_length == 50 + different_wavelength = evaluate_delay(evaluator, east, replace(model, wavelength=1.5e-6), net_id="east") + assert different_wavelength is not None + assert different_wavelength.optical_length == 90 + diagonal_process = DelayModel(1.55e-6, process_angle=pi / 4, group_indices={"guide": UniaxialGroupIndex(4, 2)}) + for path in (east, west): + delay = evaluate_delay(evaluator, path, diagonal_process, net_id="route") + assert delay is not None + assert delay.optical_length == pytest.approx(60) + + +@pytest.mark.parametrize(("cap", "available"), [(110.0, True), (100.0, False)]) +def test_generated_45_degree_bend_uses_tangent_leads(cap, available) -> None: + grid = Grid((0, 0), 100, 1e-9) + bend = BendVariant("guide", 45, 10_000, 0.01, max_lead=cap, lead_cost_per_cm=1, sagitta=2) + evaluator = MoveEvaluator(grid, Catalog("circular", {"guide": Profile("ridge", 4000)}, {"bend": bend})) + start = Pose(0, 0, 0, "guide") + target = Pose(7200, 3000, 45, "guide") + matching = [move for move in evaluator.bend_moves("bend", 0, bend) if move.displacement == (7200, 3000)] + assert bool(matching) == available + if available: + [move] = matching + assert move.leads == pytest.approx((57.864376, 100.505063)) + result = search_path(evaluator, start, target, board=box(-4000, -4000, 20_000, 20_000), face_tolerance=0.002) + assert result.path is not None + [evaluated] = result.path + assert evaluated.length == pytest.approx(2500 * pi + sum(move.leads)) + assert evaluated.cost == pytest.approx(0.01 + sum(move.leads) / 1e7) + assert evaluated.end == target + + +@pytest.mark.parametrize(("floor", "expected"), [(5000, 1.0), (8000, "partial"), (10_000, 0.0), (11_000, None)]) +def test_euler_fraction_satisfies_minimum_radius_and_preserves_ports(floor, expected) -> None: + bend = BendVariant("guide", 90, 10_000, 0.01, minimum_radius=floor, euler_fraction=None, sagitta=2) + evaluator = MoveEvaluator( + Grid((0, 0), 100, 1e-9), Catalog("euler", {"guide": Profile("ridge", 4000)}, {"bend": bend}), + ) + start = Pose(0, 0, 0, "guide") + moves = evaluator.bend_moves("bend", 0, bend) + if expected is None: + assert moves == () + return + [move] = moves + result = evaluator.evaluate(move, start) + assert result is not None + assert result.end == Pose(10_000, 10_000, 90, "guide") + assert result.minimum_radius is not None + assert result.minimum_radius == pytest.approx(1 / max( + max(abs(section.entry_curvature), abs(section.exit_curvature)) for section in result.curve_sections + )) + assert result.minimum_radius >= floor - 1e-8 + if expected == "partial": + assert result.euler_fraction is not None + assert 0 < result.euler_fraction < 1 + assert result.minimum_radius == pytest.approx(floor) + else: + assert result.euler_fraction == expected + + +def test_generated_uturn_preserves_distinct_leads_at_same_ports(monkeypatch) -> None: + bend = BendVariant("guide", 180, 10_000, 0.01, max_lead=2000, sagitta=2) + evaluator = MoveEvaluator( + Grid((0, 0), 100, 1e-9), Catalog("turnaround", {"guide": Profile("ridge", 400)}, { + "bend": bend, "quarter": BendVariant("guide", 90, 10_000, 0.001, sagitta=2), + }), + ) + assert evaluator.bend_moves("bend", 45, bend) == () + no_leads = replace(bend, max_lead=0) + assert evaluator.bend_moves("no-leads", 45, no_leads) == () + start = Pose(0, 0, 0, "guide") + target = Pose(0, 20_000, 180, "guide") + choices = [move for move in evaluator.bend_moves("bend", 0, bend) if move.displacement == (0, 20_000)] + assert [move.leads for move in choices] == [(0.0, 0.0), (2000.0, 2000.0)] + replay_only = Move("bend", displacement=(0, 20_000), leads=(1000, 1000)) + assert replay_only not in choices + evaluated = evaluator.evaluate(replay_only, start) + assert evaluated is not None + assert evaluated.length == pytest.approx(10_000 * pi + 2000) + assert evaluator.evaluate(replace(replay_only, leads=(1000, 900)), start) is None + result = search_path( + evaluator, start, target, board=box(-1000, -1000, 15_000, 21_000), + keepouts=(box(9900, 9900, 10_100, 10_100),), clearance=250, + ) + assert result.path is not None + assert result.path[0].move == choices[1] + two_turns = replay_moves(evaluator, start, ( + Move("quarter", displacement=(10_000, 10_000)), Move("quarter", displacement=(-10_000, 10_000)), + )) + assert two_turns is not None + check = {"board": box(-1000, -1000, 15_000, 21_000), "clearance": 250} + assert verify_path(evaluator, two_turns, start, target, **check) is None + assert verify_path(evaluator, two_turns, start, target, keepouts=(box(9900, 9900, 10_100, 10_100),), **check) == "keepout" + + reverse_evaluator = MoveEvaluator(evaluator.grid, evaluator.catalog) + natural_order = reverse_evaluator.bend_moves + monkeypatch.setattr(reverse_evaluator, "bend_moves", lambda *args: tuple(reversed(natural_order(*args)))) + reversed_result = search_path( + reverse_evaluator, start, target, board=box(-1000, -1000, 15_000, 21_000), + keepouts=(box(9900, 9900, 10_100, 10_100),), clearance=250, + ) + assert reversed_result.path == result.path + + +@pytest.mark.parametrize("sign", [1, -1]) +def test_rotated_process_delay_integrates_the_curved_tangent(sign) -> None: + bend = BendVariant("guide", sign * 90, 10, 0.01) + evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog( + "curve-timing", {"guide": Profile("ridge", 4)}, {"bend": bend}, + )) + path = replay_moves(evaluator, Pose(0, 0, 0, "guide"), evaluator.bend_moves("bend", 0, bend)) + assert path is not None + model = DelayModel(1.55e-6, process_angle=pi / 4, group_indices={"guide": UniaxialGroupIndex(4, 2)}) + delay = evaluate_delay(evaluator, path, model, net_id="curve") + assert delay is not None + assert delay.optical_length == pytest.approx(15 * pi + sign * 10) + + +def test_match_tolerance_accepts_a_cheaper_nonzero_skew() -> None: + pose = Pose(0, 0, 0, "guide") + + def choice(optical_length, cost): + path = (Evaluation(Move("s"), pose, pose, (), 1, cost),) + return DelayChoice(path, Delay(optical_length, optical_length * 1e-6 / 299_792_458)) + + group = MatchGroup("tolerance", {"ref": 0, "tuned": 0}, 1.55e-6, 0.05) + reference = choice(400, 0) + alternatives = [choice(400, 3), choice(400.05, 2), choice(400.06, 1)] + for order in (alternatives, alternatives[::-1]): + choices = {"ref": (reference,), "tuned": order} + selected, skew, matched = choose_match(group, choices) + assert matched + assert skew == pytest.approx(0.05) + assert selected["tuned"] == alternatives[1] + stricter, skew, matched = choose_match(replace(group, tolerance=0.04), choices) + assert matched + assert skew == 0 + assert stricter["tuned"] == alternatives[0] + + +@pytest.mark.parametrize(("window_height", "expected", "case"), [ + (155_000, "matched", "nominal"), + (123_000, "unmatched", "nominal"), + (None, "unmatched", "nominal"), + (155_000, "unmatched", "between-settings"), + (152_000, "unmatched", "lower-delay"), +]) +def test_match_uses_only_supplied_tuning_space(window_height, expected, case) -> None: + evaluator = MoveEvaluator(Grid((0, 0), 100, 1e-9), Catalog( + "detour", {"guide": Profile("ridge", 4000)}, { + "s": StraightVariant("guide", 1), + "left": BendVariant("guide", 90, 10_000, 0.01, sagitta=2), + "right": BendVariant("guide", -90, 10_000, 0.01, sagitta=2), + }, + )) + fixed = box(15_000, 118_000, 20_000, 122_000) + access = Attachment(fixed, box(18_000, 117_000, 22_000, 123_000)) + nets = { + name: CatalogNet( + Pose(20_000, y, 0, "guide"), Pose(140_000, y, 0, "guide"), + source_attachment=access if name == "adjust" else None, seed=(Move("s", steps=1200),), + ) + for name, y in (("reference", 40_000), ("adjust", 120_000)) + } + overrides = {"left": 1, "right": 1} if case == "lower-delay" else {} + model = DelayModel(1.55e-6, group_indices={"guide": 4}, fixed_contributions={"adjust": (20_000,)}, bend_group_indices=overrides) + extra = 400 if case == "between-settings" else 0 + group = MatchGroup("delay", {"reference": 0, "adjust": (80 * pi - 60) * 1000 + extra}, 1.55e-6, 50) + settings = LayoutSettings(box(0, 0, 400_000, 300_000), (fixed,), clearance=1000, node_limit=0) + windows = {} if window_height is None else {"adjust": box(40_000, 117_000, 100_000, window_height)} + result = route_layout(evaluator, nets, settings, timing=model, groups=(group,), windows=windows) + match = result.matching["delay"] + assert match.status == expected + assert result.routes["adjust"].path is not None + assert result.routes["reference"].path is not None + if expected == "matched": + assert result.completed == ("reference", "adjust") + assert match.skew == pytest.approx(0, abs=1e-6) + assert sum(part.move.variant in ("left", "right") for part in result.routes["adjust"].path) == 4 + assert match.delays["adjust"].optical_length == pytest.approx((420 + 80 * pi) * 1000) + else: + assert result.completed == () + if case == "between-settings": + assert match.skew == pytest.approx(400) + assert sum(part.move.variant in ("left", "right") for part in result.routes["adjust"].path) == 4 + else: + assert match.skew == pytest.approx((80 * pi - 80) * 1000) + assert len(result.routes["adjust"].path) == 1 + if case == "lower-delay": + assert match.verified_replacements > 0 + + +def test_diagonal_sbend_rejects_wrong_parity_and_uses_lobe_radius_floor() -> None: + bend = SBendVariant("guide", 1000, 1, ((50, 5), (51, 5), (52, 6)), minimum_radius=800, euler_fraction=None, sagitta=2) + evaluator = MoveEvaluator(Grid((0, 0), 100, 1e-9), Catalog( + "shift", {"guide": Profile("ridge", 400)}, {"s": bend}, + )) + candidates = evaluator.local_moves("guide", 45) + [unavailable] = evaluator.unavailable + assert unavailable.reason == "off_grid_projections" + assert unavailable.projections == (50, 5) + assert [end for _, end in candidates] == [Pose(2300, 2800, 45, "guide"), Pose(2300, 2900, 45, "guide")] + target = Pose(2300, 2800, 45, "guide") + result = search_path(evaluator, Pose(0, 0, 45, "guide"), target, board=box(-1000, -1000, 4000, 4000)) + assert result.path is not None + [evaluated] = result.path + assert evaluated.minimum_radius == pytest.approx(800) + assert evaluated.end == target + + +def test_unmatched_group_releases_window_for_independent_net() -> None: + evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog( + "retry", {"guide": Profile("ridge", 2)}, {"s": StraightVariant("guide", 1)}, + )) + nets = { + "mixed-a": CatalogNet(Pose(10, 10, 0, "guide"), Pose(90, 10, 0, "guide")), + "mixed-b": CatalogNet(Pose(10, 30, 0, "guide"), Pose(90, 30, 0, "guide")), + "independent": CatalogNet(Pose(10, 40, 0, "guide"), Pose(90, 40, 0, "guide")), + } + windows = {"mixed-b": box(20, 25, 80, 45)} + model = DelayModel(1.55e-6, group_indices={"guide": 4}) + group = MatchGroup("miss", {"mixed-a": 0, "mixed-b": 1}, 1.55e-6, 0) + settings = LayoutSettings(box(0, 0, 100, 50), refinement=False) + args = {"timing": model, "groups": (group,), "windows": windows} + partial = route_layout(evaluator, nets, settings, **args) + assert partial.completed == ("independent",) + assert partial.routes["mixed-a"].path is not None + assert partial.routes["mixed-b"].path is not None + assert partial.matching["miss"].status == "unmatched" + complete = route_layout(evaluator, nets, settings, require_complete=True, **args) + assert complete.completed == () + assert complete.routes["independent"].path is None + # Reporting alone leaves the overlapping window inactive. + reporting = route_layout(evaluator, nets, settings, timing=model, windows=windows) + baseline = route_layout(evaluator, nets, settings) + assert reporting.routes == baseline.routes + assert reporting.completed == baseline.completed + + +def test_masque_preflights_duplicate_terminal_assignments(masque_4a3) -> None: + masque = masque_4a3 + ports = { + "a": masque.Port((2, 4), rotation=pi), + "b": masque.Port((18, 4), rotation=0), + "c": masque.Port((18, 8), rotation=0), + } + layout = masque.Pattern(ports=ports) + catalog = Catalog("preflight", {"w": Profile("ridge", 2)}, {"s": StraightVariant("w", 1)}) + with pytest.raises(ValueError, match="Duplicate routing terminal 'a'"): + route_and_place( + layout, {}, ( + Connection("first", Endpoint("a", "w"), Endpoint("b", "w")), + Connection("second", Endpoint("a", "w"), Endpoint("c", "w")), + ), catalog=catalog, grid=Grid((0, 0), 1, 1e-6), board=box(0, 0, 20, 12), layer=1, + ) + assert tuple(layout.ports) == ("a", "b", "c") + assert not layout.shapes + assert not layout.refs + + +@pytest.mark.parametrize("require_complete", [False, True]) +def test_masque_propagates_execution_failure_and_stops_placing(masque_4a3, monkeypatch, require_complete) -> None: + masque = masque_4a3 + ports = { + f"{name}{y}": masque.Port((x, y), rotation=angle) + for y in (4, 8, 12) for name, x, angle in (("a", 2, pi), ("b", 18, 0)) + } + layout = masque.Pattern(ports=ports) + catalog = Catalog("fatal", {"w": Profile("ridge", 2)}, {"s": StraightVariant("w", 1)}) + connections = tuple(Connection(str(y), Endpoint(f"a{y}", "w"), Endpoint(f"b{y}", "w")) for y in (4, 8, 12)) + write = masque.Pattern.polygon + calls = 0 + + def fail_on_second(pattern, layer, *args, **kwargs): + nonlocal calls + calls += 1 + if calls == 2: + raise RuntimeError("Injected placement failure") + return write(pattern, layer, *args, **kwargs) + + monkeypatch.setattr(masque.Pattern, "polygon", fail_on_second) + with pytest.raises(RuntimeError, match="Injected placement failure"): + route_and_place( + layout, {}, connections, catalog=catalog, grid=Grid((0, 0), 1, 1e-6), + board=box(0, 0, 20, 16), layer=1, require_complete=require_complete, + ) + assert calls == 2 + assert tuple(layout.ports) == ("a8", "b8", "a12", "b12") + assert len(layout.shapes[1]) == 1 + + +@pytest.fixture +def off_coarse_transition() -> tuple[Catalog, Pose, Pose]: + start = Pose(20_001, 30_001, 0, "4") + target = Pose(170_001, 30_201, 0, "8") + profiles = {"4": Profile("ridge4", 4000), "8": Profile("ridge8", 8000)} + physical = Polygon(((0, -2000), (100_000, -3800), (100_000, 4200), (0, 2000))) + transition = FixedVariant( + "displaced", {"a": Pose(0, 0, 0, "4"), "b": Pose(100_000, 200, 180, "8")}, + (physical,), (("a", "b"),), (Orientation(),), 0.2, 100_010, + ) + return Catalog("coarse", profiles, {"s4": StraightVariant("4", 1), "s8": StraightVariant("8", 0.2), "t": transition}), start, target + + +@pytest.mark.parametrize("pitch", [1000, 10_000]) +def test_coarse_corridor_realizes_a_transition_at_exact_terminal_poses(off_coarse_transition, pitch) -> None: + catalog, start, target = off_coarse_transition + nets = {"off-coarse": CatalogNet(start, target)} + fine = MoveEvaluator(Grid((0, 0), 1, 1e-9), catalog) + coarse = MoveEvaluator(Grid((start.x, start.y), pitch, 1e-9), catalog) + board = box(0, 0, 200_000, 80_000) + assert coarse.grid.lattice_position(target.x, target.y) is None + with pytest.raises(ValueError, match="invalid terminal"): + route_layout(coarse, nets, LayoutSettings(board)) + settings = LayoutSettings(board, node_limit=100, guidance=CoarseGuidance(pitch)) + open_run = route_layout(fine, nets, settings).routes["off-coarse"] + assert open_run.path is not None + assert open_run.used_guidance + assert open_run.path[0].start == start + assert open_run.path[-1].end == target + [transition] = [part for part in open_run.path if part.move.variant == "t"] + assert transition.end.y - transition.start.y == 200 + assert verify_path(fine, open_run.path, start, target, board=board) is None + + # Block the selected transition while leaving generous physical board space. + x = transition.start.x + 50_000 + obstacle = box(x, transition.start.y - 500, x + 1_000, transition.start.y + 500) + assert verify_path(fine, open_run.path, start, target, board=board, keepouts=(obstacle,)) == "keepout" + retry = route_layout(fine, nets, replace(settings, keepouts=(obstacle,))).routes["off-coarse"] + if retry.path is not None: + assert retry.path != open_run.path + assert verify_path(fine, retry.path, start, target, board=board, keepouts=(obstacle,)) is None + else: + assert retry.outcome in ("exhausted", "node_limit") + + +def test_automatic_grid_uses_port_differences_and_authored_displacements(off_coarse_transition) -> None: + catalog, start, target = off_coarse_transition + selected = AutomaticGrid(1000, 1e-9).select((start, target), catalog) + assert selected == Grid((20_001, 30_001), 200, 1e-9) + assert AutomaticGrid(1000, 1e-9).select((start, replace(target, x=target.x + 1)), catalog).pitch == 1 + assert AutomaticGrid(1000, 1e-9).select((start,), catalog).pitch == 200 + + +def test_coarse_corridor_uses_sparse_search_around_an_obstacle() -> None: + board = box(0, 0, 80, 80) + obstacle = box(33, 25, 47, 55) + a, b = Pose(10, 40, 0, "wide"), Pose(70, 40, 0, "wide") + guide, expanded = find_corridor(a, b, CoarseGuidance(5), board=board, obstacles=(obstacle,), margin=2) + assert guide is not None + assert expanded > 0 + assert len(guide.points) > 2 + assert guide.points[0] == (10, 40) + assert guide.points[-1] == (70, 40) + no_guide, limited = find_corridor(a, b, CoarseGuidance(5, node_limit=1), board=board, obstacles=(obstacle,), margin=2) + assert no_guide is None + assert limited == 1 + + +@pytest.mark.parametrize("condition", ["enabled", "disabled", "keepout", "matching", "budget"]) +def test_catalog_refinement_keeps_the_incumbent_until_a_cheaper_layout_verifies(condition) -> None: + transition = FixedVariant( + "centered", {"a": Pose(0, 0, 0, "4"), "b": Pose(10_000, 0, 180, "5")}, + (Polygon(((0, -2000), (10_000, -2500), (10_000, 2500), (0, 2000))),), + (("a", "b"), ("b", "a")), (Orientation(), Orientation(180)), 0.01, 10_000, + ) + evaluator = MoveEvaluator(Grid((0, 0), 100, 1e-9), Catalog( + "refine", {"4": Profile("thin", 4000), "5": Profile("wide", 5000)}, + {"4": StraightVariant("4", 1), "5": StraightVariant("5", 0.5), "change": transition}, + )) + seed = (Move("4", steps=3900),) + nets = { + name: CatalogNet(Pose(10_000, y, 0, "4"), Pose(400_000, y, 0, "4"), seed=seed) + for name, y in (("lane", 10_000), ("peer", 25_000)) + } + keepouts = (box(0, 12_250, 420_000, 12_800),) if condition == "keepout" else () + settings = LayoutSettings( + box(0, 0, 420_000, 35_000), keepouts, node_limit=100, refinement=condition != "disabled", + refinement_node_limit=1 if condition == "budget" else 64, + ) + if condition == "matching": + timing = DelayModel(1.55e-6, group_indices={"4": 4, "5": 2}, variant_delays={"change": 40_000}) + result = route_layout(evaluator, nets, settings, timing=timing, groups=(MatchGroup("delay", {"lane": 0, "peer": 0}, 1.55e-6, 50),)) + assert result.matching["delay"].complete + else: + result = route_layout(evaluator, nets, settings) + assert result.completed == ("lane", "peer") + lane = result.routes["lane"].path + assert lane is not None + if condition == "enabled": + assert sum(part.cost for part in lane) == pytest.approx(0.0385) + assert sum(part.move.variant == "change" for part in lane) == 2 + else: + assert tuple(part.move for part in lane) == seed + assert verify_path(evaluator, lane, nets["lane"].start, nets["lane"].target, board=settings.board, keepouts=keepouts) is None + if condition == "keepout": + assert result.routes["peer"].cost == pytest.approx(0.0385) + assert result.routes["lane"].cost == pytest.approx(0.039) + + +def test_diagonal_join_limits_numerical_overlap_to_the_finite_face() -> None: + seam = Pose(0, 0, 45, "g") + a, b = Pose(-4, -4, 45, "g"), Pose(4, 4, 45, "g") + aligned = rotate(box(-4, -1, 0.001, 1), 45, origin=(0, 0)) + onward = rotate(box(0, -1, 4, 1), 45, origin=(0, 0)) + left = Evaluation(Move("from"), a, seam, (aligned,), 4, 1) + right = Evaluation(Move("to"), seam, b, (onward,), 4, 1) + assert compatible_join(left, right, 2, 0.002) + assert not compatible_join(left, right, 2, 0.0001) + + bulge_left = rotate(box(-4, 1.1, 0.001, 1.2), 45, origin=(0, 0)) + bulge_right = rotate(box(0, 1.1, 4, 1.2), 45, origin=(0, 0)) + assert not compatible_join( + replace(left, footprints=(aligned, bulge_left)), replace(right, footprints=(onward, bulge_right)), 2, 0.002, + ) + assert not compatible_join(left, replace(right, start=replace(seam, profile="other-mode")), 2, 0.002) + + +def test_self_clearance_rejects_long_parallel_legs_around_a_half_turn() -> None: + evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog("self-clearance", {"g": Profile("waveguide", 4)}, { + "straight": StraightVariant("g", 1), "turn": BendVariant("g", 180, 3, 0.02), + })) + start = Pose(0, 0, 0, "g") + target = Pose(0, 6, 180, "g") + path = replay_moves(evaluator, start, (Move("straight", steps=20), Move("turn", displacement=(0, 6)), Move("straight", steps=20))) + assert path is not None + board = box(-4, -4, 30, 12) + assert verify_path(evaluator, path, start, target, board=board, self_clearance=2) is None + assert verify_path(evaluator, path, start, target, board=board, self_clearance=3) == "self_clearance" + uncharacterized = (path[0], replace(path[1], length=None), path[2]) + assert verify_path(evaluator, uncharacterized, start, target, board=board, self_clearance=7) == "self_clearance" + + +@pytest.mark.parametrize("sign", [1, -1]) +def test_masque_places_a_fixed_cell_with_a_native_diagonal_port(masque_4a3, sign) -> None: + masque = masque_4a3 + grid = Grid((0, 0), 100, 1e-9) + profile = {"g": Profile("ridge", 4000)} + generated = BendVariant("g", 45 * sign, 10_000, 0.01, max_lead=110, sagitta=2) + evaluator = MoveEvaluator(grid, Catalog("authoring", profile, {"curve": generated})) + [move] = [choice for choice in evaluator.bend_moves("curve", 0, generated) if choice.displacement == (7200, 3000 * sign)] + authored = evaluator.evaluate(move, Pose(0, 0, 0, "g")) + assert authored is not None + origin = (2000, 3000) + entry = Pose(*origin, 0, "g") + exit = authored.end.shifted(*origin) + inward_exit = exit.reversed() + polygon = translate(authored.footprints[0], *origin) + cell = masque.Pattern(ports={ + "in": masque.Port(origin, rotation=0), + "out": masque.Port((exit.x, exit.y), rotation=radians(inward_exit.heading)), + }) + cell.polygon(5, vertices=polygon.exterior.coords[:-1]) + orientation = Orientation(90, True) + fixed = FixedVariant( + "authored", {"in": entry, "out": inward_exit}, (box(*polygon.bounds),), + (("in", "out"),), (orientation,), 0.01, authored.length, + ) + catalog = Catalog("diagonal-device", profile, {"authored": fixed, "straight": StraightVariant("g", 1)}) + with pytest.raises(ValueError, match="quarter turns"): + Orientation(45) + + start = orientation.port(entry).shifted(40_000, 50_000) + output = orientation.port(exit).shifted(40_000, 50_000) + target = output.shifted(10_000 * sign, 10_000) + layout = masque.Pattern(ports={ + "source": masque.Port((start.x, start.y), rotation=radians(start.reversed().heading)), + "destination": masque.Port((target.x, target.y), rotation=radians(target.heading)), + }) + result = route_and_place( + layout, {"authored": cell}, (Connection("native", Endpoint("source", "g"), Endpoint("destination", "g")),), + catalog=catalog, grid=grid, board=box(0, 0, 100_000, 100_000), layer=5, face_tolerance=0.002, + ) + assert result.placed == ("native",) + assert not layout.ports + recorded = result.routes["native"].path + assert recorded is not None + assert recorded[0].end == output + assert recorded[0].move.traversal == ("in", "out") + [reference] = layout.refs["authored"] + assert tuple(reference.offset) == (40_000, 50_000) + assert reference.rotation == pi / 2 + assert reference.mirrored + emitted = tuple(Polygon(shape.vertices + shape.offset) for shape in layout.layer_as_polygons(5, library={"authored": cell})) + assert any(shape.symmetric_difference(recorded[0].port_shapes[0]).area < 1e-6 for shape in emitted) + + +def test_masque_places_and_replays_an_authored_sbend_span(masque_4a3) -> None: + masque = masque_4a3 + left, right = [], [] + for i in range(101): + t = i / 100 + x, y = 26_000 * t, 6000 * (3 * t * t - 2 * t * t * t) + dx, dy = 26_000, 36_000 * t * (1 - t) + factor = 2000 / hypot(dx, dy) + left.append((x - dy * factor, y + dx * factor)) + right.append((x + dy * factor, y - dx * factor)) + polygon = Polygon((*left, *reversed(right))) + length = quad(lambda t: hypot(26_000, 36_000 * t * (1 - t)), 0, 1)[0] + cell = masque.Pattern(ports={"a": masque.Port((0, 0), rotation=0), "b": masque.Port((26_000, 6000), rotation=pi)}) + cell.polygon(7, vertices=polygon.exterior.coords[:-1]) + source = Pose(20_000, 20_000, 0, "g") + target = Pose(70_000, 26_000, 0, "g") + grid = Grid((0, 0), 100, 1e-9) + fixed = FixedVariant( + "sbend", {"a": Pose(0, 0, 0, "g"), "b": Pose(26_000, 6000, 180, "g")}, (polygon,), + (("a", "b"),), (Orientation(),), 0.02, length, + ) + catalog = Catalog("authored-span", {"g": Profile("ridge", 4000)}, {"sbend": fixed, "straight": StraightVariant("g", 1)}) + seed = (Move("sbend", traversal=("a", "b")), Move("straight", steps=240)) + layout = masque.Pattern(ports={ + "start": masque.Port((source.x, source.y), rotation=pi), + "finish": masque.Port((target.x, target.y), rotation=0), + }) + request = Connection("offset", Endpoint("start", "g"), Endpoint("finish", "g"), seed=seed) + result = route_and_place( + layout, {"sbend": cell}, (request,), catalog=catalog, grid=grid, board=box(0, 0, 100_000, 60_000), layer=7, node_limit=0, + ) + assert result.placed == ("offset",) + assert result.routes["offset"].length == pytest.approx(length + 24_000) + path = result.routes["offset"].path + assert path is not None + assert path[0].end == Pose(46_000, 26_000, 0, "g") + assert path[0].footprints[0].equals(translate(polygon, 20_000, 20_000)) + assert path[-1].end == target + + +def test_catalog_pair_repair_can_release_one_independent_peer() -> None: + evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog( + "contention", {"g": Profile("guide", 2), "h": Profile("straight-only", 2)}, { + "straight": StraightVariant("g", 1), "vertical-straight": StraightVariant("h", 1), + "left": BendVariant("g", 90, 5, 0.01), + "right": BendVariant("g", -90, 5, 0.01), + }, + )) + nets = { + "horizontal": CatalogNet(Pose(10, 50, 0, "g"), Pose(90, 50, 0, "g")), + "vertical": CatalogNet(Pose(50, 10, 90, "h"), Pose(50, 70, 90, "h")), + } + baseline = LayoutSettings(box(0, 0, 100, 100), clearance=1, node_limit=800, refinement=False) + raw = route_layout(evaluator, nets, baseline) + assert raw.completed == ("horizontal",) + refined = route_layout(evaluator, nets, replace(baseline, refinement=True, refinement_node_limit=400)) + assert refined.completed == tuple(nets) + assert refined.attempts[0].pair_repairs == 1 + assert refined.routes["vertical"].cost == pytest.approx(0.006) + detour = refined.routes["horizontal"].path + assert detour is not None + assert any(part.move.variant in ("left", "right") for part in detour) + + +def test_flat_diagonal_launch_and_arrival_use_exact_clearance() -> None: + evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog( + "diagonal-access", {"g": Profile("ridge", 2)}, {"s": StraightVariant("g", 1)}, + )) + start = Pose(0, 0, 45, "g") + target = Pose(10, 10, 45, "g") + walls = tuple(rotate(box(-4, y, 19, y + 1), 45, origin=(0, 0)) for y in (-3, 2)) + board = box(-10, -10, 25, 25) + intrusion = translate(walls[1], xoff=0.001 / sqrt(2), yoff=-0.001 / sqrt(2)) + for a, b in ((start, target), (target.reversed(), start.reversed())): + allowed = search_path(evaluator, a, b, board=board, keepouts=walls, clearance=1) + assert allowed.path is not None + assert allowed.path[0].move.steps == 10 + denied = search_path(evaluator, a, b, board=board, keepouts=(walls[0], intrusion), clearance=1) + assert denied.outcome == "exhausted" + + +@pytest.mark.parametrize("other_type", ["ridge", "strip"]) +def test_equal_width_profiles_require_a_declared_traversal(other_type) -> None: + profiles = {"mode1": Profile("ridge", 2), "mode2": Profile(other_type, 2)} + a, b = Pose(0, 0, 0, "mode1"), Pose(7, 0, 0, "mode2") + variant = FixedVariant( + "mode-converter", {"left": Pose(0, 0, 0, "mode1"), "right": Pose(7, 0, 180, "mode2")}, + (box(0, -1, 7, 1),), (("left", "right"),), (Orientation(),), 0.02, + ) + straight = StraightVariant("mode1", 1) + grid = Grid((0, 0), 1, 1e-6) + board = box(-2, -3, 9, 3) + evaluator = MoveEvaluator(grid, Catalog("strict", profiles, {"straight": straight})) + assert search_path(evaluator, a, b, board=board).outcome == "exhausted" + evaluator = MoveEvaluator(grid, Catalog("directed", profiles, {"change": variant, "straight": straight})) + route = search_path(evaluator, a, b, board=board) + assert route.outcome == "verified" + assert route.length is None + assert route.cost == pytest.approx(0.02) + assert search_path(evaluator, b.reversed(), a.reversed(), board=board).outcome == "exhausted" + model = DelayModel(1.55e-6, variant_delays={"change": 21.03}) + assert route.path is not None + delay = evaluate_delay(evaluator, route.path, model, net_id="converter") + assert delay is not None + assert delay.optical_length == 21.03 + + +def test_a_single_135_degree_bend_can_clear_an_opening_smaller_turns_miss() -> None: + grid = Grid((0, 0), 100, 1e-9) + variants = { + "straight": StraightVariant("g", 1), + "45": BendVariant("g", 45, 7000, 0.005, max_lead=400, sagitta=5), + "90": BendVariant("g", 90, 10_000, 0.006, sagitta=5), + "135": BendVariant("g", 135, 10_000, 0.02, max_lead=200, sagitta=5), + } + evaluator = MoveEvaluator(grid, Catalog("tight-135", {"g": Profile("ridge", 400)}, variants)) + start, target = Pose(0, 0, 0, "g"), Pose(7200, 17_100, 135, "g") + board = box(-1000, -1000, 13_000, 19_000) + radius = 10_000 + exit_lead = (target.y - radius * (1 + 1 / sqrt(2))) * sqrt(2) + entry_lead = target.x - radius / sqrt(2) + exit_lead / sqrt(2) + opening_points = [(0, 0)] + for i in range(257): + angle = i * (3 * pi / 4) / 256 + opening_points.append((entry_lead + radius * sin(angle), radius * (1 - cos(angle)))) + opening_points.append((target.x, target.y)) + opening = LineString(opening_points).buffer(300, cap_style="square") + keepouts = (board.difference(opening),) + open_run = search_path(evaluator, start, target, board=board) + assert open_run.path is not None + assert open_run.cost < 0.02 + assert verify_path(evaluator, open_run.path, start, target, board=board, keepouts=keepouts, clearance=20) == "keepout" + + only_single = search_path(evaluator, start, target, board=board, keepouts=keepouts, clearance=20) + assert only_single.path is not None + [bend] = only_single.path + assert bend.move.variant == "135" + assert bend.move.leads == pytest.approx((entry_lead, exit_lead)) + + +def test_bend_leads_use_profile_straight_price_by_default() -> None: + left = BendVariant("g", 45, 10_000, 0.01, max_lead=200, sagitta=5) + catalog = Catalog("lead-price", {"g": Profile("ridge", 4000)}, { + "straight": StraightVariant("g", 1), "l45": left, "l90": BendVariant("g", 90, 10_000, 0.01), + }) + evaluator = MoveEvaluator(Grid((0, 0), 100, 1e-9), catalog) + start = Pose(0, 0, 0, "g") + [first] = [move for move in evaluator.bend_moves("l45", 0, left) if move.displacement == (7200, 3000)] + [second] = [move for move in evaluator.bend_moves("l45", 45, left) if move.displacement == (3000, 7200)] + two = replay_moves(evaluator, start, (first, second)) + one = replay_moves(evaluator, start, (Move("l90", displacement=(10_000, 10_000)),)) + assert two is not None + assert one is not None + assert sum(move.cost for move in two) == pytest.approx(0.02 + (sum(first.leads) + sum(second.leads)) / 1e7) + assert one[0].cost == pytest.approx(0.01) + + +@pytest.mark.parametrize("source_attachment", [True, False]) +def test_attachment_does_not_grant_clearance_to_a_later_visit(source_attachment) -> None: + grid = Grid((0, 0), 100, 1e-9) + evaluator = MoveEvaluator(grid, Catalog("short-access", {"g": Profile("ridge", 4000)}, {"s": StraightVariant("g", 1)})) + terminal, outside = Pose(0, 0, 0, "g"), Pose(3000, 0, 0, "g") + fixed = box(-10_000, -2000, 0, 2000) + attachment = Attachment(fixed, box(-2000, -3000, 2000, 3000)) + access = evaluator.evaluate(Move("s", steps=30), terminal) + assert access is not None + far = Pose(4000, 5000, 0, "g") + later = Evaluation(Move("return"), outside, far, (box(250, 2250, 500, 2750),), None, 0.01) + geometry = {"board": box(-12_000, -5000, 15_000, 10_000), "keepouts": (fixed,), "clearance": 1000} + if source_attachment: + assert verify_path(evaluator, (access,), terminal, outside, source_attachment=attachment, **geometry) is None + assert verify_path(evaluator, (access, later), terminal, far, source_attachment=attachment, **geometry) == "fixed_attachment" + else: + arrival = replace(access, start=outside.reversed(), end=terminal.reversed()) + reversed_visit = replace(later, start=far.reversed(), end=outside.reversed()) + assert verify_path(evaluator, (arrival,), outside.reversed(), terminal.reversed(), destination_attachment=attachment, **geometry) is None + assert verify_path( + evaluator, (reversed_visit, arrival), far.reversed(), terminal.reversed(), destination_attachment=attachment, **geometry, + ) == "fixed_attachment" + + +@pytest.mark.parametrize("at_attachment", [False, True]) +@pytest.mark.parametrize("other_first", [False, True]) +def test_a_reserved_join_blocks_a_foreign_route_in_either_net_order(at_attachment, other_first) -> None: + before = Pose(-2000, 0, 0, "guide") + seam = Pose(0, 0, 0, "guide") + after = Pose(2000, 0, 0, "guide") + cells = { + "before": FixedVariant( + "before", {"a": before, "b": seam.reversed()}, (box(-2000, -1000, -1, 1000),), + (("a", "b"),), (Orientation(),), 1, + ), + "after": FixedVariant( + "after", {"a": seam, "b": after.reversed()}, (box(1, -1000, 2000, 1000),), + (("a", "b"),), (Orientation(),), 1, + ), + } + evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-9), Catalog( + "seam", {"guide": Profile("ridge", 2000), "foreign": Profile("other", 0.5)}, + {**cells, "foreign": StraightVariant("foreign", 1)}, + )) + fixed = cells["before"].footprints[0] + end_move = Move("after", traversal=("a", "b")) + if at_attachment: + attachment = Attachment(fixed, box(-20, -1100, 20, 1100)) + horizontal = CatalogNet(seam, after, source_attachment=attachment, seed=(end_move,)) + keepouts = (fixed,) + else: + horizontal = CatalogNet(before, after, seed=(Move("before", traversal=("a", "b")), end_move)) + keepouts = () + vertical = CatalogNet(Pose(0, -2000, 90, "foreign"), Pose(0, 2000, 90, "foreign")) + nets = {"horizontal": horizontal, "vertical": vertical} + if other_first: + nets = dict(reversed(tuple(nets.items()))) + result = route_layout( + evaluator, nets, LayoutSettings(box(-3000, -3000, 3000, 3000), keepouts, face_tolerance=2, refinement=False), + ) + assert result.completed == (("vertical",) if other_first else ("horizontal",)) + assert set(result.routes) == set(nets) + + +@pytest.mark.parametrize("require_complete", [False, True]) +def test_masque_releases_provisional_group_geometry_and_preserves_a_completed_group(masque_4a3, require_complete) -> None: + masque = masque_4a3 + poses = { + "failed-a": (Pose(20, 50, 0, "g"), Pose(90, 50, 0, "g")), + "failed-b": (Pose(20, 80, 0, "g"), Pose(90, 80, 0, "g")), + "keep-a": (Pose(110, 20, 0, "g"), Pose(180, 20, 0, "g")), + "keep-b": (Pose(110, 40, 0, "g"), Pose(180, 40, 0, "g")), + "independent": (Pose(50, 10, 90, "g"), Pose(50, 70, 90, "g")), + } + ports = {} + connections = [] + for name, (a, b) in poses.items(): + first, last = f"{name}-source", f"{name}-target" + ports[first] = masque.Port((a.x, a.y), rotation=radians(a.reversed().heading)) + ports[last] = masque.Port((b.x, b.y), rotation=radians(b.heading)) + connections.append(Connection(name, Endpoint(first, "g"), Endpoint(last, "g"))) + layout = masque.Pattern(ports=ports) + catalog = Catalog("group-placement", {"g": Profile("ridge", 2)}, {"s": StraightVariant("g", 1)}) + groups = ( + MatchGroup("failed", {"failed-a": 0, "failed-b": 1}, 1.55e-6, 0.05), + MatchGroup("held", {"keep-a": 0, "keep-b": 0}, 1.55e-6, 0.05), + ) + result = route_and_place( + layout, {}, connections, catalog=catalog, grid=Grid((0, 0), 1, 1e-6), board=box(0, 0, 200, 100), + layer=1, clearance=1, timing=DelayModel(1.55e-6, group_indices={"g": 4}), + match_groups=groups, refinement=False, require_complete=require_complete, + ) + assert result.matching["held"].complete + assert result.matching["failed"].status == "unmatched" + assert result.routes["failed-a"].path is not None + assert result.routes["failed-b"].path is not None + if require_complete: + assert result.placed == () + assert tuple(layout.ports) == tuple(ports) + assert not layout.shapes + assert result.attempts[0].independent_retries == 0 + else: + assert result.placed == ("keep-a", "keep-b", "independent") + assert set(layout.ports) == {name for name in ports if name.startswith("failed")} + assert len(layout.shapes[1]) == 3 + assert result.attempts[0].independent_retries == 1 + + +@pytest.mark.parametrize("authorization_first", [False, True]) +def test_two_preplaced_crossing_ports_have_independent_attachments(masque_4a3, authorization_first) -> None: + masque = masque_4a3 + cross = masque.Pattern() + for shape in (box(-10, -2, 10, 2), box(-2, -10, 2, 10)): + cross.polygon(7, vertices=shape.exterior.coords[:-1]) + real = (box(40, 48, 60, 52), box(48, 40, 52, 60)) + envelope = box(40, 40, 60, 60) + attaches = { + "east": Attachment(envelope, box(58, 47, 62, 53), real), + "north": Attachment(envelope, box(47, 58, 53, 62), real), + } + catalog = Catalog("crossing", {"g": Profile("ridge", 4)}, {"s": StraightVariant("g", 1)}) + for authorized in (authorization_first, not authorization_first): + layout = masque.Pattern(ports={ + "east": masque.Port((60, 50), rotation=pi), + "east-target": masque.Port((80, 50), rotation=0), + "north": masque.Port((50, 60), rotation=3 * pi / 2), + "north-target": masque.Port((50, 80), rotation=pi / 2), + }) + layout.ref("cross", offset=(50, 50)) + result = route_and_place( + layout, {"cross": cross}, tuple( + Connection(name, Endpoint(name, "g", attaches[name] if authorized else None), Endpoint(f"{name}-target", "g")) + for name in ("east", "north") + ), + catalog=catalog, grid=Grid((0, 0), 1, 1e-6), board=box(0, 0, 100, 100), layer=7, + keepouts=(envelope,), clearance=1, refinement=False, + ) + assert result.placed == (("east", "north") if authorized else ()) + assert len(layout.refs["cross"]) == 1 + assert len(layout.shapes.get(7, ())) == (2 if authorized else 0) + + +def test_masque_places_both_directions_of_a_displaced_transition(masque_4a3) -> None: + masque = masque_4a3 + a, b = Pose(0, 0, 0, "4"), Pose(100_000, 200, 180, "8") + actual = Polygon(((0, -2000), (100_000, -3800), (100_000, 4200), (0, 2000))) + envelope = box(0, -5000, 100_000, 5000) + native, reflected_reverse = Orientation(), Orientation(180, True) + cell = masque.Pattern(ports={"A": masque.Port((a.x, a.y), rotation=0), "B": masque.Port((b.x, b.y), rotation=pi)}) + cell.polygon(1, vertices=actual.exterior.coords[:-1]) + fixed = FixedVariant( + "displaced", {"A": a, "B": b}, (envelope,), (("A", "B"), ("B", "A")), + (native, reflected_reverse), 0.2, 100_010, + ) + catalog = Catalog("displaced", {"4": Profile("ridge4", 4000), "8": Profile("ridge8", 8000)}, { + "t": fixed, "s8": StraightVariant("8", 0.2), + }) + pose = Pose(10_000, 20_000, 0, "4") + target = Pose(230_000, 20_000, 0, "4") + layout = masque.Pattern(ports={ + "input": masque.Port((pose.x, pose.y), rotation=pi), + "output": masque.Port((target.x, target.y), rotation=0), + }) + seed = ( + Move("t", traversal=("A", "B")), Move("s8", steps=200), + Move("t", traversal=("B", "A"), orientation=reflected_reverse), + ) + result = route_and_place( + layout, {"displaced": cell}, (Connection("twice", Endpoint("input", "4"), Endpoint("output", "4"), seed),), + catalog=catalog, grid=Grid((0, 0), 100, 1e-9), board=box(0, 0, 300_000, 100_000), + layer=1, node_limit=0, timing=DelayModel(1.55e-6, group_indices={"8": 2}, variant_delays={"t": 300_030}), + ) + assert result.outcome == "complete" + assert result.placed == ("twice",) + path = result.routes["twice"].path + assert path is not None + assert tuple(part.move for part in path) == seed + assert [part.end.profile for part in path] == ["8", "8", "4"] + assert path[0].end == Pose(110_000, 20_200, 0, "8") + assert path[1].end == Pose(130_000, 20_200, 0, "8") + assert path[2].end == target + first, second = layout.refs["displaced"] + assert tuple(first.offset) == (10_000, 20_000) + assert tuple(second.offset) == (230_000, 20_000) + assert second.mirrored + assert second.rotation == pi + assert result.routes["twice"].cost == pytest.approx(0.4004) + assert result.delays["twice"].optical_length == 640_060 + + +def test_three_reference_profiles_use_the_declared_physical_straight_rates() -> None: + profiles = {name: Profile(f"ridge-{name}", int(name) * 1000) for name in ("4", "5", "8")} + prices = {"4": 1.0, "5": 0.5, "8": 0.2} + catalog = Catalog("device-set", profiles, {name: StraightVariant(name, rate) for name, rate in prices.items()}) + evaluator = MoveEvaluator(Grid((0, 0), 100, 1e-9), catalog) + for name, price in (("4", 0.1), ("5", 0.05), ("8", 0.02)): + cardinal = evaluator.evaluate(Move(name, steps=10_000), Pose(0, 0, 0, name)) + diagonal = evaluator.evaluate(Move(name, steps=10_000), Pose(0, 0, 45, name)) + assert cardinal is not None + assert diagonal is not None + assert cardinal.cost == pytest.approx(price) + assert diagonal.cost == pytest.approx(price * sqrt(2)) + + +def test_native_diagonal_transition_accepts_exact_displacement_and_diagnoses_off_grid_fit() -> None: + entry, exit = Pose(0, 0, 45, "4"), Pose(70_000, 70_200, 45, "8") + near, far = 2000 / sqrt(2), 4000 / sqrt(2) + a_left, a_right = (-near, near), (near, -near) + b_left, b_right = (exit.x - far, exit.y + far), (exit.x + far, exit.y - far) + footprint = Polygon((a_left, b_left, b_right, a_right)) + variant = FixedVariant( + "diagonal", {"a": entry, "b": exit.reversed()}, (footprint,), (("a", "b"),), (Orientation(),), 0.2, + ) + catalog = Catalog( + "diagonal-cell", {"4": Profile("ridge4", 4000), "8": Profile("ridge8", 8000)}, + {"change": variant, "8-straight": StraightVariant("8", 0.2)}, + ) + evaluator = MoveEvaluator(Grid((0, 0), 100, 1e-9), catalog) + board = box(-4000, -4000, 100_000, 105_000) + result = search_path(evaluator, entry, exit.shifted(10_000, 10_000), board=board) + assert result.path is not None + assert result.path[0].end == exit + assert result.path[1].end == exit.shifted(10_000, 10_000) + assert result.path[1].length == pytest.approx(10_000 * sqrt(2)) + coarse = MoveEvaluator(Grid((0, 0), 1000, 1e-9), catalog) + assert coarse.local_moves("4", 45) == () + [diagnostic] = coarse.unavailable + assert diagnostic.move.variant == "change" + assert diagnostic.reason == "off_grid_output" + + +def test_masque_rounds_to_layout_units_before_exact_lattice_validation(masque_4a3) -> None: + masque = masque_4a3 + catalog = Catalog("metric-origin", {"g": Profile("ridge", 40)}, {"s": StraightVariant("g", 1)}) + args = { + "catalog": catalog, "grid": Grid((30, -20), 100, 1e-9), "board": box(0, 0, 1000, 400), "layer": 1, + } + connection = Connection("rounding", Endpoint("a", "g"), Endpoint("b", "g")) + layout = masque.Pattern(ports={ + "a": masque.Port((330.00000000000006, 180), rotation=pi), + "b": masque.Port((830, 180), rotation=0), + }) + result = route_and_place(layout, {}, (connection,), **args) + assert result.placed == ("rounding",) + assert result.routes["rounding"].path[0].start == Pose(330, 180, 0, "g") + off_grid = masque.Pattern(ports={"a": masque.Port((331, 180), rotation=pi), "b": masque.Port((830, 180), rotation=0)}) + with pytest.raises(ValueError, match="invalid terminal"): + route_and_place(off_grid, {}, (connection,), **args) + assert tuple(off_grid.ports) == ("a", "b") + assert not off_grid.shapes + + +@pytest.mark.parametrize("turn", [45, 90, 135, 180]) +def test_euler_selection_stops_at_the_radius_floor(turn) -> None: + angle = radians(turn) + reference, floor = 10_000, 8_000 + partial = bend_curve(reference, angle, floor, None) + assert partial is not None + assert partial.radius == pytest.approx(floor) + assert 0 < partial.fraction < 1 + assert bend_curve(reference, angle, floor, partial.fraction + 1e-5) is None + assert bend_curve(reference, angle, floor, 1.0) is None + circular = bend_curve(reference, angle, floor, 0.0) + assert circular is not None + assert circular.radius == reference + + +def test_asymmetric_fixed_bend_after_diagonal_straight_replays_the_same_ports() -> None: + # Independent fixture construction. A northeast lead of 2√2 µm followed by + # a quarter turn of radius 4√2 µm ends 2 µm east and 10 µm north of entry. + local_radius = 4000 * sqrt(2) + local_lead = 2000 * sqrt(2) + centerline = [(0.0, 0.0)] + centerline.extend( + (local_lead + local_radius * sin(angle), local_radius * (1 - cos(angle))) + for angle in (pi * i / 1024 for i in range(513)) + ) + # Construct a fixed polygon with its two complete authored faces. + left, right = [], [] + headings = (0, *(pi * i / 1024 for i in range(513))) + for (x, y), angle in zip(centerline, headings, strict=True): + left.append((x - 500 * sin(angle), y + 500 * cos(angle))) + right.append((x + 500 * sin(angle), y - 500 * cos(angle))) + footprint = rotate(Polygon((*left, *reversed(right))), 45, origin=(0, 0)) + fixed = FixedVariant( + "asymmetric-diagonal", {"a": Pose(0, 0, 45, "g"), "b": Pose(2000, 10_000, 315, "g")}, (footprint,), + (("a", "b"),), (Orientation(),), 0.01, local_lead + local_radius * pi / 2, + ) + catalog = Catalog("asymmetric-diagonal", {"g": Profile("ridge", 1000)}, {"corner": fixed, "straight": StraightVariant("g", 1)}) + evaluator = MoveEvaluator(Grid((0, 0), 100, 1e-9), catalog) + start = Pose(20_000, 20_000, 45, "g") + target = Pose(17_000, 38_000, 135, "g") + run = search_path(evaluator, start, target, board=box(0, 0, 60_000, 60_000), face_tolerance=0.01) + assert run.path is not None + assert tuple(move.move.variant for move in run.path) == ("straight", "corner", "straight") + assert run.path[1].start == Pose(21_500, 21_500, 45, "g") + assert run.path[1].end == Pose(23_500, 31_500, 135, "g") + assert replay_moves(evaluator, start, tuple(move.move for move in run.path)) == run.path diff --git a/inire/tests/test_catalog_search_oracle.py b/inire/tests/test_catalog_search_oracle.py new file mode 100644 index 0000000..4ed7947 --- /dev/null +++ b/inire/tests/test_catalog_search_oracle.py @@ -0,0 +1,153 @@ +"""Compare catalog search with complete path histories on small fixtures.""" + +from dataclasses import replace +from heapq import heappop, heappush +from itertools import count + +from shapely.geometry import LineString, Polygon, box + +from inire._catalog import BendVariant, Catalog, FixedVariant, Grid, Move, MoveEvaluator, Orientation, Pose, Profile, StraightVariant +from inire.router._catalog_layout import CatalogNet, LayoutSettings, route_layout +from inire.router._catalog_search import _Proposals, search_path +from inire.router._catalog_verify import verify_path + + +def exhaustive_paths(evaluator, start, target, moves_from, *, depth, **geometry): + queue = [(0.0, 0, start, ())] + order = count(1) + complete = [] + expanded = 0 + while queue: + cost, _, pose, path = heappop(queue) + expanded += 1 + if path and pose == target: + complete.append((cost, path)) + continue + if len(path) == depth: + continue + for move in moves_from(pose): + candidate = evaluator.evaluate(move, pose) + if candidate is None: + continue + trial = (*path, candidate) + if verify_path(evaluator, trial, start, candidate.end, **geometry) is None: + heappush(queue, (cost + candidate.cost, next(order), candidate.end, trial)) + return complete, expanded + + +def test_launch_proposal_gaps_and_dominance_can_be_measured_separately(monkeypatch) -> None: + start, target = Pose(2, 4, 0, "a"), Pose(28, 8, 0, "b") + transition = FixedVariant( + "displaced", {"in": Pose(0, 0, 0, "a"), "out": Pose(8, 4, 180, "b")}, + (Polygon(((0, -1), (8, 3), (8, 5), (0, 1))),), + (("in", "out"),), (Orientation(),), 0.2, + ) + evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog( + "oracle", {"a": Profile("ridge", 2), "b": Profile("ridge", 2)}, + {"a": StraightVariant("a", 1), "b": StraightVariant("b", 1), "change": transition}, + )) + board = box(0, 0, 30, 12) + keepouts = (box(0, 5, 10, 12), box(18, 0, 30, 7)) + geometry = {"board": board, "keepouts": keepouts} + bound = 3 + + def complete_moves(pose): + straight = [Move(pose.profile, steps=size) for size in range(1, 31 - pose.x)] + return [*straight, Move("change", traversal=("in", "out"))] if pose.profile == "a" else straight + + oracle, oracle_expanded = exhaustive_paths(evaluator, start, target, complete_moves, depth=bound, **geometry) + [best] = oracle + assert best[1][1].start == Pose(10, 4, 0, "a") + + real_proposals = _Proposals(evaluator, start, target, keepouts, 0.0) + initial_moves = tuple(real_proposals.from_pose(start, board.bounds)) + # Production narrows the complete launch set but must keep the only legal launch. + assert set(initial_moves) < set(complete_moves(start)) + assert best[1][0].move in initial_moves + proposed, proposed_expanded = exhaustive_paths( + evaluator, start, target, lambda pose: real_proposals.from_pose(pose, board.bounds), depth=bound, **geometry, + ) + assert proposed == oracle + assert proposed_expanded < oracle_expanded + + def reference_proposals(_self, pose, _bounds): + return complete_moves(pose) + + with monkeypatch.context() as patch: + patch.setattr(_Proposals, "from_pose", reference_proposals) + pruned = search_path(evaluator, start, target, **geometry) + assert pruned.path == best[1] + assert pruned.expanded < oracle_expanded + + +def test_search_retains_the_arrival_that_can_continue(monkeypatch) -> None: + start, meeting, goal = (Pose(x, 5, 0, "p") for x in (0, 5, 9)) + width = 0.1 + detour = ((0, 5), (2, 5), (2, 9), (7, 9), (7, 2), (3, 2), (3, 5), (5, 5)) + + def cell(name, points, cost): + journey = LineString(points) + return FixedVariant( + name, {"in": Pose(*points[0], 0, "p"), "out": Pose(*points[-1], 180, "p")}, + (journey.buffer(width / 2, cap_style="flat", join_style="round"),), + (("in", "out"),), (Orientation(),), cost, journey.length, + ) + + choices = { + "direct": cell("direct", ((0, 5), (5, 5)), 5), + "cheap": cell("cheap", detour, 1), + "last": cell("last", ((5, 5), (9, 5)), 1), + } + evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog("history", {"p": Profile("waveguide", width)}, choices)) + board = box(-1, 0, 10, 10) + edges = { + start: tuple(Move(name, traversal=("in", "out")) for name in ("direct", "cheap")), + meeting: (Move("last", traversal=("in", "out")),), + } + + def script(_self, pose, _bounds): + return edges.get(pose, ()) + + def from_pose(pose): + return edges.get(pose, ()) + + short, cheap = (evaluator.evaluate(move, start) for move in edges[start]) + tail = evaluator.evaluate(edges[meeting][0], meeting) + assert short is not None + assert cheap is not None + assert tail is not None + assert cheap.end == short.end == meeting + assert cheap.cost < short.cost + assert verify_path(evaluator, (cheap,), start, meeting, board=board) is None + assert verify_path(evaluator, (cheap, tail), start, goal, board=board) == "join" + assert verify_path(evaluator, (short, tail), start, goal, board=board) is None + + oracle, _ = exhaustive_paths(evaluator, start, goal, from_pose, depth=2, board=board) + assert oracle == [(6, (short, tail))] + monkeypatch.setattr(_Proposals, "from_pose", script) + assert search_path(evaluator, start, goal, board=board, arrivals_per_pose=1).outcome == "exhausted" + assert search_path(evaluator, start, goal, board=board, arrivals_per_pose=2).path == oracle[0][1] + assert search_path(evaluator, start, goal, board=board, node_limit=1).outcome == "node_limit" + + +def test_refinement_prefers_the_cheaper_of_two_full_coverage_orders() -> None: + catalog = Catalog("order", {"g": Profile("ridge", 2)}, { + "s": StraightVariant("g", 1), "left": BendVariant("g", 90, 5, 0.01), "right": BendVariant("g", -90, 5, 0.01), + }) + grid = Grid((0, 0), 1, 1e-6) + nets = { + "horizontal": CatalogNet(Pose(10, 50, 0, "g"), Pose(90, 50, 0, "g")), + "vertical": CatalogNet(Pose(50, 10, 90, "g"), Pose(50, 70, 90, "g")), + } + settings = LayoutSettings(box(0, 0, 100, 100), clearance=1, node_limit=800, refinement=False) + first = route_layout(MoveEvaluator(grid, catalog), nets, settings) + second = route_layout(MoveEvaluator(grid, catalog), dict(reversed(tuple(nets.items()))), settings) + assert set(first.completed) == set(second.completed) == set(nets) + assert len(first.routes["horizontal"].path) == 1 + assert len(second.routes["vertical"].path) == 1 + assert sum(route.cost for route in second.routes.values()) < sum(route.cost for route in first.routes.values()) + + refined = route_layout(MoveEvaluator(grid, catalog), nets, replace(settings, refinement=True)) + assert refined.completed == tuple(nets) + assert len(refined.attempts) == 2 + assert all(refined.routes[name].path == second.routes[name].path for name in nets) diff --git a/inire/tests/test_catalog_timing_cases.py b/inire/tests/test_catalog_timing_cases.py new file mode 100644 index 0000000..4ba12d5 --- /dev/null +++ b/inire/tests/test_catalog_timing_cases.py @@ -0,0 +1,266 @@ +"""Timing models, ranked alternatives, and bounded matching.""" + +from dataclasses import replace +from math import sqrt + +import pytest +from shapely.geometry import LineString, Polygon, box + +from inire._catalog import BendVariant, Catalog, Evaluation, FixedVariant, Grid, Move, MoveEvaluator, Orientation, Pose, Profile, StraightVariant +from inire._catalog_timing import Delay, DelayModel +from inire.router import _catalog_layout, _catalog_tuning +from inire.router._catalog_layout import CatalogNet, LayoutResult, LayoutSettings, _layout_rank, route_layout +from inire.router._catalog_matching import MatchGroup, MatchResult +from inire.router._catalog_search import SearchResult +from inire.router._catalog_tuning import tune_group, window_replacements +from inire.router._catalog_verify import replay_moves, verify_path + + +@pytest.mark.parametrize("units", ["optical_length", "seconds"]) +def test_matching_retries_a_more_expensive_baseline_across_a_fixed_crossing(units) -> None: + meter_per_unit = 1e-6 + scale = meter_per_unit / 299_792_458 if units == "seconds" else 1 + evaluator = MoveEvaluator(Grid((0, 0), 1, meter_per_unit), Catalog( + "crossing", {"g": Profile("ridge", 2)}, {"regular": StraightVariant("g", 1), "slow": StraightVariant("g", 2)}, + )) + nets = { + "after-crossing": CatalogNet(Pose(5, 5, 0, "g"), Pose(40, 5, 0, "g")), + "reference": CatalogNet(Pose(5, 15, 0, "g"), Pose(40, 15, 0, "g")), + } + observations = [] + + def fixed_side(wavelength): + observations.append(("fixed-route", wavelength)) + return 100 if wavelength == 1.55e-6 else 50 + + def crossing(wavelength): + observations.append(("crossing", wavelength)) + return 5 + + def group_index(wavelength, _angle): + observations.append(("straight", wavelength)) + return 4 if wavelength == 1.55e-6 else 3 + + timing = DelayModel( + 1.3e-6, group_indices={"g": group_index}, variant_delays={"slow": lambda _move, wavelength: 145 if wavelength == 1.55e-6 else 50}, + fixed_contributions={"after-crossing": (fixed_side, crossing), "reference": (110,)}, + ) + settings = LayoutSettings(box(0, 0, 50, 20), node_limit=30, refinement=False) + report = route_layout(evaluator, nets, settings, timing=timing) + normal = report.routes["after-crossing"].path + assert normal is not None + assert normal[0].move.variant == "regular" + assert report.completed == tuple(nets) + assert report.delays["after-crossing"].optical_length == 160 + assert all(wavelength == 1.3e-6 for _, wavelength in observations) + observations.clear() + + group = MatchGroup("timing", {"after-crossing": 0, "reference": 0}, 1.55e-6, 0.05 * scale, units=units) + matched = route_layout(evaluator, nets, settings, timing=timing, groups=(group,)) + chosen = matched.routes["after-crossing"].path + assert matched.completed == tuple(nets) + assert chosen is not None + assert chosen[0].move.variant == "slow" + assert matched.matching["timing"].delays["after-crossing"].optical_length == 250 + assert matched.matching["timing"].skew == 0 + assert {"fixed-route", "crossing", "straight"} <= {name for name, _ in observations} + assert all(wavelength == group.wavelength for _, wavelength in observations) + + restricted = MoveEvaluator(evaluator.grid, replace(evaluator.catalog, variants={"regular": StraightVariant("g", 1)})) + unmatched = route_layout(restricted, nets, settings, timing=timing, groups=(group,)) + assert unmatched.completed == () + assert all(candidate.path is not None for candidate in unmatched.routes.values()) + assert unmatched.matching["timing"].skew == pytest.approx(5 * scale, abs=1e-12 * scale) + assert unmatched.matching["timing"].status == "unmatched" + + +@pytest.mark.parametrize(("limit", "expected_status", "expected_skew"), [ + (0, "unmatched", 1), (1, "unmatched", 0.2), (2, "unmatched", 0.2), (3, "matched", 0), (4, "matched", 0), +]) +def test_tuning_budget_keeps_the_best_verified_delay_choices(monkeypatch, limit, expected_status, expected_skew) -> None: + # The second proposal is for b. Its baseline remains eligible and pairs + # more closely with a's first improvement. + catalog = Catalog( + "timing-budget", {"g": Profile("ridge", 1)}, + {name: StraightVariant("g", 1) for name in ("base-a", "base-b", "middle", "last")}, + ) + evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), catalog) + board = box(0, 0, 20, 20) + terminals = { + "a": (Pose(2, 4, 0, "g"), Pose(17, 4, 0, "g")), + "b": (Pose(2, 8, 0, "g"), Pose(17, 8, 0, "g")), + } + + def recipe(name, variant): + return replay_moves(evaluator, terminals[name][0], (Move(variant, steps=15),)) + + base = {name: recipe(name, f"base-{name}") for name in terminals} + proposals = {"a": (recipe("a", "middle"), recipe("a", "last")), "b": (recipe("b", "last"),)} + + def replacements(_evaluator, path, _window): + return iter(proposals["a" if path[0].start.y == 4 else "b"]) + + monkeypatch.setattr(_catalog_tuning, "window_replacements", replacements) + timing = DelayModel(1.55e-6, variant_delays={"base-a": 400, "base-b": 401, "middle": 400.8, "last": 401.6}) + group = MatchGroup("budget", {"a": 0, "b": 0}, 1.55e-6, 0.05) + windows = {"a": box(2, 2, 17, 6), "b": box(2, 6, 17, 10)} + + report, changes = tune_group( + evaluator, group, timing, base, windows, + lambda name, path: verify_path(evaluator, path, *terminals[name], board=board) is None, + proposal_limit=limit, + ) + assert report.status == expected_status + assert report.skew == pytest.approx(expected_skew) + assert report.budget_exhausted == (limit < 4) + if limit == 0: + assert not changes + if limit == 1: + assert changes == {"a": proposals["a"][0]} + + +def test_missing_fixed_contribution_leaves_the_verified_geometry_available() -> None: + evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog("unknown", {"g": Profile("ridge", 2)}, {"s": StraightVariant("g", 1)})) + nets = {"member": CatalogNet(Pose(5, 5, 0, "g"), Pose(40, 5, 0, "g"))} + settings = LayoutSettings(box(0, 0, 50, 20)) + model = DelayModel(1.55e-6, group_indices={"g": 4}, fixed_contributions={"member": (None,)}) + report_only = route_layout(evaluator, nets, settings, timing=model) + assert report_only.completed == ("member",) + assert report_only.delays["member"] is None + grouped = route_layout(evaluator, nets, settings, timing=model, groups=(MatchGroup("requires-fixed", {"member": 0}, 1.55e-6, 0.05),)) + assert grouped.completed == () + assert grouped.routes["member"].path == report_only.routes["member"].path + assert grouped.matching["requires-fixed"].status == "missing_delay" + assert not grouped.matching["requires-fixed"].budget_exhausted + + +@pytest.mark.parametrize("reverse_order", [False, True]) +def test_adjacent_windows_keep_clearance_for_the_other_owner(reverse_order) -> None: + square = box(0, -1, 16, 1) + protruding = Polygon(((0, -1), (16, -1), (16, 1), (12, 1), (10, 1.1), (6, 1.1), (4, 1), (0, 1))) + profiles = {"g": Profile("ridge", 2)} + altered = FixedVariant( + "protruding", {"in": Pose(0, 0, 0, "g"), "out": Pose(16, 0, 180, "g")}, + (protruding,), (("in", "out"),), (Orientation(),), 1, 16, + ) + safe = replace(altered, cell="safe", footprints=(square,)) + variants = {"s": StraightVariant("g", 1), "protruding": altered, "safe": safe} + evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog("adjacent", profiles, variants)) + settings = LayoutSettings(box(0, 0, 24, 22), clearance=1, node_limit=0, refinement=False) + windows = {"a": box(2, 8, 18, 12), "b": box(2, 12, 18, 16)} + timing = DelayModel(1.55e-6, group_indices={"g": 4}, variant_delays={"protruding": 64, "safe": 64}) + group = MatchGroup("adjacent", {"a": 0, "b": 0}, 1.55e-6, 0) + for candidate in ("safe", "protruding"): + nets = { + "a": CatalogNet(Pose(2, 10, 0, "g"), Pose(18, 10, 0, "g"), seed=(Move(candidate, traversal=("in", "out")),)), + "b": CatalogNet(Pose(2, 14, 0, "g"), Pose(18, 14, 0, "g"), seed=(Move("s", steps=16),)), + } + if reverse_order: + nets = dict(reversed(tuple(nets.items()))) + result = route_layout(evaluator, nets, settings, timing=timing, groups=(group,), windows=windows) + if candidate == "safe": + assert result.completed == tuple(nets) + assert result.matching["adjacent"].complete + else: + assert result.completed == () + assert result.routes["a"].path is None + assert result.matching["adjacent"].status == "unrouted" + + +def test_four_completed_independent_nets_outrank_a_three_net_match() -> None: + evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog("ranking", {"g": Profile("ridge", 2)}, { + "low": StraightVariant("g", 1), "high": StraightVariant("g", 2), + })) + low = {} + high = {} + for i in range(4): + start = Pose(2, i * 5 + 2, 0, "g") + name = f"net{i}" + low[name] = SearchResult(replay_moves(evaluator, start, (Move("low", steps=6),)), "verified", 0, 0) + high[name] = SearchResult(replay_moves(evaluator, start, (Move("high", steps=8),)), "verified", 0, 0) + report = MatchResult("matched", "matched", {}, 0.0) + three = LayoutResult(low, tuple(low)[:3], matching={"matched": report}) + four = LayoutResult(high, tuple(high)) + assert _layout_rank(four) < _layout_rank(three) + assert _layout_rank(LayoutResult(low, tuple(low))) < _layout_rank(four) + + +def test_final_layout_verification_preserves_the_incumbent_on_a_conflicting_match(monkeypatch) -> None: + evaluator = MoveEvaluator( + Grid((0, 0), 1, 1e-6), Catalog("joint-verification", {"g": Profile("ridge", 2)}, {"s": StraightVariant("g", 1)}), + ) + board = box(0, 0, 30, 30) + nets = { + name: CatalogNet(Pose(4, y, 0, "g"), Pose(26, y, 0, "g"), seed=(Move("s", steps=22),)) + for name, y in (("a", 9), ("b", 21)) + } + groups = (MatchGroup("joint", {"a": 0, "b": 4}, 1.55e-6, 0.05),) + originals = {name: evaluator.evaluate(net.seed[0], net.start) for name, net in nets.items()} + proposed = {} + for name, net in nets.items(): + line = LineString(((4, net.start.y), (8, net.start.y), (12, 15), (18, 15), (22, net.target.y), (26, net.target.y))) + proposed[name] = (Evaluation(Move("s", steps=22), net.start, net.target, (line.buffer(1, cap_style="flat"),), line.length, 1),) + other = originals["b" if name == "a" else "a"] + assert other is not None + assert verify_path(evaluator, proposed[name], net.start, net.target, board=board, occupied=other.footprints) is None + + original_tune = _catalog_layout.tune_group + + def conflicting_tune(evaluator, group, timing, baselines, windows, verifies, *, proposal_limit): + if proposal_limit == 0: + return original_tune(evaluator, group, timing, baselines, windows, verifies, proposal_limit=0) + return MatchResult("joint", "matched", {"a": Delay(100, 0), "b": Delay(104, 0)}, 0.0), proposed + + monkeypatch.setattr(_catalog_layout, "tune_group", conflicting_tune) + timing = DelayModel(1.55e-6, group_indices={"g": 4}) + result = route_layout(evaluator, nets, LayoutSettings(board, node_limit=0, refinement=False), timing=timing, groups=groups) + assert result.completed == () + assert result.matching["joint"].status == "unmatched" + assert result.matching["joint"].skew == 4 + assert {name: report.path for name, report in result.routes.items()} == {name: (move,) for name, move in originals.items()} + + +@pytest.mark.parametrize(("poses", "expected"), [ + ((((20, 40, 0), (120, 40, 0)), ((120, 70, 180), (20, 70, 180)), ((160, 20, 90), (160, 120, 90))), 400), + ((((20, 160, 45), (50, 190, 45)), ((90, 190, 225), (60, 160, 225)), ((130, 190, 315), (160, 160, 315))), 120 * sqrt(2)), +]) +def test_cardinal_and_diagonal_directions_match_on_total_delay(poses, expected) -> None: + evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog("axes", {"g": Profile("ridge", 4)}, {"s": StraightVariant("g", 1)})) + nets = { + str(i): CatalogNet(Pose(*a, "g"), Pose(*b, "g")) for i, (a, b) in enumerate(poses) + } + settings = LayoutSettings(box(0, 0, 400, 300), clearance=1) + timing = DelayModel(1.55e-6, group_indices={"g": 4}) + group = MatchGroup("matched", dict.fromkeys(nets, 0.0), 1.55e-6, 0.05) + result = route_layout(evaluator, nets, settings, timing=timing, groups=(group,)) + assert result.completed == tuple(nets) + report = result.matching["matched"] + assert report.skew == 0 + assert [delay.optical_length for delay in report.delays.values()] == pytest.approx([expected] * 3) + repeated = MatchGroup("duplicate", {"0": 0}, 1.55e-6, 0) + with pytest.raises(ValueError, match="multiple groups"): + route_layout(evaluator, nets, settings, timing=timing, groups=(group, repeated)) + + +def test_four_turn_tuning_includes_the_window_edge_and_rejects_protrusion() -> None: + evaluator = MoveEvaluator( + Grid((0, 0), 1, 1e-6), Catalog("boundary", {"g": Profile("ridge", 4)}, { + "s": StraightVariant("g", 1), + "left": BendVariant("g", 90, 10, 0.01, sagitta=0.01), + "right": BendVariant("g", -90, 10, 0.01, sagitta=0.01), + }), + ) + original = replay_moves(evaluator, Pose(20, 120, 0, "g"), (Move("s", steps=120),)) + assert original is not None + exact = box(40, 115, 100, 152) + outside = box(40, 115, 100, 151.99) + boundary_candidates = [ + path for path in window_replacements(evaluator, original, exact) if path is not None + and any(shape.bounds[3] == 152 for move in path for shape in move.footprints) + ] + assert boundary_candidates + for path in boundary_candidates: + assert verify_path(evaluator, path, original[0].start, original[0].end, board=box(0, 0, 400, 300)) is None + accepted = tuple(path for path in window_replacements(evaluator, original, outside) if path is not None) + assert accepted + assert all(path not in accepted for path in boundary_candidates) diff --git a/scripts/benchmark_catalog_routing.py b/scripts/benchmark_catalog_routing.py new file mode 100644 index 0000000..776e530 --- /dev/null +++ b/scripts/benchmark_catalog_routing.py @@ -0,0 +1,312 @@ +"""Compare catalog and native routing on 5 mm layouts at 100 nm pitch.""" + +from __future__ import annotations + +import argparse +import json +import platform +import resource +from dataclasses import asdict, dataclass, field +from math import fsum, pi, sqrt +from statistics import median +from time import perf_counter + +from shapely.affinity import scale +from shapely.geometry import Polygon, box + +from inire import NetSpec, ObjectiveWeights, Port, RefinementOptions, RoutingOptions, RoutingProblem, SearchOptions, TopologyOptions, route +from inire._catalog import BendVariant, Catalog, FixedVariant, Grid, Move, MoveEvaluator, Orientation, Pose, Profile, StraightVariant +from inire._catalog_timing import DelayModel +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_verify import replay_moves, verify_path + + +@dataclass(frozen=True, slots=True) +class ScaleCase: + grid: Grid + board: Polygon + nets: dict[str, CatalogNet] + obstacles: tuple[Polygon, ...] + references: dict[str, tuple[Move, ...]] + timing: DelayModel | None = None + groups: tuple[MatchGroup, ...] = () + windows: dict[str, Polygon] = field(default_factory=dict) + clearance: float = 1000.0 + + +def timing_case(name: str) -> ScaleCase: + grid = Grid((0, 0), 100, 1e-9) + if name == "tuning": + nets = { + net: CatalogNet(Pose(20_000, y, 0, "4"), Pose(140_000, y, 0, "4")) + for net, y in (("reference", 40_000), ("adjust", 120_000)) + } + timing = DelayModel(1.55e-6, group_indices={"4": 4}, fixed_contributions={"adjust": (20_000,)}) + group = MatchGroup("delay", {"reference": 0, "adjust": (80 * pi - 60) * 1000}, 1.55e-6, 50) + windows = {"adjust": box(40_000, 115_000, 100_000, 155_000)} + else: + nets = { + net: CatalogNet(Pose(20_000, y, 0, "4"), Pose(140_000, y, 0, "4")) + for net, y in (("reference", 40_000), ("adjust", 120_000), ("independent", 140_000)) + } + timing = DelayModel(1.55e-6, group_indices={"4": 4}) + group = MatchGroup("delay", {"reference": 0, "adjust": -1000}, 1.55e-6, 50) + windows = {"adjust": box(40_000, 115_000, 100_000, 155_000)} + return ScaleCase( + grid, box(0, 0, 400_000, 300_000), nets, (), {net: (Move("4-straight", steps=1200),) for net in nets}, + timing, (group,), windows, + ) + + +def corpus_lanes(name: str) -> ScaleCase: + from inire.tests.routing_corpus import CASE_GROUPS # noqa: PLC0415 + + case = "scale-bank-216-with-keepouts" if name == "corpus-lanes" else "scale-bank-224" + problem = CASE_GROUPS[case][0].problem + grid = Grid((0, 0), 100, 1e-9) + nets = { + net.net_id: CatalogNet( + Pose(1000 * net.start.x, 1000 * net.start.y, net.start.r, "4"), + Pose(1000 * net.target.x, 1000 * net.target.y, net.target.r, "4"), + ) + for net in problem.nets[:12] + } + references = {name: (Move("4-straight", steps=abs(net.target.x - net.start.x) // grid.pitch),) for name, net in nets.items()} + obstacles = tuple(scale(shape, xfact=1000, yfact=1000, origin=(0, 0)) for shape in problem.static_obstacles) + return ScaleCase( + grid, box(*(1000 * coord for coord in problem.bounds)), nets, obstacles, references, clearance=1000 * problem.clearance, + ) + + +def scale_case(name: str) -> ScaleCase: + if name in ("tuning", "retry"): + return timing_case(name) + if name in ("corpus-lanes", "corpus-open-lanes"): + return corpus_lanes(name) + grid = Grid((0, 0), 100, 1e-9) + obstacles = [ + box(x, y, x + 250_000, y + 140_000) + for j in range(8) for i in range(9) + for x, y in ((400_000 + 500_000 * i, 400_000 + 550_000 * j),) + ] + nets = { + f"lane-{row}-{lane}": CatalogNet(Pose(200_000, y, 0, "4"), Pose(4_800_000, y, 0, "4")) + for row in range(8) for lane in range(5) + for y in (170_000 + 550_000 * row + 20_000 * lane,) + } + references = {net: (Move("4-straight", steps=46_000),) for net in nets} + if name == "constrained": + obstacles[0] = box(400_000, 20_000, 650_000, 160_000) + special = "lane-0-0" + nets[special] = CatalogNet(Pose(200_000, 60_000, 0, "4"), Pose(4_800_000, 60_000, 0, "4")) + references[special] = ( + Move("4-straight", steps=1700), Move("right-90", displacement=(10_000, -10_000)), + Move("4-straight", steps=300), Move("left-90", displacement=(10_000, -10_000)), + Move("4-straight", steps=2800), Move("left-90", displacement=(10_000, 10_000)), + Move("4-straight", steps=300), Move("right-90", displacement=(10_000, 10_000)), + Move("4-straight", steps=41_100), + ) + if name == "diagonal-savings": + special = "lane-7-4" + nets[special] = CatalogNet(Pose(300_000, 4_500_000, 0, "4"), Pose(700_000, 4_700_000, 0, "4")) + references[special] = ( + Move("4-straight", steps=200), Move("left-90", displacement=(10_000, 10_000)), + Move("4-straight", steps=1800), Move("right-90", displacement=(10_000, 10_000)), Move("4-straight", steps=3600), + ) + if name == "diagonal": + special = "lane-7-4" + nets[special] = CatalogNet(Pose(300_000, 4_600_000, 45, "4"), Pose(500_000, 4_800_000, 45, "4")) + references[special] = (Move("4-straight", steps=2000),) + if name == "off-coarse": + grid = Grid((0, 0), 1, 1e-9) + nets = {"displaced": CatalogNet(Pose(20_001, 30_001, 0, "4"), Pose(170_001, 30_201, 0, "8"))} + references = {"displaced": (Move("displaced", traversal=("a", "b")), Move("8-straight", steps=50_000))} + return ScaleCase(grid, box(0, 0, 5_000_000, 5_000_000), nets, tuple(obstacles), references) + + +def catalog(mode: str, case: str) -> Catalog: + profiles = {"4": Profile("4 µm", 4000), "5": Profile("5 µm", 5000), "8": Profile("8 µm", 8000)} + variants: dict[str, StraightVariant | FixedVariant | BendVariant] = {"4-straight": StraightVariant("4", 1)} + if mode in ("typed", "octagonal"): + variants["5-straight"] = StraightVariant("5", 0.5) + variants["centered"] = FixedVariant( + "centered", + {"a": Pose(0, 0, 0, "4"), "b": Pose(10_000, 0, 180, "5")}, + (Polygon(((0, -2000), (10_000, -2500), (10_000, 2500), (0, 2000))),), + (("a", "b"), ("b", "a")), (Orientation(), Orientation(180)), 0.01, 10_000, + ) + if case in ("constrained", "diagonal-savings", "tuning"): + variants["left-90"] = BendVariant("4", 90, 10_000, 0.01, sagitta=30) + variants["right-90"] = BendVariant("4", -90, 10_000, 0.01, sagitta=30) + if mode == "octagonal": + variants["left-45"] = BendVariant("4", 45, 10_000, 0.01, max_lead=200, lead_cost_per_cm=1, sagitta=30) + variants["right-45"] = BendVariant("4", -45, 10_000, 0.01, max_lead=200, lead_cost_per_cm=1, sagitta=30) + if case == "off-coarse": + variants["8-straight"] = StraightVariant("8", 0.2) + variants["displaced"] = FixedVariant( + "displaced", {"a": Pose(0, 0, 0, "4"), "b": Pose(100_000, 200, 180, "8")}, + (Polygon(((0, -2000), (100_000, -3800), (100_000, 4200), (0, 2000))),), + (("a", "b"),), (Orientation(),), 0.2, 100_010, + ) + return Catalog("scale", profiles, variants) + + +def verify_references(case: ScaleCase, technology: Catalog) -> None: + evaluator = MoveEvaluator(case.grid, technology) + placed = {} + for name, recipe in case.references.items(): + net = case.nets[name] + path = replay_moves(evaluator, net.start, recipe) + if path is None: + raise AssertionError(f"Reference recipe did not evaluate for {name}") + placed[name] = path + for name, path in placed.items(): + net = case.nets[name] + occupied = tuple(shape for owner, other in placed.items() if owner != name for piece in other for shape in piece.footprints) + error = verify_path( + evaluator, path, net.start, net.target, board=case.board, keepouts=case.obstacles, occupied=occupied, clearance=case.clearance, + ) + if error is not None: + raise AssertionError(f"Invalid reference for {name}: {error}") + + +def run_catalog(case: ScaleCase, technology: Catalog, args: argparse.Namespace) -> tuple[dict, float]: + settings = LayoutSettings( + case.board, case.obstacles, clearance=case.clearance, node_limit=args.node_limit, refinement=not args.no_refinement, + guidance=None if args.guide_pitch is None else CoarseGuidance(args.guide_pitch), + retry_independent=not args.no_independent_retry, + ) + start = perf_counter() + grid = case.grid + if args.auto_pitch is not None: + terminals = tuple(pose for net in case.nets.values() for pose in (net.start, net.target)) + grid = AutomaticGrid(args.auto_pitch, grid.meters_per_unit).select(terminals, technology) + result = route_layout( + MoveEvaluator(grid, technology), case.nets, settings, + timing=case.timing, groups=case.groups, windows=case.windows, + ) + elapsed = perf_counter() - start + paths = {name: result.routes[name].path or () for name in result.completed} + expanded = sum(attempt.expanded for attempt in result.attempts) + proposed = sum(attempt.proposed for attempt in result.attempts) + measurements = { + "proposals_per_expansion": proposed / expanded if expanded else None, + "completed": result.completed, + "verified": tuple(name for name, report in result.routes.items() if report.path is not None), + "matching": {name: asdict(report) for name, report in result.matching.items()}, + "outcomes": {name: report.outcome for name, report in result.routes.items()}, + "per_net": { + name: {"cost": result.routes[name].cost, "length_nm": result.routes[name].length} + for name in paths + }, + "routing_pitch_nm": grid.pitch, + "typed_improvements": sum(any(move.move.variant == "centered" for move in path) for path in paths.values()), + "used_guidance": sum(report.used_guidance for report in result.routes.values()), + "guide_fallbacks": sum(report.guide_fallback for report in result.routes.values()), + "profile_fallbacks": sum(report.profile_fallback for report in result.routes.values()), + "attempts": [asdict(attempt) for attempt in result.attempts], + } + if args.geometry: + measurements["polygons"] = { + name: [shape.wkb_hex for move in path for shape in move.footprints] for name, path in paths.items() + } + measurements["moves"] = {name: [asdict(piece.move) for piece in path] for name, path in paths.items()} + return measurements, elapsed + + +def run_native(case: ScaleCase, args: argparse.Namespace) -> tuple[dict, float]: + pitch = case.grid.pitch + specs = tuple( + NetSpec(name, Port(net.start.x // pitch, net.start.y // pitch, net.start.heading), + Port(net.target.x // pitch, net.target.y // pitch, net.target.heading), width=4000 / pitch) + for name, net in case.nets.items() + ) + problem = RoutingProblem( + tuple(value / pitch for value in case.board.bounds), specs, + tuple(scale(shape, xfact=1 / pitch, yfact=1 / pitch, origin=(0, 0)) for shape in case.obstacles), + clearance=case.clearance / pitch, + ) + rate = pitch * case.grid.meters_per_unit * 100 + radius = 10_000 / pitch + options = RoutingOptions( + search=SearchOptions(node_limit=args.node_limit, max_straight_length=50_000, bend_radii=(radius,), sbend_radii=()), + objective=ObjectiveWeights(unit_length_cost=rate, bend_penalty=(0.01 - radius * pi / 2 * rate) * sqrt(radius / 10), danger_weight=0), + topology=TopologyOptions(mode="off"), + refinement=RefinementOptions(enabled=not args.no_refinement), + ) + start = perf_counter() + result = route(problem, options=options) + elapsed = perf_counter() - start + paths = {name: outcome.path for name, outcome in result.results_by_net.items() if outcome.is_valid} + metrics = result.metrics + measurements = { + "completed": tuple(paths), + "outcomes": {name: outcome.outcome for name, outcome in result.results_by_net.items()}, + "per_net": { + name: { + "cost": fsum(move.length * rate if move.move_type == "straight" else 0.01 for move in path), + "length_nm": fsum(move.length * pitch for move in path), + } + for name, path in paths.items() + }, + "expanded": metrics.nodes_expanded, + "proposed": metrics.moves_generated, + "proposals_per_expansion": metrics.moves_generated / metrics.nodes_expanded if metrics.nodes_expanded else None, + "geometry_cache_hits": metrics.move_cache_abs_hits + metrics.move_cache_rel_hits, + "geometry_cache_misses": metrics.move_cache_abs_misses + metrics.move_cache_rel_misses, + "exact_ray_checks": metrics.ray_cast_exact_geometry_checks, + } + if args.geometry: + measurements["polygons"] = { + name: [ + scale(shape, xfact=pitch, yfact=pitch, origin=(0, 0)).wkb_hex for move in path for shape in move.physical_geometry + ] for name, path in paths.items() + } + return measurements, elapsed + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--mode", choices=("native", "manhattan", "typed", "octagonal"), default="typed") + parser.add_argument( + "--case", default="aligned", + choices=( + "aligned", "constrained", "diagonal-savings", "diagonal", "off-coarse", "tuning", "retry", "corpus-lanes", "corpus-open-lanes", + ), + ) + parser.add_argument("--guide-pitch", type=int, help="coarse pitch in nanometers") + parser.add_argument("--auto-pitch", type=int, help="preferred pitch for automatic grid selection in nanometers") + parser.add_argument("--repeat", type=int, default=3) + parser.add_argument("--node-limit", type=int, default=1000) + parser.add_argument("--no-refinement", action="store_true") + parser.add_argument("--no-independent-retry", action="store_true") + parser.add_argument("--geometry", action="store_true") + args = parser.parse_args() + if args.repeat < 1: + parser.error("--repeat must be positive") + if args.case == "diagonal" and args.mode != "octagonal": + parser.error("The native-diagonal terminal case requires octagonal mode") + if args.mode == "native" and ( + args.guide_pitch is not None or args.auto_pitch is not None + or args.case not in ("constrained", "aligned", "diagonal-savings", "corpus-lanes", "corpus-open-lanes") + ): + parser.error("Native mode needs a case with cardinal terminals on the explicit grid") + case = scale_case(args.case) + technology = catalog(args.mode, args.case) + verify_references(case, technology) + samples = [] + measurements = {} + for _ in range(args.repeat): + measurements, elapsed = run_native(case, args) if args.mode == "native" else run_catalog(case, technology, args) + samples.append(elapsed) + print(json.dumps({ + "options": vars(args), "machine": platform.machine(), "python": platform.python_version(), "requested": len(case.nets), + "wall_seconds": samples, "median_seconds": median(samples), "peak_rss": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss, + "catalog_cost": fsum(entry["cost"] for entry in measurements["per_net"].values()), **measurements, + }, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/scripts/capture_legacy_routing.py b/scripts/capture_legacy_routing.py new file mode 100644 index 0000000..007df06 --- /dev/null +++ b/scripts/capture_legacy_routing.py @@ -0,0 +1,92 @@ +"""Capture routes and deterministic work on the legacy corpus and holdouts.""" + +import argparse +import json +import platform +import subprocess +from dataclasses import asdict, replace +from importlib.metadata import version +from pathlib import Path +from statistics import median +from time import perf_counter + +import shapely + +from inire import route +from inire.tests.routing_corpus import automatic_options, profile_options, select_cases + + +def capture(repeat: int, revision: str | None) -> dict: + cases = select_cases(("corpus", "retry-holdout")) + runs = {} + for case in cases: + options = automatic_options(profile_options(case, "corpus-regression"), "corpus-regression") + attempts = {"automatic": options} + if case.problem.initial_paths: + attempts["verify-only"] = replace(options, search=replace(options.search, node_limit=0)) + for mode, settings in attempts.items(): + key = f"{case.name}:{mode}" + timings = [] + reference = None + stable = True + for _ in range(repeat): + started = perf_counter() + run = route(case.problem, options=settings) + timings.append(perf_counter() - started) + metrics = asdict(run.metrics) + sample = { + "options": repr(settings), + "metrics": {key: value for key, value in metrics.items() if not key.endswith("_ns")}, + "results": { + net_id: { + "verified": result.is_valid, + "outcome": result.outcome, + "effective_net": repr(result.effective_net), + "path": [ + { + "move": repr(move.move_spec), + "start": move.start_port.as_tuple(), + "end": move.end_port.as_tuple(), + "length": move.length, + "physical_wkb": [shape.wkb_hex for shape in move.physical_geometry], + } + for move in result.path + ], + } + for net_id, result in run.results_by_net.items() + }, + } + if reference is None: + reference = sample + elif reference != sample: + stable = False + assert reference is not None + runs[key] = {**reference, "wall_seconds": median(timings), "wall_samples": timings, "stable": stable} + return { + "revision": revision or subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip(), + "tracked_worktree": ( + subprocess.check_output(["git", "status", "--short", "--untracked-files=no"], text=True).splitlines() + if revision is None else [] + ), + "versions": { + "python": platform.python_version(), + "geos": shapely.geos_version_string, + **{name: version(name) for name in ("numpy", "scipy", "shapely", "rtree")}, + }, + "runs": runs, + } + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("output", type=Path) + parser.add_argument("--repeat", type=int, default=1) + parser.add_argument("--revision", help="source revision when running against a Git archive") + args = parser.parse_args() + if args.repeat < 1: + parser.error("--repeat must be positive") + args.output.write_text(json.dumps(capture(args.repeat, args.revision), indent=2) + "\n") + + +if __name__ == "__main__": + main()