Bound search memory and verify process geometry before layout export

This commit is contained in:
Jan Petykiewicz 2026-11-28 20:42:25 -08:00
commit e6ae242cb2
27 changed files with 645 additions and 102 deletions

View file

@ -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. - [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. - [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. - [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. - [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. - [Adjust a setting](docs/user/tune-and-troubleshoot.md#choose-the-next-setting) if routes collide, take too long, or use too many bends.

View file

@ -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). `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 ## Traces
Enable the `DiagnosticsOptions` flag for the question you want to answer. Enable the `DiagnosticsOptions` flag for the question you want to answer.

View file

@ -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. | | `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"`. | | `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. | | `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. 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.

89
docs/user/fabrication.md Normal file
View file

@ -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)

View file

@ -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. 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 ## 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. 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 ```python
from pathlib import Path from pathlib import Path

View file

@ -24,6 +24,7 @@ if TYPE_CHECKING:
from inire.geometry.components import ComponentResult from inire.geometry.components import ComponentResult
from inire.geometry.primitives import Port from inire.geometry.primitives import Port
from inire.model import RoutingProblem
_RAY_CAST_CACHE_LIMIT = 8192 _RAY_CAST_CACHE_LIMIT = 8192
@ -128,6 +129,19 @@ class RoutingWorld:
self._static_obstacles = StaticObstacleIndex(self) self._static_obstacles = StaticObstacleIndex(self)
self._dynamic_paths = DynamicPathIndex(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: def get_static_version(self) -> int:
return self._static_obstacles.version return self._static_obstacles.version

View file

@ -1,12 +1,12 @@
from __future__ import annotations from __future__ import annotations
from dataclasses import dataclass, field from dataclasses import dataclass, field, replace
from itertools import pairwise from itertools import pairwise
from math import asin, ceil, pi, radians, sqrt from math import asin, ceil, pi, radians, sqrt
from typing import TYPE_CHECKING, Literal from typing import TYPE_CHECKING, Literal
import numpy 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 rotate as shapely_rotate
from shapely.affinity import scale as shapely_scale from shapely.affinity import scale as shapely_scale
from shapely.affinity import translate as shapely_translate from shapely.affinity import translate as shapely_translate
@ -151,6 +151,7 @@ class ComponentResult:
_total_physical_bounds: tuple[float, float, float, float] | None = field(init=False, repr=False, compare=False, default=None) _total_physical_bounds: tuple[float, float, float, float] | None = field(init=False, repr=False, compare=False, default=None)
_physical_checks: tuple[bool, bool] | None = field(init=False, repr=False, compare=False, default=None) _physical_checks: tuple[bool, bool] | None = field(init=False, repr=False, compare=False, default=None)
_port_faces: tuple[PortFace | None, PortFace | None] | None = field(init=False, repr=False, compare=False, default=None) _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: def __post_init__(self) -> None:
collision_geometry = tuple(self.collision_geometry) collision_geometry = tuple(self.collision_geometry)
@ -201,6 +202,19 @@ class ComponentResult:
def bend_radius(self) -> float | None: def bend_radius(self) -> float | None:
return self.move_spec.radius if isinstance(self.move_spec, Bend90Seed) else None return self.move_spec.radius if isinstance(self.move_spec, Bend90Seed) else None
@property
def 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 @property
def port_faces(self) -> tuple[PortFace | None, PortFace | None]: def port_faces(self) -> tuple[PortFace | None, PortFace | None]:
if self._port_faces is None: if self._port_faces is None:
@ -242,7 +256,7 @@ class ComponentResult:
geometry.append(shifted) geometry.append(shifted)
return tuple(geometry) return tuple(geometry)
return ComponentResult( result = ComponentResult(
start_port=self.start_port.translate(dx, dy), start_port=self.start_port.translate(dx, dy),
collision_geometry=translate_geometry(self.collision_geometry), collision_geometry=translate_geometry(self.collision_geometry),
end_port=self.end_port.translate(dx, dy), end_port=self.end_port.translate(dx, dy),
@ -255,6 +269,8 @@ class ComponentResult:
width=self.width, width=self.width,
standard_faces=self.standard_faces, 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]: 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, clip_margin: float | None,
dilation: float, dilation: float,
sbend_outline: Polygon | None = None, sbend_outline: Polygon | None = None,
physical_length: float | None = None,
) -> ComponentResult: ) -> ComponentResult:
if kind == "straight": if kind == "straight":
return Straight.generate(start, parameters[0], width, dilation=dilation) return Straight.generate(start, parameters[0], width, dilation=dilation)
if kind == "bend90": if kind == "bend90":
return Bend90.generate( component = Bend90.generate(
start, parameters[0], width, parameters[1], start, parameters[0], width, parameters[1],
collision_type=collision_type, physical_geometry_type=physical_geometry_type, clip_margin=clip_margin, dilation=dilation, collision_type=collision_type, physical_geometry_type=physical_geometry_type, clip_margin=clip_margin, dilation=dilation,
) )
return SBend.generate( else:
start, parameters[0], parameters[1], width, component = SBend.generate(
collision_type="arc" if isinstance(collision_type, Polygon) else collision_type, start, parameters[0], parameters[1], width,
outline=sbend_outline, clip_margin=clip_margin, dilation=dilation, 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

166
inire/layout.py Normal file
View file

@ -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}

View file

@ -72,11 +72,14 @@ class SBendOutline:
radius: float radius: float
width: float width: float
polygon: Polygon polygon: Polygon
length: float | None = None
def __post_init__(self) -> None: def __post_init__(self) -> None:
seed = SBendSeed(self.offset, self.radius) seed = SBendSeed(self.offset, self.radius)
if not isfinite(self.width) or self.width <= 0 or not bend_fits_width(seed.radius, self.width): 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") 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: if not isinstance(self.polygon, Polygon) or self.polygon.is_empty or not self.polygon.is_valid:
raise ValueError("S-bend outline must be a valid, nonempty Polygon") raise ValueError("S-bend outline must be a valid, nonempty Polygon")
end = Port(sbend_grid_span(seed.offset, seed.radius), seed.offset, 0) end = Port(sbend_grid_span(seed.offset, seed.radius), seed.offset, 0)
@ -103,10 +106,18 @@ class SearchOptions:
bend_clip_margin: float | None = None bend_clip_margin: float | None = None
visibility_guidance: VisibilityGuidance = "tangent_corner" visibility_guidance: VisibilityGuidance = "tangent_corner"
sbend_outlines: tuple[SBendOutline, ...] = () sbend_outlines: tuple[SBendOutline, ...] = ()
proximity_range: float = 10.0
bend_physical_length: float | None = None
def __post_init__(self) -> None: def __post_init__(self) -> None:
_require_budget("node_limit", self.node_limit) _require_budget("node_limit", self.node_limit)
_require_nonnegative("greedy_h_weight", self.greedy_h_weight) _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"): if self.visibility_guidance not in ("off", "exact_corner", "tangent_corner"):
raise ValueError(f"Unknown visibility_guidance: {self.visibility_guidance!r}") raise ValueError(f"Unknown visibility_guidance: {self.visibility_guidance!r}")
for field_name in ("bend_radii", "sbend_radii"): for field_name in ("bend_radii", "sbend_radii"):
@ -154,12 +165,16 @@ class SearchOptions:
def has_applicable_sbend_outline(self, widths: Iterable[float]) -> bool: 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) 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: def sbend_template(self, offset: float, radius: float, width: float) -> SBendOutline | None:
matches = [outline.polygon for outline in self.sbend_outlines_for_width(width) if (outline.offset, outline.radius) == (offset, radius)] matches = [outline for outline in self.sbend_outlines_for_width(width) if (outline.offset, outline.radius) == (offset, radius)]
if len(matches) > 1: if len(matches) > 1:
raise ValueError(f"Ambiguous S-bend outlines for offset {offset}, radius {radius}, width {width}") raise ValueError(f"Ambiguous S-bend outlines for offset {offset}, radius {radius}, width {width}")
return matches[0] if matches else None 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: def seed_geometry_error(self, seed: PathSeed) -> str | None:
for segment in seed.segments: for segment in seed.segments:
if isinstance(segment, Bend90Seed) and segment.radius not in self.bend_radii: if isinstance(segment, Bend90Seed) and segment.radius not in self.bend_radii:

View file

@ -154,6 +154,8 @@ class RouteMetrics:
warm_start_paths_used: int warm_start_paths_used: int
refine_path_calls: int refine_path_calls: int
timeout_events: int timeout_events: int
frontier_trim_events: int
frontier_nodes_discarded: int
iteration_reverify_calls: int iteration_reverify_calls: int
iteration_reverified_nets: int iteration_reverified_nets: int
iteration_conflicting_nets: int iteration_conflicting_nets: int

View file

@ -37,7 +37,9 @@ def process_move(
coll_key = id(coll_type) if isinstance(coll_type, Polygon) else coll_type coll_key = id(coll_type) if isinstance(coll_type, Polygon) else coll_type
physical_type = config.bend_physical_geometry physical_type = config.bend_physical_geometry
physical_key = id(physical_type) if isinstance(physical_type, Polygon) else physical_type 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 self_dilation = context.cost_evaluator.collision_engine.clearance / 2.0
abs_key = ( abs_key = (
@ -55,7 +57,6 @@ def process_move(
res = context.move_cache_abs[abs_key] res = context.move_cache_abs[abs_key]
else: else:
context.metrics.total_move_cache_abs_misses += 1 context.metrics.total_move_cache_abs_misses += 1
context.check_cache_eviction()
base_port = Port(0, 0, cp.r) base_port = Port(0, 0, cp.r)
rel_key = ( rel_key = (
cp.r, cp.r,
@ -83,12 +84,13 @@ def process_move(
clip_margin=config.bend_clip_margin, clip_margin=config.bend_clip_margin,
dilation=self_dilation, dilation=self_dilation,
sbend_outline=outline, sbend_outline=outline,
physical_length=search.bend_physical_length if move_class == "bend90" else (template.length if template else None),
) )
except ValueError: except ValueError:
return 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) 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( add_node(
parent, parent,
@ -155,13 +157,15 @@ def add_node(
or ce.check_move_static(result, start_port=parent_p, end_port=end_p) or ce.check_move_static(result, start_port=parent_p, end_port=end_p)
) )
if collision_found: 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: if frontier_trace is not None:
frontier_trace.record("hard_collision", move_type, parent.port.as_tuple(), state, result.total_dilated_bounds) frontier_trace.record("hard_collision", move_type, parent.port.as_tuple(), state, result.total_dilated_bounds)
metrics.pruned_hard_collision += 1 metrics.pruned_hard_collision += 1
metrics.total_pruned_hard_collision += 1 metrics.total_pruned_hard_collision += 1
return 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 predecessor = parent.component_result
self_clearance = context.cost_evaluator.collision_engine.self_clearance self_clearance = context.cost_evaluator.collision_engine.self_clearance

View file

@ -1,5 +1,6 @@
from __future__ import annotations from __future__ import annotations
from collections import OrderedDict
from dataclasses import dataclass, field from dataclasses import dataclass, field
from operator import attrgetter from operator import attrgetter
from typing import TYPE_CHECKING, get_type_hints from typing import TYPE_CHECKING, get_type_hints
@ -229,6 +230,8 @@ class AStarContext:
"hard_collision_set", "hard_collision_set",
"static_safe_cache", "static_safe_cache",
"static_cache_version", "static_cache_version",
"_relative_coordinates",
"_absolute_coordinates",
) )
def __init__( def __init__(
@ -237,7 +240,7 @@ class AStarContext:
problem: RoutingProblem, problem: RoutingProblem,
options: RoutingOptions, options: RoutingOptions,
metrics: AStarMetrics | None = None, metrics: AStarMetrics | None = None,
max_cache_size: int = 1000000, max_cache_size: int = 8192,
) -> None: ) -> None:
self.cost_evaluator = cost_evaluator self.cost_evaluator = cost_evaluator
self.metrics = metrics if metrics is not None else AStarMetrics() self.metrics = metrics if metrics is not None else AStarMetrics()
@ -247,8 +250,10 @@ class AStarContext:
self.options = options self.options = options
self.min_bend_radius = min(self.options.search.bend_radii, default=50.0) self.min_bend_radius = min(self.options.search.bend_radii, default=50.0)
self.visibility_manager = VisibilityManager(self.cost_evaluator.collision_engine) self.visibility_manager = VisibilityManager(self.cost_evaluator.collision_engine)
self.move_cache_rel: dict[tuple, ComponentResult] = {} self.move_cache_rel: OrderedDict[tuple, ComponentResult] = OrderedDict()
self.move_cache_abs: dict[tuple, ComponentResult] = {} self.move_cache_abs: OrderedDict[tuple, ComponentResult] = OrderedDict()
self._relative_coordinates = 0
self._absolute_coordinates = 0
self.hard_collision_set: set[tuple] = set() self.hard_collision_set: set[tuple] = set()
self.static_safe_cache: set[tuple] = set() self.static_safe_cache: set[tuple] = set()
self.static_cache_version = self.cost_evaluator.collision_engine.get_static_version() 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: if self.static_cache_version != current_version:
self.clear_static_caches() self.clear_static_caches()
def _evict_cache(self, cache: dict[tuple, ComponentResult]) -> None: def cache_move(self, key: tuple, result: ComponentResult, *, relative: bool) -> None:
if len(cache) <= self.max_cache_size * 1.2: 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 return
cache[key] = result
num_to_evict = max(1, int(len(cache) * 0.25)) total += result.coordinate_count
for idx, key in enumerate(tuple(cache.keys())): while len(cache) > self.max_cache_size or total > coordinate_limit:
if idx >= num_to_evict: removed_key, removed = cache.popitem(last=False)
break total -= removed.coordinate_count
del cache[key] if not relative:
self.hard_collision_set.discard(removed_key)
def check_cache_eviction(self) -> None: self.static_safe_cache.discard(removed_key)
self._evict_cache(self.move_cache_rel) if relative:
self._evict_cache(self.move_cache_abs) self._relative_coordinates = total
else:
self._absolute_coordinates = total

View file

@ -155,7 +155,9 @@ class _AutomaticRun:
if self.length_weights is not None: if self.length_weights is not None:
return weighted_path_length(result.path, self.length_weights) return weighted_path_length(result.path, self.length_weights)
if self.evaluator is None: 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) return self.evaluator.path_cost(result.path[0].start_port, result.path)
def _trial(self, run: RoutingRunResult, stage: RoutingStage) -> Trial: def _trial(self, run: RoutingRunResult, stage: RoutingStage) -> Trial:
@ -305,9 +307,7 @@ class _AutomaticRun:
problem, options = self.problem, self.options problem, options = self.problem, self.options
if len(problem.nets) != 2: if len(problem.nets) != 2:
return return
world = RoutingWorld(clearance=problem.clearance, safety_zone_radius=problem.safety_zone_radius, board=self.board) world = RoutingWorld.from_problem(problem, board=self.board)
for obstacle in problem.static_obstacles:
world.add_static_obstacle(obstacle)
def footprints(net: NetSpec, seeds: Iterable[PathSeed]) -> list[tuple[PathSeed, BaseGeometry]]: def footprints(net: NetSpec, seeds: Iterable[PathSeed]) -> list[tuple[PathSeed, BaseGeometry]]:
choices = [] choices = []
@ -637,7 +637,7 @@ class _AutomaticRun:
return None return None
if not refined.selectable: if not refined.selectable:
return best 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: def cost(trial: Trial) -> float:
paths = (trial.run.results_by_net[net_id].path for net_id in trial.valid_costs) paths = (trial.run.results_by_net[net_id].path for net_id in trial.valid_costs)

View file

@ -156,10 +156,8 @@ def compact_port_seed_set(problem: RoutingProblem, search: SearchOptions) -> dic
return None 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): 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 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) board = box(*problem.bounds)
world = RoutingWorld.from_problem(problem, board=board)
candidates = {} candidates = {}
for net in problem.nets: for net in problem.nets:
jogs = islice(_candidate_jogs(net, problem, search, radii), 512) 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): if not all(seeds_by_net):
return None 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) board = box(*problem.bounds)
world = RoutingWorld.from_problem(problem, board=board)
candidates = {} candidates = {}
for net, seeds in zip(problem.nets, seeds_by_net, strict=True): for net, seeds in zip(problem.nets, seeds_by_net, strict=True):
ranked = [ ranked = [

View file

@ -10,8 +10,7 @@ from inire.results import RoutingResult
from inire.router._astar_types import AStarContext, AStarMetrics, SearchRunConfig from inire.router._astar_types import AStarContext, AStarMetrics, SearchRunConfig
from inire.router._congestion_policy import can_reserve from inire.router._congestion_policy import can_reserve
from inire.router._search import incumbent_guidance, route_astar from inire.router._search import incumbent_guidance, route_astar
from inire.router.cost import CostEvaluator from inire.router.cost import CostEvaluator, proximity_map
from inire.router.danger_map import DangerMap
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Callable, Mapping, Set from collections.abc import Callable, Mapping, Set
@ -45,7 +44,7 @@ def _build_pair_local_context(
for polygon in component.physical_geometry: for polygon in component.physical_geometry:
world.add_static_obstacle(polygon, reserved=True) 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: if context.options.objective.danger_weight:
danger_map.precompute(list(static_obstacles)) danger_map.precompute(list(static_obstacles))
evaluator = CostEvaluator.from_objective( evaluator = CostEvaluator.from_objective(

View file

@ -82,9 +82,7 @@ def _direct_paths(
*, *,
priority: frozenset[str] = frozenset(), priority: frozenset[str] = frozenset(),
) -> dict[str, RoutingResult]: ) -> dict[str, RoutingResult]:
world = RoutingWorld(clearance=problem.clearance, safety_zone_radius=problem.safety_zone_radius, board=board) world = RoutingWorld.from_problem(problem, board=board)
for obstacle in problem.static_obstacles:
world.add_static_obstacle(obstacle)
ordered = ordered_nets(problem.nets, options.congestion.net_order) ordered = ordered_nets(problem.nets, options.congestion.net_order)
if priority: if priority:
ordered.sort(key=lambda net: net.net_id not in priority) ordered.sort(key=lambda net: net.net_id not in priority)

View file

@ -1,6 +1,7 @@
from __future__ import annotations from __future__ import annotations
import heapq import heapq
from math import inf
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from inire.constants import TOLERANCE_LINEAR from inire.constants import TOLERANCE_LINEAR
@ -93,6 +94,16 @@ def route_astar(
deferred_turns.clear() deferred_turns.clear()
if not open_set: if not open_set:
break 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) current = heapq.heappop(open_set)
if config.max_cost is not None and current.fh_cost[0] > config.max_cost: if config.max_cost is not None and current.fh_cost[0] > config.max_cost:

View file

@ -49,7 +49,7 @@ def materialize_path_seed(
for segment in seed.segments: for segment in seed.segments:
kind, parameters = seed_move(segment) 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( component = build_component(
current, current,
net_width, net_width,
@ -59,7 +59,8 @@ def materialize_path_seed(
physical_geometry_type=bend_physical_geometry, physical_geometry_type=bend_physical_geometry,
clip_margin=bend_clip_margin, clip_margin=bend_clip_margin,
dilation=dilation, 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) path.append(component)
current = component.end_port current = component.end_port

View file

@ -3,14 +3,11 @@ from __future__ import annotations
from dataclasses import dataclass, replace from dataclasses import dataclass, replace
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from shapely.geometry import box
from inire.geometry.collision import RoutingWorld from inire.geometry.collision import RoutingWorld
from inire.results import RoutingRunResult, _sum_route_metrics from inire.results import RoutingRunResult, _sum_route_metrics
from inire.router._astar_types import AStarContext from inire.router._astar_types import AStarContext
from inire.router._router import PathFinder from inire.router._router import PathFinder
from inire.router.cost import CostEvaluator from inire.router.cost import CostEvaluator, proximity_map
from inire.router.danger_map import DangerMap
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Callable from collections.abc import Callable
@ -19,6 +16,7 @@ if TYPE_CHECKING:
from inire.results import RoutingResult from inire.results import RoutingResult
from inire.router._router import PhaseTimer from inire.router._router import PhaseTimer
from inire.router._topology import Corridor from inire.router._topology import Corridor
from inire.router.danger_map import DangerMap
@dataclass(frozen=True, slots=True) @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) problem = plan_ordered_bundle(problem, options.search, infer_terminal_headings=options.topology.infer_terminal_headings)
world = RoutingWorld( world = RoutingWorld.from_problem(problem)
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)
danger_map = DangerMap(bounds=problem.bounds) danger_map = proximity_map(problem, options.search.proximity_range)
refinement = options.refinement refinement = options.refinement
if options.search.node_limit > 0 and options.congestion.max_iterations > 0 and ( 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) options.objective.danger_weight or (refinement.enabled and refinement.objective is not None and refinement.objective.danger_weight)

View file

@ -176,7 +176,7 @@ class CostEvaluator:
) )
# Skip danger sampling entirely when there are no static obstacles in the KD-tree. # 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_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) cost_e = danger_map.get_cost(end_port.x, end_port.y)
if start_port: if start_port:
@ -230,10 +230,17 @@ class CostEvaluator:
return total 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.""" """Score candidate paths using the original layout's obstacles and objective."""
danger = None danger = None
if objective.danger_weight and problem.static_obstacles: if objective.danger_weight and problem.static_obstacles:
danger = DangerMap(bounds=problem.bounds) danger = proximity_map(problem, proximity_range)
danger.precompute(list(problem.static_obstacles)) danger.precompute(problem.static_obstacles)
return CostEvaluator.from_objective(RoutingWorld(clearance=problem.clearance), danger, objective) return CostEvaluator.from_objective(RoutingWorld(clearance=problem.clearance), danger, objective)

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