suffixwalk.py

"""suffixwalk.py -- the shortest filter with taps -1, 0 and 1 that
annihilates every polynomial signal below a given degree: the least
degree d_1(J) of a polynomial of height 1 vanishing to order J at 1,
with every polynomial that attains it, by a walk down the top
coefficients; and the same with integer taps of size at most k, the
least degree d_k(J) at height k.

USE. In Python, from the folder holding suffixwalk.py and flatten.py.
least_degree(J) returns d_1(J) and every vector of that degree with
coefficients -1, 0, 1 whose polynomial vanishes to order J at 1,
lowest coefficient first, top coefficient 1 (each stands for itself
and its negative). Read as a filter, such a vector is d_1(J) + 1 taps
that annihilate every polynomial signal of degree below J, and no
shorter set of such taps does. walk(J, W) lists every such vector of
exactly W taps, with a nonzero lowest tap, and its two counts:

    >>> from suffixwalk import least_degree, walk
    >>> least_degree(3)
    (6, [[-1, 1, 1, 0, -1, -1, 1]])
    >>> d, taps = least_degree(6)
    >>> d, len(taps)
    (22, 1)
    >>> [sum(c * i**j for i, c in enumerate(taps[0])) for j in range(7)]
    [0, 0, 0, 0, 0, 0, 604800]
    >>> len(least_degree(8)[1])                # two shortest filters
    2
    >>> len(walk(3, 9)[0])                     # 9 taps, order 3
    2
    >>> least_degree(0) is None                # refused: no order
    True
    >>> least_degree(3, 2)                     # taps -2..2
    (4, [[-1, 2, 0, -2, 1]])
    >>> least_degree(10, 9)[0]                 # taps -9..9, order 10
    22

least_degree(J, k) and walk(J, W, k) are the same with integer taps
-k..k, the top one positive.

A call's cost grows with the order: under a second to 11, 2 s at 12,
40 s at 13, 4 s at 14, 85 s at 15, some five minutes at 16, and
hours at 17, priced here and decided by walkc.py, this walk with its
node compiled (FINDINGS). At height k the cost is in RUN
RECORD AT HEIGHT k: 4 s at least_degree(12, 2), two to eight minutes
at five more of the dial's capped cells, half an hour at
least_degree(16, 6). walk returns None where k times the taps passes
5000, where its float argument is not made, and least_degree with it.

QUESTION. d_1(J) is the least degree of a nonzero multiple of
(x - 1)^J of height 1. The lattice walk of flatten.py decides it to
depth 11 and is capped from depth 12; the OEIS entry A059753 gives
93, 112 and 120 at depths 12 to 14 and stops there. Two things are
asked. (a) Whether a
walk built for height 1, three choices a coefficient from the top
down, each suffix killed once no real prefix inside the cube can
flatten it, decides depths 12 to 14 and prices depth 15. (b) At each
depth it decides, the whole list of extremal vectors (height 1,
flattened to J, degree exactly d_1(J)), each read for whether it is a
pure product, a product of factors x^g - 1: the source of the column
(Borwein and Mossinghoff, Experiment. Math. 9 (2000) 425-433) asks
for a depth where one is not.

THE HAND ATTACK, on paper before the engine. Width W, indices
0..W-1, depth J, a(t) the column (C(t, j))_{j<J}, so c is flattened
to J exactly when sum_t c_t a(t) = 0.
  (1) THE ENDS. A vector of least degree among those of height 1
      flattened to J has c_0 != 0 (else divide by x), and its top
      coefficient is 1 up to sign. So "nothing below degree d" is: at
      every width W <= d, no vector with c_(W-1) = 1 and c_0 != 0.
  (2) THE CYLINDER. Fix the suffix c_t, t >= m, with moment vector
      mu = sum_(t>=m) c_t a(t). A prefix y on [0, m) completes it
      exactly when sum_(t<m) y_t a(t) = -mu, and a prefix of height
      <= 1 has |y|^2 <= m. The least |y|^2 over real prefixes is
      E_m = mu^T G_m^(-1) mu, G_m = sum_(t<m) a(t) a(t)^T (m >= J, so
      G_m is invertible). So E_m > m kills the suffix (property).
  (3) ONE SQUARE A LEVEL. G_(m+1) = G_m + a(m) a(m)^T, so with
      kappa = a(m)^T G_m^(-1) a(m), mu' the moments of the suffix above
      m and S = a(m)^T G_m^(-1) mu',
        E_m = E_(m+1) + (S + c_m (1 + kappa))^2 / (1 + kappa) - c_m^2
      (Sherman-Morrison). S is one linear form in the J integers mu',
      its coefficients g_m = G_m^(-1) a(m) rational and fixed by the
      level; the three children share it.
  (4) THE BOTTOM. At m = J the matrix (a(t))_(t<J) is unitriangular,
      so the prefix is the one integer vector y with
      sum_(t<J) y_t a(t) = -mu; the suffix is a vector exactly when y
      has height <= 1, and y_0 != 0 is read there.
  (5) THE FLOATS. mu and the numerator N of S + c_m (1 + kappa) over
      the level's common denominator Den are exact integers, and
      A = (1 + kappa) Den. The square enters E as the float
      (N / Den)(N / A): two quotients of integers, each the correctly
      rounded double, and their product, the true increment times a
      factor within 3.1 u of 1, u = 2^-53. An increment above 4 W
      kills at once: the
      true one is above W, and E_(m+1) >= 0 gives
      E_m >= increment - 1 > m. A kill is wrong only on a suffix some
      vector completes, and every suffix above such a one on its path
      is completed by the same vector, so every true E on the path is
      at most its level, below W. By induction down that path every
      float E is under W + 1 and every increment under W + 1, so a
      level's error (the increment's and two additions') is under
      10 u W and the path's under 10 u W^2: 5e-11 at W = 200, 2.8e-8
      at W = 5000, past which walk refuses. The early kill apart, a
      suffix dies only at a
      float E above its level by the slack 1e-6, so a float can keep
      a dead suffix, never kill a live one. The top level's E is
      never tested and needs no test: a top above its level is dead
      with every suffix below it, since a level lowers E by at most
      1. A vector the walk returns is exact, the bottom an integer
      solve; the run's checks re-read each by J exact sums.

PREDICTIONS, before the engine.
  P1 At depths J = 1..11 the walk finds nothing at any width
     W <= d_1(J) and a vector at width d_1(J) + 1, for d_1 = 1, 3, 6,
     11, 15, 22, 30, 41, 48, 61, 69, the lattice's own column.
  P2 The same at depths 12, 13, 14 for 93, 112, 120, another's terms,
     as far as the walk's cost allows.
  P3 Every extremal vector at depths 1..10 is a pure product (the
     source's finding, a TRANSPLANT until the walk lists them); at
     depths 11..14, unknown to this record, predicted the same.
  P4 The level counts rise from the top and die before the suffix
     reaches half the width: a TRANSPLANT from a Gaussian count of
     suffixes inside the cylinder, to be read off the counts.
  P5 d_1(15) = 141: nothing at any width W <= 141.

KILLS, as prints.
  K1 (a bug) at a depth J <= 11, a vector at a width W <= d_1(J), or
     none at width d_1(J) + 1.
  K2 (a finding, or the other record's fault) the same at depths 12
     to 14 against 93, 112, 120.
  K3 (a finding) an extremal vector that is no pure product: the
     count "extremal, not pure" above 0 at any depth.
  K4 (a finding) a vector at a width W <= 141 at depth 15: the pure
     law broken in the column k = 1.
  KP THE PRICE. Depth 15's nodes are estimated from the growth of the
     decided depths' node counts, read against their widths. At the
     measured rate: within 12 core-hours it runs at once, four
     processes at most, sharded and resumable; within 1000 core-hours
     it is a run laid out in stages, checkpointed; past that the
     price is the front's reopen clause.

CONTROLS, named before the run.
  C1 the known vector's path. At each depth the walk's own first
     vector at width d_1(J) + 1 is found only if no level's cylinder
     kills its suffix; at depth 15, before any long run, the least
     pure product of degree 141 is walked down its own path at width
     142 and the largest E_m / m along it printed: above 1 the bound
     is wrong.
  C2 the prune fires. The same path with one coefficient flipped must
     die, at a level or at the bottom; a flipped path that survives
     says the filter passes anything.
  C3 the walk against a brute count. At widths W <= 13 every vector
     of height 1 flattened to J with c_(W-1) = 1 and c_0 != 0 is
     counted by exhaustion over the 3^(W-2) middles and by the walk:
     the two counts equal at every (W, J).

CHANGED AFTER THE FREEZE, before any verdict was read. C4 added: the
walk's float E_m along the first extremal vector's path against
mu^T G_m^(-1) mu in exact rationals, G_m summed and solved apart from
the walk's own levels; and, for a flipped path a level kills, the exact
E_m at that level against m. No frozen line moved. Depth 16 was run
with no prediction or kill frozen for it: its line is its own. Two
controls first ran narrower than frozen and were run as frozen after
the verdicts: C3 at W <= 11, and C1 on the walk's own first vector, a
path the walk cannot kill, in place of flatten.py's least pure
product. After the findings: C2 left the run, as F6 says; every check
now reaches the exit code against the record below; the bare run
stops at depth 14, and "python suffixwalk.py 16" runs the whole
record. KP's two phrases for when a long run is made were reworded,
its thresholds as frozen. Step (5) of the hand attack was rewritten
after the findings as the proof it is now, walk refusing past 5000
taps with it, and the question names its two records.

FINDINGS.
  F1 P1 and P2 hold, K1 and K2 silent: at depths 1..14 the first width
     with a vector is d_1(J) + 1 at the column's value, 14 of 14.
  F2 P5 holds, K4 silent: d_1(15) = 141. And d_1(16) = 159. Each is
     the least pure degree flatten.py's walk gives at that part count.
  F3 P3 holds, K3 silent: 19 extremal vectors over depths 1..16,
     counted up to sign, one
     a depth but 2 at depth 8 and 3 at depth 13, every one a pure
     product. At 15 the parts are (1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 13,
     14, 16, 17, 23); at 16, (1, 2, 3, 4, 5, 7, 7, 9, 10, 11, 12, 13,
     16, 17, 19, 23).
  F4 P4 fails as worded: the counts peak near a third of the width
     (suffix length 51 of 160 at depth 16) but die past half of it: at
     depth 16, width 156, three suffixes of length 84 are alive and
     none of length 88 (a print of walk(16, 156)'s kept, outside the
     bare run).
  F5 KP: depth 15 cost 146387613 children tried over all its widths,
     82.4 s on one process; depth 16, 496443528 and 305.2 s. The one
     estimate made before a run was depth 16's, by hand from the
     counts at widths 152 to 156: about 520 million children and
     350 s.
  F6 The controls, C3 and C1 as frozen.
     C3: 78 cells, W = 2..13, 71838 vectors, no cell disagrees. C1:
     the least pure product, built from flatten.py's parts, survives
     its own path at each of the 16 depths, the largest E_m / m
     1.0000 (depths 1 to 3), 0.6245 at depth 15 and 0.7500 at depth
     16. C2 read nothing and is no longer run: the bottom is exact
     and rejects a flipped path whether or not a level kills it, and
     its flips planted no -1 and none below index J. C4: the float
     E_m within 8.1e-15 of the exact one at every level of each
     depth's first vector's path; of the flipped paths it samples,
     each one a level kills has the exact E_m > m (13 of 13 at depth
     16).
  DEPTH 17, PRICED HERE AND NOT RUN. walk(17, W) tried 1232355, 3636642
     and 9955482 children at W = 166, 168, 170 and found no vector at
     the even widths 150 to 170 (a print outside the bare run): 2.95
     and 2.74 times per two widths, at some 1.6 million children a
     second. The least pure product of height 1 with 17 parts has
     degree 185 (flatten.py's least_pure_degree), so deciding depth
     17 means every width to 185: at that growth some 6e10 children,
     about ten hours of one process. The price read high, the growth
     falling with the width: walkc.py tries 20788555758 children over
     the widths to 185, the three counts above among them to the
     unit, and decides d_1(17) = 185 and d_1(18) = 207.

RUN RECORD. python suffixwalk.py 16, before the checks were written:
434 s, one process. The last five depths' lines, abridged:
  J = 12: d_1 =  93, extremal 1, tried 3588285, 1.6 s
  J = 13: d_1 = 112, extremal 3, tried 77545929, 38.4 s
  J = 14: d_1 = 120, extremal 1, tried 7668786, 3.9 s
  J = 15: d_1 = 141, extremal 1, tried 146387613, 82.4 s
  J = 16: d_1 = 159, extremal 1, tried 496443528, 305.2 s
  depths 1..16: 14 of 14 at the column's value where it has one;
  extremal vectors 19, not pure 0; C3 held
The controls as frozen, 13 s: C3 78 cells, 71838 vectors in all, 0
cells disagree; C1 the least pure products' paths, 16 of 16 alive.
With the checks, python suffixwalk.py 16: "depths 1..16: extremal
vectors 19, not pure 0; 49 of 49 checks, 449 s", depth 16's line
"d_1 = 159, tried 496443528, extremal 1, not pure 0, peak 2596446 at
suffix length 51 of 160, 309.9 s"; the bare run, "depths 1..14:
extremal vectors 17, not pure 0; 45 of 45 checks, 48 s".

AT HEIGHT k. The walk with 2k + 1 choices a coefficient, asked of the
cells of the inverse dial that flatten.py's lattice walk left capped.
Its ask was frozen with the engine a script of its own, since merged
into walk here (k = 1 the default); the lines below are that ask's,
their labels given an H.

QUESTION. d_k(J) is the least degree of a nonzero multiple of
(x - 1)^J of height at most k. flatten.py's lattice walk decides 115
cells of the dial at J <= 16, k <= 8, and its cap stops it at 13; the
walk above decides the five of them in the column k = 1. Eight are
left, each with the least pure degree as an upper bound only: (k, J,
least pure degree) = (2, 12, 65), (2, 14, 89), (2, 16, 118), (3, 13,
65), (3, 14, 73), (3, 15, 80), (6, 16, 71), (8, 16, 63). Two things
are asked. (a) Whether the same walk with 2k + 1 choices a coefficient
and the cylinder k^2 m decides them, or prices them. (b) Whether any
is a break: a vector of height at most k flattened to J of degree
below the least pure degree.

THE HAND ATTACK AT HEIGHT k: the five steps, each re-derived at
height k, not carried over.
  (H1) THE ENDS. A vector of least degree among those of height <= k
      flattened to J has c_0 != 0 (else divide by x) and, up to sign,
      a top coefficient in 1..k. So "nothing below degree d" is: at
      every width W <= d, no vector with c_(W-1) in 1..k and c_0 != 0.
      The top is no longer one value: the walk's root has k children.
  (H2) THE CYLINDER. A prefix on [0, m) of height <= k has
      |y|^2 <= k^2 m, so the suffix dies at E_m > k^2 m, E_m as at
      height 1 (the least |y|^2 over real prefixes completing it).
  (H3) ONE SQUARE A LEVEL. The identity
        E_m = E_(m+1) + (S + c_m (1 + kappa))^2 / (1 + kappa) - c_m^2
      is algebra in c_m and holds for any real c_m; the children are
      c_m = -k..k and the square subtracted is c_m^2, not 1. At the
      top E_(W-1) = c^2 kappa_(W-1) for the top coefficient c.
  (H4) THE BOTTOM. The prefix on [0, J) is the one integer vector y
      solving the unitriangular system; the suffix is a vector
      exactly when |y_t| <= k for every t, and y_0 != 0 is read there.
  (H5) THE FLOATS. (5) with k^2 beside every level. An increment
      above 4 k^2 W kills at once: the true one is above k^2 (W + 1),
      and E_(m+1) >= 0 with c_m^2 <= k^2 gives E_m > k^2 W. A kill is
      wrong only on a suffix some vector of height <= k completes, and
      on that vector's path every true E is at most k^2 times its
      level and every true increment, E_m - E_(m+1) + c_m^2, at most
      k^2 W. By induction down the path a level's error is under
      10 u k^2 W (3.1 u of the increment, and two additions, each u
      of a sum under 2 k^2 W; at the top, the two roundings of
      c^2 kappa), and the path's under 10 u k^2 W^2: 2.8e-8 at
      k W = 5000, past which walk refuses, against the slack 1e-6. A
      top above its level is dead with every suffix below it, since a
      level lowers E by at most k^2, so the top is never tested.
  TRANSPLANTS, to be read off the prints and not assumed: that the
  level counts peak near a third of the width and die a little past
  half of it (the height-1 walk's own counts); that the cost at a
  cell grows by a steady factor a width (1.68 at k = 1, J = 17); that
  the walk's edge over the lattice walk survives k > 1 at all: at
  height 1 the cube costs the suffix three values a coefficient where
  the ball allows more, and at height k the cube and the ball's
  section draw closer as k grows.

PREDICTIONS AT HEIGHT k, before the engine.
  HP1 At every cell the lattice walk decided where the walk's cost
     allows (a cap of 20 million children a width), the walk returns
     flatten.py's d_k(J): nothing at any width W <= d_k(J), a vector
     at width d_k(J) + 1.
  HP2 The dial's three breaks are among them and the walk sees each:
     d_9(10) = 22 under the pure degree 23, d_8(15) = 55 under 56,
     d_11(15) = 48 under 49; the vector it returns at the break's
     width is not required to be the recorded witness.
  HP3 At the six capped cells of k = 2, 3 and 6 the pure law holds:
     nothing at any width up to the least pure degree. The law held
     at 114 of the 115 cells decided, and no break is known below
     height 8.
  HP4 At (8, 16) no prediction: d_8(16) lies in 56..63 (nothing of
     height <= 8 flattened to 16 has degree below 56, flatten.py's
     break stage), and height 8 broke one depth up.
  HP5 The walk's reach falls as k grows: it decides the capped cells
     of k = 2 before those of k = 3, and (8, 16) last or not at all.

KILLS AT HEIGHT k, as prints.
  HK1 (a bug) "decided cells: the walk at flatten.py's d at N of M
     run": N < M, a cell where the walk finds a vector at a width
     W <= d_k(J) or none at width d_k(J) + 1, over the cells run under
     the cap, the three breaks counted among them.
  HK2 (a finding) "capped cells: (k, J): first vector at width W,
     least pure degree dp": W <= dp at any of the eight. The vector is
     printed and checked by exact division, its height and its
     flattening read apart from the walk.
  HK3 (the walk's edge is height 1's alone) "capped cells decided: 0
     of 8" with every one priced past ten minutes on one process.
  HKP THE PRICE. A cell's widths run upward from J + 1; a width whose
     children pass the cap stops the cell, and its price is read from
     the growth of the last three widths' counts to the least pure
     degree. Under ten minutes on one process the cell is run without
     the cap; past it the price is the cell's line.

CONTROLS AT HEIGHT k, named before the run.
  HC1 the walk against exhaustion. At k = 2, widths W <= 9, and k = 3,
     widths W <= 8, every vector of height <= k flattened to J with a
     top coefficient in 1..k and c_0 != 0 is counted by exhaustion
     over the middles and by the walk: equal at every (W, J).
  HC2 the positive control for HK2: the break d_9(10) = 22, the answer
     read from members.py's print and flatten.py's (d_8(15) = 55),
     never from a doc. The walk must print a vector at a width at or
     below the least pure degree there; a walk that cannot see a known
     break reads nothing at the capped cells. Read before any capped
     cell.
  HC3 the known vector's path. At each cell the least pure product of
     height <= k, built from flatten.py's parts, is walked down its
     own path at the width that holds it: a level that kills it says
     the bound is wrong at height k. At the three breaks the recorded
     witness of d_8(15), flatten.py's traded product, down its path.
  HC4 the float E against exact rationals along HC3's paths at k > 1,
     by suffixwalk.py's energy_exact: the gap printed, and required
     under 1e-9.
  HC5 the height-1 walk recovered: at k = 1 the engine returns
     suffixwalk.py's vectors and its count of children at depths 1 to
     11, so the four changed lines changed nothing else.

CHANGED AFTER THE FREEZE AT HEIGHT k. No frozen line moved but its
label. The cells were first rehearsed at a cap of 300000 children a
width, and a capped cell was run with no cap on that rehearsal's
price, which read low: the growth a width rises with the width
((8, 16) priced 4.11e8 children to width 63 and cost 913218223).
(8, 15), which HP1's cap stopped at width 54, was then run with no
cap, so HP2's third break is read outside HP1's cap. HC3 walks the
nine known vectors (the eight capped cells' least pure products and
the traded product of (8, 15)), not every cell's. Read after the
findings were first written: HP3 counts six capped cells at k = 2, 3
and 6 where there are seven; HK3's line is printed by no code, its
count HF7's by hand; the transplant's 1.68 reads 1.69 off its counts.
(6, 16) was first priced with a rate that charged the capped width's
seconds to the widths below it, 18 minutes; at the walk's own rate the
price was 9.3 minutes, under HKP's line, and the cell was run.
Then the engine was merged into walk. The refusal moved from
2.5e-15 k^2 W^2 > 1e-7 to k W > 5000, with (H5) rewritten as the proof
it is now (the frozen form bounded a level's error by 22.5 u k^2 W).
HC5 became the column's own record, one engine walking both. HK2's
line and HKP's are printed by no code now: a cell's run prints its
check line, its last width listed whole, and HF6 holds the two prices
read. The ten decided cells HP1's cap stopped are run with no cap
(the argument decided 0). HC2's cell is a check of the bare run's
controls, read before the dial's.

FINDINGS AT HEIGHT k.
  HF1 The controls held. HC1: at k = 2, W = 2..9, 36 cells and 73422
     vectors, at k = 3, W = 2..8, 28 cells and 173657 vectors, no cell
     disagrees. HC2: at the break (9, 10) the first vector is at width
     23, d = 22 under the least pure degree 23. HC3 and HC4: the nine
     known vectors alive down their paths, the largest E_m / (k^2 m)
     0.4917 (the traded product of (8, 15)), the float E within
     1.8e-13 of the exact one at worst. HC5: the first form differed
     from the height-1 walk at 0 of 22 widths, two a depth, d_1 and
     d_1 + 1, not every width; in this form it is the column's own
     record, one walk at every height.
  HF2 HP1 holds, HK1 silent: "decided cells: the walk at flatten.py's
     d at 96 of 96 run (10 capped at 20000000 children a width)". The
     ten, (2, 15), (3, 16), (4, 15), (4, 16), (5, 15), (5, 16),
     (6, 15), (7, 15), (7, 16), (8, 15), agree with no cap: 106 of
     106, the lattice's 103 cells at k = 2..8 and the three breaks.
  HF3 HP2 holds: all three breaks seen, and each has one extremal
     vector up to sign, no pure product: (9, 10) after 18962 children
     over all widths, (11, 15) after 34860456, (8, 15) after
     259791858, where it is flatten.py's traded product.
  HF4 HP3 holds at the six cells of k = 2, 3 and 6 run, HK2 silent: each
     first vector sits one width past the least pure degree, and every
     vector there is a pure product.
       (2, 12): d = 65, 2 vectors, 10385190 children; parts
         (1, 1, 2, 3, 3, 4, 5, 6, 7, 9, 11, 13) and
         (1, 1, 2, 3, 4, 4, 5, 5, 7, 9, 11, 13)
       (2, 14): d = 89, 2 vectors, 783535200 children; parts
         (1, 1, 2, 3, 3, 4, 5, 5, 7, 8, 9, 11, 13, 17) and
         (1, 1, 2, 3, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13)
       (3, 13): d = 65, 1 vector, 435486933 children; parts
         (1, 1, 2, 2, 3, 3, 4, 5, 5, 7, 8, 11, 13)
       (3, 14): d = 73, 1 vector, 686754516 children; parts
         (1, 1, 2, 2, 3, 4, 4, 5, 6, 7, 8, 9, 10, 11)
       (3, 15): d = 80, 1 vector, 388298981 children; parts
         (1, 1, 2, 2, 3, 3, 4, 5, 5, 6, 7, 8, 9, 11, 13)
       (6, 16): d = 71, 2 vectors, 9048986414 children, 3602510093 of
         them below the last width; parts
         (1, 1, 1, 1, 2, 2, 3, 3, 3, 4, 5, 5, 7, 9, 11, 13) and
         (1, 1, 1, 2, 2, 3, 3, 3, 4, 5, 5, 6, 7, 8, 9, 11)
  HF5 HP4's cell: d_8(16) = 63, the least pure degree, no break:
     nothing to width 63 (913218223 children), one vector at width 64,
     a pure product with parts (1, 1, 1, 1, 1, 2, 2, 3, 3, 3, 4, 5, 5,
     7, 11, 13); 2426507155 children over all widths.
  HF6 HKP. (6, 16), priced at the 20 million cap: capped at width 66
     of 71, the last counts 2511795, 5536427, 12374531, growth 2.22 a
     width, 2.67e9 children to width 71; its widths 66 to 71 cost
     3579788017, the price a quarter low. (2, 16), priced and not
     run: capped at width 105 of 118, the last counts 4514755,
     7574550, 12859905, growth 1.69, 4.80e10 children, a low read as
     the growth rises: walkc.py runs the cell, 107340779935 children
     over its widths to 118, and decides d_2(16) = 118.
  HF7 HK3 silent: 7 of 8 capped cells decided. HP5 fails as worded:
     the reach is set by the width more than the height, (8, 16)
     decided and (2, 16) the dearest. The transplants: at (8, 16) the
     counts peak at suffix length 20 of 63 and the last suffix alive
     has length 37, as at height 1; the growth a width is not steady,
     it rises (2.51, 2.59, 2.64 over widths 60 to 63 there). The walk
     decides seven cells the lattice walk's cap left, at heights 2,
     3, 6 and 8; a cap of 20 million children a width stops it at ten
     cells the lattice walk decides, the two caps counting different
     things.

RUN RECORD AT HEIGHT k. The first form, the engine a script of its
own: its decided cells at the cap of 20 million, 160 s; a line a cell,
one process each, three at once at most, for HF4's cells of k = 2 and
3, HF5 and (8, 15), each listing its last width; the two prices of
HF6; and (6, 16) to width 71 alone, "capped cells: (6, 16): no vector
at any width to 71, the least pure degree; 3602510093 children over
all widths, 751 s". Its counts of children over the widths below a
cell's last and its level counts (HF7) are that form's prints.
This form, the engine walk itself, six check lines more than the
runs recorded above. python suffixwalk.py: "depths
1..14: extremal vectors 17, not pure 0; 51 of 51 checks, 77 s", peak
commit 32.0 MB; python suffixwalk.py 16: "depths 1..16: extremal
vectors 19, not pure 0; 55 of 55 checks, 464 s", the column's counts
as recorded above. python suffixwalk.py decided: 96 of 96, 143 s;
python suffixwalk.py decided 0: "decided cells: the walk at
flatten.py's d at 106 of 106 run (0 capped at None children a
width)", 406 s. python suffixwalk.py cell k J, four processes at
most: every count of children the first form's, to the unit.
  (2, 12): tried 10385190 (5400955 below the last width), 3.7 s
  (2, 14): tried 783535200 (415328415 below), 306.8 s
  (3, 13): tried 435486933 (202650518 below), 123.5 s
  (3, 14): tried 686754516 (332194184 below), 205.4 s
  (3, 15): tried 388298981 (198231509 below), 122.7 s
  (6, 16): tried 9048986414 (3602510093 below), 1927.0 s
  (8, 16): tried 2426507155 (913218223 below), 461.6 s
  (8, 15): tried 259791858 (98015880 below), 47.5 s
  (9, 10): tried 18962 (8094 below), 0.0 s
  (11, 15): tried 34860456 (12763160 below), 5.5 s
Entered from this form's first print, no earlier value behind them:
the records of (9, 10), (11, 15) and (6, 16), whose last widths the
first form never listed whole.
"""
import itertools
import sys
import time
from fractions import Fraction
from math import comb, lcm
from operator import add, mul, sub

import flatten as F

LISTED = (1, 3, 6, 11, 15, 22, 30, 41, 48, 61, 69, 93, 112, 120)
SLACK = 1e-6
WMAX = 5000    # the largest k W walked


def col(t, J):
    return [comb(t, j) for j in range(J)]


class Levels:
    """Per depth J: for each level m >= J the integers (gi, A, Den) with
    g_m = gi / Den = G_m^(-1) a(m) and 1 + kappa_m = A / Den, and
    kappa_m as a float for the top level's E, built from
    G_J^(-1) by one Sherman-Morrison step a level, in exact rationals."""

    def __init__(self, J):
        self.J = J
        # B[j][t] = C(t, j), t < J, unitriangular; its inverse is signed
        binv = [[(-1) ** (j - t) * comb(j, t) if j >= t else 0
                 for j in range(J)] for t in range(J)]
        # G_J^(-1) = B^(-T) B^(-1): entry (i, k) = sum_t binv[t][i] binv[t][k]
        self.ginv = [[Fraction(sum(binv[t][i] * binv[t][k] for t in range(J)))
                      for k in range(J)] for i in range(J)]
        self.m = J
        self.rows = {}

    def upto(self, top):
        J = self.J
        while self.m <= top:
            a = col(self.m, J)
            g = [sum(self.ginv[i][k] * a[k] for k in range(J))
                 for i in range(J)]
            kap = sum(g[i] * a[i] for i in range(J))
            den = 1
            for x in g:
                den = lcm(den, x.denominator)
            den = lcm(den, kap.denominator)
            self.rows[self.m] = (tuple(int(x * den) for x in g),
                                 int((1 + kap) * den), den, float(kap))
            w = 1 + kap
            for i in range(J):
                gi = g[i] / w
                row = self.ginv[i]
                for k in range(J):
                    row[k] -= gi * g[k]
            self.m += 1


_LEVELS = {}


def levels(J, top):
    lv = _LEVELS.setdefault(J, Levels(J))
    lv.upto(top)
    return lv.rows


class Capped(Exception):
    """walk's cap of children met."""


class _Found(Exception):
    pass


def bottom(mu, J, k=1):
    """The integer prefix y on [0, J) with sum_t y_t a(t) = -mu, or None
    once an entry leaves -k..k; y_0 != 0 is the caller's read."""
    y = [0] * J
    for j in range(J - 1, -1, -1):
        v = -mu[j]
        for t in range(j + 1, J):
            if y[t]:
                v -= y[t] * comb(t, j)
        if v > k or v < -k:
            return None
        y[j] = v
    return y


def walk(J, W, k=1, path=None, trace=None, first=False, cap=None):
    """Every vector of height <= k flattened to J at width W with
    c_(W-1) in 1..k and c_0 != 0, by the suffix walk. Returns (vectors,
    kept, tried): kept[m] counts the suffixes alive with c_t fixed for
    t >= m, tried the children tested. None where k W passes WMAX and
    the float argument (5) is not made.
    path: walk only this vector's own suffixes, its top coefficient
    positive, and return in place of the vectors the largest
    E_m / (k^2 m) met (None if a level or the bottom kills it);
    trace then takes E_m at every level the path reaches alive.
    first: stop at one vector. cap: raise Capped once tried passes it."""
    if k * W > WMAX:
        return None
    if W <= J:
        return [], {}, 0
    rows = levels(J, W - 1)
    acol = [col(t, J) for t in range(W)]
    kept = {m: 0 for m in range(J, W)}
    tried = [0]
    out = []
    worst = [0.0]
    kk = k * k
    big = 4.0 * kk * W
    every = tuple(range(-k, k + 1))

    def rec(m, mu, E, suffix):
        # suffix fixed for t >= m, moments mu, E = E_m
        kept[m] += 1
        if path is not None:
            worst[0] = max(worst[0], E / (kk * m))
            if trace is not None:
                trace[m] = E
        if m == J:
            y = bottom(mu, J, k)
            if y is not None and y[0] != 0:
                out.append(y + suffix[::-1])
                if first:
                    raise _Found
            return
        gi, A, den, _ = rows[m - 1]
        s = sum(map(mul, gi, mu))
        a = acol[m - 1]
        lim = kk * (m - 1) + SLACK
        for c in (every if path is None else (path[m - 1],)):
            tried[0] += 1
            n = s + c * A if c else s
            inc = (n / den) * (n / A)
            if inc > big:
                continue
            e = E + inc - c * c
            if e > lim:
                continue
            if c == 0:
                mu2 = mu
            elif c == 1:
                mu2 = list(map(add, mu, a))
            elif c == -1:
                mu2 = list(map(sub, mu, a))
            else:
                mu2 = [x + c * z for x, z in zip(mu, a)]
            suffix.append(c)
            rec(m - 1, mu2, e, suffix)
            suffix.pop()
        if cap is not None and tried[0] > cap:
            raise Capped

    try:
        for top in (range(1, k + 1) if path is None else (path[W - 1],)):
            rec(W - 1, [top * x for x in acol[W - 1]],
                top * top * rows[W - 1][3], [top])
    except _Found:
        pass
    if path is not None:
        return (worst[0] if out else None), kept, tried[0]
    return out, kept, tried[0]


def depth(J, k=1):
    """Widths W = J + 1, J + 2, ... until the walk first returns
    vectors: (d_k(J), the extremal vectors with top coefficient
    positive, tried summed over every width, the last width's kept,
    seconds). None once walk refuses a width."""
    t0 = time.time()
    tried = 0
    W = J + 1
    while True:
        got = walk(J, W, k)
        if got is None:
            return None
        out, kept, n = got
        tried += n
        if out:
            return W - 1, out, tried, kept, time.time() - t0
        W += 1


def least_degree(J, k=1):
    """(d_k(J), every extremal vector with top coefficient positive),
    or None unless J and k are positive integers, and where walk
    refuses a width on the way."""
    if type(J) is not int or J < 1 or type(k) is not int or k < 1:
        return None
    got = depth(J, k)
    return None if got is None else got[:2]


def first_vector(J, k, wstop, cap=None):
    """Widths J + 1 .. wstop, stopping at the first that holds a vector:
    (that width or None, a vector or None, the children tried a width,
    "found" / "none" / "capped" / "refused")."""
    counts = []
    for W in range(J + 1, wstop + 1):
        try:
            got = walk(J, W, k, first=True, cap=cap)
        except Capped:
            return W, None, counts, "capped"
        if got is None:
            return W, None, counts, "refused"
        out, _, n = got
        counts.append(n)
        if out:
            return W, out[0], counts, "found"
    return None, None, counts, "none"


