knife_limit.py

Checks: RULER: The knife: a consistent point inside an inconsistent interval property; known; theorem; rule; RULER: Coverage is a function of two ratios property; observation.

Cited on: RULER.

To run it: save knife_limit.py; needs numpy.

"""knife_limit.py -- the knife's coverage in the limit: a law of M alone.

QUESTION. At a knife slice every bin of M equiprobable bins has label
rate 1/2 and resubstitution states est +- 1.96 sqrt(est(1 - est)/n),
est = (1/n) sum_r min(n_r0, n_r1). Its coverage of R* = 1/2 was read
at 0 or 1 of 40 trials at n = 500 to 32,000 (M = 15). Does it have a
limit as n grows, free of n, and what is it? And the dial, label rate
1/2 + delta at every bin: is its coverage a function of M and
mu = 2 delta sqrt(n/M) alone?

BY HAND (before any engine code).
  (a) THE LIMIT (theorem). min(B, m - B) = m/2 - |B - m/2|, so
  est = 1/2 - D/n, D = sum_r |B_r - m_r/2|, m_r the points in bin r and
  B_r its labels 1. Point i, in bin r_i with label y_i, gives the vector
  X_i = (y_i - 1/2) e_{r_i} in R^M; the X_i are iid and bounded, of mean
  0 and covariance I/(4M) (bin and label independent, (y - 1/2)^2 =
  1/4), and B_r - m_r/2 is coordinate r of sum_i X_i. By the
  multivariate central limit theorem V = (sum_i X_i)/sqrt(n/(4M)) =>
  (Z_1, ..., Z_M), Z_r iid N(0, 1), so D/sqrt(n/(4M)) = sum_r |V_r| =>
  S = sum_r |Z_r| by continuous mapping; no conditioning on the counts
  m_r is needed. The interval covers 1/2 iff D/n <= 1.96 sqrt(est(1 -
  est)/n), iff sum_r |V_r| <= 1.96 sqrt(M) g with g = 2 sqrt(est(1 -
  est)) = sqrt(1 - 4 (D/n)^2). D/n = O_p(n^(-1/2)), so g -> 1 in
  probability and (sum_r |V_r|, g) => (S, 1) (Slutsky). The closed set
  {(s, g): s <= 1.96 sqrt(M) g} has boundary s = 1.96 sqrt(M) g, of
  probability P(S = 1.96 sqrt M) = 0 under (S, 1), S a sum of
  independent variables with densities; by the portmanteau theorem
      coverage -> C_M(0) = P(|Z_1| + ... + |Z_M| <= 1.96 sqrt M),
  at every M, free of n.
  (b) THE DIAL (theorem). At rate 1/2 + delta, delta = mu sqrt(M)/(2
  sqrt n) for a fixed mu >= 0, R* = 1/2 - delta, and the X_i form a
  triangular array: mean (delta/M)(1, ..., 1), covariance I/(4M) -
  (delta/M)^2 J -> I/(4M), J the all-ones matrix; bounded summands meet
  Lindeberg's condition, so sum_i (X_i - E X_i)/sqrt(n/(4M)) => Z and
  V_r = that coordinate + n(delta/M)/sqrt(n/(4M)) = it + mu. Then
  sqrt(n)(est - R*) = sqrt(n) delta - D/sqrt(n) = (M mu - sum_r
  |V_r|)/(2 sqrt M), the interval covers iff |sum_r |V_r| - M mu| <=
  1.96 sqrt(M) g, g -> 1, and T = sum_r (|Z_r + mu| - mu) has a density,
  so by (a)'s two steps
      coverage -> C_M(mu) = P(|sum_r (|Z_r + mu| - mu)| <= 1.96 sqrt M),
  a function of M and mu alone; as mu -> infinity |Z + mu| - mu -> Z
  pointwise, T => N(0, M), and C_M(mu) -> 2 Phi(1.96) - 1.
  (c) CONTROLS BY HAND. C_1(0) = P(|Z| <= 1.96) = 2 Phi(1.96) - 1. At
  M = 2, in u = (z_1 + z_2)/sqrt 2, v = (z_1 - z_2)/sqrt 2,
  |z_1| + |z_2| = sqrt 2 max(|u|, |v|), so C_2(0) = (2 Phi(1.96) - 1)^2.
  (d) A BRACKET. Cut Y = |Z + mu| into cells [kh, (k + 1)h) with exact
  masses Phi((k+1)h - mu) - Phi(kh - mu) + Phi((k+1)h + mu) - Phi(kh + mu);
  K = sum of the M cell indices puts sum Y in [Kh, (K + M)h). So
  P(the cell range lies inside the window) <= C_M(mu) <= P(it meets
  the window) + M times the mass above the last cell, each a sum over
  K's law, the M-fold convolution of the cell masses, taken by FFT in
  floating point.

PREDICTIONS. (1) C_15(0) lies in [0.02194, 0.02216] (a scratch
convolution at h = 0.0005) and the bracket narrows with h (strongly:
(a) and (d) are proofs). (2) C_15(0) is far from the normal plane's
reading of the same statement, 0.0304 (strongly). (3) A simulation of
the estimator itself, bins and labels drawn exactly, at n = 10^6 reads
C_15(0) within 4 standard errors (strongly); at n = 500 it reads lower,
near 0.0196 (weakly: a scratch read). (4) At fixed mu the simulated
coverage at n = 32,000 and 10^6 sits within 4 standard errors of
C_15(mu) at mu = 0.25, 0.7217 (the 1/64 dial row's mu at n = 8000), 2
and 5 (strongly, from (b)); C_15(0.7217) near 0.9, the dial row read
36 of 40 (weakly).

KILL (frozen before the run; what the script PRINTS):
  "KILL C_15(mu): widest bracket W, largest |z| Z at (n, mu) = ...";
  it fires iff W > 0.001 or Z > 4. The family: the ten cells
  n in {32000, 10^6} x mu in {0, 0.25, 0.7217, 2, 5}, M = 15,
  T = 200,000 trials a cell; z = max(0, |rate - mid| - half) / se,
  mid and half the bracket's midpoint and half-width,
  se = sqrt(mid (1 - mid) / T).

CONTROLS (read before any verdict).
  POSITIVE, the bracket: C_1(0) and C_2(0) by (c) inside their brackets
  at the h the kill uses. POSITIVE, the trials: the simulator at M = 2,
  n = 10^6, mu = 0 reads C_2(0) within 4 se; at M = 15, mu = 8 within
  4 se of its bracket (near 0.95). PLANT, the bracket: a half-normal of
  scale 1.001 must put C_2(0)'s hand value outside its bracket (the
  first run planted 1.05). PLANT, the trials: the bar 1% wide at
  M = 15, mu = 0, n = 10^6, about 6.3 se off C_15(0) by its own bracket,
  must give z > 4 (the first run doubled the bar).

FINDINGS. The kill as frozen FIRES, on its bracket clause alone: "KILL
C_15(mu): widest bracket 0.001195, largest |z| 2.77 at (n, mu) =
(32000, 0.25)", the widest mu = 0.25's, [0.352201, 0.353398]. The
clause guarded the z clause: z subtracts the bracket's half-width, so a
wide bracket hides a deviation. ADDED after the run, every cell read
again at h/4: "THE LAW at h/4: widest bracket 0.000299, largest |z|
3.16 at (n, mu) = (32000, 0.25)", against [0.352619, 0.352919]. So
the law's arm misses at every bracket read, but the cell (n = 32000,
mu = 0.25) sits about 3.2 se low, rising as
the bracket narrows (3.03 at h/2 in the first run); n = 10^6 there
reads z 0.00. Every prediction held, (2) having frozen no bar:
  CONTROLS: "C_1(0) by hand 0.950004, bracket [0.950004, 0.950063];
  C_2(0) by hand 0.902508, bracket [0.902412, 0.902570]"; trials
  "0.90216 z 0.38" (M = 2) and "0.94993 against [0.94989, 0.95013]
  z 0.00" (M = 15, mu = 8). The first run's plants were gross (scale
  1.05 "[0.879833, 0.880011]", the doubled bar "0.90846, z 2699.5");
  sized near each arm's resolution, scale 1.001 reads "[0.901976,
  0.902134]" and the bar 1% wide "0.02420, z 6.23; its own law
  [0.02410, 0.02433], z 6.30 off C_15(0)".
  (1), (2): "C_15(0) at h = 0.0005: [0.021940, 0.022149]", the width
  0.000831, 0.000416, 0.000208 at h = 0.002, 0.001, 0.0005, halving
  with h, and at h/4 "[0.022013, 0.022065]"; "the normal plane at
  h/S = Z/sqrt(1 - 2/pi) = 3.2514, b/h = sqrt(2M/pi)/Z = 1.5766:
  0.03040".
  (3): "n = 32000: 0.02217 (z 0.05, at h/4 0.30); n = 1000000: 0.02218
  (z 0.08, at h/4 0.34)"; "trials at n = 500, mu = 0: 0.01954 (z
  7.30)", below the limit.
  (4): at mu = 0.25, 0.7217, 2, 5 the brackets [0.352201, 0.353398],
  [0.887084, 0.887555], [0.957242, 0.957448], [0.949897, 0.950124], at
  h/4 [0.352619, 0.352919], [0.887249, 0.887367], [0.957314, 0.957366],
  [0.949976, 0.950034]; the
  trials at n = 32000 and 10^6 z 2.77 and 0.00, 1.34 and 0.04, 0.09
  and 0.00, 0.00 and 1.15. C_15(0.7217) is about 0.887 (the dial row
  at n = 8000, 36 of 40). Unpredicted: the limit C_15(2) lies above
  0.95; read at five mu, C_15 rises from 0.022 past the nominal level,
  and mu = 5's bracket straddles 0.95.
  Brackets print outward at six places, to floating point. The first
  run: 4/4 checks, 3.0 s, 52.9 MB peak commit; with the findings as
  checks reaching the exit code, 9/9 checks, 3.5 s, 89.8 MB, the law's
  width bar set after the run at 0.0004 above the 0.000299 read, and
  (1)'s scratch convolution's "outside the tree" cut from the frozen
  text as a workshop word.

RUN: python knife_limit.py.
"""
import os
import sys
import time
from math import ceil, erfc, floor, pi, sqrt

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

