"""Independent recomputation of every number the distilled document states."""
from fractions import Fraction as F
import math, itertools
import numpy as np

ok = []
def check(name, cond):
    ok.append((name, bool(cond)))
    if not cond: print("FAIL:", name)

# ---------- carrier, Casimir, multiplicities (exact via Clebsch-Gordan census)
def couple(j, n):
    m = {j: 1}
    for _ in range(n - 1):
        o = {}
        for J, c in m.items():
            for x in range(abs(J - j), J + j + 1):
                o[x] = o.get(x, 0) + c
        m = o
    return m                                   # spin J -> multiplicity
mult = couple(2, 3)
spec = {J*(J+1): c*(2*J+1) for J, c in mult.items()}
check("multiplicities 1,3,5,4,3,2,1", [mult[J] for J in range(7)] == [1,3,5,4,3,2,1])
check("dims 1,9,25,28,27,22,13", [spec[l] for l in (0,2,6,12,20,30,42)] == [1,9,25,28,27,22,13])
N = sum(spec.values()); check("dim 125", N == 125)
mu = F(sum(l*d for l,d in spec.items()), N)
var = F(sum(l*l*d for l,d in spec.items()), N) - mu*mu
check("mu=18, var=144", mu == 18 and var == 144)
sig = 12
check("selected 6,30", (mu - sig, mu + sig) == (6, 30))
check("dim ker K = 25+22 = 47", spec[6] + spec[30] == 47)
Kev = {l: (l-6)*(l-30) for l in spec}
check("K eigenvalues", [Kev[l] for l in (0,2,6,12,20,30,42)] == [180,112,0,-108,-140,0,432])

# ---------- moment formula n = 2..5, j = 1..3
for n in range(2, 6):
    for j in (1, 2, 3):
        m_ = couple(j, n); s = {J*(J+1): c*(2*J+1) for J, c in m_.items()}; M = sum(s.values())
        m1 = F(sum(l*d for l,d in s.items()), M); v = F(sum(l*l*d for l,d in s.items()), M) - m1*m1
        check(f"moment formula n={n} j={j}", m1 == n*j*(j+1) and v == F(2*n*(n-1),3)*(j*(j+1))**2)

# ---------- Pell ladder for integral sigma: (2n-1)^2 - 6 m^2 = 1
orders = [n for n in range(2, 3000) if (lambda t: t.denominator == 1 and math.isqrt(t.numerator)**2 == t.numerator)(F(2*n*(n-1), 3))]
check("orders 3, 25, 243, 2401", orders == [3, 25, 243, 2401])

# ---------- Fibonacci-Lucas tower on the cube
Fib = [0, 1]; [Fib.append(Fib[-1] + Fib[-2]) for _ in range(30)]
Luc = [2, 1]; [Luc.append(Luc[-1] + Luc[-2]) for _ in range(30)]
for k in (5, 7, 11, 13):
    j2, J2 = Fib[k], Luc[k]                       # 2j+1, 2J+1
    check(f"Pell -4 at k={k}", J2**2 - 5*j2**2 == -4)
for k, j, J in ((5,2,5), (7,6,14), (11,44,99)):
    m_ = couple(j, 3); s = {JJ*(JJ+1): c*(2*JJ+1) for JJ, c in m_.items()}
    kd = s[j*(j+1)] + s[J*(J+1)]
    check(f"tower k={k}: ker = F^2 + F_(k-2) L_k", kd == Fib[k]**2 + Fib[k-2]*Luc[k] and sum(s.values()) == Fib[k]**3)
    check(f"tower k={k}: 3j - J = F_(k-2) - 1", 3*j - J == Fib[k-2] - 1)
    if k == 5: check("47/125", F(kd, 125) == F(47,125))
    if k == 7: check("314/2197", F(kd, sum(s.values())) == F(314, 2197))
    if k == 11: check("14687/704969", F(kd, sum(s.values())) == F(14687, 704969))
