altproof.py

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

Cited on: FLATTEN.

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

"""altproof.py -- the d = 2 alternation certificate by hand: does a
proof with no step a run put order r - 3's real least above H_ch from
(2 sqrt(2 exp 1) + o(1)) l^(3/2), l = r - 2?

Frozen before this file's code.

NOTATION. Flipped. n0 = (J + l + 1)/2, j = k - n0. Q = (1 + x)^(J+1)(1 -
x)^l, beta = P = (1 + x)^J (1 - x)^(l+1), the champion, both of degree
2n0, alpha = (1 + x)^(J+2) (1 - x)^(l-1)/4. At real e* = n0/(2l), F =
alpha + (e* - 1/4) beta has F_k = -j q_k/(2l) (losses.py's (H1) at real
e). D at a pair is unchanged by alpha -> alpha + c beta, so D_(i,i+1) =
|F_i b_(i+1) - F_(i+1) b_i|/(|b_i| + |b_(i+1)|), b beta's coefficients;
where b changes sign and F does not, D >= min(|F_i|, |F_(i+1)|); a zero
b_i gives |F_i| alone.

BY HAND. t_Q = t_l and t_P = t_(l+1) are f_l's and f_(l+1)'s peaks, A_Q =
A_l, A_P = A_(l+1), eps_Q = eps_l, eps_P = eps_(l+1) (Lemma A).
 (S1) On z = e^(it), |t| < pi, f_a(t) = (2 cos(t/2))^(2n0 - a)(2
      sin(t/2))^a, f_a(-t) = (-1)^a f_a(t): 1 + z = 2 cos(t/2) e^(it/2),
      1 - z = -2i sin(t/2) e^(it/2), so Q = (-i)^l e^(i n0 t) f_l, P =
      (-i)^(l+1) e^(i n0 t) f_(l+1). Folding (-pi, 0) onto (0, pi) by the
      parity, with I_a(j) = (1/pi) int_0^pi f_a e^(ijt) dt: q_(n0+j) =
      Re(i^(-l) I_l(j)) and p_(n0+j) = -Im(i^(-l) I_(l+1)(j)) at even l,
      both negated at odd l.
 (S2) LEMMA A. phi = log f_a, phi'' = -(a csc^2 x + b sec^2 x)/4 (x =
      t/2, b = 2n0 - a) < 0, peak tan^2(t_a/2) = a/b, -phi''(t_a) = n0
      (csc^2 = (a + b)/a, sec^2 = (a + b)/b there); phi''' = (a csc^2 x
      cot x - b sec^2 x tan x)/4, two positive terms, the first falling,
      the second rising, so on [t_a - s1, t_a + s1] |phi'''| <= K =
      max(a csc^2 cot at the left end, b sec^2 tan at the right)/4. If s1
      <= t_a/2, t_a + s1 < pi, K s1^3 <= 6 and m > 0 (below): |I_a(j) -
      A_a e^(i j t_a - j^2/(2n0))| <=
      A_a eps_a at every real j, A_a = f_a(t_a) sqrt(2 pi/n0)/pi, eps_a =
      (e - 1)(2K/3)/(sqrt(2 pi) n0^(3/2)) + 2(e/m + 1/n0) e^(-n0
      s1^2/2)/(s1 sqrt(2 pi/n0)), m = n0 - K s1/2. Proof: inner, |s| <=
      s1, phi(t_a + s) = phi(t_a) - n0 s^2/2 + R, |R| <= K|s|^3/6 <= 1,
      |e^R - 1| <= (e - 1)|R| ((e^R - 1)/R rises), int |s|^3 e^(-n0 s^2/2)
      ds = 4/n0^2. Outer: |phi''(t_a + u) + n0| <= K|u|, so phi' at t_a
      + s1 is at most -m s1 and phi(t_a + s1) <= phi(t_a) - n0 s1^2/2 + 1;
      concavity bounds f beyond by f(t_a) e^(1 - n0 s1^2/2) e^(-m s1 v),
      integral f(t_a) e^(1 - n0 s1^2/2)/(m s1), the same on the left; the
      Gaussian's tails beyond +-s1 (all of it outside (0, pi)) add
      f(t_a) e^(-n0 s1^2/2)/(n0 s1) each.
 (S3) THE ZERO. theta(x) = x t_P - l pi/2; p's main term A_P e^(-j^2/
      (2n0)) sin theta(j), q's A_Q e^(-j^2/(2n0)) cos(j t_Q - l pi/2) (up
      to (S1)'s signs). x_m, a zero of sin theta within pi/(2 t_P) of j* =
      sqrt(n0); eta = eps_P e^((j* + pi/t_P)^2/(2n0)), delta = arcsin(eta)
      /t_P, U = pi/(2 t_P) + delta + 1 (owed eta < 1, U <= pi/t_P, the
      latter giving (delta + 1) t_P <= pi/2). The
      lattice points j_a < x_m - delta and j_b > x_m + delta nearest it lie
      within delta + 1 of x_m, so (delta + 1) t_P <= pi/2 gives |sin
      theta| > sin(delta t_P) = eta there, and |j| <= j* + pi/t_P gives
      e^(-j^2/(2n0)) eta >= eps_P: p has the main term's sign at both,
      opposite, so a strict sign change or a zero lies between, inside
      [x_m - delta - 1, x_m + delta + 1].
 (S4) THERE, q keeps its sign: j t_Q - l pi/2 = theta(x_m) + (j - x_m)
      t_P + j(t_Q - t_P), theta(x_m) in pi Z, so |cos(j t_Q - l pi/2)| >=
      cos Dth with one sign over the window, Dth = (delta + 1) t_P + (j* +
      U)|t_Q - t_P| (owed Dth < pi/2, cos Dth > eps_Q e^((j* + U)^2/(2n0)),
      j* > U, so j > 0 too). F = -j q/(2l) then keeps one sign, and D >=
      (A_Q/(2l))[w_min cos Dth - (j* + U) eps_Q], w_min the least of j
      e^(-j^2/(2n0)) at j* -+ U (it is unimodal, its peak at j*).
 (S5) H_ch <= mean(P) = 2^(2n0) B((l + 2)/2, (J + 1)/2)/pi (a coefficient
      is at most the mean modulus). With a' = (l + 2)/2, b' = (J + 1)/2,
      a' - 1 + b' = n0: f_l(t_Q) = 2^(2n0) (b'/n0)^(b') ((a' - 1)/n0)^(a'
      - 1), 1/B = Gamma(n0 + 1)/(Gamma(a') Gamma(b')), Gamma(n0 + 1) = n0
      Gamma(n0), Gamma(a') = (a' - 1) Gamma(a' - 1) and Gamma(x) = sqrt(2
      pi) x^(x - 1/2) e^(-x + mu(x)), 0 < mu(x) < 1/(12x) (Binet), so,
      the exponentials cancelling, EXACTLY f_l(t_Q)/(2^(2n0) B) =
      sqrt(n0 (J + 1)/l) e^(Dmu)/sqrt(2 pi), Dmu = mu(n0) - mu(l/2) -
      mu((J + 1)/2) > -1/(6l) - 1/(6(J + 1)). So D/H_ch >= Ratio =
      sqrt((J + 1)/l) e^(Dmu) [w_min cos Dth - (j* + U) eps_Q]/(2l), and
      Ratio > 1 with the owed conditions certifies order r - 3 at (r, J).
 (S6) THE LIMIT, uniformly over J >= l^(3/2) as l grows. Take s1 =
      a^(1/6)/sqrt(n0). x_a = t_a/2 has sin^2 x_a = a/(2n0) and sqrt(n0)
      x_a >= sqrt(a/2), so s1/t_a <= a^(-1/3)/sqrt(2), free of n0; on the
      interval sin x >= sin x_a (1 - s1/t_a) (sin concave), so the first
      term of K is at most (2n0)^(3/2)/(4 sqrt a)(1 + O(a^(-1/3))); the
      second, b tan sec^2 near x_a, is O(sqrt(a b)) = O(sqrt(a n0)), at
      most O(a/b) = O(l^(-1/2)) of the first. So K = n0^(3/2)(1 +
      O(l^(-1/3)))/sqrt(2a), K s1^3 -> 1/sqrt 2 < 6, K s1/n0 -> 0, and
      eps <= 0.3232(1 + O(a^(-1/3)))/sqrt(a) + O(a^(-1/6) e^(-a^(1/3)/
      2)) -> 0 (s1 <= t_a/2 once a >= 3), every bound
      free of J. tan x_P = sqrt((l + 1)/J) <= l^(-1/4)(1 + o(1)), so t_P
      <= 2.1 l^(-1/4) and t_P sqrt(n0) = sqrt(2(l + 1))(1 + O(l^(-1/2))):
      U/j* ~ pi/(2 sqrt(2l)) -> 0 and delta t_P = arcsin eta -> 0. d
      t_a/da = 1/sqrt(a(2n0 - a)), so |t_Q - t_P| <= 1/sqrt(l J) and (j*
      + U)|t_Q - t_P| <= 2 sqrt(n0/(l J)) -> 0; Dth -> 0; Dmu -> 0. Every
      owed condition then holds, w_min = sqrt(n0) e^(-1/2)(1 + o(1)), and
      sqrt((J + 1) n0) >= J/sqrt 2: Ratio >= J (1 - o(1))/(2 sqrt(2 exp
      1) l^(3/2)), the o(1) free of J.

PREDICTIONS (frozen).
  P1 CONTROL (Lemma A against exact integers): at l = 20, 40, 80, 160, J
     = round(C l^1.5), C = 4, 6, 10: max over j of |q - main|/A_Q <= eps_Q
     and |p - main|/A_P <= eps_P, one global sign each; actual/eps in
     [0.02, 1].
  P2 at those reads with Ratio > 0: the window holds a sign change or
     zero of p in integers; the exact D there over mean(P) >= Ratio; that
     D equals the alpha-form D for the same pair at one small cell.
  P3 J^P(l), the least J on the grid C step 0.01 from which Ratio > 1 up
     to C = 1000: J^P/l^1.5 in [5.0, 6.5] at l = 100, [4.663, 4.85] at
     10^4, [4.663, 4.70] at 10^6, falling.
  P4 every owed condition of (S2)..(S4) holds on P3's grid from C = 4.6
     at l >= 100.
KILL. K1 J^P/l^1.5 > 5.1296 (1.1 x 4.66329) at l = 10^4 or 10^6. K2 the
  exact D/mean(P) below Ratio at any read. K3 P1 fails.
CONTROLS. P1; (S1)'s sign read off; plants: eps_Q x 0.1 must fail P1 at
  some read; x_m moved by pi/(2 t_P) must leave a window with no sign
  change at some read.

FINDINGS (copied from the printed output). K1, K2, K3 miss; P1..P4 hold.
  (1) CONTROLS: the F-form D equals the alpha-form D exactly at (r,
      J) = (12, 150), pair k = 48. Lemma A holds at all 27 cells (q and
      p, 54 reads), actual/eps 0.0636..0.2427. The signs are +1, -1 (q,
      p) at even l and -1, +1 at odd, as (S1) says, the wrong sign erring
      over 10x more, q and p, at every cell. Both plants fire at 21 of 27.
  (2) P2: at every cell with Ratio > 0 the owed conditions hold, the
      window holds a sign change or zero of p, and its exact D/mean(P)
      sits above Ratio: 0.8572, 1.2868, 2.1368 at l = 161, C = 4, 6, 10
      against C/(2 sqrt(2 exp 1)) = 0.858, 1.287, 2.144; Ratio there
      0.6897, 1.0582, 1.7996. At l = 20, 21 Ratio < 0 (eps 0.42988..0.51686).
  (3) P3, P4: J^P/l^1.5 = 6.43, 5.24, 4.90, 4.78, 4.72, 4.68, 4.67 at l =
      100, 300, 10^3, 3000, 10^4, 10^5, 10^6, falling; Ratio x 2 sqrt(2
      exp 1) l^1.5/J over C >= J^P/l^1.5, to C = 1000, lies in
      0.7261..0.8074 at l = 100, 0.9888..0.9931 at 10^4 and
      0.9991..0.9994 at 10^6; no owed condition fails on the grid from C =
      4.6. eps_Q at C = 5 is 0.07594 at l = 100, 0.00392 at 10^4, 0.00034
      at 10^6.
  So, by hand ((S1)..(S6), no step a run): for every C > 2 sqrt(2 exp 1)
  there is an l_0 with order r - 3's real least height above H_ch at
  every J >= C l^(3/2), l >= l_0. With the lattice F_e at J_e = (4e -
  1) l - 1 from below (losses.py), order r - 3's last failing depth is
  (2 sqrt(2 exp 1) + o(1)) l^(3/2). The grid's crossings are reads at C
  step 0.01, not every J.
CHANGED AFTER THE FREEZE. P1's family froze l = 20, 40, 80, 160, all
  even; (S1) parts on the parity of l, so l = 21, 42, 43, 81, 161 joined
  it (27 cells; l = 40, dropped by an edit, was restored). (S1)'s sign
  check reads the parity rule and both arrays. P2's invariance reads
  the alpha-form D written out at one pair, not a certificate search;
  P2 and K2 read only cells whose owed conditions hold (all 21 with
  Ratio > 0). J^P counts a grid point as certified only where Ratio > 1
  and the owed conditions hold. (S6) takes s1 = a^(1/6)/sqrt(n0); the
  script takes the largest feasible s1 by bisection. FINDINGS entered
  with the file; (1) and the record were read again after the repairs.
RUN RECORD. Bare: 8/8, 2.4 s, peak 173.4 MB.

RUN: python altproof.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

CHECKS = []
C1 = 2 * math.sqrt(2 * math.e)
E1 = math.e - 1


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)


# ------------------------------------------------------------- the bound
# Every function below takes numpy arrays (or floats) in J at fixed l.

def peak(a, n0):
    """t_a, the peak of f_a: tan^2(t_a/2) = a/(2 n0 - a)."""
    return 2 * np.arctan(np.sqrt(a / (2 * n0 - a)))


def kbound(a, n0, ta, s):
    """K on [ta - s, ta + s]: the larger end value of phi''''s two
    monotone terms, over 4."""
    b = 2 * n0 - a
    xl, xr = (ta - s) / 2, (ta + s) / 2
    t1 = a / np.sin(xl) ** 2 / np.tan(xl)
    t2 = b * np.tan(xr) / np.cos(xr) ** 2
    return np.maximum(t1, t2) / 4


def lemma_a(a, n0):
    """(eps_a, t_a, s1, K, m): s1 the largest s <= t_a/2 with K s^3 <= 6
    (bisection; K s^3 rises in s)."""
    ta = peak(a, n0)
    lo, hi = np.zeros_like(n0), ta / 2
    full = kbound(a, n0, ta, hi) * hi ** 3 <= 6
    for _ in range(60):
        mid = (lo + hi) / 2
        ok = kbound(a, n0, ta, mid) * mid ** 3 <= 6
        lo, hi = np.where(ok, mid, lo), np.where(ok, hi, mid)
    s1 = np.where(full, ta / 2, lo)
    K = kbound(a, n0, ta, s1)
    m = n0 - K * s1 / 2
    eps_in = E1 * (2 * K / 3) / (math.sqrt(2 * math.pi) * n0 ** 1.5)
    eps_out = (2 * (math.e / m + 1 / n0) * np.exp(-n0 * s1 ** 2 / 2)
               / (s1 * np.sqrt(2 * math.pi / n0)))
    return eps_in + eps_out, ta, s1, K, m


def ratio(l, J):
    """Ratio of (S5) and its pieces; owed conditions as a boolean."""
    J = np.asarray(J, dtype=float)
    n0 = (J + l + 1) / 2
    eQ, tQ, s1Q, KQ, mQ = lemma_a(l, n0)
    eP, tP, s1P, KP, mP = lemma_a(l + 1, n0)
    js = np.sqrt(n0)
    eta = eP * np.exp((js + math.pi / tP) ** 2 / (2 * n0))
    delta = np.arcsin(np.minimum(eta, 1.0)) / tP
    U = math.pi / (2 * tP) + delta + 1
    Dth = (delta + 1) * tP + (js + U) * np.abs(tQ - tP)
    w_min = np.minimum((js - U) * np.exp(-(js - U) ** 2 / (2 * n0)),
                       (js + U) * np.exp(-(js + U) ** 2 / (2 * n0)))
    dmu = -1 / (6 * l) - 1 / (6 * (J + 1))
    R = (np.sqrt((J + 1) / l) * np.exp(dmu)
         * (w_min * np.cos(Dth) - (js + U) * eQ) / (2 * l))
    owed = ((mQ > 0) & (mP > 0) & (eta < 1) & (U <= math.pi / tP)
            & (Dth < math.pi / 2)
            & (np.cos(Dth) > eQ * np.exp((js + U) ** 2 / (2 * n0)))
            & (js > U))
    return R, dict(eQ=eQ, eP=eP, tQ=tQ, tP=tP, js=js, delta=delta, U=U,
                   Dth=Dth, w_min=w_min, owed=owed, n0=n0)


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

def logabs(v):
    return math.log(abs(v))


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


def log_meanP(l, J):
    n0 = (J + l + 1) / 2
    return (2 * n0 * math.log(2) + math.lgamma((l + 2) / 2)
            + math.lgamma((J + 1) / 2) - math.lgamma(n0 + 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(logabs(v) - la) * (1.0 if v > 0 else -1.0)


def lemma_read(l, J, q, p, info):
    """max over j of |q/A_Q -+ main| and |p/A_P -+ main|, the better
    global sign each; returns (errQ, errP, signQ, signP, wrong-sign errQ,
    wrong-sign errP)."""
    n0 = (J + l + 1) / 2
    lQ, lP = log_A(l, l, J), log_A(l + 1, l, J)
    tQ, tP = float(info["tQ"]), float(info["tP"])
    best = {}
    for name, arr, la, t, trig in (("Q", q, lQ, tQ, math.cos),
                                   ("P", p, lP, tP, math.sin)):
        errs = {1: 0.0, -1: 0.0}
        for k, v in enumerate(arr):
            j = k - n0
            main = math.exp(-j * j / (2 * n0)) * trig(j * t - l * math.pi / 2)
            x = scaled(v, la)
            for sg in (1, -1):
                errs[sg] = max(errs[sg], abs(sg * x - main))
        sg = min(errs, key=errs.get)
        best[name] = (errs[sg], sg, errs[-sg])
    return (best["Q"][0], best["P"][0], best["Q"][1], best["P"][1], best["Q"][2],
            best["P"][2])


def window(l, J, info, shift=0.0):
    """(lo, hi, x_m): the window of (S3) as k indices; x_m the zero of
    sin theta nearest j* (shift moves it, the plant)."""
    n0 = (J + l + 1) / 2
    tP, js, delta = float(info["tP"]), float(info["js"]), float(info["delta"])
    # zeros of sin(x tP - l pi/2): x = (c pi + l pi/2)/tP
    c = round((js * tP - l * math.pi / 2) / math.pi)
    xm = (c * math.pi + l * math.pi / 2) / tP + shift
    lo = math.ceil(n0 + xm - delta - 1)
    hi = math.floor(n0 + xm + delta + 1)
    return lo, hi, xm


def window_D(l, J, q, p, lo, hi):
    """Exact certificates inside [lo, hi]: the largest D over strict sign
    changes and zeros of p there, as a Fraction (None if neither)."""
    twon0 = J + l + 1
    best, found = None, False
    for k in range(max(lo, 0), min(hi, len(p) - 1) + 1):
        Nk = (2 * k - twon0) * q[k]           # 4l F_k
        if p[k] == 0:
            found = True
            d = Fraction(abs(Nk), 4 * l)
        elif k + 1 <= hi and p[k] * p[k + 1] < 0:
            found = True
            N1 = (2 * (k + 1) - twon0) * q[k + 1]
            d = Fraction(abs(Nk * p[k + 1] - N1 * p[k]),
                         4 * l * (abs(p[k]) + abs(p[k + 1])))
        else:
            continue
        if best is None or d > best:
            best = d
    return best if found else None


def alpha_D(r, J, k):
    """The alpha-form D at the pair (k, k + 1): A = 4 alpha, B = beta."""
    A, B = coeffs(J + 2, r - 3), coeffs(J, r - 1)
    return Fraction(abs(A[k] * B[k + 1] - A[k + 1] * B[k]),
                    4 * (abs(B[k]) + abs(B[k + 1])))


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

def stage_exact():
    print("EXACT READS: Lemma A and the window against integers", flush=True)
    bad1, bad2, ratios, planted, shifted_empty, k2 = 0, 0, [], 0, 0, 0
    signs_ok = True
    LS = (20, 21, 40, 42, 43, 80, 81, 160, 161)
    for l in LS:
        for C in (4, 6, 10):
            t0 = time.time()
            J = round(C * l ** 1.5)
            q, p = coeffs(J + 1, l), coeffs(J, l + 1)
            R, info = ratio(l, J)
            R = float(R)
            eQ, eP = float(info["eQ"]), float(info["eP"])
            erQ, erP, sQ, sP, wrongQ, wrongP = lemma_read(l, J, q, p, info)
            signs_ok &= wrongQ > 10 * erQ and wrongP > 10 * erP
            # (S1): q = Re(i^-l I), p = -Im(i^-l I_P) at even l; both flip at odd
            signs_ok &= (sQ, sP) == ((1, -1) if l % 2 == 0 else (-1, 1))
            ok1 = erQ <= eQ and erP <= eP
            bad1 += not ok1
            planted += erQ > 0.1 * eQ
            ratios += [erQ / eQ, erP / eP]
            lo, hi, xm = window(l, J, info)
            D = window_D(l, J, q, p, lo, hi)
            owed = bool(info["owed"])
            line = (f"  l = {l:3d}, C = {C:2d}, J = {J:5d}: errQ {erQ:.5f} <= "
                    f"epsQ {eQ:.5f}, errP {erP:.5f} <= epsP {eP:.5f} "
                    f"({'ok' if ok1 else 'BREACH'}); signs {sQ:+d} {sP:+d}; "
                    f"Ratio {R:.4f} (owed {'held' if owed else 'not held'})")
            if D is None:
                line += f"; window [{lo}, {hi}] EMPTY"
                if R > 0 and owed:
                    bad2 += 1
            else:
                dm = math.exp(math.log(D.numerator) - math.log(D.denominator)
                              - log_meanP(l, J))
                line += f"; window D/mean(P) {dm:.4f}"
                if R > 0 and owed and dm < R:
                    k2 += 1
            lo2, hi2, _ = window(l, J, info, shift=math.pi / (2 * float(info["tP"])))
            shifted_empty += window_D(l, J, q, p, lo2, hi2) is None
            print(line + f"  ({time.time() - t0:.1f} s)", flush=True)
    check("K3 misses / P1: Lemma A's bound holds at every read (q and p)",
          bad1 == 0, f"{bad1} breaches")
    check("(S1)'s signs: +1, -1 (q, p) at even l, -1, +1 at odd; the wrong "
          "sign errs >10x more, q and p, at every read",
          signs_ok)
    print(f"  P1 actual/eps over the {len(ratios)} reads: {min(ratios):.4f}.."
          f"{max(ratios):.4f} (frozen band [0.02, 1])", flush=True)
    check("plant: eps_Q x 0.1 is breached at some read", planted > 0,
          f"{planted} of {3 * len(LS)}")
    check("P2: every window with Ratio > 0 and its conditions held has a "
          "sign change or zero", bad2 == 0, f"{bad2} empty")
    check("K2 misses: exact window D/mean(P) >= Ratio wherever owed",
          k2 == 0, f"{k2} below")
    check("plant: x_m moved by pi/(2 t_P) leaves some window empty",
          shifted_empty > 0, f"{shifted_empty} of {3 * len(LS)}")


def stage_invariance():
    print("INVARIANCE: F-form D = alpha-form D at one cell", flush=True)
    r, J = 12, 150
    l = r - 2
    q, p = coeffs(J + 1, l), coeffs(J, l + 1)
    twon0 = J + l + 1
    k = next(i for i in range(len(p) - 1) if p[i] * p[i + 1] < 0)
    N0, N1 = (2 * k - twon0) * q[k], (2 * (k + 1) - twon0) * q[k + 1]
    dF = Fraction(abs(N0 * p[k + 1] - N1 * p[k]),
                  4 * l * (abs(p[k]) + abs(p[k + 1])))
    dA = alpha_D(r, J, k)
    check(f"F-form D = alpha-form D at (r, J) = ({r}, {J}), pair k = {k}",
          dF == dA, f"{float(dF):.6g}")


def stage_grid():
    print("GRID: the hand crossing J^P(l)/l^1.5, C = 4.00..1000 step 0.01",
          flush=True)
    Cs = np.round(np.arange(400, 100001) / 100, 2)
    out = {}
    for l in (100, 300, 1000, 3000, 10 ** 4, 10 ** 5, 10 ** 6):
        J = np.floor(Cs * l ** 1.5)
        R, info = ratio(l, J)
        good = (R > 1) & info["owed"]
        bad = np.nonzero(~good)[0]
        cP = Cs[bad[-1] + 1] if len(bad) else Cs[0]
        from_ = Cs >= 4.6
        owed_fail = int(np.sum(~info["owed"][from_]))
        norm = R * C1 * l ** 1.5 / J
        sel = Cs >= cP
        out[l] = (cP, owed_fail)
        print(f"  l = {l:7d}: J^P/l^1.5 = {cP:.2f}; owed conditions fail at "
              f"{owed_fail} of {int(from_.sum())} grid points from C = 4.6; "
              f"Ratio x 2 sqrt(2e) l^1.5/J over C >= J^P: "
              f"{norm[sel].min():.4f}..{norm[sel].max():.4f}; epsQ at C = 5: "
              f"{float(info['eQ'][100]):.5f}", flush=True)
    print(f"  P3 bands: l = 100 in [5.0, 6.5]: {out[100][0]}; 10^4 in "
          f"[4.663, 4.85]: {out[10 ** 4][0]}; 10^6 in [4.663, 4.70]: "
          f"{out[10 ** 6][0]}", flush=True)
    seq = [out[l][0] for l in sorted(out)]
    print(f"  falling: {all(a >= b for a, b in zip(seq, seq[1:]))}", flush=True)
    check("K1 misses: J^P/l^1.5 <= 5.1296 at l = 10^4 and 10^6",
          out[10 ** 4][0] <= 5.1296 and out[10 ** 6][0] <= 5.1296,
          f"{out[10 ** 4][0]}, {out[10 ** 6][0]}")
    print(f"  P4 owed failures from C = 4.6: "
          f"{[out[l][1] for l in sorted(out)]}", flush=True)
    return out


def main():
    t0 = time.time()
    stage_invariance()
    stage_exact()
    stage_grid()
    print(f"{sum(CHECKS)}/{len(CHECKS)} checks, {time.time() - t0:.1f} s",
          flush=True)
    return 0 if all(CHECKS) else 1


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