Use reachable offset strides in the S-bend sequence table

This commit is contained in:
Jan Petykiewicz 2026-11-30 09:25:59 -08:00
commit f4b16d3c55
2 changed files with 29 additions and 5 deletions

View file

@ -265,6 +265,9 @@ def _bend_sequences(
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),)]
@lru_cache(maxsize=4096)
@ -273,13 +276,16 @@ def _bend_sequences(
# A circular S-bend advances at least as far as it shifts.
if magnitude > usable:
return None
while len(sequences) <= magnitude:
index, remainder = divmod(magnitude, stride)
if remainder or (index and not bends):
return None
while len(sequences) <= index:
height = len(sequences)
candidates = [
_BendSequence((offset, *prefix.offsets), span + prefix.span, bend_costs[offset] + prefix.cost)
for offset, span in spans.items()
if offset <= height
for prefix in sequences[height - offset]
for step, offset, span in bends
if step <= height
for prefix in sequences[height - step]
]
candidates.sort(
key=lambda candidate: (
@ -293,7 +299,7 @@ def _bend_sequences(
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[magnitude] if candidate.span <= usable]
viable = [candidate for candidate in sequences[index] if candidate.span <= usable]
if not viable:
return None
best = viable[-1]

View file

@ -34,6 +34,24 @@ def test_sbend_sequence_skips_table_growth_for_shifts_larger_than_the_window(mon
assert choose(-10, 30).offsets == (-10,)
def test_sbend_sequences_use_the_common_offset_stride() -> None:
class SparseSpans(dict):
def items(self):
self.scans += 1
assert self.scans <= 3
return super().items()
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)
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, 120_000_000).offsets == (-40_000_000,)
assert choose(80_000_000, 160_000_000).offsets == (80_000_000,)
assert choose(120_000_000, 280_000_000).offsets == (80_000_000, 40_000_000)
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,)) == {}