knife_zone.py

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

Cited on: RULER.

To run it: save knife_zone.py, with knife_limit.py beside it; needs numpy.

"""knife_zone.py -- how wide is the knife's failure zone?

QUESTION. At M equiprobable bins of label rate 1/2 + delta,
resubstitution's 95% interval covers, as n grows at mu = 2 delta
sqrt(n/M) fixed, at C_M(mu) = P(|sum_r (|Z_r + mu| - mu)| <= c sqrt M),
c = 1.96 (knife_limit.py). C_15(0) is about 0.022, C_15(2) above 0.95.
Where does C_M first reach 0.95 (the zone's edge mu*(M), so the
interval fails for |delta| < mu* sqrt(M/n)/2), how does mu* grow with
M, and does C_M fall below 0.95 again past it?

BY HAND (before any engine code).
  (a) M = 1, a theorem. W = |Z + mu| - mu is Z on Z >= -mu and
  -Z - 2 mu below. So |W| <= c iff max(-mu, -c) <= Z <= c or (Z < -mu
  and |Z + 2 mu| <= c). For mu <= c, -2 mu + c >= -mu and the union is
  [-2 mu - c, c]: C_1(mu) = Phi(c) - Phi(-2 mu - c), increasing, 0.95 at
  mu = 0 only. For mu >= c the second piece lies below -mu and misses
  [-c, c]: C_1(mu) = 0.95 + Phi(c - 2 mu) - Phi(-c - 2 mu), decreasing
  to 0.95. So C_1 >= 0.95 at every mu, peak at mu = c, Phi(c) -
  Phi(-3c) = 0.97500 (to 5 places). One bin never under-covers.
  (b) M >= 2: C_2(0) = 0.9025 < 0.95 (knife_limit.py (c)); that every
  M >= 2 has an edge mu*(M) > 0 is not argued here (C_M -> 0.95 alone
  does not give a crossing), and is read at the family's M.
  (c) An expansion, not a proof (TRANSPLANT: the normal law of T, a
  sum of M terms, carried to moderate M). W has mean m1 = 2(phi(mu) -
  mu Phi(-mu)) ~ 2 phi(mu)/mu^2 and variance 1 - 2 mu m1 - m1^2. With
  T normal of mean M m1 and variance M v, the coverage of [-c sqrt M,
  c sqrt M] is 0.95 + 2 c phi(c) (mu m1) - c phi(c) M m1^2 to second
  order, the first the narrowed variance's gain, the second the mean's
  loss. They balance at M m1 = 2 mu, so phi(mu*) ~ mu*^3 / M:
  mu*^2 + 6 ln mu* + ln(2 pi) ~ 2 ln M, mu* ~ sqrt(2 ln M). The excess
  past the edge peaks near M m1 = mu at about c phi(c) mu^2 / M,
  falling as (ln M)/M. In delta: the zone is |delta| < mu* sqrt(M/(4n)),
  of order sqrt(M ln M / (2n)).

PREDICTIONS. (1) The bracket of knife_limit.py holds C_1's closed
form at every mu read, the peak 0.97500 at mu = 1.96 (strongly: (a)).
(2) At each M in the family C_M crosses 0.95 once on the grid: below
mu* no bracket lies above 0.95, past it to mu = 4 none lies below
(strongly near the edge; past mu ~ 3 the excess, about 0.23 mu m1, is
under the bracket's width and the read is a straddle, not a crossing).
(3) mu*(M) increases with M; mu*(15) in [1.0, 1.6] (C_15(0.7217) is
0.887, C_15(2) 0.957). (4) mu* within 15% of (c)'s root of
mu^2 + 6 ln mu + ln(2 pi) = 2 ln M at M >= 32 (weakly: (c) is for
large mu). (5) The largest C_M on the grid falls with M, C_15's in
[0.955, 0.970] (weakly).

KILL (frozen; what the script PRINTS):
  "KILL zone: second crossings S, early crossings E, mu* drops D" and
  it fires iff S + E + D > 0. The family: M in {2, 3, 4, 6, 8, 12, 15,
  16, 24, 32, 48, 64}, mu on the grid 0, 0.05, ..., 4, h = 0.0005. An
  early crossing is a grid mu below mu*'s bisection bracket whose
  coverage bracket lies wholly above 0.95; a second crossing a grid mu
  above it, to 4, whose bracket lies wholly below 0.95; a drop an M
  whose mu* (the bisection's midpoint, to 0.002) is below the previous
  M's. "0.95" here and in (2) is the nominal level 2 Phi(c) - 1 =
  0.950004, C_M's limit as mu grows.

CONTROLS (read before any verdict).
  POSITIVE, the bracket: C_1(mu) by (a) inside its bracket at mu = 0,
  0.5, 1.96, 3. POSITIVE, the trials: knife_limit.trials at M = 4,
  n = 10^6, mu = mu*(4) reads 0.95 within 4 se (200,000 trials).
  PLANT, the bracket: (a)'s form with c = 1.9595 must fall below the
  bracket, and with c = 1.961 above it, each at some mu of the four
  (each about one bracket width off at mu = 0; the first run planted
  c = 1.955 alone, about ten widths off).

FINDINGS. The kill misses: "KILL zone: second crossings 0, early
crossings 0, mu* drops 0". Every prediction held, (4) by a margin of
0.3% at M = 32.
  CONTROLS: "C_1(0.0): by hand 0.950004, bracket [0.950004, 0.950063]",
  and at mu = 0.5, 1.96, 3 by hand 0.973464, 0.975002, 0.950031, each
  inside; the plants read "below at 4 of 4 mu, above at 4 of 4", at
  mu = 0 0.949946 and 0.950121 against [0.950004, 0.950063]; the hand
  value sits on the bracket's lower end at every mu (within 1e-6), its
  upper end about one cell h of c above; trials at M = 4 "mu* 0.5244,
  rate 0.95039, z 0.63".
  (1): "C_1 peak at mu = 1.96: 0.975002".
  (2), (3): a crossing lies in M = 2 [0.2392, 0.2413], 3 [0.4023, 0.4043],
  4 [0.5234, 0.5254], 6 [0.6933, 0.6954], 8 [0.8105, 0.8125], 12
  [0.9687, 0.9717], 15 [1.0527, 1.0567], 16 [1.0771, 1.0801], 24
  [1.2246, 1.2295], 32 [1.3271, 1.3331], 48 [1.4687, 1.4766], 64
  [1.5664, 1.5772], printed outward; below it every grid bracket lies
  wholly under the nominal level ("12 of 12 M"), so on the grid mu*
  is the first crossing, between grid points unread; no grid mu past
  it to 4 has a bracket below the level at any M; the first grid mu
  past it whose bracket
  straddles that level is 3.6 at M = 2, 3.5 at 15, 3.3 at 64 (in
  family order, "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).
  (4): the leading-order root sits above mu* at every M, "off -71.0%"
  at M = 2, -21.5% at 15, -14.7% at 32, -10.6% at 64, and sqrt(2 ln M)
  (2.8841 at M = 64) far above both. Unpredicted: the balance itself,
  M m1(mu) = 2 mu with m1 exact, closes on mu* faster, off -44.9% at
  M = 2, -2.1% at 15, -0.7% at 32, -0.2% at 64 (1.5755), each against
  the interval's midpoint. (c)'s "to second order" is leading order in
  1/M: the variance's m1^2 and T's departures from the normal law are
  a factor 1/M smaller there, and unread.
  (5): the grid's largest lower bracket falls with M: 0.97487 at M = 2
  (mu = 1.35), 0.97242 at 4, 0.96782 at 8, 0.96346 at 15 (mu = 1.45),
  0.96303 at 16, 0.95888 at 32, 0.95570 at 64 (mu = 1.9).
  In delta at M = 15 and n = 8000 the zone is |delta| < mu*
  sqrt(15/32000), 0.02279 to 0.02288, about 1/44, so the dial row 1/64
  (mu = 0.7217) lies inside it.
  The first run bisected each mu* on its bracket's midpoint, an
  interval where the midpoint crosses, not C_M; the edges above bisect
  the upper bracket and the lower each on its own, and the grid's mu
  is rounded to two places, which moved M = 4's largest lower bracket
  from 0.97243 to 0.97242 (a boundary cell). The drop test reads the
  intervals' midpoints, the intervals 0.0019 to 0.0108 wide (the frozen
  "to 0.002" was that width's guess), disjoint and rising. The edges
  were first printed at :.4f, inward at seven M (0.2393 for
  0.2392578); a check now reads the printed ends outside the bisection's
  ("12 of 12 M"; at :.4f "5 of 12 M"). A check reads a crossing
  located by the float brackets in
  each, "12 of 12 M"; with the midpoint bisection put back
  it prints "0 of 12 M". The kill, (3) (the twelve intervals disjoint
  and rising, "11 of 11 steps") and (5) ("11 of 11 steps; C_15's
  0.96346") are checks reaching the exit code: 9/9 checks, 40.0 s,
  86.7 MB.

RUN: python knife_zone.py.
"""
import os
import sys
import time
from math import erfc, exp, log, pi, sqrt

os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
import numpy as np  # noqa: E402
from knife_limit import bracket, out, trials, zscore  # noqa: E402

C = 1.96
PLANTS = (1.9595, 1.961)
FAMILY = (2, 3, 4, 6, 8, 12, 15, 16, 24, 32, 48, 64)
GRID = [round(k * 0.05, 2) for k in range(81)]
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 0.5 * erfc(-x / sqrt(2))


NOMINAL = 2 * Phi(C) - 1


def c1(mu, c=C):
    """(a)'s closed form for C_1(mu)."""
    if mu <= c:
        return Phi(c) - Phi(-2 * mu - c)
    return 2 * Phi(c) - 1 + Phi(c - 2 * mu) - Phi(-c - 2 * mu)


def edge(M, steps=12):
    """(a, b) over [0, 4]: C_M(a) < NOMINAL by its upper bracket, C_M(b)
    > NOMINAL by its lower, each end bisected on its own bracket side."""
    ends = []
    for side in (1, 0):
        a, b = 0.0, 4.0
        for _ in range(steps):
            m = (a + b) / 2
            v = bracket(M, m)[side]
            if (v < NOMINAL) if side else (v <= NOMINAL):
                a = m
            else:
                b = m
        ends.append(a if side else b)
    return tuple(ends)


def balance(M):
    """(c)'s balance M m1(mu) = 2 mu with m1 exact, by bisection."""
    m1 = lambda u: 2 * (exp(-u * u / 2) / sqrt(2 * pi) - u * Phi(-u))
    a, b = 0.01, 10.0
    for _ in range(60):
        m = (a + b) / 2
        a, b = (m, b) if M * m1(m) > 2 * m else (a, m)
    return (a + b) / 2


