colnormal.py

Checks: BINDING: The capacity sweep pattern.

Cited on: BINDING.

To run it: save colnormal.py, with binding.py beside it; needs numpy, scipy.

"""colnormal.py — is the correlation column two moments?

QUESTION. The capacity sweep (binding.py::section_c: D = 1000
coordinates, N = 100 candidates, 200 trials per m, seed 2024) scores
each +-1 candidate by its dot product with the bundle s = V_0 + R read
in the centred representatives of Z/c, R a sum of m - 1 random +-1
words. Is its correlation success rate on a finite carrier the normal
approximation's P(the true score beats the N - 1 wrong ones), from two
exact moments of one coordinate?

THE MODEL (by hand). Per coordinate, with V_0 = 1 by the symmetry
c(-x) = -c(x) (c odd), X = c(1 + R), R = 2B - (m - 1), B ~ Bin(m - 1,
1/2): mu = E X (binding.expected_corr), tau = E X^2, sigma^2 = tau -
mu^2. The true score is near N(D mu, D sigma^2); a wrong score, given
the bundle, has mean 0 and variance sum c(s_i)^2, near D tau, the N - 1
of them independent given the bundle. So

    P(m, c) = integral phi(z) Phi((D mu + sqrt(D) sigma z)/sqrt(D tau))^(N-1) dz.

TRANSPLANTS, to re-derive: the wrong scores' variance read at its mean
D tau (it moves with the true score's, both functions of the bundle);
ties (integer scores, credit 1/ties in binding.py) read as continuous;
the tails at N - 1 = 99 maxima, where a normal law is least exact.

PREDICTIONS, frozen before any engine.
  Q1 the observed rates are binding.py's own: its draws replayed
     (seed 2024, the same order), the correlation readout alone, every
     cell equal to its print at two decimals.
  Q2 at the 112 finite cells (Z/9, Z/27, Z/81 and F_3, F_5, F_7, F_11,
     F_13, Z/3 being F_3, each at the 14 grid m), |observed - P| within
     0.064 everywhere, as a first rough run read.

THE KILL, as the script will print it:
    KILL: largest |obs - P| / se over the 112 cells at D = 1000: ...;
          at D = 2000: ...
  se = sqrt(P(1 - P)/200), P the model's: the conjecture dies at a cell
  off by more than 3 se at either D. Read first, as its own print: the
  same statistic at D = 1000 on a model given the observed mu only
  (tau = 1, the uncentred variance), whether the number can tell the
  two moments from one.

CONTROLS, read before any verdict.
  R1 at m = 1 the model gives P = Phi(sqrt(D))^99 > 0.999999 and every
     arm reads 1.00 (binding.py's own positive control).
  R2 mu by this script's binomial sum against binding.expected_corr at
     every cell, exactly.
  R3 a plant pushed toward a kill: the observed column of F_5 replaced
     by F_7's must fire the statistic at D = 1000.

FINDINGS (the first run, its lines copied; the kill reprinted at three
decimals, the first print's 3.0 being a rounding of the bar's side).
  R2 112 of 112; R1 least model P 1.0000000, every arm 1.0; Q1 the
  replay equals binding.py's print at 112 of 112 cells. R3 as run (the
  plan's plant, F_5's column swapped for F_7's, fired at a cell of P
  near 0, caught by construction): 0.05 added at the 16 live cells,
  0.05 < P < 0.95, fires at 3.9 se at (Z/81, 64), 2.46 se of plant and
  1.39 of the cell's own noise: at 200 trials a 0.05 offset clears 3 se
  alone only near P = 0.95 (2 of the 16), about 1.4 se mid-range (these
  splits by hand, printed by no line). READ
  as run (tau = 1 is a strawman): mu with Z's second moment tau = m
  reads 19.1 se at (F_5, 8), off by 0.537, so the statistic tells two
  moments from one. Q2 MISSED: the largest |obs - P| is 0.067 at D =
  1000 (not within 0.064) and 0.080 at D = 2000 (seed 2025).
    KILL: largest |obs - P| / se over the 112 cells at D = 1000: 2.847
    at (F_13, 16, 0.9, 0.9456); at D = 2000: 2.965 at (Z/9, 24, 0.26,
    0.1795)
  So the kill missed, at 0.99 of its bar. It cannot tell settling from
  flat: by the normal tail one cell passes 3 se with probability 0.0027,
  so an exact model's cells of P strictly inside (0, 1) pass it
  often, a rate unprinted, and the gap at D = 2000 sits inside 3 se of
  200 trials. REFROZEN on that print, before its run: at D = 2000, seed
  2026, 2000 trials a cell, the conjecture dies when the largest
  |obs - P| / se over the 112 cells passes 3.5 (0.00047 a cell by the
  normal tail). The refrozen kill missed (its line copied):
    REFROZEN: largest |obs - P| / se over the 112 cells at D = 2000,
    2000 trials: 3.146 at (F_5, 96, 0.017, 0.01); largest |obs - P|
    0.0146
  So at 2000 trials every cell sits within 0.015 of the two-moment
  model, the first run's 0.080 being its 200 trials' noise; the worst
  cell is at chance (mu 1.1e-9, by hand). The refrozen read has no control of
  its own size; R1 and R2 hold at any D. Toy scale: one N = 100, two D,
  one seed a D.

RUN RECORD. First run: 7.4 s wall, one process, its peak
unmeasured, exit 0; the refrozen read alone 46.7 s. Bare, both reads:
53.3 s, peak 44.2 MB, exit 0, its print the lines above.
"""

import os
import sys
from fractions import Fraction
from math import comb, sqrt

os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
import numpy as np
from scipy.special import ndtr

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                "..", "code"))
import binding  # noqa: E402

GRID = binding.GRID
NCAND, TRIALS = binding.NCAND, binding.TRIALS
ARMS = [("Z/9", 9), ("Z/27", 27), ("Z/81", 81), ("F_3", 3), ("F_5", 5),
        ("F_7", 7), ("F_11", 11), ("F_13", 13)]
PRINTED = {   # binding.py's correlation rows, as its run printed them
    "Z/9": [1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 0.81, 0.38, 0.10, 0.04,
            0.03, 0.01, 0.02, 0.01],
    "Z/27": [1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 0.95,
             0.47, 0.17, 0.03, 0.00],
    "Z/81": [1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00,
             0.99, 0.94, 0.79, 0.54],
    "F_3": [1.00, 0.00, 1.00, 0.00, 0.00, 0.01, 0.02, 0.01, 0.01, 0.00,
            0.01, 0.01, 0.00, 0.02],
    "F_5": [1.00, 1.00, 0.00, 1.00, 0.97, 0.73, 0.15, 0.03, 0.01, 0.01,
            0.01, 0.02, 0.03, 0.01],
    "F_7": [1.00, 1.00, 1.00, 0.42, 0.00, 0.00, 0.00, 0.00, 0.01, 0.00,
            0.01, 0.01, 0.01, 0.01],
    "F_11": [1.00, 1.00, 1.00, 1.00, 1.00, 0.98, 0.10, 0.00, 0.00, 0.00,
             0.01, 0.01, 0.03, 0.01],
    "F_13": [1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 0.90, 0.29, 0.14,
             0.01, 0.04, 0.01, 0.01],
}


def cen(x, g):
    x %= g
    return x - g if x > g // 2 else x


def moments(g, m):
    """mu = E c(1 + R), tau = E c(1 + R)^2, exact."""
    n = m - 1
    mu = sum(Fraction(comb(n, b), 2 ** n) * cen(1 + 2 * b - n, g)
             for b in range(n + 1))
    tau = sum(Fraction(comb(n, b), 2 ** n) * cen(1 + 2 * b - n, g) ** 2
              for b in range(n + 1))
    return mu, tau


Z = np.linspace(-12, 12, 24001)
PHI = np.exp(-Z ** 2 / 2) / sqrt(2 * np.pi)


def model(mu, tau, D, n=NCAND):
    var = float(tau - mu * mu)
    x = D * float(mu) + sqrt(D * max(var, 0.0)) * Z
    if var <= 0:
        return float(ndtr(D * float(mu) / sqrt(D * float(tau)))) ** (n - 1)
    return float(np.trapezoid(PHI * ndtr(x / sqrt(D * float(tau))) ** (n - 1), Z))


def observe(D, seed, trials=TRIALS):
    """binding.py's correlation sweep replayed, finite arms alone."""
    rng = np.random.default_rng(seed)
    obs = {a: [] for a, _ in ARMS}
    for m in GRID:
        tot = {a: 0.0 for a, _ in ARMS}
        for _ in range(trials):
            V = rng.choice(np.array([-1, 1], dtype=np.int64),
                           size=(NCAND, D))
            if m > 1:
                rest = rng.choice(np.array([-1, 1], dtype=np.int64),
                                  size=(m - 1, D)).sum(axis=0)
            else:
                rest = np.zeros(D, dtype=np.int64)
            s = V[0] + rest
            for a, g in ARMS:
                sc = V @ binding.centred(s, g)
                top = sc.max()
                win = np.flatnonzero(sc >= top - 1e-9)
                if sc[0] >= top - 1e-9:
                    tot[a] += 1.0 / len(win)
        for a, _ in ARMS:
            obs[a].append(tot[a] / trials)
    return obs


