#!/usr/bin/env python3
"""Independent reconstruction of the E47 and AES spectral invariants.

Claude (Anthropic), 2026-11-30. Shares no code with validate.py, aes_spectrum.py or
verify_sbox_graph.py; it rebuilds both objects from their definitions.

E47  The real symmetric Casimir C = J² of V₂⊗V₂⊗V₂ in the uncoupled basis, held exactly
     over Q(√6) (no similarity transform), block-diagonal by total weight M.
AES  The S-box from GF(2⁸) log tables and the FIPS-197 bitwise affine map; the quadratic
     relation space derived as a GF(2) nullspace; the energy census of the listed
     relations computed as one matrix product over all 2¹⁶ states.

Usage:  python3 independent_validation.py PATH/TO/aes_sbox_mq.txt [--json results.json]
Needs numpy (AES part only). Exit status 0 means every check passed.
"""
import json
import math
import sys
from collections import Counter
from fractions import Fraction as Fr
from itertools import combinations, product

CHECKS = []


def check(label, ok):
    CHECKS.append((label, bool(ok)))
    print(f"  {'✓' if ok else '✗'} {label}")
    return ok


# ───────────────────────────── exact arithmetic in Q(√6) ─────────────────────────────
class Q6:
    """a + b·√6 with rational a, b. √6 is irrational, so a² − 6b² ≠ 0 unless a = b = 0."""
    __slots__ = ("a", "b")

    def __init__(self, a=0, b=0):
        self.a, self.b = Fr(a), Fr(b)

    @staticmethod
    def of(x):
        return x if isinstance(x, Q6) else Q6(x)

    def __add__(self, o):
        o = Q6.of(o); return Q6(self.a + o.a, self.b + o.b)
    __radd__ = __add__

    def __sub__(self, o):
        o = Q6.of(o); return Q6(self.a - o.a, self.b - o.b)

    def __rsub__(self, o):
        return Q6.of(o) - self

    def __mul__(self, o):
        o = Q6.of(o); return Q6(self.a * o.a + 6 * self.b * o.b, self.a * o.b + self.b * o.a)
    __rmul__ = __mul__

    def __truediv__(self, o):
        o = Q6.of(o); n = o.a * o.a - 6 * o.b * o.b
        return self * Q6(o.a / n, -o.b / n)

    def __eq__(self, o):
        o = Q6.of(o); return self.a == o.a and self.b == o.b

    def zero(self):
        return self.a == 0 and self.b == 0


def mat_mul(A, B):
    n, k, m = len(A), len(B), len(B[0])
    return [[sum((A[i][t] * B[t][j] for t in range(k) if not A[i][t].zero()), Q6()) for j in range(m)] for i in range(n)]


def mat_sub_scalar(A, s):
    return [[A[i][j] - (s if i == j else 0) for j in range(len(A))] for i in range(len(A))]


def rank(A):
    A = [row[:] for row in A]; r = 0
    for c in range(len(A[0]) if A else 0):
        p = next((i for i in range(r, len(A)) if not A[i][c].zero()), None)
        if p is None:
            continue
        A[r], A[p] = A[p], A[r]
        for i in range(len(A)):
            if i != r and not A[i][c].zero():
                f = A[i][c] / A[r][c]
                A[i] = [A[i][j] - f * A[r][j] for j in range(len(A[0]))]
        r += 1
    return r


def is_zero(A):
    return all(x.zero() for row in A for x in row)


