#!/usr/bin/env python3
"""
E₄₇ QUANTUM ENERGY — a first-principles proof, validated in Python.

Every symbolic line printed below is asserted before it is shown.
✓   exact over ℚ (integer 125 × 125 model, no floating point)
≈✓  float64 cross-check in the Hermitian model

Nothing is inserted by hand: no projector, no 47, no 6 or 30.
The construction starts from the spin-2 ladder relations alone.
"""
from fractions import Fraction as Fr
from math import lcm, prod, isqrt, log
import numpy as np

EXACT, FLOAT = "✓", "≈✓"


def show(sym, ok, mark=EXACT):
    if not ok:
        raise AssertionError(sym)
    print(f"  {sym}  {mark}")


def head(t):
    print(f"\n{t}")


# ── integer model of V₂ ─────────────────────────────────────────────────────
# basis |m⟩′ = |m⟩ / N_m with N_{m+1} = N_m·√((2−m)(3+m)); then
# J₊|m⟩′ = (2−m)(3+m)|m+1⟩′ , J₋|m+1⟩′ = |m⟩′ , J_z|m⟩′ = m|m⟩′ (all integer)
j, ms = 2, (2, 1, 0, -1, -2)
pos = {m: i for i, m in enumerate(ms)}


def Z(n):
    return np.zeros((n, n), dtype=object)


def Id(n):
    M = Z(n)
    for i in range(n):
        M[i, i] = 1
    return M


jz, jp, jm = Z(5), Z(5), Z(5)
for m in ms:
    jz[pos[m], pos[m]] = m
    if m < j:
        jp[pos[m + 1], pos[m]] = (j - m) * (j + m + 1)
        jm[pos[m], pos[m + 1]] = 1
w1 = (1, 4, 24, 144, 576)          # Gram weights ⟨m|m⟩′ × 576, m = 2 … −2


def kron(A, B):
    n, k = A.shape[0], B.shape[0]
    R = Z(n * k)
    for a in range(n):
        for b in range(n):
            if A[a, b] != 0:
                R[a * k:(a + 1) * k, b * k:(b + 1) * k] = A[a, b] * B
    return R


I5 = Id(5)


def total(x):
    return kron(kron(x, I5), I5) + kron(kron(I5, x), I5) + kron(kron(I5, I5), x)


D = 125
I = Id(D)
Jz, Jp, Jm = total(jz), total(jp), total(jm)
W = [w1[a] * w1[b] * w1[c] for a in range(5) for b in range(5) for c in range(5)]


def nz(A):
    return [(r, c, A[r, c]) for r in range(A.shape[0]) for c in range(A.shape[1]) if A[r, c] != 0]


def lmul(S, X):                    # (sparse S) · X
    R = np.zeros_like(X)
    for r, c, v in S:
        R[r] = R[r] + v * X[c]
    return R


def rmul(X, S):                    # X · (sparse S)
    R = np.zeros_like(X)
    for r, c, v in S:
        R[:, c] = R[:, c] + X[:, r] * v
    return R


def tr(X):
    return sum(X[i, i] for i in range(X.shape[0]))


def same(A, B):
    return bool(np.all(A == B))


sJz, sJp, sJm = nz(Jz), nz(Jp), nz(Jm)
C = lmul(sJz, Jz) - Jz + lmul(sJp, Jm)          # J² = J_z² − J_z + J₊J₋
sC = nz(C)


def polyC(roots, X):               # Π (C − r) · X
    for r in roots:
        X = lmul(sC, X) - r * X
    return X


def wdot(x, y):                    # ⟨x|y⟩_W
    return sum(W[i] * x[i] * y[i] for i in range(D))


def selfadj_W(A):                  # W·A = Aᵀ·W
    return all(W[r] * A[r, c] == A[c, r] * W[c] for r in range(D) for c in range(D))


rng = np.random.default_rng(47125)
PSI = [np.array([int(v) for v in rng.integers(-3, 4, D)], dtype=object) for _ in range(4)]

