Compare commits

..
Author SHA1 Message Date
8b32d68496 Reuse geometry and conflict reports during seed replay
Check a replayed route against itself and fixed geometry before adding it to the collision index. Add cross-net conflicts once the index is populated, then share reports across review, traces, and the callback. Recheck changed geometry after refinement.
2026-11-29 19:13:44 -08:00
fd6f96f341 Name collision-index additions by their inputs
Use add_route for route components and add_path_geometry for prepared polygons. Update the router, tests, and index helpers to use those names.
2026-11-29 19:12:15 -08:00
a6b0b9216a Query exact corner visibility on demand
Cache local queries at indexed corners and preserve exact distance limits. Keep the legacy counters available and report corner-index builds in the performance summary.
2026-11-29 16:37:41 -08:00
725f385ba3 Preserve structured serialization of routing snapshots
Allow dataclass and JSON conversion to traverse seed and result mappings while keeping the public snapshot mutation methods read-only.
2026-11-29 16:37:28 -08:00
8a97c1e64b Check actual terminal faces in search and seed replay
Keep nominal terminal checks for standard geometry. Defer to materialized geometry when a custom outline can reach a terminal and report blocked terminals consistently in iteration callbacks.
2026-11-29 16:37:14 -08:00
23d0a140c1 Use physical clearance for fixed routes and terminal bounds
Use the same physical clearance rule for fixed-route admission and verification. Preserve imported vertices while clearing GEOS precision metadata. Count touching terminal faces as conflicts at zero clearance.
2026-11-29 16:36:54 -08:00
42e1de9884 Keep route placement at the layout writer boundary
Use the effective net, seed, and search settings as the placement recipe. Remove the export-grid, whole-layer, and CPW mask assembly helpers and cover replay from resolved ports.
2026-11-29 16:36:32 -08:00
07f1c47e26 Document and test history-sensitive A* successors 2026-11-29 00:37:13 -08:00
aac0353382 Verify whole-layer exports against current profiles 2026-11-29 00:36:50 -08:00
8e8c8a7ba0 Keep routing and export verification snapshots read-only 2026-11-29 00:31:51 -08:00
9ba1dc048a Reserve search budget for deferred turns 2026-11-29 00:24:00 -08:00
491988d620 Coordinate routing attempts and isolate scheduling effort 2026-11-29 00:18:30 -08:00
c480871f07 Preflight component geometry before tessellation 2026-11-29 00:16:13 -08:00
286caa273b Preserve route identity through reservation and export 2026-11-29 00:12:59 -08:00
cea23ef1b4 Fix fabrication verification and routing diagnostics follow-up 2026-11-29 00:09:54 -08:00
1eed75ff5a Refresh the routing walkthrough and record final verification 2026-11-28 21:01:41 -08:00
8f6a917f51 Preserve routing coverage and verify release and example regressions 2026-11-28 20:57:22 -08:00
e6ae242cb2 Bound search memory and verify process geometry before layout export 2026-11-28 20:42:25 -08:00
facde64f09 Package only runtime code in wheels and set compatible dependency floors 2026-11-28 20:42:25 -08:00
af3ddfbb09 Recover bounded routes around bends and through narrow corridors 2026-11-28 20:29:40 -08:00
d02dbb872f Check physical separation within and between routed nets 2026-11-28 20:16:29 -08:00
9ee786d138 Repair exact visibility and hole rendering and streamline search state 2026-11-28 20:13:00 -08:00
8ad26cc3c1 Use cardinal headings and objective units in search estimates 2026-11-28 20:07:20 -08:00
2611085808 Preserve verify-only diagnostics and honor refinement objectives 2026-11-28 20:06:06 -08:00
f9ba5669dd Validate routing options and match custom S-bend widths consistently 2026-11-28 20:03:41 -08:00
a86e0a4f5a Verify physical bend joins and preserve fine-grid arc accuracy 2026-11-28 20:01:29 -08:00
3d7fc3a705 Support whole custom S-bend outlines and recover routing detours 2026-11-28 10:57:01 -08:00
e0f5543578 Reject invalid path reservations and improve seeded routing 2026-11-28 00:09:11 -08:00
b3580a9c07 Keep partial routes diagnostic and recover width-specific corridors 2026-11-27 22:52:06 -08:00
196cd00445 Fix routing clearance, retries, and S-bend verification 2026-11-27 21:40:53 -08:00
760182f25c Keep constructive routing available without triangulation 2026-11-27 21:14:09 -08:00
81 changed files with 4895 additions and 1319 deletions

View file

