Improve verified routing cost and runtime

Use verified terminal and column constructions, cheaper straight profiles, and tighter cost bounds to reduce routing work. Reuse geometry in clearance checks and tuning while retaining verified coverage and timing constraints.

Report median routing time times squared cost in the benchmark tools and record the comparisons and regression coverage.
This commit is contained in:
Jan Petykiewicz 2026-12-05 12:05:07 -08:00
commit 13594632d4
17 changed files with 1022 additions and 135 deletions

View file

@ -40,12 +40,28 @@ 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. **Search and time.** Compare expansions and repeated wall times at the same settings. Constructive stages can spend time planning and verifying even with zero expansions. Inspect the [automatic reports](routing-diagnostics.md#automatic-reports) to find which stage performed the work.
3. **Time and cost.** On identical verified net sets, compare median routing time × total cost². The legacy capture uses benchmark-weighted length and the catalog benchmark uses catalog cost. Compare expansion counts and inspect the [automatic reports](routing-diagnostics.md#automatic-reports) when the score changes. Constructive stages can spend time planning and verifying even with zero expansions.
## Capture legacy parity
Run `PYTHONPATH=. python scripts/capture_legacy_routing.py /tmp/inire-parity.json --repeat 3` from the checkout under test. Compare against revision `3b3d1c7` to measure the change to the move evaluator. To capture a Git archive, run the same script by absolute path from the extracted source tree and pass `--revision 3b3d1c7`. The capture records the effective ports, ordered moves, lengths, physical polygons, work counters, options, dependencies, and elapsed time. Use the same dependencies and compare route and work fields independently of elapsed time. The comparison covered 154 cases and modes with three repetitions per checkout and used Python 3.13.18, GEOS 3.13.1, NumPy 2.4.2, SciPy 1.17.1, Shapely 2.1.2, and Rtree 1.4.1. All recorded outcomes, routes, polygons, and deterministic work counters agreed. The sum of the per-case median times was 21.87 s at the reference revision and 21.88 s with the evaluation boundary.
### Weighted column routing
Under the corpus weights, verified quarter-turn layouts reduced weighted length by 70–75% on five ordered column fixtures. Across eleven interleaved runs per fixture, time × cost² fell by 64–94%. The largest time increase was on `complex-column-6x3`, from 52 ms to 298 ms. Its weighted length fell from 64,043 to 16,052. A three-repeat comparison across 152 automatic cases verified the same 2,245 net IDs. The other 147 cases retained identical routes and polygons.
For dense fields, the quarter-turn planner intersects apertures across neighboring columns when the gap cannot fit a jog. The S-bend planner only considers unchanged track rows in windows too short for an S-bend and reuses aperture profiles and bend-spacing measurements. Compared with the previous planner in eleven interleaved runs, `scale-field-16x16` fell from 183 to 153 ms and from 3,319 to 2,678 weighted length, lowering time × cost² by 46%. Physical length rose from 1,983 to 2,112 µm. The same score fell by 53% on `holdout-uneven-bypass` and 14% on `bypass-mixed-width`, with identical routes and costs on both.
After verifying a weighted S-bend column layout, the planner checks whether a straight can replace an excursion that returns to the same track. Indexed geometry rejects blocked shortcuts before replay. The replacement keeps both endpoint poses and must satisfy the board, keepout, peer-route, and self-clearance checks. Across the 152 automatic cases, this shortened routes on four boards and retained the same 2,245 verified net IDs. In eleven interleaved runs per case, time × cost² fell by 36% on `bypass-opposed-banks`, 19% on `bypass-three-branches`, 18% on `holdout-uneven-bypass`, and 3% on `bypass-long-dividers`.
### Terminal detours and refinement
The weighted native planner can compare a four-turn detour with a verified S-bend route between aligned ports. On `precision-forward-large-radius` the winning route uses four quarter turns at the configured radius. Weighted length fell from 4,290 to 2,513 and physical length rose from 433 to 628 µm. In eleven interleaved runs, median time rose from 49 to 56 ms and time × cost² fell by 61%.
Native refinement checks the center straight of a proposed dogleg before placing its bends. In the same comparison, `complex-column-6x3` took 59% less time and `stress-refine-alternating-doglegs` took 72% less time. Both kept the same verified geometry and cost. Across the 152 automatic cases, the same 2,245 net IDs verified, and `precision-forward-large-radius` was the sole geometry change.
When disjoint terminal conflicts set the coverage limit, automatic routing can try short terminal links and jogs, checking each route against the occupied board. If a seeded replay reaches the certified limit, the planner can skip the detailed search. On `lidar-clements-8x8`, nine interleaved runs reduced the median from 772 ms to 8 ms. Both versions verified the same three routes at the same weighted cost.
## Catalog scale benchmarks
The default `floorplan` case represents a synthetic single-layer photonic layout on a 5 × 5 mm die at 100 nm pitch. It uses 40 nets across seven port banks, with mixed approach directions, staggered fan-outs, and a short local connection. The 60 keepouts cover 11.0% of the die and represent clustered device and pad banks, larger electronics and thermal regions, and stepped block boundaries. Six reference routes pass through an 82 µm gap between two blocks. A separate keepout forces one aligned eastbound connection to detour. The frozen reference paths range from 0.33 to 2.52 mm. Each is verified against the board, keepouts, and the other reference paths before timing unseeded search. [Floorplan coordinates](../scripts/catalog_floorplan.py)
@ -59,30 +75,34 @@ PYTHONPATH=. python scripts/benchmark_catalog_routing.py --case floorplan --mode
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 launch positions around keepouts and peer routes. [Native search options](user/api-reference.md#searchoptions)
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, and two-turn candidates before falling back to detailed search. After placing the routes, they try cheaper collinear profile changes with the installed routes in place. 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.
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, and per-net cost and physical length. Compare costs on the intersection of the completed net sets. Catalog reports also include work from discarded search attempts and budgeted retries.
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 five unseeded runs per setting on an AMD Ryzen 9 5900X with a 1,000-node detailed-search limit. Routing time includes final verification. All four modes verified all 40 nets, including the six in the shared passage, with both refinement settings.
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.37 s | 0.37 s | 0.49 s | 8.0379 |
| Single-profile catalog Manhattan | 0.81 s | 0.74 s | 1.27 s | 8.0379 |
| Typed Manhattan | 1.50 s | 2.31 s | 2.40 s | 6.3917 |
| Octagonal | 2.00 s | 1.64 s | 2.47 s | 6.3881 |
| 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 |
Catalog cost was the same under both refinement settings. Compared with the prior 40-net results for each mode and setting, every route matched or improved its physical length and catalog cost, and the minimum clearances were unchanged. The typed and octagonal runs used profile changes on 26 nets each. The octagonal layouts retained their 45° bends.
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.
Fresh Python invocations with refinement enabled and `--repeat 1` took 0.94–3.08 s across the four modes, including startup, reference verification, and JSON output.
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
@ -99,6 +119,8 @@ The following constrained-case runs used an AMD Ryzen 9 5900X and a 1000-node de
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.
@ -117,7 +139,7 @@ PYTHONPATH=. python scripts/benchmark_catalog_routing.py --case retry --no-refin
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.
On the same machine the tuning case matched both routes at zero residual skew in a median of 1.59 s with the shared tuning and retry budget. The first pass examined 1334 proposals, with 524 verified replacements from one eligible span. The released-reservation case completed one independent route with retry and zero with retry disabled, at 1.17 s and 1.15 s median respectively.
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.
## Catalog acceptance checks

View file

@ -94,7 +94,7 @@ For structured logging, `dataclasses.asdict(run)` preserves the per-net fields.
| `proximity_range` | `10.0` | Obstacle proximity scoring range in layout units. Scale it with the coordinates when changing units. Large perimeters use an exact boundary index once the sample budget is reached. |
| `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. For parallel ports with a lateral offset, it also caps the number of two-turn launch positions checked per net. Zero skips this planning step. |
| `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,9 +153,11 @@ Increase the iteration limit when later reroutes might resolve conflicts. Adjust
| `guide_strength` | `0.75` | Maximum added guidance cost per unit length. Explicit guide and seed runs with at least two configured congestion iterations may try one additional iteration from the start with zero guidance cost. The retry retains corridor move proposals and wins only with higher verified coverage. |
| `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 a second column-planning pass based on route cost when the first pass chains short S-bends. Use `"always"` to try both passes or `"never"` to plan by span alone. |
| `automatic_cost` | `"selective"` | Try weighted column planning when the span planner chains short S-bends. Explicit length weights that put a premium on S-bends can also trigger a verified quarter-turn column candidate, including through shared apertures where adjacent columns leave too little room for a jog, or a detour between aligned ports for a single net. Use `"always"` to run both S-bend planning passes or `"never"` to plan by span alone. |
| `automatic_length_weights` | `None` | Optional straight, 90-degree bend, and S-bend length multipliers for automatic candidate selection. The default uses the search objective. |
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`.

View file

@ -5,20 +5,25 @@ 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 box
from shapely.geometry import LineString, box
from shapely.strtree import STRtree
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 (
@ -26,6 +31,7 @@ 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 (
@ -42,7 +48,7 @@ from inire.router._seed_materialization import materialize_path_seed, seed_prepa
from inire.router._stack import RoutingAttempts
from inire.router.cost import build_native_cost_evaluator, weighted_path_length
from inire.router.refiner import PathRefiner
from inire.seeds import SBendSeed
from inire.seeds import PathSeed, SBendSeed, StraightSeed
if TYPE_CHECKING:
from collections.abc import Callable, Iterable, Iterator
@ -54,7 +60,6 @@ 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]
@ -63,6 +68,8 @@ 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:
@ -255,14 +262,40 @@ 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):
@ -283,6 +316,27 @@ 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)
@ -535,12 +589,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) -> bool:
def _try_column_jogs(self, options: RoutingOptions, trials: list[Trial], target: int, *, merge_close: bool = False) -> 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):
for seeds in column_jog_candidates(problem, options.search, limit_per_pass=8, merge_close=merge_close):
trial = self._verify(replace(problem, initial_paths=seeds), "column-jogs")
if len(trial.valid_costs) == target:
trials.append(trial)
@ -707,6 +761,35 @@ 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(
@ -740,6 +823,105 @@ 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 execute(self) -> RoutingRunResult:
started = perf_counter()
options = self.options
@ -769,8 +951,12 @@ 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)
refinement_choice = self._refine(trials)
best = refinement_choice or _best_trial(trials)
metrics = self.attempts.metrics()

