alt4proof.py

Checks: FLATTEN: The takeover depth grows as r^(3/2) theorem; property; rule; pattern; observation.

Cited on: FLATTEN.

To run it: save alt4proof.py, with alt4.py, altproof.py, band.py, bandend.py, bandfamily.py, bandheight.py, bandscale.py, circlemean.py, flatten.py, losses.py, prunerr.py beside it; needs mpmath, numpy, scipy.

"""alt4proof.py -- order r - 5's three-point certificate by hand: does a
proof with no step a run put order r - 5's real least height above
H_ch from (2/sqrt(W(1/e)) + o(1)) r^(3/2)?

Frozen before this file's code: the question, (T1)..(T8), the
predictions, the kill and the controls (below, copied).

NOTATION. Flipped. s = r - 5, N = J + s + 4 = J + r - 1, n0 = N/2, j =
k - n0, Q_a = (1 + x)^(N - a)(1 - x)^a, B_k = Q_(s+k); q = Q_(s+2) = B_2,
u = Q_(s+3), P = Q_(s+4) = B_4 the champion. theta = x d/dx - n0, which
multiplies coefficient k by j. beta = W(1/e) = 0.278465, beta e^beta =
1/e, so e^(-(1 + beta)) = beta. E(j) = exp(-j^2/(2 n0)).

BY HAND.
 (T1) THE CLASS. x Q_a'/Q_a = (N - a)x/(1 + x) - a x/(1 - x), so
      theta Q_a = -((N - a) Q_(a+1) + a Q_(a-1))/2, and
      4 theta^2 q = (J + 2)(J + 1) P + [(J + 2)(s + 3) + (s + 2)(J + 3)] q
                   + (s + 2)(s + 1) B_0,
      2 theta u = -((J + 1) P + (s + 3) q).
      The real least of order r - 5 is that of B_0/16 + span(B_1..B_4);
      reversal at degree N sends B_k to (-1)^(s+k) B_k, so averaging with
      the signed reversal keeps B_0, B_2, B_4 at no larger height. So with
      K = 4(s + 1)(s + 2), F = theta^2 q/K is in the class, F_j = j^2
      q_j/K, span(B_2, B_4) = span(q, theta u), and
      L = min over (c, b) of max_j |(j^2 - c) q_j/K + b j u_j|.
 (T2) THREE-POINT LEMMA. Indices c, i, i + 1 with q_c != 0; kappa = j_c
      u_c/q_c, G = j u - kappa q (G_c = 0), A_j = (j^2 - j_c^2) q_j/K. If
      G_i G_(i+1) <= 0 and A_i A_(i+1) > 0, then
      L >= min(|A_i|, |A_(i+1)|)/(1 + max(|q_i|, |q_(i+1)|)/|q_c|).
      Proof. X = (j^2 - c)q/K + b j u, h = max |X| at the three. From X_c:
      (c - j_c^2)/K = (b j_c u_c - X_c)/q_c, so X_m = A_m + b G_m + X_c
      q_m/q_c at m = i, i + 1, and |A_m + b G_m| <= h(1 + |q_m/q_c|). b
      G_i, b G_(i+1) have opposite signs or one is 0, A one sign: one of
      them has |A_m + b G_m| >= |A_m|. Free of (c, b).
 (T3) LEMMA A (altproof.py's (S2)) at a = s + 2, s + 3, 2 n0 = N; (S1)
      gives coefficient_(n0+j)(Q_a) = Re(i^a I_a(j)), main term A_a E(j)
      cos(j t_a + a pi/2): q ~ A_q E cos(j t_q + (s+2)pi/2), u ~ -A_u E
      sin psi(j), psi(x) = x t_u + (s + 2)pi/2. Dt = |t_u - t_q| <=
      1/sqrt((s + 2)(J + 1)) (dt_a/da = 1/sqrt(a(N - a))).
 (T4) THE CENTRE. x_c a crest of q's main term (x_c t_q + (s+2)pi/2 in pi
      Z) nearest 0, |x_c| <= pi/(2 t_q); c the lattice point nearest,
      |j_c| <= U_c = pi/(2 t_q) + 1/2. |q_c| >= A_q Q_c, Q_c = E(U_c)
      cos(t_q/2) - eps_q (owed Q_c > 0); psi(j_c) = (x_c t_q + (s+2)pi/2) + (j_c - x_c)
      t_q + j_c(t_u - t_q), so |u_c| <= A_u (t_q/2 + U_c Dt + eps_u) and
      kappa-bar := |kappa| A_q (1 + eps_q)/(A_u (j* - pi/t_u)) <= U_c
      (t_q/2 + U_c Dt + eps_u)(1 + eps_q)/(Q_c (j* - pi/t_u)).
 (T5) THE PAIR. j* = sqrt(2 n0 (1 + beta)); x_m a zero of sin psi within
      pi/(2 t_u) of j*; eta = (eps_u + kappa-bar)/E(j* + pi/t_u), delta =
      arcsin(eta)/t_u, U = pi/(2 t_u) + delta + 1 (owed eta < 1, U <=
      pi/t_u, j* > pi/t_u). The lattice points j_a < x_m - delta, j_b >
      x_m + delta nearest it lie within delta + 1 of x_m, |sin psi| > eta
      there, and |G_j - j main_u(j)| <= j A_u eps_u + |kappa| A_q (1 +
      eps_q) <= j A_u (eps_u + kappa-bar) < |j main_u(j)|: G has main_u's
      opposite signs at j_a, j_b, so an adjacent pair in [j_a, j_b] has
      G_i G_(i+1) <= 0.
 (T6) q KEEPS ITS SIGN there (altproof's (S4) with q, u for Q, P): Dth =
      (delta + 1) t_u + (j* + U) Dt, owed Dth < pi/2, E(j* + U) cos Dth >
      eps_q; |q_m| >= A_q (E(j* + U) cos Dth - eps_q), |q_m| <= A_q
      (E(j* - U) + eps_q); owed j* - U > U_c, so A_i A_(i+1) > 0, and
      j* + U < n0 (the window on the coefficients).
 (T7) THE RATIO. H_ch <= mean(P) = 2^N B((s + 5)/2, (J + 1)/2)/pi. With
      alpha = (s + 2)/2, gamma = (J + 2)/2, alpha + gamma = n0, f_q(t_q) =
      2^N (gamma/n0)^gamma (alpha/n0)^alpha, Binet and Wendel (Gamma(x +
      1/2) <= sqrt(x) Gamma(x), twice) give EXACTLY A_q/mean(P) =
      sqrt(alpha gamma) e^Dmu Gamma(alpha) Gamma(gamma)/(Gamma(alpha +
      3/2) Gamma(gamma - 1/2)) >= (J + 1)/(s + 3) e^Dmu, Dmu = mu(n0) -
      mu(alpha) - mu(gamma) > -1/(6(s + 2)) - 1/(6(J + 2)). So
      L/H_ch >= Ratio = (J + 1)/(s + 3) e^Dmu [(j* - U)^2 - U_c^2]
         (E(j* + U) cos Dth - eps_q) / (K [1 + (E(j* - U) + eps_q)/Q_c]).
 (T8) THE LIMIT, over J >= s^(3/2) as s grows: altproof's (S6) at a = s +
      2, s + 3 gives eps -> 0, t_a sqrt(n0) ~ sqrt(2a) -> infinity, every
      bound free of J. So U/j* -> 0, U_c/j* -> 0, U_c^2/n0 ~ pi^2/(8 s) ->
      0, Q_c -> 1, kappa-bar -> 0 (U_c t_q/2 <= pi/4 + t_q/4 is bounded,
      U_c^2 Dt/j* = O(s^(-3/2)) and U_c/j* = O(s^(-1/2)), each free of
      J), delta t_u -> 0, Dth -> 0, Dmu -> 0,
      E(j* +- U) -> beta, every owed condition holds, and Ratio >= beta
      J^2 (1 - o(1))/(4 (s + 3)^3), the o(1) free of J: Ratio > 1 at every
      J >= C r^(3/2) > C s^(3/2) once r is large, for every C >
      2/sqrt(beta) = 3.79005.

PREDICTIONS (frozen).
 P1 (T1)'s two identities hold in exact integers at (r, J) = (9, 88),
    (12, 150), (25, 600), (40, 1500).
 P2 CONTROL (Lemma A at a = s + 2, s + 3 against exact integers): at s
    = 20, 21, 40, 41, 80, 81, 160, 161, J = round(C s^1.5), C = 4, 6,
    10: max_j |coef/A_a - E cos(j t_a + a pi/2)| <= eps_a, sign +1 at
    every cell (no parity flip); actual/eps in [0.02, 1].
 P3 at P2's cells with the owed conditions: the window holds a pair with
    G_i G_(i+1) <= 0 in integers; there exact D3 (alt4.cert) >= (T2)'s
    bound >= Ratio * mean(P); D3 at the proof's triple over the LP
    (alt4.lp) in [0.9, 1] at s >= 80.
 P4 J^P(s), the least J on the grid C step 0.01 (J = ceil(C s^1.5))
    from which Ratio > 1 with the owed conditions to C = 1000:
    J^P/s^1.5 in [3.79, 4.6] at s = 10^3, [3.79, 4.0] at 10^4, [3.79,
    3.82] at 10^6, falling.
 P5 Ratio / (beta J^2/(4 s^3)) at s = 10^6 over C in [4, 1000] lies in
    [0.97, 1.01].
KILL. K1: J^P/s^1.5 > 4.663 at s = 10^4 or 10^6 (printed "KILL K1").
 K2: at any read with the owed conditions, exact D3 at the proof's
 triple below (T2)'s bound or (T2)'s bound below Ratio * mean(P), or no
 G sign change in the window ("KILL K2"). K3: P1 or P2 fails.
CONTROLS. P2 is the positive control (read before any verdict). Plants:
 eps_q x 0.1 must fail P2 at some read; x_m moved by pi/(2 t_u) must
 leave a window with no G sign change at some read; the centre moved
 to q's node (x_c + pi/(2 t_q)) must drop exact D3 below the unplanted
 triple's at every read with owed conditions (read in its direction).

FINDINGS (copied from the printed output). K1, K2, K3 miss; P1..P5 hold.
  (1) CONTROLS: (T1)'s two identities hold at all 2424 coefficients
      (4848 identities). Lemma A
      holds at all 48 reads (q and u at 24 cells), actual/eps
      0.0715..0.2437, sign +1 better at every read: (S1)'s Re(i^a I_a)
      carries no parity flip. eps x 0.1 (q's and u's) fails at 36 of 48
      reads. x_m moved
      by pi/(2 t_u) leaves no G sign change at 9 of 9 owed cells; the
      centre moved to q's node lowers D3 at 9 of 9.
  (2) P3: the owed conditions hold at 9 of 24 cells (s = 80 at C = 10,
      s = 81 at C = 6, 10, s = 160, 161 at all three; at s <= 41 eps_q is
      0.1760..0.4424 and Ratio < 0). At each, the window holds exactly
      one pair with G_i G_(i+1) <= 0, and D3 >= (T2) >= Ratio mean(P):
      1.0835 >= 1.0472 >= 0.3711, 2.4350 >= 2.4153 >= 0.9000, 6.7177 >=
      6.6882 >= 2.6743 at s = 160, C = 4, 6, 10 (over mean(P)). The
      proof's triple is the LP's optimum: D3/LP 1.000000 at 8 cells,
      0.999693 at s = 161, C = 4, an observation: (T2) is a lower bound on
      D3, strictly below it at all 9.
  (3) P4, P5: J^P/s^1.5 = 9.43, 5.08, 4.30, 4.04, 3.92, 3.83, 3.81 at s =
      100, 300, 10^3, 3000, 10^4, 10^5, 10^6, falling (in r^1.5: 8.76,
      4.96, 4.27, 4.03, 3.92, 3.83, 3.81); Ratio/(beta J^2/(4 s^3)) over
      C in [4, 1000] lies in 0.7779..0.8124 at 10^3, 0.9386..0.9458 at
      10^4, 0.9945..0.9949 at 10^6. eps_q at C = 4 is 0.07443, 0.00392,
      0.00034 at s = 100, 10^4, 10^6.
  So, by hand ((T1)..(T8) with altproof's (S1), (S2), (S4), (S6) and
  alt4's reduction of the class by signed reversal, no step a run): for every C > 2/sqrt(W(1/e)) = 3.79005 there is an r_0 with order
  r - 5's real least height above H_ch at every J >= C r^(3/2), r >=
  r_0. With the closed bound's limit margins (margins.py: every order
  but r - 3 and r - 5 at
  every C > 2 sqrt(2 exp 1)) and order r - 3's alternation certificate,
  limsup J_ch/r^(3/2) <= 2 sqrt(2 exp 1); with the liminf, lim J_ch/
  r^(3/2) = 2 sqrt(2 exp 1). The grid's crossings are reads at C step
  0.01, not every J.
CHANGED AFTER THE FREEZE. Before the first complete run: D3 is read in
  logs (a float of D3 overflowed at s = 80), and the node plant compared
  against the last pair's D3, not the kept one's. P3's family is P2's
  cells where the owed conditions hold, 9 of 24, as frozen. At the
  audit: the eps plant scales q's and u's eps alike (frozen: eps_q); a
  window whose every pair has A changing sign prints, not crashes.
RUN RECORD. Bare: 9/9, 3.1 s, peak 330.7 MB.

RUN: python alt4proof.py
"""
import math
import os
import sys
import time
from fractions import Fraction

os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
import numpy as np  # noqa: E402
from losses import coeffs  # noqa: E402
from altproof import lemma_a  # noqa: E402
import alt4  # noqa: E402

CHECKS = []


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


def lambert_beta():
    """beta = W(1/e): beta e^beta = 1/e, by Newton."""
    b = 0.3
    for _ in range(60):
        f = b * math.exp(b) - math.exp(-1)
        b -= f / (math.exp(b) * (1 + b))
    return b


BETA = lambert_beta()
CB = 2 / math.sqrt(BETA)
CL = 2 * math.sqrt(2 * math.e)


# ------------------------------------------------------------- the bound

def bound(s, J):
    """Ratio of (T7) and its pieces, numpy over J at fixed s; owed as a
    boolean array."""
    J = np.asarray(J, dtype=float)
    N = J + s + 4
    n0 = N / 2
    eq, tq, _, _, mq = lemma_a(s + 2, n0)
    eu, tu, _, _, mu = lemma_a(s + 3, n0)

    def E(x):
        return np.exp(-x ** 2 / (2 * n0))
    Dt = np.abs(tu - tq)
    js = np.sqrt(2 * n0 * (1 + BETA))
    Uc = math.pi / (2 * tq) + 0.5
    Qc = E(Uc) * np.cos(tq / 2) - eq
    gap = js - math.pi / tu
    kb = (Uc * (tq / 2 + Uc * Dt + eu) * (1 + eq)
          / (np.where(Qc > 0, Qc, np.nan) * np.where(gap > 0, gap, np.nan)))
    eta = (eu + kb) / E(js + math.pi / tu)
    delta = np.arcsin(np.minimum(np.nan_to_num(eta, nan=1.0), 1.0)) / tu
    U = math.pi / (2 * tu) + delta + 1
    Dth = (delta + 1) * tu + (js + U) * Dt
    num = (js - U) ** 2 - Uc ** 2
    loq = E(js + U) * np.cos(Dth) - eq
    den = 4 * (s + 1) * (s + 2) * (1 + (E(js - U) + eq) / Qc)
    dmu = -1 / (6 * (s + 2)) - 1 / (6 * (J + 2))
    R = (J + 1) / (s + 3) * np.exp(dmu) * num * loq / den
    owed = ((mq > 0) & (mu > 0) & (Qc > 0) & (gap > 0) & (eta < 1)
            & (U <= math.pi / tu) & (Dth < math.pi / 2) & (loq > 0)
            & (js - U > Uc) & (js + U < n0))
    return R, dict(eq=eq, eu=eu, tq=tq, tu=tu, js=js, Uc=Uc, Qc=Qc,
                   kb=kb, eta=eta, delta=delta, U=U, Dth=Dth, owed=owed,
                   n0=n0)


