reading.py

"""reading.py -- which maps a digit-by-digit reader computes at bounded
lookahead, what the numeration's tiles charge for it, and which place
pays for a wall.

QUESTION. A NUMERATION writes the points of a complete metric space X
as digit streams: its depth-t TILES are the sets of points sharing a
t-digit prefix, nested, with mesh delta_t -> 0 and Lebesgue number l_t
(every set of diameter < l_t lies in one depth-t tile). A reader of f
at lookahead c sees an input tile at depth t + c and must commit an
output tile at depth t holding the image, the commitments nesting.
Which f can be read at bounded c, what does the tiles' shape charge,
and for the integer maps n -> mn and n -> floor(n/m), what decides?
The specimens: base b (trailing digits of n, completing to the b-adic
integers), a divisor chain M_1 | M_2 | ... (the classes n mod M_t; the
primorial chain completes to the product of the F_p), leading base b
(the reals by their high digits), and over F_q[x] both the trailing
x-adic numeration and the leading one at the place at infinity.

BY HAND.
  (1) THE READING LEMMA. If f is L-Lipschitz, a depth-(t + c) tile has
      image of diameter <= L delta_(t+c), which lies in one depth-t
      tile once L delta_(t+c) < l_t; where the tiles chosen nest, that
      fit at every depth is a reader. Ball tiles of an ultrametric
      have l_t >= delta_t (at base b exactly b delta_t), so the fit
      costs at most floor(log_b L) digits. A partition of a connected
      space into two tiles or more has l_t = 0: the lemma is silent
      and readability is asked map by map. An overlapping cover can
      have l_t > 0, but a Lebesgue number alone does not make the next
      commitment a child of the last.
  (2) THE PLACE. In an ultrametric a set of diameter <= r lies in the
      closed ball of radius r about any of its points, and the digit
      tiles of a completion of Q or F_q(x) at a non-archimedean place,
      fixed in position, are its balls: every Lipschitz self-map of
      the unit ball is read at bounded lookahead there. A WALL, a
      point where the committed depth stays bounded however far the
      input is read, needs for a Lipschitz map a partition of a
      connected space, and of those completions only R is connected.
      Read with the leading exponent first, tiles move with the point
      and y -> y - 1, which cancels leading digits, has no bounded
      lookahead at any place; scaling still reads off R: at the
      1/x-adic place the leading j digits of u y are fixed by the
      leading j digits of y for every u != 0, since with no carries a
      lower term of y reaches only lower terms of u y. The 3-adic arm
      (multiplication mod 3^j is well defined) and the leading base 10
      arms (3 (10^k - 1)/3 = 10^k - 1, so 3y maps the tile 0.3...3
      onto [1 - 10^-k, 1 + 2 10^-k), which holds 1 inside; 2a + 2 <=
      10 (floor(2a/10) + 1), so 2y reads at c = 1) are these lines and
      no code.
  (3) THE WALL CRITERION. Take a partition of a real interval by
      half-open tiles whose endpoints B stay endpoints at every deeper
      depth, f continuous and strictly increasing, y not in B. If f(y)
      is not in B it lies inside its tile at every depth and a fine
      enough input tile maps into it: the committed depth grows
      without bound. If f(y) is in B, an endpoint first at depth e,
      every input tile about y has an image holding f(y) inside, which
      no tile of depth e or more holds: the committed depth is at most
      e - 1, and is e - 1 once the image sits in one depth-(e - 1)
      tile. For y -> y^2 at leading base 10, B = Z[1/10], the depth-n
      input tile about y is [Y, Y + 1) 10^-n, Y = floor(10^n y), and
      its image [Y^2, (Y + 1)^2) 10^-2n has width (2Y + 1) 10^-2n. At
      y = sqrt(1/3) that width is over 10^-n and under 1.16 10^-n,
      while 1/3 sits 3.33 10^-n from the nearer end of its depth- (n -
      1) tile: the committed depth is n - 1 at every n >= 1. At y =
      sqrt(1/7) the width is under 0.76 10^-n + 10^-2n and over
      10^-(n+1), and 1/7 sits at least 1.42 10^-n from each end of its
      depth-(n - 1) tile: the committed depth is n - 1 or n.
  (4) THE LIPSCHITZ CRITERION. On a trailing numeration "agreement to
      depth t + c forces image agreement to depth t" is dist(fy, fz)
      <= b^c dist(y, z) in the agreement ultrametric, so f is read at
      lookahead c at every depth iff it is b^c-Lipschitz. Continuity
      is weaker: on a compact completion it gives a lookahead finite
      at every depth. Three classes: LIPSCHITZ (bounded lookahead),
      MIDDLE (finite at every depth, unbounded), DISCONTINUOUS (none
      at some depth). The decimation D(n)
      = sum over j >= 0 of n_2j 2^j at base 2, n_j the digit of n at
      position j, needs input digits 0..2t - 2 for output digits
      0..t - 1: c_min(D, t) = t - 1. Its witnesses below t - 1: with
      M = 2^(t+c), if t + c is even D(M) = 2^((t+c)/2), not 0 mod 2^t;
      if t + c is odd D(M + j) = D(j) for j < M and D(2M) =
      2^((t+c+1)/2), not 0 mod 2^t.
  (5) THE DIVISION CRITERION. On a divisor chain, n -> mn keeps every
      agreement mod M_t. At a depth with N = M_t >= 2, floor(n/m) is
      read at lookahead c iff m N | M, M = M_(t+c). If m N | M, n mod
      m is fixed by n mod M and the quotients of inputs agreeing there
      differ by a multiple of M/m, which N divides. Conversely inputs
      agreeing mod M are joined by steps of M, and the step from n
      moves the quotient by floor((r + M)/m), r = n mod m, which takes
      the value floor(M/m) and, when m does not divide M, also
      floor(M/m) + 1: two consecutive integers are not both divisible
      by N, so m | M, and then N | M/m. Over F_q[x] the sufficiency
      transfers (the remainder has degree below deg m) and necessity
      is by linearity: the condition is that floor(kM/m) lies in (N)
      for every polynomial k; if m does not divide M, write M = hm +
      s, s != 0, and k = 1 asks h in (N), after which k = x^(deg m -
      deg s) gives floor(kM/m) = kh + a, a a nonzero constant, which
      (N) does not hold, deg N being at least 1. At base b the
      condition is m | b^c. At the primorial chain it holds iff m is a
      squarefree product of primes in (p_t, p_(t+c)]. At the factorial
      chain M_t = (t + 1)! it is m | (t + 2)...(t + c + 1), true by c
      = m, m consecutive integers having a product divisible by m!.
  (6) THREE CLASSES ON ONE CHAIN. By (5) floor(n/m) is LIPSCHITZ iff
      the least c with m M_t | M_(t+c) is bounded over t, MIDDLE iff
      it is finite at every t and unbounded, DISCONTINUOUS iff some
      depth has none; at a fixed base it is constant in t, so the
      middle is empty there. Radix 2 at the depths that are
      powers of two and radix 3 elsewhere: M_(t+c)/M_t is the product
      of the radices at depths t + 1..t + c. floor(n/2) waits for the
      next power of two, c = 2^(bits of t) - t, finite and unbounded;
      floor(n/4) for the second, 2^(bits of t + 1) - t; floor(n/3)
      reads at c = 1, or 2 where t + 1 is a power of two; floor(n/5)
      at no c.

THE ENGINE. Integers throughout; a polynomial over F_2 is its bit mask.
  scan(f, m_in, m_out, span) reads n = 0..span - 1 in order, keeps
  f(n) mod m_out of the first input of each class mod m_in, and
  returns the first later input that differs from its class's first,
  as the pair (n0, n1), with the count of inputs compared; (None,
  count) when none differs. is_witness re-reads a pair by subtraction;
  on scan's own pairs it cannot fail (scan returns only such pairs), so
  the counts "re-read" below are consistency, and its test is the hand
  control's.
  lookahead(f, mod, per, t, cmax) is the least c <= cmax whose scan of
  span 2 lcm(per(t), mod(t + c)) finds no pair, with a witness for
  each c below it and the inputs the pass compared. per(t) is a period
  of f mod mod(t), given by hand: 10^t for 7n; m M_t for floor(n/m),
  as (n + m N)//m = n//m + N; 2^(2t-1) for D, since adding 2^(2t-1)
  moves bits 2t - 1 and up, so output bits t and up. Given the period,
  the pair (n mod M_(t+c), f(n) mod M_t) has period P = lcm(per,
  M_(t+c)): if two congruent inputs differ in output, one of them
  differs from the first of its class, and so does its residue mod P,
  which the scan meets below P. So a pass is exact; the second period
  is the scan's own read of the period. At every pass of this record
  the period divides the input modulus, so the span is two input
  periods and no record moves if a period is given too small there;
  where it earns its place is at a failure whose second input is 2 M
  or more: D's at t + c odd, and floor(n/m)'s where M <= m/2. decimate
  is D. decimation_witness(t, c) is (4)'s pair. pmul, pdivmod, ppow
  are F_2[x]'s product, division and power; pdivmod raises on a zero
  divisor, and refuses says whether a call raised. lead(Y, j) is the
  top j binary digits of Y. conflicts(out, N, j) runs X over the
  2^(N-1) inputs of N digits with top digit 1 and returns the number
  of keys (the top j digits of X) and of keys whose inputs give two
  different lead(out(X), j). times(u) is y -> u y and over(u) is y ->
  y/u carried to y's own N digits (how far it is carried past j is
  free: a longer quotient has the same leading digits); triple is the
  integer 3X. root(num, den, n) is Y = floor(10^n sqrt(num/den)), the
  integer root of floor(num 10^(2n)/den). emission(num, den, n) is the
  output depth y -> y^2 commits at leading base 10 on the depth-n
  input tile about sqrt(num/den), the image held in integers, units of
  10^-2n: -1 is a tile of width 10, -2 not even that.
  vertex_depth(num, den) is the least e >= 0 with 10^e num/den an
  integer, the larger exponent of 2 and 5 in the denominator, None off
  Z[1/10]; a multiple of 10, an endpoint before depth 0, is outside it
  and none is read. criterion(m, N, M) is m N | M. one_step(m, N, M)
  reads (5)'s steps at r = 0..m - 1. full(m, N, M) is the scan of
  floor(n/m) over two periods of the pair: it reduces nothing to one
  step, and where the divisibility holds its pass is the period's.
  chain_c(test, m, mod, t, cmax) is the least c <= cmax with test(m,
  mod(t), mod(t + c)). poly_brute(m, N, M) groups every polynomial n
  of degree at most deg M + deg m by n mod M and returns the first
  pair whose quotients by m differ mod N; is_poly_witness re-reads
  one. The degree is (5)'s: its two witnesses are kM at k = 1 and k =
  x^(deg m - deg s). primorial(t) is p_t#; table(radix, top) a chain
  from its radices; form(m, t) is (6)'s closed form.

THE STAGES.
  lemma    trailing base 10, depths 1 to 3: 7n, floor(n/2), floor(n/4)
           and floor(n/3) through lookahead at c <= 3.
  place    the 1/x-adic numeration of F_2((1/x)): y u and y/u at u =
           x + 1 and x^2 + x + 1 through conflicts at every j = 2..11
           of 12 digits (j = 1 and j = 12 read nothing: the top digit
           is 1, and at 12 the key is the input). Its CONTROL: the
           integer 3X, whose carries move its leading digits.
  wall     y -> y^2 at seven points, every input depth n = 1..200:
           five images that are endpoints, of depth 0, 1 and 2, and
           sqrt(1/3), sqrt(1/7).
  middle   the decimation through lookahead at t = 1..10.
  chain    m M_t | M_(t+c) against the one-step test at bases 10 and
           12 (m = 2..12, t = 1..3, c = 0..4) and the primorial chain
           (m = 2..30, t = 1..4, c = 0..6), and against the full scan
           where M_(t+c) <= 2310; the primorial depths with a
           lookahead, by the divisibility.
  poly     the same against poly_brute over F_2[x]: bases x and x (x
           + 1), m of degree 1 to 3, t = 1, 2, c = 0, 1, 2.
  classes  (6)'s chain at t = 1..40, c <= 200, by the divisibility and
           by the one-step test, and the factorial chain at m = 2..7,
           c <= 10.

BY HAND, the controls' values.
  scan. f = n//2, m_in = 2, m_out = 2, span 8: classes 0, 1 start at 0,
  0; n = 2 reads 1: (0, 2), one compared. f = n//2, m_in = 4, m_out =
  2, span 8: 0, 0, 1, 1 twice: none, 4 compared. f = n//3, m_in = 3,
  m_out = 2, span 6: (0, 3), one compared. A span of one period
  compares nothing. For floor(n/3), m_in = m_out = 10: (0, 10) is a
  witness (3 against 0); (0, 30) is not (10 against 0), nor (3, 33)
  (11 against 1), nor (0, 3) (1 against 0, not congruent), nor (10, 0)
  (out of order).
  lookahead at base 10, t = 1: 7n reads at 0 with 10 compared;
  floor(n/2) at 1 past the witness (0, 10) with 100 compared;
  floor(n/3) at neither c <= 1. floor(n/5) at base 2, t = 1, c <= 1:
  at c = 0 the classes mod 2 start at 0, 0 and n = 2, 3, 4 read 0; 5
  reads 1: (1, 5), its second input past 2 M = 4, which a span of 2
  M would miss; at c = 1, (1, 5) again.
  D(0b1011) = 1, D(0b10101) = 7, D(0b1010) = 0, D(0b110) = 2. The
  witness at (t, c) = (2, 0) is (0, 4), at (3, 0) (0, 16), at (5, 3)
  (0, 256).
  (x + 1)(x^2 + x + 1) = x^3 + 1: pmul(0b11, 0b111) = 0b1001;
  pdivmod(0b1001, 0b11) = (0b111, 0); pdivmod(0b1000, 0b11) = (0b111,
  1); pdivmod(0b101, 0b110) = (1, 0b11); pdivmod(0b10000, 0b11) =
  (0b1111, 1). Division by 0 is refused, by 1 not. ppow(0b110, 2) =
  0b10100; ppow(0b10, 3) = 0b1000.
  lead(0b110101, 2) = 0b11, lead(0b110101, 4) = 0b1101. (x + 1)(x^2
  + x) = x^3 + x: times(0b11) sends 0b110 to 0b1010. (x^3 + x^2 + x)/
  (x + 1) = x^2 + 1: over(0b11) sends 0b111 to 0b101. x^4/(x^2 + x +
  1) = x^2 + x: over(0b111) sends 0b100 to 0b110. triple sends 5 to
  15.
  conflicts, as (keys, keys with two outputs). y -> (x + 1) y at N =
  3, j = 2: 100 -> 1100, 101 -> 1111, 110 -> 1010, 111 -> 1001: (2,
  0). y -> y/(x + 1) at N = 3, j = 2: 111, 110, 100, 101: (2, 0).
  The integer 3X at N = 3, j = 2: 1100, 1111, 10010, 10101: (2, 0). At
  N = 4, j = 2: key 10: 24 = 11000, 27, 30 = 11110, 33 = 100001, a
  conflict; key 11: 36 = 100100 .. 45 = 101101: (2, 1). At N = 12: j =
  1: (1, 0). j = 2: key 10 holds X = 2048 (3X = 6144, top 11) and X =
  2731 (3X = 8193, top 10); key 11: 3X in [9216, 12288), top 10: (2,
  1). j = 3: key 100: [6144, 7680) crosses 7168; 101: [7680, 9216)
  crosses 8192; 110: [9216, 10752) crosses 10240 (14 digits, cells of
  2048); 111: [10752, 12288) inside [10240, 12288): (4, 3). j = 12:
  (2048, 0).
  root(num, den, n) = floor(10^n sqrt(num/den)): (2, 1, 0) 1, (9, 10,
  1) 9, (1, 3, 2) 57, (1, 7, 3) 377 (377^2 = 142129, 378^2 = 142884);
  (1, 3, 3) 577 (577^2 = 332929, 578^2 = 334084).
  emission(num, den, n), the image [Y^2, (Y + 1)^2) 10^-2n. (2, 1, 0):
  [1, 4): -1. (50, 1, 0): [49, 64): -2. (9, 10, 1): [0.81, 1.00), its
  right end on the endpoint: 0. (1, 200, 1): Y = 0, [0, 0.01): 2.
  (1, 5, 1): [0.16, 0.25): 0. (1, 2, 1): [0.49, 0.64): 0. (3, 25, 1):
  [0.09, 0.16) holds 0.1: 0. (3, 25, 2): [0.1156, 0.1225) in [0.1,
  0.2): 1. (1, 3, 1): [0.25, 0.36): 0. (1, 3, 2): [0.3249, 0.3364): 1.
  (1, 7, 1): [0.09, 0.16): 0. (1, 7, 2): [0.1369, 0.1444): 1. (1, 7,
  3): [0.142129, 0.142884) in [0.142, 0.143): 3.
  vertex_depth: (2, 1) 0, (1, 5) 1, (1, 2) 1, (3, 25) 2, (1, 8) 3,
  (5, 10) 1, (6, 4) 1, (1, 3) and (1, 7) None.
  The cells (m, N, M), by the divisibility and by the steps (r + M)//m
  - r//m at r = 0..m - 1 mod N. (4, 10, 100): no; 25 at r = 0. (4,
  10, 1000): yes; 250 throughout. (3, 2, 6): yes. (3, 6, 30): no. (5,
  3, 3): no; 0, 0, 1, 1, 1, the first failing residue 2. (3, 2, 7):
  no; 2, 2, 3, only the last residue. (2, 2, 5): no; 2, 3. The full
  scan at (4, 10, 100): (0, 100), one compared; at (4, 10, 1000): none,
  1000 compared; at (3, 2, 7): 7//3 = 2, 8//3 = 2, 9//3 = 3 against
  0: (2, 9), 3 compared.
  primorial(1..5) = 2, 6, 30, 210, 2310. chain_c on it at c <= 7:
  floor(n/3) at t = 1 reads at 1, at t = 2 never; floor(n/5) at t = 2
  at 1; floor(n/4) at t = 1 never; m = 1 at 0. At c <= 1 floor(n/3)
  at t = 1 still reads at 1, at c <= 0 not.
  poly_brute(m, N, M). (x, x, x): key the constant term, value the
  coefficient of x: 0 and 2 = x share key 0: (0, 2). (x, x, x^2):
  none. (x + 1, x, x^2): x^2 = (x + 1)^2 + 1, quotient x + 1 against
  0: (0, 4). (x + 1, x, x^2 + x + 1), where M = x m + 1 and k = 1
  passes: the keys 0, 1, x, x + 1 start at values 0, 0, 1, 1, and n =
  x^2 .. x^2 + x + 1 repeat them; x^3 = (x + 1)(x^2 + x + 1) + 1 has
  key 1 and quotient x^2 + x + 1, value 1 against 0: (1, 8), of
  degree deg M + deg m, the bound's own.
  The chain of (6): M_1..M_5 = 2, 4, 12, 24, 72; the factorial chain's
  2, 6, 24. form: (2, 1) 1, (2, 4) 4, (2, 5) 3, (4, 1) 3, (4, 4) 12,
  (3, 1) 2, (3, 2) 1, (3, 7) 2, (5, 9) None.

FROZEN FOR THIS ENGINE, before it first ran.
  F1 lemma. At t = 1, 2, 3: 7n reads at c = 0 with 10^t inputs
     compared; floor(n/2) at 1 past the witness (0, 10^t), 10^(t+1)
     compared; floor(n/4) at 2 past (0, 10^t) and (0, 10^(t+1)),
     10^(t+2) compared; floor(n/3) at no c <= 3, its witnesses (0,
     10^(t+c)): the first input of a class is its residue, and 10^k//3
     = 33..3. All 21 witnesses re-read.
  F2 middle. c_min(D, t) = t - 1 at t = 1..10; the 45 witnesses are
     (4)'s, 25 of them (0, 2^(t+c)), which D makes a witness only at
     t + c even; the pass compares 2^(2t-1).
  F3 place. 40 cells, 8184 keys (2046 a map), none with two outputs.
     The integer 3X has such a key at every j = 2..11; 0, 1, 3, 0 of
     them at j = 1, 2, 3, 12. Not predicted: its counts at j = 4..11.
     (Three keys first drafted, each implied by another, were cut
     before the script was kept: the count of those j, floor(n/5)'s 40
     depths, and the factorial cells at most m.)
  F4 wall. The endpoint images freeze at one less than their depth at
     200, 200, 200, 200 of the 200 input depths (0.2, 0.5, 2, 3) and
     at 199 for 0.12, whose depth-1 input tile maps across 0.1.
     sqrt(1/3) emits n - 1 at 200 of 200; sqrt(1/7) n - 1 or n at 200
     of 200. Not predicted: at how many it is n. (A key of 0.12's
     first three depths was cut for the hand rows that hold them, and
     the two points' third digits, 577 and 377, entered by hand.)
  F5 chain. The divisibility holds at 51, 78 and 93 of the 165, 165
     and 812 cells; the one-step test agrees at all 1142. The full
     scan runs at 66, 66 and 406 cells, finds no witness at 10, 17
     and 25, agrees at all 538, its 486 witnesses re-read, its passes
     comparing 7300, 21456 and 29526 inputs. By the divisibility the
     primorial chain has a lookahead for floor(n/3) at depth 1 alone,
     for floor(n/5) at 1 and 2, for floor(n/4) at none.
  F6 poly. The divisibility holds at 6 and 20 of the 84 and 84 cells;
     the brute agrees at all 168.
  F7 classes. The closed forms at 40 of 40 depths for each of the
     four divisors, by both tests. The factorial chain's largest least
     c over t = 1..40 is 2, 3, 4, 5, 3, 7 at m = 2..7; at m = 2 it
     reads 2, 1, 2, 1, 2, 1 at t = 1..6.

FINDINGS (copied from the printed output).
  (1) The fourteen control lines pass, 92 cases by hand.
  (2) F1 holds. At trailing base 10, depths 1 to 3, the least c is 0
      for 7n, 1 for floor(n/2), 2 for floor(n/4) and none to 3 for
      floor(n/3); the witnesses are (0, 10^(t+c)) at every failing c,
      21 of 21 re-read; the passes compare 10^t, 10^(t+1) and 10^(t+2)
      inputs.
  (3) F3 holds. At the 1/x-adic place the 40 cells hold 8184 keys and
      no cell has a key with two outputs. The integer 3X has 0, 1, 3,
      5, 11, 21, 43, 85, 171, 341, 341, 0 keys with two outputs at j =
      1..12: one or more at each of j = 2..11.
  (4) F4 holds. The images 0.2, 0.5, 2, 3, 0.12 are endpoints of depth
      1, 1, 0, 0, 2 and the committed depth is one less at 200, 200,
      200, 200 and 199 of the input depths 1..200 (0.12 reads 0 at n
      = 1). sqrt(1/3) commits n - 1 at 200 of 200. sqrt(1/7) commits
      n - 1 at 143 input depths and n at 57.
  (5) F2 holds. c_min(D, t) = 0, 1, ..., 9 at t = 1..10; the 45
      witnesses are the predicted pairs, 25 of them (0, 2^(t+c)) and
      20 (0, 2^(t+c+1)), 45 of 45 re-read; the passes compare 2, 8,
      ..., 524288 inputs.
  (6) F5 holds. m M_t | M_(t+c) at 51 of 165 cells at base 10, 78 of
      165 at base 12 and 93 of 812 on the primorial chain, and the
      one-step test agrees at all 1142. The full scan, at the 66, 66
      and 406 cells with M_(t+c) <= 2310, finds no witness at 10, 17
      and 25 and a witness at the other 56, 49 and 381, each re-read,
      agreeing with the divisibility at all 538; its passes compare
      7300, 21456 and 29526 inputs. On the primorial chain, by the
      divisibility, floor(n/3) has a lookahead at depth 1 alone,
      floor(n/5) at depths 1 and 2 and floor(n/4) at none, depths 1
      to 5.
  (7) F6 holds. Over F_2[x] the divisibility holds at 6 of 84 cells
      at base x and 20 of 84 at base x (x + 1); the brute agrees at
      all 168, its 78 and 64 witnesses re-read.
  (8) F7 holds. On the sparse chain the least c is the closed form at
      40 of 40 depths for each of floor(n/2), floor(n/3), floor(n/4)
      and floor(n/5), by the divisibility and by the one-step test:
      1, 2, 1, 4, 3, 2, 1, 8, 7, 6 and 3, 6, 5, 12, 11, 10, 9, 24, 23,
      22 at t = 1..10 for 2 and 4, largest 32, 2 and 96 over t = 1..40
      for 2, 3 and 4, and no c <= 200 for 5 at any of the 40 depths.
      On the factorial chain the largest least c over t = 1..40 is 2,
      3, 4, 5, 3, 7 at m = 2..7, at most m, and 2, 1, 2, 1, 2, 1 at m
      = 2, t = 1..6.
  What the record does not read: a pass of the full scan past its hand
  period; the full scan at M_(t+c) > 2310; any integer divisor chain
  for division but the five named (base 2 carries the decimation, F_2[x]
  its two bases); the 3-adic and leading base 10 arms of (2), which are
  argued.
  And what no recorded value depends on: the multiplier 7 (every n ->
  mn reads at 0); a hand period at a cell where it divides the input
  modulus, or at floor(n/3), which never passes; the depths and
  lookaheads listed past the last that reads (the primorial's t <= 5
  and c <= 7, the factorial's c past 7); which of the two tests a
  closed-form count is taken from, the two agreeing at every depth,
  and which divisor's, the four counts being equal; the depths t = 1,
  2 over F_2[x], whose counts are the same at every depth; the modulus
  a decimation witness is re-read at, any divisor of 2^(t+c) holding
  the pair congruent; a degree bound or a loop's end above the
  proof's.

RUN RECORD. python reading.py: 39 of 39 checks, 1.4 s, peak commit
45.3 MB under a 512 MB guard. The form it replaces ran 19 checks in
2.5 s at 104 MB: its scans read four periods of the input modulus, a
sample where this one covers the pair's period; its wall arm read four
input depths (19, 59, 119, 199 at sqrt(1/3) and 19, 59, 119, 200 at
sqrt(1/7), inside this record's n - 1, and n - 1 or n); its division
arm ran the one-step test alone. Its first run had failed a control,
floor(n/3) "reading" at base 10 on a scan of n < 30000 that held one
input a tile, and its classes arm floor(n/4) on a lookahead ceiling of
80, under the 96 that depth 32 needs: hence this record's 200. Its
print of the primorial depths at m = 15 and 35 is dropped, and three
arguments it settled with no run are left to the proofs they belong
to: that a wall needs a non-redundant numeration of R, that a
decreasing map walls at every endpoint of a symmetric set, that a
middle empty at every fixed base is filled on a chain. Its arm on the
d-bonacci numerations is in bonacci.py. Entered from this engine's first
print, not predicted: the integer 3X's counts at j = 4..11, and
sqrt(1/7)'s 143 and 57. Changed after the predictions were frozen,
each by hand before the run that read it: the rows of floor(n/5) at
base 2, of the polynomial cell (x + 1, x, x^2 + x + 1), with the
brute's degree lowered from one past the proof's to the proof's, of
chain_c at c = 0 and at its last c, of the three maps' values and of
the refused division; y/u carried to y's own digits where it had one
more; three keys cut that another implies; and 1/7's distance from its
tile's ends, written 1.43 10^-n, a lower bound rounded up, found by a
reader of the draft. After single-token faults were run through it:
is_witness's rows at (3, 33) and (0, 3), where the first set's
non-congruent pair had equal values; the middle stage's two counts,
which a parity clause had made the same with or without the predicted
pair; the place stage's third count, a sum of zeros before; root and
the two growing points' third digits.
"""

import math
import sys
import time


# ----------------------------------------------------------- the scan
def scan(f, m_in, m_out, span):
    first = [f(n) % m_out for n in range(min(m_in, span))]
    compared = 0
    for n in range(m_in, span):
        compared += 1
        if f(n) % m_out != first[n % m_in]:
            return (n % m_in, n), compared
    return None, compared


def is_witness(f, pair, m_in, m_out):
    n0, n1 = pair
    return (n0 < n1 and (n1 - n0) % m_in == 0
            and (f(n1) - f(n0)) % m_out != 0)


def lookahead(f, mod, per, t, cmax):
    wits = []
    for c in range(cmax + 1):
        m_in, m_out = mod(t + c), mod(t)
        pair, compared = scan(f, m_in, m_out, 2 * math.lcm(per(t), m_in))
        if pair is None:
            return c, tuple(wits), compared
        wits.append(pair)
    return None, tuple(wits), 0


def base(b):
    return lambda t: b ** t


def floor_by(m):
    return lambda n: n // m


def decimate(n):
    out, t = 0, 0
    while n >> (2 * t):
        out |= ((n >> (2 * t)) & 1) << t
        t += 1
    return out


def decimation_witness(t, c):
    k = t + c
    return (0, 2 ** k) if k % 2 == 0 else (0, 2 ** (k + 1))


# ------------------------------------------------------------- F_2[x]
def pmul(a, b):
    r = 0
    while b:
        if b & 1:
            r ^= a
        a <<= 1
        b >>= 1
    return r


def pdivmod(a, b):
    if b == 0:
        raise ZeroDivisionError("division by the zero polynomial")
    q, db = 0, b.bit_length() - 1
    while a.bit_length() - 1 >= db:
        s = a.bit_length() - 1 - db
        q ^= 1 << s
        a ^= b << s
    return q, a


def refuses(f, *args):
    try:
        f(*args)
    except ZeroDivisionError:
        return True
    return False


def ppow(a, k):
    r = 1
    for _ in range(k):
        r = pmul(r, a)
    return r


# ---------------------------------------------------------- the place
def lead(Y, j):
    return Y >> (Y.bit_length() - j)


def conflicts(out, N, j):
    tops, bad = {}, set()
    for low in range(1 << (N - 1)):
        X = (1 << (N - 1)) | low
        key, top = X >> (N - j), lead(out(X), j)
        if tops.setdefault(key, top) != top:
            bad.add(key)
    return len(tops), len(bad)


def times(u):
    return lambda X: pmul(X, u)


def over(u):
    du = u.bit_length() - 1
    return lambda X: pdivmod(X << du, u)[0]


