knife_cross.py

Checks: RULER: The knife: a consistent point inside an inconsistent interval property; known; theorem; rule.

Cited on: RULER.

To run it: save knife_cross.py, with knife_edge.py, knife_limit.py beside it; needs mpmath, numpy, scipy.

"""knife_cross.py -- does the knife's excess keep its sign past the edge?

QUESTION. C_M(mu) = P(|T| <= w), T = sum_r Y_r, Y_r = |Z_r + mu| - mu =
Z_r + u_r, u_r = 2(-Z_r - mu)_+, w = 1.96 sqrt M, level L. knife_edge.py
certified X = C_M(mu) - L > 0 where the one-tail term Q beats the
crude remainder R = (3/2) M (M - 1) p^2, p = Phi(-mu), from mu_c(M) to
12 on the grid (step 0.05); at M = 64 its mu_c, 3.85, sits above the
first grid bracket holding the level (3.3, knife_zone.py), so the grid
there between 3.3 and 3.8 is read by neither. Does the exact second
order of the excess close it, at every M of the brackets' twelve?

BY HAND (before any engine code).
  (E) The expansion. With G = sum Z_r, f the indicator of [-w, w] and
  u_C = sum_{r in C} u_r, Moebius inversion on the subsets of [M] gives
      f(G + u_[M]) - f(G) = sum_{B nonempty} D_B,
      D_B = sum_{C subset of B} (-1)^{|B| - |C|} f(G + u_C).
  D_B = 0 unless u_r > 0 at every r in B (pair C with C + {r}); its
  2^|B| terms are 0 or 1, half of each sign, so |D_B| <= 2^(|B| - 1).
  The B of size 1 give Q. So X = Q + Q2 + T3 exactly, Q2 the sum over
  pairs, and by independence (u_r > 0 with probability p each)
      |T3| <= sum_{k >= 3} C(M, k) 2^(k - 1) p^k
            = ((1 + 2p)^M - 1 - 2Mp - 2M(M - 1)p^2)/2 =: B3.
  At M = 2, T3 = 0 and X = Q + Q2 exactly; at M = 3, B3 = 4p^3.
  (Q2) One pair, Z_1 = -mu - a, Z_2 = -mu - b, a, b > 0, G = Z_1 + Z_2
  + G'', G'' ~ N(0, M - 2) independent; with F2(c) = P(|G'' + c| <= w),
  even, the four points read, after the evenness,
      E[D_12 | a, b] = H(a + b) - H(a - b),  H(x) = F2(2mu - x) + F2(2mu + x).
  phi(mu + a) phi(mu + b) = exp(-(mu + S/2)^2 - d^2/4)/(2 pi) at S = a
  + b, d = a - b, da db = dS dd/2 over |d| < S; integrating the H(S)
  part over d (erf) and the H(d) part over S > |d| (erfc), and H even,
      Q2 = C(M, 2)/(2 sqrt(pi)) int_0^inf H(x) K(x) dx,
      K(x) = exp(-(mu + x/2)^2) erf(x/2) - exp(-x^2/4) erfc(mu + x/2).
  H constant must give Q2 = 0, so int_0^inf K = 0: a check. At M = 2,
  G'' = 0 and F2 is the indicator of [-w, w], H's jumps at x = |2mu -+
  w|.
  (C) The certificate. X >= Q + Q2 - B3, so Q + Q2 > B3 certifies X >
  0. Sizes at M = 64, mu = 3.3 (p = 4.8e-4, Mp = 0.031): R is about
  (3/2)(Mp)^2 = 1.4e-3, B3 about (2/3)(Mp)^3 = 2e-5, and Q2/Q should
  be of order Mp (a TRANSPLANT from the large-mu split, where pairs are
  rare: unproved near the edge, where X/Q is 0.70 at M = 2, mu = 1).

PREDICTIONS. (1) M = 2: |X - Q - Q2| under 1e-12 at mu = 0.25, 0.5,
..., 8, X from knife_edge.excess (strongly: an identity). (2) M = 3:
|X - Q - Q2| <= 4p^3 at mu = 0.5, 1, ..., 3 (strongly: a proof). (3)
int_0^inf K = 0 to 1e-15 at mu = 0, 1, 3 (strongly). (4) The new
certificate mu_c2(M), the least grid mu (step 0.05, to 12) from which
Q + Q2 > B3 at every grid mu, at M in {3, 4, 5, 6, 8, 12, 15, 16, 24,
32, 48, 64, 100, 1000}: at most 3.3 at every M to 64, and below
mu_c(M) at every M (weakly: the sizes in (C) at 64 alone). (5) At M =
2, Q + Q2 = X, so its sign on mu = 0.01, ..., 8 changes once, between
0.24 and 0.25, as knife_edge (5) reads.

KILL (frozen; what the script PRINTS):
  "KILL cross: mu_c2(64) v" fires iff v > 3.3 (or None): then the
  second order leaves 64's stretch unread.

CONTROLS (read before any verdict). POSITIVE: (1) and (2), X from
knife_edge.excess, an instrument with its own controls there; (3).
PLANTS: Q2 with K's second term dropped must fail (1) (a constant-order
error); Q2 halved must fail (1) at some mu (Q2 is read only where it is
large against 1e-12, that count printed).

FINDINGS. The kill misses: "KILL cross: mu_c2(64) 3.0". Every
prediction held.
  CONTROLS: (3) "-2.96e-44, -7.72e-46, 1.66e-49"; (1) "worst 1.09e-41"
  over 32 mu, Q2 above 1e-10 at 11 of them (mu <= 2.75; the frozen
  count's bar, 1e-12, printed at 1e-10): at M = 2 the
  excess is exactly Q + Q2, e.g. mu = 0.25 "X 0.001076712, Q
  0.027116652, Q2 -0.02603994", mu = 1 X 0.024275291 = 0.034644939 -
  0.010369648; plants "worst 0.321" (K's term dropped), "worst 0.013"
  (halved); (2) |X - Q - Q2| / 4p^3 0.054, 0.093, 0.039, 0.0038,
  9.2e-6, 1.7e-9 at mu = 0.5, 1, ..., 3. Near the edge Q2 is of Q's
  size and negative (M = 2), so the (C) transplant fails near the edge;
  at mu = 3.3 Q2/Q sits far under Mp (about Mp/100 at M = 3, Mp/11 at
  64).
  (4): mu_c2 = 0.95, 1.25, 1.45, 1.6, 1.85, 2.1, 2.25, 2.3, 2.5, 2.65,
  2.85, 3.0, 3.2, 4.1 at M = 3, 4, 5, 6, 8, 12, 15, 16, 24, 32, 48, 64,
  100, 1000, each 0.75 to 0.95 under mu_c (recomputed in the same scan,
  equal to knife_edge's print at all 14). At mu = 3.3, Q2/Q runs from
  +1.4e-5 (M = 3), rising to 2.5e-4 (M = 6), through a sign change
  between M = 8 and 12, to -2.8e-3 (M = 64); B3 is 1.9e-5 at 64, R 1.4e-3. The sanity check
  (mu_c2 above the edge's bracket at 15, 64) passes.
  So, with knife_zone's brackets (wholly under the level below the
  edge, wholly over it from the edge to the first bracket holding the
  level, knife_zone's print "first straddle at mu =" 3.6, 3.65, 3.75,
  3.6, 3.6, 3.55, 3.5, 3.5, 3.4, 3.35, 3.3, 3.3 at M = 2, ..., 64), the
  grid mu = 0, 0.05, ..., 12 sees
  one crossing at every M of the eleven from 3 (M = 2 by knife_two.py's
  theorem): no grid mu past the edge is unread.
  (5): "sign changes at mu = [0.25]" from Q + Q2 alone: at M = 2 the
  sign of C_2 - L is that of two one-dimensional integrals. The stage
  is cut, knife_two.py proving the one crossing; the print is the
  record of the last run that held it.
  Run: 9/9 checks, 330.8 s, peak commit 104.4 MB, serial; again 349.8
  s, 104.2 MB, the figures above reproduced. With (5) cut, through the
  gate: 8/8 checks, 280.9 s, 97.3 MB.

RUN: python knife_cross.py.
"""
import os
import sys
import time

