Refactor routing internals and archive retry benchmarks
This commit is contained in:
parent
a8720ac8c9
commit
ea5cfe7f31
66 changed files with 3481 additions and 2583 deletions
4
DOCS.md
4
DOCS.md
|
|
@ -181,7 +181,9 @@ For eligible unseeded layouts with fixed headings along both axes, `local-sbend`
|
|||
|
||||
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.
|
||||
|
||||
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. When only one net remains after an incumbent-residual attempt, `residual-dogleg` tries a four-turn detour through gaps between the locked paths and obstacles. Both planners verify the complete layout before selecting it.
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
|
|
|
|||
|
|
@ -19,7 +19,10 @@
|
|||
- `inire/geometry/static_obstacle_index.py` and `inire/geometry/dynamic_path_index.py`: Spatial-index management for static obstacles and routed paths, including dynamic per-object indices, per-net grid occupancy, congestion grid membership, and per-net dynamic envelopes.
|
||||
- `inire/router/_search.py`, `_astar_moves.py`, `_astar_admission.py`, `_astar_types.py`: The state-lattice A* search loop and move admission pipeline.
|
||||
- `inire/router/_router.py`: The negotiated-congestion driver and refinement orchestration.
|
||||
- `inire/router/_congestion_policy.py` contains the iteration review, reroute selection, and stopping rules. `_route_traces.py` formats diagnostics from the driver’s collected data.
|
||||
- `inire/router/_pair_local.py` searches for replacements in a separate routing world. The driver installs and verifies proposed replacements and restores the incumbent layout when a candidate is rejected.
|
||||
- `inire/router/_automatic.py` selects and verifies planner candidates for the default public routing mode. It retries at the configured lattice search ceiling when the first pass falls short of the routing bound.
|
||||
- `inire/router/_capacity.py` calculates vertical cut bounds and disjoint fixed-port conflicts for the automatic router.
|
||||
- `inire/router/_topology.py` builds alternative corridors through triangulated free space and ranks portal lanes using capacity, route overlap, and estimated turn clearance.
|
||||
- `inire/router/_bundle.py` constructs ordered routes from rectangular barriers and terminal order for the opt-in bundle mode. `_waypoints.py` compiles its turns and S-bends into physical path seeds.
|
||||
- `inire/router/refiner.py`: Post-route path simplification for completed paths.
|
||||
|
|
@ -55,4 +58,4 @@ When enabled, topological planning runs before the first iteration. The lattice
|
|||
|
||||
`RoutingRunResult.metrics` includes both A* counters and index/cache/verification counters. The committed example-corpus baseline for those counters is tracked in `docs/performance.md` and `docs/performance_baseline.json`.
|
||||
|
||||
The [topological routing experiment](topological-routing.md) compares soft corridor guidance and corridor-first seed generation with the state-lattice baseline.
|
||||
The [topological routing experiment](topological-routing.md) compares soft corridor guidance and corridor-first seed generation with the state-lattice baseline. The [refactor plan](routing-refactor-plan.md) documents the exact parity command for checking implementation changes against a baseline.
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
# Automatic routing policy and route cost goals
|
||||
|
||||
This historical milestone describes the original 37-board automatic-routing objective. The [routing benchmark record](topological-routing.md) tracks the expanded corpus and subsequent tuning.
|
||||
|
||||
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.
|
||||
|
||||
## Benchmark baseline
|
||||
|
|
|
|||
59
docs/routing-refactor-plan.md
Normal file
59
docs/routing-refactor-plan.md
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
# Routing refactor plan
|
||||
|
||||
Make routing behavior easier to measure, test, and change through independent refactors. Start with shared benchmark configuration and parity checks, then make temporary obstacle cleanup exception-safe. Keep the [public routing API](../DOCS.md) and current planner behavior as the baseline for planned changes.
|
||||
|
||||
## Planned
|
||||
|
||||
### Benchmark reproducibility and router state
|
||||
|
||||
1. **Share the corpus and benchmark profiles.** Give the comparison CLI, pytest, and the performance snapshot tools one source for case groups and named configurations. The CLI's matched-budget defaults currently use two congestion iterations and a 600-node seed budget. The corpus test uses three iterations and a 500-node seed budget. Make those settings explicit and preserve the existing configurations when moving them. Store expected coverage with the fixtures, including the bounds for `overloaded-gate` and `lidar-clements-8x8`. [Benchmark CLI](../scripts/compare_topological_routing.py) · [Corpus tests](../inire/tests/test_routing_benchmarks.py)
|
||||
2. **Make exact parity a reusable benchmark command.** Compare runs by case and effective profile. Check verified net IDs, path seeds, per-net costs, selected stages and stage order, stable counters, and callback payloads. Report the first differing case, stage, or net and compare elapsed time separately. Use the command when checking subsequent behavior-preserving work.
|
||||
3. **Scope temporary obstacle reservations.** Greedy warm starts remove temporary obstacles on normal completion, and corridor seeding already uses `finally`. Share the cleanup rule while preserving insertion order and cache invalidation. Test that an interrupted greedy search leaves the routing world reusable. [Warm starts and corridor seeds](../inire/router/_router.py)
|
||||
4. **Consolidate routing counter definitions.** Define counter defaults, reset behavior, and snapshot aggregation once. Keep direct attribute increments in the search loop, preserve the distinction between per-search and cumulative counters, and retain the public `RouteMetrics` fields. Check that runs and reports expose the same counter values. [Mutable counters](../inire/router/_astar_types.py) · [Public metrics](../inire/results.py)
|
||||
|
||||
### Routing decisions and diagnostics
|
||||
|
||||
5. **Extract trace formatting from `PathFinder`.** Start with pure formatters for conflict and iteration entries. Keep trace capture points visible in the routing loop, including the stages around best-iteration restoration and pair-local repair. Compare the serialized traces before and after. [Trace capture](../inire/router/_router.py)
|
||||
6. **Extract negotiated-congestion decisions.** Make reroute selection, late search caps, and stop conditions testable against an iteration review and recent search work. Use small tests to exercise those rules independently of A*, with corpus parity to check their integration. [Congestion routing](../inire/router/_router.py)
|
||||
7. **Group the per-search congestion caches.** Give the six congestion cache dictionaries one owner for each A* search. Simplify the signatures between the search loop, move expansion, and admission while preserving cache keys and lifetime. Compare stable counters and runtime. [Search loop](../inire/router/_search.py) · [Move admission](../inire/router/_astar_admission.py)
|
||||
8. **Consolidate direct-policy settings.** Define each direct policy's connectivity checks, lookahead, budget splitting, and unlocked probe in one internal table. Keep the attempt sequence and early exits explicit and preserve policies exposed by the benchmark CLI. [Direct and residual policies](../inire/router/_routing_policy.py)
|
||||
9. **Make automatic trial acceptance explicit.** Distinguish locally feasible candidates, whole-board validity, and eligibility to replace an incumbent. Preserve the rule that cost ranks alternatives with the same verified net IDs. Record when residual results are checked and when unresolved results are merged so stage metadata remains consistent. [Trial selection](../inire/router/_routing_policy.py) · [Automatic orchestration](../inire/router/_automatic.py)
|
||||
10. **Make capacity bounds independently testable.** Extract the cut-capacity calculation and the disjoint port-conflict check. State the geometry assumptions beside each bound and test when a bound applies separately from the policy decision to stop. Preserve reported cuts, conflict pairs, and routing targets. [Capacity and port checks](../inire/router/_automatic.py)
|
||||
11. **Separate topological planning from corridor construction.** Give endpoint access, mesh paths, lane assignments, and conversion to `Corridor` explicit internal boundaries. That lets lane-allocation tests exercise choices and tie-breaking independently of the lattice router. [Topological corridors](../inire/router/_topology.py)
|
||||
12. **Separate column scheduling from seed generation.** Distinguish opening and track assignment, feasible S-bend schedules, and the conversion of a schedule to seeds. Preserve candidate order and full-board verification. Exercise individual transition failures so new passage patterns can be tested in isolation. [Column planning](../inire/router/_columns.py)
|
||||
13. **Reuse verification details in final diagnostics.** Share final verification details with conflict and frontier reporting where they cover the same net population and installed geometry. Compare exact routes and trace payloads, then measure the change in verification calls and runtime. [Final verification and frontier capture](../inire/router/_router.py)
|
||||
|
||||
### Geometry and tooling cleanup
|
||||
|
||||
14. **Expose live raw static obstacles through `RoutingWorld`.** Give pair-local search and corridor setup an ordered iterator so both can use current obstacles, including obstacles added after problem creation. Keep index storage details inside the world. [Routing world](../inire/geometry/collision.py) · [Pair-local search](../inire/router/_pair_local.py)
|
||||
15. **Centralize cardinal coordinate transforms.** Share forward and lateral projection across the refiner, perimeter planner, and direct-route planner. Cover all four headings and leave snapping at its current points. [Port primitives](../inire/geometry/primitives.py) · [Refiner](../inire/router/refiner.py)
|
||||
16. **Move shared geometry helpers out of planner modules.** Give helpers such as exact S-bend spans a neutral home so compact routing can reuse them directly. Preserve exact integer spans for constructive routing and floating-point reach calculations for search. [Compact routing](../inire/router/_compact.py) · [Column planning](../inire/router/_columns.py)
|
||||
17. **Share component construction between seed replay and A*.** Reuse the mapping from move parameters to straight, 90-degree bend, and S-bend geometry. Preserve A* cache keys, handling of infeasible moves, and the geometry options applied during seed replay. [Seed materialization](../inire/router/_seed_materialization.py) · [Move admission](../inire/router/_astar_admission.py)
|
||||
18. **Name scoring objectives by purpose.** Make search cost, refinement cost, automatic trial ranking, and benchmark-weighted length clear in code and reports. Reuse the weighted-length calculation where it is identical and label native and benchmark costs explicitly. [Automatic scoring](../inire/router/_automatic.py) · [Benchmark reporting](../scripts/compare_topological_routing.py)
|
||||
19. **Share trace recorder boilerplate.** Reuse scenario selection, result summaries, command-line arguments, and artifact writing across conflict, frontier, pre-pair, and iteration recorders. Keep each report's renderer and schema in its own script. [Frontier recorder](../scripts/record_frontier_trace.py) · [Iteration recorder](../scripts/record_iteration_trace.py)
|
||||
20. **Keep fixtures and routing docs easy to maintain.** Organize large fixture modules by family while preserving stable case names and corpus order. Keep feasibility witnesses separate from timed inputs. Update the architecture map for pair-local search and label the original routing goal as a historical milestone. [Benchmark fixtures](../inire/tests/routing_benchmarks.py) · [Architecture](architecture.md) · [Original routing goal](routing-policy-goal.md)
|
||||
21. **Resolve the remaining lint findings.** Review and fix the reported issues in `inire` and `scripts`, including redundant comprehensions and long lines. Review suggested fixes individually where they touch search or benchmark behavior. [Lint configuration](../pyproject.toml)
|
||||
|
||||
## Future-looking
|
||||
|
||||
22. **Consider a common residual routing interface when a new recovery strategy needs it.** Identify which operations can be shared across direct locks, incumbent seeding, perimeter recovery, and pair-local search. Preserve their distinct roles for frozen obstacles, seed hints, and merge-time verification. [Residual policies](../inire/router/_routing_policy.py) · [Pair-local search](../inire/router/_pair_local.py)
|
||||
23. **Split collision queries further when profiling or geometry work identifies a reason.** Candidate lookup, exact overlap, and ray casting are possible boundaries. Compare clearance, boundary touches, physical and proxy geometry, and cache behavior before adopting a new split. [Collision queries](../inire/geometry/collision.py)
|
||||
24. **Revisit public option grouping with a compatibility plan.** Consider grouping planner settings or bend geometry when an API change is warranted. Account for legacy custom bend polygons and separate physical and proxy geometry. Handle changes to defaults, validation, and public names as explicit API decisions. [Public options](../inire/model.py)
|
||||
|
||||
## 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)
|
||||
|
||||
Capture the same cases and options from the baseline and the changed checkout, then compare them with the parity command. Its default capture uses `corpus-regression` (the 500-node, three-iteration pytest configuration) and `public-defaults`. Use `--profile matched-budget` for the original comparison CLI configuration. Use `--case` to select a case or group, `--callbacks` to add runs with live callbacks, and `--diagnostics` to capture detailed traces.
|
||||
|
||||
```sh
|
||||
python -m scripts.routing_benchmark_parity capture /tmp/routing-before.json
|
||||
python -m scripts.routing_benchmark_parity capture /tmp/routing-after.json
|
||||
python -m scripts.routing_benchmark_parity compare /tmp/routing-before.json /tmp/routing-after.json
|
||||
```
|
||||
|
||||
### Refactor validation
|
||||
|
||||
The 134 corpus runs matched the baseline exactly. In 20 runs with diagnostics enabled, the routes, costs, stage metadata, traces, and callback results also matched. Reusing final verification details eliminated 172 path verification calls, 524 static buffer operations, and 48 dynamic candidate-net checks across those diagnostic runs.
|
||||
|
||||
On a 32-net seeded straight-route layout with conflict and frontier diagnostics enabled, verification calls fell from 224 to 160 and median routing time fell from 19.05 ms to 15.28 ms. Each checkout ran 27 measured samples in alternating batches after warmup. The corpus timing totals stayed close at 105.04 s before and 105.74 s after, measured as the sum of individual runs.
|
||||
|
|
@ -239,6 +239,8 @@ python -m scripts.compare_topological_routing --profile public-defaults \
|
|||
|
||||
`--profile matched-budget` is the default CLI profile. It uses the configured common budget and iteration count and retains the benchmark weights for automatic candidate selection. Use it for controlled mode and policy comparisons. Automatic rows print median elapsed time by operation, with individual timings and the planner, mode, and retry policy in JSON. [Report fields](../DOCS.md#automatic-routing)
|
||||
|
||||
Use `--profile corpus-regression --case corpus` to reproduce the pytest configuration with 500 search nodes, 500 seed nodes, and three congestion iterations. The comparison reports both benchmark-weighted length (`valid_costs` in JSON) and the native objective (`native_valid_costs`) for verified nets. The native objective uses the run's length, bend, and danger weights. The profile also controls which cost automatic routing uses to rank candidates. [Exact parity command](routing-refactor-plan.md#verification)
|
||||
|
||||
One full-corpus run per profile verified 384/388 nets and completed 55/57 boards. Both profiles matched the baseline net IDs and geometric bounds on every board. In the matched-budget run at 500 nodes and three congestion iterations, fixed-heading Terminal-Bench spent 10.42 of 10.60 seconds in refinement and used zero A* expansions. The staggered crossing grid spent 10.00 of 10.08 seconds in search.
|
||||
|
||||
### Refinement and early guide experiments
|
||||
|
|
@ -327,6 +329,8 @@ Four bend-first windows are now the default. A full comparison against the 24-wi
|
|||
|
||||
Trying column jogs before the near-port probe reproduced exact paths and costs on all 67 boards in both profiles. On the alternating doglegs, width-key passage, and split-merge passage, the new order reduced A* expansions from 3,300, 7,200, and 7,200 to zero under public defaults. The earlier constructive planners still run first.
|
||||
|
||||
Trying the residual dogleg as soon as the near-port probe left one net unfinished reproduced exact paths, costs, and routing bounds on all 67 boards in both profiles. For the straight decoy, public-default search fell from 13,200 to 1,200 A* expansions and elapsed time fell from 5.47 to 0.67 seconds in the corpus sweeps. At the matched budget, expansions fell from 5,500 to 500 and elapsed time fell from 3.69 to 0.41 seconds.
|
||||
|
||||
### External and fallback benchmarks
|
||||
|
||||
`--case external` runs six fixed-placement problems from two public sources. The fixtures preserve net IDs and device locations, with optical ports snapped to a 0.1 µm lattice and expressed relative to the imported board. Device boxes become obstacles with outward access cutouts at the selected ports. The timed runs start from empty initial paths. The converted inputs are checked into the repo so benchmark runs work offline. [Fixture data](../inire/tests/data/external_routing_benchmarks.json)
|
||||
|
|
@ -382,6 +386,99 @@ python -m scripts.compare_topological_routing --case all --case broad --mode aut
|
|||
--nodes 173 --seed-nodes 173 --iterations 3 --json /tmp/inire-budget-173.json
|
||||
```
|
||||
|
||||
### Earlier lattice and incumbent retries
|
||||
|
||||
The opt-in `lattice-1500` policy tries lattice routing before seed recovery when the near-port and lookahead searches stop at the same verified set, one net short. It requires a configured ceiling of at least 1,500 nodes. On the return shelf, early caps of 500, 750, and 1,000 spent extra work before the usual fallback completed the board. The 1,500- and 2,000-node retries both completed it with the same paths and expansion count.
|
||||
|
||||
The opt-in `recover-near-port` policy tries locked incumbent recovery before the second direct search when the first has verified at least two thirds of the nets and leaves at most two unresolved. The recovery uses at most 500 nodes per search and two congestion iterations. The direct retry is skipped once recovery verifies the complete layout. The `recover-lookahead` variant applies the same idea one net short during the wider split-budget attempt. Both worked on the crossing detour, with near-port recovery completing earlier. [Retry benchmark driver](../scripts/benchmark_retry_order.py)
|
||||
|
||||
The full sweep ran the baseline and four experimental policies over all 67 boards under public defaults and corpus-regression settings, with three interleaved repeats per case and policy. All policies preserved the same verified net IDs, path seeds, and per-net benchmark and native costs. Each reached every board's bound and verified 433/437 nets in both profiles. The combined policy changed search stages only on the return shelf and crossing detour. The splitter tree kept the same stages and expansion count.
|
||||
|
||||
| Case and profile | Baseline median | Combined median | Baseline to combined expansions |
|
||||
| --- | ---: | ---: | ---: |
|
||||
| Return shelf, public defaults | 10.04 s | 4.34 s | 21,199 → 8,399 |
|
||||
| Crossing detour, public defaults | 5.67 s | 0.86 s | 11,373 → 1,370 |
|
||||
| Crossing detour, corpus regression | 5.12 s | 0.85 s | 5,959 → 839 |
|
||||
|
||||
| Profile | Baseline to combined median | Baseline to combined p95 | Baseline to combined sum of medians |
|
||||
| --- | ---: | ---: | ---: |
|
||||
| Public defaults | 0.370 → 0.369 s | 3.94 → 2.33 s | 55.13 → 44.57 s |
|
||||
| Corpus regression | 0.181 → 0.180 s | 2.49 → 2.26 s | 36.00 → 31.74 s |
|
||||
|
||||
The corpus percentile and sum are calculated over the 67 board medians.
|
||||
|
||||
```sh
|
||||
python -m scripts.benchmark_retry_order --case corpus \
|
||||
--policy baseline --policy lattice-1500 --policy recover-lookahead \
|
||||
--policy recover-near-port --policy lattice-1500-and-recover-near-port \
|
||||
--repeat 3 --jobs 6 --json /tmp/inire-retry-order.json
|
||||
```
|
||||
|
||||
#### Retry holdouts
|
||||
|
||||
The `retry-holdout` group contains ten unseeded layouts with 63 nets across three families. The return shelves vary the wall and return bay. The crossing detours vary the floor keepout, outer bypass, and port headings. The competing trunks test straight locks against perpendicular branches. Separate waypoint witnesses establish that all ten layouts are feasible. The 67-board regression corpus keeps its original membership. [Holdout fixtures](../inire/tests/retry_holdout_benchmarks.py)
|
||||
|
||||
The baseline verified 60/63 nets under public defaults and 59/63 under the 500-node corpus-regression profile. Both retry policies verified exactly the same net IDs in both profiles. Each row aggregates three interleaved repeats into per-board medians. The p95 equals the slowest board median in this ten-board sample. Failed retry time is the sum of time spent inside the unsuccessful retries, with one median per affected board.
|
||||
|
||||
| Profile and policy | Median / p95 across boards | Sum of board medians | Completed / failed early retries | Time / expansions spent on failed retries |
|
||||
| --- | ---: | ---: | ---: | ---: |
|
||||
| Public defaults, baseline | 7.00 / 33.37 s | 92.50 s | — | — |
|
||||
| Public defaults, `lattice-1500` | 4.61 / 33.40 s | 91.54 s | 1 / 4 | 9.79 s / 5,398 |
|
||||
| Public defaults, `recover-near-port` | 5.74 / 30.58 s | 86.11 s | 2 / 1 | 1.51 s / 2,000 |
|
||||
| Corpus regression, baseline | 4.88 / 12.97 s | 50.54 s | — | — |
|
||||
| Corpus regression, `recover-near-port` | 4.86 / 12.44 s | 49.56 s | 1 / 2 | 3.48 s / 4,338 |
|
||||
|
||||
Keep both experiments opt-in. `lattice-1500` cut the stepped-roof median from 11.00 s to 3.88 s with identical paths. It failed on four of the five boards where it ran. The corpus-regression ceiling of 500 nodes prevented it from running in that profile. Near-port recovery cut the public floor-pocket median from 4.67 s to 0.77 s with identical paths. On stretched crossings it cut the median from 1.46 s to 0.71 s and increased the cost of `outside_lower` from 1,097.65 to 1,107.65 by the weighted benchmark and from 1,432.12 to 1,437.77 by the native objective. All other per-net costs matched.
|
||||
|
||||
```sh
|
||||
python -m scripts.benchmark_retry_order --case retry-holdout \
|
||||
--policy baseline --policy lattice-1500 --policy recover-near-port \
|
||||
--repeat 3 --jobs 6 --json /tmp/inire-retry-holdout.json
|
||||
```
|
||||
|
||||
#### Splitter tree probe budget
|
||||
|
||||
The public near-port probe spent its last seven congestion iterations retrying the same four unresolved nets at 16 expansions each and stayed at 2/6. The lookahead retry spent another 475 expansions on negotiated iterations, reached 4/6, and supplied the paths that let ordinary incumbent recovery complete the layout.
|
||||
|
||||
| Profile | Baseline | One probe iteration | Two probe iterations |
|
||||
| --- | ---: | ---: | ---: |
|
||||
| Public defaults | 5.76 s / 5,764 expansions | 5.08 s / 4,436 | 5.38 s / 4,875 |
|
||||
| Corpus regression | 4.16 s / 4,689 expansions | 3.78 s / 4,057 | 4.00 s / 4,389 |
|
||||
|
||||
The splitter tree verified all six nets with identical paths and costs in three interleaved repeats of each policy. The one-iteration cap also verified the same net IDs across all 67 regression boards in both profiles. On `crossing-obstructed-approaches` under public defaults, it increased the weighted cost of `x0.e->south-east` by 872.96 and its native cost by 478.21.
|
||||
|
||||
The two-iteration cap preserved exact paths on all 77 boards in both profiles. The 67-board sweep reduced public-default expansions from 59,695 to 46,066 (23%) and corpus-regression expansions from 30,093 to 27,743 (8%). The ten holdouts ran twice per policy. Expansions fell from 121,941 to 109,549 (10%) under public defaults and from 71,761 to 69,511 (3%) under corpus regression. This comparison applies to the initial probe only. The lookahead and incumbent stages retain their existing budgets.
|
||||
|
||||
```sh
|
||||
python -m scripts.benchmark_retry_order --case pic-splitter-tree-1x8-ew \
|
||||
--policy baseline --policy probe-iterations-1 --policy probe-iterations-2 --policy probe-iterations-3 \
|
||||
--repeat 3 --jobs 2 --json /tmp/inire-splitter-probe.json
|
||||
```
|
||||
|
||||
#### Wider search for one unresolved net
|
||||
|
||||
The three public-default holdouts that stopped one net short still had connected residuals with the verified paths locked. Raising the residual search and corridor seed limits let the router finish with those exact paths. The experiment freezes the incumbents, uses at most two congestion iterations for the remaining net, and verifies the merged layout before it can win. Timed runs start with no supplied paths.
|
||||
|
||||
| When the residual budget rises | Verified nets | Fully routed boards | Sum of public-default board times |
|
||||
| --- | ---: | ---: | ---: |
|
||||
| Baseline for the early sweep | 60/63 | 7/10 | 100.12 s |
|
||||
| Before the remaining fallbacks, 1,500 nodes | 62/63 | 9/10 | 104.75 s |
|
||||
| Before the remaining fallbacks, 3,000 nodes | 63/63 | 10/10 | 75.02 s |
|
||||
| Baseline for the late sweep | 60/63 | 7/10 | 87.57 s |
|
||||
| After the ordinary fallbacks, 3,000 nodes | 63/63 | 10/10 | 90.55 s |
|
||||
|
||||
The early sweeps used medians of three repeats. Early 3,000-node recovery changed `fold` on deep roof by +6.44 weighted cost and −226.61 native cost. It also spent 11,000 expansions on a failed stepped-roof attempt. On the 67-board public-default corpus it added 10,025 expansions to the original return shelf and the existing fallback supplied the same result.
|
||||
|
||||
The late sweep ran once across all ten holdouts. Its three retries added 3,881 expansions and preserved every baseline path. The two crossing boards also completed 9/9 in two additional runs each. The seven already complete holdouts kept their exact search stages and expansion counts. Across the original corpus, all 134 case/profile results matched the baseline and the late retry never ran. Keep the escalation opt-in while testing more one-net misses. The existing residual search and verification functions were enough to run this experiment.
|
||||
|
||||
```sh
|
||||
python -m scripts.benchmark_retry_order --case retry-holdout --profile public-defaults \
|
||||
--policy baseline --policy residual-1500 --policy residual-3000 \
|
||||
--repeat 3 --jobs 6 --json /tmp/inire-wider-residual.json
|
||||
python -m scripts.benchmark_retry_order --case retry-holdout --profile public-defaults \
|
||||
--policy baseline --policy late-residual-3000 --jobs 5 --json /tmp/inire-late-residual.json
|
||||
```
|
||||
|
||||
### Selective column scoring
|
||||
|
||||
All three column policies verified the same 335 net IDs across three repeats at 200 nodes per attempt. The cost totals sum one run across all 53 boards. Runtime statistics pool the three runs per board. The column-board median uses the 21 boards where span scoring produced a column candidate.
|
||||
|
|
|
|||
|
|
@ -23,6 +23,9 @@ if TYPE_CHECKING:
|
|||
from inire.geometry.primitives import Port
|
||||
|
||||
|
||||
_RAY_CAST_CACHE_LIMIT = 8192
|
||||
|
||||
|
||||
def _intersection_distance(origin: Port, geometry: BaseGeometry) -> float:
|
||||
if hasattr(geometry, "geoms"):
|
||||
return min(_intersection_distance(origin, sub_geometry) for sub_geometry in geometry.geoms)
|
||||
|
|
@ -103,6 +106,10 @@ class RoutingWorld:
|
|||
def get_static_version(self) -> int:
|
||||
return self._static_obstacles.version
|
||||
|
||||
def iter_static_geometries(self) -> Iterable[Polygon]:
|
||||
"""Iterate over the current raw obstacles in insertion order."""
|
||||
return self._static_obstacles.geometries.values()
|
||||
|
||||
def iter_static_dilated_geometries(self) -> Iterable[Polygon]:
|
||||
return self._static_obstacles.dilated.values()
|
||||
|
||||
|
|
@ -777,6 +784,31 @@ class RoutingWorld:
|
|||
self.metrics.total_ray_cast_calls_visibility_tangent += 1
|
||||
else:
|
||||
self.metrics.total_ray_cast_calls_other += 1
|
||||
|
||||
# Static obstacle changes clear these results along with the trees.
|
||||
cache = self._static_obstacles.ray_cast_cache
|
||||
# Equal NumPy and Python scalars can produce different ray geometry.
|
||||
key = (
|
||||
origin.x, origin.y, angle_deg, max_dist, net_width, self.clearance,
|
||||
type(angle_deg), type(max_dist), type(net_width), type(self.clearance),
|
||||
)
|
||||
reach = cache.get(key)
|
||||
if reach is not None:
|
||||
return reach
|
||||
|
||||
reach = self._cast_static_ray(origin, angle_deg, max_dist, net_width)
|
||||
if len(cache) >= _RAY_CAST_CACHE_LIMIT:
|
||||
cache.clear()
|
||||
cache[key] = reach
|
||||
return reach
|
||||
|
||||
def _cast_static_ray(
|
||||
self,
|
||||
origin: Port,
|
||||
angle_deg: float,
|
||||
max_dist: float,
|
||||
net_width: float | None,
|
||||
) -> float:
|
||||
static_obstacles = self._static_obstacles
|
||||
tree: STRtree | None
|
||||
is_rect_array: numpy.ndarray | None
|
||||
|
|
|
|||
|
|
@ -91,16 +91,30 @@ class ComponentResult:
|
|||
return self._total_dilated_bounds
|
||||
|
||||
def translate(self, dx: int | float, dy: int | float) -> ComponentResult:
|
||||
# The collision and physical views often reference the same polygons.
|
||||
translated: dict[int, Polygon] = {}
|
||||
|
||||
def translate_geometry(polygons: Sequence[Polygon]) -> tuple[Polygon, ...]:
|
||||
geometry = []
|
||||
for polygon in polygons:
|
||||
key = id(polygon)
|
||||
shifted = translated.get(key)
|
||||
if shifted is None:
|
||||
shifted = shapely_translate(polygon, dx, dy)
|
||||
translated[key] = shifted
|
||||
geometry.append(shifted)
|
||||
return tuple(geometry)
|
||||
|
||||
return ComponentResult(
|
||||
start_port=self.start_port.translate(dx, dy),
|
||||
collision_geometry=[shapely_translate(poly, dx, dy) for poly in self.collision_geometry],
|
||||
collision_geometry=translate_geometry(self.collision_geometry),
|
||||
end_port=self.end_port.translate(dx, dy),
|
||||
length=self.length,
|
||||
move_type=self.move_type,
|
||||
move_spec=self.move_spec,
|
||||
physical_geometry=[shapely_translate(poly, dx, dy) for poly in self.physical_geometry],
|
||||
dilated_collision_geometry=[shapely_translate(poly, dx, dy) for poly in self.dilated_collision_geometry],
|
||||
dilated_physical_geometry=[shapely_translate(poly, dx, dy) for poly in self.dilated_physical_geometry],
|
||||
physical_geometry=translate_geometry(self.physical_geometry),
|
||||
dilated_collision_geometry=translate_geometry(self.dilated_collision_geometry),
|
||||
dilated_physical_geometry=translate_geometry(self.dilated_physical_geometry),
|
||||
)
|
||||
|
||||
|
||||
|
|
@ -486,3 +500,27 @@ class SBend:
|
|||
dilated_collision_geometry=dilated_collision_geometry,
|
||||
dilated_physical_geometry=dilated_physical_geometry,
|
||||
)
|
||||
|
||||
|
||||
def build_component(
|
||||
start: Port,
|
||||
width: float,
|
||||
kind: MoveKind,
|
||||
parameters: tuple,
|
||||
*,
|
||||
collision_type: BendCollisionModel,
|
||||
physical_geometry_type: BendPhysicalGeometry,
|
||||
clip_margin: float | None,
|
||||
dilation: float,
|
||||
) -> ComponentResult:
|
||||
if kind == "straight":
|
||||
return Straight.generate(start, parameters[0], width, dilation=dilation)
|
||||
if kind == "bend90":
|
||||
return Bend90.generate(
|
||||
start, parameters[0], width, parameters[1],
|
||||
collision_type=collision_type, physical_geometry_type=physical_geometry_type, clip_margin=clip_margin, dilation=dilation,
|
||||
)
|
||||
return SBend.generate(
|
||||
start, parameters[0], parameters[1], width,
|
||||
collision_type=collision_type, physical_geometry_type=physical_geometry_type, clip_margin=clip_margin, dilation=dilation,
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from contextlib import suppress
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import numpy
|
||||
|
|
@ -153,10 +154,8 @@ class DynamicPathIndex:
|
|||
for cell in cells:
|
||||
obj_ids = self.grid.get(cell)
|
||||
if obj_ids is not None:
|
||||
try:
|
||||
with suppress(ValueError):
|
||||
obj_ids.remove(obj_id)
|
||||
except ValueError:
|
||||
pass
|
||||
if not obj_ids:
|
||||
self.grid.pop(cell, None)
|
||||
net_obj_ids = self.grid_net_obj_ids.get(cell)
|
||||
|
|
|
|||
17
inire/geometry/intervals.py
Normal file
17
inire/geometry/intervals.py
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
"""Intervals left open by solid spans."""
|
||||
|
||||
Gap = tuple[float, float]
|
||||
|
||||
|
||||
def open_intervals(solid: list[Gap], ymin: float, ymax: float) -> tuple[Gap, ...]:
|
||||
openings = []
|
||||
cursor = ymin
|
||||
for bottom, top in sorted(solid):
|
||||
if top <= ymin or bottom >= ymax:
|
||||
continue
|
||||
if cursor < bottom:
|
||||
openings.append((cursor, bottom))
|
||||
cursor = max(cursor, top)
|
||||
if cursor < ymax:
|
||||
openings.append((cursor, ymax))
|
||||
return tuple(openings)
|
||||
|
|
@ -63,3 +63,20 @@ ROT2_270 = numpy.array(((0, 1), (-1, 0)), dtype=numpy.int32)
|
|||
def rotation_matrix2(rotation_deg: int | float) -> NDArray[numpy.int32]:
|
||||
quadrant = (_normalize_angle(rotation_deg) // 90) % 4
|
||||
return (ROT2_0, ROT2_90, ROT2_180, ROT2_270)[quadrant]
|
||||
|
||||
|
||||
def rotate_cardinal(x: float, y: float, heading: int) -> tuple[float, float]:
|
||||
"""Rotate by a multiple of 90 degrees without snapping the point."""
|
||||
angle = heading % 360
|
||||
if angle == 0:
|
||||
return x, y
|
||||
if angle == 90:
|
||||
return -y, x
|
||||
if angle == 180:
|
||||
return -x, -y
|
||||
return y, -x
|
||||
|
||||
|
||||
def port_local_coordinates(origin: Port, x: float, y: float) -> tuple[float, float]:
|
||||
"""Project a point into the forward and leftward axes of a port."""
|
||||
return rotate_cardinal(x - origin.x, y - origin.y, -int(origin.r))
|
||||
|
|
|
|||
14
inire/geometry/sbend.py
Normal file
14
inire/geometry/sbend.py
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
"""Exact S-bend dimensions for constructive planners."""
|
||||
|
||||
from math import isqrt
|
||||
|
||||
|
||||
def exact_sbend_spans(radius: int) -> dict[int, int]:
|
||||
"""Map lateral offsets to their positive integer spans for a fixed radius."""
|
||||
spans = {}
|
||||
for offset in range(1, 2 * radius):
|
||||
squared = offset * (4 * radius - offset)
|
||||
span = isqrt(squared)
|
||||
if span * span == squared:
|
||||
spans[offset] = span
|
||||
return spans
|
||||
|
|
@ -30,6 +30,7 @@ class StaticObstacleIndex:
|
|||
"net_specific_trees",
|
||||
"net_specific_is_rect",
|
||||
"net_specific_bounds",
|
||||
"ray_cast_cache",
|
||||
"id_counter",
|
||||
"version",
|
||||
)
|
||||
|
|
@ -49,6 +50,7 @@ class StaticObstacleIndex:
|
|||
self.net_specific_trees: dict[tuple[float, float], STRtree] = {}
|
||||
self.net_specific_is_rect: dict[tuple[float, float], numpy.ndarray] = {}
|
||||
self.net_specific_bounds: dict[tuple[float, float], numpy.ndarray] = {}
|
||||
self.ray_cast_cache: dict[tuple[float, float, float, float, float | None, float, type, type, type, type], float] = {}
|
||||
self.id_counter = 0
|
||||
self.version = 0
|
||||
|
||||
|
|
@ -89,6 +91,7 @@ class StaticObstacleIndex:
|
|||
self.net_specific_trees.clear()
|
||||
self.net_specific_is_rect.clear()
|
||||
self.net_specific_bounds.clear()
|
||||
self.ray_cast_cache.clear()
|
||||
self.version += 1
|
||||
|
||||
def ensure_tree(self) -> None:
|
||||
|
|
|
|||
|
|
@ -1,11 +1,13 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from dataclasses import dataclass, field, fields
|
||||
from typing import TYPE_CHECKING, Literal
|
||||
|
||||
from inire.seeds import PathSeed
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterable
|
||||
|
||||
from shapely.geometry import Polygon
|
||||
|
||||
from inire.geometry.components import ComponentResult
|
||||
|
|
@ -235,6 +237,11 @@ class RouteMetrics:
|
|||
late_phase_capped_fallbacks: int
|
||||
|
||||
|
||||
def _sum_route_metrics(samples: Iterable[RouteMetrics]) -> RouteMetrics:
|
||||
runs = tuple(samples)
|
||||
return RouteMetrics(*(sum(getattr(run, metric.name) for run in runs) for metric in fields(RouteMetrics)))
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class RoutingResult:
|
||||
net_id: str
|
||||
|
|
|
|||
|
|
@ -6,14 +6,15 @@ from typing import TYPE_CHECKING
|
|||
from shapely.geometry import Polygon
|
||||
|
||||
from inire.constants import TOLERANCE_LINEAR
|
||||
from inire.geometry.components import Bend90, SBend, Straight, MoveKind
|
||||
from inire.geometry.components import build_component
|
||||
from inire.geometry.primitives import Port
|
||||
from inire.router.refiner import component_hits_ancestor_chain
|
||||
|
||||
from ._astar_types import AStarContext, AStarMetrics, AStarNode, SearchRunConfig
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from inire.geometry.components import ComponentResult
|
||||
from inire.geometry.components import ComponentResult, MoveKind
|
||||
from ._astar_types import CongestionCaches
|
||||
|
||||
|
||||
def process_move(
|
||||
|
|
@ -25,12 +26,7 @@ def process_move(
|
|||
closed_set: dict[tuple[int, int, int], float],
|
||||
context: AStarContext,
|
||||
metrics: AStarMetrics,
|
||||
congestion_cache: dict[tuple, int],
|
||||
congestion_presence_cache: dict[tuple[str, int, int, int, int], bool],
|
||||
congestion_candidate_precheck_cache: dict[tuple[str, int, int, int, int], bool],
|
||||
congestion_net_envelope_cache: dict[tuple[str, int, int, int, int], tuple[str, ...]],
|
||||
congestion_grid_net_cache: dict[tuple[str, int, int, int, int], tuple[str, ...]],
|
||||
congestion_grid_span_cache: dict[tuple[str, int, int, int, int], dict[str, tuple[int, ...]]],
|
||||
congestion: CongestionCaches,
|
||||
config: SearchRunConfig,
|
||||
move_class: MoveKind,
|
||||
params: tuple,
|
||||
|
|
@ -73,27 +69,13 @@ def process_move(
|
|||
else:
|
||||
context.metrics.total_move_cache_rel_misses += 1
|
||||
try:
|
||||
if move_class == "straight":
|
||||
res_rel = Straight.generate(base_port, params[0], net_width, dilation=self_dilation)
|
||||
elif move_class == "bend90":
|
||||
res_rel = Bend90.generate(
|
||||
res_rel = build_component(
|
||||
base_port,
|
||||
params[0],
|
||||
net_width,
|
||||
params[1],
|
||||
move_class,
|
||||
params,
|
||||
collision_type=coll_type,
|
||||
physical_geometry_type=config.bend_physical_geometry,
|
||||
clip_margin=config.bend_clip_margin,
|
||||
dilation=self_dilation,
|
||||
)
|
||||
else:
|
||||
res_rel = SBend.generate(
|
||||
base_port,
|
||||
params[0],
|
||||
params[1],
|
||||
net_width,
|
||||
collision_type=coll_type,
|
||||
physical_geometry_type=config.bend_physical_geometry,
|
||||
physical_geometry_type=physical_type,
|
||||
clip_margin=config.bend_clip_margin,
|
||||
dilation=self_dilation,
|
||||
)
|
||||
|
|
@ -113,12 +95,7 @@ def process_move(
|
|||
closed_set,
|
||||
context,
|
||||
metrics,
|
||||
congestion_cache,
|
||||
congestion_presence_cache,
|
||||
congestion_candidate_precheck_cache,
|
||||
congestion_net_envelope_cache,
|
||||
congestion_grid_net_cache,
|
||||
congestion_grid_span_cache,
|
||||
congestion,
|
||||
config,
|
||||
move_class,
|
||||
abs_key,
|
||||
|
|
@ -135,12 +112,7 @@ def add_node(
|
|||
closed_set: dict[tuple[int, int, int], float],
|
||||
context: AStarContext,
|
||||
metrics: AStarMetrics,
|
||||
congestion_cache: dict[tuple, int],
|
||||
congestion_presence_cache: dict[tuple[str, int, int, int, int], bool],
|
||||
congestion_candidate_precheck_cache: dict[tuple[str, int, int, int, int], bool],
|
||||
congestion_net_envelope_cache: dict[tuple[str, int, int, int, int], tuple[str, ...]],
|
||||
congestion_grid_net_cache: dict[tuple[str, int, int, int, int], tuple[str, ...]],
|
||||
congestion_grid_span_cache: dict[tuple[str, int, int, int, int], dict[str, tuple[int, ...]]],
|
||||
congestion: CongestionCaches,
|
||||
config: SearchRunConfig,
|
||||
move_type: MoveKind,
|
||||
cache_key: tuple,
|
||||
|
|
@ -252,27 +224,27 @@ def add_node(
|
|||
total_overlaps = 0
|
||||
if not config.skip_congestion and context.cost_evaluator.collision_engine.has_dynamic_paths():
|
||||
ce = context.cost_evaluator.collision_engine
|
||||
if ce.has_possible_move_congestion(result, net_id, congestion_presence_cache):
|
||||
if ce.has_possible_move_congestion(result, net_id, congestion.presence):
|
||||
if ce.has_candidate_move_congestion(
|
||||
result,
|
||||
net_id,
|
||||
congestion_candidate_precheck_cache,
|
||||
congestion_net_envelope_cache,
|
||||
congestion_grid_net_cache,
|
||||
congestion.candidate_precheck,
|
||||
congestion.net_envelopes,
|
||||
congestion.grid_nets,
|
||||
):
|
||||
if cache_key in congestion_cache:
|
||||
if cache_key in congestion.overlaps:
|
||||
context.metrics.total_congestion_cache_hits += 1
|
||||
total_overlaps = congestion_cache[cache_key]
|
||||
total_overlaps = congestion.overlaps[cache_key]
|
||||
else:
|
||||
context.metrics.total_congestion_cache_misses += 1
|
||||
total_overlaps = ce.check_move_congestion(
|
||||
result,
|
||||
net_id,
|
||||
net_envelope_cache=congestion_net_envelope_cache,
|
||||
grid_net_cache=congestion_grid_net_cache,
|
||||
broad_phase_cache=congestion_grid_span_cache,
|
||||
net_envelope_cache=congestion.net_envelopes,
|
||||
grid_net_cache=congestion.grid_nets,
|
||||
broad_phase_cache=congestion.grid_spans,
|
||||
)
|
||||
congestion_cache[cache_key] = total_overlaps
|
||||
congestion.overlaps[cache_key] = total_overlaps
|
||||
else:
|
||||
context.metrics.total_congestion_candidate_precheck_skips += 1
|
||||
else:
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ from ._astar_admission import process_move
|
|||
if TYPE_CHECKING:
|
||||
from inire.geometry.components import MoveKind
|
||||
from inire.geometry.primitives import Port
|
||||
from ._astar_types import AStarContext, AStarMetrics, AStarNode, SearchRunConfig
|
||||
from ._astar_types import AStarContext, AStarMetrics, AStarNode, CongestionCaches, SearchRunConfig
|
||||
|
||||
|
||||
def _quantized_lengths(values: list[float], max_reach: float) -> list[int]:
|
||||
|
|
@ -165,12 +165,7 @@ def expand_moves(
|
|||
closed_set: dict[tuple[int, int, int], float],
|
||||
context: AStarContext,
|
||||
metrics: AStarMetrics,
|
||||
congestion_cache: dict[tuple, int],
|
||||
congestion_presence_cache: dict[tuple[str, int, int, int, int], bool],
|
||||
congestion_candidate_precheck_cache: dict[tuple[str, int, int, int, int], bool],
|
||||
congestion_net_envelope_cache: dict[tuple[str, int, int, int, int], tuple[str, ...]],
|
||||
congestion_grid_net_cache: dict[tuple[str, int, int, int, int], tuple[str, ...]],
|
||||
congestion_grid_span_cache: dict[tuple[str, int, int, int, int], dict[str, tuple[int, ...]]],
|
||||
congestion: CongestionCaches,
|
||||
config: SearchRunConfig,
|
||||
) -> None:
|
||||
search_options = context.options.search
|
||||
|
|
@ -214,12 +209,7 @@ def expand_moves(
|
|||
closed_set,
|
||||
context,
|
||||
metrics,
|
||||
congestion_cache,
|
||||
congestion_presence_cache,
|
||||
congestion_candidate_precheck_cache,
|
||||
congestion_net_envelope_cache,
|
||||
congestion_grid_net_cache,
|
||||
congestion_grid_span_cache,
|
||||
congestion,
|
||||
config,
|
||||
"straight",
|
||||
(int(round(proj_t)),),
|
||||
|
|
@ -292,12 +282,7 @@ def expand_moves(
|
|||
closed_set,
|
||||
context,
|
||||
metrics,
|
||||
congestion_cache,
|
||||
congestion_presence_cache,
|
||||
congestion_candidate_precheck_cache,
|
||||
congestion_net_envelope_cache,
|
||||
congestion_grid_net_cache,
|
||||
congestion_grid_span_cache,
|
||||
congestion,
|
||||
config,
|
||||
"straight",
|
||||
(length,),
|
||||
|
|
@ -325,12 +310,7 @@ def expand_moves(
|
|||
closed_set,
|
||||
context,
|
||||
metrics,
|
||||
congestion_cache,
|
||||
congestion_presence_cache,
|
||||
congestion_candidate_precheck_cache,
|
||||
congestion_net_envelope_cache,
|
||||
congestion_grid_net_cache,
|
||||
congestion_grid_span_cache,
|
||||
congestion,
|
||||
config,
|
||||
"bend90",
|
||||
(radius, direction),
|
||||
|
|
@ -365,12 +345,7 @@ def expand_moves(
|
|||
closed_set,
|
||||
context,
|
||||
metrics,
|
||||
congestion_cache,
|
||||
congestion_presence_cache,
|
||||
congestion_candidate_precheck_cache,
|
||||
congestion_net_envelope_cache,
|
||||
congestion_grid_net_cache,
|
||||
congestion_grid_span_cache,
|
||||
congestion,
|
||||
config,
|
||||
"sbend",
|
||||
(offset, radius),
|
||||
|
|
|
|||
|
|
@ -1,7 +1,8 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import TYPE_CHECKING
|
||||
from operator import attrgetter
|
||||
from typing import TYPE_CHECKING, get_type_hints
|
||||
|
||||
from inire.model import resolve_bend_geometry
|
||||
from inire.results import RouteMetrics
|
||||
|
|
@ -60,6 +61,21 @@ class FrontierTraceCollector:
|
|||
self.samples.append((reason, move_type, hotspot_index, parent_state, end_state))
|
||||
|
||||
|
||||
_CongestionLocation = tuple[str, int, int, int, int]
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class CongestionCaches:
|
||||
"""Congestion queries cached for one A* search of a single net."""
|
||||
|
||||
overlaps: dict[tuple, int] = field(default_factory=dict)
|
||||
presence: dict[_CongestionLocation, bool] = field(default_factory=dict)
|
||||
candidate_precheck: dict[_CongestionLocation, bool] = field(default_factory=dict)
|
||||
net_envelopes: dict[_CongestionLocation, tuple[str, ...]] = field(default_factory=dict)
|
||||
grid_nets: dict[_CongestionLocation, tuple[str, ...]] = field(default_factory=dict)
|
||||
grid_spans: dict[_CongestionLocation, dict[str, tuple[int, ...]]] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class SearchRunConfig:
|
||||
bend_collision_type: BendCollisionModel
|
||||
|
|
@ -173,460 +189,31 @@ class AStarNode:
|
|||
return self.fh_cost < other.fh_cost
|
||||
|
||||
|
||||
class AStarMetrics:
|
||||
__slots__ = (
|
||||
"total_nodes_expanded",
|
||||
"total_moves_generated",
|
||||
"total_moves_added",
|
||||
"total_pruned_closed_set",
|
||||
"total_pruned_hard_collision",
|
||||
"total_pruned_cost",
|
||||
"total_route_iterations",
|
||||
"total_nets_routed",
|
||||
"total_nets_reached_target",
|
||||
"total_warm_start_paths_built",
|
||||
"total_warm_start_paths_used",
|
||||
"total_refine_path_calls",
|
||||
"total_timeout_events",
|
||||
"total_iteration_reverify_calls",
|
||||
"total_iteration_reverified_nets",
|
||||
"total_iteration_conflicting_nets",
|
||||
"total_iteration_conflict_edges",
|
||||
"total_nets_carried_forward",
|
||||
"total_score_component_calls",
|
||||
"total_score_component_total_ns",
|
||||
"total_path_cost_calls",
|
||||
"total_danger_map_lookup_calls",
|
||||
"total_danger_map_cache_hits",
|
||||
"total_danger_map_cache_misses",
|
||||
"total_danger_map_query_calls",
|
||||
"total_danger_map_total_ns",
|
||||
"total_move_cache_abs_hits",
|
||||
"total_move_cache_abs_misses",
|
||||
"total_move_cache_rel_hits",
|
||||
"total_move_cache_rel_misses",
|
||||
"total_guidance_match_moves",
|
||||
"total_guidance_match_moves_straight",
|
||||
"total_guidance_match_moves_bend90",
|
||||
"total_guidance_match_moves_sbend",
|
||||
"total_guidance_bonus_applied",
|
||||
"total_guidance_bonus_applied_straight",
|
||||
"total_guidance_bonus_applied_bend90",
|
||||
"total_guidance_bonus_applied_sbend",
|
||||
"total_static_safe_cache_hits",
|
||||
"total_hard_collision_cache_hits",
|
||||
"total_congestion_cache_hits",
|
||||
"total_congestion_cache_misses",
|
||||
"total_congestion_presence_cache_hits",
|
||||
"total_congestion_presence_cache_misses",
|
||||
"total_congestion_presence_skips",
|
||||
"total_congestion_candidate_precheck_hits",
|
||||
"total_congestion_candidate_precheck_misses",
|
||||
"total_congestion_candidate_precheck_skips",
|
||||
"total_congestion_grid_net_cache_hits",
|
||||
"total_congestion_grid_net_cache_misses",
|
||||
"total_congestion_grid_span_cache_hits",
|
||||
"total_congestion_grid_span_cache_misses",
|
||||
"total_congestion_candidate_nets",
|
||||
"total_congestion_net_envelope_cache_hits",
|
||||
"total_congestion_net_envelope_cache_misses",
|
||||
"total_dynamic_path_objects_added",
|
||||
"total_dynamic_path_objects_removed",
|
||||
"total_dynamic_tree_rebuilds",
|
||||
"total_dynamic_grid_rebuilds",
|
||||
"total_static_tree_rebuilds",
|
||||
"total_static_raw_tree_rebuilds",
|
||||
"total_static_net_tree_rebuilds",
|
||||
"total_visibility_corner_index_builds",
|
||||
"total_visibility_builds",
|
||||
"total_visibility_corner_pairs_checked",
|
||||
"total_visibility_corner_queries_exact",
|
||||
"total_visibility_corner_hits_exact",
|
||||
"total_visibility_point_queries",
|
||||
"total_visibility_point_cache_hits",
|
||||
"total_visibility_point_cache_misses",
|
||||
"total_visibility_tangent_candidate_scans",
|
||||
"total_visibility_tangent_candidate_corner_checks",
|
||||
"total_visibility_tangent_candidate_ray_tests",
|
||||
"total_ray_cast_calls",
|
||||
"total_ray_cast_calls_straight_static",
|
||||
"total_ray_cast_calls_expand_snap",
|
||||
"total_ray_cast_calls_expand_forward",
|
||||
"total_ray_cast_calls_visibility_build",
|
||||
"total_ray_cast_calls_visibility_query",
|
||||
"total_ray_cast_calls_visibility_tangent",
|
||||
"total_ray_cast_calls_other",
|
||||
"total_ray_cast_candidate_bounds",
|
||||
"total_ray_cast_exact_geometry_checks",
|
||||
"total_congestion_check_calls",
|
||||
"total_congestion_lazy_resolutions",
|
||||
"total_congestion_lazy_requeues",
|
||||
"total_congestion_candidate_ids",
|
||||
"total_congestion_exact_pair_checks",
|
||||
"total_verify_path_report_calls",
|
||||
"total_verify_static_buffer_ops",
|
||||
"total_verify_dynamic_candidate_nets",
|
||||
"total_verify_dynamic_exact_pair_checks",
|
||||
"total_refinement_windows_considered",
|
||||
"total_refinement_static_bounds_checked",
|
||||
"total_refinement_dynamic_bounds_checked",
|
||||
"total_refinement_candidate_side_extents",
|
||||
"total_refinement_candidates_built",
|
||||
"total_refinement_candidates_verified",
|
||||
"total_refinement_candidates_accepted",
|
||||
"total_pair_local_search_pairs_considered",
|
||||
"total_pair_local_search_attempts",
|
||||
"total_pair_local_search_accepts",
|
||||
"total_pair_local_search_nodes_expanded",
|
||||
"total_late_phase_capped_nets",
|
||||
"total_late_phase_capped_fallbacks",
|
||||
"last_expanded_nodes",
|
||||
"nodes_expanded",
|
||||
"moves_generated",
|
||||
"moves_added",
|
||||
"pruned_closed_set",
|
||||
"pruned_hard_collision",
|
||||
"pruned_cost",
|
||||
_TOTAL_COUNTERS = tuple(
|
||||
(f"total_{name}", counter_type()) for name, counter_type in get_type_hints(RouteMetrics).items()
|
||||
)
|
||||
_PER_SEARCH_COUNTERS = ("nodes_expanded", "moves_generated", "moves_added", "pruned_closed_set", "pruned_hard_collision", "pruned_cost")
|
||||
_READ_TOTALS = attrgetter(*(name for name, _ in _TOTAL_COUNTERS))
|
||||
|
||||
|
||||
class AStarMetrics:
|
||||
__slots__ = (*(name for name, _ in _TOTAL_COUNTERS), *_PER_SEARCH_COUNTERS, "last_expanded_nodes")
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.total_nodes_expanded = 0
|
||||
self.total_moves_generated = 0
|
||||
self.total_moves_added = 0
|
||||
self.total_pruned_closed_set = 0
|
||||
self.total_pruned_hard_collision = 0
|
||||
self.total_pruned_cost = 0
|
||||
self.total_route_iterations = 0
|
||||
self.total_nets_routed = 0
|
||||
self.total_nets_reached_target = 0
|
||||
self.total_warm_start_paths_built = 0
|
||||
self.total_warm_start_paths_used = 0
|
||||
self.total_refine_path_calls = 0
|
||||
self.total_timeout_events = 0
|
||||
self.total_iteration_reverify_calls = 0
|
||||
self.total_iteration_reverified_nets = 0
|
||||
self.total_iteration_conflicting_nets = 0
|
||||
self.total_iteration_conflict_edges = 0
|
||||
self.total_nets_carried_forward = 0
|
||||
self.total_score_component_calls = 0
|
||||
self.total_score_component_total_ns = 0
|
||||
self.total_path_cost_calls = 0
|
||||
self.total_danger_map_lookup_calls = 0
|
||||
self.total_danger_map_cache_hits = 0
|
||||
self.total_danger_map_cache_misses = 0
|
||||
self.total_danger_map_query_calls = 0
|
||||
self.total_danger_map_total_ns = 0
|
||||
self.total_move_cache_abs_hits = 0
|
||||
self.total_move_cache_abs_misses = 0
|
||||
self.total_move_cache_rel_hits = 0
|
||||
self.total_move_cache_rel_misses = 0
|
||||
self.total_guidance_match_moves = 0
|
||||
self.total_guidance_match_moves_straight = 0
|
||||
self.total_guidance_match_moves_bend90 = 0
|
||||
self.total_guidance_match_moves_sbend = 0
|
||||
self.total_guidance_bonus_applied = 0.0
|
||||
self.total_guidance_bonus_applied_straight = 0.0
|
||||
self.total_guidance_bonus_applied_bend90 = 0.0
|
||||
self.total_guidance_bonus_applied_sbend = 0.0
|
||||
self.total_static_safe_cache_hits = 0
|
||||
self.total_hard_collision_cache_hits = 0
|
||||
self.total_congestion_cache_hits = 0
|
||||
self.total_congestion_cache_misses = 0
|
||||
self.total_congestion_presence_cache_hits = 0
|
||||
self.total_congestion_presence_cache_misses = 0
|
||||
self.total_congestion_presence_skips = 0
|
||||
self.total_congestion_candidate_precheck_hits = 0
|
||||
self.total_congestion_candidate_precheck_misses = 0
|
||||
self.total_congestion_candidate_precheck_skips = 0
|
||||
self.total_congestion_grid_net_cache_hits = 0
|
||||
self.total_congestion_grid_net_cache_misses = 0
|
||||
self.total_congestion_grid_span_cache_hits = 0
|
||||
self.total_congestion_grid_span_cache_misses = 0
|
||||
self.total_congestion_candidate_nets = 0
|
||||
self.total_congestion_net_envelope_cache_hits = 0
|
||||
self.total_congestion_net_envelope_cache_misses = 0
|
||||
self.total_dynamic_path_objects_added = 0
|
||||
self.total_dynamic_path_objects_removed = 0
|
||||
self.total_dynamic_tree_rebuilds = 0
|
||||
self.total_dynamic_grid_rebuilds = 0
|
||||
self.total_static_tree_rebuilds = 0
|
||||
self.total_static_raw_tree_rebuilds = 0
|
||||
self.total_static_net_tree_rebuilds = 0
|
||||
self.total_visibility_corner_index_builds = 0
|
||||
self.total_visibility_builds = 0
|
||||
self.total_visibility_corner_pairs_checked = 0
|
||||
self.total_visibility_corner_queries_exact = 0
|
||||
self.total_visibility_corner_hits_exact = 0
|
||||
self.total_visibility_point_queries = 0
|
||||
self.total_visibility_point_cache_hits = 0
|
||||
self.total_visibility_point_cache_misses = 0
|
||||
self.total_visibility_tangent_candidate_scans = 0
|
||||
self.total_visibility_tangent_candidate_corner_checks = 0
|
||||
self.total_visibility_tangent_candidate_ray_tests = 0
|
||||
self.total_ray_cast_calls = 0
|
||||
self.total_ray_cast_calls_straight_static = 0
|
||||
self.total_ray_cast_calls_expand_snap = 0
|
||||
self.total_ray_cast_calls_expand_forward = 0
|
||||
self.total_ray_cast_calls_visibility_build = 0
|
||||
self.total_ray_cast_calls_visibility_query = 0
|
||||
self.total_ray_cast_calls_visibility_tangent = 0
|
||||
self.total_ray_cast_calls_other = 0
|
||||
self.total_ray_cast_candidate_bounds = 0
|
||||
self.total_ray_cast_exact_geometry_checks = 0
|
||||
self.total_congestion_check_calls = 0
|
||||
self.total_congestion_lazy_resolutions = 0
|
||||
self.total_congestion_lazy_requeues = 0
|
||||
self.total_congestion_candidate_ids = 0
|
||||
self.total_congestion_exact_pair_checks = 0
|
||||
self.total_verify_path_report_calls = 0
|
||||
self.total_verify_static_buffer_ops = 0
|
||||
self.total_verify_dynamic_candidate_nets = 0
|
||||
self.total_verify_dynamic_exact_pair_checks = 0
|
||||
self.total_refinement_windows_considered = 0
|
||||
self.total_refinement_static_bounds_checked = 0
|
||||
self.total_refinement_dynamic_bounds_checked = 0
|
||||
self.total_refinement_candidate_side_extents = 0
|
||||
self.total_refinement_candidates_built = 0
|
||||
self.total_refinement_candidates_verified = 0
|
||||
self.total_refinement_candidates_accepted = 0
|
||||
self.total_pair_local_search_pairs_considered = 0
|
||||
self.total_pair_local_search_attempts = 0
|
||||
self.total_pair_local_search_accepts = 0
|
||||
self.total_pair_local_search_nodes_expanded = 0
|
||||
self.total_late_phase_capped_nets = 0
|
||||
self.total_late_phase_capped_fallbacks = 0
|
||||
self.last_expanded_nodes: list[tuple[int, int, int]] = []
|
||||
self.nodes_expanded = 0
|
||||
self.moves_generated = 0
|
||||
self.moves_added = 0
|
||||
self.pruned_closed_set = 0
|
||||
self.pruned_hard_collision = 0
|
||||
self.pruned_cost = 0
|
||||
self.reset_totals()
|
||||
self.reset_per_route()
|
||||
|
||||
def reset_totals(self) -> None:
|
||||
self.total_nodes_expanded = 0
|
||||
self.total_moves_generated = 0
|
||||
self.total_moves_added = 0
|
||||
self.total_pruned_closed_set = 0
|
||||
self.total_pruned_hard_collision = 0
|
||||
self.total_pruned_cost = 0
|
||||
self.total_route_iterations = 0
|
||||
self.total_nets_routed = 0
|
||||
self.total_nets_reached_target = 0
|
||||
self.total_warm_start_paths_built = 0
|
||||
self.total_warm_start_paths_used = 0
|
||||
self.total_refine_path_calls = 0
|
||||
self.total_timeout_events = 0
|
||||
self.total_iteration_reverify_calls = 0
|
||||
self.total_iteration_reverified_nets = 0
|
||||
self.total_iteration_conflicting_nets = 0
|
||||
self.total_iteration_conflict_edges = 0
|
||||
self.total_nets_carried_forward = 0
|
||||
self.total_score_component_calls = 0
|
||||
self.total_score_component_total_ns = 0
|
||||
self.total_path_cost_calls = 0
|
||||
self.total_danger_map_lookup_calls = 0
|
||||
self.total_danger_map_cache_hits = 0
|
||||
self.total_danger_map_cache_misses = 0
|
||||
self.total_danger_map_query_calls = 0
|
||||
self.total_danger_map_total_ns = 0
|
||||
self.total_move_cache_abs_hits = 0
|
||||
self.total_move_cache_abs_misses = 0
|
||||
self.total_move_cache_rel_hits = 0
|
||||
self.total_move_cache_rel_misses = 0
|
||||
self.total_guidance_match_moves = 0
|
||||
self.total_guidance_match_moves_straight = 0
|
||||
self.total_guidance_match_moves_bend90 = 0
|
||||
self.total_guidance_match_moves_sbend = 0
|
||||
self.total_guidance_bonus_applied = 0.0
|
||||
self.total_guidance_bonus_applied_straight = 0.0
|
||||
self.total_guidance_bonus_applied_bend90 = 0.0
|
||||
self.total_guidance_bonus_applied_sbend = 0.0
|
||||
self.total_static_safe_cache_hits = 0
|
||||
self.total_hard_collision_cache_hits = 0
|
||||
self.total_congestion_cache_hits = 0
|
||||
self.total_congestion_cache_misses = 0
|
||||
self.total_congestion_presence_cache_hits = 0
|
||||
self.total_congestion_presence_cache_misses = 0
|
||||
self.total_congestion_presence_skips = 0
|
||||
self.total_congestion_candidate_precheck_hits = 0
|
||||
self.total_congestion_candidate_precheck_misses = 0
|
||||
self.total_congestion_candidate_precheck_skips = 0
|
||||
self.total_congestion_grid_net_cache_hits = 0
|
||||
self.total_congestion_grid_net_cache_misses = 0
|
||||
self.total_congestion_grid_span_cache_hits = 0
|
||||
self.total_congestion_grid_span_cache_misses = 0
|
||||
self.total_congestion_candidate_nets = 0
|
||||
self.total_congestion_net_envelope_cache_hits = 0
|
||||
self.total_congestion_net_envelope_cache_misses = 0
|
||||
self.total_dynamic_path_objects_added = 0
|
||||
self.total_dynamic_path_objects_removed = 0
|
||||
self.total_dynamic_tree_rebuilds = 0
|
||||
self.total_dynamic_grid_rebuilds = 0
|
||||
self.total_static_tree_rebuilds = 0
|
||||
self.total_static_raw_tree_rebuilds = 0
|
||||
self.total_static_net_tree_rebuilds = 0
|
||||
self.total_visibility_corner_index_builds = 0
|
||||
self.total_visibility_builds = 0
|
||||
self.total_visibility_corner_pairs_checked = 0
|
||||
self.total_visibility_corner_queries_exact = 0
|
||||
self.total_visibility_corner_hits_exact = 0
|
||||
self.total_visibility_point_queries = 0
|
||||
self.total_visibility_point_cache_hits = 0
|
||||
self.total_visibility_point_cache_misses = 0
|
||||
self.total_visibility_tangent_candidate_scans = 0
|
||||
self.total_visibility_tangent_candidate_corner_checks = 0
|
||||
self.total_visibility_tangent_candidate_ray_tests = 0
|
||||
self.total_ray_cast_calls = 0
|
||||
self.total_ray_cast_calls_straight_static = 0
|
||||
self.total_ray_cast_calls_expand_snap = 0
|
||||
self.total_ray_cast_calls_expand_forward = 0
|
||||
self.total_ray_cast_calls_visibility_build = 0
|
||||
self.total_ray_cast_calls_visibility_query = 0
|
||||
self.total_ray_cast_calls_visibility_tangent = 0
|
||||
self.total_ray_cast_calls_other = 0
|
||||
self.total_ray_cast_candidate_bounds = 0
|
||||
self.total_ray_cast_exact_geometry_checks = 0
|
||||
self.total_congestion_check_calls = 0
|
||||
self.total_congestion_lazy_resolutions = 0
|
||||
self.total_congestion_lazy_requeues = 0
|
||||
self.total_congestion_candidate_ids = 0
|
||||
self.total_congestion_exact_pair_checks = 0
|
||||
self.total_verify_path_report_calls = 0
|
||||
self.total_verify_static_buffer_ops = 0
|
||||
self.total_verify_dynamic_candidate_nets = 0
|
||||
self.total_verify_dynamic_exact_pair_checks = 0
|
||||
self.total_refinement_windows_considered = 0
|
||||
self.total_refinement_static_bounds_checked = 0
|
||||
self.total_refinement_dynamic_bounds_checked = 0
|
||||
self.total_refinement_candidate_side_extents = 0
|
||||
self.total_refinement_candidates_built = 0
|
||||
self.total_refinement_candidates_verified = 0
|
||||
self.total_refinement_candidates_accepted = 0
|
||||
self.total_pair_local_search_pairs_considered = 0
|
||||
self.total_pair_local_search_attempts = 0
|
||||
self.total_pair_local_search_accepts = 0
|
||||
self.total_pair_local_search_nodes_expanded = 0
|
||||
self.total_late_phase_capped_nets = 0
|
||||
self.total_late_phase_capped_fallbacks = 0
|
||||
for name, default in _TOTAL_COUNTERS:
|
||||
setattr(self, name, default)
|
||||
|
||||
def reset_per_route(self) -> None:
|
||||
self.nodes_expanded = 0
|
||||
self.moves_generated = 0
|
||||
self.moves_added = 0
|
||||
self.pruned_closed_set = 0
|
||||
self.pruned_hard_collision = 0
|
||||
self.pruned_cost = 0
|
||||
self.last_expanded_nodes = []
|
||||
for name in _PER_SEARCH_COUNTERS:
|
||||
setattr(self, name, 0)
|
||||
self.last_expanded_nodes: list[tuple[int, int, int]] = []
|
||||
|
||||
def snapshot(self) -> RouteMetrics:
|
||||
return RouteMetrics(
|
||||
nodes_expanded=self.total_nodes_expanded,
|
||||
moves_generated=self.total_moves_generated,
|
||||
moves_added=self.total_moves_added,
|
||||
pruned_closed_set=self.total_pruned_closed_set,
|
||||
pruned_hard_collision=self.total_pruned_hard_collision,
|
||||
pruned_cost=self.total_pruned_cost,
|
||||
route_iterations=self.total_route_iterations,
|
||||
nets_routed=self.total_nets_routed,
|
||||
nets_reached_target=self.total_nets_reached_target,
|
||||
warm_start_paths_built=self.total_warm_start_paths_built,
|
||||
warm_start_paths_used=self.total_warm_start_paths_used,
|
||||
refine_path_calls=self.total_refine_path_calls,
|
||||
timeout_events=self.total_timeout_events,
|
||||
iteration_reverify_calls=self.total_iteration_reverify_calls,
|
||||
iteration_reverified_nets=self.total_iteration_reverified_nets,
|
||||
iteration_conflicting_nets=self.total_iteration_conflicting_nets,
|
||||
iteration_conflict_edges=self.total_iteration_conflict_edges,
|
||||
nets_carried_forward=self.total_nets_carried_forward,
|
||||
score_component_calls=self.total_score_component_calls,
|
||||
score_component_total_ns=self.total_score_component_total_ns,
|
||||
path_cost_calls=self.total_path_cost_calls,
|
||||
danger_map_lookup_calls=self.total_danger_map_lookup_calls,
|
||||
danger_map_cache_hits=self.total_danger_map_cache_hits,
|
||||
danger_map_cache_misses=self.total_danger_map_cache_misses,
|
||||
danger_map_query_calls=self.total_danger_map_query_calls,
|
||||
danger_map_total_ns=self.total_danger_map_total_ns,
|
||||
move_cache_abs_hits=self.total_move_cache_abs_hits,
|
||||
move_cache_abs_misses=self.total_move_cache_abs_misses,
|
||||
move_cache_rel_hits=self.total_move_cache_rel_hits,
|
||||
move_cache_rel_misses=self.total_move_cache_rel_misses,
|
||||
guidance_match_moves=self.total_guidance_match_moves,
|
||||
guidance_match_moves_straight=self.total_guidance_match_moves_straight,
|
||||
guidance_match_moves_bend90=self.total_guidance_match_moves_bend90,
|
||||
guidance_match_moves_sbend=self.total_guidance_match_moves_sbend,
|
||||
guidance_bonus_applied=self.total_guidance_bonus_applied,
|
||||
guidance_bonus_applied_straight=self.total_guidance_bonus_applied_straight,
|
||||
guidance_bonus_applied_bend90=self.total_guidance_bonus_applied_bend90,
|
||||
guidance_bonus_applied_sbend=self.total_guidance_bonus_applied_sbend,
|
||||
static_safe_cache_hits=self.total_static_safe_cache_hits,
|
||||
hard_collision_cache_hits=self.total_hard_collision_cache_hits,
|
||||
congestion_cache_hits=self.total_congestion_cache_hits,
|
||||
congestion_cache_misses=self.total_congestion_cache_misses,
|
||||
congestion_presence_cache_hits=self.total_congestion_presence_cache_hits,
|
||||
congestion_presence_cache_misses=self.total_congestion_presence_cache_misses,
|
||||
congestion_presence_skips=self.total_congestion_presence_skips,
|
||||
congestion_candidate_precheck_hits=self.total_congestion_candidate_precheck_hits,
|
||||
congestion_candidate_precheck_misses=self.total_congestion_candidate_precheck_misses,
|
||||
congestion_candidate_precheck_skips=self.total_congestion_candidate_precheck_skips,
|
||||
congestion_grid_net_cache_hits=self.total_congestion_grid_net_cache_hits,
|
||||
congestion_grid_net_cache_misses=self.total_congestion_grid_net_cache_misses,
|
||||
congestion_grid_span_cache_hits=self.total_congestion_grid_span_cache_hits,
|
||||
congestion_grid_span_cache_misses=self.total_congestion_grid_span_cache_misses,
|
||||
congestion_candidate_nets=self.total_congestion_candidate_nets,
|
||||
congestion_net_envelope_cache_hits=self.total_congestion_net_envelope_cache_hits,
|
||||
congestion_net_envelope_cache_misses=self.total_congestion_net_envelope_cache_misses,
|
||||
dynamic_path_objects_added=self.total_dynamic_path_objects_added,
|
||||
dynamic_path_objects_removed=self.total_dynamic_path_objects_removed,
|
||||
dynamic_tree_rebuilds=self.total_dynamic_tree_rebuilds,
|
||||
dynamic_grid_rebuilds=self.total_dynamic_grid_rebuilds,
|
||||
static_tree_rebuilds=self.total_static_tree_rebuilds,
|
||||
static_raw_tree_rebuilds=self.total_static_raw_tree_rebuilds,
|
||||
static_net_tree_rebuilds=self.total_static_net_tree_rebuilds,
|
||||
visibility_corner_index_builds=self.total_visibility_corner_index_builds,
|
||||
visibility_builds=self.total_visibility_builds,
|
||||
visibility_corner_pairs_checked=self.total_visibility_corner_pairs_checked,
|
||||
visibility_corner_queries_exact=self.total_visibility_corner_queries_exact,
|
||||
visibility_corner_hits_exact=self.total_visibility_corner_hits_exact,
|
||||
visibility_point_queries=self.total_visibility_point_queries,
|
||||
visibility_point_cache_hits=self.total_visibility_point_cache_hits,
|
||||
visibility_point_cache_misses=self.total_visibility_point_cache_misses,
|
||||
visibility_tangent_candidate_scans=self.total_visibility_tangent_candidate_scans,
|
||||
visibility_tangent_candidate_corner_checks=self.total_visibility_tangent_candidate_corner_checks,
|
||||
visibility_tangent_candidate_ray_tests=self.total_visibility_tangent_candidate_ray_tests,
|
||||
ray_cast_calls=self.total_ray_cast_calls,
|
||||
ray_cast_calls_straight_static=self.total_ray_cast_calls_straight_static,
|
||||
ray_cast_calls_expand_snap=self.total_ray_cast_calls_expand_snap,
|
||||
ray_cast_calls_expand_forward=self.total_ray_cast_calls_expand_forward,
|
||||
ray_cast_calls_visibility_build=self.total_ray_cast_calls_visibility_build,
|
||||
ray_cast_calls_visibility_query=self.total_ray_cast_calls_visibility_query,
|
||||
ray_cast_calls_visibility_tangent=self.total_ray_cast_calls_visibility_tangent,
|
||||
ray_cast_calls_other=self.total_ray_cast_calls_other,
|
||||
ray_cast_candidate_bounds=self.total_ray_cast_candidate_bounds,
|
||||
ray_cast_exact_geometry_checks=self.total_ray_cast_exact_geometry_checks,
|
||||
congestion_check_calls=self.total_congestion_check_calls,
|
||||
congestion_lazy_resolutions=self.total_congestion_lazy_resolutions,
|
||||
congestion_lazy_requeues=self.total_congestion_lazy_requeues,
|
||||
congestion_candidate_ids=self.total_congestion_candidate_ids,
|
||||
congestion_exact_pair_checks=self.total_congestion_exact_pair_checks,
|
||||
verify_path_report_calls=self.total_verify_path_report_calls,
|
||||
verify_static_buffer_ops=self.total_verify_static_buffer_ops,
|
||||
verify_dynamic_candidate_nets=self.total_verify_dynamic_candidate_nets,
|
||||
verify_dynamic_exact_pair_checks=self.total_verify_dynamic_exact_pair_checks,
|
||||
refinement_windows_considered=self.total_refinement_windows_considered,
|
||||
refinement_static_bounds_checked=self.total_refinement_static_bounds_checked,
|
||||
refinement_dynamic_bounds_checked=self.total_refinement_dynamic_bounds_checked,
|
||||
refinement_candidate_side_extents=self.total_refinement_candidate_side_extents,
|
||||
refinement_candidates_built=self.total_refinement_candidates_built,
|
||||
refinement_candidates_verified=self.total_refinement_candidates_verified,
|
||||
refinement_candidates_accepted=self.total_refinement_candidates_accepted,
|
||||
pair_local_search_pairs_considered=self.total_pair_local_search_pairs_considered,
|
||||
pair_local_search_attempts=self.total_pair_local_search_attempts,
|
||||
pair_local_search_accepts=self.total_pair_local_search_accepts,
|
||||
pair_local_search_nodes_expanded=self.total_pair_local_search_nodes_expanded,
|
||||
late_phase_capped_nets=self.total_late_phase_capped_nets,
|
||||
late_phase_capped_fallbacks=self.total_late_phase_capped_fallbacks,
|
||||
)
|
||||
return RouteMetrics(*_READ_TOTALS(self))
|
||||
|
||||
|
||||
class AStarContext:
|
||||
|
|
|
|||
|
|
@ -3,10 +3,9 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from contextlib import contextmanager, suppress
|
||||
from dataclasses import fields, replace
|
||||
from dataclasses import replace
|
||||
from functools import partial
|
||||
from itertools import chain, combinations, islice, pairwise, product
|
||||
from math import floor, isfinite
|
||||
from itertools import chain, islice, pairwise, product
|
||||
from time import perf_counter
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
|
|
@ -15,10 +14,12 @@ from shapely.geometry import box
|
|||
|
||||
from inire.constants import TOLERANCE_LINEAR
|
||||
from inire.geometry.collision import RoutingWorld
|
||||
from inire.geometry.primitives import port_local_coordinates
|
||||
from inire.model import resolve_bend_geometry
|
||||
from inire.results import AutomaticRoutingReport, CapacityLimit, RouteMetrics, RoutingStage, RoutingTiming, _planner_for_mode
|
||||
from inire.results import AutomaticRoutingReport, RoutingStage, RoutingTiming, _planner_for_mode, _sum_route_metrics
|
||||
from inire.router._bundle import ordered_bundle_terminal_headings, plan_ordered_bundle
|
||||
from inire.router._columns import column_jog_candidates, column_seed_candidates, open_intervals, rectangular_obstacle_bounds
|
||||
from inire.router._capacity import cut_capacity, port_conflicts
|
||||
from inire.router._columns import column_jog_candidates, column_seed_candidates
|
||||
from inire.router._compact import compact_port_seed_set, short_shift_seed_set
|
||||
from inire.router._perimeter import (
|
||||
bundle_turnaround_candidates,
|
||||
|
|
@ -32,7 +33,6 @@ from inire.router._routing_policy import (
|
|||
_direct_trials,
|
||||
_disconnected_nets,
|
||||
_is_short_shift,
|
||||
_local_delta,
|
||||
_residual_problem,
|
||||
_route_residual,
|
||||
_trial,
|
||||
|
|
@ -40,17 +40,18 @@ from inire.router._routing_policy import (
|
|||
from inire.router._seed_materialization import materialize_path_seed
|
||||
from inire.router._stack import route_once
|
||||
from inire.router._topology import plan_corridors
|
||||
from inire.router.cost import CostEvaluator
|
||||
from inire.router.cost import CostEvaluator, weighted_path_length
|
||||
from inire.router.danger_map import DangerMap
|
||||
from inire.seeds import SBendSeed
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable, Iterable, Iterator
|
||||
from typing import Literal
|
||||
|
||||
from shapely.geometry.base import BaseGeometry
|
||||
|
||||
from inire.model import NetSpec, RoutingOptions, RoutingProblem
|
||||
from inire.results import RoutingOperation, RoutingResult, RoutingRunResult
|
||||
from inire.results import RouteMetrics, RoutingOperation, RoutingResult, RoutingRunResult
|
||||
from inire.router._routing_policy import Trial
|
||||
from inire.router._topology import Corridor
|
||||
from inire.seeds import PathSeed
|
||||
|
|
@ -60,65 +61,6 @@ _INITIAL_NODE_LIMIT = 500
|
|||
_NEAR_PORT_NODE_LIMIT = 100
|
||||
|
||||
|
||||
def _cut_capacity(problem: RoutingProblem, options: RoutingOptions) -> CapacityLimit | None:
|
||||
_, physical_geometry = resolve_bend_geometry(options.search)
|
||||
obstacles = rectangular_obstacle_bounds(problem)
|
||||
if physical_geometry != "arc" or not obstacles or not problem.nets:
|
||||
return None
|
||||
# The narrowest guide gives an optimistic upper bound for mixed widths.
|
||||
width = min(net.width for net in problem.nets)
|
||||
if not isfinite(width) or width <= 0 or problem.clearance < 0:
|
||||
return None
|
||||
pitch = width + problem.clearance
|
||||
limit = None
|
||||
edges = sorted({x for left, _, right, _ in obstacles for x in (left, right)})
|
||||
for left, right in pairwise(edges):
|
||||
x = (left + right) / 2
|
||||
crossing = sum(min(net.start.x, net.target.x) + width / 2 < x < max(net.start.x, net.target.x) - width / 2 for net in problem.nets)
|
||||
if not crossing:
|
||||
continue
|
||||
solid = [(bottom, top) for start, bottom, end, top in obstacles if start < x < end]
|
||||
if not solid:
|
||||
continue
|
||||
ymin, ymax = problem.bounds[1], problem.bounds[3]
|
||||
tracks = 0
|
||||
for low, high in open_intervals(solid, ymin, ymax):
|
||||
bottom = low + width / 2 + (problem.clearance if low != ymin else 0)
|
||||
top = high - width / 2 - (problem.clearance if high != ymax else 0)
|
||||
room = top - bottom + 2 * TOLERANCE_LINEAR
|
||||
if room >= 0:
|
||||
tracks += 1 + floor(room / max(TOLERANCE_LINEAR, pitch - TOLERANCE_LINEAR))
|
||||
max_routed = len(problem.nets) - crossing + tracks
|
||||
if tracks < crossing and (limit is None or max_routed < limit.max_routed):
|
||||
limit = CapacityLimit(x, crossing, tracks, max_routed)
|
||||
return limit
|
||||
|
||||
|
||||
def _port_conflicts(problem: RoutingProblem, options: RoutingOptions) -> tuple[tuple[str, str], ...]:
|
||||
_, physical_geometry = resolve_bend_geometry(options.search)
|
||||
if physical_geometry != "arc" or problem.clearance <= TOLERANCE_LINEAR:
|
||||
return ()
|
||||
aligned: dict[tuple[int, int], list[tuple[str, float, float]]] = {}
|
||||
for net in problem.nets:
|
||||
for port in (net.start, net.target):
|
||||
axis = port.r % 180
|
||||
longitudinal, lateral = (port.x, port.y) if axis == 0 else (port.y, port.x)
|
||||
aligned.setdefault((axis, longitudinal), []).append((net.net_id, lateral, net.width))
|
||||
# Each disjoint conflict pair forces at least one route to be omitted.
|
||||
# A terminal's physical cross-section is fixed by its heading and width.
|
||||
pairs = []
|
||||
matched = set()
|
||||
for ports in aligned.values():
|
||||
for (a, y1, w1), (b, y2, w2) in combinations(ports, 2):
|
||||
if a == b or a in matched or b in matched:
|
||||
continue
|
||||
gap = abs(y1 - y2) - (w1 + w2) / 2
|
||||
if gap < problem.clearance - TOLERANCE_LINEAR:
|
||||
pairs.append((a, b))
|
||||
matched.update((a, b))
|
||||
return tuple(pairs)
|
||||
|
||||
|
||||
def _has_fragmented_shifts(trial: Trial) -> bool:
|
||||
for net_id in trial.valid_costs:
|
||||
path = trial.run.results_by_net[net_id].path
|
||||
|
|
@ -201,9 +143,9 @@ class _AutomaticRun:
|
|||
self.metrics.append(run.metrics)
|
||||
return run
|
||||
|
||||
def _score(self, result: RoutingResult) -> float:
|
||||
def _selection_cost(self, result: RoutingResult) -> float:
|
||||
if self.length_weights is not None:
|
||||
return sum(component.length * self.length_weights[component.move_type] for component in result.path)
|
||||
return weighted_path_length(result.path, self.length_weights)
|
||||
if self.evaluator is None:
|
||||
objective = self.options.objective
|
||||
danger = None
|
||||
|
|
@ -222,19 +164,48 @@ class _AutomaticRun:
|
|||
|
||||
def _trial(self, run: RoutingRunResult, stage: RoutingStage) -> Trial:
|
||||
with self._time("verify", planner=stage.planner, mode=stage.mode, policy=stage.policy):
|
||||
return _trial(run, stage, self.board, score=self._score)
|
||||
return _trial(run, stage, self.board, score=self._selection_cost)
|
||||
|
||||
def _verify(self, problem: RoutingProblem, planner: str, *, kind: str | None = None, policy: str | None = None) -> Trial:
|
||||
def _seeded_problem(self, trial: Trial) -> RoutingProblem:
|
||||
seeds = {net_id: trial.run.results_by_net[net_id].as_seed() for net_id in trial.valid_costs}
|
||||
nets = tuple(net for net in self.problem.nets if net.net_id in seeds)
|
||||
return replace(self.problem, nets=nets, initial_paths=seeds)
|
||||
|
||||
def _seeded_attempt(
|
||||
self,
|
||||
problem: RoutingProblem,
|
||||
planner: str,
|
||||
*,
|
||||
kind: str,
|
||||
policy: str | None,
|
||||
operation: Literal["verify", "refine"],
|
||||
) -> tuple[RoutingRunResult, RoutingStage]:
|
||||
options = self.options
|
||||
check = replace(
|
||||
refinement = options.refinement
|
||||
if operation == "verify":
|
||||
refinement = replace(refinement, enabled=False)
|
||||
worker = replace(
|
||||
options,
|
||||
search=replace(options.search, node_limit=1),
|
||||
topology=replace(options.topology, mode="off"),
|
||||
congestion=replace(options.congestion, max_iterations=1),
|
||||
refinement=replace(options.refinement, enabled=False),
|
||||
refinement=refinement,
|
||||
)
|
||||
run = self._run(problem, options=check, operation="verify", planner=planner, policy=policy)
|
||||
stage = RoutingStage("off", (), run.metrics.nodes_expanded, 1, kind=kind or planner, planner=planner, operation="verify", policy=policy)
|
||||
run = self._run(problem, options=worker, operation=operation, planner=planner, policy=policy)
|
||||
stage = RoutingStage(
|
||||
worker.topology.mode,
|
||||
(),
|
||||
run.metrics.nodes_expanded,
|
||||
worker.search.node_limit,
|
||||
kind=kind,
|
||||
planner=planner,
|
||||
operation=operation,
|
||||
policy=policy,
|
||||
)
|
||||
return run, stage
|
||||
|
||||
def _verify(self, problem: RoutingProblem, planner: str, *, kind: str | None = None, policy: str | None = None) -> Trial:
|
||||
run, stage = self._seeded_attempt(problem, planner, kind=kind or planner, policy=policy, operation="verify")
|
||||
return self._trial(run, stage)
|
||||
|
||||
def _constructive_trials(self) -> tuple[list[Trial], tuple[str, ...]]:
|
||||
|
|
@ -278,11 +249,11 @@ class _AutomaticRun:
|
|||
if not trials or len(_best_trial(trials).valid_costs) < len(problem.nets):
|
||||
planner = "local-sbend"
|
||||
with self._time("plan", planner=planner):
|
||||
shifts = short_shift_seed_set(problem, options.search, self._score)
|
||||
shifts = short_shift_seed_set(problem, options.search, self._selection_cost)
|
||||
if shifts is not None:
|
||||
trial = self._verify(replace(problem, initial_paths=shifts), planner)
|
||||
complete = len(trial.valid_costs) == len(problem.nets)
|
||||
trials.append(replace(trial, selectable=complete))
|
||||
trials.append(trial if complete else replace(trial, selection="incomplete-layout"))
|
||||
if not complete:
|
||||
rejections.append("Local S-bend layout failed full verification")
|
||||
return trials, tuple(rejections)
|
||||
|
|
@ -351,7 +322,7 @@ class _AutomaticRun:
|
|||
trials.append(trial)
|
||||
if len(trial.valid_costs) == len(problem.nets):
|
||||
return
|
||||
trials[-1] = replace(trial, selectable=False)
|
||||
trials[-1] = replace(trial, selection="incomplete-layout")
|
||||
|
||||
def _perimeter_trials(self, options: RoutingOptions) -> list[Trial]:
|
||||
problem = self.problem
|
||||
|
|
@ -367,7 +338,7 @@ class _AutomaticRun:
|
|||
if len(problem.nets) == 1 and candidate.valid_costs:
|
||||
trials.append(replace(candidate, stage=replace(candidate.stage, kind="perimeter")))
|
||||
break
|
||||
trials.append(replace(candidate, selectable=False))
|
||||
trials.append(replace(candidate, selection="local-only"))
|
||||
if not candidate.valid_costs:
|
||||
continue
|
||||
chosen = candidate.run.results_by_net[net.net_id]
|
||||
|
|
@ -390,19 +361,21 @@ class _AutomaticRun:
|
|||
)
|
||||
trials.append(self._trial(replace(run, results_by_net=combined), stage))
|
||||
if len(trials[-1].valid_costs) == len(problem.nets):
|
||||
trials[-1] = replace(trials[-1], selectable=False)
|
||||
trials[-1] = replace(trials[-1], selection="requires-layout-check")
|
||||
seeds = {net_id: result.as_seed() for net_id, result in combined.items()}
|
||||
trials.append(self._verify(replace(problem, initial_paths=seeds), "perimeter"))
|
||||
if len(trials[-1].valid_costs) == len(problem.nets):
|
||||
break
|
||||
return trials
|
||||
|
||||
def _incumbent_trials(self, options: RoutingOptions, best: Trial, target: int) -> list[Trial]:
|
||||
def _incumbent_trials(self, options: RoutingOptions, best: Trial, target: int, *, retry_disconnected: bool = True) -> list[Trial]:
|
||||
problem = self.problem
|
||||
retained = {net_id: best.run.results_by_net[net_id] for net_id in best.valid_costs}
|
||||
with self._time("plan", policy="incumbent-retry"):
|
||||
blocked = _disconnected_nets(problem, self.board, options, retained)
|
||||
if blocked:
|
||||
if not retry_disconnected:
|
||||
return []
|
||||
seeds = {net_id: result.as_seed() for net_id, result in retained.items()}
|
||||
run = self._run(replace(problem, initial_paths=seeds), options=options, policy="incumbent-retry")
|
||||
stage = RoutingStage(
|
||||
|
|
@ -423,7 +396,7 @@ class _AutomaticRun:
|
|||
stage = replace(stage, kind=policy, policy=policy, retry_reason="Residual terminals remain connected with the incumbents locked")
|
||||
trial = self._trial(run, stage)
|
||||
if len(trial.valid_costs) == len(problem.nets):
|
||||
return [replace(trial, selectable=False), self._verify_incumbent(trial)]
|
||||
return [replace(trial, selection="requires-layout-check"), self._verify_incumbent(trial)]
|
||||
trials = [trial]
|
||||
if len(trial.valid_costs) < target:
|
||||
dogleg = self._residual_dogleg_trial(options, _best_trial([best, trial]))
|
||||
|
|
@ -431,17 +404,17 @@ class _AutomaticRun:
|
|||
return [trial, dogleg]
|
||||
joint = self._joint_lane_trial(options, locks, trial)
|
||||
if joint is not None:
|
||||
trials.append(replace(joint, selectable=False))
|
||||
trials.append(replace(joint, selection="requires-layout-check"))
|
||||
if joint.improves_on(_best_trial([best, trial])):
|
||||
trials.append(self._verify_incumbent(joint))
|
||||
return trials
|
||||
|
||||
def _verify_incumbent(self, trial: Trial) -> Trial:
|
||||
seeds = {net_id: trial.run.results_by_net[net_id].as_seed() for net_id in trial.valid_costs}
|
||||
problem = replace(self.problem, nets=tuple(net for net in self.problem.nets if net.net_id in seeds), initial_paths=seeds)
|
||||
problem = self._seeded_problem(trial)
|
||||
# Check the seeded subproblem before restoring the unresolved results.
|
||||
verified = self._verify(problem, trial.stage.planner, kind="incumbent-verified", policy=trial.stage.policy)
|
||||
results = {**trial.run.results_by_net, **verified.run.results_by_net}
|
||||
return replace(verified, run=replace(verified.run, results_by_net=results), selectable=verified.valid_costs.keys() == seeds.keys())
|
||||
return replace(verified.as_replacement_for(trial), run=replace(verified.run, results_by_net=results))
|
||||
|
||||
def _residual_dogleg_trial(self, options: RoutingOptions, incumbent: Trial) -> Trial | None:
|
||||
problem = self.problem
|
||||
|
|
@ -502,7 +475,6 @@ class _AutomaticRun:
|
|||
return False
|
||||
|
||||
def _search_trials(self, trials: list[Trial], target: int) -> None:
|
||||
problem = self.problem
|
||||
configured_search = self.options.search
|
||||
first_limit = min(_INITIAL_NODE_LIMIT, configured_search.node_limit)
|
||||
options = replace(
|
||||
|
|
@ -510,43 +482,9 @@ class _AutomaticRun:
|
|||
search=replace(configured_search, node_limit=first_limit),
|
||||
refinement=replace(self.options.refinement, enabled=False),
|
||||
)
|
||||
early = self._early_guide(options)
|
||||
if early is not None:
|
||||
trials.append(early)
|
||||
if len(_best_trial(trials).valid_costs) >= target:
|
||||
if self._initial_search_trials(options, trials, target):
|
||||
return
|
||||
|
||||
early_jogs = self.iteration_callback is None and not options.congestion.shuffle_nets
|
||||
if early_jogs and self._try_column_jogs(options, trials, target):
|
||||
return
|
||||
small = replace(options, search=replace(options.search, node_limit=min(_NEAR_PORT_NODE_LIMIT, options.search.node_limit)))
|
||||
trials.extend(self._direct(small, "direct-probe-near-port"))
|
||||
if len(_best_trial(trials).valid_costs) >= target:
|
||||
return
|
||||
|
||||
if not early_jogs and self._try_column_jogs(options, trials, target):
|
||||
return
|
||||
|
||||
if len(problem.nets) <= 2:
|
||||
with self._time("plan", planner="perimeter"):
|
||||
trials.extend(self._perimeter_trials(options))
|
||||
if len(_best_trial(trials).valid_costs) >= target:
|
||||
return
|
||||
|
||||
# Every short shift has lateral displacement, so the direct retry cannot lock
|
||||
# any straight paths. It would run the same guide with the same budget.
|
||||
if early is None or early.run.metrics.timeout_events:
|
||||
trials.extend(self._direct(options, "direct-lookahead-retry"))
|
||||
best = _best_trial(trials)
|
||||
if len(best.valid_costs) >= target:
|
||||
return
|
||||
seeded = replace(options, topology=replace(options.topology, mode="seed"))
|
||||
if best.valid_costs and len(problem.nets) > 2 and not problem.initial_paths:
|
||||
trials.extend(self._incumbent_trials(seeded, best, target))
|
||||
if len(_best_trial(trials).valid_costs) < target:
|
||||
run = self._run(problem, options=seeded, policy="seed-fallback")
|
||||
stage = RoutingStage("seed", (), run.metrics.nodes_expanded, options.search.node_limit, policy="seed-fallback")
|
||||
trials.append(self._trial(run, stage))
|
||||
self._seed_recovery_trials(options, trials, target)
|
||||
if len(_best_trial(trials).valid_costs) < target:
|
||||
self._lattice_fallback(trials, options, "Automatic planners left unresolved nets")
|
||||
if first_limit < configured_search.node_limit and len(_best_trial(trials).valid_costs) < target:
|
||||
|
|
@ -557,6 +495,55 @@ class _AutomaticRun:
|
|||
policy="budget-escalation",
|
||||
)
|
||||
|
||||
def _initial_search_trials(self, options: RoutingOptions, trials: list[Trial], target: int) -> bool:
|
||||
problem = self.problem
|
||||
early = self._early_guide(options)
|
||||
if early is not None:
|
||||
trials.append(early)
|
||||
if len(_best_trial(trials).valid_costs) >= target:
|
||||
return True
|
||||
|
||||
try_construction_early = self.iteration_callback is None and not options.congestion.shuffle_nets
|
||||
if try_construction_early and self._try_column_jogs(options, trials, target):
|
||||
return True
|
||||
small = replace(options, search=replace(options.search, node_limit=min(_NEAR_PORT_NODE_LIMIT, options.search.node_limit)))
|
||||
probe = self._direct(small, "direct-probe-near-port")
|
||||
trials.extend(probe)
|
||||
if len(_best_trial(trials).valid_costs) >= target:
|
||||
return True
|
||||
|
||||
if not try_construction_early and self._try_column_jogs(options, trials, target):
|
||||
return True
|
||||
|
||||
if try_construction_early and target == len(problem.nets) and target > 2 and not problem.initial_paths:
|
||||
dogleg = self._residual_dogleg_trial(options, _best_trial(probe))
|
||||
if dogleg is not None:
|
||||
trials.append(dogleg)
|
||||
return True
|
||||
|
||||
if len(problem.nets) <= 2:
|
||||
with self._time("plan", planner="perimeter"):
|
||||
trials.extend(self._perimeter_trials(options))
|
||||
if len(_best_trial(trials).valid_costs) >= target:
|
||||
return True
|
||||
|
||||
# Every short shift has lateral displacement, so the direct retry cannot lock
|
||||
# any straight paths. It would run the same guide with the same budget.
|
||||
if early is None or early.run.metrics.timeout_events:
|
||||
trials.extend(self._direct(options, "direct-lookahead-retry"))
|
||||
return len(_best_trial(trials).valid_costs) >= target
|
||||
|
||||
def _seed_recovery_trials(self, options: RoutingOptions, trials: list[Trial], target: int) -> None:
|
||||
problem = self.problem
|
||||
best = _best_trial(trials)
|
||||
seeded = replace(options, topology=replace(options.topology, mode="seed"))
|
||||
if best.valid_costs and len(problem.nets) > 2 and not problem.initial_paths:
|
||||
trials.extend(self._incumbent_trials(seeded, best, target))
|
||||
if len(_best_trial(trials).valid_costs) < target:
|
||||
run = self._run(problem, options=seeded, policy="seed-fallback")
|
||||
stage = RoutingStage("seed", (), run.metrics.nodes_expanded, options.search.node_limit, policy="seed-fallback")
|
||||
trials.append(self._trial(run, stage))
|
||||
|
||||
def _joint_lane_trial(self, options: RoutingOptions, locks: LockPlan, previous: Trial) -> Trial | None:
|
||||
residual = _residual_problem(self.problem, locks)
|
||||
if len(residual.nets) < 2:
|
||||
|
|
@ -566,7 +553,11 @@ class _AutomaticRun:
|
|||
order = options.congestion.net_order
|
||||
nets = residual.nets
|
||||
if order != "user":
|
||||
nets = tuple(sorted(nets, key=lambda net: sum(map(abs, _local_delta(net))), reverse=order == "longest"))
|
||||
nets = tuple(sorted(
|
||||
nets,
|
||||
key=lambda net: sum(map(abs, port_local_coordinates(net.start, net.target.x, net.target.y))),
|
||||
reverse=order == "longest",
|
||||
))
|
||||
with self._time("plan", planner="corridor-seed", mode="seed", policy=policy):
|
||||
corridors = plan_corridors(
|
||||
residual.bounds,
|
||||
|
|
@ -608,24 +599,18 @@ class _AutomaticRun:
|
|||
best = _best_trial(trials)
|
||||
if not self.options.refinement.enabled or not best.valid_costs:
|
||||
return
|
||||
problem = replace(
|
||||
self.problem,
|
||||
nets=tuple(net for net in self.problem.nets if net.net_id in best.valid_costs),
|
||||
initial_paths={net_id: best.run.results_by_net[net_id].as_seed() for net_id in best.valid_costs},
|
||||
run, stage = self._seeded_attempt(
|
||||
self._seeded_problem(best),
|
||||
best.stage.planner,
|
||||
kind="refinement",
|
||||
policy=best.stage.policy,
|
||||
operation="refine",
|
||||
)
|
||||
options = replace(
|
||||
self.options,
|
||||
search=replace(self.options.search, node_limit=1),
|
||||
topology=replace(self.options.topology, mode="off"),
|
||||
congestion=replace(self.options.congestion, max_iterations=1),
|
||||
)
|
||||
planner, policy = best.stage.planner, best.stage.policy
|
||||
run = self._run(problem, options=options, operation="refine", planner=planner, policy=policy)
|
||||
stage = RoutingStage("off", (), run.metrics.nodes_expanded, 1, kind="refinement", policy=policy, planner=planner, operation="refine")
|
||||
# Audit the merged result so the stage still reports unresolved routes outside the board.
|
||||
results = {**best.run.results_by_net, **run.results_by_net}
|
||||
refined = self._trial(replace(run, results_by_net=results), stage)
|
||||
# Only a whole verified replacement of the incumbent can win.
|
||||
trials.append(replace(refined, selectable=refined.valid_costs.keys() == best.valid_costs.keys()))
|
||||
trials.append(refined.as_replacement_for(best))
|
||||
|
||||
def execute(self) -> RoutingRunResult:
|
||||
started = perf_counter()
|
||||
|
|
@ -647,8 +632,8 @@ class _AutomaticRun:
|
|||
if options.topology.infer_terminal_headings and not self.problem.initial_paths:
|
||||
with suppress(ValueError):
|
||||
self.problem = ordered_bundle_terminal_headings(self.raw_problem)
|
||||
cut = _cut_capacity(self.problem, options)
|
||||
conflicts = _port_conflicts(self.problem, options)
|
||||
cut = cut_capacity(self.problem, options)
|
||||
conflicts = port_conflicts(self.problem, options)
|
||||
target -= len(conflicts)
|
||||
if cut:
|
||||
target = min(target, cut.max_routed)
|
||||
|
|
@ -658,7 +643,7 @@ class _AutomaticRun:
|
|||
self._search_trials(trials, target)
|
||||
self._refine(trials)
|
||||
best = _best_trial(trials)
|
||||
metrics = replace(best.run.metrics, **{field.name: sum(getattr(m, field.name) for m in self.metrics) for field in fields(RouteMetrics)})
|
||||
metrics = _sum_route_metrics(self.metrics)
|
||||
report = AutomaticRoutingReport(
|
||||
tuple(trial.stage for trial in trials),
|
||||
next(i for i, trial in enumerate(trials) if trial is best),
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ from typing import TYPE_CHECKING
|
|||
from shapely.geometry import box
|
||||
|
||||
from inire.geometry.primitives import Port
|
||||
from inire.geometry.sbend import exact_sbend_spans
|
||||
from inire.model import resolve_bend_geometry
|
||||
from inire.router._waypoints import XY, compile_waypoints
|
||||
|
||||
|
|
@ -110,7 +111,7 @@ def ordered_bundle_terminal_headings(problem: RoutingProblem) -> RoutingProblem:
|
|||
|
||||
|
||||
def _exact_offsets(radius: int) -> tuple[int, ...]:
|
||||
return tuple(d for d in range(1, 2 * radius) if isqrt(d * (4 * radius - d)) ** 2 == d * (4 * radius - d))
|
||||
return tuple(exact_sbend_spans(radius))
|
||||
|
||||
|
||||
def _assign_shifts(
|
||||
|
|
|
|||
85
inire/router/_capacity.py
Normal file
85
inire/router/_capacity.py
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
"""Geometric upper bounds on automatic routing coverage."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from itertools import combinations, pairwise
|
||||
from math import floor, isfinite
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from shapely.geometry import box
|
||||
|
||||
from inire.constants import TOLERANCE_LINEAR
|
||||
from inire.geometry.intervals import open_intervals
|
||||
from inire.model import resolve_bend_geometry
|
||||
from inire.results import CapacityLimit
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from inire.model import RoutingOptions, RoutingProblem
|
||||
|
||||
|
||||
def _rectangular_obstacle_bounds(problem: RoutingProblem) -> tuple[tuple[float, float, float, float], ...] | None:
|
||||
bounds = tuple(tuple(shape.bounds) for shape in problem.static_obstacles)
|
||||
if any(shape.is_empty or not shape.equals(box(*extent)) for shape, extent in zip(problem.static_obstacles, bounds, strict=True)):
|
||||
return None
|
||||
return bounds
|
||||
|
||||
|
||||
def cut_capacity(problem: RoutingProblem, options: RoutingOptions) -> CapacityLimit | None:
|
||||
"""Bound routes across vertical cuts through truly rectangular obstacles."""
|
||||
_, physical_geometry = resolve_bend_geometry(options.search)
|
||||
obstacles = _rectangular_obstacle_bounds(problem)
|
||||
if physical_geometry != "arc" or not obstacles or not problem.nets:
|
||||
return None
|
||||
# The narrowest guide gives an optimistic upper bound for mixed widths.
|
||||
width = min(net.width for net in problem.nets)
|
||||
if not isfinite(width) or width <= 0 or problem.clearance < 0:
|
||||
return None
|
||||
pitch = width + problem.clearance
|
||||
limit = None
|
||||
edges = sorted({x for left, _, right, _ in obstacles for x in (left, right)})
|
||||
for left, right in pairwise(edges):
|
||||
x = (left + right) / 2
|
||||
crossing = sum(min(net.start.x, net.target.x) + width / 2 < x < max(net.start.x, net.target.x) - width / 2 for net in problem.nets)
|
||||
if not crossing:
|
||||
continue
|
||||
solid = [(bottom, top) for start, bottom, end, top in obstacles if start < x < end]
|
||||
if not solid:
|
||||
continue
|
||||
ymin, ymax = problem.bounds[1], problem.bounds[3]
|
||||
tracks = 0
|
||||
for low, high in open_intervals(solid, ymin, ymax):
|
||||
bottom = low + width / 2 + (problem.clearance if low != ymin else 0)
|
||||
top = high - width / 2 - (problem.clearance if high != ymax else 0)
|
||||
room = top - bottom + 2 * TOLERANCE_LINEAR
|
||||
if room >= 0:
|
||||
tracks += 1 + floor(room / max(TOLERANCE_LINEAR, pitch - TOLERANCE_LINEAR))
|
||||
max_routed = len(problem.nets) - crossing + tracks
|
||||
if tracks < crossing and (limit is None or max_routed < limit.max_routed):
|
||||
limit = CapacityLimit(x, crossing, tracks, max_routed)
|
||||
return limit
|
||||
|
||||
|
||||
def port_conflicts(problem: RoutingProblem, options: RoutingOptions) -> tuple[tuple[str, str], ...]:
|
||||
"""Find disjoint fixed-heading terminal pairs with insufficient optical clearance."""
|
||||
_, physical_geometry = resolve_bend_geometry(options.search)
|
||||
if physical_geometry != "arc" or problem.clearance <= TOLERANCE_LINEAR:
|
||||
return ()
|
||||
aligned: dict[tuple[int, int], list[tuple[str, float, float]]] = {}
|
||||
for net in problem.nets:
|
||||
for port in (net.start, net.target):
|
||||
axis = port.r % 180
|
||||
longitudinal, lateral = (port.x, port.y) if axis == 0 else (port.y, port.x)
|
||||
aligned.setdefault((axis, longitudinal), []).append((net.net_id, lateral, net.width))
|
||||
# Each disjoint conflict pair forces at least one route to be omitted.
|
||||
# A terminal's physical cross-section is fixed by its heading and width.
|
||||
pairs = []
|
||||
matched = set()
|
||||
for ports in aligned.values():
|
||||
for (a, y1, w1), (b, y2, w2) in combinations(ports, 2):
|
||||
if a == b or a in matched or b in matched:
|
||||
continue
|
||||
gap = abs(y1 - y2) - (w1 + w2) / 2
|
||||
if gap < problem.clearance - TOLERANCE_LINEAR:
|
||||
pairs.append((a, b))
|
||||
matched.update((a, b))
|
||||
return tuple(pairs)
|
||||
|
|
@ -6,11 +6,13 @@ from collections import defaultdict
|
|||
from dataclasses import dataclass
|
||||
from functools import lru_cache
|
||||
from itertools import combinations_with_replacement, islice, pairwise, product
|
||||
from math import acos, ceil, comb, cos, floor, gcd, isfinite, isqrt, pi, sin
|
||||
from math import acos, ceil, comb, cos, floor, gcd, isfinite, pi, sin
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from shapely.geometry import LineString, box
|
||||
from shapely.geometry import LineString
|
||||
|
||||
from inire.geometry.intervals import Gap, open_intervals
|
||||
from inire.geometry.sbend import exact_sbend_spans
|
||||
from inire.model import resolve_bend_geometry
|
||||
from inire.router._waypoints import compile_waypoints
|
||||
from inire.seeds import PathSeed, SBendSeed, StraightSeed
|
||||
|
|
@ -25,7 +27,6 @@ if TYPE_CHECKING:
|
|||
|
||||
|
||||
Profile = tuple[int, ...]
|
||||
Gap = tuple[float, float]
|
||||
Window = tuple[int, int]
|
||||
JogPivots = tuple[int | None, ...]
|
||||
JogSchedule = tuple[float, tuple[Profile, ...], tuple[JogPivots, ...]]
|
||||
|
|
@ -45,6 +46,17 @@ class _Column:
|
|||
openings: tuple[Gap, ...]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class _ColumnLayout:
|
||||
tracks: tuple[_Track, ...]
|
||||
columns: tuple[_Column, ...]
|
||||
spans: tuple[Window, ...]
|
||||
launch: Profile
|
||||
arrival: Profile
|
||||
widths: tuple[float, ...]
|
||||
preferences: tuple[tuple[float, ...], ...]
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class _BendSequence:
|
||||
offsets: tuple[int, ...]
|
||||
|
|
@ -52,27 +64,6 @@ class _BendSequence:
|
|||
cost: float
|
||||
|
||||
|
||||
def rectangular_obstacle_bounds(problem: RoutingProblem) -> tuple[tuple[float, float, float, float], ...] | None:
|
||||
bounds = tuple(tuple(shape.bounds) for shape in problem.static_obstacles)
|
||||
if any(shape.is_empty or not shape.equals(box(*extent)) for shape, extent in zip(problem.static_obstacles, bounds, strict=True)):
|
||||
return None
|
||||
return bounds
|
||||
|
||||
|
||||
def open_intervals(solid: list[Gap], ymin: float, ymax: float) -> tuple[Gap, ...]:
|
||||
openings = []
|
||||
cursor = ymin
|
||||
for bottom, top in sorted(solid):
|
||||
if top <= ymin or bottom >= ymax:
|
||||
continue
|
||||
if cursor < bottom:
|
||||
openings.append((cursor, bottom))
|
||||
cursor = max(cursor, top)
|
||||
if cursor < ymax:
|
||||
openings.append((cursor, ymax))
|
||||
return tuple(openings)
|
||||
|
||||
|
||||
def _columns(problem: RoutingProblem, start: int, finish: int) -> tuple[_Column, ...]:
|
||||
# A bounding rectangle only reserves extra space in this candidate
|
||||
# planner. Capacity proofs still require the actual rectangular obstacles.
|
||||
|
|
@ -113,6 +104,25 @@ def _ordered_tracks(problem: RoutingProblem) -> tuple[_Track, ...]:
|
|||
return tuple(tracks)
|
||||
|
||||
|
||||
def _column_layout(problem: RoutingProblem) -> _ColumnLayout | None:
|
||||
tracks = _ordered_tracks(problem)
|
||||
if len(tracks) < 3 or any(not isfinite(track.net.width) or track.net.width <= 0 for track in tracks):
|
||||
return None
|
||||
start = max(int(track.left.x) for track in tracks)
|
||||
finish = min(int(track.right.x) for track in tracks)
|
||||
columns = _columns(problem, start, finish)
|
||||
if not columns:
|
||||
return None
|
||||
launch = tuple(int(track.left.y) for track in tracks)
|
||||
arrival = tuple(int(track.right.y) for track in tracks)
|
||||
spans = ((start, start), *(column.span for column in columns), (finish, finish))
|
||||
preferences = []
|
||||
for column in columns:
|
||||
fraction = (sum(column.span) / 2 - start) / (finish - start)
|
||||
preferences.append(tuple(a + fraction * (b - a) for a, b in zip(launch, arrival, strict=True)))
|
||||
return _ColumnLayout(tracks, columns, spans, launch, arrival, tuple(track.net.width for track in tracks), tuple(preferences))
|
||||
|
||||
|
||||
def _round_up(y: float, residue: int, modulus: int) -> int:
|
||||
return ceil((y - residue) / modulus) * modulus + residue
|
||||
|
||||
|
|
@ -240,16 +250,6 @@ def _column_profiles(
|
|||
return sorted(profiles, key=lambda row: (sum(abs(a - b) for a, b in zip(row, desired, strict=True)), row))[:140]
|
||||
|
||||
|
||||
def _exact_spans(radius: int) -> dict[int, int]:
|
||||
spans = {}
|
||||
for offset in range(1, 2 * radius):
|
||||
squared = offset * (4 * radius - offset)
|
||||
span = isqrt(squared)
|
||||
if span * span == squared:
|
||||
spans[offset] = span
|
||||
return spans
|
||||
|
||||
|
||||
def _bend_sequences(
|
||||
spans: dict[int, int],
|
||||
radius: int,
|
||||
|
|
@ -410,41 +410,24 @@ def _seeds(
|
|||
return seeds
|
||||
|
||||
|
||||
def column_seed_candidates(
|
||||
def _column_sbend_schedules(
|
||||
problem: RoutingProblem,
|
||||
search: SearchOptions,
|
||||
layout: _ColumnLayout,
|
||||
radius: int,
|
||||
weights: Mapping[str, float],
|
||||
*,
|
||||
weighted: bool,
|
||||
sbend_penalty: float = 0.0,
|
||||
) -> Iterator[dict[str, PathSeed]]:
|
||||
"""Yield candidate routes from configured circular bends and problem geometry."""
|
||||
_, physical_geometry = resolve_bend_geometry(search)
|
||||
bend = min(search.sbend_radii, default=0.0)
|
||||
if problem.initial_paths or physical_geometry != "arc" or not isfinite(bend) or bend <= 0 or bend != int(bend):
|
||||
return
|
||||
tracks = _ordered_tracks(problem)
|
||||
if len(tracks) < 3 or any(not isfinite(track.net.width) or track.net.width <= 0 for track in tracks):
|
||||
return
|
||||
start, finish = max(track.left.x for track in tracks), min(track.right.x for track in tracks)
|
||||
columns = _columns(problem, start, finish)
|
||||
if not columns:
|
||||
return
|
||||
radius = int(bend)
|
||||
spans = _exact_spans(radius)
|
||||
sbend_penalty: float,
|
||||
) -> Iterator[tuple[tuple[_BendSequence, ...], ...]]:
|
||||
spans = exact_sbend_spans(radius)
|
||||
if not spans:
|
||||
return
|
||||
modulus = gcd(*spans)
|
||||
launch, arrival = tuple(track.left.y for track in tracks), tuple(track.right.y for track in tracks)
|
||||
launch, arrival = layout.launch, layout.arrival
|
||||
residues = tuple(y % modulus for y in launch)
|
||||
if tuple(y % modulus for y in arrival) != residues:
|
||||
return
|
||||
widths = tuple(track.net.width for track in tracks)
|
||||
windows = ((start, start), *(column.span for column in columns), (finish, finish))
|
||||
preferences = []
|
||||
for column in columns:
|
||||
share = (sum(column.span) / 2 - start) / (finish - start)
|
||||
preferences.append(tuple(a + share * (b - a) for a, b in zip(launch, arrival, strict=True)))
|
||||
columns, widths, windows, preferences = layout.columns, layout.widths, layout.spans, layout.preferences
|
||||
# The first pass uses moderate lateral shifts. Later passes relax the
|
||||
# spacing or try smaller or larger bends if a transition will not fit.
|
||||
limits = tuple(dict.fromkeys(min(2 * radius - 1, ceil(radius * frac)) for frac in (0.8, 0.4, 1.44)))
|
||||
|
|
@ -476,7 +459,29 @@ def column_seed_candidates(
|
|||
signature = rows, moves
|
||||
if signature not in seen:
|
||||
seen.add(signature)
|
||||
yield _seeds(tracks, windows, moves, radius)
|
||||
yield moves
|
||||
|
||||
|
||||
|
||||
def column_seed_candidates(
|
||||
problem: RoutingProblem,
|
||||
search: SearchOptions,
|
||||
weights: Mapping[str, float],
|
||||
*,
|
||||
weighted: bool,
|
||||
sbend_penalty: float = 0.0,
|
||||
) -> Iterator[dict[str, PathSeed]]:
|
||||
"""Yield candidate routes from configured circular bends and problem geometry."""
|
||||
_, physical_geometry = resolve_bend_geometry(search)
|
||||
bend = min(search.sbend_radii, default=0.0)
|
||||
if problem.initial_paths or physical_geometry != "arc" or not isfinite(bend) or bend <= 0 or bend != int(bend):
|
||||
return
|
||||
layout = _column_layout(problem)
|
||||
if layout is None:
|
||||
return
|
||||
radius = int(bend)
|
||||
for moves in _column_sbend_schedules(problem, layout, radius, weights, weighted=weighted, sbend_penalty=sbend_penalty):
|
||||
yield _seeds(layout.tracks, layout.spans, moves, radius)
|
||||
|
||||
|
||||
def _jog_pivots(
|
||||
|
|
@ -568,41 +573,44 @@ def _jog_seeds(
|
|||
return seeds
|
||||
|
||||
|
||||
def column_jog_candidates(problem: RoutingProblem, search: SearchOptions) -> Iterator[dict[str, PathSeed]]:
|
||||
"""Allocate tracks through ordered apertures using staggered 90-degree jogs."""
|
||||
if problem.initial_paths:
|
||||
return
|
||||
tracks = _ordered_tracks(problem)
|
||||
if len(tracks) < 3 or any(not isfinite(track.net.width) or track.net.width <= 0 for track in tracks):
|
||||
return
|
||||
radii = sorted({int(r) for r in search.bend_radii if isfinite(r) and r > 0 and r == int(r)})
|
||||
if not radii:
|
||||
return
|
||||
start, finish = max(int(track.left.x) for track in tracks), min(int(track.right.x) for track in tracks)
|
||||
columns = _columns(problem, start, finish)
|
||||
if not columns or any(comb(len(tracks) + len(column.openings) - 1, len(column.openings) - 1) > 4096 for column in columns):
|
||||
return
|
||||
launch = tuple(int(track.left.y) for track in tracks)
|
||||
arrival = tuple(int(track.right.y) for track in tracks)
|
||||
widths = tuple(track.net.width for track in tracks)
|
||||
spans = ((start, start), *(column.span for column in columns), (finish, finish))
|
||||
windows = tuple((after, before) for (_, after), (before, _) in pairwise(spans))
|
||||
preferences = []
|
||||
for column in columns:
|
||||
fraction = (sum(column.span) / 2 - start) / (finish - start)
|
||||
preferences.append(tuple(a + fraction * (b - a) for a, b in zip(launch, arrival, strict=True)))
|
||||
def _column_jog_schedules(
|
||||
problem: RoutingProblem,
|
||||
layout: _ColumnLayout,
|
||||
radii: list[int],
|
||||
minimum: float,
|
||||
) -> Iterator[tuple[int, tuple[Profile, ...], tuple[JogPivots, ...]]]:
|
||||
columns, widths, preferences = layout.columns, layout.widths, layout.preferences
|
||||
launch, arrival = layout.launch, layout.arrival
|
||||
windows = tuple((after, before) for (_, after), (before, _) in pairwise(layout.spans))
|
||||
for slack in (1, 0):
|
||||
# Modulus one allows any integer track level, independent of the
|
||||
# set of exact S-bend spans.
|
||||
interior = [
|
||||
_column_profiles(problem, column, widths, (0,) * len(tracks), desired, slack, slack, 1, combinations_limit=8192)
|
||||
_column_profiles(problem, column, widths, (0,) * len(widths), desired, slack, slack, 1, combinations_limit=8192)
|
||||
for column, desired in zip(columns, preferences, strict=True)
|
||||
]
|
||||
for radius in radii:
|
||||
schedules = _jog_schedules(
|
||||
[[launch], *interior, [arrival]], windows, widths, problem.clearance, radius, search.min_straight_length
|
||||
[[launch], *interior, [arrival]], windows, widths, problem.clearance, radius, minimum
|
||||
)
|
||||
for _, rows, moves in schedules:
|
||||
seeds = _jog_seeds(tracks, rows, moves, radius, search)
|
||||
yield radius, rows, moves
|
||||
|
||||
|
||||
|
||||
def column_jog_candidates(problem: RoutingProblem, search: SearchOptions) -> Iterator[dict[str, PathSeed]]:
|
||||
"""Allocate tracks through ordered apertures using staggered 90-degree jogs."""
|
||||
if problem.initial_paths:
|
||||
return
|
||||
radii = sorted({int(r) for r in search.bend_radii if isfinite(r) and r > 0 and r == int(r)})
|
||||
if not radii:
|
||||
return
|
||||
layout = _column_layout(problem)
|
||||
if layout is None or any(
|
||||
comb(len(layout.tracks) + len(column.openings) - 1, len(column.openings) - 1) > 4096 for column in layout.columns
|
||||
):
|
||||
return
|
||||
for radius, rows, moves in _column_jog_schedules(problem, layout, radii, search.min_straight_length):
|
||||
seeds = _jog_seeds(layout.tracks, rows, moves, radius, search)
|
||||
if seeds is not None:
|
||||
yield seeds
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue