knife_two.py

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

Cited on: RULER.

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

"""knife_two.py -- the knife's limit at M = 2 in closed form, one crossing.

QUESTION. At M = 2, C_2(mu) = P(| |A| + |B| - 2 mu | <= w), A, B iid
N(mu, 1), w = 1.96 sqrt 2, level L = 2 Phi(1.96) - 1. Does C_2 - L
change sign exactly once on mu >= 0?

BY HAND (before any engine code; the proof is the result, this script
its numeric control).
  |x| + |y| = max(|x + y|, |x - y|), so |A| + |B| = sqrt2 max(|U|, |V|),
  U = (A + B)/sqrt2 ~ N(t, 1), V = (A - B)/sqrt2 ~ N(0, 1), independent,
  t = sqrt2 mu. With a = w/sqrt2 = 1.96 the window is max(|U|, |V|) in
  [t - a, t + a], and P(max <= s) = [Phi(s - t) - Phi(-s - t)][2 Phi(s)
  - 1], so
      C_2 = g(t) - h(t),
      g(t) = [Phi(a) - Phi(-a - 2t)][2 Phi(a + t) - 1],
      h(t) = [Phi(-a) - Phi(a - 2t)][2 Phi(t - a) - 1] at t > a, else 0.
  (i) t <= a: both factors of g are positive and strictly increasing, so
  C_2 strictly increases; g(0) = L^2 < L; with eps = Phi(-a), g(a) >=
  1 - eps - Phi(-3a) - 2 Phi(-2a) > 1 - 2 eps = L, as eps > Phi(-3a) +
  2 Phi(-2a): Mills' bounds x phi(x)/(1 + x^2) <= Phi(-x) <= phi(x)/x
  give eps >= 0.02365, Phi(-2a) <= 4.69e-5, Phi(-3a) <= 2.2e-9
  (phi(1.96) >= 0.05844, phi(3.92) <= 1.84e-4, phi(5.88) <= 1.3e-8).
  One crossing in (0, a/sqrt2).
  (ii) t > a, u = t - a: with alpha = Phi(-3a - 2u), beta = Phi(-2a - u),
  gamma = Phi(-a - 2u), delta = Phi(-u) <= 1/2,
      X = C_2 - L = gamma(1 - 2 delta) + 2 eps delta
                    - alpha - 2 beta(1 - eps - alpha)
        >= 2 eps delta - 3 beta = Phi(-u)[2 eps - 3 r(u)],
  r(u) = Phi(-2a - u)/Phi(-u) decreasing (the normal tail is
  log-concave), r(0) = 2 Phi(-2a): X >= Phi(-u)[2 Phi(-a) - 6 Phi(-2a)]
  >= 0.047 Phi(-u) > 0 by the same bounds. h(a) = 0, so C_2 is
  continuous at t = a.
  (iii) As u grows, gamma, beta, alpha are o(delta): X ~ 2 Phi(-1.96)
  Phi(1.96 - sqrt2 mu).

PREDICTIONS. (1) The closed form equals knife_edge.excess at M = 2 to
1e-30 at mu = 0.25, 0.5, ..., 8 (strongly: an identity; excess is good
to about 1e-38, its own error printed, and X stays above 1e-22 by hand,
2.2e-22 at mu = 8 from (iii), so the bar reads 8 digits or more). (2)
mu*(2), the root of g(sqrt2 mu) = L, lies in knife_zone's [0.2392,
0.2413] (strongly). (3) The lower bound Phi(-u)[2 eps - 3 r(u)] is <= X
at every grid u, and r decreases on the grid (strongly). (4) X / [2
Phi(-a) Phi(a - t)] tends to 1: within 1e-3 of 1 by mu = 8 (weakly).

KILL (frozen; what the script PRINTS):
  "KILL two: worst |closed - excess| v" fires iff v >= 1e-30 over the
  32 mu: the closed form is wrong.

CONTROLS (read before any verdict). POSITIVE: C_2(0) = L^2 to 1e-30;
knife_edge.excess is an instrument with its own controls there.
PLANTS: h dropped must fail (1) (caught at mu > 1.386, where h > 1e-30:
counted); the V factor 2 Phi(t + a) - 1 replaced by 2 Phi(a) - 1 must
fail (1) at every mu > 0.

FINDINGS. The kill misses: "KILL two: worst |closed - excess| 1.7e-41".
Every prediction held.
  CONTROLS: C_2(0) = L^2 exactly at 40 digits ("0.0"), an identity of
  g; the instrument at the same known answer, excess at mu = 0 against
  L^2 - L, "0.0" too (an arm added after the first run). The excess's
  own error is at most 8.43e-32 over the 32 mu (its 30- against
  40-digit gap, not the 1e-38 predicted; the bar 1e-30 sits above
  it), the least |X| 2.12e-22 (mu = 8, "2.11550321392e-22" both
  ways); plants: h dropped caught at 27 mu,
  exactly the mu > 1.386; the V factor frozen at 32 of 32 (the plant
  freezes h's factor 2 Phi(t - a) - 1 as well as g's, beyond the frozen
  wording).
  (1) e.g. mu = 1: excess and closed form both 0.0242752913495, gap
  7.53e-42.
  The proof's constants: (i) "0.024909344", (ii) "0.049730143".
  (2) "mu*(2) = 0.240152725641689", inside [0.2392, 0.2413]; C_2 at
  1.96/sqrt2 exceeds L by 0.024911558.
  (3) on mu = 0, 0.001, ..., 8, X rises strictly to 1.96/sqrt2, and at
  the 6615 grid mu past it X > 0, X at least the lower bound, r falling
  from 8.852e-5 to 3.886e-20; "sign changes ... at [0.241]". The float
  wall: near mu = 8 the margin X - lower is about beta, 1.7e-40 (the
  printed r times delta, by hand), under twice the 40-digit floor of
  X = g - h - L, so the check's top end resolves by well under a digit;
  the proof's (ii) does not lean on it.
  (4) the tail ratio reads 1.006799503, 0.9999990945, 0.9999999954 at
  mu = 2, 3, 4 and 1.0 to 10 places at 6 and 8.
  So the proof's two halves meet their controls: C_2 - L has one zero
  on mu >= 0, at 0.240152725641689, and X ~ 2 Phi(-1.96) Phi(1.96 -
  sqrt2 mu).
  Run: 10/10 checks, 13.5 s, peak commit 61.2 MB; with the instrument
  arm, 11/11, 11.0 s, 60.8 MB, every other print unchanged.

RUN: python knife_two.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, Phi, excess  # noqa: E402

CHECKS = []
ZONE = (0.2392, 0.2413)   # knife_zone.py's bracket of the edge at M = 2


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 level():
    return 2 * Phi(CZ) - 1


def g(t, plant=None):
    a = CZ
    v = 2 * Phi(a) - 1 if plant == "v" else 2 * Phi(a + t) - 1
    return (Phi(a) - Phi(-a - 2 * t)) * v


def h(t, plant=None):
    a = CZ
    if t <= a or plant == "drop":
        return mp.mpf(0)
    v = 2 * Phi(a) - 1 if plant == "v" else 2 * Phi(t - a) - 1
    return (Phi(-a) - Phi(a - 2 * t)) * v


def closed(mu, plant=None):
    """X = C_2(mu) - L from the product of two normal windows."""
    t = mp.sqrt(2) * mu
    return g(t, plant) - h(t, plant) - level()


def lower(mu):
    """Phi(-u)[2 eps - 3 r(u)] at t > a, u = t - a."""
    u = mp.sqrt(2) * mu - CZ
    return Phi(-u) * (2 * Phi(-CZ) - 3 * Phi(-2 * CZ - u) / Phi(-u))


if __name__ == "__main__":
    t0 = time.time()
    mp.mp.dps = 40
    L = level()
    print("CONTROLS")
    c0 = g(mp.mpf(0))
    check("POSITIVE: C_2(0) = L^2 to 1e-30", abs(c0 - L ** 2) < 1e-30,
          f"{mp.nstr(abs(c0 - L ** 2), 3)}")
    x0 = mp.mpf(excess((2, 0))[0])
    mp.mp.dps = 40
    check("POSITIVE: the instrument, excess at mu = 0, is L^2 - L to 1e-30",
          abs(x0 - (L ** 2 - L)) < 1e-30, f"{mp.nstr(abs(x0 - L ** 2 + L), 3)}")
    fam = [0.25 * k for k in range(1, 33)]
    rows = []
    for mu in fam:
        xs, es = excess((2, mu))
        mp.mp.dps = 40
        m = mp.mpf(mu)
        rows.append((mu, mp.mpf(xs), mp.mpf(es), closed(m),
                     closed(m, "drop"), closed(m, "v")))
    for mu, x, e, c, _, _ in rows:
        if mu in (0.25, 0.5, 1, 1.5, 2, 3, 4, 6, 8):
            print(f"  mu = {mu}: excess {mp.nstr(x, 12)} (err {mp.nstr(e, 2)}),"
                  f" closed {mp.nstr(c, 12)}, gap {mp.nstr(abs(x - c), 3)}")
    worst = max(abs(x - c) for _, x, _, c, _, _ in rows)
    least = min(abs(x) for _, x, _, _, _, _ in rows)
    print(f"  least |X| on the family {mp.nstr(least, 3)}; largest excess err "
          f"{mp.nstr(max(r[2] for r in rows), 3)}")
    drop = [r[0] for r in rows if abs(r[1] - r[4]) >= 1e-30]
    vbad = [r[0] for r in rows if abs(r[1] - r[5]) >= 1e-30]
    check("PLANT: h dropped fails (1) at every mu > 1.386 and no other",
          drop == [mu for mu in fam if mu > 1.386], f"caught at {len(drop)} mu")
    check("PLANT: the V factor frozen fails (1) at every mu",
          len(vbad) == len(fam), f"caught at {len(vbad)} of {len(fam)}")
    if not all(CHECKS):
        print("CONTROL FAILED: nothing below is read.")
        sys.exit(1)

    print("THE KILL")
    print(f"KILL two: worst |closed - excess| {mp.nstr(worst, 3)}")
    print(f"KILL fires: {worst >= 1e-30}")
    check("(1) closed form = excess to 1e-30 at 32 mu", worst < 1e-30)

    print("THE PROOF'S CONSTANTS")
    eps = Phi(-CZ)
    k1 = eps - Phi(-3 * CZ) - 2 * Phi(-2 * CZ)
    k2 = 2 * Phi(-CZ) - 6 * Phi(-2 * CZ)
    print(f"  (i)  eps - Phi(-3a) - 2 Phi(-2a) = {mp.nstr(k1, 8)}")
    print(f"  (ii) 2 Phi(-a) - 6 Phi(-2a)      = {mp.nstr(k2, 8)}")
    check("(i), (ii): both constants positive", k1 > 0 and k2 > 0)

    print("THE CROSSING")
    a = CZ
    root = mp.findroot(lambda m: g(mp.sqrt(2) * m) - L, (0.0, a / mp.sqrt(2)),
                       solver="bisect")
    print(f"  mu*(2) = {mp.nstr(root, 15)}; g at a: C_2(1.96/sqrt2) - L = "
          f"{mp.nstr(g(a) - L, 8)}")
    check("(2) mu*(2) inside knife_zone's bracket", ZONE[0] < root < ZONE[1])
    fine = [mp.mpf(k) / 1000 for k in range(0, 8001)]
    xs = [closed(m) for m in fine]
    flips = [float(fine[i]) for i in range(1, len(fine))
             if mp.sign(xs[i]) != mp.sign(xs[i - 1])]
    print(f"  sign changes of X on mu = 0, 0.001, ..., 8: at {flips}")
    up = all(xs[i] > xs[i - 1] for i in range(1, len(fine))
             if mp.sqrt(2) * fine[i] <= a)
    check("(i) X strictly increasing on the grid to 1.96/sqrt2", up)
    past = [i for i in range(len(fine)) if mp.sqrt(2) * fine[i] > a]
    lb_ok = all(lower(fine[i]) <= xs[i] for i in past)
    pos = all(xs[i] > 0 for i in past)
    us = [mp.sqrt(2) * fine[i] - a for i in past]
    rs = [Phi(-2 * a - u) / Phi(-u) for u in us]
    dec = all(rs[j] < rs[j - 1] for j in range(1, len(rs)))
    print(f"  past 1.96/sqrt2: {len(past)} grid mu, least X/lower "
          f"{mp.nstr(min(xs[i] / lower(fine[i]) for i in past), 6)}, "
          f"r from {mp.nstr(rs[0], 4)} to {mp.nstr(rs[-1], 4)}")
    check("(3) lower bound <= X, X > 0 and r decreasing past 1.96/sqrt2",
          lb_ok and pos and dec)
    check("one sign change on the grid (the theorem's grid read)",
          len(flips) == 1)

    print("THE TAIL RATE")
    for mu in (2, 3, 4, 6, 8):
        m = mp.mpf(mu)
        q = closed(m) / (2 * Phi(-a) * Phi(a - mp.sqrt(2) * m))
        print(f"  mu = {mu}: X / [2 Phi(-a) Phi(a - t)] = {mp.nstr(q, 10)}")
    q8 = closed(mp.mpf(8)) / (2 * Phi(-a) * Phi(a - mp.sqrt(2) * 8))
    check("(4) the tail ratio within 1e-3 of 1 at mu = 8", abs(q8 - 1) < 1e-3)
    print(f"\n{sum(CHECKS)}/{len(CHECKS)} checks, {time.time() - t0:.1f} s")
    sys.exit(0 if all(CHECKS) else 1)