def mobius(n):
    r, p = 1, 2
    while p * p <= n:
        if n % p == 0:
            n //= p
            if n % p == 0:
                return 0
            r = -r
        p += 1
    return -r if n > 1 else r


def pure_parts(v):
    """The parts g of v = +-prod (x^g - 1), or None when v is no pure
    product: the cyclotomic multiplicities e_d = #{g : d | g} inverted
    over multiples."""
    mult, res = F.cyclotomic_split(v)
    if res != [1]:
        return None
    top = max(mult)
    parts = []
    for g in range(1, top + 1):
        cnt = sum(mobius(k) * mult.get(g * k, 0)
                  for k in range(1, top // g + 1))
        if cnt < 0:
            return None
        parts += [g] * cnt
    if sum(parts) != len(v) - 1:
        return None
    return tuple(parts)


def energy_exact(J, m, v):
    """E_m of v's suffix from level m by its definition, mu^T G_m^(-1)
    mu, in exact rationals: G_m summed directly and the system solved
    by elimination, sharing nothing with Levels."""
    mu = [sum(v[t] * comb(t, j) for t in range(m, len(v)))
          for j in range(J)]
    G = [[Fraction(sum(comb(t, i) * comb(t, k) for t in range(m)))
          for k in range(J)] + [Fraction(mu[i])] for i in range(J)]
    for i in range(J):
        piv = next(r for r in range(i, J) if G[r][i] != 0)
        G[i], G[piv] = G[piv], G[i]
        inv = 1 / G[i][i]
        G[i] = [x * inv for x in G[i]]
        for r in range(J):
            if r != i and G[r][i] != 0:
                f = G[r][i]
                G[r] = [x - f * y for x, y in zip(G[r], G[i])]
    return sum(mu[i] * G[i][J] for i in range(J))


def brute(J, W, k=1):
    """The count C3 reads the walk against: exhaustion over the middles."""
    cnt = 0
    vals = range(-k, k + 1)
    for mid in itertools.product(vals, repeat=W - 2):
        for c0 in vals:
            if c0 == 0:
                continue
            for top in range(1, k + 1):
                if F.clears([c0] + list(mid) + [top], J):
                    cnt += 1
    return cnt


# ------------------------------------------------------------- the record

# depth: (d_1, children tried over all widths, the extremal vectors' parts)
RECORD = {
    1: (1, 0, ((1,),)),
    2: (3, 3, ((1, 2),)),
    3: (6, 15, ((1, 2, 3),)),
    4: (11, 57, ((1, 2, 3, 5),)),
    5: (15, 72, ((1, 2, 3, 4, 5),)),
    6: (22, 201, ((1, 2, 3, 4, 5, 7),)),
    7: (30, 543, ((1, 2, 3, 4, 5, 7, 8),)),
    8: (41, 4737, ((1, 2, 3, 4, 5, 7, 8, 11),
                   (1, 2, 3, 5, 6, 7, 8, 9))),
    9: (48, 2847, ((1, 2, 3, 4, 5, 6, 7, 9, 11),)),
    10: (61, 21690, ((1, 2, 3, 4, 5, 6, 7, 9, 11, 13),)),
    11: (69, 5190, ((1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 13),)),
    12: (93, 3588285, ((1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 15, 17),)),
    13: (112, 77545929,
         ((1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 15, 17, 19),
          (1, 2, 3, 5, 5, 7, 8, 9, 11, 12, 13, 17, 19),
          (1, 2, 3, 5, 6, 7, 8, 9, 11, 11, 13, 17, 19))),
    14: (120, 7668786,
         ((1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 13, 15, 17, 19),)),
    15: (141, 146387613,
         ((1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 13, 14, 16, 17, 23),)),
    16: (159, 496443528,
         ((1, 2, 3, 4, 5, 7, 7, 9, 10, 11, 12, 13, 16, 17, 19, 23),)),
}
BRUTE = (13, 78, 71838)   # C3: widest W, cells, vectors in all

# at height k: (k, widest W, cells, vectors in all) against exhaustion
BRUTE_K = ((2, 9, 36, 73422), (3, 8, 28, 173657))
# the dial's three breaks: k, J, d_k(J), flatten.py's lattice's at
# (8, 15) and members.py's at the other two
BREAKS = ((8, 15, 55), (9, 10, 22), (11, 15, 48))
# cap of children a width: (cells at the lattice's d, cells run, capped)
DECIDED = {300000: (86, 86, 20), 20000000: (96, 96, 10), None: (106, 106, 0)}
# (k, J): (d_k(J), the least pure degree, children tried over all widths,
#          the extremal vectors' parts, extremal vectors of no pure product)
DIAL = {
    (2, 12): (65, 65, 10385190,
              ((1, 1, 2, 3, 3, 4, 5, 6, 7, 9, 11, 13),
               (1, 1, 2, 3, 4, 4, 5, 5, 7, 9, 11, 13)), 0),
    (2, 14): (89, 89, 783535200,
              ((1, 1, 2, 3, 3, 4, 5, 5, 7, 8, 9, 11, 13, 17),
               (1, 1, 2, 3, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13)), 0),
    (3, 13): (65, 65, 435486933,
              ((1, 1, 2, 2, 3, 3, 4, 5, 5, 7, 8, 11, 13),), 0),
    (3, 14): (73, 73, 686754516,
              ((1, 1, 2, 2, 3, 4, 4, 5, 6, 7, 8, 9, 10, 11),), 0),
    (3, 15): (80, 80, 388298981,
              ((1, 1, 2, 2, 3, 3, 4, 5, 5, 6, 7, 8, 9, 11, 13),), 0),
    (6, 16): (71, 71, 9048986414,
              ((1, 1, 1, 1, 2, 2, 3, 3, 3, 4, 5, 5, 7, 9, 11, 13),
               (1, 1, 1, 2, 2, 3, 3, 3, 4, 5, 5, 6, 7, 8, 9, 11)), 0),
    (8, 16): (63, 63, 2426507155,
              ((1, 1, 1, 1, 1, 2, 2, 3, 3, 3, 4, 5, 5, 7, 11, 13),), 0),
    (8, 15): (55, 56, 259791858, (), 1),
    (9, 10): (22, 23, 18962, (), 1),
    (11, 15): (48, 49, 34860456, (), 1),
}
SEEN = (9, 10)        # the positive control: a break the walk must see
BARE_CELL = (2, 12)   # the one capped cell of the bare run
BARE_CAP = 300000

CHECKS = []


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


def stage_brute(wmax, k=1):
    """C3: the walk's count against exhaustion at every cell W = 2..wmax,
    J = 1..W-1: (cells, vectors in all, cells that disagree)."""
    bad = cells = total = 0
    for W in range(2, wmax + 1):
        for J in range(1, W):
            b = brute(J, W, k)
            cells += 1
            total += b
            bad += (b != len(walk(J, W, k)[0]))
    return cells, total, bad


def stage_paths(jmax):
    """C1: at each depth the least pure product, built from flatten.py's
    parts and never from the walk, down its own path at the width that
    holds it: per depth (its degree, the largest E_m / m or None)."""
    rows = []
    for J in range(1, jmax + 1):
        dp, parts = F.least_pure_degree(J, 1, 400)
        v = [1]
        for g in parts:
            v = F.mul_part(v, g)
        assert F.height(v) == 1 and F.clears(v, J) and len(v) == dp + 1
        rows.append((dp, walk(J, dp + 1, path=v)[0]))
    return rows


def stage_exact(J, d, v):
    """C4 on one extremal vector: the largest gap between the walk's
    float E_m and the exact one over its path's levels, and of a
    sample of paths with one coefficient flipped, how many a level
    kills and at how many of those the exact E_m is above m."""
    trace = {}
    walk(J, d + 1, path=v, trace=trace)
    gap = max(abs(Fraction(E) - energy_exact(J, m, v))
              for m, E in trace.items())
    killed = right = 0
    for i in range(J, d, max(1, (d - J) // 12)):
        w = list(v)
        w[i] = 1 if w[i] != 1 else 0
        tr = {}
        walk(J, d + 1, path=w, trace=tr)
        m = min(tr) - 1
        if m >= J:
            killed += 1
            right += energy_exact(J, m, w) > m
    return len(trace), float(gap), killed, right


def stage_depth(J):
    """One depth through depth(): d_1(J), the children tried and the
    extremal vectors' parts against the record, every vector checked
    apart from the walk, then C4 on the first."""
    d, out, tried, kept, secs = depth(J)
    sound = all(F.height(v) == 1 and F.clears(v, J) and len(v) == d + 1
                for v in out)
    pure = [pure_parts(v) for v in out]
    notpure = sum(1 for p in pure if p is None)
    parts = tuple(sorted(p for p in pure if p is not None))
    peak = max(kept, key=lambda m: kept[m])
    want = RECORD[J]
    check("J = %2d: d_1, children tried, the extremal vectors' parts"
          % J, (d, tried, parts) == want and sound and notpure == 0,
          "d_1 = %d, tried %d, extremal %d, not pure %d, peak %d at "
          "suffix length %d of %d, %.1f s"
          % (d, tried, len(out), notpure, kept[peak], d + 1 - peak,
             d + 1, secs))
    if J <= len(LISTED):
        check("        A059753's term", d == LISTED[J - 1],
              "%d" % LISTED[J - 1])
    levs, gap, killed, right = stage_exact(J, d, out[0])
    check("        C4 the float E_m within 1e-9 of the exact one; a "
          "flipped path a level kills has the exact E_m > m",
          gap < 1e-9 and right == killed,
          "%d levels within %.1e; %d killed, %d right"
          % (levs, gap, killed, right))
    return d, len(out), notpure


def capped_cells():
    """The cells flatten.py's node cap stops at height k > 1: (k, J,
    least pure degree)."""
    return [c for c in F.EXTEND_CAPPED if c[0] > 1]


def decided_cells():
    """The cells of the dial flatten.py's lattice decides at height
    k > 1, J <= 16, and the three breaks: (k, J, d_k(J))."""
    cells = [(k, J, d) for k in sorted(F.OLD_TABLE) if k > 1
             for J, d in enumerate(F.OLD_TABLE[k], 1)]
    cells += list(F.RECORD["extend"]["past the table, pure: k, J, d"])
    return cells + list(BREAKS)


def stage_known():
    """At height k: the least pure product at each capped cell, built
    from flatten.py's parts, and the traded product at (8, 15), each
    down its own path at the width that holds it: per vector (k, J,
    its degree, the largest E_m / (k^2 m) or None, the float E's
    largest gap from the exact one, the levels read)."""
    known = []
    for k, J, dp in capped_cells():
        got, parts = F.least_pure_degree(J, k, 400)
        v = [1]
        for g in parts:
            v = F.mul_part(v, g)
        assert got == dp and F.height(v) <= k and F.clears(v, J)
        known.append((k, J, v))
    known.append((8, 15, F.traded(F.BREAK_PARTS, F.BREAK_R)))
    rows = []
    for k, J, v in known:
        if v[-1] < 0:
            v = [-c for c in v]
        trace = {}
        worst = walk(J, len(v), k, path=v, trace=trace)[0]
        gap = max(abs(Fraction(E) - energy_exact(J, m, v))
                  for m, E in trace.items())
        rows.append((k, J, len(v) - 1, worst, float(gap), len(trace)))
    return rows


def stage_decided(cap):
    """Every cell of decided_cells() through first_vector under a cap
    of children a width: (cells whose first vector sits at width
    d + 1 and is sound, cells run, the cells the cap stopped)."""
    agree = run = 0
    stopped = []
    for k, J, d in decided_cells():
        t0 = time.time()
        W, v, counts, status = first_vector(J, k, d + 1, cap)
        if status == "capped":
            stopped.append((k, J))
            continue
        run += 1
        good = (status == "found" and W == d + 1 and F.height(v) <= k
                and F.clears(v, J))
        agree += good
        if not good or sum(counts) > 20000000:
            print("  (%2d, %2d) d = %2d: %s at width %s, %d children, "
                  "%.1f s%s" % (k, J, d, status, W, sum(counts),
                                time.time() - t0,
                                "" if good else "  DISAGREES"), flush=True)
    return agree, run, stopped


def check_decided(cap):
    agree, run, stopped = stage_decided(cap)
    want = DECIDED.get(cap, (run, run, len(stopped)))
    check("the walk's first vector one width past the lattice's d",
          (agree, run, len(stopped)) == want and run > 0,
          "decided cells: the walk at flatten.py's d at %d of %d run "
          "(%d capped at %s children a width)"
          % (agree, run, len(stopped), cap))
    if stopped and cap != BARE_CAP:
        print("        capped: %s" % (stopped,))


def stage_cell(k, J):
    """One cell of the dial with no cap: every width from J + 1 to the
    first that holds a vector, that width listed whole, read against
    DIAL."""
    t0 = time.time()
    dp = F.least_pure_degree(J, k, 400)[0]
    total = below = 0
    W = J + 1
    while True:
        out, _, n = walk(J, W, k)
        total += n
        if n > 20000000:
            print("  (%d, %d) width %d: %d children, %d vectors; %.0f s"
                  % (k, J, W, n, len(out), time.time() - t0), flush=True)
        if out:
            break
        below = total
        W += 1
    d = W - 1
    sound = all(F.height(v) <= k and F.clears(v, J) for v in out)
    pure = [pure_parts(v) for v in out]
    parts = tuple(sorted(q for q in pure if q is not None))
    notpure = [v for v, q in zip(out, pure) if q is None]
    check("(%d, %d): d, the least pure degree, children tried, the "
          "extremal vectors' parts, those of no pure product" % (k, J),
          (d, dp, total, parts, len(notpure)) == DIAL[(k, J)] and sound,
          "d_%d(%d) = %d%s, least pure degree %d, tried %d (%d below "
          "the last width), extremal %d, not pure %d, %.1f s"
          % (k, J, d, ", a break" if d < dp else "", dp, total, below,
             len(out), len(notpure), time.time() - t0))
    for q in parts:
        print("        parts %s" % (q,))
    for v in notpure:
        print("        no pure product: %s" % (v,))
    if (k, J) == (8, 15):
        check("        its extremal vector is flatten.py's traded product",
              len(out) == 1 and F.same_up_to_sign(
                  out[0], F.traded(F.BREAK_PARTS, F.BREAK_R)))


def finish(t0, head):
    print("\n%s%d of %d checks, %.0f s"
          % (head, sum(CHECKS), len(CHECKS), time.time() - t0))
    sys.exit(0 if all(CHECKS) else 1)


def main(argv):
    t0 = time.time()
    if argv and argv[0] == "cell":
        key = tuple(int(x) for x in argv[1:3])
        if key not in DIAL:
            print("cell k J, (k, J) one of %s" % (sorted(DIAL),))
            sys.exit(2)
        stage_cell(*key)
        finish(t0, "")
    if argv and argv[0] == "decided":
        cap = int(argv[1]) if len(argv) > 1 else 20000000
        check_decided(cap or None)
        finish(t0, "")
    jmax = int(argv[0]) if argv else 14
    if not 1 <= jmax <= len(RECORD):
        print("depth 1..%d" % len(RECORD))
        sys.exit(2)
    print("THE CONTROLS")
    cells, total, bad = stage_brute(BRUTE[0])
    check("C3 the walk against exhaustion, W = 2..%d, J = 1..W-1"
          % BRUTE[0], (cells, total, bad) == BRUTE[1:] + (0,),
          "%d cells, %d vectors in all, %d cells disagree"
          % (cells, total, bad))
    paths = stage_paths(jmax)
    check("C1 the least pure products' paths alive, their degrees the "
          "record's d_1",
          all(w is not None and w <= 1 + SLACK for _, w in paths)
          and [dp for dp, _ in paths] == [RECORD[J][0]
                                          for J in range(1, jmax + 1)],
          "%d of %d alive, the largest E_m / m %.4f; at the last "
          "depth %.4f"
          % (sum(1 for _, w in paths if w is not None), jmax,
             max(w or 0 for _, w in paths), paths[-1][1] or 0))
    if not all(CHECKS):
        print("\nCONTROL FAILED: nothing below is read.")
        sys.exit(1)
    print("\nTHE COLUMN: depths 1..%d" % jmax)
    rows = [stage_depth(J) for J in range(1, jmax + 1)]
    print("\nAT HEIGHT k: THE CONTROLS")
    mark = len(CHECKS)
    for k, wmax, want_cells, want_total in BRUTE_K:
        cells, total, bad = stage_brute(wmax, k)
        check("the walk against exhaustion at k = %d, W = 2..%d, "
              "J = 1..W-1" % (k, wmax),
              (cells, total, bad) == (want_cells, want_total, 0),
              "%d cells, %d vectors in all, %d cells disagree"
              % (cells, total, bad))
    known = stage_known()
    check("the known vectors' paths alive, the float E within 1e-9 of "
          "the exact one",
          all(r[3] is not None and r[3] <= 1 + SLACK and r[4] < 1e-9
              for r in known),
          "%d of %d alive, the largest E_m / (k^2 m) %.4f at (%d, %d); "
          "the largest gap %.1e"
          % ((sum(1 for r in known if r[3] is not None), len(known))
             + max((r[3] or 0, r[0], r[1]) for r in known)
             + (max(r[4] for r in known),)))
    stage_cell(*SEEN)
    if not all(CHECKS[mark:]):
        print("\nCONTROL FAILED: nothing below is read.")
        sys.exit(1)
    print("\nAT HEIGHT k: THE DIAL")
    check_decided(BARE_CAP)
    stage_cell(*BARE_CELL)
    lines = (2 + sum(3 if J <= len(LISTED) else 2
                     for J in range(1, jmax + 1))
             + len(BRUTE_K) + 4)
    check("every check line of the run printed, this one aside",
          len(CHECKS) == lines, "%d of %d" % (len(CHECKS), lines))
    finish(t0, "depths 1..%d: extremal vectors %d, not pure %d; "
           % (jmax, sum(r[1] for r in rows), sum(r[2] for r in rows)))


if __name__ == "__main__":
    main(sys.argv[1:])