From ea5cfe7f31d6fc35a5a61734404516e0cc4cd149 Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Thu, 26 Nov 2026 19:58:46 -0800 Subject: [PATCH] Refactor routing internals and archive retry benchmarks --- DOCS.md | 4 +- docs/architecture.md | 5 +- docs/routing-policy-goal.md | 2 + docs/routing-refactor-plan.md | 59 ++ docs/topological-routing.md | 97 +++ inire/geometry/collision.py | 32 + inire/geometry/components.py | 46 +- inire/geometry/dynamic_path_index.py | 5 +- inire/geometry/intervals.py | 17 + inire/geometry/primitives.py | 17 + inire/geometry/sbend.py | 14 + inire/geometry/static_obstacle_index.py | 3 + inire/results.py | 9 +- inire/router/_astar_admission.py | 80 +-- inire/router/_astar_moves.py | 37 +- inire/router/_astar_types.py | 479 +------------ inire/router/_automatic.py | 267 ++++--- inire/router/_bundle.py | 3 +- inire/router/_capacity.py | 85 +++ inire/router/_columns.py | 184 ++--- inire/router/_compact.py | 8 +- inire/router/_congestion_policy.py | 97 +++ inire/router/_pair_local.py | 119 ++++ inire/router/_perimeter.py | 7 +- inire/router/_route_traces.py | 107 +++ inire/router/_router.py | 652 ++++++------------ inire/router/_routing_policy.py | 111 +-- inire/router/_search.py | 27 +- inire/router/_seed_materialization.py | 43 +- inire/router/_topology.py | 63 +- inire/router/cost.py | 6 +- inire/router/refiner.py | 50 +- .../data/external_routing_benchmarks.json | 1 + inire/tests/example_scenarios.py | 29 +- inire/tests/retry_holdout_benchmarks.py | 265 +++++++ inire/tests/routing_benchmark_case.py | 44 ++ inire/tests/routing_benchmarks.py | 586 ++-------------- inire/tests/routing_corpus.py | 145 ++++ inire/tests/routing_crossing_benchmarks.py | 143 ++++ inire/tests/routing_external_benchmarks.py | 39 ++ inire/tests/routing_gate_benchmarks.py | 352 ++++++++++ inire/tests/stress_routing_benchmarks.py | 5 +- inire/tests/test_api.py | 12 +- inire/tests/test_astar.py | 99 +-- inire/tests/test_capacity.py | 25 + inire/tests/test_collision.py | 82 ++- inire/tests/test_columns.py | 21 + inire/tests/test_components.py | 26 + inire/tests/test_congestion_policy.py | 36 + inire/tests/test_failed_net_congestion.py | 4 +- inire/tests/test_pathfinder.py | 79 +++ inire/tests/test_primitives.py | 13 +- inire/tests/test_routing_benchmark_parity.py | 31 + inire/tests/test_routing_benchmarks.py | 81 ++- inire/tests/test_topology.py | 17 +- inire/tests/trace_recording.py | 80 +++ scripts/benchmark_retry_order.py | 285 ++++++++ scripts/compare_topological_routing.py | 160 ++--- scripts/import_external_routing_benchmarks.py | 5 +- scripts/record_conflict_trace.py | 129 +--- scripts/record_frontier_trace.py | 114 +-- scripts/record_iteration_trace.py | 126 +--- scripts/record_performance_baseline.py | 6 +- scripts/record_pre_pair_frontier_trace.py | 126 +--- scripts/route_terminal_bench.py | 5 +- scripts/routing_benchmark_parity.py | 192 ++++++ 66 files changed, 3498 insertions(+), 2600 deletions(-) create mode 100644 docs/routing-refactor-plan.md create mode 100644 inire/geometry/intervals.py create mode 100644 inire/geometry/sbend.py create mode 100644 inire/router/_capacity.py create mode 100644 inire/router/_congestion_policy.py create mode 100644 inire/router/_pair_local.py create mode 100644 inire/router/_route_traces.py create mode 100644 inire/tests/retry_holdout_benchmarks.py create mode 100644 inire/tests/routing_benchmark_case.py create mode 100644 inire/tests/routing_corpus.py create mode 100644 inire/tests/routing_crossing_benchmarks.py create mode 100644 inire/tests/routing_external_benchmarks.py create mode 100644 inire/tests/routing_gate_benchmarks.py create mode 100644 inire/tests/test_capacity.py create mode 100644 inire/tests/test_columns.py create mode 100644 inire/tests/test_congestion_policy.py create mode 100644 inire/tests/test_routing_benchmark_parity.py create mode 100644 inire/tests/trace_recording.py create mode 100644 scripts/benchmark_retry_order.py create mode 100644 scripts/routing_benchmark_parity.py diff --git a/DOCS.md b/DOCS.md index 6f3821e..096cc37 100644 --- a/DOCS.md +++ b/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. diff --git a/docs/architecture.md b/docs/architecture.md index 7a375b8..9fd337e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -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. diff --git a/docs/routing-policy-goal.md b/docs/routing-policy-goal.md index b30c647..bd098eb 100644 --- a/docs/routing-policy-goal.md +++ b/docs/routing-policy-goal.md @@ -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 diff --git a/docs/routing-refactor-plan.md b/docs/routing-refactor-plan.md new file mode 100644 index 0000000..fea52f6 --- /dev/null +++ b/docs/routing-refactor-plan.md @@ -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. diff --git a/docs/topological-routing.md b/docs/topological-routing.md index 7f53a81..ea5b99b 100644 --- a/docs/topological-routing.md +++ b/docs/topological-routing.md @@ -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. diff --git a/inire/geometry/collision.py b/inire/geometry/collision.py index 3b0084a..dd6f166 100644 --- a/inire/geometry/collision.py +++ b/inire/geometry/collision.py @@ -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 diff --git a/inire/geometry/components.py b/inire/geometry/components.py index 6e0a293..031911c 100644 --- a/inire/geometry/components.py +++ b/inire/geometry/components.py @@ -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, + ) diff --git a/inire/geometry/dynamic_path_index.py b/inire/geometry/dynamic_path_index.py index 70d4b9f..a0807f8 100644 --- a/inire/geometry/dynamic_path_index.py +++ b/inire/geometry/dynamic_path_index.py @@ -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) diff --git a/inire/geometry/intervals.py b/inire/geometry/intervals.py new file mode 100644 index 0000000..68fbf2a --- /dev/null +++ b/inire/geometry/intervals.py @@ -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) diff --git a/inire/geometry/primitives.py b/inire/geometry/primitives.py index db61198..d76aa13 100644 --- a/inire/geometry/primitives.py +++ b/inire/geometry/primitives.py @@ -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)) diff --git a/inire/geometry/sbend.py b/inire/geometry/sbend.py new file mode 100644 index 0000000..2239dbf --- /dev/null +++ b/inire/geometry/sbend.py @@ -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 diff --git a/inire/geometry/static_obstacle_index.py b/inire/geometry/static_obstacle_index.py index d0b4ad6..9582d50 100644 --- a/inire/geometry/static_obstacle_index.py +++ b/inire/geometry/static_obstacle_index.py @@ -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: diff --git a/inire/results.py b/inire/results.py index 4795f33..83e94f3 100644 --- a/inire/results.py +++ b/inire/results.py @@ -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 diff --git a/inire/router/_astar_admission.py b/inire/router/_astar_admission.py index e1ce3c8..711247e 100644 --- a/inire/router/_astar_admission.py +++ b/inire/router/_astar_admission.py @@ -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,30 +69,16 @@ 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( - base_port, - params[0], - net_width, - params[1], - 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, - clip_margin=config.bend_clip_margin, - dilation=self_dilation, - ) + res_rel = build_component( + base_port, + net_width, + move_class, + params, + collision_type=coll_type, + physical_geometry_type=physical_type, + clip_margin=config.bend_clip_margin, + dilation=self_dilation, + ) except ValueError: return context.move_cache_rel[rel_key] = res_rel @@ -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: diff --git a/inire/router/_astar_moves.py b/inire/router/_astar_moves.py index 3d98d9d..e54bba6 100644 --- a/inire/router/_astar_moves.py +++ b/inire/router/_astar_moves.py @@ -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), diff --git a/inire/router/_astar_types.py b/inire/router/_astar_types.py index 33034c6..8f4fbc3 100644 --- a/inire/router/_astar_types.py +++ b/inire/router/_astar_types.py @@ -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 +_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__ = ( - "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", - ) + __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: diff --git a/inire/router/_automatic.py b/inire/router/_automatic.py index 7d3d2a8..2734766 100644 --- a/inire/router/_automatic.py +++ b/inire/router/_automatic.py @@ -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: - 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): + if self._initial_search_trials(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), diff --git a/inire/router/_bundle.py b/inire/router/_bundle.py index 3654115..59a0b19 100644 --- a/inire/router/_bundle.py +++ b/inire/router/_bundle.py @@ -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( diff --git a/inire/router/_capacity.py b/inire/router/_capacity.py new file mode 100644 index 0000000..1810964 --- /dev/null +++ b/inire/router/_capacity.py @@ -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) diff --git a/inire/router/_columns.py b/inire/router/_columns.py index d89c697..3999504 100644 --- a/inire/router/_columns.py +++ b/inire/router/_columns.py @@ -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) - if seeds is not None: - yield seeds + 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 diff --git a/inire/router/_compact.py b/inire/router/_compact.py index 61e5bc9..ba479bd 100644 --- a/inire/router/_compact.py +++ b/inire/router/_compact.py @@ -11,10 +11,10 @@ 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.geometry.sbend import exact_sbend_spans from inire.model import resolve_bend_geometry from inire.results import RoutingResult -from inire.router._columns import _exact_spans -from inire.router._routing_policy import _local_delta from inire.router._seed_materialization import materialize_path_seed from inire.seeds import Bend90Seed, PathSeed, SBendSeed, StraightSeed @@ -80,7 +80,7 @@ def _candidate_jogs( continue # Move the middle of the jog between two independently positioned # turn lanes. The S-bend stays away from the terminal access cutouts. - for offset, span in reversed(tuple(_exact_spans(radius).items())): + for offset, span in reversed(tuple(exact_sbend_spans(radius).items())): if span > reach: continue available = reach - span @@ -200,7 +200,7 @@ def short_shift_seed_set(problem: RoutingProblem, search: SearchOptions, score: return None if any(net.start.r != net.target.r for net in problem.nets): return None - deltas = [_local_delta(net) for net in problem.nets] + deltas = [port_local_coordinates(net.start, net.target.x, net.target.y) for net in problem.nets] if any(forward <= 0 for forward, _ in deltas) or not any(offset for _, offset in deltas): return None seeds_by_net = [tuple(_shift_seeds(int(forward), int(offset), search)) for forward, offset in deltas] diff --git a/inire/router/_congestion_policy.py b/inire/router/_congestion_policy.py new file mode 100644 index 0000000..1bd0153 --- /dev/null +++ b/inire/router/_congestion_policy.py @@ -0,0 +1,97 @@ +"""Decisions taken between negotiated-congestion iterations.""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from collections.abc import Mapping, Sequence, Set + + from inire.geometry.collision import PathVerificationDetail + from inire.results import RoutingResult + + +@dataclass(slots=True) +class IterationReview: + conflicting_nets: set[str] + conflict_edges: set[tuple[str, str]] + completed_net_ids: set[str] + total_dynamic_collisions: int + + +def review_verified_results( + results: Mapping[str, RoutingResult], + details_by_net: Mapping[str, PathVerificationDetail], +) -> IterationReview: + conflict_edges: set[tuple[str, str]] = set() + conflicting_nets: set[str] = set() + completed_net_ids: set[str] = set() + total_dynamic_collisions = 0 + for net_id, detail in details_by_net.items(): + result = results[net_id] + if not result.reached_target: + continue + total_dynamic_collisions += detail.report.dynamic_collision_count + if result.is_valid: + completed_net_ids.add(net_id) + if detail.conflicting_net_ids: + conflicting_nets.add(net_id) + conflicting_nets.update(detail.conflicting_net_ids) + conflict_edges.update( + (net_id, peer) if net_id < peer else (peer, net_id) + for peer in detail.conflicting_net_ids + if peer != net_id + ) + return IterationReview(conflicting_nets, conflict_edges, completed_net_ids, total_dynamic_collisions) + + +def all_results_reached_target(ordered_net_ids: Sequence[str], results: Mapping[str, RoutingResult]) -> bool: + return len(results) == len(ordered_net_ids) and all(result.reached_target for result in results.values()) + + +def reroute_plan( + ordered_net_ids: Sequence[str], + reroute_net_ids: Set[str], + recent_attempt_work: Mapping[str, int], + *, + best_conflict_edges: int, + results: Mapping[str, RoutingResult], +) -> tuple[list[str], set[str]]: + routed_net_ids = [net_id for net_id in ordered_net_ids if net_id in reroute_net_ids] + if len(reroute_net_ids) >= len(ordered_net_ids) or not recent_attempt_work: + return routed_net_ids, set() + + order_index = {net_id: idx for idx, net_id in enumerate(ordered_net_ids)} + routed_net_ids.sort(key=lambda net_id: (recent_attempt_work.get(net_id, 0), order_index[net_id])) + if len(routed_net_ids) != 4 or best_conflict_edges > 2 or not all_results_reached_target(ordered_net_ids, results): + return routed_net_ids, set() + + heaviest = sorted(routed_net_ids, key=lambda net_id: (-recent_attempt_work.get(net_id, 0), order_index[net_id]))[:2] + return routed_net_ids, {net_id for net_id in heaviest if recent_attempt_work.get(net_id, 0) >= 200} + + +def next_reroute_net_ids( + ordered_net_ids: Sequence[str], + review: IterationReview, + *, + all_reached_target: bool, + has_corridors: bool, +) -> set[str]: + if all_reached_target and 0 < len(review.conflict_edges) <= 3: + return set(review.conflicting_nets) + if has_corridors: + return set(ordered_net_ids).difference(review.completed_net_ids) + return set(ordered_net_ids) + + +def reached_pair_local_plateau(*, improved: bool, all_reached_target: bool, best_conflict_edges: int) -> bool: + # A non-improving iteration with at most two remaining conflicts is + # enough to hand the reached-target layout to bounded pair-local repair. + return not improved and all_reached_target and best_conflict_edges <= 2 + + +def repeated_conflict_count(current_edges: int, previous_edges: int, previous_repeats: int) -> int: + if current_edges and current_edges == previous_edges: + return previous_repeats + 1 + return 0 diff --git a/inire/router/_pair_local.py b/inire/router/_pair_local.py new file mode 100644 index 0000000..8fe23f3 --- /dev/null +++ b/inire/router/_pair_local.py @@ -0,0 +1,119 @@ +"""Candidate search for a pair of conflicting routes in a local routing world.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from inire.geometry.collision import RoutingWorld +from inire.model import RoutingProblem +from inire.results import RoutingResult +from inire.router._astar_types import AStarContext, AStarMetrics, SearchRunConfig +from inire.router._search import incumbent_guidance, route_astar +from inire.router.cost import CostEvaluator +from inire.router.danger_map import DangerMap + +if TYPE_CHECKING: + from collections.abc import Mapping, Set + + from inire.model import NetSpec + + +def _build_pair_local_context( + context: AStarContext, + ordered_nets: tuple[NetSpec, ...], + incumbent_results: Mapping[str, RoutingResult], + pair_order: tuple[str, str], + *, + lock_partial_paths: bool, +) -> AStarContext: + problem = context.problem + objective = context.options.objective + live_world = context.cost_evaluator.collision_engine + static_obstacles = tuple(live_world.iter_static_geometries()) + world = RoutingWorld(clearance=live_world.clearance, safety_zone_radius=live_world.safety_zone_radius) + for obstacle in static_obstacles: + world.add_static_obstacle(obstacle) + for net in ordered_nets: + if net.net_id in pair_order: + continue + result = incumbent_results.get(net.net_id) + if result is None or not result.path or (not lock_partial_paths and not result.reached_target): + continue + for component in result.path: + for polygon in component.physical_geometry: + world.add_static_obstacle(polygon) + + danger_map = DangerMap(bounds=problem.bounds) + danger_map.precompute(list(static_obstacles)) + evaluator = CostEvaluator( + world, + danger_map, + unit_length_cost=objective.unit_length_cost, + greedy_h_weight=context.cost_evaluator.greedy_h_weight, + bend_penalty=objective.bend_penalty, + sbend_penalty=objective.sbend_penalty, + danger_weight=objective.danger_weight, + ) + return AStarContext( + evaluator, + RoutingProblem( + bounds=problem.bounds, + nets=ordered_nets, + static_obstacles=static_obstacles, + clearance=problem.clearance, + safety_zone_radius=problem.safety_zone_radius, + ), + context.options, + metrics=AStarMetrics(), + ) + + +def search_pair_candidate( + context: AStarContext, + ordered_nets: tuple[NetSpec, ...], + incumbent_results: Mapping[str, RoutingResult], + pair_order: tuple[str, str], + *, + needs_self_collision_check: Set[str], + lock_partial_paths: bool, +) -> tuple[dict[str, RoutingResult], int] | None: + """Return both locally verified replacements and their search work.""" + local = _build_pair_local_context(context, ordered_nets, incumbent_results, pair_order, lock_partial_paths=lock_partial_paths) + world = local.cost_evaluator.collision_engine + options = local.options + nets = {net.net_id: net for net in ordered_nets} + replacements: dict[str, RoutingResult] = {} + for net_id in pair_order: + net = nets[net_id] + guidance_seed, guidance_bonus = incumbent_guidance(incumbent_results.get(net_id), options.objective.bend_penalty) + config = SearchRunConfig.from_options( + options, + return_partial=False, + skip_congestion=True, + self_collision_check=net_id in needs_self_collision_check, + guidance_seed=guidance_seed, + guidance_bonus=guidance_bonus, + node_limit=options.search.node_limit, + ) + path = route_astar( + net.start, + net.target, + net.width, + context=local, + metrics=local.metrics, + net_id=net_id, + config=config, + ) + if not path or path[-1].end_port != net.target: + return None + + report = world.verify_path_report(net_id, path) + if not report.is_valid: + return None + replacements[net_id] = RoutingResult(net_id, tuple(path), reached_target=True, report=report) + for component in path: + for polygon in component.physical_geometry: + world.add_static_obstacle(polygon) + local.clear_static_caches() + + return replacements, local.metrics.total_nodes_expanded diff --git a/inire/router/_perimeter.py b/inire/router/_perimeter.py index a4f3426..40e6be1 100644 --- a/inire/router/_perimeter.py +++ b/inire/router/_perimeter.py @@ -7,6 +7,7 @@ from itertools import combinations, pairwise, product from math import ceil, floor, isfinite from typing import TYPE_CHECKING +from inire.geometry.primitives import rotate_cardinal from inire.model import resolve_bend_geometry from inire.router._seed_materialization import materialize_path_seed from inire.router._waypoints import _direction, compile_waypoints, export_waypoints @@ -26,13 +27,13 @@ def residual_dogleg_candidates(problem: RoutingProblem, search: SearchOptions) - (net,) = problem.nets if net.start.r != net.target.r: return - forward, lateral = ((1, 0), (0, 1), (-1, 0), (0, -1))[int(net.start.r) // 90] + heading = int(net.start.r) def project(x: float, y: float) -> tuple[float, float]: - return forward * x + lateral * y, forward * y - lateral * x + return rotate_cardinal(x, y, -heading) def physical(x: int, y: int) -> XY: - return forward * x - lateral * y, lateral * x + forward * y + return rotate_cardinal(x, y, heading) def extent(bounds: tuple[float, float, float, float]) -> tuple[float, float, float, float]: x0, y0, x1, y1 = bounds diff --git a/inire/router/_route_traces.py b/inire/router/_route_traces.py new file mode 100644 index 0000000..e8192ce --- /dev/null +++ b/inire/router/_route_traces.py @@ -0,0 +1,107 @@ +"""Construct diagnostic entries from already collected routing data.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from inire.results import ( + ComponentConflictTrace, + ConflictTraceEntry, + IterationNetAttemptTrace, + IterationTraceEntry, + NetConflictTrace, + RoutingResult, +) + +if TYPE_CHECKING: + from collections.abc import Mapping, Sequence + + from inire.geometry.collision import PathVerificationDetail + from inire.results import ConflictTraceStage + from inire.router._congestion_policy import IterationReview + + +def conflict_trace_entry( + ordered_net_ids: Sequence[str], + results: Mapping[str, RoutingResult], + details_by_net: Mapping[str, PathVerificationDetail], + review: IterationReview, + *, + stage: ConflictTraceStage, + iteration: int | None, +) -> ConflictTraceEntry: + nets = [] + for net_id in ordered_net_ids: + result = results.get(net_id) + if result is None: + result = RoutingResult(net_id=net_id, path=(), reached_target=False) + detail = details_by_net.get(net_id) + component_conflicts = () + conflicting_net_ids = () + if detail is not None: + conflicting_net_ids = detail.conflicting_net_ids + component_conflicts = tuple( + ComponentConflictTrace( + other_net_id=other_net_id, + self_component_index=self_component_index, + other_component_index=other_component_index, + ) + for self_component_index, other_net_id, other_component_index in detail.component_conflicts + ) + nets.append(NetConflictTrace( + net_id=net_id, + outcome=result.outcome, + reached_target=result.reached_target, + report=result.report, + conflicting_net_ids=conflicting_net_ids, + component_conflicts=component_conflicts, + )) + return ConflictTraceEntry( + stage=stage, + iteration=iteration, + completed_net_ids=tuple(sorted(review.completed_net_ids)), + conflict_edges=tuple(sorted(review.conflict_edges)), + nets=tuple(nets), + ) + + +def net_attempt_trace( + net_id: str, + deltas: Mapping[str, int], + *, + reached_target: bool, + guidance_seed_present: bool, +) -> IterationNetAttemptTrace: + return IterationNetAttemptTrace( + net_id=net_id, + reached_target=reached_target, + nodes_expanded=deltas["nodes_expanded"], + congestion_check_calls=deltas["congestion_check_calls"], + pruned_closed_set=deltas["pruned_closed_set"], + pruned_cost=deltas["pruned_cost"], + pruned_hard_collision=deltas["pruned_hard_collision"], + guidance_seed_present=guidance_seed_present, + ) + + +def iteration_trace_entry( + iteration: int, + penalty: float, + routed_net_ids: Sequence[str], + review: IterationReview, + deltas: Mapping[str, int], + net_attempts: Sequence[IterationNetAttemptTrace], +) -> IterationTraceEntry: + return IterationTraceEntry( + iteration=iteration, + congestion_penalty=penalty, + routed_net_ids=tuple(routed_net_ids), + completed_nets=len(review.completed_net_ids), + conflict_edges=len(review.conflict_edges), + total_dynamic_collisions=review.total_dynamic_collisions, + nodes_expanded=deltas["nodes_expanded"], + congestion_check_calls=deltas["congestion_check_calls"], + congestion_candidate_ids=deltas["congestion_candidate_ids"], + congestion_exact_pair_checks=deltas["congestion_exact_pair_checks"], + net_attempts=tuple(net_attempts), + ) diff --git a/inire/router/_router.py b/inire/router/_router.py index 4c2cbd8..53bf2f6 100644 --- a/inire/router/_router.py +++ b/inire/router/_router.py @@ -2,43 +2,48 @@ from __future__ import annotations import random import time -from contextlib import nullcontext +from contextlib import contextmanager, nullcontext from dataclasses import dataclass, field from typing import TYPE_CHECKING -from inire.geometry.collision import RoutingWorld -from inire.model import NetOrder, NetSpec, RoutingProblem, resolve_bend_geometry +from inire.model import NetOrder, NetSpec, resolve_bend_geometry from inire.results import ( - ComponentConflictTrace, ConflictTraceEntry, FrontierPruneSample, IterationNetAttemptTrace, IterationTraceEntry, - NetConflictTrace, NetFrontierTrace, PrePairFrontierTraceEntry, PrePairNetTrace, - RoutingOutcome, RoutingReport, RoutingResult, TopologyReport, ) from inire.router._astar_types import AStarContext, AStarMetrics, FrontierTraceCollector, SearchRunConfig -from inire.router._search import route_astar +from inire.router._congestion_policy import ( + IterationReview as _IterationReview, + all_results_reached_target, + next_reroute_net_ids, + reached_pair_local_plateau, + repeated_conflict_count, + reroute_plan, + review_verified_results, +) +from inire.router._pair_local import search_pair_candidate +from inire.router._route_traces import conflict_trace_entry, iteration_trace_entry, net_attempt_trace +from inire.router._search import incumbent_guidance, route_astar from inire.router._seed_materialization import materialize_path_seed -from inire.router.cost import CostEvaluator -from inire.router.danger_map import DangerMap from inire.router.refiner import PathRefiner if TYPE_CHECKING: - from collections.abc import Callable, Sequence + from collections.abc import Callable, Iterator, Sequence from contextlib import AbstractContextManager from shapely.geometry import Polygon from inire.geometry.collision import PathVerificationDetail from inire.geometry.components import ComponentResult - from inire.results import RoutingOperation + from inire.results import ConflictTraceStage, RoutingOperation from inire.router._topology import Corridor PhaseTimer = Callable[[RoutingOperation], AbstractContextManager[None]] @@ -58,23 +63,13 @@ class _RoutingState: best_completed_nets: int best_conflict_edges: int best_dynamic_collisions: int - last_conflict_signature: tuple[tuple[str, str], ...] last_conflict_edge_count: int repeated_conflict_count: int - pair_local_plateau_count: int recent_attempt_work: dict[str, int] pre_pair_candidate: _PrePairCandidate | None corridors: dict[str, tuple[Corridor, ...]] = field(default_factory=dict) -@dataclass(slots=True) -class _IterationReview: - conflicting_nets: set[str] - conflict_edges: set[tuple[str, str]] - completed_net_ids: set[str] - total_dynamic_collisions: int - - @dataclass(frozen=True, slots=True) class _PairLocalTarget: net_ids: tuple[str, str] @@ -145,12 +140,6 @@ class PathFinder: def _metric_deltas(self, before: dict[str, int], after: dict[str, int]) -> dict[str, int]: return {metric_name: after[metric_name] - before[metric_name] for metric_name in before} - def _results_all_reached_target(self, state: _RoutingState) -> bool: - return ( - len(state.results) == len(state.ordered_net_ids) - and all(result.reached_target for result in state.results.values()) - ) - def _has_incumbent_fallback(self, result: RoutingResult | None) -> bool: return bool(result and result.reached_target and result.path) @@ -164,18 +153,6 @@ class PathFinder: self._install_path(net_id, result.path) return result, guidance_seed_present - def _guidance_for_result( - self, - result: RoutingResult | None, - ) -> tuple[Sequence[ComponentResult] | None, float, bool]: - if result is None or not result.reached_target or not result.path: - return None, 0.0, False - return ( - result.as_seed().segments, - max(10.0, self.context.options.objective.bend_penalty * 0.25), - True, - ) - def _install_path(self, net_id: str, path: Sequence[ComponentResult]) -> None: all_geoms: list[Polygon] = [] all_dilated: list[Polygon] = [] @@ -206,60 +183,9 @@ class PathFinder: ) return ordered_net_ids - def _build_greedy_warm_start_paths( - self, - net_specs: dict[str, NetSpec], - order: NetOrder, - corridors: dict[str, tuple[Corridor, ...]], - ) -> dict[str, tuple[ComponentResult, ...]]: - greedy_paths: dict[str, tuple[ComponentResult, ...]] = {} - temp_obj_ids: list[int] = [] - greedy_node_limit = min(self.context.options.search.node_limit, 2000) - for net_id in self._routing_order(net_specs, order): - net = net_specs[net_id] - h_start = self.context.cost_evaluator.h_manhattan( - net.start, - net.target, - min_bend_radius=self.context.min_bend_radius, - ) - max_cost_limit = max(h_start * 3.0, 2000.0) - candidates = corridors.get(net_id, ()) - run_config = SearchRunConfig.from_options( - self.context.options, - skip_congestion=True, - max_cost=max_cost_limit, - self_collision_check=True, - node_limit=greedy_node_limit, - corridor=candidates[0] if candidates else None, - corridor_strength=self.context.options.topology.guide_strength, - ) - path = route_astar( - net.start, - net.target, - net.width, - context=self.context, - metrics=self.metrics, - net_id=net_id, - config=run_config, - ) - if not path: - continue - self.metrics.total_warm_start_paths_built += 1 - greedy_paths[net_id] = tuple(path) - for result in path: - for polygon in result.physical_geometry: - temp_obj_ids.append(self.context.cost_evaluator.collision_engine.add_static_obstacle(polygon)) - self.context.clear_static_caches() - - for obj_id in temp_obj_ids: - self.context.cost_evaluator.collision_engine.remove_static_obstacle(obj_id) - return greedy_paths - - def _build_corridor_seeds(self, state: _RoutingState) -> dict[str, tuple[ComponentResult, ...]]: - topology = self.context.options.topology + @contextmanager + def _temporary_path_reservations(self) -> Iterator[Callable[[Sequence[ComponentResult]], None]]: world = self.context.cost_evaluator.collision_engine - existing = state.initial_paths or {} - seeds: dict[str, tuple[ComponentResult, ...]] = {} temporary: list[int] = [] def reserve(path: Sequence[ComponentResult]) -> None: @@ -268,6 +194,62 @@ class PathFinder: temporary.append(world.add_static_obstacle(shape)) try: + yield reserve + finally: + for obstacle in temporary: + world.remove_static_obstacle(obstacle) + self.context.clear_static_caches() + + def _build_greedy_warm_start_paths( + self, + net_specs: dict[str, NetSpec], + order: NetOrder, + corridors: dict[str, tuple[Corridor, ...]], + ) -> dict[str, tuple[ComponentResult, ...]]: + greedy_paths: dict[str, tuple[ComponentResult, ...]] = {} + greedy_node_limit = min(self.context.options.search.node_limit, 2000) + with self._temporary_path_reservations() as reserve: + for net_id in self._routing_order(net_specs, order): + net = net_specs[net_id] + h_start = self.context.cost_evaluator.h_manhattan( + net.start, + net.target, + min_bend_radius=self.context.min_bend_radius, + ) + max_cost_limit = max(h_start * 3.0, 2000.0) + candidates = corridors.get(net_id, ()) + run_config = SearchRunConfig.from_options( + self.context.options, + skip_congestion=True, + max_cost=max_cost_limit, + self_collision_check=True, + node_limit=greedy_node_limit, + corridor=candidates[0] if candidates else None, + corridor_strength=self.context.options.topology.guide_strength, + ) + path = route_astar( + net.start, + net.target, + net.width, + context=self.context, + metrics=self.metrics, + net_id=net_id, + config=run_config, + ) + if not path: + continue + self.metrics.total_warm_start_paths_built += 1 + greedy_paths[net_id] = tuple(path) + reserve(path) + self.context.clear_static_caches() + return greedy_paths + + def _build_corridor_seeds(self, state: _RoutingState) -> dict[str, tuple[ComponentResult, ...]]: + topology = self.context.options.topology + world = self.context.cost_evaluator.collision_engine + existing = state.initial_paths or {} + seeds: dict[str, tuple[ComponentResult, ...]] = {} + with self._temporary_path_reservations() as reserve: for net_id, path in existing.items(): if path and path[-1].end_port == state.net_specs[net_id].target and world.verify_path_report(net_id, path).is_valid: reserve(path) @@ -299,10 +281,6 @@ class PathFinder: self.metrics.total_warm_start_paths_built += 1 reserve(path) break - finally: - for obstacle in temporary: - world.remove_static_obstacle(obstacle) - self.context.clear_static_caches() return seeds def _prepare_topology(self, state: _RoutingState, corridors: dict[str, tuple[Corridor, ...]] | None) -> None: @@ -321,7 +299,7 @@ class PathFinder: if corridors is None: corridors = plan_corridors( self.context.problem.bounds, - world._static_obstacles.geometries.values(), + world.iter_static_geometries(), [state.net_specs[net_id] for net_id in state.ordered_net_ids], clearance=world.clearance, bend_radius=min(self.context.options.search.bend_radii, default=0.0), @@ -357,17 +335,14 @@ class PathFinder: best_completed_nets=-1, best_conflict_edges=10**9, best_dynamic_collisions=10**9, - last_conflict_signature=(), last_conflict_edge_count=0, repeated_conflict_count=0, - pair_local_plateau_count=0, recent_attempt_work={}, pre_pair_candidate=None, ) self._prepare_topology(state, corridors) if state.initial_paths is None and congestion.warm_start_enabled: state.initial_paths = self._build_greedy_warm_start_paths(net_specs, congestion.net_order, state.corridors) - self.context.clear_static_caches() if state.corridors and state.initial_paths and congestion.max_iterations > 0: world = self.context.cost_evaluator.collision_engine for net_id, path in state.initial_paths.items(): @@ -435,7 +410,6 @@ class PathFinder: state, state.results, details_by_net, - review, ) return details_by_net, review @@ -475,7 +449,7 @@ class PathFinder: self, state: _RoutingState, *, - stage: str, + stage: ConflictTraceStage, iteration: int | None, results: dict[str, RoutingResult], details_by_net: dict[str, PathVerificationDetail], @@ -484,43 +458,8 @@ class PathFinder: if not self.context.options.diagnostics.capture_conflict_trace: return - nets = [] - for net_id in state.ordered_net_ids: - result = results.get(net_id) - if result is None: - result = RoutingResult(net_id=net_id, path=(), reached_target=False) - detail = details_by_net.get(net_id) - component_conflicts = () - conflicting_net_ids = () - if detail is not None: - conflicting_net_ids = detail.conflicting_net_ids - component_conflicts = tuple( - ComponentConflictTrace( - other_net_id=other_net_id, - self_component_index=self_component_index, - other_component_index=other_component_index, - ) - for self_component_index, other_net_id, other_component_index in detail.component_conflicts - ) - nets.append( - NetConflictTrace( - net_id=net_id, - outcome=result.outcome, - reached_target=result.reached_target, - report=result.report, - conflicting_net_ids=tuple(conflicting_net_ids), - component_conflicts=component_conflicts, - ) - ) - self.conflict_trace.append( - ConflictTraceEntry( - stage=stage, # type: ignore[arg-type] - iteration=iteration, - completed_net_ids=tuple(sorted(review.completed_net_ids)), - conflict_edges=tuple(sorted(review.conflict_edges)), - nets=tuple(nets), - ) + conflict_trace_entry(state.ordered_net_ids, results, details_by_net, review, stage=stage, iteration=iteration) ) def _build_frontier_hotspot_bounds( @@ -582,6 +521,31 @@ class PathFinder: return tuple(hotspot_bounds) + @contextmanager + def _frontier_replay(self, net_id: str, path: tuple[ComponentResult, ...]) -> Iterator[AStarMetrics]: + """Use scratch counters while replaying a net with its path temporarily removed.""" + context = self.context + world = context.cost_evaluator.collision_engine + danger_map = context.cost_evaluator.danger_map + context_metrics, world_metrics = context.metrics, world.metrics + danger_metrics = danger_map.metrics if danger_map is not None else None + scratch_metrics = AStarMetrics() + try: + context.metrics = world.metrics = scratch_metrics + if danger_map is not None: + danger_map.metrics = scratch_metrics + + world.remove_path(net_id) + try: + yield scratch_metrics + finally: + if path: + self._install_path(net_id, path) + finally: + context.metrics, world.metrics = context_metrics, world_metrics + if danger_map is not None: + danger_map.metrics = danger_metrics + def _capture_single_frontier_trace( self, state: _RoutingState, @@ -599,75 +563,50 @@ class PathFinder: pruned_cost=0, ) - original_metrics = self.metrics - original_context_metrics = self.context.metrics - original_engine_metrics = self.context.cost_evaluator.collision_engine.metrics - original_danger_metrics = None - if self.context.cost_evaluator.danger_map is not None: - original_danger_metrics = self.context.cost_evaluator.danger_map.metrics + guidance_seed = result.as_seed().segments if result.path else None + guidance_bonus = max(10.0, self.context.options.objective.bend_penalty * 0.25) if guidance_seed else 0.0 + collector = FrontierTraceCollector(hotspot_bounds=hotspot_bounds) + run_config = SearchRunConfig.from_options( + self.context.options, + return_partial=True, + store_expanded=False, + guidance_seed=guidance_seed, + guidance_bonus=guidance_bonus, + frontier_trace=collector, + self_collision_check=(net_id in state.needs_self_collision_check), + node_limit=self.context.options.search.node_limit, + ) - try: - scratch_metrics = AStarMetrics() - self.context.metrics = scratch_metrics - self.context.cost_evaluator.collision_engine.metrics = scratch_metrics - if self.context.cost_evaluator.danger_map is not None: - self.context.cost_evaluator.danger_map.metrics = scratch_metrics - - guidance_seed = result.as_seed().segments if result.path else None - guidance_bonus = 0.0 - if guidance_seed: - guidance_bonus = max(10.0, self.context.options.objective.bend_penalty * 0.25) - collector = FrontierTraceCollector(hotspot_bounds=hotspot_bounds) - run_config = SearchRunConfig.from_options( - self.context.options, - return_partial=True, - store_expanded=False, - guidance_seed=guidance_seed, - guidance_bonus=guidance_bonus, - frontier_trace=collector, - self_collision_check=(net_id in state.needs_self_collision_check), - node_limit=self.context.options.search.node_limit, - ) - - self.context.cost_evaluator.collision_engine.remove_path(net_id) - try: - route_astar( - state.net_specs[net_id].start, - state.net_specs[net_id].target, - state.net_specs[net_id].width, - context=self.context, - metrics=scratch_metrics, - net_id=net_id, - config=run_config, - ) - finally: - if result.path: - self._install_path(net_id, result.path) - - return NetFrontierTrace( + net = state.net_specs[net_id] + with self._frontier_replay(net_id, result.path) as scratch_metrics: + route_astar( + net.start, + net.target, + net.width, + context=self.context, + metrics=scratch_metrics, net_id=net_id, - hotspot_bounds=hotspot_bounds, - pruned_closed_set=collector.pruned_closed_set, - pruned_hard_collision=collector.pruned_hard_collision, - pruned_self_collision=collector.pruned_self_collision, - pruned_cost=collector.pruned_cost, - samples=tuple( - FrontierPruneSample( - reason=reason, # type: ignore[arg-type] - move_type=move_type, - hotspot_index=hotspot_index, - parent_state=parent_state, - end_state=end_state, - ) - for reason, move_type, hotspot_index, parent_state, end_state in collector.samples - ), + config=run_config, ) - finally: - self.metrics = original_metrics - self.context.metrics = original_context_metrics - self.context.cost_evaluator.collision_engine.metrics = original_engine_metrics - if self.context.cost_evaluator.danger_map is not None: - self.context.cost_evaluator.danger_map.metrics = original_danger_metrics + + return NetFrontierTrace( + net_id=net_id, + hotspot_bounds=hotspot_bounds, + pruned_closed_set=collector.pruned_closed_set, + pruned_hard_collision=collector.pruned_hard_collision, + pruned_self_collision=collector.pruned_self_collision, + pruned_cost=collector.pruned_cost, + samples=tuple( + FrontierPruneSample( + reason=reason, # type: ignore[arg-type] + move_type=move_type, + hotspot_index=hotspot_index, + parent_state=parent_state, + end_state=end_state, + ) + for reason, move_type, hotspot_index, parent_state, end_state in collector.samples + ), + ) def _analyze_results( self, @@ -679,10 +618,6 @@ class PathFinder: ) -> tuple[dict[str, RoutingResult], dict[str, PathVerificationDetail], _IterationReview]: if count_iteration_metrics: self.metrics.total_iteration_reverify_calls += 1 - conflict_edges: set[tuple[str, str]] = set() - conflicting_nets: set[str] = set() - completed_net_ids: set[str] = set() - total_dynamic_collisions = 0 analyzed_results = dict(results) details_by_net: dict[str, PathVerificationDetail] = {} @@ -705,48 +640,23 @@ class PathFinder: reached_target=result.reached_target, report=detail.report, ) - total_dynamic_collisions += detail.report.dynamic_collision_count - if analyzed_results[net_id].outcome == "completed": - completed_net_ids.add(net_id) - if not detail.conflicting_net_ids: - continue - conflicting_nets.add(net_id) - for other_net_id in detail.conflicting_net_ids: - conflicting_nets.add(other_net_id) - if other_net_id == net_id: - continue - conflict_edges.add(tuple(sorted((net_id, other_net_id)))) - + review = review_verified_results(analyzed_results, details_by_net) if count_iteration_metrics: - self.metrics.total_iteration_conflicting_nets += len(conflicting_nets) - self.metrics.total_iteration_conflict_edges += len(conflict_edges) - return ( - analyzed_results, - details_by_net, - _IterationReview( - conflicting_nets=conflicting_nets, - conflict_edges=conflict_edges, - completed_net_ids=completed_net_ids, - total_dynamic_collisions=total_dynamic_collisions, - ), - ) + self.metrics.total_iteration_conflicting_nets += len(review.conflicting_nets) + self.metrics.total_iteration_conflict_edges += len(review.conflict_edges) + return analyzed_results, details_by_net, review def _capture_frontier_trace( self, state: _RoutingState, final_results: dict[str, RoutingResult], + details_by_net: dict[str, PathVerificationDetail], ) -> None: if not self.context.options.diagnostics.capture_frontier_trace: return self.frontier_trace = [] state.results = dict(final_results) - state.results, details_by_net, _ = self._analyze_results( - state.ordered_net_ids, - state.results, - capture_component_conflicts=True, - count_iteration_metrics=False, - ) for net_id in state.ordered_net_ids: result = state.results.get(net_id) detail = details_by_net.get(net_id) @@ -833,61 +743,11 @@ class PathFinder: targets.sort(key=lambda target: min(order_index[target.net_ids[0]], order_index[target.net_ids[1]])) return targets - def _build_pair_local_context( - self, - state: _RoutingState, - incumbent_results: dict[str, RoutingResult], - pair_net_ids: tuple[str, str], - ) -> AStarContext: - problem = self.context.problem - objective = self.context.options.objective - static_obstacles = tuple(self.context.cost_evaluator.collision_engine._static_obstacles.geometries.values()) - engine = RoutingWorld( - clearance=self.context.cost_evaluator.collision_engine.clearance, - safety_zone_radius=self.context.cost_evaluator.collision_engine.safety_zone_radius, - ) - for obstacle in static_obstacles: - engine.add_static_obstacle(obstacle) - for net_id in state.ordered_net_ids: - if net_id in pair_net_ids: - continue - result = incumbent_results.get(net_id) - if result is None or not result.path or (state.corridors and not result.reached_target): - continue - for component in result.path: - for polygon in component.physical_geometry: - engine.add_static_obstacle(polygon) - - danger_map = DangerMap(bounds=problem.bounds) - danger_map.precompute(list(static_obstacles)) - evaluator = CostEvaluator( - engine, - danger_map, - unit_length_cost=objective.unit_length_cost, - greedy_h_weight=self.context.cost_evaluator.greedy_h_weight, - bend_penalty=objective.bend_penalty, - sbend_penalty=objective.sbend_penalty, - danger_weight=objective.danger_weight, - ) - return AStarContext( - evaluator, - RoutingProblem( - bounds=problem.bounds, - nets=tuple(state.net_specs[net_id] for net_id in state.ordered_net_ids), - static_obstacles=static_obstacles, - clearance=problem.clearance, - safety_zone_radius=problem.safety_zone_radius, - ), - self.context.options, - metrics=AStarMetrics(), - ) - def _materialize_pre_pair_frontier_trace( self, state: _RoutingState, results: dict[str, RoutingResult], details_by_net: dict[str, PathVerificationDetail], - review: _IterationReview, ) -> PrePairFrontierTraceEntry | None: candidate = state.pre_pair_candidate if candidate is None: @@ -926,32 +786,6 @@ class PathFinder: nets=tuple(nets), ) - def _build_iteration_reroute_plan( - self, - state: _RoutingState, - reroute_net_ids: set[str], - ) -> tuple[list[str], set[str]]: - routed_net_ids = [net_id for net_id in state.ordered_net_ids if net_id in reroute_net_ids] - capped_net_ids: set[str] = set() - if len(reroute_net_ids) >= len(state.ordered_net_ids) or not state.recent_attempt_work: - return routed_net_ids, capped_net_ids - - order_index = {net_id: idx for idx, net_id in enumerate(state.ordered_net_ids)} - routed_net_ids.sort(key=lambda net_id: (state.recent_attempt_work.get(net_id, 0), order_index[net_id])) - if ( - len(routed_net_ids) == 4 - and state.best_conflict_edges <= 2 - and self._results_all_reached_target(state) - ): - heavy_net_ids = sorted( - routed_net_ids, - key=lambda net_id: (-state.recent_attempt_work.get(net_id, 0), order_index[net_id]), - )[:2] - capped_net_ids = { - net_id for net_id in heavy_net_ids if state.recent_attempt_work.get(net_id, 0) >= 200 - } - return routed_net_ids, capped_net_ids - def _update_pre_pair_candidate( self, state: _RoutingState, @@ -962,7 +796,11 @@ class PathFinder: attempt_traces: list[IterationNetAttemptTrace], review: _IterationReview, ) -> None: - if self._results_all_reached_target(state) and len(reroute_net_ids) < len(state.ordered_net_ids) and review.conflict_edges: + if ( + len(reroute_net_ids) < len(state.ordered_net_ids) + and review.conflict_edges + and all_results_reached_target(state.ordered_net_ids, state.results) + ): state.pre_pair_candidate = _PrePairCandidate( iteration=iteration, routed_net_ids=tuple(routed_net_ids), @@ -972,103 +810,6 @@ class PathFinder: return state.pre_pair_candidate = None - def _next_reroute_net_ids( - self, - state: _RoutingState, - review: _IterationReview, - ) -> set[str]: - if self._results_all_reached_target(state) and 0 < len(review.conflict_edges) <= 3: - return set(review.conflicting_nets) - if state.corridors: - return set(state.ordered_net_ids).difference(review.completed_net_ids) - return set(state.ordered_net_ids) - - def _should_stop_for_pair_local_plateau( - self, - state: _RoutingState, - *, - improved: bool, - ) -> bool: - if improved: - state.pair_local_plateau_count = 0 - return False - if self._results_all_reached_target(state) and state.best_conflict_edges <= 2: - # Once the run is fully reached-target and already in the final <=2-edge - # basin, another non-improving negotiated iteration is just churn before - # the bounded pair-local repair. - state.pair_local_plateau_count += 1 - return state.pair_local_plateau_count >= 1 - state.pair_local_plateau_count = 0 - return False - - def _update_repeated_conflict_state( - self, - state: _RoutingState, - review: _IterationReview, - ) -> bool: - current_signature = tuple(sorted(review.conflict_edges)) - repeated = ( - bool(current_signature) - and ( - current_signature == state.last_conflict_signature - or len(current_signature) == state.last_conflict_edge_count - ) - ) - state.repeated_conflict_count = state.repeated_conflict_count + 1 if repeated else 0 - state.last_conflict_signature = current_signature - state.last_conflict_edge_count = len(current_signature) - return state.repeated_conflict_count >= 2 - - def _run_pair_local_attempt( - self, - state: _RoutingState, - incumbent_results: dict[str, RoutingResult], - pair_order: tuple[str, str], - ) -> tuple[dict[str, RoutingResult], int] | None: - local_context = self._build_pair_local_context(state, incumbent_results, pair_order) - local_results = dict(incumbent_results) - - for net_id in pair_order: - net = state.net_specs[net_id] - guidance_seed, guidance_bonus, _ = self._guidance_for_result(incumbent_results.get(net_id)) - - run_config = SearchRunConfig.from_options( - self.context.options, - return_partial=False, - skip_congestion=True, - self_collision_check=(net_id in state.needs_self_collision_check), - guidance_seed=guidance_seed, - guidance_bonus=guidance_bonus, - node_limit=self.context.options.search.node_limit, - ) - path = route_astar( - net.start, - net.target, - net.width, - context=local_context, - metrics=local_context.metrics, - net_id=net_id, - config=run_config, - ) - if not path or path[-1].end_port != net.target: - return None - - report = local_context.cost_evaluator.collision_engine.verify_path_report(net_id, path) - if not report.is_valid: - return None - local_results[net_id] = RoutingResult( - net_id=net_id, - path=tuple(path), - reached_target=True, - report=report, - ) - for component in path: - for polygon in component.physical_geometry: - local_context.cost_evaluator.collision_engine.add_static_obstacle(polygon) - local_context.clear_static_caches() - - return local_results, local_context.metrics.total_nodes_expanded - def _apply_pair_local_candidate( self, state: _RoutingState, @@ -1104,17 +845,25 @@ class PathFinder: ) -> _IterationReview: incumbent_results = dict(state.results) incumbent_review = review + ordered_nets = tuple(state.net_specs[net_id] for net_id in state.ordered_net_ids) self.metrics.total_pair_local_search_pairs_considered += 1 for pair_order in self._pair_local_attempt_orders(target): self.metrics.total_pair_local_search_attempts += 1 - candidate = self._run_pair_local_attempt(state, incumbent_results, pair_order) + candidate = search_pair_candidate( + self.context, + ordered_nets, + incumbent_results, + pair_order, + needs_self_collision_check=state.needs_self_collision_check, + lock_partial_paths=not state.corridors, + ) if candidate is None: continue - candidate_results, nodes_expanded = candidate + replacements, nodes_expanded = candidate self.metrics.total_pair_local_search_nodes_expanded += nodes_expanded accepted, next_review = self._apply_pair_local_candidate( state, - candidate_results, + {**incumbent_results, **replacements}, incumbent_results, incumbent_review, ) @@ -1164,15 +913,16 @@ class PathFinder: else: coll_model, _ = resolve_bend_geometry(search) skip_congestion = False - guidance_seed, guidance_bonus, guidance_seed_present = (None, 0.0, False) + guidance_seed, guidance_bonus = None, 0.0 if congestion.use_tiered_strategy and iteration == 0 and not state.corridors: skip_congestion = True if coll_model == "arc": coll_model = "clipped_bbox" elif iteration > 0: - guidance_seed, guidance_bonus, guidance_seed_present = self._guidance_for_result( - state.results.get(net_id) + guidance_seed, guidance_bonus = incumbent_guidance( + state.results.get(net_id), self.context.options.objective.bend_penalty ) + guidance_seed_present = guidance_seed is not None if node_limit_override is not None and self._has_incumbent_fallback(incumbent_fallback): return self._restore_incumbent_fallback(net_id, incumbent_fallback, guidance_seed_present) @@ -1249,7 +999,13 @@ class PathFinder: random.Random(iteration_seed).shuffle(state.ordered_net_ids) iteration_penalty = self.context.congestion_penalty - routed_net_ids, capped_net_ids = self._build_iteration_reroute_plan(state, reroute_net_ids) + routed_net_ids, capped_net_ids = reroute_plan( + state.ordered_net_ids, + reroute_net_ids, + state.recent_attempt_work, + best_conflict_edges=state.best_conflict_edges, + results=state.results, + ) self.metrics.total_nets_carried_forward += len(state.ordered_net_ids) - len(routed_net_ids) iteration_before = {} attempt_traces: list[IterationNetAttemptTrace] = [] @@ -1280,16 +1036,7 @@ class PathFinder: deltas = self._metric_deltas(attempt_before, attempt_after) attempt_work[net_id] = deltas["nodes_expanded"] + deltas["congestion_check_calls"] attempt_traces.append( - IterationNetAttemptTrace( - net_id=net_id, - reached_target=result.reached_target, - nodes_expanded=deltas["nodes_expanded"], - congestion_check_calls=deltas["congestion_check_calls"], - pruned_closed_set=deltas["pruned_closed_set"], - pruned_cost=deltas["pruned_cost"], - pruned_hard_collision=deltas["pruned_hard_collision"], - guidance_seed_present=guidance_seed_present, - ) + net_attempt_trace(net_id, deltas, reached_target=result.reached_target, guidance_seed_present=guidance_seed_present) ) state.recent_attempt_work = attempt_work @@ -1306,19 +1053,7 @@ class PathFinder: iteration_after = self._capture_metric_totals(_ITERATION_TRACE_TOTALS) deltas = self._metric_deltas(iteration_before, iteration_after) self.iteration_trace.append( - IterationTraceEntry( - iteration=iteration, - congestion_penalty=iteration_penalty, - routed_net_ids=tuple(routed_net_ids), - completed_nets=len(review.completed_net_ids), - conflict_edges=len(review.conflict_edges), - total_dynamic_collisions=review.total_dynamic_collisions, - nodes_expanded=deltas["nodes_expanded"], - congestion_check_calls=deltas["congestion_check_calls"], - congestion_candidate_ids=deltas["congestion_candidate_ids"], - congestion_exact_pair_checks=deltas["congestion_exact_pair_checks"], - net_attempts=tuple(attempt_traces), - ) + iteration_trace_entry(iteration, iteration_penalty, routed_net_ids, review, deltas, attempt_traces) ) if iteration_callback: @@ -1365,11 +1100,17 @@ class PathFinder: ): return False - reroute_net_ids = self._next_reroute_net_ids(state, review) - if self._should_stop_for_pair_local_plateau(state, improved=improved): + all_reached = all_results_reached_target(state.ordered_net_ids, state.results) + reroute_net_ids = next_reroute_net_ids( + state.ordered_net_ids, review, all_reached_target=all_reached, has_corridors=bool(state.corridors) + ) + if reached_pair_local_plateau(improved=improved, all_reached_target=all_reached, best_conflict_edges=state.best_conflict_edges): return False - if self._update_repeated_conflict_state(state, review): + edge_count = len(review.conflict_edges) + state.repeated_conflict_count = repeated_conflict_count(edge_count, state.last_conflict_edge_count, state.repeated_conflict_count) + state.last_conflict_edge_count = edge_count + if state.repeated_conflict_count >= 2: return False self.context.congestion_penalty *= congestion.multiplier return False @@ -1396,7 +1137,8 @@ class PathFinder: report=result.report, ) - def _verify_results(self, state: _RoutingState) -> dict[str, RoutingResult]: + def _verify_results(self, state: _RoutingState) -> tuple[dict[str, RoutingResult], dict[str, PathVerificationDetail]]: + diagnostics = self.context.options.diagnostics final_results: dict[str, RoutingResult] = {} details_by_net: dict[str, PathVerificationDetail] = {} for net in self.context.problem.nets: @@ -1404,10 +1146,11 @@ class PathFinder: if not result or not result.path: final_results[net.net_id] = RoutingResult(net_id=net.net_id, path=(), reached_target=False) continue + capture_conflicts = diagnostics.capture_conflict_trace or (diagnostics.capture_frontier_trace and result.reached_target) detail = self.context.cost_evaluator.collision_engine.verify_path_details( net.net_id, result.path, - capture_component_conflicts=self.context.options.diagnostics.capture_conflict_trace, + capture_component_conflicts=capture_conflicts, ) details_by_net[net.net_id] = detail final_results[net.net_id] = RoutingResult( @@ -1416,13 +1159,8 @@ class PathFinder: reached_target=result.reached_target, report=detail.report, ) - if self.context.options.diagnostics.capture_conflict_trace: - _, _, review = self._analyze_results( - state.ordered_net_ids, - final_results, - capture_component_conflicts=True, - count_iteration_metrics=False, - ) + if diagnostics.capture_conflict_trace: + review = review_verified_results(final_results, details_by_net) self._capture_conflict_trace_entry( state, stage="final", @@ -1431,7 +1169,7 @@ class PathFinder: details_by_net=details_by_net, review=review, ) - return final_results + return final_results, details_by_net def route_all( self, @@ -1461,6 +1199,6 @@ class PathFinder: with phase_timer("refine") if phase_timer is not None and self.context.options.refinement.enabled else nullcontext(): self._refine_results(state) with phase_timer("verify") if phase_timer is not None else nullcontext(): - final_results = self._verify_results(state) - self._capture_frontier_trace(state, final_results) + final_results, details_by_net = self._verify_results(state) + self._capture_frontier_trace(state, final_results, details_by_net) return final_results diff --git a/inire/router/_routing_policy.py b/inire/router/_routing_policy.py index 981ad9f..f678b4d 100644 --- a/inire/router/_routing_policy.py +++ b/inire/router/_routing_policy.py @@ -11,12 +11,14 @@ from shapely.geometry import Point from inire.constants import TOLERANCE_LINEAR from inire.geometry.collision import RoutingWorld from inire.geometry.components import Straight +from inire.geometry.primitives import port_local_coordinates from inire.model import resolve_bend_geometry from inire.results import RoutingResult, RoutingStage from inire.router._stack import route_once if TYPE_CHECKING: from collections.abc import Callable + from typing import Literal from shapely.geometry import Polygon @@ -31,22 +33,31 @@ class RouteCall(Protocol): def __call__(self, problem: RoutingProblem, *, options: RoutingOptions) -> RoutingRunResult: ... -PROBE_FIRST_POLICIES = ("direct-probe-first", "direct-probe-near-port") -PROBE_POLICIES = (*PROBE_FIRST_POLICIES, "direct-probe-after") -DIRECT_POLICIES = ( - "direct-guide", - "direct-seed", - "direct-adaptive", - "direct-adaptive-retry", - "direct-cull", - "direct-lookahead", - "direct-budgeted-retry", - "direct-lookahead-retry", - *PROBE_POLICIES, -) -LOOKAHEAD_POLICIES = ("direct-lookahead", "direct-lookahead-retry", *PROBE_POLICIES) -CONNECTIVITY_POLICIES = ("direct-cull", *LOOKAHEAD_POLICIES) -BUDGETED_POLICIES = ("direct-budgeted-retry", "direct-lookahead-retry", *PROBE_POLICIES) +@dataclass(frozen=True, slots=True) +class _DirectPolicy: + residual_mode: Literal["guide", "seed"] | None = None + check_connectivity: bool = False + reorder_disconnected: bool = False + split_budget: bool = False + probe: Literal["first", "near-port", "after"] | None = None + retry_unresolved: bool = False + + +_LOOKAHEAD_RETRY = _DirectPolicy(check_connectivity=True, reorder_disconnected=True, split_budget=True) +_DIRECT_POLICY_SETTINGS = { + "direct-guide": _DirectPolicy(residual_mode="guide"), + "direct-seed": _DirectPolicy(residual_mode="seed"), + "direct-adaptive": _DirectPolicy(), + "direct-adaptive-retry": _DirectPolicy(retry_unresolved=True), + "direct-cull": _DirectPolicy(check_connectivity=True), + "direct-lookahead": _DirectPolicy(check_connectivity=True, reorder_disconnected=True), + "direct-budgeted-retry": _DirectPolicy(split_budget=True), + "direct-lookahead-retry": _LOOKAHEAD_RETRY, + "direct-probe-first": replace(_LOOKAHEAD_RETRY, probe="first"), + "direct-probe-near-port": replace(_LOOKAHEAD_RETRY, probe="near-port"), + "direct-probe-after": replace(_LOOKAHEAD_RETRY, probe="after"), +} +DIRECT_POLICIES = tuple(_DIRECT_POLICY_SETTINGS) @dataclass(frozen=True, slots=True) @@ -57,25 +68,35 @@ class LockPlan: @dataclass(frozen=True, slots=True) class Trial: + """A checked result and its eligibility for automatic selection. + + A local check or residual search can establish coverage worth verifying + on the whole layout. Only eligible trials may win final selection. + """ + run: RoutingRunResult stage: RoutingStage valid_costs: dict[str, float] - selectable: bool = True + selection: Literal["eligible", "local-only", "requires-layout-check", "incomplete-layout", "changed-net-set"] = "eligible" + + @property + def selectable(self) -> bool: + return self.selection == "eligible" + + def as_replacement_for(self, incumbent: Trial) -> Trial: + if self.valid_costs.keys() == incumbent.valid_costs.keys(): + return self + return replace(self, selection="changed-net-set") def improves_on(self, other: Trial) -> bool: + """Prefer greater coverage, then lower cost within the same net set.""" return len(self.valid_costs) > len(other.valid_costs) or ( self.valid_costs.keys() == other.valid_costs.keys() and sum(self.valid_costs.values()) < sum(other.valid_costs.values()) ) -def _local_delta(net: NetSpec) -> tuple[float, float]: - heading = ((1, 0), (0, 1), (-1, 0), (0, -1))[int(net.start.r) // 90] - dx, dy = net.target.x - net.start.x, net.target.y - net.start.y - return dx * heading[0] + dy * heading[1], dy * heading[0] - dx * heading[1] - - def _is_short_shift(net: NetSpec, max_offset: float) -> bool: - forward, lateral = _local_delta(net) + forward, lateral = port_local_coordinates(net.start, net.target.x, net.target.y) return net.start.r == net.target.r and forward > 0 and 0 < abs(lateral) < max_offset @@ -94,13 +115,13 @@ def _direct_paths( ordered = list(problem.nets) order = options.congestion.net_order if order != "user": - ordered.sort(key=lambda net: sum(map(abs, _local_delta(net))), reverse=order == "longest") + ordered.sort(key=lambda net: sum(map(abs, port_local_coordinates(net.start, net.target.x, net.target.y))), reverse=order == "longest") if priority: ordered.sort(key=lambda net: net.net_id not in priority) paths = {} for net in ordered: - forward, lateral = _local_delta(net) + forward, lateral = port_local_coordinates(net.start, net.target.x, net.target.y) if net.start.r != net.target.r or forward <= 0 or lateral: continue component = Straight.generate(net.start, forward, net.width, dilation=problem.clearance / 2) @@ -155,12 +176,12 @@ def _plan_locks( problem: RoutingProblem, board: Polygon, options: RoutingOptions, - strategy: str, + policy: _DirectPolicy, *, priority: frozenset[str] = frozenset(), ) -> LockPlan: direct = _direct_paths(problem, board, options, priority=priority) - disconnected = _disconnected_nets(problem, board, options, direct) if direct and strategy in CONNECTIVITY_POLICIES else frozenset() + disconnected = _disconnected_nets(problem, board, options, direct) if direct and policy.check_connectivity else frozenset() return LockPlan(direct, disconnected) @@ -183,10 +204,11 @@ def _route_residual( direct = locks.direct problem = _residual_problem(problem, locks) residual = problem.nets + residual_mode = _DIRECT_POLICY_SETTINGS[policy].residual_mode if not residual: mode = "off" - elif policy in ("direct-guide", "direct-seed"): - mode = "guide" if policy == "direct-guide" else "seed" + elif residual_mode is not None: + mode = residual_mode else: max_offset = 2 * max(options.search.sbend_radii, default=0) mode = "guide" if any(_is_short_shift(net, max_offset) for net in residual) else "seed" @@ -273,14 +295,16 @@ def _direct_trials( run_route: RouteCall = route_once, score: Scorer = _length, check_trial: CheckTrial | None = None, + recover_before_retry: Callable[[Trial], list[Trial]] | None = None, ) -> list[Trial]: def check(run: RoutingRunResult, stage: RoutingStage) -> Trial: stage = replace(stage, policy=strategy) return _trial(run, stage, board, score=score) if check_trial is None else check_trial(run, stage) - locks = _plan_locks(problem, board, options, strategy) - if locks.disconnected and strategy in LOOKAHEAD_POLICIES: - candidate = _plan_locks(problem, board, options, strategy, priority=locks.disconnected) + policy = _DIRECT_POLICY_SETTINGS[strategy] + locks = _plan_locks(problem, board, options, policy) + if locks.disconnected and policy.reorder_disconnected: + candidate = _plan_locks(problem, board, options, policy, priority=locks.disconnected) if len(candidate.disconnected) < len(locks.disconnected): locks = candidate @@ -288,14 +312,14 @@ def _direct_trials( retry_locks = None probe_limit = 0 can_reorder = 0 < len(locks.direct) < len(problem.nets) - if can_reorder and strategy in BUDGETED_POLICIES and options.search.node_limit > 1: + if can_reorder and policy.split_budget and options.search.node_limit > 1: priority = frozenset(net.net_id for net in problem.nets if net.net_id not in locks.direct) - candidate = _plan_locks(problem, board, options, strategy, priority=priority) + candidate = _plan_locks(problem, board, options, policy, priority=priority) if candidate.direct.keys() != locks.direct.keys() and len(candidate.disconnected) <= len(locks.disconnected): retry_locks = candidate limit = options.search.node_limit - if strategy in PROBE_POLICIES and ( - strategy != "direct-probe-near-port" or _lock_near_new_port(problem, options, locks, retry_locks) + if policy.probe is not None and ( + policy.probe != "near-port" or _lock_near_new_port(problem, options, locks, retry_locks) ): probe_limit = min(32, limit // 3) remaining = limit - probe_limit @@ -304,7 +328,7 @@ def _direct_trials( retry_options = replace(options, search=replace(options.search, node_limit=remaining - first_limit)) trials = [] - if probe_limit and strategy in PROBE_FIRST_POLICIES: + if probe_limit and policy.probe in ("first", "near-port"): probe = _lattice_probe(problem, options, probe_limit, run_route=run_route, check_trial=check) trials.append(probe) if len(probe.valid_costs) == len(problem.nets): @@ -315,18 +339,23 @@ def _direct_trials( if len(first.valid_costs) == len(problem.nets): return trials - if probe_limit and strategy == "direct-probe-after": + if probe_limit and policy.probe == "after": probe = _lattice_probe(problem, options, probe_limit, run_route=run_route, check_trial=check) trials.append(probe) if len(probe.valid_costs) == len(problem.nets): return trials - if strategy == "direct-adaptive-retry" and can_reorder: + if policy.retry_unresolved and can_reorder: unresolved = frozenset(first.run.results_by_net.keys() - first.valid_costs.keys()) - candidate = _plan_locks(problem, board, options, strategy, priority=unresolved) + candidate = _plan_locks(problem, board, options, policy, priority=unresolved) if candidate.direct.keys() != locks.direct.keys(): retry_locks = candidate if retry_locks is not None: + if recover_before_retry is not None: + recovered = recover_before_retry(first) + trials.extend(recovered) + if any(trial.selectable and len(trial.valid_costs) == len(problem.nets) for trial in recovered): + return trials trials.append(check(*_route_residual(problem, retry_options, strategy, retry_locks, run_route=run_route))) return trials diff --git a/inire/router/_search.py b/inire/router/_search.py index 89bc12d..440bf72 100644 --- a/inire/router/_search.py +++ b/inire/router/_search.py @@ -6,11 +6,22 @@ from typing import TYPE_CHECKING from inire.constants import TOLERANCE_LINEAR from ._astar_moves import expand_moves as _expand_moves -from ._astar_types import AStarContext, AStarMetrics, AStarNode as _AStarNode, SearchRunConfig +from ._astar_types import AStarContext, AStarMetrics, AStarNode as _AStarNode, CongestionCaches, SearchRunConfig if TYPE_CHECKING: from inire.geometry.components import ComponentResult from inire.geometry.primitives import Port + from inire.results import RoutingResult + from inire.seeds import PathSegmentSeed + + +def incumbent_guidance( + result: RoutingResult | None, + bend_penalty: float, +) -> tuple[tuple[PathSegmentSeed, ...] | None, float]: + if result is None or not result.reached_target or not result.path: + return None, 0.0 + return result.as_seed().segments, max(10.0, bend_penalty * 0.25) def _reconstruct_path(end_node: _AStarNode) -> list[ComponentResult]: @@ -40,12 +51,7 @@ def route_astar( context.cost_evaluator.set_target(target) open_set: list[_AStarNode] = [] closed_set: dict[tuple[int, int, int], float] = {} - 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() start_node = _AStarNode( start, @@ -94,12 +100,7 @@ def route_astar( 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=config, ) diff --git a/inire/router/_seed_materialization.py b/inire/router/_seed_materialization.py index 25a76be..5d9ba3d 100644 --- a/inire/router/_seed_materialization.py +++ b/inire/router/_seed_materialization.py @@ -2,12 +2,15 @@ from __future__ import annotations from typing import TYPE_CHECKING -from inire.model import SearchOptions, resolve_bend_geometry -from inire.seeds import Bend90Seed, PathSeed, SBendSeed, StraightSeed +from inire.geometry.components import build_component +from inire.model import resolve_bend_geometry +from inire.seeds import Bend90Seed, SBendSeed, StraightSeed if TYPE_CHECKING: from inire.geometry.components import ComponentResult from inire.geometry.primitives import Port + from inire.model import SearchOptions + from inire.seeds import PathSeed def materialize_path_seed( @@ -18,8 +21,6 @@ def materialize_path_seed( search: SearchOptions, clearance: float, ) -> tuple[ComponentResult, ...]: - from inire.geometry.components import Bend90, SBend, Straight - path: list[ComponentResult] = [] current = start dilation = clearance / 2.0 @@ -28,31 +29,23 @@ def materialize_path_seed( for segment in seed.segments: if isinstance(segment, StraightSeed): - component = Straight.generate(current, segment.length, net_width, dilation=dilation) + kind, parameters = "straight", (segment.length,) elif isinstance(segment, Bend90Seed): - component = Bend90.generate( - current, - segment.radius, - net_width, - segment.direction, - collision_type=bend_collision_type, - physical_geometry_type=bend_physical_geometry, - clip_margin=bend_clip_margin, - dilation=dilation, - ) + kind, parameters = "bend90", (segment.radius, segment.direction) elif isinstance(segment, SBendSeed): - component = SBend.generate( - current, - segment.offset, - segment.radius, - net_width, - collision_type=bend_collision_type, - physical_geometry_type=bend_physical_geometry, - clip_margin=bend_clip_margin, - dilation=dilation, - ) + kind, parameters = "sbend", (segment.offset, segment.radius) else: raise TypeError(f"Unsupported seed segment: {type(segment)!r}") + component = build_component( + current, + net_width, + kind, + parameters, + collision_type=bend_collision_type, + physical_geometry_type=bend_physical_geometry, + clip_margin=bend_clip_margin, + dilation=dilation, + ) path.append(component) current = component.end_port return tuple(path) diff --git a/inire/router/_topology.py b/inire/router/_topology.py index 50bb0cd..9713d8d 100644 --- a/inire/router/_topology.py +++ b/inire/router/_topology.py @@ -302,23 +302,12 @@ def _assign_shared_lanes( return changed -def plan_corridors( - bounds: tuple[float, float, float, float], - obstacles: Iterable[Polygon], +def _endpoint_access( + mesh: _Mesh, nets: Sequence[NetSpec], - *, - clearance: float, bend_radius: float, - limit: int, - joint_net_ids: frozenset[str] = frozenset(), -) -> dict[str, tuple[Corridor, ...]]: - """Plan normal guides, or return a changed assignment for a targeted joint retry.""" - if not nets: - return {} - - mesh = _Mesh(box(*bounds), obstacles, max(net.width for net in nets) / 2, clearance) - board = box(*bounds) - endpoints = {} +) -> tuple[dict[str, tuple[_Endpoint, _Endpoint]], dict[int, list[tuple[str, BaseGeometry]]]]: + endpoints: dict[str, tuple[_Endpoint, _Endpoint]] = {} leads: dict[int, list[tuple[str, BaseGeometry]]] = {} for net in nets: span = hypot(net.target.x - net.start.x, net.target.y - net.start.y) @@ -333,7 +322,19 @@ def plan_corridors( shape = LineString((end.port, end.lead)).buffer(mesh.pitch - 0.01) for cell in mesh.index.query(shape, predicate="intersects"): leads.setdefault(cell, []).append((net.net_id, shape)) + return endpoints, leads + +def _plan_lane_assignments( + mesh: _Mesh, + nets: Sequence[NetSpec], + endpoints: dict[str, tuple[_Endpoint, _Endpoint]], + leads: dict[int, list[tuple[str, BaseGeometry]]], + *, + bend_radius: float, + limit: int, + joint_net_ids: frozenset[str], +) -> dict[str, list[_Assignment]]: occupied: dict[int, list[tuple[str, BaseGeometry]]] = {} demand: dict[Edge, int] = {} users: dict[Edge, list[str]] = {} @@ -370,7 +371,16 @@ def plan_corridors( if joint_net_ids and not _assign_shared_lanes(mesh, assignments_by_net, endpoints, users, occupied, leads, joint_net_ids, bend_radius): return {} + return assignments_by_net + +def _build_corridors( + mesh: _Mesh, + board: Polygon, + nets: Sequence[NetSpec], + assignments_by_net: dict[str, list[_Assignment]], + bend_radius: float, +) -> dict[str, tuple[Corridor, ...]]: guides: dict[str, tuple[Corridor, ...]] = {} for net in nets: if net.net_id not in assignments_by_net: @@ -384,3 +394,26 @@ def plan_corridors( corridors.append(Corridor(line, footprint, max(bend_radius, mesh.pitch))) guides[net.net_id] = tuple(corridors) return guides + + +def plan_corridors( + bounds: tuple[float, float, float, float], + obstacles: Iterable[Polygon], + nets: Sequence[NetSpec], + *, + clearance: float, + bend_radius: float, + limit: int, + joint_net_ids: frozenset[str] = frozenset(), +) -> dict[str, tuple[Corridor, ...]]: + """Plan normal guides, or return a changed assignment for a targeted joint retry.""" + if not nets: + return {} + + board = box(*bounds) + mesh = _Mesh(board, obstacles, max(net.width for net in nets) / 2, clearance) + endpoints, leads = _endpoint_access(mesh, nets, bend_radius) + assignments = _plan_lane_assignments( + mesh, nets, endpoints, leads, bend_radius=bend_radius, limit=limit, joint_net_ids=joint_net_ids + ) + return _build_corridors(mesh, board, nets, assignments, bend_radius) diff --git a/inire/router/cost.py b/inire/router/cost.py index 059c0c8..b18391d 100644 --- a/inire/router/cost.py +++ b/inire/router/cost.py @@ -9,7 +9,7 @@ from inire.constants import TOLERANCE_LINEAR from inire.model import ObjectiveWeights if TYPE_CHECKING: - from collections.abc import Sequence + from collections.abc import Iterable, Mapping, Sequence from typing import Protocol from inire.geometry.collision import RoutingWorld @@ -26,6 +26,10 @@ if TYPE_CHECKING: def move_type(self) -> MoveKind: ... +def weighted_path_length(path: Iterable[ScoreableMove], weights: Mapping[MoveKind, float]) -> float: + return sum(component.length * weights[component.move_type] for component in path) + + class CostEvaluator: __slots__ = ( "collision_engine", diff --git a/inire/router/refiner.py b/inire/router/refiner.py index 3ddd698..4383770 100644 --- a/inire/router/refiner.py +++ b/inire/router/refiner.py @@ -7,7 +7,7 @@ from typing import TYPE_CHECKING, Any from inire.geometry.component_overlap import components_overlap from inire.geometry.components import Bend90, Straight, _advance_port, _bend90_length -from inire.geometry.primitives import rotation_matrix2 +from inire.geometry.primitives import port_local_coordinates, rotation_matrix2 if TYPE_CHECKING: from collections.abc import Iterator, Sequence @@ -68,28 +68,6 @@ class PathRefiner: ports.extend(comp.end_port for comp in path) return ports - def _to_local(self, start: Port, point: Port) -> tuple[float, float]: - dx = point.x - start.x - dy = point.y - start.y - if start.r == 0: - return dx, dy - if start.r == 90: - return dy, -dx - if start.r == 180: - return -dx, -dy - return -dy, dx - - def _to_local_xy(self, start: Port, x: float, y: float) -> tuple[float, float]: - dx = float(x) - start.x - dy = float(y) - start.y - if start.r == 0: - return dx, dy - if start.r == 90: - return dy, -dx - if start.r == 180: - return -dx, -dy - return -dy, dx - def _window_query_bounds(self, start: Port, target: Port, path: Sequence[ComponentResult], pad: float) -> tuple[float, float, float, float]: min_x = float(min(start.x, target.x)) min_y = float(min(start.y, target.y)) @@ -111,12 +89,12 @@ class PathRefiner: net_width: float, radius: float, ) -> list[float]: - local_dx, local_dy = self._to_local(start, target) + local_dx, local_dy = port_local_coordinates(start, target.x, target.y) if local_dx < 4.0 * radius - 0.01: return [] - local_points = [self._to_local(start, start)] - local_points.extend(self._to_local(start, comp.end_port) for comp in window_path) + local_points = [port_local_coordinates(start, start.x, start.y)] + local_points.extend(port_local_coordinates(start, comp.end_port.x, comp.end_port.y) for comp in window_path) min_side = float(min(point[1] for point in local_points)) max_side = float(max(point[1] for point in local_points)) @@ -143,10 +121,10 @@ class PathRefiner: for bounds in self.collision_engine.iter_static_obstacle_bounds(query_bounds): self.context.metrics.total_refinement_static_bounds_checked += 1 local_corners = ( - self._to_local_xy(start, bounds[0], bounds[1]), - self._to_local_xy(start, bounds[0], bounds[3]), - self._to_local_xy(start, bounds[2], bounds[1]), - self._to_local_xy(start, bounds[2], bounds[3]), + port_local_coordinates(start, bounds[0], bounds[1]), + port_local_coordinates(start, bounds[0], bounds[3]), + port_local_coordinates(start, bounds[2], bounds[1]), + port_local_coordinates(start, bounds[2], bounds[3]), ) obs_min_x = min(pt[0] for pt in local_corners) obs_max_x = max(pt[0] for pt in local_corners) @@ -160,10 +138,10 @@ class PathRefiner: for bounds in self.collision_engine.iter_dynamic_path_bounds(query_bounds): self.context.metrics.total_refinement_dynamic_bounds_checked += 1 local_corners = ( - self._to_local_xy(start, bounds[0], bounds[1]), - self._to_local_xy(start, bounds[0], bounds[3]), - self._to_local_xy(start, bounds[2], bounds[1]), - self._to_local_xy(start, bounds[2], bounds[3]), + port_local_coordinates(start, bounds[0], bounds[1]), + port_local_coordinates(start, bounds[0], bounds[3]), + port_local_coordinates(start, bounds[2], bounds[1]), + port_local_coordinates(start, bounds[2], bounds[3]), ) obs_min_x = min(pt[0] for pt in local_corners) obs_max_x = max(pt[0] for pt in local_corners) @@ -191,7 +169,7 @@ class PathRefiner: radius: float, side_extent: float, ) -> list[_DoglegMove] | None: - local_dx, local_dy = self._to_local(start, target) + local_dx, local_dy = port_local_coordinates(start, target.x, target.y) if local_dx < 4.0 * radius - 0.01 or abs(side_extent) < 0.01: return None @@ -282,7 +260,7 @@ class PathRefiner: window_end = ports[end_idx] if window_start.r != window_end.r: continue - local_dx, _ = self._to_local(window_start, window_end) + local_dx, _ = port_local_coordinates(window_start, window_end.x, window_end.y) if local_dx >= 4.0 * min_radius - 0.01: yield start_idx, end_idx diff --git a/inire/tests/data/external_routing_benchmarks.json b/inire/tests/data/external_routing_benchmarks.json index d41fa0b..18cc8fb 100644 --- a/inire/tests/data/external_routing_benchmarks.json +++ b/inire/tests/data/external_routing_benchmarks.json @@ -1671,6 +1671,7 @@ }, { "name": "lidar-clements-8x8", + "expected_routed": 3, "source": "lidar", "member": "clements_8x8/clements_8x8.yml", "crop_um": [ diff --git a/inire/tests/example_scenarios.py b/inire/tests/example_scenarios.py index 2508cc7..9489d98 100644 --- a/inire/tests/example_scenarios.py +++ b/inire/tests/example_scenarios.py @@ -3,6 +3,7 @@ from __future__ import annotations from dataclasses import dataclass from functools import partial from time import perf_counter +from typing import TYPE_CHECKING from collections.abc import Callable from shapely.geometry import Polygon, box @@ -22,14 +23,17 @@ from inire import ( ) from inire.geometry.collision import RoutingWorld from inire.geometry.primitives import Port -from inire.results import RouteMetrics +from inire.results import RouteMetrics, _sum_route_metrics from inire.router._astar_types import AStarContext, AStarMetrics from inire.router._router import PathFinder from inire.router.cost import CostEvaluator from inire.router.danger_map import DangerMap -from inire.tests.routing_benchmarks import BENCHMARK_CASES, EXTERNAL_BENCHMARK_CASES, FALLBACK_BENCHMARK_CASES, BenchmarkCase +from inire.tests.routing_corpus import SNAPSHOT_CASES, profile_options from inire.tests.terminal_bench_scenario import terminal_bench_options, terminal_bench_problem +if TYPE_CHECKING: + from inire.tests.routing_benchmark_case import BenchmarkCase + _SEARCH_FIELDS = set(SearchOptions.__dataclass_fields__) _CONGESTION_FIELDS = set(CongestionOptions.__dataclass_fields__) _REFINEMENT_FIELDS = set(RefinementOptions.__dataclass_fields__) @@ -100,16 +104,6 @@ def _make_run_result( ) -def _sum_metrics(metrics_list: tuple[RouteMetrics, ...]) -> RouteMetrics: - metric_names = RouteMetrics.__dataclass_fields__ - return RouteMetrics( - **{ - name: sum(getattr(metrics, name) for metrics in metrics_list) - for name in metric_names - } - ) - - def _build_evaluator( bounds: tuple[float, float, float, float], *, @@ -276,7 +270,7 @@ def snapshot_example_03() -> ScenarioSnapshot: ) results_b = pathfinder_b.route_all() t1 = perf_counter() - combined_metrics = _sum_metrics((metrics_a, pathfinder_b.metrics.snapshot())) + combined_metrics = _sum_route_metrics((metrics_a, pathfinder_b.metrics.snapshot())) return _make_snapshot("example_03_locked_paths", {**results_a, **results_b}, t1 - t0, combined_metrics) @@ -408,7 +402,7 @@ def snapshot_example_06() -> ScenarioSnapshot: "example_06_bend_collision_models", combined_results, t1 - t0, - _sum_metrics(tuple(route_metrics)), + _sum_route_metrics(route_metrics), ) @@ -610,7 +604,7 @@ def snapshot_example_08() -> ScenarioSnapshot: ) results_custom = pathfinder_custom.route_all() t1 = perf_counter() - combined_metrics = _sum_metrics((pathfinder_std.metrics.snapshot(), pathfinder_custom.metrics.snapshot())) + combined_metrics = _sum_route_metrics((pathfinder_std.metrics.snapshot(), pathfinder_custom.metrics.snapshot())) return _make_snapshot( "example_08_custom_bend_geometry", {**results_std, **results_custom}, @@ -657,7 +651,7 @@ def snapshot_terminal_bench_pr345() -> ScenarioSnapshot: def _snapshot_routing_benchmark(case: BenchmarkCase) -> ScenarioSnapshot: start = perf_counter() - run = route(case.problem, options=case.options) + run = route(case.problem, options=profile_options(case, "fixture")) return _make_snapshot(f"routing_benchmark_{case.name.replace('-', '_')}", run.results_by_net, perf_counter() - start, run.metrics) @@ -691,8 +685,7 @@ PERFORMANCE_SCENARIO_SNAPSHOTS: tuple[tuple[str, ScenarioSnapshotRun], ...] = ( ("terminal_bench_pr345", snapshot_terminal_bench_pr345), *( (f"routing_benchmark_{case.name.replace('-', '_')}", partial(_snapshot_routing_benchmark, case)) - for case in (*BENCHMARK_CASES, *FALLBACK_BENCHMARK_CASES, *EXTERNAL_BENCHMARK_CASES) - if case.name != "terminal-bench" + for case in SNAPSHOT_CASES ), ) diff --git a/inire/tests/retry_holdout_benchmarks.py b/inire/tests/retry_holdout_benchmarks.py new file mode 100644 index 0000000..6c1b12c --- /dev/null +++ b/inire/tests/retry_holdout_benchmarks.py @@ -0,0 +1,265 @@ +"""Feasible placements reserved for evaluating experimental retry orders.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from shapely.geometry import box + +from inire.tests.routing_crossing_benchmarks import _crossing_keepout +from inire.tests.stress_routing_benchmarks import _Track, _waypoint_case + +if TYPE_CHECKING: + from shapely.geometry import Polygon + + from inire.tests.routing_benchmark_case import BenchmarkCase + + +def _shelf( + name: str, + description: str, + *, + width: int, + wall: tuple[int, int, int], + bay: tuple[int, int, int], + launch: tuple[int, int], + arrival: tuple[int, int], + radius: int = 20, + side_block: tuple[Polygon, ...] = (), +) -> BenchmarkCase: + wall_left, wall_right, wall_bottom = wall + left_turn, right_turn, bottom = bay + x_start, y_start = launch + x_finish, y_finish = arrival + return _waypoint_case( + f"retry-holdout-{name}", + description, + (0, 0, width, 520), + ( + box(wall_left, wall_bottom, wall_right, 520), + box(260, 127, 353, 154), + *side_block, + ), + ( + _Track( + "fold", + ( + (x_start, y_start), + (width - 67, y_start), + (width - 67, 414), + (right_turn, 414), + (right_turn, bottom), + (left_turn, bottom), + (left_turn, 414), + (138, 414), + (138, y_finish), + (x_finish, y_finish), + ), + ), + _Track("edge", ((212, 278), (x_finish + 49, 278)), width=4), + _Track("lower", ((x_finish + 26, 171), (61, 171))), + _Track("east", ((width - 116, 461), (right_turn + 58, 461))), + ), + radius=radius, + extra_bend_radius=radius + 7, + ) + + +def _crossing_detour( + name: str, + description: str, + *, + left: int, + right: int, + level: int, + width: int, + floor: tuple[int, int], + left_turn: int, + right_turn: int, + extra: tuple[Polygon, ...] = (), + reverse: frozenset[str] = frozenset(), +) -> BenchmarkCase: + floor_bottom, floor_top = floor + outside_y = level - 50 + tracks = ( + _Track("west_link", ((30, level - 20), (left - 112, level - 20), (left - 72, level), (left - 14, level)), radius=25), + _Track("device_link", ((left + 14, level), (right - 14, level))), + _Track("east_link", ((right + 14, level), (right + 97, level), (right + 137, level + 20), (width - 46, level + 20)), radius=25), + _Track("west_south", ((left, floor_top + 8), (left, level - 14))), + _Track("east_south", ((right, level - 14), (right, floor_top + 9))), + _Track("west_north", ((left, level + 14), (left, level + 48), (left - 20, level + 88), (left - 20, level + 141)), radius=25), + _Track("east_north", ((right + 20, level + 138), (right + 20, level + 84), (right, level + 44), (right, level + 14)), radius=25), + _Track( + "outside_lower", + ( + (35, outside_y), + (left_turn, outside_y), + (left_turn, floor_bottom - 23), + (right_turn, floor_bottom - 23), + (right_turn, outside_y), + (width - 38, outside_y), + ), + width=4, + ), + _Track("outside_upper", ((width - 37, level + 177), (33, level + 177))), + ) + ordered = tuple( + _Track(track.name, tuple(reversed(track.points)), track.width, track.radius) if track.name in reverse else track for track in tracks + ) + return _waypoint_case( + f"retry-holdout-{name}", + description, + (0, 0, width, level + 230), + ( + _crossing_keepout(left, level), + _crossing_keepout(right, level), + box(left - 57, floor_bottom, right + 64, floor_top), + box(left - 122, level + 37, left - 79, level + 81), + *extra, + ), + ordered, + sbend_radius=25, + clearance=4, + ) + + +def _competing_lock( + name: str, + description: str, + *, + inset: int, + radius: int, + top_detour: bool, + branch_stagger: int, + obstacles: tuple[Polygon, ...], + reverse: bool = False, +) -> BenchmarkCase: + y = 190 + detour_y = 296 if top_detour else 68 + branch_start, branch_end = 137 - branch_stagger, 241 + branch_stagger + points = ((inset, y), (78, y), (78, detour_y), (461, detour_y), (461, y), (550 - inset, y)) + trunk = _Track("trunk", tuple(reversed(points)) if reverse else points, width=4) + return _waypoint_case( + f"retry-holdout-{name}", + description, + (0, 0, 550, 365), + obstacles, + ( + trunk, + _Track("west_branch", ((241, branch_start), (241, branch_end))), + _Track("east_branch", ((302, branch_end - 4), (302, branch_start + 7)), width=3), + _Track("upper", ((31, 331), (513, 331))), + _Track("lower", ((508, 38), (30, 38))), + ), + radius=radius, + clearance=5, + ) + + +RETRY_HOLDOUT_CASES = ( + _shelf( + "stepped-roof", + "A widened roof and shifted return bay with a second right-hand obstacle", + width=850, + wall=(431, 529, 332), + bay=(386, 570, 310), + launch=(675, 148), + arrival=(572, 236), + side_block=(box(651, 257, 704, 308),), + ), + _shelf( + "deep-roof", + "A deeper roof and a longer western run past a mixed-width shelf edge", + width=823, + wall=(448, 511, 324), + bay=(400, 553, 298), + launch=(654, 153), + arrival=(579, 221), + radius=22, + ), + _shelf( + "west-roof", + "A western roof position with uneven reach and a blocked approach above the return", + width=835, + wall=(391, 489, 321), + bay=(347, 535, 298), + launch=(655, 159), + arrival=(574, 233), + side_block=(box(188, 335, 230, 361),), + ), + _crossing_detour( + "stretched-crossings", + "A long center link and a raised floor between differently spaced crossing ports", + left=234, + right=399, + level=198, + width=680, + floor=(80, 96), + left_turn=104, + right_turn=557, + ), + _crossing_detour( + "floor-pocket", + "An extra keepout inside the lower detour and staggered port access", + left=216, + right=366, + level=187, + width=648, + floor=(70, 84), + left_turn=99, + right_turn=527, + extra=(box(128, 98, 162, 118),), + ), + _crossing_detour( + "reversed-bank", + "Two reversed links compete with an offset lower approach", + left=231, + right=374, + level=193, + width=657, + floor=(71, 88), + left_turn=105, + right_turn=520, + reverse=frozenset({"outside_lower", "east_link", "west_north"}), + ), + _crossing_detour( + "tight-right-bank", + "A short right bypass and an irregular gap beside the south approach", + left=219, + right=382, + level=191, + width=625, + floor=(66, 80), + left_turn=100, + right_turn=538, + extra=(box(321, 100, 340, 130),), + ), + _competing_lock( + "sealed-trunk", + "A near-boundary trunk can seal two short perpendicular branches", + inset=2, + radius=20, + top_detour=False, + branch_stagger=0, + obstacles=(box(167, 101, 196, 119),), + ), + _competing_lock( + "turn-limited-trunk", + "Topologically connected side gaps are too narrow for a branch turn", + inset=12, + radius=27, + top_detour=True, + branch_stagger=5, + obstacles=(box(346, 237, 381, 261),), + ), + _competing_lock( + "offset-trunk", + "An offset return has wider side room and two independently routed branches", + inset=29, + radius=18, + top_detour=False, + branch_stagger=12, + reverse=True, + obstacles=(box(127, 103, 170, 125), box(374, 248, 409, 268)), + ), +) diff --git a/inire/tests/routing_benchmark_case.py b/inire/tests/routing_benchmark_case.py new file mode 100644 index 0000000..2ddb1b2 --- /dev/null +++ b/inire/tests/routing_benchmark_case.py @@ -0,0 +1,44 @@ +"""Common fixture data and options for the routing benchmark families.""" + +from __future__ import annotations + +from dataclasses import dataclass, replace +from math import pi +from typing import TYPE_CHECKING + +from inire.router._bundle import ordered_bundle_terminal_headings +from inire.tests.terminal_bench_scenario import LENGTH_COST, terminal_bench_options + +if TYPE_CHECKING: + from inire import PathSeed, RoutingOptions, RoutingProblem + + +@dataclass(frozen=True, slots=True) +class BenchmarkCase: + name: str + description: str + problem: RoutingProblem + options: RoutingOptions + reference_paths: tuple[tuple[str, PathSeed], ...] = () + expected_routed: int | None = None + + @property + def routing_bound(self) -> int: + return len(self.problem.nets) if self.expected_routed is None else self.expected_routed + + def fixed_headings_problem(self) -> RoutingProblem: + if self.options.topology.infer_terminal_headings: + return ordered_bundle_terminal_headings(self.problem) + return self.problem + + +def benchmark_options(bend_radius: float, sbend_radius: float | None = None) -> RoutingOptions: + options = terminal_bench_options() + return replace( + options, + search=replace(options.search, bend_radii=(bend_radius,), sbend_radii=(sbend_radius or bend_radius,)), + objective=replace( + options.objective, + bend_penalty=(LENGTH_COST["bend90"] - 1) * (pi * bend_radius / 2) * (bend_radius / 10) ** 0.5, + ), + ) diff --git a/inire/tests/routing_benchmarks.py b/inire/tests/routing_benchmarks.py index af6ecde..ef4f766 100644 --- a/inire/tests/routing_benchmarks.py +++ b/inire/tests/routing_benchmarks.py @@ -1,56 +1,40 @@ +"""Core, Terminal-Bench, and fallback routing fixtures.""" + from __future__ import annotations -from dataclasses import dataclass, replace -from itertools import pairwise, product -from json import loads -from math import pi -from pathlib import Path -from typing import TYPE_CHECKING +from dataclasses import replace from shapely.geometry import Polygon, box -from inire import Bend90Seed, NetSpec, PathSeed, Port, RoutingOptions, RoutingProblem, SBendSeed, StraightSeed -from inire.router._bundle import ordered_bundle_terminal_headings -from inire.router._waypoints import compile_waypoints -from inire.tests.terminal_bench_scenario import LENGTH_COST, OBSTACLES, terminal_bench_options, terminal_bench_problem - -if TYPE_CHECKING: - from inire.seeds import PathSegmentSeed +from inire import Bend90Seed, NetSpec, PathSeed, Port, RoutingProblem, SBendSeed, StraightSeed +from inire.tests.routing_benchmark_case import BenchmarkCase, benchmark_options +from inire.tests.routing_crossing_benchmarks import CROSSING_BENCHMARK_CASES as CROSSING_BENCHMARK_CASES +from inire.tests.routing_external_benchmarks import EXTERNAL_BENCHMARK_CASES as EXTERNAL_BENCHMARK_CASES +from inire.tests.routing_gate_benchmarks import ( + GATE_BENCHMARK_CASES, + VALIDATION_BENCHMARK_CASES as VALIDATION_BENCHMARK_CASES, + _band, + _Gate, + _gate_benchmark, +) +from inire.tests.terminal_bench_scenario import OBSTACLES, terminal_bench_options, terminal_bench_problem -@dataclass(frozen=True, slots=True) -class BenchmarkCase: - name: str - description: str - problem: RoutingProblem - options: RoutingOptions - reference_paths: tuple[tuple[str, PathSeed], ...] = () - - def fixed_headings_problem(self) -> RoutingProblem: - if self.options.topology.infer_terminal_headings: - return ordered_bundle_terminal_headings(self.problem) - return self.problem - - -def _options(bend_radius: float, sbend_radius: float | None = None) -> RoutingOptions: - options = terminal_bench_options() - return replace( - options, - search=replace(options.search, bend_radii=(bend_radius,), sbend_radii=(sbend_radius or bend_radius,)), - objective=replace( - options.objective, - bend_penalty=(LENGTH_COST["bend90"] - 1) * (pi * bend_radius / 2) * (bend_radius / 10) ** 0.5, - ), - ) - - -def _open_or_shared_gate(name: str, description: str, heights: tuple[int, ...], *, wall: bool = False) -> BenchmarkCase: +def _open_or_shared_gate( + name: str, + description: str, + heights: tuple[int, ...], + *, + wall: bool = False, + expected_routed: int | None = None, +) -> BenchmarkCase: # A 34-unit aperture with 2-unit guides and 6-unit clearance leaves 20 units # for centerlines. At 8-unit pitch this admits at most three routes. obstacles = (box(200, 0, 250, 132), box(200, 166, 250, 300)) if wall else () nets = tuple(NetSpec(f"track_{y}", Port(25, y, 0), Port(425, y, 0)) for y in heights) reference = tuple((net.net_id, PathSeed((StraightSeed(400),))) for net in nets if not wall or 139 <= net.start.y <= 159) - return BenchmarkCase(name, description, RoutingProblem((0, 0, 450, 300), nets, obstacles, clearance=6), _options(25), reference) + problem = RoutingProblem((0, 0, 450, 300), nets, obstacles, clearance=6) + return BenchmarkCase(name, description, problem, benchmark_options(25), reference, expected_routed) def _competing_detours() -> BenchmarkCase: @@ -77,7 +61,7 @@ def _competing_detours() -> BenchmarkCase: ) ) return BenchmarkCase( - "competing-detours", "Two nets compete for a short detour around the same obstacle", problem, _options(25), tuple(reference) + "competing-detours", "Two nets compete for a short detour around the same obstacle", problem, benchmark_options(25), tuple(reference) ) @@ -97,7 +81,7 @@ def _offset_gates(mirrored: bool = False) -> BenchmarkCase: ) seed = PathSeed((StraightSeed(220), SBendSeed(arrival_y - launch_y, 25), StraightSeed(280))) name = "offset-gates-mirrored" if mirrored else "offset-gates" - return BenchmarkCase(name, "A lateral shift between two narrow apertures", problem, _options(30, 25), (("offset", seed),)) + return BenchmarkCase(name, "A lateral shift between two narrow apertures", problem, benchmark_options(30, 25), (("offset", seed),)) def _reversed_heading() -> BenchmarkCase: @@ -110,7 +94,7 @@ def _reversed_heading() -> BenchmarkCase: bend = Bend90Seed(30, "CCW") seed = PathSeed((StraightSeed(60), bend, StraightSeed(40), bend, StraightSeed(440), bend, StraightSeed(120), bend, StraightSeed(60))) return BenchmarkCase( - "reversed-heading", "East-facing ports require westward travel past an obstacle", problem, _options(30), (("return", seed),) + "reversed-heading", "East-facing ports require westward travel past an obstacle", problem, benchmark_options(30), (("return", seed),) ) @@ -126,7 +110,7 @@ def _mixed_width_gates() -> BenchmarkCase: "mixed-width-gates", "A narrow aperture fits only the narrow net", problem, - _options(25), + benchmark_options(25), reference, ) @@ -149,9 +133,15 @@ def _blocking_straight(*, turn_limited: bool = False) -> BenchmarkCase: reference = (("horizontal", detour), ("vertical", PathSeed((StraightSeed(vertical_target - vertical_start),)))) if turn_limited: return BenchmarkCase( - "blocking-turn-room", "A straight leaves side passages but challenges the other net's launch turn", problem, _options(25), reference + "blocking-turn-room", + "A straight leaves side passages but challenges the other net's launch turn", + problem, + benchmark_options(25), + reference, ) - return BenchmarkCase("blocking-straight", "A legal straight divides the board and traps a second net", problem, _options(25), reference) + return BenchmarkCase( + "blocking-straight", "A legal straight divides the board and traps a second net", problem, benchmark_options(25), reference + ) def _crossing_with_room() -> BenchmarkCase: @@ -167,7 +157,7 @@ def _crossing_with_room() -> BenchmarkCase: bypass = PathSeed((StraightSeed(10), cw, StraightSeed(85), ccw, StraightSeed(120), ccw, StraightSeed(85), cw, StraightSeed(10))) reference = (("horizontal", PathSeed((StraightSeed(240),))), ("vertical", bypass)) return BenchmarkCase( - "crossing-with-room", "An unlocked junction with room to route around either straight", problem, _options(25), reference + "crossing-with-room", "An unlocked junction with room to route around either straight", problem, benchmark_options(25), reference ) @@ -221,7 +211,7 @@ def _ordered_bundle_benchmarks() -> tuple[BenchmarkCase, ...]: def obstacles(changes: dict[int, tuple[float, float, float, float]]) -> RoutingProblem: return replace(base.problem, static_obstacles=tuple(box(*changes.get(i, bounds)) for i, bounds in enumerate(OBSTACLES))) - radius_40 = _options(40) + radius_40 = benchmark_options(40) return ( replace( base, @@ -257,342 +247,7 @@ def _ordered_bundle_benchmarks() -> tuple[BenchmarkCase, ...]: ) -@dataclass(frozen=True, slots=True) -class _Gate: - left: int - right: int - openings: tuple[tuple[int, ...], ...] - - @property - def tracks(self) -> tuple[int, ...]: - return tuple(y for opening in self.openings for y in opening) - - -def _band(first: int, pitch: int = 18, count: int = 9) -> tuple[int, ...]: - return tuple(range(first, first + pitch * count, pitch)) - - -def _gate_path(columns: tuple[tuple[int, int], ...], tracks: tuple[int, ...], start_x: int, finish_x: int) -> PathSeed: - """Construct a feasibility witness with S-bends centered between columns.""" - segments: list[PathSegmentSeed] = [] - x = start_x - for ((_, after), (before, _)), (start_y, end_y) in zip(pairwise(columns), pairwise(tracks), strict=True): - if start_y == end_y: - continue - sign = 1 if end_y > start_y else -1 - remaining = abs(end_y - start_y) - bends = [] - advance = 0 - # These offsets have integer forward spans at radius 50. - for offset, span in ((40, 80), (20, 60), (4, 28)): - count, remaining = divmod(remaining, offset) - bends.extend([SBendSeed(sign * offset, 50)] * count) - advance += span * count - if remaining or before - after <= advance: - raise ValueError("The benchmark's track shift must fit between its columns") - entrance = (after + before - advance) // 2 - segments.append(StraightSeed(entrance - x)) - segments.extend(bends) - x = entrance + advance - segments.append(StraightSeed(finish_x - x)) - return PathSeed(tuple(segments)) - - -def _gate_benchmark( - name: str, - description: str, - launch: tuple[int, ...], - arrival: tuple[int, ...], - gates: tuple[_Gate, ...], - *, - widths: tuple[int, ...] = (2,) * 9, - westbound: tuple[int, ...] = (), - edge_walls: bool = True, - terminal_stagger: int = 0, -) -> BenchmarkCase: - bounds = (0, 0, 2400, 1000) - launch_x, arrival_x = 40, 2360 - clearance = 6 - obstacles = [] - for gate in gates: - openings = [] - first = 0 - for tracks in gate.openings: - margin = max(widths[first : first + len(tracks)]) / 2 + clearance + 1 - openings.append((tracks[0] - margin, tracks[-1] + margin)) - first += len(tracks) - intervals = [(end, start) for (_, end), (start, _) in pairwise(openings)] - if edge_walls: - intervals.extend(((0, openings[0][0]), (openings[-1][1], bounds[3]))) - if any(end <= start for start, end in intervals): - raise ValueError("The benchmark's gate openings must leave room for their walls") - obstacles.extend(box(gate.left, start, gate.right, end) for start, end in intervals) - - first_column = launch_x + 2 * terminal_stagger - last_column = arrival_x - 2 * terminal_stagger - columns = ((first_column, first_column), *((gate.left, gate.right) for gate in gates), (last_column, last_column)) - profiles = (launch, *(gate.tracks for gate in gates), arrival) - nets = [] - references = [] - for i, (width, track) in enumerate(zip(widths, zip(*profiles, strict=True), strict=True)): - net_id = f"net_{i:02d}" - left_x = launch_x + terminal_stagger * (i % 3) - right_x = arrival_x - terminal_stagger * ((i + 1) % 3) - path = _gate_path(columns, track, left_x, right_x) - if i in westbound: - start, target = Port(right_x, track[-1], 180), Port(left_x, track[0], 180) - # Reversal rotates the local frame by 180 degrees, preserving the signed S-bend offset. - path = PathSeed(path.segments[::-1]) - else: - start, target = Port(left_x, track[0], 0), Port(right_x, track[-1], 0) - nets.append(NetSpec(net_id, start, target, width=width)) - references.append((net_id, path)) - options = _options(50) - options = replace(options, refinement=replace(options.refinement, enabled=False)) - problem = RoutingProblem(bounds, tuple(nets), tuple(obstacles), clearance=clearance) - return BenchmarkCase(name, description, problem, options, tuple(references)) - - -def _serial_gate_benchmarks() -> tuple[BenchmarkCase, ...]: - return ( - _gate_benchmark( - "serial-alternating", - "Three single apertures make the entire bundle shift up, down, and up", - _band(300), - _band(340), - (_Gate(450, 520, (_band(340),)), _Gate(990, 1060, (_band(300),)), _Gate(1640, 1720, (_band(340),))), - ), - _gate_benchmark( - "serial-staircase", - "Four apertures step a densely packed bundle upward in 20-unit increments", - _band(250, 12), - _band(350, 12), - tuple(_Gate(x, x + 65, (_band(y, 12),)) for x, y in zip((420, 850, 1290, 1760), (270, 290, 310, 330), strict=True)), - ), - _gate_benchmark( - "serial-compression", - "Four apertures compress a bundle from 18-unit track pitch to 10 and allow a staged fan-out", - _band(300), - _band(300), - ( - _Gate(450, 520, (_band(300),)), - _Gate(860, 930, (_band(316, 14),)), - _Gate(1340, 1400, (_band(332, 10),)), - _Gate(1820, 1880, (_band(316, 14),)), - ), - ), - _gate_benchmark( - "serial-terminal-jogs", - "Staggered ports bring small lateral shifts close to both ends of the gate sequence", - (296, 320, 344, 356, 380, 404, 416, 440, 464), - (344, 360, 376, 404, 420, 436, 464, 480, 496), - (_Gate(290, 350, (_band(300, 20),)), _Gate(1070, 1130, (_band(320, 20),)), _Gate(2030, 2100, (_band(340, 20),))), - ), - _gate_benchmark( - "serial-close-walls", - "Four closely spaced walls limit the run-up for alternating 40-unit lateral shifts", - _band(500), - _band(500), - ( - _Gate(720, 820, (_band(500),)), - _Gate(920, 1000, (_band(540),)), - _Gate(1110, 1190, (_band(500),)), - _Gate(1310, 1430, (_band(540),)), - ), - ), - ) - - -def _split_gate_benchmarks() -> tuple[BenchmarkCase, ...]: - return ( - _gate_benchmark( - "split-four-five", - "A single opening divides into four- and five-track branches and then merges", - _band(360), - _band(360), - (_Gate(470, 550, (_band(360),)), _Gate(1040, 1170, (_band(320, count=4), _band(472, count=5))), _Gate(1690, 1770, (_band(360),))), - ), - _gate_benchmark( - "split-moving-divider", - "The first divider splits two and seven tracks, and the next splits five and four", - _band(350, 20), - _band(370, 20), - ( - _Gate(420, 495, (_band(310, 20, 2), _band(410, 20, 7))), - _Gate(1000, 1110, (_band(330, 20, 5), _band(470, 20, 4))), - _Gate(1670, 1750, (_band(370, 20),)), - ), - ), - _gate_benchmark( - "split-three-branches", - "Nine tracks split into three apertures before two of the branches merge", - _band(380), - _band(380), - ( - _Gate(460, 530, (_band(340, count=3), _band(434, count=3), _band(528, count=3))), - _Gate(1110, 1190, (_band(380, count=6), _band(528, count=3))), - _Gate(1710, 1790, (_band(380),)), - ), - ), - _gate_benchmark( - "split-mixed-width", - "The branch openings have distinct clearances for width-2, width-4, and width-6 tracks", - _band(270, 22), - _band(290, 22), - ( - _Gate(450, 550, (_band(270, 22),)), - _Gate(1070, 1140, (_band(250, 22, 3), _band(336, 22, 3), _band(442, 22, 3))), - _Gate(1720, 1820, (_band(290, 22),)), - ), - widths=(2, 2, 2, 4, 4, 4, 6, 6, 6), - ), - _gate_benchmark( - "split-asymmetric-merge", - "Three unequal apertures close down to two as the central track joins the lower branch", - _band(470, 20), - _band(490, 20), - ( - _Gate(470, 560, (_band(430, 20, 2), (510,), _band(570, 20, 6))), - _Gate(1000, 1080, (_band(470, 20, 3), _band(550, 20, 6))), - _Gate(1620, 1710, (_band(490, 20),)), - ), - ), - ) - - -def _bypass_benchmarks() -> tuple[BenchmarkCase, ...]: - return ( - _gate_benchmark( - "bypass-opposed-banks", - "A four-net westbound bank and a five-net eastbound bank detour around three free-standing obstacles", - _band(380), - _band(380), - ( - _Gate(430, 620, (_band(340, count=4), _band(492, count=5))), - _Gate(1070, 1250, (_band(380, count=4), _band(472, count=5))), - _Gate(1720, 1890, (_band(340, count=4), _band(492, count=5))), - ), - westbound=(0, 1, 2, 3), - edge_walls=False, - ), - _gate_benchmark( - "bypass-interleaved-directions", - "Interleaved eastbound and westbound terminals detour around blockers with alternating cut points", - _band(370, 20), - _band(370, 20), - ( - _Gate(410, 580, (_band(350, 20, 3), _band(450, 20, 6))), - _Gate(1010, 1200, (_band(350, 20, 5), _band(490, 20, 4))), - _Gate(1640, 1800, (_band(350, 20, 3), _band(450, 20, 6))), - ), - westbound=(1, 3, 5, 7), - edge_walls=False, - ), - _gate_benchmark( - "bypass-long-dividers", - "Long free-standing dividers leave short gaps to adjust lanes before the next bypass", - _band(300), - _band(340), - ( - _Gate(290, 680, (_band(280, count=5), _band(430, count=4))), - _Gate(820, 1210, (_band(300, count=5), _band(430, count=4))), - _Gate(1380, 1790, (_band(320, count=5), _band(450, count=4))), - ), - westbound=(5, 6, 7, 8), - edge_walls=False, - ), - _gate_benchmark( - "bypass-three-branches", - "Two central obstacles per column create three detour choices with mixed travel directions", - _band(330, 20), - _band(330, 20), - ( - _Gate(370, 530, (_band(290, 20, 3), _band(390, 20, 3), _band(490, 20, 3))), - _Gate(990, 1170, (_band(310, 20, 3), _band(390, 20, 3), _band(470, 20, 3))), - _Gate(1580, 1770, (_band(290, 20, 3), _band(390, 20, 3), _band(490, 20, 3))), - ), - westbound=(3, 4, 5), - edge_walls=False, - ), - _gate_benchmark( - "bypass-mixed-width", - "Wide westbound routes share the bypass area with six narrower eastbound routes", - _band(520, 22), - _band(500, 22), - ( - _Gate(450, 600, (_band(500, 22, 3), _band(606, 22, 6))), - _Gate(1010, 1190, (_band(480, 22, 3), _band(606, 22, 6))), - _Gate(1650, 1810, (_band(480, 22, 6), _band(672, 22, 3))), - ), - widths=(2, 2, 2, 3, 3, 3, 6, 6, 6), - westbound=(6, 7, 8), - edge_walls=False, - ), - ) - - -COMPLEX_BENCHMARK_CASES = ( - *_ordered_bundle_benchmarks(), - *_serial_gate_benchmarks(), - *_split_gate_benchmarks(), - *_bypass_benchmarks(), -) - - -def _validation_benchmarks() -> tuple[BenchmarkCase, ...]: - return ( - _gate_benchmark( - "holdout-staggered-five-gates", - "Staggered terminals and five unequal walls with alternating apertures", - _band(280, 16), - _band(320, 16), - tuple( - _Gate(left, right, (_band(y, 16),)) - for left, right, y in ((300, 365, 300), (610, 710, 320), (930, 1020, 280), (1240, 1340, 300), (1760, 1840, 320)) - ), - terminal_stagger=31, - ), - _gate_benchmark( - "holdout-staggered-opposed", - "Opposing travel with staggered banks and narrow gaps between three walls", - _band(520, 16), - _band(500, 16), - (_Gate(670, 820, (_band(520, 16),)), _Gate(925, 1040, (_band(480, 16),)), _Gate(1145, 1220, (_band(520, 16),))), - westbound=(0, 3, 5, 6), - terminal_stagger=24, - ), - _gate_benchmark( - "holdout-uneven-split", - "Interleaved waveguide widths through three apertures and a single merge", - _band(360, 24), - _band(380, 24), - ( - _Gate(440, 610, (_band(340, 24, 2), _band(408, 24, 4), _band(544, 24, 3))), - _Gate(1030, 1110, (_band(360, 24),)), - _Gate(1530, 1770, (_band(340, 24, 2), _band(408, 24, 4), _band(544, 24, 3))), - ), - widths=(2, 5, 2, 4, 3, 6, 2, 5, 3), - terminal_stagger=23, - ), - _gate_benchmark( - "holdout-uneven-bypass", - "Asymmetric free-standing obstacles with mixed widths and opposing launches", - _band(370, 24), - _band(350, 24), - ( - _Gate(350, 510, (_band(330, 24, 4), _band(486, 24, 5))), - _Gate(810, 1150, (_band(350, 24, 3), _band(462, 24, 6))), - _Gate(1600, 1920, (_band(330, 24, 4), _band(486, 24, 5))), - ), - widths=(4, 2, 6, 2, 5, 2, 3, 4, 2), - westbound=(1, 2, 7), - edge_walls=False, - terminal_stagger=41, - ), - ) - - -VALIDATION_BENCHMARK_CASES = _validation_benchmarks() +COMPLEX_BENCHMARK_CASES = (*_ordered_bundle_benchmarks(), *GATE_BENCHMARK_CASES) def _fallback_benchmarks() -> tuple[BenchmarkCase, ...]: @@ -629,7 +284,7 @@ def _fallback_benchmarks() -> tuple[BenchmarkCase, ...]: (net.net_id, PathSeed((StraightSeed(net.target.x - net.start.x - 10), Bend90Seed(10, "CCW"), StraightSeed(40)))) for net in custom_nets ) custom_problem = RoutingProblem((0, 0, 320, 300), custom_nets, (box(90, 65, 130, 90), box(110, 137, 160, 153)), clearance=4) - custom_options = _options(10) + custom_options = benchmark_options(10) custom_options = replace(custom_options, refinement=replace(custom_options.refinement, enabled=False)) custom_outline = Polygon([(0, -11), (11, -11), (11, 0), (9, 0), (9, -9), (0, -9)]) custom_proxy = box(0, -11, 11, 0) @@ -675,170 +330,13 @@ def _fallback_benchmarks() -> tuple[BenchmarkCase, ...]: FALLBACK_BENCHMARK_CASES = _fallback_benchmarks() -def _external_benchmarks() -> tuple[BenchmarkCase, ...]: - fixture = Path(__file__).with_name("data") / "external_routing_benchmarks.json" - cases = [] - for row in loads(fixture.read_text(encoding="utf-8"))["cases"]: - problem = RoutingProblem( - tuple(row["bounds"]), - tuple(NetSpec(net["id"], Port(*net["start"]), Port(*net["target"]), width=net["width"]) for net in row["nets"]), - tuple(Polygon(parts[0], parts[1:]) for parts in row["obstacles"]), - clearance=row["clearance"], - ) - options = _options(row["bend_radius"]) - options = replace( - options, - search=replace(options.search, min_straight_length=row["min_straight"]), - refinement=replace(options.refinement, enabled=False), - ) - cases.append(BenchmarkCase(row["name"], f"Fixed-placement routing from {row['source']}", problem, options)) - return tuple(cases) - - -EXTERNAL_BENCHMARK_CASES = _external_benchmarks() - - -_CROSSING_RADIUS = 25 -_CROSSING_PORT_OFFSET = 14 -_CROSSING_CLEARANCE = 4 - - -def _crossing_keepout(x: int, y: int) -> Polygon: - # Recessed ports sit at the ends of access slots in a fixed 40-unit device. - # The remaining polygon reserves the crossing's core for the placed cell. - face, port = 20, _CROSSING_PORT_OFFSET - slot = _CROSSING_CLEARANCE + 2 # Unit guide half-width and access margin. - body = box(x - face, y - face, x + face, y + face) - for access in ( - box(x - face, y - slot, x - port + slot, y + slot), - box(x + port - slot, y - slot, x + face, y + slot), - box(x - slot, y - face, x + slot, y - port + slot), - box(x - slot, y + port - slot, x + slot, y + face), - ): - body = body.difference(access) - return body - - -def _crossing_leg_seed(net: NetSpec) -> PathSeed: - dx, dy = net.target.x - net.start.x, net.target.y - net.start.y - forward, offset = ((dx, dy), (dy, -dx), (-dx, -dy), (-dy, dx))[int(net.start.r) // 90] - if not offset: - return PathSeed((StraightSeed(forward),)) - # Each stagger in the crossing grids uses a 20-unit offset. At radius - # 25 its forward span is exactly 40, leaving clearance at both ports. - assert abs(offset) == 20 - assert forward > 40 - first = (forward - 40) // 2 - return PathSeed((StraightSeed(first), SBendSeed(offset, _CROSSING_RADIUS), StraightSeed(forward - first - 40))) - - -def _crossing_grid( - name: str, - description: str, - xs: tuple[int, ...], - ys: tuple[int, ...], - *, - staggered: bool = False, -) -> BenchmarkCase: - width, height = xs[-1] + 180, ys[-1] + 180 - offset = _CROSSING_PORT_OFFSET - stagger = 20 if staggered else 0 - cells = { - (row, column): (x + stagger * (row % 2), y + stagger * (column % 2)) for (row, y), (column, x) in product(enumerate(ys), enumerate(xs)) - } - nets = [] - - def add_bank(label: str, ports: list[tuple[str, Port]], *, reverse: bool) -> None: - for (source, start), (sink, target) in zip(ports[::2], ports[1::2], strict=True): - if reverse: - nets.append(NetSpec(f"{label}:{sink}->{source}", target.translate(0, 0, 180), start.translate(0, 0, 180))) - else: - nets.append(NetSpec(f"{label}:{source}->{sink}", start, target)) - - for row in range(len(ys)): - left_y = cells[row, 0][1] - stagger - right_y = cells[row, len(xs) - 1][1] + stagger - ports = [("west", Port(30, left_y, 0))] - for column in range(len(xs)): - x, y = cells[row, column] - cell = f"x{row}_{column}" - ports.extend(((f"{cell}.w", Port(x - offset, y, 0)), (f"{cell}.e", Port(x + offset, y, 0)))) - ports.append(("east", Port(width - 30, right_y, 0))) - add_bank(f"h{row}", ports, reverse=bool(row % 2)) - - for column in range(len(xs)): - bottom_x = cells[0, column][0] + stagger - top_x = cells[len(ys) - 1, column][0] - stagger - ports = [("south", Port(bottom_x, 30, 90))] - for row in range(len(ys)): - x, y = cells[row, column] - cell = f"x{row}_{column}" - ports.extend(((f"{cell}.s", Port(x, y - offset, 90)), (f"{cell}.n", Port(x, y + offset, 90)))) - ports.append(("north", Port(top_x, height - 30, 90))) - add_bank(f"v{column}", ports, reverse=bool(column % 2)) - - problem = RoutingProblem( - (0, 0, width, height), tuple(nets), tuple(_crossing_keepout(*center) for center in cells.values()), clearance=_CROSSING_CLEARANCE - ) - reference = tuple((net.net_id, _crossing_leg_seed(net)) for net in nets) - return BenchmarkCase(name, description, problem, _options(_CROSSING_RADIUS), reference) - - -def _crossing_obstructed_approaches() -> BenchmarkCase: - offset = _CROSSING_PORT_OFFSET - nets = ( - NetSpec("west->x0.w", Port(30, 300, 0), Port(300 - offset, 300, 0)), - NetSpec("x0.e->south-east", Port(300 + offset, 300, 0), Port(530, 204, 270)), - NetSpec("south->x0.s", Port(280, 35, 90), Port(300, 300 - offset, 90)), - NetSpec("x0.n->north", Port(300, 300 + offset, 90), Port(300, 570, 90)), - ) - west, east, south, north = nets - west_seed, _ = compile_waypoints( - ((30, 300), (66, 300), (66, 215), (220, 215), (220, 300), (west.target.x, 300)), west.start, _CROSSING_RADIUS - ) - east_seed, _ = compile_waypoints(((east.start.x, 300), (530, 300), (530, 204)), east.start, _CROSSING_RADIUS) - problem = RoutingProblem( - (0, 0, 600, 600), - nets, - (_crossing_keepout(300, 300), box(98, 265, 153, 335), box(402, 222, 468, 280)), - clearance=_CROSSING_CLEARANCE, - ) - reference = ( - (west.net_id, west_seed), - (east.net_id, east_seed), - (south.net_id, _crossing_leg_seed(south)), - (north.net_id, _crossing_leg_seed(north)), - ) - return BenchmarkCase( - "crossing-obstructed-approaches", - "A fixed crossing with a blocked approach, offset launch, and turning exit", - problem, - _options(_CROSSING_RADIUS), - reference, - ) - - -CROSSING_BENCHMARK_CASES = ( - _crossing_grid("crossing-single", "Four straight legs at one placed crossing", (160,), (160,)), - _crossing_obstructed_approaches(), - _crossing_grid("crossing-aligned-grid", "Six placed crossings linked between opposite port banks", (160, 263, 366), (165, 285)), - _crossing_grid( - "crossing-staggered-grid", - "Nine staggered crossings with short S-bend links and offset terminal banks", - (175, 280, 395), - (160, 266, 388), - staggered=True, - ), -) - - DETOUR = _detour() BENCHMARK_CASES = ( _open_or_shared_gate("open-bundle", "Four parallel routes on an open board", (122, 131, 140, 149)), DETOUR, _competing_detours(), _open_or_shared_gate("shared-gate", "Three nets fit through one aperture", (140, 149, 158), wall=True), - _open_or_shared_gate("overloaded-gate", "Four nets contend for a three-track aperture", (131, 140, 149, 158), wall=True), + _open_or_shared_gate("overloaded-gate", "Four nets contend for a three-track aperture", (131, 140, 149, 158), wall=True, expected_routed=3), _mixed_width_gates(), _blocking_straight(), _blocking_straight(turn_limited=True), diff --git a/inire/tests/routing_corpus.py b/inire/tests/routing_corpus.py new file mode 100644 index 0000000..351f779 --- /dev/null +++ b/inire/tests/routing_corpus.py @@ -0,0 +1,145 @@ +"""Case selection and effective options shared by routing benchmarks and tests.""" + +from __future__ import annotations + +from dataclasses import replace +from typing import TYPE_CHECKING + +from inire import RoutingOptions +from inire.geometry.collision import RoutingWorld +from inire.router.cost import CostEvaluator, weighted_path_length +from inire.router.danger_map import DangerMap +from inire.tests.retry_holdout_benchmarks import RETRY_HOLDOUT_CASES +from inire.tests.routing_benchmarks import ( + BENCHMARK_CASES, + COMPLEX_BENCHMARK_CASES, + CROSSING_BENCHMARK_CASES, + EXTERNAL_BENCHMARK_CASES, + FALLBACK_BENCHMARK_CASES, + VALIDATION_BENCHMARK_CASES, +) +from inire.tests.stress_routing_benchmarks import STRESS_BENCHMARK_CASES +from inire.tests.terminal_bench_scenario import LENGTH_COST + +if TYPE_CHECKING: + from collections.abc import Iterable + + from inire.results import RoutingResult + from inire.tests.routing_benchmark_case import BenchmarkCase + + +BROAD_CASES = (*VALIDATION_BENCHMARK_CASES, *FALLBACK_BENCHMARK_CASES, *EXTERNAL_BENCHMARK_CASES) +CORPUS_CASES = (*BENCHMARK_CASES, *BROAD_CASES, *CROSSING_BENCHMARK_CASES, *STRESS_BENCHMARK_CASES) +SNAPSHOT_CASES = tuple( + case for case in (*BENCHMARK_CASES, *FALLBACK_BENCHMARK_CASES, *EXTERNAL_BENCHMARK_CASES) if case.name != "terminal-bench" +) +CASE_GROUPS = { + **{case.name: (case,) for case in (*CORPUS_CASES, *RETRY_HOLDOUT_CASES)}, + "all": BENCHMARK_CASES, + "complex": COMPLEX_BENCHMARK_CASES, + "holdout": VALIDATION_BENCHMARK_CASES, + "fallback": FALLBACK_BENCHMARK_CASES, + "external": EXTERNAL_BENCHMARK_CASES, + "broad": BROAD_CASES, + "crossings": CROSSING_BENCHMARK_CASES, + "stress": STRESS_BENCHMARK_CASES, + "retry-holdout": RETRY_HOLDOUT_CASES, + "corpus": CORPUS_CASES, +} +PROFILES = ("matched-budget", "public-defaults", "corpus-regression") +AUTOMATIC_COST_MODES = {"automatic": "selective", "automatic-span": "never", "automatic-weighted": "always"} +AUTOMATIC_POLICIES = tuple(AUTOMATIC_COST_MODES) + + +def select_cases(groups: Iterable[str]) -> tuple[BenchmarkCase, ...]: + return tuple({case.name: case for group in groups for case in CASE_GROUPS[group]}.values()) + + +def _public_defaults(case: BenchmarkCase, defaults: RoutingOptions) -> RoutingOptions: + geometry = case.options.search + return replace( + defaults, + search=replace( + defaults.search, + bend_radii=geometry.bend_radii, + sbend_radii=geometry.sbend_radii, + sbend_offsets=geometry.sbend_offsets, + bend_collision_type=geometry.bend_collision_type, + bend_proxy_geometry=geometry.bend_proxy_geometry, + bend_physical_geometry=geometry.bend_physical_geometry, + bend_clip_margin=geometry.bend_clip_margin, + min_straight_length=geometry.min_straight_length, + max_straight_length=geometry.max_straight_length, + ), + topology=replace(defaults.topology, infer_terminal_headings=case.options.topology.infer_terminal_headings), + ) + + +def profile_options(case: BenchmarkCase, profile: str) -> RoutingOptions: + """Resolve fixture geometry and the named budget before mode or CLI overrides.""" + base = case.options + if profile == "fixture": + return base + if profile == "corpus-regression": + return replace( + base, + search=replace(base.search, node_limit=500), + congestion=replace(base.congestion, max_iterations=3), + topology=replace(base.topology, seed_node_limit=500), + ) + defaults = RoutingOptions() + if profile == "public-defaults": + return _public_defaults(case, defaults) + if profile != "matched-budget": + raise ValueError(f"Unknown benchmark profile: {profile}") + return replace( + base, + search=replace(base.search, node_limit=500), + congestion=replace( + base.congestion, + max_iterations=2, + net_order=defaults.congestion.net_order, + warm_start_enabled=defaults.congestion.warm_start_enabled, + ), + topology=replace(defaults.topology, infer_terminal_headings=base.topology.infer_terminal_headings), + ) + + +def automatic_options(options: RoutingOptions, profile: str, strategy: str = "automatic") -> RoutingOptions: + topology = options.topology + weights = topology.automatic_length_weights + if profile in ("matched-budget", "corpus-regression"): + weights = (LENGTH_COST["straight"], LENGTH_COST["bend90"], LENGTH_COST["sbend"]) + cost_policy = topology.automatic_cost if profile == "public-defaults" and strategy == "automatic" else AUTOMATIC_COST_MODES[strategy] + return replace(options, topology=replace(topology, mode="automatic", automatic_cost=cost_policy, automatic_length_weights=weights)) + + +def benchmark_weighted_length(result: RoutingResult) -> float: + return weighted_path_length(result.path, LENGTH_COST) + + +def native_verified_costs( + case: BenchmarkCase, + options: RoutingOptions, + results: dict[str, RoutingResult], + verified_net_ids: Iterable[str], +) -> dict[str, float]: + objective = options.objective + problem = case.problem + danger = None + if objective.danger_weight and problem.static_obstacles: + danger = DangerMap(bounds=problem.bounds) + danger.precompute(list(problem.static_obstacles)) + scorer = CostEvaluator( + RoutingWorld(clearance=problem.clearance), + danger, + unit_length_cost=objective.unit_length_cost, + bend_penalty=objective.bend_penalty, + sbend_penalty=objective.sbend_penalty, + danger_weight=objective.danger_weight, + ) + costs = {} + for net_id in verified_net_ids: + path = results[net_id].path + costs[net_id] = scorer.path_cost(path[0].start_port, path) + return costs diff --git a/inire/tests/routing_crossing_benchmarks.py b/inire/tests/routing_crossing_benchmarks.py new file mode 100644 index 0000000..445324d --- /dev/null +++ b/inire/tests/routing_crossing_benchmarks.py @@ -0,0 +1,143 @@ +"""Fixtures with user-placed crossing devices and fixed access ports.""" + +from itertools import product + +from shapely.geometry import Polygon, box + +from inire import NetSpec, PathSeed, Port, RoutingProblem, SBendSeed, StraightSeed +from inire.router._waypoints import compile_waypoints +from inire.tests.routing_benchmark_case import BenchmarkCase, benchmark_options + + +_CROSSING_RADIUS = 25 +_CROSSING_PORT_OFFSET = 14 +_CROSSING_CLEARANCE = 4 + + +def _crossing_keepout(x: int, y: int) -> Polygon: + # Recessed ports sit at the ends of access slots in a fixed 40-unit device. + # The remaining polygon reserves the crossing's core for the placed cell. + face, port = 20, _CROSSING_PORT_OFFSET + slot = _CROSSING_CLEARANCE + 2 # Unit guide half-width and access margin. + body = box(x - face, y - face, x + face, y + face) + for access in ( + box(x - face, y - slot, x - port + slot, y + slot), + box(x + port - slot, y - slot, x + face, y + slot), + box(x - slot, y - face, x + slot, y - port + slot), + box(x - slot, y + port - slot, x + slot, y + face), + ): + body = body.difference(access) + return body + + +def _crossing_leg_seed(net: NetSpec) -> PathSeed: + dx, dy = net.target.x - net.start.x, net.target.y - net.start.y + forward, offset = ((dx, dy), (dy, -dx), (-dx, -dy), (-dy, dx))[int(net.start.r) // 90] + if not offset: + return PathSeed((StraightSeed(forward),)) + # Each stagger in the crossing grids uses a 20-unit offset. At radius + # 25 its forward span is exactly 40, leaving clearance at both ports. + assert abs(offset) == 20 + assert forward > 40 + first = (forward - 40) // 2 + return PathSeed((StraightSeed(first), SBendSeed(offset, _CROSSING_RADIUS), StraightSeed(forward - first - 40))) + + +def _crossing_grid( + name: str, + description: str, + xs: tuple[int, ...], + ys: tuple[int, ...], + *, + staggered: bool = False, +) -> BenchmarkCase: + width, height = xs[-1] + 180, ys[-1] + 180 + offset = _CROSSING_PORT_OFFSET + stagger = 20 if staggered else 0 + cells = { + (row, column): (x + stagger * (row % 2), y + stagger * (column % 2)) for (row, y), (column, x) in product(enumerate(ys), enumerate(xs)) + } + nets = [] + + def add_bank(label: str, ports: list[tuple[str, Port]], *, reverse: bool) -> None: + for (source, start), (sink, target) in zip(ports[::2], ports[1::2], strict=True): + if reverse: + nets.append(NetSpec(f"{label}:{sink}->{source}", target.translate(0, 0, 180), start.translate(0, 0, 180))) + else: + nets.append(NetSpec(f"{label}:{source}->{sink}", start, target)) + + for row in range(len(ys)): + left_y = cells[row, 0][1] - stagger + right_y = cells[row, len(xs) - 1][1] + stagger + ports = [("west", Port(30, left_y, 0))] + for column in range(len(xs)): + x, y = cells[row, column] + cell = f"x{row}_{column}" + ports.extend(((f"{cell}.w", Port(x - offset, y, 0)), (f"{cell}.e", Port(x + offset, y, 0)))) + ports.append(("east", Port(width - 30, right_y, 0))) + add_bank(f"h{row}", ports, reverse=bool(row % 2)) + + for column in range(len(xs)): + bottom_x = cells[0, column][0] + stagger + top_x = cells[len(ys) - 1, column][0] - stagger + ports = [("south", Port(bottom_x, 30, 90))] + for row in range(len(ys)): + x, y = cells[row, column] + cell = f"x{row}_{column}" + ports.extend(((f"{cell}.s", Port(x, y - offset, 90)), (f"{cell}.n", Port(x, y + offset, 90)))) + ports.append(("north", Port(top_x, height - 30, 90))) + add_bank(f"v{column}", ports, reverse=bool(column % 2)) + + problem = RoutingProblem( + (0, 0, width, height), tuple(nets), tuple(_crossing_keepout(*center) for center in cells.values()), clearance=_CROSSING_CLEARANCE + ) + reference = tuple((net.net_id, _crossing_leg_seed(net)) for net in nets) + return BenchmarkCase(name, description, problem, benchmark_options(_CROSSING_RADIUS), reference) + + +def _crossing_obstructed_approaches() -> BenchmarkCase: + offset = _CROSSING_PORT_OFFSET + nets = ( + NetSpec("west->x0.w", Port(30, 300, 0), Port(300 - offset, 300, 0)), + NetSpec("x0.e->south-east", Port(300 + offset, 300, 0), Port(530, 204, 270)), + NetSpec("south->x0.s", Port(280, 35, 90), Port(300, 300 - offset, 90)), + NetSpec("x0.n->north", Port(300, 300 + offset, 90), Port(300, 570, 90)), + ) + west, east, south, north = nets + west_seed, _ = compile_waypoints( + ((30, 300), (66, 300), (66, 215), (220, 215), (220, 300), (west.target.x, 300)), west.start, _CROSSING_RADIUS + ) + east_seed, _ = compile_waypoints(((east.start.x, 300), (530, 300), (530, 204)), east.start, _CROSSING_RADIUS) + problem = RoutingProblem( + (0, 0, 600, 600), + nets, + (_crossing_keepout(300, 300), box(98, 265, 153, 335), box(402, 222, 468, 280)), + clearance=_CROSSING_CLEARANCE, + ) + reference = ( + (west.net_id, west_seed), + (east.net_id, east_seed), + (south.net_id, _crossing_leg_seed(south)), + (north.net_id, _crossing_leg_seed(north)), + ) + return BenchmarkCase( + "crossing-obstructed-approaches", + "A fixed crossing with a blocked approach, offset launch, and turning exit", + problem, + benchmark_options(_CROSSING_RADIUS), + reference, + ) + + +CROSSING_BENCHMARK_CASES = ( + _crossing_grid("crossing-single", "Four straight legs at one placed crossing", (160,), (160,)), + _crossing_obstructed_approaches(), + _crossing_grid("crossing-aligned-grid", "Six placed crossings linked between opposite port banks", (160, 263, 366), (165, 285)), + _crossing_grid( + "crossing-staggered-grid", + "Nine staggered crossings with short S-bend links and offset terminal banks", + (175, 280, 395), + (160, 266, 388), + staggered=True, + ), +) diff --git a/inire/tests/routing_external_benchmarks.py b/inire/tests/routing_external_benchmarks.py new file mode 100644 index 0000000..77ae861 --- /dev/null +++ b/inire/tests/routing_external_benchmarks.py @@ -0,0 +1,39 @@ +"""Fixed-placement routing fixtures imported from external benchmarks.""" + +from dataclasses import replace +from json import loads +from pathlib import Path + +from shapely.geometry import Polygon + +from inire import NetSpec, Port, RoutingProblem +from inire.tests.routing_benchmark_case import BenchmarkCase, benchmark_options + + +def _external_benchmarks() -> tuple[BenchmarkCase, ...]: + fixture = Path(__file__).with_name("data") / "external_routing_benchmarks.json" + cases = [] + for row in loads(fixture.read_text(encoding="utf-8"))["cases"]: + problem = RoutingProblem( + tuple(row["bounds"]), + tuple(NetSpec(net["id"], Port(*net["start"]), Port(*net["target"]), width=net["width"]) for net in row["nets"]), + tuple(Polygon(parts[0], parts[1:]) for parts in row["obstacles"]), + clearance=row["clearance"], + ) + options = benchmark_options(row["bend_radius"]) + options = replace( + options, + search=replace(options.search, min_straight_length=row["min_straight"]), + refinement=replace(options.refinement, enabled=False), + ) + cases.append(BenchmarkCase( + row["name"], + f"Fixed-placement routing from {row['source']}", + problem, + options, + expected_routed=row.get("expected_routed"), + )) + return tuple(cases) + + +EXTERNAL_BENCHMARK_CASES = _external_benchmarks() diff --git a/inire/tests/routing_gate_benchmarks.py b/inire/tests/routing_gate_benchmarks.py new file mode 100644 index 0000000..bf6de7b --- /dev/null +++ b/inire/tests/routing_gate_benchmarks.py @@ -0,0 +1,352 @@ +"""Serial, split, bypass, and held-out gate benchmark families.""" + +from __future__ import annotations + +from dataclasses import dataclass, replace +from itertools import pairwise +from typing import TYPE_CHECKING + +from shapely.geometry import box + +from inire import NetSpec, PathSeed, Port, RoutingProblem, SBendSeed, StraightSeed +from inire.tests.routing_benchmark_case import BenchmarkCase, benchmark_options + +if TYPE_CHECKING: + from inire.seeds import PathSegmentSeed + + +@dataclass(frozen=True, slots=True) +class _Gate: + left: int + right: int + openings: tuple[tuple[int, ...], ...] + + @property + def tracks(self) -> tuple[int, ...]: + return tuple(y for opening in self.openings for y in opening) + + +def _band(first: int, pitch: int = 18, count: int = 9) -> tuple[int, ...]: + return tuple(range(first, first + pitch * count, pitch)) + + +def _gate_path(columns: tuple[tuple[int, int], ...], tracks: tuple[int, ...], start_x: int, finish_x: int) -> PathSeed: + """Construct a feasibility witness with S-bends centered between columns.""" + segments: list[PathSegmentSeed] = [] + x = start_x + for ((_, after), (before, _)), (start_y, end_y) in zip(pairwise(columns), pairwise(tracks), strict=True): + if start_y == end_y: + continue + sign = 1 if end_y > start_y else -1 + remaining = abs(end_y - start_y) + bends = [] + advance = 0 + # These offsets have integer forward spans at radius 50. + for offset, span in ((40, 80), (20, 60), (4, 28)): + count, remaining = divmod(remaining, offset) + bends.extend([SBendSeed(sign * offset, 50)] * count) + advance += span * count + if remaining or before - after <= advance: + raise ValueError("The benchmark's track shift must fit between its columns") + entrance = (after + before - advance) // 2 + segments.append(StraightSeed(entrance - x)) + segments.extend(bends) + x = entrance + advance + segments.append(StraightSeed(finish_x - x)) + return PathSeed(tuple(segments)) + + +def _gate_benchmark( + name: str, + description: str, + launch: tuple[int, ...], + arrival: tuple[int, ...], + gates: tuple[_Gate, ...], + *, + widths: tuple[int, ...] = (2,) * 9, + westbound: tuple[int, ...] = (), + edge_walls: bool = True, + terminal_stagger: int = 0, +) -> BenchmarkCase: + bounds = (0, 0, 2400, 1000) + launch_x, arrival_x = 40, 2360 + clearance = 6 + obstacles = [] + for gate in gates: + openings = [] + first = 0 + for tracks in gate.openings: + margin = max(widths[first : first + len(tracks)]) / 2 + clearance + 1 + openings.append((tracks[0] - margin, tracks[-1] + margin)) + first += len(tracks) + intervals = [(end, start) for (_, end), (start, _) in pairwise(openings)] + if edge_walls: + intervals.extend(((0, openings[0][0]), (openings[-1][1], bounds[3]))) + if any(end <= start for start, end in intervals): + raise ValueError("The benchmark's gate openings must leave room for their walls") + obstacles.extend(box(gate.left, start, gate.right, end) for start, end in intervals) + + first_column = launch_x + 2 * terminal_stagger + last_column = arrival_x - 2 * terminal_stagger + columns = ((first_column, first_column), *((gate.left, gate.right) for gate in gates), (last_column, last_column)) + profiles = (launch, *(gate.tracks for gate in gates), arrival) + nets = [] + references = [] + for i, (width, track) in enumerate(zip(widths, zip(*profiles, strict=True), strict=True)): + net_id = f"net_{i:02d}" + left_x = launch_x + terminal_stagger * (i % 3) + right_x = arrival_x - terminal_stagger * ((i + 1) % 3) + path = _gate_path(columns, track, left_x, right_x) + if i in westbound: + start, target = Port(right_x, track[-1], 180), Port(left_x, track[0], 180) + # Reversal rotates the local frame by 180 degrees, preserving the signed S-bend offset. + path = PathSeed(path.segments[::-1]) + else: + start, target = Port(left_x, track[0], 0), Port(right_x, track[-1], 0) + nets.append(NetSpec(net_id, start, target, width=width)) + references.append((net_id, path)) + options = benchmark_options(50) + options = replace(options, refinement=replace(options.refinement, enabled=False)) + problem = RoutingProblem(bounds, tuple(nets), tuple(obstacles), clearance=clearance) + return BenchmarkCase(name, description, problem, options, tuple(references)) + + +def _serial_gate_benchmarks() -> tuple[BenchmarkCase, ...]: + return ( + _gate_benchmark( + "serial-alternating", + "Three single apertures make the entire bundle shift up, down, and up", + _band(300), + _band(340), + (_Gate(450, 520, (_band(340),)), _Gate(990, 1060, (_band(300),)), _Gate(1640, 1720, (_band(340),))), + ), + _gate_benchmark( + "serial-staircase", + "Four apertures step a densely packed bundle upward in 20-unit increments", + _band(250, 12), + _band(350, 12), + tuple(_Gate(x, x + 65, (_band(y, 12),)) for x, y in zip((420, 850, 1290, 1760), (270, 290, 310, 330), strict=True)), + ), + _gate_benchmark( + "serial-compression", + "Four apertures compress a bundle from 18-unit track pitch to 10 and allow a staged fan-out", + _band(300), + _band(300), + ( + _Gate(450, 520, (_band(300),)), + _Gate(860, 930, (_band(316, 14),)), + _Gate(1340, 1400, (_band(332, 10),)), + _Gate(1820, 1880, (_band(316, 14),)), + ), + ), + _gate_benchmark( + "serial-terminal-jogs", + "Staggered ports bring small lateral shifts close to both ends of the gate sequence", + (296, 320, 344, 356, 380, 404, 416, 440, 464), + (344, 360, 376, 404, 420, 436, 464, 480, 496), + (_Gate(290, 350, (_band(300, 20),)), _Gate(1070, 1130, (_band(320, 20),)), _Gate(2030, 2100, (_band(340, 20),))), + ), + _gate_benchmark( + "serial-close-walls", + "Four closely spaced walls limit the run-up for alternating 40-unit lateral shifts", + _band(500), + _band(500), + ( + _Gate(720, 820, (_band(500),)), + _Gate(920, 1000, (_band(540),)), + _Gate(1110, 1190, (_band(500),)), + _Gate(1310, 1430, (_band(540),)), + ), + ), + ) + + +def _split_gate_benchmarks() -> tuple[BenchmarkCase, ...]: + return ( + _gate_benchmark( + "split-four-five", + "A single opening divides into four- and five-track branches and then merges", + _band(360), + _band(360), + (_Gate(470, 550, (_band(360),)), _Gate(1040, 1170, (_band(320, count=4), _band(472, count=5))), _Gate(1690, 1770, (_band(360),))), + ), + _gate_benchmark( + "split-moving-divider", + "The first divider splits two and seven tracks, and the next splits five and four", + _band(350, 20), + _band(370, 20), + ( + _Gate(420, 495, (_band(310, 20, 2), _band(410, 20, 7))), + _Gate(1000, 1110, (_band(330, 20, 5), _band(470, 20, 4))), + _Gate(1670, 1750, (_band(370, 20),)), + ), + ), + _gate_benchmark( + "split-three-branches", + "Nine tracks split into three apertures before two of the branches merge", + _band(380), + _band(380), + ( + _Gate(460, 530, (_band(340, count=3), _band(434, count=3), _band(528, count=3))), + _Gate(1110, 1190, (_band(380, count=6), _band(528, count=3))), + _Gate(1710, 1790, (_band(380),)), + ), + ), + _gate_benchmark( + "split-mixed-width", + "The branch openings have distinct clearances for width-2, width-4, and width-6 tracks", + _band(270, 22), + _band(290, 22), + ( + _Gate(450, 550, (_band(270, 22),)), + _Gate(1070, 1140, (_band(250, 22, 3), _band(336, 22, 3), _band(442, 22, 3))), + _Gate(1720, 1820, (_band(290, 22),)), + ), + widths=(2, 2, 2, 4, 4, 4, 6, 6, 6), + ), + _gate_benchmark( + "split-asymmetric-merge", + "Three unequal apertures close down to two as the central track joins the lower branch", + _band(470, 20), + _band(490, 20), + ( + _Gate(470, 560, (_band(430, 20, 2), (510,), _band(570, 20, 6))), + _Gate(1000, 1080, (_band(470, 20, 3), _band(550, 20, 6))), + _Gate(1620, 1710, (_band(490, 20),)), + ), + ), + ) + + +def _bypass_benchmarks() -> tuple[BenchmarkCase, ...]: + return ( + _gate_benchmark( + "bypass-opposed-banks", + "A four-net westbound bank and a five-net eastbound bank detour around three free-standing obstacles", + _band(380), + _band(380), + ( + _Gate(430, 620, (_band(340, count=4), _band(492, count=5))), + _Gate(1070, 1250, (_band(380, count=4), _band(472, count=5))), + _Gate(1720, 1890, (_band(340, count=4), _band(492, count=5))), + ), + westbound=(0, 1, 2, 3), + edge_walls=False, + ), + _gate_benchmark( + "bypass-interleaved-directions", + "Interleaved eastbound and westbound terminals detour around blockers with alternating cut points", + _band(370, 20), + _band(370, 20), + ( + _Gate(410, 580, (_band(350, 20, 3), _band(450, 20, 6))), + _Gate(1010, 1200, (_band(350, 20, 5), _band(490, 20, 4))), + _Gate(1640, 1800, (_band(350, 20, 3), _band(450, 20, 6))), + ), + westbound=(1, 3, 5, 7), + edge_walls=False, + ), + _gate_benchmark( + "bypass-long-dividers", + "Long free-standing dividers leave short gaps to adjust lanes before the next bypass", + _band(300), + _band(340), + ( + _Gate(290, 680, (_band(280, count=5), _band(430, count=4))), + _Gate(820, 1210, (_band(300, count=5), _band(430, count=4))), + _Gate(1380, 1790, (_band(320, count=5), _band(450, count=4))), + ), + westbound=(5, 6, 7, 8), + edge_walls=False, + ), + _gate_benchmark( + "bypass-three-branches", + "Two central obstacles per column create three detour choices with mixed travel directions", + _band(330, 20), + _band(330, 20), + ( + _Gate(370, 530, (_band(290, 20, 3), _band(390, 20, 3), _band(490, 20, 3))), + _Gate(990, 1170, (_band(310, 20, 3), _band(390, 20, 3), _band(470, 20, 3))), + _Gate(1580, 1770, (_band(290, 20, 3), _band(390, 20, 3), _band(490, 20, 3))), + ), + westbound=(3, 4, 5), + edge_walls=False, + ), + _gate_benchmark( + "bypass-mixed-width", + "Wide westbound routes share the bypass area with six narrower eastbound routes", + _band(520, 22), + _band(500, 22), + ( + _Gate(450, 600, (_band(500, 22, 3), _band(606, 22, 6))), + _Gate(1010, 1190, (_band(480, 22, 3), _band(606, 22, 6))), + _Gate(1650, 1810, (_band(480, 22, 6), _band(672, 22, 3))), + ), + widths=(2, 2, 2, 3, 3, 3, 6, 6, 6), + westbound=(6, 7, 8), + edge_walls=False, + ), + ) + + +GATE_BENCHMARK_CASES = ( + *_serial_gate_benchmarks(), + *_split_gate_benchmarks(), + *_bypass_benchmarks(), +) + + +def _validation_benchmarks() -> tuple[BenchmarkCase, ...]: + return ( + _gate_benchmark( + "holdout-staggered-five-gates", + "Staggered terminals and five unequal walls with alternating apertures", + _band(280, 16), + _band(320, 16), + tuple( + _Gate(left, right, (_band(y, 16),)) + for left, right, y in ((300, 365, 300), (610, 710, 320), (930, 1020, 280), (1240, 1340, 300), (1760, 1840, 320)) + ), + terminal_stagger=31, + ), + _gate_benchmark( + "holdout-staggered-opposed", + "Opposing travel with staggered banks and narrow gaps between three walls", + _band(520, 16), + _band(500, 16), + (_Gate(670, 820, (_band(520, 16),)), _Gate(925, 1040, (_band(480, 16),)), _Gate(1145, 1220, (_band(520, 16),))), + westbound=(0, 3, 5, 6), + terminal_stagger=24, + ), + _gate_benchmark( + "holdout-uneven-split", + "Interleaved waveguide widths through three apertures and a single merge", + _band(360, 24), + _band(380, 24), + ( + _Gate(440, 610, (_band(340, 24, 2), _band(408, 24, 4), _band(544, 24, 3))), + _Gate(1030, 1110, (_band(360, 24),)), + _Gate(1530, 1770, (_band(340, 24, 2), _band(408, 24, 4), _band(544, 24, 3))), + ), + widths=(2, 5, 2, 4, 3, 6, 2, 5, 3), + terminal_stagger=23, + ), + _gate_benchmark( + "holdout-uneven-bypass", + "Asymmetric free-standing obstacles with mixed widths and opposing launches", + _band(370, 24), + _band(350, 24), + ( + _Gate(350, 510, (_band(330, 24, 4), _band(486, 24, 5))), + _Gate(810, 1150, (_band(350, 24, 3), _band(462, 24, 6))), + _Gate(1600, 1920, (_band(330, 24, 4), _band(486, 24, 5))), + ), + widths=(4, 2, 6, 2, 5, 2, 3, 4, 2), + westbound=(1, 2, 7), + edge_walls=False, + terminal_stagger=41, + ), + ) + + +VALIDATION_BENCHMARK_CASES = _validation_benchmarks() diff --git a/inire/tests/stress_routing_benchmarks.py b/inire/tests/stress_routing_benchmarks.py index 66d6728..568aa77 100644 --- a/inire/tests/stress_routing_benchmarks.py +++ b/inire/tests/stress_routing_benchmarks.py @@ -10,7 +10,8 @@ from shapely.geometry import Polygon, box from inire import NetSpec, Port, RoutingProblem from inire.router._waypoints import _direction, compile_waypoints -from inire.tests.routing_benchmarks import BenchmarkCase, _crossing_keepout, _options +from inire.tests.routing_benchmark_case import BenchmarkCase, benchmark_options +from inire.tests.routing_crossing_benchmarks import _crossing_keepout if TYPE_CHECKING: from inire.router._waypoints import XY @@ -45,7 +46,7 @@ def _waypoint_case( seed, end = compile_waypoints(track.points, start, track.radius if track.radius is not None else radius) nets.append(NetSpec(track.name, start, end, track.width)) reference.append((track.name, seed)) - options = _options(radius, sbend_radius) + options = benchmark_options(radius, sbend_radius) if extra_bend_radius is not None: options = replace(options, search=replace(options.search, bend_radii=(radius, extra_bend_radius))) problem = RoutingProblem(bounds, tuple(nets), obstacles, clearance=clearance) diff --git a/inire/tests/test_api.py b/inire/tests/test_api.py index 686116c..46a0d76 100644 --- a/inire/tests/test_api.py +++ b/inire/tests/test_api.py @@ -4,6 +4,7 @@ import pytest import shapely from shapely.geometry import box +import inire import inire.router._router as router_module from inire import ( CongestionOptions, @@ -26,8 +27,6 @@ from inire.router._router import PathFinder, _IterationReview from inire.router.cost import CostEvaluator from inire.router.danger_map import DangerMap def test_root_module_exports_only_stable_surface() -> None: - import inire - assert not hasattr(inire, "RoutingWorld") assert not hasattr(inire, "AStarContext") assert not hasattr(inire, "PathFinder") @@ -389,6 +388,7 @@ def test_capture_frontier_trace_preserves_route_outputs() -> None: net_id: result.outcome for net_id, result in run_with_trace.results_by_net.items() } assert {trace.net_id for trace in run_with_trace.frontier_trace} == {"horizontal", "vertical"} + assert run_with_trace.metrics.verify_path_report_calls == run_without_trace.metrics.verify_path_report_calls def test_capture_pre_pair_frontier_trace_preserves_route_outputs() -> None: @@ -518,7 +518,7 @@ def test_reverify_iterations_limit_late_reroutes_to_conflicting_nets(monkeypatch ) monkeypatch.setattr(PathFinder, "_run_iteration", fake_run_iteration) - monkeypatch.setattr(PathFinder, "_verify_results", lambda self, state: dict(state.results)) + monkeypatch.setattr(PathFinder, "_verify_results", lambda self, state: (dict(state.results), {})) monkeypatch.setattr(PathFinder, "_run_pair_local_search", lambda self, state: None) results = pathfinder.route_all() @@ -657,7 +657,7 @@ def test_route_net_once_skips_search_for_capped_incumbent_fallback(monkeypatch: state.results["netA"] = incumbent installed: list[tuple[str, tuple[object, ...]]] = [] - def fail_route_astar(*args, **kwargs): + def fail_route_astar(*_args, **_kwargs): raise AssertionError("route_astar should not run for capped incumbent fallback") def record_install(self, net_id, path): @@ -726,7 +726,7 @@ def test_route_all_restores_best_iteration_snapshot(monkeypatch: pytest.MonkeyPa ) monkeypatch.setattr(PathFinder, "_run_iteration", fake_run_iteration) - monkeypatch.setattr(PathFinder, "_verify_results", lambda self, state: dict(state.results)) + monkeypatch.setattr(PathFinder, "_verify_results", lambda self, state: (dict(state.results), {})) results = pathfinder.route_all() @@ -770,7 +770,7 @@ def test_route_all_restores_best_iteration_snapshot_on_timeout(monkeypatch: pyte return True monkeypatch.setattr(PathFinder, "_run_iterations", fake_run_iterations) - monkeypatch.setattr(PathFinder, "_verify_results", lambda self, state: dict(state.results)) + monkeypatch.setattr(PathFinder, "_verify_results", lambda self, state: (dict(state.results), {})) results = pathfinder.route_all() diff --git a/inire/tests/test_astar.py b/inire/tests/test_astar.py index 445991f..87e9393 100644 --- a/inire/tests/test_astar.py +++ b/inire/tests/test_astar.py @@ -6,13 +6,13 @@ from inire import CongestionOptions, NetSpec, RoutingProblem, RoutingOptions, Ro from inire.geometry.components import Bend90, Straight from inire.geometry.collision import RoutingWorld from inire.geometry.primitives import Port -from inire.router._astar_types import AStarContext, AStarNode, SearchRunConfig +from inire.router._astar_types import AStarContext, AStarNode, CongestionCaches, SearchRunConfig from inire.router._astar_admission import add_node from inire.router._astar_moves import ( _distance_to_bounds_in_heading, _should_cap_straights_to_bounds, ) -from inire.router._router import PathFinder, _RoutingState +from inire.router._pair_local import _build_pair_local_context from inire.router._search import route_astar from inire.router.cost import CostEvaluator from inire.router.danger_map import DangerMap @@ -256,46 +256,18 @@ def test_pair_local_context_clones_live_static_obstacles() -> None: danger_map = DangerMap(bounds=BOUNDS) danger_map.precompute([obstacle]) evaluator = CostEvaluator(engine, danger_map, bend_penalty=50.0, sbend_penalty=150.0) - finder = PathFinder( - AStarContext( - evaluator, - RoutingProblem( - bounds=BOUNDS, - nets=( - NetSpec("pair_a", Port(0, 0, 0), Port(60, 0, 0), width=2.0), - NetSpec("pair_b", Port(0, 10, 0), Port(60, 10, 0), width=2.0), - ), - ), - RoutingOptions(), - ) - ) - state = _RoutingState( - net_specs={ - "pair_a": NetSpec("pair_a", Port(0, 0, 0), Port(60, 0, 0), width=2.0), - "pair_b": NetSpec("pair_b", Port(0, 10, 0), Port(60, 10, 0), width=2.0), - }, - ordered_net_ids=["pair_a", "pair_b"], - results={}, - needs_self_collision_check=set(), - start_time=0.0, - timeout_s=1.0, - initial_paths=None, - accumulated_expanded_nodes=[], - best_results={}, - best_completed_nets=-1, - best_conflict_edges=10**9, - best_dynamic_collisions=10**9, - last_conflict_signature=(), - last_conflict_edge_count=0, - repeated_conflict_count=0, - pair_local_plateau_count=0, - recent_attempt_work={}, - pre_pair_candidate=None, + problem = RoutingProblem( + bounds=BOUNDS, + nets=( + NetSpec("pair_a", Port(0, 0, 0), Port(60, 0, 0), width=2.0), + NetSpec("pair_b", Port(0, 10, 0), Port(60, 10, 0), width=2.0), + ), ) + context = AStarContext(evaluator, problem, RoutingOptions()) - local_context = finder._build_pair_local_context(state, {}, ("pair_a", "pair_b")) + local_context = _build_pair_local_context(context, problem.nets, {}, ("pair_a", "pair_b"), lock_partial_paths=True) - assert finder.context.problem.static_obstacles == () + assert context.problem.static_obstacles == () assert len(local_context.problem.static_obstacles) == 1 assert len(local_context.cost_evaluator.collision_engine._static_obstacles.geometries) == 1 assert next(iter(local_context.problem.static_obstacles)).equals(obstacle) @@ -446,12 +418,7 @@ def test_self_collision_prunes_before_congestion_check(basic_evaluator: CostEval closed_set=closed_set, context=context, metrics=context.metrics, - congestion_cache={}, - congestion_presence_cache={}, - congestion_candidate_precheck_cache={}, - congestion_net_envelope_cache={}, - congestion_grid_net_cache={}, - congestion_grid_span_cache={}, + congestion=CongestionCaches(), config=SearchRunConfig.from_options(context.options, self_collision_check=True), move_type="straight", cache_key=("overlap",), @@ -479,12 +446,7 @@ def test_closed_set_dominance_prunes_before_congestion_check(basic_evaluator: Co closed_set=closed_set, context=context, metrics=context.metrics, - congestion_cache={}, - congestion_presence_cache={}, - congestion_candidate_precheck_cache={}, - congestion_net_envelope_cache={}, - congestion_grid_net_cache={}, - congestion_grid_span_cache={}, + congestion=CongestionCaches(), config=SearchRunConfig.from_options(context.options), move_type="straight", cache_key=("dominated",), @@ -512,12 +474,7 @@ def test_no_dynamic_paths_skips_congestion_check(basic_evaluator: CostEvaluator) closed_set=closed_set, context=context, metrics=context.metrics, - congestion_cache={}, - congestion_presence_cache={}, - congestion_candidate_precheck_cache={}, - congestion_net_envelope_cache={}, - congestion_grid_net_cache={}, - congestion_grid_span_cache={}, + congestion=CongestionCaches(), config=SearchRunConfig.from_options(context.options), move_type="straight", cache_key=("no-dynamic",), @@ -548,12 +505,7 @@ def test_guidance_seed_matching_move_reduces_cost_and_advances_seed_index( closed_set=closed_set, context=context, metrics=context.metrics, - congestion_cache={}, - congestion_presence_cache={}, - congestion_candidate_precheck_cache={}, - congestion_net_envelope_cache={}, - congestion_grid_net_cache={}, - congestion_grid_span_cache={}, + congestion=CongestionCaches(), config=SearchRunConfig.from_options( context.options, guidance_seed=(StraightSeed(length=10.0),), @@ -572,12 +524,7 @@ def test_guidance_seed_matching_move_reduces_cost_and_advances_seed_index( closed_set={}, context=context, metrics=context.metrics, - congestion_cache={}, - congestion_presence_cache={}, - congestion_candidate_precheck_cache={}, - congestion_net_envelope_cache={}, - congestion_grid_net_cache={}, - congestion_grid_span_cache={}, + congestion=CongestionCaches(), config=SearchRunConfig.from_options(context.options), move_type="straight", cache_key=("unguided",), @@ -618,12 +565,7 @@ def test_guidance_seed_bend90_keeps_full_bonus( closed_set={}, context=context, metrics=context.metrics, - congestion_cache={}, - congestion_presence_cache={}, - congestion_candidate_precheck_cache={}, - congestion_net_envelope_cache={}, - congestion_grid_net_cache={}, - congestion_grid_span_cache={}, + congestion=CongestionCaches(), config=SearchRunConfig.from_options( context.options, guidance_seed=(result.move_spec,), @@ -642,12 +584,7 @@ def test_guidance_seed_bend90_keeps_full_bonus( closed_set={}, context=context, metrics=context.metrics, - congestion_cache={}, - congestion_presence_cache={}, - congestion_candidate_precheck_cache={}, - congestion_net_envelope_cache={}, - congestion_grid_net_cache={}, - congestion_grid_span_cache={}, + congestion=CongestionCaches(), config=SearchRunConfig.from_options(context.options), move_type="bend90", cache_key=("unguided-bend90",), diff --git a/inire/tests/test_capacity.py b/inire/tests/test_capacity.py new file mode 100644 index 0000000..fe558c9 --- /dev/null +++ b/inire/tests/test_capacity.py @@ -0,0 +1,25 @@ +from dataclasses import replace + +from shapely.geometry import Polygon + +from inire.router._capacity import cut_capacity, port_conflicts +from inire.tests.routing_corpus import CASE_GROUPS + + +def test_cut_capacity_requires_rectangular_obstacles() -> None: + (case,) = CASE_GROUPS["overloaded-gate"] + bound = cut_capacity(case.problem, case.options) + assert bound is not None + assert (bound.crossing_nets, bound.tracks, bound.max_routed) == (4, 3, case.routing_bound) + + triangle = Polygon([(10, 10), (20, 10), (10, 20)]) + changed = replace(case.problem, static_obstacles=(*case.problem.static_obstacles, triangle)) + assert cut_capacity(changed, case.options) is None + + +def test_fixed_port_conflicts_are_disjoint_and_depend_on_clearance() -> None: + (case,) = CASE_GROUPS["lidar-clements-8x8"] + pairs = port_conflicts(case.problem, case.options) + assert len(case.problem.nets) - len(pairs) == case.routing_bound + assert len({net_id for pair in pairs for net_id in pair}) == 2 * len(pairs) + assert port_conflicts(replace(case.problem, clearance=0), case.options) == () diff --git a/inire/tests/test_collision.py b/inire/tests/test_collision.py index 7150358..02ed644 100644 --- a/inire/tests/test_collision.py +++ b/inire/tests/test_collision.py @@ -1,5 +1,8 @@ +import numpy +import pytest from shapely.geometry import box +import inire.geometry.collision as collision_module from inire.geometry.collision import RoutingWorld from inire.geometry.components import ComponentResult from inire.geometry.components import Straight @@ -63,6 +66,61 @@ def test_ray_cast_width_clearance() -> None: assert reach_fail < 10.0 +def test_ray_cast_reuses_exact_queries_and_separates_parameters() -> None: + engine = RoutingWorld(clearance=2.0) + engine.metrics = AStarMetrics() + engine.add_static_obstacle(box(10, -1, 20, 1)) + origin = Port(0, 0, 0) + + assert engine.ray_cast(origin, 0, 30, net_width=2.0) == pytest.approx(7.0) + assert engine.metrics.total_ray_cast_candidate_bounds == 1 + assert engine.ray_cast(origin, 0, 30, net_width=2.0, caller="expand_forward") == pytest.approx(7.0) + assert engine.metrics.total_ray_cast_calls == 2 + assert engine.metrics.total_ray_cast_calls_expand_forward == 1 + assert engine.metrics.total_ray_cast_candidate_bounds == 1 + + assert engine.ray_cast(origin, 0, 30, net_width=6.0) == pytest.approx(5.0) + assert engine.ray_cast(origin, 0, 30) == pytest.approx(9.0) + assert engine.ray_cast(origin, 0, 4, net_width=2.0) == 4.0 + assert engine.ray_cast(origin, 90, 30, net_width=2.0) == 30.0 + engine.clearance = 4.0 + assert engine.ray_cast(origin, 0, 30, net_width=2.0) == pytest.approx(5.0) + + +def test_ray_cast_discards_results_after_obstacle_changes() -> None: + engine = RoutingWorld(clearance=0.0) + origin = Port(0, 0, 0) + assert engine.ray_cast(origin, 0, 30, net_width=2.0) == 30.0 + + first = engine.add_static_obstacle(box(10, -1, 20, 1)) + assert engine.ray_cast(origin, 0, 30, net_width=2.0) == pytest.approx(9.0) + second = engine.add_static_obstacle(box(4, -1, 6, 1)) + assert engine.ray_cast(origin, 0, 30, net_width=2.0) == pytest.approx(3.0) + engine.remove_static_obstacle(second) + assert engine.ray_cast(origin, 0, 30, net_width=2.0) == pytest.approx(9.0) + engine.remove_static_obstacle(first) + assert engine.ray_cast(origin, 0, 30, net_width=2.0) == 30.0 + + +def test_ray_cast_preserves_scalar_precision_at_an_obstacle_boundary() -> None: + engine = RoutingWorld(clearance=0.0) + engine.add_static_obstacle(box(0, 10, 10, 20)) + origin = Port(0, 0, 0) + + assert engine.ray_cast(origin, 90.0, 30.0) == pytest.approx(10.0) + assert engine.ray_cast(origin, numpy.float32(90), 30.0) == 30.0 + + +def test_ray_cast_cache_has_a_fixed_capacity(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(collision_module, "_RAY_CAST_CACHE_LIMIT", 2) + engine = RoutingWorld(clearance=0.0) + engine.add_static_obstacle(box(10, -1, 20, 1)) + origin = Port(0, 0, 0) + for limit in (30, 40, 50): + assert engine.ray_cast(origin, 0, limit) == pytest.approx(10.0) + assert len(engine._static_obstacles.ray_cast_cache) <= 2 + + def test_check_move_static_clearance() -> None: engine = RoutingWorld(clearance=2.0) _install_static_straight(engine, Port(10, 50, 0), 10.0, width=100.0, dilation=1.0) @@ -331,8 +389,8 @@ def test_congestion_query_uses_per_polygon_bounds() -> None: blocker = Straight.generate(Port(40, 4, 90), 2.0, width=2.0, dilation=1.0) engine.add_path( "netB", - [poly for poly in blocker.collision_geometry], - dilated_geometry=[poly for poly in blocker.dilated_collision_geometry], + list(blocker.collision_geometry), + dilated_geometry=list(blocker.dilated_collision_geometry), ) move = ComponentResult( @@ -362,8 +420,8 @@ def test_congestion_touching_geometries_do_not_count_as_overlap() -> None: engine.add_path( "netB", - [poly for poly in existing.collision_geometry], - dilated_geometry=[poly for poly in existing.dilated_collision_geometry], + list(existing.collision_geometry), + dilated_geometry=list(existing.dilated_collision_geometry), ) assert engine.check_move_congestion(touching, "netA") == 0 @@ -376,8 +434,8 @@ def test_congestion_exact_checks_only_touch_relevant_move_polygons() -> None: blocker = Straight.generate(Port(0, 0, 0), 10.0, width=2.0, dilation=1.0) engine.add_path( "netB", - [poly for poly in blocker.collision_geometry], - dilated_geometry=[poly for poly in blocker.dilated_collision_geometry], + list(blocker.collision_geometry), + dilated_geometry=list(blocker.dilated_collision_geometry), ) move = ComponentResult( @@ -407,8 +465,8 @@ def test_congestion_grid_span_cache_reuses_broad_phase_candidates() -> None: blocker = Straight.generate(Port(15, 0, 0), 20.0, width=2.0, dilation=1.0) engine.add_path( "netB", - [poly for poly in blocker.collision_geometry], - dilated_geometry=[poly for poly in blocker.dilated_collision_geometry], + list(blocker.collision_geometry), + dilated_geometry=list(blocker.dilated_collision_geometry), ) move_a = Straight.generate(Port(5, 0, 0), 20.0, width=2.0, dilation=1.0) @@ -445,8 +503,8 @@ def test_has_possible_move_congestion_uses_presence_cache_and_skips_empty_spans( blocker = Straight.generate(Port(10, 0, 0), 20.0, width=2.0, dilation=1.0) engine.add_path( "netB", - [poly for poly in blocker.collision_geometry], - dilated_geometry=[poly for poly in blocker.dilated_collision_geometry], + list(blocker.collision_geometry), + dilated_geometry=list(blocker.dilated_collision_geometry), ) empty_move = Straight.generate(Port(200, 0, 0), 20.0, width=2.0, dilation=1.0) @@ -470,8 +528,8 @@ def test_has_candidate_move_congestion_uses_candidate_precheck_cache() -> None: blocker = Straight.generate(Port(10, 0, 0), 20.0, width=2.0, dilation=1.0) engine.add_path( "netB", - [poly for poly in blocker.collision_geometry], - dilated_geometry=[poly for poly in blocker.dilated_collision_geometry], + list(blocker.collision_geometry), + dilated_geometry=list(blocker.dilated_collision_geometry), ) empty_move = Straight.generate(Port(200, 0, 0), 20.0, width=2.0, dilation=1.0) occupied_move = Straight.generate(Port(0, 0, 0), 20.0, width=2.0, dilation=1.0) diff --git a/inire/tests/test_columns.py b/inire/tests/test_columns.py new file mode 100644 index 0000000..fccb95f --- /dev/null +++ b/inire/tests/test_columns.py @@ -0,0 +1,21 @@ +from inire.geometry.sbend import exact_sbend_spans +from inire.router._columns import _jog_pivots, _schedules +from inire.tests.terminal_bench_scenario import LENGTH_COST + + +def test_sbend_schedule_requires_a_window_long_enough_for_exact_spans() -> None: + profiles = [[(10, 30, 50)], [(30, 50, 70)]] + widths = (2, 2, 2) + spans = exact_sbend_spans(25) + short = _schedules(((0, 0), (35, 35)), profiles, widths, 2, 25, spans, LENGTH_COST, weighted=False, sbend_penalty=0) + assert list(short) == [] + + long = _schedules(((0, 0), (50, 50)), profiles, widths, 2, 25, spans, LENGTH_COST, weighted=False, sbend_penalty=0) + [(rows, transitions)] = list(long) + assert rows == ((10, 30, 50), (30, 50, 70)) + assert [(sequence.span, sequence.offsets) for sequence in transitions[0]] == [(40, (20,))] * 3 + + +def test_jog_transition_rejects_an_offset_that_cannot_fit_two_bends() -> None: + assert _jog_pivots((10, 40), (17, 40), (0, 100), (2, 2), 2, 5, 1) is None + assert _jog_pivots((10, 40), (25, 40), (0, 100), (2, 2), 2, 5, 1) == (8, None) diff --git a/inire/tests/test_components.py b/inire/tests/test_components.py index 3c14326..0a79666 100644 --- a/inire/tests/test_components.py +++ b/inire/tests/test_components.py @@ -5,6 +5,7 @@ from shapely.affinity import scale as shapely_scale from shapely.affinity import translate as shapely_translate from shapely.geometry import Polygon +import inire.geometry.components as components_module from inire.geometry.components import Bend90, SBend, Straight from inire.geometry.primitives import Port @@ -77,6 +78,31 @@ def test_sbend_generation_negative_offset_keeps_second_arc_below_centerline() -> assert second_arc_miny < -width / 2.0 +@pytest.mark.parametrize("collision_type", ["arc", "clipped_bbox"]) +def test_translate_reuses_shared_polygons_and_preserves_each_geometry_view( + monkeypatch: pytest.MonkeyPatch, collision_type: str +) -> None: + component = SBend.generate(Port(0, 0, 90), -5.0, 10.0, 2.0, collision_type=collision_type, dilation=1.0) + calls = [] + + def translate(polygon, dx, dy): + calls.append(id(polygon)) + return shapely_translate(polygon, dx, dy) + + monkeypatch.setattr(components_module, "shapely_translate", translate) + dx, dy = 81.25, -31.5 + shifted = component.translate(dx, dy) + + roles = ("collision_geometry", "physical_geometry", "dilated_collision_geometry", "dilated_physical_geometry") + for role in roles: + original = getattr(component, role) + assert tuple(poly.wkb for poly in getattr(shifted, role)) == tuple(shapely_translate(poly, dx, dy).wkb for poly in original) + assert set(calls) == {id(poly) for role in roles for poly in getattr(component, role)} + assert len(calls) == len(set(calls)) + assert shifted.start_port == component.start_port.translate(dx, dy) + assert shifted.end_port == component.end_port.translate(dx, dy) + + def test_bend_collision_models() -> None: start = Port(0, 0, 0) radius = 10.0 diff --git a/inire/tests/test_congestion_policy.py b/inire/tests/test_congestion_policy.py new file mode 100644 index 0000000..26a3cfc --- /dev/null +++ b/inire/tests/test_congestion_policy.py @@ -0,0 +1,36 @@ +from inire.results import RoutingResult +from inire.router._congestion_policy import ( + IterationReview, + next_reroute_net_ids, + reached_pair_local_plateau, + repeated_conflict_count, + reroute_plan, +) + + +def test_reroute_plan_caps_only_heavy_nets_in_the_final_conflict_regime() -> None: + ordered = ("a", "b", "c", "d", "e") + results = {net_id: RoutingResult(net_id, (), reached_target=True) for net_id in ordered} + last_work = {"a": 320, "b": 199, "c": 320, "d": 20} + reroute = set(last_work) + + assert reroute_plan(ordered, reroute, last_work, best_conflict_edges=2, results=results) == (["d", "b", "a", "c"], {"a", "c"}) + assert reroute_plan(ordered, reroute, last_work, best_conflict_edges=3, results=results) == (["d", "b", "a", "c"], set()) + assert reroute_plan(ordered, set(ordered), last_work, best_conflict_edges=2, results=results) == (list(ordered), set()) + + +def test_next_reroute_nets_respect_reached_targets_and_corridors() -> None: + ordered = ("a", "b", "c", "d") + review = IterationReview({"a", "b"}, {("a", "b")}, {"d"}, 2) + assert next_reroute_net_ids(ordered, review, all_reached_target=True, has_corridors=True) == {"a", "b"} + assert next_reroute_net_ids(ordered, review, all_reached_target=False, has_corridors=True) == {"a", "b", "c"} + assert next_reroute_net_ids(ordered, review, all_reached_target=False, has_corridors=False) == set(ordered) + + +def test_stopping_rules_track_plateau_and_repeated_conflict_count() -> None: + assert reached_pair_local_plateau(improved=False, all_reached_target=True, best_conflict_edges=2) + assert not reached_pair_local_plateau(improved=True, all_reached_target=True, best_conflict_edges=2) + assert not reached_pair_local_plateau(improved=False, all_reached_target=True, best_conflict_edges=3) + assert repeated_conflict_count(2, 2, 1) == 2 + assert repeated_conflict_count(3, 2, 1) == 0 + assert repeated_conflict_count(0, 0, 1) == 0 diff --git a/inire/tests/test_failed_net_congestion.py b/inire/tests/test_failed_net_congestion.py index db300ce..4e09f82 100644 --- a/inire/tests/test_failed_net_congestion.py +++ b/inire/tests/test_failed_net_congestion.py @@ -1,3 +1,5 @@ +from shapely.geometry import box + from inire import CongestionOptions, RoutingOptions, RoutingProblem from inire.geometry.primitives import Port from inire.geometry.collision import RoutingWorld @@ -27,8 +29,6 @@ def test_failed_net_visibility() -> None: # Start (0,0) -> Target (100,0) is 100um away. # Let's add a static obstacle that blocks the direct path. - from shapely.geometry import box - obstacle = box(40, -10, 60, 10) # Wall at x=50 engine.add_static_obstacle(obstacle) diff --git a/inire/tests/test_pathfinder.py b/inire/tests/test_pathfinder.py index 0c5b6e0..05e9851 100644 --- a/inire/tests/test_pathfinder.py +++ b/inire/tests/test_pathfinder.py @@ -1,6 +1,7 @@ import pytest from shapely.geometry import box +import inire.router._router as router_module from inire import ( CongestionOptions, DiagnosticsOptions, @@ -14,6 +15,7 @@ from inire import ( from inire.geometry.collision import RoutingWorld from inire.geometry.components import Bend90, Straight from inire.geometry.primitives import Port +from inire.results import RoutingResult from inire.router._astar_types import AStarContext from inire.router._router import PathFinder from inire.router.cost import CostEvaluator @@ -101,6 +103,83 @@ def _build_manual_path(start: Port, width: float, clearance: float, steps: list[ path.append(comp) curr = comp.end_port return path + + +@pytest.mark.parametrize("search_raises", [False, True], ids=["success", "exception"]) +def test_frontier_replay_restores_installed_path_and_metrics(monkeypatch: pytest.MonkeyPatch, search_raises: bool) -> None: + world = RoutingWorld(clearance=2.0) + danger_map = DangerMap(bounds=DEFAULT_BOUNDS) + finder = _build_pathfinder( + CostEvaluator(world, danger_map), + netlist={"replayed": (Port(10, 20, 0), Port(90, 20, 0)), "other": (Port(10, 40, 0), Port(90, 40, 0))}, + net_widths={}, + warm_start_enabled=False, + ) + state = finder._prepare_state() + for net_id, net in state.net_specs.items(): + path = (Straight.generate(net.start, 80, net.width, dilation=world.clearance / 2),) + state.results[net_id] = RoutingResult(net_id, path, reached_target=True) + finder._install_path(net_id, path) + + original_metrics = finder.metrics + original_snapshot = original_metrics.snapshot() + original_bounds = sorted(world.iter_dynamic_path_bounds(DEFAULT_BOUNDS)) + other_bounds = [component.bounds for component in state.results["other"].path[0].collision_geometry] + hotspot_bounds = ((30.0, 15.0, 50.0, 25.0),) + + def replay_search(_start, _target, _width, *, context, metrics, net_id, config): + assert net_id == "replayed" + assert config.frontier_trace.hotspot_bounds == hotspot_bounds + assert list(world.iter_dynamic_path_bounds(DEFAULT_BOUNDS)) == other_bounds + assert metrics is context.metrics is world.metrics is danger_map.metrics + assert metrics is not original_metrics + metrics.total_nodes_expanded += 1 + if search_raises: + raise RuntimeError("frontier search failed") + + monkeypatch.setattr(router_module, "route_astar", replay_search) + result = state.results["replayed"] + if search_raises: + with pytest.raises(RuntimeError, match="frontier search failed"): + finder._capture_single_frontier_trace(state, result.net_id, result, hotspot_bounds) + else: + trace = finder._capture_single_frontier_trace(state, result.net_id, result, hotspot_bounds) + assert trace.net_id == result.net_id + assert trace.hotspot_bounds == hotspot_bounds + + assert finder.metrics is finder.context.metrics is world.metrics is danger_map.metrics is original_metrics + assert original_metrics.snapshot() == original_snapshot + assert sorted(world.iter_dynamic_path_bounds(DEFAULT_BOUNDS)) == original_bounds + + +def test_failed_greedy_warm_start_releases_obstacles(monkeypatch: pytest.MonkeyPatch) -> None: + world = RoutingWorld(clearance=2.0) + obstacle = box(20, 60, 40, 80) + world.add_static_obstacle(obstacle) + finder = _build_pathfinder( + CostEvaluator(world), + netlist={"first": (Port(10, 20, 0), Port(90, 20, 0)), "second": (Port(10, 40, 0), Port(90, 40, 0))}, + net_widths={}, + max_iterations=1, + ) + + def interrupted_search(start, _target, width, *, net_id, **_options): + if net_id == "first": + return [Straight.generate(start, 80, width, dilation=world.clearance / 2)] + assert len(tuple(world.iter_static_geometries())) == 2 + raise RuntimeError("warm start interrupted") + + with monkeypatch.context() as patch: + patch.setattr(router_module, "route_astar", interrupted_search) + with pytest.raises(RuntimeError, match="warm start interrupted"): + finder.route_all() + + assert tuple(world.iter_static_geometries()) == (obstacle,) + assert finder.context.static_cache_version == world.get_static_version() + assert all(result.is_valid for result in finder.route_all().values()) + assert tuple(world.iter_static_geometries()) == (obstacle,) + + def test_route_all_refreshes_static_caches_after_static_topology_changes() -> None: netlist = {"net": (Port(0, 0, 0), Port(10, 10, 90))} widths = {"net": 2.0} diff --git a/inire/tests/test_primitives.py b/inire/tests/test_primitives.py index 7e2bd5b..15d3659 100644 --- a/inire/tests/test_primitives.py +++ b/inire/tests/test_primitives.py @@ -4,7 +4,18 @@ from typing import Any from hypothesis import given, strategies as st import pytest -from inire.geometry.primitives import Port +from inire.geometry.primitives import Port, port_local_coordinates, rotate_cardinal + + +@pytest.mark.parametrize( + ("heading", "expected"), + [(0, (3.5, 7.25)), (90, (7.25, -3.5)), (180, (-3.5, -7.25)), (270, (-7.25, 3.5))], +) +def test_port_local_coordinates_preserve_fractional_points(heading, expected) -> None: + origin = Port(10, -4, heading) + local = port_local_coordinates(origin, 13.5, 3.25) + assert local == expected + assert rotate_cardinal(*local, heading) == (3.5, 7.25) @st.composite diff --git a/inire/tests/test_routing_benchmark_parity.py b/inire/tests/test_routing_benchmark_parity.py new file mode 100644 index 0000000..010cf7f --- /dev/null +++ b/inire/tests/test_routing_benchmark_parity.py @@ -0,0 +1,31 @@ +import json +import sys + +from scripts.routing_benchmark_parity import main + + +def test_parity_command_reports_the_first_net_difference(tmp_path, monkeypatch, capsys) -> None: + before = tmp_path / "before.json" + after = tmp_path / "after.json" + monkeypatch.setattr(sys, "argv", [ + "parity", "capture", str(before), "--case", "reversed-heading", "--profile", "corpus-regression", "--callbacks", + ]) + assert main() == 0 + payload = json.loads(before.read_text()) + ordinary, with_callback = payload["runs"] + assert ordinary["stable"]["callbacks"] == [] + assert with_callback["stable"]["callbacks"] + assert "native" in ordinary["stable"]["costs"]["return"] + + ordinary["elapsed_s"] += 5 + after.write_text(json.dumps(payload)) + monkeypatch.setattr(sys, "argv", ["parity", "compare", str(before), str(after)]) + assert main() == 0 + assert "2 runs match." in capsys.readouterr().out + + ordinary["stable"]["nets"]["return"]["seed"][0]["kind"] = "DifferentMove" + after.write_text(json.dumps(payload)) + assert main() == 1 + message = capsys.readouterr().out + assert "reversed-heading / corpus-regression" in message + assert "nets.return.seed[0].kind" in message diff --git a/inire/tests/test_routing_benchmarks.py b/inire/tests/test_routing_benchmarks.py index 41c6b38..cd8bf5f 100644 --- a/inire/tests/test_routing_benchmarks.py +++ b/inire/tests/test_routing_benchmarks.py @@ -11,15 +11,17 @@ from inire import Bend90Seed, NetSpec, Port, RoutingOptions, RoutingProblem, SBe from inire.constants import TOLERANCE_LINEAR from inire.router._automatic import _AutomaticRun from inire.router._routing_policy import _disconnected_nets +from inire.tests.retry_holdout_benchmarks import RETRY_HOLDOUT_CASES from inire.tests.routing_benchmarks import ( BENCHMARK_CASES, COMPLEX_BENCHMARK_CASES, CROSSING_BENCHMARK_CASES, EXTERNAL_BENCHMARK_CASES, FALLBACK_BENCHMARK_CASES, - VALIDATION_BENCHMARK_CASES, ) +from inire.tests.routing_corpus import CASE_GROUPS, CORPUS_CASES, automatic_options, profile_options from inire.tests.stress_routing_benchmarks import STRESS_BENCHMARK_CASES +from scripts.benchmark_retry_order import _POLICIES, _RetryExperiment from scripts.compare_topological_routing import ( _direct_trials, _geometry_json, @@ -36,41 +38,24 @@ def _measure(case, options, strategy): @pytest.mark.routing_corpus @pytest.mark.parametrize( "case", - [ - pytest.param(case, id=case.name) - for case in ( - *BENCHMARK_CASES, *VALIDATION_BENCHMARK_CASES, *FALLBACK_BENCHMARK_CASES, *EXTERNAL_BENCHMARK_CASES, *CROSSING_BENCHMARK_CASES, - *STRESS_BENCHMARK_CASES, - ) - ], + [pytest.param(case, id=case.name) for case in CORPUS_CASES], ) def test_automatic_reaches_corpus_routing_bound(case) -> None: - options = replace( - case.options, - search=replace(case.options.search, node_limit=500), - topology=replace(case.options.topology, seed_node_limit=500), - congestion=replace(case.options.congestion, max_iterations=3), - ) - run = route(case.problem, options=_mode_options(options, "automatic", "matched-budget")) + profile = "corpus-regression" + options = automatic_options(profile_options(case, profile), profile) + run = route(case.problem, options=options) assert run.automatic is not None assert run.results_by_net.keys() == {net.net_id for net in case.problem.nets} verified = {net_id for net_id, result in run.results_by_net.items() if result.is_valid} - expected = {"overloaded-gate": 3, "lidar-clements-8x8": 3}.get(case.name, len(case.problem.nets)) - assert run.automatic.max_routed == expected + assert run.automatic.max_routed == case.routing_bound assert set(run.automatic.verified_net_ids) == verified - assert len(verified) == expected + assert len(verified) == case.routing_bound @pytest.mark.parametrize( "case", - [ - pytest.param(case, id=case.name) - for case in ( - *BENCHMARK_CASES, *VALIDATION_BENCHMARK_CASES, *FALLBACK_BENCHMARK_CASES, *CROSSING_BENCHMARK_CASES, *STRESS_BENCHMARK_CASES - ) - if case.reference_paths - ], + [pytest.param(case, id=case.name) for case in (*CORPUS_CASES, *RETRY_HOLDOUT_CASES) if case.reference_paths], ) def test_benchmark_reference_paths_are_feasible(case) -> None: reference = dict(case.reference_paths) @@ -92,9 +77,10 @@ def test_benchmark_reference_paths_are_feasible(case) -> None: assert a.distance(b) >= problem.clearance - TOLERANCE_LINEAR -def test_stress_cases_start_unseeded_with_complete_reference_paths() -> None: - assert len({case.name for case in STRESS_BENCHMARK_CASES}) == len(STRESS_BENCHMARK_CASES) - for case in STRESS_BENCHMARK_CASES: +def test_stress_and_retry_holdout_cases_start_unseeded_with_complete_reference_paths() -> None: + cases = (*STRESS_BENCHMARK_CASES, *RETRY_HOLDOUT_CASES) + assert len({case.name for case in cases}) == len(cases) + for case in cases: assert not case.problem.initial_paths assert dict(case.reference_paths).keys() == {net.net_id for net in case.problem.nets} search = case.options.search @@ -136,6 +122,39 @@ def test_stress_opposed_sbends_fit_together_without_search() -> None: assert run.metrics.nodes_expanded == 0 +def test_stress_residual_dogleg_completes_layout_before_wider_search() -> None: + case = next(case for case in STRESS_BENCHMARK_CASES if case.name == "stress-retry-straight-decoy") + options = replace( + case.options, + topology=TopologyOptions(mode="automatic"), + congestion=replace(case.options.congestion, max_iterations=3), + ) + + report = route(case.problem, options=options).automatic + + assert report is not None + assert set(report.verified_net_ids) == {net.net_id for net in case.problem.nets} + assert report.selected_planner == "residual-dogleg" + [search] = [stage for stage in report.stages if stage.operation == "search"] + assert search.policy == "direct-probe-near-port" + assert set(search.valid_net_ids) == {"branch_west", "branch_east", "lower_rail"} + + +def test_opt_in_near_port_recovery_finishes_before_the_direct_retry() -> None: + (case,) = CASE_GROUPS["stress-crossings-shared-outside-detour"] + profile = "corpus-regression" + options = automatic_options(profile_options(case, profile), profile) + + report = _RetryExperiment(case.problem, options, _POLICIES["recover-near-port"]).execute().automatic + + assert report is not None + assert set(report.verified_net_ids) == {net.net_id for net in case.problem.nets} + searches = [stage for stage in report.stages if stage.operation == "search"] + assert [stage.policy for stage in searches] == ["direct-probe-near-port", "incumbent-residual"] + assert len(searches[0].valid_net_ids) == 7 + assert report.stages[report.selected_stage].kind == "incumbent-verified" + + def test_automatic_routes_an_unseeded_grid_between_preplaced_crossing_ports() -> None: case = next(case for case in CROSSING_BENCHMARK_CASES if case.name == "crossing-aligned-grid") assert not case.problem.initial_paths @@ -213,6 +232,7 @@ def test_automatic_times_planning_search_verification_and_refinement() -> None: ("public-defaults", "on", "1"), ("matched-budget", None, "unlimited"), ("matched-budget", "on", None), + ("corpus-regression", None, None), ], ) def test_benchmark_profile_records_effective_options(profile, refinement, max_windows, tmp_path, monkeypatch) -> None: @@ -237,6 +257,8 @@ def test_benchmark_profile_records_effective_options(profile, refinement, max_wi assert options["search"]["bend_radii"] == list(geometry.bend_radii) assert shape(options["search"]["bend_physical_geometry"]).equals(geometry.bend_physical_geometry) [sample] = run["samples"] + assert payload["cost_metrics"] == {"valid_costs": "benchmark_weighted_length", "native_valid_costs": "native_objective"} + assert sample["native_valid_costs"].keys() == sample["valid_costs"].keys() stage = sample["stages"][sample["selected_stage"]] assert stage["planner"] == "lattice" assert stage["mode"] == "off" @@ -257,7 +279,8 @@ def test_benchmark_profile_records_effective_options(profile, refinement, max_wi else: assert options["search"]["node_limit"] == 500 assert options["objective"] == asdict(case.options.objective) - assert options["congestion"]["max_iterations"] == 2 + assert options["congestion"]["max_iterations"] == (3 if profile == "corpus-regression" else 2) + assert options["topology"]["seed_node_limit"] == (500 if profile == "corpus-regression" else defaults.topology.seed_node_limit) assert options["topology"]["automatic_length_weights"] == [1.0, 4.0, 13.0] diff --git a/inire/tests/test_topology.py b/inire/tests/test_topology.py index 18a90ae..81b92b2 100644 --- a/inire/tests/test_topology.py +++ b/inire/tests/test_topology.py @@ -5,10 +5,25 @@ from shapely.geometry import LineString, box from inire import CongestionOptions, NetSpec, PathSeed, Port, RoutingOptions, RoutingProblem, SearchOptions, StraightSeed, TopologyOptions, route from inire.router._stack import build_routing_stack -from inire.router._topology import plan_corridors +from inire.router._topology import _Assignment, _endpoint_access, _Mesh, _plan_lane_assignments, plan_corridors from inire.tests.routing_benchmarks import DETOUR +def test_lane_assignment_keeps_mesh_path_order_on_equal_costs(monkeypatch: pytest.MonkeyPatch) -> None: + problem = DETOUR.problem + mesh = _Mesh(box(*problem.bounds), problem.static_obstacles, problem.nets[0].width / 2, problem.clearance) + endpoints, leads = _endpoint_access(mesh, problem.nets, 50) + paths = mesh.alternatives(*endpoints["detour"], {}, 2) + assert len(paths) == 2 + + def equal_cost(_self, cells, start, target, _reservations, _bend_radius): + return _Assignment(cells, (start.port, target.port), 1.0) + + monkeypatch.setattr(_Mesh, "assign_lanes", equal_cost) + assignments = _plan_lane_assignments(mesh, problem.nets, endpoints, leads, bend_radius=50, limit=2, joint_net_ids=frozenset()) + assert [assignment.cells for assignment in assignments["detour"]] == paths + + def test_topological_planner_finds_both_sides_of_an_obstacle() -> None: problem = DETOUR.problem corridors = plan_corridors(problem.bounds, problem.static_obstacles, problem.nets, clearance=6, bend_radius=50, limit=2) diff --git a/inire/tests/trace_recording.py b/inire/tests/trace_recording.py new file mode 100644 index 0000000..5f826d6 --- /dev/null +++ b/inire/tests/trace_recording.py @@ -0,0 +1,80 @@ +"""Shared scenario selection and artifact writing for the trace scripts.""" + +from __future__ import annotations + +from argparse import ArgumentParser +from dataclasses import asdict +from datetime import datetime +from json import dumps +from pathlib import Path +from typing import TYPE_CHECKING + +from inire.tests.example_scenarios import TRACE_PERFORMANCE_SCENARIO_RUNS, TRACE_SCENARIO_RUNS + +if TYPE_CHECKING: + from collections.abc import Callable + + from inire.results import RoutingRunResult + + +NO_WARM_START_SCENARIOS = ( + "example_07_large_scale_routing_no_warm_start", + "example_07_large_scale_routing_no_warm_start_seed43", +) + + +def result_summary(run: RoutingRunResult) -> dict[str, object]: + results = run.results_by_net.values() + return { + "total_results": len(results), + "valid_results": sum(result.is_valid for result in results), + "reached_targets": sum(result.reached_target for result in results), + } + + +def record_trace( + source: str, + name: str, + *, + scenario_label: str, + default_scenarios: tuple[str, ...], + scenario_payload: Callable[[RoutingRunResult], dict[str, object]], + render_markdown: Callable[[dict[str, object]], str], +) -> None: + parser = ArgumentParser(description=f"Record {name.replace('_', '-')} artifacts for selected trace scenarios.") + parser.add_argument("--scenario", action="append", help="Trace scenario name. Repeat to select multiple scenarios.") + parser.add_argument("--include-performance-only", action="store_true", help="Accept performance-only scenario names.") + parser.add_argument("--output-dir", type=Path, help=f"Directory for {name}.json and {name}.md. Defaults to /docs.") + args = parser.parse_args() + + registry = dict(TRACE_SCENARIO_RUNS + TRACE_PERFORMANCE_SCENARIO_RUNS) + selected = args.scenario or default_scenarios + for scenario in selected: + if scenario not in registry: + valid = ", ".join(sorted(registry)) + raise SystemExit(f"Unknown {scenario_label} scenario: {scenario}. Valid scenarios: {valid}") + + source_path = Path(source).resolve() + repo_root = source_path.parents[1] + output_dir = repo_root / "docs" if args.output_dir is None else args.output_dir.resolve() + output_dir.mkdir(exist_ok=True) + scenarios = [] + for scenario in selected: + run = registry[scenario]() + scenarios.append({ + "name": scenario, + "summary": result_summary(run), + "metrics": asdict(run.metrics), + **scenario_payload(run), + }) + payload = { + "generated_at": datetime.now().astimezone().isoformat(timespec="seconds"), + "generator": f"scripts/{source_path.name}", + "scenarios": scenarios, + } + json_path = output_dir / f"{name}.json" + markdown_path = output_dir / f"{name}.md" + json_path.write_text(dumps(payload, indent=2, sort_keys=True) + "\n") + markdown_path.write_text(render_markdown(payload) + "\n") + for path in (json_path, markdown_path): + print(f"Wrote {path.relative_to(repo_root) if path.is_relative_to(repo_root) else path}") diff --git a/scripts/benchmark_retry_order.py b/scripts/benchmark_retry_order.py new file mode 100644 index 0000000..64441e3 --- /dev/null +++ b/scripts/benchmark_retry_order.py @@ -0,0 +1,285 @@ +"""Compare opt-in automatic retry orders on the routing corpus.""" + +from __future__ import annotations + +from argparse import ArgumentParser +from concurrent.futures import ProcessPoolExecutor +from dataclasses import asdict, dataclass, replace +from functools import partial +from json import dumps +from pathlib import Path +from statistics import median +from time import perf_counter +from typing import TYPE_CHECKING + +from inire import route +from inire.router._automatic import _AutomaticRun, _INITIAL_NODE_LIMIT +from inire.router._routing_policy import LockPlan, _best_trial, _direct_trials, _disconnected_nets, _route_residual +from inire.tests.routing_corpus import ( + CASE_GROUPS, + PROFILES, + automatic_options, + benchmark_weighted_length, + native_verified_costs, + profile_options, + select_cases, +) + +if TYPE_CHECKING: + from inire.model import RoutingOptions, RoutingProblem + from inire.results import RoutingResult + from inire.router._routing_policy import Trial + from inire.tests.routing_benchmark_case import BenchmarkCase + + +@dataclass(frozen=True, slots=True) +class _RetryPolicy: + lattice_limit: int | None = None + recovery_stage: str | None = None + recovery_remaining: int = 1 + probe_iterations: int | None = None + residual_limit: int | None = None + residual_after_fallback: bool = False + + +_POLICIES = { + "baseline": _RetryPolicy(), + **{f"lattice-{limit}": _RetryPolicy(lattice_limit=limit) for limit in (500, 750, 1000, 1500, 2000)}, + "recover-lookahead": _RetryPolicy(recovery_stage="direct-lookahead-retry"), + "recover-near-port": _RetryPolicy(recovery_stage="direct-probe-near-port", recovery_remaining=2), + "lattice-1500-and-recover-near-port": _RetryPolicy( + lattice_limit=1500, recovery_stage="direct-probe-near-port", recovery_remaining=2 + ), + **{f"probe-iterations-{count}": _RetryPolicy(probe_iterations=count) for count in (1, 2, 3)}, + **{f"residual-{limit}": _RetryPolicy(residual_limit=limit) for limit in (1500, 3000)}, + "late-residual-3000": _RetryPolicy(residual_limit=3000, residual_after_fallback=True), +} + + +class _RetryExperiment(_AutomaticRun): + def __init__(self, problem: RoutingProblem, options: RoutingOptions, policy: _RetryPolicy) -> None: + super().__init__(problem, options, None) + self.retry_policy = policy + self.retry_attempts: list[dict] = [] + + def _record_retry(self, policy: str, outcome: str, started: float, first_run: int) -> None: + self.retry_attempts.append({ + "policy": policy, + "outcome": outcome, + "elapsed_s": perf_counter() - started, + "nodes_expanded": sum(metrics.nodes_expanded for metrics in self.metrics[first_run:]), + }) + + def _search_trials(self, trials: list[Trial], target: int) -> None: + self.routing_bound = target + super()._search_trials(trials, target) + limit = self.retry_policy.residual_limit + if ( + not self.retry_policy.residual_after_fallback + or limit is None + or limit > self.options.search.node_limit + or target != len(self.problem.nets) + or self.problem.initial_paths + ): + return + best = _best_trial(trials) + if target <= 2 or len(best.valid_costs) != target - 1: + return + + retained = {net_id: best.run.results_by_net[net_id] for net_id in best.valid_costs} + options = replace(self.options, refinement=replace(self.options.refinement, enabled=False)) + trials.extend(self._widen_residual(options, retained, limit, target, policy="late-bounded-residual", check_connectivity=True)) + + def _recover_before_direct_retry(self, attempt: Trial, options: RoutingOptions) -> list[Trial]: + target = len(self.problem.nets) + verified = len(attempt.valid_costs) + if ( + self.routing_bound < target + or target <= 2 + or self.problem.initial_paths + or not 0 < target - verified <= self.retry_policy.recovery_remaining + or 3 * verified < 2 * target + ): + return [] + + seeded = replace( + options, + search=replace(options.search, node_limit=min(_INITIAL_NODE_LIMIT, self.options.search.node_limit)), + congestion=replace(options.congestion, max_iterations=min(2, options.congestion.max_iterations)), + topology=replace(options.topology, mode="seed"), + ) + started, first_run = perf_counter(), len(self.metrics) + recovered = self._incumbent_trials(seeded, attempt, target, retry_disconnected=False) + complete = any(candidate.selectable and len(candidate.valid_costs) == target for candidate in recovered) + outcome = "incomplete" if recovered else "disconnected" + self._record_retry("incumbent-recovery", "complete" if complete else outcome, started, first_run) + if complete: + return recovered + # Keep failed experimental work visible without changing the fallback incumbent. + return [replace(candidate, selection="incomplete-layout") for candidate in recovered] + + def _direct(self, options: RoutingOptions, policy: str) -> list[Trial]: + if policy == "direct-probe-near-port" and self.retry_policy.probe_iterations is not None: + iterations = min(options.congestion.max_iterations, self.retry_policy.probe_iterations) + options = replace(options, congestion=replace(options.congestion, max_iterations=iterations)) + if policy != self.retry_policy.recovery_stage: + return super()._direct(options, policy) + with self._time("plan", planner="direct", policy=policy): + return _direct_trials( + self.problem, + self.board, + options, + policy, + run_route=partial(self._run, policy=policy), + check_trial=self._trial, + recover_before_retry=partial(self._recover_before_direct_retry, options=options), + ) + + def _seed_recovery_trials(self, options: RoutingOptions, trials: list[Trial], target: int) -> None: + limit = self.retry_policy.lattice_limit + if ( + limit is not None + and limit <= self.options.search.node_limit + and target == len(self.problem.nets) > 2 + and not self.problem.initial_paths + and _near_port_coverage_stalled(trials, target) + ): + retry = replace(options, search=replace(options.search, node_limit=limit)) + started, first_run = perf_counter(), len(self.metrics) + self._lattice_fallback(trials, retry, "Near-port and lookahead searches were one net short", policy="early-bounded-lattice") + complete = len(trials[-1].valid_costs) == target + self._record_retry("bounded-lattice", "complete" if complete else "incomplete", started, first_run) + if complete: + return + trials[-1] = replace(trials[-1], selection="incomplete-layout") + super()._seed_recovery_trials(options, trials, target) + + def _incumbent_trials(self, options: RoutingOptions, best: Trial, target: int, *, retry_disconnected: bool = True) -> list[Trial]: + trials = super()._incumbent_trials(options, best, target, retry_disconnected=retry_disconnected) + limit = self.retry_policy.residual_limit + if ( + limit is None + or self.retry_policy.residual_after_fallback + or not options.search.node_limit < limit <= self.options.search.node_limit + or target != len(self.problem.nets) + or len(best.valid_costs) != target - 1 + or not trials + or trials[0].stage.kind != "incumbent-residual" + or any(trial.selectable and len(trial.valid_costs) >= target for trial in trials) + ): + return trials + + retained = {net_id: best.run.results_by_net[net_id] for net_id in best.valid_costs} + return [*trials, *self._widen_residual(options, retained, limit, target, policy="bounded-residual")] + + def _widen_residual( + self, + options: RoutingOptions, + retained: dict[str, RoutingResult], + limit: int, + target: int, + *, + policy: str, + check_connectivity: bool = False, + ) -> list[Trial]: + started, first_run = perf_counter(), len(self.metrics) + if check_connectivity: + with self._time("plan", policy=policy): + blocked = _disconnected_nets(self.problem, self.board, options, retained) + if blocked: + self._record_retry(policy, "disconnected", started, first_run) + return [] + + retry = replace( + options, + search=replace(options.search, node_limit=limit), + topology=replace(options.topology, seed_node_limit=max(limit, options.topology.seed_node_limit)), + congestion=replace(options.congestion, max_iterations=min(2, options.congestion.max_iterations)), + ) + run, stage = _route_residual(self.problem, retry, "direct-seed", LockPlan(retained), run_route=partial(self._run, policy=policy)) + trial = self._trial(run, replace(stage, kind=policy, policy=policy, incumbent_net_ids=tuple(retained))) + trials = [replace(trial, selection="requires-layout-check")] + complete = False + if len(trial.valid_costs) == target: + verified = self._verify_incumbent(trial) + complete = len(verified.valid_costs) == target + trials.append(verified if complete else replace(verified, selection="incomplete-layout")) + self._record_retry(policy, "complete" if complete else "incomplete", started, first_run) + return trials + + +def _near_port_coverage_stalled(trials: list[Trial], target: int) -> bool: + near = [trial for trial in trials if trial.selectable and trial.stage.policy == "direct-probe-near-port"] + wider = [trial for trial in trials if trial.selectable and trial.stage.policy == "direct-lookahead-retry"] + if not near or not wider: + return False + first, second = _best_trial(near), _best_trial(wider) + return len(first.valid_costs) == target - 1 and first.valid_costs.keys() == second.valid_costs.keys() + + +def _measure(case: BenchmarkCase, profile: str, name: str) -> dict: + options = automatic_options(profile_options(case, profile), profile) + started = perf_counter() + experiment = None if name == "baseline" else _RetryExperiment(case.problem, options, _POLICIES[name]) + if experiment is None: + run = route(case.problem, options=options) + else: + run = experiment.execute() + elapsed = perf_counter() - started + report = run.automatic + assert report is not None + verified = sorted(report.verified_net_ids) + return { + "elapsed_s": elapsed, + "verified": verified, + "routing_bound": report.max_routed, + "nodes_expanded": run.metrics.nodes_expanded, + "weighted_cost": {net_id: benchmark_weighted_length(run.results_by_net[net_id]) for net_id in verified}, + "native_cost": native_verified_costs(case, options, run.results_by_net, verified), + "seeds": {net_id: repr(run.results_by_net[net_id].as_seed()) for net_id in verified}, + "stages": [asdict(stage) for stage in report.stages], + "selected_stage": report.selected_stage, + "retry_attempts": [] if experiment is None else experiment.retry_attempts, + "timings": [asdict(timing) for timing in report.timings], + } + + +def _measure_case(job: tuple[BenchmarkCase, str, tuple[str, ...], int]) -> dict: + case, profile, policies, repeats = job + samples = {name: [] for name in policies} + for index in range(repeats): + offset = index % len(policies) + for name in policies[offset:] + policies[:offset]: + samples[name].append(_measure(case, profile, name)) + return {"case": case.name, "profile": profile, "required": len(case.problem.nets), "samples": samples} + + +def main() -> None: + parser = ArgumentParser(description=__doc__) + parser.add_argument("--case", choices=tuple(CASE_GROUPS), action="append") + parser.add_argument("--profile", choices=PROFILES, action="append") + parser.add_argument("--policy", choices=tuple(_POLICIES), action="append") + parser.add_argument("--repeat", type=int, default=1) + parser.add_argument("--jobs", type=int, default=1) + parser.add_argument("--json", type=Path, required=True) + args = parser.parse_args() + if args.repeat < 1 or args.jobs < 1: + parser.error("--repeat and --jobs must be positive") + cases = select_cases(args.case or ["corpus"]) + profiles = tuple(dict.fromkeys(args.profile or ("public-defaults", "corpus-regression"))) + policies = tuple(dict.fromkeys(args.policy or _POLICIES)) + jobs = [(case, profile, policies, args.repeat) for case in cases for profile in profiles] + rows = [] + with ProcessPoolExecutor(max_workers=args.jobs) as pool: + for result in pool.map(_measure_case, jobs): + rows.append(result) + summary = " ".join( + f"{name}={len(samples[0]['verified'])}/{result['required']}@{median(s['elapsed_s'] for s in samples):.3f}s" + for name, samples in result["samples"].items() + ) + print(result["case"], result["profile"], summary, flush=True) + args.json.write_text(dumps({"runs": rows}, indent=2) + "\n", encoding="utf-8") + + +if __name__ == "__main__": + main() diff --git a/scripts/compare_topological_routing.py b/scripts/compare_topological_routing.py index 2493227..783c905 100644 --- a/scripts/compare_topological_routing.py +++ b/scripts/compare_topological_routing.py @@ -20,30 +20,27 @@ from inire import RoutingOptions, RoutingStage, route from inire.router._routing_policy import DIRECT_POLICIES, _best_trial from inire.router._routing_policy import _direct_trials as _run_direct_trials from inire.router._routing_policy import _trial as _summarize_trial -from inire.tests.routing_benchmarks import ( - BENCHMARK_CASES, - COMPLEX_BENCHMARK_CASES, - CROSSING_BENCHMARK_CASES, - EXTERNAL_BENCHMARK_CASES, - FALLBACK_BENCHMARK_CASES, - VALIDATION_BENCHMARK_CASES, +from inire.tests.routing_corpus import ( + AUTOMATIC_POLICIES, + CASE_GROUPS, + PROFILES, + automatic_options, + benchmark_weighted_length, + native_verified_costs, + profile_options, + select_cases, ) -from inire.tests.stress_routing_benchmarks import STRESS_BENCHMARK_CASES -from inire.tests.terminal_bench_scenario import LENGTH_COST if TYPE_CHECKING: from shapely.geometry import Polygon - from inire import CapacityLimit, RoutingProblem, RoutingResult, RoutingTiming, TopologyReport + from inire import CapacityLimit, RoutingProblem, RoutingTiming, TopologyReport from inire.router._routing_policy import Trial - from inire.tests.routing_benchmarks import BenchmarkCase + from inire.tests.routing_benchmark_case import BenchmarkCase ORDER_POLICIES = ("seed-order-restart", "seed-order-initial", "seed-order-locked") BUNDLE_POLICIES = ("bundle-first", "bundle-first-refine") -AUTOMATIC_COST_MODES = {"automatic": "selective", "automatic-span": "never", "automatic-weighted": "always"} -AUTOMATIC_POLICIES = tuple(AUTOMATIC_COST_MODES) POLICIES = (*DIRECT_POLICIES, *ORDER_POLICIES, *BUNDLE_POLICIES, *AUTOMATIC_POLICIES) -PROFILES = ("matched-budget", "public-defaults") @dataclass(frozen=True, slots=True) @@ -51,6 +48,7 @@ class RunSample: duration_s: float net_outcomes: dict[str, str] valid_costs: dict[str, float] + native_valid_costs: dict[str, float] reached_net_ids: tuple[str, ...] out_of_bounds_net_ids: tuple[str, ...] nodes_expanded: int @@ -68,51 +66,14 @@ class RunSample: timings: tuple[RoutingTiming, ...] = () -def _benchmark_score(result: RoutingResult) -> float: - return sum(component.length * LENGTH_COST[component.move_type] for component in result.path) - - -_trial = partial(_summarize_trial, score=_benchmark_score) -_direct_trials = partial(_run_direct_trials, score=_benchmark_score) +_trial = partial(_summarize_trial, score=benchmark_weighted_length) +_direct_trials = partial(_run_direct_trials, score=benchmark_weighted_length) def _mode_options(options: RoutingOptions, strategy: str, profile: str = "matched-budget") -> RoutingOptions: - if strategy not in AUTOMATIC_POLICIES: - return replace(options, topology=replace(options.topology, mode="off" if strategy in POLICIES else strategy)) - - weights = options.topology.automatic_length_weights - if profile == "matched-budget": - weights = (LENGTH_COST["straight"], LENGTH_COST["bend90"], LENGTH_COST["sbend"]) - cost_policy = options.topology.automatic_cost if profile == "public-defaults" and strategy == "automatic" else AUTOMATIC_COST_MODES[strategy] - return replace( - options, - topology=replace( - options.topology, - mode="automatic", - automatic_cost=cost_policy, - automatic_length_weights=weights, - ), - ) - - -def _public_defaults(case: BenchmarkCase, defaults: RoutingOptions) -> RoutingOptions: - geometry = case.options.search - return replace( - defaults, - search=replace( - defaults.search, - bend_radii=geometry.bend_radii, - sbend_radii=geometry.sbend_radii, - sbend_offsets=geometry.sbend_offsets, - bend_collision_type=geometry.bend_collision_type, - bend_proxy_geometry=geometry.bend_proxy_geometry, - bend_physical_geometry=geometry.bend_physical_geometry, - bend_clip_margin=geometry.bend_clip_margin, - min_straight_length=geometry.min_straight_length, - max_straight_length=geometry.max_straight_length, - ), - topology=replace(defaults.topology, infer_terminal_headings=case.options.topology.infer_terminal_headings), - ) + if strategy in AUTOMATIC_POLICIES: + return automatic_options(options, profile, strategy) + return replace(options, topology=replace(options.topology, mode="off" if strategy in POLICIES else strategy)) def _order_trials(problem: RoutingProblem, board: Polygon, options: RoutingOptions, strategy: str) -> list[Trial]: @@ -164,11 +125,12 @@ def _measure(case: BenchmarkCase, options: RoutingOptions, strategy: str) -> Run report = run.automatic assert report is not None selected = report.stages[report.selected_stage] - valid_costs = {net_id: _benchmark_score(run.results_by_net[net_id]) for net_id in report.verified_net_ids} + valid_costs = {net_id: benchmark_weighted_length(run.results_by_net[net_id]) for net_id in report.verified_net_ids} return RunSample( duration_s=perf_counter() - started, net_outcomes={net_id: result.outcome for net_id, result in run.results_by_net.items()}, valid_costs=valid_costs, + native_valid_costs=native_verified_costs(case, options, run.results_by_net, report.verified_net_ids), reached_net_ids=tuple(net_id for net_id, result in run.results_by_net.items() if result.reached_target), out_of_bounds_net_ids=selected.out_of_bounds_net_ids, nodes_expanded=run.metrics.nodes_expanded, @@ -216,6 +178,7 @@ def _measure(case: BenchmarkCase, options: RoutingOptions, strategy: str) -> Run duration_s=duration, net_outcomes={net_id: result.outcome for net_id, result in run.results_by_net.items()}, valid_costs=best.valid_costs, + native_valid_costs=native_verified_costs(case, options, run.results_by_net, best.valid_costs), reached_net_ids=tuple(net_id for net_id, result in run.results_by_net.items() if result.reached_target), out_of_bounds_net_ids=best.stage.out_of_bounds_net_ids, nodes_expanded=sum(trial.stage.nodes_expanded for trial in trials), @@ -238,7 +201,11 @@ def _print_summary(mode: str, samples: list[RunSample]) -> None: flush=True, ) if run.valid_costs: - print(f" valid-net cost {sum(run.valid_costs.values()):.2f}, nets {', '.join(run.valid_costs)}", flush=True) + print( + f" benchmark-weighted length {sum(run.valid_costs.values()):.2f}, " + f"native objective cost {sum(run.native_valid_costs.values()):.2f}, nets {', '.join(run.valid_costs)}", + flush=True, + ) if run.out_of_bounds_net_ids: print(f" outside board {', '.join(run.out_of_bounds_net_ids)}", flush=True) if run.bundle_rejection is not None: @@ -294,28 +261,13 @@ def _geometry_json(value: object) -> dict: def main() -> None: - broader = (*VALIDATION_BENCHMARK_CASES, *FALLBACK_BENCHMARK_CASES, *EXTERNAL_BENCHMARK_CASES) - corpus = (*BENCHMARK_CASES, *broader, *CROSSING_BENCHMARK_CASES, *STRESS_BENCHMARK_CASES) - case_groups = {case.name: (case,) for case in corpus} - case_groups.update( - { - "all": BENCHMARK_CASES, - "complex": COMPLEX_BENCHMARK_CASES, - "holdout": VALIDATION_BENCHMARK_CASES, - "fallback": FALLBACK_BENCHMARK_CASES, - "external": EXTERNAL_BENCHMARK_CASES, - "broad": broader, - "crossings": CROSSING_BENCHMARK_CASES, - "stress": STRESS_BENCHMARK_CASES, - "corpus": corpus, - } - ) - defaults = RoutingOptions() parser = ArgumentParser(description=__doc__) - parser.add_argument("--profile", choices=PROFILES, default="matched-budget", help="Use controlled budgets or the public API defaults.") + parser.add_argument( + "--profile", choices=PROFILES, default="matched-budget", help="Use CLI budgets, API defaults, or pytest corpus settings." + ) parser.add_argument( "--case", - choices=tuple(case_groups), + choices=tuple(CASE_GROUPS), action="append", help="Select a case or suite. Use 'corpus' to select all boards.", ) @@ -331,11 +283,11 @@ def main() -> None: parser.add_argument("--iterations", type=int) parser.add_argument("--refinement", choices=("on", "off"), help="Override refinement for public routing modes.") parser.add_argument("--refinement-windows", metavar="N", help="Limit attempted windows per net, or use 'unlimited'.") - parser.add_argument("--max-corridors", type=int, default=defaults.topology.max_corridors) - parser.add_argument("--guide-strength", type=float, default=defaults.topology.guide_strength) - parser.add_argument("--seed-nodes", type=int, default=defaults.topology.seed_node_limit) + parser.add_argument("--max-corridors", type=int) + parser.add_argument("--guide-strength", type=float) + parser.add_argument("--seed-nodes", type=int) parser.add_argument("--sbend-offset", type=float, action="append", help="Override search S-bend offsets. Repeat for multiple offsets.") - parser.add_argument("--net-order", choices=("user", "shortest", "longest"), default=defaults.congestion.net_order) + parser.add_argument("--net-order", choices=("user", "shortest", "longest")) parser.add_argument("--no-warm-start", action="store_true") parser.add_argument("--repeat", type=int, default=1, help="Run each configuration this many times and report median runtime.") parser.add_argument("--json", type=Path, help="Write options and individual runs to this file.") @@ -349,16 +301,13 @@ def main() -> None: ("external", "External cases"), ("crossings", "Preplaced crossings"), ("stress", "Stress cases"), + ("retry-holdout", "Retry-policy holdouts"), ): print(f"{title} (--case {group})") - for case in case_groups[group]: + for case in CASE_GROUPS[group]: print(f" {case.name:40} {case.description}") return - use_public_defaults = args.profile == "public-defaults" - default_budget = defaults.search.node_limit if use_public_defaults else 500 - budgets = tuple(dict.fromkeys(args.nodes or (default_budget,))) - iterations = args.iterations if args.iterations is not None else (defaults.congestion.max_iterations if use_public_defaults else 2) - if min(budgets) < 1 or iterations < 1 or args.repeat < 1: + if (args.nodes and min(args.nodes) < 1) or (args.iterations is not None and args.iterations < 1) or args.repeat < 1: parser.error("--nodes, --iterations and --repeat must be positive") if args.sbend_offset is not None and not all(isfinite(offset) for offset in args.sbend_offset): parser.error("--sbend-offset must be finite") @@ -374,30 +323,34 @@ def main() -> None: if limit is not None and limit < 1: parser.error(limit_error) refinement_overrides["max_windows_per_net"] = limit - try: - topology = replace( - defaults.topology, - max_corridors=args.max_corridors, - guide_strength=args.guide_strength, - seed_node_limit=args.seed_nodes, + topology_overrides = { + name: value + for name, value in ( + ("max_corridors", args.max_corridors), + ("guide_strength", args.guide_strength), + ("seed_node_limit", args.seed_nodes), ) - except ValueError as exc: - parser.error(str(exc)) - - groups = args.case or ["terminal-bench"] - cases = {case.name: case for group in groups for case in case_groups[group]}.values() + if value is not None + } + cases = select_cases(args.case or ["terminal-bench"]) sbend_offsets = tuple(args.sbend_offset) if args.sbend_offset is not None else None records = [] requested = [*(args.mode or ()), *(args.policy or ())] - default_modes = (defaults.topology.mode,) if use_public_defaults else ("off", "guide", "seed") + default_modes = ("off", "guide", "seed") if args.profile == "matched-budget" else (RoutingOptions().topology.mode,) modes = tuple(dict.fromkeys(requested or default_modes)) for case in cases: - base = _public_defaults(case, defaults) if use_public_defaults else case.options + base = profile_options(case, args.profile) + try: + topology = replace(base.topology, **topology_overrides) + except ValueError as exc: + parser.error(str(exc)) + budgets = tuple(dict.fromkeys(args.nodes or (base.search.node_limit,))) + iterations = base.congestion.max_iterations if args.iterations is None else args.iterations for budget in budgets: print(f"{case.name} | {budget} nodes per attempt", flush=True) options = replace( base, - topology=replace(topology, infer_terminal_headings=base.topology.infer_terminal_headings), + topology=topology, search=replace( base.search, node_limit=budget, sbend_offsets=sbend_offsets if sbend_offsets is not None else base.search.sbend_offsets ), @@ -405,8 +358,8 @@ def main() -> None: congestion=replace( base.congestion, max_iterations=iterations, - net_order=args.net_order, - warm_start_enabled=not args.no_warm_start and defaults.congestion.warm_start_enabled, + net_order=args.net_order or base.congestion.net_order, + warm_start_enabled=not args.no_warm_start and base.congestion.warm_start_enabled, ), ) mode_options = {mode: _mode_options(options, mode, args.profile) for mode in modes} @@ -435,6 +388,7 @@ def main() -> None: "python": python_version(), "shapely": shapely.__version__, "geos": shapely.geos_version_string, + "cost_metrics": {"valid_costs": "benchmark_weighted_length", "native_valid_costs": "native_objective"}, "runs": records, } args.json.write_text(dumps(payload, indent=2, default=_geometry_json) + "\n") diff --git a/scripts/import_external_routing_benchmarks.py b/scripts/import_external_routing_benchmarks.py index 5fee7fb..bb8054a 100644 --- a/scripts/import_external_routing_benchmarks.py +++ b/scripts/import_external_routing_benchmarks.py @@ -103,6 +103,7 @@ def _fixture( *, die: tuple[float, float, float, float] | None = None, min_straight: float = 0.5, + expected_routed: int | None = None, ) -> dict: if not connections: raise ValueError(f"No compatible connections in {name}") @@ -150,6 +151,7 @@ def _fixture( obstacles.append(encoded) return { "name": name, + **({"expected_routed": expected_routed} if expected_routed is not None else {}), "source": source, "member": member, "crop_um": list(die), @@ -292,7 +294,8 @@ def _lidar_cases(archive: TarFile) -> list[dict]: settings = netlist["settings"] die = tuple(value for corner in settings["die_area"] for value in corner) if not selected else None name = f"lidar-{settings['design'].replace('_', '-')}" - cases.append(_fixture(name, "lidar", member, devices, connections, settings["wg_radius"], 1.0, die=die)) + expected_routed = 3 if name == "lidar-clements-8x8" else None + cases.append(_fixture(name, "lidar", member, devices, connections, settings["wg_radius"], 1.0, die=die, expected_routed=expected_routed)) return cases diff --git a/scripts/record_conflict_trace.py b/scripts/record_conflict_trace.py index 2baaf9c..a5435f9 100644 --- a/scripts/record_conflict_trace.py +++ b/scripts/record_conflict_trace.py @@ -1,82 +1,26 @@ #!/usr/bin/env python3 from __future__ import annotations -import argparse -import json from collections import Counter from dataclasses import asdict -from datetime import datetime -from pathlib import Path +from typing import TYPE_CHECKING -from inire.results import RoutingRunResult -from inire.tests.example_scenarios import TRACE_PERFORMANCE_SCENARIO_RUNS, TRACE_SCENARIO_RUNS +from inire.tests.trace_recording import NO_WARM_START_SCENARIOS, record_trace, result_summary + +if TYPE_CHECKING: + from inire.results import RoutingRunResult -def _trace_registry(include_performance_only: bool) -> tuple[tuple[str, object], ...]: - if include_performance_only: - return TRACE_SCENARIO_RUNS + TRACE_PERFORMANCE_SCENARIO_RUNS - return TRACE_SCENARIO_RUNS - - -def _selected_runs( - selected_scenarios: tuple[str, ...] | None, - *, - include_performance_only: bool, -) -> tuple[tuple[str, object], ...]: - if selected_scenarios is None: - return (("example_07_large_scale_routing_no_warm_start", dict(TRACE_PERFORMANCE_SCENARIO_RUNS)["example_07_large_scale_routing_no_warm_start"]),) - - registry = dict(TRACE_SCENARIO_RUNS + TRACE_PERFORMANCE_SCENARIO_RUNS) - allowed_standard = dict(_trace_registry(include_performance_only)) - runs = [] - for name in selected_scenarios: - if name in allowed_standard: - runs.append((name, allowed_standard[name])) - continue - if name in registry: - runs.append((name, registry[name])) - continue - valid = ", ".join(sorted(registry)) - raise SystemExit(f"Unknown trace scenario: {name}. Valid scenarios: {valid}") - return tuple(runs) - - -def _result_summary(run: RoutingRunResult) -> dict[str, object]: +def _scenario_payload(result: RoutingRunResult) -> dict[str, object]: return { - "total_results": len(run.results_by_net), - "valid_results": sum(1 for result in run.results_by_net.values() if result.is_valid), - "reached_targets": sum(1 for result in run.results_by_net.values() if result.reached_target), - "results_by_net": { - net_id: { - "outcome": result.outcome, - "reached_target": result.reached_target, - "report": asdict(result.report), - } - for net_id, result in run.results_by_net.items() + "summary": { + **result_summary(result), + "results_by_net": { + net_id: {"outcome": entry.outcome, "reached_target": entry.reached_target, "report": asdict(entry.report)} + for net_id, entry in result.results_by_net.items() + }, }, - } - - -def _build_payload( - selected_scenarios: tuple[str, ...] | None, - *, - include_performance_only: bool, -) -> dict[str, object]: - scenarios = [] - for name, run in _selected_runs(selected_scenarios, include_performance_only=include_performance_only): - result = run() - scenarios.append( - { - "name": name, - "summary": _result_summary(result), - "metrics": asdict(result.metrics), - "conflict_trace": [asdict(entry) for entry in result.conflict_trace], - } - ) - return { - "generated_at": datetime.now().astimezone().isoformat(timespec="seconds"), - "generator": "scripts/record_conflict_trace.py", - "scenarios": scenarios, + "conflict_trace": [asdict(entry) for entry in result.conflict_trace], } @@ -181,47 +125,14 @@ def _render_markdown(payload: dict[str, object]) -> str: def main() -> None: - parser = argparse.ArgumentParser(description="Record conflict-trace artifacts for selected trace scenarios.") - parser.add_argument( - "--scenario", - action="append", - dest="scenarios", - default=[], - help="Optional trace scenario name to include. May be passed more than once.", + record_trace( + __file__, + "conflict_trace", + scenario_label="trace", + default_scenarios=NO_WARM_START_SCENARIOS[:1], + scenario_payload=_scenario_payload, + render_markdown=_render_markdown, ) - parser.add_argument( - "--include-performance-only", - action="store_true", - help="Include performance-only trace scenarios when selecting from the standard registry.", - ) - parser.add_argument( - "--output-dir", - type=Path, - default=None, - help="Directory to write conflict_trace.json and conflict_trace.md into. Defaults to /docs.", - ) - args = parser.parse_args() - - repo_root = Path(__file__).resolve().parents[1] - output_dir = repo_root / "docs" if args.output_dir is None else args.output_dir.resolve() - output_dir.mkdir(exist_ok=True) - - selected = tuple(args.scenarios) if args.scenarios else None - payload = _build_payload(selected, include_performance_only=args.include_performance_only) - json_path = output_dir / "conflict_trace.json" - markdown_path = output_dir / "conflict_trace.md" - - json_path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n") - markdown_path.write_text(_render_markdown(payload) + "\n") - - if json_path.is_relative_to(repo_root): - print(f"Wrote {json_path.relative_to(repo_root)}") - else: - print(f"Wrote {json_path}") - if markdown_path.is_relative_to(repo_root): - print(f"Wrote {markdown_path.relative_to(repo_root)}") - else: - print(f"Wrote {markdown_path}") if __name__ == "__main__": diff --git a/scripts/record_frontier_trace.py b/scripts/record_frontier_trace.py index e101c90..682d91c 100644 --- a/scripts/record_frontier_trace.py +++ b/scripts/record_frontier_trace.py @@ -1,71 +1,18 @@ #!/usr/bin/env python3 from __future__ import annotations -import argparse -import json from collections import Counter from dataclasses import asdict -from datetime import datetime -from pathlib import Path +from typing import TYPE_CHECKING -from inire.tests.example_scenarios import TRACE_PERFORMANCE_SCENARIO_RUNS, TRACE_SCENARIO_RUNS +from inire.tests.trace_recording import NO_WARM_START_SCENARIOS, record_trace + +if TYPE_CHECKING: + from inire.results import RoutingRunResult -def _trace_registry(include_performance_only: bool) -> tuple[tuple[str, object], ...]: - if include_performance_only: - return TRACE_SCENARIO_RUNS + TRACE_PERFORMANCE_SCENARIO_RUNS - return TRACE_SCENARIO_RUNS - - -def _selected_runs( - selected_scenarios: tuple[str, ...] | None, - *, - include_performance_only: bool, -) -> tuple[tuple[str, object], ...]: - if selected_scenarios is None: - default_registry = dict(TRACE_PERFORMANCE_SCENARIO_RUNS) - return (("example_07_large_scale_routing_no_warm_start", default_registry["example_07_large_scale_routing_no_warm_start"]),) - - registry = dict(TRACE_SCENARIO_RUNS + TRACE_PERFORMANCE_SCENARIO_RUNS) - allowed_standard = dict(_trace_registry(include_performance_only)) - runs = [] - for name in selected_scenarios: - if name in allowed_standard: - runs.append((name, allowed_standard[name])) - continue - if name in registry: - runs.append((name, registry[name])) - continue - valid = ", ".join(sorted(registry)) - raise SystemExit(f"Unknown trace scenario: {name}. Valid scenarios: {valid}") - return tuple(runs) - - -def _build_payload( - selected_scenarios: tuple[str, ...] | None, - *, - include_performance_only: bool, -) -> dict[str, object]: - scenarios = [] - for name, run in _selected_runs(selected_scenarios, include_performance_only=include_performance_only): - result = run() - scenarios.append( - { - "name": name, - "summary": { - "total_results": len(result.results_by_net), - "valid_results": sum(1 for entry in result.results_by_net.values() if entry.is_valid), - "reached_targets": sum(1 for entry in result.results_by_net.values() if entry.reached_target), - }, - "metrics": asdict(result.metrics), - "frontier_trace": [asdict(entry) for entry in result.frontier_trace], - } - ) - return { - "generated_at": datetime.now().astimezone().isoformat(timespec="seconds"), - "generator": "scripts/record_frontier_trace.py", - "scenarios": scenarios, - } +def _scenario_payload(result: RoutingRunResult) -> dict[str, object]: + return {"frontier_trace": [asdict(entry) for entry in result.frontier_trace]} def _render_markdown(payload: dict[str, object]) -> str: @@ -158,47 +105,14 @@ def _render_markdown(payload: dict[str, object]) -> str: def main() -> None: - parser = argparse.ArgumentParser(description="Record frontier-trace artifacts for selected trace scenarios.") - parser.add_argument( - "--scenario", - action="append", - dest="scenarios", - default=[], - help="Optional trace scenario name to include. May be passed more than once.", + record_trace( + __file__, + "frontier_trace", + scenario_label="trace", + default_scenarios=NO_WARM_START_SCENARIOS[:1], + scenario_payload=_scenario_payload, + render_markdown=_render_markdown, ) - parser.add_argument( - "--include-performance-only", - action="store_true", - help="Include performance-only trace scenarios when selecting from the standard registry.", - ) - parser.add_argument( - "--output-dir", - type=Path, - default=None, - help="Directory to write frontier_trace.json and frontier_trace.md into. Defaults to /docs.", - ) - args = parser.parse_args() - - repo_root = Path(__file__).resolve().parents[1] - output_dir = repo_root / "docs" if args.output_dir is None else args.output_dir.resolve() - output_dir.mkdir(exist_ok=True) - - selected = tuple(args.scenarios) if args.scenarios else None - payload = _build_payload(selected, include_performance_only=args.include_performance_only) - json_path = output_dir / "frontier_trace.json" - markdown_path = output_dir / "frontier_trace.md" - - json_path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n") - markdown_path.write_text(_render_markdown(payload) + "\n") - - if json_path.is_relative_to(repo_root): - print(f"Wrote {json_path.relative_to(repo_root)}") - else: - print(f"Wrote {json_path}") - if markdown_path.is_relative_to(repo_root): - print(f"Wrote {markdown_path.relative_to(repo_root)}") - else: - print(f"Wrote {markdown_path}") if __name__ == "__main__": diff --git a/scripts/record_iteration_trace.py b/scripts/record_iteration_trace.py index 7691558..7bb72bb 100644 --- a/scripts/record_iteration_trace.py +++ b/scripts/record_iteration_trace.py @@ -1,80 +1,18 @@ #!/usr/bin/env python3 from __future__ import annotations -import argparse -import json from collections import Counter from dataclasses import asdict -from datetime import datetime -from pathlib import Path +from typing import TYPE_CHECKING -from inire.tests.example_scenarios import TRACE_PERFORMANCE_SCENARIO_RUNS, TRACE_SCENARIO_RUNS +from inire.tests.trace_recording import NO_WARM_START_SCENARIOS, record_trace + +if TYPE_CHECKING: + from inire.results import RoutingRunResult -def _trace_registry(include_performance_only: bool) -> tuple[tuple[str, object], ...]: - if include_performance_only: - return TRACE_SCENARIO_RUNS + TRACE_PERFORMANCE_SCENARIO_RUNS - return TRACE_SCENARIO_RUNS - - -def _selected_runs( - selected_scenarios: tuple[str, ...] | None, - *, - include_performance_only: bool, -) -> tuple[tuple[str, object], ...]: - if selected_scenarios is None: - perf_registry = dict(TRACE_PERFORMANCE_SCENARIO_RUNS) - return ( - ( - "example_07_large_scale_routing_no_warm_start", - perf_registry["example_07_large_scale_routing_no_warm_start"], - ), - ( - "example_07_large_scale_routing_no_warm_start_seed43", - perf_registry["example_07_large_scale_routing_no_warm_start_seed43"], - ), - ) - - registry = dict(TRACE_SCENARIO_RUNS + TRACE_PERFORMANCE_SCENARIO_RUNS) - allowed_standard = dict(_trace_registry(include_performance_only)) - runs = [] - for name in selected_scenarios: - if name in allowed_standard: - runs.append((name, allowed_standard[name])) - continue - if name in registry: - runs.append((name, registry[name])) - continue - valid = ", ".join(sorted(registry)) - raise SystemExit(f"Unknown iteration-trace scenario: {name}. Valid scenarios: {valid}") - return tuple(runs) - - -def _build_payload( - selected_scenarios: tuple[str, ...] | None, - *, - include_performance_only: bool, -) -> dict[str, object]: - scenarios = [] - for name, run in _selected_runs(selected_scenarios, include_performance_only=include_performance_only): - result = run() - scenarios.append( - { - "name": name, - "summary": { - "total_results": len(result.results_by_net), - "valid_results": sum(1 for entry in result.results_by_net.values() if entry.is_valid), - "reached_targets": sum(1 for entry in result.results_by_net.values() if entry.reached_target), - }, - "metrics": asdict(result.metrics), - "iteration_trace": [asdict(entry) for entry in result.iteration_trace], - } - ) - return { - "generated_at": datetime.now().astimezone().isoformat(timespec="seconds"), - "generator": "scripts/record_iteration_trace.py", - "scenarios": scenarios, - } +def _scenario_payload(result: RoutingRunResult) -> dict[str, object]: + return {"iteration_trace": [asdict(entry) for entry in result.iteration_trace]} def _render_markdown(payload: dict[str, object]) -> str: @@ -94,7 +32,8 @@ def _render_markdown(payload: dict[str, object]) -> str: f"{scenario['summary']['reached_targets']} reached / " f"{scenario['summary']['total_results']} total.", "", - "| Iteration | Penalty | Routed Nets | Completed | Conflict Edges | Dynamic Collisions | Nodes | Congestion Checks | Candidate Ids | Exact Pairs |", + "| Iteration | Penalty | Routed Nets | Completed | Conflict Edges | Dynamic Collisions | " + "Nodes | Congestion Checks | Candidate Ids | Exact Pairs |", "| --: | --: | --: | --: | --: | --: | --: | --: | --: | --: |", ] ) @@ -139,47 +78,14 @@ def _render_markdown(payload: dict[str, object]) -> str: def main() -> None: - parser = argparse.ArgumentParser(description="Record iteration-trace artifacts for selected trace scenarios.") - parser.add_argument( - "--scenario", - action="append", - dest="scenarios", - default=[], - help="Optional trace scenario name to include. May be passed more than once.", + record_trace( + __file__, + "iteration_trace", + scenario_label="iteration-trace", + default_scenarios=NO_WARM_START_SCENARIOS, + scenario_payload=_scenario_payload, + render_markdown=_render_markdown, ) - parser.add_argument( - "--include-performance-only", - action="store_true", - help="Include performance-only trace scenarios when selecting from the standard registry.", - ) - parser.add_argument( - "--output-dir", - type=Path, - default=None, - help="Directory to write iteration_trace.json and iteration_trace.md into. Defaults to /docs.", - ) - args = parser.parse_args() - - repo_root = Path(__file__).resolve().parents[1] - output_dir = repo_root / "docs" if args.output_dir is None else args.output_dir.resolve() - output_dir.mkdir(exist_ok=True) - - selected = tuple(args.scenarios) if args.scenarios else None - payload = _build_payload(selected, include_performance_only=args.include_performance_only) - json_path = output_dir / "iteration_trace.json" - markdown_path = output_dir / "iteration_trace.md" - - json_path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n") - markdown_path.write_text(_render_markdown(payload) + "\n") - - if json_path.is_relative_to(repo_root): - print(f"Wrote {json_path.relative_to(repo_root)}") - else: - print(f"Wrote {json_path}") - if markdown_path.is_relative_to(repo_root): - print(f"Wrote {markdown_path.relative_to(repo_root)}") - else: - print(f"Wrote {markdown_path}") if __name__ == "__main__": diff --git a/scripts/record_performance_baseline.py b/scripts/record_performance_baseline.py index 14944bb..d0b4062 100644 --- a/scripts/record_performance_baseline.py +++ b/scripts/record_performance_baseline.py @@ -58,7 +58,8 @@ def _render_markdown(payload: dict[str, object]) -> str: "The full machine-readable snapshot lives in `docs/performance_baseline.json`.", "Use `scripts/diff_performance_baseline.py` to compare a fresh run against that snapshot.", "", - "| Scenario | Duration (s) | Total | Valid | Reached | Iter | Nets Routed | Nodes | Ray Casts | Moves Gen | Moves Added | Dyn Tree | Visibility Builds | Congestion Checks | Verify Calls |", + "| Scenario | Duration (s) | Total | Valid | Reached | Iter | Nets Routed | Nodes | Ray Casts | " + "Moves Gen | Moves Added | Dyn Tree | Visibility Builds | Congestion Checks | Verify Calls |", "| :-- | --: | --: | --: | --: | --: | --: | --: | --: | --: | --: | --: | --: | --: | --: |", ] for row in rows: @@ -87,7 +88,8 @@ def _render_markdown(payload: dict[str, object]) -> str: "", "## Full Counter Set", "", - "Each scenario entry in `docs/performance_baseline.json` records the full `RouteMetrics` snapshot, including cache, index, congestion, and verification counters.", + "Each scenario entry in `docs/performance_baseline.json` records the full `RouteMetrics` snapshot, " + "including cache, index, congestion, and verification counters.", "These counters are currently observational only and are not enforced as CI regression gates.", "", "Tracked metric keys:", diff --git a/scripts/record_pre_pair_frontier_trace.py b/scripts/record_pre_pair_frontier_trace.py index 398fc0d..a5486dd 100644 --- a/scripts/record_pre_pair_frontier_trace.py +++ b/scripts/record_pre_pair_frontier_trace.py @@ -1,82 +1,19 @@ #!/usr/bin/env python3 from __future__ import annotations -import argparse -import json from collections import Counter from dataclasses import asdict -from datetime import datetime -from pathlib import Path +from typing import TYPE_CHECKING -from inire.tests.example_scenarios import TRACE_PERFORMANCE_SCENARIO_RUNS, TRACE_SCENARIO_RUNS +from inire.tests.trace_recording import NO_WARM_START_SCENARIOS, record_trace + +if TYPE_CHECKING: + from inire.results import RoutingRunResult -def _trace_registry(include_performance_only: bool) -> tuple[tuple[str, object], ...]: - if include_performance_only: - return TRACE_SCENARIO_RUNS + TRACE_PERFORMANCE_SCENARIO_RUNS - return TRACE_SCENARIO_RUNS - - -def _selected_runs( - selected_scenarios: tuple[str, ...] | None, - *, - include_performance_only: bool, -) -> tuple[tuple[str, object], ...]: - if selected_scenarios is None: - perf_registry = dict(TRACE_PERFORMANCE_SCENARIO_RUNS) - return ( - ( - "example_07_large_scale_routing_no_warm_start", - perf_registry["example_07_large_scale_routing_no_warm_start"], - ), - ( - "example_07_large_scale_routing_no_warm_start_seed43", - perf_registry["example_07_large_scale_routing_no_warm_start_seed43"], - ), - ) - - registry = dict(TRACE_SCENARIO_RUNS + TRACE_PERFORMANCE_SCENARIO_RUNS) - allowed_standard = dict(_trace_registry(include_performance_only)) - runs = [] - for name in selected_scenarios: - if name in allowed_standard: - runs.append((name, allowed_standard[name])) - continue - if name in registry: - runs.append((name, registry[name])) - continue - valid = ", ".join(sorted(registry)) - raise SystemExit(f"Unknown pre-pair frontier-trace scenario: {name}. Valid scenarios: {valid}") - return tuple(runs) - - -def _build_payload( - selected_scenarios: tuple[str, ...] | None, - *, - include_performance_only: bool, -) -> dict[str, object]: - scenarios = [] - for name, run in _selected_runs(selected_scenarios, include_performance_only=include_performance_only): - result = run() - scenarios.append( - { - "name": name, - "summary": { - "total_results": len(result.results_by_net), - "valid_results": sum(1 for entry in result.results_by_net.values() if entry.is_valid), - "reached_targets": sum(1 for entry in result.results_by_net.values() if entry.reached_target), - }, - "metrics": asdict(result.metrics), - "pre_pair_frontier_trace": None - if result.pre_pair_frontier_trace is None - else asdict(result.pre_pair_frontier_trace), - } - ) - return { - "generated_at": datetime.now().astimezone().isoformat(timespec="seconds"), - "generator": "scripts/record_pre_pair_frontier_trace.py", - "scenarios": scenarios, - } +def _scenario_payload(result: RoutingRunResult) -> dict[str, object]: + trace = result.pre_pair_frontier_trace + return {"pre_pair_frontier_trace": asdict(trace) if trace is not None else None} def _render_markdown(payload: dict[str, object]) -> str: @@ -144,47 +81,14 @@ def _render_markdown(payload: dict[str, object]) -> str: def main() -> None: - parser = argparse.ArgumentParser(description="Record pre-pair frontier-trace artifacts for selected trace scenarios.") - parser.add_argument( - "--scenario", - action="append", - dest="scenarios", - default=[], - help="Optional trace scenario name to include. May be passed more than once.", + record_trace( + __file__, + "pre_pair_frontier_trace", + scenario_label="pre-pair frontier-trace", + default_scenarios=NO_WARM_START_SCENARIOS, + scenario_payload=_scenario_payload, + render_markdown=_render_markdown, ) - parser.add_argument( - "--include-performance-only", - action="store_true", - help="Include performance-only trace scenarios when selecting from the standard registry.", - ) - parser.add_argument( - "--output-dir", - type=Path, - default=None, - help="Directory to write pre_pair_frontier_trace.json and .md into. Defaults to /docs.", - ) - args = parser.parse_args() - - repo_root = Path(__file__).resolve().parents[1] - output_dir = repo_root / "docs" if args.output_dir is None else args.output_dir.resolve() - output_dir.mkdir(exist_ok=True) - - selected = tuple(args.scenarios) if args.scenarios else None - payload = _build_payload(selected, include_performance_only=args.include_performance_only) - json_path = output_dir / "pre_pair_frontier_trace.json" - markdown_path = output_dir / "pre_pair_frontier_trace.md" - - json_path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n") - markdown_path.write_text(_render_markdown(payload) + "\n") - - if json_path.is_relative_to(repo_root): - print(f"Wrote {json_path.relative_to(repo_root)}") - else: - print(f"Wrote {json_path}") - if markdown_path.is_relative_to(repo_root): - print(f"Wrote {markdown_path.relative_to(repo_root)}") - else: - print(f"Wrote {markdown_path}") if __name__ == "__main__": diff --git a/scripts/route_terminal_bench.py b/scripts/route_terminal_bench.py index 638848a..b10f182 100644 --- a/scripts/route_terminal_bench.py +++ b/scripts/route_terminal_bench.py @@ -10,6 +10,7 @@ from shapely.geometry import box from inire import TopologyOptions, route from inire.router._waypoints import export_waypoints +from inire.router.cost import weighted_path_length from inire.tests.terminal_bench_scenario import LENGTH_COST, terminal_bench_options, terminal_bench_problem @@ -39,9 +40,9 @@ def main() -> None: if not result.is_valid or any(not board.covers(shape) for shape in result.locked_geometry): parser.exit(1, f"Lane plan failed inire verification for {net_id}\n") - cost = sum(component.length * LENGTH_COST[component.move_type] for result in run.results_by_net.values() for component in result.path) + cost = weighted_path_length((component for result in run.results_by_net.values() for component in result.path), LENGTH_COST) total = len(problem.nets) - print(f"{total}/{total} verified, weighted cost {cost:.2f}, {run.metrics.nodes_expanded} A* expansions, {elapsed:.3f} s") + print(f"{total}/{total} verified, benchmark-weighted length {cost:.2f}, {run.metrics.nodes_expanded} A* expansions, {elapsed:.3f} s") if args.output is not None: waypoints = {net_id: export_waypoints(result.path) for net_id, result in run.results_by_net.items()} args.output.write_text(dumps({"nets": {net_id: {"waypoints": path} for net_id, path in waypoints.items()}}, indent=2) + "\n") diff --git a/scripts/routing_benchmark_parity.py b/scripts/routing_benchmark_parity.py new file mode 100644 index 0000000..2f2a8fc --- /dev/null +++ b/scripts/routing_benchmark_parity.py @@ -0,0 +1,192 @@ +"""Capture and compare exact automatic-routing benchmark results.""" + +from __future__ import annotations + +from argparse import ArgumentParser +from concurrent.futures import ProcessPoolExecutor +from dataclasses import asdict, replace +from json import dumps, loads +from pathlib import Path +from time import perf_counter +from typing import TYPE_CHECKING + +from inire import DiagnosticsOptions, route +from inire.results import RouteMetrics +from inire.tests.routing_corpus import ( + CASE_GROUPS, + PROFILES, + automatic_options, + benchmark_weighted_length, + native_verified_costs, + profile_options, + select_cases, +) +from scripts.compare_topological_routing import _geometry_json + +if TYPE_CHECKING: + from inire import RoutingResult + + +SCHEMA_VERSION = 1 +STABLE_COUNTERS = tuple(name for name in RouteMetrics.__dataclass_fields__ if not name.endswith("_ns")) + + +def _paths(results: dict[str, RoutingResult]) -> dict: + return { + "net_order": list(results), + "nets": { + net_id: { + "outcome": result.outcome, + "reached_target": result.reached_target, + "seed": [{"kind": type(move).__name__, **asdict(move)} for move in result.as_seed().segments], + "report": asdict(result.report), + } + for net_id, result in results.items() + }, + } + + +def _capture(job: tuple[str, str, bool, bool]) -> dict: + name, profile, with_callback, with_diagnostics = job + (case,) = CASE_GROUPS[name] + options = automatic_options(profile_options(case, profile), profile) + if with_diagnostics: + options = replace( + options, + diagnostics=DiagnosticsOptions( + capture_conflict_trace=True, + capture_iteration_trace=True, + capture_frontier_trace=True, + capture_pre_pair_frontier_trace=True, + ), + ) + callbacks = [] + + def notify(index: int, results: dict[str, RoutingResult]) -> None: + callbacks.append({"index": index, **_paths(results)}) + + started = perf_counter() + run = route(case.problem, options=options, iteration_callback=notify if with_callback else None) + elapsed = perf_counter() - started + report = run.automatic + assert report is not None + native_costs = native_verified_costs(case, options, run.results_by_net, report.verified_net_ids) + costs = { + net_id: {"native": cost, "benchmark_weighted_length": benchmark_weighted_length(run.results_by_net[net_id])} + for net_id, cost in native_costs.items() + } + return { + "case": name, + "profile": profile, + "with_callback": with_callback, + "with_diagnostics": with_diagnostics, + "elapsed_s": elapsed, + "stable": { + "options": asdict(options), + **_paths(run.results_by_net), + "costs": costs, + "verified_net_ids": report.verified_net_ids, + "automatic": asdict(replace(report, duration_s=0.0, timings=())), + "timing_labels": [(item.operation, item.planner, item.mode, item.policy) for item in report.timings], + "metrics": {field: getattr(run.metrics, field) for field in STABLE_COUNTERS}, + "topology": asdict(run.topology) if run.topology is not None else None, + "conflict_trace": [asdict(item) for item in run.conflict_trace], + "frontier_trace": [asdict(item) for item in run.frontier_trace], + "pre_pair_frontier_trace": asdict(run.pre_pair_frontier_trace) if run.pre_pair_frontier_trace is not None else None, + "iteration_trace": [asdict(item) for item in run.iteration_trace], + "callbacks": callbacks, + }, + } + + +def _first_difference(expected: object, actual: object, field: str = "") -> str | None: + if expected == actual: + return None + if isinstance(expected, dict) and isinstance(actual, dict): + for key in dict.fromkeys((*expected, *actual)): + path = f"{field}.{key}" if field else str(key) + if key not in expected or key not in actual: + return f"{path} exists on only one side" + difference = _first_difference(expected[key], actual[key], path) + if difference is not None: + return difference + if isinstance(expected, list) and isinstance(actual, list): + for index, (left, right) in enumerate(zip(expected, actual, strict=False)): + difference = _first_difference(left, right, f"{field}[{index}]") + if difference is not None: + return difference + return f"{field} length is {len(expected)} before and {len(actual)} after" + return f"{field} is {expected!r} before and {actual!r} after" + + +def _read(path: Path) -> dict: + payload = loads(path.read_text(encoding="utf-8")) + if payload["schema_version"] != SCHEMA_VERSION: + raise ValueError(f"Unsupported parity schema in {path}") + rows = payload["runs"] + by_key = {(row["case"], row["profile"], row["with_callback"], row["with_diagnostics"]): row for row in rows} + if len(by_key) != len(rows): + raise ValueError(f"Duplicate parity run in {path}") + return by_key + + +def _compare(before: Path, after: Path, allowed_counters: list[str]) -> int: + baseline, current = _read(before), _read(after) + for key in sorted(baseline.keys() | current.keys()): + label = f"{key[0]} / {key[1]} (callback={key[2]}, diagnostics={key[3]})" + if key not in baseline or key not in current: + print(f"{label}: run exists on only one side") + return 1 + expected, actual = baseline[key]["stable"], current[key]["stable"] + for counter in allowed_counters: + old, new = expected["metrics"].pop(counter), actual["metrics"].pop(counter) + if old != new: + print(f"{label}: allowed counter change {counter} from {old} to {new}") + difference = _first_difference(expected, actual) + if difference is not None: + print(f"{label}: {difference}") + return 1 + print(f"{len(current)} runs match.") + baseline_elapsed = sum(row["elapsed_s"] for row in baseline.values()) + current_elapsed = sum(row["elapsed_s"] for row in current.values()) + print(f"Sum of measured routing times: {baseline_elapsed:.3f}s before and {current_elapsed:.3f}s after.") + return 0 + + +def main() -> int: + parser = ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + capture = commands.add_parser("capture") + capture.add_argument("output", type=Path) + capture.add_argument("--case", choices=tuple(CASE_GROUPS), action="append") + capture.add_argument("--profile", choices=PROFILES, action="append") + capture.add_argument("--callbacks", action="store_true", help="Also capture routing with an iteration callback.") + capture.add_argument("--diagnostics", action="store_true", help="Enable conflict, frontier, and iteration traces.") + capture.add_argument("--jobs", type=int, default=1) + compare = commands.add_parser("compare") + compare.add_argument("before", type=Path) + compare.add_argument("after", type=Path) + compare.add_argument("--allow-counter-change", choices=STABLE_COUNTERS, action="append", default=[]) + args = parser.parse_args() + if args.command == "compare": + return _compare(args.before, args.after, list(dict.fromkeys(args.allow_counter_change))) + + if args.jobs < 1: + parser.error("--jobs must be positive") + cases = select_cases(args.case or ("corpus",)) + profiles = dict.fromkeys(args.profile or ("corpus-regression", "public-defaults")) + callback_modes = (False, True) if args.callbacks else (False,) + jobs = [(case.name, profile, callback, args.diagnostics) for case in cases for profile in profiles for callback in callback_modes] + if args.jobs == 1: + rows = list(map(_capture, jobs)) + else: + with ProcessPoolExecutor(max_workers=args.jobs) as pool: + rows = list(pool.map(_capture, jobs)) + payload = {"schema_version": SCHEMA_VERSION, "runs": rows} + args.output.write_text(dumps(payload, indent=2, default=_geometry_json) + "\n", encoding="utf-8") + print(f"Captured {len(rows)} runs in {args.output}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main())