View file

@ -4,29 +4,30 @@ from __future__ import annotations
from dataclasses import dataclass, field, replace
from itertools import combinations
from math import fsum, inf, isfinite
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, MoveEvaluator, _require_integer
from inire._catalog import HEADING_STEPS, Move, MoveEvaluator, _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 face_reservation, replay_moves, validate_attachment, verify_path
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, Move, Pose
from inire._catalog import Evaluation, Pose
from inire._catalog_timing import Delay, DelayModel
from ._catalog_guidance import CoarseGuidance
@ -114,6 +115,7 @@ class _LayoutSearch:
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]
@ -127,6 +129,7 @@ class _LayoutSearch:
"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:
@ -204,7 +207,7 @@ class _LayoutSearch:
original = path[index]
best = (original,)
best_cost = original.cost
for recipe in straight_replacements(self.evaluator, original):
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:
@ -219,6 +222,16 @@ class _LayoutSearch:
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)
@ -228,6 +241,54 @@ class _LayoutSearch:
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
@ -552,10 +613,9 @@ def _route_attempt(
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
)
if settings.constructive:
for name in order:
if name not in members:
routing.improve_straights(name)
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

View file

@ -2,15 +2,16 @@
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, isfinite
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, Move, Pose, StraightVariant, _require_integer
from inire._catalog import HEADING_STEPS, BendVariant, Move, Pose, StraightVariant, _require_integer
from inire.geometry.collision import _violates_net_clearance
from ._catalog_verify import (
@ -18,7 +19,7 @@ from ._catalog_verify import (
verify_move, verify_path, wholly_in_attachment,
)
from ._jog import jog_launch_steps
from ._jog import detour_blocker_spans, jog_launch_steps
if TYPE_CHECKING:
from collections.abc import Iterator, Sequence
@ -29,7 +30,7 @@ if TYPE_CHECKING:
from inire._catalog import Evaluation, MoveEvaluator
from ._catalog_guidance import Corridor
from ._catalog_verify import Attachment
from ._catalog_verify import Attachment, VerificationCache
@dataclass(frozen=True, slots=True)
@ -101,6 +102,15 @@ class _PendingMove:
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:
@ -123,10 +133,9 @@ def path_recipe(path: Sequence[Evaluation]) -> tuple[Move, ...]:
return tuple(recipe)
def straight_replacements(evaluator: MoveEvaluator, original: Evaluation) -> Iterator[tuple[Move, ...]]:
def straight_replacements(evaluator: MoveEvaluator, start: Pose, original: Move) -> Iterator[tuple[Move, ...]]:
"""Offer cheaper straight variants and centered profile changes on the same axis."""
start = original.start
steps = original.move.steps
steps = original.steps
if steps is None:
return
pitch = int(evaluator.grid.pitch)
@ -143,7 +152,7 @@ def straight_replacements(evaluator: MoveEvaluator, original: Evaluation) -> Ite
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.move.variant:
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)
@ -195,6 +204,7 @@ class _Proposals:
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
@ -202,7 +212,8 @@ class _Proposals:
self.clearance = clearance
self.guide_points = corridor.points if corridor is not None else ()
self.scan_steps = scan_steps
self.blocker_bounds = tuple(shape.bounds for shape in blockers if not shape.is_empty)
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] = {}
@ -218,11 +229,20 @@ class _Proposals:
(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 profiles:
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):
@ -326,7 +346,7 @@ class _Proposals:
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[Move, ...]]:
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:
@ -388,10 +408,10 @@ class _Proposals:
assert not isinstance(variant, StraightVariant)
price += variant.cost
candidates.append((price, before, recipe))
for _, _, recipe in sorted(candidates, key=lambda item: item[:2]):
yield recipe
for price, _, recipe in sorted(candidates, key=lambda item: item[:2]):
yield price, recipe
def direct_recipes(self, start: Pose) -> Iterator[tuple[Move, ...]]:
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]
@ -405,7 +425,7 @@ class _Proposals:
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 (Move(variant, steps=steps),)
yield unit * self._straight_prices[variant] * steps * hypot(ux, uy), (Move(variant, steps=steps),)
if not divisor:
return
candidates = []
@ -418,7 +438,9 @@ class _Proposals:
if lead_rem or tail_rem or min(lead, tail) < 0:
continue
recipe: list[Move] = []
cost = self._fixed_offsets[start.profile, start.heading][move][1]
fixed = self.evaluator.catalog.variants[move.variant]
assert not isinstance(fixed, StraightVariant)
cost = fixed.cost
if lead:
if not start_straights:
continue
@ -433,8 +455,145 @@ class _Proposals:
recipe.append(Move(variant, steps=tail))
cost += self._straight_prices[variant] * tail * hypot(vx, vy) * unit
candidates.append((cost, tuple(recipe)))
for _, recipe in sorted(candidates, key=lambda item: item[0]):
yield 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) -> 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)
}
# 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 = []
unit_price = self._straight_prices[straight] * self.evaluator.grid.meters_per_unit * 100
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))
full_span = (*out_moves, Move(straight, steps=center // pitch), *in_moves)
candidates.append((cost, lane, True, full_span))
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)
@ -602,6 +761,7 @@ def search_path(
scan_steps: bool = False,
bias: SearchBias | None = None,
method: Literal["detailed", "constructive_first", "constructive_only"] = "detailed",
cache: VerificationCache | None = None,
) -> SearchResult:
"""Search physical paths while retaining a bounded number of distinct arrival histories."""
_require_integer(node_limit)
@ -621,26 +781,38 @@ def search_path(
attached[id(attachment.obstacle)] = attachment.obstacle
seam = face_reservation(pose, evaluator.catalog.profiles[pose.profile].width, face_tolerance)
end_permissions.append((attachment, seam, source))
ordinary_keepouts = STRtree([obstacle for obstacle in keepouts if id(obstacle) not in attached])
installed = 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
proposals = _Proposals(evaluator, start, target, (*keepouts, *occupied), clearance, corridor, scan_steps)
proposals = _Proposals(evaluator, start, target, (*keepouts, *occupied), clearance, corridor, scan_steps, cache)
origin = start.x, start.y, start.heading, start.profile
initial_bound = proposals.lower_bound(origin)
if initial_bound == inf or initial_bound > max_cost + COST_TOLERANCE:
return SearchResult(None, "exhausted", 0, 0)
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":
recipes = chain(proposals.direct_recipes(start), recipes)
for recipe in islice(recipes, min(node_limit // 2, 48)):
recipes = chain(proposals.direct_recipes(start), recipes, proposals.detour_recipes(start))
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:
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)
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)
@ -650,17 +822,29 @@ def search_path(
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,
source_attachment=source_attachment, destination_attachment=destination_attachment, cache=cache, defer_faces=True,
) is None:
incumbent = path
max_cost = cost
if method == "constructive_first":
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),
@ -751,7 +935,7 @@ def search_path(
) 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,
source_attachment=source_attachment, destination_attachment=destination_attachment, cache=cache,
) is None:
return SearchResult(
path, "verified", expanded, proposed, geometry_checks=geometry_checks,

View file

@ -5,7 +5,7 @@ from __future__ import annotations
from collections import deque
from dataclasses import replace
from itertools import product
from math import ceil, floor
from math import ceil, floor, inf
from typing import TYPE_CHECKING
from shapely import get_parts
@ -23,7 +23,7 @@ if TYPE_CHECKING:
from shapely.geometry import Polygon
from inire._catalog import Evaluation, MoveEvaluator
from inire._catalog import Evaluation, MoveEvaluator, Pose
from inire._catalog_timing import DelayModel
from ._catalog_matching import MatchGroup
@ -96,6 +96,13 @@ def _doglegs(
)
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)
@ -105,7 +112,6 @@ def _doglegs(
if remainder or lateral_remainder or forward < 0:
yield None
continue
begin = start.shifted(first * dx * pitch, first * dy * pitch)
for height in range(max(0, -sideways), width_limit + 1):
return_height = height + sideways
legs = (height, forward, return_height, 0)
@ -114,18 +120,12 @@ def _doglegs(
replacement.append(turn_move)
if leg:
replacement.append(Move(straight_name, steps=leg))
trial = replay_moves(evaluator, begin, replacement)
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
prefix = ()
suffix = ()
if first:
prefix = replay_moves(evaluator, start, (Move(straight_name, steps=first),))
assert prefix is not None
if last < steps:
suffix = replay_moves(evaluator, trial[-1].end, (Move(straight_name, steps=steps - last),))
assert suffix is not None
yield (*prefix, *trial, *suffix)
def tune_group(
@ -158,6 +158,12 @@ def tune_group(
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()
@ -167,12 +173,23 @@ def tune_group(
continue
pending.append((net, generator))
proposed += 1
if path is None or not verifies(net, path):
if path is None or (verify_first and not verifies(net, path)):
continue
accepted += 1
delay = evaluate_delay(evaluator, path, model, net_id=net)
if delay is not None and delay.optical_length > choices[net][0].delay.optical_length:
choices[net].append(DelayChoice(path, delay))
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()}

View file

@ -6,8 +6,9 @@ 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, box
from shapely.geometry import LineString, Polygon
from shapely.strtree import STRtree
from inire._catalog import HEADING_STEPS, face_endpoints
@ -30,6 +31,43 @@ class Attachment:
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,
@ -147,11 +185,12 @@ def _matches_face(
def compatible_join(left: Evaluation, right: Evaluation, width: float, tolerance: float) -> bool:
if left.end != right.start:
return False
seam = face_reservation(left.end, width, tolerance)
for first in left.port_shapes or left.footprints:
for second in right.port_shapes or right.footprints:
if first.relate_pattern(second, "2********") and not _seam_covers(seam, first.intersection(second)):
return False
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
@ -165,19 +204,35 @@ def _internal_edges(path: Sequence[Evaluation], clearance: float) -> Iterable[tu
yield i, j, clearance if uncertain or separation >= clearance else 0.0
def _colliders(tree: STRtree, shapes: Sequence[BaseGeometry], clearance: float) -> tuple[BaseGeometry, ...]:
def _colliders(
tree: STRtree, shapes: Sequence[BaseGeometry], clearance: float, cache: VerificationCache | None = None,
) -> tuple[BaseGeometry, ...]:
if not len(tree) or not shapes:
return ()
bounds = [extent for shape in shapes if not isnan((extent := shape.bounds)[0])]
if not bounds:
return ()
area = box(
min(b[0] for b in bounds) - clearance, min(b[1] for b in bounds) - clearance,
max(b[2] for b in bounds) + clearance, max(b[3] for b in bounds) + clearance,
)
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,
@ -186,10 +241,14 @@ def verify_move(
occupied: Sequence[BaseGeometry],
clearance: float,
face_tolerance: float,
cache: VerificationCache | None = None,
*,
check_faces: bool = True,
) -> str | None:
profiles = evaluator.catalog.profiles
for pose, arrival in ((move.start, False), (move.end, True)):
if not _matches_face(move.port_shapes or move.footprints, pose, profiles[pose.profile].width, face_tolerance, arrival=arrival):
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"
@ -214,6 +273,8 @@ def verify_path(
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)):
@ -222,15 +283,16 @@ def verify_path(
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}
ordinary_keepouts = STRtree([obstacle for obstacle in keepouts if id(obstacle) not in attached])
installed = STRtree(occupied)
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)):
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:
@ -245,16 +307,22 @@ def verify_path(
for move in path:
if error := verify_move(
evaluator, move, board,
_colliders(ordinary_keepouts, move.footprints, clearance), _colliders(installed, move.footprints, clearance),
clearance, face_tolerance,
_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 occupied):
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):
@ -266,14 +334,22 @@ 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
placements = []
path = []
for move in moves:
evaluated = evaluator.evaluate(move, current)
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
placements.append(evaluated)
path.append(evaluated)
current = evaluated.end
return tuple(placements)
return tuple(path)

View file

@ -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 combinations_with_replacement, islice, pairwise, product
from itertools import accumulate, combinations_with_replacement, islice, pairwise, product
from math import acos, ceil, comb, cos, floor, gcd, isfinite, pi, sin
from typing import TYPE_CHECKING
@ -25,6 +25,7 @@ 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
@ -39,6 +40,27 @@ _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
@ -137,13 +159,41 @@ def column_partition_budget_exceeded(problem: RoutingProblem) -> bool:
return bool(tracks) and _partition_budget_exceeded(tracks, _track_columns(problem, tracks)[2])
def _column_layout(problem: RoutingProblem, *, min_tracks: int = 3) -> _ColumnLayout | None:
def _merge_close_columns(columns: tuple[_Column, ...], minimum_gap: int) -> tuple[_Column, ...]:
"""Intersect apertures across gaps shorter than a jog's forward span."""
merged: list[_Column] = []
for column in columns:
if not merged or column.span[0] - merged[-1].span[1] >= minimum_gap:
merged.append(column)
continue
previous = merged[-1]
left, right = iter(previous.openings), iter(column.openings)
a, b = next(left, None), next(right, None)
shared = []
while a is not None and b is not None:
low, high = max(a[0], b[0]), min(a[1], b[1])
if low < high:
shared.append((low, high))
if a[1] <= b[1]:
a = next(left, None)
else:
b = next(right, None)
merged[-1] = _Column((previous.span[0], column.span[1]), tuple(shared))
return tuple(merged)
def _column_layout(problem: RoutingProblem, *, min_tracks: int = 3, merge_gap: int = 0) -> _ColumnLayout | None:
tracks = _ordered_tracks(problem)
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))
@ -416,6 +466,18 @@ 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]],
@ -428,6 +490,7 @@ 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(
@ -435,6 +498,8 @@ 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.
@ -447,21 +512,19 @@ def _schedules(
lower, upper = choose(da, window - 4), choose(db, window - 4)
assert lower is not None
assert upper is not None
# 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)
return distance(lower, upper, window, gap) >= need + 0.025
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 rows:
for row in eligible_rows:
scores = []
for previous, histories in approaches.items():
predecessors = approaches.items() if can_shift else ((row, approaches[row]),)
for previous, histories in predecessors:
offsets = tuple(b - a for a, b in zip(previous, row, strict=True))
if straight_tracks and any(offsets[i] for i in straight_tracks):
continue
@ -538,8 +601,15 @@ def _column_sbend_schedules(
limits = (min(2 * radius - 1, ceil(radius * frac)) for frac in (0.8, 0.4, 1.44))
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(
@ -548,7 +618,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 range(len(columns))]
interior = [profiles_for(i, spacing_slack, wall_slack) for i in profile_indices]
if weighted:
adjacent = [[launch], *interior, [arrival]]
reachable_offsets = (0, *(
@ -563,12 +633,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(i, spacing_slack + 5, wall_slack)
roomier = profiles_for(profile_indices[i], spacing_slack + 5, wall_slack)
interior[i] = sorted(set(interior[i] + roomier[:45]))
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,
weighted=weighted, sbend_penalty=sbend_penalty, allowed_offsets=allowed_offsets, pair_distance=pair_distance,
):
signature = rows, moves
if signature not in seen:
@ -735,7 +805,7 @@ def _column_jog_schedules(
def column_jog_candidates(
problem: RoutingProblem, search: SearchOptions, *, limit_per_pass: int | None = None, recovery: bool = False,
problem: RoutingProblem, search: SearchOptions, *, limit_per_pass: int | None = None, recovery: bool = False, merge_close: bool = False,
) -> Iterator[dict[str, PathSeed]]:
"""Allocate tracks through ordered apertures using staggered 90-degree jogs."""
if problem.initial_paths:
@ -743,7 +813,7 @@ def column_jog_candidates(
radii = sorted({int(r) for r in search.bend_radii if isfinite(r) and r > 0 and r == int(r)})
if not radii:
return
layout = _column_layout(problem, min_tracks=1 if recovery else 3)
layout = _column_layout(problem, min_tracks=1 if recovery else 3, merge_gap=2 * radii[0] if merge_close else 0)
if layout is None:
return
circular = bend90_uses_circular_geometry(*resolve_bend_geometry(search))

View file

@ -1,4 +1,4 @@
"""Obstacle-driven launch positions for two-turn paths between parallel ports."""
"""Obstacle-driven positions for constructive paths between parallel ports."""
from __future__ import annotations
@ -10,6 +10,41 @@ 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],

View file

@ -12,7 +12,7 @@ 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.primitives import Port, rotate_cardinal
from inire.model import resolve_bend_geometry
from inire.router._jog import jog_launch_steps
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
@ -233,18 +233,23 @@ def terminal_link_seed(net: NetSpec, search: SearchOptions) -> PathSeed | None:
return seed if end == target else None
def _terminal_jogs(net: NetSpec, search: SearchOptions, world: RoutingWorld) -> Iterator[PathSeed]:
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 or lateral == 0:
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):
@ -259,13 +264,32 @@ def _terminal_jogs(net: NetSpec, search: SearchOptions, world: RoutingWorld) ->
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 straight, single-turn, and two-turn paths before native search."""
"""Try verified terminal links and detours before native search."""
link = terminal_link_seed(net, search)
jogs = islice(_terminal_jogs(net, search, world), search.terminal_jog_limit)
for seed in chain((link,) if link else (), jogs):
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)

View file

@ -376,6 +376,7 @@ 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
@ -396,6 +397,22 @@ 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

View file

@ -9,7 +9,7 @@ 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 verify_path
from inire.router._catalog_verify import VerificationCache, verify_path
def exhaustive_paths(evaluator, start, target, moves_from, *, depth, **geometry):
@ -172,6 +172,72 @@ def test_catalog_jog_can_launch_between_obstacles(monkeypatch) -> None:
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),

View file

@ -134,6 +134,43 @@ def test_missing_fixed_contribution_leaves_the_verified_geometry_available() ->
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)

View file

@ -110,10 +110,14 @@ def _build_manual_path(start: Port, width: float, clearance: float, steps: list[
return path
def test_native_warm_start_can_place_an_interior_jog() -> None:
@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, 0, 130, 60), (NetSpec("jog", Port(0, 10, 0), Port(120, 40, 0), 2),),
(box(49, 7, 110, 13), box(-5, 37, 22, 43)), clearance=1,
(-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=()),
@ -126,6 +130,7 @@ def test_native_warm_start_can_place_an_interior_jog() -> None:
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

View file

@ -344,6 +344,70 @@ 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)
@ -355,6 +419,17 @@ 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")

View file

@ -346,7 +346,7 @@ def main() -> None:
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="two-turn launch attempts per native warm start")
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")
@ -380,10 +380,13 @@ def main() -> None:
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": median(samples), "peak_rss": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss,
"catalog_cost": fsum(entry["cost"] for entry in measurements["per_net"].values()), **measurements,
"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,
**measurements,
}, indent=2))

View file

@ -13,7 +13,7 @@ from time import perf_counter
import shapely
from inire import route
from inire.tests.routing_corpus import automatic_options, profile_options, select_cases
from inire.tests.routing_corpus import automatic_options, benchmark_weighted_length, profile_options, select_cases
def capture(repeat: int, revision: str | None) -> dict:
@ -55,13 +55,21 @@ def capture(repeat: int, revision: str | None) -> dict:
}
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
runs[key] = {**reference, "wall_seconds": median(timings), "wall_samples": timings, "stable": stable}
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": (