BOX = ("E₄₇ QUANTUM ENERGY", "first-principles proof · Python-validated",
       "✓ exact over ℚ    ≈✓ float64 cross-check")
wbox = max(len(t) for t in BOX) + 4
print("╔" + "═" * wbox + "╗")
for t in BOX:
    print("║  " + t.ljust(wbox - 2) + "║")
print("╚" + "═" * wbox + "╝")

# §1 ─────────────────────────────────────────────────────────────────────────
head("§1  Axioms")
print("  J_z|m⟩ = m|m⟩ ,  J₊|m⟩ = √((2−m)(3+m)) |m+1⟩ ,  J₋ = J₊†")
print("  V = V₂^⊗3 ,  J_a = Σₖ J_a⁽ᵏ⁾ ,  C = J² = J_z² − J_z + J₊J₋")
print("  τ = Tr/dim V ,  μ = τ(C) ,  σ² = τ(C²) − μ²")
print("  K = (C − (μ−σ))(C − (μ+σ)) ,  H = g·K² ,  g > 0")

# §2 ─────────────────────────────────────────────────────────────────────────
head("§2  Carrier")
show("dim V = 5³ = 125", Jz.shape == (125, 125))
show("[J_z, J±] = ±J± ,  [J₊, J₋] = 2J_z",
     same(lmul(sJz, Jp) - lmul(sJp, Jz), Jp) and same(lmul(sJz, Jm) - lmul(sJm, Jz), -Jm)
     and same(lmul(sJp, Jm) - lmul(sJm, Jp), 2 * Jz))
show("[C, J_a] = 0  ∀a ∈ {z, +, −}",
     all(same(lmul(sC, X) - lmul(sX, C), 0 * X) for X, sX in ((Jz, sJz), (Jp, sJp), (Jm, sJm))))
s12 = [25 * b + 5 * a + c for a in range(5) for b in range(5) for c in range(5)]
s123 = [25 * c + 5 * a + b for a in range(5) for b in range(5) for c in range(5)]
show("[C, π] = 0  ∀π ∈ S₃  (generators (12), (123))",
     same(C[np.ix_(s12, s12)], C) and same(C[np.ix_(s123, s123)], C))
show("C = C†  (W·C = Cᵀ·W ,  W = Gram matrix)", selfadj_W(C))

# §3 ─────────────────────────────────────────────────────────────────────────
head("§3  Spectrum")
Lam = [0, 2, 6, 12, 20, 30, 42]
show("Π_{λ∈Λ} (C − λ) = 0 ,  Λ = {0, 2, 6, 12, 20, 30, 42}", same(polyC(Lam, I), 0 * I))
Nl, dl = {}, {}
for l in Lam:
    oth = [x for x in Lam if x != l]
    Nl[l], dl[l] = polyC(oth, I), prod(l - x for x in oth)
show("P_λ = Π_{μ≠λ} (C − μ)/(λ − μ) ≠ 0  ∀λ  ⇒  spec C = Λ",
     all(not same(Nl[l], 0 * I) for l in Lam))