os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
import mpmath as mp  # noqa: E402

from knife_edge import CZ, L, Phi, excess, q_term  # noqa: E402

CHECKS = []
EDGE_HI = {15: 1.0567, 64: 1.5772}   # knife_zone.py's print


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 kernel(x, mu, plant=None):
    a = mp.exp(-(mu + x / 2) ** 2) * mp.erf(x / 2)
    b = mp.exp(-x * x / 4) * mp.erfc(mu + x / 2)
    return a if plant == "drop" else a - b


def q2_term(M, mu, plant=None):
    """Q2 = C(M, 2)/(2 sqrt pi) int_0^inf H(x) K(x) dx."""
    w = CZ * mp.sqrt(M)
    if M == 2:
        F2 = lambda c: mp.mpf(1) if abs(c) <= w else mp.mpf(0)
    else:
        sd = mp.sqrt(M - 2)
        F2 = lambda c: Phi((w - c) / sd) - Phi((-w - c) / sd)
    H = lambda x: F2(2 * mu - x) + F2(2 * mu + x)
    top = 60
    pts = sorted({mp.mpf(0), mp.mpf(top),
                  *(x for x in (abs(2 * mu - w), 2 * mu + w, 2 * mu)
                    if 0 < x < top)})
    v = mp.quad(lambda x: H(x) * kernel(x, mu, plant), pts)
    v *= mp.binomial(M, 2) / (2 * mp.sqrt(mp.pi))
    return v / 2 if plant == "half" else v


def b3(M, p):
    return sum(mp.binomial(M, k) * 2 ** (k - 1) * p ** k
               for k in range(3, M + 1))


