From e6ae242cb262740d2e250e9297b9833703d9768f Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Sat, 28 Nov 2026 20:42:25 -0800 Subject: [PATCH] Bound search memory and verify process geometry before layout export --- DOCS.md | 1 + docs/routing-diagnostics.md | 2 + docs/user/api-reference.md | 4 +- docs/user/fabrication.md | 89 ++++++++++++++ docs/user/route-a-layout.md | 4 + inire/geometry/collision.py | 14 +++ inire/geometry/components.py | 37 ++++-- inire/layout.py | 166 ++++++++++++++++++++++++++ inire/model.py | 19 ++- inire/results.py | 2 + inire/router/_astar_admission.py | 16 ++- inire/router/_astar_types.py | 40 ++++--- inire/router/_automatic.py | 10 +- inire/router/_compact.py | 8 +- inire/router/_pair_local.py | 5 +- inire/router/_routing_policy.py | 4 +- inire/router/_search.py | 11 ++ inire/router/_seed_materialization.py | 5 +- inire/router/_stack.py | 18 +-- inire/router/cost.py | 15 ++- inire/router/danger_map.py | 68 ++++++++--- inire/router/refiner.py | 3 +- inire/tests/test_astar.py | 3 + inire/tests/test_cost.py | 27 ++++- inire/tests/test_layout.py | 154 ++++++++++++++++++++++++ inire/utils/visualization.py | 16 +-- plans/full-project-review.md | 6 + 27 files changed, 645 insertions(+), 102 deletions(-) create mode 100644 docs/user/fabrication.md create mode 100644 inire/layout.py create mode 100644 inire/tests/test_layout.py diff --git a/DOCS.md b/DOCS.md index 2268d67..a9cf9b9 100644 --- a/DOCS.md +++ b/DOCS.md @@ -23,6 +23,7 @@ If you're new to Inire, start with the [single-net quick start](README.md#route- - [Check the result](docs/user/tune-and-troubleshoot.md#read-the-result) to see whether each net reached its target port and passed verification. - [Export verified geometry](docs/user/route-a-layout.md#export-verified-geometry) to use the physical polygons in your layout. +- [Check geometry against fabrication inputs](docs/user/fabrication.md) for layout-grid rounding, process layers, optical joins, and coplanar waveguides. - [Diagnose an unfinished net](docs/user/tune-and-troubleshoot.md#why-a-net-stopped-short) to decide whether to change the layout or spend more search time. - [Choose a routing mode](docs/user/tune-and-troubleshoot.md#choose-a-routing-mode) when your layout calls for a specific planner. - [Adjust a setting](docs/user/tune-and-troubleshoot.md#choose-the-next-setting) if routes collide, take too long, or use too many bends. diff --git a/docs/routing-diagnostics.md b/docs/routing-diagnostics.md index 6f716b8..807e3d1 100644 --- a/docs/routing-diagnostics.md +++ b/docs/routing-diagnostics.md @@ -24,6 +24,8 @@ Pair each counter with a question about the work. Use a repeated wall-time compa `nets_routed` and `nets_reached_target` count attempts. Use `result.is_valid` or `verified_net_ids` to count final successes. Duration counters ending in `_total_ns` can vary between identical runs. For the full field list, see the [`RouteMetrics` definition](../inire/results.py). +Search bounds the two move caches by entries and polygon coordinates. It drops the corresponding static-admission keys when evicting positioned moves. An unusually large live frontier drops dominated nodes and retains the best 40,000 entries once it exceeds 50,000. Check `frontier_trim_events` and `frontier_nodes_discarded` when diagnosing a large failed attempt. + ## Traces Enable the `DiagnosticsOptions` flag for the question you want to answer. diff --git a/docs/user/api-reference.md b/docs/user/api-reference.md index 4f4376f..63c7e89 100644 --- a/docs/user/api-reference.md +++ b/docs/user/api-reference.md @@ -80,8 +80,10 @@ To read a route's polygons and write them to a test file, follow the [geometry e | `bend_clip_margin` | `None` | Optional legacy shrink margin for `"clipped_bbox"`. The default uses an eight-point proxy for each arc and extends it along any grid tangents. | | `visibility_guidance` | `"tangent_corner"` | Choose tangent candidates, exact corner visibility with `"exact_corner"`, or no visibility suggestions with `"off"`. | | `sbend_outlines` | `()` | Complete custom S-bend polygons, supplied as `SBendOutline(offset, radius, width, polygon)` entries. Each entry applies to its signed offset, radius, and net width. | +| `proximity_range` | `10.0` | Obstacle proximity scoring range in layout units. Scale it with the coordinates when changing units. Large perimeters use an exact boundary index once the sample budget is reached. | +| `bend_physical_length` | `None` | Optional authored centerline length for the shared custom 90-degree template, including tangent extensions. Search, refinement, and reports use it when supplied. | -A custom S-bend outline uses local coordinates. Its input face is centered at `(0, 0)`, its output face at `(span, offset)`, and both ports face east. Use the same grid span as `SBendSeed(offset, radius)`, including any tangent extension to reach the output face. For example, an offset of `40` with radius `50` has its output at `(80, 40)`. The router rotates and translates the entire outline and uses it for collision checks and export. Supply a separate outline to customize the opposite offset. Width matching allows a relative difference of `1e-12` to account for floating-point conversions. An ambiguous match raises an error. Unmatched moves use the circular S-bend, and matching moves use the same nominal length as that circular bend for scoring. Automatic mode uses lattice search when a registered outline matches a net width. Bundle mode requires circular bends for its nets. +A custom S-bend outline uses local coordinates. Its input face is centered at `(0, 0)`, its output face at `(span, offset)`, and both ports face east. Use the same grid span as `SBendSeed(offset, radius)`, including any tangent extension to reach the output face. For example, an offset of `40` with radius `50` has its output at `(80, 40)`. The router rotates and translates the entire outline and uses it for collision checks and export. Supply a separate outline to customize the opposite offset. Width matching allows a relative difference of `1e-12` to account for floating-point conversions. An ambiguous match raises an error. Unmatched moves use the circular S-bend. Set `SBendOutline.length` to use a process-specific centerline length for scoring, refinement, and reporting. The default is the nominal circular length. Automatic mode uses lattice search when a registered outline matches a net width. Bundle mode requires circular bends for its nets. When migrating a half-arc template, supply the complete outline through `sbend_outlines` and keep `bend_physical_geometry` for custom 90-degree bends. Both terminal faces of each custom polygon must be centered on their ports and match the routed width. A custom 90-degree template is shared across nets, so it can only be used by nets whose width matches its faces. Replay an `SBendSeed` with the same outlines and bend settings to recover its physical geometry. diff --git a/docs/user/fabrication.md b/docs/user/fabrication.md new file mode 100644 index 0000000..9f00901 --- /dev/null +++ b/docs/user/fabrication.md @@ -0,0 +1,89 @@ +# Check routed geometry before fabrication + +Inire checks continuity, board containment, and clearance for the shapes and constraints in the routing problem. The placed-cell and process data determine port compatibility, layer assignment, length tolerances, and conductor connectivity. Keep those values with the layout through verification and export. + +## Check placed optical ports + +Read the physical widths from the placed devices' port metadata. `PlacedPort.connect` checks both declared widths before constructing the constant-width net. + +```python +from inire import Port +from inire.layout import PlacedPort + +source = PlacedPort(Port(10000, 10000, 0), width=500) +taper_input = PlacedPort(Port(70000, 10000, 0), width=500) +net = source.connect("source_to_taper", taper_input) +``` + +For a 3,000 nm target, place the 40 µm taper with its 500 nm face at `taper_input` and its 3,000 nm face abutting the target. Include the placed taper in the cell geometry and open only the intentional join in the routing keepouts. Check the two actual joins in the assembled layer after writing the file. [EBeam taper cell](https://github.com/SiEPIC/SiEPIC_EBeam_PDK/blob/363fbb52eefa8669100499ab531d3fe7befc4867/klayout/EBeam/gds/EBeam/ebeam_routing_taper_te1550_w%3D500nm_to_w%3D3000nm_L%3D40um.gds) + +## Preserve length-sensitive paths + +Keep the original polygons and authored length when rerouting one arm of an interferometer. Compare the replacement to the tolerance supplied by the circuit designer. For a matched pair, compare the signed difference between the two arm lengths before and after the replacement. + +```python +from inire.layout import preserves_length + +# Lengths are in the same units as the routing layout. +geometry = replacement.locked_geometry if preserves_length(replacement, authored_length, length_tolerance) else original_geometry +``` + +An authored 286.770 µm path in the Raymond MZI array can be replaced geometrically by a 127.208 µm route. If the circuit uses process-specific Bézier bends, supply the measured centerline length with the custom bend template and use the same setting for search and replay. Use the geometry comparison above to retain the original path when the replacement falls outside the circuit tolerance. [Raymond MZI layout](https://github.com/SiEPIC/openEBL-2025-02/blob/a887476a301db2a014be007717cd1821e111f58e/submissions/EBeam_hannahraymond_MZIv21.gds) · [Custom bend lengths](api-reference.md#searchoptions) + +## Check the export grid + +Use the layout writer's rounding grid in routing units. `verify_export_grid` rounds route vertices while holding the supplied keepouts fixed. Supply the actual keepout geometry as it will appear in the file. Export the returned polygons only if their reports pass. Recheck the assembled cell after writing when the writer performs further operations such as path merging or coordinate transforms. + +```python +from inire.layout import verify_export_grid + +verified = {name: result for name, result in run.results_by_net.items() if result.is_valid} +export = verify_export_grid(problem, verified, grid=1.0) +assert export.is_valid, export.reports_by_net +geometry_by_net = export.geometry_by_net +``` + +For example, two concentric bends with approximately 70.02 nm floating-point clearance can fall below 70 nm on a 1 nm grid. Use an allowed finer database unit or increase the route's margin, then recheck the rounded geometry and run the process deck. [Pinned EBeam spacing deck](https://github.com/SiEPIC/SiEPIC_EBeam_PDK/blob/363fbb52eefa8669100499ab531d3fe7befc4867/klayout/EBeam/drc/SiEPIC_EBeam.drc) + +## Keep layers and process profiles with the nets + +Each `RoutingProblem` represents one collision plane. Group independent layers by the layer and datatype used by the writer, then keep that pair on the output. Add projected keepouts from other layers when the process requires cross-layer spacing. Keep intentional transitions between layers as placed circuit devices. + +```python +from inire import RoutingProblem, route +from inire.layout import partition_layers, verify_export_grid + +geometry_by_layer = {} +for layer, nets in partition_layers([((1, 0), silicon_net), ((4, 0), nitride_net)]).items(): + plane = RoutingProblem(bounds, nets, static_obstacles=keepouts_by_layer[layer], clearance=clearance_by_layer[layer]) + run = route(plane, options=options_by_layer[layer]) + export = verify_export_grid(plane, run.results_by_net, grid=1.0) + assert export.is_valid, export.reports_by_net + geometry_by_layer[layer] = export.geometry_by_net +``` + +For different bend rules on the same layer, supply each group's allowed radii in `SearchOptions`. `route_profiles` applies those options to search, seed replay, and refinement, and reserves the verified groups in the order supplied. In the QFoundry example, the flux line can use 15 µm radius while the feedline requires at least 50 µm although both have a 15.5 µm signal width and 7 µm gaps. [QFoundry process profiles](https://github.com/tii-qfoundry/PDK_QFoundry/blob/9c31db1d6879c96bd98460ee134181a865481d75/qfoundry/tech/waveguides.xml#L21-L64) + +```python +from inire.layout import route_profiles + +results = route_profiles(plane, [ + (("flux",), flux_options), + (("feed",), feed_options), +]) +``` + +## Verify a coplanar waveguide cross-section + +For a 15.5 µm signal with a 7 µm gap on each side, route the 29.5 µm envelope. Use the required ground-strip width as the clearance between envelopes. Replay the verified seed with a 15.5 µm net using the same ports and bend rules. The conductor and envelope together define the negative gap mask. A separate wider ground exclusion can be buffered locally from the envelope. This fills the inside of turns where a constant-width circular strip wider than the bend diameter would collapse. + +```python +from inire.layout import coplanar_geometry + +cpw = coplanar_geometry(verified_signal, verified_envelope, ground_margin=10000) +signal = cpw.conductor +negative_gap_mask = cpw.gaps +ground_exclusion = cpw.ground_exclusion +``` + +On the 1 nm grid, a 3 µm minimum ground strip rejects the 28 µm and 32 µm pitches. A 36 µm pitch leaves a 6.5 µm strip. After applying the negative mask in the layout tool, check that the expected ground regions are connected and that separate signal conductors remain separate. For a coupling capacitor, route one connection on either side of the intentional conductor break and keep its etch mask in the layout. Removing that mask can short the two sections even when a width check passes. [QFoundry DRC](https://github.com/tii-qfoundry/PDK_QFoundry/blob/9c31db1d6879c96bd98460ee134181a865481d75/qfoundry/tech/drc/drc.lydrc) · [CPW chip with coupling capacitor](https://github.com/paulggin/klayout-cpw-design/blob/a38dc34cf6785ba0af41b27f43b6137fd2b69cc7/layouts/cpw_full_layout.gds) diff --git a/docs/user/route-a-layout.md b/docs/user/route-a-layout.md index 95e5a0d..4101986 100644 --- a/docs/user/route-a-layout.md +++ b/docs/user/route-a-layout.md @@ -65,10 +65,14 @@ assert result.is_valid Before export, check the port joins and clearance against the actual placed-cell geometry. Inire verifies the external route against the keepouts you supplied. +For declared port widths and transition cells, see [Check placed optical ports](fabrication.md#check-placed-optical-ports). + ## Export verified geometry Use `result.locked_geometry` to pass a verified net's physical polygons to a layout writer. To inspect the coordinates in a text file, continue from the quick start or the crossing example and write the polygons as well-known text (WKT). Keep track of your coordinate unit when importing the file into another tool. +Port positions snap to integers. Arc vertices can remain fractional. If the writer uses an integer database grid, [verify the coordinates that will be written](fabrication.md#check-the-export-grid). + ```python from pathlib import Path diff --git a/inire/geometry/collision.py b/inire/geometry/collision.py index 2d4a85b..3b79488 100644 --- a/inire/geometry/collision.py +++ b/inire/geometry/collision.py @@ -24,6 +24,7 @@ if TYPE_CHECKING: from inire.geometry.components import ComponentResult from inire.geometry.primitives import Port + from inire.model import RoutingProblem _RAY_CAST_CACHE_LIMIT = 8192 @@ -128,6 +129,19 @@ class RoutingWorld: self._static_obstacles = StaticObstacleIndex(self) self._dynamic_paths = DynamicPathIndex(self) + @classmethod + def from_problem(cls, problem: RoutingProblem, *, board: Polygon | None = None) -> RoutingWorld: + world = cls( + clearance=problem.clearance, + safety_zone_radius=problem.safety_zone_radius, + board=box(*problem.bounds) if board is None else board, + self_clearance=problem.self_clearance, + ) + reserved_ids = {id(polygon) for polygon in problem._reserved_obstacles} + for obstacle in problem.static_obstacles: + world.add_static_obstacle(obstacle, reserved=id(obstacle) in reserved_ids) + return world + def get_static_version(self) -> int: return self._static_obstacles.version diff --git a/inire/geometry/components.py b/inire/geometry/components.py index 26d3bf5..dfa1d22 100644 --- a/inire/geometry/components.py +++ b/inire/geometry/components.py @@ -1,12 +1,12 @@ from __future__ import annotations -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from itertools import pairwise from math import asin, ceil, pi, radians, sqrt from typing import TYPE_CHECKING, Literal import numpy -from shapely import snap +from shapely import get_num_coordinates, snap from shapely.affinity import rotate as shapely_rotate from shapely.affinity import scale as shapely_scale from shapely.affinity import translate as shapely_translate @@ -151,6 +151,7 @@ class ComponentResult: _total_physical_bounds: tuple[float, float, float, float] | None = field(init=False, repr=False, compare=False, default=None) _physical_checks: tuple[bool, bool] | None = field(init=False, repr=False, compare=False, default=None) _port_faces: tuple[PortFace | None, PortFace | None] | None = field(init=False, repr=False, compare=False, default=None) + _coordinate_count: int | None = field(init=False, repr=False, compare=False, default=None) def __post_init__(self) -> None: collision_geometry = tuple(self.collision_geometry) @@ -201,6 +202,19 @@ class ComponentResult: def bend_radius(self) -> float | None: return self.move_spec.radius if isinstance(self.move_spec, Bend90Seed) else None + @property + def coordinate_count(self) -> int: + count = self._coordinate_count + if count is None: + polygons = { + id(polygon): polygon + for group in (self.physical_geometry, self.collision_geometry, self.dilated_physical_geometry, self.dilated_collision_geometry) + for polygon in group + } + count = sum(int(get_num_coordinates(polygon)) for polygon in polygons.values()) + object.__setattr__(self, "_coordinate_count", count) + return count + @property def port_faces(self) -> tuple[PortFace | None, PortFace | None]: if self._port_faces is None: @@ -242,7 +256,7 @@ class ComponentResult: geometry.append(shifted) return tuple(geometry) - return ComponentResult( + result = ComponentResult( start_port=self.start_port.translate(dx, dy), collision_geometry=translate_geometry(self.collision_geometry), end_port=self.end_port.translate(dx, dy), @@ -255,6 +269,8 @@ class ComponentResult: width=self.width, standard_faces=self.standard_faces, ) + object.__setattr__(result, "_coordinate_count", self._coordinate_count) + return result def _combine_bounds(bounds_list: list[tuple[float, float, float, float]]) -> tuple[float, float, float, float]: @@ -670,16 +686,19 @@ def build_component( clip_margin: float | None, dilation: float, sbend_outline: Polygon | None = None, + physical_length: float | None = None, ) -> ComponentResult: if kind == "straight": return Straight.generate(start, parameters[0], width, dilation=dilation) if kind == "bend90": - return Bend90.generate( + component = Bend90.generate( start, parameters[0], width, parameters[1], collision_type=collision_type, physical_geometry_type=physical_geometry_type, clip_margin=clip_margin, dilation=dilation, ) - return SBend.generate( - start, parameters[0], parameters[1], width, - collision_type="arc" if isinstance(collision_type, Polygon) else collision_type, - outline=sbend_outline, clip_margin=clip_margin, dilation=dilation, - ) + else: + component = SBend.generate( + start, parameters[0], parameters[1], width, + collision_type="arc" if isinstance(collision_type, Polygon) else collision_type, + outline=sbend_outline, clip_margin=clip_margin, dilation=dilation, + ) + return replace(component, length=physical_length) if physical_length is not None else component diff --git a/inire/layout.py b/inire/layout.py new file mode 100644 index 0000000..71b3179 --- /dev/null +++ b/inire/layout.py @@ -0,0 +1,166 @@ +"""Checks for assembling and exporting routed geometry with process data.""" + +from __future__ import annotations + +from dataclasses import dataclass, replace +from math import fsum, isfinite +from typing import TYPE_CHECKING + +from shapely import set_precision, union_all + +from inire import route +from inire.constants import TOLERANCE_LINEAR +from inire.geometry.collision import RoutingWorld +from inire.model import NetSpec + +if TYPE_CHECKING: + from collections.abc import Iterable, Mapping + + from shapely.geometry.base import BaseGeometry + from shapely.geometry import Polygon + + from inire.geometry.components import ComponentResult + from inire.geometry.primitives import Port + from inire.model import RoutingOptions, RoutingProblem + from inire.results import RoutingReport, RoutingResult + + +@dataclass(frozen=True, slots=True) +class PlacedPort: + port: Port + width: float + + def __post_init__(self) -> None: + if not isfinite(self.width) or self.width <= 0: + raise ValueError("Placed port width must be finite and positive") + + def connect(self, net_id: str, target: PlacedPort) -> NetSpec: + if abs(self.width - target.width) > TOLERANCE_LINEAR: + raise ValueError(f"Net {net_id!r} joins widths {self.width:g} and {target.width:g}; place a transition first") + return NetSpec(net_id, self.port, target.port, self.width) + + +@dataclass(frozen=True, slots=True) +class ExportVerification: + geometry_by_net: dict[str, tuple[Polygon, ...]] + reports_by_net: dict[str, RoutingReport] + + @property + def is_valid(self) -> bool: + return all(report.is_valid for report in self.reports_by_net.values()) + + +def verify_export_grid( + problem: RoutingProblem, + results: Mapping[str, RoutingResult], + *, + grid: float, +) -> ExportVerification: + """Round vertices to the export grid and check the geometry the writer will receive.""" + if not isfinite(grid) or grid <= 0: + raise ValueError("Export grid must be finite and positive") + net_ids = {net.net_id for net in problem.nets} + paths: dict[str, tuple[ComponentResult, ...]] = {} + for net_id, result in results.items(): + if net_id not in net_ids or net_id != result.net_id: + raise ValueError(f"Export result {net_id!r} has no matching routing net") + if not result.is_valid: + raise ValueError(f"Export result {net_id!r} must already be verified") + paths[net_id] = tuple(_round_component(component, grid) for component in result.path) + + world = RoutingWorld.from_problem(problem) + for net_id, path in paths.items(): + # Invalid snapped outlines still get a report. Only valid polygons can enter the index. + if all(component.physical_checks[0] for component in path): + world.install_path(net_id, path) + return ExportVerification( + geometry_by_net={ + net_id: tuple(polygon for component in path for polygon in component.physical_geometry) + for net_id, path in paths.items() + }, + reports_by_net={net_id: world.verify_path_report(net_id, path) for net_id, path in paths.items()}, + ) + + +def _round_component(component: ComponentResult, grid: float) -> ComponentResult: + rounded = tuple(set_precision(polygon, grid, mode="pointwise") for polygon in component.physical_geometry) + return replace( + component, physical_geometry=rounded, collision_geometry=rounded, + dilated_physical_geometry=rounded, dilated_collision_geometry=rounded, + standard_faces=False, width=None, + ) + + +def preserves_length(result: RoutingResult, authored_length: float, tolerance: float) -> bool: + """Check the recorded length of a verified replacement against an authored length.""" + if not isfinite(authored_length) or authored_length <= 0 or not isfinite(tolerance) or tolerance < 0: + raise ValueError("Authored length must be finite and positive and tolerance finite and nonnegative") + return result.is_valid and abs(fsum(component.length for component in result.path) - authored_length) <= tolerance + + +@dataclass(frozen=True, slots=True) +class CPWGeometry: + conductor: BaseGeometry + gaps: BaseGeometry + ground_exclusion: BaseGeometry + + +def coplanar_geometry( + conductor: RoutingResult, + gap_envelope: RoutingResult, + *, + ground_margin: float = 0.0, +) -> CPWGeometry: + """Assemble a negative gap mask and optional wider ground exclusion for one CPW.""" + if not isfinite(ground_margin) or ground_margin < 0: + raise ValueError("CPW ground margin must be finite and nonnegative") + if not conductor.is_valid or not gap_envelope.is_valid or conductor.as_seed() != gap_envelope.as_seed(): + raise ValueError("CPW conductor and gap envelope need verified geometry from the same seed") + if any( + a.start_port != b.start_port or a.end_port != b.end_port for a, b in zip(conductor.path, gap_envelope.path, strict=True) + ): + raise ValueError("CPW conductor and gap envelope must use the same ports") + core = union_all(conductor.locked_geometry) + envelope = union_all(gap_envelope.locked_geometry) + if not envelope.covers(core) and not envelope.buffer(TOLERANCE_LINEAR).covers(core): + raise ValueError("CPW gap envelope must contain its conductor") + return CPWGeometry(core, envelope.difference(core), envelope.buffer(ground_margin) if ground_margin else envelope) + + +def partition_layers(nets_with_layers: Iterable[tuple[tuple[int, int], NetSpec]]) -> dict[tuple[int, int], tuple[NetSpec, ...]]: + """Group nets by layout layer and datatype while retaining their input order.""" + layers: dict[tuple[int, int], list[NetSpec]] = {} + seen = set() + for layer, net in nets_with_layers: + if net.net_id in seen: + raise ValueError(f"Duplicate net ID across layout layers: {net.net_id!r}") + seen.add(net.net_id) + layers.setdefault(layer, []).append(net) + return {layer: tuple(nets) for layer, nets in layers.items()} + + +def route_profiles( + problem: RoutingProblem, + profiles: Iterable[tuple[Iterable[str], RoutingOptions]], +) -> dict[str, RoutingResult]: + """Route each group on the same layer and reserve earlier verified geometry.""" + groups = tuple((tuple(net_ids), options) for net_ids, options in profiles) + net_by_id = {net.net_id: net for net in problem.nets} + assigned = [net_id for net_ids, _ in groups for net_id in net_ids] + if len(set(assigned)) != len(assigned) or set(assigned) != net_by_id.keys(): + raise ValueError("Process profiles must assign every net to exactly one group") + + results: dict[str, RoutingResult] = {} + reservations: list[Polygon] = [] + for net_ids, options in groups: + grouped = replace( + problem, + nets=tuple(net_by_id[net_id] for net_id in net_ids), + initial_paths={net_id: problem.initial_paths[net_id] for net_id in net_ids if net_id in problem.initial_paths}, + static_obstacles=problem.static_obstacles + tuple(reservations), + _reserved_obstacles=problem._reserved_obstacles + tuple(reservations), + ) + current = route(grouped, options=options).results_by_net + results.update(current) + reservations.extend(polygon for result in current.values() if result.is_valid for polygon in result.locked_geometry) + return {net_id: results[net_id] for net_id in net_by_id} diff --git a/inire/model.py b/inire/model.py index aac7b9b..be13302 100644 --- a/inire/model.py +++ b/inire/model.py @@ -72,11 +72,14 @@ class SBendOutline: radius: float width: float polygon: Polygon + length: float | None = None def __post_init__(self) -> None: seed = SBendSeed(self.offset, self.radius) if not isfinite(self.width) or self.width <= 0 or not bend_fits_width(seed.radius, self.width): raise ValueError("S-bend outline needs a finite positive width no greater than twice its radius") + if self.length is not None and (not isfinite(self.length) or self.length <= 0): + raise ValueError("S-bend outline length must be finite and positive") if not isinstance(self.polygon, Polygon) or self.polygon.is_empty or not self.polygon.is_valid: raise ValueError("S-bend outline must be a valid, nonempty Polygon") end = Port(sbend_grid_span(seed.offset, seed.radius), seed.offset, 0) @@ -103,10 +106,18 @@ class SearchOptions: bend_clip_margin: float | None = None visibility_guidance: VisibilityGuidance = "tangent_corner" sbend_outlines: tuple[SBendOutline, ...] = () + proximity_range: float = 10.0 + bend_physical_length: float | None = None def __post_init__(self) -> None: _require_budget("node_limit", self.node_limit) _require_nonnegative("greedy_h_weight", self.greedy_h_weight) + if not isfinite(self.proximity_range) or self.proximity_range <= 0: + raise ValueError("proximity_range must be finite and positive") + if self.bend_physical_length is not None: + _, physical = resolve_bend_geometry(self) + if physical == "arc" or not isfinite(self.bend_physical_length) or self.bend_physical_length <= 0: + raise ValueError("bend_physical_length needs custom physical geometry and a finite positive length") if self.visibility_guidance not in ("off", "exact_corner", "tangent_corner"): raise ValueError(f"Unknown visibility_guidance: {self.visibility_guidance!r}") for field_name in ("bend_radii", "sbend_radii"): @@ -154,12 +165,16 @@ class SearchOptions: def has_applicable_sbend_outline(self, widths: Iterable[float]) -> bool: return bool(self.sbend_outlines) and any(next(self.sbend_outlines_for_width(width), None) is not None for width in widths) - def sbend_outline(self, offset: float, radius: float, width: float) -> Polygon | None: - matches = [outline.polygon for outline in self.sbend_outlines_for_width(width) if (outline.offset, outline.radius) == (offset, radius)] + def sbend_template(self, offset: float, radius: float, width: float) -> SBendOutline | None: + matches = [outline for outline in self.sbend_outlines_for_width(width) if (outline.offset, outline.radius) == (offset, radius)] if len(matches) > 1: raise ValueError(f"Ambiguous S-bend outlines for offset {offset}, radius {radius}, width {width}") return matches[0] if matches else None + def sbend_outline(self, offset: float, radius: float, width: float) -> Polygon | None: + template = self.sbend_template(offset, radius, width) + return template.polygon if template is not None else None + def seed_geometry_error(self, seed: PathSeed) -> str | None: for segment in seed.segments: if isinstance(segment, Bend90Seed) and segment.radius not in self.bend_radii: diff --git a/inire/results.py b/inire/results.py index 31626dd..93b99fa 100644 --- a/inire/results.py +++ b/inire/results.py @@ -154,6 +154,8 @@ class RouteMetrics: warm_start_paths_used: int refine_path_calls: int timeout_events: int + frontier_trim_events: int + frontier_nodes_discarded: int iteration_reverify_calls: int iteration_reverified_nets: int iteration_conflicting_nets: int diff --git a/inire/router/_astar_admission.py b/inire/router/_astar_admission.py index 86619e6..eb3b867 100644 --- a/inire/router/_astar_admission.py +++ b/inire/router/_astar_admission.py @@ -37,7 +37,9 @@ def process_move( 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 - outline = context.options.search.sbend_outline(params[0], params[1], net_width) if move_class == "sbend" else None + search = context.options.search + template = search.sbend_template(params[0], params[1], net_width) if move_class == "sbend" and search.sbend_outlines else None + outline = template.polygon if template else None self_dilation = context.cost_evaluator.collision_engine.clearance / 2.0 abs_key = ( @@ -55,7 +57,6 @@ def process_move( res = context.move_cache_abs[abs_key] else: context.metrics.total_move_cache_abs_misses += 1 - context.check_cache_eviction() base_port = Port(0, 0, cp.r) rel_key = ( cp.r, @@ -83,12 +84,13 @@ def process_move( 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), ) except ValueError: return - context.move_cache_rel[rel_key] = res_rel + context.cache_move(rel_key, res_rel, relative=True) res = res_rel.translate(cp.x, cp.y) - context.move_cache_abs[abs_key] = res + context.cache_move(abs_key, res, relative=False) add_node( parent, @@ -155,13 +157,15 @@ def add_node( or ce.check_move_static(result, start_port=parent_p, end_port=end_p) ) if collision_found: - context.hard_collision_set.add(cache_key) + if cache_key in context.move_cache_abs: + context.hard_collision_set.add(cache_key) if frontier_trace is not None: frontier_trace.record("hard_collision", move_type, parent.port.as_tuple(), state, result.total_dilated_bounds) metrics.pruned_hard_collision += 1 metrics.total_pruned_hard_collision += 1 return - context.static_safe_cache.add(cache_key) + if cache_key in context.move_cache_abs: + context.static_safe_cache.add(cache_key) predecessor = parent.component_result self_clearance = context.cost_evaluator.collision_engine.self_clearance diff --git a/inire/router/_astar_types.py b/inire/router/_astar_types.py index bcacd82..303a8f0 100644 --- a/inire/router/_astar_types.py +++ b/inire/router/_astar_types.py @@ -1,5 +1,6 @@ from __future__ import annotations +from collections import OrderedDict from dataclasses import dataclass, field from operator import attrgetter from typing import TYPE_CHECKING, get_type_hints @@ -229,6 +230,8 @@ class AStarContext: "hard_collision_set", "static_safe_cache", "static_cache_version", + "_relative_coordinates", + "_absolute_coordinates", ) def __init__( @@ -237,7 +240,7 @@ class AStarContext: problem: RoutingProblem, options: RoutingOptions, metrics: AStarMetrics | None = None, - max_cache_size: int = 1000000, + max_cache_size: int = 8192, ) -> None: self.cost_evaluator = cost_evaluator self.metrics = metrics if metrics is not None else AStarMetrics() @@ -247,8 +250,10 @@ class AStarContext: self.options = options self.min_bend_radius = min(self.options.search.bend_radii, default=50.0) self.visibility_manager = VisibilityManager(self.cost_evaluator.collision_engine) - self.move_cache_rel: dict[tuple, ComponentResult] = {} - self.move_cache_abs: dict[tuple, ComponentResult] = {} + self.move_cache_rel: OrderedDict[tuple, ComponentResult] = OrderedDict() + self.move_cache_abs: OrderedDict[tuple, ComponentResult] = OrderedDict() + self._relative_coordinates = 0 + self._absolute_coordinates = 0 self.hard_collision_set: set[tuple] = set() self.static_safe_cache: set[tuple] = set() self.static_cache_version = self.cost_evaluator.collision_engine.get_static_version() @@ -264,16 +269,21 @@ class AStarContext: if self.static_cache_version != current_version: self.clear_static_caches() - def _evict_cache(self, cache: dict[tuple, ComponentResult]) -> None: - if len(cache) <= self.max_cache_size * 1.2: + def cache_move(self, key: tuple, result: ComponentResult, *, relative: bool) -> None: + cache = self.move_cache_rel if relative else self.move_cache_abs + total = self._relative_coordinates if relative else self._absolute_coordinates + coordinate_limit = 500_000 if relative else 1_000_000 + if result.coordinate_count > coordinate_limit or not self.max_cache_size: return - - num_to_evict = max(1, int(len(cache) * 0.25)) - for idx, key in enumerate(tuple(cache.keys())): - if idx >= num_to_evict: - break - del cache[key] - - def check_cache_eviction(self) -> None: - self._evict_cache(self.move_cache_rel) - self._evict_cache(self.move_cache_abs) + cache[key] = result + total += result.coordinate_count + while len(cache) > self.max_cache_size or total > coordinate_limit: + removed_key, removed = cache.popitem(last=False) + total -= removed.coordinate_count + if not relative: + self.hard_collision_set.discard(removed_key) + self.static_safe_cache.discard(removed_key) + if relative: + self._relative_coordinates = total + else: + self._absolute_coordinates = total diff --git a/inire/router/_automatic.py b/inire/router/_automatic.py index 6dcbdae..dea8e80 100644 --- a/inire/router/_automatic.py +++ b/inire/router/_automatic.py @@ -155,7 +155,9 @@ class _AutomaticRun: if self.length_weights is not None: return weighted_path_length(result.path, self.length_weights) if self.evaluator is None: - self.evaluator = build_native_cost_evaluator(self.problem, self.options.objective) + self.evaluator = build_native_cost_evaluator( + self.problem, self.options.objective, proximity_range=self.options.search.proximity_range, + ) return self.evaluator.path_cost(result.path[0].start_port, result.path) def _trial(self, run: RoutingRunResult, stage: RoutingStage) -> Trial: @@ -305,9 +307,7 @@ class _AutomaticRun: problem, options = self.problem, self.options if len(problem.nets) != 2: return - world = RoutingWorld(clearance=problem.clearance, safety_zone_radius=problem.safety_zone_radius, board=self.board) - for obstacle in problem.static_obstacles: - world.add_static_obstacle(obstacle) + world = RoutingWorld.from_problem(problem, board=self.board) def footprints(net: NetSpec, seeds: Iterable[PathSeed]) -> list[tuple[PathSeed, BaseGeometry]]: choices = [] @@ -637,7 +637,7 @@ class _AutomaticRun: return None if not refined.selectable: return best - evaluator = build_native_cost_evaluator(self.problem, objective) + evaluator = build_native_cost_evaluator(self.problem, objective, proximity_range=self.options.search.proximity_range) def cost(trial: Trial) -> float: paths = (trial.run.results_by_net[net_id].path for net_id in trial.valid_costs) diff --git a/inire/router/_compact.py b/inire/router/_compact.py index a36d09c..7848791 100644 --- a/inire/router/_compact.py +++ b/inire/router/_compact.py @@ -156,10 +156,8 @@ def compact_port_seed_set(problem: RoutingProblem, search: SearchOptions) -> dic return None if any(net.start.r != 0 or net.target.r != 0 or not 0 < net.target.x - net.start.x <= 4 * radii[-1] for net in problem.nets): return None - world = RoutingWorld(clearance=problem.clearance, safety_zone_radius=problem.safety_zone_radius) - for obstacle in problem.static_obstacles: - world.add_static_obstacle(obstacle) board = box(*problem.bounds) + world = RoutingWorld.from_problem(problem, board=board) candidates = {} for net in problem.nets: jogs = islice(_candidate_jogs(net, problem, search, radii), 512) @@ -209,10 +207,8 @@ def short_shift_seed_set(problem: RoutingProblem, search: SearchOptions, score: if not all(seeds_by_net): return None - world = RoutingWorld(clearance=problem.clearance, safety_zone_radius=problem.safety_zone_radius) - for obstacle in problem.static_obstacles: - world.add_static_obstacle(obstacle) board = box(*problem.bounds) + world = RoutingWorld.from_problem(problem, board=board) candidates = {} for net, seeds in zip(problem.nets, seeds_by_net, strict=True): ranked = [ diff --git a/inire/router/_pair_local.py b/inire/router/_pair_local.py index aced7ca..f102b33 100644 --- a/inire/router/_pair_local.py +++ b/inire/router/_pair_local.py @@ -10,8 +10,7 @@ from inire.results import RoutingResult from inire.router._astar_types import AStarContext, AStarMetrics, SearchRunConfig from inire.router._congestion_policy import can_reserve from inire.router._search import incumbent_guidance, route_astar -from inire.router.cost import CostEvaluator -from inire.router.danger_map import DangerMap +from inire.router.cost import CostEvaluator, proximity_map if TYPE_CHECKING: from collections.abc import Callable, Mapping, Set @@ -45,7 +44,7 @@ def _build_pair_local_context( for polygon in component.physical_geometry: world.add_static_obstacle(polygon, reserved=True) - danger_map = DangerMap(bounds=problem.bounds) + danger_map = proximity_map(problem, context.options.search.proximity_range) if context.options.objective.danger_weight: danger_map.precompute(list(static_obstacles)) evaluator = CostEvaluator.from_objective( diff --git a/inire/router/_routing_policy.py b/inire/router/_routing_policy.py index 0101031..5e268e5 100644 --- a/inire/router/_routing_policy.py +++ b/inire/router/_routing_policy.py @@ -82,9 +82,7 @@ def _direct_paths( *, priority: frozenset[str] = frozenset(), ) -> dict[str, RoutingResult]: - world = RoutingWorld(clearance=problem.clearance, safety_zone_radius=problem.safety_zone_radius, board=board) - for obstacle in problem.static_obstacles: - world.add_static_obstacle(obstacle) + world = RoutingWorld.from_problem(problem, board=board) ordered = ordered_nets(problem.nets, options.congestion.net_order) if priority: ordered.sort(key=lambda net: net.net_id not in priority) diff --git a/inire/router/_search.py b/inire/router/_search.py index d2327a4..90f0360 100644 --- a/inire/router/_search.py +++ b/inire/router/_search.py @@ -1,6 +1,7 @@ from __future__ import annotations import heapq +from math import inf from typing import TYPE_CHECKING from inire.constants import TOLERANCE_LINEAR @@ -93,6 +94,16 @@ def route_astar( deferred_turns.clear() if not open_set: break + if len(open_set) > 50_000: + retained = heapq.nsmallest( + 40_000, + (node for node in open_set if closed_set.get(node.port.as_tuple(), inf) > node.g_cost + TOLERANCE_LINEAR), + ) + metrics.total_frontier_trim_events += 1 + metrics.total_frontier_nodes_discarded += len(open_set) - len(retained) + open_set = retained + if not open_set: + continue current = heapq.heappop(open_set) if config.max_cost is not None and current.fh_cost[0] > config.max_cost: diff --git a/inire/router/_seed_materialization.py b/inire/router/_seed_materialization.py index 44c30ac..018b3d5 100644 --- a/inire/router/_seed_materialization.py +++ b/inire/router/_seed_materialization.py @@ -49,7 +49,7 @@ def materialize_path_seed( for segment in seed.segments: kind, parameters = seed_move(segment) - outline = search.sbend_outline(segment.offset, segment.radius, net_width) if isinstance(segment, SBendSeed) else None + template = search.sbend_template(segment.offset, segment.radius, net_width) if isinstance(segment, SBendSeed) else None component = build_component( current, net_width, @@ -59,7 +59,8 @@ def materialize_path_seed( physical_geometry_type=bend_physical_geometry, clip_margin=bend_clip_margin, dilation=dilation, - sbend_outline=outline, + sbend_outline=template.polygon if template is not None else None, + physical_length=search.bend_physical_length if kind == "bend90" else (template.length if template else None), ) path.append(component) current = component.end_port diff --git a/inire/router/_stack.py b/inire/router/_stack.py index 2f33167..48ea24e 100644 --- a/inire/router/_stack.py +++ b/inire/router/_stack.py @@ -3,14 +3,11 @@ from __future__ import annotations from dataclasses import dataclass, replace from typing import TYPE_CHECKING -from shapely.geometry import box - from inire.geometry.collision import RoutingWorld from inire.results import RoutingRunResult, _sum_route_metrics from inire.router._astar_types import AStarContext from inire.router._router import PathFinder -from inire.router.cost import CostEvaluator -from inire.router.danger_map import DangerMap +from inire.router.cost import CostEvaluator, proximity_map if TYPE_CHECKING: from collections.abc import Callable @@ -19,6 +16,7 @@ if TYPE_CHECKING: from inire.results import RoutingResult from inire.router._router import PhaseTimer from inire.router._topology import Corridor + from inire.router.danger_map import DangerMap @dataclass(frozen=True, slots=True) @@ -36,17 +34,9 @@ def build_routing_stack(problem: RoutingProblem, options: RoutingOptions) -> Rou problem = plan_ordered_bundle(problem, options.search, infer_terminal_headings=options.topology.infer_terminal_headings) - world = RoutingWorld( - clearance=problem.clearance, - safety_zone_radius=problem.safety_zone_radius, - board=box(*problem.bounds), - self_clearance=problem.self_clearance, - ) - reserved_ids = {id(polygon) for polygon in problem._reserved_obstacles} - for obstacle in problem.static_obstacles: - world.add_static_obstacle(obstacle, reserved=id(obstacle) in reserved_ids) + world = RoutingWorld.from_problem(problem) - danger_map = DangerMap(bounds=problem.bounds) + danger_map = proximity_map(problem, options.search.proximity_range) refinement = options.refinement if options.search.node_limit > 0 and options.congestion.max_iterations > 0 and ( options.objective.danger_weight or (refinement.enabled and refinement.objective is not None and refinement.objective.danger_weight) diff --git a/inire/router/cost.py b/inire/router/cost.py index 02bd882..909388f 100644 --- a/inire/router/cost.py +++ b/inire/router/cost.py @@ -176,7 +176,7 @@ class CostEvaluator: ) # Skip danger sampling entirely when there are no static obstacles in the KD-tree. - if danger_map is not None and active_weights.danger_weight and danger_map.tree is not None: + if danger_map is not None and active_weights.danger_weight and danger_map.has_data: cost_s = danger_map.get_cost(start_port.x, start_port.y) if start_port else 0.0 cost_e = danger_map.get_cost(end_port.x, end_port.y) if start_port: @@ -230,10 +230,17 @@ class CostEvaluator: return total -def build_native_cost_evaluator(problem: RoutingProblem, objective: ObjectiveWeights) -> CostEvaluator: +def proximity_map(problem: RoutingProblem, proximity_range: float) -> DangerMap: + return DangerMap( + bounds=problem.bounds, resolution=proximity_range / 2 or proximity_range, safety_threshold=proximity_range, + cost_distance_range=proximity_range, + ) + + +def build_native_cost_evaluator(problem: RoutingProblem, objective: ObjectiveWeights, *, proximity_range: float = 10.0) -> CostEvaluator: """Score candidate paths using the original layout's obstacles and objective.""" danger = None if objective.danger_weight and problem.static_obstacles: - danger = DangerMap(bounds=problem.bounds) - danger.precompute(list(problem.static_obstacles)) + danger = proximity_map(problem, proximity_range) + danger.precompute(problem.static_obstacles) return CostEvaluator.from_objective(RoutingWorld(clearance=problem.clearance), danger, objective) diff --git a/inire/router/danger_map.py b/inire/router/danger_map.py index 339ad15..f45bc6e 100644 --- a/inire/router/danger_map.py +++ b/inire/router/danger_map.py @@ -1,23 +1,27 @@ from __future__ import annotations from collections import OrderedDict -from itertools import chain, pairwise -from math import ceil, floor, hypot +from itertools import chain, islice, pairwise +from math import ceil, floor, hypot, isfinite from time import perf_counter_ns from typing import TYPE_CHECKING import numpy +import shapely from scipy.spatial import cKDTree -from shapely.geometry import box +from shapely.geometry import Point, box +from shapely.strtree import STRtree if TYPE_CHECKING: from collections.abc import Iterable, Iterator from shapely.geometry import LinearRing, Polygon + from numpy.typing import NDArray from inire.router._astar_types import AStarMetrics _COST_CACHE_SIZE = 100000 +_MAX_SAMPLES = 20000 def _clip_segment( @@ -68,7 +72,10 @@ class DangerMap: A proximity cost evaluator using a KD-Tree of obstacle boundary points. Samples the part of the obstacle perimeter within range of the design. """ - __slots__ = ('minx', 'miny', 'maxx', 'maxy', 'resolution', 'safety_threshold', 'k', 'tree', '_cost_cache', 'metrics') + __slots__ = ( + "minx", "miny", "maxx", "maxy", "resolution", "safety_threshold", "k", "tree", + "_boundary_tree", "_cost_distance_range", "_cost_cache", "metrics", + ) def __init__( self, @@ -76,6 +83,8 @@ class DangerMap: resolution: float = 5.0, safety_threshold: float = 10.0, k: float = 1.0, + *, + cost_distance_range: float = 10.0, ) -> None: """ Initialize the Danger Map. @@ -91,6 +100,8 @@ class DangerMap: self.safety_threshold = safety_threshold self.k = k self.tree: cKDTree | None = None + self._boundary_tree: STRtree | None = None + self._cost_distance_range = cost_distance_range self._cost_cache: OrderedDict[tuple[int, int], float] = OrderedDict() self.metrics: AStarMetrics | None = None @@ -101,19 +112,37 @@ class DangerMap: reach = self.safety_threshold bounds = (self.minx - reach, self.miny - reach, self.maxx + reach, self.maxy + reach) window = box(*bounds) - all_points = [] - for poly in obstacles: - for ring in chain((poly.exterior,), poly.interiors): - if window.intersects(ring): - all_points.extend(_sample_ring(ring, bounds, self.resolution)) - - if all_points: - self.tree = cKDTree(numpy.array(all_points)) - else: + rings = [ + ring for poly in obstacles for ring in chain((poly.exterior,), poly.interiors) + if window.intersects(ring) + ] + if any(not isfinite(ring.length / self.resolution) for ring in rings): self.tree = None + self._boundary_tree = STRtree(rings) + self._cost_cache.clear() + return + points = list(islice(chain.from_iterable(_sample_ring(ring, bounds, self.resolution) for ring in rings), _MAX_SAMPLES + 1)) + self.tree = cKDTree(numpy.array(points)) if 0 < len(points) <= _MAX_SAMPLES else None + self._boundary_tree = STRtree(rings) if len(points) > _MAX_SAMPLES else None self._cost_cache.clear() + @property + def has_data(self) -> bool: + return self.tree is not None or self._boundary_tree is not None + + def costs_at_points(self, coordinates: NDArray[numpy.float64]) -> NDArray[numpy.float64]: + distances = numpy.full(len(coordinates), numpy.inf) + if self.tree is not None: + distances, _ = self.tree.query(coordinates, distance_upper_bound=self.safety_threshold) + elif self._boundary_tree is not None: + indices, measured = self._boundary_tree.query_nearest( + shapely.points(coordinates), max_distance=self.safety_threshold, return_distance=True, all_matches=False, + ) + distances[indices[0]] = measured + safe = numpy.maximum(0.1, 10 * (distances / self._cost_distance_range)) + return numpy.where(distances < self.safety_threshold, self.k / safe ** 2, 0.0) + def is_within_bounds(self, x: float, y: float) -> bool: """ Check if a coordinate is within the design bounds. @@ -154,12 +183,19 @@ class DangerMap: qy = qy_milli / 1000.0 if not self.is_within_bounds(qx, qy): return 1e15 - if self.tree is None: + if not self.has_data: return 0.0 if self.metrics is not None: self.metrics.total_danger_map_query_calls += 1 - dist, _ = self.tree.query([qx, qy], distance_upper_bound=self.safety_threshold) + if self.tree is not None: + dist, _ = self.tree.query([qx, qy], distance_upper_bound=self.safety_threshold) + else: + assert self._boundary_tree is not None + _, distances = self._boundary_tree.query_nearest( + Point(qx, qy), max_distance=self.safety_threshold, return_distance=True, all_matches=False, + ) + dist = distances[0] if len(distances) else numpy.inf if dist >= self.safety_threshold: return 0.0 - safe_dist = max(dist, 0.1) + safe_dist = max(10 * (dist / self._cost_distance_range), 0.1) return float(self.k / (safe_dist ** 2)) diff --git a/inire/router/refiner.py b/inire/router/refiner.py index 8b91633..66ab7b3 100644 --- a/inire/router/refiner.py +++ b/inire/router/refiner.py @@ -239,7 +239,7 @@ class PathRefiner: if 0.01 < forward_length < min_straight - 0.01: return None - bend_length = _bend90_length(radius) + bend_length = self.context.options.search.bend_physical_length or _bend90_length(radius) moves: list[_DoglegMove] = [] curr = start for sign, straight_len in ( @@ -267,6 +267,7 @@ class PathRefiner: 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, ) path.append(component) port = component.end_port diff --git a/inire/tests/test_astar.py b/inire/tests/test_astar.py index a9b3c0e..6b9eaa3 100644 --- a/inire/tests/test_astar.py +++ b/inire/tests/test_astar.py @@ -424,6 +424,9 @@ def test_route_astar_repeated_searches_succeed_with_small_cache_limit(basic_eval path = _route(context, start, target) assert path is not None assert path[-1].end_port == target + assert len(context.move_cache_abs) <= 2 + assert len(context.move_cache_rel) <= 2 + assert context.hard_collision_set | context.static_safe_cache <= context.move_cache_abs.keys() def test_self_collision_prunes_before_congestion_check(basic_evaluator: CostEvaluator) -> None: diff --git a/inire/tests/test_cost.py b/inire/tests/test_cost.py index 68f85c7..1623a9c 100644 --- a/inire/tests/test_cost.py +++ b/inire/tests/test_cost.py @@ -1,10 +1,12 @@ from math import ceil +from numpy import array from numpy.testing import assert_allclose from shapely.geometry import Polygon, box from inire.geometry.collision import RoutingWorld from inire.geometry.primitives import Port -from inire.router.cost import CostEvaluator +from inire import RoutingProblem +from inire.router.cost import CostEvaluator, proximity_map from inire.router.danger_map import DangerMap @@ -136,3 +138,26 @@ def test_danger_map_samples_only_the_nearby_edge_of_a_large_keepout() -> None: assert danger.tree is not None assert danger.tree.n < 30 assert danger.get_cost(85, 40) == 0.04 + + +def test_large_perimeter_uses_bounded_exact_index_with_interior_opening() -> None: + problem = RoutingProblem((0, 0, 1_100_000, 1_100_000)) + hole = box(100, 100, 900, 900) + obstacle = Polygon(box(50, 50, 1_000_050, 1_000_050).exterior, [hole.exterior]) + danger = proximity_map(problem, 10) + danger.precompute((obstacle,)) + + assert danger.tree is None + assert danger.has_data + assert_allclose(danger.costs_at_points(array([[45, 500], [105, 500], [500, 500]])), [0.04, 0.04, 0.0]) + assert danger.get_cost(105, 500) == 0.04 + + +def test_proximity_cost_is_stable_when_layout_units_change() -> None: + for scale in (1, 10, 1000): + problem = RoutingProblem((0, 0, 1500 * scale, 1600 * scale)) + danger = proximity_map(problem, 10 * scale) + danger.precompute((box(200 * scale, 200 * scale, 1200 * scale, 1200 * scale),)) + + assert danger.tree.n == 800 + assert danger.get_cost(500 * scale, 195 * scale) == 0.04 diff --git a/inire/tests/test_layout.py b/inire/tests/test_layout.py new file mode 100644 index 0000000..905fb74 --- /dev/null +++ b/inire/tests/test_layout.py @@ -0,0 +1,154 @@ +from dataclasses import replace + +import pytest +from shapely import union_all +from shapely.geometry import box + +from inire import ( + Bend90Seed, CongestionOptions, NetSpec, PathSeed, Port, RefinementOptions, + RoutingOptions, RoutingProblem, SBendOutline, SearchOptions, StraightSeed, TopologyOptions, route, +) +from inire.layout import PlacedPort, coplanar_geometry, partition_layers, preserves_length, route_profiles, verify_export_grid + + +_REPLAY = RoutingOptions(search=SearchOptions(node_limit=0), refinement=RefinementOptions(enabled=False)) + + +def test_declared_port_width_check_requires_transition_for_wider_device() -> None: + source = PlacedPort(Port(10000, 10000, 0), 500) + target = PlacedPort(Port(110000, 10000, 0), 3000) + with pytest.raises(ValueError, match="joins widths 500 and 3000"): + source.connect("wide", target) + + inlet = PlacedPort(Port(70000, 10000, 0), 500) + net = source.connect("before_taper", inlet) + assert net.width == 500 + assert net.target == inlet.port + rotated = replace(source, port=source.port.rotated(90)).connect("rotated", replace(inlet, port=inlet.port.rotated(90))) + assert rotated.start.r == rotated.target.r == 90 + + +@pytest.mark.parametrize(("outer_radius", "grid", "valid"), [(3070, 1, False), (3070, 0.01, True), (3072, 1, True)]) +def test_export_verifies_actual_rounded_bend_clearance(outer_radius, grid, valid) -> None: + center_x, center_y = 3000, 6070 + inner = NetSpec("inside", Port(center_x, center_y - 2500, 0), Port(center_x + 2500, center_y, 90), 490) + outer = NetSpec("outside", Port(center_x, center_y - outer_radius, 0), Port(center_x + outer_radius, center_y, 90), 509.94) + seeds = {"inside": PathSeed((Bend90Seed(2500, "CCW"),)), "outside": PathSeed((Bend90Seed(outer_radius, "CCW"),))} + problem = RoutingProblem((0, 0, 7000, 7000), (inner, outer), initial_paths=seeds, clearance=70) + options = replace(_REPLAY, search=replace(_REPLAY.search, bend_radii=(2500, outer_radius))) + results = route(problem, options=options).results_by_net + assert all(result.is_valid for result in results.values()) + + exported = verify_export_grid(problem, results, grid=grid) + + assert exported.is_valid is valid + assert all(not report.discontinuous for report in exported.reports_by_net.values()) + assert all(report.dynamic_collision_count == int(not valid) for report in exported.reports_by_net.values()) + + +@pytest.mark.parametrize(("pitch", "valid"), [(28000, False), (32000, False), (36000, True)]) +def test_cpw_ground_strip_is_verified_using_gap_envelope(pitch, valid) -> None: + width = 15500 + nets = tuple(NetSpec(f"cpw{i}", Port(10000, 30000 + i * pitch, 0), Port(210000, 30000 + i * pitch, 0), width) + for i in range(2)) + seeds = {net.net_id: PathSeed((StraightSeed(200000),)) for net in nets} + problem = RoutingProblem((0, 0, 220000, 100000), nets, initial_paths=seeds, clearance=3000) + signals = route(problem, options=_REPLAY).results_by_net + envelopes = route(replace(problem, nets=tuple(replace(net, width=29500) for net in nets)), options=_REPLAY).results_by_net + assert all(signal.is_valid for signal in signals.values()) + assert all(envelope.is_valid for envelope in envelopes.values()) == valid + if valid: + shapes = [coplanar_geometry(signals[net.net_id], envelopes[net.net_id]) for net in nets] + assert shapes[0].ground_exclusion.distance(shapes[1].ground_exclusion) == 6500 + assert all(shape.gaps.area == 14000 * 200000 for shape in shapes) + + +def test_cpw_turn_builds_wider_exclusion_from_the_verified_envelope() -> None: + radius = 15000 + net = NetSpec("flux", Port(35000, 20000, 0), Port(50000, 35000, 90), 15500) + problem = RoutingProblem((0, 0, 100000, 80000), (net,), initial_paths={"flux": PathSeed((Bend90Seed(radius, "CCW"),))}) + options = replace(_REPLAY, search=SearchOptions(node_limit=0, bend_radii=(radius,), sbend_radii=())) + signal = route(problem, options=options).results_by_net["flux"] + envelope = route(replace(problem, nets=(replace(net, width=29500),)), options=options).results_by_net["flux"] + + cpw = coplanar_geometry(signal, envelope, ground_margin=10000) + + assert cpw.ground_exclusion.covers(union_all(envelope.locked_geometry)) + assert cpw.gaps.area > 0 + + +def test_profile_options_apply_to_active_search_and_seed_replay() -> None: + flux = NetSpec("flux", Port(35000, 20000, 0), Port(50000, 35000, 90), 29500) + feed = NetSpec("feed", Port(100000, 20000, 0), Port(115000, 35000, 90), 29500) + problem = RoutingProblem((0, 0, 220000, 95000), (flux, feed), clearance=3000) + options = RoutingOptions( + search=SearchOptions(node_limit=80, bend_radii=(15000,), sbend_radii=()), + refinement=RefinementOptions(enabled=False), + congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False), + topology=TopologyOptions(mode="off"), + ) + feed_profile = replace(options, search=replace(options.search, bend_radii=(50000,))) + profiles = ((("flux",), options), (("feed",), feed_profile)) + + restricted = route_profiles(problem, profiles) + + assert restricted["flux"].is_valid + assert not restricted["feed"].is_valid + feed = replace(feed, target=Port(150000, 70000, 90)) + open_board = replace(problem, nets=(flux, feed)) + both = route_profiles(open_board, profiles) + assert both["feed"].as_seed() == PathSeed((Bend90Seed(50000, "CCW"),)) + assert all(result.is_valid for result in both.values()) + invalid = replace(open_board, initial_paths={"feed": PathSeed((Bend90Seed(15000, "CCW"),))}) + with pytest.raises(ValueError, match="'feed'.*outside bend_radii"): + route_profiles(invalid, profiles) + + +def test_independent_layer_outputs_retain_assignment_and_connectivity() -> None: + silicon = NetSpec("si", Port(1000, 10000, 0), Port(19000, 10000, 0), 500) + nitride = NetSpec("sin", Port(10000, 1000, 90), Port(10000, 19000, 90), 750) + geometry = {} + for layer, nets in partition_layers((((1, 0), silicon), ((4, 0), nitride))).items(): + problem = RoutingProblem( + (0, 0, 20000, 20000), nets, + initial_paths={net.net_id: PathSeed((StraightSeed(18000),)) for net in nets}, + ) + results = route(problem, options=_REPLAY).results_by_net + export = verify_export_grid(problem, results, grid=1) + assert export.is_valid + geometry[layer] = union_all(tuple(polygon for shapes in export.geometry_by_net.values() for polygon in shapes)) + assert set(geometry) == {(1, 0), (4, 0)} + assert all(shape.geom_type == "Polygon" for shape in geometry.values()) + assert geometry[1, 0].intersection(geometry[4, 0]).area > 0 + + +def test_authored_template_lengths_are_used_for_candidate_acceptance() -> None: + net = NetSpec("arm", Port(20, 20, 0), Port(30, 30, 90)) + problem = RoutingProblem((0, 0, 100, 100), (net,)) + outline = box(0, -11, 11, -9).union(box(9, -11, 11, 0)) + options = RoutingOptions(search=SearchOptions( + node_limit=100, bend_radii=(10,), bend_physical_geometry=outline, bend_physical_length=18.7, + )) + result = route(problem, options=options).results_by_net["arm"] + assert preserves_length(result, 18.7, tolerance=1e-6) + assert not preserves_length(result, 37.4, tolerance=1e-6) + assert result.report.total_length == 18.7 + + +def test_authored_sbend_length_survives_seed_replay() -> None: + polygon = box(0, -1, 80, 41).intersection( + box(0, -1, 80, 1).union(box(1, 0, 79, 41)).union(box(79, 39, 80, 41)), + ) + outline = SBendOutline(40, 50, 2, polygon, length=95) + net = NetSpec("shift", Port(10, 10, 0), Port(90, 50, 0)) + seed = PathSeed(()) + search = SearchOptions(node_limit=80, bend_radii=(), sbend_radii=(50,), sbend_outlines=(outline,)) + problem = RoutingProblem((0, 0, 110, 110), (net,)) + options = RoutingOptions(search=search) + result = route(problem, options=options).results_by_net["shift"] + assert result.as_seed() != seed + replay = route( + replace(problem, initial_paths={"shift": result.as_seed()}), + options=replace(options, search=replace(search, node_limit=0)), + ).results_by_net["shift"] + assert preserves_length(replay, 95, tolerance=0) diff --git a/inire/utils/visualization.py b/inire/utils/visualization.py index 65f4174..f7fd1d8 100644 --- a/inire/utils/visualization.py +++ b/inire/utils/visualization.py @@ -154,20 +154,8 @@ def plot_danger_map( y_coords = numpy.arange(danger_map.miny + res/2, danger_map.maxy, res) xv, yv = numpy.meshgrid(x_coords, y_coords, indexing='ij') - if danger_map.tree is not None: - points = numpy.stack([xv.ravel(), yv.ravel()], axis=1) - dists, _ = danger_map.tree.query(points, distance_upper_bound=danger_map.safety_threshold) - - # Apply cost function - safe_dists = numpy.maximum(dists, 0.1) - grid_flat = numpy.where( - dists < danger_map.safety_threshold, - danger_map.k / (safe_dists**2), - 0.0 - ) - grid = grid_flat.reshape(xv.shape) - else: - grid = numpy.zeros(xv.shape) + points = numpy.column_stack((xv.ravel(), yv.ravel())) + grid = danger_map.costs_at_points(points).reshape(xv.shape) # Need to transpose because grid is [x, y] and imshow expects [row, col] (y, x) im = ax.imshow( diff --git a/plans/full-project-review.md b/plans/full-project-review.md index 2e4845e..49a8ad4 100644 --- a/plans/full-project-review.md +++ b/plans/full-project-review.md @@ -34,6 +34,12 @@ Implemented items 23 and 38 expose optional same-net spacing and reject edge and Implemented items 4, 5, 12, 15, 16, 18, 20, 24, 26, 27, 28, 32, 37, and 41 cover straight and turn recovery, width-specific corridors, search deadlines, partial hints, inferred headings, terminal diagnostics, and bounded guidance retries. The saved CROW fixtures reproduce all nine physical inputs on their authored grid. Each routes in its authored direction at the 225-node limit. The legacy canary and per-board parity checks remain open. +Implemented items 14 and 22 exclude repository tests from the wheel and declare compatible NumPy and Shapely floors. The source archive rebuilt a wheel and verified 9/9 nets on complex-routing example 1. The extracted wheel passed with warnings treated as errors on Python 3.11 with Shapely 2.0.7 and NumPy 1.26.4 and 2.2.6. The current Python 3.13 environment also passed. + +Implemented items 19 and 29 bound proximity sampling and move-cache memory. The 8,000-expansion blocked-board probe retained 8,192 absolute move entries and used about 418 MiB peak RSS. The review baseline retained 111,086 entries and used about 648 MiB. + +Implemented items 31, 33, 34, 35, 39, and 40 add authored bend lengths, physical CPW envelopes, process-profile routing, placed-port width checks, rounded export verification, and layer grouping. The local tests use the reviewed widths, radii, pitches, and export grid controls. + | Batch | Work | Acceptance gate | | --- | --- | --- | | Physical verification | 1, 2, 17, 23, and 38 | Reject the faulty geometry and keep legal joins valid in search and seed replay. Check circular bend accuracy, folded-route spacing, and isolation between different nets. |