viable.py

Checks: BONACCI: The closing carry theorem; property; rule.

Cited on: BONACCI.

To run it: save viable.py, with real_support.py beside it; needs mpmath, numpy, scipy.

"""
viable.py -- does the convex relaxation of S's two-sided viable set
hold the zero window alone at some phase?

QUESTION. cycles.py reads that S's window graph has no cycle avoiding
W = 0 at d = 4..10, its two-sided pruned set the zero window and the
excursion's d nodes. That set, at each phase N, is the theta in Z[beta]
with A_N + theta in [0, 1/(beta - 1)] and f_N - sigma(theta) a future
of some 0/1 string (below), so the cycle statement at d follows from
ONE phase admitting theta = 0 alone. Would a proof of that at every d
get by on convexity: with y' let run over [0, 1]^Z, real, does some
phase still hold the zero window alone? The first engine asked whether
the pruned set is that set, and read (2) alone, in floating point; its
record is kept below.

BY HAND (before the engine).
  (1) Coordinates. With c_k = x_N + ... + x_(N+d-k), theta_N = phi(W_N)
= sum_k c_k beta^(-k) maps Z^d onto Z[beta^(-1)] = Z[beta] (beta a
unit), and the step is theta_(N+1) = (theta_N - delta_N)/beta
(cycles.py's step, by 1 = sum_(k<=d) beta^(-k)). Its d embeddings, the
real one and the conjugates gamma_j (|gamma_j| < 1) acting as
sigma_j(theta_(N+1)) = (sigma_j(theta_N) - delta_N)/gamma_j, form a
linear isomorphism R^d -> R^d (beta has degree d, the d-bonacci
polynomial being irreducible, so phi is injective), so a path of
windows is bounded iff every embedding is.
  (2) Backward. theta_(N-1) = beta theta_N + delta_(N-1) expands the
real coordinate and contracts the conjugates. The real coordinate stays
bounded into the past iff theta_N = -sum_(k>=1) delta_(N-k) beta^(-k) =
A'_N - A_N, A_N = sum_(k>=1) S_(N-k) beta^(-k) and A' y''s; since beta
<= 2, the past values of 0/1 strings fill [0, 1/(beta - 1)]. So (W, N)
has a bounded backward path iff A_N + theta_N in I = [0, 1/(beta - 1)].
  (3) Forward. The conjugates stay bounded into the future iff
sigma(theta_N) = sum_(m>=0) delta_(N+m) gamma^m = f_N - f'_N, f_N =
sum_(m>=0) S_(N+m) gamma^m (a vector over the conjugates) and f' y''s.
So (W, N) has a bounded forward path iff f_N - sigma(theta_N) lies in
F = {sum_(m>=0) e_m gamma^m : e a 0/1 sequence}.
  (4) The past and the future of y' are chosen independently, so (W, N)
lies on a bi-infinite bounded path iff both hold: the two-sided viable
set at N is Lambda_N = {theta in Z[beta] : A_N + theta in I, f_N -
sigma(theta) in F}, finite, with no box. A cycle avoiding 0 passes
every phase, so Lambda_N = {0} at one phase N rules it out at that d;
the excursion puts a second point in Lambda_N at phases 3..d + 2.
TRANSPLANT to re-derive: "every value in I has a 0/1 expansion"
(true for beta <= 2, greedy) is the one-sided fact; it is used here for
the reversed past, weights beta^(-1), beta^(-2), ..., the same fact.
BY HAND (the certificate engine's, before it).
  (5) The relaxation and its certificate. Let y' run over [0, 1]^Z:
delta_t = x_t - (x_(t+1) + ... + x_(t+d)) is then any real in [S_t - 1,
S_t], and R_N is the set of integer windows at N of the bounded real x
with every delta_t there. Lambda_N lies in R_N (a 0/1 string is one of
[0, 1]^Z), and R_N is the integer points of a convex set, F replaced by
its convex hull. A finitely supported x, zero off the places a..b, is
bounded, and its delta is 0 at every t outside a - d..b, which [S_t -
1, S_t] holds whatever S_t is. So a finitely supported rational x with
a nonzero integer window at N and delta_t in [S_t - 1, S_t] at t = a -
d..b puts that window in R_N, by arithmetic in fractions: no kernel, no
beta, no box and no tolerance. The excursion, x = 1 at d + 2 alone, is
such a path at the phases 3..d + 2, an integer one (S_(d+2) = 1 over
d + 1 zeros). A path moved by S's period is a path, so R_N is its
phase's. If every phase has one, no phase's relaxed set holds 0 alone,
and a proof that some Lambda_N = {0} must use that y' is 0/1.

ARMS. A path is (x, a): x[0], x[1], ... sit at the places a, a + 1, ...
and the rest is 0. gaps(x, a, d) is delta at a - d..b. verdict(word, d,
N, x, a) reads the window at N and then every delta in order: ("yes",
W) for a nonzero integer window W with every delta in range, else what
fails first, ("fraction", W), ("zero", W), ("below", t) or ("above",
t), every entry read as the exact rational it is, a float too. Every
certificate below is its yes. seek(word, d, N, W, m) proposes a path
through W at N on the places N - m..N + d - 1 + m: a linear program
(scipy's HiGHS) for the largest s with every delta of the support in
[S_t - 1 + s, S_t - s] and |x| <= 8, its solution rounded to multiples
of 2^-40. Nothing of the solver's answer is believed: find(word, d, N)
takes the first m of 4d, 8d, 12d and at it the first candidate window,
of +-e_i then e_j - e_i, whose proposal verdict calls "yes" at that
window; the proposer is its argument, seek unless a control hands it
another. A phase
where find returns nothing is a search that failed, no proof that R_N
is {0}. read(d) is the record's entry at d: the phases where the
excursion's path certifies its window, and of the others the phases
where find certifies one.

CONTROLS, read first; a failure stops the run. Hand rows of verdict: S
at d = 4, 1000001010, with x = 1 at 6 alone, the windows (0, 0, 0, 1),
(0, 0, 1, 0), (0, 1, 0, 0), (1, 0, 0, 0) at N = 3..6 and the zero one
at 7; half of it, a window not integer; each bound on a row of its
own, the word (1, 0, 0, 0) with x = 1 at 4, whose one failing row is
the lowest, a - d, below its range, and the word (0) with x = 1 at 0,
whose one failing row is the top one, above; a real path with an
integer window, d = 2, the word (1, 0, 1, 0, 0), x_0 = 1, x_2 = 1/2,
its five deltas -1, -1, 1/2, -1/2, 1/2, the windows (1, 0) at 0 and (0,
1) at -1, (0, 1/2) at 1, with x_2 = 3/2 the first failing row t =
0, and on the word (1, 0, 0, 0, 0) delta_2 = 1/2 above S_2 = 0; the
same path in floats with x_1 = 2^-54, delta_-1 = -1 - 2^-54, below; a
path in halves at d = 6, on 14 places from 15, its window (0, 0,
0, 0, 0, -1) at 10 and its 20 deltas by hand, and
the same path with its last entry 1 for 1/2, failing first at t = 26.
The candidates at d = 2 as a list, and their number at d = 4. The
search: on the d = 2 word it certifies a window at 0; through (1, 0)
on 24 places a side it proposes a path, and through (3, 0) none, as
none exists (|x| <= 1 + 2/sqrt 5 on every bounded real path with
|delta| <= 1 at d = 2). find against proposers of hand paths: one that
always hands the path with x_2 = 3/2 is refused at every candidate; one
that hands the good path is taken at the window it holds, (1, 0) at 0
and (0, 1) at -1, the third candidate, not at the first tried.

THE FIRST ENGINE'S RECORD, kept as it stood: prunes of a dense box in
floating point, then a linear program over the kernel h. Its code, its
flags --hull and --hull-all and its class Graph left with it.

FROZEN (before the engine).
  PRINT, d = 4..9 at K = floor(L) (cycles.Graph): per phase, the
    backward-pruned set against {W in the box : A_N + phi(W) in I},
    the least distance of any phi(W) + A_N to I's ends; the forward-
    pruned set's size per phase.
  KILL (of (2)): a window in one backward set and not the other at a
    distance above 1e-9 from I's ends; a window of the interval set
    missing from the box's prune (a backward path may leave the box,
    which (2) does not bound) is read again at K + 1 before it counts.
    (3) has no print, F having no closed form, and rests on the hand
    step. Box-freedom of the two-sided set is no test: a bi-infinite
    path has |x| <= L (cycles.py (2)), inside the box. Lambda_N = {0}
    at phases 0, 1, 2 and d + 3 .. 2d + 1 is no prediction either:
    given (1)-(4) it is cycles.py's recurrent print at d = 4..10.
  CONTROLS, read first: C1 the excursion's window at phase 3, x_(d+2)
    = 1 alone (c = e_1, phi = 1/beta), has A_3 + 1/beta in I and
    survives both prunes; C2 phi of the c-step
    equals (phi - delta)/beta on 1000 random windows, d = 4..9, to
    1e-12.
  ENVELOPE: d = 9 at K = 2, three prunes and the distances, about
    2 min and 200 MB.
ADDED TO THE PRINT (named, before the run): the forward-pruned windows
at phase 0 with their A_0 + phi, one line per d.

THE HULL (frozen after the backward run, before its engine). Does the
convex relaxation already hold 0 alone at phase 0? Let y' run over
[0, 1]^Z, delta_k in [S_k - 1, S_k] real. x_t = sum_k h_(k-t) delta_k
(cycles.py (2)) is then a bounded real solution, and R_N, the integer
windows W with W = W_N(S) - sum_k t_k H_k, t in [0, 1]^Z, H_k the
window of h at N, is the integer points of a zonoid: Lambda_N lies in
R_N, and R_N's real projection is exactly (2)'s interval (its kernel
is the past's beta^(-k), positive). If R_0 = {0} at every d, a proof
at every d needs only directions u separating each candidate,
sup <u, .> over the zonoid being sum_k max(0, <u, H_k>), the legal
hull's form. If R_0 holds a nonzero window, the relaxation cannot prove
phase 0, and a proof must use that y' is 0/1.
  PRINT: at phase 0, d = 4..8, |R_0| and its windows, against
    Lambda_0 = {0}; at d = 4, 5 every phase, |R_N| against |Lambda_N|.
    Candidates: the interval set in [-K, K]^d (R_N lies in the box: |delta_k| <= 1
    gives |x_t| <= L, cycles.py (2)), cut by the d coordinate
    slabs, each survivor an LP over t, k within N +- M, the tail of h
    past M widening each equality by its l1 mass.
  PREDICTION: R_0 = {0} at d = 4..8, held weakly: the true forward
    set's neighbours of 0 sit 0.62 below I and 0.35 above it, but
    conv F may admit points F does not.
  KILL (of the hull route): a nonzero window in R_0 at some d in 4..8.
  CONTROLS, read first: C3 h obeys delta_t = x_t - (x_(t+1) + ... +
    x_(t+d)) on a random delta truncated to |k| <= M, away from the
    ends, to 1e-9, d = 4..8; C4 the LP finds the excursion's window at
    phase 3 and 0 at phase 0 feasible; C5 it finds 20 slab-rejected
    windows infeasible (it can say no). Changed at its first run (named):
    up to 20, at least 10, d = 4 having 19.
  ENVELOPE: d = 8, phase 0, about 42,600 candidates before the slabs;
    a minute or two, under 300 MB.
  ADDED after the kill fired (named, before its run): --hull-all reads
    every phase at d = 6, 7, 8, |R_N| against |Lambda_N|. PREDICTION:
    no phase holds R_N = {0} at d = 8, the excess growing with d.

PREDICTIONS AND KILL (the certificate engine's, fixed before it with
(5) and every hand row; each prediction's source is the first engine's
print, a floating verdict).
  X0 CONTROLS, read first, a failure stopping the run: the hand rows
    as written; the excursion's d nodes certified by x = 1 at d + 2
    alone at each d = 4..10, and the zero window refused.
  X1 (control rows, the search against the first engine's R at d = 4,
    5, 6, K's box): of the d + 2 phases off the excursion a nonzero window is
    certified at d = 4 at phase 7 alone, at d = 5 at phase 8 alone, at
    d = 6 at 0, 9, 10, 11, 12, 13 and not at 1, 2: 1 of 6, 1 of 7, 6
    of 8. A "none found" is a search's and proves nothing.
  X2 d = 7, 8: every one certified, 9 of 9 and 10 of 10, each by a
    window with at most two nonzero entries, +-1 (the first engine's
    print shows such at the phases it lists; d = 7's phases 10 to 14
    and d = 8's 0, 1, 6 to 17 it does not list: a prediction).
  X3 d = 9, 10, unread by the first engine: 11 of 11, 12 of 12.
  P0 (the design's): a finitely supported path exists wherever the
    kernel's LP found one. If it fails, the fallback is a
    periodic tail, named in the record.
  KILL: "RELAXED: n of 42 phases off the excursion at d = 7..10 hold a
    nonzero window on a rational path" at n < 42: the statement is then
    cut back to the d where its row is whole.
  ENVELOPE: candidates e_j - e_i, +-e_i (d(d - 1) + 2d a phase), one
    LP each until the first certificate, 63 phases: under 90 s, under
    400 MB (an estimate before any probe).
CHANGED FROM THE FROZEN (named). A probe outside the script, run before
the engine and after the predictions, chose the search: a support of 2d
places each side certified almost nothing; the vertex of least sum |x|
on 40 a side, read as fractions under 10^6, gave small paths (the
halves at d = 6 among the hand rows is one) and lost d = 7's phases 1
and 2 to its denominators; the largest margin, rounded, is the engine.
It certified every phase of X1, X2 and X3 as predicted, and d = 11 and
12 beyond them. So d = 11..16 joined the record, their rows seen at 11
and 12 and not past: "FURTHER: n of 93". The phases are named off the
excursion's own path, not read off cycles.py's set, and the statement
is of every phase: it needs no fact about Lambda_N. The hand note of
the path with x_2 = 3/2 named its failing rows t = 1 and 2 and missed
delta_0 = -1/2, the first. Written with the draft, not frozen: the
halves path and its plant, the candidates' hand row, the count of the
check lines. The envelope's "one program each" is up to three, one a
support. Added at the draft's read, each for an edit its reader named
that no line would fail: the delta above by a half (the bound moved up
by one passed every row), the proposers handed to find (find believing
its proposer passed every row), and the path proposed through (1, 0)
beside the one refused. The frozen block named its hand rows by
label, its phases as those where cycles.py's set holds the zero window
alone, and its kill as cutting a sentence back; the candidates run
+-e_i first; X2's "at most two nonzero entries" is the candidates'
shape, no finding. Added after a second read, which made verdict say
yes to a path in floats whose delta_-1 = -1 - 2^-54 the floats
rounded to -1: verdict reads every entry as a fraction, and the path
is a hand row.

FINDINGS (copied from the runs' prints).
  - The controls hold, each hand value as written, the note on x_2 =
    3/2 aside (above).
  - The KILL misses: "RELAXED: 42 of 42 phases off the excursion at d =
    7..10 hold a nonzero window on a rational path", 9, 10, 11 and 12
    of them, and "FURTHER: 93 of 93 at d = 11..16". The excursion's own
    path holds the phases 3..d + 2. So at each d = 7..16 the relaxed
    set R_N holds a nonzero window at every phase: convexity proves
    Lambda_N = {0} at no phase there, and a proof must use that y' is
    0/1, the gap between F and its hull. Every certificate is, by
    construction, a path in multiples of 2^-40 on at most 25d places,
    checked in fractions.
  - The control rows: at d = 4, 5, 6 the search certifies a window at
    the phases 7; 8; 0, 9, 10, 11, 12, 13 and at no other phase off
    the excursion, the phases where the first engine's program put a
    nonzero window in R_N beyond Lambda_N. Where it finds none (d = 4:
    0, 1, 2, 8, 9; d = 5: 0, 1, 2, 9, 10, 11; d = 6: 1, 2) this script
    proves nothing.
  - What the rows rest on, by the mutation meter and breaks by hand,
    each run with the controls' stop lifted too. Every change the meter
    makes in at, gaps, verdict, candidates, find and read turns a line
    to FAIL. Its eight that move no line sit in seek, parameters of a
    proposal the verdict then rules: the cap 9 for 8, the support 3m +
    d and 2m - d, the margin's weight, its ceiling and its cost
    doubled (the weight at either of its two rows), the grid 2^-41.
    Its three past the clock sit there too; one, the row's reach cut
    to d - 1, run to its end by hand, fails every row in 282 s, its
    proposals refused, and the other two were run to no end. A coarser
    proposer loses rows and gains none: rounded to sixteenths, held to
    |x| <= 1, or on the support 4d alone, it fails rows and passes no
    row it should not. The bound above moved up by one and find
    believing its proposer, the two edits the draft's reader named,
    each fail the one line written for it.
  - The first engine, in floating point. At d = 4..9 the backward-
    pruned set of the box was the interval set {W : A_N + phi(W) in I}
    at every phase, no window in one alone, none missed by the box, the
    least distance of A_N + phi(W) to I's ends 1.01e-3, 4.03e-4,
    1.16e-5, 1.36e-6, 1.64e-7, 2.01e-8; C1 held and C2's worst was
    1.8e-15. The forward-pruned set held 6 windows a phase (5 at phase
    2) at K = 1 and 10 (9 at phase 2) at K = 2, at phase 0 one list at
    d = 6..9, nonzero on x_0, x_1, x_2 only, 0's neighbours among them
    0.62 below I and 0.37 above at d = 9; with the backward set it left
    cycles.py's set; (3) had no print. Its program over the kernel (C3's worst 9.7e-13)
    read R_0 = {0} at d = 4, 5 and |R_0| = 3, 4, 9 at d = 6, 7, 8, the
    hull's kill firing; over every phase, by its --hull and --hull-all
    prints run once more before it left, R_N = {0} at the phases off
    the excursion but 7 at d = 4 and but 8 at d = 5, at d = 6 at phases
    1 and 2 alone, at d = 7 and 8 at none. Each nonzero R_0 window
    stayed feasible with every t_k held to [1e-3, 1 - 1e-3].

RUN RECORD: python viable.py (under a 2 GB cap) 13/13, 22.3 s, peak
232.8 MB; --hull 15/18, its 3 FAILs the kill at d = 6, 7, 8, 5.9 s,
125.8 MB; --hull-all 9/12 (the same), 36.7 s, 127.9 MB. With the
phase-0 margin print: bare 13/13, 21.9 s, 232.0 MB (through the gate);
--hull 15/18, 5.9 s, 125.5 MB.
Those the first engine's; once more before it left, bare 13/13, 21.0 s,
236.8 MB, --hull 15/18, 6.6 s, --hull-all 9/12, 35.4 s.
The certificate engine: the draft's first run, controls and d = 4..16,
24 of 25 checks, 25.7 s, peak commit 75.5 MB under a 2 GB cap, its one
FAIL the count of its own check lines, written 29 for 25. With the
controls its draft's reader asked for, bare under a 512 MB cap: 26 of
26 checks, 26.1 s, 76.1 MB. The mutation meter, every one-token and
structural change of its functions, 97, each run: 86 red, 8 moving no
line, 3 past the clock. 16 breaks by hand, each one edit, each run
twice: 16 red; with the controls' stop lifted 15 red and one, the
lower bound read a place late, past the clock at 520 s. With the
floats' row and verdict reading fractions: 27 of 27 checks, 26.0 s,
75.8 MB; that fix undone in a copy fails the floats' row alone. The
meter again at this code, 98: 87 red, the same 8 and the same 3.

USAGE. python viable.py reads the controls and d = 4..16.
"""
import os
import sys
import time
from fractions import Fraction

os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
import numpy as np  # noqa: E402
from scipy.optimize import linprog  # noqa: E402

from real_support import S_WORD  # noqa: E402

DS = range(4, 17)
FOUND = {4: (7,), 5: (8,), 6: (0, 9, 10, 11, 12, 13)}
LADDER = (4, 8, 12)
LINES = 27
CHECKS = []


def at(x, a, t):
    """x_t of the path (x, a)."""
    return x[t - a] if a <= t < a + len(x) else 0


def gaps(x, a, d):
    """delta_t = x_t - (x_(t+1) + ... + x_(t+d)) at t = a - d..b, b the
    path's last place; it is 0 at every other t."""
    return {t: at(x, a, t) - sum(at(x, a, t + i) for i in range(1, d + 1))
            for t in range(a - d, a + len(x))}


def verdict(word, d, N, x, a):
    """("yes", W) when the path's window W at N is integer and nonzero
    and every delta_t lies in [word_t - 1, word_t]; else what fails
    first: the window, then the least t."""
    x = [Fraction(v) for v in x]
    W = tuple(at(x, a, N + i) for i in range(d))
    if any(w.denominator != 1 for w in W):
        return "fraction", W
    if not any(W):
        return "zero", W
    P = len(word)
    for t, g in sorted(gaps(x, a, d).items()):
        if g < word[t % P] - 1:
            return "below", t
        if g > word[t % P]:
            return "above", t
    return "yes", W


def candidates(d):
    """e_i and -e_i, then e_j - e_i."""
    out = []
    for i in range(d):
        for s in (1, -1):
            out.append(tuple(s * (k == i) for k in range(d)))
    for i in range(d):
        for j in range(d):
            if i != j:
                out.append(tuple((k == j) - (k == i) for k in range(d)))
    return out


def seek(word, d, N, W, m, cap=8, bits=40):
    """A path proposed through W at N on the places N - m..N + d - 1 +
    m, or None: the largest s with every delta of the support in
    [word_t - 1 + s, word_t - s], |x| <= cap, rounded to 2^-bits."""
    P, a, n = len(word), N - m, 2 * m + d
    A, b = [], []
    for t in range(a - d, a + n):
        r = np.zeros(n + 1)
        r[n] = 1
        for i in range(d + 1):
            if a <= t + i < a + n:
                r[t + i - a] = -1 if i else 1
        A.append(r)
        b.append(word[t % P])
        r = -r
        r[n] = 1
        A.append(r)
        b.append(1 - word[t % P])
    bounds = [(-cap, cap)] * n + [(0, 1)]
    for i in range(d):
        bounds[m + i] = (W[i], W[i])
    cost = np.zeros(n + 1)
    cost[n] = -1
    res = linprog(cost, A_ub=np.array(A), b_ub=np.array(b), bounds=bounds,
                  method="highs")
    if res.status != 0:
        return None
    q = 1 << bits
    return [Fraction(round(float(v) * q), q) for v in res.x[:n]], a


def find(word, d, N, propose=seek):
    """(W, x, a): the first support and candidate window whose proposed
    path the verdict calls yes at that window; None when none is."""
    for m in LADDER:
        for W in candidates(d):
            path = propose(word, d, N, W, m * d)
            if path and verdict(word, d, N, *path) == ("yes", W):
                return (W,) + path
    return None


def read(d):
    """The record's entry at d: the phases where the excursion's path
    certifies a window, and of the others those where find does."""
    word = S_WORD(d)
    P = len(word)
    on = [N for N in range(P)
          if verdict(word, d, N, [1], d + 2)[0] == "yes"]
    off = [N for N in range(P) if N not in on]
    found = [N for N in off if find(word, d, N)]
    return {"on": tuple(on), "off": tuple(off), "found": tuple(found)}


def check(name, ok, detail=""):
    CHECKS.append(bool(ok))
    print(f"  [{'PASS' if ok else 'FAIL'}] {name}"
          + (f"  {detail}" if detail else ""), flush=True)


def section_hand():
    print("CONTROLS", flush=True)
    F = Fraction
    S4 = S_WORD(4)
    got = [verdict(S4, 4, N, [1], 6) for N in range(3, 8)]
    check("S at d = 4 is 1000001010; x = 1 at 6 alone certifies (0, 0, "
          "0, 1) at 3, the 1 moving down to 6, and at 7 the window is zero",
          list(S4) == [1, 0, 0, 0, 0, 0, 1, 0, 1, 0]
          and got == [("yes", (0, 0, 0, 1)), ("yes", (0, 0, 1, 0)),
                      ("yes", (0, 1, 0, 0)), ("yes", (1, 0, 0, 0)),
                      ("zero", (0, 0, 0, 0))], f"{[g[0] for g in got]}")
    got = verdict(S4, 4, 3, [F(1, 2)], 6)
    check("half of it: the window (0, 0, 0, 1/2) is not integer",
          got == ("fraction", (0, 0, 0, F(1, 2))), f"{got[0]}")
    got = [verdict([1, 0, 0, 0], 4, 4, [1], 4), verdict([0], 4, 0, [1], 0)]
    check("one failing row each: the word (1, 0, 0, 0), x = 1 at 4, below "
          "at t = 0, the lowest row; the word (0), x = 1 at 0, above at t "
          "= 0, the top row", got == [("below", 0), ("above", 0)], f"{got}")
    Y = [1, 0, 1, 0, 0]
    x = [1, 0, F(1, 2)]
    got = gaps(x, 0, 2)
    check("d = 2, x_0 = 1, x_2 = 1/2: delta at -2..2 is -1, -1, 1/2, -1/2, "
          "1/2", got == {-2: -1, -1: -1, 0: F(1, 2), 1: F(-1, 2), 2: F(1, 2)},
          f"{[str(got[t]) for t in sorted(got)]}")
    got = [verdict(Y, 2, N, x, 0) for N in (0, -1, 1)]
    got.append(verdict(Y, 2, 0, [1, 0, F(3, 2)], 0))
    got.append(verdict([1, 0, 0, 0, 0], 2, 0, x, 0))
    check("on the word (1, 0, 1, 0, 0) it certifies (1, 0) at 0 and (0, 1) "
          "at -1; at 1 the window is (0, 1/2); with x_2 = 3/2 the first "
          "failing row is t = 0, below; on the word (1, 0, 0, 0, 0) delta_2 "
          "= 1/2 is above",
          got == [("yes", (1, 0)), ("yes", (0, 1)),
                  ("fraction", (0, F(1, 2))), ("below", 0), ("above", 2)],
          f"{got[3:]}")
    got = verdict(Y, 2, -1, [1.0, 2.0 ** -54, 0.5], 0)
    check("a path handed in floats is read exactly: x_1 = 2^-54 puts "
          "delta_-1 below -1", got == ("below", -1), f"{got}")
    h = F(1, 2)
    x = [-1, h, h, 0, 0, -h, -h, 1, h, 0, -h, 0, -h, h]
    want = {9: 1, 10: h, 14: h, 15: -1, 18: -h, 20: -1, 21: -1, 22: 1,
            23: 1, 24: h, 25: -h, 27: -1, 28: h}
    got = gaps(x, 15, 6)
    check("d = 6, the path in halves on 15..28: its deltas at 9..28",
          got == {t: want.get(t, 0) for t in range(9, 29)},
          f"{sum(1 for v in got.values() if v)} nonzero of {len(got)}")
    got = [verdict(S_WORD(6), 6, 10, x, 15),
           verdict(S_WORD(6), 6, 10, x[:-1] + [1], 15)]
    check("it certifies (0, 0, 0, 0, 0, -1) at phase 10 of S at d = 6; "
          "with its last entry 1 the first failing row is t = 26, below",
          got == [("yes", (0, 0, 0, 0, 0, -1)), ("below", 26)], f"{got}")
    got = candidates(2)
    check("the candidates at d = 2, and 20 distinct ones at d = 4",
          got == [(1, 0), (-1, 0), (0, 1), (0, -1), (-1, 1), (1, -1)]
          and len(set(candidates(4))) == len(candidates(4)) == 20, f"{got}")
    got = [find(Y, 2, 0) is not None, seek(Y, 2, 0, (1, 0), 24) is not None,
           seek(Y, 2, 0, (3, 0), 24)]
    check("the search on the d = 2 word: a window certified at 0; on 24 "
          "places a side a path proposed through (1, 0), none through (3, "
          "0)", got == [True, True, None], f"{got}")
    good, bad = ([1, 0, F(1, 2)], 0), ([1, 0, F(3, 2)], 0)
    got = [find(Y, 2, 0, lambda *_: bad), find(Y, 2, 0, lambda *_: good),
           find(Y, 2, -1, lambda *_: good)]
    check("find hears the verdict: a proposer of the path with x_2 = 3/2 "
          "is refused throughout; one of the good path is taken at the "
          "window it holds, (1, 0) at 0 and (0, 1) at -1",
          got == [None, ((1, 0),) + good, ((0, 1),) + good],
          f"{[g and g[0] for g in got]}")


def section_rows(rows):
    print("THE ROWS  d = 4..16: a nonzero window on a rational path, by "
          "phase", flush=True)
    for d in DS:
        r = rows[d]
        print(f"  d = {d}: the excursion at {len(r['on'])} phases, a found "
              f"path at {len(r['found'])} of the other {len(r['off'])}, "
              f"{r['wall']:.1f} s", flush=True)
    got = [rows[d]["on"] == tuple(range(3, d + 3)) for d in DS]
    check("the excursion's path certifies its window at the phases 3..d + "
          "2 and no other, at each d", got == [True] * 13,
          f"{sum(got)} of 13")
    for d in (4, 5, 6):
        check(f"d = {d}: the search certifies the first engine's phases "
              "and no other", rows[d]["found"] == FOUND[d],
              f"{rows[d]['found']}")
    for d in DS[3:]:
        r = rows[d]
        check(f"d = {d}: every phase off the excursion holds a nonzero "
              "window on a rational path", r["found"] == r["off"],
              f"{len(r['found'])} of {len(r['off'])}")
    held = sum(len(rows[d]["found"]) for d in range(7, 11))
    print(f"RELAXED: {held} of 42 phases off the excursion at d = 7..10 "
          "hold a nonzero window on a rational path", flush=True)
    more = sum(len(rows[d]["found"]) for d in range(11, 17))
    print(f"FURTHER: {more} of 93 at d = 11..16", flush=True)
    check("the kill misses: every phase off the excursion, d = 7..16",
          held == 42 and more == 93, f"{held} of 42, {more} of 93")


def main():
    t_all = time.time()
    section_hand()
    if not all(CHECKS):
        print("\nCONTROL FAILED: nothing below is read.")
        sys.exit(1)
    rows = {}
    for d in DS:
        t0 = time.time()
        rows[d] = read(d)
        rows[d]["wall"] = time.time() - t0
    section_rows(rows)
    ran = len(CHECKS)
    check("every check line of the run printed, this one aside",
          ran == LINES - 1, f"{ran} of {LINES - 1}")
    print()
    print("%d of %d checks, %.1f s"
          % (sum(CHECKS), len(CHECKS), time.time() - t_all))
    sys.exit(0 if all(CHECKS) else 1)


if __name__ == "__main__":
    main()