casetree.py

Checks: BONACCI: The carry bound rule.

Cited on: BONACCI.

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

"""casetree.py -- the carry bound at d = 11 and 20, where the real
support misses it, by a tree of integer cases on neighbouring carries,
each leaf closed by one rational combination of the real support's
rows, checked exactly.

QUESTION. At d = 11 and 20 (C_d + 1 = 3 and 5), is x_t <= C_d and s_t =
x_t - delta_t <= C_d at every t, for every bounded integer x with delta
in {-1, 0, 1} and first window sum 0? real_support.py's sups pass C_d +
1 there (3.04 and 5.03), so the carries' integrality is put back: a
finite tree whose nodes fix the carries x_u at a few u near t to
integers, each leaf closed by one rational combination of the real
support's rows, read in integers.

BY HAND.
(S) Soundness. real_support.py's (a): x_u = g^(u) . delta, |delta_k| <=
1, g^(u) in l^1. Let f = g^(t) (the carry) or g^(t) - e_t (the window
sum), and suppose x_(u_i) = n_i at times u_i >= 0, i = 1..m. For any
reals lam_i,
    f . delta = (f + sum lam_i g^(u_i)) . delta - sum lam_i n_i
             <= ||f + sum lam_i g^(u_i)||_1 - sum lam_i n_i.
If the right side is below X = C_d + 1, no such path has f . delta >= X,
and f . delta is an integer, so it is at most C_d. Nothing is asked of
lam: a float optimizer proposes it, the check is exact. Only |delta| <=
1 and the integrality of the m fixed carries are used. The lower side
is the upper's under x -> -x, which keeps every hypothesis.
(C) Cases. |x_u| <= H_x, so a carry takes one of the integers -N..N, N
= floor(the upper end of H_x), from real_support's record.
(V) The verdict is the list's. A list of nodes is a COVER at N when it
is the root alone, or its nodes all begin with one offset j, their
first values are exactly -N..N, and the tails under each value are a
cover.
If an arm's leaves are a cover and (S)'s bound is below X at each, then
on any path every carry named along a branch takes one of its values
(C), so the path lies in a leaf, which (S) refutes. Nothing is asked of
how the list was found: the search only proposes it.
(A) Absolute rows, t < T and u_i < T + J. With gh and tau of
real_support's (c),
    ||f + sum lam_i g^(u_i)||_1 <= ||fh + sum lam_i gh^(u_i)||_1
                                   + tau_t + sum |lam_i| tau_(u_i),
fh = gh^(t) or gh^(t) - e_t. lam_i = a_i/2^24: integers over 2^(62+24).
(T) Every t >= T at once, u_i = t + j_i, J- = max(0, -min j_i) <= T.
g^(t+j)_k = h_(k-t-j) - eps_(t+j) h_(k+1), so over k >= 0
    ||f + sum lam_i g^(t+j_i)||_1
      <= ||h [- e_0] + sum lam_i h_(. - j_i)||_(l^1(Z))
         + (eps_t + sum |lam_i| eps_(t+j_i)) L
      <= ||hh [- e_0] + sum lam_i hh_(. - j_i)||_1 + (1 + sum |lam_i|)
         (eta + top_(T - J-) (||hh||_1 + eta)),
eps falling in t, top_s an upper end of eps_s, and L <= ||hh||_1 + eta.
(W) Where it must refuse. The wave at d = 13 (x = 0 1 2 3 2 1 0 -1 -2
-3 -2 -1, period 12, delta_k = x_k - x_(k+1), first window sum x_0 = 0)
has x_t = 3 at t = 3 + 12i and s_t = x_(t+1) = 3 at t = 2 + 12i. On the
node that fixes its own values, (S)'s right side is at least f . delta =
3 for every lam: at target 3 no lam closes it. The same at d = 11,
target 2 (x = 0 1 2 2 1 0 -1 -2 -2 -1, x_2 = 2), and at d = 2, target 1:
x = e_2 has delta = (-1, -1, 1, 0, ...), first window sum 0, x_2 = 1,
its neighbours 0.
(Y) The checker's hand rows: f = (3, -1, 2), g = (1, 1, -2), n = 1. The
bound at lam = 0, 1/2, 1, 2 is 6, 9/2, 3, 6; with n = 0 at lam = 1, 4.
With an error term 1/8 on f and 1/4 on g: 19/4 at lam = 1/2 and 31/4 at
lam = -1/2 (||(5/2, -3/2, 3)||_1 = 7). With a second row g2 = (0, 1,
0), n = (1, -1), terms (1/4, 1/2) and 1/8, lam = (1, 1/2): f + g + g2/2
= (4, 1/2, 0), so 9/2 + 1/8 + 1/2 - 1/2 = 37/8 (38/8 with the terms
swapped, 45/8 with the n), and the same with every vector doubled at
unit 2.
(G) Hand arms, unit 1, no error term, N = 1. toy: f = (3, -1, 2), its
one offset 1 the row g. ||f + lam g||_1 - n lam is 6 - (2 + n) lam on
[-3, 1] and (4 - n) lam past 1, least at lam = 1 alone: 3, 4, 5 at n =
1, 0, -1; the root's bound is 6. So the growth at X = 6 leaves the root
open and closes the three cases in the order popped (1, 0, -1), 4
nodes; at X = 5 the case -1 meets the bar and stays open with no offset
left ("spent"); at X = 7 the root closes alone; under a cap of 3 the
fourth node passes it. The X = 6 list read at X = 4, 5, 6 is a cover
with 1, 2, 3 of 3 closed, proved at 6 alone, least margin 1, deepest 1
(the bar met with equality at 4 and at 5). early: f = (3, 1, 2), the
same row; ||f + lam g||_1 is 6 on [-1, 1], 4 - 2 lam below, 4 lam + 2
above, so toy's leaves (lam = 1) read 5, 6, 7 there. Carried over at X
= 7: two kept, the case -1
regrown from its node, where ||.|| + lam is least at lam = -1 alone (5):
one node. At X = 6 the case 0 reads 6 at every lam, its regrowth stays
open, and the arm is grown from the root: the root open, the case 1
closed (5, at lam = 1), the case 0 open, 1 + 3 nodes, not a cover.
blind: toy's f with the one offset 2, row (0, 1, 0): toy's leaves name
a carry it lacks, so it is grown from the root, which closes at X = 7;
toy's own list reads 0 closed there.
(P) Why a shallow tree was expected, a TRANSPLANT from the periodic
picture: over the reals a P-periodic zigzag of steps +-1 and mean 0 at
even P = 10 takes the values +-1/2, +-3/2, +-5/2, so the real optimum's
neighbours sit near half-integers.

ENGINE. grow: depth-first; at a node an LP in floats (min over lam of
||f + G lam||_1 - n . lam, |lam| <= 64) proposes lam, rounded to 2^-24;
the exact bound decides; an open node branches on the arm's next offset
in the order 0 (the sum alone), 1, -1, 2, -2, ..., 8, -8, all 2N + 1
cases. The tree is grown once a kind, at t >= T = 40. carry_over reads
its leaves at each t < 40 with their own lam: a leaf that closes there
is kept, one that does not is regrown from its node, and where a leaf
names a carry before time 0, or a regrowth stays open, the arm is grown
from the root, as is every earlier arm where the tree of t >= 40 stays
open. verify then reads each arm's list alone: (V). Rows from
real_support.certificate; a row before time 0 raises.

ARMS. d = 11 at target 3 and d = 20 at target 5: t >= 40 and every t <
40, carry and sum, 82 arms a d. A record a d (tree): the arms proved,
N, real_support's C_d, and the proposer's figures (the leaves at t >=
40 and in all, the most in an arm, the deepest, the least margin, the
arms carried whole, with a leaf regrown, grown from the root), which
no check reads at d = 11 and 20, the carrying-over's predictions and
KILL with them: they are this run's, the lists coming from a float
transform and a float LP, and under another library the checks read
whatever lists that run grows.

CONTROLS, read first; a failure stops the run before any tree of d =
11 or 20. (Y)'s nine bounds from
the checker; the proposer's least 3 at lam 1 on (Y); nine hand lists,
a cover or not (the root alone, no node, three cases, one missing, a
value outside, a case grown, siblings on two offsets, a leaf beside its
extension, a case twice); (G)'s eight runs of grow, verify and
carry_over, value for value; at d = 13 the carry arm's rows at offset 0
and at each offset of its order, and the sum arm's form, dotted with
the wave's delta, within tau or eta of the wave's own carry there (the
sum's: the next carry), at t = 4 and at t >= 40 from phase 4, 32 forms;
at d = 13 each arm's bound at the root equal to real_support's upper
end at its t (80 rows) and the largest of each kind's 41 equal to the
record's upper ends of H_x and H_s (a row's at d = 13, so the root of t
>= 40 is read by the next line alone); the error terms at four hand nodes
of d = 13, their indices by hand (t = 4 with offsets 1, -1, 2: tau_4
and tau_5, tau_3, tau_6; t >= 40 with 1, -3, 2: top_37; the sum's with
1, 2: top_40; no offset: top_40); which carries seven hand nodes name
exist (at t = 4 the offset -4 and not -5; -8 at t >= 40; the offset 0
for the sum alone, at t = 4 and at t >= 40); (W)'s refusals, the
checker on each known path's own node at
every depth 1..8 of the order, lam the proposer's and lam = 0, 112
bounds each at least its target; at d = 13, target 3, the wave's four
arms unproved (t >= 40, carry and sum; t = 3, carry; t = 2, sum; the
sum at 3 and the carry at 2 are grown beside them, their answer not
known); at d = 13, target 4, which real_support proves, every arm
proved at the root (82 leaves, one an arm), 80 carried whole, the least
margin 4 less the larger of the record's upper ends. The hand controls
(the first four) stop the run before a real row is read. And a known
answer at depth: d = 5 and d = 6 at target 2, where C_d = 1 is the pair
graph's and a root is open (the larger sup 2.06 and 2.18; at d = 5 the
sum's alone), every arm proved.

The block below was fixed before the engine's first run, on a first
form that searched every arm apart, at the four d the real support
leaves open (the times t >= 40, 0 and 20 alone at d = 12 and 16); it
stands word for word. Changed since, each named: its line "closed"
now prints "proved"; K3 counts the wave's four arms; K4 is read at d
= 5 and 6, in the bare run; K5 is the root's weld by value, at d = 13
alone, d = 9 and 10 gone with its arm; d = 12 and 16 left the bare run
when the KILL fired there.

FROZEN.
  T = 40 (real_support's), offsets |j| <= 8 (j = 0 for the sum alone),
  cap 5000 nodes an arm. Arms a d: every t < 40 and t >= 40, carry and
  sum, 82.
  CONTROL, read first, a failure stops the run:
   K1 (Y)'s four bounds from the exact checker, and the proposer's
      least within 1e-6 of 3 at lam within 1e-6 of 1.
   K2 refusals, the checker on the wave's own node at every depth 1..8
      of the search's order, lam the proposer's and lam = 0: d = 13
      target 3 at t = 3 carry, t = 2 sum, t >= 40 carry and sum; d = 11
      target 2 at t = 2 carry and t >= 40 carry (t = 42); d = 2 target 1
      at t = 2. Every exact bound >= the target: a count of refusals
      against the nodes tried, none closed.
   K3 the search itself at d = 13 target 3 on those four arms: OPEN at
      the cap or exhausted with an open leaf, never CLOSED.
   K4 power, a known answer through the same filter: d = 5..8 (C_d = 1;
      the pair graph's cube, in integers, with delta free), every arm
      CLOSED at target 2. A miss here reads the instrument's cost at
      slack 0.06..0.49, not its soundness.
   K5 d = 9, 10, 13 at their own targets (the first route proves them):
      every arm closed at the root, no branching.
  PREDICTIONS.
   Q1 N = C_d + 1 at d = 11, 12, 16, 20.
   Q2 every arm of the four d CLOSED.
   Q3 (TRANSPLANT (P)) depth at most 2 at d = 11 and 20 (missed by 0.04
      and 0.03), at most 6 at d = 16 and 12 (0.11, 0.24); under 1000
      leaves in any arm.
   Q4 the whole under 600 s and 512 MB.
  KILL of the route at d: the line "TREE d = <d>: A of 82 arms closed"
  at A < 82 for d in 11, 12, 16, 20; then integral.py keeps HiGHS at
  that d and the tier line says observation there. KILL of the
  instrument: K2 or K3 closing anything.
Fixed before this form's first run: every arm of d = 11 and of d = 20 a
cover with every leaf closed (seen on the first form); (TRANSPLANT from
an unrecorded read) the tree of t >= 40 carried whole at every t =
11..39, at most 12 arms a d regrowing a leaf, an arm grown from the
root only at t < 8; the two trees under 200 s. Fixed after that run and
before its own: d = 5 and 6 proved at target 2 (seen on the first
form).
KILL of the carrying-over: an arm proved only from the root at t >= 8.

FINDINGS (copied from the runs' prints).
  - The controls hold: the nine bounds; the proposer's least
    3.000000000 at 1.000000000; 9 of 9 lists; 8 of 8 hand runs; 32 of
    32 forms; 80 of 80 rows and both sups; 4 of 4 nodes' terms; the
    seven nodes read as by hand; 112 of 112 refused, the least bounds
    3.354985374, 3.000000147, 3.366105350, 3.000000002 (d = 13),
    2.864054879, 2.831179662 (d = 11) and 1.000000614 (d = 2); at d =
    13, target 3, the wave's 4 of 4 arms unproved, 6 of the 6 grown; at
    target 4, 82 of 82 at the root, margin 0.543819; 82 of 82 at d = 5
    (deepest 3, leaves at t >= 40 [1, 7]) and at d = 6 (deepest 5, [29,
    29]), target 2.
  - The route holds at d = 11 and d = 20, its KILL missing there:
    "TREE d = 11: 82 of 82 arms proved  target 3  N 3  leaves at t >=
    40 [43, 43]  in all 3364  most in an arm 49  deepest 5  least
    margin 7.089e-06  carried whole 74  a leaf regrown 2  from the root
    4" and "TREE d = 20: 82 of 82 arms proved  target 5  N 5  leaves at
    t >= 40 [111, 111]  in all 9592  most in an arm 311  deepest 7
    least margin 2.967e-04  carried whole 65  a leaf regrown 11  from
    the root 4". With real_support's (a) and certificate and (S), (C),
    (V), (A), (T) above, x_t <= C_d and s_t <= C_d at every t at d = 11
    and 20, in exact arithmetic, the float LP only proposing.
  - The carrying-over holds, its KILL missing: a leaf is regrown at t =
    4, 5 (the carry) at d = 11 and at t = 6..10 (the carry) and 5..10
    (the sum) at d = 20; an arm is grown from the root at t = 0, 1
    alone, both kinds; every other arm is the tree of t >= 40 with its
    own lam.
  - On the first form, which no entry point of this script reproduces:
    the KILL fired at d = 12 and d = 16, "TREE d = 12: 2 of 6 arms
    closed" and "TREE d = 16: 2 of 6 arms closed", the arms t >= 40 and
    t = 20 each open with every offset fixed and the proposer's lam not
    closing, t = 0's two closed at the root; and at target 2 it closed
    82 of 82 arms at d = 5 and 6 and 2 of 82 at d = 7 and at d = 8,
    where the bound is true (the pair graph). The real support misses
    by 0.06, 0.18, 0.32, 0.49 at d = 5..8 and by 0.04, 0.24, 0.11, 0.03
    at d = 11, 12, 16, 20, to two places of the larger sup: the tree
    closed at 0.03, 0.04, 0.06 and 0.18 and stayed open at 0.11, 0.24,
    0.32 and 0.49, so the miss alone does not order them. Q1 held at
    the four d; Q2 failed at 12 and 16; Q3's depths failed, 5 and 7
    where at most 2 was predicted, the periodic picture not carrying
    over, and its leaves held at d = 11 and 20 (49 and 311 in an arm)
    and not at d = 16, whose open arms reached 1152; Q4's clock failed
    on that form (62.0, 146.2, 577.1 and 247.7 s for d = 11 with the
    controls, d = 5..8, d = 20 and the open d), its memory held (108.1
    MB at most). K5 held: 82 of 82 at the root at d = 9, 10 and 13.
    Another search under the same checker, cases x_u <= n | x_u >= n +
    1 on the carry the float optimum leaves farthest from an integer,
    offsets -8..40, left open d = 12's two arms at t >= 40 and d = 16's
    carry at 8000 nodes each, and d = 7's at 3000.

  - What no check reads: the proposer's figures at d = 11 and 20; N
    off the lower end of H_x for the upper (one floor wherever no
    enclosure holds an integer: every check passes); the raise on a row
    before time 0, which no run reaches, verify and carry_over asking
    reads first (with it cut every check passes).

RUN RECORD. 17/17 checks, 131.1 s, peak commit 107.3 MB. The mutation
meter, every one-token and structural change of the checker's functions
(bound, covers, cases, verify, carry_over, tree and Arm's but offer),
162, each run: 152 red, 10 moving no line. Of the ten, nine are
equivalent (a zero tail longer, or one shorter and still long enough,
four; a certificate one row longer; the most in an arm started at 1;
the least margin's tie) or unreached (a certificate two rows shorter,
the rows it drops named by no node; the margin's guard, no arm closing no
leaf), and covers' scan for an empty node cut to its first element
accepts no list the whole scan refuses: one it then misreads raises. A
first run of the 162 had three more moving a printed value no check
read (the sum's own time at t >= 40 dropped from its order; the total
of leaves started at 1, and summed with the wrong sign) and one
outrunning its clock (the checker's scale doubled, every control tree
then grown to its cap); two hand nodes, the total at d = 13, target 4,
and the hand controls' stop answer them. No mutant fails the four check
lines behind the controls' stop; each fails under a break by hand with
the stop lifted (3 breaks, 3 red). 15 breaks by hand, each one edit,
the stop in place: 13 red and 2 green, the two as predicted (N off the
lower end; the raise cut). Every predicted line was among those failing
but one: the term of t >= 40 cut to eta failed the error terms' line
and not the root's, whose largest at d = 13 is a row's.
Unmetered: propose, numerators, Arm.offer and grow, which only propose,
and the controls' own functions.
"""

