flatten.py

"""flatten.py -- the least height of an integer polynomial forced to
vanish to a given order at 1: the exact chart, where products of
x^g - 1 attain it and where they do not, and the inverse dial read as
the shortest integer-tap filter that kills polynomial signals below
a given degree.

USE. In Python, from the folder holding flatten.py. least_height
returns the least height of a nonzero integer vector of the given
width whose polynomial vanishes to the given order at 1, a vector that
attains it, and the nodes the search cost; read as a filter, the
vector is a set of taps that annihilates every polynomial signal of
degree below the order. The vector's height and order are checked
by hand, as below; that none is lower rests on a float enumeration
and its slack:

    >>> from flatten import least_height
    >>> h, taps, nodes = least_height(12, 5)   # 12 taps, order 5
    >>> h, taps
    (2, [-1, 2, 0, -1, 0, -2, 2, 0, 1, 0, -2, 1])
    >>> [sum(c * i**j for i, c in enumerate(taps)) for j in range(6)]
    [0, 0, 0, 0, 0, 2880]
    >>> least_height(8, 3)[:2]                 # taps of -1, 0, 1 suffice
    (1, [-1, 1, 1, 0, -1, -1, 1, 0])

QUESTION. A vector c of M integers is the polynomial P(x) = sum c_i x^i
of degree < M. Its FLATTENING is the multiplicity of the root 1 and
its HEIGHT is max |c_i|. h(M, J) is the least height of a nonzero P of
degree < M flattened to depth J. How small is it, what attains it, and
read the other way, how short can a vector of taps bounded by k be if
it must annihilate every polynomial signal of degree < J?

THE OBJECTS.
  THE LATTICE. The vectors flattened to J are exactly (x - 1)^J Z[x]
      cut at degree < M, a lattice of rank r = M - J with basis
      x^i (x - 1)^J, i < r, so h(M, J) is a shortest vector in the sup
      norm. A CELL is a pair (M, J) with J < M.
  THE PURE PRODUCTS. prod (x^{g_i} - 1) over a multiset of positive
      PARTS g_i: it has degree sum g_i and flattening equal to the
      number of parts. One is ADMISSIBLE at a cell when its degree is
      below M and its part count at least J; ph(M, J) is the least
      height of an admissible one, so h <= ph, and a cell FAILS when
      h < ph.
  THE INVERSE DIAL. d_k(J) is the least degree of a nonzero multiple
      of (x - 1)^J of height at most k, so h(M, J) <= k iff M > d_k(J). A
      tap vector c annihilates every signal n -> n^j, j < J, under
      sum_i c_i s(n - i) exactly when sum_i c_i i^j = 0 for j < J,
      which is exactly flattening to depth J; so d_k(J) + 1 is the
      least number of taps of such a filter with integer taps bounded
      by k (property, by the moment identity below).

THE HAND ATTACK, on paper before the engine.
  (1) THE MOMENT IDENTITY. P(x) = sum_j m_j (x - 1)^j with
      m_j = sum_i C(i, j) c_i, and sum_i C(i, j) c_i = 0 for all j < J
      is the same linear system as sum_i i^j c_i = 0 for j < J (the
      binomials C(i, j), j < J, and the powers i^j span the same
      polynomials in i of degree < J). So flattening is annihilation.
  (2) THE FREE RADIUS. A vector of sup norm at most H has Euclidean
      norm at most H sqrt(M), so the Euclidean ball of radius
      (q - 1) sqrt(M) holds every lattice vector of height below q. An
      enumeration of that ball, shrunk each time a vector of height below
      q is met, returns h exactly in exact arithmetic; its starting q is
      the least height among the reduced basis's own vectors, so the pure
      family under test supplies nothing to the number it is compared
      with.
  (3) RANK 1. At M = J + 1 the lattice is generated by (x - 1)^J
      alone, h = C(J, floor(J/2)), and the only pure product with J
      parts and degree J is (x - 1)^J, so ph = h there (property).
  (4) THE FINAL COEFFICIENTS. Multiplying P by a part x^g - 1 sends
      the coefficient at i < g to -c_i. So in a product built in
      nondecreasing part order, once the last part is g every
      coefficient below index g is final up to sign, and a walk may
      discard a partial product with such a coefficient above k. That
      makes the least degree of a J-part pure product of height <= k
      an exact branch-and-bound over partitions.
  (5) THE CYCLOTOMIC FLOOR. Let P have height <= k, degree <= T and
      (x - 1)^J | P, and let zeta be a primitive p^u-th root of unity,
      p prime. If Phi_{p^u} does not divide P, the norm of P(zeta) is a
      nonzero integer divisible by the norm of (zeta - 1)^J, which is
      p^J, while |P(zeta)| <= k(T + 1) at every conjugate; so
      J log p > phi(p^u) log(k(T + 1)) forces Phi_{p^u} | P. The forced
      factors are coprime to (x - 1)^J, so J + sum phi(p^u) <= T, and
      the least T passing that test is a floor on d_k(J) (property).
  (6) THE BOX PRINCIPLE. Over 0/1 vectors the moment m_j ranges over
      0..C(M, j + 1); if 2^M exceeds prod_{j<J} (C(M, j + 1) + 1), two
      vectors share their first J moments and their difference is a
      height-1 vector flattened to J, so h(M, J) = 1 (property).

THE SLATE, frozen before the engine first ran. Every figure below is
a TRANSPLANT from an older record of the same question and was read
as a prediction, never as a fact.
  P1 THE CORNER. At all 63 cells M = 4..12, J = 1..M-1, h = ph.
  P2 THE CHART. Over the 695 cells M = 4..40, J = 2..min(30, M - 1),
     h = ph at 612 and h < ph at 83; the failures fall 3 of 362 at
     J <= 12, 17 of 188 at J = 13..20 and 63 of 145 at J >= 21.
  P3 RANK 1. h = ph = C(J, floor(J/2)) at every rank-1 cell.
  P4 THE DIAL. For k = 1..8 and J = 1..14 where the older table has a
     value, d_k(J) equals the least degree of a pure product of height
     <= k with exactly J parts, and the table reads
        J   k=1 k=2 k=3 k=4 k=5 k=6 k=7 k=8
        1     1   1   1   1   1   1   1   1
        2     3   2   2   2   2   2   2   2
        3     6   4   3   3   3   3   3   3
        4    11   7   5   5   5   4   4   4
        5    15  11   8   8   6   6   6   6
        6    22  16  11  10   9   9   9   9
        7    30  22  17  14  14  11  11  11
        8    41  26  20  19  18  16  15  15
        9    48  34  27  22  22  21  20  19
       10    61  45  33  29  27  23  23  23
       11    69  51  43  34  30  30  25  25
       12     .   .   .  44  38  36  32  31
       13     .   .   .   .  46  46  37  37
       14     .   .   .   .   .   .  49  47
  P5 THE FLOOR sits at or below every dial value read.
  P6 THE BOX. Every cell the box principle reaches has h = 1.

KILLS, as prints.
  K1 A corner cell with h < ph: the corner's count of them above 0.
  K2 A dial cell where the lattice holds a vector of height <= k and
     degree below the walk's least pure degree: the pure law broken on
     the inverse dial (a finding, not a bug; inside the older table,
     whose cells were decided, it fails the run).
  KB (bugs, never findings) h > ph; a witness not cleared by J
     synthetic divisions; a floor above a dial value; a box cell with
     h > 1.

THE DESIGN. Exact integers throughout: an integral LLL (Cohen's
fraction-free form, delta = 99/100) returns a reduced basis with its
Gram-Schmidt data as integers; the enumeration runs Schnorr-Euchner
over those data converted to floats with a slack on the squared
radius, a factor 1 + 1e-9 and an added 1e-9, and every vector it
returns is recomputed exactly from integer coefficients, so a float
error can only cost nodes, never
admit a wrong vector; missing one would need an error above the slack.
The chart's pure products are one depth-first walk over the multisets
of degree sum <= 39, keeping the least height per (part count,
degree); the dial's are the walk of hand attack (4).

THE ARMS. Each stage is a function that prints nothing and returns a
record, a dictionary of counts and values under their own names, and
the run sets each entry against RECORD, a check line an entry. Stages
by argv: chart, dial and break by default, extend on request.
  chart   every cell M = 4..40, J = 1..min(30, M - 1) through
          chart_row (h with its witness, ph), counted by chart_record:
          the witnesses cleared, where h is below the reduced basis's
          own least height, where exactly J parts attain ph, h against
          ph over the corner, the chart and its three depth bins, the
          failing ranks, the first failures, rank 1 against
          C(J, J // 2), the box principle's reach, and the route
          against two exhaustions.
  dial    every cell of the older table through dial_row: the walk's
          least pure degree dp, then the lattice at width dp decides
          whether anything of height <= k has lower degree ("pure"
          when nothing does), then the same route one width up,
          where the product sits, which must return some vector of
          height <= k (a reduced basis vector counts, with no
          enumeration), then the floor.
  break   the one cell where the dial's pure law fails, k = 8, J = 15,
          through dial_row, the one cell of the default run whose
          verdict is not "pure", so the one place a lattice that
          decided nothing would show. The walk reads no product with
          more than J parts, so the stage closes those with the
          lattice at depth J + 1.
  extend  the dial with each column carried past the older table to
          J = 16, under a cap of 2 x 10^7 nodes an enumeration (a
          cell runs up to two, a break more): a cell the cap stops is
          "capped", its pure degree an upper bound only. At a break
          the width steps down to the exact
          d_k(J); the step-down runs under the same cap with no
          handler, so a capped step-down ends the run with a traceback.

CONTROLS, run before any stage; one failing stops the run.
  Each helper on cases worked by hand, the values in the check lines:
  pow_xm1, clears, mul_part, the pure table to degree 3 with ph at
  four cells, the walk's least pure degree at six (the four 3-part
  products of degree <= 5 have heights 3, 2, 2, 2, so d = 6 at
  k = 1, and under a cap of degree 3 the walk still returns 3),
  prime_powers to 7, 9 and 10, box_reach at the five widths where
  its depth is said to step (256 < 261 at M = 8, 512 > 370 at M = 9)
  and at M = 1, the tie 2 = 2, and M = 2, phi at seven orders, the
  exhaustion at four cells.
  THE REDUCTION. lll's output on the cell (4, 2) is set against
     Cohen's steps taken by hand: one size reduction, one swap, then
     the tie 2 |lam| = d, which must not reduce. basis_law reads what
     the enumeration rests on (the integers returned are the rows'
     own Gram-Schmidt data, redone in fractions; every row cleared J
     times; the Gram determinant the input's) at five cells,
     r(r - 1)/2 + 2r + 1 readings at rank r,
     and its three plants each miss as counted: one coefficient moved
     (5 of 6), the depth claimed one higher (4 of 6), a sublattice of
     index 2 (5 of 6).
  THE ENUMERATION. u = (3, -1, 1, 1), v = (-1, 3, 1, 1) are reduced as
     given, of height 3, and a u + b v = (3a - b, 3b - a, a + b,
     a + b) has height 1 nowhere and height 2 exactly at +-(u + v) =
     +-(2, 2, 2, 2). So the least height is at no basis vector, and
     its norm^2, 16, is the ball's radius^2 at q = 3 exactly, a
     vector a float error could lose; from q = 4 the first vector met
     is u, the shrunk radius meets the same tie, and a stop at height
     2 must pass u by. With u negated the centre falls on the other
     side of its rounding. A second pair, in width 9: u = (1, -3, -1,
     -1, -1, -1, -1, -1, -1), v = (3, -1, 1, 1, 1, 1, 1, 1, 1),
     |u|^2 = |v|^2 = 17, u.v = -1, reduced as given; b f + c u with
     f = v - u = (2, ..., 2) has entries 2b + c, 2b - 3c and 2b - c:
     the first and third within 2 leave b = 0 or c = 0, and at b = 0
     the second is 3c, so the height is <= 2 only at +-f. There the
     least vector is the level's third point,
     on the far side of the centre 1/17 at distance 18/17, again on
     the radius exactly (36), and with u negated it is the far side
     of the other direction. The slack itself is read by none of
     these: dropped from radius2, every line of the default run
     still passes (RUN RECORD); prunerr.py reads radius2 against the
     enumeration's float error. Then three
     cells of the chart where the route's h is below the reduced
     basis's least height H:
     (17, 10) with h = 23 against 24, (18, 11) with 33
     against 44, (22, 13) with 67 against 76. At each, an exhaustion
     of the sums of basis vectors with coefficients in {-1, 0, 1}, a
     search that shares the reduced basis with the enumeration and
     nothing else, finds h too.
  ONE_UP, DIAL_ROW AND STEP_DOWN. one_up says no where nothing is
     (width 3 at J = 2, k = 1; height 22 at the cell (17, 10), whose
     h is 23) and
     under a cap of no nodes; dial_row by hand at (k, J) = (1, 1),
     where the lattice below has rank 0, at (1, 2), d = 3, and at
     (1, 2) under a cap of no nodes, "capped". step_down from width
     6 at J = 2, k = 1 descends two widths to 4, where the vector is
     +-(x - 1)(x^2 - 1), the only one of height 1 by the rank-2
     theorem; at every break the stages read it stops after one.
  THE RECORDS. chart_record on fourteen rows written by hand, every
     entry counted by hand, each built to miss somewhere: a witness
     not cleared, an h above ph, an h off its exhaustion, a rank-1
     cell off its binomial, a corner cell that fails, a box cell with
     h = 2, a box cell whose ph is not 1, a cell where h is below
     the basis at width 10. dial_record on the older table with seven
     rows rewritten (a capped cell, a break whose witness is not the
     product, a floor above its value, a cell not found one width up,
     a value off the table, two floors equal to their values) and
     three added past it, one pure and two capped.
  THE SPLIT finds Phi_6 beside 1 + 2x, Phi_14 and Phi_22 beside
     2 + 3x + 2x^2, and Phi_22 alone, though deg Phi_n is not monotone
     in n: a loop stopping at the first Phi_n longer than what is left
     stops at Phi_5, Phi_11, Phi_17 and Phi_13 and finds none of the
     four.
  THE TIE. The floor's test p^J > (k(T + 1))^phi is strict: at
     3^10 = 243^2 it forces nothing, at 242 it forces, and the float
     gap J log p - phi log 243 is printed: positive, so a float
     comparison alone calls the tie forced (that line reads the
     machine's floats and no line of the engine). The floor by hand
     at k = 1: 1, 3, 5 at J = 1, 2, 3, through three more exact ties
     (2 = 2 at J = 1; 3^2 = 3^2 at J = 2, T = 2; 2^2 = 4 at T = 3).
  THE BREAK'S WITNESS BY ARITHMETIC. The product with parts 1, 1, 1,
     1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 5, 7 times
     R = 2 + 3x + 3x^2 + 3x^3 + 4x^4 + 5x^5 + 4x^6 + 3x^7 + 3x^8
     + 3x^9 + 2x^10 has degree 55 and height 8 and is cleared 15
     times and not 16: d_8(15) <= 55 with no lattice. The stages then
     set the lattice's own witness against it, equal up to sign.
  In the stages: at rank 1 the lattice is the multiples of
     (x - 1)^J, its one basis vector, so that entry reads that the
     reduction leaves it, that the enumeration finds nothing lower
     and that the walk's ph agrees, the binomial being the vector's
     own largest entry; and the two exhaustions, of [-3, 3]^M at
     width <= 6 and [-1, 1]^M at width <= 9, decide h at 10 of their
     12 cells and h = 1 at 15 of
     their 33, and only a lower bound at the rest. At every cell they
     reach, the reduced basis already holds a vector of height h (F5),
     so they read the reduction and that the enumeration finds
     nothing lower, never that it finds what is there: that is the
     hand lattices' and the coefficient boxes'.

FINDINGS (copied from the printed output).
  F1 THE CORNER (P1 holds, K1 never fired): 63 cells, h = ph at all.
  F2 THE CHART (P2 holds to the cell): 695 cells, h = ph at 612 and
     h < ph at 83; by depth 3 of 362, 17 of 188 and 63 of 145. The
     failing ranks are 5..18, all fourteen. The first failures by
     depth: h(23, 10) = 9 against 10, h(21, 12) = 39 against 44,
     h(25, 12) = 25 against 28. All 732 witnesses, the J = 1 column
     among them, are cleared J times, and no h is above ph. At all
     732 cells a product of exactly J parts attains ph: no cell needs
     the "at least" of its definition.
  F3 RANK 1 (P3 holds): the 28 rank-1 cells.
  F4 THE BOX (P6 holds): it reaches depth 1 at M = 4..8, depth 2 at
     M = 9..23 and depth 3 at M = 24..40, 86 cells, each with h = 1.
  F5 THE EXHAUSTIONS agree with the route at their 12 and 33 cells.
     The enumeration goes below the reduced basis's own least height
     at 36 of the 732 cells, none of width <= 9.
  F6 THE DIAL (P4 holds at every older cell): all 99 cells decided,
     pure and equal to the older table, the least of whose columns'
     last entries is 43, above the chart's widths. One width up the
     route finds a vector at all 99, and at all 115 with extend.
  F7 THE FLOOR (P5 holds): at or below every value decided; equal at
     27 cells of the table, none deeper than J = 5; 26 against 69 at
     k = 1, J = 11.
  F8 THE EXTENSION. Fifteen new cells pure: d_2(13) = 74,
     d_2(15) = 95; d_3(12) = 52, d_3(16) = 87; d_4 = 52, 60, 70, 78
     at J = 13..16; d_5 = 55, 64, 71 at J = 14..16; d_6 = 52, 60 at
     J = 14, 15; d_7 = 56, 64 at J = 15, 16. Thirteen cells capped,
     among them every k = 1 cell past J = 11, whose least pure degrees
     are 93, 112, 120, 141 and 159 at J = 12..16: upper bounds by
     this walk. suffixwalk.py's walk decides twelve of the thirteen,
     each at its least pure degree, and walkc.py, the same walk
     compiled, the last: d_2(16) = 118, its least pure degree.
  F9 ONE BREAK, AT k = 8, J = 15: d_8(15) = 55 against the least pure
     degree 56, parts (1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 5, 6, 7, 9).
     The lattice's witness has height 8, is cleared 15 times, and is
     the control's product up to sign; it splits as Phi_1^15 Phi_2^4
     Phi_3^2 Phi_4^2 Phi_5^3 Phi_7, of degree 45, times R: a pure
     product with ten degrees of it traded for a non-cyclotomic
     factor. Nothing of height <= 8 has degree below 55, and nothing
     of height <= 8 flattened to 16 has degree below 56, which covers
     every product with 16 or more parts: the pure law on the inverse
     dial fails at height 8.

RUN RECORD. python flatten.py: 39 of 39 checks, 28.7 s (chart 2.7 s,
dial 6.5 s, break 19.2 s), peak commit 12.5 MB.
Entered from this form's first print, no hand value behind them: the
36 cells where the enumeration goes below the basis, the 732 where
exactly J parts attain ph, the float gap at the tie, 1.776e-15, and
the three cells of the coefficient box with their h and H.
Edits by hand, each with the FAIL lines it should print named before
its run: 46 runs of 42 edits over two drafts. Seven passed every
check as named, the
slack's two on both drafts and the rest on the first: ph_of taking
exactly J parts (F2's 732 cells); the slack dropped from the first
radius, and from the shrunk one; exists_at_most's shortcut
through the basis cut to heights below k (the enumeration finds the
vector); box_reach's > made >= (no width to 40 meets equality); the
split's skip of a totient too long made strict (its inner loop guards
it); one_up's height test dropped (the route returns nothing above
k). One passed unnamed, on the first draft and in 677 s against 29:
the zigzag's far side never walked. The width-9 pair is its control.
python flatten.py extend: 22 of 22 checks, its six entries among
them, 477.4 s, peak commit 13.2 MB. The entries were first
read off an earlier form's run, which carried a wall of 240 s a
column that never fell (the longest column took 135 s); this form
has none.
One site changed at a time, at every site of every function but main
and those named check or section, the default run read: 703 mutants,
572 failing a check, 63 past the clock, 68 passing, none of the 68
moving a line of the print. Read one by one, most of the 68 are equal
on every input: a symmetry cut of the exhaustion, a sign that
cancels, a value every path overwrites, a tie's other witness, a
larger radius or a longer list that only costs time. The rest are
what no check here reads. The slack, above. The node count and its
cap, which are extend's alone. The zigzag past a level's fifth point
(t % 2 made t % 3). one_up's tests of height and of clearing, which
the route's own contract implies. The break's "flattened to 16" read
at 17, a weaker emptiness. And in chart_record the second count of h
below the basis with ph in place of h: the hand row (4, 2) has both
below H, so a row at width <= 9 with ph at or above H and h below it
is owed. Six check lines no mutant turned: the float gap; the dial's
three entries past the table, empty in the default run; the break's
least pure degree and parts, since what moves them fails the walk's
hand cases first; the count of lines.
"""
import sys
import time
from fractions import Fraction
from math import comb, log, isqrt


