bonacci.py

Checks: BONACCI: The comb theorem; BONACCI: Floor division on the d-bonacci completion theorem; BONACCI: The scaling certificate rule.

Cited on: BONACCI.

To run it: save bonacci.py; standard library only.

"""
bonacci.py -- the trailing d-bonacci numerations: the comb that tears
doubling, the successor's lookahead, floor division along the state
classes, and the certificate that tears n -> mn pair by pair.

QUESTION. The trailing d-bonacci numeration, d >= 2, has places q_j =
2^j for j < d and q_k = q_(k-1) + ... + q_(k-d) after, and writes
every n >= 0 by greedy digits; d = 2 is Zeckendorf. Its depth-t tile
is the integers sharing their t lowest digits, its completion K_d the
infinite digit strings under the agreement metric, and a reader at
lookahead c sees an input's tile at depth t + c and commits the
output's tile at depth t. Which of n -> n + 1, n -> 2n, n -> mn and n
-> floor(n/m) extend continuously to K_d, and at what lookahead? At d
= 2 the circle decides every scaling (ostrowski.py); past it the
completion sits over a torus (fibre.py).

THE ARGUMENT.
  (0) LEMMA 0. A 0/1 string with no d consecutive ones (LEGAL) on
      positions below k sums to at most q_k - 1. At k < d that is 2^k
      - 1. At k >= d one of its top d positions, j, is empty; what
      lies below j sums to at most q_j - 1 by induction, so the whole
      to at most q_(k-1) + ... + q_j - 1 <= q_k - 1, as j >= k - d. So
      a legal string is its value's greedy string; and d ones in a row
      at j, .., j - d + 1 sum to q_(j+1), so a greedy string is legal.
  (1) THE COMB. 2 q_k = q_(k+1) + q_(k-d) for k >= d, as 2 q_k -
      q_(k+1) = q_k - q_(k-1) - ... - q_(k-d+1) = q_(k-d); and q_0 +
      ... + q_(d-1) = q_d. Let K = d + (d + 1) i, r = i mod d, and T_K
      = q_d + q_(2d+1) + ... + q_K, a comb of step d + 1. THE PHASES:
      the digits of 2 T_K are the bottom {0, .., r} and the teeth j =
      r + 1 mod d, d + 1 + r <= j <= K + 1, when r <= d - 2; the teeth
      j = 0 mod d, d <= j <= K + 1, when r = d - 1. Base: 2 T_d =
      q_(d+1) + q_0. Step: 2 T_(K+d+1) = 2 T_K + q_(K+d+2) + q_(K+1);
      the added q_(K+1) doubles the top tooth, each 2 q_j = q_(j+1) +
      q_(j-d) doubles the tooth d below, so every tooth moves up one;
      at the bottom tooth the carry puts q_(r+1) on the bottom, at r =
      d - 2 the full bottom {0, .., d - 1} sums to the tooth q_d, and
      at r = d - 1 the tooth d splits to q_(d+1) + q_0. Each result
      has teeth d apart above a bottom run shorter than d, so it is
      legal, hence greedy. T_K and T_(K+d+1) first differ at K + d +
      1. Their doubles, of phases r and r + 1, first differ at r + 1
      when r <= d - 3 (bottoms {0..r}, {0..r + 1}) and at 0 otherwise
      (the bottom {0..d - 2} against none, none against {0}): at a
      digit <= d - 2 whatever K. So n -> 2n has no continuous
      extension, and K_d carries no continuous addition extending the
      integers'.
  (2) THE SUCCESSOR reads at lookahead exactly d - 1, at every depth
      t >= 1. Let y be n's string and a <= d - 1 its run of ones at
      the bottom: 1 + q_0 + ... + q_(a-1) = 2^a = q_a. Adding q_j
      where y_j = 0 and all below is 0: if the run of ones from j + 1
      is shorter than d - 1, write a one at j; else q_j + ... +
      q_(j+d-1) = q_(j+d), clear them and go on at j + d, where y is
      0. So n + 1 is zeros below L, a one at L and y above it, L = a +
      d k the first stop. Seeing y below t + d - 1, every stop j <= t
      - 1 shows its whole block j + 1 .. j + d - 1, so the low t
      digits of n + 1 are known: lookahead d - 1 reads. Lookahead d -
      2 does not, nor any less, a shallower tile being a union of
      deeper ones: with a = (t - 1) mod d and k = (t - 1) div d, let n0
      have ones on [0, a), k blocks of d - 1 ones above the zeros at
      a, a + d, .., t - 1 - d, and ones on [t, t + d - 2), and n1 = n0
      + q_(t+d-2). Both are legal and agree below t + d - 2; n0 + 1
      has a one at t - 1 and n1 + 1 a zero.
  (3) FLOOR DIVISION IS TORN at every d >= 2, m >= 2. Let beta be the
      largest root of x^d - x^(d-1) - ... - 1, a Pisot number (Brauer,
      Math. Nachr. 4, 1950), alpha = (beta^-1, .., beta^-(d-1)), q
      continued backward by the recurrence, nu_k = (q_(k-1), ..,
      q_(k-d+1)) and theta_k = q_k alpha - nu_k. Each coordinate of
      theta solves the recurrence with its beta-part cancelled, so
      theta_k shrinks geometrically, phi(y) = sum y_k theta_k mod
      Z^(d-1) is continuous on K_d, and phi(n) = n alpha. The inputs
      q_K tend to 0 in K_d, and floor(q_K/m) alpha = (theta_K + nu_K -
      r_K alpha)/m with r_K = q_K mod m. The STATE (q_K, ..,
      q_(K-d+1)) mod m is purely periodic, the recurrence running
      backward mod m, and not constant (it holds 2 beside 1 at K = d -
      1, or 0 beside 1 at m = 2). On a class of K mod its period
      floor(q_K/m) has cluster points, K_d being compact, and phi maps
      each to (nu - r alpha)/m at the class's values. The states of
      one period are distinct, and two classes with different states
      give different points, beta being irrational. So floor(n/m) has
      at least two cluster values over the one input limit 0, and as
      many as the period wherever each class converges.
  (4) LEMMA V. q_K - 1 = q_(K-1) + ... + q_(K-d+1) + (q_(K-d) - 1),
      down to q_j - 1 = 2^j - 1 at j < d: below K its zeros sit
      exactly at the positions = K mod d. For r >= 1 and any L < K
      with L = K mod d and q_L >= r, q_K - r is that string from L up
      with q_L - r < q_L written below L: the zero at L keeps it
      legal. So along K = a mod d the strings of q_K - r converge, to
      d distinct limits.
  (5) THE CERTIFICATE. Let W = w_1 w_2 .. be purely periodic with
      period L and no d consecutive ones around the cycle, and A_K =
      sum_(i=1..K) w_i q_(K-i), W written down from position K - 1: a
      legal string, so A_K's own, whose digit at j < K is w_(K-j). On
      each class of K mod L the A_K converge. Let e_K = q_K - m A_K,
      Delta(z) = 1 - z - ... - z^d, N(z) = Delta(z) sum q_k z^k = 1 +
      z + ... + z^(d-1) and R(z) = sum_(i=1..L) w_i z^i. Then sum e_K
      z^K = N (1 - z^L - m R)/(Delta (1 - z^L)). If Delta S = 1 - z^L
      - m R for a polynomial S, then N S has degree at most L - 1 and
      e is purely periodic with period L, with e_0 = q_0 = 1. Delta is
      irreducible (its reversal has beta outside the unit circle, its
      other roots inside, and constant term -1), so the division says
      1/beta is a root: the sum of w_i beta^-i over all i >= 1 is 1/m,
      a property of the infinite word. THE WORD IS COMPUTED, not
      searched: e_L = 1 says m A_L = q_L - 1, so w_i is the digit of
      (q_L - 1)/m at position L - i, and there is no word of period L
      unless m divides q_L - 1. And e_K is congruent to q_K mod m, so
      the state's period divides L. The certified periods are
      therefore multiples of the state's, one candidate word at each.
      The first that certifies is its word's least period: a shorter
      period of the word certifies too, the sum being the word's, and
      it is a multiple met earlier.
  (6) THE TEAR. On the class K = 0 mod L, m A_K = q_K - 1, whose
      string by (4) is every position below K off the class of K mod
      d. If d does not divide L, then L and 2L, and jL and (j + 1)L,
      differ mod d: the inputs A_(jL) and A_((j+1)L) agree below jL
      while their images first differ at min(jL mod d, (j + 1)L mod
      d), a digit below d. So n -> mn has no continuous extension.
      The divisibility is a finite check: each pair it passes with d
      not dividing L is PROVED torn. If d divides L every class of K
      mod L lies in one class mod d and the certificate decides
      nothing. A WITNESS at j = 1 is four strings: x1, x2 (W down from
      L - 1 and from 2L - 1) and y1, y2 (the positions below L, 2L off
      the class of L, 2L mod d), with m val(x) = val(y) twice. The
      first identity is how the word was computed; the second is the
      periodicity. x1 and x2 first differ at 2L - i*, i* the last i
      with w_i = 1; y1 and y2 at min(L mod d, 2L mod d), or at L + 1
      when d divides L.
  (7) m = 2 AND m = 1. q_k mod 2 repeats the block 1 0^(d-1) 1, so
      the state has period d + 1; (q_(d+1) - 1)/2 = 2^d - 2 = q_1 +
      ... + q_(d-1), so W = 0
      1^(d-1) 0, and (1 + z) Delta = 1 - z^(d+1) - 2 (z^2 + ... +
      z^d): S = 1 + z. gcd(d, d + 1) = 1, so n -> 2n is torn at every
      d a second time, with no comb. At m = 1 the state's period is 1
      and (q_k - 1)/1 = 2^k - 1 is 1^k at k < d, every position a one;
      at k = d it is 1^(d-1) 0 with S = 1. So the first certified
      multiple is d, which d divides: the certificate decides nothing
      about n -> n, as it must.

THE ENGINE. Integers throughout; a digit string is the set of its
positions, a word W the list w_1 .. w_L.
  places(d, n) is q_0 .. q_(n-1); stream(d) yields them without end.
  greedy(n, q) is what greedy subtraction takes on the places q: n's
  string when n is below the place after them, which every call here
  sees to. A remainder left over is refused; an n past that place but
  within the places' sum is written all the same, as no string of the
  numeration. low(s, t) is s below t; apart(a, b) the first
  position where two strings differ, None if none; value(d, s) the sum
  of the places of s. comb(d, i) is T_K at K = d + (d + 1) i; phase(d,
  i) the digits (1) gives 2 T_K; parting(d, i) the digit (1) gives
  for where 2 T_K and its successor's double part. comb_row(d, i)
  reads, by greedy strings alone: the digits of 2 T_K, where T_K and
  T_(K+d+1) first differ, where their doubles do. comb_pair(d, depth)
  is the first (T_K, T_(K+d+1)) with K + d + 1 >= depth.
  table(d, top) holds the digits of every n < top as a bit mask.
  scan(f, digs, t, c, span) reads n = 0 .. span - 1 in order, keeps
  the low t digits of f(n) for the first n of each low-(t + c) string,
  and returns the first later input that differs from its string's
  first, as the pair (n0, n1), with the count of inputs compared;
  (None, count) when none differs. is_witness re-reads a pair from the
  table. lookahead(f, digs, t, cmax, span) is the least c <= cmax
  whose scan finds no pair, the pairs found below it, and the inputs
  its pass compared. A pair is exact; a pass is a sample of n < span,
  and (2) is what makes the successor's a law. succ_pair(d, t) is
  (2)'s pair.
  state_period(d, m, cap) is the least p <= cap bringing the state
  back to its start, None above cap. floor_low(d, m, K, t) is the low
  t digits of floor(q_K/m). floor_row(d, m, start, depth) reads one
  period of K from start and the period after it, None where the
  period is above 400: the period, the K whose low depth digits repeat
  a period on, the distinct patterns of the period, and the least
  depth at which they are all apart (None past depth).
  minus(d, r, K) is (4)'s string for q_K - r at the least L, None when
  no L exists.
  cyclic(W, d) says no d consecutive ones around the cycle. word(d, m,
  L) is (5)'s candidate, None unless m divides q_L - 1. quotient(d, m,
  W) is S, None unless W is cyclic and the division by Delta exact.
  certificate(d, m, cap) tries L = k pi_s for k = 1, 2, .. while L <=
  cap and returns the first certified, as W, its period pi, k, S and
  tear (d does not divide pi); None when the state's period is above
  cap or no multiple certifies. witness(d, m, W) is (6)'s read: how
  many of the two identities hold, where x1 and x2 first differ, where
  y1 and y2 do; witness_law(d, W) is what (6) says it reads at a
  certificate. pair_row(d, m, cap) is one pair's letter (T torn, .
  certified and undecided, n no multiple certifies, ? the state's
  period above cap), the state's period, k, and whether the witness
  reads its law.

THE STAGES.
  comb     d = 2..8, i = 0..3d: the 112 doubles against phase, and
           each with its successor against K + d + 1 and parting.
  succ     the successor at d = 2, 3, 4 and t = 1..6 through lookahead
           at c <= d - 1, over n below the first place at or above
           5000 (6765, 5768, 5536); succ_pair at c = d - 2.
  double   the control that the scan sees a tear: 2n at Zeckendorf, t
           = 1..3, through lookahead at c <= 6, and the comb's pair as
           a witness beside each pair the scan finds; the strings of
           T_5 = 16, T_8 = 71 and their doubles, read off the table.
  floor    d = 2..6, m = 2..5, the 18 pairs of state period at most
           400, through floor_row from K = 100 at depth 40.
  minus    (4) at the least L against greedy, wherever an L exists:
           d = 2..8, r = 1..12, d <= K <= 80.
  pairs    d = 2..10, m = 1..12 through pair_row at cap 20000.

BY HAND, the controls' values.
  places. d = 2: 1 2 3 5 8 13 21 34 55 89 144. d = 3: 1 2 4 7 13 24 44
  81 149 274 504 927 1705 3136. d = 4: 1 2 4 8 15 29 56 108.
  greedy. d = 2: 12 = {0, 2, 4}, 72 = {0, 2, 5, 8}, 3 = {2}. d = 3: 78
  = {0, 1, 3, 5, 6}, 1045 = {4, 5, 7, 11}. On the three places 1, 2,
  3 of d = 2, 8 is refused and 5, which is the next place, comes back
  {1, 2}.
  The comb. d = 2: T_2 = 3, 6 = {0, 3}; T_5 = 16, 32 = {2, 4, 6}; T_8
  = 71, 142 = {0, 3, 5, 7, 9}. d = 3: T_3 = 7, 14 = {0, 4}; T_7 = 88,
  176 = {0, 1, 5, 8}; T_11 = 1015, 2030 = {3, 6, 9, 12}. Partings, i
  from 0: d = 2: 0, 0, 0; d = 3: 1, 0, 0, 1; d = 4: 1, 2, 0, 0, 1.
  Rows: (2, 0) ({0, 3}, 5, 0); (2, 1) ({2, 4, 6}, 8, 0); (3, 0) ({0,
  4}, 7, 1); (3, 1) ({0, 1, 5, 8}, 11, 0). comb_pair at d = 2, whose
  pairs first differ at 5, 8, 11: depths 1 and 5 (3, 16), 6 and 8 (16,
  71), 9 (71, 304).
  The scan, Zeckendorf, the successor at t = 1. c = 0, span 8: n = 0
  has string {} and 1 = {0}; n = 2 = {1} has string {} and 3 = {2},
  low digit none: (0, 2), one compared. c = 1, span 8: n = 0..7 have
  low two digits {} {0} {1} {} {0} {} {0} {1} and n + 1 low digit {0}
  {} {} {0} {} {0} {} {}: none, 5 compared. (0, 2) is a witness at c =
  0 and not at c = 1 (strings {} and {1}); (0, 3) is none at c = 1
  (equal images); (2, 0) is out of order; (1, 4), with images 2 = {1}
  and 5 = {3}, is none at t = 1 and one at t = 2. lookahead to c = 1
  over n < 8: 1, past ((0, 2),), 5 compared; held to c = 0: None.
  succ_pair. (2, 1) (0, 2): 1 = {0}, 3 = {2}. (2, 2) (1, 4): 2 = {1},
  5 = {3}. (2, 3) (2, 7): 3 = {2}, 8 = {4}. (3, 1) (2, 6): 3 = {0, 1},
  7 = {3}. (3, 2) (5, 12): 6 = {1, 2}, 13 = {4}. (4, 6): ones at 0; 2,
  3, 4; 6, 7: 1 + 27 + 164 = 192, and 192 + q_8 = 400.
  state_period. (2, 2) 3: 1 0 1 1 0 1. (2, 3) 8: 1 2 0 2 2 1 0 1 | 1
  2. (3, 3) 13: 1 2 1 1 1 0 2 0 2 1 0 0 1 | 1 2 1. (5, 2) 6 and (9, 2)
  10, by (7). (4, 1) 1. (2, 5) 20, the Pisano period of 5. (2, 3) at
  cap 7 None, at cap 8 8.
  floor_low at (2, 2), depth 12: K = 9: 44 = {1, 4, 7}; K = 10: 72 =
  {0, 2, 5, 8}, at depth 5 {0, 2}; K = 8: 27 = {0, 3, 6}. The three
  limits are {1, 4, 7,
  ..}, {0, 2, 5, 8, ..}, {0, 3, 6, ..}: depth 2 shows {1}, {0}, {0},
  depth 3 parts them: from K = 100 at depth 40, (3, 3, 3, 3); at
  depth 3 the same, at depth 2, (3, 3, 2, None). From K = 1 the
  floors are 1, 1, 2, 4, 6, 10 = {0}, {0}, {1}, {0, 2}, {0, 3}, {1,
  4}: no K repeats, two patterns: (3, 0, 2, None).
  minus. (2, 1, 5): 12 = {0, 2, 4}. (3, 3, 7): L = 4, 13 - 3 = 10 =
  {0, 1, 3}, with {5, 6}: 78. (2, 3, 4), the boundary q_2 = 3: L = 2,
  nothing below, {3}: 5. (2, 3, 3): no L.
  cyclic. ([1], 3) no; ([1, 0], 3) yes; ([1, 1, 0], 2) no; ([1, 0, 1],
  2) no, by the wrap; ([0, 1, 0], 2) yes; ([1, 1, 0], 3) yes; ([0], 2)
  yes.
  word. (2, 2, 3): 4/2 = 2 = {1}: 010. (2, 2, 6): 20/2 = 10 = {1, 4}:
  010010. (3, 3, 13): 3135/3 = 1045: 0100010110000. (2, 3, 8): 54/3 =
  18 = {3, 5}: 00101000. (3, 1, 3): 6 = {1, 2}: 110. (3, 1, 2): 3 =
  {0, 1}: 11. (2, 3, 4): 7 is no multiple of 3. (2, 2, 2): 1 = {0}:
  01.
  quotient. (2, 2, 010): (1 + z)(1 - z - z^2) = 1 - 2z^2 - z^3: 1 + z.
  (2, 2, 010010): (1 + z)(1 + z^3). (3, 1, 110): 1. (3, 1, 11): not
  cyclic. (2, 2, 001): 1 - 3z^3, not divisible. (2, 2, 01): 1 - 3z^2,
  not divisible. (2, 2, 10): 1 - 2z - z^2 = Delta - z, a remainder
  with one coefficient 0. (2, 3, 00101000): 1 - 3z^3 - 3z^5 - z^8 =
  (1 - z - z^2)(1 + z + 2z^2 + 2z^4 - z^5 + z^6).
  certificate. (d, 1): 1^(d-1) 0, period d, k = d, S = 1, no tear. (d,
  2): 0 1^(d-1) 0, period d + 1, k = 1, S = 1 + z, a tear: both at
  every d = 2..12. (3, 3): the word above, 13, k = 1, a tear. (2, 3):
  00101000, 8, k = 1, no tear. (2, 3) at cap 7: None.
  witness. (2, 2, 010): x1 = {1} = 2, y1 = {0, 2} = 4; x2 = {1, 4} =
  10, y2 = {1, 3, 5} = 20: (2, 4, 0). (3, 1, 110): 6 = 6, 43 = 43: (2,
  4, 4). (3, 3, the word): 3 * 1045 = 3135; (2, 17, 1). (2, 2, 01): x1
  = {0} = 1, y1 = {1} = 2; x2 = {0, 2} = 4, y2 = {1, 3} = 7, not 8:
  (1, 2, 3). (2, 2, 001): 1 against 4, 6 against 20: (0, 3, 0). The
  law at the first three words is what they read; at 01 it is (2, 2,
  3), d dividing L.
  pair_row. (3, 3) at cap 50: T, 13, 1, the law read. (2, 3): ., 8, 1,
  read. (3, 1): ., 1, 3, read, and the same at cap 3, the last
  multiple tried; at cap 2 n, 1. (2, 3) at cap 7: ?.

THE RECORD, each value predicted by hand before the engine ran but
where it says otherwise.
  comb     112 doubles, each the phase set, each pair of inputs first
           apart at K + d + 1, each pair of doubles parting by the
           law; d bottoms and largest parting digit d - 2 at every d.
  succ     least lookahead d - 1 at all 18 (d, t); 36 scan pairs, all
           witnesses; the 18 pairs of (2) witnesses at c = d - 2; the
           passes compared span - q_(t+d-1) inputs, every legal string
           of that length being met.
  double   no lookahead to 6 at the three depths; 21 scan pairs, all
           witnesses, the comb's pair a witness beside each; 001001,
           001001001, 0010101 and 1001010101 (by hand: 16 = 13 + 3,
           71 = 55 + 13 + 3, 32 = 21 + 8 + 3, 142 = 89 + 34 + 13 + 5 +
           1), added later.
  floor    18 pairs read and (5, 5), (6, 3) above the bound; every K
           stable and as many patterns as the period at each; of the
           parting depths, (2, 2)'s, the rest entered from the first
           print (at most 12 but 13 at (4, 5) and 14 at (6, 5), as
           predicted).
  minus    6144 cells, all matching, 29 on the boundary, where the one
           L is K - d and q_L = r, and 240 (d, r, K) with no L.
  pairs    the nine rows; at m >= 2, 56 torn, 28 certified and
           undecided, none uncertified, 15 unread; the rows with every
           period above 1199 struck; k = 1 at all 84 certificates with
           m >= 2 and k = d at m = 1; the witness reading its law at
           all 93; n -> 3n torn at d = 3, 4, 5, 6, 9, 10 and undecided
           at d = 2, 7, 8, its words of periods 8, 364, 80.

  What the record does not read: a pair whose state has period above
  20000 (15 of the 99); whether a pair the
  certificate leaves undecided is torn (fibre.py reads those another
  way); a pass of the successor's scan past its span, which (2)
  covers; the floors past depth 40 or at a period above 400. And what
  no recorded value depends on: the cap raised to 26000 (at 19000 a
  pair is lost); the floor stage's first K once the
  patterns have settled (60 reads as 100 does); where phase's teeth
  start between r + 2 and d + 1 + r, the positions between being off
  their class. The quotient's remainder test and floor_row's two
  counts move in the controls alone: at every pair read the first
  candidate certifies and every K is stable, and there the witness's
  second identity is the read of the periodicity that stands apart
  from the division.

RUN RECORD. python bonacci.py: 44 of 44 checks, 1.9 s, peak commit
38.4 MB under a 512 MB guard. The form it replaces ran 13 checks in
3.3 s, and the comb's five in a script of their own. It guessed each
word from 2400 top digits of floor(q_3000/m) under a period below
1200, and found none at 29 pairs: the 29 whose state has period above
1199, 14 of them within this record's 20000. It read Lemma V at 6115
strings, its filter skipping the boundary; the comb's bottoms and
period at d = 2..6, here corollaries of the phase sets; the successor
at Zeckendorf alone, depths 1 to 8 over n < 46368, with no proof.
Dropped with it: a decimal read of theta's contraction at k <= 240
(from 2.51e-14 to 1.73e-27 at d = 3, from 4.36e-03 to 1.91e-04 at d =
10), which (3) takes from its source; the floors' patterns at depth
12, 311 of 312 at (4, 5) and 206 of 208 at (6, 5), now those two
parting depths; the errors e, read periodic over three periods at
its 70 certificates and 1, 2, .., 2, 1 at m = 2, both consequences of
the division, and three K at d = 3, m = 3: now the witness at every
certificate, on the class of 0; the quotient's print at d = 3, m = 3;
the comb's control of phase sets shifted by one (0 of 112 matched),
which differed whatever the code did. Changed after the
predictions were frozen, each by hand before the run that read it:
the comb's pairs are 112, each double with its successor's, where the
freeze counted 105; the scans' counts of inputs compared, left there
to the first print, were derived before it; floor_row takes its start
and depth, for rows where its counts move; the pairs above the floor's
bound are named,
the undecided words' periods are the words' and not the states', and
five rows (comb_pair at depths 5 and 8, the pair (1, 4) at two
depths, the certificate at its last multiple) stand at boundaries a
reader of the draft found unmet, with a "=" that was a congruence.
Predicted wrong by hand: at the freeze, that phase's teeth started
one lower would fail the doubles (the position is off its class and
nothing moves); after it, that the state's period survives its start
written in reverse (the control's rows catch it). After every
single-token fault of the engine and the stages was run through it
(409: 368 fail a check, 3 loop without end, 38 print the same lines):
the doubling stage reads through lookahead, where its count of passes
was a zero nothing had seen move; the quotient gained the word 10,
whose remainder has one coefficient 0; floor_row a row at the depth
where its patterns part; minus builds only the places it reads. The 38
are of five kinds: a place, a table entry or a loop end past what is
read (comb, comb_row, floor_low, word, table, value, the stages'
spans); a bound off its class or never met (phase's K + 2, the strict
inequalities of span_of and of the struck rows, is_witness's n0 < n1,
floor_row's range past its depth); an index walked the other way
round a cycle (cyclic, floor_row's second period); columns equal at
every pair read, which the controls' rows part (the floor stage's
stable K and patterns; in the pairs stage k, 1 at every certificate
with m >= 2, beside the witness's verdict, true at each); and the
doubling control's three depths, alike in every cell.
"""