import os
import sys
import time
from fractions import Fraction

os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
import numpy as np  # noqa: E402
from scipy.optimize import linprog  # noqa: E402
from scipy.sparse import bmat, csr_matrix, identity  # noqa: E402
import real_support as rs  # noqa: E402

T = 40
J = 8
Q = 24
CAP = 5000
LAMBOX = 64.0
UNIT = 1 << rs.QH + rs.QE
ORDER = [0] + [s * j for j in range(1, J + 1) for s in (1, -1)]
CHECKS = []


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


# ------------------------------------------------------------ the checker
def bound(F, G, a, ns, unit, tol0, tols, q=Q):
    """||F + sum (a_i/2^q) G_i||_1 / unit + tol0 + sum |a_i|/2^q tols_i
    - sum (a_i/2^q) n_i, exactly: F and the G_i hold Python integers."""
    v = F * (1 << q)
    for ai, g in zip(a, G, strict=True):
        v = v + ai * g
    out = Fraction(int(np.abs(v).sum()), unit << q) + tol0
    for ai, ti, n in zip(a, tols, ns, strict=True):
        out += Fraction(abs(ai), 1 << q) * ti - Fraction(ai * n, 1 << q)
    return out


def covers(nodes, N):
    """Is a list of nodes a cover at N: the root alone, or every node
    opening with one offset, the first values exactly -N..N, and the
    tails under each value a cover."""
    if not nodes:
        return False
    if len(nodes) == 1 and nodes[0] == ():
        return True
    if any(len(node) == 0 for node in nodes):
        return False
    j = nodes[0][0][0]
    under = {}
    for node in nodes:
        if node[0][0] != j:
            return False
        under.setdefault(node[0][1], []).append(node[1:])
    return (sorted(under) == list(range(-N, N + 1)) and
            all(covers(tails, N) for tails in under.values()))


# ----------------------------------------------------------- the proposer
def propose(Ff, Gf, ns):
    """Floats: lam minimizing ||Ff + Gf lam||_1 - ns . lam in the box,
    and the least value. Its answer is ruled by bound, never trusted."""
    m = len(Gf)
    if m == 0:
        return [], float(np.abs(Ff).sum())
    keep = np.abs(Ff) > 1e-11
    for g in Gf:
        keep |= np.abs(g) > 1e-11
    f = Ff[keep]
    Gs = csr_matrix(np.array([g[keep] for g in Gf]).T)
    K = len(f)
    Id = identity(K, format="csr")
    res = linprog(np.concatenate([-np.array(ns, float), np.ones(K)]),
                  A_ub=bmat([[Gs, -Id], [-Gs, -Id]], format="csr"),
                  b_ub=np.concatenate([-f, f]),
                  bounds=[(-LAMBOX, LAMBOX)] * m + [(0, None)] * K,
                  method="highs")
    if res.status != 0:
        return [0.0] * m, float(np.abs(Ff).sum())
    return list(res.x[:m]), float(res.fun)


def numerators(lam):
    return [int(round(x * (1 << Q))) for x in lam]


# ---------------------------------------------------------------- the arms
class Arm:
    """One form (t None: every t >= T) and its neighbours' rows, in
    integers over unit and in floats."""

    def __init__(self, c, t, kind):
        self.t, self.kind, self.c = t, kind, c
        A, nb = c["A"], c["nb"]
        nf = len(A) - nb
        if t is None:
            self.unit = 1 << rs.QH
            lo = -nb - J
            n = nb + nf + 2 * J

            def vec(j):
                v = np.zeros(n, dtype=object)
                v[j - lo - nb:j - lo - nb + len(A)] = [int(a) for a in A]
                return v
            at = -lo
            self.lo = lo
            self.offsets = [j for j in ORDER if kind == "sum" or j != 0]
        else:
            self.unit = UNIT
            n = nf + T + J + 1

            def vec(j):
                if t + j < 0:
                    raise ValueError("a carry before time 0")
                r = rs.row(A, nb, t + j, c["E"][t + j])
                v = np.zeros(n, dtype=object)
                v[:len(r)] = [int(a) for a in r]
                return v
            at = t
            self.lo = 0
            self.offsets = [j for j in ORDER if t + j >= 0 and
                            (kind == "sum" or j != 0)]
        self.vec = vec
        self.F = vec(0)
        if kind == "sum":
            self.F[at] -= self.unit
        self.Ff = np.array([float(Fraction(int(x), self.unit))
                            for x in self.F])
        self.G, self.Gf = {}, {}

    def reads(self, node):
        """Does every carry the node names exist at this arm's time."""
        return all(j in self.offsets for j, _ in node)

    def rows(self, js):
        for j in js:
            if j not in self.G:
                self.G[j] = self.vec(j)
                self.Gf[j] = np.array([float(Fraction(int(x), self.unit))
                                       for x in self.G[j]])
        return [self.G[j] for j in js], [self.Gf[j] for j in js]

    def tols(self, js):
        """(A)'s or (T)'s error terms: the target's and each row's."""
        c = self.c
        if self.t is None:
            jm = max([0] + [-j for j in js])
            e = c["eta"] + c["top"][T - jm] * (c["norm"] + c["eta"])
            return e, [e] * len(js)
        return c["tau"][self.t], [c["tau"][self.t + j] for j in js]

    def exact(self, node, a):
        """(S)'s right side at a node, lam = a/2^Q, a in integers."""
        js = [j for j, _ in node]
        t0, ts = self.tols(js)
        return bound(self.F, self.rows(js)[0], a, [n for _, n in node],
                     self.unit, t0, ts)

    def offer(self, node):
        js = [j for j, _ in node]
        return numerators(propose(self.Ff, self.rows(js)[1],
                                  [n for _, n in node])[0])


def cases(N):
    """(C)'s cover: every integer a carry of size at most N takes."""
    return list(range(-N, N + 1))


def grow(arm, X, N, root=(), cap=CAP):
    """Depth-first from root: (leaves, nodes, stuck). A leaf is a node
    with the numerators that close it; stuck is None, or "spent" at the
    first node left open with no offset to fix, or "cap"."""
    stack = [tuple(root)]
    leaves, nodes = [], 0
    while stack:
        node = stack.pop()
        nodes += 1
        if nodes > cap:
            return leaves, nodes, "cap"
        a = arm.offer(node)
        if arm.exact(node, a) < X:
            leaves.append((node, a))
            continue
        used = [j for j, _ in node]
        rest = [j for j in arm.offsets if j not in used]
        if not rest:
            return leaves, nodes, "spent"
        stack += [node + ((rest[0], n),) for n in cases(N)]
    return leaves, nodes, None


def verify(arm, leaves, X, N):
    """A leaf list's verdict at an arm, however it was found: is it a
    cover, how many of its leaves read there and close, the deepest of
    those and their least margin; proved when it is a cover and every
    leaf closes."""
    closed = deep = 0
    margin = None
    for node, a in leaves:
        if not arm.reads(node):
            continue
        b = arm.exact(node, a)
        if b < X:
            closed += 1
            deep = max(deep, len(node))
            margin = X - b if margin is None else min(margin, X - b)
    cover = covers([node for node, _ in leaves], N)
    return {"cover": cover, "closed": closed, "leaves": len(leaves),
            "deep": deep, "margin": margin,
            "proved": cover and closed == len(leaves)}


def carry_over(arm, far, X, N):
    """The tree of t >= T at an earlier time: (leaves, how). Each leaf
    is kept where its own numerators close it there and regrown from
    its node where they do not; where a leaf names a carry before time
    0, or a regrowth stays open, the arm is grown from the root."""
    how = {"kept": 0, "regrown": 0, "rooted": False, "nodes": 0}
    out = []
    if all(arm.reads(node) for node, _ in far):
        for node, a in far:
            if arm.exact(node, a) < X:
                out.append((node, a))
                how["kept"] += 1
                continue
            more, nodes, stuck = grow(arm, X, N, root=node)
            how["nodes"] += nodes
            if stuck:
                break
            out += more
            how["regrown"] += 1
        else:
            return out, how
    out, nodes, _ = grow(arm, X, N)
    return out, {"kept": 0, "regrown": 0, "rooted": True,
                 "nodes": how["nodes"] + nodes}


def tree(d, X, ts=None):
    """Every arm of d at the target X (t >= T, and every t < T or the
    times ts): the TREE record. Where the tree of t >= T stays open the
    earlier times are grown from the root."""
    c = rs.certificate(d, T + J + 1)
    real = rs.record(c, d)
    N = int(real["Hx"][1])
    rec = {"d": d, "X": X, "N": N, "C": real["C"], "arms": 0, "proved": 0,
           "far": [], "leaves": 0, "most": 0, "deep": 0, "margin": None,
           "whole": 0, "regrew": [], "rooted": [], "open": [],
           "sup": max(real["Hx"][1], real["Hs"][1])}

    def tally(t, kind, v):
        rec["arms"] += 1
        rec["proved"] += v["proved"]
        if not v["proved"]:
            rec["open"].append((">= %d" % T if t is None else t, kind))
        rec["leaves"] += v["leaves"]
        rec["most"] = max(rec["most"], v["leaves"])
        rec["deep"] = max(rec["deep"], v["deep"])
        if v["margin"] is not None and (rec["margin"] is None or
                                        v["margin"] < rec["margin"]):
            rec["margin"] = v["margin"]

    for kind in ("carry", "sum"):
        arm = Arm(c, None, kind)
        far, _, stuck = grow(arm, X, N)
        rec["far"].append(len(far))
        tally(None, kind, verify(arm, far, X, N))
        for t in (range(T) if ts is None else ts):
            arm = Arm(c, t, kind)
            if stuck:
                leaves, how = grow(arm, X, N)[0], {"rooted": True}
            else:
                leaves, how = carry_over(arm, far, X, N)
            if how["rooted"]:
                rec["rooted"].append((t, kind))
            elif how["regrown"]:
                rec["regrew"].append((t, kind))
            else:
                rec["whole"] += 1
            tally(t, kind, verify(arm, leaves, X, N))
    return rec


def tree_line(rec):
    m = rec["margin"]
    return (f"TREE d = {rec['d']}: {rec['proved']} of {rec['arms']} arms "
            f"proved  target {rec['X']}  N {rec['N']}  leaves at t >= "
            f"{T} {rec['far']}  in all {rec['leaves']}  most in an arm "
            f"{rec['most']}  deepest "
            f"{rec['deep']}  least margin "
            f"{'none' if m is None else '%.3e' % float(m)}  carried whole "
            f"{rec['whole']}  a leaf regrown {len(rec['regrew'])}  from "
            f"the root {len(rec['rooted'])}")


# ------------------------------------------------------------ the controls
class Toy(Arm):
    """A hand arm: integer rows by offset, unit 1, no error term."""

    def __init__(self, F, rows):
        self.unit = 1
        self.F = np.array(F, dtype=object)
        self.Ff = np.array(F, dtype=float)
        self.G = {j: np.array(g, dtype=object) for j, g in rows.items()}
        self.Gf = {j: np.array(g, dtype=float) for j, g in rows.items()}
        self.offsets = list(rows)

    def tols(self, js):
        return Fraction(0), [Fraction(0)] * len(js)


G1, G2 = (1, 1, -2), (0, 1, 0)


def toy_bounds():
    """The checker on (Y)'s rows, every field apart."""
    F = np.array((3, -1, 2), dtype=object)
    g, g2 = np.array(G1, dtype=object), np.array(G2, dtype=object)
    zero, e8, e4, e2 = (Fraction(0), Fraction(1, 8), Fraction(1, 4),
                        Fraction(1, 2))
    return {"plain": [bound(F, [g], [a], [1], 1, zero, [zero], q=1)
                      for a in (0, 1, 2, 4)],
            "n0": bound(F, [g], [2], [0], 1, zero, [zero], q=1),
            "terms": [bound(F, [g], [a], [1], 1, e8, [e4], q=1)
                      for a in (1, -1)],
            "two": bound(F, [g, g2], [2, 1], [1, -1], 1, e8, [e4, e2], q=1),
            "unit": bound(2 * F, [2 * g, 2 * g2], [2, 1], [1, -1], 2, e8,
                          [e4, e2], q=1)}


A3 = [((1, -1),), ((1, 0),), ((1, 1),)]
B5 = [((1, -1),), ((1, 1),), ((1, 0), (-1, -1)), ((1, 0), (-1, 0)),
      ((1, 0), (-1, 1))]
HAND_TREES = (("the root alone", [()], True),
              ("no node", [], False),
              ("three cases", A3, True),
              ("a case missing", A3[:2], False),
              ("a value outside", A3[:2] + [((1, 2),)], False),
              ("a case grown", B5, True),
              ("siblings on two offsets", B5[:4] + [((1, 0), (2, 1))],
               False),
              ("a leaf and its extension", A3 + [((1, 0), (-1, 0))], False),
              ("a case twice", A3 + [((1, 0),)], False))


def toy_runs():
    """grow, carry_over and verify on hand arms, each value by hand."""
    toy = Toy((3, -1, 2), {1: G1})
    far, nodes, left = grow(toy, 6, 1)
    early = Toy((3, 1, 2), {1: G1})
    kept, how = carry_over(early, far, 7, 1)
    stuck, how6 = carry_over(early, far, 6, 1)
    blind = Toy((3, -1, 2), {2: G2})
    rooted, howb = carry_over(blind, far, 7, 1)
    return {
        "grown at 6": (far, nodes, left),
        "grown at 5": grow(toy, 5, 1),
        "grown at 7": grow(toy, 7, 1),
        "capped": grow(toy, 6, 1, cap=3)[1:],
        "read at 4, 5, 6": [(w["cover"], w["closed"], w["leaves"],
                             w["margin"], w["deep"], w["proved"])
                            for w in (verify(toy, far, X, 1)
                                      for X in (4, 5, 6))],
        "carried at 7": (kept, how, verify(early, kept, 7, 1)["closed"]),
        "stuck at 6": (stuck, how6, verify(early, stuck, 6, 1)["cover"]),
        "blind": (rooted, howb, verify(blind, far, 7, 1)["closed"])}


def toy_want():
    """toy_runs by hand (the docstring's (G))."""
    one = 1 << Q
    L = [(((1, 1),), [one]), (((1, 0),), [one]), (((1, -1),), [one])]
    return {
        "grown at 6": (L, 4, None),
        "grown at 5": (L[:2], 4, "spent"),
        "grown at 7": ([((), [])], 1, None),
        "capped": (4, "cap"),
        "read at 4, 5, 6": [(True, 1, 3, Fraction(1), 1, False),
                            (True, 2, 3, Fraction(1), 1, False),
                            (True, 3, 3, Fraction(1), 1, True)],
        "carried at 7": (L[:2] + [(((1, -1),), [-one])],
                         {"kept": 2, "regrown": 1, "rooted": False,
                          "nodes": 1}, 3),
        "stuck at 6": (L[:1], {"kept": 0, "regrown": 0, "rooted": True,
                               "nodes": 4}, False),
        "blind": ([((), [])], {"kept": 0, "regrown": 0, "rooted": True,
                               "nodes": 1}, 0)}


W13 = [0, 1, 2, 3, 2, 1, 0, -1, -2, -3, -2, -1]
W11 = [0, 1, 2, 2, 1, 0, -1, -2, -2, -1]
REFUSE = (("d = 13 target 3, t = 3 carry", 13, 3, 3, "carry", W13, 3),
          ("d = 13 target 3, t = 2 sum", 13, 3, 2, "sum", W13, 2),
          ("d = 13 target 3, t >= 40 carry", 13, 3, None, "carry", W13, 3),
          ("d = 13 target 3, t >= 40 sum", 13, 3, None, "sum", W13, 2),
          ("d = 11 target 2, t = 2 carry", 11, 2, 2, "carry", W11, 2),
          ("d = 11 target 2, t >= 40 carry", 11, 2, None, "carry", W11, 2),
          ("d = 2 target 1, t = 2 carry", 2, 1, 2, "carry", None, 2))


def refusals(d, target, t, kind, xs, phase, depths=8):
    """A known path's own node at depths 1..depths, lam the proposer's
    and lam = 0: (tried, refused, the least bound)."""
    arm = Arm(rs.certificate(d, T + J + 1), t, kind)
    tried = refused = 0
    least = None
    for k in range(1, depths + 1):
        js = arm.offsets[:k]
        if xs is None:                      # e_2: x_2 = 1, the rest 0
            node = tuple((j, int(phase + j == 2)) for j in js)
        else:
            node = tuple((j, xs[(phase + j) % len(xs)]) for j in js)
        for a in (arm.offer(node), [0] * k):
            b = arm.exact(node, a)
            tried += 1
            refused += b >= target
            least = b if least is None else min(least, b)
    return tried, refused, least


def rows_read(c, xs, t, phase):
    """The carry arm's rows at offset 0 and at every offset of its
    order, and the sum arm's form, each dotted with a periodic path's
    delta: how many lie within their error term of the path's own carry
    (the sum's: the next carry, the path's period being d - 1), of how
    many. At t None the path is two-sided and the term is eta."""
    arm = Arm(c, t, "carry")
    P = len(xs)
    base = arm.lo + (phase if t is None else 0)
    dl = np.array([xs[(base + i) % P] - xs[(base + i + 1) % P]
                   for i in range(len(arm.F))], dtype=object)
    forms = [(arm.vec(j), j, j) for j in [0] + arm.offsets]
    forms.append((Arm(c, t, "sum").F, 0, 1))
    good = 0
    for v, j, shift in forms:
        val = Fraction(int((v * dl).sum()), arm.unit)
        tol = c["eta"] if t is None else c["tau"][t + j]
        good += abs(val - xs[(phase + shift) % P]) <= tol
    return good, len(forms)


def roots_read(c, d):
    """An arm's bound at the root beside real_support's enclosures: how
    many of the 80 rows' upper ends it equals, and whether the largest
    of each kind's 41 is the record's upper end of H_x and of H_s."""
    rec = rs.record(c, d)
    same = 0
    tops = []
    for i, kind in enumerate(("carry", "sum")):
        got = [Arm(c, t, kind).exact((), []) for t in range(T)]
        same += sum(g == rs.enclose(c, t)[i][1] for t, g in enumerate(got))
        tops.append(max(got + [Arm(c, None, kind).exact((), [])]))
    return same, tops == [rec["Hx"][1], rec["Hs"][1]]


def terms_read(c):
    """Arm.tols at hand nodes beside the constants named by hand."""
    def e(i):
        return c["eta"] + c["top"][i] * (c["norm"] + c["eta"])
    tau = c["tau"]
    got = [Arm(c, 4, "carry").tols([1, -1, 2]),
           Arm(c, None, "carry").tols([1, -3, 2]),
           Arm(c, None, "sum").tols([1, 2]),
           Arm(c, None, "carry").tols([])]
    want = [(tau[4], [tau[5], tau[3], tau[6]]), (e(37), [e(37)] * 3),
            (e(40), [e(40)] * 2), (e(40), [])]
    return sum(g == w for g, w in zip(got, want, strict=True)), len(want)


def reads_read(c):
    """Arm.reads at seven hand nodes: which name carries that exist."""
    return [Arm(c, 4, "carry").reads(((1, 0), (-4, 0))),
            Arm(c, 4, "carry").reads(((1, 0), (-5, 0))),
            Arm(c, 4, "carry").reads(((0, 0),)),
            Arm(c, 4, "sum").reads(((0, 0),)),
            Arm(c, None, "carry").reads(((1, 0), (-8, 0))),
            Arm(c, None, "carry").reads(((0, 0),)),
            Arm(c, None, "sum").reads(((0, 0),))]


WAVE_ARMS = [(">= 40", "carry"), (">= 40", "sum"), (3, "carry"), (2, "sum")]


def section_control():
    print("CONTROL", flush=True)
    got = toy_bounds()
    h = Fraction
    check("the checker's hand rows",
          got == {"plain": [6, h(9, 2), 3, 6], "n0": 4,
                  "terms": [h(19, 4), h(31, 4)], "two": h(37, 8),
                  "unit": h(37, 8)},
          f"{[str(x) for x in got['plain']]}, {got['n0']}, "
          f"{[str(x) for x in got['terms']]}, {got['two']}, {got['unit']}")
    lam, val = propose(np.array([3.0, -1.0, 2.0]),
                       [np.array([1.0, 1.0, -2.0])], [1])
    check("the proposer's least 3 at lam 1",
          abs(val - 3) < 1e-6 and abs(lam[0] - 1) < 1e-6,
          f"{val:.9f} at {float(lam[0]):.9f}")
    right = sum(covers(nodes, 1) is want for _, nodes, want in HAND_TREES)
    check("the nine hand trees: a cover or not", right == len(HAND_TREES)
          == 9, f"{right} of {len(HAND_TREES)}")
    runs, want = toy_runs(), toy_want()
    same = [k for k in want if runs[k] == want[k]]
    check("the hand arms grown, read and carried over", len(same) ==
          len(want) == 8, f"{len(same)} of {len(want)}")
    for k in want:
        if runs[k] != want[k]:
            print(f"    {k}: {runs[k]}", flush=True)
    if not all(CHECKS):
        return
    c13 = rs.certificate(13, T + J + 1)
    a, b = rows_read(c13, W13, None, 4)
    a2, b2 = rows_read(c13, W13, 4, 4)
    check("the rows carry the wave to its own carries, d = 13, phase 4",
          a + a2 == b + b2 == 32, f"{a + a2} of {b + b2}")
    same, tops = roots_read(c13, 13)
    check("d = 13: the root's bounds are real_support's upper ends",
          same == 80 and tops, f"{same} of 80 rows, the two sups {tops}")
    a, b = terms_read(c13)
    check("d = 13: the error terms at four hand nodes", a == b == 4,
          f"{a} of {b}")
    got = reads_read(c13)
    check("d = 13: the carries seven hand nodes name exist or not",
          got == [True, False, False, True, True, False, True], f"{got}")
    tried = refused = 0
    for name, *args in REFUSE:
        a, b, least = refusals(*args)
        tried += a
        refused += b
        print(f"    {name}: refused {b} of {a}, least bound "
              f"{float(least):.9f}", flush=True)
    check("every known path's node refused", tried == refused == 112,
          f"{refused} of {tried}")
    rec = tree(13, 3, ts=[3, 2])
    print("  " + tree_line(rec), flush=True)
    known = sum(arm in rec["open"] for arm in WAVE_ARMS)
    check("d = 13, target 3: the wave's four arms unproved",
          known == len(WAVE_ARMS) == 4,
          f"{known} of {len(WAVE_ARMS)}; open {len(rec['open'])} of "
          f"{rec['arms']}")
    rec = tree(13, 4)
    print("  " + tree_line(rec), flush=True)
    check("d = 13, target 4: every arm proved at the root, the least "
          "margin real_support's",
          rec["proved"] == rec["arms"] == rec["leaves"] == 82 and
          rec["most"] == 1 and rec["deep"] == 0 and rec["whole"] == 80
          and rec["margin"] == 4 - rec["sup"],
          f"{rec['proved']} of {rec['arms']}, margin "
          f"{float(rec['margin']):.6f}")
    for d in (5, 6):
        rec = tree(d, 2)
        print("  " + tree_line(rec), flush=True)
        check(f"d = {d}, target 2: every arm proved, a root open",
              rec["proved"] == rec["arms"] == 82 and rec["deep"] > 0,
              f"{rec['proved']} of {rec['arms']}")


def section_tree():
    print("TREE", flush=True)
    for d, X in ((11, 3), (20, 5)):
        rec = tree(d, X)
        print("  " + tree_line(rec), flush=True)
        print(f"    a leaf regrown at {rec['regrew']}", flush=True)
        print(f"    from the root at {rec['rooted']}  open {rec['open']}",
              flush=True)
        check(f"d = {d}: every arm a cover with every leaf closed",
              rec["proved"] == rec["arms"] == 82,
              f"{rec['proved']} of {rec['arms']}")
        check(f"d = {d}: N = C_d + 1 = {X}",
              rec["N"] == rec["C"] + 1 == X)


def main():
    t0 = time.time()
    section_control()
    if not all(CHECKS):
        print("a control failed: no tree is read")
        sys.exit(1)
    print(f"  [{time.time() - t0:.1f} s]", flush=True)
    section_tree()
    print(f"{sum(CHECKS)}/{len(CHECKS)} checks passed  "
          f"[{time.time() - t0:.1f} s]")
    sys.exit(0 if all(CHECKS) else 1)


if __name__ == "__main__":
    main()