Rewrite routing documentation for users and developers

This commit is contained in:
Jan Petykiewicz 2026-11-26 20:25:20 -08:00
commit 2b02c6eae9

504
DOCS.md
View file

@ -1,437 +1,145 @@
# Inire Configuration & API Documentation
# Inire API and tuning guide
This document describes the current public API for `inire`.
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)
## 1. Primary API
## Describe a layout
### `RoutingProblem`
Use `RoutingProblem` to describe a single routing layer. Use the same unit for bounds, coordinates, widths, spacing, and radii. Ports snap to the integer grid. Their headings are degrees counterclockwise from east and must be multiples of 90 after rounding. A target heading gives the direction of travel at arrival.
`RoutingProblem` describes the physical routing problem:
- `bounds`
- `nets`
- `static_obstacles`
- `initial_paths`
- `clearance`
- `safety_zone_radius`
### `RoutingOptions`
`RoutingOptions` groups all expert controls for the routing engine:
- `search`
- `objective`
- `congestion`
- `refinement`
- `diagnostics`
- `topology`
Route a problem with:
```python
run = route(problem, options=options)
```
If you omit `options`, `route(problem)` uses `RoutingOptions()` with automatic routing enabled.
The package root is the stable API surface. Deep imports under `inire.router.*` and `inire.geometry.*` remain accessible for advanced use, but they are unstable semi-private interfaces and may change without notice.
Stable example:
```python
from inire import route, RoutingOptions, RoutingProblem
```
Unstable example:
```python
from inire.router._router import PathFinder
```
| 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. For a preplaced crossing, provide access to its ports and route each external leg as a net. |
| `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`. |
### Incremental routing with locked geometry
For incremental workflows, route one problem, reuse the result's locked geometry, and feed it into the next problem:
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
run_a = route(problem_a)
problem_b = RoutingProblem(
bounds=problem_a.bounds,
nets=(...),
static_obstacles=run_a.results_by_net["netA"].locked_geometry,
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
)
run_b = route(problem_b)
second = route(replace(next_problem, static_obstacles=next_problem.static_obstacles + locked))
```
`RoutingResult.locked_geometry` stores canonical physical geometry only. The next run applies its own clearance rules when treating it as a static obstacle.
### Initial paths with PathSeed
### Initial paths with `PathSeed`
Use `result.as_seed()` to replay a path for the same net, or construct a `PathSeed` from `StraightSeed`, `Bend90Seed`, and `SBendSeed` segments. The router materializes seeds from each net's start port with the current geometry settings. It can use partial seeds as hints and reroute nets as needed. Use static obstacles when a route must remain fixed. [Locked paths example](examples/03_locked_paths.py)
Use `RoutingProblem.initial_paths` to provide semantic per-net seeds. Seeds are materialized with the current width, clearance, and bend collision settings for the run, and partial seeds are retried by normal routing in later iterations.
## Read the result
## 2. Search Options
`route(problem, options=..., iteration_callback=...)` returns a `RoutingRunResult`. Read `results_by_net[net_id]` and check `is_valid` before exporting a path. The `outcome` is `completed`, `colliding`, `partial`, or `unroutable`. A path can reach the requested port and still fail clearance or board containment. The per-net `report` gives physical length and collision counts.
`RoutingOptions.search` is a `SearchOptions` object.
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)
| Field | Default | Description |
| :-- | :-- | :-- |
| `node_limit` | `1_000_000` | Maximum number of states to explore per search attempt. Automatic routing uses at most 500 states per attempt in its first pass. |
| `max_straight_length` | `2000.0` | Maximum length of a single straight segment. |
| `min_straight_length` | `5.0` | Minimum length of a single straight segment. |
| `greedy_h_weight` | `1.5` | Heuristic weight. `1.0` is optimal but slower. |
| `bend_radii` | `(50.0, 100.0)` | Available radii for 90-degree bends. |
| `sbend_radii` | `(10.0,)` | Available radii for S-bends. |
| `sbend_offsets` | `None` | Optional explicit lateral offsets for S-bends. |
| `bend_collision_type` | `"arc"` | Bend collision/proxy model: `"arc"`, `"bbox"`, `"clipped_bbox"`, or, for backward compatibility, a custom polygon. A legacy custom polygon here is treated as both the physical bend and its proxy unless overridden by the split fields below. |
| `bend_proxy_geometry` | `None` | Optional explicit bend proxy geometry. Use this when you want a custom search/collision envelope that differs from the routed bend shape. Supplying only a custom polygon proxy warns and keeps the physical bend as the standard arc. |
| `bend_physical_geometry` | `None` | Optional explicit bend physical geometry. Use `"arc"` or a custom polygon. If you set a custom physical polygon and do not set a proxy, the proxy defaults to the same polygon. |
| `bend_clip_margin` | `None` | Optional legacy shrink margin for `"clipped_bbox"`. Leave `None` for the default 8-point proxy. |
| `visibility_guidance` | `"tangent_corner"` | Visibility-derived straight candidate strategy. |
## Topological routing
## 3. Objective Weights
Set `RoutingOptions(topology=TopologyOptions(mode=...))` when you need a particular mode.
`RoutingOptions.objective` and `RoutingOptions.refinement.objective` use `ObjectiveWeights`.
| Mode | When to use it |
| --- | --- |
| `"automatic"` | The default. Chooses from constructive planners and detailed search stages based on the layout. |
| `"off"` | Run the lattice router directly. Useful for custom bends and controlled comparisons. |
| `"guide"` | Add corridor waypoints and a soft guidance cost to lattice search. |
| `"seed"` | Try to realize and verify corridor paths before the detailed router completes the layout. |
| `"bundle"` | Construct tracks for supported ordered rectangular bundles. Unsupported layouts or failed verification raise `ValueError`. |
| Field | Default | Description |
| :-- | :-- | :-- |
| `unit_length_cost` | `1.0` | Cost per unit length. |
| `bend_penalty` | `250.0` | Flat bend penalty before radius scaling. |
| `sbend_penalty` | `500.0` | Flat S-bend penalty. |
| `danger_weight` | `1.0` | Weight applied to danger-map proximity costs. |
## 4. Congestion Options
`RoutingOptions.congestion` is a `CongestionOptions` object.
| Field | Default | Description |
| :-- | :-- | :-- |
| `max_iterations` | `10` | Maximum rip-up and reroute iterations. |
| `base_penalty` | `100.0` | Starting overlap penalty for negotiated congestion. |
| `multiplier` | `1.5` | Multiplier applied after an iteration still needs retries. |
| `use_tiered_strategy` | `True` | Use cheaper collision proxies in the first pass when applicable. |
| `net_order` | `"user"` | Net ordering strategy for warm-start seeding and routed iterations. |
| `warm_start_enabled` | `True` | Run the greedy warm-start seeding pass before negotiated congestion iterations. |
| `shuffle_nets` | `False` | Shuffle routing order between iterations. |
| `seed` | `None` | RNG seed for shuffled routing order. |
## 5. Refinement Options
`RoutingOptions.refinement` is a `RefinementOptions` object.
| Field | Default | Description |
| :-- | :-- | :-- |
| `enabled` | `True` | Enable post-route refinement. |
| `objective` | `None` | Optional override objective for refinement. `None` reuses the search objective. |
| `max_windows_per_net` | `4` | Maximum candidate windows attempted per net, shared across improvement rounds. Use `1` for a faster pass or `None` to remove the window limit. |
With a finite limit greater than one, the refiner tries windows with a bend at each end first, then those with one bend at an end, and finally the rest. Within each group it tries the longest windows first. A limit of one and unlimited refinement use longest-first ordering across all windows. The refiner scores candidate moves from their ports and lengths before building polygons. When the incumbent is valid in the current collision world, it verifies the replacement window against obstacles, other nets, and the unchanged parts of its own path. The router verifies the final layout in full.
## Topological Routing
`RoutingOptions.topology` accepts a `TopologyOptions` value. The `mode` is the caller's routing choice. In automatic mode, inire selects a planner for the layout and can retry with another one. Seed mode generates verified initial paths before the current router completes and refines the layout.
```python
from inire import RoutingOptions, TopologyOptions, route
run = route(problem, options=RoutingOptions(topology=TopologyOptions(mode="seed")))
```
| Field | Default | Behavior |
| --- | --- | --- |
| `mode` | `"automatic"` | `"automatic"` selects planners and retries from the board geometry. `"off"` uses lattice-only routing. `"guide"` adds portal waypoints and a soft cost to lattice search. `"seed"` realizes candidate corridors and hands verified paths to the router as initial paths. `"bundle"` constructs ordered waveguide tracks for a supported rectangular layout. |
| `max_corridors` | `3` | Maximum number of candidate corridors per net. |
| `guide_strength` | `0.75` | Maximum extra cost per unit length during soft guidance. Zero retains the suggested moves. |
| `seed_node_limit` | `600` | Total seed-search expansions per net, capped by `SearchOptions.node_limit`. |
| `infer_terminal_headings` | `False` | Allow bundle heading inference for point terminals in bundle or automatic mode. Automatic mode uses the supplied headings whenever the problem includes initial paths. |
| `automatic_cost` | `"selective"` | Re-score column transitions when a verified span layout chains short S-bends. `"always"` requests a weighted pass whenever column planning is tried. `"never"` uses span scoring alone. |
| `automatic_length_weights` | `None` | Optional straight, 90-degree bend, and S-bend length multipliers for automatic candidate selection. By default candidates are compared using `RoutingOptions.objective`. Lattice search continues to use the search objective. |
Caller-supplied initial paths take precedence in guide and seed modes. A net with no corridor can use ordinary lattice search. The triangulation modes require Shapely 2.1 and GEOS 3.10 or newer.
`RoutingRunResult.topology` is populated when the stage is enabled. Its `corridor_counts` lists the nets with candidate corridors. Its `seeded_net_ids` and `seed_nodes_expanded` describe the constrained seed pass. See the [comparison and tuning notes](docs/topological-routing.md).
### Ordered bundles
Bundle mode takes an unseeded problem and constructs its schedule from the obstacle rectangles, terminal coordinates, waveguide width, clearance, and bend radius. It supports eastbound bundles with two paired barriers, three interior obstacles, a short net, and an outer return. Unsupported layouts and schedules that fail final geometric verification raise `ValueError`. Use a circular bend radius that is enabled for both 90-degree bends and S-bends.
```python
from inire import RefinementOptions, RoutingOptions, SearchOptions, TopologyOptions, route
options = RoutingOptions(
search=SearchOptions(bend_radii=(50,), sbend_radii=(50,)),
topology=TopologyOptions(mode="bundle", infer_terminal_headings=True),
refinement=RefinementOptions(enabled=False),
)
run = route(unseeded_problem, options=options)
```
For this mode, `run.topology.seeded_net_ids` records the routes generated by the bundle planner. Only enable heading inference for point terminals. [Terminal-Bench reproduction](docs/topological-routing.md#automatic-nine-net-terminal-bench-routing)
`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
Automatic routing verifies planner candidates and keeps the best coverage it finds. The near-port probe uses at most 100 nodes per search and two congestion iterations with the standard arc proxy, subject to any smaller caller limits. Alternate proxies use the configured iteration budget. The wider initial pass can use up to 500 nodes per search and the configured iteration limit. When coverage remains below the routing bound, a lattice fallback can use the configured search ceiling. Automatic uses lattice directly for custom bend geometry or when constrained triangulation is unavailable.
`run.automatic` reports `verified_net_ids`, the selected planner, its stages, and the upper bound `max_routed`. A cut with finite capacity or conflicting fixed ports can make that bound smaller than the requested net count. Detailed traces describe the selected attempt. Counters and stage timings include work done in other attempts. [Automatic stage order](docs/architecture.md#automatic-routing) · [Report fields](docs/routing-diagnostics.md#automatic-reports)
## Tune a run
Start with the process constraints in `SearchOptions` and the layout's clearance. If routing stops early, inspect the returned net outcomes and the automatic routing bound before increasing budgets. Set `SearchOptions(node_limit=500)` to cap each search at 500 expansions. The entire run may do several searches per net. If refinement dominates runtime, try `RefinementOptions(max_windows_per_net=1)`. Compare verified net IDs and paths as well as time.
```python
run = route(problem)
report = run.automatic
from inire import RefinementOptions, RoutingOptions, SearchOptions, route
options = RoutingOptions(
search=SearchOptions(node_limit=500, bend_radii=(50,), sbend_radii=(25,)),
refinement=RefinementOptions(max_windows_per_net=1),
)
run = route(problem, options=options)
```
Automatic routing verifies generated layouts with inire and uses guide, seed, and lattice retries where needed. The first pass uses at most 500 nodes per search attempt. If it falls short of the routing bound and the configured ceiling is higher, automatic tries the lattice router at that ceiling and retains the best verified coverage. Set `SearchOptions(node_limit=500)` for a hard 500-node limit per search attempt. Each routing attempt respects the configured congestion limit.
### SearchOptions
Automatic carries caller-supplied paths into the usual seed handling. For custom bend geometry or an installation without constrained triangulation, it uses the lattice router directly at the configured limit. The optional refinement pass runs on the selected layout when enabled. Set `TopologyOptions(mode="off")` to select lattice-only routing explicitly.
| 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"`. |
For eligible unseeded layouts with fixed headings along both axes, `local-sbend` fits one S-bend between each pair of shifted ports using a configured radius and an exact forward span on the port lattice. It samples positions along the link, packs paths to meet clearance, and accepts the layout only after all nets pass verification. Crossings use the supplied port positions and keepouts.
### ObjectiveWeights
If short, forward, same-heading shifts across both axes still need search, automatic can run the full initial guide budget first. The near-port probe and other fallbacks follow if needed. The identical guide retry is skipped when the first pass ran without a timeout. Calls with an iteration callback, shuffled net ordering, or at most 100 nodes per search use the regular search order.
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.
On eligible ordered horizontal banks, `column-jogs` can assign lanes across separated obstacle columns before the initial search probe. It schedules the rises and drops as staggered pairs of 90-degree turns, using each net's width and the configured clearance. Calls with an iteration callback or shuffled ordering try column jogs after the probe if needed.
| 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. |
The `residual-dogleg` planner tries a four-turn detour through gaps between verified paths and obstacles. When the near-port probe leaves one unfinished net on an unseeded layout of at least three nets, automatic can try this detour before expanding the search budget. This early attempt requires full coverage to be the target and runs with deterministic ordering and no iteration callback. The planner can also run after an incumbent-residual attempt. Both constructive planners verify the complete layout before selecting it.
### CongestionOptions
When an incumbent-residual attempt falls short of the routing bound, automatic can retry a shared portal with a joint lane assignment. It keeps the incumbent paths locked and assigns distinct lanes to two to four residual nets at one portal. The retry needs an unresolved net at that portal and a changed guide. It uses the initial node budget and at most three congestion iterations. An improving candidate is checked together with the incumbent paths before it can be selected.
Increase the iteration limit when later reroutes might resolve conflicts. Adjust the initial penalty or multiplier when nets keep competing for the same space.
The report records the `selected_planner`, `verified_net_ids`, and the overall `max_routed` upper bound. Each stage includes the verified net IDs and any paths that went outside the board. A path whose physical geometry crosses the board boundary has `result.report.out_of_bounds=True`, which contributes one collision to the result. `result.reached_target` still records whether that path reached its target port.
| 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. |
`capacity_limit` and `port_conflicts` explain cuts and pairs of terminals that lower the bound. `cost_pass_performed` records whether the policy attempted weighted column scoring. Metrics count work across attempts. Detailed traces belong to the selected attempt, and a live iteration callback receives increasing indices across attempts with the nets in each attempt. [Expanded benchmark comparison](docs/topological-routing.md#public-api-budget-sweep)
### RefinementOptions
Each routing stage records its `planner`, the `mode` used by its routing worker, its `operation`, and any retry or scoring `policy`. For example, a bundle turnaround can appear as planner `bundle-turnaround` with worker mode `off` and operation `verify`. A guide retry can appear as planner `portal-guide` with worker mode `guide`, operation `search`, and policy `direct-lookahead-retry`. `selected_planner` reports the planner that produced the selected layout, including when a refinement stage wins.
| 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. |
`run.automatic.timings` records exclusive wall time for `plan`, `verify`, `search`, and `refine`, including rejected candidates. Planning covers candidate generation and screening inside the planner. Search covers the routing worker, including corridor setup and its iteration loop. Verification covers candidate acceptance and final geometry checks. Nested timings exclude time already recorded under another operation. The report's `duration_s` also includes orchestration and other work between timed operations.
### TopologyOptions
## 6. Diagnostics Options
| 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. |
`RoutingOptions.diagnostics` is a `DiagnosticsOptions` object.
### DiagnosticsOptions
| Field | Default | Description |
| :-- | :-- | :-- |
| `capture_expanded` | `False` | Record expanded nodes for diagnostics and visualization. |
| `capture_conflict_trace` | `False` | Capture authoritative post-reverify conflict trace entries for debugging negotiated-congestion failures. |
| `capture_frontier_trace` | `False` | Run an analysis-only reroute for reached-but-colliding nets and capture prune causes near their final conflict hotspots. |
| `capture_iteration_trace` | `False` | Capture per-iteration and per-net route-attempt attribution for negotiated-congestion diagnosis. |
| `capture_pre_pair_frontier_trace` | `False` | Capture the final unresolved pre-pair-local subset iteration plus hotspot-adjacent frontier prunes for the routed nets in that basin. |
## 7. Conflict Trace
`RoutingRunResult.conflict_trace` is an immutable tuple of post-reverify conflict snapshots. It is empty unless `RoutingOptions.diagnostics.capture_conflict_trace=True`.
Trace types:
- `ConflictTraceEntry`
- `stage`: `"iteration"`, `"restored_best"`, or `"final"`
- `iteration`: Iteration index for `"iteration"` entries, otherwise `None`
- `completed_net_ids`: Nets with collision-free reached-target paths at that stage
- `conflict_edges`: Undirected dynamic-conflict net pairs seen after full reverify
- `nets`: Per-net trace payloads in routing-order order
- `NetConflictTrace`
- `net_id`
- `outcome`
- `reached_target`
- `report`
- `conflicting_net_ids`: Dynamic conflicting nets for that stage
- `component_conflicts`: Dynamic component-pair overlaps for that stage
- `ComponentConflictTrace`
- `other_net_id`
- `self_component_index`
- `other_component_index`
The conflict trace only records dynamic net-vs-net component overlaps. Static-obstacle and self-collision details remain count-only in `RoutingReport`.
Use `scripts/record_conflict_trace.py` to capture JSON and Markdown trace artifacts for the built-in trace scenarios. The default target is `example_07_large_scale_routing_no_warm_start`.
## 8. Frontier Trace
`RoutingRunResult.frontier_trace` is an immutable tuple of per-net post-run frontier analyses. It is empty unless `RoutingOptions.diagnostics.capture_frontier_trace=True`.
Trace types:
- `NetFrontierTrace`
- `net_id`
- `hotspot_bounds`: Buffered bounds around the net's final dynamic component-overlap hotspots
- `pruned_closed_set`
- `pruned_hard_collision`
- `pruned_self_collision`
- `pruned_cost`
- `samples`: First traced prune events near those hotspots
- `FrontierPruneSample`
- `reason`: `"closed_set"`, `"hard_collision"`, `"self_collision"`, or `"cost"`
- `move_type`
- `hotspot_index`
- `parent_state`
- `end_state`
The frontier trace is observational only. It reruns only the final reached-but-colliding nets in analysis mode, with scratch metrics, after the routed result is already fixed.
Use `scripts/record_frontier_trace.py` to capture JSON and Markdown frontier-prune artifacts for the built-in trace scenarios. The default target is `example_07_large_scale_routing_no_warm_start`.
Separately from the observational trace tooling, the router may run a bounded post-loop pair-local scratch reroute before refinement when the restored best snapshot ends with final two-net reached-target dynamic conflicts. In the late all-reached low-edge regime, the negotiated-congestion loop also narrows reroutes to the current conflict set and may carry capped heavy nets forward by immediately restoring their incumbent reached-target paths instead of spending more search work on pathological late reroutes. That behavior is part of normal routing and is reported through the `pair_local_search_*` and `late_phase_capped_*` counters below.
## 9. Pre-Pair Frontier Trace
`RoutingRunResult.pre_pair_frontier_trace` is either a single immutable trace entry or `None`. It is populated only when `RoutingOptions.diagnostics.capture_pre_pair_frontier_trace=True`.
Trace types:
- `PrePairFrontierTraceEntry`
- `iteration`: The final unresolved subset-reroute iteration immediately before pair-local handoff
- `routed_net_ids`: Nets rerouted in that iteration, in routing order
- `conflict_edges`: Dynamic conflict edges reported for that unresolved basin
- `nets`: Per-net attempt attribution plus hotspot-adjacent frontier rerun data
- `PrePairNetTrace`
- `net_id`
- `nodes_expanded`
- `congestion_check_calls`
- `pruned_closed_set`
- `pruned_cost`
- `pruned_hard_collision`
- `guidance_seed_present`
- `frontier`: A `NetFrontierTrace` captured against the restored best unresolved state
Use `scripts/record_pre_pair_frontier_trace.py` to capture JSON and Markdown artifacts. Its default comparison target is the solved seed-42 no-warm canary versus the heavier seed-43 no-warm canary.
## 10. Iteration Trace
`RoutingRunResult.iteration_trace` is an immutable tuple of negotiated-congestion iteration summaries. It is empty unless `RoutingOptions.diagnostics.capture_iteration_trace=True`.
Trace types:
- `IterationTraceEntry`
- `iteration`
- `congestion_penalty`: Penalty in effect for that iteration
- `routed_net_ids`: Nets rerouted during that iteration, in routing order
- `completed_nets`
- `conflict_edges`
- `total_dynamic_collisions`
- `nodes_expanded`
- `congestion_check_calls`
- `congestion_candidate_ids`
- `congestion_exact_pair_checks`
- `net_attempts`: Per-net attribution for that iteration
- `IterationNetAttemptTrace`
- `net_id`
- `reached_target`
- `nodes_expanded`
- `congestion_check_calls`
- `pruned_closed_set`
- `pruned_cost`
- `pruned_hard_collision`
- `guidance_seed_present`
Use `scripts/record_iteration_trace.py` to capture JSON and Markdown iteration-attribution artifacts. Its default comparison target is the solved seed-42 no-warm canary versus the pathological seed-43 no-warm canary.
## 11. RouteMetrics
`RoutingRunResult.metrics` is an immutable per-run snapshot.
### Search Counters
- `nodes_expanded`: Total nodes expanded during the run.
- `moves_generated`: Total candidate moves generated during the run.
- `moves_added`: Total candidate moves admitted to the open set.
- `pruned_closed_set`: Total moves pruned because the state was already closed at lower cost.
- `pruned_hard_collision`: Total moves pruned by hard collision checks.
- `pruned_cost`: Total moves pruned by cost ceilings or invalid costs.
- `route_iterations`: Number of negotiated-congestion iterations entered.
- `nets_routed`: Number of net-routing attempts executed across all iterations.
- `nets_reached_target`: Number of those attempts that reached the requested target port.
- `warm_start_paths_built`: Number of warm-start seed paths built by the greedy bootstrap pass.
- `warm_start_paths_used`: Number of routing attempts satisfied directly from an initial or warm-start path.
- `refine_path_calls`: Number of completed paths passed through the post-route refiner.
- `timeout_events`: Number of timeout exits encountered during the run.
- `iteration_reverify_calls`: Number of end-of-iteration full reverify passes against the final installed dynamic geometry.
- `iteration_reverified_nets`: Number of reached-target nets reverified at iteration boundaries.
- `iteration_conflicting_nets`: Total unique nets found in end-of-iteration dynamic conflicts.
- `iteration_conflict_edges`: Total undirected dynamic-conflict edges observed at iteration boundaries.
- `nets_carried_forward`: Number of nets retained unchanged between iterations.
### Cache Counters
- `move_cache_abs_hits` / `move_cache_abs_misses`: Absolute move-geometry cache activity.
- `move_cache_rel_hits` / `move_cache_rel_misses`: Relative move-geometry cache activity.
- `guidance_match_moves`: Number of moves that matched the reroute guidance seed and received the guidance bonus.
- `guidance_match_moves_straight`, `guidance_match_moves_bend90`, `guidance_match_moves_sbend`: Guidance-match counts split by move type.
- `guidance_bonus_applied`: Total reroute-guidance bonus subtracted from move costs across the run.
- `guidance_bonus_applied_straight`, `guidance_bonus_applied_bend90`, `guidance_bonus_applied_sbend`: Guidance bonus totals split by move type.
- `static_safe_cache_hits`: Reuse count for the static-safe admission cache.
- `hard_collision_cache_hits`: Reuse count for the hard-collision cache.
- `congestion_cache_hits` / `congestion_cache_misses`: Per-search congestion-cache activity.
### Index And Collision Counters
- `dynamic_path_objects_added` / `dynamic_path_objects_removed`: Dynamic-path geometry objects inserted into or removed from the live routing index.
- `dynamic_tree_rebuilds`: Number of dynamic STRtree rebuilds.
- `dynamic_grid_rebuilds`: Number of dynamic congestion-grid rebuilds.
- `static_tree_rebuilds`: Number of static dilated-obstacle STRtree rebuilds.
- `static_raw_tree_rebuilds`: Number of raw static-obstacle STRtree rebuilds used for verification.
- `static_net_tree_rebuilds`: Number of net-width-specific static STRtree rebuilds.
- `visibility_corner_index_builds`: Number of lazy corner-index rebuilds.
- `visibility_builds`: Number of exact corner-visibility graph rebuilds.
- `visibility_corner_pairs_checked`: Number of corner-pair visibility probes considered while building the exact graph.
- `visibility_corner_queries_exact` / `visibility_corner_hits_exact`: Exact-corner visibility query activity.
- `visibility_point_queries`, `visibility_point_cache_hits`, `visibility_point_cache_misses`: Arbitrary-point visibility query and cache activity.
- `ray_cast_calls`: Number of ray-cast queries issued against static obstacles.
- `ray_cast_candidate_bounds`: Total broad-phase candidate bounds considered by ray casts.
- `ray_cast_exact_geometry_checks`: Total exact non-rectangular geometry checks performed by ray casts.
- `congestion_check_calls`: Number of congestion broad-phase checks requested by search.
- `congestion_presence_cache_hits` / `congestion_presence_cache_misses`: Reuse of cached per-span booleans indicating whether a move polygon could overlap any other routed net at all.
- `congestion_presence_skips`: Number of moves that bypassed full congestion evaluation because the presence precheck found no other routed nets in any covered dynamic-grid span.
- `congestion_candidate_precheck_hits` / `congestion_candidate_precheck_misses`: Reuse of cached conservative per-span booleans indicating whether any candidate nets survive the net-envelope and grid-net broad phases.
- `congestion_candidate_precheck_skips`: Number of moves that bypassed full congestion evaluation because the candidate-net precheck found no surviving candidate nets after those broad phases.
- `congestion_candidate_nets`: Total candidate net ids returned by the dynamic net-envelope broad phase during routing.
- `congestion_net_envelope_cache_hits` / `congestion_net_envelope_cache_misses`: Reuse of cached dynamic net-envelope candidate sets keyed by the queried grid-cell span.
- `congestion_grid_net_cache_hits` / `congestion_grid_net_cache_misses`: Reuse of cached per-span candidate net ids gathered from dynamic grid occupancy.
- `congestion_grid_span_cache_hits` / `congestion_grid_span_cache_misses`: Reuse of cached dynamic-path candidate unions keyed by the queried grid-cell span.
- `congestion_lazy_resolutions`: Number of popped nodes whose pending congestion was resolved lazily.
- `congestion_lazy_requeues`: Number of lazily resolved nodes requeued after a positive congestion penalty was applied.
- `congestion_candidate_ids`: Total dynamic-path object ids returned by the congestion broad phase before exact confirmation.
- `congestion_exact_pair_checks`: Number of exact geometry-pair checks performed while confirming congestion hits.
### Verification Counters
- `verify_path_report_calls`: Number of full path-verification passes.
- `verify_static_buffer_ops`: Number of static-verification `buffer()` operations.
- `verify_dynamic_candidate_nets`: Total candidate net ids returned by the dynamic net-envelope broad phase during final verification.
- `verify_dynamic_exact_pair_checks`: Number of exact geometry-pair checks performed during dynamic-path verification.
### Local Search Counters
- `pair_local_search_pairs_considered`: Number of final reached-target conflict pairs considered by the bounded post-loop pair-local-search phase.
- `pair_local_search_attempts`: Number of pair-local-search reroute attempts executed across all considered pairs.
- `pair_local_search_accepts`: Number of pair-local-search attempts accepted into the whole routed result set.
- `pair_local_search_nodes_expanded`: Total A* node expansions spent inside pair-local-search attempts.
- `late_phase_capped_nets`: Number of heavy nets identified in the final all-reached late phase and handled by the capped carry-forward path before pair-local handoff.
- `late_phase_capped_fallbacks`: Number of those capped late-phase nets that kept their incumbent reached-target paths instead of accepting a newly searched replacement.
## 10. Internal Modules
Lower-level search and collision modules are semi-private implementation details. They remain accessible through deep imports for advanced use, but they are unstable and may change without notice. The stable supported entrypoint is `route(problem, options=...)`.
The current implementation structure is summarized in **[docs/architecture.md](docs/architecture.md)**. The committed example-corpus counter baseline is tracked in **[docs/performance.md](docs/performance.md)**.
Use `scripts/diff_performance_baseline.py` to compare a fresh local run against that baseline. Use `scripts/record_conflict_trace.py` for opt-in conflict-hotspot traces, `scripts/record_frontier_trace.py` for hotspot-adjacent prune traces, `scripts/record_pre_pair_frontier_trace.py` for the final unresolved pre-pair basin, `scripts/record_iteration_trace.py` for per-iteration negotiated-congestion attribution, and `scripts/characterize_pair_local_search.py` to sweep example_07-style no-warm runs for pair-local repair behavior. The counter baseline is currently observational and is not enforced as a CI gate.
## 11. Tuning Notes
### Speed vs. optimality
- Lower `search.greedy_h_weight` toward `1.0` for better optimality.
- Raise `search.greedy_h_weight` for faster, greedier routing.
### Congestion handling
- Increase `congestion.base_penalty` to separate nets more aggressively in the first iteration.
- Increase `congestion.max_iterations` if congestion needs more reroute passes.
- Increase `congestion.multiplier` if later iterations need to escalate more quickly.
### Bend-heavy routes
- Increase `objective.bend_penalty` to discourage ladders of small bends.
- Increase available `search.bend_radii` when larger turns are physically acceptable.
- Use `search.bend_physical_geometry` and `search.bend_proxy_geometry` together when you need a real custom bend shape plus a different conservative proxy.
### Visibility guidance
- `"tangent_corner"` is the default and best general-purpose setting in obstacle-dense layouts.
- `"exact_corner"` is more conservative.
- `"off"` disables visibility-derived straight candidates.
### S-bends
- Leave `search.sbend_offsets=None` to let the router derive natural offsets automatically.
- Provide explicit `search.sbend_offsets` for known process-preferred offsets.
- S-bends are only used for offsets smaller than `2R`.
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)