diff --git a/docs/benchmarks.md b/docs/benchmarks.md index 74a5bbc..2bfe860 100644 --- a/docs/benchmarks.md +++ b/docs/benchmarks.md @@ -141,6 +141,27 @@ The tuning case measures a four-turn detour inside a caller-supplied window. The For constant timing models, a verified choice can eliminate a later candidate at the exact same adjusted delay when it also costs the same or less. In seven interleaved octagonal runs without refinement, this reduced the tuning median from 2.26 s to 1.02 s. Both runs considered 1,334 proposals and selected identical routes at zero residual skew and the same catalog cost. Verified replacements fell from 524 to 136. The released-reservation case completed one independent route with retry and zero with retry disabled. +## Routing cost holdouts + +```sh +PYTHONPATH=. python scripts/benchmark_catalog_routing.py --case peer-cost-holdout --mode typed --repeat 30 +PYTHONPATH=. python scripts/benchmark_catalog_routing.py --case matched-cost-holdout --mode typed --repeat 30 +``` + +Both cases put a bypass beside a straight lane where the two routes compete for clearance. The matched case adds a reference lane. Each includes two authored reference layouts, which are verified before routing is timed. The benchmark starts from the ports and keepouts and reports the reference costs alongside its own result. The references for the matched case must both satisfy the zero-skew constraint. + +In 30 interleaved runs per mode against `1359463`, the router completed every net on both holdouts. The matched result kept zero skew. + +| Case | Prior cost | New cost | Cheaper reference | Change in time × cost² | +| --- | ---: | ---: | ---: | ---: | +| Competing profiles | 0.9560 | 0.5477 | 0.5480 | −34% in both modes | +| Matched competing profiles | 1.4160 | 0.7967 | 0.7970 | −23% typed, −24% octagonal | + +After a complete layout verifies, catalog refinement can try a cheaper straight profile that displaces one independent peer. It ranks straight spans by potential savings, checks at most four spans, and can reroute at most two peers in separate trials. It accepts a trial only if it lowers the joint cost, verifies the entire layout, and keeps any affected match group within tolerance. + +Native automatic routing with explicit length weights ranks windows containing S-bends by the difference between their verified cost and a geometric lower bound. It budgets up to one eighth of the preceding search expansions for this pass and caps it at 12 windows. It accepts only cheaper, verified splices into the incumbent. + +In five interleaved native runs, the six-net splitter dropped from 39,963.88 to 36,661.15 in weighted cost and improved its time × cost² score by 15%. The single-net north-launch case kept its route and took about 5% longer. ## Catalog acceptance checks diff --git a/inire/router/_automatic.py b/inire/router/_automatic.py index 66b9e8d..eb61803 100644 --- a/inire/router/_automatic.py +++ b/inire/router/_automatic.py @@ -46,6 +46,7 @@ from inire.router._routing_policy import ( ) from inire.router._seed_materialization import materialize_path_seed, seed_preparation_error from inire.router._stack import RoutingAttempts +from inire.router._weighted_local import improve_weighted_windows from inire.router.cost import build_native_cost_evaluator, weighted_path_length from inire.router.refiner import PathRefiner from inire.seeds import PathSeed, SBendSeed, StraightSeed @@ -922,6 +923,31 @@ class _AutomaticRun: return trial if len(trial.valid_costs) == target else None return None + def _try_weighted_windows(self, trials: list[Trial]) -> None: + options, weights = self.options, self.length_weights + if ( + weights is None or options.topology.automatic_cost == "never" + or self.problem.initial_paths or options.refinement.objective is not None + or options.search.bend_physical_length is not None + ): + return + incumbent = _best_trial(trials) + planner = "weighted-windows" + with self._time("refine", planner=planner): + changes, metrics = improve_weighted_windows( + self.problem, options, incumbent.run.results_by_net, weights, + search_expansions=self.attempts.metrics().nodes_expanded, + ) + self.attempts.samples.append(metrics.snapshot()) + if changes: + self.cost_pass_performed = True + stage = RoutingStage( + "off", (), metrics.total_nodes_expanded, options.search.node_limit, + kind="refinement", planner=planner, policy="weighted", operation="refine", + ) + results = {**incumbent.run.results_by_net, **changes} + trials.append(self._trial(replace(incumbent.run, results_by_net=results), stage).as_replacement_for(incumbent)) + def execute(self) -> RoutingRunResult: started = perf_counter() options = self.options @@ -957,6 +983,7 @@ class _AutomaticRun: self._search_trials(trials, target) self._try_weighted_detour(trials) self._try_weighted_shortcuts(trials) + self._try_weighted_windows(trials) refinement_choice = self._refine(trials) best = refinement_choice or _best_trial(trials) metrics = self.attempts.metrics() diff --git a/inire/router/_catalog_layout.py b/inire/router/_catalog_layout.py index feac81d..02e128a 100644 --- a/inire/router/_catalog_layout.py +++ b/inire/router/_catalog_layout.py @@ -3,6 +3,7 @@ from __future__ import annotations from dataclasses import dataclass, field, replace +from heapq import nlargest from itertools import combinations from math import ceil, floor, fsum, inf, isfinite from time import perf_counter @@ -10,7 +11,7 @@ from typing import TYPE_CHECKING from shapely.geometry import LineString, Polygon, box -from inire._catalog import HEADING_STEPS, Move, MoveEvaluator, _require_integer +from inire._catalog import HEADING_STEPS, Move, MoveEvaluator, StraightVariant, _require_integer from inire._catalog_timing import evaluate_delay from inire._snapshot import snapshot from inire.geometry.collision import _violates_net_clearance @@ -407,6 +408,7 @@ class _LayoutSearch: trial = search_path( self.evaluator, start, target, node_limit=budget, max_cost=cost - 2 * COST_TOLERANCE, corridor=corridor, **settings, method="constructive_only" if self.settings.constructive else "detailed", + constructive_profiles=group is not None, ) budget -= trial.expanded result = result.including_work(trial) @@ -423,6 +425,93 @@ class _LayoutSearch: break return report + def improve_profile_pair( + self, members: Mapping[str, str], groups: Mapping[str, MatchGroup], reports: dict[str, MatchResult], timing: DelayModel | None, + ) -> None: + """Try a wider straight and reroute its one independent blocker under a joint cost cap.""" + limit = min(self.settings.node_limit, self.settings.refinement_node_limit) + if limit < 2 or len(self.installed) < 2: + return + rates = {variant.cost_per_cm for variant in self.evaluator.catalog.variants.values() if isinstance(variant, StraightVariant)} + if len(rates) < 2: + return + floor_rate = min(rates) * self.evaluator.grid.meters_per_unit * 100 + # A two-route probe needs meaningful headroom in whole-layout cost. + layout_cost = fsum(move.cost for path in self.installed_paths.values() for move in path) + minimum_saving = max(COST_TOLERANCE, layout_cost / 16) + spans = ( + (move.cost - floor_rate * move.length, name, index) + for name, path in self.installed_paths.items() if not self.nets[name].seed + for index, move in enumerate(path) if move.move.steps is not None and move.length is not None + ) + candidates = [] + for cap, name, index in nlargest(4, spans): + if cap < minimum_saving: + break + path = self.installed_paths[name] + original = path[index] + for recipe in straight_replacements(self.evaluator, original.start, original.move): + portion = replay_moves(self.evaluator, original.start, recipe) + if portion is None or portion[-1].end != original.end: + continue + saving = original.cost - fsum(move.cost for move in portion) + if saving < minimum_saving: + continue + footprints = tuple(shape for move in portion for shape in move.footprints) + candidate = (*path[:index], *portion, *path[index + 1:]) + candidates.append((saving, name, footprints, candidate)) + + probes = 0 + for saving, name, footprints, candidate in sorted(candidates, key=lambda item: item[0], reverse=True): + group_id = members.get(name) + updated = self._refined_match(name, candidate, groups.get(group_id), reports.get(group_id), timing) + if group_id is not None and updated is None: + continue + geometry = self._geometry_settings(name) + cache, clearance = self._verification_cache, self.settings.clearance + colliders = _colliders(cache.tree(geometry["occupied"], installed=True), footprints, clearance, cache) + blocked = { + id(other) for other in colliders if any(_violates_net_clearance(shape, other, clearance) for shape in footprints) + } + peers = [peer for peer, shapes in self.installed.items() if peer != name and any(id(shape) in blocked for shape in shapes)] + if len(peers) != 1 or peers[0] in members or self.nets[peers[0]].seed: + continue + [peer] = peers + probes += 1 + if self._reroute_profile_peer(name, candidate, peer, saving, limit): + if group_id is not None and updated is not None: + reports[group_id] = updated + return + if probes == 2: + return + + def _reroute_profile_peer( + self, name: str, candidate: tuple[Evaluation, ...], peer: str, saving: float, limit: int, + ) -> bool: + original_shapes, original_path = self.installed[name], self.installed_paths[name] + peer_shapes, peer_path = self.installed.pop(peer), self.installed_paths.pop(peer) + net = self.nets[peer] + self._install(name, candidate) + try: + if not self.verify(name, candidate): + return False + trial = search_path( + self.evaluator, net.start, net.target, node_limit=limit, + max_cost=fsum(move.cost for move in peer_path) + saving - COST_TOLERANCE, + method="constructive_only", constructive_profiles=True, **self._geometry_settings(peer), + ) + self.routes[peer] = self.routes[peer].including_work(trial) + if trial.path is None or not self._verify_replacements({name: candidate, peer: trial.path}): + return False + finally: + self.installed[name], self.installed_paths[name] = original_shapes, original_path + self.installed[peer], self.installed_paths[peer] = peer_shapes, peer_path + self.routes[name] = replace(self.routes[name], path=candidate) + self.routes[peer] = replace(self.routes[peer], path=trial.path) + self._install(name, candidate) + self._install(peer, trial.path) + return True + def _refined_match( self, name: str, path: tuple[Evaluation, ...], group: MatchGroup | None, report: MatchResult | None, timing: DelayModel | None, ) -> MatchResult | None: @@ -645,6 +734,8 @@ def _route_attempt( report = routing.refine(name, group_by_id.get(group_id), reports.get(group_id), timing) if group_id is not None and report is not None: reports[group_id] = report + if len(completed) == len(nets): + routing.improve_profile_pair(members, group_by_id, reports, timing) for name in completed: path = routing.routes[name].path assert path is not None diff --git a/inire/router/_catalog_search.py b/inire/router/_catalog_search.py index f080a24..534d1ca 100644 --- a/inire/router/_catalog_search.py +++ b/inire/router/_catalog_search.py @@ -521,7 +521,7 @@ class _Proposals: # 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, ...]]]: + def detour_recipes(self, start: Pose, *, widen: bool = False) -> Iterator[tuple[float, tuple[Move, ...]]]: """Try local and full-span bypasses for a blocked cardinal straight.""" target = self.target if start.heading % 90 or (start.heading, start.profile) != (target.heading, target.profile): @@ -542,6 +542,18 @@ class _Proposals: lane for _, _, low, high in blockers for lane in (floor((low - margin) / pitch) * pitch, ceil((high + margin) / pitch) * pitch) } + if widen: + profiles = self.evaluator.catalog.profiles + widths = {profiles[profile].width for profile, runs in self._straights.items() if any( + self._straight_prices[name] < self._straight_prices[straight] for name in runs + )} + for width in widths: + wider_margin = self.clearance + width / 2 + if wider_margin > margin: + lane_bounds.update( + lane for _, _, low, high in blockers + for lane in (floor((low - wider_margin) / pitch) * pitch, ceil((high + wider_margin) / pitch) * pitch) + ) # Additional straight sections are useful when they can switch to a # cheaper profile. A shape at exactly the clearance margin can sit # beside the lead or tail, subject to exact replay. @@ -568,7 +580,9 @@ class _Proposals: 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 + variants = self.evaluator.catalog.variants + price_scale = self.evaluator.grid.meters_per_unit * 100 + unit_price = self._straight_prices[straight] * price_scale for side in sorted(lane_bounds): direction = 1 if side >= 0 else -1 for outward in jogs[direction]: @@ -590,8 +604,23 @@ class _Proposals: *((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) + middle = Move(straight, steps=center // pitch) + full_span = (*out_moves, middle, *in_moves) candidates.append((cost, lane, True, full_span)) + if widen: + # Place the profile changes on the parallel run between the two jogs. + for replacement in straight_replacements(self.evaluator, start, middle): + if len(replacement) != 3: + continue + first, body, last = replacement + entry, exit_variant = variants[first.variant], variants[last.variant] + assert body.steps is not None + assert not isinstance(entry, StraightVariant) + assert not isinstance(exit_variant, StraightVariant) + wide_cost = body.steps * pitch * price_scale * self._straight_prices[body.variant] + saving = center * unit_price - wide_cost - entry.cost - exit_variant.cost + if saving > COST_TOLERANCE: + candidates.append((cost - saving, lane, True, (*out_moves, *replacement, *in_moves))) for price, _, _, recipe in sorted(candidates, key=lambda item: item[:3]): yield price, recipe @@ -761,6 +790,7 @@ def search_path( scan_steps: bool = False, bias: SearchBias | None = None, method: Literal["detailed", "constructive_first", "constructive_only"] = "detailed", + constructive_profiles: bool = False, cache: VerificationCache | None = None, ) -> SearchResult: """Search physical paths while retaining a bounded number of distinct arrival histories.""" @@ -795,7 +825,11 @@ def search_path( placements: dict[tuple[Pose, Move], Evaluation | None] = {} recipes = proposals.two_turn_recipes(start) if method != "detailed": - recipes = chain(proposals.direct_recipes(start), recipes, proposals.detour_recipes(start)) + aligned = proposals.aligned_recipes(start) if constructive_profiles else () + recipes = chain( + aligned, proposals.direct_recipes(start), recipes, + proposals.detour_recipes(start, widen=constructive_profiles and corridor is None), + ) elif bias is None: aligned = proposals.aligned_recipes(start) if aligned: diff --git a/inire/router/_weighted_local.py b/inire/router/_weighted_local.py new file mode 100644 index 0000000..1dbcb3d --- /dev/null +++ b/inire/router/_weighted_local.py @@ -0,0 +1,123 @@ +"""Bounded native window searches using the automatic selection cost.""" + +from __future__ import annotations + +from dataclasses import replace +from heapq import nsmallest +from itertools import accumulate +from math import hypot, pi +from typing import TYPE_CHECKING + +from inire.constants import TOLERANCE_LINEAR +from inire.geometry.collision import RoutingWorld +from inire.router._astar_types import AStarContext, AStarMetrics, SearchRunConfig +from inire.router._search import route_astar +from inire.router.cost import CostEvaluator, weighted_path_length + +if TYPE_CHECKING: + from collections.abc import Iterator, Mapping + + from inire.geometry.components import ComponentResult + from inire.geometry.primitives import Port + from inire.model import RoutingOptions, RoutingProblem + from inire.results import RoutingResult + from inire.router.cost import ScoreableMove + + +_WINDOW_NODE_LIMIT = 64 +_WINDOW_ATTEMPT_LIMIT = 12 +_WINDOW_COMPONENT_LIMIT = 16 +_SEARCH_WORK_DIVISOR = 8 + + +class _LengthCost(CostEvaluator): + def __init__(self, world: RoutingWorld, weights: Mapping[str, float]) -> None: + super().__init__(world, greedy_h_weight=1, danger_weight=0) + self.weights = weights + self.minimum_rate = min(weights.values()) + + def score_component(self, component: ScoreableMove, **_ignored: object) -> float: + if self.collision_engine.metrics is not None: + self.collision_engine.metrics.total_score_component_calls += 1 + return component.length * self.weights[component.move_type] + + def h_manhattan(self, current: Port, target: Port, *, min_bend_radius: float = 50.0) -> float: + # All generated moves pay at least minimum_rate times their length. + # Changing heading also requires the excess cost of quarter turns. + turn = int(target.r - current.r) % 360 + turns = min(turn, 360 - turn) // 90 + bend_cost = (self.weights["bend90"] - self.minimum_rate) * pi * min_bend_radius / 2 + return self.minimum_rate * hypot(target.x - current.x, target.y - current.y) + turns * bend_cost + + +def _windows( + paths: Mapping[str, tuple[ComponentResult, ...]], evaluator: _LengthCost, min_radius: float, +) -> Iterator[tuple[float, int, str, int, int, float]]: + for name, path in paths.items(): + if not any(move.move_type == "sbend" for move in path): + continue + costs = tuple(accumulate((evaluator.score_component(move) for move in path), initial=0.0)) + bends = tuple(accumulate((move.move_type == "sbend" for move in path), initial=0)) + for begin, move in enumerate(path): + start = move.start_port + for end in range(begin + 1, min(len(path), begin + _WINDOW_COMPONENT_LIMIT) + 1): + if bends[end] == bends[begin]: + continue + cost = costs[end] - costs[begin] + bound = evaluator.h_manhattan(start, path[end - 1].end_port, min_bend_radius=min_radius) + if cost - bound > TOLERANCE_LINEAR: + yield bound - cost, end - begin, name, begin, end, cost + + +def improve_weighted_windows( + problem: RoutingProblem, + options: RoutingOptions, + incumbent: Mapping[str, RoutingResult], + weights: Mapping[str, float], + *, + search_expansions: int, +) -> tuple[dict[str, RoutingResult], AStarMetrics]: + """Spend a fraction of the preceding search work on high-headroom windows.""" + metrics = AStarMetrics() + node_limit = min(options.search.node_limit, _WINDOW_NODE_LIMIT) + attempts = min(_WINDOW_ATTEMPT_LIMIT, search_expansions // (_SEARCH_WORK_DIVISOR * node_limit)) if node_limit else 0 + if not attempts or not all(result.is_valid for result in incumbent.values()): + return {}, metrics + paths = {name: result.path for name, result in incumbent.items() if result.path} + if not any(move.move_type == "sbend" for path in paths.values() for move in path): + return {}, metrics + world = RoutingWorld.from_problem(problem, use_dynamic_grid=False) + world.metrics = metrics + evaluator = _LengthCost(world, weights) + context = AStarContext(evaluator, problem, options, metrics=metrics) + windows = nsmallest(attempts, _windows(paths, evaluator, context.min_bend_radius)) + if not windows: + return {}, metrics + nets = {net.net_id: net for net in problem.nets} + for name, path in paths.items(): + world.add_route(name, path) + + changed = {} + for _, _, name, begin, end, cost in windows: + if name in changed: + continue + path = paths[name] + portion = path[begin:end] + start, target = portion[0].start_port, portion[-1].end_port + metrics.total_refinement_windows_considered += 1 + config = SearchRunConfig.from_options( + options, node_limit=node_limit, hard_congestion=True, self_collision_check=True, max_cost=cost - TOLERANCE_LINEAR, + guidance_seed=tuple(move.move_spec for move in portion), propose_guidance_moves=True, + ) + result = route_astar(start, target, nets[name].width, context, metrics=metrics, net_id=name, config=config) + if not result or result[-1].end_port != target or weighted_path_length(result, weights) >= cost - TOLERANCE_LINEAR: + continue + candidate = (*path[:begin], *result, *path[end:]) + metrics.total_refinement_candidates_verified += 1 + report = world.verify_path_report(name, candidate) + if report.is_valid: + world.remove_path(name) + world.add_route(name, candidate) + metrics.total_refinement_candidates_accepted += 1 + changed[name] = replace(incumbent[name], path=candidate, report=report) + return changed, metrics diff --git a/inire/tests/test_catalog_timing_cases.py b/inire/tests/test_catalog_timing_cases.py index 8b353c7..f90af90 100644 --- a/inire/tests/test_catalog_timing_cases.py +++ b/inire/tests/test_catalog_timing_cases.py @@ -14,6 +14,31 @@ from inire.router._catalog_matching import MatchGroup, MatchResult from inire.router._catalog_search import SearchResult from inire.router._catalog_tuning import tune_group, window_replacements from inire.router._catalog_verify import replay_moves, verify_path +from scripts.benchmark_catalog_routing import catalog, scale_case, verify_references + + +@pytest.mark.parametrize("condition", ["independent", "matched", "delay-conflict"]) +def test_profile_pair_refinement_preserves_coverage_and_timing(condition) -> None: + name = "peer-cost-holdout" if condition == "independent" else "matched-cost-holdout" + case = scale_case(name) + technology = catalog("typed", name) + references = verify_references(case, technology) + timing = case.timing + if condition == "delay-conflict": + assert timing is not None + timing = replace(timing, group_indices={"4": 4, "5": 5}) + settings = LayoutSettings(case.board, case.obstacles, clearance=case.clearance, constructive=True) + result = route_layout(MoveEvaluator(case.grid, technology), case.nets, settings, timing=timing, groups=case.groups) + assert result.completed == tuple(case.nets) + if case.groups: + assert result.matching["delay"].complete + assert result.matching["delay"].skew == 0 + through = result.routes["through"] + if condition == "delay-conflict": + assert through.cost == pytest.approx(0.46) + else: + assert through.cost == pytest.approx(0.249) + assert sum(route.cost for route in result.routes.values()) <= references["cheaper"] + 1e-12 @pytest.mark.parametrize("units", ["optical_length", "seconds"]) diff --git a/inire/tests/test_routing_fixtures.py b/inire/tests/test_routing_fixtures.py index 7b98fc5..cdfeac8 100644 --- a/inire/tests/test_routing_fixtures.py +++ b/inire/tests/test_routing_fixtures.py @@ -8,7 +8,7 @@ from inire import Bend90Seed, RoutingRunResult, SBendSeed, StraightSeed, route from inire.constants import TOLERANCE_LINEAR from inire.tests.retry_holdout_benchmarks import RETRY_HOLDOUT_CASES from inire.tests.routing_benchmarks import BENCHMARK_CASES, COMPLEX_BENCHMARK_CASES, EXTERNAL_BENCHMARK_CASES -from inire.tests.routing_corpus import CASE_GROUPS, CORPUS_CASES, automatic_options, profile_options, select_cases +from inire.tests.routing_corpus import CASE_GROUPS, CORPUS_CASES, automatic_options, benchmark_weighted_length, profile_options, select_cases from inire.tests.routing_expanded_benchmarks import LOW_LENGTH_COST_CASES from inire.tests.stress_routing_benchmarks import STRESS_BENCHMARK_CASES @@ -84,7 +84,8 @@ def test_automatic_reaches_corpus_routing_bound(case) -> None: assert set(partial.valid_net_ids) == verified - {"outside_lower"} if case.name == "pic-splitter-tree-1x8-ew": assert any(stage.policy == "direct-lookahead-hinted" for stage in run.automatic.stages) - assert run.automatic.stages[run.automatic.selected_stage].kind == "incumbent-verified" + assert any(stage.kind == "incumbent-verified" and set(stage.valid_net_ids) == verified for stage in run.automatic.stages) + assert sum(benchmark_weighted_length(run.results_by_net[net_id]) for net_id in verified) < 38_000 if case.name == "overloaded-gate": capacity = run.automatic.capacity_limit assert capacity is not None diff --git a/scripts/benchmark_catalog_routing.py b/scripts/benchmark_catalog_routing.py index baa0200..d5af850 100644 --- a/scripts/benchmark_catalog_routing.py +++ b/scripts/benchmark_catalog_routing.py @@ -19,14 +19,17 @@ from inire import NetSpec, ObjectiveWeights, Port, RefinementOptions, RoutingOpt from inire._catalog import ( HEADING_STEPS, BendVariant, Catalog, FixedVariant, Grid, Move, MoveEvaluator, Orientation, Pose, Profile, StraightVariant, ) -from inire._catalog_timing import DelayModel +from inire._catalog_timing import DelayModel, evaluate_delay from inire.router._catalog_guidance import AutomaticGrid, CoarseGuidance from inire.router._catalog_layout import CatalogNet, LayoutSettings, route_layout -from inire.router._catalog_matching import MatchGroup +from inire.router._catalog_matching import DelayChoice, MatchGroup, choose_match from inire.router._catalog_verify import replay_moves, verify_path from scripts.catalog_floorplan import BLOCKS, COMPONENTS, NET_BANKS, STEPPED_BLOCKS +PROFILE_HOLDOUTS = ("peer-cost-holdout", "matched-cost-holdout") + + @dataclass(frozen=True, slots=True) class ScaleCase: grid: Grid @@ -38,6 +41,45 @@ class ScaleCase: groups: tuple[MatchGroup, ...] = () windows: dict[str, Polygon] = field(default_factory=dict) clearance: float = 1000.0 + cheaper_references: dict[str, tuple[Move, ...]] | None = None + + +def profile_holdout(matched: bool) -> ScaleCase: + """Two nearby lanes compete for a cheaper profile beside a long keepout.""" + grid = Grid((0, 0), 100, 1e-9) + lanes = {"bypass": 975_000, "through": 1_000_000} + if matched: + lanes["reference"] = 1_150_000 + nets = {name: CatalogNet(Pose(200_000, y, 0, "4"), Pose(4_800_000, y, 0, "4")) for name, y in lanes.items()} + enter_wide = Move("centered", traversal=("a", "b")) + exit_wide = Move("centered", traversal=("b", "a"), orientation=Orientation(180)) + widen = (enter_wide, Move("5-straight", steps=45_800), exit_wide) + left_up = Move("left-90", displacement=(10_000, 10_000)) + left_down = Move("left-90", displacement=(10_000, -10_000)) + right_up = Move("right-90", displacement=(10_000, 10_000)) + right_down = Move("right-90", displacement=(10_000, -10_000)) + references = { + "bypass": (left_up, right_up, Move("4-straight", steps=45_600), right_down, left_down), + "through": (Move("4-straight", steps=46_000),), + } + cheaper = { + "bypass": ( + right_down, Move("4-straight", steps=600), left_down, + enter_wide, Move("5-straight", steps=45_400), exit_wide, + left_up, Move("4-straight", steps=600), right_up, + ), + "through": widen, + } + timing = None + groups = () + if matched: + references["reference"] = cheaper["reference"] = widen + timing = DelayModel(1.55e-6, group_indices={"4": 4, "5": 4}, variant_delays={"centered": 40_000}) + groups = (MatchGroup("delay", {"through": 0, "reference": 0}, timing.wavelength, 0),) + return ScaleCase( + grid, box(0, 0, 5_000_000, 1_200_000), nets, (box(400_000, 900_000, 4_600_000, 990_000),), + references, timing, groups, cheaper_references=cheaper, + ) def timing_case(name: str) -> ScaleCase: @@ -133,6 +175,8 @@ def scale_case(name: str) -> ScaleCase: return floorplan_case() if name in ("tuning", "retry"): return timing_case(name) + if name in PROFILE_HOLDOUTS: + return profile_holdout(matched=name == "matched-cost-holdout") if name in ("corpus-lanes", "corpus-open-lanes"): return corpus_lanes(name) grid = Grid((0, 0), 100, 1e-9) @@ -187,7 +231,7 @@ def catalog(mode: str, case: str) -> Catalog: (Polygon(((0, -2000), (10_000, -2500), (10_000, 2500), (0, 2000))),), (("a", "b"), ("b", "a")), (Orientation(), Orientation(180)), 0.01, 10_000, ) - if case in ("floorplan", "constrained", "diagonal-savings", "tuning"): + if case in ("floorplan", "constrained", "diagonal-savings", "tuning", *PROFILE_HOLDOUTS): variants["left-90"] = BendVariant("4", 90, 10_000, 0.01, sagitta=30) variants["right-90"] = BendVariant("4", -90, 10_000, 0.01, sagitta=30) if mode == "octagonal": @@ -203,10 +247,12 @@ def catalog(mode: str, case: str) -> Catalog: return Catalog("scale", profiles, variants) -def verify_references(case: ScaleCase, technology: Catalog) -> None: +def _reference_cost(case: ScaleCase, technology: Catalog, recipes: dict[str, tuple[Move, ...]]) -> float: + if recipes.keys() != case.nets.keys(): + raise AssertionError("Reference layout must route every net") evaluator = MoveEvaluator(case.grid, technology) placed = {} - for name, recipe in case.references.items(): + for name, recipe in recipes.items(): net = case.nets[name] path = replay_moves(evaluator, net.start, recipe) if path is None: @@ -220,6 +266,28 @@ def verify_references(case: ScaleCase, technology: Catalog) -> None: ) if error is not None: raise AssertionError(f"Invalid reference for {name}: {error}") + if case.cheaper_references is not None and case.timing is not None: + for group in case.groups: + timing = replace(case.timing, wavelength=group.wavelength) + choices = {} + for name in group.offsets: + delay = evaluate_delay(evaluator, placed[name], timing, net_id=name) + if delay is None: + raise AssertionError(f"Missing reference delay for {name}") + choices[name] = (DelayChoice(placed[name], delay),) + if not choose_match(group, choices)[2]: + raise AssertionError(f"Unmatched reference group {group.group_id}") + return fsum(piece.cost for path in placed.values() for piece in path) + + +def verify_references(case: ScaleCase, technology: Catalog) -> dict[str, float]: + cost = _reference_cost(case, technology, case.references) + if case.cheaper_references is None: + return {} + cheaper = _reference_cost(case, technology, case.cheaper_references) + if cheaper >= cost: + raise AssertionError("Cheaper reference must lower the total cost") + return {"original": cost, "cheaper": cheaper} def bank_order_key(net: CatalogNet) -> tuple[int, int, bool, int, int]: @@ -338,7 +406,7 @@ def main() -> None: "--case", default="floorplan", help="routing fixture (default: floorplan)", choices=( "floorplan", "aligned", "constrained", "diagonal-savings", "diagonal", "off-coarse", "tuning", "retry", - "corpus-lanes", "corpus-open-lanes", + "corpus-lanes", "corpus-open-lanes", *PROFILE_HOLDOUTS, ), ) parser.add_argument("--guide-pitch", type=int, help="coarse pitch in nanometers") @@ -358,6 +426,8 @@ def main() -> None: parser.error("--native-jog-limit requires native mode and a nonnegative limit") if args.case == "diagonal" and args.mode != "octagonal": parser.error("The native-diagonal terminal case requires octagonal mode") + if args.case in PROFILE_HOLDOUTS and args.mode not in ("typed", "octagonal"): + parser.error("The profile holdouts require typed or octagonal mode") if args.mode == "native" and ( args.guide_pitch is not None or args.auto_pitch is not None or args.case not in ("floorplan", "constrained", "aligned", "diagonal-savings", "corpus-lanes", "corpus-open-lanes") @@ -365,7 +435,7 @@ def main() -> None: parser.error("Native mode needs a case with cardinal terminals on the explicit grid") case = scale_case(args.case) technology = catalog(args.mode, args.case) - verify_references(case, technology) + reference_costs = verify_references(case, technology) if args.net_order is None: args.net_order = "bank" if args.case == "floorplan" else "input" if args.net_order == "bank": @@ -374,7 +444,7 @@ def main() -> None: if args.mode == "native" and args.native_jog_limit is None: args.native_jog_limit = 48 if args.case == "floorplan" else 0 if args.constructive is None: - args.constructive = args.case == "floorplan" and args.mode != "native" + args.constructive = args.case in ("floorplan", *PROFILE_HOLDOUTS) and args.mode != "native" samples = [] measurements = {} for _ in range(args.repeat): @@ -386,6 +456,7 @@ def main() -> None: "options": vars(args), "machine": platform.machine(), "python": platform.python_version(), "requested": len(case.nets), "wall_seconds": samples, "median_seconds": elapsed, "peak_rss": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss, "catalog_cost": total_cost, "time_cost_squared": elapsed * total_cost**2 if measurements["completed"] else None, + **({"reference_costs": reference_costs} if reference_costs else {}), **measurements, }, indent=2))