@ -22,7 +22,8 @@ If you're new to Inire, start with the [single-net quick start](README.md#route-
## Check and improve a 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.
- [Save a placement recipe](docs/user/route-a-layout.md#save-a-placement-recipe) to place the verified components in your layout.
- [Route with process constraints](docs/user/fabrication.md) for placed ports, process layers, authored lengths, 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.

View file

@ -33,7 +33,7 @@ else:
![A short solid waveguide connects the start at (50, 100) and target at (250, 100). Both port arrows point east.](docs/figures/first-route.png)
The example prints `200.0` in the layout's coordinate unit. Both ports use heading 0 because the path leaves the source and enters the target travelling east. Use this result to try [exporting the physical path](docs/user/route-a-layout.md#export-verified-geometry).
The example prints `200.0` in the layout's coordinate unit. Both ports use heading 0 because the path leaves the source and enters the target travelling east. Use `result.as_seed()` to [save the placement recipe](docs/user/route-a-layout.md#save-a-placement-recipe).
## Route your own layout

View file

@ -1,6 +1,6 @@
# Router architecture
An explicit routing mode runs one worker with that mode's settings. Automatic routing can run several workers with different obstacles, locks, or starting paths, then select a result. To see what a single worker receives and returns, start at [`route_once()`](../inire/router/_stack.py#L71).
An explicit mode starts one worker with that mode’s settings. Guide and seed can retry with zero guidance cost. Automatic routing can try several combinations of obstacles, locks, and starting paths. All modes use the same worker and assign iteration indices across attempts. See [`route_once()`](../inire/router/_stack.py#L65).
Follow one complete run from board input through planning, verification, and plotting in [Complex-routing example 1](complex-routing-example-1.md).
@ -8,15 +8,15 @@ Follow one complete run from board input through planning, verification, and plo
![Automatic routing sets a target for the number of verified nets and tries several ways to reach it. The router selects and optionally refines its best layout before returning a result for each net.](figures/automatic-stages.png)
Follow the left column down while the number of verified nets is below the target. The router selects a layout when an attempt reaches that target or the attempts run out. It uses lattice search directly for custom physical bends, polygonal proxies, or a run without constrained triangulation.
Follow the left column down while the number of verified nets is below the target. The router selects a layout when an attempt reaches that target or the attempts run out. It uses lattice search directly for custom physical bends or polygonal proxies. If constructive planning falls short and constrained triangulation is unavailable, it continues with lattice search.
1. **Set the coverage target.** A pair of nets with fixed ports that are too close can supply at most one route. Count such pairs using each net at most once. For rectangular keepouts, also bound the number of paths that can cross a vertical cut by packing tracks at the narrowest requested width. To see how the openings are counted, start with [`cut_capacity()`](../inire/router/_capacity.py#L27).
1. **Set the coverage target.** A pair of nets with aligned terminal faces that violate clearance can supply at most one route. At zero clearance, faces that touch also conflict. Count such pairs using each net at most once. For rectangular keepouts, also bound the number of paths that can cross a vertical cut by packing tracks at the narrowest requested width. To see how the openings are counted, start with [`cut_capacity()`](../inire/router/_capacity.py#L28).
2. **Try constructive planners.** Bundles assign ordered tracks through barriers. Column schedules place turns between openings. Compact planners fit short connections between constrained ports. Each produces seeds whose physical geometry the worker checks.
3. **Start with a small search budget.** Lock verified straight links and search for the remaining nets. A different lock order or a small unlocked probe can free room for a turn. Promising guide and column attempts can run first.
4. **Decide what to keep fixed.** If the remaining ports are connected, route around the locked geometry. If the locks disconnect them, pass the previously verified paths as seeds that can move. A joint retry can assign different lanes through a shared opening. If recovery stalls, seed and lattice attempts can search the whole layout. The final lattice retry can use the caller's full node limit.
5. **Select a verified layout.** Prefer more verified nets and compare cost when the verified net IDs match. A completed `incumbent-residual` trial or an improving `joint-portal-lanes` trial must pass another check with the original keepouts before it can win. Refinement can replace the selected layout only if it preserves the verified net IDs. See [the refinement handoff](../inire/router/_automatic.py#L581).
5. **Select a verified layout.** Prefer more verified nets and compare cost when the verified net IDs match. A completed `incumbent-residual` trial or an improving `joint-portal-lanes` trial must pass another check with the original keepouts before it can win. Refinement can replace the selected layout only if it preserves the verified net IDs. See [the refinement handoff](../inire/router/_automatic.py#L610).
The near-port attempt uses up to 100 nodes per search and two congestion iterations with the arc proxy. Alternate proxies use the configured iteration limit because a later shallow iteration can find a cheaper path. Wider lookahead uses up to 500 nodes per search and the configured iteration limit. Follow the caps and early exits in [the initial search trials](../inire/router/_automatic.py#L480).
The near-port attempt uses up to 100 nodes per search and two congestion iterations with the arc proxy. Alternate proxies use the configured iteration limit because a later shallow iteration can find a cheaper path. Wider lookahead uses up to 500 nodes per search and the configured iteration limit. Follow the caps and early exits in [the initial search trials](../inire/router/_automatic.py#L509).
### Example of a poor lock
@ -26,21 +26,29 @@ The near-port attempt uses up to 100 nodes per search and two congestion iterati
## Detailed search and congestion
- **Build and admit moves.** Weighted A* searches snapped positions and headings. Rays, visible corners, and corridor waypoints propose straight endpoints. Admission checks clearance, cost, and state dominance. To understand which endpoints a net can reach within the same node budget, start with [move generation](../inire/router/_astar_moves.py).
- **Build and admit moves.** Weighted A* searches snapped positions and headings. Rays, visible corners, and corridor waypoints propose straight endpoints. If a ray blocks a launch, a flat-ended trace scan checks for room to move. An aligned target goes directly to admission, which checks the straight's rectangular footprint for clearance. A long lead can use consecutive straights when a single forward scan cannot cover it. Search releases turns away from a distant target when preferred moves run out or the reserved share of the expansion budget begins. Searches with up to 16 expansions consider these turns immediately. Larger searches release them with at least one tenth of the budget left, rounded down with a minimum of one expansion. S-bends can follow each other when the configured moves permit it. Admission also checks cost and state dominance. [Move generation](../inire/router/_astar_moves.py)
- **Recheck the installed set.** The driver raises the overlap penalty when successive routes collide. After an iteration it verifies the installed paths, since a later route can collide with one completed earlier. It ranks snapshots by completed nets, then by conflicts and dynamic collisions. To see when it reroutes just the conflicting nets, read [`next_reroute_net_ids()`](../inire/router/_congestion_policy.py#L93).
The closed set groups states by snapped position and heading. Arrivals with different final straight lengths, seed progress, or occupied path geometry can offer different continuations. This pruning keeps the search bounded in practice and can discard an alternative history. A regression test demonstrates different straight proposals from equal-cost arrivals at one port.
- **Recheck the installed set.** Paths that reach their targets and pass geometry checks against themselves, the board, and keepouts participate in congestion. Partial and geometrically invalid paths remain available for diagnosis. After an iteration the driver verifies the installed paths, since a later route can collide with one completed earlier. It ranks snapshots by completed nets, then by conflicts and dynamic collisions. A narrowed retry includes every net that still fails verification. [`next_reroute_net_ids()`](../inire/router/_congestion_policy.py#L99)
- **Repair a small conflict set.** The driver returns to the best iteration and can reuse its verification when those paths are still installed and restored-stage traces are disabled. If the conflicts form separate pairs, the router can try repairing up to two of them. It holds the other paths fixed, tries both routing orders as needed, and checks proposed replacements against the installed layout. For a worked trace, [follow a late conflict](routing-diagnostics.md#follow-a-late-conflict-into-pair-local-repair).
## Geometry and refinement
Search uses proxies to check moves and estimate congestion. Verification rejects invalid polygons and checks each port for a finite-width face with material on the correct side. It checks adjacent components for overlap and checks the route against keepouts, other nets, and the board rectangle in every routing mode. Refinement uses the same configured bend geometry as search and seed materialization. A circular S-bend with a fractional forward span ends with a short tangent extension to the next grid point, keeping the requested radius. Boundary contact with the board is allowed.
A result carries the requested and effective net specs. The effective net records the resolved ports for replaying the move sequence after heading inference. Fixed routes carry their owner and physical polygons into the same collision world used by search and verification. The world applies distinct-net clearance to fixed geometry, and planners see fixed routes alongside keepouts. Routing preserves the vertices of imported polygons and clears their GEOS precision metadata so geometric operations use full coordinate precision. [Placement recipes](user/route-a-layout.md#save-a-placement-recipe)
Search, seed replay, and refinement share analytic endpoint and circular sampling calculations. Preparation rejects oversized sampling requests before allocating the outline. Verification uses the materialized polygons for exact containment and clearance.
Zero-node replay checks each complete path against the board, itself, and fixed geometry before adding eligible paths to the collision index. A second pass adds cross-net conflicts to those reports. Iteration review and final reporting reuse the results while the indexed routes stay the same.
Search uses proxies to check moves and estimate congestion. Verification rejects invalid polygons and checks each port for a finite-width face with material on the correct side. It checks for overlap within components and unintended contact between components, and checks the route against keepouts, other nets, and the board rectangle in every routing mode. Search and seed materialization use the same custom S-bend outline when one is configured. A circular S-bend with a fractional forward span ends with a short tangent extension to the next grid point, keeping the requested radius. Boundary contact with the board is allowed.
At a keepout corner, a mitred clearance buffer can reach farther than the specified clearance. Verification checks the actual distance before counting these hits as collisions. For an example with a corner close to the required clearance, see the [mitred-corner test](../inire/tests/test_collision.py#L146).
When expansion counts are similar but routing time rises, inspect ray casts for repeated visibility queries and exact pair checks for an overly broad dynamic lookup. The [metrics guide](routing-diagnostics.md#route-metrics) maps those questions to counters.
Dynamic congestion queries use a grid for small spans and an R-tree for large spans. When expansion counts are similar but routing time rises, inspect ray casts for repeated visibility queries and exact pair checks for an overly broad dynamic lookup. The [metrics guide](routing-diagnostics.md#route-metrics) maps those questions to counters.
Refinement tries replacing sections of routes with at least four 90-degree bends. It scores proposed detours before constructing their polygons. With a finite budget above one, it tries sections with bends at both ends first. With a budget of one or no window limit, it starts with the longest section by component count. It can check just the replacement when the original route is valid against the installed geometry. Final verification checks the entire updated route.
Refinement tries replacing sections of routes with at least four 90-degree bends. It indexes endpoints by heading and forward position to find eligible sections, then scores proposed detours before constructing their polygons. With a finite budget above one, it tries sections with bends at both ends first. With a budget of one or no window limit, it starts with the longest eligible section by component count. It can check just the replacement when the original route is valid against the installed geometry. Final verification checks the entire updated route. Automatic refinement also rechecks retained partial paths against the updated layout.
## Validate a change

View file

@ -14,7 +14,7 @@ Origin. The problem uses board 1 from Terminal-Bench pull request 345. [Pinned l
`build_problem()` reads the example entry into a `RoutingProblem` and `RoutingOptions`. The board is 2,500 by 1,000 units with seven rectangular keepouts and nine nets. The guides are 2 units wide, the clearance is 6, and both kinds of bends use radius 50. The fixed-heading case starts with no seeds and requires each net to launch and arrive heading east. [Example inputs](../examples/advanced-layouts.json) · [Problem builder](../examples/advanced_layouts.py#L34)
`route()` dispatches to automatic routing. The router checks whether any aligned terminal pairs are too close and whether a vertical cut has fewer tracks than nets that need to cross it. The board passes both checks, so automatic asks the constructive planners to verify all nine nets. [Automatic entry point](../inire/router/_automatic.py#L597) · [Capacity checks](../inire/router/_capacity.py#L27)
`route()` dispatches to automatic routing. The router checks whether any aligned terminal pairs are too close and whether a vertical cut has fewer tracks than nets that need to cross it. The board passes both checks, so automatic asks the constructive planners to verify all nine nets. [Automatic entry point](../inire/router/_automatic.py#L641) · [Capacity checks](../inire/router/_capacity.py#L28)
![The nine input nets surround seven rectangular keepouts. A cut at x = 500 has openings at the bottom, center, and top of the board.](figures/complex-routing-example-1-input.png)
@ -32,7 +32,7 @@ The dots mark waypoints in the proposed seeds. The lower inset shows the two con
## 3. Fit the required eastbound arrival
Automatic routing compares the bundle's inferred headings with the input. Only `net_08` differs. Its initial bundle arrives from the east heading west. The turnaround planner adjusts the upper shelf route `net_07` and brings `net_08` back below it. Near the target, `net_08` rises west of `x = 1112` and takes a final right turn to arrive heading east. The planner recompiles the two changed seeds and submits the full set for verification. [Constructive planner dispatch](../inire/router/_automatic.py#L202) · [Turnaround candidates](../inire/router/_perimeter.py#L103)
Automatic routing compares the bundle's inferred headings with the input. Only `net_08` differs. Its initial bundle arrives from the east heading west. The turnaround planner adjusts the upper shelf route `net_07` and brings `net_08` back below it. Near the target, `net_08` rises west of `x = 1112` and takes a final right turn to arrive heading east. The planner recompiles the two changed seeds and submits the full set for verification. [Constructive planner dispatch](../inire/router/_automatic.py#L228) · [Turnaround candidates](../inire/router/_perimeter.py#L103)
![Two views show the materialized shelf and return paths. In the initial plan net_08 arrives westbound. In the turnaround candidate it passes below the shelf, rises left of the target, and arrives eastbound.](figures/complex-routing-example-1-turnaround.png)
@ -40,13 +40,13 @@ The arrow above each red target square shows the arrival heading.
## 4. Verify the seeds and refine the layout
The first `bundle-turnaround` candidate verifies all nine nets. Automatic routing runs a worker in mode `off` for one iteration with a one-node search limit and refinement disabled. The worker materializes each seed into physical polygons, installs the paths, and rechecks the installed layout for port joins, board containment, and collisions. Every net has a complete seed, so the worker records zero A* expansions. The full coverage lets automatic routing skip its search trials. [Seeded worker setup](../inire/router/_automatic.py#L165) · [Seed installation](../inire/router/_router.py#L819) · [Physical verification](../inire/geometry/collision.py#L656)
The first `bundle-turnaround` candidate verifies all nine nets. Automatic routing runs a worker in mode `off` for one verification pass with a zero-node search limit and refinement disabled. The worker materializes each seed into physical polygons, installs the paths, and rechecks the installed layout for port joins, board containment, and collisions. The full coverage lets automatic routing skip its search trials. [Seeded worker setup](../inire/router/_automatic.py#L173) · [Seed installation](../inire/router/_router.py#L877) · [Physical verification](../inire/geometry/collision.py#L708)
![The upper panel shows the physical paths of the first four nets in installation order. The lower panel shows all nine paths after verification.](figures/complex-routing-example-1-verification.png)
The upper panel reconstructs the first four installed paths from the worker's verified seeds. The lower panel shows the full set checked together.
Automatic then replays the verified seeds in a worker with refinement enabled. The refiner tries replacing sections with at least four 90-degree bends and verifies the resulting layout. In this run, refinement changes `net_05` and `net_07` and keeps all nine nets verified. The refined layout wins on the configured objective, which includes component penalties as well as length. [Refinement handoff](../inire/router/_automatic.py#L580) · [Trial comparison](../inire/router/_routing_policy.py#L44)
Automatic then replays the verified seeds in a worker with refinement enabled. The refiner tries replacing sections with at least four 90-degree bends and verifies the resulting layout. In this run, refinement changes `net_05` and `net_07` and keeps all nine nets verified. The refined layout wins on the configured objective, which includes component penalties as well as length. [Refinement handoff](../inire/router/_automatic.py#L610) · [Trial comparison](../inire/router/_routing_policy.py#L45)
![The refined net_07 stays near the top edge longer and descends close to its target. Its earlier approach is dashed, and the outer return remains visible below it.](figures/complex-routing-example-1-refinement.png)
@ -67,6 +67,32 @@ python -m scripts.compare_topological_routing \
To see how heading inference changes the route, rerun the gallery command with `--case complex-routing-example-1-point-terminals`. Automatic accepts the westbound arrival for `net_08`, verifies the original `bundle` plan, and then refines it. Both stages again verify nine nets with zero A* expansions. [Point-terminal figure](../examples/advanced.md#point-terminals) · [Waypoint export command](benchmark-fixtures.md#complex-routing-example-1)
## Compare all routing modes
These runs use the same nine-net board with a 100-node limit per search, one congestion iteration, warm start disabled, and refinement disabled. The table compares a run with triangulation available against a run with that capability disabled. Each mode keeps the input headings except `bundle`, which uses `infer_terminal_headings=True` so `net_08` can arrive westbound. Explicit `bundle` with the original fixed eastbound headings raises a heading mismatch for that net.
| Mode | With triangulation available | Without triangulation |
| --- | --- | --- |
| `automatic` | 9/9 verified. The turnaround plan completes the layout without building a mesh. | 9/9 verified through the same turnaround plan. Automatic uses lattice search if constructive planning leaves work. |
| `off` | 0/9 verified at this budget. The worker runs lattice search directly. | Same search and result. |
| `guide` | 1/9 verified. The worker builds a mesh and suggests corridors to lattice search. | Raises a dependency error when planning corridors. |
| `seed` | 1/9 verified. The worker builds a mesh and searches for starting paths inside the corridors before its routing iteration. | Raises a dependency error when planning corridors. |
| `bundle` | 9/9 verified. The worker builds and verifies ordered tracks directly from the board geometry. | Same plan and result. |
![Five panels show route outcomes at the same search budget. Automatic and bundle verify all nine nets. Off, guide, and seed leave partial paths.](figures/complex-routing-example-1-modes.png)
### Triangulation support
Corridor planning uses Shapely's constrained Delaunay triangulation to keep triangle edges inside free space and respect keepout boundaries. It requires **Shapely 2.1 or later and GEOS 3.10 or later**. On supported platforms a Shapely wheel bundles GEOS. In a pip environment, use `python -m pip install --upgrade "shapely>=2.1"`. A source build needs a compatible system GEOS. [Shapely triangulation reference](https://shapely.readthedocs.io/en/2.1.2/reference/shapely.constrained_delaunay_triangles.html) · [Shapely installation guide](https://shapely.readthedocs.io/en/2.1.2/installation.html)
Check the versions in the environment that runs Inire.
```sh
python -c 'import shapely; print(shapely.__version__, shapely.geos_version_string)'
```
Inire supports Shapely 2.0.7 for lattice routing and constructive plans. With a compatible backend, automatic already uses triangulation whenever it needs corridor search. Here the ordered bundle and turnaround cover all nine nets, so automatic can move directly to verification. Explicit `guide` and `seed` also verify supplied paths without a mesh when `node_limit=0`.
## Compare a guide-mode search
The successful bundle run above reaches verification before the corridor search. To see that search's working model, the figure generator runs `net_08` by itself in guide mode on the same board. The left panel shows the actual triangulation, corridor cells in green, and the guide through them as a dashed line. The right panel zooms in on the expanded positions and physical partial path returned when A* reaches its 12-node budget. [Corridor planning](topological-routing.md#corridor-planning-and-realization)

View file

@ -9,6 +9,8 @@
## Check a change
The wheel contains the runtime package. Repository tests and benchmark fixtures are available in the source distribution. Build both locally with `uv build`. For release smoke checks, import and route from the wheel outside the checkout with NumPy 1.26 and NumPy 2.x on Python 3.11, using Shapely 2.0.7 in both environments. Automatic routing falls back to lattice search on Shapely 2.0.7. Guide and seed search require Shapely 2.1 and a GEOS build with constrained triangulation.
1. From the repository root, run `uv sync` to install development dependencies. Activate `.venv` or prefix commands with `uv run`.
2. Run `python -m pytest` for the correctness suite and `ruff check inire scripts` for lint. Use `python -m pytest -m "not routing_corpus"` for a shorter local check.
3. For a cleanup that should preserve paths, capture both revisions and run an [exact parity comparison](routing-diagnostics.md#reproduce-and-compare). Include callbacks or traces if the change affects them.

Binary file not shown.

After

Width:  |  Height:  |  Size: 130 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 32 KiB

After

Width:  |  Height:  |  Size: 32 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 45 KiB

After

Width:  |  Height:  |  Size: 45 KiB

Before After
Before After

View file

@ -24,10 +24,16 @@ 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).
Exact corner visibility uses cached local queries. Track them with `visibility_corner_queries_exact` and `visibility_point_cache_hits`. The legacy graph counters `visibility_builds` and `visibility_corner_pairs_checked` report zero, as do `ray_cast_calls_visibility_build` and `ray_cast_calls_visibility_query`.
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.
Returned traces describe the selected attempt. Numbered entries use the same run-wide indices as progress callbacks. A timed-out iteration can consume an index without calling back. Work counters include all attempts. Reroute scheduling tracks its own effort from node expansions and uncached congestion queries.
| Question | Flag and result |
| --- | --- |
| Which net consumed an iteration's budget? | `capture_iteration_trace` records `iteration_trace`. Inspect per-net `net_attempts` for expansions, pruning, congestion calls, and seed usage. |

View file

@ -10,13 +10,13 @@ Guide mode suggests where a path can pass through free space and lets detailed s
In the offset-gates example, the two openings are at different heights. The top panel highlights the proposed sequence of triangle edges to cross. In the middle panel, the dashed line joins suggested crossing points. In the bottom panel, the solid route uses an S-bend to change height between the openings.
1. **Find connected space for centerlines.** Inset the board by half the widest guide's width and expand obstacles by that half-width plus clearance. To connect a port to the mesh, try a short straight along its departure or arrival heading, or use the port position itself. The common padding can exclude openings that a narrower net can still use in lattice search.
1. **Find connected space for centerlines.** Inset the board by half the widest guide's width and expand obstacles by that half-width plus clearance. To connect a port to the mesh, try a short straight along its departure or arrival heading, or use the port position itself. A lead from a flush port can cross the inset boundary when its flat-ended footprint fits inside the board and clears the keepouts. If the shared mesh finds no passage for a narrower net, retry with padding for its width.
<a id="design-background"></a>
A portal is an edge shared by adjacent free-space triangles. For an earlier representation of a route by its crossings of triangle edges, see Section III-A and Figure 1 of [Hama and Etoh's curvilinear detailed-routing paper](https://www.cecs.uci.edu/~papers/compendium94-03/papers/1998/aspdac98/pdffiles/06c_3.pdf).
2. **Choose a passage and a lane.** Rank a sequence of portals by distance and how many other nets want to use the same edges. A lane is a suggested position along an edge where a net can cross into the next triangle. Rank those positions by turn room and the lanes reserved for other nets. A joint retry can change the lane positions for several nets at the same opening. To see how the positions are scored, inspect [`assign_lanes()`](../inire/router/_topology.py#L214).
2. **Choose a passage and a lane.** Rank a sequence of portals by distance and how many other nets want to use the same edges. A lane is a suggested position along an edge where a net can cross into the next triangle. Rank those positions by turn room and the lanes reserved for other nets. A joint retry can change the lane positions for several nets at the same opening. To see how the positions are scored, inspect [`assign_lanes()`](../inire/router/_topology.py#L247).
3. **Turn the sketch into a path.** Guide mode uses the corridor to suggest moves and add a soft cost, so search can leave it to make a turn. Seed mode first searches inside a corridor and checks any seed against obstacles and earlier seeds. With alternatives, the first corridor gets at least half the per-net seed budget. Later detailed iterations can move an incumbent or use another guide. Final verification checks the installed geometry.

View file

@ -8,14 +8,16 @@ Import these types from `inire`. To see how the inputs fit together in a runnabl
route(problem, *, options=None, iteration_callback=None) -> RoutingRunResult
```
Omitting `options` uses `RoutingOptions()`. To observe progress, pass a callable accepting `(index, results_by_net)`. Each call receives a snapshot of the nets in one completed congestion iteration. Automatic mode keeps increasing the index across attempts and uses the same planner order with or without a callback. Check the returned result for final coverage, including on runs that finish without a callback.
Omitting `options` uses `RoutingOptions()`. To observe progress, pass a callable accepting `(index, results_by_net)`. Each call receives a snapshot of the nets in one completed congestion iteration. Indices increase across attempts. An iteration that times out can consume an index without calling back. Automatic mode uses the same planner order with or without a callback. Check the returned result for final coverage, including on runs that finish without a callback.
For a zero-node attempt that completes its replay iteration, the callback receives the verified results after any refinement.
## Layout inputs
### Ports and nets
- `Port(x, y, r)` rounds coordinates to integers. The heading `r` is in degrees, with 0 east, 90 north, 180 west, and 270 south. The rounded angle must be a multiple of 90 and is wrapped to the range 0–359.
- `NetSpec(net_id, start, target, width=2.0)` uses a unique ID, two ports, and a finite positive width. Set the start heading to the direction of departure and the target heading to the direction of arrival.
- `NetSpec(net_id, start, target, width=2.0)` uses a unique string ID, two ports, and a finite positive width. Set the start heading to the direction of departure and the target heading to the direction of arrival. If both snapped ports are identical, connect the placed ports directly and omit that net from the routing problem.
### RoutingProblem
@ -25,10 +27,12 @@ The fields below appear in constructor order. Use one layout unit for coordinate
| --- | --- | --- |
| `bounds` | Required | Finite board rectangle as `(xmin, ymin, xmax, ymax)`, with each minimum below its maximum. |
| `nets` | `()` | Sequence of `NetSpec` objects with unique IDs. Duplicate IDs raise `ValueError`. |
| `static_obstacles` | `()` | Valid, nonempty Shapely `Polygon` objects that define keepouts. |
| `initial_paths` | Empty mapping | Net IDs mapped to `PathSeed` objects. |
| `clearance` | `2.0` | Finite, nonnegative spacing required between physical shapes. |
| `safety_zone_radius` | `0.0021` | Tolerance for small obstacle intersections at a move's endpoints during search. |
| `static_obstacles` | `()` | Valid, nonempty Shapely `Polygon` objects in board coordinates that define routing keepouts. Coordinates may be fractional. |
| `initial_paths` | Empty mapping | A read-only snapshot of net IDs mapped to `PathSeed` objects. Supply a new mapping to change seeds. |
| `clearance` | `2.0` | Finite, nonnegative spacing required between distinct nets and between a net and a keepout. At zero clearance, distinct nets must still be disjoint, including at vertices. Boundary contact with a keepout is allowed. |
| `safety_zone_radius` | `0.0021` | Tolerance for small keepout intersections at a move's endpoints during search. |
| `self_clearance` | `0.0` | Optional spacing within one net. Applies between components when the intervening centerline is at least this long. Adjacent joins and components immediately on either side of one bend are exempt. Unintended contact is always checked. |
| `fixed_routes` | `()` | Completed or imported net geometry supplied as `FixedRoute(net_id, polygons)`. Search and verification check clearance to fixed routes using the physical outlines. IDs must be unique across fixed and active nets. |
## Path seeds
@ -38,16 +42,20 @@ The fields below appear in constructor order. Use one layout unit for coordinate
| Value | Read it for |
| --- | --- |
| `RoutingRunResult.results_by_net` | A mapping from net ID to `RoutingResult`. |
| `RoutingRunResult.results_by_net` | A read-only mapping from net ID to `RoutingResult`. Use `dict(run.results_by_net)` to make an editable copy. |
| `RoutingResult.is_valid` and `outcome` | `is_valid` is true when the outcome is `completed`. Read `outcome` to distinguish success, a failed geometry check (`colliding`), a path that stopped short (`partial`), or an empty path (`unroutable`). |
| `RoutingResult.path` | Ordered path components from the source to the last reached state. An unroutable result has an empty path. |
| `RoutingResult.requested_net` and `effective_net` | The net as supplied and the net used by the worker, including resolved headings. |
| `RoutingResult.path` | Ordered path components from the source to the last reached state. Each component carries its move specification and placed start and end ports. An unroutable result has an empty path. |
| `RoutingResult.reached_target` | Whether the path reached the target position and heading. With heading inference, the check uses the chosen heading. Read `is_valid` for the result of geometry verification. |
| `RoutingResult.report` | `total_length` in layout units plus static, dynamic, and self-collision counts. `out_of_bounds` flags geometry outside the board. `discontinuous` flags missing or point-only joins, including at terminal faces. `invalid_geometry` flags invalid or empty physical polygons. |
| `RoutingResult.locked_geometry` and `as_seed()` | Physical polygons and the sequence of moves, respectively. Check validity before exporting polygons or using them as keepouts. |
| `RoutingResult.report` | `total_length` in layout units plus static, dynamic, and self-collision counts. `out_of_bounds` flags geometry outside the board. `discontinuous` flags missing or point-only joins, including at terminal faces. `invalid_geometry` flags invalid or empty physical polygons. `seed_error` identifies a supplied bend that cannot carry the net's width or cannot be safely materialized. `terminal_error` identifies an inaccessible start or target face. |
| `RoutingResult.as_seed()` | The ordered moves for [saving a placement recipe](route-a-layout.md#save-a-placement-recipe) or replaying a path. |
| `RoutingResult.locked_geometry` | Physical polygons checked during routing. Use these to inspect the route or [reserve a completed net](route-a-layout.md#reuse-an-existing-route). |
| `RoutingRunResult.automatic` | In automatic mode, the selected planner, verified IDs, stage history, and any capacity or port-conflict bound. `None` for explicit modes. |
| `RoutingRunResult.topology` and `metrics` | Corridor counts and seed work when reported by the selected worker, plus work counters across the run. |
To read a route's polygons and write them to a test file, follow the [geometry export steps](route-a-layout.md#export-verified-geometry).
Check `is_valid` and keep the effective net and geometry settings with each placement recipe. [Placement workflow](route-a-layout.md#save-a-placement-recipe)
For structured logging, `dataclasses.asdict(run)` preserves the per-net fields. Choose how to encode the Shapely polygons when writing JSON.
## Options and defaults
@ -66,26 +74,38 @@ To read a route's polygons and write them to a test file, follow the [geometry e
| Field | Default | Effect |
| --- | --- | --- |
| `node_limit` | `1_000_000` | Per-search expansion ceiling. Automatic uses smaller budgets for its initial stages. |
| `node_limit` | `1_000_000` | Nonnegative integer per-search expansion ceiling. Automatic uses smaller budgets for its initial stages. Zero skips search and corridor preparation and verifies supplied seeds in one pass if congestion iterations are enabled. Disable refinement to inspect the unchanged seed geometry. |
| `min_straight_length` | `5.0` | Finite, nonnegative minimum length for regular forward moves in lattice search. |
| `max_straight_length` | `2000.0` | Finite, positive maximum distance for the forward scan in lattice search. |
| `greedy_h_weight` | `1.5` | Weight on the estimated cost still needed to reach the target. Lower values give more influence to the cost of the path so far. |
| `greedy_h_weight` | `1.5` | Finite, nonnegative weight on the estimated cost still needed to reach the target. Lower values give more influence to the cost of the path so far. |
| `bend_radii` | `(50.0, 100.0)` | Finite, positive radii permitted for 90-degree bends in search and seeds. Each move needs a radius of at least half its net width. Fractional radii retain their curvature and extend both tangents to the next grid point. An empty list disables 90-degree bends. |
| `sbend_radii` | `(10.0,)` | Finite, positive radii permitted for S-bends in search and seeds, subject to the same width requirement. An empty list disables S-bends. |
| `sbend_offsets` | `None` | `None` lets the router choose signed lateral offsets. An explicit list restricts routing and seeds to those offsets after rounding to the grid. An empty list disables S-bends. |
| `bend_collision_type` | `"arc"` | Search proxy, one of `"arc"`, `"bbox"`, or `"clipped_bbox"`. The legacy polygon form defines both shapes unless split geometry is supplied. |
| `bend_proxy_geometry` | `None` | Override the proxy. A custom polygon proxy by itself keeps the standard physical arc and emits a warning. |
| `bend_physical_geometry` | `None` | Override the physical geometry with `"arc"` or a polygon. A custom physical polygon also supplies the default proxy when the collision type is `"arc"`. Custom polygons for fractional 90-degree bends are positioned relative to the arc center and must include both tangent extensions. |
| `bend_proxy_geometry` | `None` | Override the bend proxy. A polygon applies to 90-degree bends. A custom polygon proxy by itself keeps the standard physical arc and emits a warning. |
| `bend_physical_geometry` | `None` | Override 90-degree bend geometry with `"arc"` or a polygon. A custom physical polygon also supplies the default proxy when the collision type is `"arc"`. Define the polygon relative to the arc center and include both tangent extensions for a fractional radius. |
| `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, local visibility tests from indexed corners 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. |
| `distance_heuristic_weight` | `1.0` | Finite, nonnegative multiplier for the remaining-distance term only. Increase it to favor progress toward the target relative to estimated turn penalties. The routed path's objective stays the same. |
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 seed replay. 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 a net can use a custom outline, search checks the geometry of each candidate move at its terminals. Seed replay verifies the materialized faces.
Circular bends approximate the outer edge within a sagitta of 0.01 layout units. The router also sizes the subdivision for the outer edge of a clearance-expanded circular proxy. A generated circular arc that needs more than 250,000 subdivisions is rejected before sampling. Use coarser layout units if the required radii exceed this limit.
### ObjectiveWeights
The search objective scores path length, components, and proximity. Increasing a component penalty makes routes with more of that component less attractive. Refinement can use its own objective.
The search objective scores path length, components, and proximity. All weights must be finite and nonnegative. Increasing a component penalty makes routes with more of that component less attractive. Refinement can use its own objective.
| Field | Default | Effect |
| --- | --- | --- |
| `unit_length_cost` | `1.0` | Cost per unit of path length. |
| `unit_length_cost` | `1.0` | Cost per unit of path length, including estimated remaining distance in lattice and corridor search. At zero, the estimate still includes configured turning penalties. |
| `bend_penalty` | `250.0` | Additional cost of a 90-degree bend. Smaller radii incur a larger surcharge when this penalty is positive. |
| `sbend_penalty` | `500.0` | Additional cost of an S-bend. |
| `danger_weight` | `1.0` | Weight of the obstacle proximity cost. |
@ -96,9 +116,9 @@ Increase the iteration limit when later reroutes might resolve conflicts. Adjust
| Field | Default | Effect |
| --- | --- | --- |
| `max_iterations` | `10` | Maximum congestion iterations per attempt. Automatic's initial probe may use fewer. Zero skips warm-start and corridor searches. |
| `base_penalty` | `100.0` | Initial penalty for overlapping other routes. |
| `multiplier` | `1.5` | Scale the penalty between unresolved iterations. |
| `max_iterations` | `10` | Nonnegative integer maximum for congestion iterations per attempt. Automatic's initial probe may use fewer. Zero skips warm-start and corridor searches. |
| `base_penalty` | `100.0` | Finite, nonnegative initial penalty for overlapping other routes. |
| `multiplier` | `1.5` | Finite, nonnegative penalty multiplier between unresolved iterations. |
| `use_tiered_strategy` | `True` | Allow a cheaper bend proxy in the first iteration when applicable. |
| `net_order` | `"user"` | Start from input order or sort by the sum of the horizontal and vertical distances between ports with `"shortest"` or `"longest"`. |
| `warm_start_enabled` | `True` | Build greedy seeds before congestion iterations. |
@ -110,7 +130,7 @@ Increase the iteration limit when later reroutes might resolve conflicts. Adjust
| Field | Default | Effect |
| --- | --- | --- |
| `enabled` | `True` | Try geometric improvements after routing. |
| `objective` | `None` | Use another `ObjectiveWeights` value for refinement, or reuse the search objective. |
| `objective` | `None` | Use another `ObjectiveWeights` value for refinement, or reuse the search objective. When set, automatic mode uses this objective to compare a verified refinement with its incumbent on the same net set. `automatic_length_weights` still applies to planner selection. |
| `max_windows_per_net` | `4` | Maximum number of path sections to try replacing per net across improvement rounds. Use `1` for a shorter pass or `None` to remove this limit. |
### TopologyOptions
@ -121,7 +141,7 @@ For a layout that repeatedly stops short at an opening, `guide` can suggest a pa
| --- | --- | --- |
| `mode` | `"automatic"` | Select a [routing mode](tune-and-troubleshoot.md#choose-a-routing-mode). |
| `max_corridors` | `3` | Maximum proposed passages per net. |
| `guide_strength` | `0.75` | Maximum added guidance cost per unit length. Zero keeps the suggested moves without adding cost. |
| `guide_strength` | `0.75` | Maximum added guidance cost per unit length. Explicit guide and seed runs with at least two configured congestion iterations may try one additional iteration from the start with zero guidance cost. The retry retains corridor move proposals and wins only with higher verified coverage. |
| `seed_node_limit` | `600` | Total seed-search expansions per net, capped by the active search limit. |
| `infer_terminal_headings` | `False` | Let automatic or bundle mode choose headings for supported layouts with flexible port directions. Automatic preserves caller headings when initial paths are supplied. |
| `automatic_cost` | `"selective"` | Try a second column-planning pass based on route cost when the first pass chains short S-bends. Use `"always"` to try both passes or `"never"` to plan by span alone. |

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

@ -0,0 +1,85 @@
# Route with process constraints
Inire checks routed-path continuity, board containment, and clearance for the geometry in the routing problem. Use the placed-cell and process data for port compatibility, layer assignment, and length tolerances. Keep that context with each [placement recipe](route-a-layout.md#save-a-placement-recipe) when assembling the layout.
## 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. Use routing keepouts with local openings for the terminal leads. When you assemble the layout, place the verified route against the device ports and check the physical joins. [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 placement 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.
placement = original_placement
if preserves_length(replacement, authored_length, length_tolerance):
placement = (replacement.effective_net, replacement.as_seed(), options.search)
```
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. The length check retains the original placement 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)
## Keep layers and process profiles with the nets
Each `RoutingProblem` represents one collision plane. Group independent layers by layer and datatype and keep that pair with the placement recipes. 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
placements_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],
)
options = options_by_layer[layer]
run = route(plane, options=options)
placements = {}
for net_id, result in run.results_by_net.items():
if not result.is_valid:
raise ValueError(f"Route {net_id!r} ended with outcome {result.outcome!r}")
placements[net_id] = (result.effective_net, result.as_seed(), options.search)
placements_by_layer[layer] = placements
```
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 import RoutingProblem
from inire.layout import route_profiles
cpw_plane = RoutingProblem(
bounds, (flux_net, feed_net), static_obstacles=cpw_keepouts, clearance=ground_strip_width,
)
profiles = [
((flux_net.net_id,), flux_options),
((feed_net.net_id,), feed_options),
]
results = route_profiles(cpw_plane, profiles)
placements = {}
for net_ids, options in profiles:
for net_id in net_ids:
result = results[net_id]
if not result.is_valid:
raise ValueError(f"Route {net_id!r} ended with outcome {result.outcome!r}")
placements[net_id] = (result.effective_net, result.as_seed(), options.search)
```
## Route a coplanar waveguide envelope
For a 15.5 µm signal with a 7 µm gap on each side, route with a width of 29.5 µm. Use the required ground-strip width as the clearance between envelopes. Save the verified placement recipe for your component library. To verify the same path at the signal width, replay its seed with a 15.5 µm net using the same effective ports and bend rules.
A 3 µm minimum ground strip rejects parallel tracks at 28 µm and 32 µm pitches. A 36 µm pitch leaves a 6.5 µm strip between their envelopes.

View file

@ -8,14 +8,14 @@ To get a result you can experiment with, run the [single-net quick start](../../
2. **Set source and target headings.** A heading is the direction the waveguide travels as it leaves its source or enters its target. Heading 0 points east and 90 points north. If a device labels a target port by the direction it faces outward, reverse that heading by 180 degrees. For example, a waveguide entering a west-facing port travels east, so its target heading is 0.
3. **Add a net for each connection.** Give each `NetSpec` a unique ID and the guide width. Use your process's allowed bend radii in [`SearchOptions`](api-reference.md#searchoptions).
4. **Set the board and keepouts.** Pass the board rectangle as `bounds`, Shapely polygons as `static_obstacles`, and the required physical spacing as `clearance`. For the defaults and accepted inputs, see [`RoutingProblem`](api-reference.md#routingproblem).
5. **Route and check.** Call `route(problem, options=options)`. Automatic mode is the default. Before exporting, [check each net's result](tune-and-troubleshoot.md#read-the-result).
5. **Route and check.** Call `route(problem, options=options)`. Automatic mode is the default. Before using a placement recipe, [check the net's result](tune-and-troubleshoot.md#read-the-result).
<a id="connect-a-preplaced-crossing"></a>
## Route between placed crossings
1. **Place the crossing cells.** Keep each cell's physical footprint and internal connections in your layout. Get the port positions and headings in board coordinates after applying placement and rotation.
2. **Reserve routing keepouts around the cells.** Use the device's routing keepout if supplied. Otherwise, start from its footprint and make local openings at the ports you're connecting. Keep the full physical cell in the exported layout.
2. **Reserve routing keepouts around the cells.** Use the device's routing keepout if supplied. Otherwise, start from its footprint and make local openings at the ports you're connecting. Keep the full physical cell in your layout.
3. **Route the external connections.** Give Inire one net per connection between devices. The example connects A's east port to B's west port. B's arrival heading points east into the cell.
![Two rectangular crossing cells at different heights. A waveguide runs from the opening on A's right edge to the opening on B's left edge. Both port arrows point east.](../figures/placed-crossing.png)
@ -63,55 +63,83 @@ result = run.results_by_net[net_id]
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.
When assembling the layout, check the port joins and clearance against the actual placed-cell geometry. Inire verifies the external route against the keepouts you supplied.
## Export verified geometry
For declared port widths and transition cells, see [Check placed optical ports](fabrication.md#check-placed-optical-ports).
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.
## Save a placement recipe
After checking `result.is_valid`, use `result.as_seed()` to get the ordered moves. Keep the effective net, the component settings, and your coordinate unit with the recipe. The effective net records the resolved terminal positions and headings and the route width.
```python
from pathlib import Path
from shapely.geometry import GeometryCollection
if not result.is_valid:
raise ValueError(f"{result.net_id}: {result.outcome}")
raise ValueError(f"Route {result.net_id!r} ended with outcome {result.outcome!r}")
geometry = GeometryCollection(result.locked_geometry)
Path("route.wkt").write_text(geometry.wkt + "\n", encoding="utf-8")
placement = (result.effective_net, result.as_seed(), options.search)
```
For a multi-net layout, apply the validity check to every net you intend to export. If a route is short or colliding, use its outcome to choose the [next troubleshooting check](tune-and-troubleshoot.md#read-the-result).
The example uses the `options` from the crossing example. If you called `route(problem)`, use `RoutingOptions().search`.
Place the first move at the effective start port and each subsequent move at the previous move's end port. For explicit placements, read the `move_spec`, `start_port`, and `end_port` of each component in `result.path`. Use the same width, radii, tangent extensions, and custom outlines that the router checked.
Your layout tool realizes the components and writes the layout. Choose widths and clearance with enough margin for any downstream rounding. Inire's verification describes the supplied geometry in routing units. Use `result.locked_geometry` to inspect the polygons it checked or reserve them in a later routing run.
## Reuse an existing route
- **Give the router a route it can move.** Put `result.as_seed()` in `initial_paths` under the net's ID. A seed uses the current start port, width, and geometry settings. A partial seed can suggest an approach. To build a hint from turns and straights, see the [path seed reference](api-reference.md#path-seeds).
- **Hold a route fixed.** Check `result.is_valid`, then add `result.locked_geometry` to `static_obstacles` while routing other nets. The next run applies its own clearance to those polygons.
- **Give the router a route it can move.** Put `result.as_seed()` in `initial_paths` under the net's ID. A seed uses the current start port, width, and geometry settings. Search can follow a partial seed from the first iteration and can leave it to find another approach. To build a hint from turns and straights, see the [path seed reference](api-reference.md#path-seeds).
- **Hold a route fixed.** Check `result.is_valid`, then use `FixedRoute.from_result(result)` and pass it in `fixed_routes` alongside the remaining nets. The next run respects it as a distinct net, including at zero clearance.
Route a straight net, then use its polygons as keepouts in a second routing problem. The second net has to detour around one end of the fixed route.
When terminal headings are inferred, use the effective net with the saved moves to replay the same placement.
```python
from inire import (
NetSpec, Port, RoutingOptions,
RoutingProblem, SearchOptions, route,
from dataclasses import replace
from inire import RefinementOptions, TopologyOptions, route
chosen = route(problem, options=options)
verified_nets = []
seeds = {}
for net in problem.nets:
result = chosen.results_by_net[net.net_id]
if result.is_valid:
verified_nets.append(result.effective_net)
seeds[net.net_id] = result.as_seed()
replay = route(
replace(problem, nets=tuple(verified_nets), initial_paths=seeds),
options=replace(
options,
search=replace(options.search, node_limit=0),
topology=TopologyOptions(mode="off"),
refinement=RefinementOptions(enabled=False),
),
)
for net in verified_nets:
result = replay.results_by_net[net.net_id]
assert result.is_valid
assert result.locked_geometry == chosen.results_by_net[net.net_id].locked_geometry
```
Route a straight net, then reserve it while routing another net on the same layer. The second net has to detour around one end of the fixed route.
```python
from dataclasses import replace
from inire import FixedRoute, NetSpec, Port, RoutingOptions, RoutingProblem, SearchOptions, route
bounds = (0, -50, 100, 50)
options = RoutingOptions(search=SearchOptions(bend_radii=(10,)))
first = RoutingProblem(
bounds=bounds,
nets=(NetSpec("fixed", Port(10, 0, 0), Port(90, 0, 0)),),
)
fixed = route(first, options=options).results_by_net["fixed"]
assert fixed.is_valid
fixed_net = NetSpec("fixed", Port(10, 0, 0), Port(90, 0, 0))
detour_net = NetSpec("detour", Port(50, -20, 90), Port(50, 20, 90))
problem = RoutingProblem(bounds=bounds, nets=(fixed_net, detour_net), clearance=0)
fixed = route(replace(problem, nets=(fixed_net,)), options=options).results_by_net["fixed"]
second = RoutingProblem(
bounds=bounds,
nets=(NetSpec("detour", Port(50, -20, 90), Port(50, 20, 90)),),
static_obstacles=fixed.locked_geometry,
)
detour = route(second, options=options).results_by_net["detour"]
remaining = replace(problem, nets=(detour_net,), fixed_routes=(FixedRoute.from_result(fixed),))
detour = route(remaining, options=options).results_by_net["detour"]
assert detour.is_valid
detour_placement = (detour.effective_net, detour.as_seed(), options.search)
```
For imported metal or waveguide polygons that belong to an existing net, use `FixedRoute("existing_net", imported_polygons)`. Supply polygons in board coordinates. For other artwork that blocks routing, use `static_obstacles`.
To compare the two paths on a plot, see the [fixed-route example](../../examples/README.md#route-around-fixed-geometry).

View file

@ -6,12 +6,12 @@ Start with `run.results_by_net[net_id].outcome`. It distinguishes a path that st
| `result.outcome` | What to inspect |
| --- | --- |
| `completed` | The path reached its target and passed verification. Read its length in `report.total_length` and follow the [geometry export steps](route-a-layout.md#export-verified-geometry). |
| `completed` | The path reached its target and passed verification. Read its length in `report.total_length` and [save its placement recipe](route-a-layout.md#save-a-placement-recipe). |
| `colliding` | The path reached its target and failed verification. Check `result.report` for keepout clearance, conflicts with another route, self-overlap, invalid geometry, a bad join, or geometry outside the board. |
| `partial` | Read the position and heading of `result.path[-1].end_port`. Check room for the path to continue from that heading. If the next turn fits, compare search limits. |
| `unroutable` | The path is empty. Check the launch heading and room for the first straight or bend. |
Check `is_valid` before exporting. Every routing mode checks that the physical polygons fit within the board.
Check `is_valid` before placing a result. Every routing mode checks that the physical polygons fit within the board.
## Why a net stopped short
@ -35,9 +35,9 @@ Set `TopologyOptions(mode=...)` and pass it as `topology` in `RoutingOptions`.
### Mode requirements
- In guide and seed modes, nets without a corridor can use ordinary lattice search. A caller-supplied seed takes precedence over a generated one. These modes require Shapely 2.1 or later with GEOS 3.10 or later for [constrained triangulation](https://shapely.readthedocs.io/en/2.1.2/reference/shapely.constrained_delaunay_triangles.html).
- Guide and seed modes need Shapely 2.1 or later with GEOS 3.10 or later when planning corridors. Nets that receive no corridor can use ordinary lattice search. A caller-supplied seed takes precedence over a generated one. Set `node_limit=0` to verify supplied seeds without planning corridors. [Constrained triangulation requirements](https://shapely.readthedocs.io/en/2.1.2/reference/shapely.constrained_delaunay_triangles.html)
- Use `infer_terminal_headings` with automatic or bundle mode if your ports may change direction and the layout supports bundle planning. Compare fixed and flexible headings in [complex-routing example 1](../../examples/advanced.md#complex-routing-example-1).
- Automatic mode starts with smaller budgets and can retry with your configured ceiling if coverage remains below the bound. It runs lattice search directly for custom physical bends or polygonal search proxies, or when constrained triangulation is unavailable.
- Automatic mode starts with smaller budgets and can retry with your configured ceiling if coverage remains below the bound. It runs lattice search directly for custom physical bends or polygonal search proxies. With no triangulation available, it tries the constructive planners before falling back to lattice search. [Example with all five modes](../complex-routing-example-1.md#compare-all-routing-modes)
## Choose the next setting

View file

@ -1,4 +1,6 @@
from inire import NetSpec, ObjectiveWeights, Port, RoutingOptions, RoutingProblem, SearchOptions, TopologyOptions, route
from dataclasses import replace
from inire import FixedRoute, NetSpec, ObjectiveWeights, Port, RoutingOptions, RoutingProblem, SearchOptions, TopologyOptions, route
from inire.utils.visualization import plot_routing_results
@ -8,31 +10,28 @@ def main() -> None:
bounds = (0, -50, 100, 50)
options = RoutingOptions(
search=SearchOptions(bend_radii=(10.0,)),
# Isolate the lattice detour and use the fixed net only for clearance checks.
# Isolate the lattice detour.
objective=ObjectiveWeights(danger_weight=0.0),
topology=TopologyOptions(mode="off"),
)
print("Routing initial net...")
problem_a = RoutingProblem(
bounds=bounds,
nets=(NetSpec("netA", Port(10, 0, 0), Port(90, 0, 0)),),
)
results_a = route(problem_a, options=options).results_by_net
fixed = results_a["netA"]
fixed_net = NetSpec("netA", Port(10, 0, 0), Port(90, 0, 0))
detour_net = NetSpec("netB", Port(50, -20, 90), Port(50, 20, 90))
problem = RoutingProblem(bounds, (fixed_net, detour_net))
fixed = route(replace(problem, nets=(fixed_net,)), options=options).results_by_net["netA"]
assert fixed.is_valid
print("Routing detour net around locked path...")
problem_b = RoutingProblem(
bounds=bounds,
nets=(NetSpec("netB", Port(50, -20, 90), Port(50, 20, 90)),),
static_obstacles=fixed.locked_geometry,
)
results_b = route(problem_b, options=options).results_by_net
assert results_b["netB"].is_valid
remaining = replace(problem, nets=(detour_net,), fixed_routes=(FixedRoute.from_result(fixed),))
run = route(remaining, options=options)
detour = run.results_by_net[detour_net.net_id]
if not detour.is_valid:
raise ValueError(detour.report)
print("Detour net", detour.effective_net)
print("Placement recipe", detour.as_seed())
results = {**results_a, **results_b}
fig, _ax = plot_routing_results(results, [], bounds)
fig, _ax = plot_routing_results({fixed.net_id: fixed, **run.results_by_net}, [], bounds)
fig.savefig("examples/03_locked_paths.png")
print("Saved plot to examples/03_locked_paths.png")

View file

@ -3,10 +3,15 @@ import time
from shapely.geometry import box
from inire import (
CongestionOptions,
DiagnosticsOptions,
NetSpec,
ObjectiveWeights,
Port,
RoutingOptions,
RoutingProblem,
RoutingResult,
SearchOptions,
)
from inire.router._stack import build_routing_stack
from inire.utils.visualization import plot_expanded_nodes, plot_routing_results
@ -40,8 +45,6 @@ def main() -> None:
static_obstacles=tuple(obstacles),
clearance=6.0,
)
from inire import CongestionOptions, DiagnosticsOptions, ObjectiveWeights, RoutingOptions, SearchOptions
options = RoutingOptions(
search=SearchOptions(
node_limit=2_000_000,
@ -49,6 +52,7 @@ def main() -> None:
sbend_radii=(50.0,),
greedy_h_weight=1.5,
bend_clip_margin=10.0,
distance_heuristic_weight=10.0,
),
objective=ObjectiveWeights(
unit_length_cost=0.1,

View file

@ -20,7 +20,7 @@ After [installing Inire](../README.md#install), run the example scripts with Pyt
![A second waveguide makes a U-shaped detour around the left end of a fixed straight waveguide.](03_locked_paths.png)
The first call routes a straight waveguide. The second uses its polygons as keepouts, so the new connection passes to the left of the fixed route. Run [`03_locked_paths.py`](03_locked_paths.py) to reproduce the detour. To hold a route fixed in your own design, follow the [route reuse workflow](../docs/user/route-a-layout.md#reuse-an-existing-route).
The first call routes a straight waveguide. `FixedRoute.from_result()` reserves its exact polygons, so the new connection detours around one end of the fixed route. Run [`03_locked_paths.py`](03_locked_paths.py) to plot the detour and print its resolved net and placement recipe. To hold a route fixed in your own design, follow the [route reuse workflow](../docs/user/route-a-layout.md#reuse-an-existing-route).
<a id="fit-bends-to-available-room"></a>

View file

@ -2,16 +2,19 @@
inire Wave-router
"""
from collections.abc import Callable
from dataclasses import replace
from .geometry.primitives import Port as Port # noqa: PLC0414
from .model import (
CongestionOptions as CongestionOptions,
FixedRoute as FixedRoute,
DiagnosticsOptions as DiagnosticsOptions,
NetSpec as NetSpec,
ObjectiveWeights as ObjectiveWeights,
RefinementOptions as RefinementOptions,
RoutingOptions as RoutingOptions,
RoutingProblem as RoutingProblem,
SBendOutline as SBendOutline,
SearchOptions as SearchOptions,
TopologyOptions as TopologyOptions,
) # noqa: PLC0414
@ -46,20 +49,46 @@ def route(
iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None = None,
) -> RoutingRunResult:
resolved_options = RoutingOptions() if options is None else options
for net in problem.nets:
if net.start == net.target:
raise ValueError(f"Net {net.net_id!r} has coincident ports after grid snapping; connect the placed ports directly")
if problem.initial_paths:
net_ids = {net.net_id for net in problem.nets}
for net_id, seed in problem.initial_paths.items():
if net_id not in net_ids:
raise ValueError(f"Initial path provided for unknown net: {net_id}")
error = resolved_options.search.seed_geometry_error(seed)
if error is not None:
raise ValueError(f"Initial path for {net_id!r} {error}")
requested = {net.net_id: net for net in problem.nets}
def attach_requested(results: dict[str, RoutingResult]) -> dict[str, RoutingResult]:
return {
key: replace(result, requested_net=requested[key], effective_net=result.effective_net or requested[key])
for key, result in results.items()
}
def notify(iteration: int, results: dict[str, RoutingResult]) -> None:
assert iteration_callback is not None
iteration_callback(iteration, attach_requested(results))
callback = notify if iteration_callback is not None else None
if resolved_options.topology.mode == "automatic":
from .router._automatic import route_automatic # noqa: PLC0415
return route_automatic(problem, resolved_options, iteration_callback)
run = route_automatic(problem, resolved_options, callback)
else:
from .router._stack import route_explicit # noqa: PLC0415
from .router._stack import route_once # noqa: PLC0415
return route_once(problem, options=resolved_options, iteration_callback=iteration_callback)
run = route_explicit(problem, options=resolved_options, iteration_callback=callback)
return replace(run, results_by_net=attach_requested(run.results_by_net))
__all__ = [
"AutomaticRoutingReport",
"Bend90Seed",
"CapacityLimit",
"CongestionOptions",
"FixedRoute",
"ComponentConflictTrace",
"ConflictTraceEntry",
"DiagnosticsOptions",
@ -81,6 +110,7 @@ __all__ = [
"RoutingRunResult",
"RoutingStage",
"RoutingTiming",
"SBendOutline",
"SBendSeed",
"SearchOptions",
"StraightSeed",

38
inire/_snapshot.py Normal file
View file

@ -0,0 +1,38 @@
"""Read-only, insertion-ordered snapshots of public mappings."""
from __future__ import annotations
from typing import Never, Self, TYPE_CHECKING, TypeVar
if TYPE_CHECKING:
from collections.abc import Iterable, Mapping
_K = TypeVar("_K")
_V = TypeVar("_V")
class _Snapshot(dict[_K, _V]):
"""A read-only dict that dataclasses.asdict can traverse."""
__slots__ = ()
def __new__(cls, source: Mapping[_K, _V] | Iterable[tuple[_K, _V]]) -> Self:
result = super().__new__(cls)
dict.update(result, source)
return result
def __init__(self, _source: Mapping[_K, _V] | Iterable[tuple[_K, _V]]) -> None:
# Populate only at allocation so reinitialization cannot change a snapshot.
pass
def _read_only(self, *_args: object, **_kwargs: object) -> Never:
raise TypeError("Snapshot mappings are read-only")
__setitem__ = __delitem__ = __ior__ = clear = pop = popitem = setdefault = update = _read_only
def __reduce__(self) -> tuple[type[_Snapshot[_K, _V]], tuple[dict[_K, _V]]]:
return type(self), (dict(self),)
def snapshot(source: Mapping[_K, _V]) -> Mapping[_K, _V]:
return source if isinstance(source, _Snapshot) else _Snapshot(source)

View file

@ -1,6 +1,6 @@
from __future__ import annotations
from dataclasses import dataclass
from dataclasses import dataclass, replace
from typing import TYPE_CHECKING
import numpy
@ -10,7 +10,8 @@ from inire.constants import TOLERANCE_LINEAR
from inire.geometry.component_overlap import count_path_self_collisions
from inire.geometry.components import check_path_geometry, path_within_board
from inire.geometry.dynamic_path_index import DynamicPathIndex
from inire.geometry.index_helpers import grid_cell_span
from inire.geometry.index_helpers import floating_polygon, grid_cell_span
from inire.geometry.primitives import rotate_cardinal
from inire.results import RoutingReport
from inire.geometry.static_obstacle_index import StaticObstacleIndex
@ -23,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
@ -50,11 +52,18 @@ def _has_non_touching_overlap(left: BaseGeometry, right: BaseGeometry) -> bool:
return left.intersects(right) and not left.touches(right)
def _clearance_limit(clearance: float) -> float:
return clearance - TOLERANCE_LINEAR * min(1.0, clearance)
def _violates_clearance(left: BaseGeometry, right: BaseGeometry, clearance: float) -> bool:
if clearance <= 0:
return _has_non_touching_overlap(left, right)
tolerance = TOLERANCE_LINEAR * min(1.0, clearance)
return left.distance(right) < clearance - tolerance
return left.distance(right) < _clearance_limit(clearance)
def _violates_net_clearance(left: BaseGeometry, right: BaseGeometry, clearance: float) -> bool:
return _violates_clearance(left, right, clearance) if clearance else left.intersects(right)
def _span_to_bounds(
@ -92,6 +101,7 @@ class RoutingWorld:
__slots__ = (
"clearance",
"self_clearance",
"safety_zone_radius",
"board",
"grid_cell_size",
@ -106,16 +116,33 @@ class RoutingWorld:
safety_zone_radius: float = 0.0021,
*,
board: Polygon | None = None,
self_clearance: float = 0.0,
) -> None:
self.clearance = clearance
self.self_clearance = self_clearance
self.safety_zone_radius = safety_zone_radius
self.board = board
self.board = floating_polygon(board) if board is not None else None
self.grid_cell_size = 50.0
self.metrics = None
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,
)
for obstacle in problem.static_obstacles:
world.add_static_obstacle(obstacle)
for fixed in problem.fixed_routes:
for polygon in fixed.polygons:
world.add_static_obstacle(polygon, owner=fixed.net_id)
return world
def get_static_version(self) -> int:
return self._static_obstacles.version
@ -140,8 +167,12 @@ class RoutingWorld:
for obj_id in self._dynamic_paths.index.intersection(query_bounds):
yield self._dynamic_paths.geometries[obj_id][1].bounds
def add_static_obstacle(self, polygon: Polygon, dilated_geometry: Polygon | None = None) -> int:
return self._static_obstacles.add_obstacle(polygon, dilated_geometry=dilated_geometry)
def iter_static_entries(self) -> Iterable[tuple[Polygon, str | None]]:
index = self._static_obstacles
return ((polygon, index.owners.get(key)) for key, polygon in index.geometries.items())
def add_static_obstacle(self, polygon: Polygon, dilated_geometry: Polygon | None = None, *, owner: str | None = None) -> int:
return self._static_obstacles.add_obstacle(polygon, dilated_geometry, owner=owner)
def remove_static_obstacle(self, obj_id: int) -> None:
self._static_obstacles.remove_obstacle(obj_id)
@ -149,13 +180,43 @@ class RoutingWorld:
def _ensure_static_tree(self) -> None:
self._static_obstacles.ensure_tree()
def _ensure_net_static_tree(self, net_width: float) -> STRtree:
return self._static_obstacles.ensure_net_tree(net_width)
def corner_segment_visible(self, start: tuple[float, float], end: tuple[float, float]) -> bool:
"""Allow endpoint contact while testing the open segment against keepouts."""
self._ensure_static_tree()
tree = self._static_obstacles.tree
if tree is None:
return True
segment = LineString((start, end))
return all(segment.relate_pattern(tree.geometries[index], "FF*******") for index in tree.query(segment))
def _ensure_static_raw_tree(self) -> None:
self._static_obstacles.ensure_raw_tree()
def add_path(
def terminal_issue(self, port: Port, width: float) -> str | None:
dx, dy = rotate_cardinal(0, width / 2, int(port.r))
bounds = (port.x - abs(dx), port.y - abs(dy), port.x + abs(dx), port.y + abs(dy))
if self.board is not None:
x0, y0, x1, y1 = self.board.bounds
if bounds[0] < x0 or bounds[1] < y0 or bounds[2] > x1 or bounds[3] > y1:
return "face extends outside the routing board"
self._ensure_static_raw_tree()
tree = self._static_obstacles.raw_tree
if tree is None:
return None
clearance = self.clearance
candidates = tree.query(box(bounds[0] - clearance, bounds[1] - clearance, bounds[2] + clearance, bounds[3] + clearance))
if not len(candidates):
return None
face = LineString(((port.x - dx, port.y - dy), (port.x + dx, port.y + dy)))
for index in candidates:
keepout = tree.geometries[index]
if (clearance or self._static_obstacles.raw_owners[index] is not None) and _violates_net_clearance(face, keepout, clearance):
return "face violates keepout clearance"
if not clearance and not face.relate_pattern(keepout, "F**F*****"):
return "face enters a keepout"
return None
def add_path_geometry(
self,
net_id: str,
geometry: Sequence[Polygon],
@ -164,7 +225,8 @@ class RoutingWorld:
*,
physical_geometry: Sequence[tuple[int, Polygon]] | None = None,
) -> None:
self._dynamic_paths.add_path(
"""Add prepared path polygons and their component indexes."""
self._dynamic_paths.add_path_geometry(
net_id,
geometry,
dilated_geometry=dilated_geometry,
@ -172,7 +234,8 @@ class RoutingWorld:
physical_geometry=physical_geometry,
)
def install_path(self, net_id: str, path: Sequence[ComponentResult]) -> None:
def add_route(self, net_id: str, path: Sequence[ComponentResult]) -> None:
"""Validate and index the polygons of a route's components."""
if any(not component.physical_checks[0] for component in path):
return
proxies: list[Polygon] = []
@ -182,7 +245,7 @@ class RoutingWorld:
proxies.extend(component.collision_geometry)
dilated_proxies.extend(component.dilated_collision_geometry)
physical_geometry.extend((component_index, polygon) for polygon in component.physical_geometry)
self.add_path(net_id, proxies, dilated_proxies, physical_geometry=physical_geometry)
self.add_path_geometry(net_id, proxies, dilated_proxies, physical_geometry=physical_geometry)
def remove_path(self, net_id: str) -> None:
self._dynamic_paths.remove_path(net_id)
@ -190,42 +253,13 @@ class RoutingWorld:
def has_dynamic_paths(self) -> bool:
return bool(self._dynamic_paths.geometries)
def check_move_straight_static(self, start_port: Port, length: float, net_width: float) -> bool:
reach = self.ray_cast(
start_port,
start_port.r,
max_dist=length + 0.01,
net_width=net_width,
caller="straight_static",
)
return reach < length - 0.001
def _is_in_safety_zone_fast(self, idx: int, start_port: Port | None, end_port: Port | None) -> bool:
bounds_array = self._static_obstacles.bounds_array
if bounds_array is None:
return False
bounds = bounds_array[idx]
safety_zone = self.safety_zone_radius
if (
start_port
and bounds[0] - safety_zone <= start_port.x <= bounds[2] + safety_zone
and bounds[1] - safety_zone <= start_port.y <= bounds[3] + safety_zone
):
return True
return bool(
end_port
and bounds[0] - safety_zone <= end_port.x <= bounds[2] + safety_zone
and bounds[1] - safety_zone <= end_port.y <= bounds[3] + safety_zone
)
def _is_in_safety_zone(
self,
geometry: Polygon,
obj_id: int,
raw_obstacle: Polygon,
start_port: Port | None,
end_port: Port | None,
) -> bool:
raw_obstacle = self._static_obstacles.geometries[obj_id]
safety_zone = self.safety_zone_radius
obstacle_bounds = raw_obstacle.bounds
@ -272,53 +306,27 @@ class RoutingWorld:
start_port: Port | None = None,
end_port: Port | None = None,
) -> bool:
# TODO: If static buffering becomes net-width-specific, add dedicated
# width-aware geometry/index handling instead of reviving dead args here.
static_obstacles = self._static_obstacles
if not static_obstacles.dilated:
self._ensure_static_raw_tree()
tree = self._static_obstacles.raw_tree
if tree is None:
return False
self._ensure_static_tree()
tree = static_obstacles.tree
bounds_array = static_obstacles.bounds_array
if tree is None or bounds_array is None:
return False
hits = tree.query(box(*result.total_dilated_bounds))
if hits.size == 0:
return False
move_poly_bounds = result.dilated_bounds
clearance = self.clearance
left, bottom, right, top = result.total_bounds
if self._static_obstacles.owners:
x0, y0, x1, y1 = result.total_physical_bounds
left, bottom, right, top = min(left, x0), min(bottom, y0), max(right, x1), max(top, y1)
# The broad phase must include both the keepout proxy and the physical outline.
hits = tree.query(box(left - clearance, bottom - clearance, right + clearance, top + clearance))
obstacles = tree.geometries
for hit_idx in hits:
obstacle_bounds = bounds_array[hit_idx]
poly_hits_obstacle_aabb = False
for poly_bounds in move_poly_bounds:
if (
poly_bounds[0] < obstacle_bounds[2]
and poly_bounds[2] > obstacle_bounds[0]
and poly_bounds[1] < obstacle_bounds[3]
and poly_bounds[3] > obstacle_bounds[1]
):
poly_hits_obstacle_aabb = True
break
if not poly_hits_obstacle_aabb:
continue
obj_id = static_obstacles.obj_ids[hit_idx]
if self._is_in_safety_zone_fast(hit_idx, start_port, end_port):
collision_found = False
for polygon in result.collision_geometry:
if not self._is_in_safety_zone(polygon, obj_id, start_port, end_port):
collision_found = True
break
if collision_found:
obstacle = obstacles[hit_idx]
if self._static_obstacles.raw_owners[hit_idx] is not None:
if any(_violates_net_clearance(polygon, obstacle, clearance) for polygon in result.physical_geometry):
return True
continue
static_obstacle = static_obstacles.dilated[obj_id]
for polygon in result.dilated_collision_geometry:
if polygon.intersects(static_obstacle) and not polygon.touches(static_obstacle):
for polygon in result.collision_geometry:
if _violates_clearance(polygon, obstacle, clearance) and not self._is_in_safety_zone(polygon, obstacle, start_port, end_port):
return True
return False
@ -359,6 +367,41 @@ class RoutingWorld:
return DynamicCongestionDetail(soft_overlap_count=real_hits_count)
def check_physical_move_congestion(
self,
result: ComponentResult,
net_id: str,
*,
frozen_net_ids: frozenset[str] = frozenset(),
) -> DynamicCongestionDetail:
"""Use physical clearance when admitting a move with a hard obstacle."""
metrics = self.metrics
if metrics is not None:
metrics.total_congestion_check_calls += 1
hits = set()
for polygon in result.physical_geometry:
candidates = self._physical_candidates(net_id, polygon)
if metrics is not None and candidates:
metrics.total_congestion_candidate_nets += len({other_net_id for other_net_id, _, _ in candidates})
metrics.total_congestion_candidate_ids += len(candidates)
for other_net_id, _index, other in candidates:
if other_net_id in hits:
continue
if metrics is not None:
metrics.total_congestion_exact_pair_checks += 1
if not _violates_net_clearance(polygon, other, self.clearance):
continue
if other_net_id in frozen_net_ids:
return DynamicCongestionDetail(soft_overlap_count=len(hits), hits_frozen_net=True)
hits.add(other_net_id)
return DynamicCongestionDetail(soft_overlap_count=len(hits))
def _physical_candidates(self, net_id: str, polygon: Polygon) -> list[tuple[str, int, Polygon]]:
minx, miny, maxx, maxy = polygon.bounds
clearance = self.clearance
bounds = (minx - clearance, miny - clearance, maxx + clearance, maxy + clearance)
return self._dynamic_paths.physical_candidates(net_id, bounds)
def _collect_congestion_candidates(
self,
result: ComponentResult,
@ -424,8 +467,13 @@ class RoutingWorld:
bounds: tuple[float, float, float, float],
net_id: str,
) -> bool:
gx_min, gy_min, gx_max, gy_max = grid_cell_span(bounds, self.grid_cell_size)
cells = self._dynamic_paths.grid_net_obj_ids
span = grid_cell_span(bounds, self.grid_cell_size)
dynamic_paths = self._dynamic_paths
if dynamic_paths.uses_tree_for_span(span):
span_bounds = _span_to_bounds(*span, self.grid_cell_size)
return next(dynamic_paths.tree_candidates(net_id, span_bounds), None) is not None
gx_min, gy_min, gx_max, gy_max = span
cells = dynamic_paths.grid_net_obj_ids
if gx_min == gx_max and gy_min == gy_max:
members = cells.get((gx_min, gy_min))
@ -517,8 +565,8 @@ class RoutingWorld:
net_id: str,
broad_phase_cache: dict[tuple[str, int, int, int, int], dict[str, tuple[int, ...]]] | None,
) -> dict[str, tuple[int, ...]]:
gx_min, gy_min, gx_max, gy_max = grid_cell_span(bounds, self.grid_cell_size)
cache_key = (net_id, gx_min, gy_min, gx_max, gy_max)
span = grid_cell_span(bounds, self.grid_cell_size)
cache_key = (net_id, *span)
if broad_phase_cache is not None and cache_key in broad_phase_cache:
if self.metrics is not None:
self.metrics.total_congestion_grid_span_cache_hits += 1
@ -529,6 +577,12 @@ class RoutingWorld:
dynamic_paths = self._dynamic_paths
candidates_by_net: dict[str, set[int]] = {}
if dynamic_paths.uses_tree_for_span(span):
span_bounds = _span_to_bounds(*span, self.grid_cell_size)
for other_net_id, obj_id in dynamic_paths.tree_candidates(net_id, span_bounds):
candidates_by_net.setdefault(other_net_id, set()).add(obj_id)
else:
gx_min, gy_min, gx_max, gy_max = span
for gx in range(gx_min, gx_max + 1):
for gy in range(gy_min, gy_max + 1):
for other_net_id, obj_ids in dynamic_paths.grid_net_obj_ids.get((gx, gy), {}).items():
@ -550,8 +604,8 @@ class RoutingWorld:
net_id: str,
grid_net_cache: dict[tuple[str, int, int, int, int], tuple[str, ...]] | None,
) -> tuple[str, ...]:
gx_min, gy_min, gx_max, gy_max = grid_cell_span(bounds, self.grid_cell_size)
cache_key = (net_id, gx_min, gy_min, gx_max, gy_max)
span = grid_cell_span(bounds, self.grid_cell_size)
cache_key = (net_id, *span)
if grid_net_cache is not None and cache_key in grid_net_cache:
if self.metrics is not None:
self.metrics.total_congestion_grid_net_cache_hits += 1
@ -561,7 +615,12 @@ class RoutingWorld:
self.metrics.total_congestion_grid_net_cache_misses += 1
dynamic_paths = self._dynamic_paths
candidate_net_ids: set[str] = set()
if dynamic_paths.uses_tree_for_span(span):
span_bounds = _span_to_bounds(*span, self.grid_cell_size)
candidate_net_ids = {other_net_id for other_net_id, _ in dynamic_paths.tree_candidates(net_id, span_bounds)}
else:
gx_min, gy_min, gx_max, gy_max = span
candidate_net_ids = set()
for gx in range(gx_min, gx_max + 1):
for gy in range(gy_min, gy_max + 1):
for other_net_id in dynamic_paths.grid_net_obj_ids.get((gx, gy), {}):
@ -632,11 +691,10 @@ class RoutingWorld:
grid_net_cache: dict[tuple[str, int, int, int, int], tuple[str, ...]] | None = None,
broad_phase_cache: dict[tuple[str, int, int, int, int], dict[str, tuple[int, ...]]] | None = None,
) -> DynamicCongestionDetail:
if not self.clearance or frozen_net_ids:
return self.check_physical_move_congestion(result, net_id, frozen_net_ids=frozen_net_ids)
if self.metrics is not None:
self.metrics.total_congestion_check_calls += 1
dynamic_paths = self._dynamic_paths
if not dynamic_paths.geometries:
return DynamicCongestionDetail()
candidates_by_net = self._collect_congestion_candidates(
result,
@ -645,35 +703,21 @@ class RoutingWorld:
grid_net_cache,
broad_phase_cache,
)
if not candidates_by_net:
return DynamicCongestionDetail()
return self._check_real_congestion(
result,
candidates_by_net,
frozen_net_ids=frozen_net_ids,
)
def verify_path_details(
self,
net_id: str,
components: Sequence[ComponentResult],
*,
capture_component_conflicts: bool = False,
) -> PathVerificationDetail:
if self.metrics is not None:
self.metrics.total_verify_path_report_calls += 1
def verify_path_geometry(self, components: Sequence[ComponentResult]) -> RoutingReport:
"""Check continuity, self-spacing, the board, and static obstacles."""
static_collision_count = 0
dynamic_collision_count = 0
total_length = sum(component.length for component in components)
valid_geometry, continuous = check_path_geometry(components)
if not valid_geometry:
return PathVerificationDetail(RoutingReport(total_length=total_length, invalid_geometry=True))
conflicting_net_ids: set[str] = set()
component_conflicts: set[tuple[int, str, int]] = set()
return RoutingReport(total_length=total_length, invalid_geometry=True)
static_obstacles = self._static_obstacles
dynamic_paths = self._dynamic_paths
self._ensure_static_raw_tree()
if static_obstacles.raw_tree is not None:
raw_geometries = static_obstacles.raw_tree.geometries
@ -688,17 +732,44 @@ class RoutingWorld:
# A mitre may extend past the physical clearance
# radius at a component corner. Check the distance
# before counting an overlap with that broad phase.
if _violates_clearance(polygon, obstacle, self.clearance):
violates = _violates_net_clearance if static_obstacles.raw_owners[hit_idx] is not None else _violates_clearance
if violates(polygon, obstacle, self.clearance):
static_collision_count += 1
if dynamic_paths.has_physical_paths():
clearance = max(0.0, self.clearance)
return RoutingReport(
static_collision_count=static_collision_count,
self_collision_count=count_path_self_collisions(components, self.self_clearance),
total_length=total_length,
out_of_bounds=self.board is not None and not path_within_board(components, self.board),
discontinuous=not continuous,
)
def verify_path_details(
self,
net_id: str,
components: Sequence[ComponentResult],
*,
capture_component_conflicts: bool = False,
include_invalid_dynamic: bool = True,
geometry_report: RoutingReport | None = None,
) -> PathVerificationDetail:
"""Check the full path, optionally reusing its report against unchanged static geometry."""
if self.metrics is not None:
self.metrics.total_verify_path_report_calls += 1
report = self.verify_path_geometry(components) if geometry_report is None else geometry_report
dynamic_collision_count = 0
conflicting_net_ids: set[str] = set()
component_conflicts: set[tuple[int, str, int]] = set()
if (
not report.invalid_geometry
and (include_invalid_dynamic or not report.intrinsic_collision_count)
and self._dynamic_paths.has_physical_paths()
):
for component_index, component in enumerate(components):
component_hits: set[str] = set()
for polygon in component.physical_geometry:
minx, miny, maxx, maxy = polygon.bounds
bounds = (minx - clearance, miny - clearance, maxx + clearance, maxy + clearance)
candidates = dynamic_paths.physical_candidates(str(net_id), bounds)
candidates = self._physical_candidates(net_id, polygon)
if self.metrics is not None:
self.metrics.total_verify_dynamic_candidate_nets += len({candidate[0] for candidate in candidates})
polygon_hits: set[str] = set()
@ -707,7 +778,7 @@ class RoutingWorld:
continue
if self.metrics is not None:
self.metrics.total_verify_dynamic_exact_pair_checks += 1
if _violates_clearance(polygon, other, clearance):
if _violates_net_clearance(polygon, other, self.clearance):
polygon_hits.add(hit_net_id)
if capture_component_conflicts:
component_conflicts.add((component_index, hit_net_id, hit_component_index))
@ -715,15 +786,10 @@ class RoutingWorld:
dynamic_collision_count += len(component_hits)
conflicting_net_ids.update(component_hits)
if dynamic_collision_count != report.dynamic_collision_count:
report = replace(report, dynamic_collision_count=dynamic_collision_count)
return PathVerificationDetail(
report=RoutingReport(
static_collision_count=static_collision_count,
dynamic_collision_count=dynamic_collision_count,
self_collision_count=count_path_self_collisions(components),
total_length=total_length,
out_of_bounds=self.board is not None and not path_within_board(components, self.board),
discontinuous=not continuous,
),
report=report,
conflicting_net_ids=tuple(sorted(conflicting_net_ids)),
component_conflicts=tuple(sorted(component_conflicts)),
)
@ -747,10 +813,6 @@ class RoutingWorld:
self.metrics.total_ray_cast_calls_expand_snap += 1
elif caller == "expand_forward":
self.metrics.total_ray_cast_calls_expand_forward += 1
elif caller == "visibility_build":
self.metrics.total_ray_cast_calls_visibility_build += 1
elif caller == "visibility_query":
self.metrics.total_ray_cast_calls_visibility_query += 1
elif caller == "visibility_tangent":
self.metrics.total_ray_cast_calls_visibility_tangent += 1
else:
@ -773,6 +835,37 @@ class RoutingWorld:
cache[key] = reach
return reach
def straight_reach(self, origin: Port, max_dist: float, net_width: float) -> float:
"""Find where a fixed-width, flat-ended trace first enters a keepout."""
self._ensure_static_raw_tree()
tree = self._static_obstacles.raw_tree
if tree is None:
return max_dist
dx, dy = rotate_cardinal(max_dist, 0, int(origin.r))
half_x, half_y = (0.0, net_width / 2) if dx else (net_width / 2, 0.0)
left, right = sorted((origin.x, origin.x + dx))
bottom, top = sorted((origin.y, origin.y + dy))
left, bottom, right, top = left - half_x, bottom - half_y, right + half_x, top + half_y
strip = box(left, bottom, right, top)
clearance = self.clearance
padding = clearance - TOLERANCE_LINEAR * min(1.0, clearance)
candidates = tree.query(box(left - padding, bottom - padding, right + padding, top + padding))
axis = 0 if dx else 1
start = origin.x if dx else origin.y
direction = 1 if (dx or dy) > 0 else -1
face = axis if direction > 0 else axis + 2
reach = max_dist
obstacles = tree.geometries
for index in candidates:
obstacle = obstacles[index]
keepout = obstacle.buffer(padding) if padding > 0 else obstacle
overlap = keepout.intersection(strip)
if overlap.area:
reach = min(reach, direction * (overlap.bounds[face] - start))
return reach
def _cast_static_ray(
self,
origin: Port,
@ -792,10 +885,7 @@ class RoutingWorld:
min_y, max_y = sorted([origin.y, origin.y + dy])
if net_width is not None:
tree = self._ensure_net_static_tree(net_width)
key = (round(net_width, 4), round(self.clearance, 4))
is_rect_array = static_obstacles.net_specific_is_rect[key]
bounds_array = static_obstacles.net_specific_bounds[key]
tree, is_rect_array, bounds_array = static_obstacles.ensure_net_tree(net_width)
else:
self._ensure_static_tree()
tree = static_obstacles.tree

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