Build only reachable S-bend sequences that fit a window

This commit is contained in:
Jan Petykiewicz 2026-11-30 09:54:11 -08:00
commit 5016c0e76a
2 changed files with 72 additions and 26 deletions

View file

@ -5,7 +5,7 @@ from __future__ import annotations
from collections import defaultdict from collections import defaultdict
from dataclasses import dataclass from dataclasses import dataclass
from functools import cache, lru_cache from functools import cache, lru_cache
from heapq import merge from heapq import heappop, heappush, merge
from itertools import combinations_with_replacement, islice, pairwise, product from itertools import combinations_with_replacement, islice, pairwise, product
from math import acos, ceil, comb, cos, floor, gcd, isfinite, pi, sin from math import acos, ceil, comb, cos, floor, gcd, isfinite, pi, sin
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
@ -290,6 +290,7 @@ def _bend_sequences(
radius: int, radius: int,
weights: Mapping[str, float], weights: Mapping[str, float],
*, *,
max_usable: int,
weighted: bool, weighted: bool,
sbend_penalty: float, sbend_penalty: float,
allowed_offsets: frozenset[float] | None = None, allowed_offsets: frozenset[float] | None = None,
@ -298,8 +299,8 @@ def _bend_sequences(
positive = {d: span for d, span in spans.items() if d in allowed_offsets} positive = {d: span for d, span in spans.items() if d in allowed_offsets}
negative = {d: span for d, span in spans.items() if -d in allowed_offsets} negative = {d: span for d, span in spans.items() if -d in allowed_offsets}
if positive != negative: if positive != negative:
choose_up = _bend_sequences(positive, radius, weights, weighted=weighted, sbend_penalty=sbend_penalty) choose_up = _bend_sequences(positive, radius, weights, max_usable=max_usable, weighted=weighted, sbend_penalty=sbend_penalty)
choose_down = _bend_sequences(negative, radius, weights, weighted=weighted, sbend_penalty=sbend_penalty) choose_down = _bend_sequences(negative, radius, weights, max_usable=max_usable, weighted=weighted, sbend_penalty=sbend_penalty)
def choose_signed(delta: int, usable: int) -> _BendSequence | None: def choose_signed(delta: int, usable: int) -> _BendSequence | None:
return (choose_down if delta < 0 else choose_up)(delta, usable) return (choose_down if delta < 0 else choose_up)(delta, usable)
@ -308,30 +309,30 @@ def _bend_sequences(
spans = positive spans = positive
# Each S-bend replaces a straight of its forward span in this window. # Each S-bend replaces a straight of its forward span in this window.
bend_costs = { bends = [
d: sbend_penalty + weights["sbend"] * 2 * radius * acos(1 - d / (2 * radius)) - weights["straight"] * span for d, span in spans.items() (d, span, sbend_penalty + weights["sbend"] * 2 * radius * acos(1 - d / (2 * radius)) - weights["straight"] * span)
} for d, span in spans.items()
# Only multiples of the common offset stride can occur in a sequence. if span <= max_usable
stride = gcd(*spans) or 1 ]
bends = [(offset // stride, offset, span) for offset, span in spans.items()] sequences = {0: (_BendSequence((), 0, 0.0),)}
sequences: list[tuple[_BendSequence, ...]] = [(_BendSequence((), 0, 0.0),)] upcoming = sorted(offset for offset, _, _ in bends)
stride = gcd(*upcoming) or 1
queued = set(upcoming)
@lru_cache(maxsize=4096) @lru_cache(maxsize=4096)
def choose(delta: int, usable: int) -> _BendSequence | None: def choose(delta: int, usable: int) -> _BendSequence | None:
magnitude = abs(delta) magnitude = abs(delta)
# A circular S-bend advances at least as far as it shifts. # A circular S-bend advances at least as far as it shifts.
if magnitude > usable: if magnitude > usable or magnitude % stride:
return None return None
index, remainder = divmod(magnitude, stride) while upcoming and upcoming[0] <= magnitude:
if remainder or (index and not bends): height = heappop(upcoming)
return None queued.remove(height)
while len(sequences) <= index:
height = len(sequences)
candidates = [ candidates = [
_BendSequence((offset, *prefix.offsets), span + prefix.span, bend_costs[offset] + prefix.cost) _BendSequence((offset, *prefix.offsets), span + prefix.span, cost + prefix.cost)
for step, offset, span in bends for offset, span, cost in bends
if step <= height for prefix in sequences.get(height - offset, ())
for prefix in sequences[height - step] if span + prefix.span <= max_usable
] ]
candidates.sort( candidates.sort(
key=lambda candidate: ( key=lambda candidate: (
@ -340,12 +341,19 @@ def _bend_sequences(
tuple(-d for d in candidate.offsets), tuple(-d for d in candidate.offsets),
) )
) )
frontier = [] frontier: list[_BendSequence] = []
for candidate in candidates: for candidate in candidates:
if not frontier or (weighted and candidate.cost < frontier[-1].cost - 1e-9): if not frontier or (weighted and candidate.cost < frontier[-1].cost - 1e-9):
frontier.append(candidate) frontier.append(candidate)
sequences.append(tuple(frontier)) sequences[height] = tuple(frontier)
viable = [candidate for candidate in sequences[index] if candidate.span <= usable] # The shortest prefix determines whether a successor can fit.
remaining = max_usable - frontier[0].span
for offset, span, _ in bends:
next_height = height + offset
if span <= remaining and next_height not in queued:
heappush(upcoming, next_height)
queued.add(next_height)
viable = [candidate for candidate in sequences.get(magnitude, ()) if candidate.span <= usable]
if not viable: if not viable:
return None return None
best = viable[-1] best = viable[-1]
@ -388,7 +396,10 @@ def _schedules(
sbend_penalty: float, sbend_penalty: float,
allowed_offsets: frozenset[float] | None = None, allowed_offsets: frozenset[float] | None = None,
) -> Iterator[tuple[tuple[Profile, ...], tuple[tuple[_BendSequence, ...], ...]]]: ) -> Iterator[tuple[tuple[Profile, ...], tuple[tuple[_BendSequence, ...], ...]]]:
choose = _bend_sequences(spans, radius, weights, weighted=weighted, sbend_penalty=sbend_penalty, allowed_offsets=allowed_offsets) max_usable = max(before - after - 4 for (_, after), (before, _) in pairwise(windows))
choose = _bend_sequences(
spans, radius, weights, max_usable=max_usable, weighted=weighted, sbend_penalty=sbend_penalty, allowed_offsets=allowed_offsets,
)
needs = tuple((a + b) / 2 + clearance for a, b in pairwise(widths)) needs = tuple((a + b) / 2 + clearance for a, b in pairwise(widths))
# The track order allows a local check of each neighboring pair. The # The track order allows a local check of each neighboring pair. The

View file

@ -48,7 +48,7 @@ def test_automatic_column_routes_use_only_enabled_signed_sbends(sign) -> None:
def test_sbend_sequence_skips_table_growth_for_shifts_larger_than_the_window(monkeypatch) -> None: def test_sbend_sequence_skips_table_growth_for_shifts_larger_than_the_window(monkeypatch) -> None:
make_sequence = Mock(wraps=_columns._BendSequence) make_sequence = Mock(wraps=_columns._BendSequence)
monkeypatch.setattr(_columns, "_BendSequence", make_sequence) monkeypatch.setattr(_columns, "_BendSequence", make_sequence)
choose = _columns._bend_sequences({10: 30}, 25, LENGTH_COST, weighted=False, sbend_penalty=0) choose = _columns._bend_sequences({10: 30}, 25, LENGTH_COST, max_usable=40, weighted=False, sbend_penalty=0)
make_sequence.reset_mock() make_sequence.reset_mock()
assert choose(100, 40) is None assert choose(100, 40) is None
@ -66,7 +66,7 @@ def test_sbend_sequences_use_the_common_offset_stride() -> None:
spans = SparseSpans({40_000_000: 120_000_000, 80_000_000: 160_000_000}) spans = SparseSpans({40_000_000: 120_000_000, 80_000_000: 160_000_000})
spans.scans = 0 spans.scans = 0
choose = _columns._bend_sequences(spans, 100_000_000, LENGTH_COST, weighted=False, sbend_penalty=0) choose = _columns._bend_sequences(spans, 100_000_000, LENGTH_COST, max_usable=280_000_000, weighted=False, sbend_penalty=0)
assert choose(40_000_001, 120_000_000) is None assert choose(40_000_001, 120_000_000) is None
assert choose(40_000_000, 119_999_999) is None assert choose(40_000_000, 119_999_999) is None
@ -75,6 +75,41 @@ def test_sbend_sequences_use_the_common_offset_stride() -> None:
assert choose(120_000_000, 280_000_000).offsets == (80_000_000, 40_000_000) assert choose(120_000_000, 280_000_000).offsets == (80_000_000, 40_000_000)
def test_sbend_sequence_only_builds_reachable_shifts_within_the_maximum_window(monkeypatch) -> None:
max_usable = 399_891
make_sequence = _columns._BendSequence
built = 0
def count_sequence(offsets, span, cost):
nonlocal built
built += 1
assert span <= max_usable
assert built <= 81
return make_sequence(offsets, span, cost)
monkeypatch.setattr(_columns, "_BendSequence", count_sequence)
choose = _columns._bend_sequences(
{20: 5000, 125_002: 375_006}, 312_505, LENGTH_COST, max_usable=max_usable, weighted=False, sbend_penalty=0,
)
assert choose(125_000, max_usable) is None
sequence = choose(125_002, max_usable)
assert sequence.offsets == (125_002,)
assert sequence.span == 375_006
def test_weighted_sbend_sequence_keeps_both_short_and_low_cost_choices() -> None:
weights = {"straight": 1.0, "sbend": 1.0}
choose = _columns._bend_sequences({2: 14, 10: 30}, 25, weights, max_usable=70, weighted=True, sbend_penalty=0)
short = choose(10, 30)
low_cost = choose(10, 70)
assert short.offsets == (10,)
assert low_cost.offsets == (2,) * 5
assert low_cost.cost < short.cost
def test_exact_sbend_spans_filter_by_window_and_configured_offsets() -> None: def test_exact_sbend_spans_filter_by_window_and_configured_offsets() -> None:
assert exact_sbend_spans(25, max_span=40, offsets=(-20, 10, 40, 0)) == {10: 30, 20: 40} assert exact_sbend_spans(25, max_span=40, offsets=(-20, 10, 40, 0)) == {10: 30, 20: 40}
assert exact_sbend_spans(25, max_span=39, offsets=(-20,)) == {} assert exact_sbend_spans(25, max_span=39, offsets=(-20,)) == {}