check("dial tower index F_(k-3)F_(k-1)", [Fib[k]**2 - Fib[k-2]*Luc[k] for k in (3,5,7,9,11,13)] == [0,3,24,168,1155,7920]
      and all(Fib[k]**2 - Fib[k-2]*Luc[k] == Fib[k-3]*Fib[k-1] for k in (3,5,7,9,11,13)))

# ---------- projector polynomial
def pmul(a, b):
    r = [0]*(len(a)+len(b)-1)
    for i, x in enumerate(a):
        for k, y in enumerate(b): r[i+k] += x*y
    return r
poly = [1]
for root in (0, 2, 12, 20, 42, 31): poly = pmul(poly, [-root, 1])
check("expanded projector numerator", poly == [0, -624960, 430848, -66940, 4088, -107, 1])
PE = lambda x: F(x*(x-2)*(x-12)*(x-20)*(x-42)*(x-31), 1814400)
check("P_E = 1 on {6,30}, 0 elsewhere", all(PE(l) == (1 if l in (6,30) else 0) for l in spec))
check("1814400 = 2^7 3^4 5^2 7 = 10!/2", 1814400 == 2**7*3**4*5**2*7 == math.factorial(10)//2)
check("commutant 25+4 = 29; 5*5 + 2*11 = 47", mult[2]**2 + mult[5]**2 == 29 and 5*5 + 2*11 == 47)

# ---------- K^2 gap, step, rate
k2 = sorted({v*v for v in Kev.values()} - {0})
check("K^2 spectrum", k2 == [11664, 12544, 19600, 32400, 186624])
g_, L_ = k2[0], k2[-1]
check("108^2, 432^2, ratio 16", g_ == 108**2 and L_ == 432**2 and L_ == 16*g_)
check("eps* = 1/99144, q* = 15/17, 2/Lambda = 1/93312", F(2, g_+L_) == F(1,99144) and F(L_-g_, L_+g_) == F(15,17) and F(2, L_) == F(1, 93312))
check("Coq identity 17*87480 = 15*99144", 17*87480 == 15*99144)
check("general rate (kappa-1)/(kappa+1) at kappa 16", F(16-1, 16+1) == F(15,17))
check("B-contraction rate 78/125", 1 - F(47,125) == F(78,125))

# ---------- quartic filter
s_vals = {l: F(Kev[l], 432) for l in spec}
Q4 = lambda s: 1 - F(2176,353)*s**2 + F(2048,353)*s**4
comp = [abs(Q4(s_vals[l])) for l in spec if l not in (6,30)]
check("Q4 = 1 on kernel, max 225/353 off it", all(Q4(s_vals[l]) == 1 for l in (6,30)) and max(comp) == F(225,353))
check("225/353 attained at J=3 and J=6", [l for l in spec if l not in (6,30) and abs(Q4(s_vals[l])) == F(225,353)] == [12, 42])

# ---------- Beta(47,78) and median
check("Beta mean 47/125", F(47, 47+78) == F(47,125))
sd = math.sqrt(47*78/((125**2)*126)); check("Beta sd 0.04315", abs(sd - 0.04315) < 5e-6)
def U(n, z):
    a, b = 1, 2*z
    if n == 0: return 1
    for _ in range(n-1): a, b = b, 2*z*b - a
    return b
dd = [1,9,25,28,27,22,13]
Rx = lambda z: 47*sum(dd[j]*U(2*j, z)**2 for j in range(7)) - 125*(25*U(4, z)**2 + 22*U(10, z)**2)
qc = [1125, -51000, 1775800, -30728960, 247566720, -1058193408, 2613002240, -3859415040, 3367403520, -1601699840, 320339968]
qp = lambda u: sum(c*u**i for i, c in enumerate(qc))
Sp = lambda u: 16*u*(2*u-1)*qp(u)
check("R(x) = S(x^2) (13 points, degree 12)", all(Rx(F(k, 3)) == Sp(F(k, 3)**2) for k in range(-6, 7)))
check("q(1-u) = q(u) (11+ points)", all(qp(F(k,7)) == qp(1 - F(k,7)) for k in range(-6, 8)))
check("S(u)S(1-u) = -256 u(1-u)(2u-1)^2 q^2 (25+ points)", all(Sp(F(k,5))*Sp(1-F(k,5)) == -256*F(k,5)*(1-F(k,5))*(2*F(k,5)-1)**2*qp(F(k,5))**2 for k in range(-12, 14)))
Mn = 200000
def eta(t):
    s_ = math.sin(t)
    ch = lambda j: (2*j+1) if abs(s_) < 1e-14 else math.sin((2*j+1)*t)/s_
    a = [dd[j]*ch(j)**2 for j in range(7)]
    return (a[2] + a[5]) / sum(a)
v = sorted(eta(2*math.pi*(i+0.5)/Mn) for i in range(Mn))
med = (v[Mn//2-1] + v[Mn//2])/2
check("median 0.376", abs(med - 0.376) < 2e-5)
mean_dtheta = sum(v)/Mn
check("dtheta mean 0.37519 (not 47/125)", abs(mean_dtheta - 0.3751893) < 2e-6)
crossings = sum(1 for i in range(1, 400001) if (eta(math.pi*(i-0.5)/400000) - 0.376) * (eta(math.pi*(i+0.5)/400000) - 0.376) < 0)
check("14 sign changes on (0, pi)", crossings == 14)
# the 15th point: theta = pi/2 is a tangency, eta touches 47/125 from above
check("eta(pi/2) = 47/125 exactly, and above it on both sides", abs(eta(math.pi/2) - 0.376) < 1e-12 and eta(math.pi/2 - 1e-3) > 0.376 and eta(math.pi/2 + 1e-3) > 0.376)
# q has 6 roots in (0,1): count sign changes of q on a fine grid
qs = [float(qp(F(i, 20000))) for i in range(1, 20000)]
check("q has six roots in (0,1)", sum(1 for a, b in zip(qs, qs[1:]) if a*b < 0) == 6)
from scipy.stats import beta as _beta
check("Beta(47,78) 1e-6 threshold 0.58715", abs(_beta.isf(1e-6, 47, 78) - 0.58715) < 5e-5)
check("Beta(47,78) 1e-2 threshold 0.47880", abs(_beta.isf(1e-2, 47, 78) - 0.47880) < 5e-5)
legendre6 = lambda q: pow(6, (q-1)//2, q) == 1
check("6 is a square mod 43, 47, 53, 67, 71, 73", all(legendre6(q) for q in (43, 47, 53, 67, 71, 73)))
check("6 is not a square mod 59, 61 (the gaps in that list)", not legendre6(59) and not legendre6(61))
check("A5 mu + sigma = 4.995..", abs(float(F(61,15)) + math.sqrt(194/225) - 4.99523) < 1e-4)
check("only {6,30} sums to 47 among sector pairs", [(a, b) for a in spec for b in spec if a < b and spec[a] + spec[b] == 47] == [(6, 30)])

# ---------- reduction mod q
diffs = sorted({abs(a-b) for a in spec for b in spec} - {0})
check("root differences top at 42", max(diffs) == 42)
for q in (43, 47, 53, 101, 1009, 65537):
    check(f"distinct eigenvalues mod {q}", len({l % q for l in spec}) == 7)
check("6 is a QR mod 47, not mod 59", pow(6, 23, 47) == 1 and pow(6, 29, 59) != 1)

# ---------- numerical: symmetric core, Lindblad-free checks, Dial grading
j = 2; n5 = 5
m = np.array([j - k for k in range(n5)], float)
Jz = np.diag(m); Jp = np.zeros((n5, n5))
for k in range(1, n5): Jp[k-1, k] = math.sqrt(j*(j+1) - m[k]*(m[k]+1))
Jm = Jp.T; Jx = (Jp + Jm)/2; Jy = (Jp - Jm)/(2j); I5 = np.eye(n5)
k3 = lambda a, b, c: np.kron(np.kron(a, b), c)
tot = lambda A: k3(A, I5, I5) + k3(I5, A, I5) + k3(I5, I5, A)
C = (tot(Jx) @ tot(Jx) + tot(Jy) @ tot(Jy) + tot(Jz) @ tot(Jz)).real
w, V = np.linalg.eigh(C)
proj = lambda lam: V[:, np.abs(w - lam) < 1e-6] @ V[:, np.abs(w - lam) < 1e-6].T
P6, P30 = proj(6.), proj(30.); P = P6 + P30
idx = list(itertools.product(range(5), repeat=3)); pos = {t: i for i, t in enumerate(idx)}
def Uperm(p):
    M = np.zeros((125, 125))
    for i, t in enumerate(idx): M[pos[tuple(t[p[k]] for k in range(3))], i] = 1
    return M
Psym = sum(Uperm(p) for p in itertools.permutations(range(3)))/6
rk = lambda A: int(round(np.trace(A)))
check("rank P_sym = 35", rk(Psym) == 35)
check("Sym^3 meets sectors 1,0,5,7,9,0,13", [rk(proj(float(l)) @ Psym) for l in (0,2,6,12,20,30,42)] == [1,0,5,7,9,0,13])
Pcan = P @ Psym
check("P_can rank 5, = P6 Psym, P30 Psym = 0", np.allclose(Pcan @ Pcan, Pcan, atol=1e-9) and rk(Pcan) == 5 and np.allclose(Pcan, P6 @ Psym, atol=1e-9) and np.allclose(P30 @ Psym, 0, atol=1e-9))
X = (tot(Jx) @ tot(Jx) + tot(Jy) @ tot(Jy) + tot(Jz) @ tot(Jz)).real  # C
# exchange operator X = J1.J2 + J2.J3 + J3.J1 with C = 18 I + 2X
def site(A, s_):
    mats = [I5, I5, I5]; mats[s_] = A; return k3(*mats)
Xex = sum(site(A, a) @ site(A, b) for (a, b) in ((0,1),(1,2),(2,0)) for A in (Jx, Jy, Jz)).real
check("C = 18I + 2X", np.allclose(C, 18*np.eye(125) + 2*Xex, atol=1e-9))
Kmat = (C - 6*np.eye(125)) @ (C - 30*np.eye(125))
check("K = 4(X^2 - 36 I)", np.allclose(Kmat, 4*(Xex @ Xex - 36*np.eye(125)), atol=1e-8))
S = (18*np.eye(125) - C) @ P / 12
check("grading S^2 = P, Tr S = 3, S = -XP/6", np.allclose(S @ S, P, atol=1e-9) and abs(np.trace(S) - 3) < 1e-9 and np.allclose(S, -Xex @ P/6, atol=1e-9))
Wv = np.linalg.eigvalsh(Kmat @ Kmat)
check("numerical K^2 gap 11664 and top 186624", abs(sorted(set(np.round(Wv, 6)))[1] - 11664) < 1e-4 and abs(Wv.max() - 186624) < 1e-3)
Gam = np.eye(125) - Kmat @ Kmat / 99144
check("||Gamma^n - P|| = (15/17)^n (n=1..5)", all(abs(np.linalg.norm(np.linalg.matrix_power(Gam, n) - P, 2) - (15/17)**n) < 1e-10 for n in range(1, 6)))
A = Kmat/432; Q4m = np.eye(125) - 2176/353*A@A + 2048/353*np.linalg.matrix_power(A, 4)
check("||Q4^n - P|| = (225/353)^n (n=1..4)", all(abs(np.linalg.norm(np.linalg.matrix_power(Q4m, n) - P, 2) - (225/353)**n) < 1e-10 for n in range(1, 5)))
Pprod = np.eye(125)
for lam in (11664, 12544, 19600, 32400, 186624): Pprod = Pprod @ (np.eye(125) - Kmat @ Kmat/lam)
check("P47 = prod(I - K^2/lambda)", np.allclose(Pprod, P, atol=1e-8))
# symmetric dial: commutant of SU(2) on E47 has dimension 29
Jtot = [tot(Jx), tot(Jy), tot(Jz)]
Q = V[:, (np.abs(w - 6) < 1e-6) | (np.abs(w - 30) < 1e-6)]
Jk = [Q.T @ Jm_ @ Q for Jm_ in Jtot]
Mcomm = np.vstack([np.kron(np.eye(47), Jkk) - np.kron(Jkk.T, np.eye(47)) for Jkk in Jk])
null = 47*47 - np.linalg.matrix_rank(Mcomm, tol=1e-8)
check("commutant on E47 has dimension 29", null == 29)

# ---------- Theorem G constants on E47
check("buoy R0 = 24", max(abs(l - 18) for l in spec) == 24)
check("K-window exact for eps < sqrt(630) - 24 = 1.0998", abs((math.sqrt(630) - 24) - 1.0998) < 1e-4 and abs((48 + (math.sqrt(630)-24))*(math.sqrt(630)-24) - 54) < 1e-9)
check("Casimir gap from {6,30} to the rest = 4", min(abs(a - b) for a in (6,30) for b in spec if b not in (6,30)) == 4)

# ---------- MGG expander: lambda_2(L_n) >= 8 - 5 sqrt 2 for small n
def mgg(n):
    Ad = np.zeros((n*n, n*n))
    for x in range(n):
        for y in range(n):
            u = x*n + y
            for (a, b) in (((x+2*y) % n, y), ((x+2*y+1) % n, y), (x, (y+2*x) % n), (x, (y+2*x+1) % n)):
                vv = a*n + b; Ad[u, vv] += 1; Ad[vv, u] += 1
    return 8*np.eye(n*n) - Ad
lam2 = [np.sort(np.linalg.eigvalsh(mgg(n)))[1] for n in range(2, 16)]
check("MGG lambda_2 >= 8 - 5 sqrt2 for n = 2..15", min(lam2) >= 8 - 5*math.sqrt(2) - 1e-9)
check("MGG smallest lambda_2 for n <= 15 is >= 1.946", min(lam2) >= 1.946)

# ---------- Valle-Puthoff counterexample
lam_, L, Lam, B = 1, F(1,2), 2, 1
check("counterexample: lambda L = 1/2, q = 5/2", lam_*L == F(1,2) and lam_*L + Lam*B == F(5,2))
check("T = id on [0,1]", all(abs((2*x/(x+1))*((x+1)/2) - x) < 1e-15 for x in np.linspace(0, 1, 101)))

# ---------- A5 analogue and selective operation
check("A5 blocks 1+9+9+16+25 = 60, 1+25 = 26, 26/60 = 13/30", 1+9+9+16+25 == 60 and F(26,60) == F(13,30))
mu5 = F(1*1 + 3*9 + 3*9 + 4*16 + 5*25, 60); v5 = F(1*1 + 9*9 + 9*9 + 16*16 + 25*25, 60) - mu5**2
check("A5 moments 61/15 and 194/225", mu5 == F(61,15) and v5 == F(194,225))
check("47^2 = 2209, 47^2 + 78^2 = 8293", 47**2 == 2209 and 47**2 + 78**2 == 8293)

bad = [nm for nm, c in ok if not c]
print(f"{len(ok) - len(bad)} / {len(ok)} checks passed")
print(f"median = {med:.6f}, d-theta mean = {mean_dtheta:.7f}, crossings = {crossings}, MGG min lambda2 (n<=15) = {min(lam2):.6f} vs {8-5*math.sqrt(2):.6f}")