def r_bound(M, p):
    return mp.mpf(3) / 2 * M * (M - 1) * p ** 2


if __name__ == "__main__":
    t0 = time.time()
    mp.mp.dps = 40
    print("CONTROLS")
    ks = [mp.quad(lambda x: kernel(x, mp.mpf(m)), [0, 2, 60]) for m in (0, 1, 3)]
    check("(3) int K = 0 at mu = 0, 1, 3", all(abs(k) < 1e-15 for k in ks),
          ", ".join(mp.nstr(k, 3) for k in ks))
    fam2 = [0.25 * k for k in range(1, 33)]
    rows2 = []
    for mu in fam2:
        x = mp.mpf(excess((2, mu))[0])
        m = mp.mpf(mu)
        rows2.append((mu, x, q_term(2, m), q2_term(2, m),
                      q2_term(2, m, "drop"), q2_term(2, m, "half")))
    mp.mp.dps = 40
    worst = max(abs(x - q - q2) for _, x, q, q2, _, _ in rows2)
    big = sum(1 for r in rows2 if abs(r[3]) > 1e-10)
    print(f"  M = 2: Q2 above 1e-10 at {big} of {len(rows2)} mu")
    for mu, x, q, q2, _, _ in rows2:
        if mu in (0.25, 0.5, 1, 2, 3, 4, 6):
            print(f"  M = 2, mu = {mu}: X {mp.nstr(x, 8)}, Q {mp.nstr(q, 8)},"
                  f" Q2 {mp.nstr(q2, 8)}, |X - Q - Q2| "
                  f"{mp.nstr(abs(x - q - q2), 3)}")
    check("(1) M = 2: |X - Q - Q2| < 1e-12 at every mu", worst < 1e-12,
          f"worst {mp.nstr(worst, 3)}")
    for key, i in (("K's second term dropped", 4), ("Q2 halved", 5)):
        bad = max(abs(r[1] - r[2] - r[i]) for r in rows2)
        check(f"PLANT: {key} fails (1)", bad >= 1e-12, f"worst {mp.nstr(bad, 3)}")
    mp.mp.dps = 24
    ok3 = []
    for mu in (0.5, 1.0, 1.5, 2.0, 2.5, 3.0):
        x = mp.mpf(excess((3, mu))[0])
        mp.mp.dps = 24
        m = mp.mpf(mu)
        p = Phi(-m)
        d = abs(x - q_term(3, m) - q2_term(3, m))
        ok3.append(d <= 4 * p ** 3)
        print(f"  M = 3, mu = {mu}: |X - Q - Q2| {mp.nstr(d, 4)}, 4p^3 "
              f"{mp.nstr(4 * p ** 3, 4)}, ratio {mp.nstr(d / (4 * p ** 3), 4)}",
              flush=True)
    check("(2) M = 3: |X - Q - Q2| <= 4p^3 at mu = 0.5..3", all(ok3))
    if not all(CHECKS):
        print("CONTROL FAILED: nothing below is read.")
        sys.exit(1)

    print("THE CERTIFICATE mu_c2(M): Q + Q2 > B3 at every grid mu to 12")
    mp.mp.dps = 25
    cert, cert1 = {}, {}
    for M in (3, 4, 5, 6, 8, 12, 15, 16, 24, 32, 48, 64, 100, 1000):
        k, k1 = 240, None
        while k > 0:
            m = mp.mpf(k) / 20
            p = Phi(-m)
            q = q_term(M, m)
            if k1 is None and not q > r_bound(M, p):
                k1 = k
            q2 = q2_term(M, m)
            if not q + q2 > b3(M, p):
                break
            if k in (66, 80):
                print(f"    M = {M}, mu = {k / 20}: Q {mp.nstr(q, 5)}, Q2 "
                      f"{mp.nstr(q2, 5)}, B3 {mp.nstr(b3(M, p), 3)}, R "
                      f"{mp.nstr(r_bound(M, p), 3)}", flush=True)
            k -= 1
        cert[M] = (k + 1) / 20 if k < 240 else None
        cert1[M] = (k1 + 1) / 20 if k1 is not None else "below mu_c2"
        print(f"  M = {M}: mu_c2 {cert[M]}, mu_c {cert1[M]}", flush=True)
    check("mu_c2 above the edge's bracket at M = 15, 64 (X < 0 below it)",
          all(cert[M] > EDGE_HI[M] for M in (15, 64)))
    check("(4) mu_c2 <= 3.3 at every M to 64",
          all(cert[M] is not None and cert[M] <= 3.3 for M in cert if M <= 64))
    check("(4) mu_c2 below mu_c at every M",
          all(not isinstance(cert1[M], str) and cert[M] < cert1[M]
              for M in cert))
    v = cert[64]
    print(f"KILL cross: mu_c2(64) {v}")
    print(f"KILL fires: {v is None or v > 3.3}")

    print(f"\n{sum(CHECKS)}/{len(CHECKS)} checks, {time.time() - t0:.1f} s")
    sys.exit(0 if all(CHECKS) else 1)