diff --git a/docs/benchmarks.md b/docs/benchmarks.md index 2bfe860..e5aaf11 100644 --- a/docs/benchmarks.md +++ b/docs/benchmarks.md @@ -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. 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. - -## 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. +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. diff --git a/docs/typed-and-octagonal-routing-plan.md b/docs/typed-and-octagonal-routing-plan.md deleted file mode 100644 index 357bbe5..0000000 --- a/docs/typed-and-octagonal-routing-plan.md +++ /dev/null @@ -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. diff --git a/docs/user/api-reference.md b/docs/user/api-reference.md index 3a4d509..5cf2bf9 100644 --- a/docs/user/api-reference.md +++ b/docs/user/api-reference.md @@ -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. | | `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. | -| `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. @@ -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. | | `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. | -| `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. | -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 The flags default to `False`. diff --git a/docs/user/route-a-layout.md b/docs/user/route-a-layout.md index 9adf02e..486daba 100644 --- a/docs/user/route-a-layout.md +++ b/docs/user/route-a-layout.md @@ -25,45 +25,6 @@ result = route(problem).results_by_net["input"] - [Bend radius settings](api-reference.md#searchoptions) - [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. - ## Route between placed crossings diff --git a/inire/_catalog.py b/inire/_catalog.py deleted file mode 100644 index c904128..0000000 --- a/inire/_catalog.py +++ /dev/null @@ -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) diff --git a/inire/_catalog_timing.py b/inire/_catalog_timing.py deleted file mode 100644 index cefee3c..0000000 --- a/inire/_catalog_timing.py +++ /dev/null @@ -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) diff --git a/inire/geometry/catalog_curve.py b/inire/geometry/catalog_curve.py deleted file mode 100644 index ca0be7d..0000000 --- a/inire/geometry/catalog_curve.py +++ /dev/null @@ -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 diff --git a/inire/masque.py b/inire/masque.py deleted file mode 100644 index 172f8eb..0000000 --- a/inire/masque.py +++ /dev/null @@ -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", - ) diff --git a/inire/model.py b/inire/model.py index 6807a17..3661639 100644 --- a/inire/model.py +++ b/inire/model.py @@ -125,11 +125,9 @@ class SearchOptions(_SearchOptionsCache): proximity_range: float = 10.0 bend_physical_length: float | None = None distance_heuristic_weight: float = 1.0 - terminal_jog_limit: int = 0 def __post_init__(self) -> None: _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("distance_heuristic_weight", self.distance_heuristic_weight) if not isfinite(self.proximity_range) or self.proximity_range <= 0: diff --git a/inire/router/_astar_admission.py b/inire/router/_astar_admission.py index b5a8c37..c782cb6 100644 --- a/inire/router/_astar_admission.py +++ b/inire/router/_astar_admission.py @@ -3,9 +3,11 @@ from __future__ import annotations import heapq from typing import TYPE_CHECKING +from shapely.geometry import Polygon + from inire.constants import TOLERANCE_LINEAR 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.router.refiner import component_hits_ancestor_chain @@ -31,7 +33,11 @@ def process_move( params: tuple, ) -> None: 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 if move_class == "sbend" and config.sbend_templates: template = config.sbend_templates.get(params) @@ -40,17 +46,32 @@ def process_move( outline = template.polygon if template else None self_dilation = context.cost_evaluator.collision_engine.clearance / 2.0 - local_settings = ( - move_class, params, net_width, *evaluator.cache_settings(), - id(outline) if outline is not None else None, template.length if template is not None else None, self_dilation, + abs_key = ( + cp.as_tuple(), + 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: context.metrics.total_move_cache_abs_hits += 1 res = context.move_cache_abs[abs_key] else: 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: context.metrics.total_move_cache_rel_hits += 1 res_rel = context.move_cache_rel[rel_key] @@ -59,9 +80,20 @@ def process_move( try: board = context.cost_evaluator.collision_engine.board # 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) - 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: return context.cache_move(rel_key, res_rel, relative=True) diff --git a/inire/router/_astar_moves.py b/inire/router/_astar_moves.py index d74e2dc..593fff1 100644 --- a/inire/router/_astar_moves.py +++ b/inire/router/_astar_moves.py @@ -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) 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: if circular_bend and not bend_fits_width(radius, net_width): continue diff --git a/inire/router/_astar_types.py b/inire/router/_astar_types.py index 473eb90..1e6ee8c 100644 --- a/inire/router/_astar_types.py +++ b/inire/router/_astar_types.py @@ -5,15 +5,14 @@ from dataclasses import dataclass, field from operator import attrgetter from typing import TYPE_CHECKING, get_type_hints +from inire.model import resolve_bend_geometry from inire.results import RouteMetrics from inire.router.visibility import VisibilityManager -from ._move_evaluation import LegacyMoveEvaluator - if TYPE_CHECKING: 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.model import RoutingOptions, RoutingProblem, SBendOutline from inire.router._topology import Corridor @@ -82,7 +81,9 @@ class CongestionCaches: @dataclass(frozen=True, slots=True) class SearchRunConfig: - evaluator: LegacyMoveEvaluator + bend_collision_type: BendCollisionModel + bend_physical_geometry: BendPhysicalGeometry + bend_clip_margin: float | None node_limit: int guidance_seed: tuple[PathSegmentSeed, ...] | None = None guidance_bonus: float = 0.0 @@ -132,8 +133,14 @@ class SearchRunConfig: expired: Callable[[], bool] | None = None, ) -> SearchRunConfig: search = options.search + bend_collision_type, bend_physical_geometry = resolve_bend_geometry( + search, + bend_collision_override=bend_collision_type, + ) 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, guidance_seed=guidance_seed, guidance_bonus=float(guidance_bonus), diff --git a/inire/router/_automatic.py b/inire/router/_automatic.py index eb61803..4f13a7c 100644 --- a/inire/router/_automatic.py +++ b/inire/router/_automatic.py @@ -5,25 +5,20 @@ from __future__ import annotations from contextlib import contextmanager, suppress from dataclasses import replace from functools import partial -from heapq import nsmallest from itertools import chain, islice, pairwise -from math import sqrt from time import perf_counter from typing import TYPE_CHECKING import shapely -from shapely.geometry import LineString, box -from shapely.strtree import STRtree +from shapely.geometry import box from inire.geometry.collision import RoutingWorld, _violates_net_clearance from inire.model import FixedRoute, resolve_bend_geometry 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._capacity import cut_capacity, port_conflicts from inire.router._columns import ( 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._perimeter import ( @@ -31,7 +26,6 @@ from inire.router._perimeter import ( perimeter_detour_candidates, residual_dogleg_candidates, terminal_link_seed, - terminal_offset_seeds, ) from inire.router._route_traces import complete_final_conflict_trace 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._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.refiner import PathRefiner -from inire.seeds import PathSeed, SBendSeed, StraightSeed +from inire.seeds import SBendSeed if TYPE_CHECKING: from collections.abc import Callable, Iterable, Iterator @@ -61,6 +54,7 @@ if TYPE_CHECKING: from inire.results import RoutingOperation, RoutingResult, RoutingRunResult from inire.router._routing_policy import Trial from inire.router.cost import CostEvaluator + from inire.seeds import PathSeed _Footprint = tuple[PathSeed, BaseGeometry] _PerimeterPair = tuple[_Footprint, _Footprint] @@ -69,8 +63,6 @@ if TYPE_CHECKING: _INITIAL_NODE_LIMIT = 500 _NEAR_PORT_NODE_LIMIT = 100 _NEAR_PORT_ITERATION_LIMIT = 2 -_COLUMN_SHORTCUT_LIMIT = 4 -_PORT_CAPACITY_JOG_LIMIT = 12 def _has_fragmented_shifts(trial: Trial) -> bool: @@ -263,40 +255,14 @@ class _AutomaticRun: if len(trials[-1].valid_costs) == len(problem.nets): 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) if span_trial is None: 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)): self.cost_pass_performed = True if self._column_trial(True, trials, problem=problem) is None: 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): planner = "local-sbend" with self._time("plan", planner=planner): @@ -317,27 +283,6 @@ class _AutomaticRun: rejections.append("Local S-bend layout failed full verification") 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: objective = self.options.objective 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) 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 if target != len(problem.nets) or problem.initial_paths: return False 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") if len(trial.valid_costs) == target: trials.append(trial) @@ -762,35 +707,6 @@ class _AutomaticRun: ) 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: best = _best_trial(trials) if not self.options.refinement.enabled or not any( @@ -824,130 +740,6 @@ class _AutomaticRun: 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: started = perf_counter() options = self.options @@ -977,13 +769,8 @@ class _AutomaticRun: target = min(target, cut.max_routed) if not cut and not conflicts: 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: 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) best = refinement_choice or _best_trial(trials) metrics = self.attempts.metrics() diff --git a/inire/router/_catalog_guidance.py b/inire/router/_catalog_guidance.py deleted file mode 100644 index 1a5673d..0000000 --- a/inire/router/_catalog_guidance.py +++ /dev/null @@ -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 diff --git a/inire/router/_catalog_layout.py b/inire/router/_catalog_layout.py deleted file mode 100644 index 02e128a..0000000 --- a/inire/router/_catalog_layout.py +++ /dev/null @@ -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,)) diff --git a/inire/router/_catalog_matching.py b/inire/router/_catalog_matching.py deleted file mode 100644 index 0fed67a..0000000 --- a/inire/router/_catalog_matching.py +++ /dev/null @@ -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], - ) diff --git a/inire/router/_catalog_search.py b/inire/router/_catalog_search.py deleted file mode 100644 index 534d1ca..0000000 --- a/inire/router/_catalog_search.py +++ /dev/null @@ -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), - ) diff --git a/inire/router/_catalog_tuning.py b/inire/router/_catalog_tuning.py deleted file mode 100644 index 703e7ce..0000000 --- a/inire/router/_catalog_tuning.py +++ /dev/null @@ -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 diff --git a/inire/router/_catalog_verify.py b/inire/router/_catalog_verify.py deleted file mode 100644 index 1ae6981..0000000 --- a/inire/router/_catalog_verify.py +++ /dev/null @@ -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) diff --git a/inire/router/_columns.py b/inire/router/_columns.py index 6182e65..30503a3 100644 --- a/inire/router/_columns.py +++ b/inire/router/_columns.py @@ -6,7 +6,7 @@ from collections import defaultdict from dataclasses import dataclass, replace from functools import cache, lru_cache 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 typing import TYPE_CHECKING @@ -25,7 +25,6 @@ if TYPE_CHECKING: from shapely.geometry import LineString, Polygon - from inire.geometry.components import ComponentResult from inire.geometry.primitives import Port from inire.model import NetSpec, RoutingProblem, SearchOptions from inire.router._waypoints import XY @@ -40,27 +39,6 @@ _MAX_COLUMN_PARTITIONS = 4096 _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) class _Track: 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]) -def _merge_close_columns(columns: tuple[_Column, ...], minimum_gap: int) -> tuple[_Column, ...]: - """Intersect apertures across gaps shorter than a jog's forward span.""" - merged: list[_Column] = [] - for column in columns: - if not merged or column.span[0] - merged[-1].span[1] >= minimum_gap: - merged.append(column) - continue - previous = merged[-1] - left, right = iter(previous.openings), iter(column.openings) - a, b = next(left, None), next(right, None) - shared = [] - while a is not None and b is not None: - low, high = max(a[0], b[0]), min(a[1], b[1]) - if low < high: - shared.append((low, high)) - if a[1] <= b[1]: - a = next(left, None) - else: - b = next(right, None) - merged[-1] = _Column((previous.span[0], column.span[1]), tuple(shared)) - return tuple(merged) - - -def _column_layout(problem: RoutingProblem, *, min_tracks: int = 3, merge_gap: int = 0) -> _ColumnLayout | None: +def _column_layout(problem: RoutingProblem, *, min_tracks: int = 3) -> _ColumnLayout | None: 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): return None start, finish, columns = _track_columns(problem, tracks) if not columns or _partition_budget_exceeded(tracks, columns): 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) arrival = tuple(int(track.right.y) for track in tracks) 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) -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( windows: tuple[Window, ...], profiles: list[list[Profile]], @@ -490,7 +428,6 @@ def _schedules( weighted: bool, sbend_penalty: float, allowed_offsets: frozenset[float] | None = None, - pair_distance: Callable[[_BendSequence, _BendSequence, int, int], float] | None = None, ) -> Iterator[tuple[tuple[Profile, ...], tuple[tuple[_BendSequence, ...], ...]]]: max_usable = max(before - after - 4 for (_, after), (before, _) in pairwise(windows)) choose = _bend_sequences( @@ -498,8 +435,6 @@ def _schedules( ) 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)) - 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 # 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) assert lower 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] approaches = {start: [(0.0, (start,))]} for ((_, after), (before, _)), rows in zip(pairwise(windows), profiles[1:], strict=True): 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 = {} - for row in eligible_rows: + for row in rows: scores = [] - predecessors = approaches.items() if can_shift else ((row, approaches[row]),) - for previous, histories in predecessors: + for previous, histories in approaches.items(): 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): 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)) 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) - 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)) def profiles_for(column_index: int, spacing_slack: int, wall_slack: int) -> list[Profile]: return _column_profiles( @@ -618,7 +548,7 @@ def _column_sbend_schedules( seen = set() 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: adjacent = [[launch], *interior, [arrival]] reachable_offsets = (0, *( @@ -633,12 +563,12 @@ def _column_sbend_schedules( interior[i] = sorted(set(interior[i] + seeded)) for i, column in enumerate(columns): 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])) profiles = [[launch], *interior, [arrival]] for rows, moves in _schedules( 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 if signature not in seen: @@ -805,7 +735,7 @@ def _column_jog_schedules( 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]]: """Allocate tracks through ordered apertures using staggered 90-degree jogs.""" 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)}) if not radii: 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: return circular = bend90_uses_circular_geometry(*resolve_bend_geometry(search)) diff --git a/inire/router/_jog.py b/inire/router/_jog.py deleted file mode 100644 index d4f4e74..0000000 --- a/inire/router/_jog.py +++ /dev/null @@ -1,73 +0,0 @@ -"""Obstacle-driven positions for constructive paths between parallel ports.""" - -from __future__ import annotations - -from itertools import pairwise -from math import ceil, floor -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from collections.abc import Iterable - - -def detour_lane_offsets( - start: tuple[int, int], - direction: tuple[int, int], - forward: int, - pitch: int, - margin: float, - blockers: Iterable[tuple[float, float, float, float]], -) -> set[int]: - """Find lateral lanes that clear each obstacle projected onto a cardinal route.""" - return { - lane - for _, _, side0, side1 in detour_blocker_spans(start, direction, forward, margin, blockers) - for lane in (floor((side0 - margin) / pitch) * pitch, ceil((side1 + margin) / pitch) * pitch) - } - - -def detour_blocker_spans( - start: tuple[int, int], - direction: tuple[int, int], - forward: int, - margin: float, - blockers: Iterable[tuple[float, float, float, float]], -) -> Iterable[tuple[float, float, float, float]]: - """Project blockers intersecting the clearance envelope of a cardinal span.""" - sx, sy = start - dx, dy = direction - for x0, y0, x1, y1 in blockers: - # Opposing corners give both projection extrema on a cardinal axis. - a, b, c, d = x0 - sx, y0 - sy, x1 - sx, y1 - sy - lo, hi = sorted((dx * a + dy * b, dx * c + dy * d)) - side0, side1 = sorted((dx * b - dy * a, dx * d - dy * c)) - if hi >= -margin and lo <= forward + margin and side0 <= margin and side1 >= -margin: - yield lo, hi, side0, side1 - - -def jog_launch_steps( - start: tuple[int, int], - direction: tuple[int, int], - lateral: int, - turn_advance: int, - steps: int, - pitch: int, - margin: float, - blockers: Iterable[tuple[float, float, float, float]], -) -> list[int]: - """Sample the free longitudinal span at obstacle boundaries and between them.""" - sx, sy = start - dx, dy = direction - step_forward = pitch * (dx * dx + dy * dy) - cuts = {0, steps} - for x0, y0, x1, y1 in blockers: - corners = tuple((x - sx, y - sy) for x in (x0, x1) for y in (y0, y1)) - side = tuple(dx * y - dy * x for x, y in corners) - if min(side) > max(0, lateral) + margin or max(side) < min(0, lateral) - margin: - continue - forward = tuple(dx * x + dy * y for x, y in corners) - for boundary in (min(forward) - margin, max(forward) + margin): - for offset in (0, turn_advance): - position = (boundary - offset) / step_forward - cuts.update(n for n in (floor(position), ceil(position)) if 0 <= n <= steps) - return sorted(cuts | {(lo + hi) // 2 for lo, hi in pairwise(sorted(cuts))} | {steps // 2}) diff --git a/inire/router/_move_evaluation.py b/inire/router/_move_evaluation.py deleted file mode 100644 index e6c33cf..0000000 --- a/inire/router/_move_evaluation.py +++ /dev/null @@ -1,71 +0,0 @@ -from __future__ import annotations - -from dataclasses import dataclass -from typing import TYPE_CHECKING - -from shapely.geometry import Polygon - -from inire.geometry.components import build_component, component_endpoint, prepare_component_sampling -from inire.model import resolve_bend_geometry - -if TYPE_CHECKING: - from inire.geometry.components import BendCollisionModel, BendPhysicalGeometry, ComponentResult, MoveKind - from inire.geometry.primitives import Port - from inire.model import SBendOutline, SearchOptions - - -@dataclass(frozen=True, slots=True) -class LegacyMoveEvaluator: - """Evaluate a chosen Manhattan move using the existing primitive geometry.""" - - collision_type: BendCollisionModel - physical_geometry: BendPhysicalGeometry - clip_margin: float | None - bend_length: float | None - - @classmethod - def from_options( - cls, search: SearchOptions, *, collision_override: BendCollisionModel | None = None, - ) -> LegacyMoveEvaluator: - proxy, physical = resolve_bend_geometry(search, bend_collision_override=collision_override) - return cls(proxy, physical, search.bend_clip_margin, search.bend_physical_length) - - def validate( - self, start: Port, width: float, kind: MoveKind, parameters: tuple, dilation: float, template: SBendOutline | None = None, - ) -> Port: - """Check a seed's endpoint and sampling requirements before allocating geometry.""" - end = component_endpoint(start, kind, parameters) - prepare_component_sampling( - kind, parameters, width, collision_type=self.collision_type, physical_geometry_type=self.physical_geometry, - dilation=dilation, sbend_outline=template.polygon if template is not None else None, - ) - return end - - def evaluate( - self, - start: Port, - width: float, - kind: MoveKind, - parameters: tuple, - dilation: float, - template: SBendOutline | None = None, - *, - bounds: tuple[float, float, float, float] | None = None, - ) -> ComponentResult: - return build_component( - start, width, kind, parameters, - collision_type=self.collision_type, physical_geometry_type=self.physical_geometry, - clip_margin=self.clip_margin, dilation=dilation, - sbend_outline=template.polygon if template is not None else None, - physical_length=self.bend_length if kind == "bend90" else (template.length if template is not None else None), - bounds=bounds, - ) - - def cache_settings(self) -> tuple: - """Key for geometry caches owned by a routing context that retains the options.""" - return ( - id(self.collision_type) if isinstance(self.collision_type, Polygon) else self.collision_type, - id(self.physical_geometry) if isinstance(self.physical_geometry, Polygon) else self.physical_geometry, - self.clip_margin, - self.bend_length, - ) diff --git a/inire/router/_perimeter.py b/inire/router/_perimeter.py index 59bfeb2..606f110 100644 --- a/inire/router/_perimeter.py +++ b/inire/router/_perimeter.py @@ -4,23 +4,21 @@ from __future__ import annotations from dataclasses import replace from functools import lru_cache -from itertools import chain, combinations, islice, pairwise, product +from itertools import combinations, islice, pairwise, product from math import ceil, floor, isfinite from typing import TYPE_CHECKING from inire.geometry.collision import RoutingWorld -from inire.geometry.components import Straight, bend90_grid_span, bend90_uses_circular_geometry, bend_fits_width +from inire.geometry.components import Straight, bend90_uses_circular_geometry, bend_fits_width from inire.geometry.primitives import Port, rotate_cardinal from inire.model import resolve_bend_geometry -from inire.router._jog import detour_lane_offsets, jog_launch_steps from inire.router._seed_materialization import materialize_path_seed from inire.router._waypoints import _direction, compile_waypoints, export_waypoints from inire.seeds import Bend90Seed, PathSeed, StraightSeed if TYPE_CHECKING: - from collections.abc import Callable, Iterator + from collections.abc import Iterator - from inire.geometry.components import ComponentResult from inire.model import NetSpec, RoutingProblem, SearchOptions from inire.router._waypoints import XY @@ -233,71 +231,6 @@ def terminal_link_seed(net: NetSpec, search: SearchOptions) -> PathSeed | None: return seed if end == target else None -def terminal_offset_seeds(net: NetSpec, search: SearchOptions, world: RoutingWorld) -> Iterator[PathSeed]: - sx, sy, heading = net.start.as_tuple() - tx, ty, target_heading = net.target.as_tuple() - if heading != target_heading or not bend90_uses_circular_geometry(*resolve_bend_geometry(search)): - return - forward, lateral = map(int, rotate_cardinal(tx - sx, ty - sy, -heading)) - if forward <= 0: - return - dx, dy = map(int, rotate_cardinal(1, 0, heading)) - margin = world.clearance + net.width / 2 - bounds = min(sx, tx) - margin, min(sy, ty) - margin, max(sx, tx) + margin, max(sy, ty) + margin - blockers = (*world.iter_static_obstacle_bounds(bounds), *world.iter_dynamic_path_bounds(bounds)) - if lateral == 0: - lanes = detour_lane_offsets((sx, sy), (dx, dy), forward, 1, margin, blockers) - if lanes: - yield from _terminal_detours(net, search, forward, lanes) - return - for radius in sorted(set(search.bend_radii)): - span = bend90_grid_span(radius) - if min(forward, abs(lateral)) < 2 * span or not bend_fits_width(radius, net.width): - continue - for lead in jog_launch_steps((sx, sy), (dx, dy), lateral, 2 * span, forward - 2 * span, 1, margin, blockers): - x = lead + span - ax, ay = rotate_cardinal(x, 0, heading) - bx, by = rotate_cardinal(x, lateral, heading) - points = ((sx, sy), (sx + int(ax), sy + int(ay)), (sx + int(bx), sy + int(by)), (tx, ty)) - seed, end = compile_waypoints(points, net.start, radius) - if end == net.target: - yield seed - - -def _terminal_detours(net: NetSpec, search: SearchOptions, forward: int, lanes: set[int]) -> Iterator[PathSeed]: - sx, sy, heading = net.start.as_tuple() - for radius in sorted(set(search.bend_radii)): - span = bend90_grid_span(radius) - if forward < 4 * span or not bend_fits_width(radius, net.width): - continue - offsets = {max(lane, 2 * span) if lane >= 0 else min(lane, -2 * span) for lane in lanes} - for lateral in sorted(offsets, key=lambda offset: (abs(offset), offset)): - midpoints = ((span, 0), (span, lateral), (forward - span, lateral), (forward - span, 0)) - points = [(sx, sy)] - for x, y in midpoints: - rx, ry = rotate_cardinal(x, y, heading) - points.append((sx + int(rx), sy + int(ry))) - points.append((int(net.target.x), int(net.target.y))) - seed, end = compile_waypoints(tuple(points), net.start, radius) - if end == net.target: - yield seed - - -def terminal_constructive_path( - net: NetSpec, search: SearchOptions, world: RoutingWorld, *, expired: Callable[[], bool], -) -> tuple[ComponentResult, ...] | None: - """Try verified terminal links and detours before native search.""" - link = terminal_link_seed(net, search) - offsets = islice(terminal_offset_seeds(net, search, world), search.terminal_jog_limit) - for seed in chain((link,) if link else (), offsets): - if expired(): - break - path = materialize_path_seed(seed, start=net.start, net_width=net.width, search=search, clearance=world.clearance) - if path and path[-1].end_port == net.target and world.verify_path_report(net.net_id, path).is_valid: - return path - return None - - def _return_detours( problem: RoutingProblem, net: NetSpec, diff --git a/inire/router/_router.py b/inire/router/_router.py index 6e7b454..94bddbb 100644 --- a/inire/router/_router.py +++ b/inire/router/_router.py @@ -35,7 +35,6 @@ from inire.router._congestion_policy import ( review_verified_results, ) from inire.router._pair_local import search_pair_candidate -from inire.router._perimeter import terminal_constructive_path from inire.router._route_traces import conflict_trace_entry, iteration_trace_entry, net_attempt_trace from inire.router._search import _distance_to_terminal, incumbent_guidance, path_guidance, route_astar from inire.router._seed_materialization import materialize_path_seed, SeedMaterializationError @@ -184,8 +183,7 @@ class PathFinder: state: _RoutingState, ) -> dict[str, tuple[ComponentResult, ...]]: greedy_paths: dict[str, tuple[ComponentResult, ...]] = {} - search = self.context.options.search - greedy_node_limit = min(search.node_limit, 2000) + greedy_node_limit = min(self.context.options.search.node_limit, 2000) world = self.context.cost_evaluator.collision_engine existing = state.initial_paths or {} expired = partial(self._expired, state) @@ -201,38 +199,34 @@ class PathFinder: if net_id in existing or net_id in state.terminal_errors: continue net = state.net_specs[net_id] - path = None - if search.terminal_jog_limit and not state.corridors: - path = terminal_constructive_path(net, search, world, expired=expired) - if path is None: - h_start = self.context.cost_evaluator.h_manhattan( - net.start, - net.target, - min_bend_radius=self.context.min_bend_radius, - ) - max_cost_limit = max(h_start * 3.0, 2000.0) - candidates = state.corridors.get(net_id, ()) - run_config = SearchRunConfig.from_options( - self.context.options, - skip_congestion=True, - max_cost=max_cost_limit, - self_collision_check=True, - node_limit=greedy_node_limit, - corridor=candidates[0] if candidates else None, - corridor_strength=self.context.options.topology.guide_strength, - expired=expired, - ) - path = route_astar( - net.start, - net.target, - net.width, - context=self.context, - metrics=self.metrics, - net_id=net_id, - config=run_config, - ) - if not path or world.verify_path_report(net_id, path).intrinsic_collision_count: - continue + h_start = self.context.cost_evaluator.h_manhattan( + net.start, + net.target, + min_bend_radius=self.context.min_bend_radius, + ) + max_cost_limit = max(h_start * 3.0, 2000.0) + candidates = state.corridors.get(net_id, ()) + run_config = SearchRunConfig.from_options( + self.context.options, + skip_congestion=True, + max_cost=max_cost_limit, + self_collision_check=True, + node_limit=greedy_node_limit, + corridor=candidates[0] if candidates else None, + corridor_strength=self.context.options.topology.guide_strength, + expired=expired, + ) + path = route_astar( + net.start, + net.target, + net.width, + context=self.context, + metrics=self.metrics, + net_id=net_id, + config=run_config, + ) + if not path or world.verify_path_report(net_id, path).intrinsic_collision_count: + continue self.metrics.total_warm_start_paths_built += 1 greedy_paths[net_id] = tuple(path) reserve(net_id, path) diff --git a/inire/router/_seed_materialization.py b/inire/router/_seed_materialization.py index c894b3e..8fa2ed1 100644 --- a/inire/router/_seed_materialization.py +++ b/inire/router/_seed_materialization.py @@ -2,12 +2,12 @@ from __future__ import annotations from typing import TYPE_CHECKING -from inire.geometry.components import ComponentPreparationError -from inire.model import _AmbiguousSBendOutlineError +from inire.geometry.components import ( + ComponentPreparationError, build_component, component_endpoint, prepare_component_sampling, +) +from inire.model import _AmbiguousSBendOutlineError, resolve_bend_geometry from inire.seeds import Bend90Seed, SBendSeed, StraightSeed -from ._move_evaluation import LegacyMoveEvaluator - if TYPE_CHECKING: from inire.geometry.components import ComponentResult, MoveKind from inire.geometry.primitives import Port @@ -26,12 +26,16 @@ def seed_move(segment: PathSegmentSeed) -> tuple[MoveKind, tuple]: def seed_preparation_error(seed: PathSeed, *, start: Port, net_width: float, search: SearchOptions, clearance: float) -> str | None: - evaluator = LegacyMoveEvaluator.from_options(search) + proxy, physical = resolve_bend_geometry(search) for index, segment in enumerate(seed.segments, start=1): kind, parameters = seed_move(segment) try: template = search.sbend_template(segment.offset, segment.radius, net_width) if isinstance(segment, SBendSeed) else None - start = evaluator.validate(start, net_width, kind, parameters, clearance / 2, template) + start = component_endpoint(start, kind, parameters) + prepare_component_sampling( + kind, parameters, net_width, collision_type=proxy, physical_geometry_type=physical, + dilation=clearance / 2, sbend_outline=template.polygon if template is not None else None, + ) except (ComponentPreparationError, OverflowError, _AmbiguousSBendOutlineError) as exc: return f"segment {index} ({type(segment).__name__}) {exc}" return None @@ -61,7 +65,8 @@ def materialize_path_seed( path: list[ComponentResult] = [] current = start dilation = clearance / 2.0 - evaluator = LegacyMoveEvaluator.from_options(search) + bend_collision_type, bend_physical_geometry = resolve_bend_geometry(search) + bend_clip_margin = search.bend_clip_margin for index, segment in enumerate(seed.segments, start=1): if component_cache is not None: @@ -74,8 +79,18 @@ def materialize_path_seed( kind, parameters = seed_move(segment) try: template = search.sbend_template(segment.offset, segment.radius, net_width) if isinstance(segment, SBendSeed) else None - component = evaluator.evaluate( - current, net_width, kind, parameters, dilation, template, bounds=None if diagnostic else bounds, + component = build_component( + current, + net_width, + kind, + parameters, + collision_type=bend_collision_type, + physical_geometry_type=bend_physical_geometry, + clip_margin=bend_clip_margin, + dilation=dilation, + sbend_outline=template.polygon if template is not None else None, + bounds=None if diagnostic else bounds, + physical_length=search.bend_physical_length if kind == "bend90" else (template.length if template else None), ) except (ComponentPreparationError, OverflowError, _AmbiguousSBendOutlineError) as exc: if diagnostic: diff --git a/inire/router/_weighted_local.py b/inire/router/_weighted_local.py deleted file mode 100644 index 1dbcb3d..0000000 --- a/inire/router/_weighted_local.py +++ /dev/null @@ -1,123 +0,0 @@ -"""Bounded native window searches using the automatic selection cost.""" - -from __future__ import annotations - -from dataclasses import replace -from heapq import nsmallest -from itertools import accumulate -from math import hypot, pi -from typing import TYPE_CHECKING - -from inire.constants import TOLERANCE_LINEAR -from inire.geometry.collision import RoutingWorld -from inire.router._astar_types import AStarContext, AStarMetrics, SearchRunConfig -from inire.router._search import route_astar -from inire.router.cost import CostEvaluator, weighted_path_length - -if TYPE_CHECKING: - from collections.abc import Iterator, Mapping - - from inire.geometry.components import ComponentResult - from inire.geometry.primitives import Port - from inire.model import RoutingOptions, RoutingProblem - from inire.results import RoutingResult - from inire.router.cost import ScoreableMove - - -_WINDOW_NODE_LIMIT = 64 -_WINDOW_ATTEMPT_LIMIT = 12 -_WINDOW_COMPONENT_LIMIT = 16 -_SEARCH_WORK_DIVISOR = 8 - - -class _LengthCost(CostEvaluator): - def __init__(self, world: RoutingWorld, weights: Mapping[str, float]) -> None: - super().__init__(world, greedy_h_weight=1, danger_weight=0) - self.weights = weights - self.minimum_rate = min(weights.values()) - - def score_component(self, component: ScoreableMove, **_ignored: object) -> float: - if self.collision_engine.metrics is not None: - self.collision_engine.metrics.total_score_component_calls += 1 - return component.length * self.weights[component.move_type] - - def h_manhattan(self, current: Port, target: Port, *, min_bend_radius: float = 50.0) -> float: - # All generated moves pay at least minimum_rate times their length. - # Changing heading also requires the excess cost of quarter turns. - turn = int(target.r - current.r) % 360 - turns = min(turn, 360 - turn) // 90 - bend_cost = (self.weights["bend90"] - self.minimum_rate) * pi * min_bend_radius / 2 - return self.minimum_rate * hypot(target.x - current.x, target.y - current.y) + turns * bend_cost - - -def _windows( - paths: Mapping[str, tuple[ComponentResult, ...]], evaluator: _LengthCost, min_radius: float, -) -> Iterator[tuple[float, int, str, int, int, float]]: - for name, path in paths.items(): - if not any(move.move_type == "sbend" for move in path): - continue - costs = tuple(accumulate((evaluator.score_component(move) for move in path), initial=0.0)) - bends = tuple(accumulate((move.move_type == "sbend" for move in path), initial=0)) - for begin, move in enumerate(path): - start = move.start_port - for end in range(begin + 1, min(len(path), begin + _WINDOW_COMPONENT_LIMIT) + 1): - if bends[end] == bends[begin]: - continue - cost = costs[end] - costs[begin] - bound = evaluator.h_manhattan(start, path[end - 1].end_port, min_bend_radius=min_radius) - if cost - bound > TOLERANCE_LINEAR: - yield bound - cost, end - begin, name, begin, end, cost - - -def improve_weighted_windows( - problem: RoutingProblem, - options: RoutingOptions, - incumbent: Mapping[str, RoutingResult], - weights: Mapping[str, float], - *, - search_expansions: int, -) -> tuple[dict[str, RoutingResult], AStarMetrics]: - """Spend a fraction of the preceding search work on high-headroom windows.""" - metrics = AStarMetrics() - node_limit = min(options.search.node_limit, _WINDOW_NODE_LIMIT) - attempts = min(_WINDOW_ATTEMPT_LIMIT, search_expansions // (_SEARCH_WORK_DIVISOR * node_limit)) if node_limit else 0 - if not attempts or not all(result.is_valid for result in incumbent.values()): - return {}, metrics - paths = {name: result.path for name, result in incumbent.items() if result.path} - if not any(move.move_type == "sbend" for path in paths.values() for move in path): - return {}, metrics - world = RoutingWorld.from_problem(problem, use_dynamic_grid=False) - world.metrics = metrics - evaluator = _LengthCost(world, weights) - context = AStarContext(evaluator, problem, options, metrics=metrics) - windows = nsmallest(attempts, _windows(paths, evaluator, context.min_bend_radius)) - if not windows: - return {}, metrics - nets = {net.net_id: net for net in problem.nets} - for name, path in paths.items(): - world.add_route(name, path) - - changed = {} - for _, _, name, begin, end, cost in windows: - if name in changed: - continue - path = paths[name] - portion = path[begin:end] - start, target = portion[0].start_port, portion[-1].end_port - metrics.total_refinement_windows_considered += 1 - config = SearchRunConfig.from_options( - options, node_limit=node_limit, hard_congestion=True, self_collision_check=True, max_cost=cost - TOLERANCE_LINEAR, - guidance_seed=tuple(move.move_spec for move in portion), propose_guidance_moves=True, - ) - result = route_astar(start, target, nets[name].width, context, metrics=metrics, net_id=name, config=config) - if not result or result[-1].end_port != target or weighted_path_length(result, weights) >= cost - TOLERANCE_LINEAR: - continue - candidate = (*path[:begin], *result, *path[end:]) - metrics.total_refinement_candidates_verified += 1 - report = world.verify_path_report(name, candidate) - if report.is_valid: - world.remove_path(name) - world.add_route(name, candidate) - metrics.total_refinement_candidates_accepted += 1 - changed[name] = replace(incumbent[name], path=candidate, report=report) - return changed, metrics diff --git a/inire/router/refiner.py b/inire/router/refiner.py index 8454619..87ea5b1 100644 --- a/inire/router/refiner.py +++ b/inire/router/refiner.py @@ -12,14 +12,12 @@ from shapely.geometry import Polygon from inire.constants import TOLERANCE_LINEAR from inire.geometry.component_overlap import components_overlap from inire.geometry.components import ( - _bend90_length, bend_fits_width, bend90_grid_span, bend90_uses_circular_geometry, component_endpoint, + _bend90_length, bend_fits_width, bend90_grid_span, bend90_uses_circular_geometry, build_component, component_endpoint, ComponentPreparationError, ) from inire.geometry.primitives import port_local_coordinates from inire.model import resolve_bend_geometry -from ._move_evaluation import LegacyMoveEvaluator - if TYPE_CHECKING: from collections.abc import Callable, Iterator, Sequence @@ -269,7 +267,7 @@ class PathRefiner: components: dict[tuple[Port, MoveKind, tuple], ComponentResult], ) -> list[ComponentResult]: search = self.context.options.search - evaluator = LegacyMoveEvaluator.from_options(search) + proxy, physical = resolve_bend_geometry(search) dilation = self.collision_engine.clearance / 2.0 path = [] port = start @@ -280,7 +278,11 @@ class PathRefiner: key = (port, move.move_type, parameters) component = components.get(key) if component is None: - component = evaluator.evaluate(port, width, move.move_type, parameters, dilation, bounds=bounds) + component = build_component( + port, width, move.move_type, parameters, + collision_type=proxy, physical_geometry_type=physical, clip_margin=search.bend_clip_margin, dilation=dilation, + physical_length=search.bend_physical_length if move.move_type == "bend90" else None, bounds=bounds, + ) if len(components) < 256: components[key] = component path.append(component) @@ -376,7 +378,6 @@ class PathRefiner: circular_bend = bend90_uses_circular_geometry(proxy, physical) custom_danger_map = self.context.cost_evaluator.danger_map if isinstance(physical, Polygon) else None components: dict[tuple[Port, MoveKind, tuple], ComponentResult] = {} - checked_spans: dict[tuple[Port, float], bool] = {} for radius in search.bend_radii: if expired is not None and expired(): break @@ -397,22 +398,6 @@ class PathRefiner: if not outside and not self.score_path(scoring_start, [*prefix, *moves, *suffix]) + 1e-6 < best_candidate_cost: continue try: - # The long straight through the middle can hit a keepout - # or peer even if its endpoint turns have room. Check it - # before materializing the bends. - middle = next(( - i for i, move in enumerate(moves) - if move.move_type == "straight" and move.end_port.r == window_start.r - ), None) - if middle is not None: - first = moves[middle - 1].end_port - span = moves[middle] - key = first, span.length - if key not in checked_spans: - pieces = self._build_dogleg(first, net_width, radius, [span], components) - checked_spans[key] = self.collision_engine.verify_path_report(net_id, pieces).is_valid - if not checked_spans[key]: - continue replacement = self._build_dogleg(window_start, net_width, radius, moves, components) except (ComponentPreparationError, OverflowError): continue diff --git a/inire/tests/catalog_device_set.py b/inire/tests/catalog_device_set.py deleted file mode 100644 index b737673..0000000 --- a/inire/tests/catalog_device_set.py +++ /dev/null @@ -1,44 +0,0 @@ -"""The synthetic 4, 5, and 8 µm waveguide technology in the routing plan.""" - -from shapely.geometry import Polygon, box - -from inire._catalog import BendVariant, Catalog, FixedVariant, Grid, Orientation, Pose, Profile, SBendVariant, StraightVariant, Variant -from inire._catalog_timing import DelayModel - - -GRID = Grid((0, 0), 100, 1e-9) -WAVELENGTH = 1.55e-6 -ORIENTATIONS = tuple(Orientation(angle, reflected) for angle in (0, 90, 180, 270) for reflected in (False, True)) -TRAVERSALS = (("a", "b"), ("b", "a")) - - -def synthetic_device_set() -> tuple[Catalog, DelayModel]: - variants: dict[str, Variant] = { - "straight-4": StraightVariant("4", 1.0), - "straight-5": StraightVariant("5", 0.5), - "straight-8": StraightVariant("8", 0.2), - } - for profile, radius, quarter_cost in (("4", 10_000, 0.01), ("8", 100_000, 0.1)): - for turns in (45, 90, 135, 180): - for sign in (-1, 1): - angle = turns * sign - variants[f"bend-{profile}-{angle}"] = BendVariant( - profile, angle, radius, quarter_cost * (2 if turns >= 135 else 1), - max_lead=200, sagitta=10, - ) - span, shift = 4 * radius // GRID.pitch, radius // (2 * GRID.pitch) - variants[f"sbend-{profile}"] = SBendVariant(profile, radius, 2 * quarter_cost, ((span, shift), (span, -shift)), sagitta=10) - a = Pose(0, 0, 0, "4") - variants["4-to-5"] = FixedVariant( - "4-to-5", {"a": a, "b": Pose(10_000, 0, 180, "5")}, - (Polygon(((0, -2000), (10_000, -2500), (10_000, 2500), (0, 2000))),), - TRAVERSALS, ORIENTATIONS, 0.01, 10_000, - ) - variants["4-to-8"] = FixedVariant( - "4-to-8", {"a": a, "b": Pose(100_000, 200, 180, "8")}, (box(0, -5000, 100_000, 5000),), - TRAVERSALS, ORIENTATIONS, 0.2, 100_010, - (Polygon(((0, -2000), (100_000, -3800), (100_000, 4200), (0, 2000))),), - ) - profiles = {name: Profile(f"ridge-{name}", int(name) * 1000) for name in ("4", "5", "8")} - timing = DelayModel(WAVELENGTH, group_indices={"4": 4, "5": 4, "8": 2}, variant_delays={"4-to-5": 40_000, "4-to-8": 300_030}) - return Catalog("synthetic-4-5-8", profiles, variants), timing diff --git a/inire/tests/test_catalog_device_set.py b/inire/tests/test_catalog_device_set.py deleted file mode 100644 index 371c7df..0000000 --- a/inire/tests/test_catalog_device_set.py +++ /dev/null @@ -1,58 +0,0 @@ -from dataclasses import replace -from math import pi, sqrt - -import pytest - -from inire._catalog import Move, MoveEvaluator, Pose -from inire._catalog_timing import evaluate_delay -from inire.tests.catalog_device_set import GRID, synthetic_device_set - - -def test_synthetic_device_set_has_the_expected_rate_radius_and_delay() -> None: - catalog, timing = synthetic_device_set() - evaluator = MoveEvaluator(GRID, catalog) - for name, cost in (("4", 0.1), ("5", 0.05), ("8", 0.02)): - cardinal = evaluator.evaluate(Move(f"straight-{name}", steps=10_000), Pose(0, 0, 0, name)) - diagonal = evaluator.evaluate(Move(f"straight-{name}", steps=10_000), Pose(0, 0, 45, name)) - assert cardinal is not None - assert diagonal is not None - assert cardinal.cost == pytest.approx(cost) - assert diagonal.cost == pytest.approx(cost * sqrt(2)) - for name, radius, cost in (("4", 10_000, 0.01), ("8", 100_000, 0.1)): - for sign in (-1, 1): - spec = Move(f"bend-{name}-{sign * 90}", displacement=(radius, sign * radius)) - bend = evaluator.evaluate(spec, Pose(0, 0, 0, name)) - assert bend is not None - assert bend.length == pytest.approx(radius * pi / 2) - assert bend.cost == pytest.approx(cost) - shift = evaluator.evaluate(Move(f"sbend-{name}", displacement=(4 * radius, radius // 2)), Pose(0, 0, 0, name)) - assert shift is not None - assert shift.cost == pytest.approx(2 * cost) - - assert {move.variant for move, _ in evaluator.local_moves("5", 0)} == {"4-to-5"} - for name, other, displacement, length, cost, optical_length in ( - ("4-to-5", "5", (10_000, 0), 10_000, 0.01, 40_000), - ("4-to-8", "8", (100_000, 200), 100_010, 0.2, 300_030), - ): - a = Pose(0, 0, 0, "4") - b = Pose(*displacement, 0, other) - for traversal, start, end in ((("a", "b"), a, b), (("b", "a"), b.reversed(), a.reversed())): - piece = evaluator.evaluate(Move(name, traversal=traversal), start) - assert piece is not None - assert piece.end == end - assert piece.length == length - assert piece.cost == cost - delay = evaluate_delay(evaluator, (piece,), timing, net_id=name) - assert delay is not None - assert delay.optical_length == optical_length - - - displaced = catalog.variants["4-to-8"] - unknown = replace(catalog, variants={**catalog.variants, "4-to-8": replace(displaced, length=None)}) - uncharacterized = MoveEvaluator(GRID, unknown) - piece = uncharacterized.evaluate(Move("4-to-8", traversal=("a", "b")), Pose(0, 0, 0, "4")) - assert piece is not None - assert piece.length is None - delay = evaluate_delay(uncharacterized, (piece,), timing, net_id="4-to-8") - assert delay is not None - assert delay.optical_length == 300_030 diff --git a/inire/tests/test_catalog_moves.py b/inire/tests/test_catalog_moves.py deleted file mode 100644 index 566f315..0000000 --- a/inire/tests/test_catalog_moves.py +++ /dev/null @@ -1,1340 +0,0 @@ -from dataclasses import replace -from math import cos, hypot, pi, radians, sin, sqrt - -import pytest -from scipy.integrate import quad -from shapely.affinity import rotate, translate -from shapely.geometry import LineString, MultiPolygon, Polygon, box - -from inire._catalog import ( - BendVariant, Catalog, Evaluation, FixedVariant, Grid, Move, MoveEvaluator, Orientation, Placement, Pose, Profile, - SBendVariant, StraightVariant, TaperVariant, -) -from inire._catalog_timing import Delay, DelayModel, UniaxialGroupIndex, evaluate_delay -from inire.geometry.catalog_curve import bend_curve -from inire.geometry.components import Bend90 -from inire.geometry.primitives import Port -from inire.masque import Connection, Endpoint, route_and_place -from inire.router._catalog_guidance import AutomaticGrid, CoarseGuidance, find_corridor -from inire.router._catalog_layout import CatalogNet, LayoutSettings, route_layout -from inire.router._catalog_matching import DelayChoice, MatchGroup, choose_match -from inire.router._catalog_search import search_path -from inire.router._catalog_verify import Attachment, compatible_join, replay_moves, verify_path - - -def test_exact_grid_membership_in_adapter_units() -> None: - grid = Grid((30, -20), 100, 1e-9) - assert grid.lattice_position(330, 180) == (3, 2) - assert grid.lattice_position(331, 180) is None - with pytest.raises(TypeError, match="integer layout coordinate"): - grid.lattice_position(330.00000000000006, 180) - - -def test_replay_a_displaced_transition_in_both_directions() -> None: - transition = FixedVariant( - "displaced", {"a": Pose(0, 0, 0, "thin"), "b": Pose(100_000, 200, 180, "wide")}, - (box(0, -5000, 100_000, 5000),), - (("a", "b"), ("b", "a")), (Orientation(), Orientation(180, True)), 0.2, 100_010, - ) - catalog = Catalog("fixture", {"thin": Profile("4 µm", 4000), "wide": Profile("8 µm", 8000)}, { - "displaced": transition, "wide-straight": StraightVariant("wide", 0.2), - }) - evaluator = MoveEvaluator(Grid((0, 0), 100, 1e-9), catalog) - start = Pose(10_000, 20_000, 0, "thin") - moves = ( - Move("displaced", traversal=("a", "b")), - Move("wide-straight", steps=200), - Move("displaced", traversal=("b", "a"), orientation=Orientation(180, True)), - ) - path = replay_moves(evaluator, start, moves) - assert path is not None - first, straight, last = path - assert first.end == Pose(110_000, 20_200, 0, "wide") - assert straight.end == Pose(130_000, 20_200, 0, "wide") - assert last.end == Pose(230_000, 20_000, 0, "thin") - assert last.placement == Placement(Orientation(180, True), 230_000, 20_000) - assert last.footprints[0].equals(box(130_000, 15_000, 230_000, 25_000)) - assert sum(move.cost for move in path) == pytest.approx(0.4004) - - directed = replace(transition, traversals=(("a", "b"),)) - forward_only = MoveEvaluator(evaluator.grid, replace(catalog, variants={**catalog.variants, "displaced": directed})) - with pytest.raises(ValueError, match="Undeclared traversal"): - forward_only.evaluate(moves[-1], straight.end) - - -def test_off_origin_reflected_cell_preserves_ports_and_footprint() -> None: - orientation = Orientation(90, True) - bend = FixedVariant( - "quarter", {"in": Pose(2, 3, 0, "ridge"), "out": Pose(14, 11, 270, "ridge")}, - (box(2, 3, 14, 11),), (("in", "out"),), (orientation,), 2, - ) - evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog("fixture", {"ridge": Profile("ridge", 4)}, {"quarter": bend})) - result = evaluator.evaluate(Move("quarter", traversal=("in", "out"), orientation=orientation), Pose(43, 52, 90, "ridge")) - assert result is not None - assert result.end == Pose(51, 64, 0, "ridge") - assert result.placement == Placement(orientation, 40, 50) - assert result.footprints[0].equals(box(43, 52, 51, 64)) - - -def test_diagonal_straight_cost_and_taper_stretch() -> None: - evaluator = MoveEvaluator( - Grid((0, 0), 100, 1e-9), - Catalog("fixture", {"thin": Profile("ridge", 4000), "wide": Profile("ridge", 5000)}, { - "straight": StraightVariant("thin", 1), - "long": TaperVariant("thin", "wide", 10_000, 0.01), - "short": TaperVariant("thin", "wide", 2000, 0.01), - "characterized": TaperVariant("thin", "wide", 2000, 0.01, max_stretch=0.07), - }), - ) - start = Pose(0, 0, 45, "thin") - straight = evaluator.evaluate(Move("straight", steps=10_000), start) - assert straight is not None - assert straight.cost == pytest.approx(0.1 * sqrt(2)) - long_taper = evaluator.evaluate(Move("long"), straight.end) - assert long_taper is not None - assert long_taper.end == Pose(1_007_100, 1_007_100, 45, "wide") - assert evaluator.evaluate(Move("short"), start) is None - shorter = evaluator.evaluate(Move("characterized"), start) - assert shorter is not None - assert shorter.length == pytest.approx(1500 * sqrt(2)) - assert shorter.start.profile == "thin" - assert shorter.end.profile == "wide" - timing = DelayModel(1.55e-6, variant_delays={"characterized": 7000}) - delay = evaluate_delay(evaluator, (shorter,), timing, net_id="taper") - assert delay is not None - assert delay.optical_length == 7000 - assert verify_path(evaluator, (shorter,), start, shorter.end, board=box(-10_000, -10_000, 2e6, 2e6)) is None - assert verify_path(evaluator, (straight, long_taper), start, long_taper.end, board=box(-10_000, -10_000, 2e6, 2e6)) is None - - -def test_replay_checks_poses_and_reserves_the_finite_seam() -> None: - input_port = Pose(-2, 0, 0, "guide") - joint = Pose(0, 0, 0, "guide") - target = Pose(2, 0, 0, "guide") - evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog("fixture", {"guide": Profile("guide", 2)}, {})) - board = box(-3, -3, 3, 3) - first = Evaluation(Move("in"), input_port, joint, (box(-2, -1, -0.001, 1),), 2, 1) - second = Evaluation(Move("out"), joint, target, (box(0.001, -1, 2, 1),), 2, 1) - path = (first, second) - assert verify_path(evaluator, path, input_port, target, board=board, face_tolerance=0.002) is None - strip = box(-0.00025, -2, 0.00025, 2) - assert verify_path(evaluator, path, input_port, target, board=board, occupied=(strip,), face_tolerance=0.002) == "occupied_seam" - gap = (replace(first, footprints=(box(-2, -1, -0.004, 1),)), replace(second, footprints=(box(0.004, -1, 2, 1),))) - assert verify_path(evaluator, gap, input_port, target, board=board, face_tolerance=0.002) == "port_face" - assert not compatible_join(first, replace(second, start=joint.shifted(1, 0)), 2, 0.002) - - -@pytest.fixture -def asymmetric_fixture(): - grid = Grid((0, 0), 100, 1e-9) - transition = FixedVariant( - "transition", {"wide": Pose(0, 0, 0, "5"), "thin": Pose(10_000, 0, 180, "4")}, - (Polygon(((0, -2500), (10_000, -2000), (10_000, 2000), (0, 2500))),), - (("wide", "thin"), ("thin", "wide")), (Orientation(), Orientation(270)), 0.01, 10_000, - ) - thin_arc = Bend90.generate(Port(4000, 0, 0), 8000, 4000, "CCW", sagitta=2) - bend = FixedVariant( - "asymmetric", {"a": Pose(0, 0, 0, "4"), "b": Pose(12_000, 8000, 270, "4")}, - (box(0, -2000, 4000, 2000), *thin_arc.physical_geometry), - (("a", "b"),), (Orientation(),), 0.01, 4000 + 4000 * pi, - ) - evaluator = MoveEvaluator(grid, Catalog("fixture", {"4": Profile("4 µm", 4000), "5": Profile("5 µm", 5000)}, { - "4-straight": StraightVariant("4", 1), - "5-straight": StraightVariant("5", 0.5), - "bend": bend, - "transition": transition, - })) - start = Pose(20_000, 30_000, 0, "5") - target = Pose(70_000, 75_000, 90, "5") - kwargs = { - "board": box(0, 0, 100_000, 100_000), - "keepouts": (box(57_000, 37_000, 59_000, 39_000),), - "clearance": 1000, - "face_tolerance": 2, - } - return evaluator, start, target, kwargs - - -def test_search_proposes_a_straight_to_an_unequal_setback_bend(asymmetric_fixture) -> None: - evaluator, start, target, kwargs = asymmetric_fixture - known = replay_moves(evaluator, start, ( - Move("5-straight", steps=280), - Move("transition", traversal=("wide", "thin")), - Move("bend", traversal=("a", "b")), - Move("transition", traversal=("thin", "wide"), orientation=Orientation(270)), - Move("5-straight", steps=270), - )) - assert known is not None - assert verify_path(evaluator, known, start, target, **kwargs) is None - result = search_path(evaluator, start, target, **kwargs) - assert result.path is not None, result - [corner] = [part for part in result.path if part.move.variant == "bend"] - assert corner.start == Pose(58_000, 30_000, 0, "4") - assert corner.end == Pose(70_000, 38_000, 90, "4") - assert [part.move.traversal for part in result.path if part.move.variant == "transition"] == [("wide", "thin"), ("thin", "wide")] - assert verify_path(evaluator, result.path, start, target, **kwargs) is None - assert replay_moves(evaluator, start, tuple(part.move for part in result.path)) == result.path - - -def test_search_finds_only_legal_interior_launch_for_displaced_transition() -> None: - a = Pose(2, 4, 0, "a") - b = Pose(28, 8, 0, "b") - transition = FixedVariant( - "displaced", {"in": Pose(0, 0, 0, "a"), "out": Pose(8, 4, 180, "b")}, - (Polygon(((0, -1), (8, 3), (8, 5), (0, 1))),), - (("in", "out"),), (Orientation(),), 0.2, - ) - evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog( - "launch", {"a": Profile("ridge", 2), "b": Profile("ridge", 2)}, { - "a-straight": StraightVariant("a", 1), "b-straight": StraightVariant("b", 1), "transition": transition, - }, - )) - result = search_path( - evaluator, a, b, board=box(0, 0, 30, 12), keepouts=(box(0, 5, 10, 12), box(18, 0, 30, 7)), - node_limit=50, - ) - assert result.outcome == "verified" - assert result.path is not None - [change] = [part for part in result.path if part.move.variant == "transition"] - assert change.start == Pose(10, 4, 0, "a") - assert change.end == Pose(18, 8, 0, "b") - - -@pytest.mark.parametrize(("distance", "transition_cost", "reversible", "count", "cost"), [ - (370, 0.010, True, 0, 0.037), - (380, 0.010, True, None, 0.038), - (390, 0.010, True, 2, 0.0385), - (390, 0.012, True, 0, 0.039), - (390, 0.010, False, 0, 0.039), -]) -def test_search_uses_catalog_cost_for_profile_tradeoffs(distance, transition_cost, reversible, count, cost) -> None: - directions = (("in", "out"), ("out", "in")) if reversible else (("in", "out"),) - transition = FixedVariant( - "centered", {"in": Pose(0, 0, 0, "4"), "out": Pose(10_000, 0, 180, "5")}, - (Polygon(((0, -2000), (10_000, -2500), (10_000, 2500), (0, 2000))),), - directions, (Orientation(), Orientation(180)), transition_cost, 10_000, - ) - evaluator = MoveEvaluator(Grid((0, 0), 100, 1e-9), Catalog( - "cost", {"4": Profile("4 µm", 4000), "5": Profile("5 µm", 5000)}, { - "4-straight": StraightVariant("4", 1), "5-straight": StraightVariant("5", 0.5), "transition": transition, - }, - )) - start = Pose(10_000, 10_000, 0, "4") - end = Pose(start.x + distance * 1000, start.y, 0, "4") - result = search_path(evaluator, start, end, board=box(0, 0, 500_000, 20_000), node_limit=1000) - assert result.outcome == "verified" - assert result.path is not None - if count is not None: - assert sum(part.move.variant == "transition" for part in result.path) == count - assert sum(part.cost for part in result.path) == pytest.approx(cost) - - -def test_constructive_profile_selection_respects_clearance() -> None: - transition = FixedVariant( - "centered", {"in": Pose(0, 0, 0, "4"), "out": Pose(10_000, 0, 180, "5")}, - (Polygon(((0, -2000), (10_000, -2500), (10_000, 2500), (0, 2000))),), - (("in", "out"), ("out", "in")), (Orientation(), Orientation(180)), 0.01, 10_000, - ) - evaluator = MoveEvaluator(Grid((0, 0), 100, 1e-9), Catalog( - "constructive", {"4": Profile("ridge", 4000), "5": Profile("ridge", 5000)}, - {"4-straight": StraightVariant("4", 1), "5-straight": StraightVariant("5", 0.5), "transition": transition}, - )) - nets = { - name: CatalogNet(Pose(10_000, y, 0, "4"), Pose(610_000, y, 0, "4")) - for name, y in (("open", 10_000), ("constrained", 30_000)) - } - settings = LayoutSettings( - box(0, 0, 620_000, 50_000), (box(100_000, 33_100, 400_000, 40_000),), - clearance=1000, node_limit=8, refinement=False, constructive=True, - ) - result = route_layout(evaluator, nets, settings) - assert result.completed == ("open", "constrained") - assert result.routes["open"].cost == pytest.approx(0.049) - assert result.routes["constrained"].cost == pytest.approx(0.06) - assert all(route.length == pytest.approx(600_000) and route.expanded == 0 for route in result.routes.values()) - - -@pytest.fixture -def masque_4a3(): - masque = pytest.importorskip("masque") - if masque.__version__ != "4.0a3": - pytest.skip("The Masque integration fixture uses 4.0a3") - return masque - - -def test_masque_route_places_verified_references_and_consumes_terminal_names(masque_4a3, asymmetric_fixture) -> None: - evaluator, start, target, kwargs = asymmetric_fixture - masque = masque_4a3 - layer = 7 - cells = {} - for variant in evaluator.catalog.variants.values(): - if isinstance(variant, FixedVariant): - pattern = masque.Pattern(ports={ - name: masque.Port((port.x, port.y), rotation=radians(port.heading)) - for name, port in variant.ports.items() - }) - for shape in variant.footprints: - pattern.polygon(layer, vertices=shape.exterior.coords[:-1]) - cells[variant.cell] = pattern - source = masque.Port((start.x, start.y), rotation=pi) - destination = masque.Port((target.x, target.y), rotation=pi / 2) - layout = masque.Pattern(ports={"source": source, "destination": destination, "other": source.copy()}) - request = (Connection("typed", Endpoint("source", "5"), Endpoint("destination", "5")),) - result = route_and_place(layout, cells, request, catalog=evaluator.catalog, grid=evaluator.grid, layer=layer, **kwargs) - assert result.placed == ("typed",) - assert tuple(layout.ports) == ("other",) - [bend] = layout.refs["asymmetric"] - assert tuple(bend.offset) == (58_000, 30_000) - assert bend.rotation == 0 - assert not bend.mirrored - assert len(layout.refs["transition"]) == 2 - assert result.routes["typed"].path is not None - generated = [part.footprints[0] for part in result.routes["typed"].path if part.placement is None] - assert len(layout.shapes[layer]) == len(generated) - for placed, expected in zip(layout.shapes[layer], generated, strict=True): - assert Polygon(placed.vertices + placed.offset).equals(expected) - - - blocked = masque.Pattern(ports={"source": source.copy(), "destination": destination.copy()}) - blocking_geometry = (*kwargs["keepouts"], box(62_000, 29_500, 62_500, 30_500)) - blocked_result = route_and_place( - blocked, cells, request, catalog=evaluator.catalog, grid=evaluator.grid, layer=layer, - **{**kwargs, "keepouts": blocking_geometry}, - ) - assert blocked_result.placed == () - assert tuple(blocked.ports) == ("source", "destination") - assert not blocked.shapes - assert not blocked.refs - - restricted = masque.Pattern(ports={"source": source.copy(), "destination": destination.copy()}) - variants = dict(evaluator.catalog.variants) - variants["transition"] = replace(variants["transition"], traversals=(("thin", "wide"),)) - restricted_result = route_and_place( - restricted, cells, request, catalog=replace(evaluator.catalog, variants=variants), grid=evaluator.grid, layer=layer, **kwargs, - ) - assert restricted_result.routes["typed"].path is None - assert restricted_result.outcome == "partial" - assert tuple(restricted.ports) == ("source", "destination") - - -@pytest.mark.parametrize("require_complete", [False, True]) -def test_masque_partial_placement_leaves_unrouted_port_names(masque_4a3, require_complete) -> None: - masque = masque_4a3 - layout = masque.Pattern(ports={ - "a": masque.Port((2, 4), rotation=pi), - "b": masque.Port((18, 4), rotation=0), - "c": masque.Port((2, 8), rotation=pi), - "d": masque.Port((18, 8), rotation=0), - }) - catalog = Catalog("placement", {"w": Profile("ridge", 2)}, {"straight": StraightVariant("w", 1)}) - routes = ( - Connection("clear", Endpoint("a", "w"), Endpoint("b", "w")), - Connection("blocked", Endpoint("c", "w"), Endpoint("d", "w")), - ) - result = route_and_place( - layout, {}, routes, catalog=catalog, grid=Grid((0, 0), 1, 1e-6), board=box(0, 0, 20, 12), - layer=1, keepouts=(box(9, 6, 11, 10),), require_complete=require_complete, - ) - assert result.routes["clear"].outcome == "verified" - assert result.routes["blocked"].outcome == "exhausted" - if require_complete: - assert tuple(layout.ports) == ("a", "b", "c", "d") - assert result.placed == () - assert not layout.shapes - else: - assert tuple(layout.ports) == ("c", "d") - assert result.placed == ("clear",) - assert len(layout.shapes[1]) == 1 - - -def test_fixed_attachment_accepts_split_approach_checks_clearance_and_rejects_shelf() -> None: - evaluator = MoveEvaluator(Grid((0, 0), 100, 1e-9), Catalog( - "attachment", {"4": Profile("ridge", 4000)}, {"s": StraightVariant("4", 1)}, - )) - start, target = Pose(0, 0, 0, "4"), Pose(10_000, 0, 0, "4") - bounds = box(-11_000, -10_000, 11_000, 10_000) - fixed = box(-10_000, -2000, 0, 2000) - region = box(-2000, -3000, 2000, 3000) - attachment = Attachment(fixed, region) - common = {"board": bounds, "clearance": 1000, "keepouts": (fixed,)} - full = replay_moves(evaluator, start, (Move("s", steps=100),)) - split = replay_moves(evaluator, start, tuple(Move("s", steps=n) for n in (5, 25, 70))) - assert full is not None - assert split is not None - assert verify_path(evaluator, full, start, target, **common) == "keepout" - assert search_path(evaluator, start, target, **common).outcome == "exhausted" - assert search_path(evaluator, start, target, source_attachment=attachment, **common).outcome == "verified" - assert verify_path(evaluator, full, start, target, source_attachment=attachment, **common) is None - assert verify_path(evaluator, split, start, target, source_attachment=attachment, self_clearance=3000, **common) is None - short = replace(attachment, region=box(-2000, -3000, 500, 3000)) - assert verify_path(evaluator, split, start, target, source_attachment=short, **common) == "fixed_attachment" - - shelving = MultiPolygon((fixed, box(300, 1500, 700, 2000))) - assert verify_path( - evaluator, full, start, target, board=bounds, clearance=1000, keepouts=(shelving,), - source_attachment=Attachment(shelving, region), - ) == "fixed_attachment" - reverse = search_path(evaluator, target.reversed(), start.reversed(), destination_attachment=attachment, **common) - assert reverse.outcome == "verified" - - -def test_delay_reporting_respects_actual_travel_direction_and_wavelength() -> None: - evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog( - "timing", {"guide": Profile("ridge", 4)}, {"s": StraightVariant("guide", 1)}, - )) - east = replay_moves(evaluator, Pose(0, 0, 0, "guide"), (Move("s", steps=20),)) - west = replay_moves(evaluator, Pose(20, 0, 180, "guide"), (Move("s", steps=20),)) - assert east is not None - assert west is not None - - def modal_index(wavelength, angle): - return (3 if wavelength == 1.55e-6 else 4) + 0.5 * cos(angle) - - model = DelayModel(1.55e-6, group_indices={"guide": modal_index}) - east_delay = evaluate_delay(evaluator, east, model, net_id="east") - west_delay = evaluate_delay(evaluator, west, model, net_id="west") - assert east_delay is not None - assert west_delay is not None - assert east_delay.optical_length == 70 - assert east_delay.seconds == pytest.approx(70e-6 / 299_792_458) - assert west_delay.optical_length == 50 - different_wavelength = evaluate_delay(evaluator, east, replace(model, wavelength=1.5e-6), net_id="east") - assert different_wavelength is not None - assert different_wavelength.optical_length == 90 - diagonal_process = DelayModel(1.55e-6, process_angle=pi / 4, group_indices={"guide": UniaxialGroupIndex(4, 2)}) - for path in (east, west): - delay = evaluate_delay(evaluator, path, diagonal_process, net_id="route") - assert delay is not None - assert delay.optical_length == pytest.approx(60) - - -@pytest.mark.parametrize(("cap", "available"), [(110.0, True), (100.0, False)]) -def test_generated_45_degree_bend_uses_tangent_leads(cap, available) -> None: - grid = Grid((0, 0), 100, 1e-9) - bend = BendVariant("guide", 45, 10_000, 0.01, max_lead=cap, lead_cost_per_cm=1, sagitta=2) - evaluator = MoveEvaluator(grid, Catalog("circular", {"guide": Profile("ridge", 4000)}, {"bend": bend})) - start = Pose(0, 0, 0, "guide") - target = Pose(7200, 3000, 45, "guide") - matching = [move for move in evaluator.bend_moves("bend", 0, bend) if move.displacement == (7200, 3000)] - assert bool(matching) == available - if available: - [move] = matching - assert move.leads == pytest.approx((57.864376, 100.505063)) - result = search_path(evaluator, start, target, board=box(-4000, -4000, 20_000, 20_000), face_tolerance=0.002) - assert result.path is not None - [evaluated] = result.path - assert evaluated.length == pytest.approx(2500 * pi + sum(move.leads)) - assert evaluated.cost == pytest.approx(0.01 + sum(move.leads) / 1e7) - assert evaluated.end == target - - -@pytest.mark.parametrize(("floor", "expected"), [(5000, 1.0), (8000, "partial"), (10_000, 0.0), (11_000, None)]) -def test_euler_fraction_satisfies_minimum_radius_and_preserves_ports(floor, expected) -> None: - bend = BendVariant("guide", 90, 10_000, 0.01, minimum_radius=floor, euler_fraction=None, sagitta=2) - evaluator = MoveEvaluator( - Grid((0, 0), 100, 1e-9), Catalog("euler", {"guide": Profile("ridge", 4000)}, {"bend": bend}), - ) - start = Pose(0, 0, 0, "guide") - moves = evaluator.bend_moves("bend", 0, bend) - if expected is None: - assert moves == () - return - [move] = moves - result = evaluator.evaluate(move, start) - assert result is not None - assert result.end == Pose(10_000, 10_000, 90, "guide") - assert result.minimum_radius is not None - assert result.minimum_radius == pytest.approx(1 / max( - max(abs(section.entry_curvature), abs(section.exit_curvature)) for section in result.curve_sections - )) - assert result.minimum_radius >= floor - 1e-8 - if expected == "partial": - assert result.euler_fraction is not None - assert 0 < result.euler_fraction < 1 - assert result.minimum_radius == pytest.approx(floor) - else: - assert result.euler_fraction == expected - - -def test_generated_uturn_preserves_distinct_leads_at_same_ports(monkeypatch) -> None: - bend = BendVariant("guide", 180, 10_000, 0.01, max_lead=2000, sagitta=2) - evaluator = MoveEvaluator( - Grid((0, 0), 100, 1e-9), Catalog("turnaround", {"guide": Profile("ridge", 400)}, { - "bend": bend, "quarter": BendVariant("guide", 90, 10_000, 0.001, sagitta=2), - }), - ) - assert evaluator.bend_moves("bend", 45, bend) == () - no_leads = replace(bend, max_lead=0) - assert evaluator.bend_moves("no-leads", 45, no_leads) == () - start = Pose(0, 0, 0, "guide") - target = Pose(0, 20_000, 180, "guide") - choices = [move for move in evaluator.bend_moves("bend", 0, bend) if move.displacement == (0, 20_000)] - assert [move.leads for move in choices] == [(0.0, 0.0), (2000.0, 2000.0)] - replay_only = Move("bend", displacement=(0, 20_000), leads=(1000, 1000)) - assert replay_only not in choices - evaluated = evaluator.evaluate(replay_only, start) - assert evaluated is not None - assert evaluated.length == pytest.approx(10_000 * pi + 2000) - assert evaluator.evaluate(replace(replay_only, leads=(1000, 900)), start) is None - result = search_path( - evaluator, start, target, board=box(-1000, -1000, 15_000, 21_000), - keepouts=(box(9900, 9900, 10_100, 10_100),), clearance=250, - ) - assert result.path is not None - assert result.path[0].move == choices[1] - two_turns = replay_moves(evaluator, start, ( - Move("quarter", displacement=(10_000, 10_000)), Move("quarter", displacement=(-10_000, 10_000)), - )) - assert two_turns is not None - check = {"board": box(-1000, -1000, 15_000, 21_000), "clearance": 250} - assert verify_path(evaluator, two_turns, start, target, **check) is None - assert verify_path(evaluator, two_turns, start, target, keepouts=(box(9900, 9900, 10_100, 10_100),), **check) == "keepout" - - reverse_evaluator = MoveEvaluator(evaluator.grid, evaluator.catalog) - natural_order = reverse_evaluator.bend_moves - monkeypatch.setattr(reverse_evaluator, "bend_moves", lambda *args: tuple(reversed(natural_order(*args)))) - reversed_result = search_path( - reverse_evaluator, start, target, board=box(-1000, -1000, 15_000, 21_000), - keepouts=(box(9900, 9900, 10_100, 10_100),), clearance=250, - ) - assert reversed_result.path == result.path - - -@pytest.mark.parametrize("sign", [1, -1]) -def test_rotated_process_delay_integrates_the_curved_tangent(sign) -> None: - bend = BendVariant("guide", sign * 90, 10, 0.01) - evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog( - "curve-timing", {"guide": Profile("ridge", 4)}, {"bend": bend}, - )) - path = replay_moves(evaluator, Pose(0, 0, 0, "guide"), evaluator.bend_moves("bend", 0, bend)) - assert path is not None - model = DelayModel(1.55e-6, process_angle=pi / 4, group_indices={"guide": UniaxialGroupIndex(4, 2)}) - delay = evaluate_delay(evaluator, path, model, net_id="curve") - assert delay is not None - assert delay.optical_length == pytest.approx(15 * pi + sign * 10) - - -def test_match_tolerance_accepts_a_cheaper_nonzero_skew() -> None: - pose = Pose(0, 0, 0, "guide") - - def choice(optical_length, cost): - path = (Evaluation(Move("s"), pose, pose, (), 1, cost),) - return DelayChoice(path, Delay(optical_length, optical_length * 1e-6 / 299_792_458)) - - group = MatchGroup("tolerance", {"ref": 0, "tuned": 0}, 1.55e-6, 0.05) - reference = choice(400, 0) - alternatives = [choice(400, 3), choice(400.05, 2), choice(400.06, 1)] - for order in (alternatives, alternatives[::-1]): - choices = {"ref": (reference,), "tuned": order} - selected, skew, matched = choose_match(group, choices) - assert matched - assert skew == pytest.approx(0.05) - assert selected["tuned"] == alternatives[1] - stricter, skew, matched = choose_match(replace(group, tolerance=0.04), choices) - assert matched - assert skew == 0 - assert stricter["tuned"] == alternatives[0] - - -@pytest.mark.parametrize(("window_height", "expected", "case"), [ - (155_000, "matched", "nominal"), - (123_000, "unmatched", "nominal"), - (None, "unmatched", "nominal"), - (155_000, "unmatched", "between-settings"), - (152_000, "unmatched", "lower-delay"), -]) -def test_match_uses_only_supplied_tuning_space(window_height, expected, case) -> None: - evaluator = MoveEvaluator(Grid((0, 0), 100, 1e-9), Catalog( - "detour", {"guide": Profile("ridge", 4000)}, { - "s": StraightVariant("guide", 1), - "left": BendVariant("guide", 90, 10_000, 0.01, sagitta=2), - "right": BendVariant("guide", -90, 10_000, 0.01, sagitta=2), - }, - )) - fixed = box(15_000, 118_000, 20_000, 122_000) - access = Attachment(fixed, box(18_000, 117_000, 22_000, 123_000)) - nets = { - name: CatalogNet( - Pose(20_000, y, 0, "guide"), Pose(140_000, y, 0, "guide"), - source_attachment=access if name == "adjust" else None, seed=(Move("s", steps=1200),), - ) - for name, y in (("reference", 40_000), ("adjust", 120_000)) - } - overrides = {"left": 1, "right": 1} if case == "lower-delay" else {} - model = DelayModel(1.55e-6, group_indices={"guide": 4}, fixed_contributions={"adjust": (20_000,)}, bend_group_indices=overrides) - extra = 400 if case == "between-settings" else 0 - group = MatchGroup("delay", {"reference": 0, "adjust": (80 * pi - 60) * 1000 + extra}, 1.55e-6, 50) - settings = LayoutSettings(box(0, 0, 400_000, 300_000), (fixed,), clearance=1000, node_limit=0) - windows = {} if window_height is None else {"adjust": box(40_000, 117_000, 100_000, window_height)} - result = route_layout(evaluator, nets, settings, timing=model, groups=(group,), windows=windows) - match = result.matching["delay"] - assert match.status == expected - assert result.routes["adjust"].path is not None - assert result.routes["reference"].path is not None - if expected == "matched": - assert result.completed == ("reference", "adjust") - assert match.skew == pytest.approx(0, abs=1e-6) - assert sum(part.move.variant in ("left", "right") for part in result.routes["adjust"].path) == 4 - assert match.delays["adjust"].optical_length == pytest.approx((420 + 80 * pi) * 1000) - else: - assert result.completed == () - if case == "between-settings": - assert match.skew == pytest.approx(400) - assert sum(part.move.variant in ("left", "right") for part in result.routes["adjust"].path) == 4 - else: - assert match.skew == pytest.approx((80 * pi - 80) * 1000) - assert len(result.routes["adjust"].path) == 1 - if case == "lower-delay": - assert match.verified_replacements > 0 - - -def test_diagonal_sbend_rejects_wrong_parity_and_uses_lobe_radius_floor() -> None: - bend = SBendVariant("guide", 1000, 1, ((50, 5), (51, 5), (52, 6)), minimum_radius=800, euler_fraction=None, sagitta=2) - evaluator = MoveEvaluator(Grid((0, 0), 100, 1e-9), Catalog( - "shift", {"guide": Profile("ridge", 400)}, {"s": bend}, - )) - candidates = evaluator.local_moves("guide", 45) - [unavailable] = evaluator.unavailable - assert unavailable.reason == "off_grid_projections" - assert unavailable.projections == (50, 5) - assert [end for _, end in candidates] == [Pose(2300, 2800, 45, "guide"), Pose(2300, 2900, 45, "guide")] - target = Pose(2300, 2800, 45, "guide") - result = search_path(evaluator, Pose(0, 0, 45, "guide"), target, board=box(-1000, -1000, 4000, 4000)) - assert result.path is not None - [evaluated] = result.path - assert evaluated.minimum_radius == pytest.approx(800) - assert evaluated.end == target - - -def test_unmatched_group_releases_window_for_independent_net() -> None: - evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog( - "retry", {"guide": Profile("ridge", 2)}, {"s": StraightVariant("guide", 1)}, - )) - nets = { - "mixed-a": CatalogNet(Pose(10, 10, 0, "guide"), Pose(90, 10, 0, "guide")), - "mixed-b": CatalogNet(Pose(10, 30, 0, "guide"), Pose(90, 30, 0, "guide")), - "independent": CatalogNet(Pose(10, 40, 0, "guide"), Pose(90, 40, 0, "guide")), - } - windows = {"mixed-b": box(20, 25, 80, 45)} - model = DelayModel(1.55e-6, group_indices={"guide": 4}) - group = MatchGroup("miss", {"mixed-a": 0, "mixed-b": 1}, 1.55e-6, 0) - settings = LayoutSettings(box(0, 0, 100, 50), refinement=False) - args = {"timing": model, "groups": (group,), "windows": windows} - partial = route_layout(evaluator, nets, settings, **args) - assert partial.completed == ("independent",) - assert partial.routes["mixed-a"].path is not None - assert partial.routes["mixed-b"].path is not None - assert partial.matching["miss"].status == "unmatched" - complete = route_layout(evaluator, nets, settings, require_complete=True, **args) - assert complete.completed == () - assert complete.routes["independent"].path is None - # Reporting alone leaves the overlapping window inactive. - reporting = route_layout(evaluator, nets, settings, timing=model, windows=windows) - baseline = route_layout(evaluator, nets, settings) - assert reporting.routes == baseline.routes - assert reporting.completed == baseline.completed - - -def test_masque_preflights_duplicate_terminal_assignments(masque_4a3) -> None: - masque = masque_4a3 - ports = { - "a": masque.Port((2, 4), rotation=pi), - "b": masque.Port((18, 4), rotation=0), - "c": masque.Port((18, 8), rotation=0), - } - layout = masque.Pattern(ports=ports) - catalog = Catalog("preflight", {"w": Profile("ridge", 2)}, {"s": StraightVariant("w", 1)}) - with pytest.raises(ValueError, match="Duplicate routing terminal 'a'"): - route_and_place( - layout, {}, ( - Connection("first", Endpoint("a", "w"), Endpoint("b", "w")), - Connection("second", Endpoint("a", "w"), Endpoint("c", "w")), - ), catalog=catalog, grid=Grid((0, 0), 1, 1e-6), board=box(0, 0, 20, 12), layer=1, - ) - assert tuple(layout.ports) == ("a", "b", "c") - assert not layout.shapes - assert not layout.refs - - -@pytest.mark.parametrize("require_complete", [False, True]) -def test_masque_propagates_execution_failure_and_stops_placing(masque_4a3, monkeypatch, require_complete) -> None: - masque = masque_4a3 - ports = { - f"{name}{y}": masque.Port((x, y), rotation=angle) - for y in (4, 8, 12) for name, x, angle in (("a", 2, pi), ("b", 18, 0)) - } - layout = masque.Pattern(ports=ports) - catalog = Catalog("fatal", {"w": Profile("ridge", 2)}, {"s": StraightVariant("w", 1)}) - connections = tuple(Connection(str(y), Endpoint(f"a{y}", "w"), Endpoint(f"b{y}", "w")) for y in (4, 8, 12)) - write = masque.Pattern.polygon - calls = 0 - - def fail_on_second(pattern, layer, *args, **kwargs): - nonlocal calls - calls += 1 - if calls == 2: - raise RuntimeError("Injected placement failure") - return write(pattern, layer, *args, **kwargs) - - monkeypatch.setattr(masque.Pattern, "polygon", fail_on_second) - with pytest.raises(RuntimeError, match="Injected placement failure"): - route_and_place( - layout, {}, connections, catalog=catalog, grid=Grid((0, 0), 1, 1e-6), - board=box(0, 0, 20, 16), layer=1, require_complete=require_complete, - ) - assert calls == 2 - assert tuple(layout.ports) == ("a8", "b8", "a12", "b12") - assert len(layout.shapes[1]) == 1 - - -@pytest.fixture -def off_coarse_transition() -> tuple[Catalog, Pose, Pose]: - start = Pose(20_001, 30_001, 0, "4") - target = Pose(170_001, 30_201, 0, "8") - profiles = {"4": Profile("ridge4", 4000), "8": Profile("ridge8", 8000)} - physical = Polygon(((0, -2000), (100_000, -3800), (100_000, 4200), (0, 2000))) - transition = FixedVariant( - "displaced", {"a": Pose(0, 0, 0, "4"), "b": Pose(100_000, 200, 180, "8")}, - (physical,), (("a", "b"),), (Orientation(),), 0.2, 100_010, - ) - return Catalog("coarse", profiles, {"s4": StraightVariant("4", 1), "s8": StraightVariant("8", 0.2), "t": transition}), start, target - - -@pytest.mark.parametrize("pitch", [1000, 10_000]) -def test_coarse_corridor_realizes_a_transition_at_exact_terminal_poses(off_coarse_transition, pitch) -> None: - catalog, start, target = off_coarse_transition - nets = {"off-coarse": CatalogNet(start, target)} - fine = MoveEvaluator(Grid((0, 0), 1, 1e-9), catalog) - coarse = MoveEvaluator(Grid((start.x, start.y), pitch, 1e-9), catalog) - board = box(0, 0, 200_000, 80_000) - assert coarse.grid.lattice_position(target.x, target.y) is None - with pytest.raises(ValueError, match="invalid terminal"): - route_layout(coarse, nets, LayoutSettings(board)) - settings = LayoutSettings(board, node_limit=100, guidance=CoarseGuidance(pitch)) - open_run = route_layout(fine, nets, settings).routes["off-coarse"] - assert open_run.path is not None - assert open_run.used_guidance - assert open_run.path[0].start == start - assert open_run.path[-1].end == target - [transition] = [part for part in open_run.path if part.move.variant == "t"] - assert transition.end.y - transition.start.y == 200 - assert verify_path(fine, open_run.path, start, target, board=board) is None - - # Block the selected transition while leaving generous physical board space. - x = transition.start.x + 50_000 - obstacle = box(x, transition.start.y - 500, x + 1_000, transition.start.y + 500) - assert verify_path(fine, open_run.path, start, target, board=board, keepouts=(obstacle,)) == "keepout" - retry = route_layout(fine, nets, replace(settings, keepouts=(obstacle,))).routes["off-coarse"] - if retry.path is not None: - assert retry.path != open_run.path - assert verify_path(fine, retry.path, start, target, board=board, keepouts=(obstacle,)) is None - else: - assert retry.outcome in ("exhausted", "node_limit") - - -def test_automatic_grid_uses_port_differences_and_authored_displacements(off_coarse_transition) -> None: - catalog, start, target = off_coarse_transition - selected = AutomaticGrid(1000, 1e-9).select((start, target), catalog) - assert selected == Grid((20_001, 30_001), 200, 1e-9) - assert AutomaticGrid(1000, 1e-9).select((start, replace(target, x=target.x + 1)), catalog).pitch == 1 - assert AutomaticGrid(1000, 1e-9).select((start,), catalog).pitch == 200 - - -def test_coarse_corridor_uses_sparse_search_around_an_obstacle() -> None: - board = box(0, 0, 80, 80) - obstacle = box(33, 25, 47, 55) - a, b = Pose(10, 40, 0, "wide"), Pose(70, 40, 0, "wide") - guide, expanded = find_corridor(a, b, CoarseGuidance(5), board=board, obstacles=(obstacle,), margin=2) - assert guide is not None - assert expanded > 0 - assert len(guide.points) > 2 - assert guide.points[0] == (10, 40) - assert guide.points[-1] == (70, 40) - no_guide, limited = find_corridor(a, b, CoarseGuidance(5, node_limit=1), board=board, obstacles=(obstacle,), margin=2) - assert no_guide is None - assert limited == 1 - - -@pytest.mark.parametrize("condition", ["enabled", "disabled", "keepout", "matching", "budget"]) -def test_catalog_refinement_keeps_the_incumbent_until_a_cheaper_layout_verifies(condition) -> None: - transition = FixedVariant( - "centered", {"a": Pose(0, 0, 0, "4"), "b": Pose(10_000, 0, 180, "5")}, - (Polygon(((0, -2000), (10_000, -2500), (10_000, 2500), (0, 2000))),), - (("a", "b"), ("b", "a")), (Orientation(), Orientation(180)), 0.01, 10_000, - ) - evaluator = MoveEvaluator(Grid((0, 0), 100, 1e-9), Catalog( - "refine", {"4": Profile("thin", 4000), "5": Profile("wide", 5000)}, - {"4": StraightVariant("4", 1), "5": StraightVariant("5", 0.5), "change": transition}, - )) - seed = (Move("4", steps=3900),) - nets = { - name: CatalogNet(Pose(10_000, y, 0, "4"), Pose(400_000, y, 0, "4"), seed=seed) - for name, y in (("lane", 10_000), ("peer", 25_000)) - } - keepouts = (box(0, 12_250, 420_000, 12_800),) if condition == "keepout" else () - settings = LayoutSettings( - box(0, 0, 420_000, 35_000), keepouts, node_limit=100, refinement=condition != "disabled", - refinement_node_limit=1 if condition == "budget" else 64, - ) - if condition == "matching": - timing = DelayModel(1.55e-6, group_indices={"4": 4, "5": 2}, variant_delays={"change": 40_000}) - result = route_layout(evaluator, nets, settings, timing=timing, groups=(MatchGroup("delay", {"lane": 0, "peer": 0}, 1.55e-6, 50),)) - assert result.matching["delay"].complete - else: - result = route_layout(evaluator, nets, settings) - assert result.completed == ("lane", "peer") - lane = result.routes["lane"].path - assert lane is not None - if condition == "enabled": - assert sum(part.cost for part in lane) == pytest.approx(0.0385) - assert sum(part.move.variant == "change" for part in lane) == 2 - else: - assert tuple(part.move for part in lane) == seed - assert verify_path(evaluator, lane, nets["lane"].start, nets["lane"].target, board=settings.board, keepouts=keepouts) is None - if condition == "keepout": - assert result.routes["peer"].cost == pytest.approx(0.0385) - assert result.routes["lane"].cost == pytest.approx(0.039) - - -def test_diagonal_join_limits_numerical_overlap_to_the_finite_face() -> None: - seam = Pose(0, 0, 45, "g") - a, b = Pose(-4, -4, 45, "g"), Pose(4, 4, 45, "g") - aligned = rotate(box(-4, -1, 0.001, 1), 45, origin=(0, 0)) - onward = rotate(box(0, -1, 4, 1), 45, origin=(0, 0)) - left = Evaluation(Move("from"), a, seam, (aligned,), 4, 1) - right = Evaluation(Move("to"), seam, b, (onward,), 4, 1) - assert compatible_join(left, right, 2, 0.002) - assert not compatible_join(left, right, 2, 0.0001) - - bulge_left = rotate(box(-4, 1.1, 0.001, 1.2), 45, origin=(0, 0)) - bulge_right = rotate(box(0, 1.1, 4, 1.2), 45, origin=(0, 0)) - assert not compatible_join( - replace(left, footprints=(aligned, bulge_left)), replace(right, footprints=(onward, bulge_right)), 2, 0.002, - ) - assert not compatible_join(left, replace(right, start=replace(seam, profile="other-mode")), 2, 0.002) - - -def test_self_clearance_rejects_long_parallel_legs_around_a_half_turn() -> None: - evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog("self-clearance", {"g": Profile("waveguide", 4)}, { - "straight": StraightVariant("g", 1), "turn": BendVariant("g", 180, 3, 0.02), - })) - start = Pose(0, 0, 0, "g") - target = Pose(0, 6, 180, "g") - path = replay_moves(evaluator, start, (Move("straight", steps=20), Move("turn", displacement=(0, 6)), Move("straight", steps=20))) - assert path is not None - board = box(-4, -4, 30, 12) - assert verify_path(evaluator, path, start, target, board=board, self_clearance=2) is None - assert verify_path(evaluator, path, start, target, board=board, self_clearance=3) == "self_clearance" - uncharacterized = (path[0], replace(path[1], length=None), path[2]) - assert verify_path(evaluator, uncharacterized, start, target, board=board, self_clearance=7) == "self_clearance" - - -@pytest.mark.parametrize("sign", [1, -1]) -def test_masque_places_a_fixed_cell_with_a_native_diagonal_port(masque_4a3, sign) -> None: - masque = masque_4a3 - grid = Grid((0, 0), 100, 1e-9) - profile = {"g": Profile("ridge", 4000)} - generated = BendVariant("g", 45 * sign, 10_000, 0.01, max_lead=110, sagitta=2) - evaluator = MoveEvaluator(grid, Catalog("authoring", profile, {"curve": generated})) - [move] = [choice for choice in evaluator.bend_moves("curve", 0, generated) if choice.displacement == (7200, 3000 * sign)] - authored = evaluator.evaluate(move, Pose(0, 0, 0, "g")) - assert authored is not None - origin = (2000, 3000) - entry = Pose(*origin, 0, "g") - exit = authored.end.shifted(*origin) - inward_exit = exit.reversed() - polygon = translate(authored.footprints[0], *origin) - cell = masque.Pattern(ports={ - "in": masque.Port(origin, rotation=0), - "out": masque.Port((exit.x, exit.y), rotation=radians(inward_exit.heading)), - }) - cell.polygon(5, vertices=polygon.exterior.coords[:-1]) - orientation = Orientation(90, True) - fixed = FixedVariant( - "authored", {"in": entry, "out": inward_exit}, (box(*polygon.bounds),), - (("in", "out"),), (orientation,), 0.01, authored.length, - ) - catalog = Catalog("diagonal-device", profile, {"authored": fixed, "straight": StraightVariant("g", 1)}) - with pytest.raises(ValueError, match="quarter turns"): - Orientation(45) - - start = orientation.port(entry).shifted(40_000, 50_000) - output = orientation.port(exit).shifted(40_000, 50_000) - target = output.shifted(10_000 * sign, 10_000) - layout = masque.Pattern(ports={ - "source": masque.Port((start.x, start.y), rotation=radians(start.reversed().heading)), - "destination": masque.Port((target.x, target.y), rotation=radians(target.heading)), - }) - result = route_and_place( - layout, {"authored": cell}, (Connection("native", Endpoint("source", "g"), Endpoint("destination", "g")),), - catalog=catalog, grid=grid, board=box(0, 0, 100_000, 100_000), layer=5, face_tolerance=0.002, - ) - assert result.placed == ("native",) - assert not layout.ports - recorded = result.routes["native"].path - assert recorded is not None - assert recorded[0].end == output - assert recorded[0].move.traversal == ("in", "out") - [reference] = layout.refs["authored"] - assert tuple(reference.offset) == (40_000, 50_000) - assert reference.rotation == pi / 2 - assert reference.mirrored - emitted = tuple(Polygon(shape.vertices + shape.offset) for shape in layout.layer_as_polygons(5, library={"authored": cell})) - assert any(shape.symmetric_difference(recorded[0].port_shapes[0]).area < 1e-6 for shape in emitted) - - -def test_masque_places_and_replays_an_authored_sbend_span(masque_4a3) -> None: - masque = masque_4a3 - left, right = [], [] - for i in range(101): - t = i / 100 - x, y = 26_000 * t, 6000 * (3 * t * t - 2 * t * t * t) - dx, dy = 26_000, 36_000 * t * (1 - t) - factor = 2000 / hypot(dx, dy) - left.append((x - dy * factor, y + dx * factor)) - right.append((x + dy * factor, y - dx * factor)) - polygon = Polygon((*left, *reversed(right))) - length = quad(lambda t: hypot(26_000, 36_000 * t * (1 - t)), 0, 1)[0] - cell = masque.Pattern(ports={"a": masque.Port((0, 0), rotation=0), "b": masque.Port((26_000, 6000), rotation=pi)}) - cell.polygon(7, vertices=polygon.exterior.coords[:-1]) - source = Pose(20_000, 20_000, 0, "g") - target = Pose(70_000, 26_000, 0, "g") - grid = Grid((0, 0), 100, 1e-9) - fixed = FixedVariant( - "sbend", {"a": Pose(0, 0, 0, "g"), "b": Pose(26_000, 6000, 180, "g")}, (polygon,), - (("a", "b"),), (Orientation(),), 0.02, length, - ) - catalog = Catalog("authored-span", {"g": Profile("ridge", 4000)}, {"sbend": fixed, "straight": StraightVariant("g", 1)}) - seed = (Move("sbend", traversal=("a", "b")), Move("straight", steps=240)) - layout = masque.Pattern(ports={ - "start": masque.Port((source.x, source.y), rotation=pi), - "finish": masque.Port((target.x, target.y), rotation=0), - }) - request = Connection("offset", Endpoint("start", "g"), Endpoint("finish", "g"), seed=seed) - result = route_and_place( - layout, {"sbend": cell}, (request,), catalog=catalog, grid=grid, board=box(0, 0, 100_000, 60_000), layer=7, node_limit=0, - ) - assert result.placed == ("offset",) - assert result.routes["offset"].length == pytest.approx(length + 24_000) - path = result.routes["offset"].path - assert path is not None - assert path[0].end == Pose(46_000, 26_000, 0, "g") - assert path[0].footprints[0].equals(translate(polygon, 20_000, 20_000)) - assert path[-1].end == target - - -def test_catalog_pair_repair_can_release_one_independent_peer() -> None: - evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog( - "contention", {"g": Profile("guide", 2), "h": Profile("straight-only", 2)}, { - "straight": StraightVariant("g", 1), "vertical-straight": StraightVariant("h", 1), - "left": BendVariant("g", 90, 5, 0.01), - "right": BendVariant("g", -90, 5, 0.01), - }, - )) - nets = { - "horizontal": CatalogNet(Pose(10, 50, 0, "g"), Pose(90, 50, 0, "g")), - "vertical": CatalogNet(Pose(50, 10, 90, "h"), Pose(50, 70, 90, "h")), - } - baseline = LayoutSettings(box(0, 0, 100, 100), clearance=1, node_limit=800, refinement=False) - raw = route_layout(evaluator, nets, baseline) - assert raw.completed == ("horizontal",) - refined = route_layout(evaluator, nets, replace(baseline, refinement=True, refinement_node_limit=400)) - assert refined.completed == tuple(nets) - assert refined.attempts[0].pair_repairs == 1 - assert refined.routes["vertical"].cost == pytest.approx(0.006) - detour = refined.routes["horizontal"].path - assert detour is not None - assert any(part.move.variant in ("left", "right") for part in detour) - - -def test_flat_diagonal_launch_and_arrival_use_exact_clearance() -> None: - evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog( - "diagonal-access", {"g": Profile("ridge", 2)}, {"s": StraightVariant("g", 1)}, - )) - start = Pose(0, 0, 45, "g") - target = Pose(10, 10, 45, "g") - walls = tuple(rotate(box(-4, y, 19, y + 1), 45, origin=(0, 0)) for y in (-3, 2)) - board = box(-10, -10, 25, 25) - intrusion = translate(walls[1], xoff=0.001 / sqrt(2), yoff=-0.001 / sqrt(2)) - for a, b in ((start, target), (target.reversed(), start.reversed())): - allowed = search_path(evaluator, a, b, board=board, keepouts=walls, clearance=1) - assert allowed.path is not None - assert allowed.path[0].move.steps == 10 - denied = search_path(evaluator, a, b, board=board, keepouts=(walls[0], intrusion), clearance=1) - assert denied.outcome == "exhausted" - - -@pytest.mark.parametrize("other_type", ["ridge", "strip"]) -def test_equal_width_profiles_require_a_declared_traversal(other_type) -> None: - profiles = {"mode1": Profile("ridge", 2), "mode2": Profile(other_type, 2)} - a, b = Pose(0, 0, 0, "mode1"), Pose(7, 0, 0, "mode2") - variant = FixedVariant( - "mode-converter", {"left": Pose(0, 0, 0, "mode1"), "right": Pose(7, 0, 180, "mode2")}, - (box(0, -1, 7, 1),), (("left", "right"),), (Orientation(),), 0.02, - ) - straight = StraightVariant("mode1", 1) - grid = Grid((0, 0), 1, 1e-6) - board = box(-2, -3, 9, 3) - evaluator = MoveEvaluator(grid, Catalog("strict", profiles, {"straight": straight})) - assert search_path(evaluator, a, b, board=board).outcome == "exhausted" - evaluator = MoveEvaluator(grid, Catalog("directed", profiles, {"change": variant, "straight": straight})) - route = search_path(evaluator, a, b, board=board) - assert route.outcome == "verified" - assert route.length is None - assert route.cost == pytest.approx(0.02) - assert search_path(evaluator, b.reversed(), a.reversed(), board=board).outcome == "exhausted" - model = DelayModel(1.55e-6, variant_delays={"change": 21.03}) - assert route.path is not None - delay = evaluate_delay(evaluator, route.path, model, net_id="converter") - assert delay is not None - assert delay.optical_length == 21.03 - - -def test_a_single_135_degree_bend_can_clear_an_opening_smaller_turns_miss() -> None: - grid = Grid((0, 0), 100, 1e-9) - variants = { - "straight": StraightVariant("g", 1), - "45": BendVariant("g", 45, 7000, 0.005, max_lead=400, sagitta=5), - "90": BendVariant("g", 90, 10_000, 0.006, sagitta=5), - "135": BendVariant("g", 135, 10_000, 0.02, max_lead=200, sagitta=5), - } - evaluator = MoveEvaluator(grid, Catalog("tight-135", {"g": Profile("ridge", 400)}, variants)) - start, target = Pose(0, 0, 0, "g"), Pose(7200, 17_100, 135, "g") - board = box(-1000, -1000, 13_000, 19_000) - radius = 10_000 - exit_lead = (target.y - radius * (1 + 1 / sqrt(2))) * sqrt(2) - entry_lead = target.x - radius / sqrt(2) + exit_lead / sqrt(2) - opening_points = [(0, 0)] - for i in range(257): - angle = i * (3 * pi / 4) / 256 - opening_points.append((entry_lead + radius * sin(angle), radius * (1 - cos(angle)))) - opening_points.append((target.x, target.y)) - opening = LineString(opening_points).buffer(300, cap_style="square") - keepouts = (board.difference(opening),) - open_run = search_path(evaluator, start, target, board=board) - assert open_run.path is not None - assert open_run.cost < 0.02 - assert verify_path(evaluator, open_run.path, start, target, board=board, keepouts=keepouts, clearance=20) == "keepout" - - only_single = search_path(evaluator, start, target, board=board, keepouts=keepouts, clearance=20) - assert only_single.path is not None - [bend] = only_single.path - assert bend.move.variant == "135" - assert bend.move.leads == pytest.approx((entry_lead, exit_lead)) - - -def test_bend_leads_use_profile_straight_price_by_default() -> None: - left = BendVariant("g", 45, 10_000, 0.01, max_lead=200, sagitta=5) - catalog = Catalog("lead-price", {"g": Profile("ridge", 4000)}, { - "straight": StraightVariant("g", 1), "l45": left, "l90": BendVariant("g", 90, 10_000, 0.01), - }) - evaluator = MoveEvaluator(Grid((0, 0), 100, 1e-9), catalog) - start = Pose(0, 0, 0, "g") - [first] = [move for move in evaluator.bend_moves("l45", 0, left) if move.displacement == (7200, 3000)] - [second] = [move for move in evaluator.bend_moves("l45", 45, left) if move.displacement == (3000, 7200)] - two = replay_moves(evaluator, start, (first, second)) - one = replay_moves(evaluator, start, (Move("l90", displacement=(10_000, 10_000)),)) - assert two is not None - assert one is not None - assert sum(move.cost for move in two) == pytest.approx(0.02 + (sum(first.leads) + sum(second.leads)) / 1e7) - assert one[0].cost == pytest.approx(0.01) - - -@pytest.mark.parametrize("source_attachment", [True, False]) -def test_attachment_does_not_grant_clearance_to_a_later_visit(source_attachment) -> None: - grid = Grid((0, 0), 100, 1e-9) - evaluator = MoveEvaluator(grid, Catalog("short-access", {"g": Profile("ridge", 4000)}, {"s": StraightVariant("g", 1)})) - terminal, outside = Pose(0, 0, 0, "g"), Pose(3000, 0, 0, "g") - fixed = box(-10_000, -2000, 0, 2000) - attachment = Attachment(fixed, box(-2000, -3000, 2000, 3000)) - access = evaluator.evaluate(Move("s", steps=30), terminal) - assert access is not None - far = Pose(4000, 5000, 0, "g") - later = Evaluation(Move("return"), outside, far, (box(250, 2250, 500, 2750),), None, 0.01) - geometry = {"board": box(-12_000, -5000, 15_000, 10_000), "keepouts": (fixed,), "clearance": 1000} - if source_attachment: - assert verify_path(evaluator, (access,), terminal, outside, source_attachment=attachment, **geometry) is None - assert verify_path(evaluator, (access, later), terminal, far, source_attachment=attachment, **geometry) == "fixed_attachment" - else: - arrival = replace(access, start=outside.reversed(), end=terminal.reversed()) - reversed_visit = replace(later, start=far.reversed(), end=outside.reversed()) - assert verify_path(evaluator, (arrival,), outside.reversed(), terminal.reversed(), destination_attachment=attachment, **geometry) is None - assert verify_path( - evaluator, (reversed_visit, arrival), far.reversed(), terminal.reversed(), destination_attachment=attachment, **geometry, - ) == "fixed_attachment" - - -@pytest.mark.parametrize("at_attachment", [False, True]) -@pytest.mark.parametrize("other_first", [False, True]) -def test_a_reserved_join_blocks_a_foreign_route_in_either_net_order(at_attachment, other_first) -> None: - before = Pose(-2000, 0, 0, "guide") - seam = Pose(0, 0, 0, "guide") - after = Pose(2000, 0, 0, "guide") - cells = { - "before": FixedVariant( - "before", {"a": before, "b": seam.reversed()}, (box(-2000, -1000, -1, 1000),), - (("a", "b"),), (Orientation(),), 1, - ), - "after": FixedVariant( - "after", {"a": seam, "b": after.reversed()}, (box(1, -1000, 2000, 1000),), - (("a", "b"),), (Orientation(),), 1, - ), - } - evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-9), Catalog( - "seam", {"guide": Profile("ridge", 2000), "foreign": Profile("other", 0.5)}, - {**cells, "foreign": StraightVariant("foreign", 1)}, - )) - fixed = cells["before"].footprints[0] - end_move = Move("after", traversal=("a", "b")) - if at_attachment: - attachment = Attachment(fixed, box(-20, -1100, 20, 1100)) - horizontal = CatalogNet(seam, after, source_attachment=attachment, seed=(end_move,)) - keepouts = (fixed,) - else: - horizontal = CatalogNet(before, after, seed=(Move("before", traversal=("a", "b")), end_move)) - keepouts = () - vertical = CatalogNet(Pose(0, -2000, 90, "foreign"), Pose(0, 2000, 90, "foreign")) - nets = {"horizontal": horizontal, "vertical": vertical} - if other_first: - nets = dict(reversed(tuple(nets.items()))) - result = route_layout( - evaluator, nets, LayoutSettings(box(-3000, -3000, 3000, 3000), keepouts, face_tolerance=2, refinement=False), - ) - assert result.completed == (("vertical",) if other_first else ("horizontal",)) - assert set(result.routes) == set(nets) - - -@pytest.mark.parametrize("require_complete", [False, True]) -def test_masque_releases_provisional_group_geometry_and_preserves_a_completed_group(masque_4a3, require_complete) -> None: - masque = masque_4a3 - poses = { - "failed-a": (Pose(20, 50, 0, "g"), Pose(90, 50, 0, "g")), - "failed-b": (Pose(20, 80, 0, "g"), Pose(90, 80, 0, "g")), - "keep-a": (Pose(110, 20, 0, "g"), Pose(180, 20, 0, "g")), - "keep-b": (Pose(110, 40, 0, "g"), Pose(180, 40, 0, "g")), - "independent": (Pose(50, 10, 90, "g"), Pose(50, 70, 90, "g")), - } - ports = {} - connections = [] - for name, (a, b) in poses.items(): - first, last = f"{name}-source", f"{name}-target" - ports[first] = masque.Port((a.x, a.y), rotation=radians(a.reversed().heading)) - ports[last] = masque.Port((b.x, b.y), rotation=radians(b.heading)) - connections.append(Connection(name, Endpoint(first, "g"), Endpoint(last, "g"))) - layout = masque.Pattern(ports=ports) - catalog = Catalog("group-placement", {"g": Profile("ridge", 2)}, {"s": StraightVariant("g", 1)}) - groups = ( - MatchGroup("failed", {"failed-a": 0, "failed-b": 1}, 1.55e-6, 0.05), - MatchGroup("held", {"keep-a": 0, "keep-b": 0}, 1.55e-6, 0.05), - ) - result = route_and_place( - layout, {}, connections, catalog=catalog, grid=Grid((0, 0), 1, 1e-6), board=box(0, 0, 200, 100), - layer=1, clearance=1, timing=DelayModel(1.55e-6, group_indices={"g": 4}), - match_groups=groups, refinement=False, require_complete=require_complete, - ) - assert result.matching["held"].complete - assert result.matching["failed"].status == "unmatched" - assert result.routes["failed-a"].path is not None - assert result.routes["failed-b"].path is not None - if require_complete: - assert result.placed == () - assert tuple(layout.ports) == tuple(ports) - assert not layout.shapes - assert result.attempts[0].independent_retries == 0 - else: - assert result.placed == ("keep-a", "keep-b", "independent") - assert set(layout.ports) == {name for name in ports if name.startswith("failed")} - assert len(layout.shapes[1]) == 3 - assert result.attempts[0].independent_retries == 1 - - -@pytest.mark.parametrize("authorization_first", [False, True]) -def test_two_preplaced_crossing_ports_have_independent_attachments(masque_4a3, authorization_first) -> None: - masque = masque_4a3 - cross = masque.Pattern() - for shape in (box(-10, -2, 10, 2), box(-2, -10, 2, 10)): - cross.polygon(7, vertices=shape.exterior.coords[:-1]) - real = (box(40, 48, 60, 52), box(48, 40, 52, 60)) - envelope = box(40, 40, 60, 60) - attaches = { - "east": Attachment(envelope, box(58, 47, 62, 53), real), - "north": Attachment(envelope, box(47, 58, 53, 62), real), - } - catalog = Catalog("crossing", {"g": Profile("ridge", 4)}, {"s": StraightVariant("g", 1)}) - for authorized in (authorization_first, not authorization_first): - layout = masque.Pattern(ports={ - "east": masque.Port((60, 50), rotation=pi), - "east-target": masque.Port((80, 50), rotation=0), - "north": masque.Port((50, 60), rotation=3 * pi / 2), - "north-target": masque.Port((50, 80), rotation=pi / 2), - }) - layout.ref("cross", offset=(50, 50)) - result = route_and_place( - layout, {"cross": cross}, tuple( - Connection(name, Endpoint(name, "g", attaches[name] if authorized else None), Endpoint(f"{name}-target", "g")) - for name in ("east", "north") - ), - catalog=catalog, grid=Grid((0, 0), 1, 1e-6), board=box(0, 0, 100, 100), layer=7, - keepouts=(envelope,), clearance=1, refinement=False, - ) - assert result.placed == (("east", "north") if authorized else ()) - assert len(layout.refs["cross"]) == 1 - assert len(layout.shapes.get(7, ())) == (2 if authorized else 0) - - -def test_masque_places_both_directions_of_a_displaced_transition(masque_4a3) -> None: - masque = masque_4a3 - a, b = Pose(0, 0, 0, "4"), Pose(100_000, 200, 180, "8") - actual = Polygon(((0, -2000), (100_000, -3800), (100_000, 4200), (0, 2000))) - envelope = box(0, -5000, 100_000, 5000) - native, reflected_reverse = Orientation(), Orientation(180, True) - cell = masque.Pattern(ports={"A": masque.Port((a.x, a.y), rotation=0), "B": masque.Port((b.x, b.y), rotation=pi)}) - cell.polygon(1, vertices=actual.exterior.coords[:-1]) - fixed = FixedVariant( - "displaced", {"A": a, "B": b}, (envelope,), (("A", "B"), ("B", "A")), - (native, reflected_reverse), 0.2, 100_010, - ) - catalog = Catalog("displaced", {"4": Profile("ridge4", 4000), "8": Profile("ridge8", 8000)}, { - "t": fixed, "s8": StraightVariant("8", 0.2), - }) - pose = Pose(10_000, 20_000, 0, "4") - target = Pose(230_000, 20_000, 0, "4") - layout = masque.Pattern(ports={ - "input": masque.Port((pose.x, pose.y), rotation=pi), - "output": masque.Port((target.x, target.y), rotation=0), - }) - seed = ( - Move("t", traversal=("A", "B")), Move("s8", steps=200), - Move("t", traversal=("B", "A"), orientation=reflected_reverse), - ) - result = route_and_place( - layout, {"displaced": cell}, (Connection("twice", Endpoint("input", "4"), Endpoint("output", "4"), seed),), - catalog=catalog, grid=Grid((0, 0), 100, 1e-9), board=box(0, 0, 300_000, 100_000), - layer=1, node_limit=0, timing=DelayModel(1.55e-6, group_indices={"8": 2}, variant_delays={"t": 300_030}), - ) - assert result.outcome == "complete" - assert result.placed == ("twice",) - path = result.routes["twice"].path - assert path is not None - assert tuple(part.move for part in path) == seed - assert [part.end.profile for part in path] == ["8", "8", "4"] - assert path[0].end == Pose(110_000, 20_200, 0, "8") - assert path[1].end == Pose(130_000, 20_200, 0, "8") - assert path[2].end == target - first, second = layout.refs["displaced"] - assert tuple(first.offset) == (10_000, 20_000) - assert tuple(second.offset) == (230_000, 20_000) - assert second.mirrored - assert second.rotation == pi - assert result.routes["twice"].cost == pytest.approx(0.4004) - assert result.delays["twice"].optical_length == 640_060 - - -def test_three_reference_profiles_use_the_declared_physical_straight_rates() -> None: - profiles = {name: Profile(f"ridge-{name}", int(name) * 1000) for name in ("4", "5", "8")} - prices = {"4": 1.0, "5": 0.5, "8": 0.2} - catalog = Catalog("device-set", profiles, {name: StraightVariant(name, rate) for name, rate in prices.items()}) - evaluator = MoveEvaluator(Grid((0, 0), 100, 1e-9), catalog) - for name, price in (("4", 0.1), ("5", 0.05), ("8", 0.02)): - cardinal = evaluator.evaluate(Move(name, steps=10_000), Pose(0, 0, 0, name)) - diagonal = evaluator.evaluate(Move(name, steps=10_000), Pose(0, 0, 45, name)) - assert cardinal is not None - assert diagonal is not None - assert cardinal.cost == pytest.approx(price) - assert diagonal.cost == pytest.approx(price * sqrt(2)) - - -def test_native_diagonal_transition_accepts_exact_displacement_and_diagnoses_off_grid_fit() -> None: - entry, exit = Pose(0, 0, 45, "4"), Pose(70_000, 70_200, 45, "8") - near, far = 2000 / sqrt(2), 4000 / sqrt(2) - a_left, a_right = (-near, near), (near, -near) - b_left, b_right = (exit.x - far, exit.y + far), (exit.x + far, exit.y - far) - footprint = Polygon((a_left, b_left, b_right, a_right)) - variant = FixedVariant( - "diagonal", {"a": entry, "b": exit.reversed()}, (footprint,), (("a", "b"),), (Orientation(),), 0.2, - ) - catalog = Catalog( - "diagonal-cell", {"4": Profile("ridge4", 4000), "8": Profile("ridge8", 8000)}, - {"change": variant, "8-straight": StraightVariant("8", 0.2)}, - ) - evaluator = MoveEvaluator(Grid((0, 0), 100, 1e-9), catalog) - board = box(-4000, -4000, 100_000, 105_000) - result = search_path(evaluator, entry, exit.shifted(10_000, 10_000), board=board) - assert result.path is not None - assert result.path[0].end == exit - assert result.path[1].end == exit.shifted(10_000, 10_000) - assert result.path[1].length == pytest.approx(10_000 * sqrt(2)) - coarse = MoveEvaluator(Grid((0, 0), 1000, 1e-9), catalog) - assert coarse.local_moves("4", 45) == () - [diagnostic] = coarse.unavailable - assert diagnostic.move.variant == "change" - assert diagnostic.reason == "off_grid_output" - - -def test_masque_rounds_to_layout_units_before_exact_lattice_validation(masque_4a3) -> None: - masque = masque_4a3 - catalog = Catalog("metric-origin", {"g": Profile("ridge", 40)}, {"s": StraightVariant("g", 1)}) - args = { - "catalog": catalog, "grid": Grid((30, -20), 100, 1e-9), "board": box(0, 0, 1000, 400), "layer": 1, - } - connection = Connection("rounding", Endpoint("a", "g"), Endpoint("b", "g")) - layout = masque.Pattern(ports={ - "a": masque.Port((330.00000000000006, 180), rotation=pi), - "b": masque.Port((830, 180), rotation=0), - }) - result = route_and_place(layout, {}, (connection,), **args) - assert result.placed == ("rounding",) - assert result.routes["rounding"].path[0].start == Pose(330, 180, 0, "g") - off_grid = masque.Pattern(ports={"a": masque.Port((331, 180), rotation=pi), "b": masque.Port((830, 180), rotation=0)}) - with pytest.raises(ValueError, match="invalid terminal"): - route_and_place(off_grid, {}, (connection,), **args) - assert tuple(off_grid.ports) == ("a", "b") - assert not off_grid.shapes - - -@pytest.mark.parametrize("turn", [45, 90, 135, 180]) -def test_euler_selection_stops_at_the_radius_floor(turn) -> None: - angle = radians(turn) - reference, floor = 10_000, 8_000 - partial = bend_curve(reference, angle, floor, None) - assert partial is not None - assert partial.radius == pytest.approx(floor) - assert 0 < partial.fraction < 1 - assert bend_curve(reference, angle, floor, partial.fraction + 1e-5) is None - assert bend_curve(reference, angle, floor, 1.0) is None - circular = bend_curve(reference, angle, floor, 0.0) - assert circular is not None - assert circular.radius == reference - - -def test_asymmetric_fixed_bend_after_diagonal_straight_replays_the_same_ports() -> None: - # Independent fixture construction. A northeast lead of 2√2 µm followed by - # a quarter turn of radius 4√2 µm ends 2 µm east and 10 µm north of entry. - local_radius = 4000 * sqrt(2) - local_lead = 2000 * sqrt(2) - centerline = [(0.0, 0.0)] - centerline.extend( - (local_lead + local_radius * sin(angle), local_radius * (1 - cos(angle))) - for angle in (pi * i / 1024 for i in range(513)) - ) - # Construct a fixed polygon with its two complete authored faces. - left, right = [], [] - headings = (0, *(pi * i / 1024 for i in range(513))) - for (x, y), angle in zip(centerline, headings, strict=True): - left.append((x - 500 * sin(angle), y + 500 * cos(angle))) - right.append((x + 500 * sin(angle), y - 500 * cos(angle))) - footprint = rotate(Polygon((*left, *reversed(right))), 45, origin=(0, 0)) - fixed = FixedVariant( - "asymmetric-diagonal", {"a": Pose(0, 0, 45, "g"), "b": Pose(2000, 10_000, 315, "g")}, (footprint,), - (("a", "b"),), (Orientation(),), 0.01, local_lead + local_radius * pi / 2, - ) - catalog = Catalog("asymmetric-diagonal", {"g": Profile("ridge", 1000)}, {"corner": fixed, "straight": StraightVariant("g", 1)}) - evaluator = MoveEvaluator(Grid((0, 0), 100, 1e-9), catalog) - start = Pose(20_000, 20_000, 45, "g") - target = Pose(17_000, 38_000, 135, "g") - run = search_path(evaluator, start, target, board=box(0, 0, 60_000, 60_000), face_tolerance=0.01) - assert run.path is not None - assert tuple(move.move.variant for move in run.path) == ("straight", "corner", "straight") - assert run.path[1].start == Pose(21_500, 21_500, 45, "g") - assert run.path[1].end == Pose(23_500, 31_500, 135, "g") - assert replay_moves(evaluator, start, tuple(move.move for move in run.path)) == run.path diff --git a/inire/tests/test_catalog_search_oracle.py b/inire/tests/test_catalog_search_oracle.py deleted file mode 100644 index e8b9fc2..0000000 --- a/inire/tests/test_catalog_search_oracle.py +++ /dev/null @@ -1,261 +0,0 @@ -"""Compare catalog search with complete path histories on small fixtures.""" - -from dataclasses import replace -from heapq import heappop, heappush -from itertools import count - -from shapely.geometry import LineString, Polygon, box - -from inire._catalog import BendVariant, Catalog, FixedVariant, Grid, Move, MoveEvaluator, Orientation, Pose, Profile, StraightVariant -from inire.router._catalog_layout import CatalogNet, LayoutSettings, route_layout -from inire.router._catalog_search import SearchBias, _Proposals, search_path -from inire.router._catalog_verify import VerificationCache, verify_path - - -def exhaustive_paths(evaluator, start, target, moves_from, *, depth, **geometry): - queue = [(0.0, 0, start, ())] - order = count(1) - complete = [] - expanded = 0 - while queue: - cost, _, pose, path = heappop(queue) - expanded += 1 - if path and pose == target: - complete.append((cost, path)) - continue - if len(path) == depth: - continue - for move in moves_from(pose): - candidate = evaluator.evaluate(move, pose) - if candidate is None: - continue - trial = (*path, candidate) - if verify_path(evaluator, trial, start, candidate.end, **geometry) is None: - heappush(queue, (cost + candidate.cost, next(order), candidate.end, trial)) - return complete, expanded - - -def test_launch_proposal_gaps_and_dominance_can_be_measured_separately(monkeypatch) -> None: - start, target = Pose(2, 4, 0, "a"), Pose(28, 8, 0, "b") - transition = FixedVariant( - "displaced", {"in": Pose(0, 0, 0, "a"), "out": Pose(8, 4, 180, "b")}, - (Polygon(((0, -1), (8, 3), (8, 5), (0, 1))),), - (("in", "out"),), (Orientation(),), 0.2, - ) - evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog( - "oracle", {"a": Profile("ridge", 2), "b": Profile("ridge", 2)}, - {"a": StraightVariant("a", 1), "b": StraightVariant("b", 1), "change": transition}, - )) - board = box(0, 0, 30, 12) - keepouts = (box(0, 5, 10, 12), box(18, 0, 30, 7)) - geometry = {"board": board, "keepouts": keepouts} - bound = 3 - - def complete_moves(pose): - straight = [Move(pose.profile, steps=size) for size in range(1, 31 - pose.x)] - return [*straight, Move("change", traversal=("in", "out"))] if pose.profile == "a" else straight - - oracle, oracle_expanded = exhaustive_paths(evaluator, start, target, complete_moves, depth=bound, **geometry) - [best] = oracle - assert best[1][1].start == Pose(10, 4, 0, "a") - - real_proposals = _Proposals(evaluator, start, target, keepouts, 0.0) - initial_moves = tuple(real_proposals.from_pose(start, board.bounds)) - # Production narrows the complete launch set but must keep the only legal launch. - assert set(initial_moves) < set(complete_moves(start)) - assert best[1][0].move in initial_moves - proposed, proposed_expanded = exhaustive_paths( - evaluator, start, target, lambda pose: real_proposals.from_pose(pose, board.bounds), depth=bound, **geometry, - ) - assert proposed == oracle - assert proposed_expanded < oracle_expanded - - def reference_proposals(_self, pose, _bounds): - return complete_moves(pose) - - with monkeypatch.context() as patch: - patch.setattr(_Proposals, "from_pose", reference_proposals) - pruned = search_path(evaluator, start, target, **geometry) - assert pruned.path == best[1] - assert pruned.expanded < oracle_expanded - - -def test_search_retains_the_arrival_that_can_continue(monkeypatch) -> None: - start, meeting, goal = (Pose(x, 5, 0, "p") for x in (0, 5, 9)) - width = 0.1 - detour = ((0, 5), (2, 5), (2, 9), (7, 9), (7, 2), (3, 2), (3, 5), (5, 5)) - - def cell(name, points, cost): - journey = LineString(points) - return FixedVariant( - name, {"in": Pose(*points[0], 0, "p"), "out": Pose(*points[-1], 180, "p")}, - (journey.buffer(width / 2, cap_style="flat", join_style="round"),), - (("in", "out"),), (Orientation(),), cost, journey.length, - ) - - choices = { - "direct": cell("direct", ((0, 5), (5, 5)), 5), - "cheap": cell("cheap", detour, 1), - "last": cell("last", ((5, 5), (9, 5)), 1), - } - evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog("history", {"p": Profile("waveguide", width)}, choices)) - board = box(-1, 0, 10, 10) - edges = { - start: tuple(Move(name, traversal=("in", "out")) for name in ("direct", "cheap")), - meeting: (Move("last", traversal=("in", "out")),), - } - - def script(_self, pose, _bounds): - return edges.get(pose, ()) - - def from_pose(pose): - return edges.get(pose, ()) - - short, cheap = (evaluator.evaluate(move, start) for move in edges[start]) - tail = evaluator.evaluate(edges[meeting][0], meeting) - assert short is not None - assert cheap is not None - assert tail is not None - assert cheap.end == short.end == meeting - assert cheap.cost < short.cost - assert verify_path(evaluator, (cheap,), start, meeting, board=board) is None - assert verify_path(evaluator, (cheap, tail), start, goal, board=board) == "join" - assert verify_path(evaluator, (short, tail), start, goal, board=board) is None - - oracle, _ = exhaustive_paths(evaluator, start, goal, from_pose, depth=2, board=board) - assert oracle == [(6, (short, tail))] - monkeypatch.setattr(_Proposals, "from_pose", script) - assert search_path(evaluator, start, goal, board=board, arrivals_per_pose=1).outcome == "exhausted" - assert search_path(evaluator, start, goal, board=board, arrivals_per_pose=2).path == oracle[0][1] - assert search_path(evaluator, start, goal, board=board, node_limit=1).outcome == "node_limit" - - -def test_search_defers_geometry_and_reorders_a_move_with_a_penalty() -> None: - start, target = Pose(10, 10, 0, "p"), Pose(30, 10, 0, "p") - detour = LineString(((10, 10), (14, 10), (14, 18), (26, 18), (26, 10), (30, 10))) - alternate = FixedVariant( - "detour", {"in": start, "out": target.reversed()}, - (detour.buffer(0.2, cap_style="flat", join_style="round"),), - (("in", "out"),), (Orientation(),), 0.01, detour.length, - ) - evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog( - "lazy geometry", {"p": Profile("ridge", 0.4)}, {"straight": StraightVariant("p", 1), "detour": alternate}, - )) - geometry = {"board": box(0, 0, 40, 25), "keepouts": (box(18, 11, 22, 12),)} - - direct = search_path(evaluator, start, target, **geometry) - assert direct.path is not None - assert [move.move.variant for move in direct.path] == ["straight"] - assert direct.geometry_checks == 1 - assert direct.proposed > direct.geometry_checks - - biased = search_path(evaluator, start, target, bias=SearchBias(range=3, proximity=0.02), **geometry) - assert biased.path is not None - assert [move.move.variant for move in biased.path] == ["detour"] - assert verify_path(evaluator, biased.path, start, target, **geometry) is None - - -def test_catalog_jog_can_launch_between_obstacles(monkeypatch) -> None: - start, target = Pose(0, 10, 0, "p"), Pose(120, 40, 0, "p") - evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog( - "jog", {"p": Profile("ridge", 2)}, - {"s": StraightVariant("p", 1), "left": BendVariant("p", 90, 5, 0.01), "right": BendVariant("p", -90, 5, 0.01)}, - )) - geometry = {"board": box(-10, 0, 130, 60), "keepouts": (box(49, 7, 110, 13), box(-5, 37, 22, 43)), "clearance": 1} - - # Isolate complete jog proposals. The source, midpoint, and destination launches all hit keepouts. - monkeypatch.setattr(_Proposals, "from_pose", lambda *_: ()) - result = search_path(evaluator, start, target, node_limit=8, **geometry) - - assert result.path is not None - assert [part.move.variant for part in result.path] == ["s", "left", "s", "right", "s"] - assert verify_path(evaluator, result.path, start, target, **geometry) is None - - -def test_constructive_path_can_detour_around_a_blocked_straight() -> None: - start, target = Pose(0, 10, 0, "p"), Pose(120, 10, 0, "p") - evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog( - "detour", {"p": Profile("ridge", 2)}, - {"s": StraightVariant("p", 1), "left": BendVariant("p", 90, 5, 0.01), "right": BendVariant("p", -90, 5, 0.01)}, - )) - geometry = {"board": box(-10, -10, 130, 30), "keepouts": (box(45, 2, 75, 18),), "clearance": 1} - result = search_path(evaluator, start, target, node_limit=10, method="constructive_only", **geometry) - - assert result.path is not None - assert result.expanded == 0 - assert sum(part.move.variant in {"left", "right"} for part in result.path) == 4 - assert verify_path(evaluator, result.path, start, target, **geometry) is None - - -def test_constructive_routing_uses_cheaper_profile_on_both_sides_of_a_blocker() -> None: - taper = FixedVariant( - "taper", {"a": Pose(0, 0, 0, "n"), "b": Pose(5, 0, 180, "w")}, - (Polygon(((0, -1), (5, -2), (5, 2), (0, 1))),), - (("a", "b"), ("b", "a")), (Orientation(), Orientation(180)), 0.001, 5, - ) - evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog( - "profiles", {"n": Profile("narrow", 2), "w": Profile("wide", 4)}, - {"narrow": StraightVariant("n", 1), "wide": StraightVariant("w", 0.1), "taper": taper}, - )) - start, target = Pose(0, 0, 0, "n"), Pose(160, 0, 0, "n") - board, keepouts = box(-10, -10, 170, 10), (box(70, 2, 90, 6),) - clear = search_path(evaluator, start, target, board=board, clearance=1) - assert clear.path is not None - assert [move.move.variant for move in clear.path] == ["taper", "wide", "taper"] - assert clear.expanded == 0 - - result = route_layout( - evaluator, {"through": CatalogNet(start, target)}, - LayoutSettings(board, keepouts, clearance=1, constructive=True, refinement=False), - ) - - path = result.routes["through"].path - assert path is not None - assert [move.move.variant for move in path] == ["taper", "wide", "taper", "narrow", "taper", "wide", "taper"] - assert result.routes["through"].cost < evaluator.evaluate(Move("narrow", steps=160), start).cost - assert result.routes["through"].length == 160 - assert verify_path(evaluator, path, start, target, board=board, keepouts=keepouts, clearance=1) is None - - short_cell = FixedVariant( - "link", {"in": start, "out": target.reversed()}, (box(0, -1, 160, 1),), - (("in", "out"),), (Orientation(),), 0.001, 160, - ) - alternatives = MoveEvaluator(evaluator.grid, replace(evaluator.catalog, variants={**evaluator.catalog.variants, "link": short_cell})) - cheaper = search_path(alternatives, start, target, board=board, clearance=1) - assert cheaper.path is not None - assert [move.move.variant for move in cheaper.path] == ["link"] - - -def test_geometry_cache_rechecks_changed_occupancy() -> None: - start, target = Pose(0, 10, 0, "p"), Pose(40, 10, 0, "p") - evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog( - "cache", {"p": Profile("ridge", 2)}, {"s": StraightVariant("p", 1)}, - )) - path = (evaluator.evaluate(Move("s", steps=40), start),) - geometry = {"board": box(-10, 0, 50, 30), "clearance": 1, "cache": VerificationCache()} - assert verify_path(evaluator, path, start, target, **geometry) is None - assert verify_path(evaluator, path, start, target, occupied=(box(15, 11.5, 20, 14),), **geometry) == "occupied" - assert verify_path(evaluator, path, start, target, occupied=(box(15, 12, 20, 14),), **geometry) is None - - -def test_refinement_prefers_the_cheaper_of_two_full_coverage_orders() -> None: - catalog = Catalog("order", {"g": Profile("ridge", 2)}, { - "s": StraightVariant("g", 1), "left": BendVariant("g", 90, 5, 0.01), "right": BendVariant("g", -90, 5, 0.01), - }) - grid = Grid((0, 0), 1, 1e-6) - nets = { - "horizontal": CatalogNet(Pose(10, 50, 0, "g"), Pose(90, 50, 0, "g")), - "vertical": CatalogNet(Pose(50, 10, 90, "g"), Pose(50, 70, 90, "g")), - } - settings = LayoutSettings(box(0, 0, 100, 100), clearance=1, node_limit=800, refinement=False) - first = route_layout(MoveEvaluator(grid, catalog), nets, settings) - second = route_layout(MoveEvaluator(grid, catalog), dict(reversed(tuple(nets.items()))), settings) - assert set(first.completed) == set(second.completed) == set(nets) - assert len(first.routes["horizontal"].path) == 1 - assert len(second.routes["vertical"].path) == 1 - assert sum(route.cost for route in second.routes.values()) < sum(route.cost for route in first.routes.values()) - - refined = route_layout(MoveEvaluator(grid, catalog), nets, replace(settings, refinement=True)) - assert refined.completed == tuple(nets) - assert len(refined.attempts) == 2 - assert all(refined.routes[name].path == second.routes[name].path for name in nets) diff --git a/inire/tests/test_catalog_timing_cases.py b/inire/tests/test_catalog_timing_cases.py deleted file mode 100644 index f90af90..0000000 --- a/inire/tests/test_catalog_timing_cases.py +++ /dev/null @@ -1,328 +0,0 @@ -"""Timing models, ranked alternatives, and bounded matching.""" - -from dataclasses import replace -from math import sqrt - -import pytest -from shapely.geometry import LineString, Polygon, box - -from inire._catalog import BendVariant, Catalog, Evaluation, FixedVariant, Grid, Move, MoveEvaluator, Orientation, Pose, Profile, StraightVariant -from inire._catalog_timing import Delay, DelayModel -from inire.router import _catalog_layout, _catalog_tuning -from inire.router._catalog_layout import CatalogNet, LayoutResult, LayoutSettings, _layout_rank, route_layout -from inire.router._catalog_matching import MatchGroup, MatchResult -from inire.router._catalog_search import SearchResult -from inire.router._catalog_tuning import tune_group, window_replacements -from inire.router._catalog_verify import replay_moves, verify_path -from scripts.benchmark_catalog_routing import catalog, scale_case, verify_references - - -@pytest.mark.parametrize("condition", ["independent", "matched", "delay-conflict"]) -def test_profile_pair_refinement_preserves_coverage_and_timing(condition) -> None: - name = "peer-cost-holdout" if condition == "independent" else "matched-cost-holdout" - case = scale_case(name) - technology = catalog("typed", name) - references = verify_references(case, technology) - timing = case.timing - if condition == "delay-conflict": - assert timing is not None - timing = replace(timing, group_indices={"4": 4, "5": 5}) - settings = LayoutSettings(case.board, case.obstacles, clearance=case.clearance, constructive=True) - result = route_layout(MoveEvaluator(case.grid, technology), case.nets, settings, timing=timing, groups=case.groups) - assert result.completed == tuple(case.nets) - if case.groups: - assert result.matching["delay"].complete - assert result.matching["delay"].skew == 0 - through = result.routes["through"] - if condition == "delay-conflict": - assert through.cost == pytest.approx(0.46) - else: - assert through.cost == pytest.approx(0.249) - assert sum(route.cost for route in result.routes.values()) <= references["cheaper"] + 1e-12 - - -@pytest.mark.parametrize("units", ["optical_length", "seconds"]) -def test_matching_retries_a_more_expensive_baseline_across_a_fixed_crossing(units) -> None: - meter_per_unit = 1e-6 - scale = meter_per_unit / 299_792_458 if units == "seconds" else 1 - evaluator = MoveEvaluator(Grid((0, 0), 1, meter_per_unit), Catalog( - "crossing", {"g": Profile("ridge", 2)}, {"regular": StraightVariant("g", 1), "slow": StraightVariant("g", 2)}, - )) - nets = { - "after-crossing": CatalogNet(Pose(5, 5, 0, "g"), Pose(40, 5, 0, "g")), - "reference": CatalogNet(Pose(5, 15, 0, "g"), Pose(40, 15, 0, "g")), - } - observations = [] - - def fixed_side(wavelength): - observations.append(("fixed-route", wavelength)) - return 100 if wavelength == 1.55e-6 else 50 - - def crossing(wavelength): - observations.append(("crossing", wavelength)) - return 5 - - def group_index(wavelength, _angle): - observations.append(("straight", wavelength)) - return 4 if wavelength == 1.55e-6 else 3 - - timing = DelayModel( - 1.3e-6, group_indices={"g": group_index}, variant_delays={"slow": lambda _move, wavelength: 145 if wavelength == 1.55e-6 else 50}, - fixed_contributions={"after-crossing": (fixed_side, crossing), "reference": (110,)}, - ) - settings = LayoutSettings(box(0, 0, 50, 20), node_limit=30, refinement=False) - report = route_layout(evaluator, nets, settings, timing=timing) - normal = report.routes["after-crossing"].path - assert normal is not None - assert normal[0].move.variant == "regular" - assert report.completed == tuple(nets) - assert report.delays["after-crossing"].optical_length == 160 - assert all(wavelength == 1.3e-6 for _, wavelength in observations) - observations.clear() - - group = MatchGroup("timing", {"after-crossing": 0, "reference": 0}, 1.55e-6, 0.05 * scale, units=units) - matched = route_layout(evaluator, nets, settings, timing=timing, groups=(group,)) - chosen = matched.routes["after-crossing"].path - assert matched.completed == tuple(nets) - assert chosen is not None - assert chosen[0].move.variant == "slow" - assert matched.matching["timing"].delays["after-crossing"].optical_length == 250 - assert matched.matching["timing"].skew == 0 - assert {"fixed-route", "crossing", "straight"} <= {name for name, _ in observations} - assert all(wavelength == group.wavelength for _, wavelength in observations) - - restricted = MoveEvaluator(evaluator.grid, replace(evaluator.catalog, variants={"regular": StraightVariant("g", 1)})) - unmatched = route_layout(restricted, nets, settings, timing=timing, groups=(group,)) - assert unmatched.completed == () - assert all(candidate.path is not None for candidate in unmatched.routes.values()) - assert unmatched.matching["timing"].skew == pytest.approx(5 * scale, abs=1e-12 * scale) - assert unmatched.matching["timing"].status == "unmatched" - - -@pytest.mark.parametrize(("limit", "expected_status", "expected_skew"), [ - (0, "unmatched", 1), (1, "unmatched", 0.2), (2, "unmatched", 0.2), (3, "matched", 0), (4, "matched", 0), -]) -def test_tuning_budget_keeps_the_best_verified_delay_choices(monkeypatch, limit, expected_status, expected_skew) -> None: - # The second proposal is for b. Its baseline remains eligible and pairs - # more closely with a's first improvement. - catalog = Catalog( - "timing-budget", {"g": Profile("ridge", 1)}, - {name: StraightVariant("g", 1) for name in ("base-a", "base-b", "middle", "last")}, - ) - evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), catalog) - board = box(0, 0, 20, 20) - terminals = { - "a": (Pose(2, 4, 0, "g"), Pose(17, 4, 0, "g")), - "b": (Pose(2, 8, 0, "g"), Pose(17, 8, 0, "g")), - } - - def recipe(name, variant): - return replay_moves(evaluator, terminals[name][0], (Move(variant, steps=15),)) - - base = {name: recipe(name, f"base-{name}") for name in terminals} - proposals = {"a": (recipe("a", "middle"), recipe("a", "last")), "b": (recipe("b", "last"),)} - - def replacements(_evaluator, path, _window): - return iter(proposals["a" if path[0].start.y == 4 else "b"]) - - monkeypatch.setattr(_catalog_tuning, "window_replacements", replacements) - timing = DelayModel(1.55e-6, variant_delays={"base-a": 400, "base-b": 401, "middle": 400.8, "last": 401.6}) - group = MatchGroup("budget", {"a": 0, "b": 0}, 1.55e-6, 0.05) - windows = {"a": box(2, 2, 17, 6), "b": box(2, 6, 17, 10)} - - report, changes = tune_group( - evaluator, group, timing, base, windows, - lambda name, path: verify_path(evaluator, path, *terminals[name], board=board) is None, - proposal_limit=limit, - ) - assert report.status == expected_status - assert report.skew == pytest.approx(expected_skew) - assert report.budget_exhausted == (limit < 4) - if limit == 0: - assert not changes - if limit == 1: - assert changes == {"a": proposals["a"][0]} - - -def test_missing_fixed_contribution_leaves_the_verified_geometry_available() -> None: - evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog("unknown", {"g": Profile("ridge", 2)}, {"s": StraightVariant("g", 1)})) - nets = {"member": CatalogNet(Pose(5, 5, 0, "g"), Pose(40, 5, 0, "g"))} - settings = LayoutSettings(box(0, 0, 50, 20)) - model = DelayModel(1.55e-6, group_indices={"g": 4}, fixed_contributions={"member": (None,)}) - report_only = route_layout(evaluator, nets, settings, timing=model) - assert report_only.completed == ("member",) - assert report_only.delays["member"] is None - grouped = route_layout(evaluator, nets, settings, timing=model, groups=(MatchGroup("requires-fixed", {"member": 0}, 1.55e-6, 0.05),)) - assert grouped.completed == () - assert grouped.routes["member"].path == report_only.routes["member"].path - assert grouped.matching["requires-fixed"].status == "missing_delay" - assert not grouped.matching["requires-fixed"].budget_exhausted - - -@pytest.mark.parametrize("uses_callback", [False, True]) -def test_tuning_verifies_cheaper_equal_delays_before_discarding_dominated_choices(monkeypatch, uses_callback) -> None: - variants = {"base": 1, "rejected": 1, "first": 3, "dominated": 4, "cheaper": 2} - evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog( - "equal delays", {"g": Profile("ridge", 1)}, {name: StraightVariant("g", cost) for name, cost in variants.items()}, - )) - start = Pose(2, 4, 0, "g") - base = replay_moves(evaluator, start, (Move("base", steps=15),)) - candidates = tuple(replay_moves(evaluator, start, (Move(name, steps=15),)) for name in tuple(variants)[1:]) - monkeypatch.setattr(_catalog_tuning, "window_replacements", lambda *_: iter(candidates)) - def characterize(move, _wavelength): - assert move.move.variant != "rejected" - return 410 - - delays = {name: 400 if name == "base" else 410 for name in variants} - if uses_callback: - delays["rejected"] = characterize - timing = DelayModel(1.55e-6, variant_delays=delays) - group = MatchGroup("equal delays", {"a": 0, "b": -10}, timing.wavelength, 0) - checked = [] - - def verify(_name, path): - variant = path[0].move.variant - checked.append(variant) - return variant != "rejected" - - report, changes = tune_group( - evaluator, group, timing, {"a": base, "b": base}, {"a": box(0, 0, 20, 10)}, verify, proposal_limit=4, - ) - - assert report.complete - assert report.skew == 0 - assert report.proposed_replacements == 4 - assert checked == (["rejected", "first", "dominated", "cheaper"] if uses_callback else ["rejected", "first", "cheaper"]) - assert changes == {"a": candidates[-1]} - - -@pytest.mark.parametrize("reverse_order", [False, True]) -def test_adjacent_windows_keep_clearance_for_the_other_owner(reverse_order) -> None: - square = box(0, -1, 16, 1) - protruding = Polygon(((0, -1), (16, -1), (16, 1), (12, 1), (10, 1.1), (6, 1.1), (4, 1), (0, 1))) - profiles = {"g": Profile("ridge", 2)} - altered = FixedVariant( - "protruding", {"in": Pose(0, 0, 0, "g"), "out": Pose(16, 0, 180, "g")}, - (protruding,), (("in", "out"),), (Orientation(),), 1, 16, - ) - safe = replace(altered, cell="safe", footprints=(square,)) - variants = {"s": StraightVariant("g", 1), "protruding": altered, "safe": safe} - evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog("adjacent", profiles, variants)) - settings = LayoutSettings(box(0, 0, 24, 22), clearance=1, node_limit=0, refinement=False) - windows = {"a": box(2, 8, 18, 12), "b": box(2, 12, 18, 16)} - timing = DelayModel(1.55e-6, group_indices={"g": 4}, variant_delays={"protruding": 64, "safe": 64}) - group = MatchGroup("adjacent", {"a": 0, "b": 0}, 1.55e-6, 0) - for candidate in ("safe", "protruding"): - nets = { - "a": CatalogNet(Pose(2, 10, 0, "g"), Pose(18, 10, 0, "g"), seed=(Move(candidate, traversal=("in", "out")),)), - "b": CatalogNet(Pose(2, 14, 0, "g"), Pose(18, 14, 0, "g"), seed=(Move("s", steps=16),)), - } - if reverse_order: - nets = dict(reversed(tuple(nets.items()))) - result = route_layout(evaluator, nets, settings, timing=timing, groups=(group,), windows=windows) - if candidate == "safe": - assert result.completed == tuple(nets) - assert result.matching["adjacent"].complete - else: - assert result.completed == () - assert result.routes["a"].path is None - assert result.matching["adjacent"].status == "unrouted" - - -def test_four_completed_independent_nets_outrank_a_three_net_match() -> None: - evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog("ranking", {"g": Profile("ridge", 2)}, { - "low": StraightVariant("g", 1), "high": StraightVariant("g", 2), - })) - low = {} - high = {} - for i in range(4): - start = Pose(2, i * 5 + 2, 0, "g") - name = f"net{i}" - low[name] = SearchResult(replay_moves(evaluator, start, (Move("low", steps=6),)), "verified", 0, 0) - high[name] = SearchResult(replay_moves(evaluator, start, (Move("high", steps=8),)), "verified", 0, 0) - report = MatchResult("matched", "matched", {}, 0.0) - three = LayoutResult(low, tuple(low)[:3], matching={"matched": report}) - four = LayoutResult(high, tuple(high)) - assert _layout_rank(four) < _layout_rank(three) - assert _layout_rank(LayoutResult(low, tuple(low))) < _layout_rank(four) - - -def test_final_layout_verification_preserves_the_incumbent_on_a_conflicting_match(monkeypatch) -> None: - evaluator = MoveEvaluator( - Grid((0, 0), 1, 1e-6), Catalog("joint-verification", {"g": Profile("ridge", 2)}, {"s": StraightVariant("g", 1)}), - ) - board = box(0, 0, 30, 30) - nets = { - name: CatalogNet(Pose(4, y, 0, "g"), Pose(26, y, 0, "g"), seed=(Move("s", steps=22),)) - for name, y in (("a", 9), ("b", 21)) - } - groups = (MatchGroup("joint", {"a": 0, "b": 4}, 1.55e-6, 0.05),) - originals = {name: evaluator.evaluate(net.seed[0], net.start) for name, net in nets.items()} - proposed = {} - for name, net in nets.items(): - line = LineString(((4, net.start.y), (8, net.start.y), (12, 15), (18, 15), (22, net.target.y), (26, net.target.y))) - proposed[name] = (Evaluation(Move("s", steps=22), net.start, net.target, (line.buffer(1, cap_style="flat"),), line.length, 1),) - other = originals["b" if name == "a" else "a"] - assert other is not None - assert verify_path(evaluator, proposed[name], net.start, net.target, board=board, occupied=other.footprints) is None - - original_tune = _catalog_layout.tune_group - - def conflicting_tune(evaluator, group, timing, baselines, windows, verifies, *, proposal_limit): - if proposal_limit == 0: - return original_tune(evaluator, group, timing, baselines, windows, verifies, proposal_limit=0) - return MatchResult("joint", "matched", {"a": Delay(100, 0), "b": Delay(104, 0)}, 0.0), proposed - - monkeypatch.setattr(_catalog_layout, "tune_group", conflicting_tune) - timing = DelayModel(1.55e-6, group_indices={"g": 4}) - result = route_layout(evaluator, nets, LayoutSettings(board, node_limit=0, refinement=False), timing=timing, groups=groups) - assert result.completed == () - assert result.matching["joint"].status == "unmatched" - assert result.matching["joint"].skew == 4 - assert {name: report.path for name, report in result.routes.items()} == {name: (move,) for name, move in originals.items()} - - -@pytest.mark.parametrize(("poses", "expected"), [ - ((((20, 40, 0), (120, 40, 0)), ((120, 70, 180), (20, 70, 180)), ((160, 20, 90), (160, 120, 90))), 400), - ((((20, 160, 45), (50, 190, 45)), ((90, 190, 225), (60, 160, 225)), ((130, 190, 315), (160, 160, 315))), 120 * sqrt(2)), -]) -def test_cardinal_and_diagonal_directions_match_on_total_delay(poses, expected) -> None: - evaluator = MoveEvaluator(Grid((0, 0), 1, 1e-6), Catalog("axes", {"g": Profile("ridge", 4)}, {"s": StraightVariant("g", 1)})) - nets = { - str(i): CatalogNet(Pose(*a, "g"), Pose(*b, "g")) for i, (a, b) in enumerate(poses) - } - settings = LayoutSettings(box(0, 0, 400, 300), clearance=1) - timing = DelayModel(1.55e-6, group_indices={"g": 4}) - group = MatchGroup("matched", dict.fromkeys(nets, 0.0), 1.55e-6, 0.05) - result = route_layout(evaluator, nets, settings, timing=timing, groups=(group,)) - assert result.completed == tuple(nets) - report = result.matching["matched"] - assert report.skew == 0 - assert [delay.optical_length for delay in report.delays.values()] == pytest.approx([expected] * 3) - repeated = MatchGroup("duplicate", {"0": 0}, 1.55e-6, 0) - with pytest.raises(ValueError, match="multiple groups"): - route_layout(evaluator, nets, settings, timing=timing, groups=(group, repeated)) - - -def test_four_turn_tuning_includes_the_window_edge_and_rejects_protrusion() -> None: - evaluator = MoveEvaluator( - Grid((0, 0), 1, 1e-6), Catalog("boundary", {"g": Profile("ridge", 4)}, { - "s": StraightVariant("g", 1), - "left": BendVariant("g", 90, 10, 0.01, sagitta=0.01), - "right": BendVariant("g", -90, 10, 0.01, sagitta=0.01), - }), - ) - original = replay_moves(evaluator, Pose(20, 120, 0, "g"), (Move("s", steps=120),)) - assert original is not None - exact = box(40, 115, 100, 152) - outside = box(40, 115, 100, 151.99) - boundary_candidates = [ - path for path in window_replacements(evaluator, original, exact) if path is not None - and any(shape.bounds[3] == 152 for move in path for shape in move.footprints) - ] - assert boundary_candidates - for path in boundary_candidates: - assert verify_path(evaluator, path, original[0].start, original[0].end, board=box(0, 0, 400, 300)) is None - accepted = tuple(path for path in window_replacements(evaluator, original, outside) if path is not None) - assert accepted - assert all(path not in accepted for path in boundary_candidates) diff --git a/inire/tests/test_pathfinder.py b/inire/tests/test_pathfinder.py index 0cf1653..1505319 100644 --- a/inire/tests/test_pathfinder.py +++ b/inire/tests/test_pathfinder.py @@ -1,5 +1,3 @@ -from dataclasses import replace - import pytest from shapely.geometry import box @@ -13,8 +11,6 @@ from inire import ( RoutingOptions, RoutingProblem, SearchOptions, - TopologyOptions, - route, ) from inire.geometry.collision import RoutingWorld from inire.geometry.components import Bend90, Straight @@ -27,7 +23,6 @@ from inire.router.danger_map import DangerMap DEFAULT_BOUNDS = (0, 0, 100, 100) - _PROBLEM_FIELDS = set(RoutingProblem.__dataclass_fields__) - {"bounds", "nets"} _SEARCH_FIELDS = set(SearchOptions.__dataclass_fields__) _CONGESTION_FIELDS = set(CongestionOptions.__dataclass_fields__) @@ -110,30 +105,6 @@ def _build_manual_path(start: Port, width: float, clearance: float, steps: list[ return path -@pytest.mark.parametrize(("target_y", "keepouts", "turns"), [ - (40, (box(49, 7, 110, 13), box(-5, 37, 22, 43)), 2), - (10, (box(45, 2, 75, 18),), 4), -]) -def test_native_warm_start_can_place_a_terminal_detour(target_y, keepouts, turns) -> None: - problem = RoutingProblem( - (-10, -10, 130, 60), (NetSpec("jog", Port(0, 10, 0), Port(120, target_y, 0), 2),), - keepouts, clearance=1, - ) - options = RoutingOptions( - search=SearchOptions(node_limit=4, bend_radii=(5,), sbend_radii=()), - congestion=CongestionOptions(max_iterations=1), - refinement=RefinementOptions(enabled=False), - topology=TopologyOptions(mode="off"), - ) - bounded = route(problem, options=options) - assert not bounded.results_by_net["jog"].is_valid - - planned = route(problem, options=replace(options, search=replace(options.search, terminal_jog_limit=8))) - assert planned.results_by_net["jog"].is_valid - assert sum(piece.move_type == "bend90" for piece in planned.results_by_net["jog"].path) == turns - assert planned.metrics.nodes_expanded == 0 - - def test_frontier_replay_restores_installed_path_and_metrics(monkeypatch: pytest.MonkeyPatch) -> None: search_raises = True world = RoutingWorld(clearance=2.0) diff --git a/inire/tests/test_routing_benchmarks.py b/inire/tests/test_routing_benchmarks.py index f74fc65..a9b7328 100644 --- a/inire/tests/test_routing_benchmarks.py +++ b/inire/tests/test_routing_benchmarks.py @@ -344,70 +344,6 @@ def test_automatic_can_force_weighted_scoring_when_the_selective_pass_is_skipped assert set(selective.automatic.verified_net_ids) == set(forced.automatic.verified_net_ids) == {net.net_id for net in case.problem.nets} -def test_weighted_column_planner_compares_quarter_turns_at_full_coverage() -> None: - [case] = CASE_GROUPS["complex-column-6x2-wide"] - span = automatic_options(profile_options(case, "corpus-regression"), "corpus-regression", "automatic-span") - weighted = replace(span, topology=replace(span.topology, automatic_cost="selective")) - baseline = route(case.problem, options=span) - result = route(case.problem, options=weighted) - - assert baseline.automatic is not None - assert result.automatic is not None - assert result.automatic.selected_planner == "column-jogs" - assert set(result.automatic.verified_net_ids) == set(baseline.automatic.verified_net_ids) == {net.net_id for net in case.problem.nets} - assert sum(map(benchmark_weighted_length, result.results_by_net.values())) < 0.3 * sum( - map(benchmark_weighted_length, baseline.results_by_net.values()), - ) - - -def test_weighted_terminal_detour_can_replace_an_expensive_s_bend_route() -> None: - [case] = CASE_GROUPS["precision-forward-large-radius"] - span = automatic_options(profile_options(case, "corpus-regression"), "corpus-regression", "automatic-span") - weighted = replace(span, topology=replace(span.topology, automatic_cost="selective")) - - baseline = route(case.problem, options=span).results_by_net["through"] - run = route(case.problem, options=weighted) - result = run.results_by_net["through"] - - assert baseline.is_valid - assert result.is_valid - assert run.automatic is not None - assert run.automatic.selected_planner == "terminal-detour" - assert [move.move_type for move in result.path] == ["bend90"] * 4 - assert benchmark_weighted_length(result) < benchmark_weighted_length(baseline) - - -def test_weighted_column_jogs_can_use_shared_apertures_in_a_dense_field() -> None: - [case] = CASE_GROUPS["scale-field-16x16"] - span = automatic_options(profile_options(case, "corpus-regression"), "corpus-regression", "automatic-span") - weighted = replace(span, topology=replace(span.topology, automatic_cost="selective")) - baseline = route(case.problem, options=span) - result = route(case.problem, options=weighted) - - assert baseline.automatic is not None - assert result.automatic is not None - assert result.automatic.selected_planner == "column-jogs" - assert set(result.automatic.verified_net_ids) == set(baseline.automatic.verified_net_ids) == {net.net_id for net in case.problem.nets} - assert sum(map(benchmark_weighted_length, result.results_by_net.values())) < 0.85 * sum( - map(benchmark_weighted_length, baseline.results_by_net.values()), - ) - - -def test_weighted_column_shortcuts_keep_the_verified_layout_at_lower_cost() -> None: - [case] = CASE_GROUPS["bypass-three-branches"] - options = automatic_options(profile_options(case, "corpus-regression"), "corpus-regression") - result = route(case.problem, options=options) - - assert result.automatic is not None - assert result.automatic.selected_planner == "straight-shortcuts" - assert set(result.automatic.verified_net_ids) == {net.net_id for net in case.problem.nets} - assert sum(map(benchmark_weighted_length, result.results_by_net.values())) < 35_000 - - seeded = replace(case.problem, initial_paths={name: path.as_seed() for name, path in result.results_by_net.items()}) - verification = route(seeded, options=replace(options, search=replace(options.search, node_limit=0))) - assert all(route_result.is_valid for route_result in verification.results_by_net.values()) - - def test_port_spacing_certificate_keeps_input_order_in_mixed_width_bank() -> None: nets = tuple( NetSpec(name, Port(5, y, 0), Port(95, y + 40, 0), width) @@ -419,17 +355,6 @@ def test_port_spacing_certificate_keeps_input_order_in_mixed_width_bank() -> Non assert port_conflicts(replace(problem, nets=(nets[0], nets[2], nets[1], *nets[3:])), RoutingOptions()) == (("a", "c"), ("b", "d")) -def test_port_capacity_planner_reaches_the_terminal_clearance_limit() -> None: - [case] = CASE_GROUPS["lidar-clements-8x8"] - options = automatic_options(profile_options(case, "corpus-regression"), "corpus-regression") - run = route(case.problem, options=options) - - assert run.automatic is not None - assert run.automatic.selected_planner == "port-capacity" - assert run.automatic.verified_net_ids == ("n_30", "n_32", "n_34") - assert run.metrics.nodes_expanded == 0 - - def test_perimeter_residual_preserves_its_lock_and_verifies_the_layout(monkeypatch: pytest.MonkeyPatch) -> None: (case,) = CASE_GROUPS["terminal-bench-pair"] options = automatic_options(profile_options(case, "corpus-regression"), "corpus-regression") diff --git a/inire/tests/test_routing_fixtures.py b/inire/tests/test_routing_fixtures.py index cdfeac8..7b98fc5 100644 --- a/inire/tests/test_routing_fixtures.py +++ b/inire/tests/test_routing_fixtures.py @@ -8,7 +8,7 @@ from inire import Bend90Seed, RoutingRunResult, SBendSeed, StraightSeed, route from inire.constants import TOLERANCE_LINEAR from inire.tests.retry_holdout_benchmarks import RETRY_HOLDOUT_CASES from inire.tests.routing_benchmarks import BENCHMARK_CASES, COMPLEX_BENCHMARK_CASES, EXTERNAL_BENCHMARK_CASES -from inire.tests.routing_corpus import CASE_GROUPS, CORPUS_CASES, automatic_options, benchmark_weighted_length, profile_options, select_cases +from inire.tests.routing_corpus import CASE_GROUPS, CORPUS_CASES, automatic_options, profile_options, select_cases from inire.tests.routing_expanded_benchmarks import LOW_LENGTH_COST_CASES from inire.tests.stress_routing_benchmarks import STRESS_BENCHMARK_CASES @@ -84,8 +84,7 @@ def test_automatic_reaches_corpus_routing_bound(case) -> None: assert set(partial.valid_net_ids) == verified - {"outside_lower"} if case.name == "pic-splitter-tree-1x8-ew": assert any(stage.policy == "direct-lookahead-hinted" for stage in run.automatic.stages) - assert any(stage.kind == "incumbent-verified" and set(stage.valid_net_ids) == verified for stage in run.automatic.stages) - assert sum(benchmark_weighted_length(run.results_by_net[net_id]) for net_id in verified) < 38_000 + assert run.automatic.stages[run.automatic.selected_stage].kind == "incumbent-verified" if case.name == "overloaded-gate": capacity = run.automatic.capacity_limit assert capacity is not None diff --git a/scripts/benchmark_catalog_routing.py b/scripts/benchmark_catalog_routing.py deleted file mode 100644 index d5af850..0000000 --- a/scripts/benchmark_catalog_routing.py +++ /dev/null @@ -1,465 +0,0 @@ -"""Compare catalog and native routing on 5 mm layouts at 100 nm pitch.""" - -from __future__ import annotations - -import argparse -import json -import platform -import resource -from dataclasses import asdict, dataclass, field, replace -from itertools import pairwise -from math import fsum, pi, sqrt -from statistics import median -from time import perf_counter - -from shapely.affinity import scale -from shapely.geometry import Polygon, box - -from inire import NetSpec, ObjectiveWeights, Port, RefinementOptions, RoutingOptions, RoutingProblem, SearchOptions, TopologyOptions, route -from inire._catalog import ( - HEADING_STEPS, BendVariant, Catalog, FixedVariant, Grid, Move, MoveEvaluator, Orientation, Pose, Profile, StraightVariant, -) -from inire._catalog_timing import DelayModel, evaluate_delay -from inire.router._catalog_guidance import AutomaticGrid, CoarseGuidance -from inire.router._catalog_layout import CatalogNet, LayoutSettings, route_layout -from inire.router._catalog_matching import DelayChoice, MatchGroup, choose_match -from inire.router._catalog_verify import replay_moves, verify_path -from scripts.catalog_floorplan import BLOCKS, COMPONENTS, NET_BANKS, STEPPED_BLOCKS - - -PROFILE_HOLDOUTS = ("peer-cost-holdout", "matched-cost-holdout") - - -@dataclass(frozen=True, slots=True) -class ScaleCase: - grid: Grid - board: Polygon - nets: dict[str, CatalogNet] - obstacles: tuple[Polygon, ...] - references: dict[str, tuple[Move, ...]] - timing: DelayModel | None = None - groups: tuple[MatchGroup, ...] = () - windows: dict[str, Polygon] = field(default_factory=dict) - clearance: float = 1000.0 - cheaper_references: dict[str, tuple[Move, ...]] | None = None - - -def profile_holdout(matched: bool) -> ScaleCase: - """Two nearby lanes compete for a cheaper profile beside a long keepout.""" - grid = Grid((0, 0), 100, 1e-9) - lanes = {"bypass": 975_000, "through": 1_000_000} - if matched: - lanes["reference"] = 1_150_000 - nets = {name: CatalogNet(Pose(200_000, y, 0, "4"), Pose(4_800_000, y, 0, "4")) for name, y in lanes.items()} - enter_wide = Move("centered", traversal=("a", "b")) - exit_wide = Move("centered", traversal=("b", "a"), orientation=Orientation(180)) - widen = (enter_wide, Move("5-straight", steps=45_800), exit_wide) - left_up = Move("left-90", displacement=(10_000, 10_000)) - left_down = Move("left-90", displacement=(10_000, -10_000)) - right_up = Move("right-90", displacement=(10_000, 10_000)) - right_down = Move("right-90", displacement=(10_000, -10_000)) - references = { - "bypass": (left_up, right_up, Move("4-straight", steps=45_600), right_down, left_down), - "through": (Move("4-straight", steps=46_000),), - } - cheaper = { - "bypass": ( - right_down, Move("4-straight", steps=600), left_down, - enter_wide, Move("5-straight", steps=45_400), exit_wide, - left_up, Move("4-straight", steps=600), right_up, - ), - "through": widen, - } - timing = None - groups = () - if matched: - references["reference"] = cheaper["reference"] = widen - timing = DelayModel(1.55e-6, group_indices={"4": 4, "5": 4}, variant_delays={"centered": 40_000}) - groups = (MatchGroup("delay", {"through": 0, "reference": 0}, timing.wavelength, 0),) - return ScaleCase( - grid, box(0, 0, 5_000_000, 1_200_000), nets, (box(400_000, 900_000, 4_600_000, 990_000),), - references, timing, groups, cheaper_references=cheaper, - ) - - -def timing_case(name: str) -> ScaleCase: - grid = Grid((0, 0), 100, 1e-9) - if name == "tuning": - nets = { - net: CatalogNet(Pose(20_000, y, 0, "4"), Pose(140_000, y, 0, "4")) - for net, y in (("reference", 40_000), ("adjust", 120_000)) - } - timing = DelayModel(1.55e-6, group_indices={"4": 4}, fixed_contributions={"adjust": (20_000,)}) - group = MatchGroup("delay", {"reference": 0, "adjust": (80 * pi - 60) * 1000}, 1.55e-6, 50) - windows = {"adjust": box(40_000, 115_000, 100_000, 155_000)} - else: - nets = { - net: CatalogNet(Pose(20_000, y, 0, "4"), Pose(140_000, y, 0, "4")) - for net, y in (("reference", 40_000), ("adjust", 120_000), ("independent", 140_000)) - } - timing = DelayModel(1.55e-6, group_indices={"4": 4}) - group = MatchGroup("delay", {"reference": 0, "adjust": -1000}, 1.55e-6, 50) - windows = {"adjust": box(40_000, 115_000, 100_000, 155_000)} - return ScaleCase( - grid, box(0, 0, 400_000, 300_000), nets, (), {net: (Move("4-straight", steps=1200),) for net in nets}, - timing, (group,), windows, - ) - - -def corpus_lanes(name: str) -> ScaleCase: - from inire.tests.routing_corpus import CASE_GROUPS # noqa: PLC0415 - - case = "scale-bank-216-with-keepouts" if name == "corpus-lanes" else "scale-bank-224" - problem = CASE_GROUPS[case][0].problem - grid = Grid((0, 0), 100, 1e-9) - nets = { - net.net_id: CatalogNet( - Pose(1000 * net.start.x, 1000 * net.start.y, net.start.r, "4"), - Pose(1000 * net.target.x, 1000 * net.target.y, net.target.r, "4"), - ) - for net in problem.nets[:12] - } - references = {name: (Move("4-straight", steps=abs(net.target.x - net.start.x) // grid.pitch),) for name, net in nets.items()} - obstacles = tuple(scale(shape, xfact=1000, yfact=1000, origin=(0, 0)) for shape in problem.static_obstacles) - return ScaleCase( - grid, box(*(1000 * coord for coord in problem.bounds)), nets, obstacles, references, clearance=1000 * problem.clearance, - ) - - -def floorplan_case() -> ScaleCase: - """Build unseeded port pairs and rounded Manhattan references from authored waypoints.""" - grid = Grid((0, 0), 100, 1e-9) - radius_um = 10 - cardinal_headings = {step: heading for heading, step in HEADING_STEPS.items() if heading % 90 == 0} - nets: dict[str, CatalogNet] = {} - references: dict[str, tuple[Move, ...]] = {} - for bank, paths in NET_BANKS.items(): - for index, points in enumerate(paths, 1): - name = f"{bank}-{index}" - deltas = [(x1 - x0, y1 - y0) for (x0, y0), (x1, y1) in pairwise(points)] - directions = [((dx > 0) - (dx < 0), (dy > 0) - (dy < 0)) for dx, dy in deltas] - headings = [cardinal_headings[direction] for direction in directions] - source, destination = points[0], points[-1] - nets[name] = CatalogNet( - Pose(1000 * source[0], 1000 * source[1], headings[0], "4"), - Pose(1000 * destination[0], 1000 * destination[1], headings[-1], "4"), - ) - recipe: list[Move] = [] - for segment, (dx, dy) in enumerate(deltas): - has_corner = segment < len(deltas) - 1 - # Each rounded corner uses one radius of the incoming and outgoing straights. - length = abs(dx) + abs(dy) - radius_um * (int(segment > 0) + int(has_corner)) - if length < 0: - raise ValueError(f"Reference bend exceeds its setback on {name}") - if length: - recipe.append(Move("4-straight", steps=1000 * length // grid.pitch)) - if has_corner: - travel, onward = directions[segment:segment + 2] - turn = travel[0] * onward[1] - travel[1] * onward[0] - if not turn: - raise ValueError(f"Reference corner must be a quarter turn on {name}") - radius = 1000 * radius_um - offset = (radius * (travel[0] + onward[0]), radius * (travel[1] + onward[1])) - recipe.append(Move("left-90" if turn > 0 else "right-90", displacement=offset)) - references[name] = tuple(recipe) - - obstacles = ( - *(box(*(1000 * coordinate for coordinate in block)) for block in (*BLOCKS, *COMPONENTS)), - *(Polygon([(1000 * x, 1000 * y) for x, y in block]) for block in STEPPED_BLOCKS), - ) - return ScaleCase(grid, box(0, 0, 5_000_000, 5_000_000), nets, obstacles, references) - - -def scale_case(name: str) -> ScaleCase: - if name == "floorplan": - return floorplan_case() - if name in ("tuning", "retry"): - return timing_case(name) - if name in PROFILE_HOLDOUTS: - return profile_holdout(matched=name == "matched-cost-holdout") - if name in ("corpus-lanes", "corpus-open-lanes"): - return corpus_lanes(name) - grid = Grid((0, 0), 100, 1e-9) - obstacles = [ - box(x, y, x + 250_000, y + 140_000) - for j in range(8) for i in range(9) - for x, y in ((400_000 + 500_000 * i, 400_000 + 550_000 * j),) - ] - nets = { - f"lane-{row}-{lane}": CatalogNet(Pose(200_000, y, 0, "4"), Pose(4_800_000, y, 0, "4")) - for row in range(8) for lane in range(5) - for y in (170_000 + 550_000 * row + 20_000 * lane,) - } - references = {net: (Move("4-straight", steps=46_000),) for net in nets} - if name == "constrained": - obstacles[0] = box(400_000, 20_000, 650_000, 160_000) - special = "lane-0-0" - nets[special] = CatalogNet(Pose(200_000, 60_000, 0, "4"), Pose(4_800_000, 60_000, 0, "4")) - references[special] = ( - Move("4-straight", steps=1700), Move("right-90", displacement=(10_000, -10_000)), - Move("4-straight", steps=300), Move("left-90", displacement=(10_000, -10_000)), - Move("4-straight", steps=2800), Move("left-90", displacement=(10_000, 10_000)), - Move("4-straight", steps=300), Move("right-90", displacement=(10_000, 10_000)), - Move("4-straight", steps=41_100), - ) - if name == "diagonal-savings": - special = "lane-7-4" - nets[special] = CatalogNet(Pose(300_000, 4_500_000, 0, "4"), Pose(700_000, 4_700_000, 0, "4")) - references[special] = ( - Move("4-straight", steps=200), Move("left-90", displacement=(10_000, 10_000)), - Move("4-straight", steps=1800), Move("right-90", displacement=(10_000, 10_000)), Move("4-straight", steps=3600), - ) - if name == "diagonal": - special = "lane-7-4" - nets[special] = CatalogNet(Pose(300_000, 4_600_000, 45, "4"), Pose(500_000, 4_800_000, 45, "4")) - references[special] = (Move("4-straight", steps=2000),) - if name == "off-coarse": - grid = Grid((0, 0), 1, 1e-9) - nets = {"displaced": CatalogNet(Pose(20_001, 30_001, 0, "4"), Pose(170_001, 30_201, 0, "8"))} - references = {"displaced": (Move("displaced", traversal=("a", "b")), Move("8-straight", steps=50_000))} - return ScaleCase(grid, box(0, 0, 5_000_000, 5_000_000), nets, tuple(obstacles), references) - - -def catalog(mode: str, case: str) -> Catalog: - profiles = {"4": Profile("4 µm", 4000), "5": Profile("5 µm", 5000), "8": Profile("8 µm", 8000)} - variants: dict[str, StraightVariant | FixedVariant | BendVariant] = {"4-straight": StraightVariant("4", 1)} - if mode in ("typed", "octagonal"): - variants["5-straight"] = StraightVariant("5", 0.5) - variants["centered"] = FixedVariant( - "centered", - {"a": Pose(0, 0, 0, "4"), "b": Pose(10_000, 0, 180, "5")}, - (Polygon(((0, -2000), (10_000, -2500), (10_000, 2500), (0, 2000))),), - (("a", "b"), ("b", "a")), (Orientation(), Orientation(180)), 0.01, 10_000, - ) - if case in ("floorplan", "constrained", "diagonal-savings", "tuning", *PROFILE_HOLDOUTS): - variants["left-90"] = BendVariant("4", 90, 10_000, 0.01, sagitta=30) - variants["right-90"] = BendVariant("4", -90, 10_000, 0.01, sagitta=30) - if mode == "octagonal": - variants["left-45"] = BendVariant("4", 45, 10_000, 0.01, max_lead=200, lead_cost_per_cm=1, sagitta=30) - variants["right-45"] = BendVariant("4", -45, 10_000, 0.01, max_lead=200, lead_cost_per_cm=1, sagitta=30) - if case == "off-coarse": - variants["8-straight"] = StraightVariant("8", 0.2) - variants["displaced"] = FixedVariant( - "displaced", {"a": Pose(0, 0, 0, "4"), "b": Pose(100_000, 200, 180, "8")}, - (Polygon(((0, -2000), (100_000, -3800), (100_000, 4200), (0, 2000))),), - (("a", "b"),), (Orientation(),), 0.2, 100_010, - ) - return Catalog("scale", profiles, variants) - - -def _reference_cost(case: ScaleCase, technology: Catalog, recipes: dict[str, tuple[Move, ...]]) -> float: - if recipes.keys() != case.nets.keys(): - raise AssertionError("Reference layout must route every net") - evaluator = MoveEvaluator(case.grid, technology) - placed = {} - for name, recipe in recipes.items(): - net = case.nets[name] - path = replay_moves(evaluator, net.start, recipe) - if path is None: - raise AssertionError(f"Reference recipe did not evaluate for {name}") - placed[name] = path - for name, path in placed.items(): - net = case.nets[name] - occupied = tuple(shape for owner, other in placed.items() if owner != name for piece in other for shape in piece.footprints) - error = verify_path( - evaluator, path, net.start, net.target, board=case.board, keepouts=case.obstacles, occupied=occupied, clearance=case.clearance, - ) - if error is not None: - raise AssertionError(f"Invalid reference for {name}: {error}") - if case.cheaper_references is not None and case.timing is not None: - for group in case.groups: - timing = replace(case.timing, wavelength=group.wavelength) - choices = {} - for name in group.offsets: - delay = evaluate_delay(evaluator, placed[name], timing, net_id=name) - if delay is None: - raise AssertionError(f"Missing reference delay for {name}") - choices[name] = (DelayChoice(placed[name], delay),) - if not choose_match(group, choices)[2]: - raise AssertionError(f"Unmatched reference group {group.group_id}") - return fsum(piece.cost for path in placed.values() for piece in path) - - -def verify_references(case: ScaleCase, technology: Catalog) -> dict[str, float]: - cost = _reference_cost(case, technology, case.references) - if case.cheaper_references is None: - return {} - cheaper = _reference_cost(case, technology, case.cheaper_references) - if cheaper >= cost: - raise AssertionError("Cheaper reference must lower the total cost") - return {"original": cost, "cheaper": cheaper} - - -def bank_order_key(net: CatalogNet) -> tuple[int, int, bool, int, int]: - """Group by heading and put the outside of each lateral fan-out first.""" - start, target = net.start, net.target - dx, dy = HEADING_STEPS[start.heading] - start_side = dx * start.y - dy * start.x - shift = dx * target.y - dy * target.x - start_side - side = (shift > 0) - (shift < 0) - return start.heading, target.heading, shift != 0, side, -side * start_side - - -def run_catalog(case: ScaleCase, technology: Catalog, args: argparse.Namespace) -> tuple[dict, float]: - settings = LayoutSettings( - case.board, case.obstacles, clearance=case.clearance, node_limit=args.node_limit, refinement=not args.no_refinement, - guidance=None if args.guide_pitch is None else CoarseGuidance(args.guide_pitch), - retry_independent=not args.no_independent_retry, - constructive=args.constructive, - ) - start = perf_counter() - grid = case.grid - if args.auto_pitch is not None: - terminals = tuple(pose for net in case.nets.values() for pose in (net.start, net.target)) - grid = AutomaticGrid(args.auto_pitch, grid.meters_per_unit).select(terminals, technology) - result = route_layout( - MoveEvaluator(grid, technology), case.nets, settings, - timing=case.timing, groups=case.groups, windows=case.windows, - ) - elapsed = perf_counter() - start - paths = {name: result.routes[name].path or () for name in result.completed} - expanded = sum(attempt.expanded for attempt in result.attempts) - proposed = sum(attempt.proposed for attempt in result.attempts) - measurements = { - "proposals_per_expansion": proposed / expanded if expanded else None, - "completed": result.completed, - "verified": tuple(name for name, report in result.routes.items() if report.path is not None), - "matching": {name: asdict(report) for name, report in result.matching.items()}, - "outcomes": {name: report.outcome for name, report in result.routes.items()}, - "per_net": { - name: {"cost": result.routes[name].cost, "length_nm": result.routes[name].length} - for name in paths - }, - "routing_pitch_nm": grid.pitch, - "typed_improvements": sum(any(move.move.variant == "centered" for move in path) for path in paths.values()), - "used_guidance": sum(report.used_guidance for report in result.routes.values()), - "guide_fallbacks": sum(report.guide_fallback for report in result.routes.values()), - "profile_fallbacks": sum(report.profile_fallback for report in result.routes.values()), - "attempts": [asdict(attempt) for attempt in result.attempts], - } - if args.geometry: - measurements["polygons"] = { - name: [shape.wkb_hex for move in path for shape in move.footprints] for name, path in paths.items() - } - measurements["moves"] = {name: [asdict(piece.move) for piece in path] for name, path in paths.items()} - return measurements, elapsed - - -def run_native(case: ScaleCase, args: argparse.Namespace) -> tuple[dict, float]: - pitch = case.grid.pitch - specs = tuple( - NetSpec(name, Port(net.start.x // pitch, net.start.y // pitch, net.start.heading), - Port(net.target.x // pitch, net.target.y // pitch, net.target.heading), width=4000 / pitch) - for name, net in case.nets.items() - ) - problem = RoutingProblem( - tuple(value / pitch for value in case.board.bounds), specs, - tuple(scale(shape, xfact=1 / pitch, yfact=1 / pitch, origin=(0, 0)) for shape in case.obstacles), - clearance=case.clearance / pitch, - ) - rate = pitch * case.grid.meters_per_unit * 100 - radius = 10_000 / pitch - options = RoutingOptions( - search=SearchOptions( - node_limit=args.node_limit, max_straight_length=50_000, bend_radii=(radius,), sbend_radii=(), - terminal_jog_limit=args.native_jog_limit, - ), - objective=ObjectiveWeights(unit_length_cost=rate, bend_penalty=(0.01 - radius * pi / 2 * rate) * sqrt(radius / 10), danger_weight=0), - topology=TopologyOptions(mode="off"), - refinement=RefinementOptions(enabled=not args.no_refinement), - ) - start = perf_counter() - result = route(problem, options=options) - elapsed = perf_counter() - start - paths = {name: outcome.path for name, outcome in result.results_by_net.items() if outcome.is_valid} - metrics = result.metrics - measurements = { - "completed": tuple(paths), - "outcomes": {name: outcome.outcome for name, outcome in result.results_by_net.items()}, - "per_net": { - name: { - "cost": fsum(move.length * rate if move.move_type == "straight" else 0.01 for move in path), - "length_nm": fsum(move.length * pitch for move in path), - } - for name, path in paths.items() - }, - "expanded": metrics.nodes_expanded, - "proposed": metrics.moves_generated, - "proposals_per_expansion": metrics.moves_generated / metrics.nodes_expanded if metrics.nodes_expanded else None, - "geometry_cache_hits": metrics.move_cache_abs_hits + metrics.move_cache_rel_hits, - "geometry_cache_misses": metrics.move_cache_abs_misses + metrics.move_cache_rel_misses, - "exact_ray_checks": metrics.ray_cast_exact_geometry_checks, - } - if args.geometry: - measurements["polygons"] = { - name: [ - scale(shape, xfact=pitch, yfact=pitch, origin=(0, 0)).wkb_hex for move in path for shape in move.physical_geometry - ] for name, path in paths.items() - } - return measurements, elapsed - - -def main() -> None: - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--mode", choices=("native", "manhattan", "typed", "octagonal"), default="typed") - parser.add_argument( - "--case", default="floorplan", help="routing fixture (default: floorplan)", - choices=( - "floorplan", "aligned", "constrained", "diagonal-savings", "diagonal", "off-coarse", "tuning", "retry", - "corpus-lanes", "corpus-open-lanes", *PROFILE_HOLDOUTS, - ), - ) - parser.add_argument("--guide-pitch", type=int, help="coarse pitch in nanometers") - parser.add_argument("--auto-pitch", type=int, help="preferred pitch for automatic grid selection in nanometers") - parser.add_argument("--repeat", type=int, default=3) - parser.add_argument("--node-limit", type=int, default=1000) - parser.add_argument("--net-order", choices=("input", "bank"), help="order for routing nets (floorplan defaults to bank order)") - parser.add_argument("--native-jog-limit", type=int, help="jog or detour attempts per net during native warm start") - parser.add_argument("--constructive", action=argparse.BooleanOptionalAction, help="try constructive catalog routes first") - parser.add_argument("--no-refinement", action="store_true") - parser.add_argument("--no-independent-retry", action="store_true") - parser.add_argument("--geometry", action="store_true") - args = parser.parse_args() - if args.repeat < 1: - parser.error("--repeat must be positive") - if args.native_jog_limit is not None and (args.mode != "native" or args.native_jog_limit < 0): - parser.error("--native-jog-limit requires native mode and a nonnegative limit") - if args.case == "diagonal" and args.mode != "octagonal": - parser.error("The native-diagonal terminal case requires octagonal mode") - if args.case in PROFILE_HOLDOUTS and args.mode not in ("typed", "octagonal"): - parser.error("The profile holdouts require typed or octagonal mode") - if args.mode == "native" and ( - args.guide_pitch is not None or args.auto_pitch is not None - or args.case not in ("floorplan", "constrained", "aligned", "diagonal-savings", "corpus-lanes", "corpus-open-lanes") - ): - parser.error("Native mode needs a case with cardinal terminals on the explicit grid") - case = scale_case(args.case) - technology = catalog(args.mode, args.case) - reference_costs = verify_references(case, technology) - if args.net_order is None: - args.net_order = "bank" if args.case == "floorplan" else "input" - if args.net_order == "bank": - names = sorted(case.nets, key=lambda name: bank_order_key(case.nets[name])) - case = replace(case, nets={name: case.nets[name] for name in names}) - if args.mode == "native" and args.native_jog_limit is None: - args.native_jog_limit = 48 if args.case == "floorplan" else 0 - if args.constructive is None: - args.constructive = args.case in ("floorplan", *PROFILE_HOLDOUTS) and args.mode != "native" - samples = [] - measurements = {} - for _ in range(args.repeat): - measurements, elapsed = run_native(case, args) if args.mode == "native" else run_catalog(case, technology, args) - samples.append(elapsed) - elapsed = median(samples) - total_cost = fsum(entry["cost"] for entry in measurements["per_net"].values()) - print(json.dumps({ - "options": vars(args), "machine": platform.machine(), "python": platform.python_version(), "requested": len(case.nets), - "wall_seconds": samples, "median_seconds": elapsed, "peak_rss": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss, - "catalog_cost": total_cost, "time_cost_squared": elapsed * total_cost**2 if measurements["completed"] else None, - **({"reference_costs": reference_costs} if reference_costs else {}), - **measurements, - }, indent=2)) - - -if __name__ == "__main__": - main() diff --git a/scripts/capture_legacy_routing.py b/scripts/capture_legacy_routing.py deleted file mode 100644 index 0bd812d..0000000 --- a/scripts/capture_legacy_routing.py +++ /dev/null @@ -1,100 +0,0 @@ -"""Capture routes and deterministic work on the legacy corpus and holdouts.""" - -import argparse -import json -import platform -import subprocess -from dataclasses import asdict, replace -from importlib.metadata import version -from pathlib import Path -from statistics import median -from time import perf_counter - -import shapely - -from inire import route -from inire.tests.routing_corpus import automatic_options, benchmark_weighted_length, profile_options, select_cases - - -def capture(repeat: int, revision: str | None) -> dict: - cases = select_cases(("corpus", "retry-holdout")) - runs = {} - for case in cases: - options = automatic_options(profile_options(case, "corpus-regression"), "corpus-regression") - attempts = {"automatic": options} - if case.problem.initial_paths: - attempts["verify-only"] = replace(options, search=replace(options.search, node_limit=0)) - for mode, settings in attempts.items(): - key = f"{case.name}:{mode}" - timings = [] - reference = None - stable = True - for _ in range(repeat): - started = perf_counter() - run = route(case.problem, options=settings) - timings.append(perf_counter() - started) - metrics = asdict(run.metrics) - sample = { - "options": repr(settings), - "metrics": {key: value for key, value in metrics.items() if not key.endswith("_ns")}, - "results": { - net_id: { - "verified": result.is_valid, - "outcome": result.outcome, - "effective_net": repr(result.effective_net), - "path": [ - { - "move": repr(move.move_spec), - "start": move.start_port.as_tuple(), - "end": move.end_port.as_tuple(), - "length": move.length, - "physical_wkb": [shape.wkb_hex for shape in move.physical_geometry], - } - for move in result.path - ], - } - for net_id, result in run.results_by_net.items() - }, - "benchmark_weighted_length": sum( - benchmark_weighted_length(result) for result in run.results_by_net.values() if result.is_valid - ), - } - if reference is None: - reference = sample - elif reference != sample: - stable = False - assert reference is not None - elapsed = median(timings) - has_verified = any(result["verified"] for result in reference["results"].values()) - runs[key] = { - **reference, "wall_seconds": elapsed, "wall_samples": timings, "stable": stable, - "time_cost_squared": elapsed * reference["benchmark_weighted_length"]**2 if has_verified else None, - } - return { - "revision": revision or subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip(), - "tracked_worktree": ( - subprocess.check_output(["git", "status", "--short", "--untracked-files=no"], text=True).splitlines() - if revision is None else [] - ), - "versions": { - "python": platform.python_version(), - "geos": shapely.geos_version_string, - **{name: version(name) for name in ("numpy", "scipy", "shapely", "rtree")}, - }, - "runs": runs, - } - - -def main() -> None: - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("output", type=Path) - parser.add_argument("--repeat", type=int, default=1) - parser.add_argument("--revision", help="source revision when running against a Git archive") - args = parser.parse_args() - if args.repeat < 1: - parser.error("--repeat must be positive") - args.output.write_text(json.dumps(capture(args.repeat, args.revision), indent=2) + "\n") - - -if __name__ == "__main__": - main() diff --git a/scripts/catalog_floorplan.py b/scripts/catalog_floorplan.py deleted file mode 100644 index 6782b76..0000000 --- a/scripts/catalog_floorplan.py +++ /dev/null @@ -1,98 +0,0 @@ -"""Synthetic photonic floorplan for the catalog routing scale benchmark.""" - -# Coordinates in micrometers. Each bank lists source-to-destination waypoint sequences. -NET_BANKS = { - "west-launch": ( - ((180, 430), (1080, 430)), - ((180, 454), (1520, 454)), - ((180, 478), (740, 478), (740, 518), (1660, 518)), - ((180, 502), (675, 502), (675, 548), (1660, 548)), - ((180, 526), (610, 526), (610, 588), (1660, 588)), - ((180, 550), (545, 550), (545, 628), (1660, 628)), - ((180, 574), (478, 574), (478, 668), (1660, 668)), - ((180, 598), (414, 598), (414, 711), (1520, 711)), - ), - "shared-trunk": ( - ((260, 1160), (1090, 1160), (1090, 1288), (2140, 1288)), - ((260, 1198), (1010, 1198), (1010, 1302), (2140, 1302)), - ((260, 1236), (930, 1236), (930, 1316), (2140, 1316)), - ((260, 1274), (850, 1274), (850, 1330), (2140, 1330)), - ((260, 1312), (775, 1312), (775, 1344), (2140, 1344)), - ((260, 1358), (2140, 1358)), - ), - "east-output": ( - ((2570, 2025), (3790, 2025), (3790, 1977), (4190, 1977), (4190, 2025), (4780, 2025)), - ((2670, 2050), (4780, 2050)), - ((2740, 2080), (3510, 2080), (3510, 2110), (4780, 2110)), - ((2740, 2110), (3420, 2110), (3420, 2160), (4780, 2160)), - ((2740, 2140), (3330, 2140), (3330, 2210), (4780, 2210)), - ), - "east-feedback": ( - ((4710, 2570), (2880, 2570)), - ((4710, 2606), (2470, 2606)), - ((4710, 2642), (3790, 2642), (3790, 2702), (2470, 2702)), - ((4710, 2678), (3860, 2678), (3860, 2752), (2470, 2752)), - ((4710, 2714), (3930, 2714), (3930, 2802), (2470, 2802)), - ), - "north-monitor": ( - ((608, 2110), (608, 4560)), - ((648, 2110), (648, 4560)), - ((688, 2110), (688, 3210), (752, 3210), (752, 4560)), - ((728, 2110), (728, 3080), (797, 3080), (797, 4560)), - ((768, 2110), (768, 2950), (842, 2950), (842, 4560)), - ((808, 2230), (808, 2880), (895, 2880), (895, 4560)), - ), - "south-access": ( - ((2970, 1730), (2970, 240)), - ((3030, 1730), (3030, 240)), - ((3100, 1660), (3100, 1080), (3170, 1080), (3170, 240)), - ((3160, 1660), (3160, 1180), (3230, 1180), (3230, 240)), - ((3220, 1660), (3220, 1280), (3290, 1280), (3290, 240)), - ((3530, 1050), (3530, 720)), - ), - "upper-transfer": ( - ((2700, 3300), (3890, 3300), (3890, 4440)), - ((2700, 3365), (3790, 3365), (3790, 4470)), - ((2700, 3430), (3690, 3430), (3690, 4500)), - ((2700, 3495), (3590, 3495), (3590, 4530)), - ), -} - -# Large keepouts reserve device, electronics, and thermal regions. -BLOCKS = ( - (1220, 955, 1610, 1282), - (1250, 1364, 1660, 1745), - (1800, 435, 2240, 815), - (2050, 1480, 2520, 1830), - (2560, 675, 2840, 1210), - (1870, 2960, 2360, 3370), - (2900, 3650, 3435, 3960), - (4190, 3180, 4530, 3530), - (3970, 1135, 4420, 1470), - (3320, 2280, 3590, 2510), - (1110, 2510, 1430, 2930), - (1140, 3730, 1470, 4170), - (1960, 3970, 2310, 4235), - (113, 1590, 420, 1850), -) -# Local device and pad banks are regular within each cluster and vary between clusters. -COMPONENTS = ( - (100, 268, 165, 394), (100, 416, 160, 494), (98, 510, 160, 573), (105, 594, 160, 671), - (165, 1125, 238, 1214), (171, 1234, 238, 1312), (169, 1332, 238, 1401), - (4788, 1954, 4880, 2054), (4788, 2070, 4880, 2190), (4788, 2206, 4880, 2270), - (4730, 2485, 4820, 2589), (4730, 2600, 4820, 2700), (4730, 2712, 4820, 2770), - (512, 4580, 625, 4670), (639, 4580, 701, 4670), (716, 4580, 817, 4670), (832, 4580, 924, 4670), - (2910, 115, 3005, 221), (3018, 115, 3122, 221), (3135, 115, 3232, 221), (3245, 115, 3320, 221), - (3480, 4560, 3610, 4690), (3626, 4540, 3730, 4690), (3744, 4520, 3945, 4690), - (1580, 2380, 1672, 2494), (1695, 2398, 1777, 2512), (1805, 2388, 1889, 2502), - (2510, 2980, 2610, 3180), (2640, 2930, 2824, 3130), (2870, 2912, 2980, 3090), - (4020, 375, 4170, 490), (4200, 410, 4330, 610), (4375, 505, 4490, 650), (4530, 580, 4630, 680), - (3890, 2005, 4090, 2039), - (3490, 1080, 3580, 1210), (3500, 533, 3640, 678), (3700, 654, 3820, 866), - (595, 1940, 682, 2070), (700, 1955, 787, 2070), (801, 1990, 886, 2150), - (1700, 4630, 1800, 4755), (1830, 4600, 1950, 4755), (1980, 4555, 2150, 4730), -) -STEPPED_BLOCKS = ( - ((800, 759), (1150, 759), (1150, 925), (1020, 925), (1020, 1025), (800, 1025)), - ((3950, 3820), (4420, 3820), (4420, 4180), (4140, 4180), (4140, 4330), (3950, 4330)), -)