def stat(obs, D, tau_z=False, trials=TRIALS):
    """The largest |obs - P|/se, its cell, and the largest |obs - P|."""
    worst, cell, gap = 0.0, None, 0.0
    for a, g in ARMS:
        for j, m in enumerate(GRID):
            mu, tau = moments(g, m)
            P = model(mu, Fraction(m) if tau_z else tau, D)
            se = sqrt(max(P * (1 - P), 1e-300) / trials)
            d = abs(obs[a][j] - P)
            gap = max(gap, d)
            if d / se > worst:
                worst, cell = d / se, (a, m, round(obs[a][j], 4), round(P, 4))
    return worst, cell, gap


def check(label, ok):
    print(("PASS  " if ok else "FAIL  ") + label)
    return ok


def refrozen():
    """The kill refrozen on the first run: D = 2000, seed 2026, 2000
    trials a cell, dead past 3.5 se."""
    o = observe(2000, 2026, trials=2000)
    w, c, g = stat(o, 2000, trials=2000)
    print(f"REFROZEN: largest |obs - P| / se over the 112 cells at D = 2000, "
          f"2000 trials: {w:.3f} at {c}; largest |obs - P| {g:.4f}")
    ok = check("the conjecture survives its refrozen kill (<= 3.5 se)",
               w <= 3.5)
    return 0 if ok else 1


def main():
    good = True
    # R2: mu against binding.expected_corr.
    off = [(a, m) for a, g in ARMS for m in GRID
           if moments(g, m)[0] != binding.expected_corr(g, m)]
    good &= check(f"R2 mu = binding.expected_corr at {112 - len(off)} of "
                  f"112 cells", not off)
    # R1: m = 1.
    p1 = min(model(*moments(g, 1), 1000) for _, g in ARMS)
    obs = observe(binding.DIM, 2024)
    good &= check(f"R1 m = 1: least model P {p1:.7f}, every arm observed "
                  f"{sorted({obs[a][0] for a, _ in ARMS})}",
                  p1 > 0.999999 and all(obs[a][0] == 1.0 for a, _ in ARMS))
    # Q1: the replay is binding.py's run.
    same = sum(round(obs[a][j], 2) == PRINTED[a][j] for a, _ in ARMS
               for j in range(len(GRID)))
    good &= check(f"Q1 the replay equals binding.py's print at {same} of 112 "
                  f"cells", same == 112)
    # R3: the plant.
    planted, live = {}, 0
    for a, g in ARMS:          # 0.05 added at every live cell alone
        col = []
        for j, m in enumerate(GRID):
            P = model(*moments(g, m), binding.DIM)
            hit = 0.05 < P < 0.95
            live += hit
            col.append(obs[a][j] + (0.05 if hit else 0.0))
        planted[a] = col
    w3, c3, _ = stat(planted, binding.DIM)
    good &= check(f"R3 the plant (+0.05 at the {live} live cells, 0.05 < P "
                  f"< 0.95) fires: {w3:.1f} se at {c3}", w3 > 3)
    if not good:
        print("controls failed: no verdict")
        return 1
    # The readability print: one moment.
    w1, c1, g1 = stat(obs, binding.DIM, tau_z=True)
    print(f"READ: tau = m (Z's second moment, mu alone) at D = 1000: "
          f"largest {w1:.1f} se at "
          f"{c1}, largest |obs - P| {g1:.3f}")
    w, c, g = stat(obs, binding.DIM)
    obs2 = observe(2000, 2025)
    w2, c2, g2 = stat(obs2, 2000)
    print(f"Q2 largest |obs - P|: {g:.3f} at D = 1000, {g2:.3f} at D = 2000")
    print(f"KILL: largest |obs - P| / se over the 112 cells at D = 1000: "
          f"{w:.3f} at {c}; at D = 2000: {w2:.3f} at {c2}")
    survived = w <= 3 and w2 <= 3
    good &= check("the conjecture survives its kill (both <= 3 se)",
                  survived)
    for D, o in ((1000, obs), (2000, obs2)):
        rows = []
        for a, gg in ARMS:
            for j, m in enumerate(GRID):
                mu, tau = moments(gg, m)
                P = model(mu, tau, D)
                se = sqrt(max(P * (1 - P), 1e-300) / TRIALS)
                if abs(o[a][j] - P) > 3 * se:
                    rows.append(f"{a} m {m}: obs {o[a][j]:.3f}, P {P:.4f}")
        print(f"      D = {D}: {len(rows)} cells past 3 se: "
              + "; ".join(rows[:10]))
    good &= refrozen() == 0
    return 0 if good else 1


if __name__ == "__main__":
    sys.exit(main())