import sys
import time

CAP = 20000
OLD_CAP = 1199
DEPTH = 40
START = 100
PERIOD_MAX = 400
SPAN_MIN = 5000

RECORD = {
    "comb": {
        "doubles": 112,
        "doubles that are the phase set": 112,
        "input pairs first apart at K + d + 1": 112,
        "double pairs parting by the law": 112,
        "bottoms at d = 2..8": (2, 3, 4, 5, 6, 7, 8),
        "largest parting digit at d = 2..8": (0, 1, 2, 3, 4, 5, 6),
    },
    "succ": {
        "least lookahead at d = 2, 3, 4, t = 1..6":
            ((1,) * 6, (2,) * 6, (3,) * 6),
        "scan pairs, and those that are witnesses": (36, 36),
        "pairs of (2) that are witnesses at c = d - 2": 18,
        "inputs compared at the pass": (
            (6762, 6760, 6757, 6752, 6744, 6731),
            (5761, 5755, 5744, 5724, 5687, 5619),
            (5521, 5507, 5480, 5428, 5328, 5135)),
    },
    "double": {
        "least lookahead at t = 1, 2, 3, c <= 6": (None, None, None),
        "scan pairs, and those that are witnesses": (21, 21),
        "comb pairs that are witnesses": 21,
        "16, 71 and their doubles, low digit first": (
            "001001", "001001001", "0010101", "1001010101"),
    },
    "floor": {
        "pairs read, pairs above the bound": (18, ((5, 5), (6, 3))),
        "periods": (3, 8, 6, 20, 4, 13, 8, 31, 5, 26, 10, 312, 6, 104, 12,
                    7, 14, 208),
        "stable K": (3, 8, 6, 20, 4, 13, 8, 31, 5, 26, 10, 312, 6, 104,
                     12, 7, 14, 208),
        "patterns": (3, 8, 6, 20, 4, 13, 8, 31, 5, 26, 10, 312, 6, 104,
                     12, 7, 14, 208),
        "parting depths": (3, 6, 5, 8, 3, 5, 7, 9, 3, 8, 6, 13, 3, 11, 7,
                           4, 8, 14),
    },
    "minus": {
        "cells": 6144,
        "strings matching": 6144,
        "cells on the boundary": 29,
        "cells with no L": 240,
    },
    "pairs": {
        "rows, m = 1..12 at d = 2..10": (
            ". T . . . . . . . . . .",
            ". T T T T T . T . T T T",
            ". T T T . T T . T . . T",
            ". T T T T T T T T T . T",
            ". T T T T T . T . T ? T",
            ". T . T T . ? T . T ? .",
            ". T . T ? . . T . ? ? .",
            ". T T T ? T ? T T ? ? T",
            ". T T T T ? T T ? ? ? ?"),
        "torn, undecided, uncertified, unread at m >= 2": (56, 28, 0, 15),
        "rows with every period above 1199 struck": (
            ". T . . . . . . . . . .",
            ". T T T T T . T . T T T",
            ". T T T . T T . T ? . T",
            ". T T T T T ? T T ? ? T",
            ". T T T T T . T ? ? ? T",
            ". T . T ? . ? T . ? ? ?",
            ". T . T ? . ? T . ? ? .",
            ". T T T ? T ? T T ? ? ?",
            ". T ? T ? ? ? T ? ? ? ?"),
        "certificates at m >= 2, and those with k = 1": (84, 84),
        "k at m = 1, d = 2..10": (2, 3, 4, 5, 6, 7, 8, 9, 10),
        "certificates, and witnesses reading the law": (93, 93),
        "m = 3 torn at d": (3, 4, 5, 6, 9, 10),
        "m = 3 undecided at (d, the word's period)":
            ((2, 8), (7, 364), (8, 80)),
    },
}