def root(M):
    """(c)'s root of mu^2 + 6 ln mu + ln(2 pi) = 2 ln M, by bisection."""
    f = lambda u: u * u + 6 * log(u) + log(2 * pi) - 2 * log(M)
    a, b = 0.5, 10.0
    for _ in range(60):
        m = (a + b) / 2
        a, b = (m, b) if f(m) < 0 else (a, m)
    return (a + b) / 2


if __name__ == "__main__":
    t0 = time.time()
    print(f"CONTROLS (nominal {NOMINAL:.6f})")
    pos, below, above = [], 0, 0
    for mu in (0.0, 0.5, 1.96, 3.0):
        lo, hi = bracket(1, mu)
        pos.append(lo <= c1(mu) <= hi)
        down, up = (c1(mu, c) for c in PLANTS)
        below += down < lo
        above += up > hi
        print(f"  C_1({mu}): by hand {c1(mu):.6f}, bracket {out(lo, hi)}, "
              f"at c = {PLANTS[0]} {down:.6f}, at c = {PLANTS[1]} {up:.6f}")
    check("POSITIVE: C_1 by hand inside its bracket at the four mu",
          all(pos))
    check(f"PLANT: c = {PLANTS[0]} below the bracket and c = {PLANTS[1]} "
          "above it, each at some mu", below and above,
          f"below at {below} of 4 mu, above at {above} of 4")
    a4, b4 = edge(4)
    m4 = (a4 + b4) / 2
    rng = np.random.default_rng(20261123)
    r4 = trials(4, 10 ** 6, m4, rng)
    z4 = zscore(r4, *bracket(4, m4))
    check("POSITIVE: trials at M = 4, n = 10^6, mu = mu*(4) on C_4",
          z4 < 4, f"mu* {m4:.4f}, rate {r4:.5f}, z {z4:.2f}")
    if not all(CHECKS):
        print("CONTROL FAILED: nothing below is read.")
        sys.exit(1)
    print(f"  C_1 peak at mu = 1.96: {c1(1.96):.6f}")
    print("THE EDGE")
    S = E = D = 0
    prev, cert = 0.0, 0
    edges, peaks = {}, []
    below_all = outward = 0
    for M in FAMILY:
        a, b = edge(M)
        edges[M] = (a, b)
        mstar = (a + b) / 2
        cert += bracket(M, a)[1] < NOMINAL < bracket(M, b)[0]
        early = second = under = n_under = 0
        best, at, straddle = 0.0, None, None
        for mu in GRID:
            lo, hi = bracket(M, mu)
            if mu < a and lo > NOMINAL:
                early += 1
            if mu < a:
                n_under += 1
                under += hi < NOMINAL
            if b < mu and hi < NOMINAL:
                second += 1
            if b < mu and straddle is None and lo <= NOMINAL <= hi:
                straddle = mu
            if lo > best:
                best, at = lo, mu
        S, E = S + second, E + early
        below_all += under == n_under
        shown = out(a, b, 4)
        lo4, hi4 = (float(v) for v in shown.strip("[]").split(", "))
        outward += lo4 <= a and b <= hi4
        peaks.append(best)
        D += mstar < prev
        prev = mstar
        r, q = root(M), balance(M)
        print(f"  M = {M:2d}: mu* in {shown}, below it {under} of {n_under} "
              f"grid brackets wholly under the level, sqrt(2 ln M) "
              f"{sqrt(2 * log(M)):.4f}, (c)'s leading-order root {r:.4f} "
              f"(off {(mstar - r) / r:+.1%}), its balance {q:.4f} (off "
              f"{(mstar - q) / q:+.1%}); early {early}, second {second}, "
              f"first straddle at mu = {straddle}; the grid's largest lower "
              f"bracket {best:.5f} at mu = {at}", flush=True)
    print(f"KILL zone: second crossings {S}, early crossings {E}, mu* drops "
          f"{D}")
    print(f"KILL fires: {S + E + D > 0}")
    check("the kill misses: no second crossing, no early crossing, no drop",
          S + E + D == 0, f"{S} + {E} + {D}")
    check("the edges located, C_M(a) < nominal < C_M(b) by the "
          "brackets", cert == len(FAMILY), f"{cert} of {len(FAMILY)} M")
    check("the edge intervals printed outward", outward == len(FAMILY),
          f"{outward} of {len(FAMILY)} M")
    check("below each edge every grid bracket wholly under the level",
          below_all == len(FAMILY), f"{below_all} of {len(FAMILY)} M")
    ends = [edges[M] for M in FAMILY]
    rising = sum(b < a2 for (_, b), (a2, _) in zip(ends, ends[1:]))
    check("(3) the edge intervals disjoint and rising, mu*(15) in "
          "[1.0, 1.6]", rising == len(FAMILY) - 1
          and 1.0 <= edges[15][0] and edges[15][1] <= 1.6,
          f"{rising} of {len(FAMILY) - 1} steps; mu*(15) in "
          f"{out(*edges[15], 4)}")
    zone = tuple(v * sqrt(15 / (4 * 8000)) for v in edges[15])
    print(f"  the limit's zone in delta at M = 15, n = 8000: |delta| < "
          f"mu* sqrt(15/32000), {out(*zone, 5)}, 1/64 = {1 / 64:.5f} "
          f"inside: {1 / 64 < zone[0]}")
    falls = sum(q < p for p, q in zip(peaks, peaks[1:]))
    p15 = peaks[FAMILY.index(15)]
    check("(5) the grid's largest lower bracket falls with M, C_15's in "
          "[0.955, 0.970]", falls == len(FAMILY) - 1
          and 0.955 <= p15 <= 0.970,
          f"{falls} of {len(FAMILY) - 1} steps; C_15's {p15:.5f}")
    if not all(CHECKS):
        print(f"\n{sum(CHECKS)}/{len(CHECKS)} checks FAILED")
        sys.exit(1)
    print(f"\n{sum(CHECKS)}/{len(CHECKS)} checks, {time.time() - t0:.1f} s")