# ------------------------------------------------------------- exact reads

def log_A(a, N):
    """log A_a = log(f_a(t_a) sqrt(2 pi/n0)/pi), n0 = N/2."""
    n0, b = N / 2, N - a
    return (N * math.log(2) + (b / 2) * math.log(b / N)
            + (a / 2) * math.log(a / N)
            + 0.5 * math.log(2 * math.pi / n0) - math.log(math.pi))


def log_meanP(s, J):
    N = J + s + 4
    return (N * math.log(2) + math.lgamma((s + 5) / 2)
            + math.lgamma((J + 1) / 2) - math.lgamma(N / 2 + 1)
            - math.log(math.pi))


def scaled(v, la):
    """v / exp(la) as a float, v a big int (0 stays 0)."""
    if v == 0:
        return 0.0
    return math.exp(math.log(abs(v)) - la) * (1.0 if v > 0 else -1.0)


def lemma_read(arr, a, N, t):
    """(err at sign +1, err at sign -1): max_j |coef/A_a -+ E cos(j t +
    a pi/2)|."""
    la, n0 = log_A(a, N), N / 2
    errs = {1: 0.0, -1: 0.0}
    for k, v in enumerate(arr):
        j = k - n0
        main = math.exp(-j * j / (2 * n0)) * math.cos(j * t + a * math.pi / 2)
        x = scaled(v, la)
        for sg in (1, -1):
            errs[sg] = max(errs[sg], abs(sg * x - main))
    return errs[1], errs[-1]


def triple(s, J, q, u, info, xm_shift=0.0, node=False):
    """The proof's indices: (kc, pairs in the window with G_i G_(i+1) <=
    0); node moves the centre to q's node (the plant)."""
    N = J + s + 4
    n0 = N / 2
    tq, tu = float(info["tq"]), float(info["tu"])
    js, delta = float(info["js"]), float(info["delta"])
    cc = math.floor((s + 2) / 2 + 0.5)
    xc = (cc - (s + 2) / 2) * math.pi / tq
    if node:
        xc += math.pi / (2 * tq)
    kc = round(n0 + xc)
    c = round((js * tu + (s + 2) * math.pi / 2) / math.pi)
    xm = (c * math.pi - (s + 2) * math.pi / 2) / tu + xm_shift
    lo = math.ceil(n0 + xm - delta - 1)
    hi = math.floor(n0 + xm + delta + 1)
    jc2 = 2 * kc - N

    def G(k):                         # 2 q_c G_k, an integer
        return (2 * k - N) * u[k] * q[kc] - jc2 * u[kc] * q[k]
    pairs = [k for k in range(lo, hi) if G(k) * G(k + 1) <= 0]
    return kc, pairs, (lo, hi)


def t2_bound(s, J, q, kc, i):
    """(T2)'s bound at (kc, i, i + 1) as a Fraction, or None if A changes
    sign there."""
    N = J + s + 4
    K4 = 16 * (s + 1) * (s + 2)       # A_m = ((2j_m)^2 - (2j_c)^2) q_m/K4
    jc2 = (2 * kc - N) ** 2
    A = [((2 * m - N) ** 2 - jc2) * q[m] for m in (i, i + 1)]
    if A[0] * A[1] <= 0 or q[kc] == 0:
        return None
    qm = max(abs(q[i]), abs(q[i + 1]))
    return Fraction(min(abs(A[0]), abs(A[1])) * abs(q[kc]),
                    K4 * (abs(q[kc]) + qm))


def logfrac(f):
    return math.log(f.numerator) - math.log(f.denominator)


# ------------------------------------------------------------- the stages

def stage_identity():
    print("P1: THE CLASS IDENTITIES IN INTEGERS", flush=True)
    bad, n = 0, 0
    for r, J in ((9, 88), (12, 150), (25, 600), (40, 1500)):
        s = r - 5
        N = J + s + 4
        B0, q, P = coeffs(J + 4, s), coeffs(J + 2, s + 2), coeffs(J, s + 4)
        u = coeffs(J + 1, s + 3)
        mid = (J + 2) * (s + 3) + (s + 2) * (J + 3)
        for k in range(N + 1):
            n += 1
            bad += ((2 * k - N) ** 2 * q[k] != (J + 2) * (J + 1) * P[k]
                    + mid * q[k] + (s + 2) * (s + 1) * B0[k])
            bad += ((2 * k - N) * u[k] != -((J + 1) * P[k] + (s + 3) * q[k]))
    check("P1: 4 theta^2 q and 2 theta u in the B basis, every coefficient",
          bad == 0, f"{bad} of {2 * n} identities fail")


def stage_exact():
    print("P2, P3: LEMMA A, THE TRIPLE AND D3 AGAINST INTEGERS", flush=True)
    SS = (20, 21, 40, 41, 80, 81, 160, 161)
    reads, worst, low, sign_ok, planted = 0, (0.0, 1.0), [], True, 0
    k2, owed_n, nopair, shifted_empty, node_low, node_n = 0, 0, 0, 0, 0, 0
    lp_rat = []
    for s in SS:
        for C in (4, 6, 10):
            J = round(C * s ** 1.5)
            N = J + s + 4
            R, info = bound(s, J)
            R = float(R)
            q, u = coeffs(J + 2, s + 2), coeffs(J + 1, s + 3)
            for arr, a, t, e in ((q, s + 2, info["tq"], info["eq"]),
                                 (u, s + 3, info["tu"], info["eu"])):
                e = float(e)
                ep, em = lemma_read(arr, a, N, float(t))
                reads += 1
                sign_ok &= ep < em
                worst = (max(worst[0], ep / e), min(worst[1], ep / e))
                planted += ep > 0.1 * e
            if not bool(info["owed"]):
                print(f"  s = {s}, C = {C}: owed conditions fail "
                      f"(eps_q {float(info['eq']):.4f}), Ratio {R:.4f}",
                      flush=True)
                continue
            owed_n += 1
            kc, pairs, win = triple(s, J, q, u, info)
            if not pairs:
                nopair += 1
                print(f"  s = {s}, C = {C}: NO G SIGN CHANGE in {win}")
                continue
            r = s + 5
            Bs = alt4.basis(r, J, 2)
            H = max(abs(v) for v in Bs[-1])
            best = None
            for i in pairs:
                b = t2_bound(s, J, q, kc, i)
                if b is None:
                    k2 += 1
                    continue
                _, d3h = alt4.cert(Bs, [kc, i, i + 1], H)
                ld3 = math.log(d3h) + math.log(H)      # log D3
                lb = logfrac(b)
                if ld3 < lb - 1e-12 or lb < math.log(R) + \
                        log_meanP(s, J) - 1e-12:
                    k2 += 1
                if best is None or d3h > best[0]:
                    best = (d3h, ld3, lb, i)
            if best is None:
                print(f"  s = {s}, C = {C}: A CHANGES SIGN at every pair")
                continue
            d3h, ld3, lb, i = best
            t, _, _ = alt4.lp(Bs, H)
            rat = d3h / t
            if s >= 80:
                lp_rat.append(rat)
            _, pairs2, _ = triple(s, J, q, u, info,
                                  xm_shift=math.pi / (2 * float(info["tu"])))
            shifted_empty += not pairs2
            kn, _, _ = triple(s, J, q, u, info, node=True)
            if kn not in (i, i + 1):
                node_n += 1
                node_low += (alt4.cert(Bs, sorted([kn, i, i + 1]), H)[1]
                             < d3h * (1 - 1e-9))
            print(f"  s = {s}, C = {C}: J = {J}, centre j {kc - N / 2:+.1f}, "
                  f"pair j {i - N / 2:+.1f} (j* {float(info['js']):.1f}), "
                  f"{len(pairs)} pair(s); D3/mean(P) "
                  f"{math.exp(ld3 - log_meanP(s, J)):.4f} >= (T2) "
                  f"{math.exp(lb - log_meanP(s, J)):.4f} >= Ratio {R:.4f}; "
                  f"D3/LP {rat:.6f}", flush=True)
    print(f"  Lemma A: {reads} reads, actual/eps {worst[1]:.4f}..{worst[0]:.4f}"
          f"; sign +1 better at every read: {sign_ok}", flush=True)
    check("P2 (CONTROL): Lemma A holds at sign +1 at every read, actual/eps "
          "in [0.02, 1]", sign_ok and worst[0] <= 1 and worst[1] >= 0.02,
          f"{reads} reads")
    check("PLANT eps x 0.1 (q and u) fails P2 at some read", planted > 0,
          f"{planted} of {reads}")
    print(f"  owed conditions hold at {owed_n} of {len(SS) * 3} cells; "
          f"no-pair windows {nopair}; K2 breaches {k2}", flush=True)
    print(f"KILL K2: {'KILLED' if k2 or nopair else 'misses'}", flush=True)
    check("P3: at every owed cell a G sign change, D3 >= (T2) >= Ratio "
          "mean(P)", k2 == 0 and nopair == 0 and owed_n > 0,
          f"{owed_n} cells")
    check("P3: D3 at the proof's triple over the LP in [0.9, 1] at s >= 80",
          bool(lp_rat) and min(lp_rat) >= 0.9 and max(lp_rat) <= 1 + 1e-9,
          f"{min(lp_rat):.6f}..{max(lp_rat):.6f} over {len(lp_rat)}"
          if lp_rat else "no cell read")
    check("PLANT x_m + pi/(2 t_u) leaves no G sign change at some read",
          shifted_empty > 0, f"{shifted_empty} of {owed_n}")
    check("PLANT centre on q's node lowers D3 at every owed read",
          node_n == owed_n and node_low == node_n,
          f"{node_low} of {node_n} moves, {owed_n} cells")