def triple(X):
    return 3 * X


# ----------------------------------------------------------- the wall
def root(num, den, n):
    return math.isqrt(num * 10 ** (2 * n) // den)


def emission(num, den, n):
    Y = root(num, den, n)
    lo, hi = Y * Y, (Y + 1) * (Y + 1)
    best = -2
    for t in range(-1, 2 * n + 1):
        w = 10 ** (2 * n - t)
        if hi <= (lo // w + 1) * w:
            best = t
        else:
            break
    return best


def vertex_depth(num, den):
    den //= math.gcd(num, den)
    twos = fives = 0
    while den % 2 == 0:
        den //= 2
        twos += 1
    while den % 5 == 0:
        den //= 5
        fives += 1
    return max(twos, fives) if den == 1 else None


# ---------------------------------------------------------- the chain
def primorial(t):
    ps, x, n = [], 1, 2
    while len(ps) < t:
        if all(n % p for p in ps):
            ps.append(n)
            x *= n
        n += 1
    return x


def criterion(m, N, M):
    return M % (m * N) == 0


def one_step(m, N, M):
    return all(((r + M) // m - r // m) % N == 0 for r in range(m))


def full(m, N, M):
    return scan(floor_by(m), M, N, 2 * math.lcm(m * N, M))


def chain_c(test, m, mod, t, cmax):
    for c in range(cmax + 1):
        if test(m, mod(t), mod(t + c)):
            return c
    return None


def poly_brute(m, N, M):
    D = (M.bit_length() - 1) + (m.bit_length() - 1) + 1
    first = {}
    for n in range(1 << D):
        key = pdivmod(n, M)[1]
        val = pdivmod(pdivmod(n, m)[0], N)[1]
        if first.setdefault(key, (val, n))[0] != val:
            return first[key][1], n
    return None


def is_poly_witness(pair, m, N, M):
    n0, n1 = pair
    return (pdivmod(n0 ^ n1, M)[1] == 0
            and pdivmod(pdivmod(n0, m)[0] ^ pdivmod(n1, m)[0], N)[1] != 0)


def table(radix, top):
    M = [1]
    for s in range(1, top + 1):
        M.append(M[-1] * radix(s))
    return M


def sparse_radix(s):
    return 2 if s & (s - 1) == 0 else 3


def factorial_radix(s):
    return s + 1


def form(m, t):
    if m == 2:
        return 2 ** t.bit_length() - t
    if m == 4:
        return 2 ** (t.bit_length() + 1) - t
    if m == 3:
        return 2 if t & (t + 1) == 0 else 1
    return None


# --------------------------------------------------------- the stages
def stage_lemma():
    ten = base(10)
    rows = {}
    for name, f, per in (
            ("7n", lambda n: 7 * n, ten),
            ("n//2", floor_by(2), lambda t: 2 * ten(t)),
            ("n//4", floor_by(4), lambda t: 4 * ten(t)),
            ("n//3", floor_by(3), lambda t: 3 * ten(t))):
        rows[name] = tuple((f, t) + lookahead(f, ten, per, t, 3)
                           for t in (1, 2, 3))
    names = ("7n", "n//2", "n//4", "n//3")
    wits = [(f, pair, ten(t + c), ten(t))
            for name in names for f, t, _, ws, _ in rows[name]
            for c, pair in enumerate(ws)]
    return {
        "trailing base 10, t = 1, 2, 3: the least c <= 3 of 7n, n//2, "
        "n//4, n//3":
            tuple(tuple(r[2] for r in rows[name]) for name in names),
        "n//2, n//4, n//3: the witnesses below it, c rising":
            tuple(tuple(r[3] for r in rows[name]) for name in names[1:]),
        "7n, n//2, n//4: inputs compared at the pass":
            tuple(tuple(r[4] for r in rows[name]) for name in names[:3]),
        "witnesses re-read by subtraction, of how many":
            (sum(1 for w in wits if is_witness(*w)), len(wits)),
    }


def stage_place():
    N = 12
    rows = [conflicts(out, N, j) for u in (0b11, 0b111)
            for out in (times(u), over(u)) for j in range(2, N)]
    carry = tuple(conflicts(triple, N, j)[1] for j in range(1, N + 1))
    return {
        "1/x-adic, y u and y/u at u = x + 1, x^2 + x + 1, j = 2..11 of "
        "12 digits: cells, keys, cells with no key of two outputs":
            (len(rows), sum(k for k, _ in rows),
             sum(1 for _, b in rows if b == 0)),
        "the integer 3X, j = 1..12: keys with two outputs": carry,
    }


VERTICES = (("sqrt(0.2)", 1, 5), ("sqrt(0.5)", 1, 2), ("sqrt(2)", 2, 1),
            ("sqrt(3)", 3, 1), ("sqrt(0.12)", 3, 25))
GROW = ((1, 3), (1, 7))
DEPTHS = range(1, 201)


def stage_wall():
    frozen, depths = [], []
    for _, num, den in VERTICES:
        e = vertex_depth(num, den)
        depths.append(e)
        frozen.append(sum(1 for n in DEPTHS
                          if emission(num, den, n) == e - 1))
    third, seventh = ([emission(num, den, n) - n for n in DEPTHS]
                      for num, den in GROW)
    return {
        "y^2 at sqrt of 0.2, 0.5, 2, 3, 0.12: the image's depth as an "
        "endpoint": tuple(depths),
        "the same five: input depths n = 1..200 emitting one less than "
        "it, then of how many": tuple(frozen) + (len(DEPTHS),),
        "sqrt(1/3), sqrt(1/7): floor(1000 y)":
            tuple(root(num, den, 3) for num, den in GROW),
        "sqrt(1/3): input depths n = 1..200 emitting n - 1, of how many":
            (third.count(-1), len(third)),
        "sqrt(1/7): those emitting n - 1, those emitting n, of how many":
            (seventh.count(-1), seventh.count(0), len(seventh)),
    }


def stage_middle():
    two = base(2)
    rows = tuple(lookahead(decimate, two, lambda t: 2 ** (2 * t - 1), t, 10)
                 for t in range(1, 11))
    wits = [(t, c, pair) for t, (_, ws, _) in enumerate(rows, 1)
            for c, pair in enumerate(ws)]
    return {
        "c_min(D, t), t = 1..10": tuple(r[0] for r in rows),
        "witnesses that are the predicted pair, those that are (0, "
        "2^(t+c)), of how many": (
            sum(1 for t, c, pair in wits
                if pair == decimation_witness(t, c)),
            sum(1 for t, c, pair in wits if pair == (0, two(t + c))),
            len(wits)),
        "witnesses re-read by subtraction, of how many": (
            sum(1 for t, c, pair in wits
                if is_witness(decimate, pair, two(t + c), two(t))),
            len(wits)),
        "inputs compared at the pass, t = 1..10":
            tuple(r[2] for r in rows),
    }


def chain_row(mod, ms, ts, cs, cap):
    cells = yes = step = 0
    fcells = fyes = fagree = reread = compared = 0
    for m in ms:
        for t in ts:
            for c in cs:
                N, M = mod(t), mod(t + c)
                crit = criterion(m, N, M)
                cells += 1
                yes += crit
                step += one_step(m, N, M) == crit
                if M <= cap:
                    pair, count = full(m, N, M)
                    fcells += 1
                    fagree += (pair is None) == crit
                    if pair is None:
                        fyes += 1
                        compared += count
                    else:
                        reread += is_witness(floor_by(m), pair, M, N)
    return (cells, yes, step), (fcells, fyes, fagree, reread, compared)


def stage_chain():
    rows = (chain_row(base(10), range(2, 13), (1, 2, 3), range(5), 2310),
            chain_row(base(12), range(2, 13), (1, 2, 3), range(5), 2310),
            chain_row(primorial, range(2, 31), (1, 2, 3, 4), range(7),
                      2310))
    return {
        "base 10, base 12, primorial: cells, those with m M_t | "
        "M_(t+c), those where the one-step test agrees":
            tuple(r[0] for r in rows),
        "the same chains at M_(t+c) <= 2310: full scans, those with no "
        "witness, those agreeing with the divisibility, witnesses "
        "re-read, inputs compared at the passes":
            tuple(r[1] for r in rows),
        "primorial, t = 1..5: the depths with m M_t | M_(t+c) at some "
        "c <= 7, m = 3, 5, 4":
            tuple(tuple(t for t in range(1, 6)
                        if chain_c(criterion, m, primorial, t, 7)
                        is not None) for m in (3, 5, 4)),
    }


def poly_row(g):
    cells = yes = agree = reread = 0
    for m in range(2, 16):
        for t in (1, 2):
            for c in (0, 1, 2):
                N, M = ppow(g, t), ppow(g, t + c)
                crit = pdivmod(M, pmul(m, N))[1] == 0
                pair = poly_brute(m, N, M)
                cells += 1
                yes += crit
                agree += (pair is None) == crit
                if pair is not None:
                    reread += is_poly_witness(pair, m, N, M)
    return cells, yes, agree, reread


def stage_poly():
    return {
        "F_2[x] at bases x and x (x + 1): cells, those with m M_t | "
        "M_(t+c), those where the brute agrees, witnesses re-read":
            (poly_row(0b10), poly_row(0b110)),
    }


def stage_classes():
    T = range(1, 41)
    sparse = table(sparse_radix, 240).__getitem__
    by = {m: (tuple(chain_c(criterion, m, sparse, t, 200) for t in T),
              tuple(chain_c(one_step, m, sparse, t, 200) for t in T))
          for m in (2, 3, 4, 5)}
    fact = table(factorial_radix, 60).__getitem__
    rows = {m: tuple(chain_c(criterion, m, fact, t, 10) for t in T)
            for m in range(2, 8)}
    return {
        "the sparse chain, t = 1..40, c <= 200, n//2, n//3, n//4, "
        "n//5: depths at the closed form (for 5, no c) by the "
        "divisibility, by the one-step test, of how many":
            tuple((sum(1 for t, c in zip(T, by[m][0], strict=True)
                       if c == form(m, t)),
                   sum(1 for t, c in zip(T, by[m][1], strict=True)
                       if c == form(m, t)), len(T)) for m in (2, 3, 4, 5)),
        "n//2 and n//4: the least c at t = 1..10":
            (by[2][0][:10], by[4][0][:10]),
        "n//2, n//3, n//4: the largest least c over t = 1..40":
            tuple(max(by[m][0]) for m in (2, 3, 4)),
        "the factorial chain, t = 1..40, m = 2..7: the largest least c":
            tuple(max(rows[m]) for m in range(2, 8)),
        "the factorial chain, m = 2: the least c at t = 1..6":
            rows[2][:6],
    }


RECORD = {
    "lemma": {
        "trailing base 10, t = 1, 2, 3: the least c <= 3 of 7n, n//2, "
        "n//4, n//3": (
            (0, 0, 0), (1, 1, 1), (2, 2, 2), (None, None, None)),
        "n//2, n//4, n//3: the witnesses below it, c rising": (
            (((0, 10),), ((0, 100),), ((0, 1000),)),
            (((0, 10), (0, 100)), ((0, 100), (0, 1000)),
             ((0, 1000), (0, 10000))),
            (((0, 10), (0, 100), (0, 1000), (0, 10000)),
             ((0, 100), (0, 1000), (0, 10000), (0, 100000)),
             ((0, 1000), (0, 10000), (0, 100000), (0, 1000000)))),
        "7n, n//2, n//4: inputs compared at the pass": (
            (10, 100, 1000), (100, 1000, 10000), (1000, 10000, 100000)),
        "witnesses re-read by subtraction, of how many": (21, 21),
    },
    "place": {
        "1/x-adic, y u and y/u at u = x + 1, x^2 + x + 1, j = 2..11 of "
        "12 digits: cells, keys, cells with no key of two outputs":
            (40, 8184, 40),
        "the integer 3X, j = 1..12: keys with two outputs": (
            0, 1, 3, 5, 11, 21, 43, 85, 171, 341, 341, 0),
    },
    "wall": {
        "y^2 at sqrt of 0.2, 0.5, 2, 3, 0.12: the image's depth as an "
        "endpoint": (1, 1, 0, 0, 2),
        "the same five: input depths n = 1..200 emitting one less than "
        "it, then of how many": (200, 200, 200, 200, 199, 200),
        "sqrt(1/3), sqrt(1/7): floor(1000 y)": (577, 377),
        "sqrt(1/3): input depths n = 1..200 emitting n - 1, of how many":
            (200, 200),
        "sqrt(1/7): those emitting n - 1, those emitting n, of how many":
            (143, 57, 200),
    },
    "middle": {
        "c_min(D, t), t = 1..10": (0, 1, 2, 3, 4, 5, 6, 7, 8, 9),
        "witnesses that are the predicted pair, those that are (0, "
        "2^(t+c)), of how many": (45, 25, 45),
        "witnesses re-read by subtraction, of how many": (45, 45),
        "inputs compared at the pass, t = 1..10": (
            2, 8, 32, 128, 512, 2048, 8192, 32768, 131072, 524288),
    },
    "chain": {
        "base 10, base 12, primorial: cells, those with m M_t | "
        "M_(t+c), those where the one-step test agrees": (
            (165, 51, 165), (165, 78, 165), (812, 93, 812)),
        "the same chains at M_(t+c) <= 2310: full scans, those with no "
        "witness, those agreeing with the divisibility, witnesses "
        "re-read, inputs compared at the passes": (
            (66, 10, 66, 56, 7300), (66, 17, 66, 49, 21456),
            (406, 25, 406, 381, 29526)),
        "primorial, t = 1..5: the depths with m M_t | M_(t+c) at some "
        "c <= 7, m = 3, 5, 4": ((1,), (1, 2), ()),
    },
    "poly": {
        "F_2[x] at bases x and x (x + 1): cells, those with m M_t | "
        "M_(t+c), those where the brute agrees, witnesses re-read": (
            (84, 6, 84, 78), (84, 20, 84, 64)),
    },
    "classes": {
        "the sparse chain, t = 1..40, c <= 200, n//2, n//3, n//4, "
        "n//5: depths at the closed form (for 5, no c) by the "
        "divisibility, by the one-step test, of how many":
            ((40, 40, 40),) * 4,
        "n//2 and n//4: the least c at t = 1..10": (
            (1, 2, 1, 4, 3, 2, 1, 8, 7, 6),
            (3, 6, 5, 12, 11, 10, 9, 24, 23, 22)),
        "n//2, n//3, n//4: the largest least c over t = 1..40":
            (32, 2, 96),
        "the factorial chain, t = 1..40, m = 2..7: the largest least c":
            (2, 3, 4, 5, 3, 7),
        "the factorial chain, m = 2: the least c at t = 1..6":
            (2, 1, 2, 1, 2, 1),
    },
}

CONTROL_LINES = 14
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")
    half, third = floor_by(2), floor_by(3)
    check_hand("scan on three small spans and one of a single period", [
        (scan(half, 2, 2, 8), ((0, 2), 1)),
        (scan(half, 4, 2, 8), (None, 4)),
        (scan(third, 3, 2, 6), ((0, 3), 1)),
        (scan(half, 4, 2, 4), (None, 0))])
    check_hand("is_witness on one witness and four that are not", [
        (is_witness(third, (0, 10), 10, 10), True),
        (is_witness(third, (0, 30), 10, 10), False),
        (is_witness(third, (3, 33), 10, 10), False),
        (is_witness(third, (0, 3), 10, 10), False),
        (is_witness(third, (10, 0), 10, 10), False)])
    ten = base(10)
    check_hand("lookahead at base 10, depth 1, and of n//5 at base 2", [
        (lookahead(lambda n: 7 * n, ten, ten, 1, 3), (0, (), 10)),
        (lookahead(half, ten, lambda t: 2 * ten(t), 1, 3),
         (1, ((0, 10),), 100)),
        (lookahead(third, ten, lambda t: 3 * ten(t), 1, 1),
         (None, ((0, 10), (0, 100)), 0)),
        (lookahead(floor_by(5), base(2), lambda t: 5 * 2 ** t, 1, 1),
         (None, ((1, 5), (1, 5)), 0))])
    check_hand("decimate on four inputs, its witness at three (t, c)", [
        (decimate(0b1011), 1), (decimate(0b10101), 7),
        (decimate(0b1010), 0), (decimate(0b110), 2),
        (decimation_witness(2, 0), (0, 4)),
        (decimation_witness(3, 0), (0, 16)),
        (decimation_witness(5, 3), (0, 256))])
    check_hand("pmul, pdivmod and ppow over F_2", [
        (pmul(0b11, 0b111), 0b1001), (pdivmod(0b1001, 0b11), (0b111, 0)),
        (pdivmod(0b1000, 0b11), (0b111, 1)),
        (pdivmod(0b101, 0b110), (1, 0b11)),
        (pdivmod(0b10000, 0b11), (0b1111, 1)),
        (refuses(pdivmod, 1, 0), True), (refuses(pdivmod, 1, 1), False),
        (ppow(0b110, 2), 0b10100), (ppow(0b10, 3), 0b1000)])
    check_hand("lead, the three maps, and conflicts at 3 and 4 digits", [
        (lead(0b110101, 2), 0b11), (lead(0b110101, 4), 0b1101),
        (times(0b11)(0b110), 0b1010), (over(0b11)(0b111), 0b101),
        (over(0b111)(0b100), 0b110), (triple(5), 15),
        (conflicts(times(0b11), 3, 2), (2, 0)),
        (conflicts(over(0b11), 3, 2), (2, 0)),
        (conflicts(triple, 3, 2), (2, 0)),
        (conflicts(triple, 4, 2), (2, 1))])
    check_hand("conflicts of the integer 3X at 12 digits, j = 1, 2, 3, 12", [
        (conflicts(triple, 12, 1), (1, 0)),
        (conflicts(triple, 12, 2), (2, 1)),
        (conflicts(triple, 12, 3), (4, 3)),
        (conflicts(triple, 12, 12), (2048, 0))])
    check_hand("root at four, emission at thirteen (num, den, n)", [
        (root(2, 1, 0), 1), (root(9, 10, 1), 9), (root(1, 3, 2), 57),
        (root(1, 7, 3), 377),
        (emission(2, 1, 0), -1), (emission(50, 1, 0), -2),
        (emission(9, 10, 1), 0), (emission(1, 200, 1), 2),
        (emission(1, 5, 1), 0), (emission(1, 2, 1), 0),
        (emission(3, 25, 1), 0), (emission(3, 25, 2), 1),
        (emission(1, 3, 1), 0), (emission(1, 3, 2), 1),
        (emission(1, 7, 1), 0), (emission(1, 7, 2), 1),
        (emission(1, 7, 3), 3)])
    check_hand("vertex_depth at nine fractions", [
        (vertex_depth(2, 1), 0), (vertex_depth(1, 5), 1),
        (vertex_depth(1, 2), 1), (vertex_depth(3, 25), 2),
        (vertex_depth(1, 8), 3), (vertex_depth(5, 10), 1),
        (vertex_depth(6, 4), 1), (vertex_depth(1, 3), None),
        (vertex_depth(1, 7), None)])
    cells = ((4, 10, 100), (4, 10, 1000), (3, 2, 6), (3, 6, 30),
             (5, 3, 3), (3, 2, 7), (2, 2, 5))
    verdicts = (False, True, True, False, False, False, False)
    check_hand("criterion and one_step at seven cells", [
        (tuple(criterion(*cell) for cell in cells), verdicts),
        (tuple(one_step(*cell) for cell in cells), verdicts)])
    check_hand("full at three cells", [
        (full(4, 10, 100), ((0, 100), 1)),
        (full(4, 10, 1000), (None, 1000)),
        (full(3, 2, 7), ((2, 9), 3))])
    check_hand("primorial, and chain_c on it at seven (m, t, cmax)", [
        (tuple(primorial(t) for t in range(1, 6)), (2, 6, 30, 210, 2310)),
        (chain_c(criterion, 3, primorial, 1, 7), 1),
        (chain_c(criterion, 3, primorial, 2, 7), None),
        (chain_c(criterion, 5, primorial, 2, 7), 1),
        (chain_c(criterion, 4, primorial, 1, 7), None),
        (chain_c(criterion, 1, primorial, 3, 7), 0),
        (chain_c(criterion, 3, primorial, 1, 1), 1),
        (chain_c(criterion, 3, primorial, 1, 0), None)])
    check_hand("poly_brute at four cells, a witness re-read", [
        (poly_brute(0b10, 0b10, 0b10), (0, 2)),
        (poly_brute(0b10, 0b10, 0b100), None),
        (poly_brute(0b11, 0b10, 0b100), (0, 4)),
        (poly_brute(0b11, 0b10, 0b111), (1, 8)),
        (is_poly_witness((0, 4), 0b11, 0b10, 0b100), True),
        (is_poly_witness((0, 2), 0b11, 0b10, 0b100), False),
        (is_poly_witness((0, 8), 0b10, 0b10, 0b100), False)])
    check_hand("the two chains' tables and form at nine (m, t)", [
        (tuple(table(sparse_radix, 5)), (1, 2, 4, 12, 24, 72)),
        (tuple(table(factorial_radix, 3)), (1, 2, 6, 24)),
        (tuple(form(m, t) for m, t in ((2, 1), (2, 4), (2, 5), (4, 1),
                                       (4, 4), (3, 1), (3, 2), (3, 7),
                                       (5, 9))),
         (1, 4, 3, 3, 12, 2, 1, 2, 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("lemma", "LEMMA: trailing base 10, depths 1 to 3",
                  stage_lemma)
    section_stage("place", "PLACE: the 1/x-adic arm and the integer 3X",
                  stage_place)
    section_stage("wall", "WALL: y -> y^2 at leading base 10, input "
                  "depths 1..200", stage_wall)
    section_stage("middle", "MIDDLE: the decimation at base 2",
                  stage_middle)
    section_stage("chain", "CHAIN: the division criterion over Z",
                  stage_chain)
    section_stage("poly", "POLY: the division criterion over F_2[x]",
                  stage_poly)
    section_stage("classes", "CLASSES: one sparse chain and the "
                  "factorial chain", stage_classes)
    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()