Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
| db685794e5 | |||
| 13594632d4 | |||
| 0183a91e9c | |||
| ee41dc600a | |||
| 7616b398e9 |
38 changed files with 7492 additions and 144 deletions
|
|
@ -40,4 +40,138 @@ For a mode comparison, use the same problem and options in each call to `route()
|
||||||
|
|
||||||
1. **Coverage and bounds.** Check which nets verified and whether their count reached the expected bound. The tests also verify known reference routes where available.
|
1. **Coverage and bounds.** Check which nets verified and whether their count reached the expected bound. The tests also verify known reference routes where available.
|
||||||
2. **Cost on matching net sets.** Benchmark-weighted length weights physical straights, 90-degree bends, and S-bends by 1, 4, and 13. Native objective cost uses the run's configured objective.
|
2. **Cost on matching net sets.** Benchmark-weighted length weights physical straights, 90-degree bends, and S-bends by 1, 4, and 13. Native objective cost uses the run's configured objective.
|
||||||
3. **Search and time.** Compare expansions and repeated wall times at the same settings. Constructive stages can spend time planning and verifying even with zero expansions. Inspect the [automatic reports](routing-diagnostics.md#automatic-reports) to find which stage performed the work.
|
3. **Time and cost.** On identical verified net sets, compare median routing time × total cost². The legacy capture uses benchmark-weighted length and the catalog benchmark uses catalog cost. Compare expansion counts and inspect the [automatic reports](routing-diagnostics.md#automatic-reports) when the score changes. Constructive stages can spend time planning and verifying even with zero expansions.
|
||||||
|
|
||||||
|
## Capture legacy parity
|
||||||
|
|
||||||
|
Run `PYTHONPATH=. python scripts/capture_legacy_routing.py /tmp/inire-parity.json --repeat 3` from the checkout under test. Compare against revision `3b3d1c7` to measure the change to the move evaluator. To capture a Git archive, run the same script by absolute path from the extracted source tree and pass `--revision 3b3d1c7`. The capture records the effective ports, ordered moves, lengths, physical polygons, work counters, options, dependencies, and elapsed time. Use the same dependencies and compare route and work fields independently of elapsed time. The comparison covered 154 cases and modes with three repetitions per checkout and used Python 3.13.18, GEOS 3.13.1, NumPy 2.4.2, SciPy 1.17.1, Shapely 2.1.2, and Rtree 1.4.1. All recorded outcomes, routes, polygons, and deterministic work counters agreed. The sum of the per-case median times was 21.87 s at the reference revision and 21.88 s with the evaluation boundary.
|
||||||
|
|
||||||
|
### Weighted column routing
|
||||||
|
|
||||||
|
Under the corpus weights, verified quarter-turn layouts reduced weighted length by 70–75% on five ordered column fixtures. Across eleven interleaved runs per fixture, time × cost² fell by 64–94%. The largest time increase was on `complex-column-6x3`, from 52 ms to 298 ms. Its weighted length fell from 64,043 to 16,052. A three-repeat comparison across 152 automatic cases verified the same 2,245 net IDs. The other 147 cases retained identical routes and polygons.
|
||||||
|
|
||||||
|
For dense fields, the quarter-turn planner intersects apertures across neighboring columns when the gap cannot fit a jog. The S-bend planner only considers unchanged track rows in windows too short for an S-bend and reuses aperture profiles and bend-spacing measurements. Compared with the previous planner in eleven interleaved runs, `scale-field-16x16` fell from 183 to 153 ms and from 3,319 to 2,678 weighted length, lowering time × cost² by 46%. Physical length rose from 1,983 to 2,112 µm. The same score fell by 53% on `holdout-uneven-bypass` and 14% on `bypass-mixed-width`, with identical routes and costs on both.
|
||||||
|
|
||||||
|
After verifying a weighted S-bend column layout, the planner checks whether a straight can replace an excursion that returns to the same track. Indexed geometry rejects blocked shortcuts before replay. The replacement keeps both endpoint poses and must satisfy the board, keepout, peer-route, and self-clearance checks. Across the 152 automatic cases, this shortened routes on four boards and retained the same 2,245 verified net IDs. In eleven interleaved runs per case, time × cost² fell by 36% on `bypass-opposed-banks`, 19% on `bypass-three-branches`, 18% on `holdout-uneven-bypass`, and 3% on `bypass-long-dividers`.
|
||||||
|
|
||||||
|
### Terminal detours and refinement
|
||||||
|
|
||||||
|
The weighted native planner can compare a four-turn detour with a verified S-bend route between aligned ports. On `precision-forward-large-radius` the winning route uses four quarter turns at the configured radius. Weighted length fell from 4,290 to 2,513 and physical length rose from 433 to 628 µm. In eleven interleaved runs, median time rose from 49 to 56 ms and time × cost² fell by 61%.
|
||||||
|
|
||||||
|
Native refinement checks the center straight of a proposed dogleg before placing its bends. In the same comparison, `complex-column-6x3` took 59% less time and `stress-refine-alternating-doglegs` took 72% less time. Both kept the same verified geometry and cost. Across the 152 automatic cases, the same 2,245 net IDs verified, and `precision-forward-large-radius` was the sole geometry change.
|
||||||
|
|
||||||
|
When disjoint terminal conflicts set the coverage limit, automatic routing can try short terminal links and jogs, checking each route against the occupied board. If a seeded replay reaches the certified limit, the planner can skip the detailed search. On `lidar-clements-8x8`, nine interleaved runs reduced the median from 772 ms to 8 ms. Both versions verified the same three routes at the same weighted cost.
|
||||||
|
|
||||||
|
## Catalog scale benchmarks
|
||||||
|
|
||||||
|
The default `floorplan` case represents a synthetic single-layer photonic layout on a 5 × 5 mm die at 100 nm pitch. It uses 40 nets across seven port banks, with mixed approach directions, staggered fan-outs, and a short local connection. The 60 keepouts cover 11.0% of the die and represent clustered device and pad banks, larger electronics and thermal regions, and stepped block boundaries. Six reference routes pass through an 82 µm gap between two blocks. A separate keepout forces one aligned eastbound connection to detour. The frozen reference paths range from 0.33 to 2.52 mm. Each is verified against the board, keepouts, and the other reference paths before timing unseeded search. [Floorplan coordinates](../scripts/catalog_floorplan.py)
|
||||||
|
|
||||||
|
```sh
|
||||||
|
PYTHONPATH=. python scripts/benchmark_catalog_routing.py --case floorplan --mode native --no-refinement
|
||||||
|
PYTHONPATH=. python scripts/benchmark_catalog_routing.py --case floorplan --mode manhattan --no-refinement
|
||||||
|
PYTHONPATH=. python scripts/benchmark_catalog_routing.py --case floorplan --mode typed --no-refinement
|
||||||
|
PYTHONPATH=. python scripts/benchmark_catalog_routing.py --case floorplan --mode octagonal --no-refinement
|
||||||
|
```
|
||||||
|
|
||||||
|
Native uses the Manhattan API. Catalog Manhattan uses the catalog evaluator with a single profile and cardinal turns. Typed adds the centered transition. Octagonal also admits 45° bends. All four modes receive the same floorplan and terminal pairs, with no supplied routes.
|
||||||
|
|
||||||
|
The floorplan defaults to `--net-order bank`, which groups nets by their terminal headings and routes the outside of a lateral fan-out first. Use `--net-order input` to route in fixture order. The native warm start defaults to `--native-jog-limit 48`. It verifies straight and single-turn links and samples two-turn jogs and four-turn detours around keepouts and peer routes. [Native search options](user/api-reference.md#searchoptions)
|
||||||
|
|
||||||
|
The catalog modes default to `--constructive` on this fixture. They verify straight, single-turn, two-turn, and four-turn candidates before falling back to detailed search. Four-turn candidates can bypass a blocker locally and return to the terminal row. After placing the routes, the router tries cheaper collinear profile changes, including changes on clear sections of a partially blocked straight. Every replacement must pass full path verification, meet the original terminal poses, and fit within the original physical length. With refinement enabled, the router also compares local replacements and can try another net order if coverage is incomplete. Use `--no-constructive` to run the detailed catalog strategy.
|
||||||
|
|
||||||
|
For aligned ports, detailed search can finish once a verified straight with profile changes meets the cost bound. The bound includes the cost of entering and leaving lower-cost profiles. When a profile-restricted fallback finds a route, the router also tries cheaper compatible straights on its existing spans.
|
||||||
|
|
||||||
|
Use `aligned` to isolate long-range profile changes and `constrained` to reproduce the rectangular obstacle grid with a single blocked lane. The `diagonal-savings` case keeps cardinal terminals and gives the octagonal search a shorter two-turn path. The `diagonal` case has a native diagonal terminal pair.
|
||||||
|
|
||||||
|
Use `--guide-pitch 1000` and `--guide-pitch 10000` to compare coarse guidance against explicit routing. The off-coarse case exercises a displaced transition at 1 nm layout precision. On the same case `--auto-pitch 1000` selects 200 nm and verifies the same terminal poses. For a bounded failure control, use `--node-limit 0`. Use `--geometry` to retain the ordered moves and physical polygons with each report.
|
||||||
|
|
||||||
|
The report includes repeated wall times, peak resident memory from the operating system, per-net cost and physical length, and `time_cost_squared`. Compare costs on the intersection of the completed net sets. Catalog reports also include work from discarded search attempts and budgeted retries.
|
||||||
|
|
||||||
|
### Photonic floorplan measurements
|
||||||
|
|
||||||
|
The table gives medians of 15 unseeded runs per setting on an AMD Ryzen 9 5900X with a 1,000-node detailed-search limit. The before and after runs alternated on one core. Routing time includes final verification. All four modes verified all 40 nets, including the six in the shared passage, with both refinement settings.
|
||||||
|
|
||||||
|
| Mode | Median without refinement | Median with refinement | Slowest run across both settings | Catalog cost |
|
||||||
|
| --- | ---: | ---: | ---: | ---: |
|
||||||
|
| Native Manhattan | 0.291 s | 0.289 s | 0.427 s | 8.0379 |
|
||||||
|
| Single-profile catalog Manhattan | 0.188 s | 0.210 s | 0.223 s | 8.0379 |
|
||||||
|
| Typed Manhattan | 0.179 s | 0.191 s | 0.271 s | 6.2756 |
|
||||||
|
| Octagonal | 0.123 s | 0.152 s | 0.162 s | 6.2720 |
|
||||||
|
|
||||||
|
The four-turn candidates resolve the blocked straight without expanding detailed search nodes on this floorplan in the catalog modes. Constructive trials reuse placed moves and check for collisions before measuring port faces.
|
||||||
|
|
||||||
|
The local east-output bypass reduced catalog cost by 1.8% in typed and octagonal modes. One route now uses cheaper straights before and after its bypass. Its neighbor uses the cheaper profile on both sides of the detour and the original profile alongside it. Every net kept its physical length, and the minimum clearances held. With refinement enabled, time × cost² fell by 33% in catalog Manhattan, 32% in typed Manhattan, and 5% in octagonal mode.
|
||||||
|
|
||||||
|
Fresh Python invocations with refinement enabled and `--repeat 1` took 0.98–1.12 s across the four modes. Those times include startup, reference verification, and JSON output.
|
||||||
|
|
||||||
|
### Controlled obstacle-grid measurements
|
||||||
|
|
||||||
|
The following constrained-case runs used an AMD Ryzen 9 5900X and a 1000-node detailed-search limit. Times are medians of three runs. The catalog Manhattan and typed configurations completed all 40 requests. Native Manhattan verified 39 within the same node limit.
|
||||||
|
|
||||||
|
| Configuration | Verified | Time | Catalog cost |
|
||||||
|
| --- | ---: | ---: | ---: |
|
||||||
|
| Native Manhattan, refinement disabled | 39 | 2.00 s | 17.9400 |
|
||||||
|
| Catalog Manhattan, refinement disabled | 40 | 0.25 s | 18.4426 |
|
||||||
|
| Typed Manhattan, refinement disabled | 40 | 1.29 s | 10.2136 |
|
||||||
|
| Typed Manhattan, refinement enabled | 40 | 0.99 s | 10.0140 |
|
||||||
|
| Octagonal, refinement disabled | 40 | 1.20 s | 10.2136 |
|
||||||
|
| Octagonal, refinement enabled | 40 | 1.52 s | 10.2136 |
|
||||||
|
|
||||||
|
On the 39 routes verified by native Manhattan, the unrefined typed and octagonal runs each cost 9.711. Deferring geometry until a proposal reaches the front of the queue, caching straight-span projections, and indexing the obstacles in final verification reduced the unrefined octagonal median from 6.40 s at `7616b39` to 1.20 s and the number of exact geometry checks in search from 19,123 to 2,483. All 40 routes kept their verified net IDs, physical lengths, and costs.
|
||||||
|
|
||||||
|
In nine interleaved runs of the current detailed strategy, the `aligned` typed case went from 139 to 65 ms with the same cost. On `constrained`, upgrading the fallback route's straight reduced that route's cost from 0.50260 to 0.30295. All 40 routes verified. Without refinement, time × cost² fell by 13% in typed Manhattan and 11% in octagonal mode. With refinement, the score fell by 6% and 32%, respectively.
|
||||||
|
|
||||||
|
The 40-net diagonal-savings case took 0.77 s in octagonal mode with refinement disabled. The planted route used 481.982 µm at a cost of 0.06663, compared with the cardinal reference's 591.416 µm and 0.076. The 40-net case with a native diagonal terminal pair took 0.24 s under the same settings.
|
||||||
|
|
||||||
|
At `7616b39`, typed Manhattan without refinement took 2.47 s with 1 µm guidance and 2.02 s with 10 µm guidance. At each pitch, 39 fine routes verified inside their first corridor and one completed after the explicit retry.
|
||||||
|
|
||||||
|
The `corpus-open-lanes` and `corpus-lanes` cases reuse twelve lanes from the existing scale banks. The open lanes all switched profiles and reduced the total catalog cost from 0.648 to 0.552. With the corpus keepouts present, all twelve routed and the total stayed at 0.648 because the wider guide would violate clearance.
|
||||||
|
|
||||||
|
The constrained run with a zero-node budget verified and completed zero routes and reported `node_limit` for all 40. On the constrained board, native Manhattan used 116 MiB peak resident memory, unrefined octagonal used 102 MiB, and refined typed Manhattan used 91 MiB.
|
||||||
|
|
||||||
|
## Delay and independent-net retry
|
||||||
|
|
||||||
|
```sh
|
||||||
|
PYTHONPATH=. python scripts/benchmark_catalog_routing.py --case tuning --no-refinement
|
||||||
|
PYTHONPATH=. python scripts/benchmark_catalog_routing.py --case retry --no-refinement
|
||||||
|
PYTHONPATH=. python scripts/benchmark_catalog_routing.py --case retry --no-refinement --no-independent-retry
|
||||||
|
```
|
||||||
|
|
||||||
|
The tuning case measures a four-turn detour inside a caller-supplied window. The retry case shows whether the released reservation lets an independent net complete. Compare the verified and completed sets, group skew, straight spans intersecting active tuning windows, checked replacements, and time spent tuning or retrying.
|
||||||
|
|
||||||
|
For constant timing models, a verified choice can eliminate a later candidate at the exact same adjusted delay when it also costs the same or less. In seven interleaved octagonal runs without refinement, this reduced the tuning median from 2.26 s to 1.02 s. Both runs considered 1,334 proposals and selected identical routes at zero residual skew and the same catalog cost. Verified replacements fell from 524 to 136. The released-reservation case completed one independent route with retry and zero with retry disabled.
|
||||||
|
|
||||||
|
## Routing cost holdouts
|
||||||
|
|
||||||
|
```sh
|
||||||
|
PYTHONPATH=. python scripts/benchmark_catalog_routing.py --case peer-cost-holdout --mode typed --repeat 30
|
||||||
|
PYTHONPATH=. python scripts/benchmark_catalog_routing.py --case matched-cost-holdout --mode typed --repeat 30
|
||||||
|
```
|
||||||
|
|
||||||
|
Both cases put a bypass beside a straight lane where the two routes compete for clearance. The matched case adds a reference lane. Each includes two authored reference layouts, which are verified before routing is timed. The benchmark starts from the ports and keepouts and reports the reference costs alongside its own result. The references for the matched case must both satisfy the zero-skew constraint.
|
||||||
|
|
||||||
|
In 30 interleaved runs per mode against `1359463`, the router completed every net on both holdouts. The matched result kept zero skew.
|
||||||
|
|
||||||
|
| Case | Prior cost | New cost | Cheaper reference | Change in time × cost² |
|
||||||
|
| --- | ---: | ---: | ---: | ---: |
|
||||||
|
| Competing profiles | 0.9560 | 0.5477 | 0.5480 | −34% in both modes |
|
||||||
|
| Matched competing profiles | 1.4160 | 0.7967 | 0.7970 | −23% typed, −24% octagonal |
|
||||||
|
|
||||||
|
After a complete layout verifies, catalog refinement can try a cheaper straight profile that displaces one independent peer. It ranks straight spans by potential savings, checks at most four spans, and can reroute at most two peers in separate trials. It accepts a trial only if it lowers the joint cost, verifies the entire layout, and keeps any affected match group within tolerance.
|
||||||
|
|
||||||
|
Native automatic routing with explicit length weights ranks windows containing S-bends by the difference between their verified cost and a geometric lower bound. It budgets up to one eighth of the preceding search expansions for this pass and caps it at 12 windows. It accepts only cheaper, verified splices into the incumbent.
|
||||||
|
|
||||||
|
In five interleaved native runs, the six-net splitter dropped from 39,963.88 to 36,661.15 in weighted cost and improved its time × cost² score by 15%. The single-net north-launch case kept its route and took about 5% longer.
|
||||||
|
|
||||||
|
## Catalog acceptance checks
|
||||||
|
|
||||||
|
Run the catalog fixtures with Masque 4.0a3 importable to include layout placement and terminal checks.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python -m pytest -q inire/tests/test_catalog_*.py
|
||||||
|
```
|
||||||
|
|
||||||
|
- The [device set](../inire/tests/catalog_device_set.py) records the three profiles, authored transitions, generated bend settings, and fixed delays. [Device checks](../inire/tests/test_catalog_device_set.py)
|
||||||
|
- The [move and placement checks](../inire/tests/test_catalog_moves.py) cover exact lattice membership, grid-compatible leads, profile transitions, attachments, replay, physical placement, and partial placement.
|
||||||
|
- The [small search oracles](../inire/tests/test_catalog_search_oracle.py) enumerate complete histories and compare them with production proposal and pruning rules.
|
||||||
|
- The [timing checks](../inire/tests/test_catalog_timing_cases.py) cover direction-aware and wavelength-aware delay, matching budgets, window containment, and final verification of the chosen layout.
|
||||||
|
|
|
||||||
|
|
@ -231,7 +231,7 @@ After defining the Masque interface, construct the synthetic cells and record th
|
||||||
|
|
||||||
### Synthetic scale benchmark
|
### Synthetic scale benchmark
|
||||||
|
|
||||||
- Use a 5 × 5 mm board at 100 nm pitch, approximately 40 nets, and 50–100 obstacles with a union covering approximately 10% of the routing area. One reproducible starting layout uses 72 rectangles of `250 × 140` µm, with lower-left corners at `(400 + 500i, 400 + 550j)` µm for `0 ≤ i < 9` and `0 ≤ j < 8`. The disjoint rectangles cover `2.52 mm²`, or `10.08%` of the board. Stagger or reshape selected obstacles while preserving the overall density to exercise constrained passages as well as open lanes.
|
- Use a 5 × 5 mm board at 100 nm pitch, approximately 40 nets, and 50–100 obstacles with a union covering approximately 10% of the routing area. The primary floorplan fixture uses seven port banks, a six-net shared passage, and 60 clustered keepouts that cover 11.0% of the board. The original grid of 72 rectangular keepouts remains available for controlled comparisons. [Catalog scale benchmarks](benchmarks.md#catalog-scale-benchmarks)
|
||||||
- Freeze 40 terminal pairs and independently verified reference paths. Include some direct lanes, obstacle detours, shared passages, and routes with a demonstrably cheaper legal typed or diagonal alternative. Start with terminals and catalog compatibility that permit a legacy Manhattan comparison on the same requested connections. Use a separate board variant or subset for terminals and profile changes that require the new capabilities. Keep the reference paths out of unseeded search runs. Record whether the router finds the planted improvements, plus the physical length and catalog cost on equal verified net sets. Look for additional examples of those improvements in the existing corpus.
|
- Freeze 40 terminal pairs and independently verified reference paths. Include some direct lanes, obstacle detours, shared passages, and routes with a demonstrably cheaper legal typed or diagonal alternative. Start with terminals and catalog compatibility that permit a legacy Manhattan comparison on the same requested connections. Use a separate board variant or subset for terminals and profile changes that require the new capabilities. Keep the reference paths out of unseeded search runs. Record whether the router finds the planted improvements, plus the physical length and catalog cost on equal verified net sets. Look for additional examples of those improvements in the existing corpus.
|
||||||
- Use the 100 nm explicit lattice as the principal comparison. At that pitch the board has about 2.5 billion lattice positions before headings or profiles. Check peak memory and use sparse search. For the grid prototype, compare explicit routing with coarse guidance at 1 µm and 10 µm followed by local refinement. Include a case containing a transition or a terminal position that cannot be represented at the coarse pitch. Report results after final verification at full layout precision.
|
- Use the 100 nm explicit lattice as the principal comparison. At that pitch the board has about 2.5 billion lattice positions before headings or profiles. Check peak memory and use sparse search. For the grid prototype, compare explicit routing with coarse guidance at 1 µm and 10 µm followed by local refinement. Include a case containing a transition or a terminal position that cannot be represented at the coarse pitch. Report results after final verification at full layout precision.
|
||||||
- Report native Manhattan, Manhattan through the evaluation boundary, typed Manhattan, and eight headings separately. Record verified and completed net IDs, geometry, catalog cost, expansions, proposals per expansion, exact geometry checks, cache entries, peak memory, and repeated wall times. Compare legacy runs under the same options and dependencies. Target at most a few minutes end to end for the representative 40-net run. Measure whether seconds are attainable. Record the machine, coverage, time to first verified layout and time to final result. Use profiles and repeated runs to set phase budgets and memory targets before stabilizing the public types. Record the diagnostics for both a successful run and a budget-limited run.
|
- Report native Manhattan, Manhattan through the evaluation boundary, typed Manhattan, and eight headings separately. Record verified and completed net IDs, geometry, catalog cost, expansions, proposals per expansion, exact geometry checks, cache entries, peak memory, and repeated wall times. Compare legacy runs under the same options and dependencies. Target at most a few minutes end to end for the representative 40-net run. Measure whether seconds are attainable. Record the machine, coverage, time to first verified layout and time to final result. Use profiles and repeated runs to set phase budgets and memory targets before stabilizing the public types. Record the diagnostics for both a successful run and a budget-limited run.
|
||||||
|
|
|
||||||
|
|
@ -94,6 +94,7 @@ For structured logging, `dataclasses.asdict(run)` preserves the per-net fields.
|
||||||
| `proximity_range` | `10.0` | Obstacle proximity scoring range in layout units. Scale it with the coordinates when changing units. Large perimeters use an exact boundary index once the sample budget is reached. |
|
| `proximity_range` | `10.0` | Obstacle proximity scoring range in layout units. Scale it with the coordinates when changing units. Large perimeters use an exact boundary index once the sample budget is reached. |
|
||||||
| `bend_physical_length` | `None` | Optional authored centerline length for the shared custom 90-degree template, including tangent extensions. Search, refinement, and reports use it when supplied. |
|
| `bend_physical_length` | `None` | Optional authored centerline length for the shared custom 90-degree template, including tangent extensions. Search, refinement, and reports use it when supplied. |
|
||||||
| `distance_heuristic_weight` | `1.0` | Finite, nonnegative multiplier for the remaining-distance term only. Increase it to favor progress toward the target relative to estimated turn penalties. The routed path's objective stays the same. |
|
| `distance_heuristic_weight` | `1.0` | Finite, nonnegative multiplier for the remaining-distance term only. Increase it to favor progress toward the target relative to estimated turn penalties. The routed path's objective stays the same. |
|
||||||
|
| `terminal_jog_limit` | `0` | Enables verified straight and single-turn candidates during native greedy warm start without corridors. It also caps the number of two-turn jogs or four-turn detours checked per net. Zero skips this planning step. |
|
||||||
|
|
||||||
A custom S-bend outline uses local coordinates. Its input face is centered at `(0, 0)`, its output face at `(span, offset)`, and both ports face east. Use the same grid span as `SBendSeed(offset, radius)`, including any tangent extension to reach the output face. For example, an offset of `40` with radius `50` has its output at `(80, 40)`. The router rotates and translates the entire outline and uses it for collision checks and seed replay. Supply a separate outline to customize the opposite offset. Width matching allows a relative difference of `1e-12` to account for floating-point conversions. If multiple outlines apply to the same move, `route()` skips that move for the affected net and sets `sbend_template_error` in the final result and iteration callbacks. Direct calls to `SearchOptions.sbend_template()` and `sbend_outline()` raise `ValueError` for an ambiguous match. Moves with no matching outline use the circular S-bend. Set `SBendOutline.length` to use a process-specific centerline length for scoring, refinement, and reporting. The default is the nominal circular length. Automatic mode uses lattice search when an enabled outline matches a net width. Bundle mode requires circular bends for its nets.
|
A custom S-bend outline uses local coordinates. Its input face is centered at `(0, 0)`, its output face at `(span, offset)`, and both ports face east. Use the same grid span as `SBendSeed(offset, radius)`, including any tangent extension to reach the output face. For example, an offset of `40` with radius `50` has its output at `(80, 40)`. The router rotates and translates the entire outline and uses it for collision checks and seed replay. Supply a separate outline to customize the opposite offset. Width matching allows a relative difference of `1e-12` to account for floating-point conversions. If multiple outlines apply to the same move, `route()` skips that move for the affected net and sets `sbend_template_error` in the final result and iteration callbacks. Direct calls to `SearchOptions.sbend_template()` and `sbend_outline()` raise `ValueError` for an ambiguous match. Moves with no matching outline use the circular S-bend. Set `SBendOutline.length` to use a process-specific centerline length for scoring, refinement, and reporting. The default is the nominal circular length. Automatic mode uses lattice search when an enabled outline matches a net width. Bundle mode requires circular bends for its nets.
|
||||||
|
|
||||||
|
|
@ -152,9 +153,11 @@ Increase the iteration limit when later reroutes might resolve conflicts. Adjust
|
||||||
| `guide_strength` | `0.75` | Maximum added guidance cost per unit length. Explicit guide and seed runs with at least two configured congestion iterations may try one additional iteration from the start with zero guidance cost. The retry retains corridor move proposals and wins only with higher verified coverage. |
|
| `guide_strength` | `0.75` | Maximum added guidance cost per unit length. Explicit guide and seed runs with at least two configured congestion iterations may try one additional iteration from the start with zero guidance cost. The retry retains corridor move proposals and wins only with higher verified coverage. |
|
||||||
| `seed_node_limit` | `600` | Total seed-search expansions per net, capped by the active search limit. |
|
| `seed_node_limit` | `600` | Total seed-search expansions per net, capped by the active search limit. |
|
||||||
| `infer_terminal_headings` | `False` | Let automatic or bundle mode choose headings for supported layouts with flexible port directions. Automatic preserves caller headings when initial paths are supplied. |
|
| `infer_terminal_headings` | `False` | Let automatic or bundle mode choose headings for supported layouts with flexible port directions. Automatic preserves caller headings when initial paths are supplied. |
|
||||||
| `automatic_cost` | `"selective"` | Try a second column-planning pass based on route cost when the first pass chains short S-bends. Use `"always"` to try both passes or `"never"` to plan by span alone. |
|
| `automatic_cost` | `"selective"` | Try weighted column planning when the span planner chains short S-bends. Explicit length weights that put a premium on S-bends can also trigger a verified quarter-turn column candidate, including through shared apertures where adjacent columns leave too little room for a jog, or a detour between aligned ports for a single net. Use `"always"` to run both S-bend planning passes or `"never"` to plan by span alone. |
|
||||||
| `automatic_length_weights` | `None` | Optional straight, 90-degree bend, and S-bend length multipliers for automatic candidate selection. The default uses the search objective. |
|
| `automatic_length_weights` | `None` | Optional straight, 90-degree bend, and S-bend length multipliers for automatic candidate selection. The default uses the search objective. |
|
||||||
|
|
||||||
|
When automatic cost planning uses explicit length weights, it may replace a verified column route's S-bend excursion with a lower-cost straight that fits the same endpoints and clears every other route.
|
||||||
|
|
||||||
### DiagnosticsOptions
|
### DiagnosticsOptions
|
||||||
|
|
||||||
The flags default to `False`.
|
The flags default to `False`.
|
||||||
|
|
|
||||||
|
|
@ -25,6 +25,45 @@ result = route(problem).results_by_net["input"]
|
||||||
- [Bend radius settings](api-reference.md#searchoptions)
|
- [Bend radius settings](api-reference.md#searchoptions)
|
||||||
- [Layout input types and defaults](api-reference.md#routingproblem)
|
- [Layout input types and defaults](api-reference.md#routingproblem)
|
||||||
|
|
||||||
|
## Route a typed Masque layout
|
||||||
|
|
||||||
|
The preview adapter lives in `inire.masque`. The integration fixtures exercise Masque 4.0a3. Define named ports on the top-level pattern, using Masque's port mappings to expose ports from preplaced cells. Assign each endpoint its canonical routing profile. The adapter rounds resolved positions to the nearest layout unit before Inire checks exact membership on the routing lattice. Dimensions in the grid, shapes, and catalog use that common layout unit.
|
||||||
|
|
||||||
|
```python
|
||||||
|
from math import pi
|
||||||
|
|
||||||
|
from masque import Pattern, Port
|
||||||
|
from shapely.geometry import box
|
||||||
|
|
||||||
|
from inire.masque import Catalog, Connection, Endpoint, Grid, Profile, StraightVariant, route_and_place
|
||||||
|
|
||||||
|
layout = Pattern(ports={
|
||||||
|
"source": Port((10_000, 20_000), rotation=pi),
|
||||||
|
"destination": Port((90_000, 20_000), rotation=0),
|
||||||
|
})
|
||||||
|
catalog = Catalog("process-a", {"ridge-4": Profile("ridge", width=4000)}, {
|
||||||
|
"ridge-straight": StraightVariant("ridge-4", cost_per_cm=1),
|
||||||
|
})
|
||||||
|
result = route_and_place(
|
||||||
|
layout,
|
||||||
|
{},
|
||||||
|
(Connection("input", Endpoint("source", "ridge-4"), Endpoint("destination", "ridge-4")),),
|
||||||
|
catalog=catalog,
|
||||||
|
grid=Grid(origin=(0, 0), pitch=100, meters_per_unit=1e-9),
|
||||||
|
board=box(0, 0, 100_000, 80_000),
|
||||||
|
layer=1,
|
||||||
|
)
|
||||||
|
assert result.placed == ("input",)
|
||||||
|
```
|
||||||
|
|
||||||
|
Pass a mapping from cell names to Masque patterns for fixed variants. Include blocking polygons from the placed layout in `keepouts`. An endpoint can carry an `Attachment` for one of those polygons when its route must join at the fixed port. Both endpoint names are consumed for each placed connection. A fixed cell can omit its physical centerline length. Nonadjacent pieces separated by a cell with unknown length must meet ordinary self-clearance. With `require_complete=True`, every requested connection and active match group must complete before placement begins.
|
||||||
|
|
||||||
|
To experiment with lattice selection, pass `AutomaticGrid(preferred_pitch=1000, meters_per_unit=1e-9)`. It uses a divisor of the preferred pitch that fits the rounded terminals and the authored fixed-cell displacements. Read the selected grid from the placement result. Pass `CoarseGuidance(pitch=1000)` to propose routes inside coarse corridors while still placing and verifying moves on the selected routing grid. The fine search can retry outside a corridor within the remaining node budget.
|
||||||
|
|
||||||
|
The placement result reports the catalog revision, evaluated routes, consumed terminals, and placement outcome. Each verified route exposes its catalog cost and physical length in layout units when the lengths of all constituent moves are known. Inspect `unavailable_variants` for grid-fit and realization diagnostics.
|
||||||
|
|
||||||
|
Give each `MatchGroup` its member offsets, wavelength in meters, and tolerance. Express offsets and tolerance in group optical length in layout units or in seconds. Supply a `DelayModel` for the process indices and characterized cell delays. To enable a tuning detour, supply that net's polygon in `tuning_windows`. A fixed contribution can be a characterized constant, a function of wavelength, or `None` for missing delay data. Bend lead costs use the profile's lowest declared straight rate by default. Set a bend's `lead_cost_per_cm=0` to include the leads in its placement charge.
|
||||||
|
|
||||||
<a id="connect-a-preplaced-crossing"></a>
|
<a id="connect-a-preplaced-crossing"></a>
|
||||||
|
|
||||||
## Route between placed crossings
|
## Route between placed crossings
|
||||||
|
|
|
||||||
679
inire/_catalog.py
Normal file
679
inire/_catalog.py
Normal file
|
|
@ -0,0 +1,679 @@
|
||||||
|
"""Evaluate catalog moves in layout coordinates, independently of search and timing."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from math import ceil, floor, fsum, hypot, isfinite, radians, sqrt, ulp
|
||||||
|
from numbers import Integral
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
from shapely.affinity import affine_transform, translate
|
||||||
|
from shapely.geometry import Polygon
|
||||||
|
|
||||||
|
from inire._snapshot import snapshot
|
||||||
|
from inire.geometry.catalog_curve import CurveSection, bend_curve, sample_section, sbend_curve, world_sections
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from collections.abc import Mapping
|
||||||
|
|
||||||
|
|
||||||
|
HEADING_STEPS = {
|
||||||
|
0: (1, 0), 45: (1, 1), 90: (0, 1), 135: (-1, 1),
|
||||||
|
180: (-1, 0), 225: (-1, -1), 270: (0, -1), 315: (1, -1),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _require_integer(value: int) -> None:
|
||||||
|
if isinstance(value, bool) or not isinstance(value, Integral):
|
||||||
|
raise TypeError(f"Expected an integer layout coordinate or heading, got {value!r}")
|
||||||
|
|
||||||
|
|
||||||
|
def _require_positive(name: str, value: float) -> None:
|
||||||
|
if not isfinite(value) or value <= 0:
|
||||||
|
raise ValueError(f"{name} must be finite and positive")
|
||||||
|
|
||||||
|
|
||||||
|
def _require_nonnegative(name: str, value: float) -> None:
|
||||||
|
if not isfinite(value) or value < 0:
|
||||||
|
raise ValueError(f"{name} must be finite and nonnegative")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class Grid:
|
||||||
|
"""A square routing lattice in the adapter's integer layout units."""
|
||||||
|
|
||||||
|
origin: tuple[int, int]
|
||||||
|
pitch: int
|
||||||
|
meters_per_unit: float
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
for coordinate in (*self.origin, self.pitch):
|
||||||
|
_require_integer(coordinate)
|
||||||
|
_require_positive("Grid pitch", self.pitch)
|
||||||
|
_require_positive("Physical layout scale", self.meters_per_unit)
|
||||||
|
|
||||||
|
def lattice_position(self, x: int, y: int) -> tuple[int, int] | None:
|
||||||
|
_require_integer(x)
|
||||||
|
_require_integer(y)
|
||||||
|
col, rx = divmod(int(x) - int(self.origin[0]), int(self.pitch))
|
||||||
|
row, ry = divmod(int(y) - int(self.origin[1]), int(self.pitch))
|
||||||
|
return (col, row) if rx == ry == 0 else None
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class Pose:
|
||||||
|
"""A layout position, heading in degrees, and canonical routing profile ID."""
|
||||||
|
|
||||||
|
x: int
|
||||||
|
y: int
|
||||||
|
heading: int
|
||||||
|
profile: str
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
for value in (self.x, self.y, self.heading):
|
||||||
|
_require_integer(value)
|
||||||
|
if self.heading not in HEADING_STEPS:
|
||||||
|
raise ValueError(f"Unsupported routing heading {self.heading}")
|
||||||
|
if not self.profile:
|
||||||
|
raise ValueError("A routing pose needs a profile ID")
|
||||||
|
# Exact arithmetic after transforms, including for numpy integer inputs.
|
||||||
|
object.__setattr__(self, "x", int(self.x))
|
||||||
|
object.__setattr__(self, "y", int(self.y))
|
||||||
|
object.__setattr__(self, "heading", int(self.heading))
|
||||||
|
|
||||||
|
def shifted(self, dx: int, dy: int) -> Pose:
|
||||||
|
return Pose(self.x + dx, self.y + dy, self.heading, self.profile)
|
||||||
|
|
||||||
|
def reversed(self) -> Pose:
|
||||||
|
return Pose(self.x, self.y, (self.heading + 180) % 360, self.profile)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class Profile:
|
||||||
|
waveguide_type: str
|
||||||
|
width: float
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
if not self.waveguide_type:
|
||||||
|
raise ValueError("A routing profile needs a waveguide type")
|
||||||
|
_require_positive("Profile width", self.width)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class Orientation:
|
||||||
|
"""Reflect about the local x-axis, then rotate about the origin."""
|
||||||
|
|
||||||
|
rotation: int = 0
|
||||||
|
reflected: bool = False
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
_require_integer(self.rotation)
|
||||||
|
if self.rotation not in (0, 90, 180, 270):
|
||||||
|
raise ValueError("Fixed-cell rotations must be declared quarter turns")
|
||||||
|
|
||||||
|
def matrix(self) -> tuple[int, int, int, int]:
|
||||||
|
x, y = HEADING_STEPS[self.rotation]
|
||||||
|
sign = -1 if self.reflected else 1
|
||||||
|
return x, -y * sign, y, x * sign
|
||||||
|
|
||||||
|
def port(self, port: Pose) -> Pose:
|
||||||
|
a, b, d, e = self.matrix()
|
||||||
|
heading = -port.heading if self.reflected else port.heading
|
||||||
|
return Pose(a * port.x + b * port.y, d * port.x + e * port.y, (heading + self.rotation) % 360, port.profile)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class Placement:
|
||||||
|
orientation: Orientation
|
||||||
|
x: int
|
||||||
|
y: int
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class FixedVariant:
|
||||||
|
"""A two-port cell with named inward-facing authored ports."""
|
||||||
|
|
||||||
|
cell: str
|
||||||
|
ports: Mapping[str, Pose]
|
||||||
|
footprints: tuple[Polygon, ...]
|
||||||
|
traversals: tuple[tuple[str, str], ...]
|
||||||
|
orientations: tuple[Orientation, ...]
|
||||||
|
cost: float
|
||||||
|
length: float | None = None
|
||||||
|
port_shapes: tuple[Polygon, ...] = ()
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
if not self.cell or len(self.ports) != 2 or not all(self.ports):
|
||||||
|
raise ValueError("A fixed variant needs a cell and two distinct named ports")
|
||||||
|
if not self.footprints or any(
|
||||||
|
not isinstance(shape, Polygon) or shape.is_empty or not shape.is_valid or shape.has_z
|
||||||
|
or not isfinite(shape.area) or shape.area <= 0 for shape in (*self.footprints, *self.port_shapes)
|
||||||
|
):
|
||||||
|
raise ValueError("Fixed variant footprints must be nonempty valid planar polygons")
|
||||||
|
if (
|
||||||
|
not self.traversals or len(set(self.traversals)) != len(self.traversals)
|
||||||
|
or any(a == b or a not in self.ports or b not in self.ports for a, b in self.traversals)
|
||||||
|
):
|
||||||
|
raise ValueError("A fixed variant needs distinct directed traversals between its named ports")
|
||||||
|
if not self.orientations or len(set(self.orientations)) != len(self.orientations):
|
||||||
|
raise ValueError("A fixed variant needs distinct declared orientations")
|
||||||
|
_require_nonnegative("Fixed placement cost", self.cost)
|
||||||
|
if self.length is not None:
|
||||||
|
_require_positive("Fixed physical length", self.length)
|
||||||
|
object.__setattr__(self, "ports", snapshot(self.ports))
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class StraightVariant:
|
||||||
|
profile: str
|
||||||
|
cost_per_cm: float
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
_require_nonnegative("Straight cost per centimeter", self.cost_per_cm)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class TaperVariant:
|
||||||
|
input_profile: str
|
||||||
|
output_profile: str
|
||||||
|
minimum_length: float
|
||||||
|
cost: float
|
||||||
|
max_stretch: float = 0.05
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
if self.input_profile == self.output_profile:
|
||||||
|
raise ValueError("A taper traversal must change profiles")
|
||||||
|
_require_positive("Taper minimum length", self.minimum_length)
|
||||||
|
_require_nonnegative("Taper cost", self.cost)
|
||||||
|
_require_nonnegative("Taper stretch limit", self.max_stretch)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class BendVariant:
|
||||||
|
profile: str
|
||||||
|
turn: int # signed degrees
|
||||||
|
radius: float
|
||||||
|
cost: float
|
||||||
|
minimum_radius: float = 0.0
|
||||||
|
euler_fraction: float | None = None
|
||||||
|
max_lead: float = 0.0
|
||||||
|
lead_cost_per_cm: float | None = None
|
||||||
|
sagitta: float = 0.01
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
_require_integer(self.turn)
|
||||||
|
if abs(self.turn) not in (45, 90, 135, 180):
|
||||||
|
raise ValueError("Generated bends must turn by 45°, 90°, 135°, or 180°")
|
||||||
|
_require_positive("Circular-equivalent radius", self.radius)
|
||||||
|
_require_positive("Bend sampling sagitta", self.sagitta)
|
||||||
|
_require_nonnegative("Minimum curvature radius", self.minimum_radius)
|
||||||
|
_require_nonnegative("Bend cost", self.cost)
|
||||||
|
_require_nonnegative("Tangent lead cap", self.max_lead)
|
||||||
|
if self.lead_cost_per_cm is not None:
|
||||||
|
_require_nonnegative("Lead cost per centimeter", self.lead_cost_per_cm)
|
||||||
|
if self.euler_fraction is not None and not 0 <= self.euler_fraction <= 1:
|
||||||
|
raise ValueError("An explicit Euler fraction must be in [0, 1]")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class SBendVariant:
|
||||||
|
profile: str
|
||||||
|
radius: float
|
||||||
|
cost: float
|
||||||
|
projections: tuple[tuple[int, int], ...]
|
||||||
|
minimum_radius: float = 0.0
|
||||||
|
euler_fraction: float | None = None
|
||||||
|
sagitta: float = 0.01
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
_require_positive("S-bend circular-equivalent radius", self.radius)
|
||||||
|
_require_positive("S-bend sampling sagitta", self.sagitta)
|
||||||
|
_require_nonnegative("S-bend minimum curvature radius", self.minimum_radius)
|
||||||
|
_require_nonnegative("S-bend cost", self.cost)
|
||||||
|
if self.euler_fraction is not None and not 0 <= self.euler_fraction <= 1:
|
||||||
|
raise ValueError("An explicit Euler fraction must be in [0, 1]")
|
||||||
|
if not self.projections or len(set(self.projections)) != len(self.projections):
|
||||||
|
raise ValueError("An S-bend needs distinct forward/lateral projection choices")
|
||||||
|
for forward, lateral in self.projections:
|
||||||
|
_require_integer(forward)
|
||||||
|
_require_integer(lateral)
|
||||||
|
if forward <= 0 or lateral == 0:
|
||||||
|
raise ValueError("S-bend projections require forward motion and nonzero lateral offset")
|
||||||
|
|
||||||
|
|
||||||
|
Variant = FixedVariant | StraightVariant | TaperVariant | BendVariant | SBendVariant
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class Catalog:
|
||||||
|
revision: str
|
||||||
|
profiles: Mapping[str, Profile]
|
||||||
|
variants: Mapping[str, Variant]
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
if not self.revision or not all(self.profiles) or not all(self.variants):
|
||||||
|
raise ValueError("Catalog revision and IDs must be nonempty")
|
||||||
|
for name, variant in self.variants.items():
|
||||||
|
if isinstance(variant, FixedVariant):
|
||||||
|
profiles = tuple(port.profile for port in variant.ports.values())
|
||||||
|
elif isinstance(variant, TaperVariant):
|
||||||
|
profiles = (variant.input_profile, variant.output_profile)
|
||||||
|
else:
|
||||||
|
profiles = (variant.profile,)
|
||||||
|
if any(profile not in self.profiles for profile in profiles):
|
||||||
|
raise ValueError(f"Variant {name!r} uses an unknown profile")
|
||||||
|
object.__setattr__(self, "profiles", snapshot(self.profiles))
|
||||||
|
object.__setattr__(self, "variants", snapshot(self.variants))
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class Move:
|
||||||
|
"""Selected parameters within one catalog revision."""
|
||||||
|
|
||||||
|
variant: str
|
||||||
|
steps: int | None = None
|
||||||
|
traversal: tuple[str, str] | None = None
|
||||||
|
orientation: Orientation = Orientation()
|
||||||
|
displacement: tuple[int, int] | None = None
|
||||||
|
leads: tuple[float, float] = (0.0, 0.0)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class Evaluation:
|
||||||
|
move: Move
|
||||||
|
start: Pose
|
||||||
|
end: Pose
|
||||||
|
footprints: tuple[Polygon, ...]
|
||||||
|
length: float | None # layout units
|
||||||
|
cost: float
|
||||||
|
placement: Placement | None = None
|
||||||
|
curve_sections: tuple[CurveSection, ...] = ()
|
||||||
|
minimum_radius: float | None = None
|
||||||
|
euler_fraction: float | None = None
|
||||||
|
port_shapes: tuple[Polygon, ...] = ()
|
||||||
|
|
||||||
|
|
||||||
|
def face_endpoints(pose: Pose, width: float) -> tuple[tuple[float, float], tuple[float, float]]:
|
||||||
|
"""Construct the same finite face for both sides of a direct join."""
|
||||||
|
dx, dy = HEADING_STEPS[pose.heading]
|
||||||
|
half_width = width / (2 * hypot(dx, dy))
|
||||||
|
nx, ny = -dy * half_width, dx * half_width
|
||||||
|
return (pose.x + nx, pose.y + ny), (pose.x - nx, pose.y - ny)
|
||||||
|
|
||||||
|
|
||||||
|
def unit_direction(heading: int) -> tuple[float, float]:
|
||||||
|
x, y = HEADING_STEPS[heading]
|
||||||
|
length = hypot(x, y)
|
||||||
|
return x / length, y / length
|
||||||
|
|
||||||
|
|
||||||
|
def _bend_port_displacement(variant: BendVariant, heading: int) -> tuple[float, float]:
|
||||||
|
turn_cos, turn_sin = unit_direction(abs(variant.turn))
|
||||||
|
forward = variant.radius * turn_sin
|
||||||
|
lateral = (1 if variant.turn > 0 else -1) * variant.radius * (1 - turn_cos)
|
||||||
|
x, y = unit_direction(heading)
|
||||||
|
return forward * x - lateral * y, forward * y + lateral * x
|
||||||
|
|
||||||
|
|
||||||
|
def _euler_setting(variant: BendVariant | SBendVariant) -> float | None:
|
||||||
|
if variant.euler_fraction is None and not variant.minimum_radius:
|
||||||
|
return 0.0
|
||||||
|
return variant.euler_fraction
|
||||||
|
|
||||||
|
|
||||||
|
def curve_polygon(
|
||||||
|
sections: tuple[CurveSection, ...], start: Pose, end: Pose, width: float, sagitta: float,
|
||||||
|
) -> Polygon:
|
||||||
|
left_edges, right_edges = [], []
|
||||||
|
current = (float(start.x), float(start.y))
|
||||||
|
for section in sections:
|
||||||
|
positions, normals = sample_section(section, current, sagitta)
|
||||||
|
offsets = normals * width / 2
|
||||||
|
left_edges.append(positions[:-1] + offsets[:-1])
|
||||||
|
right_edges.append(positions[:-1] - offsets[:-1])
|
||||||
|
current = tuple(positions[-1])
|
||||||
|
left_start, right_start = face_endpoints(start, width)
|
||||||
|
left_end, right_end = face_endpoints(end, width)
|
||||||
|
left = np.vstack((*left_edges, left_end))
|
||||||
|
right = np.vstack((*right_edges, right_end))
|
||||||
|
left[0], right[0] = left_start, right_start
|
||||||
|
return Polygon(np.concatenate((left, right[::-1])))
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class _LocalFixed:
|
||||||
|
entry: Pose
|
||||||
|
exit: Pose
|
||||||
|
footprints: tuple[Polygon, ...]
|
||||||
|
port_shapes: tuple[Polygon, ...]
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class VariantDiagnostic:
|
||||||
|
move: Move
|
||||||
|
entry_heading: int
|
||||||
|
reason: str
|
||||||
|
projections: tuple[int, int] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class MoveEvaluator:
|
||||||
|
"""Evaluate known move parameters with a request-local fixed geometry cache."""
|
||||||
|
|
||||||
|
def __init__(self, grid: Grid, catalog: Catalog) -> None:
|
||||||
|
self.grid = grid
|
||||||
|
self.catalog = catalog
|
||||||
|
self._fixed: dict[Move, _LocalFixed] = {}
|
||||||
|
self._bend_moves: dict[tuple[str, int], tuple[Move, ...]] = {}
|
||||||
|
self._bend_shapes: dict[tuple[Move, int], Evaluation] = {}
|
||||||
|
self._local_moves: dict[tuple[str, int], tuple[tuple[Move, Pose], ...]] = {}
|
||||||
|
self._sbend_shapes: dict[tuple[Move, int], Evaluation | None] = {}
|
||||||
|
self._unavailable: dict[tuple[Move, int, tuple[int, int] | None], VariantDiagnostic] = {}
|
||||||
|
|
||||||
|
@property
|
||||||
|
def unavailable(self) -> tuple[VariantDiagnostic, ...]:
|
||||||
|
return tuple(self._unavailable.values())
|
||||||
|
|
||||||
|
def _diagnose(self, move: Move, heading: int, reason: str, projections: tuple[int, int] | None = None) -> None:
|
||||||
|
self._unavailable.setdefault((move, heading, projections), VariantDiagnostic(move, heading, reason, projections))
|
||||||
|
|
||||||
|
def coverage_catalog(self, profile: str, *, cardinal: bool) -> Catalog:
|
||||||
|
"""Keep the profile's own primitives for a bounded coverage retry."""
|
||||||
|
variants = {}
|
||||||
|
for name, variant in self.catalog.variants.items():
|
||||||
|
if isinstance(variant, FixedVariant):
|
||||||
|
eligible = all(port.profile == profile and (not cardinal or port.heading % 90 == 0) for port in variant.ports.values())
|
||||||
|
elif isinstance(variant, TaperVariant):
|
||||||
|
eligible = False
|
||||||
|
else:
|
||||||
|
eligible = variant.profile == profile and (not cardinal or not isinstance(variant, BendVariant) or variant.turn % 90 == 0)
|
||||||
|
if eligible:
|
||||||
|
variants[name] = variant
|
||||||
|
return Catalog(self.catalog.revision, {profile: self.catalog.profiles[profile]}, variants)
|
||||||
|
|
||||||
|
def _local_fixed(self, move: Move, variant: FixedVariant) -> _LocalFixed:
|
||||||
|
if (
|
||||||
|
move.steps is not None or move.displacement is not None or move.leads != (0.0, 0.0)
|
||||||
|
or move.traversal not in variant.traversals or move.orientation not in variant.orientations
|
||||||
|
):
|
||||||
|
raise ValueError(f"Undeclared traversal or transform for fixed variant {move.variant!r}")
|
||||||
|
cached = self._fixed.get(move)
|
||||||
|
if cached is None:
|
||||||
|
assert move.traversal is not None
|
||||||
|
input_port, output_port = (variant.ports[name] for name in move.traversal)
|
||||||
|
orientation = move.orientation
|
||||||
|
cached = _LocalFixed(
|
||||||
|
orientation.port(input_port), orientation.port(output_port).reversed(),
|
||||||
|
tuple(affine_transform(shape, (*orientation.matrix(), 0, 0)) for shape in variant.footprints),
|
||||||
|
tuple(affine_transform(shape, (*orientation.matrix(), 0, 0)) for shape in variant.port_shapes),
|
||||||
|
)
|
||||||
|
self._fixed[move] = cached
|
||||||
|
return cached
|
||||||
|
|
||||||
|
def fixed_exit(self, move: Move, start: Pose, variant: FixedVariant) -> Pose | None:
|
||||||
|
"""Compute compatible fixed-cell displacement before translating polygons."""
|
||||||
|
local = self._local_fixed(move, variant)
|
||||||
|
if (start.profile, start.heading) != (local.entry.profile, local.entry.heading):
|
||||||
|
return None
|
||||||
|
end = local.exit.shifted(start.x - local.entry.x, start.y - local.entry.y)
|
||||||
|
if self.grid.lattice_position(end.x, end.y) is None:
|
||||||
|
self._diagnose(move, start.heading, "off_grid_output")
|
||||||
|
return None
|
||||||
|
return end
|
||||||
|
|
||||||
|
def local_moves(self, profile: str, heading: int) -> tuple[tuple[Move, Pose], ...]:
|
||||||
|
"""Finite compatible moves and their port displacement from the start."""
|
||||||
|
key = (profile, heading)
|
||||||
|
if key not in self._local_moves:
|
||||||
|
ox, oy = self.grid.origin
|
||||||
|
origin = Pose(ox, oy, heading, profile)
|
||||||
|
variants = self.catalog.variants
|
||||||
|
steps = []
|
||||||
|
for name, variant in variants.items():
|
||||||
|
if isinstance(variant, FixedVariant):
|
||||||
|
for traversal in variant.traversals:
|
||||||
|
for orientation in variant.orientations:
|
||||||
|
move = Move(name, traversal=traversal, orientation=orientation)
|
||||||
|
if end := self.fixed_exit(move, origin, variant):
|
||||||
|
steps.append((move, end.shifted(-ox, -oy)))
|
||||||
|
elif isinstance(variant, BendVariant) and variant.profile == profile:
|
||||||
|
for move in self.bend_moves(name, heading, variant):
|
||||||
|
assert move.displacement is not None
|
||||||
|
x, y = move.displacement
|
||||||
|
steps.append((move, Pose(x, y, (heading + variant.turn) % 360, profile)))
|
||||||
|
elif isinstance(variant, SBendVariant) and variant.profile == profile:
|
||||||
|
for move in self._sbend_specs(name, heading, variant):
|
||||||
|
if sbend := self._local_sbend(move, heading, variant):
|
||||||
|
steps.append((move, sbend.end))
|
||||||
|
elif isinstance(variant, TaperVariant):
|
||||||
|
move = Move(name)
|
||||||
|
result = self.evaluate(move, origin)
|
||||||
|
if result is not None:
|
||||||
|
steps.append((move, result.end.shifted(-ox, -oy)))
|
||||||
|
self._local_moves[key] = tuple(steps)
|
||||||
|
return self._local_moves[key]
|
||||||
|
|
||||||
|
def bend_moves(self, name: str, heading: int, variant: BendVariant) -> tuple[Move, ...]:
|
||||||
|
"""Return bounded grid-compatible lead choices in stable order."""
|
||||||
|
key = (name, heading)
|
||||||
|
if key not in self._bend_moves:
|
||||||
|
self._bend_moves[key] = self._bend_choices(name, heading, variant)
|
||||||
|
return self._bend_moves[key]
|
||||||
|
|
||||||
|
def _bend_choices(self, name: str, heading: int, variant: BendVariant) -> tuple[Move, ...]:
|
||||||
|
angle = radians(abs(variant.turn))
|
||||||
|
curve = bend_curve(variant.radius, angle, variant.minimum_radius, _euler_setting(variant))
|
||||||
|
if curve is None or curve.radius <= self.catalog.profiles[variant.profile].width / 2:
|
||||||
|
self._diagnose(Move(name), heading, "curvature_radius")
|
||||||
|
return ()
|
||||||
|
ux, uy = unit_direction(heading)
|
||||||
|
vx, vy = unit_direction((heading + variant.turn) % 360)
|
||||||
|
bare_x, bare_y = _bend_port_displacement(variant, heading)
|
||||||
|
cap = variant.max_lead
|
||||||
|
pitch = int(self.grid.pitch)
|
||||||
|
residual = 16 * ulp(max(variant.radius, cap, pitch))
|
||||||
|
det = ux * vy - uy * vx
|
||||||
|
# Enumerate the lattice points in the reachable lead box. Keep a
|
||||||
|
# bounded neighborhood of the bare port for each proposed variant.
|
||||||
|
start_x = ceil((bare_x + min(0, cap * ux) + min(0, cap * vx) - residual) / pitch)
|
||||||
|
end_x = floor((bare_x + max(0, cap * ux) + max(0, cap * vx) + residual) / pitch)
|
||||||
|
start_y = ceil((bare_y + min(0, cap * uy) + min(0, cap * vy) - residual) / pitch)
|
||||||
|
end_y = floor((bare_y + max(0, cap * uy) + max(0, cap * vy) + residual) / pitch)
|
||||||
|
|
||||||
|
def near(lo: int, hi: int, center: float) -> range:
|
||||||
|
mid = round(center / pitch)
|
||||||
|
return range(max(lo, mid - 8), min(hi, mid + 8) + 1)
|
||||||
|
|
||||||
|
moves = []
|
||||||
|
for ix in near(start_x, end_x, bare_x):
|
||||||
|
for iy in near(start_y, end_y, bare_y):
|
||||||
|
dx, dy = ix * pitch - bare_x, iy * pitch - bare_y
|
||||||
|
if abs(variant.turn) == 180:
|
||||||
|
if abs(ux * dy - uy * dx) > residual:
|
||||||
|
continue
|
||||||
|
difference = ux * dx + uy * dy
|
||||||
|
lead_pairs = ((max(0.0, difference), max(0.0, -difference)),)
|
||||||
|
if cap:
|
||||||
|
lead_pairs += ((cap + min(0.0, difference), cap - max(0.0, difference)),)
|
||||||
|
else:
|
||||||
|
lead_pairs = (((dx * vy - dy * vx) / det, (ux * dy - uy * dx) / det),)
|
||||||
|
for first, last in lead_pairs:
|
||||||
|
if not (-residual <= first <= cap + residual and -residual <= last <= cap + residual):
|
||||||
|
continue
|
||||||
|
leads = (max(0.0, min(cap, first)), max(0.0, min(cap, last)))
|
||||||
|
move = Move(name, displacement=(ix * pitch, iy * pitch), leads=leads)
|
||||||
|
if move not in moves:
|
||||||
|
moves.append(move)
|
||||||
|
if not moves:
|
||||||
|
self._diagnose(Move(name), heading, "no_grid_fit_within_lead_limit")
|
||||||
|
return tuple(sorted(moves, key=lambda item: (*item.leads, item.displacement)))
|
||||||
|
|
||||||
|
def _generated_bend(self, move: Move, start: Pose, variant: BendVariant) -> Evaluation | None:
|
||||||
|
if start.profile != variant.profile:
|
||||||
|
return None
|
||||||
|
if move.displacement is None or any(not isfinite(lead) or not 0 <= lead <= variant.max_lead for lead in move.leads):
|
||||||
|
self._diagnose(move, start.heading, "invalid_tangent_leads")
|
||||||
|
return None
|
||||||
|
key = (move, start.heading)
|
||||||
|
local = self._bend_shapes.get(key)
|
||||||
|
if local is None:
|
||||||
|
dx, dy = move.displacement
|
||||||
|
end_heading = (start.heading + variant.turn) % 360
|
||||||
|
local_start = Pose(0, 0, start.heading, start.profile)
|
||||||
|
local_end = Pose(dx, dy, end_heading, start.profile)
|
||||||
|
first, last = move.leads
|
||||||
|
ux, uy = unit_direction(start.heading)
|
||||||
|
vx, vy = unit_direction(end_heading)
|
||||||
|
bare_x, bare_y = _bend_port_displacement(variant, start.heading)
|
||||||
|
residual = 16 * ulp(max(variant.radius, variant.max_lead, self.grid.pitch))
|
||||||
|
expected_x, expected_y = bare_x + first * ux + last * vx, bare_y + first * uy + last * vy
|
||||||
|
if dx % self.grid.pitch or dy % self.grid.pitch or max(abs(expected_x - dx), abs(expected_y - dy)) > residual:
|
||||||
|
self._diagnose(move, start.heading, "off_grid_output")
|
||||||
|
return None
|
||||||
|
heading = radians(start.heading)
|
||||||
|
sign = 1 if variant.turn > 0 else -1
|
||||||
|
width = self.catalog.profiles[start.profile].width
|
||||||
|
curve = bend_curve(variant.radius, radians(abs(variant.turn)), variant.minimum_radius, _euler_setting(variant))
|
||||||
|
if curve is None or curve.radius <= width / 2:
|
||||||
|
self._diagnose(move, start.heading, "curvature_radius")
|
||||||
|
return None
|
||||||
|
sections = world_sections(curve, heading, sign)
|
||||||
|
if first:
|
||||||
|
sections = (CurveSection(first, heading), *sections)
|
||||||
|
if last:
|
||||||
|
sections = (*sections, CurveSection(last, heading + radians(variant.turn)))
|
||||||
|
polygon = curve_polygon(sections, local_start, local_end, width, variant.sagitta)
|
||||||
|
if not polygon.is_valid:
|
||||||
|
self._diagnose(move, start.heading, "invalid_footprint")
|
||||||
|
return None
|
||||||
|
lead_rate = variant.lead_cost_per_cm
|
||||||
|
if lead_rate is None:
|
||||||
|
lead_rate = min(
|
||||||
|
(
|
||||||
|
item.cost_per_cm for item in self.catalog.variants.values()
|
||||||
|
if isinstance(item, StraightVariant) and item.profile == start.profile
|
||||||
|
),
|
||||||
|
default=0.0,
|
||||||
|
)
|
||||||
|
cost = variant.cost + (first + last) * self.grid.meters_per_unit * 100 * lead_rate
|
||||||
|
local = Evaluation(
|
||||||
|
move, local_start, local_end, (polygon,), fsum(s.length for s in sections), cost,
|
||||||
|
curve_sections=sections, minimum_radius=curve.radius, euler_fraction=curve.fraction,
|
||||||
|
)
|
||||||
|
self._bend_shapes[key] = local
|
||||||
|
return Evaluation(
|
||||||
|
move, start, local.end.shifted(start.x, start.y), tuple(translate(shape, start.x, start.y) for shape in local.footprints),
|
||||||
|
local.length, local.cost, curve_sections=local.curve_sections,
|
||||||
|
minimum_radius=local.minimum_radius, euler_fraction=local.euler_fraction,
|
||||||
|
)
|
||||||
|
|
||||||
|
def _sbend_specs(self, name: str, heading: int, variant: SBendVariant) -> tuple[Move, ...]:
|
||||||
|
dx, dy = HEADING_STEPS[heading]
|
||||||
|
denominator = dx * dx + dy * dy
|
||||||
|
pitch = int(self.grid.pitch)
|
||||||
|
specs = []
|
||||||
|
for forward, lateral in variant.projections:
|
||||||
|
x, rx = divmod(dx * int(forward) - dy * int(lateral), denominator)
|
||||||
|
y, ry = divmod(dy * int(forward) + dx * int(lateral), denominator)
|
||||||
|
if rx == ry == 0:
|
||||||
|
specs.append(Move(name, displacement=(x * pitch, y * pitch)))
|
||||||
|
else:
|
||||||
|
self._diagnose(Move(name), heading, "off_grid_projections", (forward, lateral))
|
||||||
|
return tuple(specs)
|
||||||
|
|
||||||
|
def _local_sbend(self, move: Move, heading: int, variant: SBendVariant) -> Evaluation | None:
|
||||||
|
key = (move, heading)
|
||||||
|
if key not in self._sbend_shapes:
|
||||||
|
self._sbend_shapes[key] = None
|
||||||
|
if move in self._sbend_specs(move.variant, heading, variant):
|
||||||
|
assert move.displacement is not None
|
||||||
|
x, y = move.displacement
|
||||||
|
dx, dy = unit_direction(heading)
|
||||||
|
curve = sbend_curve(
|
||||||
|
x * dx + y * dy, y * dx - x * dy, variant.radius, variant.minimum_radius, _euler_setting(variant), radians(heading),
|
||||||
|
)
|
||||||
|
width = self.catalog.profiles[variant.profile].width
|
||||||
|
if curve is not None and curve.radius > width / 2:
|
||||||
|
origin, end = Pose(0, 0, heading, variant.profile), Pose(x, y, heading, variant.profile)
|
||||||
|
polygon = curve_polygon(curve.sections, origin, end, width, variant.sagitta)
|
||||||
|
if polygon.is_valid:
|
||||||
|
self._sbend_shapes[key] = Evaluation(
|
||||||
|
move, origin, end, (polygon,), fsum(section.length for section in curve.sections), variant.cost,
|
||||||
|
curve_sections=curve.sections, minimum_radius=curve.radius, euler_fraction=curve.fraction,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
self._diagnose(move, heading, "invalid_footprint")
|
||||||
|
else:
|
||||||
|
self._diagnose(move, heading, "sbend_curvature_or_span")
|
||||||
|
return self._sbend_shapes[key]
|
||||||
|
|
||||||
|
def evaluate(self, move: Move, start: Pose) -> Evaluation | None:
|
||||||
|
"""Return an evaluated placement, or None when its pose is unavailable."""
|
||||||
|
if self.grid.lattice_position(start.x, start.y) is None:
|
||||||
|
raise ValueError("Move starts off the routing lattice")
|
||||||
|
variant = self.catalog.variants[move.variant]
|
||||||
|
if isinstance(variant, FixedVariant):
|
||||||
|
end = self.fixed_exit(move, start, variant)
|
||||||
|
if end is None:
|
||||||
|
return None
|
||||||
|
local = self._fixed[move]
|
||||||
|
x, y = start.x - local.entry.x, start.y - local.entry.y
|
||||||
|
return Evaluation(
|
||||||
|
move, start, end, tuple(translate(shape, x, y) for shape in local.footprints),
|
||||||
|
variant.length, variant.cost, Placement(move.orientation, x, y),
|
||||||
|
port_shapes=tuple(translate(shape, x, y) for shape in local.port_shapes),
|
||||||
|
)
|
||||||
|
|
||||||
|
if move.traversal is not None or move.orientation != Orientation():
|
||||||
|
raise ValueError(f"Unexpected traversal or transform for generated variant {move.variant!r}")
|
||||||
|
if isinstance(variant, BendVariant):
|
||||||
|
if move.steps is not None:
|
||||||
|
raise ValueError("A bend uses a displacement and two leads")
|
||||||
|
return self._generated_bend(move, start, variant)
|
||||||
|
if isinstance(variant, SBendVariant):
|
||||||
|
if move.steps is not None or move.leads != (0.0, 0.0):
|
||||||
|
raise ValueError("An S-bend uses a displacement")
|
||||||
|
if start.profile != variant.profile:
|
||||||
|
return None
|
||||||
|
local = self._local_sbend(move, start.heading, variant)
|
||||||
|
if local is None:
|
||||||
|
return None
|
||||||
|
return Evaluation(
|
||||||
|
move, start, local.end.shifted(start.x, start.y), tuple(translate(shape, start.x, start.y) for shape in local.footprints),
|
||||||
|
local.length, local.cost, curve_sections=local.curve_sections,
|
||||||
|
minimum_radius=local.minimum_radius, euler_fraction=local.euler_fraction,
|
||||||
|
)
|
||||||
|
if move.displacement is not None or move.leads != (0.0, 0.0):
|
||||||
|
raise ValueError("Straight and taper moves cannot specify bend parameters")
|
||||||
|
dx, dy = HEADING_STEPS[start.heading]
|
||||||
|
pitch = int(self.grid.pitch)
|
||||||
|
step_length = pitch * (sqrt(2) if dx and dy else 1.0)
|
||||||
|
if isinstance(variant, StraightVariant):
|
||||||
|
if move.steps is None:
|
||||||
|
raise ValueError("A straight requires a step count")
|
||||||
|
_require_integer(move.steps)
|
||||||
|
if move.steps <= 0:
|
||||||
|
raise ValueError("A straight requires a positive step count")
|
||||||
|
if variant.profile != start.profile:
|
||||||
|
return None
|
||||||
|
steps = int(move.steps)
|
||||||
|
length = steps * step_length
|
||||||
|
cost = length * self.grid.meters_per_unit * 100 * variant.cost_per_cm
|
||||||
|
profile = variant.profile
|
||||||
|
else:
|
||||||
|
if move.steps is not None:
|
||||||
|
raise ValueError("Taper length is determined by its minimum length and heading")
|
||||||
|
if variant.input_profile != start.profile:
|
||||||
|
return None
|
||||||
|
steps = ceil(variant.minimum_length / step_length)
|
||||||
|
length = steps * step_length
|
||||||
|
if length > variant.minimum_length * (1 + variant.max_stretch):
|
||||||
|
self._diagnose(move, start.heading, "taper_stretch")
|
||||||
|
return None
|
||||||
|
cost = variant.cost
|
||||||
|
profile = variant.output_profile
|
||||||
|
|
||||||
|
end = Pose(start.x + steps * dx * pitch, start.y + steps * dy * pitch, start.heading, profile)
|
||||||
|
start_left, start_right = face_endpoints(start, self.catalog.profiles[start.profile].width)
|
||||||
|
end_left, end_right = face_endpoints(end, self.catalog.profiles[end.profile].width)
|
||||||
|
shape = Polygon((start_left, end_left, end_right, start_right))
|
||||||
|
return Evaluation(move, start, end, (shape,), length, cost)
|
||||||
155
inire/_catalog_timing.py
Normal file
155
inire/_catalog_timing.py
Normal file
|
|
@ -0,0 +1,155 @@
|
||||||
|
"""Timing evaluation of selected catalog geometry."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections.abc import Callable
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from math import cos, fsum, isfinite, radians, sin, tau
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from scipy.integrate import quad
|
||||||
|
|
||||||
|
from inire._catalog import StraightVariant, _require_nonnegative, _require_positive
|
||||||
|
from inire._snapshot import snapshot
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from collections.abc import Mapping, Sequence
|
||||||
|
|
||||||
|
from inire._catalog import Evaluation, MoveEvaluator
|
||||||
|
from inire.geometry.catalog_curve import CurveSection
|
||||||
|
|
||||||
|
|
||||||
|
FixedDelay = float | Callable[[float], float | None] | None
|
||||||
|
|
||||||
|
|
||||||
|
class _UnavailableDelay(Exception):
|
||||||
|
"""Characterization is unavailable at this wavelength or tangent."""
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class UniaxialGroupIndex:
|
||||||
|
parallel: float
|
||||||
|
perpendicular: float
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
_require_positive("Parallel group index", self.parallel)
|
||||||
|
_require_positive("Perpendicular group index", self.perpendicular)
|
||||||
|
|
||||||
|
def __call__(self, _wavelength: float, angle: float) -> float:
|
||||||
|
return self.parallel * cos(angle) ** 2 + self.perpendicular * sin(angle) ** 2
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class DelayModel:
|
||||||
|
"""Optical length in layout units at a wavelength in meters.
|
||||||
|
|
||||||
|
Group-index callbacks receive (wavelength, travel angle relative to the
|
||||||
|
process axis in radians). Characterized variants receive their evaluated
|
||||||
|
placement and the wavelength. Fixed contributions can be constants,
|
||||||
|
wavelength callbacks, or None for a known missing contribution.
|
||||||
|
"""
|
||||||
|
|
||||||
|
wavelength: float
|
||||||
|
process_angle: float = 0.0
|
||||||
|
group_indices: Mapping[str, float | Callable[[float, float], float | None]] = field(default_factory=dict)
|
||||||
|
variant_delays: Mapping[str, float | Callable[[Evaluation, float], float | None]] = field(default_factory=dict)
|
||||||
|
fixed_contributions: Mapping[str, tuple[FixedDelay, ...]] = field(default_factory=dict)
|
||||||
|
bend_group_indices: Mapping[str, float | Callable[[float, float], float | None]] = field(default_factory=dict)
|
||||||
|
integration_tolerance: float = 1e-5
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
_require_positive("Timing wavelength", self.wavelength)
|
||||||
|
if not isfinite(self.process_angle):
|
||||||
|
raise ValueError("The process axis angle must be finite")
|
||||||
|
_require_positive("Delay integration tolerance", self.integration_tolerance)
|
||||||
|
for group_index in (*self.group_indices.values(), *self.bend_group_indices.values()):
|
||||||
|
if not callable(group_index):
|
||||||
|
_require_positive("Group index", group_index)
|
||||||
|
for delay in self.variant_delays.values():
|
||||||
|
if not callable(delay):
|
||||||
|
_require_nonnegative("Characterized delay", delay)
|
||||||
|
for contributions in self.fixed_contributions.values():
|
||||||
|
for contribution in contributions:
|
||||||
|
if contribution is not None and not callable(contribution):
|
||||||
|
_require_nonnegative("Fixed delay contribution", contribution)
|
||||||
|
object.__setattr__(self, "group_indices", snapshot(self.group_indices))
|
||||||
|
object.__setattr__(self, "variant_delays", snapshot(self.variant_delays))
|
||||||
|
object.__setattr__(self, "fixed_contributions", snapshot(self.fixed_contributions))
|
||||||
|
object.__setattr__(self, "bend_group_indices", snapshot(self.bend_group_indices))
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class Delay:
|
||||||
|
optical_length: float
|
||||||
|
seconds: float
|
||||||
|
|
||||||
|
|
||||||
|
def _integrated_delay(move: Evaluation, model: DelayModel) -> float:
|
||||||
|
contributions = []
|
||||||
|
base_index = model.group_indices.get(move.start.profile)
|
||||||
|
for section in move.curve_sections:
|
||||||
|
curved = section.entry_curvature != 0 or section.exit_curvature != 0
|
||||||
|
group_index = model.bend_group_indices.get(move.move.variant, base_index) if curved else base_index
|
||||||
|
if group_index is None:
|
||||||
|
raise _UnavailableDelay
|
||||||
|
if not callable(group_index):
|
||||||
|
contributions.append(group_index * section.length)
|
||||||
|
continue
|
||||||
|
|
||||||
|
def integrand(
|
||||||
|
fraction: float,
|
||||||
|
*,
|
||||||
|
section: CurveSection = section,
|
||||||
|
group_index: Callable[[float, float], float | None] = group_index,
|
||||||
|
) -> float:
|
||||||
|
index = group_index(model.wavelength, (section.angle(fraction) - model.process_angle) % tau)
|
||||||
|
if index is None:
|
||||||
|
raise _UnavailableDelay
|
||||||
|
_require_positive("Evaluated group index", index)
|
||||||
|
return index
|
||||||
|
|
||||||
|
tolerance = model.integration_tolerance / (len(move.curve_sections) * section.length)
|
||||||
|
averaged = quad(integrand, 0, 1, epsabs=tolerance, epsrel=0)[0] if curved else integrand(0)
|
||||||
|
contributions.append(averaged * section.length)
|
||||||
|
return fsum(contributions)
|
||||||
|
|
||||||
|
|
||||||
|
def evaluate_delay(
|
||||||
|
evaluator: MoveEvaluator, path: Sequence[Evaluation], model: DelayModel, *, net_id: str,
|
||||||
|
) -> Delay | None:
|
||||||
|
"""Evaluate the placed route and its declared fixed contributions."""
|
||||||
|
contributions = []
|
||||||
|
for contribution in model.fixed_contributions.get(net_id, ()):
|
||||||
|
delay = contribution(model.wavelength) if callable(contribution) else contribution
|
||||||
|
if delay is None:
|
||||||
|
return None
|
||||||
|
_require_nonnegative("Evaluated fixed delay", delay)
|
||||||
|
contributions.append(delay)
|
||||||
|
for move in path:
|
||||||
|
spec = evaluator.catalog.variants[move.move.variant]
|
||||||
|
characterized = model.variant_delays.get(move.move.variant)
|
||||||
|
if characterized is not None:
|
||||||
|
optical_length = characterized(move, model.wavelength) if callable(characterized) else characterized
|
||||||
|
elif move.curve_sections:
|
||||||
|
try:
|
||||||
|
optical_length = _integrated_delay(move, model)
|
||||||
|
except _UnavailableDelay:
|
||||||
|
return None
|
||||||
|
elif isinstance(spec, StraightVariant):
|
||||||
|
angle = (radians(move.start.heading) - model.process_angle) % tau
|
||||||
|
group_index = model.group_indices.get(move.start.profile)
|
||||||
|
if callable(group_index):
|
||||||
|
group_index = group_index(model.wavelength, angle)
|
||||||
|
if group_index is None:
|
||||||
|
return None
|
||||||
|
_require_positive("Evaluated group index", group_index)
|
||||||
|
assert move.length is not None
|
||||||
|
optical_length = group_index * move.length
|
||||||
|
else:
|
||||||
|
return None
|
||||||
|
if optical_length is None:
|
||||||
|
return None
|
||||||
|
_require_nonnegative("Evaluated delay", optical_length)
|
||||||
|
contributions.append(optical_length)
|
||||||
|
length = fsum(contributions)
|
||||||
|
return Delay(length, length * evaluator.grid.meters_per_unit / 299_792_458)
|
||||||
147
inire/geometry/catalog_curve.py
Normal file
147
inire/geometry/catalog_curve.py
Normal file
|
|
@ -0,0 +1,147 @@
|
||||||
|
"""Circular and partial Euler centerlines for evaluated catalog geometry."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from functools import lru_cache
|
||||||
|
from math import acos, atan2, ceil, cos, hypot, pi, sin, sqrt, ulp
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
from scipy.integrate import quad
|
||||||
|
from scipy.optimize import brentq
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class CurveSection:
|
||||||
|
"""A tangent angle and a linear curvature ramp over a known arclength."""
|
||||||
|
|
||||||
|
length: float
|
||||||
|
heading: float
|
||||||
|
entry_curvature: float = 0.0
|
||||||
|
exit_curvature: float = 0.0
|
||||||
|
|
||||||
|
def angle(self, fraction: float) -> float:
|
||||||
|
return self.heading + self.length * fraction * (
|
||||||
|
self.entry_curvature + fraction * (self.exit_curvature - self.entry_curvature) / 2
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class BendCurve:
|
||||||
|
radius: float
|
||||||
|
fraction: float
|
||||||
|
sections: tuple[CurveSection, ...]
|
||||||
|
|
||||||
|
|
||||||
|
def _normalized_sections(angle: float, fraction: float) -> tuple[CurveSection, ...]:
|
||||||
|
ramp = angle * fraction
|
||||||
|
plateau = angle * (1 - fraction)
|
||||||
|
candidates = (
|
||||||
|
CurveSection(ramp, 0, 0, 1),
|
||||||
|
CurveSection(plateau, ramp / 2, 1, 1),
|
||||||
|
CurveSection(ramp, angle - ramp / 2, 1, 0),
|
||||||
|
)
|
||||||
|
return tuple(section for section in candidates if section.length > 0)
|
||||||
|
|
||||||
|
|
||||||
|
def _minimum_radius(equivalent_radius: float, angle: float, fraction: float) -> float:
|
||||||
|
if fraction == 0:
|
||||||
|
return equivalent_radius
|
||||||
|
# The curve is symmetric about its mid-tangent. Its chord points in
|
||||||
|
# that direction, so a scalar integral gives the chord length.
|
||||||
|
normalized_chord = sum(
|
||||||
|
section.length * quad(lambda t, section=section: cos(section.angle(t) - angle / 2), 0, 1, epsabs=1e-12)[0]
|
||||||
|
for section in _normalized_sections(angle, fraction)
|
||||||
|
)
|
||||||
|
return 2 * equivalent_radius * sin(angle / 2) / normalized_chord
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache(maxsize=128)
|
||||||
|
def bend_curve(
|
||||||
|
equivalent_radius: float, angle: float, minimum_radius: float, fraction: float | None,
|
||||||
|
) -> BendCurve | None:
|
||||||
|
"""Scale a symmetric unit-curvature bend to the circular endpoint chord."""
|
||||||
|
if minimum_radius > equivalent_radius:
|
||||||
|
return None
|
||||||
|
if fraction is None:
|
||||||
|
if _minimum_radius(equivalent_radius, angle, 1.0) >= minimum_radius:
|
||||||
|
fraction = 1.0
|
||||||
|
elif minimum_radius == equivalent_radius:
|
||||||
|
fraction = 0.0
|
||||||
|
else:
|
||||||
|
fraction = brentq(lambda f: _minimum_radius(equivalent_radius, angle, f) - minimum_radius, 0, 1, xtol=1e-12)
|
||||||
|
radius = _minimum_radius(equivalent_radius, angle, fraction)
|
||||||
|
if radius < minimum_radius * (1 - 1e-12):
|
||||||
|
return None
|
||||||
|
return BendCurve(radius, fraction, tuple(
|
||||||
|
CurveSection(section.length * radius, section.heading, section.entry_curvature / radius, section.exit_curvature / radius)
|
||||||
|
for section in _normalized_sections(angle, fraction)
|
||||||
|
))
|
||||||
|
|
||||||
|
|
||||||
|
def world_sections(curve: BendCurve, heading: float, sign: int) -> tuple[CurveSection, ...]:
|
||||||
|
return tuple(
|
||||||
|
CurveSection(
|
||||||
|
section.length, heading + sign * section.heading, sign * section.entry_curvature, sign * section.exit_curvature,
|
||||||
|
) for section in curve.sections
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def sbend_curve(
|
||||||
|
forward: float,
|
||||||
|
lateral: float,
|
||||||
|
radius: float,
|
||||||
|
minimum_radius: float,
|
||||||
|
fraction: float | None,
|
||||||
|
heading: float,
|
||||||
|
) -> BendCurve | None:
|
||||||
|
"""Fit two opposed lobes and an optional straight at their shared tangent."""
|
||||||
|
offset = abs(lateral)
|
||||||
|
distance = hypot(forward, 2 * radius - offset)
|
||||||
|
roundoff = 16 * ulp(max(forward, offset, radius))
|
||||||
|
if distance < 2 * radius - roundoff:
|
||||||
|
return None
|
||||||
|
angle = atan2(forward, 2 * radius - offset) - acos(min(1.0, 2 * radius / distance))
|
||||||
|
if not 0 < angle <= pi / 2:
|
||||||
|
return None
|
||||||
|
straight = (forward - 2 * radius * sin(angle)) * cos(angle) + (offset - 2 * radius * (1 - cos(angle))) * sin(angle)
|
||||||
|
if straight < -roundoff:
|
||||||
|
return None
|
||||||
|
lobe = bend_curve(radius, angle, minimum_radius, fraction)
|
||||||
|
if lobe is None:
|
||||||
|
return None
|
||||||
|
sign = 1 if lateral > 0 else -1
|
||||||
|
middle_heading = heading + sign * angle
|
||||||
|
middle = (CurveSection(straight, middle_heading),) if straight > roundoff else ()
|
||||||
|
return BendCurve(lobe.radius, lobe.fraction, (
|
||||||
|
*world_sections(lobe, heading, sign), *middle, *world_sections(lobe, middle_heading, -sign),
|
||||||
|
))
|
||||||
|
|
||||||
|
|
||||||
|
_QUADRATURE_NODES, _QUADRATURE_WEIGHTS = np.polynomial.legendre.leggauss(8)
|
||||||
|
|
||||||
|
|
||||||
|
def sample_section(
|
||||||
|
section: CurveSection, start: tuple[float, float], sagitta: float,
|
||||||
|
) -> tuple[np.ndarray, np.ndarray]:
|
||||||
|
"""Sample a curvature section and its normals using bounded angular segments."""
|
||||||
|
curvature = max(abs(section.entry_curvature), abs(section.exit_curvature))
|
||||||
|
if curvature:
|
||||||
|
angle_limit = min(pi / 12, 2 * acos(max(-1.0, 1 - curvature * sagitta)))
|
||||||
|
# The small-sagitta limit of the expression avoids cancellation at 1.
|
||||||
|
if not angle_limit:
|
||||||
|
angle_limit = sqrt(8 * curvature * sagitta)
|
||||||
|
segments = ceil(section.length * curvature / angle_limit)
|
||||||
|
else:
|
||||||
|
segments = 1
|
||||||
|
if segments > 100_000:
|
||||||
|
raise ValueError("Curve sampling requires more than 100000 segments")
|
||||||
|
|
||||||
|
ends = np.linspace(0.0, 1.0, segments + 1)
|
||||||
|
fractions = (ends[:-1, None] + (_QUADRATURE_NODES + 1) / (2 * segments))
|
||||||
|
headings = section.angle(fractions)
|
||||||
|
step = section.length / (2 * segments)
|
||||||
|
delta = step * np.column_stack((np.cos(headings) @ _QUADRATURE_WEIGHTS, np.sin(headings) @ _QUADRATURE_WEIGHTS))
|
||||||
|
positions = np.vstack((start, np.cumsum(delta, axis=0) + start))
|
||||||
|
endpoint_headings = section.angle(ends)
|
||||||
|
normals = np.column_stack((-np.sin(endpoint_headings), np.cos(endpoint_headings)))
|
||||||
|
return positions, normals
|
||||||
227
inire/masque.py
Normal file
227
inire/masque.py
Normal file
|
|
@ -0,0 +1,227 @@
|
||||||
|
"""Route named Masque ports and place the catalog moves selected by Inire."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass, field, replace
|
||||||
|
from math import degrees, isfinite, radians
|
||||||
|
from typing import TYPE_CHECKING, Literal
|
||||||
|
|
||||||
|
from shapely import union_all
|
||||||
|
from shapely.geometry import Polygon
|
||||||
|
|
||||||
|
from inire._catalog import (
|
||||||
|
BendVariant, Catalog, FixedVariant, Grid, Move, MoveEvaluator, Orientation, Pose, Profile, SBendVariant, StraightVariant, TaperVariant,
|
||||||
|
)
|
||||||
|
from inire._catalog_timing import DelayModel, UniaxialGroupIndex
|
||||||
|
from inire.router._catalog_guidance import AutomaticGrid, CoarseGuidance
|
||||||
|
from inire.router._catalog_layout import CatalogNet, LayoutSettings, route_layout
|
||||||
|
from inire.router._catalog_matching import MatchGroup
|
||||||
|
from inire.router._catalog_search import SearchBias
|
||||||
|
from inire.router._catalog_verify import Attachment, _matches_face
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from collections.abc import Mapping, Sequence
|
||||||
|
|
||||||
|
from masque import Pattern, Port
|
||||||
|
from shapely.geometry.base import BaseGeometry
|
||||||
|
|
||||||
|
from inire._catalog import VariantDiagnostic
|
||||||
|
from inire._catalog_timing import Delay
|
||||||
|
from inire.router._catalog_layout import LayoutAttempt
|
||||||
|
from inire.router._catalog_matching import MatchResult
|
||||||
|
from inire.router._catalog_search import SearchResult
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"Attachment",
|
||||||
|
"AutomaticGrid",
|
||||||
|
"BendVariant",
|
||||||
|
"Catalog",
|
||||||
|
"CoarseGuidance",
|
||||||
|
"Connection",
|
||||||
|
"DelayModel",
|
||||||
|
"Endpoint",
|
||||||
|
"FixedVariant",
|
||||||
|
"Grid",
|
||||||
|
"MatchGroup",
|
||||||
|
"Move",
|
||||||
|
"Orientation",
|
||||||
|
"PlacementResult",
|
||||||
|
"Pose",
|
||||||
|
"Profile",
|
||||||
|
"SBendVariant",
|
||||||
|
"SearchBias",
|
||||||
|
"StraightVariant",
|
||||||
|
"TaperVariant",
|
||||||
|
"UniaxialGroupIndex",
|
||||||
|
"route_and_place",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class Endpoint:
|
||||||
|
port: str
|
||||||
|
profile: str
|
||||||
|
attachment: Attachment | None = None
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class Connection:
|
||||||
|
net_id: str
|
||||||
|
source: Endpoint
|
||||||
|
destination: Endpoint
|
||||||
|
seed: tuple[Move, ...] = ()
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class PlacementResult:
|
||||||
|
"""Ordered route results and IDs whose terminals were consumed."""
|
||||||
|
|
||||||
|
catalog_revision: str
|
||||||
|
routes: Mapping[str, SearchResult]
|
||||||
|
placed: tuple[str, ...]
|
||||||
|
delays: Mapping[str, Delay | None] = field(default_factory=dict)
|
||||||
|
matching: Mapping[str, MatchResult] = field(default_factory=dict)
|
||||||
|
grid: Grid | None = None
|
||||||
|
attempts: tuple[LayoutAttempt, ...] = ()
|
||||||
|
unavailable_variants: tuple[VariantDiagnostic, ...] = ()
|
||||||
|
outcome: Literal["complete", "partial", "withheld"] = "complete"
|
||||||
|
|
||||||
|
|
||||||
|
def _port_pose(port: Port, profile: str, heading_tolerance: float) -> Pose:
|
||||||
|
if port.rotation is None or not isfinite(port.rotation) or not all(isfinite(value) for value in port.offset):
|
||||||
|
raise ValueError("Masque routing ports require a finite position and orientation")
|
||||||
|
angle = degrees(port.rotation)
|
||||||
|
heading = round(angle / 45) * 45
|
||||||
|
if abs(angle - heading) > heading_tolerance:
|
||||||
|
raise ValueError(f"Masque routing port heading {angle}° is outside the supported headings")
|
||||||
|
return Pose(round(port.x), round(port.y), heading % 360, profile)
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_connections(
|
||||||
|
layout: Pattern, connections: Sequence[Connection], catalog: Catalog, heading_tolerance: float,
|
||||||
|
) -> dict[str, CatalogNet]:
|
||||||
|
resolved = {}
|
||||||
|
terminals = set()
|
||||||
|
for connection in connections:
|
||||||
|
if not connection.net_id or connection.net_id in resolved:
|
||||||
|
raise ValueError(f"Duplicate or empty routing net ID {connection.net_id!r}")
|
||||||
|
poses = []
|
||||||
|
for endpoint in (connection.source, connection.destination):
|
||||||
|
if endpoint.port in terminals:
|
||||||
|
raise ValueError(f"Duplicate routing terminal {endpoint.port!r}")
|
||||||
|
if endpoint.port not in layout.ports or endpoint.profile not in catalog.profiles:
|
||||||
|
raise ValueError(f"Unknown Masque routing port or profile for {endpoint!r}")
|
||||||
|
pose = _port_pose(layout.ports[endpoint.port], endpoint.profile, heading_tolerance)
|
||||||
|
poses.append(pose)
|
||||||
|
terminals.add(endpoint.port)
|
||||||
|
resolved[connection.net_id] = CatalogNet(
|
||||||
|
poses[0].reversed(), poses[1], connection.source.attachment, connection.destination.attachment, connection.seed,
|
||||||
|
)
|
||||||
|
return resolved
|
||||||
|
|
||||||
|
|
||||||
|
def _resolve_cells(
|
||||||
|
cells: Mapping[str, Pattern],
|
||||||
|
catalog: Catalog,
|
||||||
|
layer: int | tuple[int, int] | str,
|
||||||
|
heading_tolerance: float,
|
||||||
|
face_tolerance: float,
|
||||||
|
) -> Catalog:
|
||||||
|
actual = {}
|
||||||
|
variants = dict(catalog.variants)
|
||||||
|
for variant, spec in catalog.variants.items():
|
||||||
|
if not isinstance(spec, FixedVariant):
|
||||||
|
continue
|
||||||
|
if spec.cell not in cells:
|
||||||
|
raise ValueError(f"Missing Masque routing cell {spec.cell!r}")
|
||||||
|
cell = cells[spec.cell]
|
||||||
|
if spec.cell not in actual:
|
||||||
|
actual[spec.cell] = tuple(Polygon(shape.vertices + shape.offset) for shape in cell.layer_as_polygons(layer, library=cells))
|
||||||
|
shapes = actual[spec.cell]
|
||||||
|
if not shapes or not union_all(spec.footprints).covers(union_all(shapes)):
|
||||||
|
raise ValueError(f"Masque cell {spec.cell!r} has missing geometry or material outside its footprint on this layer")
|
||||||
|
for name, pose in spec.ports.items():
|
||||||
|
port = cell.ports.get(name)
|
||||||
|
if port is None or _port_pose(port, pose.profile, heading_tolerance) != pose:
|
||||||
|
raise ValueError(f"Masque cell {spec.cell!r} has an incompatible routing port {name!r}")
|
||||||
|
if not _matches_face(shapes, pose, catalog.profiles[pose.profile].width, face_tolerance, arrival=False):
|
||||||
|
raise ValueError(f"Masque cell {spec.cell!r} has an incompatible physical face at {name!r}")
|
||||||
|
variants[variant] = replace(spec, port_shapes=shapes)
|
||||||
|
return replace(catalog, variants=variants)
|
||||||
|
|
||||||
|
|
||||||
|
def route_and_place(
|
||||||
|
layout: Pattern,
|
||||||
|
cells: Mapping[str, Pattern],
|
||||||
|
connections: Sequence[Connection],
|
||||||
|
*,
|
||||||
|
catalog: Catalog,
|
||||||
|
grid: Grid | AutomaticGrid,
|
||||||
|
board: Polygon,
|
||||||
|
layer: int | tuple[int, int] | str,
|
||||||
|
keepouts: Sequence[BaseGeometry] = (),
|
||||||
|
clearance: float = 0.0,
|
||||||
|
self_clearance: float = 0.0,
|
||||||
|
face_tolerance: float = 0.0,
|
||||||
|
heading_tolerance: float = 1e-6,
|
||||||
|
node_limit: int = 1000,
|
||||||
|
require_complete: bool = False,
|
||||||
|
timing: DelayModel | None = None,
|
||||||
|
match_groups: Sequence[MatchGroup] = (),
|
||||||
|
tuning_windows: Mapping[str, Polygon] | None = None,
|
||||||
|
tuning_proposal_limit: int = 2000,
|
||||||
|
refinement: bool = True,
|
||||||
|
guidance: CoarseGuidance | None = None,
|
||||||
|
refinement_node_limit: int = 64,
|
||||||
|
retry_independent: bool = True,
|
||||||
|
search_bias: SearchBias | None = None,
|
||||||
|
) -> PlacementResult:
|
||||||
|
"""Route in the Pattern's layout units and consume both named ports for each placed net."""
|
||||||
|
if not isfinite(heading_tolerance) or not 0 <= heading_tolerance < 22.5:
|
||||||
|
raise ValueError("Heading tolerance must be finite and in [0°, 22.5°)")
|
||||||
|
catalog = _resolve_cells(cells, catalog, layer, heading_tolerance, face_tolerance)
|
||||||
|
resolved = _resolve_connections(layout, connections, catalog, heading_tolerance)
|
||||||
|
if isinstance(grid, AutomaticGrid):
|
||||||
|
grid = grid.select(tuple(pose for net in resolved.values() for pose in (net.start, net.target)), catalog)
|
||||||
|
evaluator = MoveEvaluator(grid, catalog)
|
||||||
|
|
||||||
|
result = route_layout(
|
||||||
|
evaluator, resolved,
|
||||||
|
LayoutSettings(
|
||||||
|
board, keepouts, clearance, self_clearance, face_tolerance, node_limit,
|
||||||
|
tuning_proposal_limit, refinement, guidance, refinement_node_limit, retry_independent, search_bias,
|
||||||
|
),
|
||||||
|
timing=timing, groups=match_groups, windows=tuning_windows, require_complete=require_complete,
|
||||||
|
)
|
||||||
|
if require_complete and len(result.completed) != len(connections):
|
||||||
|
return PlacementResult(
|
||||||
|
catalog.revision, result.routes, (), result.delays, result.matching, grid, result.attempts, evaluator.unavailable, "withheld",
|
||||||
|
)
|
||||||
|
completed = set(result.completed)
|
||||||
|
|
||||||
|
placed = []
|
||||||
|
for connection in connections:
|
||||||
|
if connection.net_id not in completed:
|
||||||
|
continue
|
||||||
|
path = result.routes[connection.net_id].path
|
||||||
|
assert path is not None
|
||||||
|
for move in path:
|
||||||
|
if move.placement is None:
|
||||||
|
for shape in move.footprints:
|
||||||
|
layout.polygon(layer, vertices=shape.exterior.coords[:-1])
|
||||||
|
else:
|
||||||
|
spec = catalog.variants[move.move.variant]
|
||||||
|
assert isinstance(spec, FixedVariant)
|
||||||
|
placement = move.placement
|
||||||
|
layout.ref(
|
||||||
|
spec.cell, offset=(placement.x, placement.y), rotation=radians(placement.orientation.rotation),
|
||||||
|
mirrored=placement.orientation.reflected,
|
||||||
|
)
|
||||||
|
del layout.ports[connection.source.port]
|
||||||
|
del layout.ports[connection.destination.port]
|
||||||
|
placed.append(connection.net_id)
|
||||||
|
|
||||||
|
return PlacementResult(
|
||||||
|
catalog.revision, result.routes, tuple(placed), result.delays, result.matching, grid, result.attempts, evaluator.unavailable,
|
||||||
|
"complete" if len(placed) == len(connections) else "partial",
|
||||||
|
)
|
||||||
|
|
@ -125,9 +125,11 @@ class SearchOptions(_SearchOptionsCache):
|
||||||
proximity_range: float = 10.0
|
proximity_range: float = 10.0
|
||||||
bend_physical_length: float | None = None
|
bend_physical_length: float | None = None
|
||||||
distance_heuristic_weight: float = 1.0
|
distance_heuristic_weight: float = 1.0
|
||||||
|
terminal_jog_limit: int = 0
|
||||||
|
|
||||||
def __post_init__(self) -> None:
|
def __post_init__(self) -> None:
|
||||||
_require_budget("node_limit", self.node_limit)
|
_require_budget("node_limit", self.node_limit)
|
||||||
|
_require_budget("terminal_jog_limit", self.terminal_jog_limit)
|
||||||
_require_nonnegative("greedy_h_weight", self.greedy_h_weight)
|
_require_nonnegative("greedy_h_weight", self.greedy_h_weight)
|
||||||
_require_nonnegative("distance_heuristic_weight", self.distance_heuristic_weight)
|
_require_nonnegative("distance_heuristic_weight", self.distance_heuristic_weight)
|
||||||
if not isfinite(self.proximity_range) or self.proximity_range <= 0:
|
if not isfinite(self.proximity_range) or self.proximity_range <= 0:
|
||||||
|
|
|
||||||
|
|
@ -3,11 +3,9 @@ from __future__ import annotations
|
||||||
import heapq
|
import heapq
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
from shapely.geometry import Polygon
|
|
||||||
|
|
||||||
from inire.constants import TOLERANCE_LINEAR
|
from inire.constants import TOLERANCE_LINEAR
|
||||||
from inire.geometry.component_overlap import components_overlap
|
from inire.geometry.component_overlap import components_overlap
|
||||||
from inire.geometry.components import build_component, check_component_endpoint, uses_custom_outline
|
from inire.geometry.components import check_component_endpoint, uses_custom_outline
|
||||||
from inire.geometry.primitives import Port
|
from inire.geometry.primitives import Port
|
||||||
from inire.router.refiner import component_hits_ancestor_chain
|
from inire.router.refiner import component_hits_ancestor_chain
|
||||||
|
|
||||||
|
|
@ -33,11 +31,7 @@ def process_move(
|
||||||
params: tuple,
|
params: tuple,
|
||||||
) -> None:
|
) -> None:
|
||||||
cp = parent.port
|
cp = parent.port
|
||||||
coll_type = config.bend_collision_type
|
evaluator = config.evaluator
|
||||||
coll_key = id(coll_type) if isinstance(coll_type, Polygon) else coll_type
|
|
||||||
physical_type = config.bend_physical_geometry
|
|
||||||
physical_key = id(physical_type) if isinstance(physical_type, Polygon) else physical_type
|
|
||||||
search = context.options.search
|
|
||||||
template = None
|
template = None
|
||||||
if move_class == "sbend" and config.sbend_templates:
|
if move_class == "sbend" and config.sbend_templates:
|
||||||
template = config.sbend_templates.get(params)
|
template = config.sbend_templates.get(params)
|
||||||
|
|
@ -46,32 +40,17 @@ def process_move(
|
||||||
outline = template.polygon if template else None
|
outline = template.polygon if template else None
|
||||||
self_dilation = context.cost_evaluator.collision_engine.clearance / 2.0
|
self_dilation = context.cost_evaluator.collision_engine.clearance / 2.0
|
||||||
|
|
||||||
abs_key = (
|
local_settings = (
|
||||||
cp.as_tuple(),
|
move_class, params, net_width, *evaluator.cache_settings(),
|
||||||
move_class,
|
id(outline) if outline is not None else None, template.length if template is not None else None, self_dilation,
|
||||||
params,
|
|
||||||
net_width,
|
|
||||||
coll_key,
|
|
||||||
physical_key,
|
|
||||||
id(outline) if outline is not None else None,
|
|
||||||
self_dilation,
|
|
||||||
)
|
)
|
||||||
|
abs_key = (cp.as_tuple(), *local_settings)
|
||||||
if abs_key in context.move_cache_abs:
|
if abs_key in context.move_cache_abs:
|
||||||
context.metrics.total_move_cache_abs_hits += 1
|
context.metrics.total_move_cache_abs_hits += 1
|
||||||
res = context.move_cache_abs[abs_key]
|
res = context.move_cache_abs[abs_key]
|
||||||
else:
|
else:
|
||||||
context.metrics.total_move_cache_abs_misses += 1
|
context.metrics.total_move_cache_abs_misses += 1
|
||||||
base_port = Port(0, 0, cp.r)
|
rel_key = (cp.r, *local_settings)
|
||||||
rel_key = (
|
|
||||||
cp.r,
|
|
||||||
move_class,
|
|
||||||
params,
|
|
||||||
net_width,
|
|
||||||
coll_key,
|
|
||||||
physical_key,
|
|
||||||
id(outline) if outline is not None else None,
|
|
||||||
self_dilation,
|
|
||||||
)
|
|
||||||
if rel_key in context.move_cache_rel:
|
if rel_key in context.move_cache_rel:
|
||||||
context.metrics.total_move_cache_rel_hits += 1
|
context.metrics.total_move_cache_rel_hits += 1
|
||||||
res_rel = context.move_cache_rel[rel_key]
|
res_rel = context.move_cache_rel[rel_key]
|
||||||
|
|
@ -80,20 +59,9 @@ def process_move(
|
||||||
try:
|
try:
|
||||||
board = context.cost_evaluator.collision_engine.board
|
board = context.cost_evaluator.collision_engine.board
|
||||||
# Reject generated bends that overshoot before tessellating them.
|
# Reject generated bends that overshoot before tessellating them.
|
||||||
if board is not None and move_class != "straight" and not uses_custom_outline(move_class, physical_type, outline):
|
if board is not None and move_class != "straight" and not uses_custom_outline(move_class, evaluator.physical_geometry, outline):
|
||||||
check_component_endpoint(cp, move_class, params, board.bounds)
|
check_component_endpoint(cp, move_class, params, board.bounds)
|
||||||
res_rel = build_component(
|
res_rel = evaluator.evaluate(Port(0, 0, cp.r), net_width, move_class, params, self_dilation, template)
|
||||||
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,
|
|
||||||
sbend_outline=outline,
|
|
||||||
physical_length=search.bend_physical_length if move_class == "bend90" else (template.length if template else None),
|
|
||||||
)
|
|
||||||
except ValueError:
|
except ValueError:
|
||||||
return
|
return
|
||||||
context.cache_move(rel_key, res_rel, relative=True)
|
context.cache_move(rel_key, res_rel, relative=True)
|
||||||
|
|
|
||||||
|
|
@ -308,7 +308,7 @@ def expand_moves(
|
||||||
angle_to_target = float((round((180.0 / math.pi) * math.atan2(dy_t, dx_t)) + 360.0) % 360.0)
|
angle_to_target = float((round((180.0 / math.pi) * math.atan2(dy_t, dx_t)) + 360.0) % 360.0)
|
||||||
prefer_toward_target = deferred_turns is not None and not config.restrict_to_corridor and dist_sq >= 150 * 150
|
prefer_toward_target = deferred_turns is not None and not config.restrict_to_corridor and dist_sq >= 150 * 150
|
||||||
|
|
||||||
circular_bend = bend90_uses_circular_geometry(config.bend_collision_type, config.bend_physical_geometry)
|
circular_bend = bend90_uses_circular_geometry(config.evaluator.collision_type, config.evaluator.physical_geometry)
|
||||||
for radius in search_options.bend_radii:
|
for radius in search_options.bend_radii:
|
||||||
if circular_bend and not bend_fits_width(radius, net_width):
|
if circular_bend and not bend_fits_width(radius, net_width):
|
||||||
continue
|
continue
|
||||||
|
|
|
||||||
|
|
@ -5,14 +5,15 @@ from dataclasses import dataclass, field
|
||||||
from operator import attrgetter
|
from operator import attrgetter
|
||||||
from typing import TYPE_CHECKING, get_type_hints
|
from typing import TYPE_CHECKING, get_type_hints
|
||||||
|
|
||||||
from inire.model import resolve_bend_geometry
|
|
||||||
from inire.results import RouteMetrics
|
from inire.results import RouteMetrics
|
||||||
from inire.router.visibility import VisibilityManager
|
from inire.router.visibility import VisibilityManager
|
||||||
|
|
||||||
|
from ._move_evaluation import LegacyMoveEvaluator
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from collections.abc import Callable
|
from collections.abc import Callable
|
||||||
|
|
||||||
from inire.geometry.components import BendCollisionModel, BendPhysicalGeometry, ComponentResult
|
from inire.geometry.components import BendCollisionModel, ComponentResult
|
||||||
from inire.geometry.primitives import Port
|
from inire.geometry.primitives import Port
|
||||||
from inire.model import RoutingOptions, RoutingProblem, SBendOutline
|
from inire.model import RoutingOptions, RoutingProblem, SBendOutline
|
||||||
from inire.router._topology import Corridor
|
from inire.router._topology import Corridor
|
||||||
|
|
@ -81,9 +82,7 @@ class CongestionCaches:
|
||||||
|
|
||||||
@dataclass(frozen=True, slots=True)
|
@dataclass(frozen=True, slots=True)
|
||||||
class SearchRunConfig:
|
class SearchRunConfig:
|
||||||
bend_collision_type: BendCollisionModel
|
evaluator: LegacyMoveEvaluator
|
||||||
bend_physical_geometry: BendPhysicalGeometry
|
|
||||||
bend_clip_margin: float | None
|
|
||||||
node_limit: int
|
node_limit: int
|
||||||
guidance_seed: tuple[PathSegmentSeed, ...] | None = None
|
guidance_seed: tuple[PathSegmentSeed, ...] | None = None
|
||||||
guidance_bonus: float = 0.0
|
guidance_bonus: float = 0.0
|
||||||
|
|
@ -133,14 +132,8 @@ class SearchRunConfig:
|
||||||
expired: Callable[[], bool] | None = None,
|
expired: Callable[[], bool] | None = None,
|
||||||
) -> SearchRunConfig:
|
) -> SearchRunConfig:
|
||||||
search = options.search
|
search = options.search
|
||||||
bend_collision_type, bend_physical_geometry = resolve_bend_geometry(
|
|
||||||
search,
|
|
||||||
bend_collision_override=bend_collision_type,
|
|
||||||
)
|
|
||||||
return cls(
|
return cls(
|
||||||
bend_collision_type=bend_collision_type,
|
evaluator=LegacyMoveEvaluator.from_options(search, collision_override=bend_collision_type),
|
||||||
bend_physical_geometry=bend_physical_geometry,
|
|
||||||
bend_clip_margin=search.bend_clip_margin,
|
|
||||||
node_limit=search.node_limit if node_limit is None else node_limit,
|
node_limit=search.node_limit if node_limit is None else node_limit,
|
||||||
guidance_seed=guidance_seed,
|
guidance_seed=guidance_seed,
|
||||||
guidance_bonus=float(guidance_bonus),
|
guidance_bonus=float(guidance_bonus),
|
||||||
|
|
|
||||||
|
|
@ -5,20 +5,25 @@ from __future__ import annotations
|
||||||
from contextlib import contextmanager, suppress
|
from contextlib import contextmanager, suppress
|
||||||
from dataclasses import replace
|
from dataclasses import replace
|
||||||
from functools import partial
|
from functools import partial
|
||||||
|
from heapq import nsmallest
|
||||||
from itertools import chain, islice, pairwise
|
from itertools import chain, islice, pairwise
|
||||||
|
from math import sqrt
|
||||||
from time import perf_counter
|
from time import perf_counter
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
import shapely
|
import shapely
|
||||||
from shapely.geometry import box
|
from shapely.geometry import LineString, box
|
||||||
|
from shapely.strtree import STRtree
|
||||||
|
|
||||||
from inire.geometry.collision import RoutingWorld, _violates_net_clearance
|
from inire.geometry.collision import RoutingWorld, _violates_net_clearance
|
||||||
from inire.model import FixedRoute, resolve_bend_geometry
|
from inire.model import FixedRoute, resolve_bend_geometry
|
||||||
from inire.results import AutomaticRoutingReport, RoutingStage, RoutingTiming, _planner_for_mode
|
from inire.results import AutomaticRoutingReport, RoutingStage, RoutingTiming, _planner_for_mode
|
||||||
|
from inire.router._astar_types import AStarMetrics
|
||||||
from inire.router._bundle import ordered_bundle_terminal_headings, plan_ordered_bundle
|
from inire.router._bundle import ordered_bundle_terminal_headings, plan_ordered_bundle
|
||||||
from inire.router._capacity import cut_capacity, port_conflicts
|
from inire.router._capacity import cut_capacity, port_conflicts
|
||||||
from inire.router._columns import (
|
from inire.router._columns import (
|
||||||
column_jog_candidates, column_partition_budget_exceeded, column_recovery_candidates, column_recovery_subproblems, column_seed_candidates,
|
column_jog_candidates, column_partition_budget_exceeded, column_recovery_candidates, column_recovery_subproblems, column_seed_candidates,
|
||||||
|
straight_column_shortcuts,
|
||||||
)
|
)
|
||||||
from inire.router._compact import compact_port_seed_set, short_shift_seed_set
|
from inire.router._compact import compact_port_seed_set, short_shift_seed_set
|
||||||
from inire.router._perimeter import (
|
from inire.router._perimeter import (
|
||||||
|
|
@ -26,6 +31,7 @@ from inire.router._perimeter import (
|
||||||
perimeter_detour_candidates,
|
perimeter_detour_candidates,
|
||||||
residual_dogleg_candidates,
|
residual_dogleg_candidates,
|
||||||
terminal_link_seed,
|
terminal_link_seed,
|
||||||
|
terminal_offset_seeds,
|
||||||
)
|
)
|
||||||
from inire.router._route_traces import complete_final_conflict_trace
|
from inire.router._route_traces import complete_final_conflict_trace
|
||||||
from inire.router._routing_policy import (
|
from inire.router._routing_policy import (
|
||||||
|
|
@ -40,9 +46,10 @@ from inire.router._routing_policy import (
|
||||||
)
|
)
|
||||||
from inire.router._seed_materialization import materialize_path_seed, seed_preparation_error
|
from inire.router._seed_materialization import materialize_path_seed, seed_preparation_error
|
||||||
from inire.router._stack import RoutingAttempts
|
from inire.router._stack import RoutingAttempts
|
||||||
|
from inire.router._weighted_local import improve_weighted_windows
|
||||||
from inire.router.cost import build_native_cost_evaluator, weighted_path_length
|
from inire.router.cost import build_native_cost_evaluator, weighted_path_length
|
||||||
from inire.router.refiner import PathRefiner
|
from inire.router.refiner import PathRefiner
|
||||||
from inire.seeds import SBendSeed
|
from inire.seeds import PathSeed, SBendSeed, StraightSeed
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from collections.abc import Callable, Iterable, Iterator
|
from collections.abc import Callable, Iterable, Iterator
|
||||||
|
|
@ -54,7 +61,6 @@ if TYPE_CHECKING:
|
||||||
from inire.results import RoutingOperation, RoutingResult, RoutingRunResult
|
from inire.results import RoutingOperation, RoutingResult, RoutingRunResult
|
||||||
from inire.router._routing_policy import Trial
|
from inire.router._routing_policy import Trial
|
||||||
from inire.router.cost import CostEvaluator
|
from inire.router.cost import CostEvaluator
|
||||||
from inire.seeds import PathSeed
|
|
||||||
|
|
||||||
_Footprint = tuple[PathSeed, BaseGeometry]
|
_Footprint = tuple[PathSeed, BaseGeometry]
|
||||||
_PerimeterPair = tuple[_Footprint, _Footprint]
|
_PerimeterPair = tuple[_Footprint, _Footprint]
|
||||||
|
|
@ -63,6 +69,8 @@ if TYPE_CHECKING:
|
||||||
_INITIAL_NODE_LIMIT = 500
|
_INITIAL_NODE_LIMIT = 500
|
||||||
_NEAR_PORT_NODE_LIMIT = 100
|
_NEAR_PORT_NODE_LIMIT = 100
|
||||||
_NEAR_PORT_ITERATION_LIMIT = 2
|
_NEAR_PORT_ITERATION_LIMIT = 2
|
||||||
|
_COLUMN_SHORTCUT_LIMIT = 4
|
||||||
|
_PORT_CAPACITY_JOG_LIMIT = 12
|
||||||
|
|
||||||
|
|
||||||
def _has_fragmented_shifts(trial: Trial) -> bool:
|
def _has_fragmented_shifts(trial: Trial) -> bool:
|
||||||
|
|
@ -255,14 +263,40 @@ class _AutomaticRun:
|
||||||
if len(trials[-1].valid_costs) == len(problem.nets):
|
if len(trials[-1].valid_costs) == len(problem.nets):
|
||||||
return trials, tuple(rejections)
|
return trials, tuple(rejections)
|
||||||
|
|
||||||
|
policy = options.topology.automatic_cost
|
||||||
|
jogs_tried = False
|
||||||
|
if policy == "selective" and (bound := self._column_s_bend_bound()) is not None:
|
||||||
|
jogs_tried = True
|
||||||
|
if self._try_column_jogs(options, trials, len(problem.nets)):
|
||||||
|
self.cost_pass_performed = True
|
||||||
|
if sum(trials[-1].valid_costs.values()) <= bound:
|
||||||
|
return trials, tuple(rejections)
|
||||||
|
|
||||||
span_trial = self._column_trial(False, trials, problem=problem)
|
span_trial = self._column_trial(False, trials, problem=problem)
|
||||||
if span_trial is None:
|
if span_trial is None:
|
||||||
rejections.append("Span scoring found no verified column layout")
|
rejections.append("Span scoring found no verified column layout")
|
||||||
policy = options.topology.automatic_cost
|
|
||||||
if policy == "always" or (policy == "selective" and span_trial is not None and _has_fragmented_shifts(span_trial)):
|
if policy == "always" or (policy == "selective" and span_trial is not None and _has_fragmented_shifts(span_trial)):
|
||||||
self.cost_pass_performed = True
|
self.cost_pass_performed = True
|
||||||
if self._column_trial(True, trials, problem=problem) is None:
|
if self._column_trial(True, trials, problem=problem) is None:
|
||||||
rejections.append("Cost scoring found no verified column layout")
|
rejections.append("Cost scoring found no verified column layout")
|
||||||
|
if (
|
||||||
|
policy != "never" and not jogs_tried and span_trial is not None and self.length_weights is not None
|
||||||
|
and self.length_weights["sbend"] > self.length_weights["bend90"]
|
||||||
|
):
|
||||||
|
chained = any(
|
||||||
|
first.move_type == second.move_type == "sbend"
|
||||||
|
for net_id in span_trial.valid_costs
|
||||||
|
for first, second in pairwise(span_trial.run.results_by_net[net_id].path)
|
||||||
|
)
|
||||||
|
# A quarter-turn layout can replace chains of S-bends. When
|
||||||
|
# neighboring columns have no room for a jog, plan their shared
|
||||||
|
# apertures as a single column to try the cheaper turn family.
|
||||||
|
if chained or any(
|
||||||
|
move.move_type == "sbend"
|
||||||
|
for net_id in span_trial.valid_costs for move in span_trial.run.results_by_net[net_id].path
|
||||||
|
):
|
||||||
|
found = self._try_column_jogs(options, trials, len(problem.nets), merge_close=not chained)
|
||||||
|
self.cost_pass_performed |= chained or found
|
||||||
if not trials or len(_best_trial(trials).valid_costs) < len(problem.nets):
|
if not trials or len(_best_trial(trials).valid_costs) < len(problem.nets):
|
||||||
planner = "local-sbend"
|
planner = "local-sbend"
|
||||||
with self._time("plan", planner=planner):
|
with self._time("plan", planner=planner):
|
||||||
|
|
@ -283,6 +317,27 @@ class _AutomaticRun:
|
||||||
rejections.append("Local S-bend layout failed full verification")
|
rejections.append("Local S-bend layout failed full verification")
|
||||||
return trials, tuple(rejections)
|
return trials, tuple(rejections)
|
||||||
|
|
||||||
|
def _column_s_bend_bound(self) -> float | None:
|
||||||
|
weights = self.length_weights
|
||||||
|
radii = self.options.search.bend_radii
|
||||||
|
if (
|
||||||
|
weights is None or weights["sbend"] <= max(weights["bend90"], weights["straight"])
|
||||||
|
or not radii or not self.problem._blocking_polygons or self.problem.initial_paths
|
||||||
|
):
|
||||||
|
return None
|
||||||
|
nets = self.problem.nets
|
||||||
|
if len(nets) < 3 or any(net.start.r != net.target.r or net.start.r not in (0, 180) for net in nets):
|
||||||
|
return None
|
||||||
|
lateral = sum(abs(net.target.y - net.start.y) for net in nets)
|
||||||
|
if lateral < 2 * min(radii) * len(nets):
|
||||||
|
return None
|
||||||
|
# A horizontal straight pays for x displacement. An S-bend's
|
||||||
|
# Euclidean length pays for both displacements under this projection.
|
||||||
|
straight, sbend = weights["straight"], weights["sbend"]
|
||||||
|
side = sbend * sqrt(1 - (straight / sbend) ** 2)
|
||||||
|
forward = sum(abs(net.target.x - net.start.x) for net in nets)
|
||||||
|
return straight * forward + side * lateral
|
||||||
|
|
||||||
def _column_trial(self, weighted: bool, trials: list[Trial], *, problem: RoutingProblem) -> Trial | None:
|
def _column_trial(self, weighted: bool, trials: list[Trial], *, problem: RoutingProblem) -> Trial | None:
|
||||||
objective = self.options.objective
|
objective = self.options.objective
|
||||||
weights = self.length_weights or dict.fromkeys(("straight", "bend90", "sbend"), objective.unit_length_cost)
|
weights = self.length_weights or dict.fromkeys(("straight", "bend90", "sbend"), objective.unit_length_cost)
|
||||||
|
|
@ -535,12 +590,12 @@ class _AutomaticRun:
|
||||||
run = self._run(problem, options=guide, policy=policy)
|
run = self._run(problem, options=guide, policy=policy)
|
||||||
return self._trial(run, RoutingStage("guide", (), run.metrics.nodes_expanded, guide.search.node_limit, policy=policy))
|
return self._trial(run, RoutingStage("guide", (), run.metrics.nodes_expanded, guide.search.node_limit, policy=policy))
|
||||||
|
|
||||||
def _try_column_jogs(self, options: RoutingOptions, trials: list[Trial], target: int) -> bool:
|
def _try_column_jogs(self, options: RoutingOptions, trials: list[Trial], target: int, *, merge_close: bool = False) -> bool:
|
||||||
problem = self.problem
|
problem = self.problem
|
||||||
if target != len(problem.nets) or problem.initial_paths:
|
if target != len(problem.nets) or problem.initial_paths:
|
||||||
return False
|
return False
|
||||||
with self._time("plan", planner="column-jogs"):
|
with self._time("plan", planner="column-jogs"):
|
||||||
for seeds in column_jog_candidates(problem, options.search, limit_per_pass=8):
|
for seeds in column_jog_candidates(problem, options.search, limit_per_pass=8, merge_close=merge_close):
|
||||||
trial = self._verify(replace(problem, initial_paths=seeds), "column-jogs")
|
trial = self._verify(replace(problem, initial_paths=seeds), "column-jogs")
|
||||||
if len(trial.valid_costs) == target:
|
if len(trial.valid_costs) == target:
|
||||||
trials.append(trial)
|
trials.append(trial)
|
||||||
|
|
@ -707,6 +762,35 @@ class _AutomaticRun:
|
||||||
)
|
)
|
||||||
trials.append(self._trial(run, stage))
|
trials.append(self._trial(run, stage))
|
||||||
|
|
||||||
|
def _try_weighted_detour(self, trials: list[Trial]) -> None:
|
||||||
|
problem, options, weights = self.problem, self.options, self.length_weights
|
||||||
|
if (
|
||||||
|
len(problem.nets) != 1 or problem.initial_paths or not problem._blocking_polygons
|
||||||
|
or options.topology.automatic_cost == "never" or weights is None
|
||||||
|
or weights["sbend"] <= weights["bend90"] or not options.search.bend_radii
|
||||||
|
):
|
||||||
|
return
|
||||||
|
incumbent = _best_trial(trials)
|
||||||
|
(net,) = problem.nets
|
||||||
|
if net.net_id not in incumbent.valid_costs:
|
||||||
|
return
|
||||||
|
path = incumbent.run.results_by_net[net.net_id].path
|
||||||
|
if not any(move.move_type == "sbend" for move in path):
|
||||||
|
return
|
||||||
|
link = terminal_link_seed(net, options.search)
|
||||||
|
if link is None or not isinstance(link.segments[0], StraightSeed):
|
||||||
|
return
|
||||||
|
|
||||||
|
planner = "terminal-detour"
|
||||||
|
with self._time("plan", planner=planner, policy="weighted"):
|
||||||
|
self.cost_pass_performed = True
|
||||||
|
world = RoutingWorld.from_problem(problem, board=self.board)
|
||||||
|
for seed in islice(terminal_offset_seeds(net, options.search, world), 4):
|
||||||
|
trial = self._verify(replace(problem, initial_paths={net.net_id: seed}), planner, policy="weighted")
|
||||||
|
trials.append(trial)
|
||||||
|
if trial.improves_on(incumbent):
|
||||||
|
break
|
||||||
|
|
||||||
def _refine(self, trials: list[Trial]) -> Trial | None:
|
def _refine(self, trials: list[Trial]) -> Trial | None:
|
||||||
best = _best_trial(trials)
|
best = _best_trial(trials)
|
||||||
if not self.options.refinement.enabled or not any(
|
if not self.options.refinement.enabled or not any(
|
||||||
|
|
@ -740,6 +824,130 @@ class _AutomaticRun:
|
||||||
|
|
||||||
return refined if cost(refined) < cost(best) else best
|
return refined if cost(refined) < cost(best) else best
|
||||||
|
|
||||||
|
def _try_weighted_shortcuts(self, trials: list[Trial]) -> None:
|
||||||
|
problem, options, weights = self.problem, self.options, self.length_weights
|
||||||
|
if weights is None or options.topology.automatic_cost == "never" or problem.initial_paths:
|
||||||
|
return
|
||||||
|
incumbent = _best_trial(trials)
|
||||||
|
if incumbent.stage.planner != "column" or len(incumbent.valid_costs) != len(problem.nets):
|
||||||
|
return
|
||||||
|
|
||||||
|
planner = "straight-shortcuts"
|
||||||
|
with self._time("plan", planner=planner, policy="weighted"):
|
||||||
|
results = dict(incumbent.run.results_by_net)
|
||||||
|
blockers = None
|
||||||
|
occupied = None
|
||||||
|
owners: tuple[str, ...] = ()
|
||||||
|
world = None
|
||||||
|
metrics = AStarMetrics()
|
||||||
|
changed = False
|
||||||
|
|
||||||
|
def rank(window: tuple[float, int, int]) -> tuple[float, int, int]:
|
||||||
|
saving, begin, end = window
|
||||||
|
return -saving, begin, end
|
||||||
|
|
||||||
|
for net in problem.nets:
|
||||||
|
result = results[net.net_id]
|
||||||
|
path = result.path
|
||||||
|
windows = straight_column_shortcuts(path, weights)
|
||||||
|
for _, begin, end in nsmallest(_COLUMN_SHORTCUT_LIMIT, windows, key=rank):
|
||||||
|
start, finish = path[begin].start_port, path[end - 1].end_port
|
||||||
|
if blockers is None:
|
||||||
|
blockers = STRtree(problem._blocking_polygons)
|
||||||
|
axis = LineString(((start.x, start.y), (finish.x, finish.y)))
|
||||||
|
# A centerline crossing a keepout cannot carry a straight
|
||||||
|
# of any width. Exact replay handles clearance and peers.
|
||||||
|
if len(blockers.query(axis, predicate="crosses")):
|
||||||
|
continue
|
||||||
|
if occupied is None:
|
||||||
|
shapes = [(other.net_id, shape) for other in results.values() for shape in other.locked_geometry]
|
||||||
|
owners = tuple(owner for owner, _ in shapes)
|
||||||
|
occupied = STRtree([shape for _, shape in shapes])
|
||||||
|
if any(owners[index] != net.net_id for index in occupied.query(axis, predicate="intersects")):
|
||||||
|
continue
|
||||||
|
seed = PathSeed((StraightSeed(abs(finish.x - start.x)),))
|
||||||
|
straight = materialize_path_seed(
|
||||||
|
seed, start=start, net_width=net.width, search=options.search, clearance=problem.clearance, bounds=problem.bounds,
|
||||||
|
)
|
||||||
|
if straight is None or straight[-1].end_port != finish:
|
||||||
|
continue
|
||||||
|
# The rest of this path was checked when it was installed.
|
||||||
|
# Only the replacement can add a collision with a peer.
|
||||||
|
if any(
|
||||||
|
owners[index] != net.net_id and _violates_net_clearance(shape, occupied.geometries[index], problem.clearance)
|
||||||
|
for shape in straight[0].physical_geometry
|
||||||
|
for index in occupied.query(shape, predicate="dwithin", distance=problem.clearance)
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
if world is None:
|
||||||
|
world = RoutingWorld.from_problem(problem, use_dynamic_grid=False)
|
||||||
|
world.metrics = metrics
|
||||||
|
candidate = (*path[:begin], *straight, *path[end:])
|
||||||
|
report = world.verify_path_report(net.net_id, candidate)
|
||||||
|
if report.is_valid:
|
||||||
|
results[net.net_id] = replace(result, path=candidate, report=report)
|
||||||
|
occupied = None
|
||||||
|
changed = True
|
||||||
|
break
|
||||||
|
self.attempts.samples.append(metrics.snapshot())
|
||||||
|
if changed:
|
||||||
|
self.cost_pass_performed = True
|
||||||
|
stage = RoutingStage("off", (), 0, 0, kind="column-shortcuts", planner=planner, policy="weighted", operation="verify")
|
||||||
|
trials.append(self._trial(replace(incumbent.run, results_by_net=results), stage).as_replacement_for(incumbent))
|
||||||
|
|
||||||
|
def _try_port_capacity(self, conflicts: tuple[tuple[str, str], ...], target: int) -> Trial | None:
|
||||||
|
"""Try to reach the certified coverage limit with verified terminal links."""
|
||||||
|
problem, search = self.problem, self.options.search
|
||||||
|
if problem.initial_paths or not search.bend_radii:
|
||||||
|
return None
|
||||||
|
reserved = {net: peer for a, b in conflicts for net, peer in ((a, b), (b, a))}
|
||||||
|
planner = "port-capacity"
|
||||||
|
with self._time("plan", planner=planner):
|
||||||
|
world = RoutingWorld.from_problem(problem, use_dynamic_grid=False)
|
||||||
|
seeds = {}
|
||||||
|
for net in problem.nets:
|
||||||
|
if reserved.get(net.net_id) in seeds:
|
||||||
|
continue
|
||||||
|
link = terminal_link_seed(net, search)
|
||||||
|
jogs = islice(terminal_offset_seeds(net, search, world), _PORT_CAPACITY_JOG_LIMIT)
|
||||||
|
for seed in chain((link,) if link is not None else (), jogs):
|
||||||
|
path = materialize_path_seed(
|
||||||
|
seed, start=net.start, net_width=net.width, search=search, clearance=problem.clearance, bounds=problem.bounds,
|
||||||
|
)
|
||||||
|
if path and path[-1].end_port == net.target and world.verify_path_report(net.net_id, path).is_valid:
|
||||||
|
world.add_route(net.net_id, path)
|
||||||
|
seeds[net.net_id] = seed
|
||||||
|
break
|
||||||
|
if len(seeds) == target:
|
||||||
|
trial = self._verify(replace(problem, initial_paths=seeds), planner)
|
||||||
|
return trial if len(trial.valid_costs) == target else None
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _try_weighted_windows(self, trials: list[Trial]) -> None:
|
||||||
|
options, weights = self.options, self.length_weights
|
||||||
|
if (
|
||||||
|
weights is None or options.topology.automatic_cost == "never"
|
||||||
|
or self.problem.initial_paths or options.refinement.objective is not None
|
||||||
|
or options.search.bend_physical_length is not None
|
||||||
|
):
|
||||||
|
return
|
||||||
|
incumbent = _best_trial(trials)
|
||||||
|
planner = "weighted-windows"
|
||||||
|
with self._time("refine", planner=planner):
|
||||||
|
changes, metrics = improve_weighted_windows(
|
||||||
|
self.problem, options, incumbent.run.results_by_net, weights,
|
||||||
|
search_expansions=self.attempts.metrics().nodes_expanded,
|
||||||
|
)
|
||||||
|
self.attempts.samples.append(metrics.snapshot())
|
||||||
|
if changes:
|
||||||
|
self.cost_pass_performed = True
|
||||||
|
stage = RoutingStage(
|
||||||
|
"off", (), metrics.total_nodes_expanded, options.search.node_limit,
|
||||||
|
kind="refinement", planner=planner, policy="weighted", operation="refine",
|
||||||
|
)
|
||||||
|
results = {**incumbent.run.results_by_net, **changes}
|
||||||
|
trials.append(self._trial(replace(incumbent.run, results_by_net=results), stage).as_replacement_for(incumbent))
|
||||||
|
|
||||||
def execute(self) -> RoutingRunResult:
|
def execute(self) -> RoutingRunResult:
|
||||||
started = perf_counter()
|
started = perf_counter()
|
||||||
options = self.options
|
options = self.options
|
||||||
|
|
@ -769,8 +977,13 @@ class _AutomaticRun:
|
||||||
target = min(target, cut.max_routed)
|
target = min(target, cut.max_routed)
|
||||||
if not cut and not conflicts:
|
if not cut and not conflicts:
|
||||||
trials, rejections = self._constructive_trials()
|
trials, rejections = self._constructive_trials()
|
||||||
|
elif not cut and conflicts and (candidate := self._try_port_capacity(conflicts, target)) is not None:
|
||||||
|
trials.append(candidate)
|
||||||
if not any(trial.selectable for trial in trials) or len(_best_trial(trials).valid_costs) < target:
|
if not any(trial.selectable for trial in trials) or len(_best_trial(trials).valid_costs) < target:
|
||||||
self._search_trials(trials, target)
|
self._search_trials(trials, target)
|
||||||
|
self._try_weighted_detour(trials)
|
||||||
|
self._try_weighted_shortcuts(trials)
|
||||||
|
self._try_weighted_windows(trials)
|
||||||
refinement_choice = self._refine(trials)
|
refinement_choice = self._refine(trials)
|
||||||
best = refinement_choice or _best_trial(trials)
|
best = refinement_choice or _best_trial(trials)
|
||||||
metrics = self.attempts.metrics()
|
metrics = self.attempts.metrics()
|
||||||
|
|
|
||||||
142
inire/router/_catalog_guidance.py
Normal file
142
inire/router/_catalog_guidance.py
Normal file
|
|
@ -0,0 +1,142 @@
|
||||||
|
"""Sparse coarse corridors and exact grid selection for catalog routing."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from heapq import heappop, heappush
|
||||||
|
from itertools import count
|
||||||
|
from math import gcd, hypot, inf
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from shapely.geometry import LineString, Point, box
|
||||||
|
from shapely.strtree import STRtree
|
||||||
|
|
||||||
|
from inire._catalog import HEADING_STEPS, FixedVariant, Grid, _require_integer, _require_positive
|
||||||
|
from inire.geometry.collision import _violates_clearance
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
from shapely.geometry.base import BaseGeometry
|
||||||
|
|
||||||
|
from inire._catalog import Catalog, Pose
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class AutomaticGrid:
|
||||||
|
"""Select a compatible divisor of a preferred routing pitch in layout units."""
|
||||||
|
|
||||||
|
preferred_pitch: int
|
||||||
|
meters_per_unit: float
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
_require_integer(self.preferred_pitch)
|
||||||
|
_require_positive("Preferred grid pitch", self.preferred_pitch)
|
||||||
|
_require_positive("Layout unit in meters", self.meters_per_unit)
|
||||||
|
|
||||||
|
def select(self, terminals: Sequence[Pose], catalog: Catalog) -> Grid:
|
||||||
|
origin = (terminals[0].x, terminals[0].y) if terminals else (0, 0)
|
||||||
|
pitch = int(self.preferred_pitch)
|
||||||
|
for pose in terminals:
|
||||||
|
pitch = gcd(pitch, pose.x - origin[0], pose.y - origin[1])
|
||||||
|
for variant in catalog.variants.values():
|
||||||
|
if isinstance(variant, FixedVariant):
|
||||||
|
a, b = variant.ports.values()
|
||||||
|
# Accepted fixed orientations swap or negate the axis differences.
|
||||||
|
pitch = gcd(pitch, a.x - b.x, a.y - b.y)
|
||||||
|
return Grid(origin, pitch, self.meters_per_unit)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class CoarseGuidance:
|
||||||
|
"""Coarse corridor search budget, independent of the realization pitch."""
|
||||||
|
|
||||||
|
pitch: int
|
||||||
|
node_limit: int = 4000
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
_require_integer(self.pitch)
|
||||||
|
_require_integer(self.node_limit)
|
||||||
|
_require_positive("Coarse guidance pitch", self.pitch)
|
||||||
|
if self.node_limit < 0:
|
||||||
|
raise ValueError("Coarse guidance node limit must be nonnegative")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class Corridor:
|
||||||
|
points: tuple[tuple[int, int], ...]
|
||||||
|
region: BaseGeometry
|
||||||
|
|
||||||
|
def admits(self, pose: Pose) -> bool:
|
||||||
|
return self.region.covers(Point(pose.x, pose.y))
|
||||||
|
|
||||||
|
|
||||||
|
def find_corridor(
|
||||||
|
start: Pose, target: Pose, settings: CoarseGuidance, *,
|
||||||
|
board: BaseGeometry, obstacles: Sequence[BaseGeometry], margin: float,
|
||||||
|
) -> tuple[Corridor | None, int]:
|
||||||
|
"""Guide on a coarse positional graph, with exact terminals as its endpoints."""
|
||||||
|
if not settings.node_limit:
|
||||||
|
return None, 0
|
||||||
|
pitch = int(settings.pitch)
|
||||||
|
start_xy, target_xy = (start.x, start.y), (target.x, target.y)
|
||||||
|
blockers = STRtree(obstacles)
|
||||||
|
|
||||||
|
def visible(a: tuple[int, int], b: tuple[int, int]) -> bool:
|
||||||
|
segment = LineString((a, b)) if a != b else Point(a)
|
||||||
|
if not board.covers(segment):
|
||||||
|
return False
|
||||||
|
x0, y0, x1, y1 = segment.bounds
|
||||||
|
nearby = blockers.query(box(x0 - margin, y0 - margin, x1 + margin, y1 + margin))
|
||||||
|
return not any(_violates_clearance(segment, blockers.geometries[index], margin) for index in nearby)
|
||||||
|
|
||||||
|
def corridor(points: Sequence[tuple[int, int]]) -> Corridor:
|
||||||
|
line = LineString(points) if len(set(points)) > 1 else Point(points[0])
|
||||||
|
return Corridor(tuple(points), line.buffer(2 * pitch + margin))
|
||||||
|
|
||||||
|
if visible(start_xy, target_xy):
|
||||||
|
return corridor((start_xy, target_xy)), 0
|
||||||
|
|
||||||
|
directions = tuple(HEADING_STEPS.values())
|
||||||
|
snapped = ((start.x + pitch // 2) // pitch) * pitch, ((start.y + pitch // 2) // pitch) * pitch
|
||||||
|
# Link the exact source to its surrounding coarse positions. The target's
|
||||||
|
# final connection is another visibility edge in this positional graph.
|
||||||
|
origins = [snapped, *((snapped[0] + dx * pitch, snapped[1] + dy * pitch) for dx, dy in directions)]
|
||||||
|
order = count()
|
||||||
|
queue = []
|
||||||
|
distances = {}
|
||||||
|
parents: dict[tuple[int, int], tuple[int, int] | None] = {}
|
||||||
|
for xy in origins:
|
||||||
|
if visible(start_xy, xy):
|
||||||
|
cost = hypot(xy[0] - start.x, xy[1] - start.y)
|
||||||
|
distances[xy], parents[xy] = cost, None
|
||||||
|
heappush(queue, (cost + hypot(xy[0] - target.x, xy[1] - target.y), next(order), cost, xy))
|
||||||
|
|
||||||
|
expanded = 0
|
||||||
|
while queue and expanded < settings.node_limit:
|
||||||
|
_, _, cost, current = heappop(queue)
|
||||||
|
if cost != distances[current]:
|
||||||
|
continue
|
||||||
|
expanded += 1
|
||||||
|
if visible(current, target_xy):
|
||||||
|
reverse = [target_xy]
|
||||||
|
ancestor = current
|
||||||
|
while ancestor is not None:
|
||||||
|
reverse.append(ancestor)
|
||||||
|
ancestor = parents[ancestor]
|
||||||
|
route = [start_xy, *reversed(reverse)]
|
||||||
|
simplified = [route[0]]
|
||||||
|
index = 0
|
||||||
|
while index < len(route) - 1:
|
||||||
|
following = next(i for i in range(len(route) - 1, index, -1) if visible(route[index], route[i]))
|
||||||
|
if route[following] != simplified[-1]:
|
||||||
|
simplified.append(route[following])
|
||||||
|
index = following
|
||||||
|
return corridor(simplified), expanded
|
||||||
|
for dx, dy in directions:
|
||||||
|
peer = current[0] + dx * pitch, current[1] + dy * pitch
|
||||||
|
estimate = cost + pitch * hypot(dx, dy)
|
||||||
|
if estimate < distances.get(peer, inf) and visible(current, peer):
|
||||||
|
distances[peer], parents[peer] = estimate, current
|
||||||
|
heappush(queue, (estimate + hypot(peer[0] - target.x, peer[1] - target.y), next(order), estimate, peer))
|
||||||
|
return None, expanded
|
||||||
759
inire/router/_catalog_layout.py
Normal file
759
inire/router/_catalog_layout.py
Normal file
|
|
@ -0,0 +1,759 @@
|
||||||
|
"""Catalog layout search, tuning, and final placement verification."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass, field, replace
|
||||||
|
from heapq import nlargest
|
||||||
|
from itertools import combinations
|
||||||
|
from math import ceil, floor, fsum, inf, isfinite
|
||||||
|
from time import perf_counter
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from shapely.geometry import LineString, Polygon, box
|
||||||
|
|
||||||
|
from inire._catalog import HEADING_STEPS, Move, MoveEvaluator, StraightVariant, _require_integer
|
||||||
|
from inire._catalog_timing import evaluate_delay
|
||||||
|
from inire._snapshot import snapshot
|
||||||
|
from inire.geometry.collision import _violates_net_clearance
|
||||||
|
from inire.geometry.intervals import open_intervals
|
||||||
|
|
||||||
|
from ._catalog_guidance import Corridor, find_corridor
|
||||||
|
from ._catalog_matching import DelayChoice, choose_match
|
||||||
|
from ._catalog_search import COST_TOLERANCE, SearchResult, path_recipe, search_path, straight_replacements
|
||||||
|
from ._catalog_tuning import tune_group
|
||||||
|
from ._catalog_verify import VerificationCache, _colliders, face_reservation, replay_moves, validate_attachment, verify_path
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from collections.abc import Mapping, Sequence
|
||||||
|
|
||||||
|
from shapely.geometry.base import BaseGeometry
|
||||||
|
|
||||||
|
from inire._catalog import Evaluation, Pose
|
||||||
|
from inire._catalog_timing import Delay, DelayModel
|
||||||
|
|
||||||
|
from ._catalog_guidance import CoarseGuidance
|
||||||
|
from ._catalog_matching import MatchGroup, MatchResult
|
||||||
|
from ._catalog_search import SearchBias
|
||||||
|
from ._catalog_verify import Attachment
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class CatalogNet:
|
||||||
|
start: Pose
|
||||||
|
target: Pose
|
||||||
|
source_attachment: Attachment | None = None
|
||||||
|
destination_attachment: Attachment | None = None
|
||||||
|
seed: tuple[Move, ...] = ()
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class LayoutSettings:
|
||||||
|
board: Polygon
|
||||||
|
keepouts: Sequence[BaseGeometry] = ()
|
||||||
|
clearance: float = 0.0
|
||||||
|
self_clearance: float = 0.0
|
||||||
|
face_tolerance: float = 0.0
|
||||||
|
node_limit: int = 1000
|
||||||
|
tuning_proposal_limit: int = 2000
|
||||||
|
refinement: bool = True
|
||||||
|
guidance: CoarseGuidance | None = None
|
||||||
|
refinement_node_limit: int = 64
|
||||||
|
retry_independent: bool = True
|
||||||
|
search_bias: SearchBias | None = None
|
||||||
|
constructive: bool = False
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
if not isinstance(self.board, Polygon) or self.board.is_empty or not self.board.is_valid:
|
||||||
|
raise ValueError("Routing board must be a valid nonempty polygon")
|
||||||
|
if any(shape.is_empty or not shape.is_valid for shape in self.keepouts):
|
||||||
|
raise ValueError("Keepouts must be valid nonempty geometries")
|
||||||
|
if any(not isfinite(value) or value < 0 for value in (self.clearance, self.self_clearance, self.face_tolerance)):
|
||||||
|
raise ValueError("Clearance and face tolerance must be finite and nonnegative")
|
||||||
|
for limit in (self.node_limit, self.tuning_proposal_limit, self.refinement_node_limit):
|
||||||
|
_require_integer(limit)
|
||||||
|
if min(self.node_limit, self.tuning_proposal_limit, self.refinement_node_limit) < 0:
|
||||||
|
raise ValueError("Routing and tuning limits must be nonnegative")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class LayoutAttempt:
|
||||||
|
order: tuple[str, ...]
|
||||||
|
covered_at: float | None
|
||||||
|
cost_at_coverage: float | None
|
||||||
|
elapsed: float
|
||||||
|
completed: tuple[str, ...]
|
||||||
|
expanded: int
|
||||||
|
proposed: int
|
||||||
|
coarse_expanded: int
|
||||||
|
geometry_checks: int
|
||||||
|
geometry_cache_hits: int
|
||||||
|
geometry_cache_entries: int
|
||||||
|
pair_repairs: int
|
||||||
|
tuning_seconds: float
|
||||||
|
independent_retry_seconds: float
|
||||||
|
independent_retries: int
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class LayoutResult:
|
||||||
|
routes: Mapping[str, SearchResult]
|
||||||
|
completed: tuple[str, ...]
|
||||||
|
delays: Mapping[str, Delay | None] = field(default_factory=dict)
|
||||||
|
matching: Mapping[str, MatchResult] = field(default_factory=dict)
|
||||||
|
attempts: tuple[LayoutAttempt, ...] = ()
|
||||||
|
|
||||||
|
|
||||||
|
class _LayoutSearch:
|
||||||
|
def __init__(
|
||||||
|
self, evaluator: MoveEvaluator, nets: Mapping[str, CatalogNet], settings: LayoutSettings, windows: Mapping[str, Polygon],
|
||||||
|
) -> None:
|
||||||
|
self.evaluator = evaluator
|
||||||
|
self.nets = nets
|
||||||
|
self.settings = settings
|
||||||
|
self.windows = dict(windows)
|
||||||
|
self.routes: dict[str, SearchResult] = {}
|
||||||
|
self.installed: dict[str, tuple[BaseGeometry, ...]] = {}
|
||||||
|
self.installed_paths: dict[str, tuple[Evaluation, ...]] = {}
|
||||||
|
self.pair_repairs = 0
|
||||||
|
self._coverage_evaluators: dict[tuple[str, bool], MoveEvaluator] = {}
|
||||||
|
self._verification_cache = VerificationCache()
|
||||||
|
|
||||||
|
def _geometry_settings(self, name: str) -> dict:
|
||||||
|
net = self.nets[name]
|
||||||
|
settings = self.settings
|
||||||
|
return {
|
||||||
|
"board": settings.board,
|
||||||
|
"keepouts": (*settings.keepouts, *(shape for owner, shape in self.windows.items() if owner != name)),
|
||||||
|
"occupied": tuple(shape for owner, shapes in self.installed.items() if owner != name for shape in shapes),
|
||||||
|
"clearance": settings.clearance,
|
||||||
|
"self_clearance": settings.self_clearance,
|
||||||
|
"face_tolerance": settings.face_tolerance,
|
||||||
|
"source_attachment": net.source_attachment,
|
||||||
|
"destination_attachment": net.destination_attachment,
|
||||||
|
"cache": self._verification_cache,
|
||||||
|
}
|
||||||
|
|
||||||
|
def _install(self, name: str, path: tuple[Evaluation, ...]) -> None:
|
||||||
|
net = self.nets[name]
|
||||||
|
profiles = self.evaluator.catalog.profiles
|
||||||
|
poses = [move.end for move in path[:-1]]
|
||||||
|
if net.source_attachment is not None:
|
||||||
|
poses.append(net.start)
|
||||||
|
if net.destination_attachment is not None:
|
||||||
|
poses.append(net.target)
|
||||||
|
self.installed_paths[name] = path
|
||||||
|
self.installed[name] = (
|
||||||
|
*(shape for move in path for shape in move.footprints),
|
||||||
|
*(face_reservation(pose, profiles[pose.profile].width, self.settings.face_tolerance) for pose in poses),
|
||||||
|
)
|
||||||
|
|
||||||
|
def verify(self, name: str, path: tuple[Evaluation, ...]) -> bool:
|
||||||
|
net = self.nets[name]
|
||||||
|
return verify_path(self.evaluator, path, net.start, net.target, **self._geometry_settings(name)) is None
|
||||||
|
|
||||||
|
def _search(self, name: str) -> SearchResult:
|
||||||
|
net = self.nets[name]
|
||||||
|
settings = {**self._geometry_settings(name), "bias": self.settings.search_bias}
|
||||||
|
node_limit = self.settings.node_limit
|
||||||
|
guidance = self.settings.guidance
|
||||||
|
coarse_expanded = 0
|
||||||
|
guided = None
|
||||||
|
guide_attempted = guidance is not None and node_limit > 1
|
||||||
|
if guide_attempted:
|
||||||
|
assert guidance is not None
|
||||||
|
attached = (net.source_attachment, net.destination_attachment)
|
||||||
|
obstacles = tuple(
|
||||||
|
shape for shape in (*settings["keepouts"], *settings["occupied"])
|
||||||
|
if all(attachment is None or shape is not attachment.obstacle for attachment in attached)
|
||||||
|
)
|
||||||
|
margin = self.settings.clearance + min(self.evaluator.catalog.profiles[pose.profile].width for pose in (net.start, net.target)) / 2
|
||||||
|
corridor, coarse_expanded = find_corridor(
|
||||||
|
net.start, net.target, guidance, board=self.settings.board, obstacles=obstacles, margin=margin,
|
||||||
|
)
|
||||||
|
if corridor is not None:
|
||||||
|
guided = search_path(
|
||||||
|
self.evaluator, net.start, net.target, node_limit=max(1, node_limit // 3), corridor=corridor, **settings,
|
||||||
|
)
|
||||||
|
if guided.path is not None:
|
||||||
|
return replace(guided, coarse_expanded=coarse_expanded, used_guidance=True)
|
||||||
|
node_limit -= guided.expanded
|
||||||
|
coverage = self._coverage_evaluator(net)
|
||||||
|
reserve = node_limit * 2 // 5 if coverage is not self.evaluator else node_limit // 4
|
||||||
|
explicit = search_path(
|
||||||
|
self.evaluator, net.start, net.target, node_limit=node_limit - reserve,
|
||||||
|
method="constructive_first" if self.settings.constructive and self.settings.search_bias is None else "detailed",
|
||||||
|
**settings,
|
||||||
|
)
|
||||||
|
remaining = node_limit - explicit.expanded
|
||||||
|
if explicit.path is None and remaining > 0 and coverage is not self.evaluator:
|
||||||
|
fallback = search_path(coverage, net.start, net.target, node_limit=remaining, **settings)
|
||||||
|
remaining -= fallback.expanded
|
||||||
|
explicit = replace(fallback.including_work(explicit), profile_fallback=True)
|
||||||
|
if explicit.path is None and remaining > 0:
|
||||||
|
scanned = search_path(self.evaluator, net.start, net.target, node_limit=remaining, scan_steps=True, **settings)
|
||||||
|
explicit = replace(scanned.including_work(explicit), profile_fallback=explicit.profile_fallback)
|
||||||
|
if guided is not None:
|
||||||
|
explicit = explicit.including_work(guided)
|
||||||
|
return replace(explicit, coarse_expanded=coarse_expanded, guide_fallback=guide_attempted)
|
||||||
|
|
||||||
|
def improve_straights(self, name: str) -> None:
|
||||||
|
"""Select cheaper profiles on installed straight spans without moving their ports."""
|
||||||
|
result = self.routes[name]
|
||||||
|
if result.path is None or self.nets[name].seed:
|
||||||
|
return
|
||||||
|
path = result.path
|
||||||
|
index = 0
|
||||||
|
checks = proposed = 0
|
||||||
|
while index < len(path):
|
||||||
|
original = path[index]
|
||||||
|
best = (original,)
|
||||||
|
best_cost = original.cost
|
||||||
|
for recipe in straight_replacements(self.evaluator, original.start, original.move):
|
||||||
|
proposed += 1
|
||||||
|
candidate = replay_moves(self.evaluator, original.start, recipe)
|
||||||
|
if candidate is None or candidate[-1].end != original.end:
|
||||||
|
continue
|
||||||
|
cost = fsum(move.cost for move in candidate)
|
||||||
|
if cost >= best_cost - COST_TOLERANCE:
|
||||||
|
continue
|
||||||
|
if original.length is None or any(move.length is None for move in candidate):
|
||||||
|
continue
|
||||||
|
if fsum(move.length for move in candidate if move.length is not None) > original.length + 1e-8:
|
||||||
|
continue
|
||||||
|
checks += 1
|
||||||
|
if self.verify(name, (*path[:index], *candidate, *path[index + 1:])):
|
||||||
|
best, best_cost = candidate, cost
|
||||||
|
elif len(candidate) == 3:
|
||||||
|
pieces = self._clear_straight_sections(name, original, candidate)
|
||||||
|
if pieces is None:
|
||||||
|
continue
|
||||||
|
proposed += 1
|
||||||
|
cost = fsum(move.cost for move in pieces)
|
||||||
|
if cost < best_cost - COST_TOLERANCE:
|
||||||
|
checks += 1
|
||||||
|
if self.verify(name, (*path[:index], *pieces, *path[index + 1:])):
|
||||||
|
best, best_cost = pieces, cost
|
||||||
|
if len(best) != 1 or best[0] is not original:
|
||||||
|
path = (*path[:index], *best, *path[index + 1:])
|
||||||
|
index += len(best)
|
||||||
|
self.routes[name] = replace(
|
||||||
|
result, path=path, proposed=result.proposed + proposed, geometry_checks=result.geometry_checks + checks,
|
||||||
|
)
|
||||||
|
if path is not result.path:
|
||||||
|
self._install(name, path)
|
||||||
|
|
||||||
|
def _clear_straight_sections(
|
||||||
|
self, name: str, original: Evaluation, wider: tuple[Evaluation, ...],
|
||||||
|
) -> tuple[Evaluation, ...] | None:
|
||||||
|
"""Keep the original profile beside blockers and widen the clear spans."""
|
||||||
|
steps = original.move.steps
|
||||||
|
middle_steps = wider[1].move.steps
|
||||||
|
if original.start.heading % 90 or steps is None or middle_steps is None:
|
||||||
|
return None
|
||||||
|
settings = self._geometry_settings(name)
|
||||||
|
cache = self._verification_cache
|
||||||
|
clearance = self.settings.clearance
|
||||||
|
shapes = (*wider[0].footprints, *wider[1].footprints, *wider[2].footprints)
|
||||||
|
keepouts = _colliders(cache.tree(settings["keepouts"], installed=False), shapes, clearance, cache)
|
||||||
|
occupied = _colliders(cache.tree(settings["occupied"], installed=True), shapes, clearance, cache)
|
||||||
|
dx, dy = HEADING_STEPS[original.start.heading]
|
||||||
|
x, y = original.start.x, original.start.y
|
||||||
|
pitch = self.evaluator.grid.pitch
|
||||||
|
solid = []
|
||||||
|
for blocker in (*keepouts, *occupied):
|
||||||
|
if any(_violates_net_clearance(shape, blocker, clearance) for shape in shapes):
|
||||||
|
x0, y0, x1, y1 = cache.bounds(blocker)
|
||||||
|
low, high = sorted((dx * (x0 - x) + dy * (y0 - y), dx * (x1 - x) + dy * (y1 - y)))
|
||||||
|
solid.append(((low - clearance) / pitch, (high + clearance) / pitch))
|
||||||
|
if not solid:
|
||||||
|
return None
|
||||||
|
narrow_price = original.cost / steps
|
||||||
|
wide_price = wider[1].cost / middle_steps
|
||||||
|
if wide_price >= narrow_price:
|
||||||
|
return None
|
||||||
|
setback = steps - middle_steps
|
||||||
|
transitions = wider[0].cost + wider[2].cost
|
||||||
|
recipe = []
|
||||||
|
cursor = 0
|
||||||
|
for low, high in open_intervals(solid, 0, steps):
|
||||||
|
begin, end = ceil(low), floor(high)
|
||||||
|
count = end - begin - setback
|
||||||
|
if count <= 0 or transitions + count * wide_price >= (end - begin) * narrow_price:
|
||||||
|
continue
|
||||||
|
if begin > cursor:
|
||||||
|
recipe.append(Move(original.move.variant, steps=begin - cursor))
|
||||||
|
recipe.extend((wider[0].move, Move(wider[1].move.variant, steps=count), wider[2].move))
|
||||||
|
cursor = end
|
||||||
|
if not recipe:
|
||||||
|
return None
|
||||||
|
if cursor < steps:
|
||||||
|
recipe.append(Move(original.move.variant, steps=steps - cursor))
|
||||||
|
return replay_moves(self.evaluator, original.start, recipe)
|
||||||
|
|
||||||
|
def _coverage_evaluator(self, net: CatalogNet) -> MoveEvaluator:
|
||||||
|
if net.start.profile != net.target.profile:
|
||||||
|
return self.evaluator
|
||||||
|
key = net.start.profile, net.start.heading % 90 == net.target.heading % 90 == 0
|
||||||
|
if key not in self._coverage_evaluators:
|
||||||
|
restricted = self.evaluator.coverage_catalog(key[0], cardinal=key[1])
|
||||||
|
self._coverage_evaluators[key] = (
|
||||||
|
MoveEvaluator(self.evaluator.grid, restricted) if restricted.variants.keys() < self.evaluator.catalog.variants.keys()
|
||||||
|
else self.evaluator
|
||||||
|
)
|
||||||
|
return self._coverage_evaluators[key]
|
||||||
|
|
||||||
|
def search(self, name: str) -> None:
|
||||||
|
net = self.nets[name]
|
||||||
|
seed = replay_moves(self.evaluator, net.start, net.seed) if net.seed else None
|
||||||
|
incumbent = seed if seed is not None and self.verify(name, seed) else None
|
||||||
|
if incumbent is not None:
|
||||||
|
result = SearchResult(incumbent, "verified", 0, 0)
|
||||||
|
else:
|
||||||
|
result = self._search(name) if self.settings.node_limit else SearchResult(None, "node_limit", 0, 0)
|
||||||
|
if name in self.routes:
|
||||||
|
result = result.including_work(self.routes[name])
|
||||||
|
self.routes[name] = result
|
||||||
|
if result.path is not None:
|
||||||
|
self._install(name, result.path)
|
||||||
|
|
||||||
|
def repair(self, name: str, group_members: Mapping[str, str]) -> None:
|
||||||
|
"""Try to add one independent route and move at most one verified peer."""
|
||||||
|
limit = min(self.settings.node_limit // 2, self.settings.refinement_node_limit)
|
||||||
|
if not limit or not self.installed:
|
||||||
|
return
|
||||||
|
net = self.nets[name]
|
||||||
|
settings = {**self._geometry_settings(name), "occupied": ()}
|
||||||
|
candidate = search_path(self.evaluator, net.start, net.target, node_limit=limit, **settings)
|
||||||
|
self.routes[name] = self.routes[name].including_work(candidate)
|
||||||
|
if candidate.path is None:
|
||||||
|
return
|
||||||
|
bounds = self.evaluator.catalog.profiles
|
||||||
|
pieces = [shape for move in candidate.path for shape in move.footprints]
|
||||||
|
pieces.extend(
|
||||||
|
face_reservation(move.end, bounds[move.end.profile].width, self.settings.face_tolerance) for move in candidate.path[:-1]
|
||||||
|
)
|
||||||
|
blockers = [
|
||||||
|
peer for peer, shapes in self.installed.items()
|
||||||
|
if any(_violates_net_clearance(shape, occupied, self.settings.clearance) for shape in pieces for occupied in shapes)
|
||||||
|
]
|
||||||
|
if not blockers:
|
||||||
|
if self._verify_replacements({name: candidate.path}):
|
||||||
|
self.routes[name] = replace(self.routes[name], path=candidate.path, outcome="verified")
|
||||||
|
self._install(name, candidate.path)
|
||||||
|
return
|
||||||
|
if len(blockers) != 1 or blockers[0] in group_members:
|
||||||
|
return
|
||||||
|
[peer] = blockers
|
||||||
|
old_shapes = self.installed.pop(peer)
|
||||||
|
old_path = self.installed_paths.pop(peer)
|
||||||
|
self._install(name, candidate.path)
|
||||||
|
try:
|
||||||
|
displaced = self.nets[peer]
|
||||||
|
trial = search_path(self.evaluator, displaced.start, displaced.target, node_limit=limit, **self._geometry_settings(peer))
|
||||||
|
self.routes[peer] = self.routes[peer].including_work(trial)
|
||||||
|
if trial.path is None or not self._verify_replacements({name: candidate.path, peer: trial.path}):
|
||||||
|
return
|
||||||
|
finally:
|
||||||
|
self.installed.pop(name)
|
||||||
|
self.installed_paths.pop(name)
|
||||||
|
self.installed[peer], self.installed_paths[peer] = old_shapes, old_path
|
||||||
|
self.routes[name] = replace(self.routes[name], path=candidate.path, outcome="verified")
|
||||||
|
self.routes[peer] = replace(self.routes[peer], path=trial.path, outcome="verified")
|
||||||
|
self._install(name, candidate.path)
|
||||||
|
self._install(peer, trial.path)
|
||||||
|
self.pair_repairs += 1
|
||||||
|
|
||||||
|
def refine(self, name: str, group: MatchGroup | None, report: MatchResult | None, timing: DelayModel | None) -> MatchResult | None:
|
||||||
|
result = self.routes[name]
|
||||||
|
path = result.path
|
||||||
|
assert path is not None
|
||||||
|
budget = min(self.settings.refinement_node_limit, self.settings.node_limit)
|
||||||
|
dx, dy = HEADING_STEPS[path[0].start.heading]
|
||||||
|
collinear = all(
|
||||||
|
move.start.heading == move.end.heading == path[0].start.heading
|
||||||
|
and dx * (move.end.y - move.start.y) == dy * (move.end.x - move.start.x)
|
||||||
|
for move in path
|
||||||
|
)
|
||||||
|
# The initial catalog search already priced unobstructed collinear
|
||||||
|
# sequences. Revisit those only if a seed, timing, or a retry shaped the result.
|
||||||
|
if not budget or (collinear and not self.nets[name].seed and group is None and not result.profile_fallback and not result.used_guidance):
|
||||||
|
return report
|
||||||
|
|
||||||
|
# Try the most expensive pieces first. Include their nearest neighbors
|
||||||
|
# so a replacement can move a transition or shorten a corner setback.
|
||||||
|
windows = sorted(
|
||||||
|
{(max(0, i - 1), min(len(path), i + 2)) for i in range(len(path))},
|
||||||
|
key=lambda pair: (-fsum(move.cost for move in path[pair[0]:pair[1]]), *pair),
|
||||||
|
)
|
||||||
|
for begin, end in windows[:3]:
|
||||||
|
original = path[begin:end]
|
||||||
|
cost = fsum(move.cost for move in original)
|
||||||
|
if cost <= COST_TOLERANCE:
|
||||||
|
continue
|
||||||
|
start, target = original[0].start, original[-1].end
|
||||||
|
shapes = [shape.bounds for move in original for shape in move.footprints]
|
||||||
|
left, bottom = min(shape[0] for shape in shapes), min(shape[1] for shape in shapes)
|
||||||
|
right, top = max(shape[2] for shape in shapes), max(shape[3] for shape in shapes)
|
||||||
|
margin = max(
|
||||||
|
2 * self.evaluator.grid.pitch,
|
||||||
|
self.evaluator.catalog.profiles[start.profile].width,
|
||||||
|
self.evaluator.catalog.profiles[target.profile].width,
|
||||||
|
)
|
||||||
|
corridor = Corridor(((start.x, start.y), (target.x, target.y)), box(left - margin, bottom - margin, right + margin, top + margin))
|
||||||
|
settings = self._geometry_settings(name)
|
||||||
|
if begin:
|
||||||
|
settings["source_attachment"] = None
|
||||||
|
if end != len(path):
|
||||||
|
settings["destination_attachment"] = None
|
||||||
|
trial = search_path(
|
||||||
|
self.evaluator, start, target, node_limit=budget, max_cost=cost - 2 * COST_TOLERANCE, corridor=corridor, **settings,
|
||||||
|
method="constructive_only" if self.settings.constructive else "detailed",
|
||||||
|
constructive_profiles=group is not None,
|
||||||
|
)
|
||||||
|
budget -= trial.expanded
|
||||||
|
result = result.including_work(trial)
|
||||||
|
self.routes[name] = result
|
||||||
|
if trial.path is not None and fsum(move.cost for move in trial.path) < cost - COST_TOLERANCE:
|
||||||
|
proposed = (*path[:begin], *trial.path, *path[end:])
|
||||||
|
if self.verify(name, proposed):
|
||||||
|
updated = self._refined_match(name, proposed, group, report, timing)
|
||||||
|
if group is None or updated is not None:
|
||||||
|
self.routes[name] = replace(result, path=proposed)
|
||||||
|
self._install(name, proposed)
|
||||||
|
return updated
|
||||||
|
if not budget:
|
||||||
|
break
|
||||||
|
return report
|
||||||
|
|
||||||
|
def improve_profile_pair(
|
||||||
|
self, members: Mapping[str, str], groups: Mapping[str, MatchGroup], reports: dict[str, MatchResult], timing: DelayModel | None,
|
||||||
|
) -> None:
|
||||||
|
"""Try a wider straight and reroute its one independent blocker under a joint cost cap."""
|
||||||
|
limit = min(self.settings.node_limit, self.settings.refinement_node_limit)
|
||||||
|
if limit < 2 or len(self.installed) < 2:
|
||||||
|
return
|
||||||
|
rates = {variant.cost_per_cm for variant in self.evaluator.catalog.variants.values() if isinstance(variant, StraightVariant)}
|
||||||
|
if len(rates) < 2:
|
||||||
|
return
|
||||||
|
floor_rate = min(rates) * self.evaluator.grid.meters_per_unit * 100
|
||||||
|
# A two-route probe needs meaningful headroom in whole-layout cost.
|
||||||
|
layout_cost = fsum(move.cost for path in self.installed_paths.values() for move in path)
|
||||||
|
minimum_saving = max(COST_TOLERANCE, layout_cost / 16)
|
||||||
|
spans = (
|
||||||
|
(move.cost - floor_rate * move.length, name, index)
|
||||||
|
for name, path in self.installed_paths.items() if not self.nets[name].seed
|
||||||
|
for index, move in enumerate(path) if move.move.steps is not None and move.length is not None
|
||||||
|
)
|
||||||
|
candidates = []
|
||||||
|
for cap, name, index in nlargest(4, spans):
|
||||||
|
if cap < minimum_saving:
|
||||||
|
break
|
||||||
|
path = self.installed_paths[name]
|
||||||
|
original = path[index]
|
||||||
|
for recipe in straight_replacements(self.evaluator, original.start, original.move):
|
||||||
|
portion = replay_moves(self.evaluator, original.start, recipe)
|
||||||
|
if portion is None or portion[-1].end != original.end:
|
||||||
|
continue
|
||||||
|
saving = original.cost - fsum(move.cost for move in portion)
|
||||||
|
if saving < minimum_saving:
|
||||||
|
continue
|
||||||
|
footprints = tuple(shape for move in portion for shape in move.footprints)
|
||||||
|
candidate = (*path[:index], *portion, *path[index + 1:])
|
||||||
|
candidates.append((saving, name, footprints, candidate))
|
||||||
|
|
||||||
|
probes = 0
|
||||||
|
for saving, name, footprints, candidate in sorted(candidates, key=lambda item: item[0], reverse=True):
|
||||||
|
group_id = members.get(name)
|
||||||
|
updated = self._refined_match(name, candidate, groups.get(group_id), reports.get(group_id), timing)
|
||||||
|
if group_id is not None and updated is None:
|
||||||
|
continue
|
||||||
|
geometry = self._geometry_settings(name)
|
||||||
|
cache, clearance = self._verification_cache, self.settings.clearance
|
||||||
|
colliders = _colliders(cache.tree(geometry["occupied"], installed=True), footprints, clearance, cache)
|
||||||
|
blocked = {
|
||||||
|
id(other) for other in colliders if any(_violates_net_clearance(shape, other, clearance) for shape in footprints)
|
||||||
|
}
|
||||||
|
peers = [peer for peer, shapes in self.installed.items() if peer != name and any(id(shape) in blocked for shape in shapes)]
|
||||||
|
if len(peers) != 1 or peers[0] in members or self.nets[peers[0]].seed:
|
||||||
|
continue
|
||||||
|
[peer] = peers
|
||||||
|
probes += 1
|
||||||
|
if self._reroute_profile_peer(name, candidate, peer, saving, limit):
|
||||||
|
if group_id is not None and updated is not None:
|
||||||
|
reports[group_id] = updated
|
||||||
|
return
|
||||||
|
if probes == 2:
|
||||||
|
return
|
||||||
|
|
||||||
|
def _reroute_profile_peer(
|
||||||
|
self, name: str, candidate: tuple[Evaluation, ...], peer: str, saving: float, limit: int,
|
||||||
|
) -> bool:
|
||||||
|
original_shapes, original_path = self.installed[name], self.installed_paths[name]
|
||||||
|
peer_shapes, peer_path = self.installed.pop(peer), self.installed_paths.pop(peer)
|
||||||
|
net = self.nets[peer]
|
||||||
|
self._install(name, candidate)
|
||||||
|
try:
|
||||||
|
if not self.verify(name, candidate):
|
||||||
|
return False
|
||||||
|
trial = search_path(
|
||||||
|
self.evaluator, net.start, net.target, node_limit=limit,
|
||||||
|
max_cost=fsum(move.cost for move in peer_path) + saving - COST_TOLERANCE,
|
||||||
|
method="constructive_only", constructive_profiles=True, **self._geometry_settings(peer),
|
||||||
|
)
|
||||||
|
self.routes[peer] = self.routes[peer].including_work(trial)
|
||||||
|
if trial.path is None or not self._verify_replacements({name: candidate, peer: trial.path}):
|
||||||
|
return False
|
||||||
|
finally:
|
||||||
|
self.installed[name], self.installed_paths[name] = original_shapes, original_path
|
||||||
|
self.installed[peer], self.installed_paths[peer] = peer_shapes, peer_path
|
||||||
|
self.routes[name] = replace(self.routes[name], path=candidate)
|
||||||
|
self.routes[peer] = replace(self.routes[peer], path=trial.path)
|
||||||
|
self._install(name, candidate)
|
||||||
|
self._install(peer, trial.path)
|
||||||
|
return True
|
||||||
|
|
||||||
|
def _refined_match(
|
||||||
|
self, name: str, path: tuple[Evaluation, ...], group: MatchGroup | None, report: MatchResult | None, timing: DelayModel | None,
|
||||||
|
) -> MatchResult | None:
|
||||||
|
if group is None or report is None or timing is None:
|
||||||
|
return report
|
||||||
|
delay = evaluate_delay(self.evaluator, path, replace(timing, wavelength=group.wavelength), net_id=name)
|
||||||
|
if delay is None:
|
||||||
|
return None
|
||||||
|
delays = {**report.delays, name: delay}
|
||||||
|
_, skew, fits = choose_match(group, {member: (DelayChoice((), value),) for member, value in delays.items()})
|
||||||
|
return replace(report, delays=snapshot(delays), skew=skew) if fits else None
|
||||||
|
|
||||||
|
def _verify_replacements(self, replacements: Mapping[str, tuple[Evaluation, ...]]) -> bool:
|
||||||
|
if not replacements:
|
||||||
|
return True
|
||||||
|
incumbent = self.installed.copy()
|
||||||
|
paths = self.installed_paths.copy()
|
||||||
|
try:
|
||||||
|
for name, path in replacements.items():
|
||||||
|
self._install(name, path)
|
||||||
|
return all(self.verify(name, path) for name, path in self.installed_paths.items())
|
||||||
|
finally:
|
||||||
|
self.installed = incumbent
|
||||||
|
self.installed_paths = paths
|
||||||
|
|
||||||
|
def tune(
|
||||||
|
self, group: MatchGroup, timing: DelayModel,
|
||||||
|
) -> MatchResult:
|
||||||
|
baselines = {name: self.routes[name].path for name in group.offsets}
|
||||||
|
alternative_limit = self.settings.node_limit // 2
|
||||||
|
total_proposals = self.settings.tuning_proposal_limit
|
||||||
|
initial_proposals = total_proposals - total_proposals // 3 if alternative_limit else total_proposals
|
||||||
|
report, replacements = tune_group(
|
||||||
|
self.evaluator, group, timing, baselines, self.windows, self.verify,
|
||||||
|
proposal_limit=initial_proposals,
|
||||||
|
)
|
||||||
|
proposed = report.proposed_replacements
|
||||||
|
verified = report.verified_replacements
|
||||||
|
eligible = report.eligible_spans
|
||||||
|
exhausted = report.budget_exhausted
|
||||||
|
found = report.tuning_space_found
|
||||||
|
if not self._verify_replacements(replacements):
|
||||||
|
report, _ = tune_group(self.evaluator, group, timing, baselines, {}, self.verify, proposal_limit=0)
|
||||||
|
replacements = {}
|
||||||
|
# Use a separate bounded search when the baseline geometry cannot
|
||||||
|
# match. Holding the other routes fixed preserves their verified spans.
|
||||||
|
if not report.complete and alternative_limit:
|
||||||
|
def rank(candidate: MatchResult, changed: Mapping[str, tuple[Evaluation, ...]]) -> tuple[bool, float, float]:
|
||||||
|
return (
|
||||||
|
not candidate.complete, 0.0 if candidate.complete else (candidate.skew if candidate.skew is not None else inf),
|
||||||
|
fsum(move.cost for name, base in baselines.items() for move in changed.get(name, base or ())),
|
||||||
|
)
|
||||||
|
|
||||||
|
best = rank(report, replacements)
|
||||||
|
for index, (name, baseline) in enumerate(baselines.items()):
|
||||||
|
net = self.nets[name]
|
||||||
|
excluded = () if baseline is None else (path_recipe(baseline),)
|
||||||
|
trial = search_path(
|
||||||
|
self.evaluator, net.start, net.target, node_limit=alternative_limit,
|
||||||
|
excluded_paths=excluded, **self._geometry_settings(name),
|
||||||
|
)
|
||||||
|
original = self.routes[name]
|
||||||
|
self.routes[name] = original.including_work(trial)
|
||||||
|
if trial.path is None:
|
||||||
|
continue
|
||||||
|
searched = dict(baselines)
|
||||||
|
searched[name] = trial.path
|
||||||
|
candidate, adjusted = tune_group(
|
||||||
|
self.evaluator, group, timing, searched, self.windows, self.verify,
|
||||||
|
proposal_limit=(total_proposals - proposed) // (len(baselines) - index),
|
||||||
|
)
|
||||||
|
proposed += candidate.proposed_replacements
|
||||||
|
verified += candidate.verified_replacements
|
||||||
|
eligible += candidate.eligible_spans
|
||||||
|
exhausted |= candidate.budget_exhausted
|
||||||
|
found |= candidate.tuning_space_found
|
||||||
|
adjusted.setdefault(name, trial.path)
|
||||||
|
if (score := rank(candidate, adjusted)) < best and self._verify_replacements(adjusted):
|
||||||
|
best, report, replacements = score, candidate, adjusted
|
||||||
|
for name, path in replacements.items():
|
||||||
|
self.routes[name] = replace(self.routes[name], path=path, outcome="verified")
|
||||||
|
if report.complete:
|
||||||
|
self._install(name, path)
|
||||||
|
return replace(
|
||||||
|
report, proposed_replacements=proposed, verified_replacements=verified, eligible_spans=eligible,
|
||||||
|
budget_exhausted=exhausted, tuning_space_found=found,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _match_members(
|
||||||
|
nets: Mapping[str, CatalogNet], groups: Sequence[MatchGroup], windows: Mapping[str, Polygon],
|
||||||
|
) -> dict[str, str]:
|
||||||
|
members = {}
|
||||||
|
group_ids = set()
|
||||||
|
for group in groups:
|
||||||
|
if group.group_id in group_ids:
|
||||||
|
raise ValueError(f"Duplicate match group ID {group.group_id!r}")
|
||||||
|
group_ids.add(group.group_id)
|
||||||
|
for name in group.offsets:
|
||||||
|
if name not in nets or name in members:
|
||||||
|
raise ValueError(f"Match member {name!r} is unknown or belongs to multiple groups")
|
||||||
|
members[name] = group.group_id
|
||||||
|
for owner, window in windows.items():
|
||||||
|
if owner in members and (window.is_empty or not window.is_valid or window.area <= 0):
|
||||||
|
raise ValueError(f"Invalid tuning window for {owner!r}")
|
||||||
|
active = [(name, window) for name, window in windows.items() if name in members]
|
||||||
|
for (left, a), (right, b) in combinations(active, 2):
|
||||||
|
if a.relate_pattern(b, "2********"):
|
||||||
|
raise ValueError(f"Tuning windows intersect for {left!r} and {right!r}")
|
||||||
|
return members
|
||||||
|
|
||||||
|
|
||||||
|
def route_layout(
|
||||||
|
evaluator: MoveEvaluator,
|
||||||
|
nets: Mapping[str, CatalogNet],
|
||||||
|
settings: LayoutSettings,
|
||||||
|
*,
|
||||||
|
timing: DelayModel | None = None,
|
||||||
|
groups: Sequence[MatchGroup] = (),
|
||||||
|
windows: Mapping[str, Polygon] | None = None,
|
||||||
|
require_complete: bool = False,
|
||||||
|
) -> LayoutResult:
|
||||||
|
if groups and timing is None:
|
||||||
|
raise ValueError("Active match groups require a timing model")
|
||||||
|
windows = {} if windows is None else windows
|
||||||
|
members = _match_members(nets, groups, windows)
|
||||||
|
active_windows = {name: window for name, window in windows.items() if name in members}
|
||||||
|
for name, net in nets.items():
|
||||||
|
for pose in (net.start, net.target):
|
||||||
|
if pose.profile not in evaluator.catalog.profiles or evaluator.grid.lattice_position(pose.x, pose.y) is None:
|
||||||
|
raise ValueError(f"Net {name!r} has an invalid terminal {pose!r}")
|
||||||
|
for attachment, pose, source in ((net.source_attachment, net.start, True), (net.destination_attachment, net.target, False)):
|
||||||
|
if attachment is not None:
|
||||||
|
validate_attachment(evaluator, attachment, pose, settings.keepouts, settings.face_tolerance, source=source)
|
||||||
|
order = tuple(nets)
|
||||||
|
first = _route_attempt(evaluator, nets, settings, timing, groups, members, active_windows, order, require_complete)
|
||||||
|
if settings.refinement and len(order) > 1 and (
|
||||||
|
len(first.completed) < len(order) or (not settings.constructive and _routes_compete(first, nets, evaluator, settings.clearance))
|
||||||
|
):
|
||||||
|
second = _route_attempt(evaluator, nets, settings, timing, groups, members, active_windows, tuple(reversed(order)), require_complete)
|
||||||
|
best = second if _layout_rank(second) < _layout_rank(first) else first
|
||||||
|
return replace(best, attempts=(*first.attempts, *second.attempts))
|
||||||
|
return first
|
||||||
|
|
||||||
|
|
||||||
|
def _routes_compete(
|
||||||
|
result: LayoutResult, nets: Mapping[str, CatalogNet], evaluator: MoveEvaluator, clearance: float,
|
||||||
|
) -> bool:
|
||||||
|
"""Only reorder a full layout when a peer may be forcing a detour."""
|
||||||
|
placements = {name: tuple(shape for move in (result.routes[name].path or ()) for shape in move.footprints) for name in result.completed}
|
||||||
|
for name in result.completed:
|
||||||
|
route = result.routes[name].path
|
||||||
|
if route is None or len(route) < 2:
|
||||||
|
continue
|
||||||
|
net = nets[name]
|
||||||
|
margin = clearance + max(evaluator.catalog.profiles[net.start.profile].width, evaluator.catalog.profiles[net.target.profile].width) / 2
|
||||||
|
direct = LineString(((net.start.x, net.start.y), (net.target.x, net.target.y)))
|
||||||
|
for peer, shapes in placements.items():
|
||||||
|
if peer != name and any(direct.distance(shape) < margin for shape in shapes):
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def _layout_rank(result: LayoutResult) -> tuple[int, int, float]:
|
||||||
|
return (
|
||||||
|
-len(result.completed),
|
||||||
|
-sum(report.complete for report in result.matching.values()),
|
||||||
|
fsum(move.cost for name in result.completed for move in (result.routes[name].path or ())),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _route_attempt(
|
||||||
|
evaluator: MoveEvaluator,
|
||||||
|
nets: Mapping[str, CatalogNet],
|
||||||
|
settings: LayoutSettings,
|
||||||
|
timing: DelayModel | None,
|
||||||
|
groups: Sequence[MatchGroup],
|
||||||
|
members: Mapping[str, str],
|
||||||
|
windows: Mapping[str, Polygon],
|
||||||
|
order: Sequence[str],
|
||||||
|
require_complete: bool,
|
||||||
|
) -> LayoutResult:
|
||||||
|
began = perf_counter()
|
||||||
|
routing = _LayoutSearch(evaluator, nets, settings, windows)
|
||||||
|
for name in order:
|
||||||
|
routing.search(name)
|
||||||
|
covered_at = perf_counter() - began if len(routing.installed) == len(nets) else None
|
||||||
|
cost_at_coverage = (
|
||||||
|
fsum(move.cost for route in routing.routes.values() for move in (route.path or ())) if covered_at is not None else None
|
||||||
|
)
|
||||||
|
for name in order:
|
||||||
|
if name not in members and (settings.constructive or routing.routes[name].profile_fallback):
|
||||||
|
routing.improve_straights(name)
|
||||||
|
tuning_start = perf_counter()
|
||||||
|
reports = {group.group_id: routing.tune(group, timing) for group in groups} if timing is not None else {}
|
||||||
|
tuning_seconds = perf_counter() - tuning_start if groups else 0.0
|
||||||
|
retry_start = perf_counter()
|
||||||
|
retries = 0
|
||||||
|
failed = {name for name, group in members.items() if not reports[group].complete}
|
||||||
|
if failed and not require_complete:
|
||||||
|
for name in failed:
|
||||||
|
routing.installed.pop(name, None)
|
||||||
|
routing.installed_paths.pop(name, None)
|
||||||
|
routing.windows.pop(name, None)
|
||||||
|
if settings.retry_independent:
|
||||||
|
for name in nets:
|
||||||
|
if name not in members and routing.routes[name].path is None:
|
||||||
|
retries += 1
|
||||||
|
routing.search(name)
|
||||||
|
retry_seconds = perf_counter() - retry_start if retries else 0.0
|
||||||
|
if settings.refinement and (not failed or not require_complete):
|
||||||
|
pending = [name for name in nets if name not in members and routing.routes[name].path is None]
|
||||||
|
for name in pending[:2]:
|
||||||
|
routing.repair(name, members)
|
||||||
|
completed = tuple(name for name in nets if name not in failed and routing.routes[name].path is not None)
|
||||||
|
if settings.refinement:
|
||||||
|
group_by_id = {group.group_id: group for group in groups}
|
||||||
|
for name in completed:
|
||||||
|
group_id = members.get(name)
|
||||||
|
report = routing.refine(name, group_by_id.get(group_id), reports.get(group_id), timing)
|
||||||
|
if group_id is not None and report is not None:
|
||||||
|
reports[group_id] = report
|
||||||
|
if len(completed) == len(nets):
|
||||||
|
routing.improve_profile_pair(members, group_by_id, reports, timing)
|
||||||
|
for name in completed:
|
||||||
|
path = routing.routes[name].path
|
||||||
|
assert path is not None
|
||||||
|
if not routing.verify(name, path):
|
||||||
|
raise RuntimeError(f"Final catalog layout verification failed for {name!r}")
|
||||||
|
|
||||||
|
delays = {}
|
||||||
|
if timing is not None:
|
||||||
|
for name, route in routing.routes.items():
|
||||||
|
if name in members:
|
||||||
|
delays[name] = reports[members[name]].delays.get(name)
|
||||||
|
elif route.path is not None:
|
||||||
|
delays[name] = evaluate_delay(evaluator, route.path, timing, net_id=name)
|
||||||
|
work = routing.routes.values()
|
||||||
|
attempt = LayoutAttempt(
|
||||||
|
tuple(order), covered_at, cost_at_coverage, perf_counter() - began, completed,
|
||||||
|
sum(route.expanded for route in work), sum(route.proposed for route in work), sum(route.coarse_expanded for route in work),
|
||||||
|
sum(route.geometry_checks for route in work), sum(route.geometry_cache_hits for route in work),
|
||||||
|
sum(route.geometry_cache_entries for route in work), routing.pair_repairs, tuning_seconds, retry_seconds, retries,
|
||||||
|
)
|
||||||
|
return LayoutResult(snapshot({name: routing.routes[name] for name in nets}), completed, snapshot(delays), snapshot(reports), (attempt,))
|
||||||
125
inire/router/_catalog_matching.py
Normal file
125
inire/router/_catalog_matching.py
Normal file
|
|
@ -0,0 +1,125 @@
|
||||||
|
"""Select verified delay choices for one catalog match group."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from bisect import bisect_left
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from math import fsum, isfinite, ulp
|
||||||
|
from typing import TYPE_CHECKING, Literal
|
||||||
|
|
||||||
|
from inire._snapshot import snapshot
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from collections.abc import Mapping, Sequence
|
||||||
|
|
||||||
|
from inire._catalog import Evaluation
|
||||||
|
from inire._catalog_timing import Delay
|
||||||
|
|
||||||
|
|
||||||
|
TimingUnits = Literal["optical_length", "seconds"]
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class MatchGroup:
|
||||||
|
group_id: str
|
||||||
|
offsets: Mapping[str, float]
|
||||||
|
wavelength: float
|
||||||
|
tolerance: float
|
||||||
|
units: TimingUnits = "optical_length"
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
if not self.group_id or not self.offsets or not all(self.offsets):
|
||||||
|
raise ValueError("A match group needs an ID and member net IDs")
|
||||||
|
if not isfinite(self.wavelength) or self.wavelength <= 0:
|
||||||
|
raise ValueError("A match group needs a positive finite wavelength")
|
||||||
|
if not isfinite(self.tolerance) or self.tolerance < 0 or any(not isfinite(offset) for offset in self.offsets.values()):
|
||||||
|
raise ValueError("Match offsets must be finite and tolerance must be finite and nonnegative")
|
||||||
|
if self.units not in ("optical_length", "seconds"):
|
||||||
|
raise ValueError("Match units must be optical_length or seconds")
|
||||||
|
object.__setattr__(self, "offsets", snapshot(self.offsets))
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class DelayChoice:
|
||||||
|
path: tuple[Evaluation, ...]
|
||||||
|
delay: Delay
|
||||||
|
|
||||||
|
@property
|
||||||
|
def cost(self) -> float:
|
||||||
|
return fsum(move.cost for move in self.path)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class MatchResult:
|
||||||
|
group_id: str
|
||||||
|
status: Literal["matched", "unmatched", "unrouted", "missing_delay"]
|
||||||
|
delays: Mapping[str, Delay]
|
||||||
|
skew: float | None
|
||||||
|
budget_exhausted: bool = False
|
||||||
|
tuning_space_found: bool = False
|
||||||
|
proposed_replacements: int = 0
|
||||||
|
verified_replacements: int = 0
|
||||||
|
eligible_spans: int = 0
|
||||||
|
|
||||||
|
@property
|
||||||
|
def complete(self) -> bool:
|
||||||
|
return self.status == "matched"
|
||||||
|
|
||||||
|
|
||||||
|
def _within(spread: float, tolerance: float, low: float, high: float) -> bool:
|
||||||
|
# Adjusted times can be very small. Use the rounding scale of the
|
||||||
|
# compared values so the same interval works in either timing unit.
|
||||||
|
return spread <= tolerance + 4 * max(ulp(low), ulp(high), ulp(tolerance))
|
||||||
|
|
||||||
|
|
||||||
|
def choose_match(
|
||||||
|
group: MatchGroup, choices: Mapping[str, Sequence[DelayChoice]],
|
||||||
|
) -> tuple[dict[str, DelayChoice], float, bool]:
|
||||||
|
"""Minimize skew until tolerance is achievable, then minimize cost."""
|
||||||
|
layers = {}
|
||||||
|
for net, offset in group.offsets.items():
|
||||||
|
layers[net] = sorted(
|
||||||
|
(
|
||||||
|
(getattr(choice.delay, group.units) - offset, order, choice.cost, choice)
|
||||||
|
for order, choice in enumerate(choices[net])
|
||||||
|
),
|
||||||
|
key=lambda item: (item[0], item[1]),
|
||||||
|
)
|
||||||
|
if any(not layer for layer in layers.values()):
|
||||||
|
raise ValueError("Every match member needs at least one verified timing choice")
|
||||||
|
starts = sorted({option[0] for layer in layers.values() for option in layer})
|
||||||
|
skew_roundoff = 4 * max(ulp(value) for value in starts)
|
||||||
|
|
||||||
|
best_pick: tuple[tuple[float, int, float, DelayChoice], ...] | None = None
|
||||||
|
best_rank: tuple[bool, float, float, tuple[int, ...]] | None = None
|
||||||
|
best_skew = 0.0
|
||||||
|
for low in starts:
|
||||||
|
first = [bisect_left(layer, low, key=lambda option: option[0]) for layer in layers.values()]
|
||||||
|
if any(index == len(layer) for index, layer in zip(first, layers.values(), strict=True)):
|
||||||
|
break
|
||||||
|
attainable_high = max(layer[index][0] for index, layer in zip(first, layers.values(), strict=True))
|
||||||
|
fits = _within(attainable_high - low, group.tolerance, low, attainable_high)
|
||||||
|
limit = group.tolerance if fits else attainable_high - low
|
||||||
|
selected = []
|
||||||
|
for index, layer in zip(first, layers.values(), strict=True):
|
||||||
|
best = layer[index]
|
||||||
|
for option in layer[index + 1:]:
|
||||||
|
if not _within(option[0] - low, limit, low, option[0]):
|
||||||
|
break
|
||||||
|
if (option[2], option[1]) < (best[2], best[1]):
|
||||||
|
best = option
|
||||||
|
selected.append(best)
|
||||||
|
skew = max(item[0] for item in selected) - min(item[0] for item in selected)
|
||||||
|
rank = (not fits, 0.0 if fits else skew, fsum(item[2] for item in selected), tuple(item[1] for item in selected))
|
||||||
|
comparable = rank
|
||||||
|
if best_rank is not None and rank[0] == best_rank[0] and abs(rank[1] - best_rank[1]) <= skew_roundoff:
|
||||||
|
comparable = (rank[0], best_rank[1], rank[2], rank[3])
|
||||||
|
if best_rank is None or comparable < best_rank:
|
||||||
|
best_rank, best_pick, best_skew = rank, tuple(selected), skew
|
||||||
|
assert best_pick is not None
|
||||||
|
assert best_rank is not None
|
||||||
|
return (
|
||||||
|
{net: selected[3] for net, selected in zip(layers, best_pick, strict=True)},
|
||||||
|
best_skew,
|
||||||
|
not best_rank[0],
|
||||||
|
)
|
||||||
998
inire/router/_catalog_search.py
Normal file
998
inire/router/_catalog_search.py
Normal file
|
|
@ -0,0 +1,998 @@
|
||||||
|
"""Bounded detailed search over evaluated catalog moves."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass, replace
|
||||||
|
from functools import cached_property
|
||||||
|
from heapq import heappop, heappush
|
||||||
|
from itertools import chain, count, islice
|
||||||
|
from math import ceil, floor, fsum, hypot, inf, isclose, isfinite
|
||||||
|
from typing import TYPE_CHECKING, Literal
|
||||||
|
|
||||||
|
from shapely.geometry import LineString, Point
|
||||||
|
from shapely.strtree import STRtree
|
||||||
|
|
||||||
|
from inire._catalog import HEADING_STEPS, BendVariant, Move, Pose, StraightVariant, _require_integer
|
||||||
|
from inire.geometry.collision import _violates_net_clearance
|
||||||
|
|
||||||
|
from ._catalog_verify import (
|
||||||
|
_colliders, compatible_join, face_reservation, meets_attachment_clearance, replay_moves, validate_attachment,
|
||||||
|
verify_move, verify_path, wholly_in_attachment,
|
||||||
|
)
|
||||||
|
|
||||||
|
from ._jog import detour_blocker_spans, jog_launch_steps
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from collections.abc import Iterator, Sequence
|
||||||
|
|
||||||
|
from shapely.geometry import Polygon
|
||||||
|
from shapely.geometry.base import BaseGeometry
|
||||||
|
|
||||||
|
from inire._catalog import Evaluation, MoveEvaluator
|
||||||
|
|
||||||
|
from ._catalog_guidance import Corridor
|
||||||
|
from ._catalog_verify import Attachment, VerificationCache
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class SearchBias:
|
||||||
|
"""Optional queue penalties in catalog cost units for nearby geometry."""
|
||||||
|
|
||||||
|
range: float = 1.0
|
||||||
|
proximity: float = 0.0
|
||||||
|
congestion: float = 0.0
|
||||||
|
guide: float = 0.0
|
||||||
|
|
||||||
|
def __post_init__(self) -> None:
|
||||||
|
if not isfinite(self.range) or self.range <= 0:
|
||||||
|
raise ValueError("Search bias range must be finite and positive")
|
||||||
|
if any(not isfinite(value) or value < 0 for value in (self.proximity, self.congestion, self.guide)):
|
||||||
|
raise ValueError("Search bias weights must be finite and nonnegative")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class SearchResult:
|
||||||
|
path: tuple[Evaluation, ...] | None
|
||||||
|
outcome: Literal["verified", "exhausted", "node_limit"]
|
||||||
|
expanded: int
|
||||||
|
proposed: int
|
||||||
|
coarse_expanded: int = 0
|
||||||
|
used_guidance: bool = False
|
||||||
|
guide_fallback: bool = False
|
||||||
|
profile_fallback: bool = False
|
||||||
|
geometry_checks: int = 0
|
||||||
|
geometry_cache_hits: int = 0
|
||||||
|
geometry_cache_entries: int = 0
|
||||||
|
budget_exhausted: bool = False
|
||||||
|
|
||||||
|
@property
|
||||||
|
def length(self) -> float | None:
|
||||||
|
if self.path is None or any(move.length is None for move in self.path):
|
||||||
|
return None
|
||||||
|
return fsum(move.length for move in self.path if move.length is not None)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def cost(self) -> float | None:
|
||||||
|
return None if self.path is None else fsum(move.cost for move in self.path)
|
||||||
|
|
||||||
|
def including_work(self, earlier: SearchResult) -> SearchResult:
|
||||||
|
return replace(
|
||||||
|
self, expanded=self.expanded + earlier.expanded, proposed=self.proposed + earlier.proposed,
|
||||||
|
coarse_expanded=self.coarse_expanded + earlier.coarse_expanded,
|
||||||
|
geometry_checks=self.geometry_checks + earlier.geometry_checks,
|
||||||
|
geometry_cache_hits=self.geometry_cache_hits + earlier.geometry_cache_hits,
|
||||||
|
geometry_cache_entries=self.geometry_cache_entries + earlier.geometry_cache_entries,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class _Arrival:
|
||||||
|
move: Evaluation
|
||||||
|
previous: _Arrival | None
|
||||||
|
cost: float
|
||||||
|
length: float
|
||||||
|
unknown_lengths: int
|
||||||
|
source_can_attach: bool
|
||||||
|
priority_penalty: float = 0.0
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class _PendingMove:
|
||||||
|
spec: Move
|
||||||
|
start: Pose
|
||||||
|
previous: _Arrival | None
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class _Jog:
|
||||||
|
first: Move
|
||||||
|
last: Move
|
||||||
|
forward: int
|
||||||
|
lateral: int
|
||||||
|
cost: float
|
||||||
|
|
||||||
|
|
||||||
|
def _placed_path(arrival: _Arrival | None) -> tuple[Evaluation, ...]:
|
||||||
|
path = []
|
||||||
|
while arrival is not None:
|
||||||
|
path.append(arrival.move)
|
||||||
|
arrival = arrival.previous
|
||||||
|
return tuple(reversed(path))
|
||||||
|
|
||||||
|
|
||||||
|
def path_recipe(path: Sequence[Evaluation]) -> tuple[Move, ...]:
|
||||||
|
"""Identify the same run of straight material regardless of its segmentation."""
|
||||||
|
recipe: list[Move] = []
|
||||||
|
for part in path:
|
||||||
|
move = part.move
|
||||||
|
if recipe and move.steps is not None and recipe[-1].variant == move.variant and recipe[-1].steps is not None:
|
||||||
|
previous = recipe.pop()
|
||||||
|
assert previous.steps is not None
|
||||||
|
recipe.append(Move(move.variant, steps=previous.steps + move.steps))
|
||||||
|
else:
|
||||||
|
recipe.append(move)
|
||||||
|
return tuple(recipe)
|
||||||
|
|
||||||
|
|
||||||
|
def straight_replacements(evaluator: MoveEvaluator, start: Pose, original: Move) -> Iterator[tuple[Move, ...]]:
|
||||||
|
"""Offer cheaper straight variants and centered profile changes on the same axis."""
|
||||||
|
steps = original.steps
|
||||||
|
if steps is None:
|
||||||
|
return
|
||||||
|
pitch = int(evaluator.grid.pitch)
|
||||||
|
dx, dy = HEADING_STEPS[start.heading]
|
||||||
|
denominator = pitch * (dx * dx + dy * dy)
|
||||||
|
|
||||||
|
def advance(end: Pose) -> int | None:
|
||||||
|
if end.heading != start.heading or dx * end.y != dy * end.x:
|
||||||
|
return None
|
||||||
|
along, remainder = divmod(dx * end.x + dy * end.y, denominator)
|
||||||
|
return along if not remainder and along >= 0 else None
|
||||||
|
|
||||||
|
straights: dict[str, list[str]] = {}
|
||||||
|
for name, variant in evaluator.catalog.variants.items():
|
||||||
|
if isinstance(variant, StraightVariant):
|
||||||
|
straights.setdefault(variant.profile, []).append(name)
|
||||||
|
if variant.profile == start.profile and name != original.variant:
|
||||||
|
yield (Move(name, steps=steps),)
|
||||||
|
for first, middle in evaluator.local_moves(start.profile, start.heading):
|
||||||
|
lead = advance(middle)
|
||||||
|
if middle.profile == start.profile or lead is None:
|
||||||
|
continue
|
||||||
|
for last, end in evaluator.local_moves(middle.profile, middle.heading):
|
||||||
|
tail = advance(end)
|
||||||
|
if end.profile != start.profile or tail is None or lead + tail >= steps:
|
||||||
|
continue
|
||||||
|
for straight in straights.get(middle.profile, ()):
|
||||||
|
yield first, Move(straight, steps=steps - lead - tail), last
|
||||||
|
|
||||||
|
|
||||||
|
COST_TOLERANCE = 1e-12
|
||||||
|
_TravelState = tuple[str, int]
|
||||||
|
_Position = tuple[int, int, int, str]
|
||||||
|
_BlockerProjection = tuple[float, float, tuple[float, ...]]
|
||||||
|
|
||||||
|
|
||||||
|
def _reverse_distances(
|
||||||
|
target: _TravelState, incoming: dict[_TravelState, list[tuple[_TravelState, float]]],
|
||||||
|
) -> dict[_TravelState, float]:
|
||||||
|
distances = {target: 0.0}
|
||||||
|
queue = [(0.0, target)]
|
||||||
|
while queue:
|
||||||
|
distance, state = heappop(queue)
|
||||||
|
if distance > distances[state]:
|
||||||
|
continue
|
||||||
|
for previous, change in incoming.get(state, ()):
|
||||||
|
estimate = distance + change
|
||||||
|
if estimate < distances.get(previous, inf):
|
||||||
|
distances[previous] = estimate
|
||||||
|
heappush(queue, (estimate, previous))
|
||||||
|
return distances
|
||||||
|
|
||||||
|
|
||||||
|
def _geometry_bias(move: Evaluation, blockers: STRtree, radius: float, weight: float, length_factor: float) -> float:
|
||||||
|
if not weight:
|
||||||
|
return 0.0
|
||||||
|
nearby = _colliders(blockers, move.footprints, radius)
|
||||||
|
if not nearby:
|
||||||
|
return 0.0
|
||||||
|
distance = min(shape.distance(other) for shape in move.footprints for other in nearby)
|
||||||
|
return weight * length_factor * max(0.0, 1 - distance / radius)
|
||||||
|
|
||||||
|
|
||||||
|
class _Proposals:
|
||||||
|
def __init__(
|
||||||
|
self, evaluator: MoveEvaluator, start: Pose, target: Pose, blockers: Sequence[BaseGeometry], clearance: float,
|
||||||
|
corridor: Corridor | None = None,
|
||||||
|
scan_steps: bool = False,
|
||||||
|
cache: VerificationCache | None = None,
|
||||||
|
) -> None:
|
||||||
|
self.evaluator = evaluator
|
||||||
|
self.target = target
|
||||||
|
self.origin = start.x, start.y
|
||||||
|
self.clearance = clearance
|
||||||
|
self.guide_points = corridor.points if corridor is not None else ()
|
||||||
|
self.scan_steps = scan_steps
|
||||||
|
self._blockers = blockers
|
||||||
|
self._verification_cache = cache
|
||||||
|
self._blocker_projections: dict[_TravelState, tuple[float, tuple[int, ...], tuple[_BlockerProjection, ...]]] = {}
|
||||||
|
self._exit_alignments: dict[_TravelState, dict[int, set[int]]] = {}
|
||||||
|
self._forward_only: dict[tuple[str, int], bool] = {}
|
||||||
|
profiles = evaluator.catalog.profiles
|
||||||
|
self._straights: dict[str, list[str]] = {profile: [] for profile in profiles}
|
||||||
|
self._straight_prices: dict[str, float] = {}
|
||||||
|
for name, variant in evaluator.catalog.variants.items():
|
||||||
|
if isinstance(variant, StraightVariant):
|
||||||
|
self._straights[variant.profile].append(name)
|
||||||
|
self._straight_prices[name] = variant.cost_per_cm
|
||||||
|
|
||||||
|
self._direction = (
|
||||||
|
(target.x > start.x) - (target.x < start.x),
|
||||||
|
(target.y > start.y) - (target.y < start.y),
|
||||||
|
)
|
||||||
|
@cached_property
|
||||||
|
def blocker_bounds(self) -> tuple[tuple[float, float, float, float], ...]:
|
||||||
|
cache = self._verification_cache
|
||||||
|
extents = (cache.bounds(shape) for shape in self._blockers) if cache is not None else (shape.bounds for shape in self._blockers)
|
||||||
|
return tuple(bounds for bounds in extents if isfinite(bounds[0]))
|
||||||
|
|
||||||
|
def prepare_detailed(self) -> None:
|
||||||
|
evaluator = self.evaluator
|
||||||
|
target = self.target
|
||||||
|
# Relax the problem to heading/profile changes and a linear distance
|
||||||
|
# term. The latter telescopes across a route regardless of detours.
|
||||||
|
incoming: dict[_TravelState, list[tuple[_TravelState, float, int, int]]] = {}
|
||||||
|
self._fixed_offsets: dict[_TravelState, dict[Move, tuple[Pose, float]]] = {}
|
||||||
|
for profile in evaluator.catalog.profiles:
|
||||||
|
for heading in HEADING_STEPS:
|
||||||
|
offsets = self._fixed_offsets.setdefault((profile, heading), {})
|
||||||
|
for move, end in evaluator.local_moves(profile, heading):
|
||||||
|
variant = evaluator.catalog.variants[move.variant]
|
||||||
|
assert not isinstance(variant, StraightVariant)
|
||||||
|
offsets[move] = end, variant.cost
|
||||||
|
incoming.setdefault((end.profile, end.heading), []).append(
|
||||||
|
((profile, heading), variant.cost, end.x, end.y),
|
||||||
|
)
|
||||||
|
|
||||||
|
target_key = (target.profile, target.heading)
|
||||||
|
reachable = {target_key}
|
||||||
|
pending = [target_key]
|
||||||
|
while pending:
|
||||||
|
for previous, *_ in incoming.get(pending.pop(), ()):
|
||||||
|
if previous not in reachable:
|
||||||
|
reachable.add(previous)
|
||||||
|
pending.append(previous)
|
||||||
|
|
||||||
|
ratios = []
|
||||||
|
for state in sorted(reachable):
|
||||||
|
for _, cost, x, y in incoming.get(state, ()):
|
||||||
|
distance = self._projection(x, y)
|
||||||
|
if distance > 0:
|
||||||
|
ratios.append(cost / distance)
|
||||||
|
profile, heading = state
|
||||||
|
dx, dy = HEADING_STEPS[heading]
|
||||||
|
progress = self._projection(dx, dy)
|
||||||
|
if progress > 0:
|
||||||
|
for name in self._straights[profile]:
|
||||||
|
variant = evaluator.catalog.variants[name]
|
||||||
|
assert isinstance(variant, StraightVariant)
|
||||||
|
ratios.append(variant.cost_per_cm * evaluator.grid.meters_per_unit * 100 * hypot(dx, dy) / progress)
|
||||||
|
self.cost_per_unit = min(ratios, default=0.0)
|
||||||
|
self.residual_cost = _reverse_distances(target_key, {
|
||||||
|
state: [(previous, max(0.0, cost - self.cost_per_unit * self._projection(x, y))) for previous, cost, x, y in edges]
|
||||||
|
for state, edges in incoming.items()
|
||||||
|
})
|
||||||
|
self.minimum_progress: list[tuple[int, int, dict[_TravelState, float]]] = []
|
||||||
|
for axis in (0, 1):
|
||||||
|
for sign in (-1, 1):
|
||||||
|
if any(sign * HEADING_STEPS[heading][axis] < 0 for profile, heading in reachable if self._straights[profile]):
|
||||||
|
continue
|
||||||
|
progress = {
|
||||||
|
state: [(previous, sign * (x, y)[axis]) for previous, _, x, y in incoming.get(state, ())]
|
||||||
|
for state in reachable
|
||||||
|
}
|
||||||
|
if any(distance < 0 for edges in progress.values() for _, distance in edges):
|
||||||
|
continue
|
||||||
|
self.minimum_progress.append((axis, sign, _reverse_distances(target_key, progress)))
|
||||||
|
|
||||||
|
def _projection(self, x: int, y: int) -> int:
|
||||||
|
dx, dy = self._direction
|
||||||
|
return dx * x + dy * y
|
||||||
|
|
||||||
|
def lower_bound(self, position: _Position) -> float:
|
||||||
|
x, y, heading, profile = position
|
||||||
|
key = profile, heading
|
||||||
|
residual = self.residual_cost.get(key, inf)
|
||||||
|
dx, dy = HEADING_STEPS[heading]
|
||||||
|
tx, ty = self.target.x - x, self.target.y - y
|
||||||
|
if any(sign * (tx, ty)[axis] < distances.get(key, inf)
|
||||||
|
for axis, sign, distances in self.minimum_progress):
|
||||||
|
return inf
|
||||||
|
if self._is_forward_only(profile, heading) and (dx * ty != dy * tx or dx * tx + dy * ty < 0):
|
||||||
|
return inf
|
||||||
|
return max(0.0, residual + self._projection(tx, ty) * self.cost_per_unit)
|
||||||
|
|
||||||
|
def _is_forward_only(self, profile: str, heading: int) -> bool:
|
||||||
|
key = profile, heading
|
||||||
|
if key not in self._forward_only:
|
||||||
|
dx, dy = HEADING_STEPS[heading]
|
||||||
|
profiles = {profile}
|
||||||
|
pending = [profile]
|
||||||
|
while pending:
|
||||||
|
current = pending.pop()
|
||||||
|
for _, end in self.evaluator.local_moves(current, heading):
|
||||||
|
if (end.profile, end.heading) not in self.residual_cost:
|
||||||
|
continue
|
||||||
|
if end.heading != heading or dx * end.y != dy * end.x or dx * end.x + dy * end.y < 0:
|
||||||
|
self._forward_only[key] = False
|
||||||
|
return False
|
||||||
|
if end.profile not in profiles:
|
||||||
|
profiles.add(end.profile)
|
||||||
|
pending.append(end.profile)
|
||||||
|
self._forward_only[key] = True
|
||||||
|
return self._forward_only[key]
|
||||||
|
|
||||||
|
def destination_bound(self, start: Pose, move: Move) -> tuple[_Position, float] | None:
|
||||||
|
"""Return the exact output pose and an inexpensive lower bound on move cost."""
|
||||||
|
if move.steps is not None:
|
||||||
|
dx, dy = HEADING_STEPS[start.heading]
|
||||||
|
pitch = int(self.evaluator.grid.pitch)
|
||||||
|
span = pitch * move.steps
|
||||||
|
length = move.steps * (pitch * hypot(dx, dy))
|
||||||
|
price = length * self.evaluator.grid.meters_per_unit * 100 * self._straight_prices[move.variant]
|
||||||
|
return (start.x + dx * span, start.y + dy * span, start.heading, start.profile), price
|
||||||
|
local = self._fixed_offsets[(start.profile, start.heading)].get(move)
|
||||||
|
if local is None:
|
||||||
|
return None
|
||||||
|
end, price = local
|
||||||
|
return (start.x + end.x, start.y + end.y, end.heading, end.profile), price
|
||||||
|
|
||||||
|
def two_turn_recipes(self, start: Pose) -> Iterator[tuple[float, tuple[Move, ...]]]:
|
||||||
|
"""Solve the straight spans of a two-turn route between parallel terminals."""
|
||||||
|
target = self.target
|
||||||
|
if target.heading != start.heading:
|
||||||
|
return
|
||||||
|
ux, uy = HEADING_STEPS[start.heading]
|
||||||
|
tx, ty = target.x - start.x, target.y - start.y
|
||||||
|
if ux * ty == uy * tx:
|
||||||
|
return
|
||||||
|
pitch = int(self.evaluator.grid.pitch)
|
||||||
|
denominator = pitch * (ux * ux + uy * uy)
|
||||||
|
cheapest = {
|
||||||
|
key: min(names, key=self._straight_prices.__getitem__)
|
||||||
|
for key, names in self._straights.items() if names
|
||||||
|
}
|
||||||
|
if start.profile not in cheapest or target.profile not in cheapest:
|
||||||
|
return
|
||||||
|
candidates = []
|
||||||
|
for first, turn in self.evaluator.local_moves(start.profile, start.heading):
|
||||||
|
vx, vy = HEADING_STEPS[turn.heading]
|
||||||
|
divisor = pitch * (ux * vy - uy * vx)
|
||||||
|
if not divisor or turn.profile not in cheapest:
|
||||||
|
continue
|
||||||
|
for second, exit_pose in self.evaluator.local_moves(turn.profile, turn.heading):
|
||||||
|
if (exit_pose.heading, exit_pose.profile) != (target.heading, target.profile):
|
||||||
|
continue
|
||||||
|
x, y = tx - turn.x - exit_pose.x, ty - turn.y - exit_pose.y
|
||||||
|
across, remainder = divmod(ux * y - uy * x, divisor)
|
||||||
|
if remainder or across < 0:
|
||||||
|
continue
|
||||||
|
x -= across * pitch * vx
|
||||||
|
y -= across * pitch * vy
|
||||||
|
parallel, remainder = divmod(ux * x + uy * y, denominator)
|
||||||
|
if remainder or parallel < 0:
|
||||||
|
continue
|
||||||
|
before_id, middle_id, after_id = (cheapest[profile] for profile in (start.profile, turn.profile, target.profile))
|
||||||
|
if ux * vx + uy * vy == 0:
|
||||||
|
margin = self.clearance + max(self.evaluator.catalog.profiles[p].width for p in (
|
||||||
|
start.profile, turn.profile, target.profile,
|
||||||
|
)) / 2
|
||||||
|
advance = ux * (turn.x + exit_pose.x) + uy * (turn.y + exit_pose.y)
|
||||||
|
launch_steps = jog_launch_steps(
|
||||||
|
(start.x, start.y), (ux, uy), ux * ty - uy * tx, advance, parallel, pitch,
|
||||||
|
margin * (ux * ux + uy * uy), self.blocker_bounds,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
launch_steps = dict.fromkeys((0, parallel, parallel // 2))
|
||||||
|
for before in launch_steps:
|
||||||
|
after = parallel - before
|
||||||
|
recipe = (
|
||||||
|
*((Move(before_id, steps=before),) if before else ()), first,
|
||||||
|
*((Move(middle_id, steps=across),) if across else ()), second,
|
||||||
|
*((Move(after_id, steps=after),) if after else ()),
|
||||||
|
)
|
||||||
|
legs = ((before_id, before, ux, uy), (middle_id, across, vx, vy), (after_id, after, ux, uy))
|
||||||
|
price = fsum(self._straight_prices[name] * steps * hypot(dx, dy) for name, steps, dx, dy in legs)
|
||||||
|
price *= pitch * self.evaluator.grid.meters_per_unit * 100
|
||||||
|
for move in (first, second):
|
||||||
|
variant = self.evaluator.catalog.variants[move.variant]
|
||||||
|
assert not isinstance(variant, StraightVariant)
|
||||||
|
price += variant.cost
|
||||||
|
candidates.append((price, before, recipe))
|
||||||
|
for price, _, recipe in sorted(candidates, key=lambda item: item[:2]):
|
||||||
|
yield price, recipe
|
||||||
|
|
||||||
|
def direct_recipes(self, start: Pose) -> Iterator[tuple[float, tuple[Move, ...]]]:
|
||||||
|
"""Connect the terminal rays with a straight or a single fixed move."""
|
||||||
|
tx, ty = self.target.x - start.x, self.target.y - start.y
|
||||||
|
ux, uy = HEADING_STEPS[start.heading]
|
||||||
|
vx, vy = HEADING_STEPS[self.target.heading]
|
||||||
|
pitch = int(self.evaluator.grid.pitch)
|
||||||
|
divisor = ux * vy - uy * vx
|
||||||
|
unit = pitch * self.evaluator.grid.meters_per_unit * 100
|
||||||
|
start_straights = self._straights[start.profile]
|
||||||
|
target_straights = self._straights[self.target.profile]
|
||||||
|
if start.heading == self.target.heading and start.profile == self.target.profile and ux * ty == uy * tx:
|
||||||
|
steps, remainder = divmod(ux * tx + uy * ty, pitch * (ux * ux + uy * uy))
|
||||||
|
if steps > 0 and not remainder:
|
||||||
|
for variant in sorted(start_straights, key=self._straight_prices.__getitem__):
|
||||||
|
yield unit * self._straight_prices[variant] * steps * hypot(ux, uy), (Move(variant, steps=steps),)
|
||||||
|
if not divisor:
|
||||||
|
return
|
||||||
|
candidates = []
|
||||||
|
for move, end in self.evaluator.local_moves(start.profile, start.heading):
|
||||||
|
if (end.heading, end.profile) != (self.target.heading, self.target.profile):
|
||||||
|
continue
|
||||||
|
x, y = tx - end.x, ty - end.y
|
||||||
|
lead, lead_rem = divmod(x * vy - y * vx, pitch * divisor)
|
||||||
|
tail, tail_rem = divmod(ux * y - uy * x, pitch * divisor)
|
||||||
|
if lead_rem or tail_rem or min(lead, tail) < 0:
|
||||||
|
continue
|
||||||
|
recipe: list[Move] = []
|
||||||
|
fixed = self.evaluator.catalog.variants[move.variant]
|
||||||
|
assert not isinstance(fixed, StraightVariant)
|
||||||
|
cost = fixed.cost
|
||||||
|
if lead:
|
||||||
|
if not start_straights:
|
||||||
|
continue
|
||||||
|
variant = min(start_straights, key=self._straight_prices.__getitem__)
|
||||||
|
recipe.append(Move(variant, steps=lead))
|
||||||
|
cost += self._straight_prices[variant] * lead * hypot(ux, uy) * unit
|
||||||
|
recipe.append(move)
|
||||||
|
if tail:
|
||||||
|
if not target_straights:
|
||||||
|
continue
|
||||||
|
variant = min(target_straights, key=self._straight_prices.__getitem__)
|
||||||
|
recipe.append(Move(variant, steps=tail))
|
||||||
|
cost += self._straight_prices[variant] * tail * hypot(vx, vy) * unit
|
||||||
|
candidates.append((cost, tuple(recipe)))
|
||||||
|
yield from sorted(candidates, key=lambda item: item[0])
|
||||||
|
|
||||||
|
def aligned_recipes(self, start: Pose) -> list[tuple[float, tuple[Move, ...]]]:
|
||||||
|
"""Price straight links with the option to change profiles along the way."""
|
||||||
|
target = self.target
|
||||||
|
if (start.heading, start.profile) != (target.heading, target.profile):
|
||||||
|
return []
|
||||||
|
dx, dy = HEADING_STEPS[start.heading]
|
||||||
|
x, y = target.x - start.x, target.y - start.y
|
||||||
|
if dx * y != dy * x or not self._straights[start.profile]:
|
||||||
|
return []
|
||||||
|
step_size = int(self.evaluator.grid.pitch) * (dx * dx + dy * dy)
|
||||||
|
steps, remainder = divmod(dx * x + dy * y, step_size)
|
||||||
|
if steps <= 0 or remainder:
|
||||||
|
return []
|
||||||
|
straight = min(self._straights[start.profile], key=self._straight_prices.__getitem__)
|
||||||
|
original = Move(straight, steps=steps)
|
||||||
|
catalog = self.evaluator.catalog
|
||||||
|
unit = self.evaluator.grid.pitch * hypot(dx, dy) * self.evaluator.grid.meters_per_unit * 100
|
||||||
|
candidates = []
|
||||||
|
direct_cost = steps * unit * self._straight_prices[straight]
|
||||||
|
for recipe in straight_replacements(self.evaluator, start, original):
|
||||||
|
if len(recipe) == 1:
|
||||||
|
continue
|
||||||
|
prices = []
|
||||||
|
for move in recipe:
|
||||||
|
variant = catalog.variants[move.variant]
|
||||||
|
if isinstance(variant, StraightVariant):
|
||||||
|
assert move.steps is not None
|
||||||
|
prices.append(move.steps * unit * variant.cost_per_cm)
|
||||||
|
else:
|
||||||
|
prices.append(variant.cost)
|
||||||
|
price = fsum(prices)
|
||||||
|
if price < direct_cost:
|
||||||
|
candidates.append((price, recipe))
|
||||||
|
return sorted(candidates, key=lambda item: item[0])
|
||||||
|
|
||||||
|
def aligned_lower_bound(self, start: Pose, price: float) -> float:
|
||||||
|
"""Relax an aligned route while charging for entry to a cheaper profile."""
|
||||||
|
distance = self._projection(self.target.x - start.x, self.target.y - start.y)
|
||||||
|
rate = price / distance
|
||||||
|
outgoing = {}
|
||||||
|
for state, moves in self._fixed_offsets.items():
|
||||||
|
edges = []
|
||||||
|
for end, cost in moves.values():
|
||||||
|
progress = self._projection(end.x, end.y)
|
||||||
|
if cost < rate * progress:
|
||||||
|
# The bound below only accounts for cheap straights.
|
||||||
|
return 0.0
|
||||||
|
edges.append(((end.profile, end.heading), max(0.0, cost - self.cost_per_unit * progress)))
|
||||||
|
outgoing[state] = edges
|
||||||
|
from_start = _reverse_distances((start.profile, start.heading), outgoing)
|
||||||
|
unit = self.evaluator.grid.meters_per_unit * 100
|
||||||
|
via_cheaper = inf
|
||||||
|
for state, entry in from_start.items():
|
||||||
|
profile, heading = state
|
||||||
|
dx, dy = HEADING_STEPS[heading]
|
||||||
|
if any(
|
||||||
|
unit * hypot(dx, dy) * self._straight_prices[name] < rate * self._projection(dx, dy)
|
||||||
|
for name in self._straights[profile]
|
||||||
|
):
|
||||||
|
via_cheaper = min(via_cheaper, entry + self.residual_cost.get(state, inf))
|
||||||
|
# Every path either pays the full rate for its net progress or
|
||||||
|
# reaches a cheaper straight and pays the residual cost on both sides.
|
||||||
|
return min(rate * distance, self.cost_per_unit * distance + via_cheaper)
|
||||||
|
|
||||||
|
def detour_recipes(self, start: Pose, *, widen: bool = False) -> Iterator[tuple[float, tuple[Move, ...]]]:
|
||||||
|
"""Try local and full-span bypasses for a blocked cardinal straight."""
|
||||||
|
target = self.target
|
||||||
|
if start.heading % 90 or (start.heading, start.profile) != (target.heading, target.profile):
|
||||||
|
return
|
||||||
|
ux, uy = HEADING_STEPS[start.heading]
|
||||||
|
tx, ty = target.x - start.x, target.y - start.y
|
||||||
|
forward = ux * tx + uy * ty
|
||||||
|
straights = self._straights[start.profile]
|
||||||
|
if forward <= 0 or ux * ty != uy * tx or not straights:
|
||||||
|
return
|
||||||
|
straight = min(straights, key=self._straight_prices.__getitem__)
|
||||||
|
pitch = int(self.evaluator.grid.pitch)
|
||||||
|
margin = self.clearance + self.evaluator.catalog.profiles[start.profile].width / 2
|
||||||
|
blockers = tuple(detour_blocker_spans((start.x, start.y), (ux, uy), forward, margin, self.blocker_bounds))
|
||||||
|
if not blockers:
|
||||||
|
return
|
||||||
|
lane_bounds = {
|
||||||
|
lane for _, _, low, high in blockers
|
||||||
|
for lane in (floor((low - margin) / pitch) * pitch, ceil((high + margin) / pitch) * pitch)
|
||||||
|
}
|
||||||
|
if widen:
|
||||||
|
profiles = self.evaluator.catalog.profiles
|
||||||
|
widths = {profiles[profile].width for profile, runs in self._straights.items() if any(
|
||||||
|
self._straight_prices[name] < self._straight_prices[straight] for name in runs
|
||||||
|
)}
|
||||||
|
for width in widths:
|
||||||
|
wider_margin = self.clearance + width / 2
|
||||||
|
if wider_margin > margin:
|
||||||
|
lane_bounds.update(
|
||||||
|
lane for _, _, low, high in blockers
|
||||||
|
for lane in (floor((low - wider_margin) / pitch) * pitch, ceil((high + wider_margin) / pitch) * pitch)
|
||||||
|
)
|
||||||
|
# Additional straight sections are useful when they can switch to a
|
||||||
|
# cheaper profile. A shape at exactly the clearance margin can sit
|
||||||
|
# beside the lead or tail, subject to exact replay.
|
||||||
|
can_save_on_straights = any(price < self._straight_prices[straight] for price in self._straight_prices.values())
|
||||||
|
interior = [(lo, hi) for lo, hi, low, high in blockers if low < margin and high > -margin] if can_save_on_straights else []
|
||||||
|
left = floor((min(lo for lo, _ in interior) - margin) / pitch) * pitch if interior else 0
|
||||||
|
right = ceil((max(hi for _, hi in interior) + margin) / pitch) * pitch if interior else forward
|
||||||
|
|
||||||
|
# Use exact catalog displacements for the two jogs, including any
|
||||||
|
# tangent leads needed to place a bend on the lattice.
|
||||||
|
jogs: dict[int, list[_Jog]] = {1: [], -1: []}
|
||||||
|
for first, middle in self.evaluator.local_moves(start.profile, start.heading):
|
||||||
|
variant = self.evaluator.catalog.variants[first.variant]
|
||||||
|
if not isinstance(variant, BendVariant) or abs(variant.turn) != 90:
|
||||||
|
continue
|
||||||
|
direction = 1 if variant.turn > 0 else -1
|
||||||
|
for last, end in self.evaluator.local_moves(middle.profile, middle.heading):
|
||||||
|
other = self.evaluator.catalog.variants[last.variant]
|
||||||
|
if not isinstance(other, BendVariant) or other.turn != -variant.turn:
|
||||||
|
continue
|
||||||
|
x, y = middle.x + end.x, middle.y + end.y
|
||||||
|
longitudinal, lateral = ux * x + uy * y, direction * (ux * y - uy * x)
|
||||||
|
if longitudinal >= 0 and lateral >= 0:
|
||||||
|
jogs[direction].append(_Jog(first, last, longitudinal, lateral, variant.cost + other.cost))
|
||||||
|
|
||||||
|
candidates = []
|
||||||
|
variants = self.evaluator.catalog.variants
|
||||||
|
price_scale = self.evaluator.grid.meters_per_unit * 100
|
||||||
|
unit_price = self._straight_prices[straight] * price_scale
|
||||||
|
for side in sorted(lane_bounds):
|
||||||
|
direction = 1 if side >= 0 else -1
|
||||||
|
for outward in jogs[direction]:
|
||||||
|
for inward in jogs[-direction]:
|
||||||
|
lane = max(abs(side), outward.lateral, inward.lateral)
|
||||||
|
rise, fall = lane - outward.lateral, lane - inward.lateral
|
||||||
|
center = forward - outward.forward - inward.forward
|
||||||
|
if not lane or center <= 0:
|
||||||
|
continue
|
||||||
|
out_moves = (outward.first, *((Move(straight, steps=rise // pitch),) if rise else ()), outward.last)
|
||||||
|
in_moves = (inward.first, *((Move(straight, steps=fall // pitch),) if fall else ()), inward.last)
|
||||||
|
length = center + rise + fall
|
||||||
|
cost = outward.cost + inward.cost + length * unit_price
|
||||||
|
lead, tail = left - outward.forward, forward - right - inward.forward
|
||||||
|
if lead >= 0 and tail >= 0 and center > lead + tail and lead + tail > 0:
|
||||||
|
local = (
|
||||||
|
*((Move(straight, steps=lead // pitch),) if lead else ()), *out_moves,
|
||||||
|
Move(straight, steps=(center - lead - tail) // pitch), *in_moves,
|
||||||
|
*((Move(straight, steps=tail // pitch),) if tail else ()),
|
||||||
|
)
|
||||||
|
candidates.append((cost, lane, False, local))
|
||||||
|
middle = Move(straight, steps=center // pitch)
|
||||||
|
full_span = (*out_moves, middle, *in_moves)
|
||||||
|
candidates.append((cost, lane, True, full_span))
|
||||||
|
if widen:
|
||||||
|
# Place the profile changes on the parallel run between the two jogs.
|
||||||
|
for replacement in straight_replacements(self.evaluator, start, middle):
|
||||||
|
if len(replacement) != 3:
|
||||||
|
continue
|
||||||
|
first, body, last = replacement
|
||||||
|
entry, exit_variant = variants[first.variant], variants[last.variant]
|
||||||
|
assert body.steps is not None
|
||||||
|
assert not isinstance(entry, StraightVariant)
|
||||||
|
assert not isinstance(exit_variant, StraightVariant)
|
||||||
|
wide_cost = body.steps * pitch * price_scale * self._straight_prices[body.variant]
|
||||||
|
saving = center * unit_price - wide_cost - entry.cost - exit_variant.cost
|
||||||
|
if saving > COST_TOLERANCE:
|
||||||
|
candidates.append((cost - saving, lane, True, (*out_moves, *replacement, *in_moves)))
|
||||||
|
for price, _, _, recipe in sorted(candidates, key=lambda item: item[:3]):
|
||||||
|
yield price, recipe
|
||||||
|
|
||||||
|
def from_pose(self, start: Pose, board_bounds: tuple[float, float, float, float]) -> Iterator[Move]:
|
||||||
|
fixed = self.evaluator.local_moves(start.profile, start.heading)
|
||||||
|
runs = self._straights[start.profile]
|
||||||
|
if not fixed:
|
||||||
|
dx, dy = HEADING_STEPS[start.heading]
|
||||||
|
tx, ty = self.target.x - start.x, self.target.y - start.y
|
||||||
|
if (start.heading, start.profile) == (self.target.heading, self.target.profile) and dx * ty == dy * tx:
|
||||||
|
steps = (dx * tx + dy * ty) // (int(self.evaluator.grid.pitch) * (dx * dx + dy * dy))
|
||||||
|
if steps > 0:
|
||||||
|
for name in runs:
|
||||||
|
yield Move(name, steps=steps)
|
||||||
|
return
|
||||||
|
if runs:
|
||||||
|
targets = self._straight_steps(start, fixed, board_bounds)
|
||||||
|
for steps in targets:
|
||||||
|
for name in runs:
|
||||||
|
yield Move(name, steps=steps)
|
||||||
|
for move, _ in fixed:
|
||||||
|
yield move
|
||||||
|
|
||||||
|
def _project_blockers(
|
||||||
|
self, profile: str, heading: int, fixed: Sequence[tuple[Move, Pose]],
|
||||||
|
) -> tuple[float, tuple[int, ...], tuple[_BlockerProjection, ...]]:
|
||||||
|
key = profile, heading
|
||||||
|
if key not in self._blocker_projections:
|
||||||
|
dx, dy = HEADING_STEPS[heading]
|
||||||
|
margin = self.clearance + self.evaluator.catalog.profiles[profile].width / 2
|
||||||
|
side_reach = margin * (dx * dx + dy * dy) + max(abs(dx * end.y - dy * end.x) for _, end in fixed)
|
||||||
|
offsets = {0, *(dx * end.x + dy * end.y for _, end in fixed)}
|
||||||
|
ox, oy = self.origin
|
||||||
|
projections = []
|
||||||
|
for bx0, by0, bx1, by1 in self.blocker_bounds:
|
||||||
|
side = [dx * (y - oy) - dy * (x - ox) for x in (bx0, bx1) for y in (by0, by1)]
|
||||||
|
xs = (bx0 - margin, bx0, bx1, bx1 + margin) if dx else (ox,)
|
||||||
|
ys = (by0 - margin, by0, by1, by1 + margin) if dy else (oy,)
|
||||||
|
along = {dx * (x - ox) + dy * (y - oy) for x in xs for y in ys}
|
||||||
|
projections.append((min(side), max(side), tuple(along)))
|
||||||
|
self._blocker_projections[key] = side_reach, tuple(offsets), tuple(projections)
|
||||||
|
return self._blocker_projections[key]
|
||||||
|
|
||||||
|
def _aligned_exits(self, profile: str, heading: int, fixed: Sequence[tuple[Move, Pose]]) -> dict[int, set[int]]:
|
||||||
|
key = profile, heading
|
||||||
|
if key not in self._exit_alignments:
|
||||||
|
dx, dy = HEADING_STEPS[heading]
|
||||||
|
offsets: dict[int, set[int]] = {}
|
||||||
|
|
||||||
|
def add_exit(x: int, y: int, exit_heading: int) -> None:
|
||||||
|
ex, ey = HEADING_STEPS[exit_heading]
|
||||||
|
offset = x * ey - y * ex if dx * ey != dy * ex else dx * x + dy * y
|
||||||
|
offsets.setdefault(exit_heading, set()).add(offset)
|
||||||
|
|
||||||
|
for end in {end for _, end in fixed}:
|
||||||
|
add_exit(end.x, end.y, end.heading)
|
||||||
|
for _, following in self.evaluator.local_moves(end.profile, end.heading):
|
||||||
|
add_exit(end.x + following.x, end.y + following.y, following.heading)
|
||||||
|
self._exit_alignments[key] = offsets
|
||||||
|
return self._exit_alignments[key]
|
||||||
|
|
||||||
|
def _straight_steps(
|
||||||
|
self, start: Pose, fixed: Sequence[tuple[Move, Pose]], board_bounds: tuple[float, float, float, float],
|
||||||
|
) -> list[int]:
|
||||||
|
dx, dy = HEADING_STEPS[start.heading]
|
||||||
|
pitch = int(self.evaluator.grid.pitch)
|
||||||
|
x0, y0, x1, y1 = board_bounds
|
||||||
|
distance_x = (x1 - start.x) if dx > 0 else (start.x - x0) if dx < 0 else inf
|
||||||
|
distance_y = (y1 - start.y) if dy > 0 else (start.y - y0) if dy < 0 else inf
|
||||||
|
limit = floor(min(distance_x, distance_y) / pitch)
|
||||||
|
magnitude = dx * dx + dy * dy
|
||||||
|
tx, ty = self.target.x - start.x, self.target.y - start.y
|
||||||
|
steps = {limit}
|
||||||
|
|
||||||
|
def add_projection(x: float, y: float) -> None:
|
||||||
|
projected = (dx * x + dy * y) / (pitch * magnitude)
|
||||||
|
steps.update((floor(projected), ceil(projected)))
|
||||||
|
|
||||||
|
add_projection(tx, ty)
|
||||||
|
for x, y in self.guide_points:
|
||||||
|
add_projection(x - start.x, y - start.y)
|
||||||
|
for _, end in fixed:
|
||||||
|
add_projection(x - start.x - end.x, y - start.y - end.y)
|
||||||
|
|
||||||
|
for heading, offsets in self._aligned_exits(start.profile, start.heading, fixed).items():
|
||||||
|
ex, ey = HEADING_STEPS[heading]
|
||||||
|
divisor = pitch * (dx * ey - dy * ex)
|
||||||
|
if divisor:
|
||||||
|
target = tx * ey - ty * ex
|
||||||
|
for offset in offsets:
|
||||||
|
n, remainder = divmod(target - offset, divisor)
|
||||||
|
if not remainder:
|
||||||
|
steps.add(n)
|
||||||
|
else:
|
||||||
|
target = dx * tx + dy * ty
|
||||||
|
for offset in offsets:
|
||||||
|
span = (target - offset) / (pitch * magnitude)
|
||||||
|
steps.update((floor(span), ceil(span)))
|
||||||
|
|
||||||
|
# Obstacle edges and the inverse displacement of fixed cells create
|
||||||
|
# interior launch points even when a long straight has clear reach.
|
||||||
|
side_reach, offsets, blockers = self._project_blockers(start.profile, start.heading, fixed)
|
||||||
|
x, y = start.x - self.origin[0], start.y - self.origin[1]
|
||||||
|
side = dx * y - dy * x
|
||||||
|
along = dx * x + dy * y
|
||||||
|
divisor = pitch * magnitude
|
||||||
|
boundaries = set()
|
||||||
|
for lo, hi, projections in blockers:
|
||||||
|
if lo <= side + side_reach and hi >= side - side_reach:
|
||||||
|
boundaries.update(projections)
|
||||||
|
for boundary in boundaries:
|
||||||
|
distance = boundary - along
|
||||||
|
for offset in offsets:
|
||||||
|
span = (distance - offset) / divisor
|
||||||
|
steps.update((floor(span), ceil(span)))
|
||||||
|
if self.scan_steps and (boundaries or not self._is_forward_only(start.profile, start.heading)):
|
||||||
|
steps.add(1)
|
||||||
|
return sorted((n for n in steps if 0 < n <= limit), reverse=True)
|
||||||
|
|
||||||
|
|
||||||
|
def _continues(
|
||||||
|
evaluator: MoveEvaluator,
|
||||||
|
parent: _Arrival | None,
|
||||||
|
move: Evaluation,
|
||||||
|
occupied: STRtree,
|
||||||
|
clearance: float,
|
||||||
|
self_clearance: float,
|
||||||
|
face_tolerance: float,
|
||||||
|
) -> bool:
|
||||||
|
if parent is None:
|
||||||
|
return True
|
||||||
|
width = evaluator.catalog.profiles[move.start.profile].width
|
||||||
|
if not compatible_join(parent.move, move, width, face_tolerance):
|
||||||
|
return False
|
||||||
|
if len(occupied):
|
||||||
|
seam = face_reservation(move.start, width, face_tolerance)
|
||||||
|
if any(_violates_net_clearance(seam, other, clearance) for other in _colliders(occupied, (seam,), clearance)):
|
||||||
|
return False
|
||||||
|
earlier = parent.previous
|
||||||
|
while earlier is not None:
|
||||||
|
uncertain = parent.unknown_lengths != earlier.unknown_lengths
|
||||||
|
spacing = self_clearance if uncertain or parent.length - earlier.length >= self_clearance else 0.0
|
||||||
|
if any(_violates_net_clearance(a, b, spacing) for a in earlier.move.footprints for b in move.footprints):
|
||||||
|
return False
|
||||||
|
earlier = earlier.previous
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def search_path(
|
||||||
|
evaluator: MoveEvaluator,
|
||||||
|
start: Pose,
|
||||||
|
target: Pose,
|
||||||
|
*,
|
||||||
|
board: Polygon,
|
||||||
|
keepouts: Sequence[BaseGeometry] = (),
|
||||||
|
occupied: Sequence[BaseGeometry] = (),
|
||||||
|
clearance: float = 0.0,
|
||||||
|
self_clearance: float = 0.0,
|
||||||
|
face_tolerance: float = 0.0,
|
||||||
|
node_limit: int = 1000,
|
||||||
|
arrivals_per_pose: int = 3,
|
||||||
|
source_attachment: Attachment | None = None,
|
||||||
|
destination_attachment: Attachment | None = None,
|
||||||
|
excluded_paths: Sequence[tuple[Move, ...]] = (),
|
||||||
|
max_cost: float = inf,
|
||||||
|
corridor: Corridor | None = None,
|
||||||
|
scan_steps: bool = False,
|
||||||
|
bias: SearchBias | None = None,
|
||||||
|
method: Literal["detailed", "constructive_first", "constructive_only"] = "detailed",
|
||||||
|
constructive_profiles: bool = False,
|
||||||
|
cache: VerificationCache | None = None,
|
||||||
|
) -> SearchResult:
|
||||||
|
"""Search physical paths while retaining a bounded number of distinct arrival histories."""
|
||||||
|
_require_integer(node_limit)
|
||||||
|
_require_integer(arrivals_per_pose)
|
||||||
|
if node_limit < 0 or arrivals_per_pose < 1:
|
||||||
|
raise ValueError("Search requires a nonnegative node limit and positive arrival limit")
|
||||||
|
if any(value < 0 or not isfinite(value) for value in (clearance, self_clearance, face_tolerance)):
|
||||||
|
raise ValueError("Clearance and face tolerance must be finite and nonnegative")
|
||||||
|
for port in (start, target):
|
||||||
|
if evaluator.grid.lattice_position(port.x, port.y) is None or port.profile not in evaluator.catalog.profiles:
|
||||||
|
raise ValueError(f"Invalid catalog terminal {port!r}")
|
||||||
|
attached = {}
|
||||||
|
end_permissions = []
|
||||||
|
for attachment, pose, source in ((source_attachment, start, True), (destination_attachment, target, False)):
|
||||||
|
if attachment is not None:
|
||||||
|
validate_attachment(evaluator, attachment, pose, keepouts, face_tolerance, source=source)
|
||||||
|
attached[id(attachment.obstacle)] = attachment.obstacle
|
||||||
|
seam = face_reservation(pose, evaluator.catalog.profiles[pose.profile].width, face_tolerance)
|
||||||
|
end_permissions.append((attachment, seam, source))
|
||||||
|
proposals = _Proposals(evaluator, start, target, (*keepouts, *occupied), clearance, corridor, scan_steps, cache)
|
||||||
|
|
||||||
|
origin = start.x, start.y, start.heading, start.profile
|
||||||
|
initial_bound: float | None = None
|
||||||
|
if method == "detailed":
|
||||||
|
proposals.prepare_detailed()
|
||||||
|
initial_bound = proposals.lower_bound(origin)
|
||||||
|
if initial_bound == inf or initial_bound > max_cost + COST_TOLERANCE:
|
||||||
|
return SearchResult(None, "exhausted", 0, 0)
|
||||||
|
incumbent = None
|
||||||
|
macro_trials = macro_checks = 0
|
||||||
|
placements: dict[tuple[Pose, Move], Evaluation | None] = {}
|
||||||
|
recipes = proposals.two_turn_recipes(start)
|
||||||
|
if method != "detailed":
|
||||||
|
aligned = proposals.aligned_recipes(start) if constructive_profiles else ()
|
||||||
|
recipes = chain(
|
||||||
|
aligned, proposals.direct_recipes(start), recipes,
|
||||||
|
proposals.detour_recipes(start, widen=constructive_profiles and corridor is None),
|
||||||
|
)
|
||||||
|
elif bias is None:
|
||||||
|
aligned = proposals.aligned_recipes(start)
|
||||||
|
if aligned:
|
||||||
|
bound = proposals.aligned_lower_bound(start, aligned[0][0])
|
||||||
|
if aligned[0][0] <= bound + COST_TOLERANCE:
|
||||||
|
assert initial_bound is not None
|
||||||
|
initial_bound = max(initial_bound, bound)
|
||||||
|
if initial_bound > max_cost + COST_TOLERANCE:
|
||||||
|
return SearchResult(None, "exhausted", 0, 0)
|
||||||
|
recipes = chain((item for item in aligned if item[0] <= bound + COST_TOLERANCE), recipes)
|
||||||
|
for price, recipe in islice(recipes, min(node_limit // 2, 48)):
|
||||||
|
macro_trials += 1
|
||||||
|
if recipe in excluded_paths or (
|
||||||
|
price > max_cost and not isclose(price, max_cost, rel_tol=1e-15, abs_tol=COST_TOLERANCE)
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
path = replay_moves(evaluator, start, recipe, placements=placements)
|
||||||
|
if path is None or (corridor is not None and any(not corridor.admits(move.end) for move in path)):
|
||||||
|
continue
|
||||||
|
cost = fsum(move.cost for move in path)
|
||||||
|
if cost >= max_cost:
|
||||||
|
continue
|
||||||
|
macro_checks += 1
|
||||||
|
if verify_path(
|
||||||
|
evaluator, path, start, target, board=board, keepouts=keepouts, occupied=occupied, clearance=clearance,
|
||||||
|
self_clearance=self_clearance, face_tolerance=face_tolerance,
|
||||||
|
source_attachment=source_attachment, destination_attachment=destination_attachment, cache=cache, defer_faces=True,
|
||||||
|
) is None:
|
||||||
|
incumbent = path
|
||||||
|
max_cost = cost
|
||||||
|
if method == "constructive_first" or (
|
||||||
|
bias is None and initial_bound is not None and cost <= initial_bound + COST_TOLERANCE
|
||||||
|
):
|
||||||
|
return SearchResult(path, "verified", 0, macro_trials, geometry_checks=macro_checks)
|
||||||
|
if method == "constructive_only":
|
||||||
|
return SearchResult(incumbent, "verified" if incumbent is not None else "exhausted", 0, macro_trials, geometry_checks=macro_checks)
|
||||||
|
if initial_bound is None:
|
||||||
|
proposals.prepare_detailed()
|
||||||
|
initial_bound = proposals.lower_bound(origin)
|
||||||
|
if initial_bound == inf or initial_bound > max_cost + COST_TOLERANCE:
|
||||||
|
return SearchResult(incumbent, "verified" if incumbent is not None else "exhausted", 0, macro_trials,
|
||||||
|
geometry_checks=macro_checks)
|
||||||
|
# Queue moves using only their output pose and a cost lower bound.
|
||||||
|
# A move that can still win is materialized and may be requeued with its
|
||||||
|
# full cost and geometry-dependent penalty before consuming an arrival.
|
||||||
|
obstacles = [obstacle for obstacle in keepouts if id(obstacle) not in attached]
|
||||||
|
ordinary_keepouts = cache.tree(obstacles, installed=False) if cache is not None else STRtree(obstacles)
|
||||||
|
installed = cache.tree(occupied, installed=True) if cache is not None else STRtree(occupied)
|
||||||
|
guide_axis = LineString(corridor.points) if bias is not None and bias.guide and corridor is not None and len(corridor.points) > 1 else None
|
||||||
|
order = count()
|
||||||
|
queue: list[tuple[float, float, int, _Position, _Arrival | _PendingMove | None]] = [
|
||||||
|
(initial_bound, initial_bound, next(order), origin, None),
|
||||||
|
]
|
||||||
|
expanded = cache_hits = 0
|
||||||
|
proposed, geometry_checks = macro_trials, macro_checks
|
||||||
|
visits: dict[_Position, int] = {}
|
||||||
|
evaluated: dict[tuple[Pose, Move], Evaluation | None] = {}
|
||||||
|
board_bounds = board.bounds
|
||||||
|
while queue and expanded < node_limit:
|
||||||
|
priority, distance_cost, ordinal, position, pending = heappop(queue)
|
||||||
|
prior = visits.get(position, 0)
|
||||||
|
if prior >= arrivals_per_pose:
|
||||||
|
continue
|
||||||
|
if isinstance(pending, _PendingMove):
|
||||||
|
move_start, spec, parent = pending.start, pending.spec, pending.previous
|
||||||
|
if parent is not None and spec.steps is not None:
|
||||||
|
previous = parent.move.move
|
||||||
|
if previous.variant == spec.variant and previous.steps is not None:
|
||||||
|
combined = Move(spec.variant, steps=previous.steps + spec.steps)
|
||||||
|
if evaluated.get((parent.move.start, combined)) is not None:
|
||||||
|
continue
|
||||||
|
source_can_attach = parent is None or parent.source_can_attach
|
||||||
|
prefix_cost = parent.cost if parent is not None else 0.0
|
||||||
|
key = (move_start, spec)
|
||||||
|
if key not in evaluated:
|
||||||
|
move = evaluator.evaluate(spec, move_start)
|
||||||
|
if move is not None and corridor is not None and not corridor.admits(move.end):
|
||||||
|
move = None
|
||||||
|
if move is not None:
|
||||||
|
geometry_checks += 1
|
||||||
|
if verify_move(
|
||||||
|
evaluator, move, board,
|
||||||
|
_colliders(ordinary_keepouts, move.footprints, clearance), _colliders(installed, move.footprints, clearance),
|
||||||
|
clearance, face_tolerance,
|
||||||
|
):
|
||||||
|
move = None
|
||||||
|
evaluated[key] = move
|
||||||
|
else:
|
||||||
|
cache_hits += 1
|
||||||
|
move = evaluated[key]
|
||||||
|
if move is None:
|
||||||
|
continue
|
||||||
|
allowed = {
|
||||||
|
key: tuple(
|
||||||
|
(attachment, seam) for attachment, seam, source in end_permissions
|
||||||
|
if id(attachment.obstacle) == key and (not source or source_can_attach)
|
||||||
|
)
|
||||||
|
for key in attached
|
||||||
|
}
|
||||||
|
# Source permission depends on the arrival history. Destination
|
||||||
|
# permission is provisional until final verification checks the suffix.
|
||||||
|
if any(not meets_attachment_clearance(move, obstacle, allowed[key], clearance) for key, obstacle in attached.items()):
|
||||||
|
continue
|
||||||
|
if not _continues(evaluator, parent, move, installed, clearance, self_clearance, face_tolerance):
|
||||||
|
continue
|
||||||
|
step_length = move.length if move.length is not None else hypot(move.end.x - move.start.x, move.end.y - move.start.y)
|
||||||
|
penalty = parent.priority_penalty if parent is not None else 0.0
|
||||||
|
if bias is not None:
|
||||||
|
length_factor = step_length / bias.range
|
||||||
|
penalty += _geometry_bias(move, ordinary_keepouts, bias.range, bias.proximity, length_factor)
|
||||||
|
penalty += _geometry_bias(move, installed, bias.range, bias.congestion, length_factor)
|
||||||
|
if guide_axis is not None:
|
||||||
|
penalty += bias.guide * length_factor * guide_axis.distance(Point(move.end.x, move.end.y)) / bias.range
|
||||||
|
arrival = _Arrival(
|
||||||
|
move, parent, prefix_cost + move.cost,
|
||||||
|
(parent.length if parent is not None else 0) + (move.length or 0.0),
|
||||||
|
(parent.unknown_lengths if parent is not None else 0) + (move.length is None),
|
||||||
|
source_can_attach and source_attachment is not None and wholly_in_attachment(move, source_attachment),
|
||||||
|
penalty,
|
||||||
|
)
|
||||||
|
if arrival.cost + distance_cost > max_cost + COST_TOLERANCE:
|
||||||
|
continue
|
||||||
|
exact_priority = round(arrival.cost + distance_cost + penalty, 12)
|
||||||
|
if exact_priority != priority:
|
||||||
|
heappush(queue, (exact_priority, distance_cost, ordinal, position, arrival))
|
||||||
|
continue
|
||||||
|
parent = arrival
|
||||||
|
else:
|
||||||
|
parent = pending
|
||||||
|
pose = parent.move.end if parent is not None else start
|
||||||
|
visits[position] = prior + 1
|
||||||
|
expanded += 1
|
||||||
|
if parent is not None and pose == target:
|
||||||
|
path = _placed_path(parent)
|
||||||
|
if (incumbent is None or fsum(move.cost for move in path) < max_cost - COST_TOLERANCE) and (
|
||||||
|
path_recipe(path) not in excluded_paths
|
||||||
|
) and verify_path(
|
||||||
|
evaluator, path, start, target, board=board, keepouts=keepouts, occupied=occupied,
|
||||||
|
clearance=clearance, self_clearance=self_clearance, face_tolerance=face_tolerance,
|
||||||
|
source_attachment=source_attachment, destination_attachment=destination_attachment, cache=cache,
|
||||||
|
) is None:
|
||||||
|
return SearchResult(
|
||||||
|
path, "verified", expanded, proposed, geometry_checks=geometry_checks,
|
||||||
|
geometry_cache_hits=cache_hits, geometry_cache_entries=len(evaluated),
|
||||||
|
)
|
||||||
|
prefix_cost = parent.cost if parent is not None else 0.0
|
||||||
|
penalty = parent.priority_penalty if parent is not None else 0.0
|
||||||
|
for spec in proposals.from_pose(pose, board_bounds):
|
||||||
|
proposed += 1
|
||||||
|
preview = proposals.destination_bound(pose, spec)
|
||||||
|
if preview is None:
|
||||||
|
continue
|
||||||
|
expected, base_cost = preview
|
||||||
|
if visits.get(expected, 0) >= arrivals_per_pose:
|
||||||
|
continue
|
||||||
|
distance_cost = proposals.lower_bound(expected)
|
||||||
|
if distance_cost == inf or prefix_cost + base_cost + distance_cost > max_cost + COST_TOLERANCE:
|
||||||
|
continue
|
||||||
|
estimated_priority = round(prefix_cost + base_cost + distance_cost + penalty, 12)
|
||||||
|
heappush(queue, (estimated_priority, distance_cost, next(order), expected, _PendingMove(spec, pose, parent)))
|
||||||
|
|
||||||
|
return SearchResult(
|
||||||
|
incumbent, "verified" if incumbent is not None else ("node_limit" if queue else "exhausted"),
|
||||||
|
expanded, proposed, geometry_checks=geometry_checks, geometry_cache_hits=cache_hits,
|
||||||
|
geometry_cache_entries=len(evaluated), budget_exhausted=bool(queue),
|
||||||
|
)
|
||||||
200
inire/router/_catalog_tuning.py
Normal file
200
inire/router/_catalog_tuning.py
Normal file
|
|
@ -0,0 +1,200 @@
|
||||||
|
"""Propose four-turn replacements inside supplied tuning windows."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from collections import deque
|
||||||
|
from dataclasses import replace
|
||||||
|
from itertools import product
|
||||||
|
from math import ceil, floor, inf
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from shapely import get_parts
|
||||||
|
from shapely.geometry import LineString
|
||||||
|
|
||||||
|
from inire._catalog import HEADING_STEPS, Move, StraightVariant
|
||||||
|
from inire._catalog_timing import evaluate_delay
|
||||||
|
from inire._snapshot import snapshot
|
||||||
|
|
||||||
|
from ._catalog_matching import DelayChoice, MatchResult, choose_match
|
||||||
|
from ._catalog_verify import replay_moves
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from collections.abc import Callable, Iterator, Mapping, Sequence
|
||||||
|
|
||||||
|
from shapely.geometry import Polygon
|
||||||
|
|
||||||
|
from inire._catalog import Evaluation, MoveEvaluator, Pose
|
||||||
|
from inire._catalog_timing import DelayModel
|
||||||
|
|
||||||
|
from ._catalog_matching import MatchGroup
|
||||||
|
|
||||||
|
|
||||||
|
def _eligible_spans(
|
||||||
|
evaluator: MoveEvaluator, path: Sequence[Evaluation], window: Polygon,
|
||||||
|
) -> Iterator[tuple[int, Evaluation, int, int]]:
|
||||||
|
pitch = int(evaluator.grid.pitch)
|
||||||
|
for index, straight in enumerate(path):
|
||||||
|
if not isinstance(evaluator.catalog.variants[straight.move.variant], StraightVariant):
|
||||||
|
continue
|
||||||
|
steps = straight.move.steps
|
||||||
|
assert steps is not None
|
||||||
|
dx, dy = HEADING_STEPS[straight.start.heading]
|
||||||
|
norm_squared = dx * dx + dy * dy
|
||||||
|
section = LineString(((straight.start.x, straight.start.y), (straight.end.x, straight.end.y)))
|
||||||
|
for part in get_parts(section.intersection(window)):
|
||||||
|
if not isinstance(part, LineString) or part.is_empty:
|
||||||
|
continue
|
||||||
|
positions = [((x - straight.start.x) * dx + (y - straight.start.y) * dy) / (pitch * norm_squared) for x, y in part.coords]
|
||||||
|
first = max(0, ceil(min(positions) - 1e-10))
|
||||||
|
last = min(steps, floor(max(positions) + 1e-10))
|
||||||
|
if first < last:
|
||||||
|
yield index, straight, first, last
|
||||||
|
|
||||||
|
|
||||||
|
def window_replacements(
|
||||||
|
evaluator: MoveEvaluator, path: Sequence[Evaluation], window: Polygon,
|
||||||
|
) -> Iterator[tuple[Evaluation, ...] | None]:
|
||||||
|
"""Yield bounded-grid detour proposals, including rejected evaluations for budget accounting."""
|
||||||
|
for index, straight, first, last in _eligible_spans(evaluator, path, window):
|
||||||
|
inset = max(1, (last - first) // 8)
|
||||||
|
spans = ((first, last), (first + inset, last), (first, last - inset), (first + inset, last - inset))
|
||||||
|
pending = deque(
|
||||||
|
_doglegs(evaluator, straight, window, a, b, sign)
|
||||||
|
for a, b in spans if a < b for sign in (1, -1)
|
||||||
|
)
|
||||||
|
while pending:
|
||||||
|
generator = pending.popleft()
|
||||||
|
try:
|
||||||
|
proposal = next(generator)
|
||||||
|
except StopIteration:
|
||||||
|
continue
|
||||||
|
pending.append(generator)
|
||||||
|
if proposal is None:
|
||||||
|
yield None
|
||||||
|
else:
|
||||||
|
yield (*path[:index], *proposal, *path[index + 1:])
|
||||||
|
|
||||||
|
|
||||||
|
def _doglegs(
|
||||||
|
evaluator: MoveEvaluator, straight: Evaluation, window: Polygon, first: int, last: int, sign: int,
|
||||||
|
) -> Iterator[tuple[Evaluation, ...] | None]:
|
||||||
|
start = straight.start
|
||||||
|
steps = straight.move.steps
|
||||||
|
assert steps is not None
|
||||||
|
pitch = int(evaluator.grid.pitch)
|
||||||
|
dx, dy = HEADING_STEPS[start.heading]
|
||||||
|
denom = pitch * (dx * dx + dy * dy)
|
||||||
|
x0, y0, x1, y1 = window.bounds
|
||||||
|
width_limit = ceil((abs(dy) * (x1 - x0) + abs(dx) * (y1 - y0)) / denom)
|
||||||
|
straight_name = straight.move.variant
|
||||||
|
turn = sign * 90
|
||||||
|
headings = (start.heading, (start.heading + turn) % 360, start.heading, (start.heading - turn) % 360, start.heading)
|
||||||
|
catalog_turns = [
|
||||||
|
tuple(
|
||||||
|
(move, end) for move, end in evaluator.local_moves(start.profile, entry)
|
||||||
|
if end.heading == exit and end.profile == start.profile
|
||||||
|
)
|
||||||
|
for entry, exit in zip(headings[:-1], headings[1:], strict=True)
|
||||||
|
]
|
||||||
|
begin = start.shifted(first * dx * pitch, first * dy * pitch)
|
||||||
|
end = start.shifted(last * dx * pitch, last * dy * pitch)
|
||||||
|
prefix = replay_moves(evaluator, start, (Move(straight_name, steps=first),)) if first else ()
|
||||||
|
suffix = replay_moves(evaluator, end, (Move(straight_name, steps=steps - last),)) if last < steps else ()
|
||||||
|
assert prefix is not None
|
||||||
|
assert suffix is not None
|
||||||
|
placements: dict[tuple[Pose, Move], Evaluation | None] = {}
|
||||||
|
for turns in product(*catalog_turns):
|
||||||
|
offsets_x = sum(end.x for _, end in turns)
|
||||||
|
offsets_y = sum(end.y for _, end in turns)
|
||||||
|
along, remainder = divmod(dx * offsets_x + dy * offsets_y, denom)
|
||||||
|
sideways, lateral_remainder = divmod(sign * (-dy * offsets_x + dx * offsets_y), denom)
|
||||||
|
forward = last - first - along
|
||||||
|
if remainder or lateral_remainder or forward < 0:
|
||||||
|
yield None
|
||||||
|
continue
|
||||||
|
for height in range(max(0, -sideways), width_limit + 1):
|
||||||
|
return_height = height + sideways
|
||||||
|
legs = (height, forward, return_height, 0)
|
||||||
|
replacement = []
|
||||||
|
for (turn_move, _), leg in zip(turns, legs, strict=True):
|
||||||
|
replacement.append(turn_move)
|
||||||
|
if leg:
|
||||||
|
replacement.append(Move(straight_name, steps=leg))
|
||||||
|
if len(placements) >= 256:
|
||||||
|
placements.clear()
|
||||||
|
trial = replay_moves(evaluator, begin, replacement, placements=placements)
|
||||||
|
if trial is None or any(not window.covers(shape) for move in trial for shape in move.footprints):
|
||||||
|
yield None
|
||||||
|
continue
|
||||||
|
yield (*prefix, *trial, *suffix)
|
||||||
|
|
||||||
|
def tune_group(
|
||||||
|
evaluator: MoveEvaluator,
|
||||||
|
group: MatchGroup,
|
||||||
|
models: DelayModel,
|
||||||
|
baselines: Mapping[str, tuple[Evaluation, ...] | None],
|
||||||
|
windows: Mapping[str, Polygon],
|
||||||
|
verifies: Callable[[str, tuple[Evaluation, ...]], bool],
|
||||||
|
*,
|
||||||
|
proposal_limit: int,
|
||||||
|
) -> tuple[MatchResult, dict[str, tuple[Evaluation, ...]]]:
|
||||||
|
if proposal_limit < 0:
|
||||||
|
raise ValueError("Tuning proposal limit must be nonnegative")
|
||||||
|
model = replace(models, wavelength=group.wavelength)
|
||||||
|
delays = {}
|
||||||
|
choices: dict[str, list[DelayChoice]] = {}
|
||||||
|
for net in group.offsets:
|
||||||
|
path = baselines[net]
|
||||||
|
if path is not None and (delay := evaluate_delay(evaluator, path, model, net_id=net)) is not None:
|
||||||
|
delays[net] = delay
|
||||||
|
choices[net] = [DelayChoice(path, delay)]
|
||||||
|
if len(choices) != len(group.offsets):
|
||||||
|
status = "unrouted" if any(baselines[net] is None for net in group.offsets) else "missing_delay"
|
||||||
|
return MatchResult(group.group_id, status, snapshot(delays), None), {}
|
||||||
|
|
||||||
|
selected, skew, matched = choose_match(group, choices)
|
||||||
|
if matched:
|
||||||
|
return MatchResult(group.group_id, "matched", snapshot(delays), skew), {}
|
||||||
|
active = tuple((net, choices[net][0].path, windows[net]) for net in group.offsets if net in windows)
|
||||||
|
eligible_spans = sum(1 for _, path, window in active for _ in _eligible_spans(evaluator, path, window))
|
||||||
|
pending = deque((net, window_replacements(evaluator, path, window)) for net, path, window in active)
|
||||||
|
# Preserve verification before invoking caller-supplied characterization.
|
||||||
|
verify_first = any(callable(value) for value in (
|
||||||
|
*model.group_indices.values(), *model.bend_group_indices.values(), *model.variant_delays.values(),
|
||||||
|
*(value for net, _, _ in active for value in model.fixed_contributions.get(net, ())),
|
||||||
|
))
|
||||||
|
verified_costs: dict[str, dict[float, float]] = {net: {} for net, _, _ in active}
|
||||||
|
proposed = accepted = 0
|
||||||
|
while pending and proposed < proposal_limit:
|
||||||
|
net, generator = pending.popleft()
|
||||||
|
try:
|
||||||
|
path = next(generator)
|
||||||
|
except StopIteration:
|
||||||
|
continue
|
||||||
|
pending.append((net, generator))
|
||||||
|
proposed += 1
|
||||||
|
if path is None or (verify_first and not verifies(net, path)):
|
||||||
|
continue
|
||||||
|
delay = evaluate_delay(evaluator, path, model, net_id=net)
|
||||||
|
if delay is None or delay.optical_length <= choices[net][0].delay.optical_length:
|
||||||
|
accepted += int(verify_first or verifies(net, path))
|
||||||
|
continue
|
||||||
|
choice = DelayChoice(path, delay)
|
||||||
|
if not verify_first:
|
||||||
|
adjusted = getattr(delay, group.units) - group.offsets[net]
|
||||||
|
cost = choice.cost
|
||||||
|
# A previously verified choice at the same adjusted delay wins on
|
||||||
|
# cost or proposal order. An unverified choice cannot dominate.
|
||||||
|
if cost >= verified_costs[net].get(adjusted, inf) or not verifies(net, path):
|
||||||
|
continue
|
||||||
|
verified_costs[net][adjusted] = cost
|
||||||
|
accepted += 1
|
||||||
|
choices[net].append(choice)
|
||||||
|
exhausted = bool(pending)
|
||||||
|
selected, skew, matched = choose_match(group, choices)
|
||||||
|
delays = {net: option.delay for net, option in selected.items()}
|
||||||
|
modified = {net: option.path for net, option in selected.items() if option is not choices[net][0]}
|
||||||
|
return MatchResult(
|
||||||
|
group.group_id, "matched" if matched else "unmatched", snapshot(delays), skew, exhausted, accepted > 0,
|
||||||
|
proposed, accepted, eligible_spans,
|
||||||
|
), modified
|
||||||
355
inire/router/_catalog_verify.py
Normal file
355
inire/router/_catalog_verify.py
Normal file
|
|
@ -0,0 +1,355 @@
|
||||||
|
"""Geometry verification shared by catalog replay and routing."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from itertools import accumulate, combinations
|
||||||
|
from math import hypot, isfinite, isnan, ulp
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from shapely import box
|
||||||
|
from shapely.affinity import affine_transform
|
||||||
|
from shapely.geometry import LineString, Polygon
|
||||||
|
from shapely.strtree import STRtree
|
||||||
|
|
||||||
|
from inire._catalog import HEADING_STEPS, face_endpoints
|
||||||
|
from inire.geometry.collision import _violates_clearance, _violates_net_clearance
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from collections.abc import Iterable, Sequence
|
||||||
|
|
||||||
|
from shapely.geometry.base import BaseGeometry
|
||||||
|
|
||||||
|
from inire._catalog import Evaluation, Move, MoveEvaluator, Pose
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class Attachment:
|
||||||
|
"""Permission to meet a specific fixed obstacle at one terminal."""
|
||||||
|
|
||||||
|
obstacle: BaseGeometry
|
||||||
|
region: Polygon
|
||||||
|
actual_shapes: tuple[Polygon, ...] = ()
|
||||||
|
|
||||||
|
|
||||||
|
class VerificationCache:
|
||||||
|
"""Reuse immutable geometry work within a single layout attempt."""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self._bounds: dict[int, tuple[BaseGeometry, tuple[float, float, float, float]]] = {}
|
||||||
|
self._faces: dict[tuple[int, float, float, float], tuple[Evaluation, bool]] = {}
|
||||||
|
self._trees: dict[bool, tuple[tuple[int, ...], STRtree]] = {}
|
||||||
|
|
||||||
|
def bounds(self, shape: BaseGeometry) -> tuple[float, float, float, float]:
|
||||||
|
key = id(shape)
|
||||||
|
cached = self._bounds.get(key)
|
||||||
|
if cached is None:
|
||||||
|
if len(self._bounds) >= 4096:
|
||||||
|
self._bounds.clear()
|
||||||
|
cached = shape, shape.bounds
|
||||||
|
self._bounds[key] = cached
|
||||||
|
return cached[1]
|
||||||
|
|
||||||
|
def faces(self, move: Evaluation, start_width: float, end_width: float, tolerance: float) -> bool:
|
||||||
|
key = id(move), start_width, end_width, tolerance
|
||||||
|
cached = self._faces.get(key)
|
||||||
|
if cached is None:
|
||||||
|
if len(self._faces) >= 4096:
|
||||||
|
self._faces.clear()
|
||||||
|
cached = move, _move_faces_match(move, start_width, end_width, tolerance)
|
||||||
|
self._faces[key] = cached
|
||||||
|
return cached[1]
|
||||||
|
|
||||||
|
def tree(self, shapes: Sequence[BaseGeometry], *, installed: bool) -> STRtree:
|
||||||
|
key = tuple(map(id, shapes))
|
||||||
|
cached = self._trees.get(installed)
|
||||||
|
if cached is None or cached[0] != key:
|
||||||
|
cached = key, STRtree(shapes)
|
||||||
|
self._trees[installed] = cached
|
||||||
|
return cached[1]
|
||||||
|
|
||||||
|
|
||||||
|
def validate_attachment(
|
||||||
|
evaluator: MoveEvaluator,
|
||||||
|
attachment: Attachment,
|
||||||
|
pose: Pose,
|
||||||
|
keepouts: Sequence[BaseGeometry],
|
||||||
|
face_tolerance: float,
|
||||||
|
*,
|
||||||
|
source: bool,
|
||||||
|
) -> None:
|
||||||
|
if not any(attachment.obstacle is obstacle for obstacle in keepouts):
|
||||||
|
raise ValueError("An attachment must identify a registered keepout")
|
||||||
|
if attachment.region.is_empty or not attachment.region.is_valid or not attachment.region.covers(
|
||||||
|
face_reservation(pose, evaluator.catalog.profiles[pose.profile].width, 0),
|
||||||
|
):
|
||||||
|
raise ValueError("An attachment region must be valid and cover the entire terminal face")
|
||||||
|
if any(
|
||||||
|
shape.is_empty or not shape.is_valid or not attachment.obstacle.covers(shape)
|
||||||
|
for shape in attachment.actual_shapes
|
||||||
|
):
|
||||||
|
raise ValueError("Fixed attachment shapes must be valid and inside the registered keepout")
|
||||||
|
actual = attachment.actual_shapes or (attachment.obstacle,)
|
||||||
|
width = evaluator.catalog.profiles[pose.profile].width
|
||||||
|
if not _matches_face(actual, pose, width, face_tolerance, arrival=source):
|
||||||
|
raise ValueError("Fixed attachment geometry does not meet its declared port face")
|
||||||
|
|
||||||
|
|
||||||
|
def wholly_in_attachment(move: Evaluation, attachment: Attachment) -> bool:
|
||||||
|
return all(attachment.region.covers(shape) for shape in move.footprints)
|
||||||
|
|
||||||
|
|
||||||
|
def meets_attachment_clearance(
|
||||||
|
move: Evaluation,
|
||||||
|
obstacle: BaseGeometry,
|
||||||
|
permissions: Sequence[tuple[Attachment, BaseGeometry]],
|
||||||
|
clearance: float,
|
||||||
|
) -> bool:
|
||||||
|
for shape in move.footprints:
|
||||||
|
outside = shape
|
||||||
|
for attachment, _ in permissions:
|
||||||
|
if outside.intersects(attachment.region):
|
||||||
|
outside = outside.difference(attachment.region)
|
||||||
|
if not outside.is_empty and _violates_clearance(outside, obstacle, clearance):
|
||||||
|
return False
|
||||||
|
for attachment, seam in permissions:
|
||||||
|
for shape in move.port_shapes or move.footprints:
|
||||||
|
if not shape.intersects(attachment.region):
|
||||||
|
continue
|
||||||
|
inside = shape.intersection(attachment.region)
|
||||||
|
for fixed in attachment.actual_shapes or (obstacle,):
|
||||||
|
if inside.relate_pattern(fixed, "2********") and not _seam_covers(seam, inside.intersection(fixed)):
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def face_reservation(pose: Pose, width: float, tolerance: float) -> BaseGeometry:
|
||||||
|
"""The finite face and its allowed normal displacement, in layout coordinates."""
|
||||||
|
left, right = face_endpoints(pose, width)
|
||||||
|
if tolerance == 0:
|
||||||
|
return LineString((left, right))
|
||||||
|
dx, dy = HEADING_STEPS[pose.heading]
|
||||||
|
scale = tolerance / hypot(dx, dy)
|
||||||
|
x, y = dx * scale, dy * scale
|
||||||
|
return Polygon((
|
||||||
|
(left[0] - x, left[1] - y), (right[0] - x, right[1] - y),
|
||||||
|
(right[0] + x, right[1] + y), (left[0] + x, left[1] + y),
|
||||||
|
))
|
||||||
|
|
||||||
|
|
||||||
|
def _seam_covers(seam: BaseGeometry, overlap: BaseGeometry) -> bool:
|
||||||
|
if seam.covers(overlap):
|
||||||
|
return True
|
||||||
|
roundoff = 8 * ulp(max(abs(value) for value in seam.bounds))
|
||||||
|
return seam.buffer(roundoff).covers(overlap)
|
||||||
|
|
||||||
|
|
||||||
|
def _lateral_intervals(geometry: BaseGeometry) -> Iterable[tuple[float, float]]:
|
||||||
|
if geometry.is_empty:
|
||||||
|
return
|
||||||
|
if hasattr(geometry, "geoms"):
|
||||||
|
for part in geometry.geoms:
|
||||||
|
yield from _lateral_intervals(part)
|
||||||
|
else:
|
||||||
|
yield geometry.bounds[1], geometry.bounds[3]
|
||||||
|
|
||||||
|
|
||||||
|
def _matches_face(
|
||||||
|
footprints: Sequence[BaseGeometry], pose: Pose, width: float, tolerance: float, *, arrival: bool,
|
||||||
|
) -> bool:
|
||||||
|
dx, dy = HEADING_STEPS[pose.heading]
|
||||||
|
norm = hypot(dx, dy)
|
||||||
|
x, y = dx / norm, dy / norm
|
||||||
|
# Transform the face to x=0 without rotating any stored geometry.
|
||||||
|
frame = (x, y, -y, x, -(pose.x * x + pose.y * y), pose.x * y - pose.y * x)
|
||||||
|
half_width = width / 2
|
||||||
|
# Allow roundoff from projecting the footprint along a diagonal normal.
|
||||||
|
roundoff = 8 * ulp(max(abs(pose.x), abs(pose.y), width, tolerance))
|
||||||
|
local = tuple(affine_transform(shape, frame) for shape in footprints)
|
||||||
|
|
||||||
|
def covers_face(depth: float) -> bool:
|
||||||
|
reach = half_width + depth
|
||||||
|
patch = box(-depth if arrival else 0, -reach, 0 if arrival else depth, reach)
|
||||||
|
intervals = sorted(interval for shape in local for interval in _lateral_intervals(shape.intersection(patch)))
|
||||||
|
if not intervals or abs(intervals[0][0] + half_width) > roundoff:
|
||||||
|
return False
|
||||||
|
covered = intervals[0][1]
|
||||||
|
for lo, hi in intervals[1:]:
|
||||||
|
if lo > covered + roundoff:
|
||||||
|
return False
|
||||||
|
covered = max(covered, hi)
|
||||||
|
return abs(covered - half_width) <= roundoff
|
||||||
|
|
||||||
|
return covers_face(roundoff) or (tolerance > 0 and covers_face(tolerance + roundoff))
|
||||||
|
|
||||||
|
|
||||||
|
def compatible_join(left: Evaluation, right: Evaluation, width: float, tolerance: float) -> bool:
|
||||||
|
if left.end != right.start:
|
||||||
|
return False
|
||||||
|
for first in left.port_shapes or left.footprints:
|
||||||
|
for second in right.port_shapes or right.footprints:
|
||||||
|
if first.relate_pattern(second, "2********"):
|
||||||
|
seam = face_reservation(left.end, width, tolerance)
|
||||||
|
if not _seam_covers(seam, first.intersection(second)):
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def _internal_edges(path: Sequence[Evaluation], clearance: float) -> Iterable[tuple[int, int, float]]:
|
||||||
|
distances = tuple(accumulate((move.length or 0.0 for move in path), initial=0.0))
|
||||||
|
unknowns = tuple(accumulate((move.length is None for move in path), initial=0))
|
||||||
|
for i, j in combinations(range(len(path)), 2):
|
||||||
|
if j > i + 1:
|
||||||
|
separation = distances[j] - distances[i + 1]
|
||||||
|
uncertain = unknowns[j] != unknowns[i + 1]
|
||||||
|
yield i, j, clearance if uncertain or separation >= clearance else 0.0
|
||||||
|
|
||||||
|
|
||||||
|
def _colliders(
|
||||||
|
tree: STRtree, shapes: Sequence[BaseGeometry], clearance: float, cache: VerificationCache | None = None,
|
||||||
|
) -> tuple[BaseGeometry, ...]:
|
||||||
|
if not len(tree) or not shapes:
|
||||||
|
return ()
|
||||||
|
if len(shapes) == 1:
|
||||||
|
shape = shapes[0]
|
||||||
|
xmin, ymin, xmax, ymax = cache.bounds(shape) if cache is not None else shape.bounds
|
||||||
|
if isnan(xmin):
|
||||||
|
return ()
|
||||||
|
else:
|
||||||
|
extents = (cache.bounds(shape) for shape in shapes) if cache is not None else (shape.bounds for shape in shapes)
|
||||||
|
bounds = [extent for extent in extents if not isnan(extent[0])]
|
||||||
|
if not bounds:
|
||||||
|
return ()
|
||||||
|
xmin, ymin = min(b[0] for b in bounds), min(b[1] for b in bounds)
|
||||||
|
xmax, ymax = max(b[2] for b in bounds), max(b[3] for b in bounds)
|
||||||
|
area = box(xmin - clearance, ymin - clearance, xmax + clearance, ymax + clearance)
|
||||||
|
return tuple(tree.geometries[index] for index in tree.query(area))
|
||||||
|
|
||||||
|
|
||||||
|
def _move_faces_match(move: Evaluation, start_width: float, end_width: float, tolerance: float) -> bool:
|
||||||
|
shapes = move.port_shapes or move.footprints
|
||||||
|
return (
|
||||||
|
_matches_face(shapes, move.start, start_width, tolerance, arrival=False)
|
||||||
|
and _matches_face(shapes, move.end, end_width, tolerance, arrival=True)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def verify_move(
|
||||||
|
evaluator: MoveEvaluator,
|
||||||
|
move: Evaluation,
|
||||||
|
board: Polygon,
|
||||||
|
keepouts: Sequence[BaseGeometry],
|
||||||
|
occupied: Sequence[BaseGeometry],
|
||||||
|
clearance: float,
|
||||||
|
face_tolerance: float,
|
||||||
|
cache: VerificationCache | None = None,
|
||||||
|
*,
|
||||||
|
check_faces: bool = True,
|
||||||
|
) -> str | None:
|
||||||
|
if check_faces:
|
||||||
|
profiles = evaluator.catalog.profiles
|
||||||
|
matches = cache.faces if cache is not None else _move_faces_match
|
||||||
|
if not matches(move, profiles[move.start.profile].width, profiles[move.end.profile].width, face_tolerance):
|
||||||
|
return "port_face"
|
||||||
|
if any(not board.covers(shape) for shape in move.footprints):
|
||||||
|
return "board_bounds"
|
||||||
|
if any(_violates_clearance(shape, keepout, clearance) for shape in move.footprints for keepout in keepouts):
|
||||||
|
return "keepout"
|
||||||
|
if any(_violates_net_clearance(shape, other, clearance) for shape in move.footprints for other in occupied):
|
||||||
|
return "occupied"
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def verify_path(
|
||||||
|
evaluator: MoveEvaluator,
|
||||||
|
path: Sequence[Evaluation],
|
||||||
|
start: Pose,
|
||||||
|
target: Pose,
|
||||||
|
*,
|
||||||
|
board: Polygon,
|
||||||
|
keepouts: Sequence[BaseGeometry] = (),
|
||||||
|
occupied: Sequence[BaseGeometry] = (),
|
||||||
|
clearance: float = 0.0,
|
||||||
|
self_clearance: float = 0.0,
|
||||||
|
face_tolerance: float = 0.0,
|
||||||
|
source_attachment: Attachment | None = None,
|
||||||
|
destination_attachment: Attachment | None = None,
|
||||||
|
cache: VerificationCache | None = None,
|
||||||
|
defer_faces: bool = False,
|
||||||
|
) -> str | None:
|
||||||
|
"""Verify a catalog path and return the first reason it cannot be placed."""
|
||||||
|
if any(value < 0 or not isfinite(value) for value in (clearance, self_clearance, face_tolerance)):
|
||||||
|
raise ValueError("Clearance and face tolerance must be finite and nonnegative")
|
||||||
|
if not path or path[0].start != start or path[-1].end != target:
|
||||||
|
return "terminal_pose"
|
||||||
|
attachments = ((source_attachment, start, True), (destination_attachment, target, False))
|
||||||
|
attached = {id(item.obstacle): item.obstacle for item, _, _ in attachments if item is not None}
|
||||||
|
obstacles = [obstacle for obstacle in keepouts if id(obstacle) not in attached]
|
||||||
|
ordinary_keepouts = cache.tree(obstacles, installed=False) if cache is not None else STRtree(obstacles)
|
||||||
|
installed = cache.tree(occupied, installed=True) if cache is not None else STRtree(occupied)
|
||||||
|
permissions: dict[tuple[int, int], list[tuple[Attachment, BaseGeometry]]] = {}
|
||||||
|
for attachment, pose, source in attachments:
|
||||||
|
if attachment is None:
|
||||||
|
continue
|
||||||
|
validate_attachment(evaluator, attachment, pose, keepouts, face_tolerance, source=source)
|
||||||
|
seam = face_reservation(pose, evaluator.catalog.profiles[pose.profile].width, face_tolerance)
|
||||||
|
if any(_violates_net_clearance(seam, shape, clearance) for shape in _colliders(installed, (seam,), clearance, cache)):
|
||||||
|
return "occupied_seam"
|
||||||
|
ordered = range(len(path)) if source else reversed(range(len(path)))
|
||||||
|
for index in ordered:
|
||||||
|
permissions.setdefault((index, id(attachment.obstacle)), []).append((attachment, seam))
|
||||||
|
if not wholly_in_attachment(path[index], attachment):
|
||||||
|
break
|
||||||
|
for index, move in enumerate(path):
|
||||||
|
for key, obstacle in attached.items():
|
||||||
|
if not meets_attachment_clearance(move, obstacle, permissions.get((index, key), ()), clearance):
|
||||||
|
return "fixed_attachment"
|
||||||
|
profiles = evaluator.catalog.profiles
|
||||||
|
for move in path:
|
||||||
|
if error := verify_move(
|
||||||
|
evaluator, move, board,
|
||||||
|
_colliders(ordinary_keepouts, move.footprints, clearance, cache), _colliders(installed, move.footprints, clearance, cache),
|
||||||
|
clearance, face_tolerance, cache, check_faces=not defer_faces,
|
||||||
|
):
|
||||||
|
return error
|
||||||
|
if defer_faces:
|
||||||
|
# Most rejected constructive paths hit a blocker. Check the full path
|
||||||
|
# for those collisions before measuring its port faces.
|
||||||
|
matches = cache.faces if cache is not None else _move_faces_match
|
||||||
|
if any(not matches(move, profiles[move.start.profile].width, profiles[move.end.profile].width, face_tolerance) for move in path):
|
||||||
|
return "port_face"
|
||||||
|
for left, right in zip(path[:-1], path[1:], strict=True):
|
||||||
|
width = profiles[left.end.profile].width
|
||||||
|
if not compatible_join(left, right, width, face_tolerance):
|
||||||
|
return "join"
|
||||||
|
seam = face_reservation(left.end, width, face_tolerance)
|
||||||
|
if any(_violates_net_clearance(seam, other, clearance) for other in _colliders(installed, (seam,), clearance, cache)):
|
||||||
|
return "occupied_seam"
|
||||||
|
for i, j, spacing in _internal_edges(path, self_clearance):
|
||||||
|
if any(_violates_net_clearance(a, b, spacing) for a in path[i].footprints for b in path[j].footprints):
|
||||||
|
return "self_clearance"
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def replay_moves(
|
||||||
|
evaluator: MoveEvaluator,
|
||||||
|
start: Pose,
|
||||||
|
moves: Sequence[Move],
|
||||||
|
*,
|
||||||
|
placements: dict[tuple[Pose, Move], Evaluation | None] | None = None,
|
||||||
|
) -> tuple[Evaluation, ...] | None:
|
||||||
|
"""Materialize a sequence without proposing alternatives."""
|
||||||
|
current = start
|
||||||
|
path = []
|
||||||
|
for move in moves:
|
||||||
|
key = current, move
|
||||||
|
if placements is None:
|
||||||
|
evaluated = evaluator.evaluate(move, current)
|
||||||
|
else:
|
||||||
|
if key not in placements:
|
||||||
|
placements[key] = evaluator.evaluate(move, current)
|
||||||
|
evaluated = placements[key]
|
||||||
|
if evaluated is None:
|
||||||
|
return None
|
||||||
|
path.append(evaluated)
|
||||||
|
current = evaluated.end
|
||||||
|
return tuple(path)
|
||||||
|
|
@ -6,7 +6,7 @@ from collections import defaultdict
|
||||||
from dataclasses import dataclass, replace
|
from dataclasses import dataclass, replace
|
||||||
from functools import cache, lru_cache
|
from functools import cache, lru_cache
|
||||||
from heapq import heappop, heappush, merge
|
from heapq import heappop, heappush, merge
|
||||||
from itertools import combinations_with_replacement, islice, pairwise, product
|
from itertools import accumulate, combinations_with_replacement, islice, pairwise, product
|
||||||
from math import acos, ceil, comb, cos, floor, gcd, isfinite, pi, sin
|
from math import acos, ceil, comb, cos, floor, gcd, isfinite, pi, sin
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
|
@ -25,6 +25,7 @@ if TYPE_CHECKING:
|
||||||
|
|
||||||
from shapely.geometry import LineString, Polygon
|
from shapely.geometry import LineString, Polygon
|
||||||
|
|
||||||
|
from inire.geometry.components import ComponentResult
|
||||||
from inire.geometry.primitives import Port
|
from inire.geometry.primitives import Port
|
||||||
from inire.model import NetSpec, RoutingProblem, SearchOptions
|
from inire.model import NetSpec, RoutingProblem, SearchOptions
|
||||||
from inire.router._waypoints import XY
|
from inire.router._waypoints import XY
|
||||||
|
|
@ -39,6 +40,27 @@ _MAX_COLUMN_PARTITIONS = 4096
|
||||||
_MAX_COLUMN_PROFILES = 140
|
_MAX_COLUMN_PROFILES = 140
|
||||||
|
|
||||||
|
|
||||||
|
def straight_column_shortcuts(
|
||||||
|
path: tuple[ComponentResult, ...], weights: Mapping[str, float],
|
||||||
|
) -> Iterator[tuple[float, int, int]]:
|
||||||
|
"""Find contiguous S-bend windows whose endpoints can be joined by a straight."""
|
||||||
|
costs = tuple(accumulate((move.length * weights[move.move_type] for move in path), initial=0.0))
|
||||||
|
starts: dict[int, list[int]] = defaultdict(list)
|
||||||
|
for i, move in enumerate(path):
|
||||||
|
if move.move_type == "bend90":
|
||||||
|
starts.clear()
|
||||||
|
continue
|
||||||
|
if move.move_type != "sbend":
|
||||||
|
continue
|
||||||
|
# Column routing preserves the horizontal heading between bends.
|
||||||
|
for begin in starts.get(move.end_port.y, ()):
|
||||||
|
length = abs(move.end_port.x - path[begin].start_port.x)
|
||||||
|
saving = costs[i + 1] - costs[begin] - length * weights["straight"]
|
||||||
|
if length and saving > 1e-9:
|
||||||
|
yield saving, begin, i + 1
|
||||||
|
starts[move.start_port.y].append(i)
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True, slots=True)
|
@dataclass(frozen=True, slots=True)
|
||||||
class _Track:
|
class _Track:
|
||||||
net: NetSpec
|
net: NetSpec
|
||||||
|
|
@ -137,13 +159,41 @@ def column_partition_budget_exceeded(problem: RoutingProblem) -> bool:
|
||||||
return bool(tracks) and _partition_budget_exceeded(tracks, _track_columns(problem, tracks)[2])
|
return bool(tracks) and _partition_budget_exceeded(tracks, _track_columns(problem, tracks)[2])
|
||||||
|
|
||||||
|
|
||||||
def _column_layout(problem: RoutingProblem, *, min_tracks: int = 3) -> _ColumnLayout | None:
|
def _merge_close_columns(columns: tuple[_Column, ...], minimum_gap: int) -> tuple[_Column, ...]:
|
||||||
|
"""Intersect apertures across gaps shorter than a jog's forward span."""
|
||||||
|
merged: list[_Column] = []
|
||||||
|
for column in columns:
|
||||||
|
if not merged or column.span[0] - merged[-1].span[1] >= minimum_gap:
|
||||||
|
merged.append(column)
|
||||||
|
continue
|
||||||
|
previous = merged[-1]
|
||||||
|
left, right = iter(previous.openings), iter(column.openings)
|
||||||
|
a, b = next(left, None), next(right, None)
|
||||||
|
shared = []
|
||||||
|
while a is not None and b is not None:
|
||||||
|
low, high = max(a[0], b[0]), min(a[1], b[1])
|
||||||
|
if low < high:
|
||||||
|
shared.append((low, high))
|
||||||
|
if a[1] <= b[1]:
|
||||||
|
a = next(left, None)
|
||||||
|
else:
|
||||||
|
b = next(right, None)
|
||||||
|
merged[-1] = _Column((previous.span[0], column.span[1]), tuple(shared))
|
||||||
|
return tuple(merged)
|
||||||
|
|
||||||
|
|
||||||
|
def _column_layout(problem: RoutingProblem, *, min_tracks: int = 3, merge_gap: int = 0) -> _ColumnLayout | None:
|
||||||
tracks = _ordered_tracks(problem)
|
tracks = _ordered_tracks(problem)
|
||||||
if len(tracks) < min_tracks or any(not isfinite(track.net.width) or track.net.width <= 0 for track in tracks):
|
if len(tracks) < min_tracks or any(not isfinite(track.net.width) or track.net.width <= 0 for track in tracks):
|
||||||
return None
|
return None
|
||||||
start, finish, columns = _track_columns(problem, tracks)
|
start, finish, columns = _track_columns(problem, tracks)
|
||||||
if not columns or _partition_budget_exceeded(tracks, columns):
|
if not columns or _partition_budget_exceeded(tracks, columns):
|
||||||
return None
|
return None
|
||||||
|
if merge_gap:
|
||||||
|
merged = _merge_close_columns(columns, merge_gap)
|
||||||
|
if len(merged) == len(columns) or any(not column.openings for column in merged) or _partition_budget_exceeded(tracks, merged):
|
||||||
|
return None
|
||||||
|
columns = merged
|
||||||
launch = tuple(int(track.left.y) for track in tracks)
|
launch = tuple(int(track.left.y) for track in tracks)
|
||||||
arrival = tuple(int(track.right.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))
|
spans = ((start, start), *(column.span for column in columns), (finish, finish))
|
||||||
|
|
@ -416,6 +466,18 @@ def _positions(radius: int, spans: dict[int, int], sequence: _BendSequence, wind
|
||||||
return linestrings(points)
|
return linestrings(points)
|
||||||
|
|
||||||
|
|
||||||
|
def _bend_pair_distances(radius: int, spans: dict[int, int]) -> Callable[[_BendSequence, _BendSequence, int, int], float]:
|
||||||
|
@lru_cache(maxsize=8192)
|
||||||
|
def positions(sequence: _BendSequence, window: int, y: int) -> LineString:
|
||||||
|
return _positions(radius, spans, sequence, window, y)
|
||||||
|
|
||||||
|
@lru_cache(maxsize=65536)
|
||||||
|
def distance(lower: _BendSequence, upper: _BendSequence, window: int, gap: int) -> float:
|
||||||
|
return positions(lower, window, 0).distance(positions(upper, window, gap))
|
||||||
|
|
||||||
|
return distance
|
||||||
|
|
||||||
|
|
||||||
def _schedules(
|
def _schedules(
|
||||||
windows: tuple[Window, ...],
|
windows: tuple[Window, ...],
|
||||||
profiles: list[list[Profile]],
|
profiles: list[list[Profile]],
|
||||||
|
|
@ -428,6 +490,7 @@ def _schedules(
|
||||||
weighted: bool,
|
weighted: bool,
|
||||||
sbend_penalty: float,
|
sbend_penalty: float,
|
||||||
allowed_offsets: frozenset[float] | None = None,
|
allowed_offsets: frozenset[float] | None = None,
|
||||||
|
pair_distance: Callable[[_BendSequence, _BendSequence, int, int], float] | None = None,
|
||||||
) -> Iterator[tuple[tuple[Profile, ...], tuple[tuple[_BendSequence, ...], ...]]]:
|
) -> Iterator[tuple[tuple[Profile, ...], tuple[tuple[_BendSequence, ...], ...]]]:
|
||||||
max_usable = max(before - after - 4 for (_, after), (before, _) in pairwise(windows))
|
max_usable = max(before - after - 4 for (_, after), (before, _) in pairwise(windows))
|
||||||
choose = _bend_sequences(
|
choose = _bend_sequences(
|
||||||
|
|
@ -435,6 +498,8 @@ def _schedules(
|
||||||
)
|
)
|
||||||
needs = tuple((a + b) / 2 + clearance for a, b in pairwise(widths))
|
needs = tuple((a + b) / 2 + clearance for a, b in pairwise(widths))
|
||||||
straight_tracks = tuple(i for i, width in enumerate(widths) if not bend_fits_width(radius, width))
|
straight_tracks = tuple(i for i, width in enumerate(widths) if not bend_fits_width(radius, width))
|
||||||
|
minimum_span = min(spans.values(), default=max_usable + 1)
|
||||||
|
distance = _bend_pair_distances(radius, spans) if pair_distance is None else pair_distance
|
||||||
|
|
||||||
# The track order allows a local check of each neighboring pair. The
|
# The track order allows a local check of each neighboring pair. The
|
||||||
# final router still verifies the exact arcs and every pair of routes.
|
# final router still verifies the exact arcs and every pair of routes.
|
||||||
|
|
@ -447,21 +512,19 @@ def _schedules(
|
||||||
lower, upper = choose(da, window - 4), choose(db, window - 4)
|
lower, upper = choose(da, window - 4), choose(db, window - 4)
|
||||||
assert lower is not None
|
assert lower is not None
|
||||||
assert upper is not None
|
assert upper is not None
|
||||||
# Cache the shapes via the local wrapper. The span map is fixed.
|
return distance(lower, upper, window, gap) >= need + 0.025
|
||||||
return positions(lower, window, 0).distance(positions(upper, window, gap)) >= need + 0.025
|
|
||||||
|
|
||||||
@lru_cache(maxsize=8192)
|
|
||||||
def positions(sequence: _BendSequence, window: int, y: int) -> LineString:
|
|
||||||
return _positions(radius, spans, sequence, window, y)
|
|
||||||
|
|
||||||
start = profiles[0][0]
|
start = profiles[0][0]
|
||||||
approaches = {start: [(0.0, (start,))]}
|
approaches = {start: [(0.0, (start,))]}
|
||||||
for ((_, after), (before, _)), rows in zip(pairwise(windows), profiles[1:], strict=True):
|
for ((_, after), (before, _)), rows in zip(pairwise(windows), profiles[1:], strict=True):
|
||||||
window = before - after
|
window = before - after
|
||||||
|
can_shift = window - 4 >= minimum_span
|
||||||
|
eligible_rows = rows if can_shift else [row for row in rows if row in approaches]
|
||||||
next_approaches = {}
|
next_approaches = {}
|
||||||
for row in rows:
|
for row in eligible_rows:
|
||||||
scores = []
|
scores = []
|
||||||
for previous, histories in approaches.items():
|
predecessors = approaches.items() if can_shift else ((row, approaches[row]),)
|
||||||
|
for previous, histories in predecessors:
|
||||||
offsets = tuple(b - a for a, b in zip(previous, row, strict=True))
|
offsets = tuple(b - a for a, b in zip(previous, row, strict=True))
|
||||||
if straight_tracks and any(offsets[i] for i in straight_tracks):
|
if straight_tracks and any(offsets[i] for i in straight_tracks):
|
||||||
continue
|
continue
|
||||||
|
|
@ -538,8 +601,15 @@ def _column_sbend_schedules(
|
||||||
limits = (min(2 * radius - 1, ceil(radius * frac)) for frac in (0.8, 0.4, 1.44))
|
limits = (min(2 * radius - 1, ceil(radius * frac)) for frac in (0.8, 0.4, 1.44))
|
||||||
span_sets = dict.fromkeys(tuple((d, span) for d, span in spans.items() if d <= maximum) for maximum in limits)
|
span_sets = dict.fromkeys(tuple((d, span) for d, span in spans.items() if d <= maximum) for maximum in limits)
|
||||||
active_span_sets = tuple(dict(span_set) for span_set in span_sets if span_set)
|
active_span_sets = tuple(dict(span_set) for span_set in span_sets if span_set)
|
||||||
|
pair_distance = _bend_pair_distances(radius, spans)
|
||||||
|
|
||||||
|
# Repeated apertures with the same track preferences have identical profiles.
|
||||||
|
representatives: dict[tuple[tuple[Gap, ...], tuple[float, ...]], int] = {}
|
||||||
|
profile_indices = [
|
||||||
|
representatives.setdefault((column.openings, preference), i)
|
||||||
|
for i, (column, preference) in enumerate(zip(columns, preferences, strict=True))
|
||||||
|
]
|
||||||
|
|
||||||
# Keep the base and extra-spacing profiles for the current slack setting.
|
|
||||||
@lru_cache(maxsize=2 * len(columns))
|
@lru_cache(maxsize=2 * len(columns))
|
||||||
def profiles_for(column_index: int, spacing_slack: int, wall_slack: int) -> list[Profile]:
|
def profiles_for(column_index: int, spacing_slack: int, wall_slack: int) -> list[Profile]:
|
||||||
return _column_profiles(
|
return _column_profiles(
|
||||||
|
|
@ -548,7 +618,7 @@ def _column_sbend_schedules(
|
||||||
|
|
||||||
seen = set()
|
seen = set()
|
||||||
for spacing_slack, wall_slack, active_spans in product((5, 3, 2, 1, 0, 7), (1, 0), active_span_sets):
|
for spacing_slack, wall_slack, active_spans in product((5, 3, 2, 1, 0, 7), (1, 0), active_span_sets):
|
||||||
interior = [profiles_for(i, spacing_slack, wall_slack) for i in range(len(columns))]
|
interior = [profiles_for(i, spacing_slack, wall_slack) for i in profile_indices]
|
||||||
if weighted:
|
if weighted:
|
||||||
adjacent = [[launch], *interior, [arrival]]
|
adjacent = [[launch], *interior, [arrival]]
|
||||||
reachable_offsets = (0, *(
|
reachable_offsets = (0, *(
|
||||||
|
|
@ -563,12 +633,12 @@ def _column_sbend_schedules(
|
||||||
interior[i] = sorted(set(interior[i] + seeded))
|
interior[i] = sorted(set(interior[i] + seeded))
|
||||||
for i, column in enumerate(columns):
|
for i, column in enumerate(columns):
|
||||||
if column.openings[0][0] == problem.bounds[1] or column.openings[-1][1] == problem.bounds[3]:
|
if column.openings[0][0] == problem.bounds[1] or column.openings[-1][1] == problem.bounds[3]:
|
||||||
roomier = profiles_for(i, spacing_slack + 5, wall_slack)
|
roomier = profiles_for(profile_indices[i], spacing_slack + 5, wall_slack)
|
||||||
interior[i] = sorted(set(interior[i] + roomier[:45]))
|
interior[i] = sorted(set(interior[i] + roomier[:45]))
|
||||||
profiles = [[launch], *interior, [arrival]]
|
profiles = [[launch], *interior, [arrival]]
|
||||||
for rows, moves in _schedules(
|
for rows, moves in _schedules(
|
||||||
windows, profiles, widths, problem.clearance, radius, active_spans, weights,
|
windows, profiles, widths, problem.clearance, radius, active_spans, weights,
|
||||||
weighted=weighted, sbend_penalty=sbend_penalty, allowed_offsets=allowed_offsets,
|
weighted=weighted, sbend_penalty=sbend_penalty, allowed_offsets=allowed_offsets, pair_distance=pair_distance,
|
||||||
):
|
):
|
||||||
signature = rows, moves
|
signature = rows, moves
|
||||||
if signature not in seen:
|
if signature not in seen:
|
||||||
|
|
@ -735,7 +805,7 @@ def _column_jog_schedules(
|
||||||
|
|
||||||
|
|
||||||
def column_jog_candidates(
|
def column_jog_candidates(
|
||||||
problem: RoutingProblem, search: SearchOptions, *, limit_per_pass: int | None = None, recovery: bool = False,
|
problem: RoutingProblem, search: SearchOptions, *, limit_per_pass: int | None = None, recovery: bool = False, merge_close: bool = False,
|
||||||
) -> Iterator[dict[str, PathSeed]]:
|
) -> Iterator[dict[str, PathSeed]]:
|
||||||
"""Allocate tracks through ordered apertures using staggered 90-degree jogs."""
|
"""Allocate tracks through ordered apertures using staggered 90-degree jogs."""
|
||||||
if problem.initial_paths:
|
if problem.initial_paths:
|
||||||
|
|
@ -743,7 +813,7 @@ def column_jog_candidates(
|
||||||
radii = sorted({int(r) for r in search.bend_radii if isfinite(r) and r > 0 and r == int(r)})
|
radii = sorted({int(r) for r in search.bend_radii if isfinite(r) and r > 0 and r == int(r)})
|
||||||
if not radii:
|
if not radii:
|
||||||
return
|
return
|
||||||
layout = _column_layout(problem, min_tracks=1 if recovery else 3)
|
layout = _column_layout(problem, min_tracks=1 if recovery else 3, merge_gap=2 * radii[0] if merge_close else 0)
|
||||||
if layout is None:
|
if layout is None:
|
||||||
return
|
return
|
||||||
circular = bend90_uses_circular_geometry(*resolve_bend_geometry(search))
|
circular = bend90_uses_circular_geometry(*resolve_bend_geometry(search))
|
||||||
|
|
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue