knife_edge.py

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

Cited on: RULER.

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

"""knife_edge.py -- the knife's limit crosses its level at every M >= 2.

QUESTION. C_M(mu) = P(|T| <= w), T = sum_r Y_r, Y_r = |Z_r + mu| - mu,
Z_r iid N(0, 1), w = 1.96 sqrt M, level L = 2 Phi(1.96) - 1. Is C_M(0)
< L and C_M(mu) > L at some mu, at every M >= 2, so that (C_M being
continuous) the zone has an edge at every M?

BY HAND (before any engine code; the proofs are the result, this
script their numeric control).
  (U) UNDER, every M >= 2. sum |Z_r| >= |sum Z_r| and sum Z_r ~ N(0, M),
  so {sum |Z_r| <= w} lies inside {|sum Z_r| <= w}, of probability L;
  the difference holds an open set (Z_1 near 0.8w, Z_2 near -0.3w, the
  rest near 0: |sum Z| near 0.5w, sum |Z| near 1.1w), of positive
  measure at M >= 2. So C_M(0) < L.
  (O) OVER, every M >= 2. Y = Z + 2(-Z - mu)_+, so T = G + 2E,
  G = sum Z_r ~ N(0, M), E = sum_r (-Z_r - mu)_+ >= 0, and with f the
  indicator of [-w, w], C_M(mu) - L = E[f(G + 2E) - f(G)]. Let A =
  {r : Z_r < -mu}, |A| ~ Bin(M, p), p = Phi(-mu), and D_r =
  f(G + 2(-Z_r - mu)_+) - f(G). On |A| = 0 every term is 0; on A = {r}
  the difference is D_r and the other D's are 0; on |A| >= 2 the
  difference is at most 1 and sum D_r at most |A| in size. So with
  Q = sum_r E[D_r] = M E[D_1], and 1 + k <= (3/2) k (k - 1) at k >= 2,
      |C_M(mu) - L - Q| <= E[(1 + |A|) 1{|A| >= 2}] <= R
                        = (3/2) M (M - 1) p^2.
  Exactly, with Z_1 = -mu - s, G = Z_1 + G', G' ~ N(0, M - 1)
  independent, f(G + 2s) = 1{|G' - (mu - s)| <= w} and f(G) =
  1{|G' - (mu + s)| <= w}, so
      Q = M int_0^inf phi(mu + s) [F(mu - s) - F(mu + s)] ds,
  F(c) = P(|G' - c| <= w), even, strictly decreasing in |c| (F'(c) =
  [phi((c + w)/sd) - phi((c - w)/sd)]/sd < 0 at c > 0, sd = sqrt(M -
  1)); |mu - s| < mu + s at mu, s > 0, so Q > 0 at every mu > 0.
  Q/R -> infinity: the bracket rises in s on [0, mu] (its derivative
  -F'(mu - s) - F'(mu + s) > 0 there), so at mu >= 1, Q >= M[F(mu - 1)
  - F(mu + 1)][Phi(-mu - 1) - Phi(-2 mu)]; w > 1, so the windows
  overlap and F(mu - 1) - F(mu + 1) = P(G' in [mu - 1 - w, mu + 1 - w))
  - P(G' in (mu - 1 + w, mu + 1 + w]) >= 2[phi_sd(mu + 1 - w) -
  phi_sd(mu - 1 + w)] at mu >= 1 + w (phi_sd the N(0, M - 1) density),
  positive since (mu - 1 + w)^2 -
  (mu + 1 - w)^2 = 4 mu (w - 1). So log(Q/R) >= mu^2 (1/2 - 1/(2(M -
  1))) - O(mu) at M >= 3, and at M = 2, where the mu^2 terms cancel,
  mu (w - 2) - O(log mu), w = 2.77. So C_M(mu) > L at every mu past
  some mu_0(M), and C_M(mu) - L = Q(1 + o(1)) as mu grows. T has a
  density, so P(|T| = w) = 0 and C_M is continuous in mu (dominated
  convergence); with (U), an edge at every M >= 2. One crossing is
  not argued.

PREDICTIONS. (1) The quadrature (mpmath; C_2 a 1-D integral of Y's
density against Y's CDF, C_3 nested) holds C_2(0) = L^2 to 1e-15 and
sits inside knife_limit.bracket at h/4 at mu = 0, 1 (M = 2, 3)
(strongly). (2) |X - Q| <= R at every mu of the family, X = C_M(mu) - L
(strongly: a proof). (3) X/Q at M = 2, mu = 8 within 1e-4 of 1 (R/Q ~
1e-6 there by hand, weakly). (4) The certificate mu_c(M), the least
grid mu (step 0.05, to 12) from which Q > R at every grid mu, is
finite at every M of {2, 3, 4, 5, 6, 8, 12, 15, 16, 24, 32, 48, 64,
100, 1000}, rises with M, mu_c(15) in [3, 4] and mu_c(1000) in [4.5,
6] (weakly: hand estimates 3.8 by the crude bound at 15, 5.2 at 1000).
(5) C_2 - L on mu = 0, 0.01, ..., 8 changes sign once, near 0.24
(knife_zone's [0.2392, 0.2413]).

KILL (frozen; what the script PRINTS):
  "KILL remainder: worst |X - Q|/R r at (M, mu)", fires iff r > 1, over
  M = 2 at mu = 0.25, 0.5, ..., 8 and M = 3 at mu = 0.5, 1, ..., 6,
  counted only where R exceeds the quadrature's error by 100x.

CONTROLS. POSITIVE: C_2(0) = L^2 by hand; C_1(mu)'s closed form
(knife_zone (a)) by the same quadrature routine at mu = 0.5, 3; the
brackets of (1). Q's instrument: mpmath against scipy's quad at M = 2,
15, mu = 3, agreeing to 1e-9 relative. PLANTS (each must give r > 1
over the kill's family): Q with the windows swapped (-Q); Q / M.

FINDINGS. The kill misses: "KILL remainder: worst |X - Q|/R 0.1373 at
(M, mu) = (2, 1.0)", "37 of 38 family points counted" (M = 2, mu = 8:
R 1.16e-30 under 100x the error 4.91e-32). Every prediction held. The
error excluding a point is the gap between X at two precisions; Q's
own quadrature error is read at mu = 3 alone (the two routines).
  CONTROLS: C_2(0) "0.902507998454483954 against 0.902507998454483954";
  C_1(0.5) 0.97346390964 and C_1(3.0) 0.950030935304 on their closed
  forms, read by window(1, ...), which is cdf_y and runs no quadrature
  (the frozen "same quadrature routine" is its base): the agreement
  is forced, the branch at -mu alone tested; C_2(0), C_2(1), C_3(0),
  C_3(1) 0.9025079985, 0.9742795011, 0.8320125876, 0.9727388532 inside
  "[0.9024811, 0.9025204]", "[0.9742721, 0.9742829]", "[0.8319731,
  0.8320492]", "[0.9727315, 0.9727457]"; Q_2(3) 0.00056124075722918
  and Q_15(3) 0.00055415738756523 by both routines. PLANTS: swap
  "r 1.779e+8", Q/M "r 4.448e+7", both at (2, 7.75), caught by
  construction (Q/R grows without bound, so any constant-factor error
  in Q fires at large mu): they read that the statistic is wired, and
  the kill tests Q's leading term at large mu, nothing at mu <= 1,
  where R exceeds X.
  (2), (3): X/Q at M = 2 reads 0.7007, 1.00697, 1.000000059 at mu = 1,
  2, 3, 1.0 to 10 places at 4 and 6, and to 12 at 8; at M = 3 0.6299,
  1.01275, 1.000143 at mu = 1, 2, 3 (the first run, to 6: 1.000000012,
  1.0 at 4, 6; same worst point, 43 of 44 counted). So the
  excess is the one-tail term from mu near 2 on; at mu = 1 Q is 1.43
  and 1.59 times X (M = 2, 3), inside R.
  (4): mu_c(M) = 1.35, 1.8, 2.05, 2.25, 2.4, 2.6, 2.9, 3.05, 3.1, 3.3,
  3.5, 3.7, 3.85, 4.05, 5.05 at M = 2, 3, 4, 5, 6, 8, 12, 15, 16, 24,
  32, 48, 64, 100, 1000, the hand estimates 3.8 and 5.2 high.
  Unpredicted: against knife_zone's first grid mu whose bracket
  straddles the level (3.6 at M = 2, 3.5 at 15, 3.3 at 64), mu_c lies
  below it at 2 and 15, but at 64 the grid's 3.3 to 3.8 is read by
  neither. The count 1 + k meets (3/2)k(k - 1) at k = 2, so the crude
  remainder leaves that stretch unread; knife_cross.py computes the
  pair term exactly instead and closes it.
  (5): "sign changes at mu = [0.25]; zeros on the grid 0": C_2 crosses
  once on mu = 0, 0.01, ..., 8, between 0.24 and 0.25, inside
  knife_zone's interval.
  The stages of (4) and (5) are cut: knife_cross.py's certificate scan
  reprints mu_c at every M from 3, and knife_two.py proves C_2's one
  crossing and places it by a 40-digit bisection. Their prints above
  are the record of the last run that held them.
  Run: the first, on three worker processes, 356.8 s, 236.3 MB; the
  script now runs serially, its M = 3 arm trimmed
  from mu = 0.5..6 to 0.5..3 (the frozen family's change: 6 points cut,
  the M = 3 cost growing to 87 s at mu = 6 alone), 11/11 checks,
  213.5 s, 117.4 MB. With (4) and (5) cut, through the gate: 8/8
  checks, 106.6 s, 87.6 MB.

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

os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
import mpmath as mp  # noqa: E402
from scipy.integrate import quad as squad  # noqa: E402
from scipy.special import ndtr  # noqa: E402

from knife_limit import bracket, H  # noqa: E402

mp.mp.dps = 40
CZ = mp.mpf("1.96")
L = 1 - mp.erfc(CZ / mp.sqrt(2))
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 Phi(x):
    return mp.ncdf(x)


def phi(x):
    return mp.npdf(x)


def cdf_y(t, mu):
    """P(Y <= t), Y = |Z + mu| - mu."""
    if t < -mu:
        return mp.mpf(0)
    return Phi(t) - Phi(-t - 2 * mu)


def dens_y(y, mu):
    return phi(y) + phi(y + 2 * mu) if y >= -mu else mp.mpf(0)


def window(k, lo, hi, mu):
    """P(Y_1 + ... + Y_k in [lo, hi]), by nested quadrature."""
    if k == 1:
        return cdf_y(hi, mu) - cdf_y(lo, mu)
    floor = -(k - 1) * mu   # the rest's sum is at least this
    top = 14 + mu
    pts = sorted({-mu, top, *(x for x in (lo - floor, hi - floor)
                               if -mu < x < top)})
    g = lambda y: dens_y(y, mu) * window(k - 1, lo - y, hi - y, mu)
    return mp.quad(g, pts)


def coverage(M, mu):
    w = CZ * mp.sqrt(M)
    return window(M, -w, w, mu)


def q_term(M, mu, swap=False):
    """Q = M int_0^inf phi(mu + s)[F(mu - s) - F(mu + s)] ds."""
    w, sd = CZ * mp.sqrt(M), mp.sqrt(M - 1)
    F = lambda c: Phi((c + w) / sd) - Phi((c - w) / sd)
    g = lambda s: phi(mu + s) * (F(mu - s) - F(mu + s))
    q = M * mp.quad(g, [0, mu, 14]) if mu > 0 else mp.mpf(0)
    return -q if swap else q


def q_scipy(M, mu):
    w, sd = 1.96 * M ** 0.5, (M - 1) ** 0.5
    F = lambda c: ndtr((c + w) / sd) - ndtr((c - w) / sd)
    ph = lambda x: 0.3989422804014327 * 2.718281828459045 ** (-x * x / 2)
    g = lambda s: ph(mu + s) * (F(mu - s) - F(mu + s))
    v1 = squad(g, 0, mu, epsabs=0, epsrel=1e-12, limit=200)[0]
    v2 = squad(g, mu, 14, epsabs=0, epsrel=1e-12, limit=200)[0]
    return M * (v1 + v2)


def excess(job):
    """X = C_M(mu) - L at two precisions (M = 2: 30, 40; M = 3: 20, 24),
    the second returned with the gap as its error, as strings."""
    M, mu = job
    lo, hi = (30, 40) if M == 2 else (20, 24)
    out = []
    for d in (lo, hi):
        mp.mp.dps = d
        out.append(coverage(M, mp.mpf(mu)) - 1 + mp.erfc(CZ / mp.sqrt(2)))
    mp.mp.dps = 40
    err = abs(out[1] - out[0]) + mp.mpf(10) ** -(hi - 2)
    return mp.nstr(out[1], hi), mp.nstr(err, 5)


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


if __name__ == "__main__":
    t0 = time.time()
    print("CONTROLS")
    c20 = coverage(2, 0)
    check("POSITIVE: C_2(0) = L^2 to 1e-15", abs(c20 - L ** 2) < 1e-15,
          f"{mp.nstr(c20, 18)} against {mp.nstr(L ** 2, 18)}")
    ok1 = []
    for mu in (0.5, 3.0):
        hand = (Phi(CZ) - Phi(-2 * mu - CZ) if mu <= CZ else
                L + Phi(CZ - 2 * mu) - Phi(-CZ - 2 * mu))
        got = coverage(1, mp.mpf(mu))
        ok1.append(abs(got - hand) < 1e-30)
        print(f"  C_1({mu}) {mp.nstr(got, 12)}, closed form "
              f"{mp.nstr(hand, 12)}")
    check("POSITIVE: C_1's closed form at mu = 0.5, 3", all(ok1))
    okb = []
    for M in (2, 3):
        for mu in (0.0, 1.0):
            lo, hi = bracket(M, mu, H / 4)
            mp.mp.dps = 40 if M == 2 else 20
            c = coverage(M, mp.mpf(mu))
            mp.mp.dps = 40
            okb.append(lo <= c <= hi)
            print(f"  C_{M}({mu}) {mp.nstr(c, 10)}, bracket at h/4 "
                  f"[{lo:.7f}, {hi:.7f}]", flush=True)
    check("POSITIVE: quadrature inside the brackets, M = 2, 3, mu = 0, 1",
          all(okb))
    okq = []
    for M in (2, 15):
        a, b = q_term(M, mp.mpf(3)), q_scipy(M, 3.0)
        okq.append(abs(a - b) / a < 1e-9)
        print(f"  Q_{M}(3): mpmath {mp.nstr(a, 14)}, scipy {b:.13e}")
    check("POSITIVE: Q by mpmath and by scipy agree to 1e-9 relative", all(okq))
    if not all(CHECKS):
        print("CONTROL FAILED: nothing below is read.")
        sys.exit(1)

    print("THE REMAINDER (X = C_M(mu) - L against Q, R)")
    fam = [(2, 0.25 * k) for k in range(1, 33)] + \
          [(3, 0.5 * k) for k in range(1, 7)]
    worst = {"Q": (-1, None), "swap": (-1, None), "Q/M": (-1, None)}
    counted = 0
    rows = [(mp.mpf(a), mp.mpf(b)) for a, b in map(excess, fam)]
    for (M, mu), (x, err) in zip(fam, rows):
        m = mp.mpf(mu)
        q, R = q_term(M, m), r_bound(M, m)
        if R < 100 * err:
            print(f"  M = {M}, mu = {mu}: R {mp.nstr(R, 3)} under 100x "
                  f"error {mp.nstr(err, 3)}, not counted")
            continue
        counted += 1
        for key, qq in (("Q", q), ("swap", -q), ("Q/M", q / M)):
            r = abs(x - qq) / R
            worst[key] = max(worst[key], (r, (M, mu)))
        if mu in (1, 2, 3, 4, 6, 8):
            print(f"  M = {M}, mu = {mu}: X {mp.nstr(x, 6)}, Q "
                  f"{mp.nstr(q, 6)}, R {mp.nstr(R, 3)}, X/Q "
                  f"{mp.nstr(x / q, 10)}", flush=True)
    print(f"  {counted} of {len(fam)} family points counted")
    for key in ("swap", "Q/M"):
        r, at = worst[key]
        check(f"PLANT: {key} gives r > 1", r > 1,
              f"r {mp.nstr(r, 4)} at {at}")
    r, at = worst["Q"]
    print(f"KILL remainder: worst |X - Q|/R {mp.nstr(r, 4)} at (M, mu) = {at}")
    print(f"KILL fires: {r > 1}")
    check("(2) |X - Q| <= R over the family", r <= 1)
    x8 = coverage(2, mp.mpf(8)) - L
    rat = x8 / q_term(2, mp.mpf(8))
    check("(3) X/Q at M = 2, mu = 8 within 1e-4 of 1", abs(rat - 1) < 1e-4,
          mp.nstr(rat, 12))

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