# ---------------------------------------------------------- the strings
def stream(d):
    q = [2 ** j for j in range(d)]
    yield from q
    while True:
        q = q[1:] + [sum(q)]
        yield q[-1]


def places(d, n):
    return [x for _, x in zip(range(n), stream(d))]


def greedy(n, q):
    digs = set()
    for k in reversed(range(len(q))):
        if q[k] <= n:
            digs.add(k)
            n -= q[k]
    if n:
        raise ValueError("the places do not reach n")
    return digs


def refuses(fn, *args):
    try:
        fn(*args)
    except ValueError:
        return True
    return False


def low(s, t):
    return frozenset(x for x in s if x < t)


def apart(a, b):
    diff = set(a) ^ set(b)
    return min(diff) if diff else None


def value(d, s):
    return sum(x for j, x in zip(range(max(s, default=-1) + 1), stream(d))
               if j in s)


# ------------------------------------------------------------- the comb
def comb(d, i):
    K = d + (d + 1) * i
    q = places(d, K + 1)
    return sum(q[j] for j in range(d, K + 1, d + 1))


def phase(d, i):
    K, r = d + (d + 1) * i, i % d
    if r <= d - 2:
        return set(range(r + 1)) | {j for j in range(d + 1 + r, K + 2)
                                    if j % d == (r + 1) % d}
    return {j for j in range(d, K + 2) if j % d == 0}