L = lcm(*[abs(dl[l]) for l in Lam])
show("Σ_λ P_λ = 𝟙", same(sum((L // dl[l]) * Nl[l] for l in Lam), L * I))
show("P_λ P_ν = δ_λν P_λ",
     all(same(polyC([x for x in Lam if x != a], Nl[b]),
              (dl[a] * Nl[a]) if a == b else 0 * I) for a in Lam for b in Lam))
mult = [Fr(tr(Nl[l]), dl[l]) for l in Lam]
show("(Tr P_λ) = (1, 9, 25, 28, 27, 22, 13) ,  Σ = 125",
     mult == [1, 9, 25, 28, 27, 22, 13] and sum(mult) == 125)
nJ = [mult[J] / (2 * J + 1) for J in range(7)]
show("λ = J(J+1) ,  Tr P_λ = (2J+1)·n_J ,  n_J = (1,3,5,4,3,2,1)",
     Lam == [J * (J + 1) for J in range(7)] and nJ == [1, 3, 5, 4, 3, 2, 1])
show("V ≅ V₀ ⊕ 3V₁ ⊕ 5V₂ ⊕ 4V₃ ⊕ 3V₄ ⊕ 2V₅ ⊕ V₆", sum(n * (2 * J + 1) for J, n in enumerate(nJ)) == 125)

# §4 ─────────────────────────────────────────────────────────────────────────
head("§4  Selector from moments")
mu = Fr(tr(C), D)
tau2 = Fr(tr(lmul(sC, C)), D)
sig2 = tau2 - mu ** 2
sig = isqrt(int(sig2))
show("μ = τ(C) = 2250/125 = 18", mu == 18)
show("τ(C²) = 58500/125 = 468 ,  σ² = 468 − 18² = 144 ,  σ = 12",
     tau2 == 468 and sig2 == 144 and sig * sig == 144)
show("μ − σ = 6 = 2·3 ∈ Λ  (J = 2) ,  μ + σ = 30 = 5·6 ∈ Λ  (J = 5)",
     mu - sig == 6 and mu + sig == 30 and 6 in Lam and 30 in Lam)
K = polyC([6, 30], I)
show("K = (C − 6)(C − 30) = (C − μ)² − σ²", same(K, polyC([18, 18], I) - 144 * I))

# §5 ─────────────────────────────────────────────────────────────────────────
head("§5  Energy law   (units g = 1)")
H = polyC([6, 30, 6, 30], I)
E = {l: ((l - 6) * (l - 30)) ** 2 for l in Lam}
show("H P_λ = E_λ P_λ ,  E_λ = [(λ − 6)(λ − 30)]²",
     all(same(polyC([6, 30, 6, 30], Nl[l]), E[l] * Nl[l]) for l in Lam))
show("H = Σ_λ E_λ P_λ", same(L * H, sum((L // dl[l]) * E[l] * Nl[l] for l in Lam)))
show("E_J = g[J(J+1) − 6]²[J(J+1) − 30]²",
     [E[J * (J + 1)] for J in range(7)] == [32400, 12544, 0, 11664, 19600, 0, 186624])
print("  (E_J)_{J=0…6} = (32400, 12544, 0, 11664, 19600, 0, 186624)·g")
show("H = g·((C − μ)² − σ²)²", same(H, polyC([18, 18], polyC([18, 18], I) - 144 * I) - 144 * (polyC([18, 18], I) - 144 * I)))

# §6 ─────────────────────────────────────────────────────────────────────────
head("§6  Positivity")
show("K = K†  ⇒  ⟨ψ|H|ψ⟩ = g‖Kψ‖² ≥ 0", selfadj_W(K) and all(
    wdot(p, polyC([6, 30, 6, 30], p)) == wdot(polyC([6, 30], p), polyC([6, 30], p)) >= 0 for p in PSI))

# §7 ─────────────────────────────────────────────────────────────────────────
head("§7  Ground manifold")
Np = polyC([0, 2, 12, 20, 31, 42], I)
DEN = 1814400
show("1814400 = 2⁷·3⁴·5²·7 = 10!/2", DEN == 2**7 * 3**4 * 5**2 * 7 == prod(range(1, 11)) // 2)
show("P = C(C−2)(C−12)(C−20)(C−31)(C−42)/1814400 = P₆ + P₃₀",
     same(Np * dl[6] * dl[30], DEN * (Nl[6] * dl[30] + Nl[30] * dl[6])))
show("P² = P ,  P = P†", same(polyC([0, 2, 12, 20, 31, 42], Np), DEN * Np) and selfadj_W(Np))
KP0 = same(polyC([6, 30], Np), 0 * I)
show("K P = 0 ,  H P = P H = 0",
     KP0 and same(polyC([6, 30, 6, 30], Np), 0 * I)
     and same(polyC([0, 2, 12, 20, 31, 42], H), 0 * I))
# 1814400 − Π(λ − r) = (λ − 6)(λ − 30)·R(λ) over ℤ[λ]
num = [1]
for r in [0, 2, 12, 20, 31, 42]:
    num = [a - r * b for a, b in zip(num + [0], [0] + num)]
num = [-a for a in num]
num[-1] += DEN
quo, rem = [], num[:]
div = [1, -36, 180]                       # (λ − 6)(λ − 30)
for i in range(len(num) - 2):
    q = rem[i]
    quo.append(q)
    for k in range(3):
        rem[i + k] -= q * div[k]
R = Z(D)
for c in quo:                              # Horner: R(C)
    R = lmul(sC, R) + c * I
RK = all(v == 0 for v in rem) and same(DEN * I - Np, polyC([6, 30], R))
show("𝟙 − P = K·R(C)/1814400 ,  R ∈ ℤ[λ]  ⇒  ker K ⊆ im P", RK)
show("ker H = ker K = im P = E₆ ⊕ E₃₀   (KP = 0 , 𝟙−P = KR , K = K†)",
     KP0 and RK and selfadj_W(K))
show("dim ker H = Tr P = 25 + 22 = 47 ,  E_ground = 0", tr(Np) == 47 * DEN and mult[2] + mult[5] == 47)
show("E₄₇ ≅ 5V₂ ⊕ 2V₅ ,  25 = 5·5 ,  22 = 2·11", nJ[2] == 5 and nJ[5] == 2)
show("Hψ = 0  ⇔  (C − μ)²ψ = σ²ψ", same(K, polyC([18, 18], I) - 144 * I))

# §8 ─────────────────────────────────────────────────────────────────────────
head("§8  Gap and coercivity")
pos_levels = sorted((E[l], l) for l in Lam if E[l] > 0)
Gap, Top = pos_levels[0][0], pos_levels[-1][0]
show("Δ = min{E_λ > 0} = 11664 = 108²  (J = 3, ×28)",
     Gap == 11664 == 108**2 and pos_levels[0][1] == 12 and mult[3] == 28)
show("M = max E_λ = 186624 = 432²  (J = 6, ×13) ,  κ = M/Δ = 16",
     Top == 186624 == 432**2 and Fr(Top, Gap) == 16)
show("spec H = {0⁴⁷, 11664²⁸, 12544⁹, 19600²⁷, 32400¹, 186624¹³}",
     [(e, mult[Lam.index(l)]) for e, l in pos_levels]
     == [(11664, 28), (12544, 9), (19600, 27), (32400, 1), (186624, 13)])
L2 = lcm(L, DEN)
out = [l for l in Lam if l not in (6, 30)]
show("H − Δ(𝟙 − P) = Σ_{λ∉{6,30}} (E_λ − Δ) P_λ ⪰ 0",
     same(L2 * H - Gap * L2 * I + Gap * (L2 // DEN) * Np,
          sum((E[l] - Gap) * (L2 // dl[l]) * Nl[l] for l in out))
     and all(E[l] - Gap >= 0 for l in out))
show("M(𝟙 − P) − H = Σ_{λ∉{6,30}} (M − E_λ) P_λ ⪰ 0",
     same(Top * L2 * I - Top * (L2 // DEN) * Np - L2 * H,
          sum((Top - E[l]) * (L2 // dl[l]) * Nl[l] for l in out)))
ok_ke, ok_co = True, True
for p in PSI:
    eH = wdot(p, polyC([6, 30, 6, 30], p))
    parts = {l: polyC([x for x in Lam if x != l], p) for l in Lam}
    ok_ke &= eH == sum(Fr(E[l] * wdot(parts[l], parts[l]), dl[l] ** 2) for l in Lam)
    q = p - polyC([0, 2, 12, 20, 31, 42], p) / Fr(DEN)
    nq = wdot(q, q)
    ok_co &= Gap * nq <= eH <= Top * nq
show("⟨ψ|H|ψ⟩ = Σ_λ E_λ ‖P_λψ‖²", ok_ke)
show("Δ‖(𝟙−P)ψ‖² ≤ ⟨ψ|H|ψ⟩ ≤ M‖(𝟙−P)ψ‖²", ok_co)

# §9 ─────────────────────────────────────────────────────────────────────────
head("§9  Dynamics")
sH = nz(H)
show("[H, J_a] = 0 ,  [H, π] = 0",
     all(same(rmul(H, sX), lmul(sX, H)) for sX in (sJz, sJp, sJm))
     and same(H[np.ix_(s12, s12)], H) and same(H[np.ix_(s123, s123)], H))
show("HP = 0  ⇒  e^{−iHt}P = P  ∀t", same(polyC([6, 30, 6, 30], Np), 0 * I))
s = np.sqrt(np.array(W, dtype=float))
Ch = (s[:, None] * np.array(C, dtype=float)) / s[None, :]
ev, U = np.linalg.eigh((Ch + Ch.T) / 2)
show("C = Cᵀ ,  spec C = Λ  (Hermitian model)",
     np.allclose(Ch, Ch.T, atol=1e-9) and np.allclose(ev, np.repeat(Lam, [int(x) for x in mult]), atol=1e-9), FLOAT)
Eh = ((ev - 6) * (ev - 30)) ** 2 / Gap               # g = 1/Δ
mask = np.isclose(Eh, 0, atol=1e-9)
Ph = U[:, mask] @ U[:, mask].T


def heat(t):
    return (U * np.exp(-t * Eh)) @ U.T


show("‖e^{−tH} − P‖ = e^{−Δt}",
     all(abs(np.linalg.norm(heat(t) - Ph, 2) - np.exp(-t)) < 1e-12 for t in (0.25, 1.0, 3.0)), FLOAT)
x0 = rng.standard_normal(D)
Hh = (U * Eh) @ U.T


def en(t):
    y = heat(t) @ x0
    return y @ Hh @ y


h = 1e-6
y3 = heat(0.3) @ x0
show("ψ̇ = −Hψ  ⇒  d⟨H⟩/dt = −2⟨H²⟩ ≤ 0",
     abs((en(0.3 + h) - en(0.3 - h)) / (2 * h) + 2 * (y3 @ Hh @ Hh @ y3)) < 1e-5 * abs(y3 @ Hh @ Hh @ y3), FLOAT)
show("⟨H⟩(t) ≤ e^{−2Δt}⟨H⟩(0) ,  Pψ(t) = Pψ(0)",
     all(en(t) <= np.exp(-2 * t) * en(0) + 1e-12 for t in (0.5, 1, 2))
     and np.allclose(Ph @ (heat(2.0) @ x0), Ph @ x0, atol=1e-12), FLOAT)

# §10 ────────────────────────────────────────────────────────────────────────
head("§10  Optimal preparation")
eps = Fr(2, Gap + Top)
show("ε⋆ = 2/(Δ + M) = 1/99144 · g⁻¹", eps == Fr(1, 99144))
gam = {l: 1 - eps * E[l] for l in out}
show("Γ = 𝟙 − ε⋆H :  max_{λ∉{6,30}} |1 − ε⋆E_λ| = 15/17",
     max(abs(v) for v in gam.values()) == Fr(15, 17))
show("1 − ε⋆Δ = +15/17 ,  1 − ε⋆M = −15/17  (equioscillation)",
     gam[12] == Fr(15, 17) and gam[42] == Fr(-15, 17))
show("(κ − 1)/(κ + 1) = 15/17", Fr(16 - 1, 16 + 1) == Fr(15, 17))
grid = [eps * Fr(k, 1000) for k in range(1, 3001)]
show("∀ε > 0 : max(|1 − εΔ|, |1 − εM|) ≥ 15/17 ,  = ⇔ ε = ε⋆",
     all(max(abs(1 - e * Gap), abs(1 - e * Top)) >= Fr(15, 17) for e in grid)
     and [e for e in grid if max(abs(1 - e * Gap), abs(1 - e * Top)) == Fr(15, 17)] == [eps])
Gh = np.eye(D) - (U * (Eh * Gap / 99144)) @ U.T
show("‖Γⁿ − P‖ = (15/17)ⁿ ,  Γⁿ → P",
     all(abs(np.linalg.norm(np.linalg.matrix_power(Gh, n) - Ph, 2) - (15 / 17) ** n) < 1e-12 for n in range(1, 9)), FLOAT)

# §11 ────────────────────────────────────────────────────────────────────────
head("§11  Thermal")
print("  Z(β) = Tr e^{−βH} = 47 + 28e^{−11664gβ} + 9e^{−12544gβ}")
print("                    + 27e^{−19600gβ} + e^{−32400gβ} + 13e^{−186624gβ}")
deg = {E[l]: 0 for l in Lam}
for l in Lam:
    deg[E[l]] += int(mult[Lam.index(l)])
show("Z(0) = 125 ,  p₀(β) = 47/Z(β) ,  p₀(0) = 47/125 = Ω_c",
     sum(deg.values()) == 125 and deg[0] == 47 and Fr(deg[0], 125) == Fr(47, 125))


def Zb(b):
    return sum(d * np.exp(-b * e) for e, d in deg.items())


bs = np.linspace(0, 2e-3, 400)
p0 = [47 / Zb(b) for b in bs]
bmax = 2e-3
Ebar = sum(d * e * np.exp(-bmax * e) for e, d in deg.items()) / Zb(bmax)
S_inf = np.log(Zb(bmax)) + bmax * Ebar
F_b = -np.log(Zb(bmax)) / bmax
show("β → ∞ :  p₀(β) ↑ 1 ,  S(β) → ln 47 ,  F(β) + β⁻¹ln 47 → 0",
     all(np.diff(p0) >= 0) and p0[-1] > p0[0] and p0[-1] > 1 - 1e-8
     and abs(S_inf - log(47)) < 1e-7 and abs(F_b + log(47) / bmax) < 1e-6, FLOAT)
show("Pe^{−βH}P = P  ⇒  argmin_{ρ=PρP} F_β(ρ) = P/47 ,  F_β = −β⁻¹ln 47",
     same(polyC([6, 30, 6, 30], Np), 0 * I) and tr(Np) == 47 * DEN)

# §12 ────────────────────────────────────────────────────────────────────────
head("§12  Haar average")
show("𝔼ψψ† = 𝟙/125  ⇒  𝔼‖Pψ‖² = Tr P/125 = 47/125 = Ω_c", Fr(tr(Np), DEN * D) == Fr(47, 125))
show("lim_{t→∞} 𝔼‖e^{−tH}ψ‖² = 47/125", Fr(tr(Np), DEN * D) == Fr(47, 125))
show("𝔼⟨ψ|H|ψ⟩ = Tr H/125 = 3427200/125 = 137088/5 · g",
     tr(H) == 3427200 == sum(E[l] * mult[Lam.index(l)] for l in Lam) and Fr(tr(H), D) == Fr(137088, 5))
z = rng.standard_normal((40000, D)) + 1j * rng.standard_normal((40000, D))
z /= np.linalg.norm(z, axis=1, keepdims=True)
eta = np.sum(np.abs(z @ Ph) ** 2, axis=1)
se = np.sqrt(47 * 78 / (125**2 * 126 * len(eta)))
show("‖Pψ‖² ~ Beta(47, 78) :  mean ≈ 0.376 ± 4·SE", abs(eta.mean() - 47 / 125) < 4 * se, FLOAT)
print("\n  ∎")