# ─────────────────────────────────────── E47 ───────────────────────────────────────
def e47():
    print("E₄₇ · three spin-2 particles, real symmetric Casimir, exact over Q(√6)")
    j, ms = 2, (2, 1, 0, -1, -2)
    root = {0: Q6(0), 4: Q6(2), 6: Q6(0, 1)}              # √(j(j+1) − m(m±1)) for j = 2
    up = {m: root[j * (j + 1) - m * (m + 1)] for m in ms}   # J₊|m⟩ = up[m]·|m+1⟩
    states = list(product(ms, repeat=3))

    def raise_op(s):  # J₊ on the product state s, as {state: coefficient}
        out = {}
        for a in range(3):
            if s[a] < j:
                t = s[:a] + (s[a] + 1,) + s[a + 1:]
                out[t] = out.get(t, Q6()) + up[s[a]]
        return out

    def lower_op(s):  # J₋ = J₊ᵀ (real matrix elements)
        out = {}
        for a in range(3):
            if s[a] > -j:
                t = s[:a] + (s[a] - 1,) + s[a + 1:]
                out[t] = out.get(t, Q6()) + up[s[a] - 1]
        return out

    def apply(op, vec):
        out = {}
        for s, c in vec.items():
            for t, d in op(s).items():
                out[t] = out.get(t, Q6()) + c * d
        return out

    C = {}
    for s in states:  # C = J_z² + ½(J₊J₋ + J₋J₊)
        col = {s: Q6(sum(s) ** 2)}
        for t, c in apply(raise_op, apply(lower_op, {s: Q6(1)})).items():
            col[t] = col.get(t, Q6()) + c * Fr(1, 2)
        for t, c in apply(lower_op, apply(raise_op, {s: Q6(1)})).items():
            col[t] = col.get(t, Q6()) + c * Fr(1, 2)
        C[s] = col

    symmetric = all(C[s].get(t, Q6()) == C[t].get(s, Q6()) for s in states for t in C[s])
    check("C is real symmetric in the uncoupled basis (Hermitian, no similarity transform)", symmetric)
    blocks_ok = all(sum(t) == sum(s) for s in states for t in C[s] if not C[s][t].zero())
    check("C commutes with total J_z: block-diagonal in M = m₁+m₂+m₃", blocks_ok)

    trC = sum((C[s].get(s, Q6()) for s in states), Q6())
    trC2 = sum((C[s][t] * C[t][s] for s in states for t in C[s]), Q6())
    mu = trC / 125
    var = trC2 / 125 - mu * mu
    check(f"μ = tr C / 125 = {mu.a}", mu == 18)
    check(f"σ² = tr C² / 125 − μ² = {var.a}", var == 144)
    sigma = Q6(12)
    lo, hi = mu - sigma, mu + sigma
    check(f"selector roots μ ∓ σ = {lo.a}, {hi.a}", lo == 6 and hi == 30)

    # weight census: copies of each total spin J
    count = Counter(sum(s) for s in states)
    copies = {J: count[J] - count[J + 1] for J in range(0, 7)}
    check(f"weight census, copies of J = 0..6: {tuple(copies.values())}", tuple(copies.values()) == (1, 3, 5, 4, 3, 2, 1))

    lam = {J: J * (J + 1) for J in range(7)}
    mult_total = Counter()
    trP = 0; rankP = 0; P_ok = True; min_ok = True
    for M in range(-6, 7):
        bs = [s for s in states if sum(s) == M]
        CM = [[C[t].get(s, Q6()) for t in bs] for s in bs]
        eig = [lam[J] for J in range(abs(M), 7)]
        prod_ = None
        for L in eig:                                       # minimal polynomial on the block
            D = mat_sub_scalar(CM, L)
            prod_ = D if prod_ is None else mat_mul(prod_, D)
            mult_total[L] += len(bs) - rank(D)
        min_ok &= is_zero(prod_)
        P = [[Q6() for _ in bs] for _ in bs]
        for L in (6, 30):                                   # Lagrange projectors onto the selected sectors
            if L not in eig:
                continue
            T = [[Q6(1 if i == k else 0) for k in range(len(bs))] for i in range(len(bs))]
            for L2 in eig:
                if L2 != L:
                    T = mat_mul(T, [[x / (L - L2) for x in row] for row in mat_sub_scalar(CM, L2)])
            P = [[P[i][k] + T[i][k] for k in range(len(bs))] for i in range(len(bs))]
        KM = mat_mul(mat_sub_scalar(CM, 6), mat_sub_scalar(CM, 30))
        PP = mat_mul(P, P)
        P_ok &= all(PP[i][k] == P[i][k] for i in range(len(bs)) for k in range(len(bs)))
        P_ok &= is_zero(mat_mul(KM, P))
        P_ok &= all(P[i][k] == P[k][i] for i in range(len(bs)) for k in range(len(bs)))
        trP += sum((P[i][i] for i in range(len(bs))), Q6()).a
        rankP += rank(P)
    check("on every M-block, ∏(C − J(J+1)) = 0 exactly: C is diagonalizable with spectrum {0,2,6,12,20,30,42}", min_ok)
    dims = tuple(mult_total[lam[J]] for J in range(7))
    check(f"eigenvalue multiplicities (exact ranks): {dims}", dims == (1, 9, 25, 28, 27, 22, 13))
    check("P = P₆ + P₃₀ satisfies P² = P, KP = 0 and Pᵀ = P exactly (an orthogonal projector)", P_ok)
    check(f"protected dimension: tr P = rank P = {trP}", trP == 47 and rankP == 47)

    Qv = {lam[J]: ((lam[J] - 6) * (lam[J] - 30)) ** 2 for J in range(7)}
    nonzero = sorted({q for q in Qv.values() if q})
    gap, top = nonzero[0], nonzero[-1]
    check(f"Q = K²: gap Δ = {gap} = 108², top Λ = {top} = 432²", gap == 11664 == 108 ** 2 and top == 186624 == 432 ** 2)
    eta = Fr(gap, 2)
    check(f"η = Δ/2 = {eta};  tr[P(Q − η)] = −47η = {-47 * eta}", eta == 5832 and -47 * eta == -274104)
    # sharpness of ℱ(P) − ℱ(P⋆) ≥ η‖P − P⋆‖²: swap one ground direction for one Δ direction
    check("η is sharp: dropping a ground direction costs η, adding a Δ direction costs Δ − η = η, per unit ‖P − P⋆‖²",
          gap - eta == eta)
    kappa = Fr(top, gap)
    eps = Fr(2, top + gap)
    rho = max(abs(1 - eps * q) for q in nonzero)
    check(f"κ = {kappa},  ε⋆ = 2/(Λ+Δ) = {eps},  ρ⋆ = max|1 − ε⋆q| = {rho}", kappa == 16 and eps == Fr(1, 99144) and rho == Fr(15, 17))
    worse = all(max(abs(1 - e * q) for q in nonzero) > rho for e in (eps * Fr(99, 100), eps * Fr(101, 100)))
    check("any other step size does worse (ε⋆ ± 1% both exceed 15/17)", worse)
    check(f"exact projector is a polynomial of degree {len(nonzero)} in Q (one factor per nonzero level)", len(nonzero) == 5)
    check("𝔼‖Pψ‖² over random unit states = tr P / 125 = 47/125 = Ω_c", Fr(trP, 125) == Fr(47, 125))
    return dict(n=125, mu=18, var=144, sigma=12, roots=[6, 30], copies=list(copies.values()),
                spectrum_C=[[lam[J], mult_total[lam[J]]] for J in range(7)],
                spectrum_Q=[[Qv[lam[J]], mult_total[lam[J]]] for J in range(7)],
                dim=trP, gap=gap, top=top, eta=eta, kappa=kappa, eps=eps, rho=rho, levels=len(nonzero),
                omega_c=Fr(trP, 125))