# ------------------------------------------------------------- polynomials

def pow_xm1(J):
    """Coefficients of (x - 1)^J, lowest degree first."""
    return [comb(J, i) * (-1) ** (J - i) for i in range(J + 1)]


def height(p):
    return max(abs(c) for c in p)


def clears(p, J):
    """True when (x - 1)^J divides p, by J synthetic divisions."""
    q = list(p)
    for _ in range(J):
        if sum(q) != 0:
            return False
        # divide by (x - 1): q = (x - 1) s, s_{n-1} = q_n, s_{i-1} = q_i + s_i
        s = [0] * (len(q) - 1)
        acc = 0
        for i in range(len(q) - 1, 0, -1):
            acc += q[i]
            s[i - 1] = acc
        q = s
    return True


def basis(M, J):
    base = pow_xm1(J)
    rows = []
    for i in range(M - J):
        v = [0] * M
        v[i:i + J + 1] = base
        rows.append(v)
    return rows


# ----------------------------------------------------------- integral LLL

def lll(B):
    """Cohen's integral LLL (Algorithm 2.6.7) at delta = 99/100. Returns
    the reduced basis, the integers d_0..d_n and lam[k][j] (j < k), with
    B*_k = d_{k+1}/d_k and mu_{k,j} = lam[k][j]/d_{j+1} (0-indexed)."""
    b = [list(v) for v in B]
    n = len(b)
    dot = lambda u, v: sum(x * y for x, y in zip(u, v))
    d = [1] + [0] * n            # d[i] for i = 0..n; d[i+1] belongs to b_i
    lam = [[0] * n for _ in range(n)]

    def redi(k, l):
        if 2 * abs(lam[k][l]) > d[l + 1]:
            q = (2 * lam[k][l] + d[l + 1]) // (2 * d[l + 1])
            bl, bk = b[l], b[k]
            b[k] = [x - q * y for x, y in zip(bk, bl)]
            lam[k][l] -= q * d[l + 1]
            for i in range(l):
                lam[k][i] -= q * lam[l][i]

    def swapi(k):
        b[k], b[k - 1] = b[k - 1], b[k]
        for j in range(k - 1):
            lam[k][j], lam[k - 1][j] = lam[k - 1][j], lam[k][j]
        la = lam[k][k - 1]
        Bn = (d[k - 1] * d[k + 1] + la * la) // d[k]
        for i in range(k + 1, kmax[0] + 1):
            t = lam[i][k]
            lam[i][k] = (d[k + 1] * lam[i][k - 1] - la * t) // d[k]
            lam[i][k - 1] = (Bn * t + la * lam[i][k]) // d[k + 1]
        d[k] = Bn

    kmax = [0]
    d[1] = dot(b[0], b[0])
    k = 1
    while k < n:
        if k > kmax[0]:
            kmax[0] = k
            for j in range(k + 1):
                u = dot(b[k], b[j])
                for i in range(j):
                    u = (d[i + 1] * u - lam[k][i] * lam[j][i]) // d[i]
                if j < k:
                    lam[k][j] = u
                else:
                    if u == 0:
                        raise ValueError("dependent basis")
                    d[k + 1] = u
        redi(k, k - 1)
        la = lam[k][k - 1]
        if 100 * d[k + 1] * d[k - 1] < 99 * d[k] * d[k] - 100 * la * la:
            swapi(k)
            k = max(1, k - 1)
        else:
            for l in range(k - 2, -1, -1):
                redi(k, l)
            k += 1
    return b, d, lam