Z = 1.96
H = 0.0005
T = 200_000
MUS = (0.0, 0.25, 0.7217, 2.0, 5.0)
NS = (32_000, 10 ** 6)
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_up(x):
    """P(Z >= x)."""
    return 0.5 * erfc(x / sqrt(2))


def cells(mu, h, scale=1.0):
    """Masses of |scale Z + mu| on [kh, (k + 1)h), and the mass above."""
    cap = mu + 10 * scale
    k = int(cap / h) + 1
    up = [phi_up((j * h - mu) / scale) + phi_up((j * h + mu) / scale)
          for j in range(k + 1)]
    mass = np.array([up[j] - up[j + 1] for j in range(k)])
    return np.clip(mass, 0, None), up[k]


def bracket(M, mu, h=H, scale=1.0, z=Z):
    """(lo, hi) for C_M(mu) = P(|sum_r |Z_r + mu| - M mu| <= z sqrt M)."""
    p, tail = cells(mu, h, scale)
    L = 1 << int(np.ceil(np.log2(M * len(p) + 1)))
    law = np.fft.irfft(np.fft.rfft(p, L) ** M, L)[:M * (len(p) - 1) + 1]
    law = np.clip(law, 0, None)
    K = np.arange(len(law))
    c, w = M * mu, z * sqrt(M)
    inside = (K * h >= c - w) & ((K + M) * h <= c + w)
    meets = ((K + M) * h > c - w) & (K * h <= c + w)
    return float(law[inside].sum()), float(law[meets].sum()) + M * tail


