Add and measure a 57-board routing benchmark corpus
This commit is contained in:
parent
be3222e5ae
commit
2f2add98ec
3 changed files with 5892 additions and 4 deletions
438
scripts/compare_topological_routing.py
Normal file
438
scripts/compare_topological_routing.py
Normal file
|
|
@ -0,0 +1,438 @@
|
|||
"""Compare the public routing modes on selected routing benchmarks."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from argparse import ArgumentParser
|
||||
from dataclasses import asdict, dataclass, replace
|
||||
from functools import partial
|
||||
from json import dumps
|
||||
from math import ceil, isfinite
|
||||
from pathlib import Path
|
||||
from platform import python_version
|
||||
from statistics import median
|
||||
from time import perf_counter
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import shapely
|
||||
from shapely.geometry import box, mapping
|
||||
|
||||
from inire import RoutingOptions, RoutingStage, route
|
||||
from inire.router._routing_policy import DIRECT_POLICIES, _best_trial
|
||||
from inire.router._routing_policy import _direct_trials as _run_direct_trials
|
||||
from inire.router._routing_policy import _trial as _summarize_trial
|
||||
from inire.tests.routing_benchmarks import (
|
||||
BENCHMARK_CASES,
|
||||
COMPLEX_BENCHMARK_CASES,
|
||||
CROSSING_BENCHMARK_CASES,
|
||||
EXTERNAL_BENCHMARK_CASES,
|
||||
FALLBACK_BENCHMARK_CASES,
|
||||
VALIDATION_BENCHMARK_CASES,
|
||||
)
|
||||
from inire.tests.terminal_bench_scenario import LENGTH_COST
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from shapely.geometry import Polygon
|
||||
from inire import CapacityLimit, RoutingProblem, RoutingResult, RoutingTiming, TopologyReport
|
||||
from inire.router._routing_policy import Trial
|
||||
from inire.tests.routing_benchmarks import BenchmarkCase
|
||||
|
||||
|
||||
ORDER_POLICIES = ("seed-order-restart", "seed-order-initial", "seed-order-locked")
|
||||
BUNDLE_POLICIES = ("bundle-first", "bundle-first-refine")
|
||||
AUTOMATIC_COST_MODES = {"automatic": "selective", "automatic-span": "never", "automatic-weighted": "always"}
|
||||
AUTOMATIC_POLICIES = tuple(AUTOMATIC_COST_MODES)
|
||||
POLICIES = (*DIRECT_POLICIES, *ORDER_POLICIES, *BUNDLE_POLICIES, *AUTOMATIC_POLICIES)
|
||||
PROFILES = ("matched-budget", "public-defaults")
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class RunSample:
|
||||
duration_s: float
|
||||
net_outcomes: dict[str, str]
|
||||
valid_costs: dict[str, float]
|
||||
reached_net_ids: tuple[str, ...]
|
||||
out_of_bounds_net_ids: tuple[str, ...]
|
||||
nodes_expanded: int
|
||||
route_iterations: int
|
||||
topology: TopologyReport | None
|
||||
stages: tuple[RoutingStage, ...]
|
||||
bundle_rejection: str | None = None
|
||||
bundle_duration_s: float | None = None
|
||||
selected_stage: int = 0
|
||||
capacity_limit: CapacityLimit | None = None
|
||||
planner_rejections: tuple[str, ...] = ()
|
||||
port_conflicts: tuple[tuple[str, str], ...] = ()
|
||||
max_routed: int | None = None
|
||||
cost_pass_performed: bool = False
|
||||
timings: tuple[RoutingTiming, ...] = ()
|
||||
|
||||
|
||||
def _benchmark_score(result: RoutingResult) -> float:
|
||||
return sum(component.length * LENGTH_COST[component.move_type] for component in result.path)
|
||||
|
||||
|
||||
_trial = partial(_summarize_trial, score=_benchmark_score)
|
||||
_direct_trials = partial(_run_direct_trials, score=_benchmark_score)
|
||||
|
||||
|
||||
def _mode_options(options: RoutingOptions, strategy: str, profile: str = "matched-budget") -> RoutingOptions:
|
||||
if strategy not in AUTOMATIC_POLICIES:
|
||||
return replace(options, topology=replace(options.topology, mode="off" if strategy in POLICIES else strategy))
|
||||
|
||||
weights = options.topology.automatic_length_weights
|
||||
if profile == "matched-budget":
|
||||
weights = (LENGTH_COST["straight"], LENGTH_COST["bend90"], LENGTH_COST["sbend"])
|
||||
cost_policy = options.topology.automatic_cost if profile == "public-defaults" and strategy == "automatic" else AUTOMATIC_COST_MODES[strategy]
|
||||
return replace(
|
||||
options,
|
||||
topology=replace(
|
||||
options.topology,
|
||||
mode="automatic",
|
||||
automatic_cost=cost_policy,
|
||||
automatic_length_weights=weights,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _public_defaults(case: BenchmarkCase, defaults: RoutingOptions) -> RoutingOptions:
|
||||
geometry = case.options.search
|
||||
return replace(
|
||||
defaults,
|
||||
search=replace(
|
||||
defaults.search,
|
||||
bend_radii=geometry.bend_radii,
|
||||
sbend_radii=geometry.sbend_radii,
|
||||
sbend_offsets=geometry.sbend_offsets,
|
||||
bend_collision_type=geometry.bend_collision_type,
|
||||
bend_proxy_geometry=geometry.bend_proxy_geometry,
|
||||
bend_physical_geometry=geometry.bend_physical_geometry,
|
||||
bend_clip_margin=geometry.bend_clip_margin,
|
||||
min_straight_length=geometry.min_straight_length,
|
||||
max_straight_length=geometry.max_straight_length,
|
||||
),
|
||||
topology=replace(defaults.topology, infer_terminal_headings=case.options.topology.infer_terminal_headings),
|
||||
)
|
||||
|
||||
|
||||
def _order_trials(problem: RoutingProblem, board: Polygon, options: RoutingOptions, strategy: str) -> list[Trial]:
|
||||
limit = options.search.node_limit
|
||||
first_limit = max(1, limit // 2)
|
||||
first_order = options.congestion.net_order
|
||||
first_options = replace(options, search=replace(options.search, node_limit=first_limit), topology=replace(options.topology, mode="seed"))
|
||||
run = route(problem, options=first_options)
|
||||
first = _trial(run, RoutingStage("seed", (), run.metrics.nodes_expanded, first_limit, net_order=first_order), board)
|
||||
if len(first.valid_costs) == len(problem.nets) or limit == 1:
|
||||
return [first]
|
||||
|
||||
second_order = "shortest" if first_order == "longest" else "longest"
|
||||
second_limit = limit - first_limit
|
||||
second_options = replace(
|
||||
first_options,
|
||||
search=replace(options.search, node_limit=second_limit),
|
||||
congestion=replace(options.congestion, net_order=second_order),
|
||||
)
|
||||
incumbents = {net_id: run.results_by_net[net_id] for net_id in first.valid_costs} if strategy != "seed-order-restart" else {}
|
||||
if strategy == "seed-order-initial":
|
||||
seeds = {net_id: result.as_seed() for net_id, result in incumbents.items()}
|
||||
second_problem = replace(problem, initial_paths={**seeds, **problem.initial_paths})
|
||||
elif strategy == "seed-order-locked" and incumbents:
|
||||
locked = tuple(shape for result in incumbents.values() for shape in result.locked_geometry)
|
||||
second_problem = replace(
|
||||
problem,
|
||||
nets=tuple(net for net in problem.nets if net.net_id not in incumbents),
|
||||
static_obstacles=problem.static_obstacles + locked,
|
||||
initial_paths={net_id: seed for net_id, seed in problem.initial_paths.items() if net_id not in incumbents},
|
||||
)
|
||||
else:
|
||||
second_problem = problem
|
||||
|
||||
run = route(second_problem, options=second_options)
|
||||
if strategy == "seed-order-locked":
|
||||
run = replace(run, results_by_net={**incumbents, **run.results_by_net})
|
||||
stage = RoutingStage("seed", (), run.metrics.nodes_expanded, second_limit, net_order=second_order, incumbent_net_ids=tuple(incumbents))
|
||||
return [first, _trial(run, stage, board)]
|
||||
|
||||
|
||||
def _measure(case: BenchmarkCase, options: RoutingOptions, strategy: str) -> RunSample:
|
||||
board = box(*case.problem.bounds)
|
||||
started = perf_counter()
|
||||
bundle_rejection = None
|
||||
bundle_duration = None
|
||||
if strategy in AUTOMATIC_POLICIES:
|
||||
run = route(case.problem, options=options)
|
||||
report = run.automatic
|
||||
assert report is not None
|
||||
selected = report.stages[report.selected_stage]
|
||||
valid_costs = {net_id: _benchmark_score(run.results_by_net[net_id]) for net_id in report.verified_net_ids}
|
||||
return RunSample(
|
||||
duration_s=perf_counter() - started,
|
||||
net_outcomes={net_id: result.outcome for net_id, result in run.results_by_net.items()},
|
||||
valid_costs=valid_costs,
|
||||
reached_net_ids=tuple(net_id for net_id, result in run.results_by_net.items() if result.reached_target),
|
||||
out_of_bounds_net_ids=selected.out_of_bounds_net_ids,
|
||||
nodes_expanded=run.metrics.nodes_expanded,
|
||||
route_iterations=run.metrics.route_iterations,
|
||||
topology=run.topology,
|
||||
stages=report.stages,
|
||||
selected_stage=report.selected_stage,
|
||||
capacity_limit=report.capacity_limit,
|
||||
planner_rejections=report.planner_rejections,
|
||||
port_conflicts=report.port_conflicts,
|
||||
max_routed=report.max_routed,
|
||||
cost_pass_performed=report.cost_pass_performed,
|
||||
timings=report.timings,
|
||||
)
|
||||
if strategy in BUNDLE_POLICIES:
|
||||
bundle_options = replace(
|
||||
options,
|
||||
topology=replace(options.topology, mode="bundle", infer_terminal_headings=case.options.topology.infer_terminal_headings),
|
||||
congestion=replace(options.congestion, max_iterations=1),
|
||||
refinement=replace(options.refinement, enabled=strategy == "bundle-first-refine"),
|
||||
)
|
||||
try:
|
||||
run = route(case.problem, options=bundle_options)
|
||||
except ValueError as exc:
|
||||
bundle_rejection = str(exc)
|
||||
bundle_duration = perf_counter() - started
|
||||
trials = _direct_trials(case.fixed_headings_problem(), board, options, "direct-probe-near-port")
|
||||
else:
|
||||
bundle_duration = perf_counter() - started
|
||||
stage = RoutingStage("bundle", (), run.metrics.nodes_expanded, options.search.node_limit, kind="bundle")
|
||||
trials = [_trial(run, stage, board)]
|
||||
elif strategy in DIRECT_POLICIES:
|
||||
problem = case.fixed_headings_problem()
|
||||
trials = _direct_trials(problem, board, options, strategy)
|
||||
elif strategy in ORDER_POLICIES:
|
||||
problem = case.fixed_headings_problem()
|
||||
trials = _order_trials(problem, board, options, strategy)
|
||||
else:
|
||||
run = route(case.fixed_headings_problem(), options=options)
|
||||
trials = [_trial(run, RoutingStage(strategy, (), run.metrics.nodes_expanded, options.search.node_limit), board)]
|
||||
best = _best_trial(trials)
|
||||
duration = perf_counter() - started
|
||||
run = best.run
|
||||
return RunSample(
|
||||
duration_s=duration,
|
||||
net_outcomes={net_id: result.outcome for net_id, result in run.results_by_net.items()},
|
||||
valid_costs=best.valid_costs,
|
||||
reached_net_ids=tuple(net_id for net_id, result in run.results_by_net.items() if result.reached_target),
|
||||
out_of_bounds_net_ids=best.stage.out_of_bounds_net_ids,
|
||||
nodes_expanded=sum(trial.stage.nodes_expanded for trial in trials),
|
||||
route_iterations=sum(trial.run.metrics.route_iterations for trial in trials),
|
||||
topology=run.topology,
|
||||
stages=tuple(trial.stage for trial in trials),
|
||||
bundle_rejection=bundle_rejection,
|
||||
bundle_duration_s=bundle_duration,
|
||||
selected_stage=next(i for i, trial in enumerate(trials) if trial is best),
|
||||
)
|
||||
|
||||
|
||||
def _print_summary(mode: str, samples: list[RunSample]) -> None:
|
||||
run = samples[0]
|
||||
print(
|
||||
f" {mode}: {median(len(sample.valid_costs) for sample in samples):g}/{len(run.net_outcomes)} valid, "
|
||||
f"{median(len(sample.reached_net_ids) for sample in samples):g} reached, "
|
||||
f"{median(sample.nodes_expanded for sample in samples):g} A* nodes, "
|
||||
f"{median(sample.duration_s for sample in samples):.3f} s median",
|
||||
flush=True,
|
||||
)
|
||||
if run.valid_costs:
|
||||
print(f" valid-net cost {sum(run.valid_costs.values()):.2f}, nets {', '.join(run.valid_costs)}", flush=True)
|
||||
if run.out_of_bounds_net_ids:
|
||||
print(f" outside board {', '.join(run.out_of_bounds_net_ids)}", flush=True)
|
||||
if run.bundle_rejection is not None:
|
||||
print(f" bundle rejected; using direct-probe-near-port. {run.bundle_rejection}", flush=True)
|
||||
if mode in AUTOMATIC_POLICIES:
|
||||
selected = run.stages[run.selected_stage]
|
||||
policy = f", policy {selected.policy}" if selected.policy else ""
|
||||
print(f" selected {selected.planner}, mode {selected.mode}, operation {selected.operation}{policy}", flush=True)
|
||||
elapsed = {
|
||||
operation: median(sum(timing.duration_s for timing in sample.timings if timing.operation == operation) for sample in samples)
|
||||
for operation in ("plan", "verify", "search", "refine")
|
||||
}
|
||||
print(" median stage time " + ", ".join(f"{operation} {seconds:.3f} s" for operation, seconds in elapsed.items()), flush=True)
|
||||
if run.capacity_limit:
|
||||
limit = run.capacity_limit
|
||||
print(
|
||||
f" capacity {limit.tracks}/{limit.crossing_nets} across x={limit.cut_x:g}, at most {limit.max_routed} on the board",
|
||||
flush=True,
|
||||
)
|
||||
if run.port_conflicts:
|
||||
print(f" port spacing limits board to {len(run.net_outcomes) - len(run.port_conflicts)} nets", flush=True)
|
||||
return
|
||||
if mode in POLICIES:
|
||||
for stage in run.stages:
|
||||
if stage.kind == "bundle":
|
||||
continue
|
||||
if stage.kind == "lattice-probe":
|
||||
print(f" unlocked lattice probe at {stage.node_limit} nodes per attempt", flush=True)
|
||||
continue
|
||||
if stage.net_order is not None:
|
||||
incumbents = f", carried {', '.join(stage.incumbent_net_ids)}" if stage.incumbent_net_ids else ""
|
||||
print(f" {stage.mode} at {stage.node_limit} nodes per attempt, order {stage.net_order}{incumbents}", flush=True)
|
||||
continue
|
||||
skipped = f", skipped {', '.join(stage.skipped_net_ids)}" if stage.skipped_net_ids else ""
|
||||
print(
|
||||
f" {stage.mode} at {stage.node_limit} nodes per attempt after locking {len(stage.direct_net_ids)} direct routes{skipped}",
|
||||
flush=True,
|
||||
)
|
||||
if run.topology is not None:
|
||||
corridors = sum(count for _, count in run.topology.corridor_counts)
|
||||
seeds = ", ".join(run.topology.seeded_net_ids) or "none"
|
||||
print(
|
||||
f" {corridors} corridors across {len(run.topology.corridor_counts)} nets, "
|
||||
f"seeds {seeds}, {run.topology.seed_nodes_expanded} seed expansions",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
|
||||
def _geometry_json(value: object) -> dict:
|
||||
if isinstance(value, shapely.Polygon):
|
||||
return mapping(value)
|
||||
raise TypeError(f"Cannot serialize {type(value).__name__}")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
broader = (*VALIDATION_BENCHMARK_CASES, *FALLBACK_BENCHMARK_CASES, *EXTERNAL_BENCHMARK_CASES)
|
||||
case_groups = {case.name: (case,) for case in (*BENCHMARK_CASES, *broader, *CROSSING_BENCHMARK_CASES)}
|
||||
case_groups.update(
|
||||
{
|
||||
"all": BENCHMARK_CASES,
|
||||
"complex": COMPLEX_BENCHMARK_CASES,
|
||||
"holdout": VALIDATION_BENCHMARK_CASES,
|
||||
"fallback": FALLBACK_BENCHMARK_CASES,
|
||||
"external": EXTERNAL_BENCHMARK_CASES,
|
||||
"broad": broader,
|
||||
"crossings": CROSSING_BENCHMARK_CASES,
|
||||
}
|
||||
)
|
||||
defaults = RoutingOptions()
|
||||
parser = ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--profile", choices=PROFILES, default="matched-budget", help="Use controlled budgets or the public API defaults.")
|
||||
parser.add_argument(
|
||||
"--case",
|
||||
choices=tuple(case_groups),
|
||||
action="append",
|
||||
help="Select a case or suite. The broad suite includes the holdout, fallback, and external suites.",
|
||||
)
|
||||
parser.add_argument("--list", action="store_true", help="List the available cases.")
|
||||
parser.add_argument(
|
||||
"--mode",
|
||||
choices=("off", "guide", "seed", "automatic"),
|
||||
action="append",
|
||||
help="Repeat to compare modes. The public-defaults profile selects the shipped mode by default.",
|
||||
)
|
||||
parser.add_argument("--policy", choices=POLICIES, action="append", help="Include a routing policy. Repeat to compare policies.")
|
||||
parser.add_argument("--nodes", type=int, action="append", help="Repeat to compare node budgets. The matched-budget profile defaults to 500.")
|
||||
parser.add_argument("--iterations", type=int)
|
||||
parser.add_argument("--refinement", choices=("on", "off"), help="Override refinement for public routing modes.")
|
||||
parser.add_argument("--refinement-windows", metavar="N", help="Limit attempted windows per net, or use 'unlimited'.")
|
||||
parser.add_argument("--max-corridors", type=int, default=defaults.topology.max_corridors)
|
||||
parser.add_argument("--guide-strength", type=float, default=defaults.topology.guide_strength)
|
||||
parser.add_argument("--seed-nodes", type=int, default=defaults.topology.seed_node_limit)
|
||||
parser.add_argument("--sbend-offset", type=float, action="append", help="Override search S-bend offsets. Repeat for multiple offsets.")
|
||||
parser.add_argument("--net-order", choices=("user", "shortest", "longest"), default=defaults.congestion.net_order)
|
||||
parser.add_argument("--no-warm-start", action="store_true")
|
||||
parser.add_argument("--repeat", type=int, default=1, help="Run each configuration this many times and report median runtime.")
|
||||
parser.add_argument("--json", type=Path, help="Write options and individual runs to this file.")
|
||||
args = parser.parse_args()
|
||||
if args.list:
|
||||
for group, title in (
|
||||
("all", "Core corpus"),
|
||||
("holdout", "Held-out boards"),
|
||||
("fallback", "Fallback cases"),
|
||||
("external", "External cases"),
|
||||
("crossings", "Preplaced crossings"),
|
||||
):
|
||||
print(f"{title} (--case {group})")
|
||||
for case in case_groups[group]:
|
||||
print(f" {case.name:40} {case.description}")
|
||||
return
|
||||
use_public_defaults = args.profile == "public-defaults"
|
||||
default_budget = defaults.search.node_limit if use_public_defaults else 500
|
||||
budgets = tuple(dict.fromkeys(args.nodes or (default_budget,)))
|
||||
iterations = args.iterations if args.iterations is not None else (defaults.congestion.max_iterations if use_public_defaults else 2)
|
||||
if min(budgets) < 1 or iterations < 1 or args.repeat < 1:
|
||||
parser.error("--nodes, --iterations and --repeat must be positive")
|
||||
if args.sbend_offset is not None and not all(isfinite(offset) for offset in args.sbend_offset):
|
||||
parser.error("--sbend-offset must be finite")
|
||||
refinement_overrides: dict[str, bool | int | None] = {}
|
||||
if args.refinement is not None:
|
||||
refinement_overrides["enabled"] = args.refinement == "on"
|
||||
if args.refinement_windows is not None:
|
||||
limit_error = "--refinement-windows must be a positive integer or 'unlimited'"
|
||||
try:
|
||||
limit = None if args.refinement_windows == "unlimited" else int(args.refinement_windows)
|
||||
except ValueError:
|
||||
parser.error(limit_error)
|
||||
if limit is not None and limit < 1:
|
||||
parser.error(limit_error)
|
||||
refinement_overrides["max_windows_per_net"] = limit
|
||||
try:
|
||||
topology = replace(
|
||||
defaults.topology,
|
||||
max_corridors=args.max_corridors,
|
||||
guide_strength=args.guide_strength,
|
||||
seed_node_limit=args.seed_nodes,
|
||||
)
|
||||
except ValueError as exc:
|
||||
parser.error(str(exc))
|
||||
|
||||
groups = args.case or ["terminal-bench"]
|
||||
cases = {case.name: case for group in groups for case in case_groups[group]}.values()
|
||||
sbend_offsets = tuple(args.sbend_offset) if args.sbend_offset is not None else None
|
||||
records = []
|
||||
requested = [*(args.mode or ()), *(args.policy or ())]
|
||||
default_modes = (defaults.topology.mode,) if use_public_defaults else ("off", "guide", "seed")
|
||||
modes = tuple(dict.fromkeys(requested or default_modes))
|
||||
for case in cases:
|
||||
base = _public_defaults(case, defaults) if use_public_defaults else case.options
|
||||
for budget in budgets:
|
||||
print(f"{case.name} | {budget} nodes per attempt", flush=True)
|
||||
options = replace(
|
||||
base,
|
||||
topology=replace(topology, infer_terminal_headings=base.topology.infer_terminal_headings),
|
||||
search=replace(
|
||||
base.search, node_limit=budget, sbend_offsets=sbend_offsets if sbend_offsets is not None else base.search.sbend_offsets
|
||||
),
|
||||
refinement=replace(base.refinement, **refinement_overrides),
|
||||
congestion=replace(
|
||||
base.congestion,
|
||||
max_iterations=iterations,
|
||||
net_order=args.net_order,
|
||||
warm_start_enabled=not args.no_warm_start and defaults.congestion.warm_start_enabled,
|
||||
),
|
||||
)
|
||||
mode_options = {mode: _mode_options(options, mode, args.profile) for mode in modes}
|
||||
samples: dict[str, list[RunSample]] = {mode: [] for mode in modes}
|
||||
for repeat in range(args.repeat):
|
||||
offset = repeat % len(modes)
|
||||
for mode in modes[offset:] + modes[:offset]:
|
||||
samples[mode].append(_measure(case, mode_options[mode], mode))
|
||||
for mode in modes:
|
||||
_print_summary(mode, samples[mode])
|
||||
records.append(
|
||||
{
|
||||
"case": case.name,
|
||||
"strategy": mode,
|
||||
"requested_mode": mode_options[mode].topology.mode,
|
||||
"reference_net_ids": [net_id for net_id, _ in case.reference_paths],
|
||||
"options": asdict(mode_options[mode]),
|
||||
"samples": [asdict(sample) for sample in samples[mode]],
|
||||
"duration_s_median": median(sample.duration_s for sample in samples[mode]),
|
||||
"duration_s_p95": sorted(sample.duration_s for sample in samples[mode])[ceil(0.95 * len(samples[mode])) - 1],
|
||||
}
|
||||
)
|
||||
if args.json is not None:
|
||||
payload = {
|
||||
"profile": args.profile,
|
||||
"python": python_version(),
|
||||
"shapely": shapely.__version__,
|
||||
"geos": shapely.geos_version_string,
|
||||
"runs": records,
|
||||
}
|
||||
args.json.write_text(dumps(payload, indent=2, default=_geometry_json) + "\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
324
scripts/import_external_routing_benchmarks.py
Normal file
324
scripts/import_external_routing_benchmarks.py
Normal file
|
|
@ -0,0 +1,324 @@
|
|||
"""Convert pinned PIC Routing Benchmark and LiDAR inputs into inire fixtures."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from argparse import ArgumentParser
|
||||
from collections import defaultdict
|
||||
from csv import DictReader
|
||||
from dataclasses import dataclass
|
||||
from hashlib import file_digest
|
||||
from json import dumps, loads
|
||||
from math import ceil, floor
|
||||
from pathlib import Path
|
||||
from tarfile import TarFile
|
||||
from typing import TYPE_CHECKING
|
||||
from zipfile import ZipFile
|
||||
|
||||
from shapely import get_parts
|
||||
from shapely.affinity import scale, translate
|
||||
from shapely.geometry import Polygon, box
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable, Iterable
|
||||
|
||||
from shapely.geometry.base import BaseGeometry
|
||||
|
||||
|
||||
PIC_REVISION = "0c1f445792926d97fae01893c89e96b8a9393800"
|
||||
LIDAR_REVISION = "4e7004d32b0b80d959553797fb30f0737513de0c"
|
||||
PIC_DIGEST = "e4a9479a7fcabe64a0083bdab42a615e2200e7245ab5863a7bf109229d7ec588"
|
||||
LIDAR_DIGEST = "cfd7a43762a9e71435d6d91a488f31ae1527c8752179805bdb4c345cb3089ba3"
|
||||
UNITS_PER_MICRON = 10
|
||||
HEADINGS = {"E": 0, "N": 90, "W": 180, "S": 270}
|
||||
ROTATIONS = ((1, 0), (0, 1), (-1, 0), (0, -1))
|
||||
OUTPUT = Path(__file__).resolve().parents[1] / "inire/tests/data/external_routing_benchmarks.json"
|
||||
PIC_DESIGNS = (
|
||||
"splitter_tree_1x8_ew",
|
||||
"splitter_ring_mod_ap_combiner_2_ew",
|
||||
"splitter_mzm_combiner_4_ew",
|
||||
)
|
||||
LIDAR_DESIGNS = {
|
||||
"toy_example/toy_example.gp.yml": (),
|
||||
"clements_8x8/clements_8x8.yml": tuple(f"n_{n}" for n in range(30, 36)),
|
||||
"mrr_weight_bank_4x4/mrr_weight_bank_4x4.yml": tuple(f"n_{n}" for n in range(18, 26)),
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Pin:
|
||||
x: float
|
||||
y: float
|
||||
heading: int
|
||||
width: float
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Device:
|
||||
footprints: tuple[Polygon, ...]
|
||||
pins: dict[str, Pin]
|
||||
|
||||
|
||||
Connection = tuple[str, tuple[str, str], tuple[str, str]]
|
||||
|
||||
|
||||
def _rotate(x: float, y: float, angle: int) -> tuple[float, float]:
|
||||
if angle % 90:
|
||||
raise ValueError(f"Cannot import noncardinal rotation {angle}")
|
||||
ux, uy = ROTATIONS[int(angle // 90) % 4]
|
||||
return ux * x - uy * y, uy * x + ux * y
|
||||
|
||||
|
||||
def _footprint(bounds: tuple[float, float, float, float], transform: Callable[[float, float], tuple[float, float]]) -> Polygon:
|
||||
left, bottom, right, top = bounds
|
||||
return Polygon([transform(left, bottom), transform(right, bottom), transform(right, top), transform(left, top)])
|
||||
|
||||
|
||||
def _port_cutout(pin: Pin, width: float, clearance: float, extent: Polygon) -> Polygon:
|
||||
# Carve access only from this port's own device. Allow one lattice unit
|
||||
# for the snap from fractional source coordinates to inire's Port.
|
||||
margin = width / 2 + clearance + 1 / UNITS_PER_MICRON
|
||||
reach = max(extent.bounds[2] - extent.bounds[0], extent.bounds[3] - extent.bounds[1]) + 2 * margin
|
||||
return _footprint((-margin, -margin, reach, margin), lambda x, y: _pin_frame(pin, x, y))
|
||||
|
||||
|
||||
def _pin_frame(pin: Pin, x: float, y: float) -> tuple[float, float]:
|
||||
dx, dy = _rotate(x, y, pin.heading)
|
||||
return pin.x + dx, pin.y + dy
|
||||
|
||||
|
||||
def _polygons(shape: BaseGeometry) -> Iterable[Polygon]:
|
||||
for part in get_parts(shape):
|
||||
if isinstance(part, Polygon) and not part.is_empty and part.area > 0:
|
||||
yield part
|
||||
|
||||
|
||||
def _fixture(
|
||||
name: str,
|
||||
source: str,
|
||||
member: str,
|
||||
devices: dict[str, Device],
|
||||
connections: list[Connection],
|
||||
radius: float,
|
||||
clearance: float,
|
||||
*,
|
||||
die: tuple[float, float, float, float] | None = None,
|
||||
min_straight: float = 0.5,
|
||||
) -> dict:
|
||||
if not connections:
|
||||
raise ValueError(f"No compatible connections in {name}")
|
||||
active = {device for _, start, finish in connections for device, _ in (start, finish)}
|
||||
if die is None:
|
||||
bounds = [footprint.bounds for key in active for footprint in devices[key].footprints]
|
||||
pad = 4 * radius
|
||||
die = (
|
||||
floor(min(b[0] for b in bounds) - pad),
|
||||
floor(min(b[1] for b in bounds) - pad),
|
||||
ceil(max(b[2] for b in bounds) + pad),
|
||||
ceil(max(b[3] for b in bounds) + pad),
|
||||
)
|
||||
x0, y0, x1, y1 = die
|
||||
board = box(*die)
|
||||
cutouts: dict[str, list[Polygon]] = defaultdict(list)
|
||||
nets = []
|
||||
for net_id, (a, ap), (b, bp) in connections:
|
||||
start, finish = devices[a].pins[ap], devices[b].pins[bp]
|
||||
width = max(start.width, finish.width)
|
||||
for key, pin in ((a, start), (b, finish)):
|
||||
for footprint in devices[key].footprints:
|
||||
cutouts[key].append(_port_cutout(pin, width, clearance, footprint))
|
||||
nets.append(
|
||||
{
|
||||
"id": net_id,
|
||||
"start": [round((start.x - x0) * UNITS_PER_MICRON), round((start.y - y0) * UNITS_PER_MICRON), start.heading],
|
||||
"target": [round((finish.x - x0) * UNITS_PER_MICRON), round((finish.y - y0) * UNITS_PER_MICRON), (finish.heading + 180) % 360],
|
||||
"width": round(width * UNITS_PER_MICRON, 6),
|
||||
}
|
||||
)
|
||||
obstacles = []
|
||||
for key, device in devices.items():
|
||||
for footprint in device.footprints:
|
||||
clipped = footprint.intersection(board)
|
||||
for access in cutouts.get(key, ()):
|
||||
clipped = clipped.difference(access)
|
||||
for part in _polygons(clipped):
|
||||
local = scale(translate(part, -x0, -y0), xfact=UNITS_PER_MICRON, yfact=UNITS_PER_MICRON, origin=(0, 0))
|
||||
encoded = [[(round(x, 6), round(y, 6)) for x, y in ring.coords] for ring in (local.exterior, *local.interiors)]
|
||||
polygon = Polygon(encoded[0], encoded[1:])
|
||||
if polygon.area > 0:
|
||||
if not polygon.is_valid:
|
||||
raise ValueError(f"Invalid device geometry in {name}: {key}")
|
||||
obstacles.append(encoded)
|
||||
return {
|
||||
"name": name,
|
||||
"source": source,
|
||||
"member": member,
|
||||
"crop_um": list(die),
|
||||
"bounds": [0, 0, round((x1 - x0) * UNITS_PER_MICRON), round((y1 - y0) * UNITS_PER_MICRON)],
|
||||
"bend_radius": radius * UNITS_PER_MICRON,
|
||||
"clearance": clearance * UNITS_PER_MICRON,
|
||||
"min_straight": min_straight * UNITS_PER_MICRON,
|
||||
"obstacles": obstacles,
|
||||
"nets": nets,
|
||||
}
|
||||
|
||||
|
||||
def _pic_transform(place: dict, x: float, y: float, *, position: bool = True) -> tuple[float, float]:
|
||||
dx, dy = _rotate(-x if place["mirror_x"] else x, -y if place["mirror_y"] else y, place["orientation_deg"])
|
||||
return (dx + place["x_um"], dy + place["y_um"]) if position else (dx, dy)
|
||||
|
||||
|
||||
def _pic_device(cell: dict, place: dict, width: float) -> Device:
|
||||
w, h = cell["bbox"]["width_um"], cell["bbox"]["height_um"]
|
||||
outline = _footprint((-w / 2, -h / 2, w / 2, h / 2), lambda x, y: _pic_transform(place, x, y))
|
||||
pins = {}
|
||||
for name, port in cell["port_geometry"].items():
|
||||
x, y = _pic_transform(place, port["x_um"], port["y_um"])
|
||||
dx, dy = _pic_transform(place, *ROTATIONS[HEADINGS[port["orientation"]] // 90], position=False)
|
||||
pins[name] = Pin(x, y, ROTATIONS.index((dx, dy)) * 90, width)
|
||||
return Device((outline,), pins)
|
||||
|
||||
|
||||
def _pic_macro(module: dict, pdk: dict, place: dict) -> Device:
|
||||
# The selected designs use vertical edge-coupler arrays at the boundary.
|
||||
# Their constituent boxes remain obstacles, while optical I/O is outside
|
||||
# the primitive-to-primitive routing subproblem.
|
||||
children = module["instances"]
|
||||
attributes = module["attributes"]
|
||||
if not (attributes["hard_macro"] and attributes["array_axis"] == "V" and all(child["module"] == "EDGE_COUPLER" for child in children)):
|
||||
raise ValueError("Unsupported PIC macro in the selected design")
|
||||
box_size = pdk["EDGE_COUPLER"]["bbox"]
|
||||
w, h = box_size["width_um"], box_size["height_um"]
|
||||
outlines = []
|
||||
for i in range(len(children)):
|
||||
row = (i - (len(children) - 1) / 2) * attributes["pitch"]
|
||||
outlines.append(_footprint((-w / 2, row - h / 2, w / 2, row + h / 2), lambda x, y: _pic_transform(place, x, y)))
|
||||
return Device(tuple(outlines), {})
|
||||
|
||||
|
||||
def _pic_cases(archive: ZipFile) -> list[dict]:
|
||||
root = "pic-benchmark"
|
||||
pdk = loads(archive.read(f"{root}/pdk/pdk_v2_mzi80.json"))["device_defs"]
|
||||
rules = loads(archive.read(f"{root}/pdk/design_rules_v2_mzi80.json"))["routing_rules"]
|
||||
summary = list(DictReader(archive.read(f"{root}/data/_batch_summary.csv").decode().splitlines()))
|
||||
cases = []
|
||||
for design in PIC_DESIGNS:
|
||||
result = next(row for row in summary if row["design"] == design and row["variant"] == "rectilinear")
|
||||
if result["lvs_ok"] != "True" or result["drc_ok"] != "True" or int(result["n_crossings"]):
|
||||
raise ValueError(f"Source variant failed the crossing-free LVS and DRC screen: {design}")
|
||||
folder = f"{root}/data/{design}"
|
||||
source = loads(archive.read(f"{folder}/{design}_netlist.json"))
|
||||
member = f"{folder}/rectilinear/{design}_placement.json"
|
||||
placements = {row["instance"]: row for row in loads(archive.read(member))["placements"]}
|
||||
modules = source["modules"]
|
||||
devices = {}
|
||||
net_ports: dict[str, list[tuple[str, str, str]]] = defaultdict(list)
|
||||
for inst in modules[source["top_module"]]["instances"]:
|
||||
key, cell = inst["name"], inst["module"]
|
||||
module = modules[cell]
|
||||
if cell not in pdk:
|
||||
devices[key] = _pic_macro(module, pdk, placements[key])
|
||||
continue
|
||||
devices[key] = _pic_device(pdk[cell], placements[key], rules["waveguide_width_um"])
|
||||
directions = {port["name"]: port["direction"] for port in module["ports"]}
|
||||
for port, wire in inst["connections"].items():
|
||||
net_ports[wire].append((directions[port], key, port))
|
||||
connections = []
|
||||
for net_id, pins in sorted(net_ports.items()):
|
||||
if len(pins) != 2:
|
||||
continue
|
||||
source_pin, sink_pin = sorted(pins, reverse=True)
|
||||
if (source_pin[0], sink_pin[0]) != ("output", "input"):
|
||||
raise ValueError(f"Expected a directed 2-pin net in {design}: {net_id}")
|
||||
connections.append((net_id, (source_pin[1], source_pin[2]), (sink_pin[1], sink_pin[2])))
|
||||
cases.append(
|
||||
_fixture(
|
||||
f"pic-{design.lower().replace('_', '-')}",
|
||||
"pic-benchmark",
|
||||
member,
|
||||
devices,
|
||||
connections,
|
||||
rules["fixed_bend_radius_um"],
|
||||
rules["min_spacing_um"],
|
||||
min_straight=rules["min_straight_section_um"],
|
||||
)
|
||||
)
|
||||
return cases
|
||||
|
||||
|
||||
def _lidar_device(inst: dict, macro: dict) -> Device:
|
||||
_, (x0, y0), orientation, _ = inst["settings"]["placement"]
|
||||
w, h = macro["size"]
|
||||
rotations = {"N": 0, "S": 180, "W": 90, "E": 270, "FN": 0, "FS": 0}
|
||||
angle = rotations[orientation]
|
||||
sx, sy = (-1 if orientation == "FN" else 1), (-1 if orientation == "FS" else 1)
|
||||
rotated = [_rotate(sx * x, sy * y, angle) for x, y in ((0, 0), (w, 0), (w, h), (0, h))]
|
||||
tx, ty = x0 - min(x for x, _ in rotated), y0 - min(y for _, y in rotated)
|
||||
|
||||
def transform(x: float, y: float) -> tuple[float, float]:
|
||||
dx, dy = _rotate(sx * x, sy * y, angle)
|
||||
return dx + tx, dy + ty
|
||||
|
||||
pins = {}
|
||||
for name, port in (macro.get("pins") or {}).items():
|
||||
px, py = transform(port["pin_offset_x"], port["pin_offset_y"])
|
||||
hx, hy = _rotate(1, 0, port["pin_orient"])
|
||||
heading = ROTATIONS.index(_rotate(sx * hx, sy * hy, angle)) * 90
|
||||
pins[name] = Pin(px, py, heading, port["pin_width"])
|
||||
return Device((_footprint((0, 0, w, h), transform),), pins)
|
||||
|
||||
|
||||
def _lidar_cases(archive: TarFile) -> list[dict]:
|
||||
import yaml # noqa: PLC0415
|
||||
|
||||
class BenchmarkLoader(yaml.SafeLoader):
|
||||
"""Accept LiDAR's tuple-valued parameters as inert YAML sequences."""
|
||||
|
||||
BenchmarkLoader.add_constructor("tag:yaml.org,2002:python/tuple", yaml.SafeLoader.construct_sequence)
|
||||
cases = []
|
||||
for member, selected in LIDAR_DESIGNS.items():
|
||||
path = f"LiDAR-{LIDAR_REVISION}/src/picroute/benchmarks/{member}"
|
||||
source = archive.extractfile(path)
|
||||
if source is None:
|
||||
raise ValueError(f"Missing LiDAR input {member}")
|
||||
with source:
|
||||
netlist = yaml.load(source, Loader=BenchmarkLoader)
|
||||
devices = {name: _lidar_device(inst, netlist["library"][inst["settings"]["macro_type"]]) for name, inst in netlist["instances"].items()}
|
||||
connections = []
|
||||
for net_id in selected or netlist["nets"]:
|
||||
start, finish = netlist["nets"][net_id]
|
||||
a, ap = start.split(",")
|
||||
b, bp = finish.split(",")
|
||||
connections.append((net_id, (a, ap), (b, bp)))
|
||||
settings = netlist["settings"]
|
||||
die = tuple(value for corner in settings["die_area"] for value in corner) if not selected else None
|
||||
name = f"lidar-{settings['design'].replace('_', '-')}"
|
||||
cases.append(_fixture(name, "lidar", member, devices, connections, settings["wg_radius"], 1.0, die=die))
|
||||
return cases
|
||||
|
||||
|
||||
def _verify_archive(path: Path, expected: str) -> None:
|
||||
with path.open("rb") as stream:
|
||||
if file_digest(stream, "sha256").hexdigest() != expected:
|
||||
raise ValueError(f"Archive does not match the pinned SHA-256: {path}")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--pic-archive", type=Path, required=True)
|
||||
parser.add_argument("--lidar-archive", type=Path, required=True)
|
||||
parser.add_argument("--output", type=Path, default=OUTPUT)
|
||||
args = parser.parse_args()
|
||||
_verify_archive(args.pic_archive, PIC_DIGEST)
|
||||
_verify_archive(args.lidar_archive, LIDAR_DIGEST)
|
||||
with ZipFile(args.pic_archive) as pic, TarFile.open(args.lidar_archive) as lidar:
|
||||
data = {
|
||||
"units_per_micron": UNITS_PER_MICRON,
|
||||
"revisions": {"pic-benchmark": PIC_REVISION, "lidar": LIDAR_REVISION},
|
||||
"cases": [*_pic_cases(pic), *_lidar_cases(lidar)],
|
||||
}
|
||||
args.output.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.output.write_text(dumps(data, indent=2) + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
51
scripts/route_terminal_bench.py
Normal file
51
scripts/route_terminal_bench.py
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
"""Automatically route Terminal-Bench PR 345 and export waypoints."""
|
||||
|
||||
from argparse import ArgumentParser
|
||||
from dataclasses import replace
|
||||
from json import dumps
|
||||
from pathlib import Path
|
||||
from time import perf_counter
|
||||
|
||||
from shapely.geometry import box
|
||||
|
||||
from inire import TopologyOptions, route
|
||||
from inire.router._waypoints import export_waypoints
|
||||
from inire.tests.terminal_bench_scenario import LENGTH_COST, terminal_bench_options, terminal_bench_problem
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--output", type=Path, help="Write the verified waypoint plan to this JSON file.")
|
||||
parser.add_argument("--reference-lane-plan", action="store_true", help="Replay the manually supplied reference for comparison.")
|
||||
parser.add_argument("--single-bottom-track", action="store_true", help="Replay the manual reference with one bottom track.")
|
||||
args = parser.parse_args()
|
||||
|
||||
options = terminal_bench_options(max_iterations=1)
|
||||
options = replace(options, refinement=replace(options.refinement, enabled=False))
|
||||
started = perf_counter()
|
||||
if args.reference_lane_plan or args.single_bottom_track:
|
||||
from inire.tests.terminal_bench_lane_plan import terminal_bench_lane_problem # noqa: PLC0415
|
||||
|
||||
problem = terminal_bench_lane_problem(share_bottom_passage=not args.single_bottom_track)
|
||||
else:
|
||||
problem = terminal_bench_problem()
|
||||
options = replace(options, topology=TopologyOptions(mode="bundle", infer_terminal_headings=True))
|
||||
run = route(problem, options=options)
|
||||
elapsed = perf_counter() - started
|
||||
board = box(*problem.bounds)
|
||||
if run.results_by_net.keys() != {net.net_id for net in problem.nets}:
|
||||
parser.exit(1, "The route results do not cover the full waypoint plan\n")
|
||||
for net_id, result in run.results_by_net.items():
|
||||
if not result.is_valid or any(not board.covers(shape) for shape in result.locked_geometry):
|
||||
parser.exit(1, f"Lane plan failed inire verification for {net_id}\n")
|
||||
|
||||
cost = sum(component.length * LENGTH_COST[component.move_type] for result in run.results_by_net.values() for component in result.path)
|
||||
total = len(problem.nets)
|
||||
print(f"{total}/{total} verified, weighted cost {cost:.2f}, {run.metrics.nodes_expanded} A* expansions, {elapsed:.3f} s")
|
||||
if args.output is not None:
|
||||
waypoints = {net_id: export_waypoints(result.path) for net_id, result in run.results_by_net.items()}
|
||||
args.output.write_text(dumps({"nets": {net_id: {"waypoints": path} for net_id, path in waypoints.items()}}, indent=2) + "\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Loading…
Reference in a new issue