def stage_grid():
    print("P4, P5: THE GRID, C step 0.01 in s^1.5 to 1000", flush=True)
    grid = np.arange(300, 100001) / 100
    out = {}
    for s in (100, 300, 1000, 3000, 10 ** 4, 10 ** 5, 10 ** 6):
        J = np.ceil(grid * s ** 1.5)
        R, info = bound(s, J)
        ok = (R > 1) & info["owed"]
        bad = np.nonzero(~ok)[0]
        cP = grid[bad[-1] + 1] if len(bad) else grid[0]
        out[s] = cP
        norm = R / (BETA * J ** 2 / (4 * s ** 3))
        sel = grid >= 4
        print(f"  s = {s}: J^P/s^1.5 {cP:.2f} (r^1.5: "
              f"{cP * (s / (s + 5)) ** 1.5:.2f}); Ratio/(beta J^2/(4 s^3)) "
              f"over C >= 4: {np.nanmin(norm[sel]):.4f}..{np.nanmax(norm[sel]):.4f}"
              f"; eps_q at C = 4 {float(info['eq'][100]):.5f}", flush=True)
        if s == 10 ** 6:
            p5 = (np.nanmin(norm[sel]), np.nanmax(norm[sel]))
    k1 = out[10 ** 4] > CL or out[10 ** 6] > CL
    print(f"KILL K1: J^P/s^1.5 at 10^4, 10^6 = {out[10 ** 4]:.2f}, "
          f"{out[10 ** 6]:.2f} against {CL:.5f}: "
          f"{'KILLED' if k1 else 'misses'}", flush=True)
    seq = [out[s] for s in sorted(out)]
    check("P4: J^P/s^1.5 in [3.79, 4.6], [3.79, 4.0], [3.79, 3.82] at 10^3, "
          "10^4, 10^6, falling",
          3.79 <= out[1000] <= 4.6 and 3.79 <= out[10 ** 4] <= 4.0
          and 3.79 <= out[10 ** 6] <= 3.82
          and all(a >= b for a, b in zip(seq, seq[1:])), str(seq))
    check("P5: Ratio/(beta J^2/(4 s^3)) at s = 10^6, C in [4, 1000], in "
          "[0.97, 1.01]", 0.97 <= p5[0] and p5[1] <= 1.01,
          f"{p5[0]:.4f}..{p5[1]:.4f}")


def main():
    t0 = time.time()
    print(f"beta = W(1/e) = {BETA:.9f}, 2/sqrt(beta) = {CB:.6f}", flush=True)
    stage_identity()
    stage_exact()
    stage_grid()
    print(f"{sum(CHECKS)}/{len(CHECKS)} checks, {time.time() - t0:.1f} s")
    return 0 if all(CHECKS) else 1


if __name__ == "__main__":
    sys.exit(main())