inire/inire/router/_automatic.py

648 lines
31 KiB
Python

"""Automatic planner selection and verified residual routing."""
from __future__ import annotations
from contextlib import contextmanager, suppress
from dataclasses import replace
from functools import partial
from itertools import chain, islice, pairwise, product
from time import perf_counter
from typing import TYPE_CHECKING
import shapely
from shapely.geometry import box
from inire.constants import TOLERANCE_LINEAR
from inire.geometry.collision import RoutingWorld
from inire.model import resolve_bend_geometry
from inire.results import AutomaticRoutingReport, RoutingStage, RoutingTiming, _planner_for_mode, _sum_route_metrics
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_seed_candidates
from inire.router._compact import compact_port_seed_set, short_shift_seed_set
from inire.router._congestion_policy import ordered_nets
from inire.router._perimeter import (
bundle_turnaround_candidates,
perimeter_detour_candidates,
residual_dogleg_candidates,
terminal_link_seed,
)
from inire.router._route_traces import complete_final_conflict_trace
from inire.router._routing_policy import (
LockPlan,
_best_trial,
_direct_trials,
_disconnected_nets,
_is_short_shift,
_residual_problem,
_route_prepared_residual,
_route_residual,
_trial,
)
from inire.router._seed_materialization import materialize_path_seed
from inire.router._stack import route_once
from inire.router._topology import plan_corridors
from inire.router.cost import build_native_cost_evaluator, weighted_path_length
from inire.seeds import SBendSeed
if TYPE_CHECKING:
from collections.abc import Callable, Iterable, Iterator
from typing import Literal
from shapely.geometry.base import BaseGeometry
from inire.model import NetSpec, RoutingOptions, RoutingProblem
from inire.results import RouteMetrics, RoutingOperation, RoutingResult, RoutingRunResult
from inire.router._routing_policy import Trial
from inire.router._topology import Corridor
from inire.router.cost import CostEvaluator
from inire.seeds import PathSeed
_INITIAL_NODE_LIMIT = 500
_NEAR_PORT_NODE_LIMIT = 100
_NEAR_PORT_ITERATION_LIMIT = 2
def _has_fragmented_shifts(trial: Trial) -> bool:
for net_id in trial.valid_costs:
path = trial.run.results_by_net[net_id].path
# A chain of S-bends with a short offset is a sign that the span
# planner is piecing together a shift across a single window.
for a, b in pairwise(path):
if a.move_type == b.move_type == "sbend" and any(
isinstance(move.move_spec, SBendSeed) and abs(move.move_spec.offset) <= move.move_spec.radius / 2 for move in (a, b)
):
return True
return False
class _AutomaticRun:
def __init__(
self,
problem: RoutingProblem,
options: RoutingOptions,
iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None,
) -> None:
self.raw_problem = problem
self.problem = problem
self.options = options
self.board = box(*problem.bounds)
self.metrics: list[RouteMetrics] = []
self.timings: list[RoutingTiming] = []
self.iteration_callback = iteration_callback
self.callback_index = 0
self.cost_pass_performed = False
self.evaluator: CostEvaluator | None = None
weights = options.topology.automatic_length_weights
self.length_weights = dict(zip(("straight", "bend90", "sbend"), weights, strict=True)) if weights is not None else None
@contextmanager
def _time(
self,
operation: RoutingOperation,
*,
planner: str | None = None,
mode: str | None = None,
policy: str | None = None,
) -> Iterator[None]:
index = len(self.timings)
timing = RoutingTiming(operation, 0.0, planner, mode, policy)
self.timings.append(timing)
started = perf_counter()
try:
yield
finally:
elapsed = perf_counter() - started
# Nested verification and search are labeled independently of candidate generation.
child_time = sum(child.duration_s for child in self.timings[index + 1 :])
self.timings[index] = replace(timing, duration_s=max(0.0, elapsed - child_time))
def _run(
self,
problem: RoutingProblem,
*,
options: RoutingOptions,
operation: RoutingOperation = "search",
planner: str | None = None,
policy: str | None = None,
corridors: dict[str, tuple[Corridor, ...]] | None = None,
) -> RoutingRunResult:
def notify(_iteration: int, results: dict[str, RoutingResult]) -> None:
assert self.iteration_callback is not None
self.iteration_callback(self.callback_index, results)
self.callback_index += 1
mode = options.topology.mode
time_operation = partial(self._time, planner=planner or _planner_for_mode(mode), mode=mode, policy=policy)
with time_operation(operation):
run = route_once(
problem,
options=options,
iteration_callback=notify if self.iteration_callback else None,
phase_timer=time_operation,
corridors=corridors,
)
self.metrics.append(run.metrics)
return run
def _selection_cost(self, result: RoutingResult) -> float:
if self.length_weights is not None:
return weighted_path_length(result.path, self.length_weights)
if self.evaluator is None:
self.evaluator = build_native_cost_evaluator(self.problem, self.options.objective)
return self.evaluator.path_cost(result.path[0].start_port, result.path)
def _trial(self, run: RoutingRunResult, stage: RoutingStage) -> Trial:
with self._time("verify", planner=stage.planner, mode=stage.mode, policy=stage.policy):
return _trial(run, stage, score=self._selection_cost)
def _seeded_problem(self, trial: Trial) -> RoutingProblem:
seeds = {net_id: trial.run.results_by_net[net_id].as_seed() for net_id in trial.valid_costs}
nets = tuple(net for net in self.problem.nets if net.net_id in seeds)
return replace(self.problem, nets=nets, initial_paths=seeds)
def _seeded_attempt(
self,
problem: RoutingProblem,
planner: str,
*,
kind: str,
policy: str | None,
operation: Literal["verify", "refine"],
) -> tuple[RoutingRunResult, RoutingStage]:
options = self.options
refinement = options.refinement
if operation == "verify":
refinement = replace(refinement, enabled=False)
worker = replace(
options,
search=replace(options.search, node_limit=1),
topology=replace(options.topology, mode="off"),
congestion=replace(options.congestion, max_iterations=1),
refinement=refinement,
)
run = self._run(problem, options=worker, operation=operation, planner=planner, policy=policy)
stage = RoutingStage(
worker.topology.mode,
(),
run.metrics.nodes_expanded,
worker.search.node_limit,
kind=kind,
planner=planner,
operation=operation,
policy=policy,
)
return run, stage
def _verify(self, problem: RoutingProblem, planner: str, *, kind: str | None = None, policy: str | None = None) -> Trial:
run, stage = self._seeded_attempt(problem, planner, kind=kind or planner, policy=policy, operation="verify")
return self._trial(run, stage)
def _constructive_trials(self) -> tuple[list[Trial], tuple[str, ...]]:
problem, options = self.problem, self.options
trials: list[Trial] = []
rejections = []
try:
with self._time("plan", planner="bundle"):
bundle = plan_ordered_bundle(self.raw_problem, options.search, infer_terminal_headings=True)
except ValueError as exc:
rejections.append(str(exc))
else:
if bundle.nets == problem.nets:
trials.append(self._verify(bundle, "bundle"))
if len(trials[-1].valid_costs) == len(problem.nets):
return trials, ()
rejections.append("Bundle candidate failed geometric verification")
elif not options.topology.infer_terminal_headings:
with self._time("plan", planner="bundle-turnaround"):
for candidate in bundle_turnaround_candidates(problem, bundle, options.search):
trials.append(self._verify(candidate, "bundle-turnaround"))
if len(trials[-1].valid_costs) == len(problem.nets):
return trials, ()
rejections.append("No geometrically verified turnaround matched the terminal headings")
with self._time("plan", planner="compact-port-jogs"):
compact = compact_port_seed_set(problem, options.search)
if compact is not None:
trials.append(self._verify(replace(problem, initial_paths=compact), "compact-port-jogs"))
if len(trials[-1].valid_costs) == len(problem.nets):
return trials, tuple(rejections)
span_trial = self._column_trial(False, trials)
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) is None:
rejections.append("Cost scoring found no verified column layout")
if not trials or len(_best_trial(trials).valid_costs) < len(problem.nets):
planner = "local-sbend"
with self._time("plan", planner=planner):
shifts = short_shift_seed_set(problem, options.search, self._selection_cost)
if shifts is not None:
trial = self._verify(replace(problem, initial_paths=shifts), planner)
complete = len(trial.valid_costs) == len(problem.nets)
trials.append(trial if complete else replace(trial, selection="incomplete-layout"))
if not complete:
rejections.append("Local S-bend layout failed full verification")
return trials, tuple(rejections)
def _column_trial(self, weighted: bool, trials: list[Trial]) -> Trial | None:
objective = self.options.objective
weights = self.length_weights or dict.fromkeys(("straight", "bend90", "sbend"), objective.unit_length_cost)
penalty = 0.0 if self.length_weights is not None else objective.sbend_penalty
policy = "weighted" if weighted else "span"
kind = "column-cost" if weighted else "column-span"
with self._time("plan", planner="column", policy=policy):
candidates = column_seed_candidates(self.problem, self.options.search, weights, weighted=weighted, sbend_penalty=penalty)
for seeds in islice(candidates, 8):
trial = self._verify(replace(self.problem, initial_paths=seeds), "column", kind=kind, policy=policy)
trials.append(trial)
if len(trial.valid_costs) == len(self.problem.nets):
return trial
return None
def _paired_perimeter(self, trials: list[Trial]) -> None:
problem, options = self.problem, self.options
if len(problem.nets) != 2:
return
world = RoutingWorld(clearance=problem.clearance, safety_zone_radius=problem.safety_zone_radius, board=self.board)
for obstacle in problem.static_obstacles:
world.add_static_obstacle(obstacle)
def footprints(net: NetSpec, seeds: Iterable[PathSeed]) -> list[tuple[PathSeed, BaseGeometry]]:
choices = []
for seed in seeds:
path = materialize_path_seed(seed, start=net.start, net_width=net.width, search=options.search, clearance=problem.clearance)
if not path or path[-1].end_port != net.target or not world.verify_path_report(net.net_id, path).is_valid:
continue
footprint = shapely.union_all([shape for component in path for shape in component.physical_geometry])
choices.append((seed, footprint))
return choices
candidates: list[list[tuple[PathSeed, BaseGeometry]]] = []
links: list[list[tuple[PathSeed, BaseGeometry]]] = []
for net in problem.nets:
supplied = problem.initial_paths.get(net.net_id)
simple = supplied if supplied is not None else terminal_link_seed(net, options.search)
links.append(footprints(net, (simple,)) if simple is not None else [])
single = replace(problem, nets=(net,), initial_paths={})
detours = (seed for _, seed in islice(perimeter_detour_candidates(single, options.search), 32))
candidates.append(links[-1] if supplied is not None else [*links[-1], *footprints(net, detours)])
pairs: Iterable[tuple[tuple[PathSeed, BaseGeometry], tuple[PathSeed, BaseGeometry]]] = product(*candidates)
first, second = problem.nets
for index, net in enumerate(problem.nets):
if net.net_id in problem.initial_paths or not links[1 - index]:
continue
peer_link = links[1 - index][0]
obstacles = problem.static_obstacles + tuple(shapely.get_parts(peer_link[1]))
reserved = replace(problem, nets=(net,), initial_paths={}, static_obstacles=obstacles)
detours = footprints(net, (seed for _, seed in islice(perimeter_detour_candidates(reserved, options.search), 16)))
reserved_pairs = product(detours, (peer_link,)) if index == 0 else product((peer_link,), detours)
pairs = chain(pairs, reserved_pairs)
for (first_seed, first_shape), (second_seed, second_shape) in pairs:
if first_shape.distance(second_shape) < problem.clearance - TOLERANCE_LINEAR:
continue
plan = replace(problem, initial_paths={first.net_id: first_seed, second.net_id: second_seed})
trial = self._verify(plan, "paired-perimeter")
trials.append(trial)
if len(trial.valid_costs) == len(problem.nets):
return
trials[-1] = replace(trial, selection="incomplete-layout")
def _perimeter_trials(self, options: RoutingOptions) -> list[Trial]:
problem = self.problem
trials = []
if len(problem.nets) == 2:
with self._time("plan", planner="paired-perimeter"):
self._paired_perimeter(trials)
if trials and len(trials[-1].valid_costs) == len(problem.nets):
return trials
for net, seed in islice(perimeter_detour_candidates(problem, options.search), 32):
detour_problem = replace(problem, nets=(net,), initial_paths={net.net_id: seed})
candidate = self._verify(detour_problem, "perimeter", kind="perimeter-check")
if len(problem.nets) == 1 and candidate.valid_costs:
trials.append(replace(candidate, stage=replace(candidate.stage, kind="perimeter")))
break
trials.append(replace(candidate, selection="local-only"))
if not candidate.valid_costs:
continue
chosen = candidate.run.results_by_net[net.net_id]
policy = "perimeter-residual"
guide = replace(options, congestion=replace(options.congestion, max_iterations=1))
run, stage = _route_residual(
problem,
guide,
LockPlan({net.net_id: chosen}),
residual_mode="guide",
run_route=partial(self._run, policy=policy),
)
stage = replace(stage, kind=policy, policy=policy, planner="perimeter")
trials.append(self._trial(run, stage))
if len(trials[-1].valid_costs) == len(problem.nets):
trials[-1] = replace(trials[-1], selection="requires-layout-check")
seeds = {net_id: result.as_seed() for net_id, result in run.results_by_net.items()}
trials.append(self._verify(replace(problem, initial_paths=seeds), "perimeter"))
if len(trials[-1].valid_costs) == len(problem.nets):
break
return trials
def _incumbent_trials(self, options: RoutingOptions, best: Trial, target: int) -> list[Trial]:
problem = self.problem
retained = {net_id: best.run.results_by_net[net_id] for net_id in best.valid_costs}
with self._time("plan", policy="incumbent-retry"):
blocked = _disconnected_nets(problem, self.board, options, retained)
if blocked:
seeds = {net_id: result.as_seed() for net_id, result in retained.items()}
run = self._run(replace(problem, initial_paths=seeds), options=options, policy="incumbent-retry")
stage = RoutingStage(
"seed",
(),
run.metrics.nodes_expanded,
options.search.node_limit,
kind="incumbent-retry",
policy="incumbent-retry",
incumbent_net_ids=tuple(retained),
retry_reason=f"Incumbents disconnect {', '.join(sorted(blocked))} when locked",
)
return [self._trial(run, stage)]
policy = "incumbent-residual"
locks = LockPlan(retained)
residual = _residual_problem(problem, locks)
run, stage = _route_prepared_residual(residual, options, locks, residual_mode="seed", run_route=partial(self._run, policy=policy))
stage = replace(stage, kind=policy, policy=policy, retry_reason="Residual terminals remain connected with the incumbents locked")
trial = self._trial(run, stage)
if len(trial.valid_costs) == len(problem.nets):
return [replace(trial, selection="requires-layout-check"), self._verify_incumbent(trial)]
trials = [trial]
if len(trial.valid_costs) < target:
dogleg = self._residual_dogleg_trial(options, _best_trial([best, trial]))
if dogleg is not None:
return [trial, dogleg]
joint = self._joint_lane_trial(residual, options, locks, trial)
if joint is not None:
trials.append(replace(joint, selection="requires-layout-check"))
if joint.improves_on(_best_trial([best, trial])):
trials.append(self._verify_incumbent(joint))
return trials
def _verify_incumbent(self, trial: Trial) -> Trial:
problem = self._seeded_problem(trial)
# Check the seeded subproblem before restoring the unresolved results.
verified = self._verify(problem, trial.stage.planner, kind="incumbent-verified", policy=trial.stage.policy)
results = {**trial.run.results_by_net, **verified.run.results_by_net}
return replace(verified.as_replacement_for(trial), run=replace(verified.run, results_by_net=results))
def _residual_dogleg_trial(self, options: RoutingOptions, incumbent: Trial) -> Trial | None:
problem = self.problem
if len(incumbent.valid_costs) != len(problem.nets) - 1:
return None
retained = {net_id: incumbent.run.results_by_net[net_id] for net_id in incumbent.valid_costs}
residual = _residual_problem(problem, LockPlan(retained))
(net,) = residual.nets
seeds = {net_id: result.as_seed() for net_id, result in retained.items()}
planner = "residual-dogleg"
with self._time("plan", planner=planner, policy=planner):
for seed in islice(residual_dogleg_candidates(residual, options.search), 8):
candidate = replace(problem, initial_paths={**seeds, net.net_id: seed})
trial = self._verify(candidate, planner, policy=planner)
if len(trial.valid_costs) == len(problem.nets):
return trial
return None
def _direct(self, options: RoutingOptions, policy: str) -> list[Trial]:
with self._time("plan", planner="direct", policy=policy):
return _direct_trials(
self.problem,
self.board,
options,
policy,
run_route=partial(self._run, policy=policy),
check_trial=self._trial,
)
def _early_guide(self, options: RoutingOptions) -> Trial | None:
problem = self.problem
if (
len(problem.nets) <= 2
or problem.initial_paths
or options.search.node_limit <= _NEAR_PORT_NODE_LIMIT
or options.congestion.shuffle_nets
):
return None
max_offset = 2 * max(options.search.sbend_radii, default=0)
if not all(_is_short_shift(net, max_offset) for net in problem.nets) or len({net.start.r % 180 for net in problem.nets}) < 2:
return None
policy = "early-guide"
guide = replace(options, topology=replace(options.topology, mode="guide"))
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:
problem = self.problem
if target != len(problem.nets) or problem.initial_paths:
return False
with self._time("plan", planner="column-jogs"):
for seeds in islice(column_jog_candidates(problem, options.search), 8):
trial = self._verify(replace(problem, initial_paths=seeds), "column-jogs")
if len(trial.valid_costs) == target:
trials.append(trial)
return True
return False
def _search_trials(self, trials: list[Trial], target: int) -> None:
configured_search = self.options.search
first_limit = min(_INITIAL_NODE_LIMIT, configured_search.node_limit)
options = replace(
self.options,
search=replace(configured_search, node_limit=first_limit),
refinement=replace(self.options.refinement, enabled=False),
)
if self._initial_search_trials(options, trials, target):
return
self._seed_recovery_trials(options, trials, target)
if len(_best_trial(trials).valid_costs) < target:
self._lattice_fallback(trials, options, "Automatic planners left unresolved nets")
if first_limit < configured_search.node_limit and len(_best_trial(trials).valid_costs) < target:
self._lattice_fallback(
trials,
replace(options, search=configured_search),
"Initial pass fell short of the routing bound",
policy="budget-escalation",
)
def _initial_search_trials(self, options: RoutingOptions, trials: list[Trial], target: int) -> bool:
problem = self.problem
early = self._early_guide(options)
if early is not None:
trials.append(early)
if len(_best_trial(trials).valid_costs) >= target:
return True
try_construction_early = not options.congestion.shuffle_nets
if try_construction_early and self._try_column_jogs(options, trials, target):
return True
probe_iterations = options.congestion.max_iterations
proxy, _ = resolve_bend_geometry(options.search)
# Clipped proxies can find cheaper routes in later probe iterations than in the wider retry.
if proxy == "arc":
probe_iterations = min(_NEAR_PORT_ITERATION_LIMIT, probe_iterations)
probe_options = replace(
options,
search=replace(options.search, node_limit=min(_NEAR_PORT_NODE_LIMIT, options.search.node_limit)),
congestion=replace(options.congestion, max_iterations=probe_iterations),
)
probe = self._direct(probe_options, "direct-probe-near-port")
trials.extend(probe)
if len(_best_trial(trials).valid_costs) >= target:
return True
if not try_construction_early and self._try_column_jogs(options, trials, target):
return True
if try_construction_early and target == len(problem.nets) and target > 2 and not problem.initial_paths:
dogleg = self._residual_dogleg_trial(options, _best_trial(probe))
if dogleg is not None:
trials.append(dogleg)
return True
if len(problem.nets) <= 2:
with self._time("plan", planner="perimeter"):
trials.extend(self._perimeter_trials(options))
if len(_best_trial(trials).valid_costs) >= target:
return True
# Every short shift has lateral displacement, so the direct retry cannot lock
# any straight paths. It would run the same guide with the same budget.
if early is None or early.run.metrics.timeout_events:
trials.extend(self._direct(options, "direct-lookahead-retry"))
return len(_best_trial(trials).valid_costs) >= target
def _seed_recovery_trials(self, options: RoutingOptions, trials: list[Trial], target: int) -> None:
problem = self.problem
best = _best_trial(trials)
seeded = replace(options, topology=replace(options.topology, mode="seed"))
if best.valid_costs and len(problem.nets) > 2 and not problem.initial_paths:
trials.extend(self._incumbent_trials(seeded, best, target))
if len(_best_trial(trials).valid_costs) < target:
run = self._run(problem, options=seeded, policy="seed-fallback")
stage = RoutingStage("seed", (), run.metrics.nodes_expanded, options.search.node_limit, policy="seed-fallback")
trials.append(self._trial(run, stage))
def _joint_lane_trial(self, residual: RoutingProblem, options: RoutingOptions, locks: LockPlan, previous: Trial) -> Trial | None:
if len(residual.nets) < 2:
return None
policy = "joint-portal-lanes"
unresolved = frozenset(net.net_id for net in residual.nets if net.net_id not in previous.valid_costs)
nets = ordered_nets(residual.nets, options.congestion.net_order)
with self._time("plan", planner="corridor-seed", mode="seed", policy=policy):
corridors = plan_corridors(
residual.bounds,
residual.static_obstacles,
nets,
clearance=residual.clearance,
bend_radius=min(options.search.bend_radii, default=0.0),
limit=options.topology.max_corridors,
joint_net_ids=unresolved,
)
if not corridors:
return None
retry = replace(options, congestion=replace(options.congestion, max_iterations=min(3, options.congestion.max_iterations)))
run, stage = _route_prepared_residual(
residual, retry, locks, residual_mode="seed", run_route=partial(self._run, policy=policy, corridors=corridors)
)
stage = replace(
stage,
policy=policy,
incumbent_net_ids=tuple(locks.direct),
retry_reason="Unresolved nets share a portal with alternative lane assignments",
)
return self._trial(run, stage)
def _lattice_fallback(self, trials: list[Trial], options: RoutingOptions, reason: str, *, policy: str | None = None) -> None:
run = self._run(self.problem, options=replace(options, topology=replace(options.topology, mode="off")), policy=policy)
stage = RoutingStage(
"off",
(),
run.metrics.nodes_expanded,
options.search.node_limit,
kind="lattice-fallback",
policy=policy,
retry_reason=reason,
)
trials.append(self._trial(run, stage))
def _refine(self, trials: list[Trial]) -> None:
best = _best_trial(trials)
if not self.options.refinement.enabled or not best.valid_costs:
return
run, stage = self._seeded_attempt(
self._seeded_problem(best),
best.stage.planner,
kind="refinement",
policy=best.stage.policy,
operation="refine",
)
# Keep reports for unresolved routes when merging the refined subset.
results = {**best.run.results_by_net, **run.results_by_net}
refined = self._trial(replace(run, results_by_net=results), stage)
# Only a whole verified replacement of the incumbent can win.
trials.append(refined.as_replacement_for(best))
def execute(self) -> RoutingRunResult:
started = perf_counter()
options = self.options
proxy, physical = resolve_bend_geometry(options.search)
cut = None
conflicts = ()
rejections = ()
target = len(self.problem.nets)
trials: list[Trial] = []
if not self.problem.nets or options.search.node_limit <= 0 or options.congestion.max_iterations <= 0:
self._lattice_fallback(trials, options, "No automatic search requested")
elif isinstance(proxy, shapely.Polygon) or physical != "arc":
self._lattice_fallback(trials, options, "Custom bend geometry uses lattice routing")
elif not hasattr(shapely, "constrained_delaunay_triangles") or shapely.geos_version < (3, 10):
self._lattice_fallback(trials, options, "Constrained triangulation is unavailable")
else:
with self._time("plan"):
if options.topology.infer_terminal_headings and not self.problem.initial_paths:
with suppress(ValueError):
self.problem = ordered_bundle_terminal_headings(self.raw_problem)
cut = cut_capacity(self.problem, options)
conflicts = port_conflicts(self.problem, options)
target -= len(conflicts)
if cut:
target = min(target, cut.max_routed)
if not cut and not conflicts:
trials, rejections = self._constructive_trials()
if not any(trial.selectable for trial in trials) or len(_best_trial(trials).valid_costs) < target:
self._search_trials(trials, target)
self._refine(trials)
best = _best_trial(trials)
metrics = _sum_route_metrics(self.metrics)
report = AutomaticRoutingReport(
tuple(trial.stage for trial in trials),
next(i for i, trial in enumerate(trials) if trial is best),
target,
capacity_limit=cut,
port_conflicts=conflicts,
planner_rejections=rejections,
cost_pass_performed=self.cost_pass_performed,
timings=tuple(self.timings),
duration_s=perf_counter() - started,
)
return replace(complete_final_conflict_trace(best.run), metrics=metrics, automatic=report)
def route_automatic(
problem: RoutingProblem,
options: RoutingOptions,
iteration_callback: Callable[[int, dict[str, RoutingResult]], None] | None = None,
) -> RoutingRunResult:
return _AutomaticRun(problem, options, iteration_callback).execute()