def parting(d, i):
    r = i % d
    return r + 1 if r <= d - 3 else 0


def comb_row(d, i):
    K = d + (d + 1) * i
    q = places(d, K + d + 3)
    a, b = comb(d, i), comb(d, i + 1)
    two = greedy(2 * a, q)
    return (two, apart(greedy(a, q), greedy(b, q)),
            apart(two, greedy(2 * b, q)))


def comb_pair(d, depth):
    i = 0
    while d + (d + 1) * i + d + 1 < depth:
        i += 1
    return comb(d, i), comb(d, i + 1)


# ------------------------------------------------------------- the scan
def table(d, top):
    n = d
    while places(d, n)[-1] < top:
        n += 1
    q = places(d, n)
    return [sum(1 << j for j in greedy(x, q)) for x in range(top)]


def scan(f, digs, t, c, span):
    first, compared = {}, 0
    for n in range(span):
        key = digs[n] % 2 ** (t + c)
        val = digs[f(n)] % 2 ** t
        if key not in first:
            first[key] = (n, val)
            continue
        compared += 1
        if first[key][1] != val:
            return (first[key][0], n), compared
    return None, compared


def is_witness(f, digs, pair, t, c):
    n0, n1 = pair
    return (n0 < n1 and digs[n0] % 2 ** (t + c) == digs[n1] % 2 ** (t + c)
            and digs[f(n0)] % 2 ** t != digs[f(n1)] % 2 ** t)


