From 5016c0e76a9d1db27ba3d5b9baf44393a246917c Mon Sep 17 00:00:00 2001 From: Jan Petykiewicz Date: Mon, 30 Nov 2026 09:54:11 -0800 Subject: [PATCH] Build only reachable S-bend sequences that fit a window --- inire/router/_columns.py | 59 ++++++++++++++++++++++--------------- inire/tests/test_columns.py | 39 ++++++++++++++++++++++-- 2 files changed, 72 insertions(+), 26 deletions(-) diff --git a/inire/router/_columns.py b/inire/router/_columns.py index bf9f4c9..7f60437 100644 --- a/inire/router/_columns.py +++ b/inire/router/_columns.py @@ -5,7 +5,7 @@ from __future__ import annotations from collections import defaultdict from dataclasses import dataclass 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 math import acos, ceil, comb, cos, floor, gcd, isfinite, pi, sin from typing import TYPE_CHECKING @@ -290,6 +290,7 @@ def _bend_sequences( radius: int, weights: Mapping[str, float], *, + max_usable: int, weighted: bool, sbend_penalty: float, 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} negative = {d: span for d, span in spans.items() if -d in allowed_offsets} if positive != negative: - choose_up = _bend_sequences(positive, radius, weights, weighted=weighted, sbend_penalty=sbend_penalty) - choose_down = _bend_sequences(negative, 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, max_usable=max_usable, weighted=weighted, sbend_penalty=sbend_penalty) def choose_signed(delta: int, usable: int) -> _BendSequence | None: return (choose_down if delta < 0 else choose_up)(delta, usable) @@ -308,30 +309,30 @@ def _bend_sequences( spans = positive # Each S-bend replaces a straight of its forward span in this window. - bend_costs = { - d: 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. - stride = gcd(*spans) or 1 - bends = [(offset // stride, offset, span) for offset, span in spans.items()] - sequences: list[tuple[_BendSequence, ...]] = [(_BendSequence((), 0, 0.0),)] + bends = [ + (d, span, sbend_penalty + weights["sbend"] * 2 * radius * acos(1 - d / (2 * radius)) - weights["straight"] * span) + for d, span in spans.items() + if span <= max_usable + ] + sequences = {0: (_BendSequence((), 0, 0.0),)} + upcoming = sorted(offset for offset, _, _ in bends) + stride = gcd(*upcoming) or 1 + queued = set(upcoming) @lru_cache(maxsize=4096) def choose(delta: int, usable: int) -> _BendSequence | None: magnitude = abs(delta) # A circular S-bend advances at least as far as it shifts. - if magnitude > usable: + if magnitude > usable or magnitude % stride: return None - index, remainder = divmod(magnitude, stride) - if remainder or (index and not bends): - return None - while len(sequences) <= index: - height = len(sequences) + while upcoming and upcoming[0] <= magnitude: + height = heappop(upcoming) + queued.remove(height) candidates = [ - _BendSequence((offset, *prefix.offsets), span + prefix.span, bend_costs[offset] + prefix.cost) - for step, offset, span in bends - if step <= height - for prefix in sequences[height - step] + _BendSequence((offset, *prefix.offsets), span + prefix.span, cost + prefix.cost) + for offset, span, cost in bends + for prefix in sequences.get(height - offset, ()) + if span + prefix.span <= max_usable ] candidates.sort( key=lambda candidate: ( @@ -340,12 +341,19 @@ def _bend_sequences( tuple(-d for d in candidate.offsets), ) ) - frontier = [] + frontier: list[_BendSequence] = [] for candidate in candidates: if not frontier or (weighted and candidate.cost < frontier[-1].cost - 1e-9): frontier.append(candidate) - sequences.append(tuple(frontier)) - viable = [candidate for candidate in sequences[index] if candidate.span <= usable] + sequences[height] = tuple(frontier) + # 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: return None best = viable[-1] @@ -388,7 +396,10 @@ def _schedules( sbend_penalty: float, allowed_offsets: frozenset[float] | None = None, ) -> 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)) # The track order allows a local check of each neighboring pair. The diff --git a/inire/tests/test_columns.py b/inire/tests/test_columns.py index e56b0c2..7b931ed 100644 --- a/inire/tests/test_columns.py +++ b/inire/tests/test_columns.py @@ -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: make_sequence = Mock(wraps=_columns._BendSequence) 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() 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.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_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) +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: 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,)) == {}