def trials(M, n, mu, rng, t=T, bar_mult=1.0):
    """The estimator's coverage rate over t exact draws."""
    delta = mu * sqrt(M) / (2 * sqrt(n))
    truth = 0.5 - delta
    hits = 0
    for start in range(0, t, 50_000):
        size = min(50_000, t - start)
        m = rng.multinomial(n, [1 / M] * M, size=size)
        b = rng.binomial(m, 0.5 + delta)
        est = np.minimum(b, m - b).sum(axis=1) / n
        bar = bar_mult * Z * np.sqrt(est * (1 - est) / n)
        hits += int((np.abs(est - truth) <= bar).sum())
    return hits / t


def out(lo, hi, d=6):
    """A bracket printed outward at d places."""
    f = 10 ** d
    return f"[{floor(lo * f) / f:.{d}f}, {ceil(hi * f) / f:.{d}f}]"


def zscore(rate, lo, hi, t=T):
    mid, half = (lo + hi) / 2, (hi - lo) / 2
    return max(0.0, abs(rate - mid) - half) / sqrt(mid * (1 - mid) / t)


if __name__ == "__main__":
    t0 = time.time()
    rng = np.random.default_rng(20261122)
    c1 = 1 - 2 * phi_up(Z)
    print("CONTROLS")
    b1, b2 = bracket(1, 0.0), bracket(2, 0.0)
    print(f"  C_1(0) by hand {c1:.6f}, bracket {out(*b1)}; "
          f"C_2(0) by hand {c1 ** 2:.6f}, bracket {out(*b2)}")
    check("POSITIVE: C_1(0), C_2(0) by hand inside their brackets",
          b1[0] <= c1 <= b1[1] and b2[0] <= c1 ** 2 <= b2[1])
    pl = bracket(2, 0.0, scale=1.001)
    check("PLANT: a half-normal of scale 1.001 leaves C_2(0) outside",
          not pl[0] <= c1 ** 2 <= pl[1], out(*pl))
    r2 = trials(2, 10 ** 6, 0.0, rng)
    z2 = zscore(r2, *b2)
    b8 = bracket(15, 8.0)
    r8 = trials(15, 10 ** 6, 8.0, rng)
    z8 = zscore(r8, *b8)
    check("POSITIVE: trials at M = 2, mu = 0 and M = 15, mu = 8, n = 10^6, "
          "within 4 se", z2 < 4 and z8 < 4,
          f"{r2:.5f} z {z2:.2f}; {r8:.5f} against {out(*b8, 5)} "
          f"z {z8:.2f}")
    b0 = bracket(15, 0.0)
    wide = bracket(15, 0.0, z=Z * 1.01)
    rp = trials(15, 10 ** 6, 0.0, rng, bar_mult=1.01)
    zp = zscore(rp, *b0)
    check("PLANT: the bar 1% wide at M = 15, mu = 0, n = 10^6 is caught",
          zp > 4, f"{rp:.5f}, z {zp:.2f}; its own law {out(*wide, 5)}, "
          f"z {zscore((wide[0] + wide[1]) / 2, *b0):.2f} off C_15(0)")
    if not all(CHECKS):
        print("CONTROL FAILED: nothing below is read.")
        sys.exit(1)
    print("THE LIMIT")
    widths = []
    for h in (0.002, 0.001, H):
        lo, hi = bracket(15, 0.0, h)
        widths.append(hi - lo)
        print(f"  C_15(0) at h = {h}: {out(lo, hi)}, width "
              f"{hi - lo:.6f}")
    check("C_15(0) at h = 0.0005 inside [0.02194, 0.02216], the width "
          "halving with h", 0.02194 <= b0[0] and b0[1] <= 0.02216
          and all(1.9 < a / b < 2.1 for a, b in zip(widths, widths[1:])))
    hs, bh = Z / sqrt(1 - 2 / pi), sqrt(30 / pi) / Z
    plane = 1 - phi_up(hs * (1 - bh)) - (1 - phi_up(-hs * (1 + bh)))
    print(f"  the normal plane at h/S = Z/sqrt(1 - 2/pi) = {hs:.4f}, "
          f"b/h = sqrt(2M/pi)/Z = {bh:.4f}: {plane:.5f}")
    check("the normal plane reads more than 0.008 above C_15(0)",
          plane - b0[1] > 0.008, f"{plane - b0[1]:.5f} to "
          f"{plane - b0[0]:.5f} above")
    r500 = trials(15, 500, 0.0, rng)
    z500 = zscore(r500, *b0)
    print(f"  trials at n = 500, mu = 0: {r500:.5f} (z {z500:.2f})")
    check("n = 500 reads below the limit, z > 4", r500 < b0[0] and z500 > 4)
    print("THE DIAL, M = 15")
    widest, worst, worst4, quarter = 0.0, (-1.0, None), (-1.0, None), {}
    for mu in MUS:
        lo, hi = bracket(15, mu)
        quarter[mu] = bracket(15, mu, H / 4)
        widest = max(widest, hi - lo)
        row = []
        for n in NS:
            r = trials(15, n, mu, rng)
            z, z4 = zscore(r, lo, hi), zscore(r, *quarter[mu])
            worst = max(worst, (z, (n, mu)))
            worst4 = max(worst4, (z4, (n, mu)))
            row.append(f"n = {n}: {r:.5f} (z {z:.2f}, at h/4 {z4:.2f})")
        print(f"  mu = {mu}: C in {out(lo, hi)}, at h/4 "
              f"{out(*quarter[mu])}; " + "; ".join(row), flush=True)
    print(f"KILL C_15(mu): widest bracket {widest:.6f}, largest |z| "
          f"{worst[0]:.2f} at (n, mu) = {worst[1]}")
    print(f"KILL fires: {widest > 0.001 or worst[0] > 4}")
    wq = max(hi - lo for lo, hi in quarter.values())
    print(f"THE LAW at h/4: widest bracket {wq:.6f}, largest |z| "
          f"{worst4[0]:.2f} at (n, mu) = {worst4[1]}")
    check("THE LAW: every cell within 4 se of C_15(mu) at h/4, every "
          "bracket under 0.0004 wide", worst4[0] < 4 and wq < 0.0004)
    check("C_15(2) lies above 0.95", quarter[2.0][0] > 0.95,
          out(*quarter[2.0]))
    print(f"\n{sum(CHECKS)}/{len(CHECKS)} checks, {time.time() - t0:.1f} s")
    sys.exit(0 if all(CHECKS) else 1)