def lookahead(f, digs, t, cmax, span):
    found = []
    for c in range(cmax + 1):
        pair, compared = scan(f, digs, t, c, span)
        if pair is None:
            return c, tuple(found), compared
        found.append(pair)
    return None, tuple(found), 0


def succ(n):
    return n + 1


def double(n):
    return 2 * n


def succ_pair(d, t):
    a, k = (t - 1) % d, (t - 1) // d
    ones = set(range(a)) | set(range(t, t + d - 2))
    for b in range(k):
        ones |= set(range(a + b * d + 1, a + b * d + d))
    n0 = value(d, ones)
    return n0, n0 + places(d, t + d - 1)[-1]


def span_of(d):
    n = d
    while places(d, n)[-1] < SPAN_MIN:
        n += 1
    return places(d, n)[-1]


# ------------------------------------------------------------ the floor
def state_period(d, m, cap):
    start = tuple(2 ** j % m for j in reversed(range(d)))
    state = start
    for p in range(1, cap + 1):
        state = (sum(state) % m,) + state[:-1]
        if state == start:
            return p
    return None


def floor_low(d, m, K, t):
    q = places(d, K + 1)
    return low(greedy(q[K] // m, q), t)


def floor_row(d, m, start, depth):
    pi = state_period(d, m, PERIOD_MAX)
    if pi is None:
        return None
    pats = [floor_low(d, m, K, depth) for K in range(start, start + 2 * pi)]
    stable = sum(1 for c in range(pi) if pats[c] == pats[c + pi])
    kinds = len(set(pats[:pi]))
    parts = next((t for t in range(depth + 1)
                  if len({low(p, t) for p in pats[:pi]}) == pi), None)
    return pi, stable, kinds, parts


def minus(d, r, K):
    q = places(d, K)
    reach = [j for j in range(K % d, K, d) if q[j] >= r]
    if not reach:
        return None
    L = reach[0]
    return greedy(q[L] - r, q) | {j for j in range(L, K) if j % d != K % d}


# ------------------------------------------------------ the certificate
def cyclic(W, d):
    L = len(W)
    return all(any(not W[(j + i) % L] for i in range(d)) for j in range(L))


def word(d, m, L):
    q = places(d, L + 1)
    if (q[L] - 1) % m:
        return None
    s = greedy((q[L] - 1) // m, q[:L])
    return [1 if L - i in s else 0 for i in range(1, L + 1)]


def quotient(d, m, W):
    L = len(W)
    if not cyclic(W, d):
        return None
    P = [1] + [-m * w for w in W]
    P[L] -= 1
    S = []
    for k in range(L - d + 1):
        S.append(P[k])
        for j in range(1, d + 1):
            P[k + j] += S[k]
    return None if any(P[len(S):]) else S


def certificate(d, m, cap):
    pi = state_period(d, m, cap)
    if pi is None:
        return None
    for k in range(1, cap // pi + 1):
        W = word(d, m, k * pi)
        S = None if W is None else quotient(d, m, W)
        if S is not None:
            return dict(W=W, pi=k * pi, k=k, S=S, tear=k * pi % d != 0)
    return None


def witness(d, m, W):
    L = len(W)
    xs = [{K - i for i in range(1, K + 1) if W[(i - 1) % L]}
          for K in (L, 2 * L)]
    ys = [{j for j in range(K) if j % d != K % d} for K in (L, 2 * L)]
    holds = sum(1 for x, y in zip(xs, ys)
                if m * value(d, x) == value(d, y))
    return holds, apart(xs[0], xs[1]), apart(ys[0], ys[1])


def witness_law(d, W):
    L = len(W)
    last = max(i for i in range(1, L + 1) if W[i - 1])
    return 2, 2 * L - last, min(L % d, 2 * L % d) if L % d else L + 1


def pair_row(d, m, cap):
    pi = state_period(d, m, cap)
    if pi is None:
        return "?", None, None, None
    cert = certificate(d, m, cap)
    if cert is None:
        return "n", pi, None, None
    W = cert["W"]
    return ("T" if cert["tear"] else ".", pi, cert["k"],
            witness(d, m, W) == witness_law(d, W))


# ----------------------------------------------------------- the stages
def stage_comb():
    cells = sets = inputs = doubles = 0
    bottoms, largest = [], []
    for d in range(2, 9):
        rows = [comb_row(d, i) for i in range(3 * d + 1)]
        for i, (two, agree, part) in enumerate(rows):
            cells += 1
            sets += two == phase(d, i)
            inputs += agree == d + (d + 1) * i + d + 1
            doubles += part == parting(d, i)
        bottoms.append(len({low(two, d) for two, _, _ in rows}))
        largest.append(max(part for _, _, part in rows))
    return {
        "doubles": cells,
        "doubles that are the phase set": sets,
        "input pairs first apart at K + d + 1": inputs,
        "double pairs parting by the law": doubles,
        "bottoms at d = 2..8": tuple(bottoms),
        "largest parting digit at d = 2..8": tuple(largest),
    }


def stage_succ():
    least, compared, pairs, good, built = [], [], 0, 0, 0
    for d in (2, 3, 4):
        span = span_of(d)
        digs = table(d, span + 1)
        row, seen = [], []
        for t in range(1, 7):
            c, found, n = lookahead(succ, digs, t, d - 1, span)
            row.append(c)
            seen.append(n)
            pairs += len(found)
            good += sum(1 for j, pair in enumerate(found)
                        if is_witness(succ, digs, pair, t, j))
            built += is_witness(succ, digs, succ_pair(d, t), t, d - 2)
        least.append(tuple(row))
        compared.append(tuple(seen))
    return {
        "least lookahead at d = 2, 3, 4, t = 1..6": tuple(least),
        "scan pairs, and those that are witnesses": (pairs, good),
        "pairs of (2) that are witnesses at c = d - 2": built,
        "inputs compared at the pass": tuple(compared),
    }


def stage_double():
    span = span_of(2)
    digs = table(2, 2 * span)
    least, pairs, good, combs = [], 0, 0, 0
    for t in (1, 2, 3):
        c, found, _ = lookahead(double, digs, t, 6, span)
        least.append(c)
        pairs += len(found)
        for j, pair in enumerate(found):
            good += is_witness(double, digs, pair, t, j)
            combs += is_witness(double, digs, comb_pair(2, t + j), t, j)
    low = tuple(bin(digs[n])[:1:-1] for n in (16, 71, 32, 142))
    return {
        "least lookahead at t = 1, 2, 3, c <= 6": tuple(least),
        "scan pairs, and those that are witnesses": (pairs, good),
        "comb pairs that are witnesses": combs,
        "16, 71 and their doubles, low digit first": low,
    }


def stage_floor():
    rows = {(d, m): floor_row(d, m, START, DEPTH)
            for d in range(2, 7) for m in range(2, 6)}
    read = [row for row in rows.values() if row is not None]
    return {
        "pairs read, pairs above the bound": (
            len(read), tuple(pair for pair in rows if rows[pair] is None)),
        "periods": tuple(row[0] for row in read),
        "stable K": tuple(row[1] for row in read),
        "patterns": tuple(row[2] for row in read),
        "parting depths": tuple(row[3] for row in read),
    }


def stage_minus():
    cells = hits = edge = none = 0
    for d in range(2, 9):
        q = places(d, 81)
        for r in range(1, 13):
            for K in range(d, 81):
                want = minus(d, r, K)
                if want is None:
                    none += 1
                    continue
                cells += 1
                hits += greedy(q[K] - r, q) == want
                edge += q[K - d] == r
    return {
        "cells": cells,
        "strings matching": hits,
        "cells on the boundary": edge,
        "cells with no L": none,
    }


def stage_pairs():
    grid = {(d, m): pair_row(d, m, CAP)
            for d in range(2, 11) for m in range(1, 13)}
    rows = tuple(" ".join(grid[d, m][0] for m in range(1, 13))
                 for d in range(2, 11))
    struck = tuple(" ".join(
        "?" if grid[d, m][1] is None or grid[d, m][1] > OLD_CAP
        else grid[d, m][0] for m in range(1, 13)) for d in range(2, 11))
    upper = [row for (d, m), row in grid.items() if m > 1]
    certs = [row for row in grid.values() if row[2] is not None]
    return {
        "rows, m = 1..12 at d = 2..10": rows,
        "torn, undecided, uncertified, unread at m >= 2": tuple(
            sum(1 for row in upper if row[0] == letter)
            for letter in "T.n?"),
        "rows with every period above 1199 struck": struck,
        "certificates at m >= 2, and those with k = 1": (
            sum(1 for row in upper if row[2] is not None),
            sum(1 for row in upper if row[2] == 1)),
        "k at m = 1, d = 2..10": tuple(grid[d, 1][2] for d in range(2, 11)),
        "certificates, and witnesses reading the law": (
            len(certs), sum(1 for row in certs if row[3])),
        "m = 3 torn at d": tuple(d for d in range(2, 11)
                                 if grid[d, 3][0] == "T"),
        "m = 3 undecided at (d, the word's period)": tuple(
            (d, grid[d, 3][1] * grid[d, 3][2]) for d in range(2, 11)
            if grid[d, 3][0] == "."),
    }


# ---------------------------------------------------------- the harness
CONTROL_LINES = 13
CHECKS = []


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


def check_hand(name, pairs):
    hits = sum(1 for got, want in pairs if got == want)
    check(name, hits == len(pairs), f"{hits} of {len(pairs)} cases")


def check_record(stage, got):
    want = RECORD[stage]
    for key in got:
        ok = got[key] == want.get(key)
        check(f"{stage}: {key}", ok,
              f"{got[key]}" + ("" if ok else f", recorded {want.get(key)}"))


def section(title):
    print()
    print(title)
    print("-" * len(title))


def section_hand():
    section("CONTROLS: each function on values written by hand")
    q2, q3 = places(2, 11), places(3, 14)
    check_hand("places at d = 2, 3, 4, by the list and by the stream", [
        (q2, [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]),
        (q3, [1, 2, 4, 7, 13, 24, 44, 81, 149, 274, 504, 927, 1705, 3136]),
        (places(4, 8), [1, 2, 4, 8, 15, 29, 56, 108]),
        (places(3, 2), [1, 2]),
        (value(2, {0, 2, 4}), 12), (value(3, {4, 5, 7, 11}), 1045),
        (value(4, set()), 0)])
    check_hand("greedy on five integers, at and past its places, low, apart", [
        (greedy(12, q2), {0, 2, 4}), (greedy(72, q2), {0, 2, 5, 8}),
        (greedy(3, q2), {2}), (greedy(78, q3), {0, 1, 3, 5, 6}),
        (greedy(1045, q3), {4, 5, 7, 11}),
        (refuses(greedy, 8, q2[:3]), True),
        (greedy(5, q2[:3]), {1, 2}),
        (low({0, 2, 5, 8}, 5), {0, 2}), (low({0, 2, 5, 8}, 6), {0, 2, 5}),
        (apart({0, 3}, {2, 4, 6}), 0), (apart({0, 4}, {0, 1, 5, 8}), 1),
        (apart({1}, {1, 4}), 4), (apart({1, 4}, {1, 4}), None)])
    check_hand("comb, phase and parting at d = 2, 3, 4", [
        (tuple(comb(2, i) for i in range(3)), (3, 16, 71)),
        (tuple(comb(3, i) for i in range(3)), (7, 88, 1015)),
        (phase(2, 0), {0, 3}), (phase(2, 1), {2, 4, 6}),
        (phase(2, 2), {0, 3, 5, 7, 9}), (phase(3, 0), {0, 4}),
        (phase(3, 1), {0, 1, 5, 8}), (phase(3, 2), {3, 6, 9, 12}),
        (tuple(parting(2, i) for i in range(3)), (0, 0, 0)),
        (tuple(parting(3, i) for i in range(4)), (1, 0, 0, 1)),
        (tuple(parting(4, i) for i in range(5)), (1, 2, 0, 0, 1))])
    check_hand("comb_row at four (d, i), comb_pair at five depths", [
        (comb_row(2, 0), ({0, 3}, 5, 0)),
        (comb_row(2, 1), ({2, 4, 6}, 8, 0)),
        (comb_row(3, 0), ({0, 4}, 7, 1)),
        (comb_row(3, 1), ({0, 1, 5, 8}, 11, 0)),
        (comb_pair(2, 1), (3, 16)), (comb_pair(2, 5), (3, 16)),
        (comb_pair(2, 6), (16, 71)), (comb_pair(2, 8), (16, 71)),
        (comb_pair(2, 9), (71, 304))])
    digs = table(2, 40)
    check_hand("table, scan, is_witness and lookahead at Zeckendorf", [
        (digs[:8], [0, 1, 2, 4, 5, 8, 9, 10]), (digs[16], 0b100100),
        (scan(succ, digs, 1, 0, 8), ((0, 2), 1)),
        (scan(succ, digs, 1, 1, 8), (None, 5)),
        (is_witness(succ, digs, (0, 2), 1, 0), True),
        (is_witness(succ, digs, (0, 2), 1, 1), False),
        (is_witness(succ, digs, (0, 3), 1, 1), False),
        (is_witness(succ, digs, (2, 0), 1, 0), False),
        (is_witness(succ, digs, (1, 4), 1, 0), False),
        (is_witness(succ, digs, (1, 4), 2, 0), True),
        (is_witness(double, digs, (3, 16), 1, 0), True),
        (lookahead(succ, digs, 1, 1, 8), (1, ((0, 2),), 5)),
        (lookahead(succ, digs, 1, 0, 8), (None, ((0, 2),), 0))])
    check_hand("succ_pair at six (d, t), the scan's span at d = 2, 3, 4", [
        (succ_pair(2, 1), (0, 2)), (succ_pair(2, 2), (1, 4)),
        (succ_pair(2, 3), (2, 7)), (succ_pair(3, 1), (2, 6)),
        (succ_pair(3, 2), (5, 12)), (succ_pair(4, 6), (192, 400)),
        (tuple(span_of(d) for d in (2, 3, 4)), (6765, 5768, 5536))])
    check_hand("state_period at seven (d, m) and at a cap one short", [
        (state_period(2, 2, 50), 3), (state_period(2, 3, 50), 8),
        (state_period(3, 3, 50), 13), (state_period(5, 2, 50), 6),
        (state_period(9, 2, 50), 10), (state_period(4, 1, 50), 1),
        (state_period(2, 5, 50), 20), (state_period(2, 3, 7), None),
        (state_period(2, 3, 8), 8)])
    check_hand("floor_low at four (K, t), floor_row at four (start, "
               "depth)", [
        (floor_low(2, 2, 9, 12), {1, 4, 7}),
        (floor_low(2, 2, 10, 12), {0, 2, 5, 8}),
        (floor_low(2, 2, 8, 12), {0, 3, 6}),
        (floor_low(2, 2, 10, 5), {0, 2}),
        (floor_row(2, 2, 100, 40), (3, 3, 3, 3)),
        (floor_row(2, 2, 100, 3), (3, 3, 3, 3)),
        (floor_row(2, 2, 100, 2), (3, 3, 2, None)),
        (floor_row(2, 2, 1, 40), (3, 0, 2, None))])
    check_hand("minus at three cells and one with no L", [
        (minus(2, 1, 5), {0, 2, 4}), (minus(3, 3, 7), {0, 1, 3, 5, 6}),
        (minus(2, 3, 4), {3}), (minus(2, 3, 3), None)])
    w33 = [0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0]
    check_hand("cyclic at seven words, word at eight (d, m, L)", [
        (cyclic([1], 3), False), (cyclic([1, 0], 3), True),
        (cyclic([1, 1, 0], 2), False), (cyclic([1, 0, 1], 2), False),
        (cyclic([0, 1, 0], 2), True), (cyclic([1, 1, 0], 3), True),
        (cyclic([0], 2), True),
        (word(2, 2, 3), [0, 1, 0]), (word(2, 2, 6), [0, 1, 0, 0, 1, 0]),
        (word(3, 3, 13), w33), (word(2, 3, 8), [0, 0, 1, 0, 1, 0, 0, 0]),
        (word(3, 1, 3), [1, 1, 0]), (word(3, 1, 2), [1, 1]),
        (word(2, 3, 4), None), (word(2, 2, 2), [0, 1])])
    check_hand("quotient at eight (d, m, W)", [
        (quotient(2, 2, [0, 1, 0]), [1, 1]),
        (quotient(2, 2, [0, 1, 0, 0, 1, 0]), [1, 1, 0, 1, 1]),
        (quotient(3, 1, [1, 1, 0]), [1]), (quotient(3, 1, [1, 1]), None),
        (quotient(2, 2, [0, 0, 1]), None), (quotient(2, 2, [0, 1]), None),
        (quotient(2, 2, [1, 0]), None),
        (quotient(2, 3, [0, 0, 1, 0, 1, 0, 0, 0]), [1, 1, 2, 0, 2, -1, 1])])
    ones = [certificate(d, 1, 50) for d in range(2, 13)]
    twos = [certificate(d, 2, 50) for d in range(2, 13)]
    check_hand("certificate at m = 1 and m = 2, d = 2..12, and three more", [
        ([c and (c["W"], c["pi"], c["k"], c["S"], c["tear"]) for c in ones],
         [([1] * (d - 1) + [0], d, d, [1], False) for d in range(2, 13)]),
        ([c and (c["W"], c["pi"], c["k"], c["S"], c["tear"]) for c in twos],
         [([0] + [1] * (d - 1) + [0], d + 1, 1, [1, 1], True)
          for d in range(2, 13)]),
        (certificate(3, 3, 50)["W"], w33),
        ([certificate(3, 3, 50)[key] for key in ("pi", "k", "tear")],
         [13, 1, True]),
        ([certificate(2, 3, 50)[key] for key in ("W", "pi", "k", "tear")],
         [[0, 0, 1, 0, 1, 0, 0, 0], 8, 1, False]),
        (certificate(2, 3, 7), None)])
    check_hand("witness at five words, its law at four, pair_row at "
               "six", [
        (witness(2, 2, [0, 1, 0]), (2, 4, 0)),
        (witness(3, 1, [1, 1, 0]), (2, 4, 4)),
        (witness(3, 3, w33), (2, 17, 1)),
        (witness(2, 2, [0, 1]), (1, 2, 3)),
        (witness(2, 2, [0, 0, 1]), (0, 3, 0)),
        (witness_law(2, [0, 1, 0]), (2, 4, 0)),
        (witness_law(3, [1, 1, 0]), (2, 4, 4)),
        (witness_law(3, w33), (2, 17, 1)),
        (witness_law(2, [0, 1]), (2, 2, 3)),
        (pair_row(3, 3, 50), ("T", 13, 1, True)),
        (pair_row(2, 3, 50), (".", 8, 1, True)),
        (pair_row(3, 1, 50), (".", 1, 3, True)),
        (pair_row(3, 1, 3), (".", 1, 3, True)),
        (pair_row(2, 3, 7), ("?", None, None, None)),
        (pair_row(3, 1, 2), ("n", 1, None, None))])


def section_stage(stage, title, stage_fn):
    t0 = time.time()
    got = stage_fn()
    section(title)
    check_record(stage, got)
    print("  (%.1f s)" % (time.time() - t0))


def main():
    t_all = time.time()
    section_hand()
    if not all(CHECKS):
        print("\nCONTROL FAILED: nothing below is read.")
        sys.exit(1)
    lines = CONTROL_LINES + sum(len(RECORD[s]) for s in RECORD)
    section_stage("comb", "COMB: the doubled comb at d = 2..8", stage_comb)
    section_stage("succ", "SUCC: the successor's lookahead at d = 2, 3, 4",
                  stage_succ)
    section_stage("double", "DOUBLE: 2n at Zeckendorf, the scan's control",
                  stage_double)
    section_stage("floor", "FLOOR: floor(q_K/m) along the state classes",
                  stage_floor)
    section_stage("minus", "MINUS: the strings of q_K - r", stage_minus)
    section_stage("pairs", "PAIRS: the certificate at d = 2..10, m = 1..12",
                  stage_pairs)
    ran = len(CHECKS)
    check("every check line of the run printed, this one aside",
          ran == lines, f"{ran} of {lines}")
    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()