Separate user guides, benchmarks, and routing internals

This commit is contained in:
Jan Petykiewicz 2026-11-26 21:14:29 -08:00
commit e4d5952677
23 changed files with 846 additions and 270 deletions

1
.gitignore vendored
View file

@ -11,4 +11,5 @@ wheels/
.hypothesis .hypothesis
*.png *.png
!/docs/figures/*.png

164
DOCS.md
View file

@ -1,162 +1,36 @@
# Inire API and tuning guide <a id="inire-api-and-tuning-guide"></a>
Start with `route(problem)`. It uses automatic routing with the default options. Import public types from `inire`. The implementation modules under `inire.router` and `inire.geometry` can change between releases. [Quick start](README.md#route-a-net) # User guide
Get a [first route running](README.md#route-a-net), then use these guides for your own layout.
## Describe a layout ## Describe a layout
Use `RoutingProblem` to describe a single routing layer. Use the same unit for bounds, coordinates, widths, spacing, and radii. Choose the unit before converting device ports so integer snapping preserves narrow gaps. Headings are degrees counterclockwise from east and must be multiples of 90 after rounding. If your device library describes port headings pointing out of a device, reverse that heading for a target so it follows the waveguide into the device. - [Route a layout](docs/user/route-a-layout.md) covers units, port headings, widths, and keepouts.
- [Connect a preplaced crossing](docs/user/route-a-layout.md#connect-a-preplaced-crossing) shows where to place the ports and how to split the external nets.
| Input | Meaning | - [Reuse an existing route](docs/user/route-a-layout.md#reuse-an-existing-route) explains fixed routes and movable seeds.
| --- | --- |
| `bounds` | Board outline as `(xmin, ymin, xmax, ymax)`. |
| `nets` | `NetSpec(net_id, start, target, width=2.0)` objects with unique IDs and `Port(x, y, r)` terminals. Defaults to an empty tuple. |
| `static_obstacles` | Shapely polygons for keepouts. Defaults to an empty tuple. |
| `initial_paths` | Mapping from net IDs to `PathSeed` objects. Defaults to an empty mapping. |
| `clearance` | Required spacing between physical shapes. Defaults to `2.0`. |
| `safety_zone_radius` | Tolerance for very small obstacle intersections at ports during search. Defaults to `0.0021`. |
For a preplaced crossing, route the connections to and from its four ports. Keep the internal crossing geometry in the device and leave access openings in its keepout. This lets the router verify clearance around the placed cell while treating each external leg as a separate connection. [Crossing benchmark fixtures](docs/topological-routing.md#benchmark-corpus)
### Incremental routing with locked geometry
Reuse the physical polygons of valid routes as static obstacles in the next run. The next run applies its own clearance to those polygons.
```python
from dataclasses import replace
from inire import route
first = route(first_problem)
locked = tuple(
polygon
for result in first.results_by_net.values()
if result.is_valid
for polygon in result.locked_geometry
)
second = route(replace(next_problem, static_obstacles=next_problem.static_obstacles + locked))
```
### Initial paths with PathSeed
Use `result.as_seed()` when you want a subsequent run to start from an existing route and still be free to move it. You can also build a `PathSeed` from `StraightSeed`, `Bend90Seed`, and `SBendSeed` segments to suggest an approach. Seeds start at the net's current start port and use the current width and geometry settings. For a route that must remain fixed, use its physical polygons as obstacles. [Locked paths example](examples/03_locked_paths.py)
## Read the result ## Read the result
`route(problem, options=..., iteration_callback=...)` returns a `RoutingRunResult`. Check `results_by_net[net_id].is_valid` before exporting any path. With explicit `off`, `guide`, or `seed` mode, also check the physical polygons against the board if your export requires containment. Automatic mode includes that check in its candidate verification. - [Interpret the result](docs/user/tune-and-troubleshoot.md#read-the-result) before exporting physical paths.
- [Diagnose an unfinished net](docs/user/tune-and-troubleshoot.md#why-a-net-stopped-short) and decide whether to change the layout or try another search.
| Outcome | What to inspect |
| --- | --- |
| `completed` | Use `report.total_length` to compare physical length. Use `locked_geometry` for the physical polygons or `as_seed()` for the move sequence. |
| `colliding` | The path reached its target. Check `report` for static, dynamic, or self-collisions, or a failed automatic board containment check. |
| `partial` | Inspect where the returned path ends. An awkward launch or arrival can leave too little room to turn, even when the ports look close in plan view. |
| `unroutable` | There is no returned path. Check the start heading and access to the first straight or bend. The outcome alone does not establish that the net is impossible. |
A live callback receives `(iteration_index, results_by_net)` after each completed congestion iteration. In automatic mode, indices increase across attempts and each callback sees the nets in that attempt. Callback counts and net sets depend on which attempts run. Use the returned result for final verified routes. [Diagnostics and metrics](docs/routing-diagnostics.md)
## Topological routing ## Topological routing
Set `RoutingOptions(topology=TopologyOptions(mode=...))` when you need a particular mode. [Choose a routing mode](docs/user/tune-and-troubleshoot.md#choose-a-routing-mode) for automatic selection, lattice search, guide, seed, or ordered bundles.
| Mode | When to use it |
| --- | --- |
| `"automatic"` | Start here for general routing. Inire tries different strategies and keeps the best verified coverage it finds. |
| `"off"` | Isolate detailed lattice search when testing custom bend geometry or comparing the effect of corridor planning. |
| `"guide"` | Try this when obstacles suggest a useful detour and the search needs freedom to leave it to make a turn. |
| `"seed"` | Try this when finding a usable route around the obstacles is the main difficulty and a verified starting route could help. |
| `"bundle"` | Use for supported ordered rectangular bundles, such as the Terminal-Bench point-terminal example. Unsupported layouts and invalid schedules raise `ValueError`. |
`guide` and `seed` require constrained triangulation from Shapely 2.1 with GEOS 3.10 or newer. Caller-supplied seeds take precedence. Nets without corridors can still use lattice search. In bundle mode, use a circular bend radius enabled for both bends and S-bends. Enable heading inference only when the supplied terminals are points with flexible headings. [Topology algorithms and bundle example](docs/topological-routing.md)
### Automatic routing
The first search stages use smaller budgets. If they leave nets unresolved, a later lattice search can use your configured ceiling. Lowering that ceiling limits each search, and can prevent a difficult net from completing. Automatic uses lattice directly for custom bend geometry or when constrained triangulation is unavailable. [Automatic stage order and budgets](docs/architecture.md#automatic-routing)
Compare `len(run.automatic.verified_net_ids)` with `max_routed`. If the verified count already reaches a bound below the requested count, examine `capacity_limit` or `port_conflicts` to find the geometric constraint. More search cannot add a route past that bound. A verified count below the bound leaves room to investigate the search or geometry. [Read a routing report](docs/routing-diagnostics.md#automatic-reports)
## Tune a run ## Tune a run
Set the layout clearance and allowed radii from your process constraints first. Then change one setting at a time on the same layout and check the affected nets as well as the elapsed time. [Choose a setting to try](docs/user/tune-and-troubleshoot.md#choose-the-next-setting), or open the [API reference](docs/user/api-reference.md) for signatures and defaults.
| If you see | Try | ## Examples
| --- | --- |
| The router reaches a reported capacity bound | Move the conflicting ports or make more room in the bottleneck. For a mixed-width passage, check the room at the approach and through the turns. |
| A net remains partial below the bound despite plausible turn room | Try a larger `search.node_limit` and check whether that net completes. The limit applies per search. One run may search for the same net several times. |
| Several nets reach their targets and collide with one another | Compare a different `congestion.net_order` or raise `max_iterations` so the router can look for separate paths. Static obstacle collisions call for a geometry check first. |
| All nets route but refinement takes most of the time | Try `refinement.max_windows_per_net=1` and compare the resulting paths. |
| All nets route but carry too many small bends | Try a higher `objective.bend_penalty`. Compare bend counts and physical lengths to see whether straighter routes need longer detours. |
To try the shorter refinement pass, derive the new settings from the `options` you already use for the layout. [Browse the visual examples](examples/README.md) for locked paths, bend geometry, congestion, and partial results.
```python ## Moved reference sections
from dataclasses import replace
from inire import route
faster_refinement = replace(options, refinement=replace(options.refinement, max_windows_per_net=1)) - <a id="incremental-routing-with-locked-geometry"></a><a id="initial-paths-with-pathseed"></a>[Fixed routes and path seeds](docs/user/route-a-layout.md#reuse-an-existing-route)
run = route(problem, options=faster_refinement) - <a id="automatic-routing"></a>[Automatic routing and other modes](docs/user/tune-and-troubleshoot.md#choose-a-routing-mode)
``` - <a id="searchoptions"></a>[SearchOptions](docs/user/api-reference.md#searchoptions) and <a id="objectiveweights"></a>[ObjectiveWeights](docs/user/api-reference.md#objectiveweights)
- <a id="congestionoptions"></a>[CongestionOptions](docs/user/api-reference.md#congestionoptions) and <a id="refinementoptions"></a>[RefinementOptions](docs/user/api-reference.md#refinementoptions)
### SearchOptions - <a id="topologyoptions"></a>[TopologyOptions](docs/user/api-reference.md#topologyoptions) and <a id="diagnosticsoptions"></a>[DiagnosticsOptions](docs/user/api-reference.md#diagnosticsoptions)
| Field | Default | Effect |
| --- | --- | --- |
| `node_limit` | `1_000_000` | Per-search expansion ceiling. Automatic uses smaller budgets for its initial stages. |
| `min_straight_length` | `5.0` | Minimum single straight length. |
| `max_straight_length` | `2000.0` | Maximum single straight length. |
| `greedy_h_weight` | `1.5` | Weight for the A* heuristic. Lower values give the path cost more influence. |
| `bend_radii` | `(50.0, 100.0)` | Permitted radii for 90-degree bends. |
| `sbend_radii` | `(10.0,)` | Permitted S-bend radii. |
| `sbend_offsets` | `None` | Set permitted lateral offsets explicitly, or let search suggest offsets. A compact S-bend needs a nonzero offset with magnitude less than twice its radius. |
| `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"`. |
| `bend_clip_margin` | `None` | Optional legacy shrink margin for `"clipped_bbox"`. The default uses the eight-point proxy. |
| `visibility_guidance` | `"tangent_corner"` | Choose tangent candidates, exact corner visibility with `"exact_corner"`, or no visibility suggestions with `"off"`. |
### 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.
| Field | Default | Effect |
| --- | --- | --- |
| `unit_length_cost` | `1.0` | Cost per unit of path length. |
| `bend_penalty` | `250.0` | Additional cost of a 90-degree bend, scaled by radius. |
| `sbend_penalty` | `500.0` | Additional cost of an S-bend. |
| `danger_weight` | `1.0` | Weight of the obstacle proximity cost. |
### CongestionOptions
Increase the iteration limit when later reroutes might resolve conflicts. Adjust the initial penalty or multiplier when nets keep competing for the same space.
| Field | Default | Effect |
| --- | --- | --- |
| `max_iterations` | `10` | Maximum congestion iterations per attempt. Automatic's initial probe may use fewer. |
| `base_penalty` | `100.0` | Initial penalty for overlapping other routes. |
| `multiplier` | `1.5` | Scale the penalty between unresolved iterations. |
| `use_tiered_strategy` | `True` | Allow a cheaper bend proxy in the first iteration when applicable. |
| `net_order` | `"user"` | Route in input order or use `"shortest"` or `"longest"`. |
| `warm_start_enabled` | `True` | Build greedy seeds before congestion iterations. |
| `shuffle_nets` | `False` | Shuffle routing order between iterations. |
| `seed` | `None` | Random seed for shuffled ordering. |
### RefinementOptions
| Field | Default | Effect |
| --- | --- | --- |
| `enabled` | `True` | Try geometric improvements after routing. |
| `objective` | `None` | Use another `ObjectiveWeights` value for refinement, or reuse the search objective. |
| `max_windows_per_net` | `4` | Maximum candidate windows per net across improvement rounds. Use `1` for a shorter pass or `None` for unlimited windows. |
### TopologyOptions
| Field | Default | Effect |
| --- | --- | --- |
| `mode` | `"automatic"` | Select a [routing mode](#topological-routing). |
| `max_corridors` | `3` | Limit alternative corridors per net. |
| `guide_strength` | `0.75` | Maximum added guidance cost per unit length. Zero keeps the suggested moves without adding cost. |
| `seed_node_limit` | `600` | Total seed-search expansions per net, capped by the active search limit. |
| `infer_terminal_headings` | `False` | Allow heading inference for bundle-style point terminals. Automatic preserves caller headings when initial paths are supplied. |
| `automatic_cost` | `"selective"` | Re-score column layouts when they chain short S-bends. Use `"always"` for both passes or `"never"` for span scoring alone. |
| `automatic_length_weights` | `None` | Optional straight, 90-degree bend, and S-bend length multipliers for automatic candidate selection. The default uses the search objective. |
### DiagnosticsOptions
The flags default to `False`. Use `capture_expanded` to plot explored states or `capture_iteration_trace` to attribute search work per net and iteration. For clearance conflicts, `capture_conflict_trace` reports overlapping pairs, `capture_frontier_trace` examines prunes near final hotspots, and `capture_pre_pair_frontier_trace` examines the state before pair-local repair. [Trace fields and examples](docs/routing-diagnostics.md#traces)

View file

@ -2,6 +2,10 @@
Use Inire to connect fixed ports on a photonic or RF layout with straight segments, 90-degree bends, and S-bends. Supply the device placement, keepouts, and allowed bend radii. The router checks the finished geometry for clearance and returns partial paths to help you diagnose unfinished nets. Use Inire to connect fixed ports on a photonic or RF layout with straight segments, 90-degree bends, and S-bends. Supply the device placement, keepouts, and allowed bend radii. The router checks the finished geometry for clearance and returns partial paths to help you diagnose unfinished nets.
<a id="develop-inire"></a>
[User guide](DOCS.md) · [Developer guide](docs/development.md) · [Benchmarks](docs/benchmarks.md)
## Install ## Install
From a checkout with Python 3.11 or newer, run `pip install .`. For development, `uv sync` also installs the test and lint tools. From a checkout with Python 3.11 or newer, run `pip install .`. For development, `uv sync` also installs the test and lint tools.
@ -9,11 +13,17 @@ From a checkout with Python 3.11 or newer, run `pip install .`. For development,
## Route a net ## Route a net
```python ```python
from inire import NetSpec, Port, RoutingProblem, route from inire import (
NetSpec, Port, RoutingProblem,
route,
)
start = Port(50, 100, 0)
target = Port(250, 100, 0)
net = NetSpec("input", start, target)
problem = RoutingProblem( problem = RoutingProblem(
bounds=(0, 0, 1000, 1000), bounds=(0, 0, 1000, 1000),
nets=(NetSpec("input", Port(50, 100, 0), Port(250, 100, 0), width=2),), nets=(net,),
clearance=2, clearance=2,
) )
@ -25,17 +35,15 @@ else:
print(result.outcome) print(result.outcome)
``` ```
This example prints `200.0`, the length in the layout's coordinate unit. The branch that prints `outcome` is where you can report an unfinished or colliding net. [Interpret results and diagnose failures](DOCS.md#read-the-result) ![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)
Use a unit fine enough to preserve your port spacing on an integer grid. A heading of 0 points east. Both ports in the example have heading 0 because the waveguide travels east when it leaves the start and when it reaches the target. [Describe a layout](DOCS.md#describe-a-layout) The example prints `200.0` in the layout's coordinate unit. Both ports have heading 0 because the path travels east at departure and arrival. The plot shows the area around the first route. [Read the result](docs/user/tune-and-troubleshoot.md#read-the-result)
## Route your own layout ## Route your own layout
Place crossing devices before routing and describe their external legs as separate nets. Use the [examples](examples/README.md) to try multi-net routing, locked paths, or custom bends, and the [tuning guide](DOCS.md#tune-a-run) to decide which settings to change. - [Define your ports and keepouts](docs/user/route-a-layout.md), including access to preplaced crossing cells.
- [Choose what to try after a partial route](docs/user/tune-and-troubleshoot.md#why-a-net-stopped-short).
## Develop Inire - [Browse visual examples](examples/README.md) of multi-net routing, locked paths, and bend geometry.
Run `python -m pytest` for the correctness suite. Use `python -m pytest -m "not routing_corpus"` for a shorter local run. Start with the [architecture](docs/architecture.md) to find where a change belongs, then use the [benchmark guide](docs/topological-routing.md) and [diagnostics](docs/routing-diagnostics.md) to check its effect.
## License ## License

View file

@ -1,26 +1,32 @@
# Router architecture # Router architecture
Use this guide when changing how Inire chooses a route, spends search time, or accepts a path. The public `route()` entry point runs one worker for an explicit mode. Automatic mode can run several workers and choose among their results. Each worker has its own collision world and search state. That boundary matters when changing a retry because the new worker sees only the obstacles, locks, and seed hints that the caller passes to it. [Public API](../DOCS.md) · [Worker setup](../inire/router/_stack.py) Start with the stage that chooses the route, then inspect the worker that produced it. The public `route()` entry point runs one worker for an explicit mode. Automatic mode can run several. Each worker sees the obstacles, locks, and seed hints passed to it. [Public API](user/api-reference.md) · [Worker setup](../inire/router/_stack.py)
## Automatic routing ## Automatic routing
![Automatic routing sets a bound, then constructs, probes, widens, and recovers while below it. Verified candidates feed selection. The chosen layout can be refined before it is returned.](figures/automatic-stages.png)
The diagram shows the usual sequence for arc bends. A verified layout can reach the routing target early. When attempts run out, selection keeps the best verified coverage found. Custom physical bends, polygonal proxies, or missing constrained triangulation take a lattice-only path.
1. **Establish a stopping target.** Each disjoint pair of incompatible fixed ports rules out one route. For supported rectangular cuts, the capacity check uses the narrowest guide to bound how many paths fit through each opening. Reaching one of these bounds can justify stopping with partial coverage. Keep those bounds separate from estimates such as corridor occupancy or a failed attempt. [Capacity checks](../inire/router/_capacity.py) 1. **Establish a stopping target.** Each disjoint pair of incompatible fixed ports rules out one route. For supported rectangular cuts, the capacity check uses the narrowest guide to bound how many paths fit through each opening. Reaching one of these bounds can justify stopping with partial coverage. Keep those bounds separate from estimates such as corridor occupancy or a failed attempt. [Capacity checks](../inire/router/_capacity.py)
2. **Exploit layout structure before search.** Bundles place ordered tracks through barriers. Column schedules assign tracks to openings and stagger turns between them. Compact planners fit local connections between constrained ports. A schedule supplies seeds to the ordinary verifier. This lets the planner make cheap geometric proposals while the verifier checks the resulting physical paths. [Bundles](../inire/router/_bundle.py) · [Columns](../inire/router/_columns.py) · [Compact planners](../inire/router/_compact.py) 2. **Exploit layout structure before search.** Bundles place ordered tracks through barriers. Column schedules assign tracks to openings and stagger turns between them. Compact planners fit local connections between constrained ports. A schedule supplies seeds to the ordinary verifier. This lets the planner make cheap geometric proposals while the verifier checks the resulting physical paths. [Bundles](../inire/router/_bundle.py) · [Columns](../inire/router/_columns.py) · [Compact planners](../inire/router/_compact.py)
3. **Probe cheaply before spending the wider budget.** Direct trials can lock verified straight links and search for the remaining nets. A change in lock order or a small unlocked probe can free a nearby turn. The near-port stage uses up to 100 nodes per search and two congestion iterations for the arc proxy. Alternate proxies use the configured iteration limit because another shallow iteration can find a path the wider retry misses or finds at higher cost. The wider lookahead uses up to 500 nodes and the configured iteration limit. Both respect smaller caller limits. Guide and column attempts can precede the probe when the geometry makes them promising. [Stage order](../inire/router/_automatic.py) · [Direct trials](../inire/router/_routing_policy.py) 3. **Probe cheaply before spending the wider budget.** Direct trials can lock verified straight links and search for the remaining nets. A change in lock order or a small unlocked probe can free a nearby turn. The near-port stage uses up to 100 nodes per search and two congestion iterations for the arc proxy. Alternate proxies use the configured iteration limit because another shallow iteration can find a path the wider retry misses or finds at higher cost. The wider lookahead uses up to 500 nodes and the configured iteration limit. Both respect smaller caller limits. Guide and column attempts can precede the probe when the geometry makes them promising. [Stage order](../inire/router/_automatic.py) · [Direct trials](../inire/router/_routing_policy.py)
4. **Choose what to keep fixed.** If the remaining ports are still connected with verified paths locked, route the unresolved nets around those paths. If locks disconnect the residual, use movable seed hints so the next search can move an incumbent. A residual with several nets sharing a portal can benefit from a different lane assignment. When those attempts stall, seed and lattice workers can search the whole layout. A final lattice retry can use the caller's ceiling. [Residual routing](../inire/router/_automatic.py) · [Corridors and lanes](topological-routing.md#corridor-planning-and-realization) 4. **Choose what to keep fixed.** If the remaining ports are still connected with verified paths locked, route the unresolved nets around those paths. If locks disconnect the residual, use movable seed hints so the next search can move an incumbent. A residual with several nets sharing a portal can benefit from a different lane assignment. When those attempts stall, seed and lattice workers can search the whole layout. A final lattice retry can use the caller's ceiling. [Residual routing](../inire/router/_automatic.py) · [Corridors and lanes](topological-routing.md#corridor-planning-and-realization)
5. **Accept a checked layout.** Compare verified coverage first. Cost breaks ties between candidates with identical verified IDs. A complete locked layout or an improving joint retry must pass its required whole-layout check before selection. Refinement is also a candidate replacement and must preserve the verified ID set. [Trial selection](../inire/router/_routing_policy.py) 5. **Accept a checked layout.** Compare verified coverage first. Cost breaks ties between candidates with identical verified IDs. A complete locked layout or an improving joint retry must pass its required whole-layout check before selection. Refinement is also a candidate replacement and must preserve the verified ID set. [Trial selection](../inire/router/_routing_policy.py)
The `stress-retry-straight-decoy` fixture shows why a valid link can be a poor lock. A straight trunk divides the board and blocks perpendicular nets. The probe can keep the branches and lower rail. A four-turn dogleg then completes the trunk around them without a wider search. If you change lock ordering or acceptance, check that all four nets still verify together. [Fixture](../inire/tests/stress_routing_benchmarks.py) · [Regression test](../inire/tests/test_routing_benchmarks.py) ### Example of a poor lock
Automatic mode dispatches directly to lattice search for custom physical or polygonal proxy bends and when constrained triangulation is unavailable. Include those layouts when changing a fallback or geometry option. [Benchmark groups](topological-routing.md#benchmark-corpus) 1. A straight trunk in `stress-retry-straight-decoy` fits on its own. Once locked, it divides the board and blocks two perpendicular nets.
2. The probe can keep the branches and lower rail. A four-turn dogleg completes the trunk around them before wider search.
3. If you change lock ordering or acceptance, check that all four nets still verify together. [Fixture](../inire/tests/stress_routing_benchmarks.py) · [Choose a benchmark](benchmarks.md#choose-a-case)
## Detailed search and congestion ## Detailed search and congestion
A search state describes a snapped position and heading. Having the right coordinates alone leaves the terminal orientation unresolved. Straight, 90-degree bend, and S-bend moves compete in weighted A*. Ray casts, visible corners, and corridor waypoints suggest where a straight could end. This is why a move-generation change can fix a partial path even at the same node budget. Admission checks collision, cost, and state dominance before enqueuing candidates. [Move generation](../inire/router/_astar_moves.py) · [Admission](../inire/router/_astar_admission.py) · [Search](../inire/router/_search.py) - **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. A move-generation change can help a net reach its target at the same node budget. [Moves](../inire/router/_astar_moves.py) · [Admission](../inire/router/_astar_admission.py) · [Search](../inire/router/_search.py)
The congestion driver removes a net's old path, installs its replacement, and then routes other nets around or across it according to the active overlap penalty. Later iterations raise that penalty to encourage separation. A route that reached its target early in the iteration can collide with a net installed later. Verify the installed paths together before reviewing conflicts or reporting progress. The best iteration is ranked by completed nets, then conflict edges and dynamic collisions. Restore that snapshot before local repair. [Routing loop](../inire/router/_router.py) · [Congestion policy](../inire/router/_congestion_policy.py) - **Recheck the installed set.** The congestion driver replaces paths in routing order and raises the overlap penalty between unresolved iterations. A later route can collide with one completed earlier, so the driver verifies the installed set. It ranks snapshots by completed nets, then by conflicts and dynamic collisions. [Routing loop](../inire/router/_router.py) · [Congestion policy](../inire/router/_congestion_policy.py)
If the remaining conflicts involve a small set of nets, another global iteration can spend most of its budget revisiting the same geometry. Late iterations can reroute the conflicting subset and keep expensive incumbents. Pair-local repair can then try two orderings with the rest of the geometry held fixed. Verify a proposed pair again in the live world before accepting it. When comparing the iteration loop, include the final result and the handoff to local repair. [Pair-local search](../inire/router/_pair_local.py) · [Read an iteration trace](routing-diagnostics.md#traces) - **Repair a small conflict set.** Late iterations can focus on the conflicting nets. Pair-local repair restores the best snapshot, keeps the remaining geometry fixed, and tries two orderings for an eligible pair. It checks the proposed replacement in the live world. [Pair-local search](../inire/router/_pair_local.py) · [Read an iteration trace](routing-diagnostics.md#traces)
## Geometry and refinement ## Geometry and refinement
@ -39,4 +45,4 @@ Refinement looks for cheaper replacements in windows of a completed path. With a
| Congestion, seeds, or pair-local repair | Coverage and conflict evolution at iteration boundaries, plus the final installed geometry after repair. | | Congestion, seeds, or pair-local repair | Coverage and conflict evolution at iteration boundaries, plus the final installed geometry after repair. |
| Cost or refinement | Equal verified ID sets before comparing per-net lengths or costs. Check that the improvement survives whole-layout verification. | | Cost or refinement | Equal verified ID sets before comparing per-net lengths or costs. Check that the improvement survives whole-layout verification. |
Use [benchmark profiles](topological-routing.md#reproduce-a-comparison) for policy comparisons and [exact parity](routing-diagnostics.md#reproduce-and-compare) for behavior-preserving changes. Use [benchmark profiles](benchmarks.md#choose-a-profile) for policy comparisons and [exact parity](routing-diagnostics.md#reproduce-and-compare) for behavior-preserving changes.

View file

@ -0,0 +1,38 @@
# Benchmark fixtures
Use the checked-in inputs to repeat a routing comparison offline. The fixture catalogue gives the geometry, options, and expected bound for each case. [Choose a case and profile](benchmarks.md#choose-a-case) · [Fixture catalogue](../inire/tests/routing_corpus.py)
## Automatic nine-net Terminal-Bench routing
Use this as a check on ordered placement and heading inference. The upstream task supplies point terminals, so `bundle` mode can infer headings and reserve room for the outer return and bend tangencies. The export command starts from the unseeded input. Its nine routes passed the pinned checker below the upstream cost limit. Use the fixed-heading `terminal-bench` fixture to check automatic routing when the headings are part of the input. [Bundle planner](../inire/router/_bundle.py) · [Pinned upstream task](https://github.com/harbor-framework/terminal-bench/tree/249d125b59c0a5352d9e132195cfead6d81446be/tasks/photonic-waveguide-routing)
```sh
python -m scripts.route_terminal_bench --output /tmp/inire-terminal-bench.json
```
The export CLI's `--reference-lane-plan` and `--single-bottom-track` flags replay authored layouts for comparison. Use the unseeded export to measure the planner and the reference flags to check feasibility or compare lane assignments. [Reference plan](../inire/tests/terminal_bench_lane_plan.py)
## Preplaced crossings
- `crossing-single` isolates port access on one placed cell with four straight external legs.
- `crossing-obstructed-approaches` adds blocked approaches and a turning exit.
- `crossing-aligned-grid` and `crossing-staggered-grid` test multiple cells and short links between device banks.
Use unseeded runs to evaluate routing policy. The fixture witnesses are checked independently for geometry and clearance. [Crossing definitions](../inire/tests/routing_crossing_benchmarks.py) · [Illustrated user workflow](user/route-a-layout.md#connect-a-preplaced-crossing)
## Imported fixtures
The six fixed-placement cases run offline from [converted inputs](../inire/tests/data/external_routing_benchmarks.json). Optical ports snap to a 0.1 µm grid. Device outlines become keepouts with access cutouts. PIC Routing Benchmark contributes splitter-tree, ring-modulator, and MZM cases. LiDAR contributes a toy layout and subsets of the Clements and MRR weight-bank layouts. These fixtures exercise waveguide routing between fixed devices. [PIC data and CC BY 4.0 attribution](https://huggingface.co/datasets/FLYR/pic-benchmark/blob/0c1f445792926d97fae01893c89e96b8a9393800/pic-benchmark/README.md) · [LiDAR source](https://github.com/ScopeX-ASU/LiDAR/tree/4e7004d32b0b80d959553797fb30f0737513de0c/src/picroute/benchmarks) · [LiDAR license](../inire/tests/data/LiDAR-LICENSE.txt)
The importer checks both pinned archive hashes. It requires PyYAML when regenerating the fixtures.
```sh
mkdir -p /tmp/inire-external-routing
curl -fL 'https://huggingface.co/datasets/FLYR/pic-benchmark/resolve/0c1f445792926d97fae01893c89e96b8a9393800/pic-benchmark.zip' \
-o /tmp/inire-external-routing/pic-benchmark.zip
curl -fL 'https://codeload.github.com/ScopeX-ASU/LiDAR/tar.gz/4e7004d32b0b80d959553797fb30f0737513de0c' \
-o /tmp/inire-external-routing/lidar.tar.gz
uv run --with 'pyyaml==6.0.3' python -m scripts.import_external_routing_benchmarks \
--pic-archive /tmp/inire-external-routing/pic-benchmark.zip \
--lidar-archive /tmp/inire-external-routing/lidar.tar.gz
```

30
docs/benchmark-results.md Normal file
View file

@ -0,0 +1,30 @@
# Benchmark results
Use these measurements to understand the current probe policy and choose follow-up retry experiments. [Run a fresh benchmark](benchmarks.md)
## Near-port probe and retry experiments
Results recorded on November 26, 2026. The probe decision compared the two-iteration cap with the full configured probe budget. The retry experiments used the pre-cap policy.
The two-iteration probe cuts repeated shallow searches on layouts such as the splitter tree. It reduced public-default expansion counts by 23% on the regression corpus with identical paths there and on the holdouts. The mixed port-bank case did more work because the shorter probe passed the last net to the wider retry. Test both stages when changing the cap. A one-iteration cap increased the cost of a crossing approach, and the clipped-proxy regression required the original probe budget to keep its cheaper route. These are reasons to check path quality and proxy geometry as well as total expansions. [Probe budget in the policy](architecture.md#automatic-routing)
```sh
python -m scripts.benchmark_retry_order --case corpus --case retry-holdout \
--policy baseline --policy probe-full-budget --jobs 6 --json /tmp/inire-probe.json
```
### Early and late retries
Early retries can save time when they replace a more expensive stage. Their failures add work before the ordinary fallback. The holdout runs found both effects and a case where early incumbent recovery selected a higher-cost path at the same coverage. Review failed-retry time and common-net cost when deciding whether an early exit is worth using. The archived experiments include the trigger counts and the original commands. [Experiment archive](#experiment-archive)
The experimental `late-residual-3000` policy tests a different question. Can a wider search recover the last net while keeping the rest fixed? It requires room in the caller's budget and skips attempts whose locks disconnect the remaining ports. In the pre-cap holdout sweep it completed the last net on two crossing boards and a return shelf, with all previously verified paths intact. Use the experiment to measure the cost of completing one more net after the normal policy stalls.
```sh
python -m scripts.benchmark_retry_order --case retry-holdout --profile public-defaults \
--policy baseline --policy late-residual-3000 --repeat 3 --jobs 6 \
--json /tmp/inire-residual.json
```
## Experiment archive
Use `git show ea5cfe7:docs/topological-routing.md` for the original retry experiments, budget sweeps, and manual Terminal-Bench lane comparisons. Use `git show 2b02c6e:docs/topological-routing.md` for the measured probe and holdout tables. For retired policies, check out `ea5cfe7` in a separate worktree to run the matching driver. [Original goal](routing-policy-goal.md) · [Refactor plan](routing-refactor-plan.md)

87
docs/benchmarks.md Normal file
View file

@ -0,0 +1,87 @@
# Routing benchmarks
## Run a benchmark
From the repository root, run the overloaded-gate fixture with the regression profile.
```sh
python -m \
scripts.compare_topological_routing \
--case overloaded-gate \
--profile corpus-regression \
--mode automatic
```
- **Coverage.** Expect `3/4 valid`. The capacity report gives three tracks across the cut. This run reached the geometric bound.
- **Path quality.** Compare the verified net IDs before comparing weighted length or native objective cost.
- **Work.** Read A* expansions and median time together. The report can show work spent planning and verifying even when it reports zero expansions.
## Choose a case
| If you are changing | Use `--case` |
| --- | --- |
| Overall coverage | `corpus` runs the regression suite. |
| Ordered tracks, shared gates, and barrier layouts | `all` selects the original fixture group. |
| Seeds, custom bend geometry, and fallback behavior | `broad` includes caller seeds, custom bends, imported layouts, and the first holdout set. |
| Ports on placed devices | `crossings` exercises external legs to preplaced crossing cells. |
| Lock ordering, tight turns, and competing passages | `stress` runs known-feasible folded returns, competing locks, and shared passages. |
| A retry tuned on the regression corpus | `retry-holdout` tests related but separate return shelves, bypasses, and competing trunks. |
Run `python -m scripts.compare_topological_routing --list` to find individual case names. Select a fixture that exhibits the behavior under study, then use the corpus and relevant holdouts to check generalization. [Fixture sources and reproduction](benchmark-fixtures.md)
## Choose a profile
| Profile | Use it to |
| --- | --- |
| `public-defaults` | Measure the public policy and objective on the fixture geometry. |
| `corpus-regression` | Reproduce the test budget of 500 search nodes, 500 seed nodes, and three configured congestion iterations. |
| `matched-budget` | Compare modes with shared budgets. It defaults to 500 search nodes and two configured iterations. Use CLI overrides to test a smaller budget. |
The two budget profiles use benchmark weights for automatic candidate selection. Match the profile, options, and worker count when measuring a change.
### Run the full regression corpus
```sh
python -m \
scripts.compare_topological_routing \
--case corpus \
--profile corpus-regression \
--mode automatic --repeat 3 \
--json /tmp/inire-corpus.json
```
### Compare routing modes
```sh
python -m \
scripts.compare_topological_routing \
--case offset-gates \
--profile matched-budget \
--mode off --mode guide \
--mode seed --nodes 100 \
--repeat 3 \
--json /tmp/inire-modes.json
```
At this budget, guide mode completes the offset net with no corridor seed. Seed mode also completes it at the same cost. Use this comparison to check corridor hints before tuning seed allocation. [How corridors are built](topological-routing.md)
### Test a retry on holdouts
```sh
python -m \
scripts.benchmark_retry_order \
--case retry-holdout \
--profile public-defaults \
--policy baseline \
--policy late-residual-3000 \
--repeat 3 --jobs 6 \
--json /tmp/inire-residual.json
```
Inspect verified IDs, paths, and time spent inside failed attempts. [Prior retry decisions and measurements](benchmark-results.md)
## Compare the results
1. **Coverage and bounds.** Check verified IDs, requested nets, and any bound. The overloaded gate exercises passage capacity. The imported LiDAR Clements layout exercises fixed-port conflicts. Verify any feasibility witness separately from the timed run.
2. **Cost on matching net sets.** Benchmark-weighted length weights physical straights, 90-degree bends, and S-bends by 1, 4, and 13. Native objective cost uses the run's configured objective. Compare costs on identical verified IDs, and report coverage changes separately.
3. **Search and time.** Compare expansions and repeated wall times at the same settings. Inspect individual slow cases and unsuccessful attempts. Use the stage and trace information to explain where the work moved. [Diagnostics and exact parity](routing-diagnostics.md)

23
docs/development.md Normal file
View file

@ -0,0 +1,23 @@
# Developer guide
## Choose a task
- **[Benchmarks](benchmarks.md)** runs a single case, the regression corpus, or a mode comparison.
- **[Architecture](architecture.md)** explains planner selection, locks, search, and verification. Start here to find where a behavior change belongs.
- **[Diagnostics](routing-diagnostics.md)** connects symptoms to stage reports, counters, and traces.
- **[Public API reference](user/api-reference.md)** gives the caller contract for compatibility checks.
## Check a change
1. Run `uv sync` to install development dependencies. Activate `.venv` or prefix the commands with `uv run`.
2. Run `python -m pytest` for the correctness suite. Use `python -m pytest -m "not routing_corpus"` for a shorter local check.
3. For a routing change, use the [benchmark profiles](benchmarks.md#choose-a-profile) or [exact parity instructions](routing-diagnostics.md#reproduce-and-compare) to compare coverage, geometry, and work.
For documentation figures, run `python -m scripts.render_documentation_figures` from the repository root. It writes the route plots and planner diagram under `docs/figures`. Pass `--output-dir` to render a scratch copy for comparison.
## Design and experiment records
- **Design history.** [Original routing goal](routing-policy-goal.md) and [routing refactor plan](routing-refactor-plan.md).
- **Benchmark evidence.** [Probe and retry results](benchmark-results.md), [fixture sources](benchmark-fixtures.md), and [historical example performance snapshot](performance.md).
- **Generated diagnostic examples.** [Iteration trace](iteration_trace.md), [conflict trace](conflict_trace.md), [frontier trace](frontier_trace.md), and [pre-pair trace](pre_pair_frontier_trace.md).
- **Optimization history.** [Pair-local characterization](pair_local_characterization.md) and [optimization log](optimization_pass_01_log.md).

View file

@ -0,0 +1,60 @@
# Documentation improvement plan
Give readers a direct path to their task. A new user should be able to route a layout and diagnose a failure. A developer should be able to run a benchmark, explain a routing decision, or find the right diagnostic. Before the reorganization, the benchmark link opened on corridor algorithms and several pages buried steps and choices in long paragraphs. The original combined page is available with `git show 24559bb:docs/topological-routing.md`.
## Proposed navigation
- **`README.md`** gives the project purpose, installation, and one runnable route with an inline result plot. Link directly to **User guide**, **Developer guide**, and **Benchmarks**.
- **`DOCS.md`** is the user landing page.
- **Route a layout** in `docs/user/route-a-layout.md`. Define ports, headings, widths, and keepouts. Show preplaced crossings, movable seeds, and fixed routes where each matters in the workflow.
- **Tune and troubleshoot** in `docs/user/tune-and-troubleshoot.md`. Read a result, distinguish a geometric bound from an unfinished search or a collision, and choose the next setting to test.
- **API reference** in `docs/user/api-reference.md`. Look up public signatures, fields, units, and defaults. Link back to a worked example when an option's effect needs explanation.
- **Examples** in `examples/README.md`. Show a small visual gallery grouped by task, with links to runnable scripts and advanced examples.
- **`docs/development.md`** is the developer landing page.
- **Benchmarks** in `docs/benchmarks.md`. Choose a case and profile, run a command, and compare the results.
- **Architecture** in `docs/architecture.md`. Explain the automatic stage sequence, what gets locked or retried, and what must be verified before selection. Link to `docs/topological-routing.md` for corridor and lane algorithms.
- **Diagnostics** in `docs/routing-diagnostics.md`. Start from a symptom and select a report, counter, or trace. Use a worked trace to show what the evidence can establish.
- **Design and experiment records** link to prior goals, refactor plans, measured results, and generated traces with their original context.
## Split benchmarks from topological routing
1. Make the README's **Benchmarks** link lead directly to `docs/benchmarks.md`. Open with `overloaded-gate` under `corpus-regression`, where three of four nets route at the three-track bound. Use the output to explain how to judge coverage. Follow with choices for the full regression corpus, mode comparisons, and holdout validation.
2. Move case groups, profile definitions, coverage and cost interpretation, and comparison commands to the benchmark guide. Put fixture provenance, import commands, and Terminal-Bench reproduction in `docs/benchmark-fixtures.md`. Put probe and retry findings in `docs/benchmark-results.md`, with the decision, the conditions, and the evidence needed to reproduce it.
3. Keep `docs/topological-routing.md` focused on free-space triangulation, portals, lane assignment, and how guide and seed modes use them. Use a contextual link to the benchmark guide when a reader wants to measure the algorithms.
4. Update inbound links as part of the move. Map old section links to their new destinations and keep brief forwarding links for useful bookmarks. Preserve the source pins, licenses, and historical commands with the fixture and experiment records.
## Write for scanning and use
- Open each page with the task it supports and put the first action or decision near the top. Name headings after what readers are looking for, such as **Run a benchmark** or **Why a net stopped short**.
- Use numbered lists for procedures, bullets for independent checks and options, and tables for lookup or comparison. Use short paragraphs to explain why a decision follows from the evidence.
- Keep the public workflows and option reference separate. Explain an option at the point where a user needs to choose it, then link to its canonical default or field definition.
- Pair an example with its expected result and the next action it demonstrates. Put implementation names and detailed counters beside the developer decisions that use them.
- Lead benchmark findings with their implication. Include the profile, comparison baseline, and relevant metric. Link to the full measurements when readers need the raw evidence.
## Illustrations to add
| Place | Show | Reader takeaway |
| --- | --- | --- |
| README quick start | A compact plot generated from the exact quick-start snippet, with start and target arrows | See what a finished path looks like and how to read arrival direction. |
| Route a layout | A preplaced crossing with the keepout, port access, and the external nets labeled | See which geometry belongs to the placed device and which connections to give Inire. |
| Troubleshooting | Two panels of the same best-effort layout showing a partial path and a completed path after increasing the budget | See why a partial path can indicate unfinished search. |
| Examples gallery | Inline previews of selected existing plots, including locked paths and S-bends | Pick the example that resembles the layout at hand. |
| Architecture | A small flow diagram of construct, probe, widen, recover, verify, and refine | See where the router stops, retries, or rejects a candidate. |
| Topological routing | A single fixture shown as free space and portals, a chosen lane, and the verified physical route | See where the corridor ends and the detailed router's work begins. |
Use the existing plots where they read clearly at page width. Regenerate focused figures from the documented inputs with the existing plotting tools. Give each figure a caption that explains what to notice and alt text that conveys the takeaway. Distinguish states with labels or line styles as well as color. Use a checked-in image for diagrams when the repository renderer needs one. [Example plots](../examples/README.md) · [Plotting helpers](../inire/utils/visualization.py)
## Order of work
1. **Fix navigation.** Split the benchmark and topology pages, add the developer landing page, and update links. This is the first reviewable change.
2. **Rebuild the user path.** Turn `DOCS.md` into a guide index, move the field tables into the reference, and write the layout and troubleshooting pages as steps and decisions. Add the quick-start, crossing, and partial-route figures.
3. **Finish the developer path.** Rework the architecture and diagnostics headings, add the flow and corridor figures, and connect the benchmark guide to fixtures and dated results. Embed the selected existing plots in the examples gallery.
4. **Check the paths as a reader.** Preview the rendered docs at normal and narrow widths. Check links, old anchors, image paths, and command output. Run the quick start, a benchmark smoke case, and a diagnostic capture from the published instructions.
## Acceptance checks
- From the README, a new user can install, run the first route, see the expected result inline, and find what to check if a real layout returns a partial path.
- From the README, a developer can click **Benchmarks** and immediately find how to run a case. The landing page gives enough context to compare verified IDs, path cost, and work under a chosen profile.
- A developer looking for corridor internals reaches the topology page through **Architecture** and can follow the stages in an annotated figure.
- Each main page has one clear job. The headings alone make the path through it apparent, and procedural sections can be followed from their lists.
- Figures match the current snippets or fixtures, remain legible at ordinary page width, and have descriptive captions. Historical measurements and fixture attributions remain findable from the relevant guide.

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

View file

@ -1,14 +1,14 @@
# Routing diagnostics and metrics # Routing diagnostics and metrics
Start with the symptom. A missing net, a worse path, and a slower run call for different evidence. For layout or option changes, first use the [user tuning guide](../DOCS.md#tune-a-run). Start with the symptom. For layout or option changes, use the [user troubleshooting guide](user/tune-and-troubleshoot.md).
## Automatic reports ## Automatic reports
**Was the run limited by the layout or by a search attempt?** Compare the number of `verified_net_ids` with `max_routed`. A reached bound with a missing net calls for a geometry change. For example, `overloaded-gate` requests four routes through a three-track cut. `capacity_limit.cut_x` locates that cut, so an extra iteration cannot recover the fourth net at the same geometry. If coverage is below the bound, use `stages` to find which nets were skipped, locked, or recovered and where coverage stopped increasing. [Bounds and fixtures](topological-routing.md#benchmark-corpus) - **A net is missing.** Compare the verified count with `max_routed`. In `overloaded-gate`, `capacity_limit.cut_x` locates the cut that fits three of four requested routes. Below the bound, read `stages` for skipped or locked nets and for the attempt where coverage stopped increasing. [Run the overloaded-gate fixture](benchmarks.md#run-a-benchmark)
**Why did the chosen route change?** Start at `stages[selected_stage]`, then work back to the search or planner that produced its paths. The `planner` identifies the source of a proposal. The `mode` identifies the worker that ran it. For example, an `off` worker can verify a bundle seed. Use `planner_rejections` when a constructive layout never reaches selection. Compare per-net paths and costs on the same verified IDs before drawing a quality conclusion. [Report definitions](../inire/results.py) - **The chosen route changed.** Start at `stages[selected_stage]`. The `planner` identifies the source of the proposal and `mode` identifies the worker, so a bundle seed can be checked by an `off` worker. Use `planner_rejections` for constructive candidates that never reached selection. [Report definitions](../inire/results.py)
**Where did the time go?** Group exclusive `timings` by policy and operation, including failed attempts. Compare with the run's `duration_s`, which also includes orchestration. A short selected search can follow a long unsuccessful one. Detailed traces, corridor reports, and plotted expanded states describe the selected attempt when present. Use `run.metrics` and stage data for work across attempts. [Benchmark profiles](topological-routing.md#reproduce-a-comparison) - **The run slowed down.** Group exclusive `timings` by policy and operation, including failed attempts. `duration_s` also includes orchestration. Detailed traces, corridor reports, and expanded states describe the selected attempt when present. Check `run.metrics` and stage data for work across attempts. [Benchmark profiles](benchmarks.md#choose-a-profile)
## Route metrics ## Route metrics
@ -36,9 +36,20 @@ Enable the `DiagnosticsOptions` flag for the question you want to answer.
| What did the last unresolved iteration hand to pair-local repair? | `capture_pre_pair_frontier_trace` records `pre_pair_frontier_trace`. Check reroute order, conflict edges, and per-net attempt work immediately before repair. | | What did the last unresolved iteration hand to pair-local repair? | `capture_pre_pair_frontier_trace` records `pre_pair_frontier_trace`. Check reroute order, conflict edges, and per-net attempt work immediately before repair. |
| Where did the router explore? | `capture_expanded` records `expanded_nodes` for plotting. See the [fan-out example](../examples/07_large_scale_routing.py). | | Where did the router explore? | `capture_expanded` records `expanded_nodes` for plotting. See the [fan-out example](../examples/07_large_scale_routing.py). |
The historical no-warm-start fan-out trace shows why both the final result and the iteration trace matter. The last iteration in the first scenario leaves two conflict edges and six completed nets. The run finishes with all ten valid after pair-local repair. When an iteration change alters that handoff, compare the restored snapshot, pair-local acceptance, and the final conflict trace. [Iteration trace](iteration_trace.md#example_07_large_scale_routing_no_warm_start) · [Conflict trace](conflict_trace.md) · [Pre-pair trace](pre_pair_frontier_trace.md) ### Follow a late conflict into pair-local repair
For live progress across attempts, use an `iteration_callback`. Use the final result to establish coverage. Callback indices increase across automatic attempts, and the number of callbacks follows the actual search schedule. [Callback API](../DOCS.md#read-the-result) Capture the no-warm-start fan-out scenario from the repository root.
```sh
python -m scripts.record_iteration_trace --scenario example_07_large_scale_routing_no_warm_start \
--include-performance-only --output-dir /tmp/inire-trace
```
1. Open the generated `iteration_trace.md`. Compare the last iteration's completed count and conflict edges with the final result summary. In the recorded example, the last iteration had six completed nets and two conflict edges.
2. Inspect the final result and pair-local counters in `iteration_trace.json`. All ten nets verified after repair in the recorded run. The last congestion iteration alone misses this improvement.
3. To see which paths overlapped, capture the same scenario with `scripts.record_conflict_trace`. Compare `restored_best` with `final`. Use the pre-pair trace to investigate reroute order and per-net work before repair. [Recorded iteration trace](iteration_trace.md#example_07_large_scale_routing_no_warm_start) · [Conflict trace](conflict_trace.md) · [Pre-pair trace](pre_pair_frontier_trace.md)
Use an `iteration_callback` for live progress across automatic attempts and the final result for coverage. [Callback API](user/api-reference.md#route-a-problem)
## Reproduce and compare ## Reproduce and compare

View file

@ -1,6 +1,6 @@
# Automatic routing policy and route cost goals # Automatic routing policy and route cost goals
Use this historical milestone to understand why automatic routing combines constructive planners with search and why the project checks coverage before cost. Use the [current benchmark guide](topological-routing.md) to evaluate a new change. Use this historical milestone to understand why automatic routing combines constructive planners with search and why the project checks coverage before cost. Use the [current benchmark guide](benchmarks.md) to evaluate a new change.
Run one inire policy across the full benchmark corpus from empty initial paths. The first milestone is to verify **242 of 243 nets and fully route 36 of 37 boards** in one run. The overloaded gate should reach its three-track capacity. Once the policy reproduces that baseline, reduce weighted route cost while preserving coverage. Run one inire policy across the full benchmark corpus from empty initial paths. The first milestone is to verify **242 of 243 nets and fully route 36 of 37 boards** in one run. The overloaded gate should reach its three-track capacity. Once the policy reproduces that baseline, reduce weighted route cost while preserving coverage.
@ -12,7 +12,7 @@ Run one inire policy across the full benchmark corpus from empty initial paths.
| Best existing policy per board after targeted retries | 190/243 | 20/37 | | Best existing policy per board after targeted retries | 190/243 | 20/37 |
| Best result per board including standalone experiments | 242/243 | 36/37 | | Best result per board including standalone experiments | 242/243 | 36/37 |
The clearance-checked column planner completed all 15 serial, split, and bidirectional bypass layouts with zero A* expansions. An experimental bundle turnaround routed all nine nets with the fixed Terminal-Bench headings. An automatic perimeter detour completed the two-net subset. The integrated policy should generate these routes from the input geometry and settings. Keep feasibility witnesses in the test harness for independent coverage and cost checks. [Benchmark corpus and methods](topological-routing.md#benchmark-corpus) The clearance-checked column planner completed all 15 serial, split, and bidirectional bypass layouts with zero A* expansions. An experimental bundle turnaround routed all nine nets with the fixed Terminal-Bench headings. An automatic perimeter detour completed the two-net subset. The integrated policy should generate these routes from the input geometry and settings. Keep feasibility witnesses in the test harness for independent coverage and cost checks. [Benchmark corpus and methods](benchmarks.md#choose-a-case)
## Planner selection and verification ## Planner selection and verification
@ -30,4 +30,4 @@ At this milestone, the column planner ranked lateral movement and forward span.
2. Set aside validation layouts with staggered terminal columns, uneven widths, and different obstacle arrangements before tuning. Keep closely related variants together so the validation set tests unfamiliar geometry. 2. Set aside validation layouts with staggered terminal columns, uneven widths, and different obstacle arrangements before tuning. Keep closely related variants together so the validation set tests unfamiliar geometry.
3. Compare weighted transition scoring against the integrated baseline, starting with `bypass-interleaved-directions`, `split-moving-divider`, and `serial-terminal-jogs`. Report complete boards, weighted cost on identical net sets, A* expansions, and median and tail runtime. Use the full corpus and the held-out layouts to evaluate a default-policy change. 3. Compare weighted transition scoring against the integrated baseline, starting with `bypass-interleaved-directions`, `split-moving-divider`, and `serial-terminal-jogs`. Report complete boards, weighted cost on identical net sets, A* expansions, and median and tail runtime. Use the full corpus and the held-out layouts to evaluate a default-policy change.
The archived automatic policy validation records the completed corpus and holdout runs and the scoring comparison. [Experiment archive](topological-routing.md#experiment-archive) The archived automatic policy validation records the completed corpus and holdout runs and the scoring comparison. [Experiment archive](benchmark-results.md#experiment-archive)

View file

@ -42,7 +42,7 @@ Use this record to recover the original refactor scope and the reason for each p
## Verification ## Verification
Use the current 67-board corpus as the regression baseline for routing changes. The `corpus-regression` and `public-defaults` profiles reach every board's routing bound and verify 433 of 437 nets each. For behavior-preserving changes, compare exact paths, per-net costs, bounds, planner stage order and metadata, and relevant callback and trace payloads. For changes that intentionally eliminate work, such as item 13, record the expected counter differences while checking route and trace parity. [Corpus results and reproduction](topological-routing.md) Use the current 67-board corpus as the regression baseline for routing changes. The `corpus-regression` and `public-defaults` profiles reach every board's routing bound and verify 433 of 437 nets each. For behavior-preserving changes, compare exact paths, per-net costs, bounds, planner stage order and metadata, and relevant callback and trace payloads. For changes that intentionally eliminate work, such as item 13, record the expected counter differences while checking route and trace parity. [Corpus reproduction](benchmarks.md#run-the-full-regression-corpus)
Capture the same cases and options at both revisions. The parity command defaults to the `corpus-regression` and `public-defaults` profiles. [Parity commands](routing-diagnostics.md#reproduce-and-compare) Capture the same cases and options at both revisions. The parity command defaults to the `corpus-regression` and `public-defaults` profiles. [Parity commands](routing-diagnostics.md#reproduce-and-compare)

View file

@ -1,95 +1,33 @@
# Topological routing and benchmarks <a id="topological-routing-and-benchmarks"></a>
Use this guide to decide whether a routing problem needs better corridors, better detailed moves, or a different retry order. If you are choosing an option for your own layout, start with the [routing modes](../DOCS.md#topological-routing). # Topological routing
Guide mode suggests routes through connected free space. Seed mode also tries to realize those suggestions as physical paths. [Run corridor benchmarks](benchmarks.md#compare-routing-modes)
## Corridor planning and realization ## Corridor planning and realization
![Three views of the offset-gates fixture. The first highlights crossed triangle edges. The second links sampled lanes. The third shows the solid physical route deviating from the dashed lane sketch.](figures/corridor-realization.png)
The offset-gates fixture has two openings at different heights. The mesh highlights the portals used by the chosen corridor. The dashed lane remains angular, while detailed guide-mode search fits an S-bend between the openings. [Reproduce the mode comparison](benchmarks.md#compare-routing-modes)
1. **Find connected space for centerlines.** Inset the board by half the widest net's width and expand obstacles by that half-width plus clearance. Shared edges of a constrained Delaunay triangulation act as portals. A short lead tries to attach each terminal to the mesh along its heading. Using the widest net gives the planner a common representation. Narrower nets may still find a path in lattice search through a passage this mesh excludes. 1. **Find connected space for centerlines.** Inset the board by half the widest net's width and expand obstacles by that half-width plus clearance. Shared edges of a constrained Delaunay triangulation act as portals. A short lead tries to attach each terminal to the mesh along its heading. Using the widest net gives the planner a common representation. Narrower nets may still find a path in lattice search through a passage this mesh excludes.
2. **Choose a passage and a lane.** Rank portal sequences by distance, occupancy, and estimated overflow. Use lane samples and estimated turn room to select where to cross each portal without crowding another net's access. A different lane through the same portal can make space for a turn. Joint retries use that distinction to revise a shared passage assignment. 2. **Choose a passage and a lane.** Rank portal sequences by distance, occupancy, and estimated overflow. Use lane samples and estimated turn room to select where to cross each portal without crowding another net's access. A different lane through the same portal can make space for a turn. Joint retries use that distinction to revise a shared passage assignment.
3. **Turn the sketch into a path.** Guide mode adds soft costs and move suggestions, so detailed search can leave an awkward corridor. Seed mode first tries to find a physical path inside a corridor and verifies it against obstacles and earlier seeds. It gives the first corridor at least half the per-net budget when there are alternatives. Later detailed iterations can move an incumbent or try another guide. Final verification checks the actual routed geometry. 3. **Turn the sketch into a path.** Guide mode adds soft costs and move suggestions, so detailed search can leave an awkward corridor. Seed mode first tries to find a physical path inside a corridor and verifies it against obstacles and earlier seeds. It gives the first corridor at least half the per-net budget when there are alternatives. Later detailed iterations can move an incumbent or try another guide. Final verification checks the actual routed geometry.
When debugging `guide` or `seed`, use the explicit mode so you can inspect that worker's `run.topology`. If a net has no corridor, check port access, mesh padding, and which passages remain connected. If it has a corridor and seed realization uses the budget without finishing, check the port headings and the space to turn at each portal. When seeds reach their targets and the final paths still overlap, inspect lane order and congestion before adding seed nodes. [Mesh and lane allocation](../inire/router/_topology.py) · [Trace guide](routing-diagnostics.md#traces) ## When a corridor does not lead to a route
- **No corridor reported.** Inspect `run.topology` from an explicit guide or seed run. Check snapped port access, mesh padding, and which passages remain connected.
- **A corridor exists but seed search stalls.** Check terminal headings and the turn room around each chosen portal.
- **Seeds reach their targets and the final routes overlap.** Inspect lane order and congestion before adding seed nodes. [Mesh and lane allocation](../inire/router/_topology.py) · [Trace guide](routing-diagnostics.md#traces)
For the design background on routing through shared triangle edges and on constraints specific to photonic waveguides, see the earlier detailed-routing work. [Curvilinear detailed routing](https://websrv.cecs.uci.edu/~papers/compendium94-03/papers/1998/aspdac98/pdffiles/06c_3.pdf) · [LiDAR 2.0](https://scopex-asu.github.io/files/publications/PD_TCAD2025_LiDARv2.pdf) For the design background on routing through shared triangle edges and on constraints specific to photonic waveguides, see the earlier detailed-routing work. [Curvilinear detailed routing](https://websrv.cecs.uci.edu/~papers/compendium94-03/papers/1998/aspdac98/pdffiles/06c_3.pdf) · [LiDAR 2.0](https://scopex-asu.github.io/files/publications/PD_TCAD2025_LiDARv2.pdf)
## Benchmark corpus ## Moved benchmark sections
| What you are changing | Select with `--case` | - <a id="benchmark-corpus"></a>[Choose a benchmark case](benchmarks.md#choose-a-case)
| --- | --- | - <a id="reproduce-a-comparison"></a>[Compare routing modes](benchmarks.md#compare-routing-modes)
| Placement and ordered-track planners | `all` covers the original layouts, including shared gates, detours, and Terminal-Bench variants. | - <a id="probe-budget-and-coverage"></a>[Probe and retry measurements](benchmark-results.md#near-port-probe-and-retry-experiments)
| Fallbacks, seed handling, or bend geometry | `broad` includes caller seeds, custom bends, imported layouts, and the first holdout set. | - <a id="retry-experiments"></a>[Early and late retries](benchmark-results.md#early-and-late-retries)
| Device access and short links | `crossings` routes external legs to preplaced crossing cells. Check that changes keep the ports accessible. | - <a id="automatic-nine-net-terminal-bench-routing"></a>[Reproduce Terminal-Bench routing](benchmark-fixtures.md#automatic-nine-net-terminal-bench-routing)
| Lock ordering, aperture allocation, or turn limits | `stress` covers known-feasible folded returns, competing locks, tight turns, and shared passages. | - <a id="imported-fixtures"></a>[Sources and regeneration](benchmark-fixtures.md#imported-fixtures)
| Overall routing coverage | `corpus` combines these four groups. The correctness suite checks expected coverage and bounds with `corpus-regression`. | - <a id="experiment-archive"></a>[Find the archived measurements and scripts](benchmark-results.md#experiment-archive)
| A retry tuned on the regression corpus | `retry-holdout` adds related but previously unseen layouts, including return shelves and crossing bypasses. It can expose a trigger that works on one fixture and wastes time on a close variant. |
Use a verified witness to establish feasibility without supplying its paths to the timed run. For intentionally overconstrained layouts, compare against the proven bound. The overloaded gate tests limited passage capacity, while the imported LiDAR Clements layout tests disjoint conflicts between fixed ports. More search cannot exceed either bound at the same geometry. [Fixture groups](../inire/tests/routing_corpus.py)
### Reproduce a comparison
Choose `public-defaults` to measure the behavior users get from the public policy with the fixture geometry. Choose `corpus-regression` to reproduce the test budget of 500 search nodes, 500 seed nodes, and three configured congestion iterations. Use `matched-budget` to isolate routing-mode differences with the same configured budget. It defaults to 500 search nodes and two configured iterations and accepts overrides. The two budget profiles use benchmark weights for automatic candidate selection.
`offset-gates` is a small check for whether a corridor helps detailed search. At the reduced budget below, `guide` completes the net with no corridor seed. `seed` also completes it at the same cost. That comparison shows that guidance alone is enough on this fixture. Use it to check a change to corridor hints before spending time tuning seed allocation.
```sh
python -m scripts.compare_topological_routing --list
python -m scripts.compare_topological_routing --case corpus --profile corpus-regression \
--mode automatic --repeat 3 --json /tmp/inire-corpus.json
python -m scripts.compare_topological_routing --case offset-gates --profile matched-budget \
--mode off --mode guide --mode seed --nodes 100 --repeat 3 \
--json /tmp/inire-modes.json
```
Check verified IDs and bounds first. A lower total cost can result from dropping a net. Compare the benchmark-weighted score when judging length by component type and native cost when judging the run's configured objective. The benchmark weights physical lengths of straight, 90-degree bend, and S-bend segments by 1, 4, and 13. Compare paired timings under the same profile and worker count. [Metrics and parity tools](routing-diagnostics.md)
## Probe budget and coverage
The two-iteration probe cuts repeated shallow searches on layouts such as the splitter tree. It reduced public-default expansion counts by 23% on the regression corpus with identical paths there and on the holdouts. The mixed port-bank case did more work because the shorter probe passed the last net to the wider retry. Test both stages when changing the cap. A one-iteration cap increased the cost of a crossing approach, and the clipped-proxy regression required the original probe budget to keep its cheaper route. These are reasons to check path quality and proxy geometry as well as total expansions. [Probe budget in the policy](architecture.md#automatic-routing)
```sh
python -m scripts.benchmark_retry_order --case corpus --case retry-holdout \
--policy baseline --policy probe-full-budget --jobs 6 --json /tmp/inire-probe.json
```
### Retry experiments
Early retries can save time when they replace a more expensive stage. Their failures add work before the ordinary fallback. The holdout runs found both effects and a case where early incumbent recovery selected a higher-cost path at the same coverage. Review failed-retry time and common-net cost when deciding whether an early exit is worth using. The archived experiments include the trigger counts and the original commands. [Experiment archive](#experiment-archive)
The experimental `late-residual-3000` policy tests a different question. Can a wider search recover the last net while keeping the rest fixed? It requires room in the caller's budget and skips attempts whose locks disconnect the remaining ports. In the pre-cap holdout sweep it completed the last net on two crossing boards and a return shelf, with all previously verified paths intact. Use the experiment to measure the cost of completing one more net after the normal policy stalls.
```sh
python -m scripts.benchmark_retry_order --case retry-holdout --profile public-defaults \
--policy baseline --policy late-residual-3000 --repeat 3 --jobs 6 \
--json /tmp/inire-residual.json
```
## Automatic nine-net Terminal-Bench routing
Use this as a check on ordered placement and heading inference. The upstream task supplies point terminals, so `bundle` mode can infer headings and reserve room for the outer return and bend tangencies. The export command starts from the unseeded input. Its nine routes passed the pinned checker below the upstream cost limit. Use the fixed-heading `terminal-bench` fixture to check automatic routing when the headings are part of the input. [Bundle planner](../inire/router/_bundle.py) · [Pinned upstream task](https://github.com/harbor-framework/terminal-bench/tree/249d125b59c0a5352d9e132195cfead6d81446be/tasks/photonic-waveguide-routing)
```sh
python -m scripts.route_terminal_bench --output /tmp/inire-terminal-bench.json
```
The export CLI's `--reference-lane-plan` and `--single-bottom-track` flags replay authored layouts for comparison. Use the unseeded export to measure the planner and the reference flags to check feasibility or compare lane assignments. [Reference plan](../inire/tests/terminal_bench_lane_plan.py)
## Imported fixtures
The six fixed-placement cases run offline from [converted inputs](../inire/tests/data/external_routing_benchmarks.json). Optical ports snap to a 0.1 µm grid. Device outlines become keepouts with access cutouts. PIC Routing Benchmark contributes splitter-tree, ring-modulator, and MZM cases. LiDAR contributes a toy layout and subsets of the Clements and MRR weight-bank layouts. These fixtures exercise waveguide routing between fixed devices. [PIC data and CC BY 4.0 attribution](https://huggingface.co/datasets/FLYR/pic-benchmark/blob/0c1f445792926d97fae01893c89e96b8a9393800/pic-benchmark/README.md) · [LiDAR source](https://github.com/ScopeX-ASU/LiDAR/tree/4e7004d32b0b80d959553797fb30f0737513de0c/src/picroute/benchmarks) · [LiDAR license](../inire/tests/data/LiDAR-LICENSE.txt)
The importer checks both pinned archive hashes. It requires PyYAML when regenerating the fixtures.
```sh
mkdir -p /tmp/inire-external-routing
curl -fL 'https://huggingface.co/datasets/FLYR/pic-benchmark/resolve/0c1f445792926d97fae01893c89e96b8a9393800/pic-benchmark.zip' \
-o /tmp/inire-external-routing/pic-benchmark.zip
curl -fL 'https://codeload.github.com/ScopeX-ASU/LiDAR/tar.gz/4e7004d32b0b80d959553797fb30f0737513de0c' \
-o /tmp/inire-external-routing/lidar.tar.gz
uv run --with 'pyyaml==6.0.3' python -m scripts.import_external_routing_benchmarks \
--pic-archive /tmp/inire-external-routing/pic-benchmark.zip \
--lidar-archive /tmp/inire-external-routing/lidar.tar.gz
```
## Experiment archive
Use `git show ea5cfe7:docs/topological-routing.md` for the original retry experiments, budget sweeps, and manual Terminal-Bench lane comparisons. Use `git show 2b02c6e:docs/topological-routing.md` for the measured probe and holdout tables. For retired policies, check out `ea5cfe7` in a separate worktree to run the matching driver. [Original goal](routing-policy-goal.md) · [Refactor plan](routing-refactor-plan.md)

123
docs/user/api-reference.md Normal file
View file

@ -0,0 +1,123 @@
# Public API reference
Import the types on this page from `inire`. The [layout guide](route-a-layout.md) shows how to assemble a problem and the [tuning guide](tune-and-troubleshoot.md) explains which settings to try.
## Route a problem
```text
route(problem, *, options=None, iteration_callback=None) -> RoutingRunResult
```
Omitting `options` uses `RoutingOptions()`. To observe live congestion iterations, pass a callable accepting `(index, results_by_net)`. The index increases across automatic attempts. Each callback sees the nets in its current attempt. Use the returned result for final coverage.
## Layout inputs
- `Port(x, y, r)` snaps coordinates to the integer grid and normalizes the heading in degrees. Heading 0 points east and 90 points north. The heading must be a multiple of 90 after rounding.
- `NetSpec(net_id, start, target, width=2.0)` uses a unique ID and two ports. The target heading is the direction of arrival.
- `RoutingProblem` describes one routing layer. Use one unit for distances, coordinates, widths, and radii.
| Input | Meaning |
| --- | --- |
| `bounds` | Board outline as `(xmin, ymin, xmax, ymax)`. |
| `nets` | `NetSpec(net_id, start, target, width=2.0)` objects with unique IDs and `Port(x, y, r)` terminals. Defaults to an empty tuple. |
| `static_obstacles` | Shapely polygons for keepouts. Defaults to an empty tuple. |
| `initial_paths` | Mapping from net IDs to `PathSeed` objects. Defaults to an empty mapping. |
| `clearance` | Required spacing between physical shapes. Defaults to `2.0`. |
| `safety_zone_radius` | Tolerance for very small obstacle intersections at ports during search. Defaults to `0.0021`. |
## Path seeds
`PathSeed(segments)` holds an ordered tuple of `StraightSeed(length)`, `Bend90Seed(radius, direction)`, and `SBendSeed(offset, radius)` moves. Bend directions are `"CW"` and `"CCW"`. A seed is materialized from the net's current start port using its width and the run's geometry options. [Seed and lock workflows](route-a-layout.md#reuse-an-existing-route)
## Results
| Value | Read it for |
| --- | --- |
| `RoutingRunResult.results_by_net` | A mapping from net ID to `RoutingResult`. |
| `RoutingResult.is_valid` and `outcome` | Final validity and a status of `completed`, `colliding`, `partial`, or `unroutable`. |
| `RoutingResult.reached_target` and `report` | Arrival status, physical length, and collision details. |
| `RoutingResult.locked_geometry` and `as_seed()` | Physical polygons for export or fixed obstacles, and the move sequence for reuse as a seed. |
| `RoutingRunResult.automatic` | In automatic mode, the selected planner, the verified IDs, stage history, and any capacity or port-conflict bound. |
| `RoutingRunResult.topology` and `metrics` | Corridor counts and seed work when reported by the selected worker, plus work counters across the run. |
See [how to read the result](tune-and-troubleshoot.md#read-the-result) for export checks and [developer diagnostics](../routing-diagnostics.md) for reports and traces.
## Options and defaults
`RoutingOptions` accepts six option groups. Each group uses the defaults in its table when omitted.
| Group | Type |
| --- | --- |
| `search` | [SearchOptions](#searchoptions) |
| `objective` | [ObjectiveWeights](#objectiveweights) |
| `congestion` | [CongestionOptions](#congestionoptions) |
| `refinement` | [RefinementOptions](#refinementoptions) |
| `topology` | [TopologyOptions](#topologyoptions) |
| `diagnostics` | [DiagnosticsOptions](#diagnosticsoptions) |
### SearchOptions
| Field | Default | Effect |
| --- | --- | --- |
| `node_limit` | `1_000_000` | Per-search expansion ceiling. Automatic uses smaller budgets for its initial stages. |
| `min_straight_length` | `5.0` | Minimum single straight length. |
| `max_straight_length` | `2000.0` | Maximum single straight length. |
| `greedy_h_weight` | `1.5` | Weight for the A* heuristic. Lower values give the path cost more influence. |
| `bend_radii` | `(50.0, 100.0)` | Permitted radii for 90-degree bends. |
| `sbend_radii` | `(10.0,)` | Permitted S-bend radii. |
| `sbend_offsets` | `None` | Set permitted lateral offsets explicitly, or let search suggest offsets. A compact S-bend needs a nonzero offset with magnitude less than twice its radius. |
| `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"`. |
| `bend_clip_margin` | `None` | Optional legacy shrink margin for `"clipped_bbox"`. The default uses the eight-point proxy. |
| `visibility_guidance` | `"tangent_corner"` | Choose tangent candidates, exact corner visibility with `"exact_corner"`, or no visibility suggestions with `"off"`. |
### 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.
| Field | Default | Effect |
| --- | --- | --- |
| `unit_length_cost` | `1.0` | Cost per unit of path length. |
| `bend_penalty` | `250.0` | Additional cost of a 90-degree bend, scaled by radius. |
| `sbend_penalty` | `500.0` | Additional cost of an S-bend. |
| `danger_weight` | `1.0` | Weight of the obstacle proximity cost. |
### CongestionOptions
Increase the iteration limit when later reroutes might resolve conflicts. Adjust the initial penalty or multiplier when nets keep competing for the same space.
| Field | Default | Effect |
| --- | --- | --- |
| `max_iterations` | `10` | Maximum congestion iterations per attempt. Automatic's initial probe may use fewer. |
| `base_penalty` | `100.0` | Initial penalty for overlapping other routes. |
| `multiplier` | `1.5` | Scale the penalty between unresolved iterations. |
| `use_tiered_strategy` | `True` | Allow a cheaper bend proxy in the first iteration when applicable. |
| `net_order` | `"user"` | Route in input order or use `"shortest"` or `"longest"`. |
| `warm_start_enabled` | `True` | Build greedy seeds before congestion iterations. |
| `shuffle_nets` | `False` | Shuffle routing order between iterations. |
| `seed` | `None` | Random seed for shuffled ordering. |
### RefinementOptions
| Field | Default | Effect |
| --- | --- | --- |
| `enabled` | `True` | Try geometric improvements after routing. |
| `objective` | `None` | Use another `ObjectiveWeights` value for refinement, or reuse the search objective. |
| `max_windows_per_net` | `4` | Maximum candidate windows per net across improvement rounds. Use `1` for a shorter pass or `None` for unlimited windows. |
### TopologyOptions
| Field | Default | Effect |
| --- | --- | --- |
| `mode` | `"automatic"` | Select a [routing mode](tune-and-troubleshoot.md#choose-a-routing-mode). |
| `max_corridors` | `3` | Limit alternative corridors per net. |
| `guide_strength` | `0.75` | Maximum added guidance cost per unit length. Zero keeps the suggested moves without adding cost. |
| `seed_node_limit` | `600` | Total seed-search expansions per net, capped by the active search limit. |
| `infer_terminal_headings` | `False` | Allow heading inference for bundle-style point terminals. Automatic preserves caller headings when initial paths are supplied. |
| `automatic_cost` | `"selective"` | Re-score column layouts when they chain short S-bends. Use `"always"` for both passes or `"never"` for span scoring alone. |
| `automatic_length_weights` | `None` | Optional straight, 90-degree bend, and S-bend length multipliers for automatic candidate selection. The default uses the search objective. |
### DiagnosticsOptions
The flags default to `False`. Use `capture_expanded` to plot explored states or `capture_iteration_trace` to attribute search work per net and iteration. For clearance conflicts, `capture_conflict_trace` reports overlapping pairs, `capture_frontier_trace` examines prunes near final hotspots, and `capture_pre_pair_frontier_trace` examines the state before pair-local repair. [Trace fields and examples](../routing-diagnostics.md#traces)

View file

@ -0,0 +1,51 @@
# Route a layout
Start with the [first route](../../README.md#route-a-net), then replace the example ports and add your layout's constraints.
## Define the inputs
1. **Choose a coordinate unit.** Inire snaps port coordinates to an integer grid. Choose a unit fine enough to preserve narrow gaps, and use it for widths, radii, clearance, and bounds too.
2. **Set source and target headings.** Heading 0 points east and 90 points north. The source heading points along the launch. The target heading points along the arrival. If your device library labels the target port with its outward heading, reverse it by 180 degrees.
3. **Add a net for each connection.** Give each `NetSpec` a unique ID and the guide width. Set your process limits through `SearchOptions` and choose the required clearance on `RoutingProblem`.
4. **Add keepouts.** Supply Shapely polygons in `static_obstacles` and use `bounds` for the board rectangle. Leave enough access at the ports for the guide and its permitted bends. [Input fields](api-reference.md#layout-inputs)
5. **Run and check.** Call `route(problem, options=options)` and check each `result.is_valid`. Start with automatic mode for general layouts. [Read the result](tune-and-troubleshoot.md#read-the-result)
## Connect a preplaced crossing
- Place the device and reserve its keepout first.
- Leave openings in the keepout at the physical ports.
- Define the external legs as separate nets. The placed cell supplies the internal connections.
![Four routed legs stop at labeled ports in the notched keepout of a preplaced crossing. Dashed links inside the cell indicate connections supplied by the device.](../figures/placed-crossing.png)
Each leg meets a port at the end of an access slot. The dashed links show the device's internal connections schematically. The four external paths come from Inire's `crossing-single` fixture. [Crossing fixtures](../benchmark-fixtures.md#preplaced-crossings)
## 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.
- **Hold a route fixed.** Add `result.locked_geometry` to `static_obstacles` while routing other nets. The next run applies its own clearance.
To reuse the verified routes from a first problem as fixed obstacles, add them to a second problem that contains the remaining nets.
```python
from dataclasses import replace
from inire import route
first = route(first_problem)
locked = tuple(
polygon
for result in first.results_by_net.values()
if result.is_valid
for polygon in result.locked_geometry
)
obstacles = (
next_problem.static_obstacles
+ locked
)
second = route(replace(
next_problem,
static_obstacles=obstacles,
))
```
See the [locked-path example](../../examples/README.md#route-around-fixed-geometry) for the resulting detour and the [seed reference](api-reference.md#path-seeds) for building a hint by hand.

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