Compare commits

..
Author SHA1 Message Date
84b76d0f6a Initial buildout 2026-12-02 20:35:06 -08:00
38 changed files with 143 additions and 7730 deletions

View file

@ -40,138 +40,4 @@ 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. **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. 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.
## 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.

View file

@ -1,239 +0,0 @@
# Preparation plan for typed and octagonal routing
Prepare Inire to route waveguides with different types, place fixed transitions and generated tapers, route through fixed and generated bends, and match total delay with orientation taken into account. The routing scope is two-port straights, bends, S-bends, and transitions on a single routing layer. The user pre-places crossings in Masque and supplies their ports and keepouts as part of the layout.
Start with a behavior-preserving change to the current Manhattan router. Define the Masque-side interface before building synthetic integration fixtures. Prepare the catalog and grid contracts for eight headings before finalizing public types. Use the existing benchmarks to distinguish the cost of introducing the catalog from the cost of adding new routing choices.
## Suggested release sequence
1. **Typed Manhattan.** Preserve the legacy path, including its default cost refinement. Use the same pass or a bounded catalog-aware equivalent for typed routes. Exercise directed fixed transitions, a fixed bend with unequal setbacks, an authored S-bend, and placement through Masque. Keep routing on a single layer, with exact profile identity at direct joins and crossings preplaced by the caller.
2. **Eight headings.** Start with diagonal straights and a small catalog of authored 45° and 90° bends. Keep 135° and 180° single moves in the catalog contract. Add automatic Euler-fraction selection and general generated S-bend proposals after measuring grid fit and proposal growth. Begin with declared quarter turns and reflections for supplied cells. Revisit 45° cell rotations if a device catalog needs them and its transformed ports fit the lattice. Use a caller-selected lattice first. Prototype automatic grid choice and coarse-to-fine routing against the same fixtures.
3. **Delay.** Ship orientation-aware delay reporting before tuning. When matching is enabled, meeting the requested tolerance is part of completing routing. Use one four-turn template inside caller-supplied windows, with at most one window per net. Defer automatic window discovery. Use one wavelength per match group. Give incomplete independent nets another routing attempt when a failed group releases space under the default partial-placement policy. Use benchmarks and profiling to tune the improvement and recovery passes. Defer multi-net chains across fixed devices, per-axis matching, and putting delay into the search state until measured cases justify them.
## Starting point
Inire uses one width per net and searches integer positions with four headings. Its lattice router already accepts non-circular bend and S-bend outlines and authored lengths. The move type and parameters still determine the port displacement. A 90° bend has equal setbacks, and an S-bend's span is derived from radius and offset. Search, seed replay, and refinement share these conventions. [Port model](../inire/geometry/primitives.py#L19) · [Component endpoints](../inire/geometry/components.py#L88) · [Routing architecture](architecture.md)
## Ownership and boundary
| Masque | Inire |
| --- | --- |
| Resolve technology-specific port types, allowed primitive variants, directionality, and process profiles. | Search for compatible sequences and placements, including where to change waveguide type. |
| Supply fixed cells, their polygons, ports, and delay data. Supply parameters for generated variants and translate layout units, frames, and layer rules. | Evaluate fixed and generated geometry against keepouts, reservations, and other routes. Reuse the existing layout ranking and pair repair where the move contract permits it. |
| Place the selected cell references and generated polygons directly into the supplied layout and connect their terminals. | Return the selected variants, parameters, and placements, resolved poses and types, verified geometry, and matching results. |
| Express matching groups, delay contributions outside the router, and any designated tuning regions. | Find and verify collision-free adjustments within the supplied regions and report achieved delay or skew. |
An attachment identifies the net endpoint, fixed instance and port, physical port face, and a bounded join region. At a butt join, positive clearance needs an exception that extends beyond the face. Apply it to the contiguous route prefix or suffix at that endpoint, ending when the route first leaves the join region. Splitting the approach into several collinear moves must preserve the permission. Each authorized route uses its own attachment. Check ordinary clearance against unrelated geometry, across the limits of the join region, and on later visits to the region. Reject interior overlap outside the numerical tolerance at the shared face, including overlap inside the join region. When a blocking envelope cannot describe the opening and face, supply the actual routed shapes near the port for that check. [Fixed-route IDs](../inire/model.py#L400) · [Static clearance](../inire/geometry/collision.py#L712)
At every join, require the same layout position, travel heading, and profile for the two resolved ports. Validate the finite common face separately. Allow small numerical overlap or missing material confined to the face tolerance, provided another net cannot fit through the seam. One implementation is to reserve the nominal face across the accepted seam band for foreign-net clearance. Include that reservation in admission and verification while keeping the evaluated polygons for placement. At a generated diagonal join, construct both faces from the same endpoints on the line perpendicular to travel. Check overlap elsewhere. Preserve the current use of along-path separation for self-clearance so splitting a continuous straight into short segments preserves its validity. Use conservative proxies to find candidate pairs and authoritative footprints for the final decision. Apply the join and attachment rules during terminal access, reach estimation, search, replay, and verification. Scope any cached clearance result that depends on an attachment to that permission. [Current join checks](../inire/geometry/component_overlap.py#L47) · [Same-path spacing](../inire/geometry/component_overlap.py#L104) · [Static admission cache](../inire/router/_astar_admission.py#L148)
A forward-moving S-bend following a straight is the ordinary successful join fixture. For a separate self-spacing control, use a 4 µm guide, a 3 µm-radius half turn, and parallel incoming and returning straights. Their centerlines are 6 µm apart and their edges are 2 µm apart. At 3 µm self-clearance the two long straights fail where they run alongside each other, well away from their joins. Check this using placed polygons. This case requires neither a turn beyond 180° nor a centerline supplied by the fixed-cell library.
### Draft Masque interface
The standalone Masque request describes the full routing problem. Use layout coordinates for positions and polygons at this boundary.
| Input | Contents |
| --- | --- |
| Board | Routing bounds, physical scale per layout unit, caller-selected lattice origin and pitch, routing layer, route and self-clearance, and the process orientation frame. |
| Connections | Stable net IDs and on-grid source and destination Masque ports. Resolve named ports on placed cells to layout coordinates and map them to catalog profiles. The mapping may need an explicit per-port assignment when a Masque port type names more than one compatible cross-section or mode. Use preplaced access pieces where a device port needs adaptation. |
| Obstacles and fixed geometry | Caller-designated blocking geometry on the routing layer, resolved to layout coordinates by the adapter. An attachment identifies the net endpoint, fixed piece and port, and geometry of the permitted join. |
| Catalog | Revision, stable variant IDs, legal traversal directions and transforms, and the data needed to evaluate and place fixed cells and supported generated geometry. Each traversal has an explicit input and output profile. |
| Timing | Optional delay reporting at a specified wavelength and optional matching. Each active match group has one operating wavelength, caller-specified units, offsets, and tolerance, plus any fixed delay contributions. A net is eligible for a tuning detour only inside its caller-supplied window. Members without windows still participate in the delay comparison. |
| Placement policy | Masque adapter option. By default, place the completed routes. Optionally require the entire request to complete before placing anything. |
Convert Masque's inward-facing source terminal to its outward travel heading and use the destination terminal's inward heading for arrival. Within a primitive the travel direction points into the input port and out of the output port. Resolve directions and validate port positions in the submitted frame before converting them to lattice coordinates. Masque rounds port coordinates to its layout resolution before submission and supplies port positions, origin, and pitch in a common integer layout unit. Inire requires both coordinate differences from the origin to be exactly divisible by the pitch. Returned placements must resolve to the submitted terminal poses. Apply quarter turns and reflections by coordinate swaps and sign changes. Keep polygon coordinates at full precision.
Resolve terminal and component ports to canonical routing profile IDs. A profile includes its waveguide type and distinguishes incompatible cross-sections or guided modes. Treat the wavelength used for a delay measurement as a timing input. It does not change profile identity. Require matching poses and equal profile IDs at every direct join, including fixed attachments and destination terminals. A declared transition traversal is how a route changes profiles.
For each supplied cell, identify the Masque cell and its two port names. Use only declared quarter-turn rotations (0°, 90°, 180°, and 270°) and reflections. Follow Masque's placement convention. Apply any reflection across the cell's local x-axis, then rotate counterclockwise about the cell origin, then translate. A cell can have native diagonal ports, such as a 45° bend with cardinal entry and diagonal exit. Derive legal entry and exit headings from the authored ports, selected input port, and allowed cell transform. Use the same contract for type transitions, including bidirectional variants and laterally displaced ports.
Evaluate candidate variants before selection. A fixed-cell entry supplies named ports and polygons. Derive the physical face from routed material at the port or reject an ambiguous face with a diagnostic. A fixed cell can supply characterized delay directly. Physical centerline length is optional for fixed cells. Mark total route length unavailable when a constituent length is unknown. Use a catalog placement charge for such a cell. A generated entry uses a supported primitive and a declared parameter domain. Both evaluations return resolved port poses, authoritative footprint polygons in the same frame as the port transform, physical length when known, cost, and optional delay. A supplied footprint may represent the exact routed shapes or a declared blocking envelope on the routing layer. Use the same generated geometry for evaluation and placement. Cache local geometry by catalog revision, variant, traversal direction, parameters, orientation, reflection, and any grid or sampling settings that affect it.
Route and place in one Masque adapter call. Before defining the public interface, choose which package owns the adapter, pin the supported Masque API in the integration fixtures, and document the caller's layout and port inputs. Resolve cells, ports, terminal assignments, and output names before writing geometry. Inire performs route and clearance verification and identifies completed routes. Masque trusts the verified placements of those routes. It writes the generated polygons and fixed-cell references at the supplied transforms and connects the assigned terminals using those placements. Specify the consumed terminal names and any exposed output names in the request or adapter contract, then check the resulting port list in integration tests.
Track geometric verification and completion separately. A net outside an active match group completes when its route verifies. A group completes when every member has a verified route and the group meets its tolerance. By default, place completed routes, including all members of each completed group. Keep geometrically verified candidates in incomplete groups available for inspection. With the complete-placement option enabled, require completion of the whole request before making any layout edits. If the request is incomplete, skip placement and return the routing and matching results with that placement outcome.
Rank verified layout alternatives first by completed net count (each member of a completed group counts once), then by completed group count. Break remaining layout ties by lowest catalog cost, with stable order for ties. Test four independent completions against one completed three-net group. The four independent nets win even when their cost is higher. Callers seeking priority can submit a smaller request.
Before finalizing default partial placement, release the provisional paths and tuning reservations of any group that will be left unplaced. Give independent nets that remain incomplete a bounded retry against the resulting layout. Hold completed routes fixed during this retry and verify the final placement set. Report any retained failed-group candidates as diagnostic geometry from the earlier attempt. The complete-placement option uses the ordinary routing and matching attempts to seek a fully complete layout.
Invalid catalog entries and invalid placement inputs are fatal to the call. If a Masque placement or connection operation raises, propagate that exception as a fatal execution error and stop executing placements. Earlier writes may remain. The complete-placement option is a check of routing and matching results before the first write. Ordinary unrouted and unmatched nets are reported through Inire's routing and matching results. Return ordered per-net placement records with the catalog revision, variant IDs, traversal directions, parameters, layout transforms, and resolved port poses and profiles for execution and inspection.
In this plan, **seed replay** is an Inire operation. Given an ordered move sequence and its start pose, Inire evaluates those moves under the supplied problem and checks the resulting geometry without searching for alternatives. Use it for legacy parity and typed move verification tests. Masque placement executes Inire's verified output for the current request. A saved-placement import API is outside the first release. To route a changed layout, submit a new problem to Inire.
### Bends, S-bends, and transitions
- Bends and S-bends preserve the routing profile and its waveguide type. A fixed bend or S-bend has authored port poses, optional physical length, and a caller-provided collision footprint. It follows the fixed-cell transform rules.
- A generated bend supports 45°, 90°, 135°, and 180° turns in either direction as single moves. The circular-equivalent radius `R` sets the bare port locations at each angle, including `(R, R)` for a left 90° turn. Keep the footprint and centerline length of the selected curve. Add short tangent leads where they make the ports grid-compatible, and include them in the evaluated footprint, port poses, length, and delay.
- Use `R` and the allowable minimum curvature radius `Rmin` to generate a partial Euler bend. Choose the largest Euler fraction that satisfies `Rmin` at the requested angle while retaining the circular-equivalent port locations. Use a fully Euler profile when it satisfies the floor. A catalog can supply an explicit `euler_frac` for a characterized shape, including `0` for circular geometry. Define the fraction as the share of the heading change in the two linear-curvature ramps. Report the actual minimum radius and enforce any declared floor.
- Generate S-bends from two opposed turns, using shallower turns for small offsets and a straight between them when needed. Apply the radius floor at each lobe's actual angle. Let search consider a bounded set of grid-compatible spans and offsets.
- A transition is a fixed cell or an explicitly declared linear taper between routing profiles. Generate the taper as a centered trapezoid whose end widths come from the two profiles. Round the specified minimum length up to a legal straight step for the heading. Admit the variant at that heading if the stretch is at most 5% by default. A characterized variant can declare a different limit with timing data valid at the admitted lengths. Charge the fixture's caller-supplied taper delay once per placement, independent of the stretch.
## First device set
Use three waveguide types on the same routing layer. Width identifies the type in this fixture. Keep type as a separate catalog field so the general contract can distinguish types of equal width.
| Type | Width | Straight cost per cm | Circular-equivalent bend radius | Cost per 90° bend | S-bend cost | Initial group index |
| --- | ---: | ---: | ---: | ---: | ---: | ---: |
| 4 µm guide | 4 µm | 1 | 10 µm | 0.01 | 0.02 | 4 |
| 5 µm guide | 5 µm | 0.5 | — | — | — | 4 |
| 8 µm guide | 8 µm | 0.2 | 100 µm | 0.1 | 0.2 | 2 |
The 5 µm guide uses straights and transitions in this fixture. Use the same circular-equivalent radius across bend angles. A 45° bend has the same cost as a 90° bend. Use twice the 90° cost for a 135° bend, a 180° bend, or an S-bend in the fixture. Allow catalog variants to supply their own charges.
| Fixed transition | Forward port displacement from the 4 µm end | Lateral displacement | Footprint | Cost | Group index for synthetic delay |
| --- | ---: | --- | --- | ---: | ---: |
| 4 µm ↔ 5 µm | 10 µm | Centered ports | Caller-supplied polygon | 0.01 | 4 |
| 4 µm ↔ 8 µm | 100 µm | 200 nm to the left when traveling from the 4 µm end | Caller-supplied polygon, 10 µm wide and centered on the 4 µm end | 0.2 | 3 |
Both transitions are bidirectional. The router may switch to another type and return to the starting type within the same net. The lateral offset of the 4-to-8 µm transition is −200 nm in the device description. Inire's travel-local lateral coordinate is positive to the left, so the reference displacement for the east-facing 4 µm input is `(100, +0.2)` µm in Inire coordinates. Evaluate each direction from its actual input port and verify the output pose and footprint together. Assign the synthetic cells authored lengths of 10 µm and 100.01 µm respectively. Supply group optical lengths of 40 µm and 300.03 µm in either direction. Test the latter as a direct characterized delay as well, with the length field absent.
Use a 100 nm grid for the fixture as a starting point. It represents the 200 nm offset in two grid units for the reference transition with cardinal ports. A supplied transition variant for diagonal travel needs authored diagonal ports and grid-compatible poses. Exercise generated tapers in a separate fixture so fixed-transition cost checks use the two fixed cells in the table. A 10 µm taper rounds to about 10.041 µm on a diagonal and is available. A 2 µm taper rounds to about 2.121 µm and exceeds the stretch limit. Require on-grid port positions and compute straight cost from physical length in centimeters, including on diagonal headings. Evaluate delay separately from routing cost.
## Preparation sequence
### 1. Prepare the technology fixture and freeze the legacy reference behavior
- Settle the Masque request, evaluation, and placement contracts before building the synthetic device set. Capture its footprints, authored port poses, and allowed cell transforms. Include an asymmetric quarter turn and an S-bend with a declared span. Evaluate the cardinal and grid-compatible diagonal variants before settling public types.
- Record the baseline revision, options, and dependency versions for the current corpus and holdouts. Capture verified net IDs, effective port poses, ordered moves, per-net physical lengths where known, and placed polygons for representative cases. Record search expansions and geometry-cache work alongside repeated wall times.
- Include standard straight, bend, and S-bend cases, custom-outline replay, exact-clearance contacts, mixed widths, pair repair, and a large board. Keep disabled search and seed replay in the comparison.
- Inventory the assumptions that depend on cardinal headings, constant width, or built-in setback formulas. Start with move proposal and admission, path cache keys, terminal access, guide generation, capacity bounds, refinement, and seed replay. [Benchmarks](benchmarks.md) · [Diagnostics](routing-diagnostics.md#reproduce-and-compare)
### 2. Put the current primitives behind one evaluation boundary
- Define the minimum evaluation contract around input and output profiles, legal entry headings, the local port transform, parameters, authoritative footprints, an optional conservative proxy, physical length when known, cost, and optional delay. A stable variant key and selected parameters must identify the replayed move against the same catalog revision. Keep layout rendering data in the adapter.
- Separate evaluating known parameters from proposing them during search. Prepare a deterministic, bounded set of candidates using rays, guides, the target pose, and the actual displacement of each compatible variant. Include a fixture where an asymmetric bend changes the straight length needed to hit the target. Keep geometry caching independent of process-dependent delay evaluation so the same footprint can be reused when comparing timing conditions.
- Make search and seed replay consume the same evaluated move. Wrap the existing straight, 90° bend, and S-bend constructors first. Preserve existing public inputs and seed recipes during this refactor.
- Include the routing profile in state and apply the direct-join predicate to target matching. Include the evaluated variant and orientation in geometry cache identity. Directed transitions define the profile changes the search can use.
- Retain the specialized bundle, column, and compact paths for their current component assumptions. Start general catalog routes in detailed search. Treat a corridor as guidance until the physical moves verify, and use a capacity bound only where its assumptions still hold for all permitted types and transitions.
- Require parity on the legacy path before changing candidate generation. Compare routes, coverage, and work separately. Review any change to a verified ID, geometry, or expansion count at the fixture level.
#### Search and cost checks
- Treat detailed search as best effort. Report a known budget exit separately from a run that finished without a verified path. A finished bounded run can still miss a legal path. On a tiny board, build a reference enumerator with a short finite move set, zero heuristic, and complete path histories. Enumerate every legal placement of those moves up to a fixture depth that includes the known solution. Compare against production proposals with relaxed history pruning to find moves that never reached admission. Then run production pruning on the reference candidate set to isolate losses from dominance. Use the same collision verifier and catalog cost in all three runs.
- Require an unseeded search to find a displaced transition whose footprint clears a constrained passage only at an interior launch point. Compare its proposed launch points and expansions with the tiny exhaustive reference before setting a production budget.
- Exercise arrival history with a scripted move graph. Let `S = (0, 5)` and `P = (5, 5)` both face east, and allow only the east straight from `P` to the goal `G = (9, 5)`. Build one direct approach to `P` and one via `(2, 5)`, `(2, 9)`, `(7, 9)`, `(7, 2)`, `(3, 2)`, and `(3, 5)`. Use small turns and a guide narrow enough for each approach to be independently valid. Give the long scripted approach lower accumulated fixture cost. Assert equal pose and profile at `P`, then assert that only the direct approach can continue because the other crosses the continuation at `(7, 5)`. The reference must find the direct route. Use this case to verify any alternate-arrival retention or weaker-pruning retry selected for production.
- Let the caller's costs and available components steer trade-offs between straight length, transitions, and bends. Among complete solutions found by search, rank by caller-supplied catalog cost. Keep congestion, guide bonuses, and proximity terms available for search ordering. Use finite nonnegative catalog costs and a cost tolerance independent of the geometric tolerances. Use catalog-only scoring with stable tie ordering in the cost fixtures. A bend's quoted cost covers its nominal footprint. Charge optional tangent leads at the profile's straight rate unless the variant declares an inclusive charge. Record which convention each fixture uses.
- Keep the current cost refinement pass or a catalog-aware equivalent enabled by default. Preserve the first verified layout that meets the coverage target as an incumbent. Give refinement a bounded opportunity to lower its catalog cost, including on a fully routed board. Within a fixed completion set, accept a cheaper verified layout even if skew increases while staying within tolerance. Try targeted local changes before considering another broad search. Accept an improvement only after verifying the replacement layout, preserving the incumbent's completed net IDs and active match tolerances. Tune the pass's scope and budget using the benchmark comparisons. [Current automatic refinement](../inire/router/_automatic.py#L710)
- Evaluate the 4, 5, and 8 µm straight rates at the same physical length, with expected charges `0.1`, `0.05`, and `0.02` at 1000 µm. Check diagonal straights against the physical length of their integer displacement. Verify each fixed transition charge in both directions. Compare one 90° bend with two 45° bends using the same profile, accounting separately for any required straight leads. For later single-move 135° and 180° fixtures, place a keepout that excludes the smaller-turn sequence while clearing the single move. Check that the move is both proposed and selected.
- For the straight trade-off, restrict the catalog to the 4 and 5 µm straights and the two traversals of the centered 10 µm transition. Route between aligned 4 µm ports at distances of 370, 380, and 390 µm on an open board. The direct route costs `L / 10000`. The switched route costs `0.02 + 0.5 × (L − 20) / 10000`. Verify direct is cheaper at 370, both cost `0.038` at 380, and switched is cheaper at 390. At the tie, use stable ordering. Repeat at 390 with each transition priced at `0.012` and expect the direct route to win. Repeat with the original prices and the return traversal absent and expect only the direct route to be feasible. Test a two-net case separately, with equal verified coverage in both alternatives and a cheaper detour on just one net, to check the layout ranking as well as the per-net objective.
- Test refinement with a search fixture that reaches full coverage on an expensive verified layout, then offers a cheaper typed or diagonal replacement. Expect the default run to take the verified improvement. Disable refinement and expect the original layout. Repeat with the replacement colliding or causing a completed group to miss its delay tolerance, and with the budget ending before the alternative can be verified. In each case expect the incumbent and its completed net IDs to be retained.
### 3. Specify the Masque integration checks
Drive these checks through the Masque adapter with real test cells and a layout. Derive expected ports and transforms from the authored cell data. Compare placed polygons by geometric equality within the polygon tolerance. For a blocking envelope, check containment of the actual routed shapes on the routing layer and check the physical join independently. Submit a second request on a fresh copy of the layout with a keepout intersecting the expected path. Inire should find a different verified path or return the net unrouted, according to whether the fixture allows a detour.
| Case | Fixture and assertions |
| --- | --- |
| Unequal setbacks and a required type change | Route 5 µm ports from `(20, 30)` east to `(70, 75)` north. Supply the centered 10 µm transition in both directions and only the 4 µm left bend for the east-to-north corner. Give the bend a 4 µm entrance straight followed by an 8 µm circular quarter turn, with local displacement `(12, 8)` and physical length `4 + 4π` µm. The minimum-cost route has 5→4 before the bend and 4→5 after it. The bend starts at `(58, 30)`, and the straight lengths total 28 µm before the bend and 27 µm after it, excluding the two transitions. A 1 µm-clearance keepout `[57, 59] × [37, 39]` intersects the bend's bounding box and clears the routed shape. Check that the valid bend is both proposed and admitted. Disable the 5→4 traversal and expect the net to remain unrouted. |
| Authored S-bend span | Supply a fixed 4 µm S-bend with input at `(0, 0)`, output at `(26, 6)`, and eastbound travel at both ports. For example, build its footprint and physical length from a centerline `(26t, 6(3t² − 2t³))` for `0 ≤ t ≤ 1`. In Inire, evaluate it at `(20, 20)` and verify a 24 µm following straight reaches the eastbound target `(70, 26)`. Check the authored span, shape, and length in the result and seed verification. |
| Displaced transition in both directions | Use authored ports `A = (0, 0)` and `B = (100, 0.2)` with inward headings east and west. Native `A→B` travels east with displacement `(100, 0.2)` µm. Native `B→A` travels west with displacement `(-100, -0.2)` µm. In a single eastbound route, go from `(10, 20)` through `A→B` to `(110, 20.2)`, along a 20 µm straight to `(130, 20.2)`, then through `B→A` with local x-axis reflection followed by 180° rotation, arriving at `(230, 20)`. Assert the composed footprints, traversal order, intermediate profiles, and two transition charges. For the composition test, force this sequence with a move seed or fixture constraints so a direct 4 µm route cannot satisfy the test by itself. |
| Off-origin reflected cell | Author a second copy of the asymmetric bend with input `(2, 3)` and output `(14, 11)` in its cell frame. Reflect across local x, rotate counterclockwise 90°, and translate by `(40, 50)`. Expect input `(43, 52)` heading north and output `(51, 64)` heading east. Check the cell reference and transformed footprint in Masque as well as the evaluated ports. |
| Profile compatibility | Test equal widths with different type IDs, then the same nominal type and width with different mode or cross-section profiles. Exercise an intermediate join and destination acceptance at otherwise identical poses. Both reject mismatched profiles. Add a directed transition and verify the same route succeeds in its allowed direction. Check the reverse request separately with the reverse traversal absent. |
| Invalid inputs | Reject an undeclared 45° rotation of a supplied cell, a missing footprint, and a duplicate terminal assignment before any writes. Snapshot geometry, references, and ports. A test of the rotation restriction should use a catalog entry with native diagonal ports in a separate successful control, so cell transform and port heading are tested independently. |
| Placement policies | Use separate layouts with an unrouted net, an unmatched group, and complete routing and matching. Include an independent completed net in the unmatched case. Under default placement, execute the independent net and leave the unmatched group's terminals and geometry untouched while returning its verified candidate routes. With complete placement enabled, the first two requests return their results with no layout edits. The third places every route. Check the returned placement outcome and Masque port changes in each case. |
| Retry after an unmatched group | Give a third, independent net just one legal passage. In one case a provisional route from an unmatched group crosses that passage. In another case only the group's tuning reservation obstructs it. With the group still unmatched after its normal attempts, release its provisional geometry and reservations and expect the independent net to complete on the retry. Include a completed group elsewhere on the board and check that its placements and delay match are preserved. Under default placement write the completed routes and keep the unmatched group's earlier geometry in diagnostics. With complete placement expect no writes. |
| Fatal execution failure | Inject a placement or connection exception after one successful write, with at least one more placement pending. Assert that the exception reaches the caller, later placements are skipped, and the call returns no ordinary routing outcome for the error. Exercise the same case with complete placement enabled and a fully successful Inire result. Use an executor spy to check that Masque receives the verified transforms and polygon payloads from Inire. |
#### Attachment and join regressions
- For an isolated butt join in µm, use the fixed rectangle `[-10, 0] × [-2, 2]`, a source at `(0, 0)` departing east, the 4 µm-wide straight to `(10, 0)`, clearance `1`, and join region `[-2, 2] × [-3, 3]`. Accept the authorized straight and the same straight split at `x = 0.5` and `x = 3`. Reject it with no attachment. Shrink the region to end at `x = 0.5` and reject the part that still needs clearance beyond that limit. Add a shelf `[0.3, 0.7] × [1.5, 2]` to the fixed footprint and reject interior overlap even with the original join region. Check search admission and Inire verification against the same cases.
- For a later visit to the same region, test a piece near `x = 0.25` to `0.5`, `y = 2.25` to `2.75`, using the same attachment. It is inside the join region and less than 1 µm from the fixed footprint. Mark it as part of the route after the initial approach has exited the region. Expect an ordinary clearance failure. Exercise the same rule from the destination by reversing the approach.
- On a preplaced crossing, use two authorized ports with distinct approach geometries. Both must succeed. At the clearance or admission layer, query identical approach geometry with and without its attachment, warming the cache in each order. The unrelated query must fail in both orders. Repeat for terminal reach estimates if they use a separate cache.
- With positive self-clearance, verify a straight and the same straight split into three short collinear moves. For a diagonal seam, test a shared finite face, a numerical sliver within the face tolerance, and an equally thin overlap displaced past the end of the face. Accept the first two and reject the third. Keep fixtures for numerical face tolerance, route clearance, and the wider attachment join region independent.
- Keep two resolved ports exactly coincident at `(0, 0)` traveling east, with nominal faces at `x = 0` spanning `y = −1` to `1`. In µm, use polygons `[-2, -0.001] × [-1, 1]` and `[0.001, 2] × [-1, 1]`, with a face tolerance of `0.002` on either side. Use zero clearance and a foreign strip `[-0.00025, 0.00025] × [-2, 2]`. The strip clears the raw polygons. Check that the join verifies on its own and that its reservation blocks the foreign move both during admission against the installed join and during layout verification. Run this between consecutive moves and at a fixed attachment. With both nets proposed in either order, the final verified set may contain at most one. Move the gap edges to `x = ±0.004` and reject the join itself. Separately offset one nominal port while leaving the polygons unchanged and reject the join on pose equality.
### 4. Specify an eight-heading grid contract
- Use eight headings on a square position grid. Define cardinal and diagonal displacements in integer grid steps and use their physical lengths for cost and delay. A step of one unit on each axis has length √2 grid units. For a northeast move with lattice displacement `(dx, dy)`, the forward and lateral projections in units of `pitch/√2` are `dx + dy` and `dy − dx`. The two projection counts must have the same parity.
- Require grid-compatible evaluated poses for each legal entry heading. Use native diagonal ports on supplied cells and generate variable geometry such as straights for the requested heading. Include any modeled lead extensions in the evaluated footprint, port poses, and length. Validate the transformed port coordinates before converting them to the lattice and keep full polygon precision.
- Prepare fixtures for a 45° turn in each direction using a cell with a native diagonal port, an asymmetric bend used after a diagonal, a diagonal port launch near a keepout, and a mixed cardinal and diagonal path. Verify and replay those cases. Check off-grid variants explicitly. For a diagonal U-turn or a displaced diagonal transition with parallel port axes, the transverse offset must be an integer multiple of `pitch/√2`. Tangent leads preserve that offset.
- Extend heading-dependent rays, straight proposals, terminal access, and search priorities after legacy parity is established. Validate diagonal routes through exact-clearance openings before extending constructive fast paths.
Use exact lattice membership for positions. Keep the heading residual and physical face tolerance separate. Construct generated moves from their selected integer output displacement, and check that their evaluated geometry meets the physical face there. Keep the authored fixed-cell geometry at its executed transform and verify its physical join under the face tolerance. Reject off-grid terminals in caller-selected lattice mode. Treat a well-formed variant with an incompatible pose for a particular heading and grid as unavailable for that evaluation, with a diagnostic reason. For tangent leads, declare a maximum per lead and require both to be nonnegative. Keep geometrically distinct footprints that share a displacement. Use stable ordering by lead lengths and lattice displacement, and record both lead lengths with the evaluated parameters.
Prototype Inire choosing the grid after the explicit-grid path works. Compare a grid selected to fit the submitted terminals and useful catalog variants with coarse route guidance at 1–10 µm pitch followed by local placement refinement at the Masque coordinate precision, for example 1 nm. Keep authored terminals and fixed-cell geometry at their exact layout poses. A coarse corridor can propose a route even when its terminal or a fixed transition does not fit the coarse lattice. Verify every realized route at full layout precision against the original problem. On a refinement failure, try a different corridor, use the explicit-grid search, or return an ordinary incomplete outcome according to the remaining search budget. Avoid an exhaustive full-board search at the finest pitch when evaluating this approach.
| Grid case | Assertions |
| --- | --- |
| Origin and tolerances | On pitch `0.1` µm and origin `(0.03, -0.02)` µm, check that `(0.33, 0.18)` maps to `(3, 2)` and the returned layout pose equals the original. Have Masque round a float-valued x coordinate of `0.33000000000000004` µm to 330 nm. Verify that Inire accepts the submitted position. Repeat with a submitted x coordinate of 331 nm and reject the 1 nm position error independently of heading and face checks. Exercise a reflected and rotated off-origin cell chain through the Masque adapter. Check the lattice decision and final join separately. Verify that polygons and fixed reference transforms retain their original precision. |
| Circular 45° bend with leads | A 10 µm left turn from east to northeast has bare displacement `(10/√2, 10 − 10/√2)`. To reach `(7.2, 3.0)` µm on the 100 nm grid, solve for an entrance lead of about `0.057864` µm and an exit lead of about `0.100505` µm. Admit that evaluated displacement with a per-lead cap of `0.11` µm and exclude it with a cap of `0.10` µm. Verify the port poses, cap handling, the bend length `2.5π` plus both leads, and the actual lead polygons. |
| Diagonal parallel ports | For northeast travel, offer projection counts `(forward, lateral) = (5, 1)` and `(5, 2)`. The first gives displacement `(2, 3)` in grid units. The second violates parity. A 10 µm-radius diagonal U-turn requires 20 µm of lateral offset, about `282.843` steps of `pitch/√2`, and is unavailable at that heading. The same radius fits the cardinal grid. Exercise both zero and nonzero tangent-lead bounds. |
| Different footprints at the same pose | Use a 10 µm-radius cardinal U-turn from `(0, 0)` east to `(0, 20)` west with two sets of tangent leads, `(0, 0)` and `(2, 2)` µm. Use a 0.4 µm guide, 0.25 µm clearance, and keepout `[9.9, 10.1] × [9.9, 10.1]`. Both moves have the same resolved ports. The no-lead move intersects the keepout and the extended curve clears it. Check that both geometries reach admission and that the extended move can be selected in either proposal order. |
| Taper rounding | On the 100 nm grid, both 10 µm and 2 µm are legal cardinal lengths. For northeast, check `71√2 × 0.1 ≈ 10.041` µm is admitted and `15√2 × 0.1 ≈ 2.121` µm exceeds 5%. If exercising a characterized 7% limit, check that it admits the shorter taper and charges its specified delay once. Inspect both finite end faces and the assigned profiles. |
| Flat-ended diagonal access | Bound a northeast approach by parallel keepouts at exactly half the guide width plus clearance on each side, using clearance and width in layout units. Put the port on the lattice. The necessary straight must appear in the proposals and pass exact verification. Move one wall inward by more than the clearance tolerance and reject the straight. Check both source launch and destination arrival. |
| Coarse-to-fine prototype | Use an eastbound 4 µm source at `(20.001, 30.001)` and 8 µm destination at `(170.001, 30.201)` on a 1 nm layout grid. Use the 100 µm transition with a lateral offset of `0.2` µm. Generate guidance at 1 µm pitch and realize the route on the fine grid. Assert exact endpoints and verify the transformed transition and final clearance. Add a keepout that blocks the first proposed realization and check that the result comes from a verified retry or is incomplete. On an explicit 1 µm grid, these authored terminal positions do not share a lattice origin. |
When adding automatic Euler-fraction selection, use a 90° turn with `R = 10` µm and minimum curvature radius floors of 5, 8, 10, and 11 µm. Expect full Euler, partial Euler, circular, and no admissible shape, respectively. All admissible bare outputs must be at `(10, 10)` µm with northward travel. Check the actual minimum radius from the centerline curvature independently of polygon sampling. For the 8 µm case, check that increasing the selected fraction beyond its numerical tolerance fails the floor. Also check that an explicitly authored `euler_frac = 1` fails that floor and `euler_frac = 0` meets it. Extend the checks to the other bend angles and to the actual lobe angles selected for generated S-bends.
### 5. Specify orientation-aware delay and tuning
- Treat reporting and matching as separate options. With no active matching, use ordinary routing, ranking, and refinement. Compute requested delay reports on the selected verified geometry. Reporting must leave placements, net order, cost, and completion unchanged. Timing data and tuning windows supplied for inactive matching have no influence on search or reservations.
- Start with **orientation-aware total-delay matching**. For generated straights, bends, and S-bends, integrate `n_g` over centerline arc length using the local travel tangent in the process frame. A bend variant can override the guide model on its curved sections. Count any straight lead extensions once using the straight-guide model. Fixed cells may supply delay by orientation and traversal. Generated tapers use their specified fixed delay. Report group optical length or divide by the speed of light to express delay in time units. Use the match group's units for offsets and tolerance.
- Evaluate each match group at one operating wavelength. Pass it to the catalog delay evaluator, along with the profile and the local travel angle measured counterclockwise from the process axis, modulo `2π`. Provide a built-in uniaxial approximation `n_g(θ) = n_g(0) cos²θ + n_g(π/2) sin²θ` from two caller-supplied principal-axis modal group indices. A single supplied `n_g` gives the constant model. Let the built-in formula supply its own half-turn symmetry. Evaluate a custom callback at the actual travel angle. Set an integration accuracy target in group optical length before choosing integration and sampling settings. [Orientation-dependent modal group index](https://www.nature.com/articles/s41377-024-01506-1)
- In the first release a match member is one routed net plus its declared fixed delay contributions at that wavelength, with each contribution counted once. This follows the Masque convention of routing one external connection per net at a crossing. For an end-to-end constraint across a preplaced crossing, first route and hold one side fixed. In the request that matches the other side, supply the fixed side’s reported delay and the characterized crossing traversal delay as additive fixed contributions at the group wavelength. Count each once. If the fixed side changes, update its contribution before matching again. Use disjoint match groups initially so tuning a net affects one group. [Existing crossing workflow](user/route-a-layout.md#connect-a-preplaced-crossing)
- A positive relative offset asks for a longer delay. Subtract each net's scalar offset from its total delay. Compare the spread across the nets with the tolerance supplied for that match group. With delay-increasing tuning, the largest current adjusted delay sets a lower bound on the reference.
- Treat caller-supplied tuning windows as location constraints for their assigned nets. Reserve them during initial routing and tuning, allow one per net, and reject intersecting supplied window interiors. Treat each as a keepout with ordinary clearance for other nets. Its boundary is a containment limit for the owner's replacement footprint. Every candidate must clear other owners’ reserved windows even where window boundaries touch.
- Without a supplied window, use the verified baseline as the sole tuning choice for that member.
- For an active window, enumerate bounded, grid-compatible four-turn replacements. Preserve both endpoint poses and profiles. Use only verified replacements with positive modeled delay increments relative to the original segment. Include the original route as a choice. A group can complete without allocating tuning space when its verified routes already meet tolerance.
- Compare attainable adjusted delays across the group, including targets above the largest baseline adjusted delay. With disjoint windows, gather the verified choices per net and look for an interval containing a choice for every member. A choice meets tolerance when its adjusted delay spread is less than or equal to the group tolerance. Among verified choices meeting tolerance, minimize total catalog cost and use stable move order for cost ties. When none meets tolerance, prefer lower skew, then lower catalog cost for the reported candidate. Verify the complete selected layout before returning it. Report final delays and residual skew, and preserve the best verified incumbent if the search budget expires. Distinguish an attempt that misses tolerance, an unrouted member, missing delay data, and budget exhaustion. For misses, record whether any legal tuning space was found. A verified incumbent that meets tolerance completes its group even if the budget expires while looking for a better match.
- With matching enabled, reaching full geometric coverage does not end the attempt if a group remains unmatched. Try tuning in supplied windows first. Use remaining routing budget to try verified baseline alternatives for the affected nets, such as a route that reaches a supplied window, frees a usable straight span, or uses a different catalog sequence. Re-evaluate eligible spans inside the supplied windows, then tune and verify the new layout. Keep delay out of the first detailed-search pruning refactor. If bounded routing retries miss too many known-feasible matches, measure a search that retains several delay labels for the same pose and profile.
- Defer **same-orientation matching** until the process model defines how to assign delay from curved and fixed components to axes. The draft rule classifies straight headings modulo 180° in the process frame. For each net and axis, subtract an offset that defaults to zero and compare the spread with the group's tolerance for that axis. The sum of a component's per-axis contributions must agree with its total contribution.
### Synthetic delay fixtures
Use the 4 µm guide with group index 4, a 100 nm grid, 1 µm clearance, and a board from `(0, 0)` to `(400, 300)` µm. Port coordinates below are in layout µm and list the source before the destination. Use a caller-supplied tolerance of 0.05 µm of group optical length for these fixtures. Use the straight primitive in all cases and enable 10 µm circular quarter turns for tuning. The per-axis expectations apply to the follow-up matching mode.
| Case | Fixture | Expected result |
| --- | --- | --- |
| Cardinal axes | East `(20, 40)` to `(120, 40)`, west `(120, 70)` to `(20, 70)`, and north `(160, 20)` to `(160, 120)`. Each route contributes 400. | All three match in any-orientation mode. East and west match on the 0° axis. Adding north to that group yields a spread of 400 on both the 0° and 90° axes. |
| Diagonal axes | Northeast `(20, 160)` to `(50, 190)`, southwest `(90, 190)` to `(60, 160)`, and southeast `(130, 190)` to `(160, 160)`. Each route contributes `120√2`. | All three match in any-orientation mode. Northeast and southwest match on the 45° axis. Adding southeast yields a spread of `120√2` on both the 45° and 135° axes. |
| Per-axis offset | Reuse east and west from the cardinal case and move the east destination to `(140, 40)`. Ask for a positive offset of 80 on the east net's 0° axis. | The 0° contributions are 480 and 400. Both adjusted contributions are 400 and the same-orientation group matches. |
| Offset with fixed access | Two eastbound straights from `x = 20` to `x = 140` at `y = 40` and `y = 120`. The second net includes an attached access straight from `(15, 120)` to `(20, 120)` contributing 20. Use any-orientation matching with a positive offset of `80π − 60` for the second net. Its tuning window is `[40, 100] × [115, 155]`. | The baseline delays are 480 and 500. A four-bend detour adds `80π − 80` to the second net, giving adjusted delays of 480 for both nets. Verify that the fixed access contributes exactly once and that all tuned geometry fits the window. |
| Insufficient room | Reuse the offset case with a caller-supplied tuning window of `[40, 100] × [117, 123]` and constrain both nets to their baseline straights outside the window. | The window fits the straight and cannot fit a 10 µm quarter turn. Keep the supplied location constraint even if space is available elsewhere. Return both verified candidates with residual skew `80π − 80` and an incomplete group. |
For the detour oracle, replace the 50 µm portion from `(45, 120)` to `(95, 120)` with four quarter turns of radius 10 µm and three 10 µm straights. The detour reaches `y = 150`. Its centerline length is `20π + 30` µm. Separately exercise an unknown fixed access delay and a tuning budget that expires before evaluating a candidate. Expect a distinct status for each and preserve the last verified geometry.
For a delay-model fixture, rotate the process axis to +45° and use principal modal group indices of 4 and 2. A 10 µm circular quarter turn from east to north contributes `15π + 10` µm of group optical length. Its reflected turn from east to south contributes `15π − 10` µm. Check the evaluated and replayed delays for both turns.
For a tuning fixture where added length reduces delay, reuse the four-turn detour with straight `ng = 4` and a bend override of `ng = 1`. The 50 µm original segment contributes 200 µm of group optical length and the detour contributes `120 + 20π` µm. Verify that the delay-increasing tuner skips this candidate. Exercise validation of a net listed in two match groups and a second net attempting to use a reserved tuning window.
| Additional case | Fixture and assertions |
| --- | --- |
| Fixed side of a crossing | At one wavelength, give the previously routed side a group optical length of 100 µm and the crossing traversal 5 µm. For the other side offer verified choices of 140 and 145 µm, with 140 cheaper. Against a reference of 250 µm at tolerance 0.05 µm, select 145 µm and report 250 µm total. Keep the first side fixed. |
| Reporting only | Run a baseline fixture twice with matching disabled, first without timing data and then with delay data, reporting enabled, and an inactive tuning window that overlaps another net's route. Expect identical placements, completed IDs, catalog cost, and routing work. The latter run reports delay. Repeat with missing fixed delay data and expect an unavailable delay for that net with the same placement and completion. |
| Wavelength held constant across the group | Use a synthetic delay evaluator with two wavelength entries and make each return a different index for one profile. Verify that all members, including fixed contributions, use the requested group wavelength. Compare two separate requests with different wavelengths and confirm that timing changes while physical profile IDs and the evaluated footprints stay the same. |
| Travel direction and units | Use a synthetic callback `ng = 3 + 0.5 cos(θ)` with the process axis pointing east. A 20 µm east straight contributes 70 µm group optical length and the reverse traversal contributes 50 µm. Verify both with the same geometry cache. Repeat with a match group expressed in time units. Convert its delays, offsets, and tolerance and expect the same matching decision. |
| Matching affects completion and route choice | Supply two verified baseline candidates for one group member. The cheaper candidate misses tolerance and has no legal tuning move. The second costs more and gives a delay inside tolerance, with the other member unchanged. With matching disabled, select the cheaper route. With matching enabled, try the second baseline and complete the group. Remove the second candidate and assert that geometric coverage stays full, group completion fails, and the verified candidate and skew are still reported. |
| No window supplied | Repeat the fixed-access offset case with the baselines fixed and no supplied windows. Expect unchanged geometry and an incomplete group despite open space. An already-matched control completes with no windows. |
| Adjacent supplied windows | Place two windows with disjoint interiors and a shared edge. Give one owner a candidate reaching that edge and another that stays at least the requested clearance away from the other window. With positive clearance only the latter is eligible. Exercise both net orders and verify the selected combination. |
| Reference above the baseline | At the choice-selection layer, give one net adjusted delays `{400, 400.8, 401.6}` and another `{400.4, 401.6}`, including each baseline. At tolerance `0.05`, expect both nets to end at `401.6`. At the same tolerance, offer verified choices with (skew, cost) of (0, 3), (0.05, 2), and (0.06, 1). Select (0.05, 2) in either proposal order. Lower the tolerance to 0.04 and select (0, 3). |
| Target between grid settings | Use the fixed-access detour fixture, limit the test to its one straight replacement and template family, and add `0.4` µm of group optical length to the second net's requested offset. The two detour heights separated by one 100 nm pitch now straddle the target. Each leaves residual skew `0.4` µm, above the `0.05` tolerance. Return the verified choice preferred by the cost ordering and report unmatched. |
| Budget after a usable improvement | Give one net adjusted delays `{400, 400.8, 401.6}` and another `{401, 401.6}`. Exhaust the budget just after evaluating `400.8` for the first net, while the second net still uses the baseline `401`. Return the improved verified routes with residual skew `0.2` and the budget status. With enough budget the group matches at `401.6`. Pair this with the existing zero-candidate budget case and the missing-delay case. |
| Budget after a match | Use the same choices and stop the budget after both members have verified choices at `401.6`. Return a completed match with zero residual skew and a budget diagnostic. |
| Window boundary and interference | Let an owner's detour footprint meet its window boundary exactly, then move it outside by more than the containment tolerance. Accept only the contained candidate. Route another net alongside the window at exact clearance, then move its only available approach inside that clearance. Reject the latter in both net orders. Keep the last verified layout if a replacement fails complete-layout verification. |
## Implementation risks and investigations
| Area | What will be difficult and how to investigate it |
| --- | --- |
| Grid fit and diagonal candidate generation | Prototype move evaluation and proposal together on a small board. Exercise diagonal S-bends with odd and even offsets, a 45° bend that needs tangent leads, and a U-turn with an incompatible diagonal leg spacing. Check how much lead the useful variants need and choose a bound from those results. Compare diagonal ray proposals and the flat-ended launch check with final polygon clearance at an exact-fit entrance. A legal endpoint and a legal footprint both need to reach the candidate list. [Current S-bend span](../inire/geometry/sbend.py#L22) · [Straight reach check](../inire/geometry/collision.py#L856) |
| Search history and runtime | The cheapest arrival at a pose and type can leave a footprint that blocks the only next move. Build a tiny case with a viable more expensive arrival and compare the production candidate set and pruning with exhaustive search. Try retaining an alternative arrival or retrying with weaker pruning if the case shows a coverage loss. Then measure coverage, candidates per expansion, geometry-cache work, and runtime on a representative board at the intended pitch. [Current closed set](../inire/router/_search.py#L125) · [Predecessor checks](../inire/router/_astar_admission.py#L180) |
| Cost scale and search priorities | The cheapest cardinal step in the fixture costs `2 × 10⁻⁶`, while current cost comparisons use a geometry tolerance of `10⁻⁶`. Use a cost-specific comparison tolerance and check congestion and guide weights against the catalog scale. Use a zero-heuristic reference on tiny cases and check any catalog cost bound against the available displacements. Verify a two-net case where the router must choose which net detours. [Cost comparisons](../inire/router/_astar_admission.py#L275) · [Congestion defaults](../inire/model.py#L268) |
| Geometry and Masque round trip | Calibrate the face tolerance independently of the positive-clearance join region, polygon sampling, and any mask export rounding. Compare the evaluated and placed geometry for a reflected and rotated fixed cell with off-origin ports and a generated diagonal bend with a numerical sliver. Check the exported geometry too if export is part of the integration boundary. [Current join checks](../inire/geometry/component_overlap.py#L47) |
| Bend model across angles | Check the generated port poses, centerline length, and minimum curvature for shallow S-bend lobes and for 45°, 90°, 135°, and 180° turns. Validate the optical model for shallow lobes as well as U-turns if the process data comes from a radius or loss limit measured on a large bend. A curvature floor leaves the rate of curvature change dependent on the angle and profile. [Partial Euler bend model](https://arxiv.org/abs/1910.07257) |
| Tuning resolution and model accuracy | Compare the rotated quarter-turn fixture with one between principal axes, where the modal group index averages to the mean of the two principal indices. Test a window with room for the detour and a target between attainable settings. The four-turn constant-index fixture changes by 0.8 µm of group optical length for a one-pitch increase in detour height. On a 100 µm route, a differential `ng` error of 0.0005 contributes 0.05 µm. On a representative multi-net layout, measure the best verified skew at caller-selected tolerances and the routing cost of reserving supplied windows. |
## Fixture data to record
After defining the Masque interface, construct the synthetic cells and record their authored geometry, port positions and headings, allowed rotations and reflections, traversal directions, and physical lengths. Include the reference layout bounds, obstacle and attachment geometry, layer, scale, grid, and tolerances for each fixture. Store expected placements and amounts independently of the evaluator so an evaluator regression can fail the comparisons.
### 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. 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.
- 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.
- Benchmark matching disabled first. Compare cost refinement on and off under the same routing budgets. Measure time and catalog cost at first full coverage and after refinement, completed net IDs, and extra work in proposals and verification. Include fixtures with a planted improvement and fixtures with no cheaper alternative. Use benchmarks and profiling to choose the default pass, its budget, and when to stop it early.
- For matching enabled, use supplied windows and record completed nets and groups, residual skew, eligible spans, verified detours, and time spent tuning. On layouts with an unmatched group, compare partial placement with and without the independent-net retry. Record its extra completed nets, elapsed time, and expansion and verification work. Use benchmarks and profiling to choose how much budget to leave for this retry and when it is worth running.

View file

@ -94,7 +94,6 @@ 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.
@ -153,11 +152,9 @@ 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 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_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_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`.

View file

@ -25,45 +25,6 @@ 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

View file

@ -1,679 +0,0 @@
"""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)

View file

@ -1,155 +0,0 @@
"""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)

View file

@ -1,147 +0,0 @@
"""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

View file

@ -1,227 +0,0 @@
"""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",
)

View file

@ -125,11 +125,9 @@ 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:

View file

@ -3,9 +3,11 @@ 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 check_component_endpoint, uses_custom_outline from inire.geometry.components import build_component, 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
@ -31,7 +33,11 @@ def process_move(
params: tuple, params: tuple,
) -> None: ) -> None:
cp = parent.port cp = parent.port
evaluator = config.evaluator coll_type = config.bend_collision_type
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)
@ -40,17 +46,32 @@ 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
local_settings = ( abs_key = (
move_class, params, net_width, *evaluator.cache_settings(), cp.as_tuple(),
id(outline) if outline is not None else None, template.length if template is not None else None, self_dilation, move_class,
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
rel_key = (cp.r, *local_settings) base_port = Port(0, 0, cp.r)
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]
@ -59,9 +80,20 @@ 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, evaluator.physical_geometry, outline): if board is not None and move_class != "straight" and not uses_custom_outline(move_class, physical_type, outline):
check_component_endpoint(cp, move_class, params, board.bounds) check_component_endpoint(cp, move_class, params, board.bounds)
res_rel = evaluator.evaluate(Port(0, 0, cp.r), net_width, move_class, params, self_dilation, template) res_rel = build_component(
base_port,
net_width,
move_class,
params,
collision_type=coll_type,
physical_geometry_type=physical_type,
clip_margin=config.bend_clip_margin,
dilation=self_dilation,
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)

View file

@ -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.evaluator.collision_type, config.evaluator.physical_geometry) circular_bend = bend90_uses_circular_geometry(config.bend_collision_type, config.bend_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

View file

@ -5,15 +5,14 @@ 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, ComponentResult from inire.geometry.components import BendCollisionModel, BendPhysicalGeometry, 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
@ -82,7 +81,9 @@ class CongestionCaches:
@dataclass(frozen=True, slots=True) @dataclass(frozen=True, slots=True)
class SearchRunConfig: class SearchRunConfig:
evaluator: LegacyMoveEvaluator bend_collision_type: BendCollisionModel
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
@ -132,8 +133,14 @@ 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(
evaluator=LegacyMoveEvaluator.from_options(search, collision_override=bend_collision_type), bend_collision_type=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),

View file

@ -5,25 +5,20 @@ 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 LineString, box from shapely.geometry import 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 (
@ -31,7 +26,6 @@ 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 (
@ -46,10 +40,9 @@ 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 PathSeed, SBendSeed, StraightSeed from inire.seeds import SBendSeed
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Callable, Iterable, Iterator from collections.abc import Callable, Iterable, Iterator
@ -61,6 +54,7 @@ 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]
@ -69,8 +63,6 @@ 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:
@ -263,40 +255,14 @@ 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):
@ -317,27 +283,6 @@ 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)
@ -590,12 +535,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, *, merge_close: bool = False) -> bool: def _try_column_jogs(self, options: RoutingOptions, trials: list[Trial], target: int) -> 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, merge_close=merge_close): for seeds in column_jog_candidates(problem, options.search, limit_per_pass=8):
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)
@ -762,35 +707,6 @@ 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(
@ -824,130 +740,6 @@ 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
@ -977,13 +769,8 @@ 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()

View file

@ -1,142 +0,0 @@
"""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

View file

@ -1,759 +0,0 @@
"""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,))

View file

@ -1,125 +0,0 @@
"""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],
)

View file

@ -1,998 +0,0 @@
"""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),
)

View file

@ -1,200 +0,0 @@
"""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

View file

@ -1,355 +0,0 @@
"""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)

View file

@ -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 accumulate, combinations_with_replacement, islice, pairwise, product from itertools import 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,7 +25,6 @@ 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
@ -40,27 +39,6 @@ _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
@ -159,41 +137,13 @@ 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 _merge_close_columns(columns: tuple[_Column, ...], minimum_gap: int) -> tuple[_Column, ...]: def _column_layout(problem: RoutingProblem, *, min_tracks: int = 3) -> _ColumnLayout | None:
"""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))
@ -466,18 +416,6 @@ 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]],
@ -490,7 +428,6 @@ 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(
@ -498,8 +435,6 @@ 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.
@ -512,19 +447,21 @@ 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
return distance(lower, upper, window, gap) >= need + 0.025 # Cache the shapes via the local wrapper. The span map is fixed.
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 eligible_rows: for row in rows:
scores = [] scores = []
predecessors = approaches.items() if can_shift else ((row, approaches[row]),) for previous, histories in approaches.items():
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
@ -601,15 +538,8 @@ 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(
@ -618,7 +548,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 profile_indices] interior = [profiles_for(i, spacing_slack, wall_slack) for i in range(len(columns))]
if weighted: if weighted:
adjacent = [[launch], *interior, [arrival]] adjacent = [[launch], *interior, [arrival]]
reachable_offsets = (0, *( reachable_offsets = (0, *(
@ -633,12 +563,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(profile_indices[i], spacing_slack + 5, wall_slack) roomier = profiles_for(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, pair_distance=pair_distance, weighted=weighted, sbend_penalty=sbend_penalty, allowed_offsets=allowed_offsets,
): ):
signature = rows, moves signature = rows, moves
if signature not in seen: if signature not in seen:
@ -805,7 +735,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, merge_close: bool = False, problem: RoutingProblem, search: SearchOptions, *, limit_per_pass: int | None = None, recovery: 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:
@ -813,7 +743,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, merge_gap=2 * radii[0] if merge_close else 0) layout = _column_layout(problem, min_tracks=1 if recovery else 3)
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