# ------------------------------------------------------------ enumeration

class NodeCap(Exception):
    pass


SLACK = 1e-9


def radius2(s, M):
    """The float squared radius the enumeration prunes at: (s - 1)^2 M,
    the ball holding every vector of height below s, widened by SLACK
    relatively and absolutely. prunerr.py reads it against the
    enumeration's float error."""
    return (s - 1) ** 2 * M * (1 + SLACK) + SLACK


def enumerate_min(b, d, lam, M, s0, cap=None, stop_at=None):
    """Least sup norm of a nonzero lattice vector below s0, by
    Schnorr-Euchner enumeration of the Euclidean ball of radius
    (s - 1) sqrt(M), s the best height met so far. Returns (s, v, nodes)
    with v None when nothing below s0 exists. stop_at: return at the
    first vector of height <= stop_at."""
    n = len(b)
    Bs = [d[i + 1] / d[i] for i in range(n)]
    mu = [[lam[k][j] / d[j + 1] for j in range(k)] for k in range(n)]
    best = [s0, None]
    R2 = [radius2(s0, M)]
    nodes = [0]
    x = [0] * n

    def leaf():
        v = [0] * M
        for i in range(n):
            xi = x[i]
            if xi:
                bi = b[i]
                for t in range(M):
                    v[t] += xi * bi[t]
        s = max(abs(c) for c in v)
        if 0 < s < best[0]:
            best[0], best[1] = s, v
            R2[0] = radius2(s, M)
            if stop_at is not None and s <= stop_at:
                raise StopIteration

    def rec(i, partial, top):
        # top: every coordinate above i is zero, so c = 0 and by the
        # sign symmetry only x_i >= 0 is walked, in order 0, 1, 2, ...
        # Otherwise the zigzag x0, x0 + s, x0 - s, x0 + 2s, ... is
        # ordered by distance from the centre c, so the first point
        # outside the ball ends the level.
        c = 0.0
        if not top:
            for j in range(i + 1, n):
                if x[j]:
                    c -= mu[j][i] * x[j]
        x0 = round(c)
        s = 1 if c >= x0 else -1
        t = 0
        while True:
            if top:
                xi = t
            elif t == 0:
                xi = x0
            elif t % 2 == 1:
                xi = x0 + s * ((t + 1) // 2)
            else:
                xi = x0 - s * (t // 2)
            t += 1
            nodes[0] += 1
            if cap is not None and nodes[0] > cap:
                raise NodeCap
            y = xi - c
            p = partial + y * y * Bs[i]
            if p > R2[0]:
                break
            x[i] = xi
            if i == 0:
                leaf()
            else:
                rec(i - 1, p, top and xi == 0)

    try:
        rec(n - 1, 0.0, True)
    except StopIteration:
        pass
    if best[1] is None:
        return None, None, nodes[0]
    return best[0], best[1], nodes[0]


def route(M, J, cap=None):
    """h(M, J) exactly with a witness: reduce, start from the reduced
    basis's own least height H, enumerate. Returns (h, v, nodes, H)."""
    b, d, lam = lll(basis(M, J))
    H = min(height(v) for v in b)
    s, v, nodes = enumerate_min(b, d, lam, M, H, cap=cap)
    if s is None:
        # nothing below H: a reduced basis vector of height H is least
        v = min(b, key=height)
        s = H
    return s, v, nodes, H


def least_height(M, J, cap=None):
    """h(M, J) with a witness and the nodes it cost: route's first
    three."""
    return route(M, J, cap)[:3]


def exists_at_most(M, J, k, cap=None):
    """A nonzero vector of height <= k in the cell's lattice, or None."""
    b, d, lam = lll(basis(M, J))
    for v in b:
        if height(v) <= k:
            return v, 0
    s, v, nodes = enumerate_min(b, d, lam, M, k + 1, cap=cap, stop_at=k)
    return v, nodes


# ---------------------------------------------------------- pure products

def mul_part(p, e):
    """p * (x^e - 1)."""
    q = [0] * (len(p) + e)
    for i, c in enumerate(p):
        q[i] -= c
        q[i + e] += c
    return q


def pure_table(maxdeg):
    """Least height of a pure product per (part count, degree), with one
    witness multiset, over every multiset of degree sum <= maxdeg."""
    best = {}

    def walk(p, parts, total, last):
        if parts:
            key = (len(parts), total)
            hgt = height(p)
            if key not in best or hgt < best[key][0]:
                best[key] = (hgt, tuple(parts))
        for e in range(last, maxdeg - total + 1):
            parts.append(e)
            walk(mul_part(p, e), parts, total + e, e)
            parts.pop()

    walk([1], [], 0, 1)
    return best


def ph_of(table, M, J):
    """ph(M, J) and an attaining multiset, or (None, None)."""
    out = (None, None)
    for (cnt, deg), (hgt, parts) in table.items():
        if cnt >= J and deg < M and (out[0] is None or hgt < out[0]):
            out = (hgt, parts)
    return out


def least_pure_degree(J, k, cap_deg):
    """Least degree of a pure product of height <= k with exactly J
    parts, by the final-coefficient walk (hand attack (4)); None when
    none has degree <= cap_deg."""
    best = [cap_deg + 1, None]

    def walk(p, parts, total, last):
        if len(parts) == J:
            if height(p) <= k:
                best[0], best[1] = total, tuple(parts)
            return
        need = J - len(parts)
        for e in range(last, best[0]):
            if total + need * e >= best[0]:
                break
            q = mul_part(p, e)
            if max(abs(c) for c in q[:e]) > k:
                continue
            parts.append(e)
            walk(q, parts, total + e, e)
            parts.pop()

    walk([1], [], 0, 1)
    if best[1] is None:
        return None, None
    return best[0], best[1]


# ------------------------------------------------------ floor and the box

def prime_powers(limit):
    out = []
    for p in range(2, limit + 1):
        if all(p % q for q in range(2, isqrt(p) + 1)):
            q, e = p, 1
            while q <= limit:
                out.append((p, e, q, q - q // p))
                q *= p
                e += 1
    return out


def forces(p, J, ph, base):
    """p^J > base^ph, in floats, and in integers near a tie."""
    gap = J * log(p) - ph * log(base)
    if abs(gap) > 1e-9 * J * log(p):
        return gap > 0
    return p ** J > base ** ph


def cyclotomic_floor(J, k):
    """Least T with J + (sum of the forced phi(p^u)) <= T. Prime
    powers past 4 J^2 + 50 are not tried: a forced factor left out
    only lowers the floor."""
    pps = prime_powers(4 * J * J + 50)
    N = J
    while True:
        forced = sum(ph for (p, e, q, ph) in pps
                     if forces(p, J, ph, k * (N + 1)))
        if J + forced <= N:
            return N
        N += 1


def box_reach(M):
    """Largest J with 2^M > prod_{j<J} (C(M, j+1) + 1), 0 if none."""
    prod, J = 1, 0
    while J < M:
        nxt = prod * (comb(M, J + 1) + 1)
        if 2 ** M > nxt:
            prod, J = nxt, J + 1
        else:
            break
    return J


# ------------------------------------------------------ the cyclotomic split

def pdivmod(a, b):
    """Quotient and remainder of integer polynomials, b monic."""
    a = list(a)
    q = [0] * max(1, len(a) - len(b) + 1)
    for i in range(len(a) - len(b), -1, -1):
        c = a[i + len(b) - 1]
        q[i] = c
        if c:
            for j, bj in enumerate(b):
                a[i + j] -= c * bj
    while len(a) > 1 and a[-1] == 0:
        a.pop()
    return q, a


def phi(n, _memo={}):
    if n not in _memo:
        p = [-1] + [0] * (n - 1) + [1]
        for d in range(1, n):
            if n % d == 0:
                p, _ = pdivmod(p, phi(d))
        _memo[n] = p
    return _memo[n]


def totients(N, _memo=[[0]]):
    """Euler's totient of 0..N, sieved once and kept."""
    if len(_memo[0]) <= N:
        t = list(range(N + 1))
        for i in range(2, N + 1):
            if t[i] == i:
                for j in range(i, N + 1, i):
                    t[j] -= t[j] // i
        _memo[0] = t
    return _memo[0]


def cyclotomic_split(v):
    """{n: multiplicity of Phi_n} and the residual, sign-normalised to a
    positive leading coefficient, with any power of x removed. Every n
    with deg Phi_n = totient(n) <= deg p is tried: the degree is not
    monotone in n (Phi_6 after Phi_5), and totient(n) >= sqrt(n / 2)
    bounds n by 2 deg^2."""
    p = list(v)
    while p[0] == 0:
        p.pop(0)
    while p[-1] == 0:
        p.pop()
    mult = {}
    top = 2 * len(p) * len(p)
    tot = totients(top)
    for n in range(1, top + 1):
        if tot[n] >= len(p):
            continue
        f = phi(n)
        while len(f) <= len(p):
            q, r = pdivmod(p, f)
            if any(r):
                break
            p = q
            mult[n] = mult.get(n, 0) + 1
    if p[-1] < 0:
        p = [-c for c in p]
    return mult, p


# --------------------------------------------------------------- controls

def brute_h(M, J, kmax):
    """Least height <= kmax of a nonzero flattened-to-J vector over the
    box [-kmax, kmax]^M, leading entry positive; None if none."""
    from itertools import product
    best = None
    for v in product(range(-kmax, kmax + 1), repeat=M):
        nz = [c for c in v if c]
        if not nz or nz[-1] < 0:
            continue
        hv = max(abs(c) for c in v)
        if best is not None and hv >= best:
            continue
        if clears(list(v), J):
            best = hv
    return best


def coefficient_box(b, B):
    """Least height of a nonzero sum x_i b_i with every |x_i| <= B, by
    exhaustion: a search that shares only its basis with the
    enumeration and holds whatever its box holds."""
    from itertools import product
    best = None
    for x in product(range(-B, B + 1), repeat=len(b)):
        if any(x):
            hv = max(abs(sum(xi * row[t] for xi, row in zip(x, b)))
                     for t in range(len(b[0])))
            if best is None or hv < best:
                best = hv
    return best


# ------------------------------------------------- the reduction's own law

def gram_schmidt(b):
    """|b*_i|^2 and mu[i][j], j < i, in Fractions, by the definition."""
    dot = lambda u, v: sum(x * y for x, y in zip(u, v))
    star, sq = [], []
    mu = [[Fraction(0)] * len(b) for _ in b]
    for i, row in enumerate(b):
        v = [Fraction(x) for x in row]
        for j in range(i):
            mu[i][j] = dot(row, star[j]) / sq[j]
            v = [x - mu[i][j] * y for x, y in zip(v, star[j])]
        star.append(v)
        sq.append(dot(v, v))
    return sq, mu


def basis_law(B, J, b, d, lam):
    """(readings, held): what the enumeration rests on. The integers
    d and lam are the Gram-Schmidt data of the rows b themselves
    (d[i+1]/d[i] = |b*_i|^2, lam[i][j]/d[j+1] = mu[i][j], one reading
    each), every row is cleared J times, and
    d[n] is the input's Gram determinant, so the rows generate the
    input's lattice and not a sublattice."""
    n = len(b)
    sq, mu = gram_schmidt(b)
    held = 0
    for i in range(n):
        held += Fraction(d[i + 1], d[i]) == sq[i]
        held += clears(b[i], J)
        for j in range(i):
            held += Fraction(lam[i][j], d[j + 1]) == mu[i][j]
    det = Fraction(1)
    for s in gram_schmidt(B)[0]:
        det *= s
    held += d[n] == det
    return n * (n - 1) // 2 + 2 * n + 1, held


# ------------------------------------------------------------- the chart

BINS = ((2, 12), (13, 20), (21, 30))


def chart_cells():
    return [(M, J) for M in range(4, 41) for J in range(1, min(30, M - 1) + 1)]


def chart_row(table, M, J):
    """(h, ph, whether the route's witness is cleared J times, the
    reduced basis's own least height, the least height of a pure
    product of degree < M with exactly J parts)."""
    h, v, _, H = route(M, J)
    exact = min(hgt for (cnt, deg), (hgt, _) in table.items()
                if cnt == J and deg < M)
    return h, ph_of(table, M, J)[0], clears(v, J), H, exact


def failing(rows, cells):
    return [c for c in cells if rows[c][0] < rows[c][1]]


def brute_agree(rows, wmax, kmax):
    """(cells, agreeing, decided) over the cells of width <= wmax: the
    route's h against an exhaustion of [-kmax, kmax]^M, which decides
    h where h <= kmax and only that h > kmax elsewhere."""
    n = same = low = 0
    for (M, J) in sorted(rows):
        if M <= wmax:
            h = rows[(M, J)][0]
            n += 1
            low += h <= kmax
            same += brute_h(M, J, kmax) == (h if h <= kmax else None)
    return n, same, low


def box_cells(rows):
    """The cells the box principle reaches: J <= box_reach(M)."""
    return [(M, J) for M in sorted(set(c[0] for c in rows))
            for J in range(1, box_reach(M) + 1)]


def chart_record(rows):
    cells = sorted(rows)
    chart = [c for c in cells if c[1] >= 2]
    corner = [c for c in cells if c[0] <= 12]
    rank1 = [c for c in cells if c[0] - c[1] == 1]
    fl = failing(rows, chart)
    ranks = sorted(set(M - J for (M, J) in fl))
    reach = [box_reach(M) for M in sorted(set(c[0] for c in cells))]
    box = box_cells(rows)
    return {
        "cells, witnesses cleared J times, h at or below ph": (
            len(cells), sum(1 for c in cells if rows[c][2]),
            sum(1 for c in cells if rows[c][0] <= rows[c][1])),
        "cells where h is below the reduced basis's least height, "
        "of them at width <= 9": (
            sum(1 for c in cells if rows[c][0] < rows[c][3]),
            sum(1 for c in cells if rows[c][0] < rows[c][3]
                and c[0] <= 9)),
        "cells where a product of exactly J parts attains ph":
            sum(1 for c in cells if rows[c][4] == rows[c][1]),
        "exhaustion of [-3, 3]^M at width <= 6: cells, agreeing, "
        "with h <= 3": brute_agree(rows, 6, 3),
        "exhaustion of [-1, 1]^M at width <= 9: cells, agreeing, "
        "with h = 1": brute_agree(rows, 9, 1),
        "rank 1: cells, with h = ph = C(J, J // 2)": (
            len(rank1), sum(1 for (M, J) in rank1 if rows[(M, J)][0]
                            == rows[(M, J)][1] == comb(J, J // 2))),
        "corner: cells, with h < ph": (
            len(corner), len(failing(rows, corner))),
        "J >= 2: cells, with h < ph": (len(chart), len(fl)),
        "by depth, J = 2..12, 13..20, 21..30: cells, with h < ph":
            tuple((sum(1 for c in chart if lo <= c[1] <= hi),
                   sum(1 for c in fl if lo <= c[1] <= hi))
                  for lo, hi in BINS),
        "failing ranks: least, largest, how many": (
            ranks[0], ranks[-1], len(ranks)),
        "first failures by depth: M, J, h, ph": tuple(
            (M, J, rows[(M, J)][0], rows[(M, J)][1])
            for (M, J) in sorted(fl, key=lambda c: (c[1], c[0]))[:3]),
        "box: widths reaching depth 1, 2, 3; cells reached, with h = 1": (
            tuple(sum(1 for r in reach if r == depth)
                  for depth in (1, 2, 3)),
            len(box), sum(1 for c in box if rows[c][0] == 1)),
    }


def stage_chart():
    """The chart and its J = 1 column, M = 4..40, J = 1..min(30,
    M - 1): every cell through chart_row, then counted."""
    table = pure_table(39)
    return chart_record({c: chart_row(table, *c) for c in chart_cells()})


# --------------------------------------------------------------- the dial

OLD_TABLE = {
    1: [1, 3, 6, 11, 15, 22, 30, 41, 48, 61, 69],
    2: [1, 2, 4, 7, 11, 16, 22, 26, 34, 45, 51],
    3: [1, 2, 3, 5, 8, 11, 17, 20, 27, 33, 43],
    4: [1, 2, 3, 5, 8, 10, 14, 19, 22, 29, 34, 44],
    5: [1, 2, 3, 5, 6, 9, 14, 18, 22, 27, 30, 38, 46],
    6: [1, 2, 3, 4, 6, 9, 11, 16, 21, 23, 30, 36, 46],
    7: [1, 2, 3, 4, 6, 9, 11, 15, 20, 23, 25, 32, 37, 49],
    8: [1, 2, 3, 4, 6, 9, 11, 15, 19, 23, 25, 31, 37, 47],
}

BREAK_PARTS = (1, 1, 1, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 5, 7)
BREAK_R = (2, 3, 3, 3, 4, 5, 4, 3, 3, 3, 2)


def traded(parts, factor):
    """factor times the pure product with these parts."""
    p = list(factor)
    for g in parts:
        p = mul_part(p, g)
    return p


def same_up_to_sign(v, w):
    return list(v) == list(w) or list(v) == [-c for c in w]


def one_up(dp, J, k, cap):
    """Whether the decision route, run one width up, where the pure
    product of degree dp sits, finds a vector of height <= k
    flattened to J."""
    try:
        w, _ = exists_at_most(dp + 1, J, k, cap=cap)
    except NodeCap:
        return False
    return w is not None and height(w) <= k and clears(w, J)


def step_down(v, width, J, k, cap):
    """From a width holding v, of height <= k and flattened to J, down
    a width at a time to the last that holds such a vector: (that
    width, its vector). No handler: a capped step ends the run."""
    while True:
        w, _ = exists_at_most(width - 1, J, k, cap=cap)
        if w is None:
            return width, v
        v, width = w, width - 1


def dial_row(k, J, cap):
    """(least pure degree dp, its parts, verdict, d_k(J), floor, one
    width up, witness). The lattice at width dp decides whether
    anything of height <= k has degree below dp: nothing ("pure", the
    pure law, d = dp), something ("break", stepped down a width at a
    time to the exact d), or the node cap met first ("capped", dp an
    upper bound only). At dp = J the lattice below has rank 0."""
    dp, parts = least_pure_degree(J, k, 400)
    v = None
    if dp > J:
        try:
            v, _ = exists_at_most(dp, J, k, cap=cap)
        except NodeCap:
            return dp, parts, "capped", None, None, None, None
    up = one_up(dp, J, k, cap)
    if v is None:
        return dp, parts, "pure", dp, cyclotomic_floor(J, k), up, None
    width, v = step_down(v, dp, J, k, cap)
    return dp, parts, "break", width - 1, cyclotomic_floor(J, k), up, v


def dial_cells(jmax):
    """The older table's cells, and each column on to depth jmax."""
    return [(k, J) for k in sorted(OLD_TABLE)
            for J in range(1, max(len(OLD_TABLE[k]), jmax) + 1)]


def dial_record(rows):
    cells = sorted(rows)
    table = [c for c in cells if c[1] <= len(OLD_TABLE[c[0]])]
    past = [c for c in cells if c[1] > len(OLD_TABLE[c[0]])]
    decided = [c for c in cells if rows[c][2] != "capped"]
    ties = [c for c in table if c in decided
            and rows[c][4] == rows[c][3]]
    product = traded(BREAK_PARTS, BREAK_R)
    return {
        "table: cells, pure, at the older table's value": (
            len(table), sum(1 for c in table if rows[c][2] == "pure"),
            sum(1 for (k, J) in table
                if rows[(k, J)][0] == OLD_TABLE[k][J - 1])),
        "one width up: cells decided, found": (
            len(decided), sum(1 for c in decided if rows[c][5])),
        "floor: at or below d; equal on the table, the deepest such; "
        "at k = 1, J = 11": (
            sum(1 for c in decided if rows[c][4] <= rows[c][3]),
            len(ties), max(J for (k, J) in ties), rows[(1, 11)][4]),
        "past the table, pure: k, J, d": tuple(
            (k, J, rows[(k, J)][3]) for (k, J) in past
            if rows[(k, J)][2] == "pure"),
        "past the table, capped: k, J, least pure degree": tuple(
            (k, J, rows[(k, J)][0]) for (k, J) in past
            if rows[(k, J)][2] == "capped"),
        "breaks: k, J, d, least pure degree, the traded product": tuple(
            (k, J, rows[(k, J)][3], rows[(k, J)][0],
             same_up_to_sign(rows[(k, J)][6], product))
            for (k, J) in cells if rows[(k, J)][2] == "break"),
    }


def stage_dial(cap, jmax):
    """Every cell of dial_cells(jmax) through dial_row, then counted."""
    rows = {c: dial_row(c[0], c[1], cap) for c in dial_cells(jmax)}
    return rows, dial_record(rows)


def stage_break(cap):
    """The dial's break at k = 8, J = 15, decided on its own through
    dial_row, the one cell of the bare run where its verdict is not
    "pure": the walk's least 15-part degree dp, a vector of height
    <= 8 below it, the step down to nothing a degree lower. Then
    nothing of height <= 8 flattened to 16 below degree dp, which
    covers every product with more parts."""
    k, J = 8, 15
    dp, parts, verdict, d, floor, up, v = dial_row(k, J, cap)
    deeper, _ = exists_at_most(dp, J + 1, k, cap=cap)
    mult, res = cyclotomic_split(v)
    return {
        "the least 15-part pure degree at height <= 8, its parts": (
            dp, parts),
        "the row's verdict, d, the floor at or below it, one width up":
            (verdict, d, floor <= d, up),
        "the witness: its height, cleared 15 times, the traded product":
            (height(v), clears(v, J),
             same_up_to_sign(v, traded(BREAK_PARTS, BREAK_R))),
        "nothing flattened to 16 below the pure degree": deeper is None,
        "the witness's cyclotomic factors and its residual": (
            tuple(sorted(mult.items())), tuple(res)),
    }


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

EXTEND_CAPPED = (
    (1, 12, 93), (1, 13, 112), (1, 14, 120), (1, 15, 141), (1, 16, 159),
    (2, 12, 65), (2, 14, 89), (2, 16, 118), (3, 13, 65), (3, 14, 73),
    (3, 15, 80), (6, 16, 71), (8, 16, 63))

RECORD = {
    "chart": {
        "cells, witnesses cleared J times, h at or below ph":
            (732, 732, 732),
        "cells where h is below the reduced basis's least height, "
        "of them at width <= 9": (36, 0),
        "cells where a product of exactly J parts attains ph": 732,
        "exhaustion of [-3, 3]^M at width <= 6: cells, agreeing, "
        "with h <= 3": (12, 12, 10),
        "exhaustion of [-1, 1]^M at width <= 9: cells, agreeing, "
        "with h = 1": (33, 33, 15),
        "rank 1: cells, with h = ph = C(J, J // 2)": (28, 28),
        "corner: cells, with h < ph": (63, 0),
        "J >= 2: cells, with h < ph": (695, 83),
        "by depth, J = 2..12, 13..20, 21..30: cells, with h < ph":
            ((362, 3), (188, 17), (145, 63)),
        "failing ranks: least, largest, how many": (5, 18, 14),
        "first failures by depth: M, J, h, ph":
            ((23, 10, 9, 10), (21, 12, 39, 44), (25, 12, 25, 28)),
        "box: widths reaching depth 1, 2, 3; cells reached, with h = 1":
            ((5, 15, 17), 86, 86),
    },
    "dial": {
        "table: cells, pure, at the older table's value": (99, 99, 99),
        "one width up: cells decided, found": (99, 99),
        "floor: at or below d; equal on the table, the deepest such; "
        "at k = 1, J = 11": (99, 27, 5, 26),
        "past the table, pure: k, J, d": (),
        "past the table, capped: k, J, least pure degree": (),
        "breaks: k, J, d, least pure degree, the traded product": (),
    },
    "break": {
        "the least 15-part pure degree at height <= 8, its parts":
            (56, (1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 5, 6, 7, 9)),
        "the row's verdict, d, the floor at or below it, one width up":
            ("break", 55, True, True),
        "the witness: its height, cleared 15 times, the traded product":
            (8, True, True),
        "nothing flattened to 16 below the pure degree": True,
        "the witness's cyclotomic factors and its residual": (
            ((1, 15), (2, 4), (3, 2), (4, 2), (5, 3), (7, 1)),
            (2, 3, 3, 3, 4, 5, 4, 3, 3, 3, 2)),
    },
    "extend": {
        "table: cells, pure, at the older table's value": (99, 99, 99),
        "one width up: cells decided, found": (115, 115),
        "floor: at or below d; equal on the table, the deepest such; "
        "at k = 1, J = 11": (115, 27, 5, 26),
        "past the table, pure: k, J, d": (
            (2, 13, 74), (2, 15, 95), (3, 12, 52), (3, 16, 87),
            (4, 13, 52), (4, 14, 60), (4, 15, 70), (4, 16, 78),
            (5, 14, 55), (5, 15, 64), (5, 16, 71), (6, 14, 52),
            (6, 15, 60), (7, 15, 56), (7, 16, 64)),
        "past the table, capped: k, J, least pure degree": EXTEND_CAPPED,
        "breaks: k, J, d, least pure degree, the traded product": (
            (8, 15, 55, 56, True),),
    },
}

CONTROL_LINES = 15
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 want:
        ok = got[key] == want[key]
        check(f"{stage}: {key}", ok,
              f"{got[key]}" + ("" if ok else f", recorded {want[key]}"))


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


def section_controls():
    section("CONTROLS: each helper on its own, before any stage")
    check_hand("pow_xm1 and clears", [
        (pow_xm1(3), [-1, 3, -3, 1]),
        (clears([1, -1, -1, 1], 2), True),
        (clears([1, -1, -1, 1], 3), False),
        (clears([1, 2], 0), True),
        (clears([1, 2], 1), False)])
    t3 = pure_table(3)
    check_hand("mul_part, pure_table and ph_of", [
        (mul_part([1], 2), [-1, 0, 1]),
        (mul_part([-1, 1], 2), [1, -1, -1, 1]),
        ({key: hgt for key, (hgt, _) in t3.items()},
         {(1, 1): 1, (1, 2): 1, (1, 3): 1, (2, 2): 2, (2, 3): 1,
          (3, 3): 3}),
        (ph_of(t3, 4, 2), (1, (1, 2))),
        (ph_of(t3, 3, 2), (2, (1, 1))),
        (ph_of(t3, 4, 3), (3, (1, 1, 1))),
        (ph_of(t3, 3, 3), (None, None))])
    check_hand("least_pure_degree", [
        (least_pure_degree(2, 1, 400), (3, (1, 2))),
        (least_pure_degree(3, 1, 400), (6, (1, 2, 3))),
        (least_pure_degree(3, 2, 400), (4, (1, 1, 2))),
        (least_pure_degree(3, 3, 400), (3, (1, 1, 1))),
        (least_pure_degree(2, 1, 3), (3, (1, 2))),
        (least_pure_degree(2, 1, 2), (None, None))])

    B = basis(4, 2)
    red = [[1, -1, -1, 1], [1, -2, 1, 0]]
    sub = [[1, -1, -1, 1], [1, -3, 3, -1]]
    laws = [basis_law(basis(M, J), J, *lll(basis(M, J)))
            for (M, J) in ((4, 2), (9, 3), (12, 5), (20, 8), (30, 21))]
    check_hand("lll on the hand cell, its law at five cells, and the "
               "law's three plants", [
        (lll(B), (red, [1, 4, 20], [[0, 0], [2, 0]])),
        ([n for n, _ in laws], [6, 28, 36, 91, 55]),
        ([held for _, held in laws], [6, 28, 36, 91, 55]),
        (basis_law(B, 2, red, [1, 4, 20], [[0, 0], [3, 0]]), (6, 5)),
        (basis_law(B, 3, red, [1, 4, 20], [[0, 0], [2, 0]]), (6, 4)),
        (basis_law(B, 2, sub, [1, 4, 80], [[0, 0], [0, 0]]), (6, 5))])

    U = [[3, -1, 1, 1], [-1, 3, 1, 1]]
    W = [[1, -3, -1, -1, -1, -1, -1, -1, -1], [3, -1, 1, 1, 1, 1, 1, 1, 1]]

    def least_in(rows, s0):
        """Whether lll leaves the rows as given, the enumeration's
        least height below s0, whether its vector is flat at 2."""
        b, d, lam = lll(rows)
        s, v, _ = enumerate_min(b, d, lam, len(rows[0]), s0)
        return b == rows, s, same_up_to_sign(v, [2] * len(rows[0]))
    b, d, lam = lll(U)
    two = [2, 2, 2, 2]
    check_hand("the enumeration where no basis vector is least", [
        (b, U),
        (basis_law(U, 0, b, d, lam), (6, 6)),
        (enumerate_min(b, d, lam, 4, 3)[0], 2),
        (same_up_to_sign(enumerate_min(b, d, lam, 4, 3)[1], two), True),
        (enumerate_min(b, d, lam, 4, 2)[:2], (None, None)),
        (enumerate_min(b, d, lam, 4, 4)[0], 2),
        (enumerate_min(b, d, lam, 4, 4, stop_at=3)[0], 3),
        (enumerate_min(b, d, lam, 4, 4, stop_at=2)[0], 2)] + [
        (least_in([[sign * c for c in first], second], 3),
         (True, 2, True))
        for first, second in ((U[0], U[1]), (W[0], W[1]))
        for sign in (1, -1)])
    check_hand("the route against a box of coefficients, where the "
               "reduced basis is not least", [
        (coefficient_box(U, 1), 2),
        (least_height(4, 2)[:2], (1, [1, -1, -1, 1])),
        (len(least_height(4, 2)), 3)] + [
        ((route(M, J)[0::3], coefficient_box(lll(basis(M, J))[0], 1)),
         ((h, H), h))
        for (M, J, h, H) in ((17, 10, 23, 24), (18, 11, 33, 44),
                             (22, 13, 67, 76))])

    check_hand("prime_powers, forces at a tie, cyclotomic_floor", [
        (prime_powers(7), [(2, 1, 2, 1), (2, 2, 4, 2), (3, 1, 3, 2),
                           (5, 1, 5, 4), (7, 1, 7, 6)]),
        (prime_powers(9), prime_powers(10)),
        (prime_powers(10), [(2, 1, 2, 1), (2, 2, 4, 2), (2, 3, 8, 4),
                            (3, 1, 3, 2), (3, 2, 9, 6), (5, 1, 5, 4),
                            (7, 1, 7, 6)]),
        (forces(3, 10, 2, 243), False),
        (forces(3, 10, 2, 242), True),
        (forces(3, 10, 2, 244), False),
        (cyclotomic_floor(1, 1), 1),
        (cyclotomic_floor(2, 1), 3),
        (cyclotomic_floor(3, 1), 5)])
    gap = 10 * log(3) - 2 * log(243)
    check("the tie 3^10 = 243^2 is one the floats misread",
          gap > 0, f"the float gap {gap:.3e}")
    check_hand("box_reach", [
        (box_reach(4), 1), (box_reach(8), 1), (box_reach(9), 2),
        (box_reach(23), 2), (box_reach(24), 3),
        (box_reach(1), 0), (box_reach(2), 1)])

    def times(a, c):
        out = [0] * (len(a) + len(c) - 1)
        for i, x in enumerate(a):
            for j, y in enumerate(c):
                out[i + j] += x * y
        return out
    BQ = [2, 3, 2]
    check_hand("phi and cyclotomic_split", [
        ([phi(n) for n in (1, 2, 3, 4, 6, 12, 30)],
         [[-1, 1], [1, 1], [1, 1, 1], [1, 0, 1], [1, -1, 1],
          [1, 0, -1, 0, 1], [1, 1, 0, -1, -1, -1, 0, 1, 1]]),
        (cyclotomic_split(phi(30)), ({30: 1}, [1])),
        (cyclotomic_split([0, -1, -2, 1, 2]), ({1: 1, 2: 1}, [1, 2])),
        (cyclotomic_split([-1, 2, -1]), ({1: 2}, [1])),
        (cyclotomic_split([-1, 2, -1, 0]), ({1: 2}, [1])),
        (cyclotomic_split(times([1, 2], phi(6))), ({6: 1}, [1, 2])),
        (cyclotomic_split(times(BQ, phi(14))), ({14: 1}, BQ)),
        (cyclotomic_split(times(BQ, phi(22))), ({22: 1}, BQ)),
        (cyclotomic_split(phi(22)), ({22: 1}, [1]))])
    check_hand("brute_h, the exhaustion", [
        (brute_h(3, 2, 3), 2), (brute_h(4, 3, 3), 3),
        (brute_h(4, 2, 3), 1), (brute_h(5, 4, 3), None)])
    P = traded(BREAK_PARTS, BREAK_R)
    check_hand("the break's witness by arithmetic: width, height, "
               "cleared 15 times and not 16", [
        (len(BREAK_PARTS), 15), (len(P), 56), (height(P), 8),
        (clears(P, 15), True), (clears(P, 16), False)])

    low = step_down(exists_at_most(6, 2, 1)[0], 6, 2, 1, None)
    check_hand("one_up, dial_row and step_down", [
        (one_up(3, 2, 1, None), True),
        (one_up(2, 2, 1, None), False),
        (one_up(16, 10, 23, None), True),
        (one_up(16, 10, 22, None), False),
        (one_up(16, 10, 23, 0), False),
        (dial_row(1, 1, None), (1, (1,), "pure", 1, 1, True, None)),
        (dial_row(1, 2, None), (3, (1, 2), "pure", 3, 3, True, None)),
        (dial_row(1, 2, 0),
         (3, (1, 2), "capped", None, None, None, None)),
        ((low[0], same_up_to_sign(low[1], [1, -1, -1, 1])), (4, True))])

    one = (1, 1, True, 1, 1)
    hand = {(4, 1): one, (4, 2): (2, 1, True, 2, 1),
            (4, 3): (3, 3, True, 3, 3), (5, 1): one,
            (5, 4): (4, 6, True, 4, 4), (9, 1): one,
            (9, 2): (2, 3, False, 3, 2), (10, 1): one,
            (10, 2): (1, 2, True, 1, 2), (10, 5): (2, 3, True, 4, 3),
            (25, 1): one, (25, 2): one, (25, 3): one,
            (25, 14): (5, 7, True, 5, 7)}
    got = chart_record(hand)
    check_hand("chart_record on fourteen rows written by hand", [
        (got[key], want) for key, want in zip(RECORD["chart"], (
            (14, 13, 13), (2, 1), 12, (5, 4, 4), (7, 5, 3), (2, 1),
            (10, 4), (9, 5), ((8, 4), (1, 1), (0, 0)), (1, 11, 5),
            ((9, 2, 2, 3), (10, 2, 1, 2), (5, 4, 4, 6)),
            ((2, 2, 1), 9, 8)), strict=True)])

    rows = {(k, J): (t, None, "pure", t, t - 1, True, None)
            for k, col in OLD_TABLE.items()
            for J, t in enumerate(col, 1)}
    rows.update({
        (1, 1): (1, None, "pure", 1, 1, True, None),
        (2, 3): (4, None, "pure", 4, 4, True, None),
        (3, 5): (8, None, "capped", None, None, None, None),
        (4, 7): (15, None, "pure", 15, 14, True, None),
        (5, 9): (22, None, "pure", 22, 23, True, None),
        (6, 2): (2, None, "pure", 2, 1, False, None),
        (7, 4): (4, None, "break", 3, 2, True, [1]),
        (1, 12): (93, None, "capped", None, None, None, None),
        (3, 12): (65, None, "capped", None, None, None, None),
        (2, 12): (65, None, "pure", 65, 60, True, None)})
    got = dial_record(rows)
    check_hand("dial_record on the older table with ten rows "
               "written by hand", [
        (got[key], want) for key, want in zip(RECORD["dial"], (
            (99, 97, 98), (99, 98), (98, 2, 3, 68), ((2, 12, 65),),
            ((1, 12, 93), (3, 12, 65)), ((7, 4, 3, 4, False),)),
            strict=True)])


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


def main(argv):
    t_all = time.time()
    stages = argv or ["chart", "dial", "break"]
    unknown = [s for s in stages if s not in RECORD]
    if unknown:
        print("unknown stage: %s" % " ".join(unknown))
        sys.exit(2)
    section_controls()
    if not all(CHECKS):
        print("\nCONTROL FAILED: nothing below is read.")
        sys.exit(1)
    lines = CONTROL_LINES + sum(len(RECORD[s]) for s in stages)
    if "chart" in stages:
        t0 = time.time()
        section_stage("chart", "THE CHART: M = 4..40, J = 1..min(30, "
                      "M - 1)", stage_chart(), t0)
    if "dial" in stages:
        t0 = time.time()
        rows, got = stage_dial(cap=20000000, jmax=0)
        section_stage("dial", "THE DIAL: the older table's cells",
                      got, t0)
        section_table(rows)
    if "break" in stages:
        t0 = time.time()
        section_stage("break", "THE BREAK: k = 8, J = 15, on its own",
                      stage_break(cap=200000000), t0)
    if "extend" in stages:
        t0 = time.time()
        rows, got = stage_dial(cap=20000000, jmax=16)
        section_stage("extend", "THE EXTENSION: each column on to "
                      "J = 16", got, t0)
        section_table(rows)
    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)


def section_table(rows):
    """d_k(J) by column: a value, a capped cell's upper bound with a
    question mark, a break as d<dp."""
    for k in sorted(OLD_TABLE):
        out = []
        for (kk, J) in sorted(rows):
            if kk == k:
                dp, _, verdict, d = rows[(kk, J)][:4]
                out.append("%d?" % dp if verdict == "capped" else
                           "%d<%d" % (d, dp) if verdict == "break"
                           else "%d" % d)
        print("  k=%d: %s" % (k, " ".join(out)))
    print("  the least of the older table's last entries, a column: %d"
          % min(col[-1] for col in OLD_TABLE.values()))


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