# ─────────────────────────────────────── AES ───────────────────────────────────────
def gf2_rank_and_rows(rows, nbits):
    """Row-reduce bitmask rows over GF(2); return (rank, reduced rows)."""
    basis = []
    for r in rows:
        for b in basis:
            r = min(r, r ^ b)
        if r:
            basis.append(r)
    return len(basis), basis


def gf2_rref(rows, order):
    """Reduced row echelon form with pivots chosen along the column order given."""
    rows = list(rows); out = []
    for c in order:
        p = next((r for r in rows if r >> c & 1), None)
        if p is None:
            continue
        rows.remove(p)
        rows = [r ^ p if r >> c & 1 else r for r in rows]
        out = [r ^ p if r >> c & 1 else r for r in out]
        out.append(p)
    return out


def aes(mq_path):
    import numpy as np
    print("AES · S-box graph, quadratic relations over GF(2), energy census over all 2¹⁶ pairs")
    exp, x = [0] * 255, 1
    for i in range(255):                                   # generator 3 of GF(2⁸)*, modulus 0x11B
        exp[i] = x
        x ^= ((x << 1) ^ (0x1B if x & 0x80 else 0)) & 0xFF   # x ← 3·x = x ⊕ xtime(x)
    log = {v: i for i, v in enumerate(exp)}
    inv = [0] + [exp[(255 - log[a]) % 255] for a in range(1, 256)]
    c = 0x63
    S = []
    for a in range(256):                                   # FIPS-197 §5.1.1 bitwise affine map
        b = inv[a]
        S.append(sum((((b >> i) ^ (b >> ((i + 4) % 8)) ^ (b >> ((i + 5) % 8)) ^ (b >> ((i + 6) % 8))
                       ^ (b >> ((i + 7) % 8)) ^ (c >> i)) & 1) << i for i in range(8)))
    fips = {0x00: 0x63, 0x01: 0x7C, 0x53: 0xED, 0x9A: 0xB8, 0xFF: 0x16}
    check("S-box from log tables + FIPS-197 affine map; FIPS-197 spot values and bijectivity",
          all(S[k] == v for k, v in fips.items()) and sorted(S) == list(range(256)))

    var = [("x", i) for i in range(8)] + [("y", i) for i in range(8)]
    mons = [()] + [(i,) for i in range(16)] + list(combinations(range(16), 2))   # 137 monomials
    idx = {m: k for k, m in enumerate(mons)}
    z = np.arange(1 << 16, dtype=np.uint32)
    B = ((z[:, None] >> np.arange(16, dtype=np.uint32)) & 1).astype(np.uint8)
    Mz = np.ones((1 << 16, len(mons)), dtype=np.uint8)
    for k, m in enumerate(mons):
        for i in m:
            Mz[:, k] &= B[:, i]
    graph = np.array([a | (S[a] << 8) for a in range(256)], dtype=np.uint32)
    G = Mz[graph]

    def nullity(cols):
        rows = [int("".join(str(int(G[r, k])) for k in reversed(cols)), 2) for r in range(256)]
        r, _ = gf2_rank_and_rows(rows, len(cols))
        return len(cols) - r
    biaffine = [idx[m] for m in mons if len(m) < 2 or (m[0] < 8 <= m[1])]
    n_all, n_bi = nullity(list(range(len(mons)))), nullity(biaffine)
    check(f"quadratic relations vanishing on the graph: dimension {n_all} (of 137 monomials); bi-affine: {n_bi}",
          n_all == 39 and n_bi == 23)

    name = {f"{v}{i}": k for k, (v, i) in enumerate(var)}
    R = []
    for line in open(mq_path).read().splitlines():
        coeffs = 0
        for t in line.split("=")[0].split("+"):
            t = t.strip()
            m = () if t == "1" else tuple(sorted(name[u] for u in t.split("*")))
            coeffs ^= 1 << idx[m]
        R.append(coeffs)
    Rm = np.array([[r >> k & 1 for k in range(len(mons))] for r in R], dtype=np.float64)
    on_graph = (G.astype(np.float64) @ Rm.T) % 2
    r_listed, _ = gf2_rank_and_rows(R, len(mons))
    check(f"the {len(R)} listed relations vanish on the graph and are independent (rank {r_listed}): a basis of that space",
          len(R) == 39 and not on_graph.any() and r_listed == 39)

    V = (Mz.astype(np.float64) @ Rm.T) % 2                  # 65 536 × 39 violation table
    E = V.sum(axis=1).astype(int)
    zero = np.flatnonzero(E == 0)
    check("zero set over all 2¹⁶ pairs is exactly the 256-point graph {(x, S(x))} (basis-free)",
          np.array_equal(np.sort(zero), np.sort(graph)))

    census = sorted(Counter(E.tolist()).items())
    nz = [e for e, _ in census if e]
    gap, top = nz[0], nz[-1]
    eps, rho = Fr(2, gap + top), Fr(top - gap, top + gap)
    print(f"    census of the listed basis: {census}")
    check(f"listed basis: Δ = {gap}, λmax = {top}, ε⋆ = {eps}, ρ⋆ = {rho}, exact-projector degree {len(nz)}",
          (gap, top, eps, rho, len(nz)) == (7, 34, Fr(2, 41), Fr(27, 41), 28))

    def census_of(rows):
        Rb = np.array([[r >> k & 1 for k in range(len(mons))] for r in rows], dtype=np.float64)
        Eb = ((Mz.astype(np.float64) @ Rb.T) % 2).sum(axis=1).astype(int)
        nzb = sorted(set(Eb.tolist()) - {0})
        return nzb[0], nzb[-1], int((Eb == 0).sum())

    alt = {}
    alt["RREF, pivots low-degree first"] = census_of(gf2_rref(R, range(len(mons))))
    alt["RREF, pivots high-degree first"] = census_of(gf2_rref(R, reversed(range(len(mons)))))
    import random
    rng = random.Random(41)
    for t in range(4):
        while True:                                          # random invertible change of basis
            Mx = [rng.getrandbits(39) for _ in range(39)]
            if gf2_rank_and_rows(Mx, 39)[0] == 39:
                break
        rows = []
        for mrow in Mx:
            acc = 0
            for k in range(39):
                if mrow >> k & 1:
                    acc ^= R[k]
            rows.append(acc)
        alt[f"random basis {t + 1}"] = census_of(rows)
    alt_record = {k: dict(gap=g, top=L, rho=str(Fr(L - g, L + g)), zero_set=z0) for k, (g, L, z0) in alt.items()}
    for k, (g, L, z0) in alt.items():
        print(f"    {k:32s} Δ = {g:2d}  λmax = {L:2d}  ρ⋆ = {Fr(L - g, L + g)}  zero set {z0}")
    moves = len({(g, L) for g, L, _ in alt.values()} | {(gap, top)}) > 1
    check("Δ and λmax move with the choice of basis, while the 256-point zero set does not", moves and all(z0 == 256 for *_, z0 in alt.values()))
    check("every off-graph pair violates some relation, hence exactly 2³⁸ of the 2³⁹ in the space: spectrum {0, 2³⁸}",
          int((E > 0).sum()) == (1 << 16) - 256)
    off = [(e, k) for e, k in census if e]
    N = sum(k for _, k in off)
    mean = sum(e * k for e, k in off) / N
    var_ = sum((e - mean) ** 2 * k for e, k in off) / N
    tv = 0.5 * sum(abs(dict(off).get(e, 0) / N - math.comb(39, e) / 2 ** 39) for e in range(1, 40))
    return dict(n=1 << 16, dim=256, relations=39, relation_space_dim=n_all, biaffine_dim=n_bi,
                census=census, gap=gap, top=top, eps=eps, rho=rho, levels=len(nz), kappa=Fr(top, gap),
                listed_basis="reduced echelon form, quadratic monomials pivoted first (verified by set equality)"
                if set(R) == set(gf2_rref(R, reversed(range(len(mons))))) else "not an echelon basis",
                alternatives=alt_record,
                off_graph=dict(states=N, mean=round(mean, 4), variance=round(var_, 4),
                               binomial_mean=19.5, binomial_variance=9.75, total_variation=round(tv, 4)))


if __name__ == "__main__":
    a = e47()
    print()
    b = aes(sys.argv[1])
    print()
    print("The contraction law, one theorem for both:  min_ε max_{γ≤λ≤Λ} |1 − ελ| = (Λ − γ)/(Λ + γ) at ε = 2/(Λ + γ)")
    for nm, d in (("E₄₇", a), ("AES", b)):
        k = float(d["kappa"])
        cheb = (math.sqrt(k) - 1) / (math.sqrt(k) + 1)
        print(f"    {nm:4s} κ = {str(d['kappa']):6s} ρ⋆ = {str(d['rho']):6s} = {float(d['rho']):.6f}   "
              f"Chebyshev rate (√κ−1)/(√κ+1) = {cheb:.6f}   exact projector degree {d['levels']}")
    passed = sum(ok for _, ok in CHECKS)
    print(f"\n{passed}/{len(CHECKS)} checks passed")
    if "--json" in sys.argv:
        def plain(v):
            if isinstance(v, Fr):
                return str(v) if v.denominator != 1 else v.numerator
            if isinstance(v, dict):
                return {k: plain(x) for k, x in v.items()}
            if isinstance(v, (list, tuple)):
                return [plain(x) for x in v]
            return v
        for d in (a, b):
            k = float(d["kappa"])
            d["chebyshev_rate"] = round((math.sqrt(k) - 1) / (math.sqrt(k) + 1), 9)
        record = dict(schema="e47-aes-independent-validation/1", model="Claude Opus 5.5 (Anthropic)", date="2026-11-30",
                      checks=[dict(label=l, passed=ok) for l, ok in CHECKS], passed=passed, total=len(CHECKS),
                      e47=plain(a), aes=plain(b))
        path = sys.argv[sys.argv.index("--json") + 1]
        with open(path, "w") as fh:
            json.dump(record, fh, ensure_ascii=False, indent=1)
            fh.write("\n")
        print("wrote", path)
    sys.exit(0 if passed == len(CHECKS) else 1)
