#!/usr/bin/env python3
"""niemeier_morse_atlas.py — single-file exact verification of the 24-shell Morse atlas.

The independent checks include 13 A_n indices (including all A24 spectral
factors), all 10 D_n indices via 42/45-dimensional signed-permutation fixed
spaces and exact trace moments, E6/E7 whole-tangent annihilators and nullity,
all 21 coupled centroid blocks built *from the Hessian*, root-line transverse
spectra, 24-cross-polytope spectrum, all 24 inertia rows, and six sharp-design
Riesz and infinite Gaussian polynomial certificates (including k >= 512 tails).

The proof uses established root-system/Weyl symmetry facts and the analytic
polynomial-hook spectral-gap theorem proved in the accompanying manuscript.
No floating-point spectral calculation is used. All signs are exact.

Run: OPENBLAS_NUM_THREADS=1 python3 niemeier_morse_atlas.py
Selective: python3 niemeier_morse_atlas.py --only dn
Requires Python 3.10+, NumPy, SymPy; do not run with python -O.
"""
from __future__ import annotations
import argparse
import itertools
import math
import sys
import time
from collections import Counter
from fractions import Fraction
from fractions import Fraction as F
import numpy as np
import sympy as S

# Integer tables: 3456*f'(s) and 3456*f''(s), f(s)=s^-2, s=1,2,3,4.
FP = {s: -2 * 3456 // s**3 for s in range(1,5)}
FPP = {s: 6 * 3456 // s**4 for s in range(1,5)}
SCALE = 4 * 3456


def verify(condition, message):
    if not condition:
        raise ArithmeticError(message)


def exact_inertia(M):
    """Returns exact (n_pos, n_neg, n_zero) of a symmetric SymPy Matrix M
    using exact rational 1x1 and 2x2 Schur-complement congruence pivots.
    """
    mat = S.Matrix(M)
    pos = neg = zero = 0
    while mat.rows:
        t = mat.rows
        diag_idx = next((i for i in range(t) if mat[i, i] != 0), None)
        if diag_idx is not None:
            if diag_idx:
                mat.row_swap(0, diag_idx)
                mat.col_swap(0, diag_idx)
            p = mat[0, 0]
            if p > 0:
                pos += 1
            else:
                neg += 1
            if t == 1:
                break
            v = mat[1:, 0]
            mat = mat[1:, 1:] - v * v.T / p
        else:
            edge = next(
                ((i, j) for i in range(t) for j in range(i + 1, t) if mat[i, j] != 0),
                None,
            )
            if edge is None:
                zero += t
                break
            i, j = edge
            for dest, src in [(0, i), (1, j)]:
                if dest != src:
                    mat.row_swap(dest, src)
                    mat.col_swap(dest, src)
                    if dest == 0 and j == 0:
                        j = src
            B = mat[:2, :2]
            v = mat[2:, :2]
            mat = mat[2:, 2:] - v * B.inv() * v.T
            pos += 1
            neg += 1
    return pos, neg, zero


def hookdim(part):
    numer = S.factorial(sum(part))
    den = S.Integer(1)
    for i, row in enumerate(part):
        for j in range(row):
            below = sum(1 for k in range(i + 1, len(part)) if part[k] > j)
            den *= row - j + below
    return int(numer / den)


def certify_sharp_designs():
    print("=" * 76)
    print("[1/8] CERTIFYING SIX ANTIPODAL SHARP-DESIGN RIESZ SPECTRAL GAPS (SEC. 8)")
    print("=" * 76)
    s, z = S.symbols("s z")

    def prod_seq(seq):
        out = S.Integer(1)
        for item in seq:
            out *= item
        return out

    cases = [
        ("Icosahedron", 3, 12, [2 - 2 / S.sqrt(5), 2 + 2 / S.sqrt(5), S.Rational(4)], S.Rational(19, 2), 5),
        ("Gosset 56", 7, 56, [S.Rational(4, 3), S.Rational(8, 3), S.Rational(4)], S.Rational(247, 32), 105),
        ("E8 roots", 8, 240, [S.Rational(1), S.Rational(2), S.Rational(3), S.Rational(4)], S.Rational(145, 8), 160),
        ("552-point shell", 23, 552, [S.Rational(8, 5), S.Rational(12, 5), S.Rational(4)], S.Rational(637, 96), 4025),
        ("4600-point shell", 23, 4600, [S.Rational(4, 3), S.Rational(2), S.Rational(8, 3), S.Rational(4)], S.Rational(455, 32), 4025),
        ("Leech minimal shell", 24, 196560, [S.Rational(1), S.Rational(3, 2), S.Rational(2), S.Rational(5, 2), S.Rational(3), S.Rational(4)], S.Rational(73073, 1800), 4576),
    ]

    for name, d, N, levels, exp_gap, exp_mult in cases:
        active = [a for a in levels if a != 4]
        m = len(levels)
        t = 2 * m - 2
        p4 = S.simplify(prod_seq((4 - a) ** 2 for a in active))
        u = {a: S.simplify(-S.Rational(2) / a ** 3) for a in levels}
        v = {a: S.simplify(S.Rational(6) / a ** 4) for a in active}
        w = {a: S.simplify(1 / ((4 - a) * prod_seq((a - b) ** 2 for b in active if b != a))) for a in active}
        L = {a: S.simplify(S.Rational(1, 2) / (a - 4) + sum((1 / (a - b) for b in active if b != a), S.Rational(0))) for a in active}

        kappa = S.simplify(
            (sum((w[a] * (v[a] - 2 * L[a] * u[a]) for a in active), S.Rational(0)) - u[S.Rational(4)] / p4)
            / sum(w.values())
        )
        pA = prod_seq((s - a) ** 2 for a in active)
        q = u[S.Rational(4)] * pA / p4
        for a in active:
            ell = prod_seq((s - b) / (a - b) for b in active if b != a)
            basis = (s - 4) / (a - 4) * ell ** 2
            q += (u[a] * (1 - 2 * L[a] * (s - a)) + (v[a] - kappa) * (s - a)) * basis
        q = S.Poly(S.simplify(q), s)
        assert q.degree() <= t - 1
        assert all(S.simplify(q.eval(a) - u[a]) == 0 for a in levels)
        qp = q.diff()
        assert all(S.simplify(qp.eval(a) - (v[a] - kappa)) == 0 for a in active)

        H = S.Poly(S.integrate(q.as_expr(), s).subs(s, 2 - 2 * z), z)
        alpha = S.Rational(d - 2, 2)
        Q = [S.gegenbauer(j, alpha, z) / S.gegenbauer(j, alpha, 1) for j in range(1, t + 1)]
        coeffs = S.symbols("c1:" + str(t + 1))
        residual = S.Poly(H.as_expr() - sum(coeffs[j] * Q[j] for j in range(t)), z)
        M_mat, rhs = S.linear_eq_to_matrix([residual.nth(j) for j in range(1, t + 1)], coeffs)
        values = [S.simplify(val) for val in list(M_mat.inv() * rhs)]
        assert all(val.is_rational and val > 0 for val in values)

        gap = S.simplify(S.Rational(4 * N, d) * kappa)
        mult = d * (d * d - 4) // 3
        assert gap == exp_gap and mult == exp_mult
        print(f"  [PASS] {name:20s} (d={d:2d}, N={N:6d}): kappa={str(kappa):12s} => gap={str(gap):10s}, mult>={mult}")


def certify_a3_counterexample():
    print("\n" + "=" * 76)
    print("[2/8] CERTIFYING A_3 ZERO-CENTROID COUNTEREXAMPLE (SEC. 16, EX. 16.1)")
    print("=" * 76)
    m = 4
    pairs = [(a, b) for a in range(m) for b in range(m) if a != b]
    N = len(pairs)
    V = S.Matrix([[1 if c == a else (-1 if c == b else 0) for c in range(m)] for a, b in pairs])
    U = S.zeros(N, m)
    v_vec = S.Matrix([[1, 1, 1, -3]])
    U[pairs.index((0, 1)), :] = v_vec
    U[pairs.index((0, 2)), :] = -v_vec

    # Verify tangency and zero centroid
    for i in range(N):
        assert (V.row(i) * U.row(i).T)[0] == 0
    assert sum((U.row(i) for i in range(N)), S.zeros(1, m)) == S.zeros(1, m)

    fp = {1: S.Rational(-2), 2: S.Rational(-1, 4), 3: S.Rational(-2, 27), 4: S.Rational(-1, 32)}
    fpp = {1: S.Rational(6), 2: S.Rational(3, 8), 3: S.Rational(2, 27), 4: S.Rational(3, 128)}

    HU = S.zeros(N, m)
    for i in range(N):
        xi = V.row(i) / S.sqrt(2)
        ui = U.row(i)
        acc = S.zeros(1, m)
        for j in range(N):
            if i == j:
                continue
            xj = V.row(j) / S.sqrt(2)
            uj = U.row(j)
            cij = (xi * xj.T)[0]
            sij = int(2 - 2 * cij)
            dij = (ui * xj.T + xi * uj.T)[0]
            term1 = 4 * fpp[sij] * dij * (xj - cij * xi)
            term2 = 2 * fp[sij] * cij * ui
            term3 = -2 * fp[sij] * (uj - (uj * xi.T)[0] * xi)
            acc += term1 + term2 + term3
        HU[i, :] = S.simplify(acc)

    centroid_HU = S.simplify(sum((HU.row(i) for i in range(N)), S.zeros(1, m)))
    expected = S.Matrix([[0, S.Rational(340, 27), S.Rational(-340, 27), 0]])
    assert centroid_HU == expected
    print(f"  [PASS] Zero-centroid A_3 input produces non-zero Hessian centroid: {list(centroid_HU)}")


def certify_an_family_and_a24():
    print("\n" + "=" * 76)
    print("[3/8] CERTIFYING FULL A_24 SPECTRUM (34-DIM) & ALL A_n INDICES (SECS. 4-7, 17.2)")
    print("=" * 76)
    an_indices = {}

    # 3A. Small ranks n = 2, 3, 4 via exact rational tangent Gram congruence
    for n in (2, 3, 4):
        m = n + 1
        pairs = [(a, b) for a in range(m) for b in range(m) if a != b]
        N = len(pairs)
        V = np.zeros((N, m), dtype=np.int64)
        for k, (a, b) in enumerate(pairs):
            V[k, a] = 1
            V[k, b] = -1
        # Build exact rational tangent basis in 1^\perp and x_i^\perp
        rows_c = []
        for k, (a, b) in enumerate(pairs):
            r1 = np.zeros(N * m, dtype=int)
            r1[k * m + a] = 1
            r1[k * m + b] = -1
            rows_c.append(r1)
            r2 = np.zeros(N * m, dtype=int)
            r2[k * m:(k + 1) * m] = 1
            rows_c.append(r2)
        B_cols = S.Matrix(np.array(rows_c, dtype=int)).nullspace()
        B_mat = S.Matrix.hstack(*B_cols)
        for j in range(B_mat.cols):
            col = B_mat[:, j]
            B_mat[:, j] = col * S.ilcm(*[z.q for z in col])
        BI = np.array(B_mat.tolist(), dtype=np.int64)
        G_v = V @ V.T
        D_v = 2 - G_v
        mask = ~np.eye(N, dtype=bool)
        L = 3456
        fp_t = {1: -2 * L, 2: -L // 4, 3: -2 * L // 27, 4: -L // 32}
        fpp_t = {1: 6 * L, 2: 3 * L // 8, 3: 2 * L // 27, 4: 3 * L // 128}
        FP = np.zeros_like(D_v, dtype=np.int64)
        Q = np.zeros_like(D_v, dtype=np.int64)
        for s in (1, 2, 3, 4):
            FP[(D_v == s) & mask] = fp_t[s]
            Q[(D_v == s) & mask] = fpp_t[s]
        HB = np.zeros_like(BI)
        for j in range(BI.shape[1]):
            W = BI[:, j].reshape(N, m)
            J = W @ V.T + V @ W.T
            R = (Q * J) @ V
            rd = (V * R).sum(axis=1)
            CW = (FP * G_v).sum(axis=1)
            F = FP @ W
            fd = (V * F).sum(axis=1)
            H_out = 8 * R - 4 * V * rd[:, None] + 4 * CW[:, None] * W - 8 * F + 4 * V * fd[:, None]
            HB[:, j] = H_out.reshape(-1)
        K_small = S.Matrix((BI.T @ HB).tolist())
        npos, nneg, nzero = exact_inertia(K_small)
        assert nzero == n * (n - 1) // 2
        an_indices[n] = nneg
        print(f"  [PASS] A_{n:2d} (direct rational congruence, dim={BI.shape[1]:2d}): inertia=({nneg} neg, {nzero} zero, {npos} pos)")

    # 3B. Ranks n >= 5 via the universal 34-dimensional S_{n-2}-fixed reduction
    fixed = 3
    for n in (5, 6, 7, 8, 9, 11, 12, 15, 17, 24):
        m = n + 1
        pairs = [(i, j) for i in range(m) for j in range(m) if j != i]
        N = len(pairs)
        V = np.zeros((N, m), dtype=np.int64)
        for k, (i, j) in enumerate(pairs):
            V[k, i] = 1
            V[k, j] = -1

        def canon(triple):
            codes = {}
            nxt = fixed
            out = []
            for x in triple:
                if x < fixed:
                    out.append(x)
                else:
                    if x not in codes:
                        codes[x] = nxt
                        nxt += 1
                    out.append(codes[x])
            return tuple(out)

        orb = []
        dct = {}
        reps = []
        sizes = []
        for k, (a, b_idx) in enumerate(pairs):
            for c in range(m):
                rep = canon((a, b_idx, c))
                oid = dct.get(rep)
                if oid is None:
                    oid = len(reps)
                    dct[rep] = oid
                    reps.append((a, b_idx, c))
                    sizes.append(0)
                sizes[oid] += 1
                orb.append(oid)
        orb = np.array(orb, dtype=np.int32)
        O = len(reps)
        assert O == 60

        rows = []
        seen = set()
        for a, b_idx in pairs:
            rep = canon((a, b_idx))
            if rep in seen:
                continue
            seen.add(rep)
            p_idx = pairs.index((a, b_idx))
            row = np.zeros(O, dtype=int)
            row[orb[p_idx * m + a]] += 1
            row[orb[p_idx * m + b_idx]] -= 1
            rows.append(row)
            row = np.bincount(orb[p_idx * m:(p_idx + 1) * m], minlength=O)
            rows.append(row)
        A = S.Matrix(np.array(rows, dtype=int))
        Zcols = A.nullspace()
        b = len(Zcols)
        assert b == 34
        Z = S.Matrix.hstack(*Zcols)
        for j in range(Z.cols):
            col = Z[:, j]
            Z[:, j] = col * S.ilcm(*[z.q for z in col])
        ZI = np.array(Z.tolist(), dtype=np.int64)

        G = V @ V.T
        D = 2 - G
        mask = ~np.eye(N, dtype=bool)
        L = 3456
        fp_t = {1: -2 * L, 2: -L // 4, 3: -2 * L // 27, 4: -L // 32}
        fpp_t = {1: 6 * L, 2: 3 * L // 8, 3: 2 * L // 27, 4: 3 * L // 128}
        FP = np.zeros_like(D, dtype=np.int64)
        Q = np.zeros_like(D, dtype=np.int64)
        for s in (1, 2, 3, 4):
            FP[(D == s) & mask] = fp_t[s]
            Q[(D == s) & mask] = fpp_t[s]

        # Fast exact integer evaluation on the 13 unique representative roots
        rep_k = [pairs.index((a, c)) for a, c, _ in reps]
        rep_c = [d_c for _, _, d_c in reps]
        u_roots = sorted(list(set(rep_k)))
        root_map = {rk: idx_u for idx_u, rk in enumerate(u_roots)}
        mapped_k = [root_map[rk] for rk in rep_k]

        V_u = V[u_roots]
        Q_u = Q[u_roots]
        FP_u = FP[u_roots]
        CW_u = (FP_u * G[u_roots]).sum(axis=1)

        HZ = np.zeros((O, b), dtype=np.int64)
        for j in range(b):
            W = ZI[orb, j].reshape(N, m)
            W_u = W[u_roots]
            J_u = W_u @ V.T + V_u @ W.T
            R_u = (Q_u * J_u) @ V
            rd_u = (V_u * R_u).sum(axis=1)
            F_u = FP_u @ W
            fd_u = (V_u * F_u).sum(axis=1)
            H_u = 8 * R_u - 4 * V_u * rd_u[:, None] + 4 * CW_u[:, None] * W_u - 8 * F_u + 4 * V_u * fd_u[:, None]
            vals = H_u[mapped_k, rep_c]
            HZ[:, j] = vals
            if n == 24 and j == 0:
                # Full 600x25 orbit-invariance check on A_24
                J_full = W @ V.T + V @ W.T
                R_full = (Q * J_full) @ V
                rd_full = (V * R_full).sum(axis=1)
                CW_full = (FP * G).sum(axis=1)
                F_full = FP @ W
                fd_full = (V * F_full).sum(axis=1)
                H_full = 8 * R_full - 4 * V * rd_full[:, None] + 4 * CW_full[:, None] * W - 8 * F_full + 4 * V * fd_full[:, None]
                assert np.array_equal(H_full.reshape(-1), vals[orb])

        C_orb = np.zeros((O, O), dtype=np.int64)
        for r, abc in enumerate(reps):
            counts = Counter()
            for i in range(m):
                for j in range(i + 1, m):
                    out = tuple(j if x == i else i if x == j else x for x in abc)
                    counts[dct[canon(out)]] += 1
            for a, v in counts.items():
                C_orb[r, a] = v
        CZ = C_orb @ ZI

        idx = list((Z.T).rref()[1])
        Zinv = Z[idx, :].inv()
        CM = Zinv * S.Matrix(CZ[idx, :].tolist())
        Wdiag = S.diag(*[int(x) for x in sizes])
        Gred = Z.T * Wdiag * Z
        Kred = Z.T * Wdiag * S.Matrix(HZ.tolist())
        assert Kred == Kred.T and Gred * CM == CM.T * Gred and Kred * CM == CM.T * Kred

        parts = [(m,), (m - 1, 1), (m - 2, 2), (m - 2, 1, 1), (m - 3, 3), (m - 3, 2, 1), (m - 3, 1, 1, 1)]
        fixmult_map = {(m,): 1, (m - 1, 1): 3, (m - 2, 2): 3, (m - 2, 1, 1): 3,
                       (m - 3, 3): 1, (m - 3, 2, 1): 2, (m - 3, 1, 1, 1): 1}

        index_n = pos_n = null_n = 0
        spec_trace = S.Rational(0)
        T = S.symbols("lam")
        expected_a24 = {
            (25,): 216 * T - 124555,
            (24, 1): (27 * T - 11000) * (46656 * T * T - 36195120 * T + 7009585325),
            (23, 2): (27 * T - 2743) * (5184 * T * T - 1261680 * T + 36844925),
            (23, 1, 1): T * (27 * T - 5600) * (216 * T - 4415),
            (22, 3): 72 * T + 955,
            (22, 2, 1): (27 * T + 725) * (72 * T + 3515),
            (22, 1, 1, 1): 54 * T + 3175,
        }

        if n == 5:
            # Handle the n=5 (m=6) central eigenvalue collision between (4,1,1) and (3,3) (both omega = 6)
            for part in parts:
                if part == (3, 3):
                    continue
                lam = sum(int(row * (row - 2 * i + 1) // 2) for i, row in enumerate(part, 1))
                E = S.Matrix.hstack(*(CM - lam * S.eye(b)).nullspace())
                Kr = E.T * Kred * E
                npos, nneg, nzero = exact_inertia(Kr)
                if part == (4, 1, 1):
                    # Merged block [4,1,1] (dim 10, fixmult 3) + [3,3] (dim 5, fixmult 1)
                    assert (npos, nzero, nneg) == (7, 3, 0)
                    null_n += 10
                    pos_n += 2 * 10 + 1 * 5
                else:
                    fm = fixmult_map[part]
                    irrep_d = hookdim(part)
                    index_n += (nneg // fm) * irrep_d
                    pos_n += (npos // fm) * irrep_d
                    null_n += (nzero // fm) * irrep_d
        else:
            for part in parts:
                lam = sum(int(row * (row - 2 * i + 1) // 2) for i, row in enumerate(part, 1))
                E = S.Matrix.hstack(*(CM - lam * S.eye(b)).nullspace())
                Kr = E.T * Kred * E
                gr = E.T * Gred * E
                npos, nneg, nzero = exact_inertia(Kr)
                fm = fixmult_map[part]
                irrep_d = hookdim(part)
                index_n += (nneg // fm) * irrep_d
                pos_n += (npos // fm) * irrep_d
                null_n += (nzero // fm) * irrep_d
                if n == 24:
                    H_blk = gr.inv() * Kr / S.Integer(4 * L)
                    spec_trace += (H_blk.trace() / S.Integer(fm)) * irrep_d
                    char = S.factor(H_blk.charpoly(T).as_expr())
                    exp_c = S.Poly(expected_a24[part], T).monic().as_expr() ** fm
                    assert S.factor(char - exp_c) == 0

        assert null_n == n * (n - 1) // 2
        assert index_n + null_n + pos_n == N * (n - 1)
        an_indices[n] = index_n
        if n == 24:
            assert (index_n, null_n, pos_n) == (12074, 276, 1450)
            assert spec_trace == S.Rational(-4740875, 18)
            print(f"  [PASS] A_24 FULL SPECTRUM: inertia=(12074 neg, 276 zero, 1450 pos), trace={spec_trace}")
        else:
            print(f"  [PASS] A_{n:2d} (34-dim Specht reduction): inertia=({index_n:4d} neg, {null_n:3d} zero, {pos_n:4d} pos)")

    expected_an_table6 = {2: 0, 3: 1, 4: 9, 5: 26, 6: 55, 7: 99, 8: 161, 9: 244, 11: 485, 12: 649, 15: 2247, 17: 3368, 24: 12074}
    assert an_indices == expected_an_table6
    return an_indices


def hessian_data(v: np.ndarray):
    """Exact Riesz kernel tables for integer roots of squared length 2."""
    dot = v @ v.T
    distances = 2 - dot
    off = ~np.eye(len(v), dtype=bool)
    fp = np.zeros_like(dot, dtype=np.int64)
    fpp = np.zeros_like(dot, dtype=np.int64)
    for s in (1, 2, 3, 4):
        cells = (distances == s) & off
        fp[cells] = FP[s]
        fpp[cells] = FPP[s]
    verify(np.all((distances == 0) | (distances == 1) | (distances == 2) |
                  (distances == 3) | (distances == 4)), "non-ADE root distances")
    verify(np.all(np.sum(v*v, axis=1) == 2), "roots not of norm squared 2")
    return dot, fp, fpp, distances


def apply_scaled_hessian(v, w, dot, fp, fpp, cached_cw=None):
    """Compute SCALE*H(W) using only bounded signed 64-bit integers.

    Exact formula follows by substituting X=V/sqrt(2) into the covariant
    Hessian formula, with W the integer-coordinate tangent velocity.
    """
    verify(np.all((v*w).sum(axis=1) == 0), "velocity not tangent")
    variation = w @ v.T + v @ w.T
    curvature = (fpp * variation) @ v
    radial_curvature = (v * curvature).sum(axis=1)
    cw = (fp * dot).sum(axis=1) if cached_cw is None else cached_cw
    forces = fp @ w
    radial_forces = (v * forces).sum(axis=1)
    return (8*curvature - 4*v*radial_curvature[:, None]
            + 4*cw[:, None]*w - 8*forces + 4*v*radial_forces[:, None])


def a_roots(n):
    v = np.zeros((n*(n+1), n+1), dtype=np.int64)
    pairs = [(a, b) for a in range(n+1) for b in range(n+1) if a != b]
    for i, (a, b) in enumerate(pairs):
        v[i, a], v[i, b] = 1, -1
    return v, pairs


def d_roots(n):
    desc = [(a, b, sa, sb) for a in range(n) for b in range(a+1, n)
            for sa in (-1, 1) for sb in (-1, 1)]
    v = np.zeros((len(desc), n), dtype=np.int64)
    for i, (a, b, sa, sb) in enumerate(desc):
        v[i, a], v[i, b] = sa, sb
    return v


def a_three_form_field(pairs, m):
    # A Hodge-star 3-form on four labels has zero contraction with 1.
    w = np.zeros((len(pairs), m), dtype=np.int64)
    for k, (a, b) in enumerate(pairs):
        if max(a, b) >= 4:
            continue
        for c in range(4):
            if c in (a, b):
                continue
            rest = next(d for d in range(4) if d not in (a, b, c))
            perm = [a, b, c, rest]
            inversions = sum(perm[i] > perm[j] for i in range(4) for j in range(i+1,4))
            w[k, c] = (-1)**inversions
    return w


def d_cubic_field(v, a=0, b=1, c=2, d=3):
    w = np.zeros_like(v)
    coordinate_diff = v[:, c]**2 - v[:, d]**2
    w[:, a] = coordinate_diff*v[:, b]
    w[:, b] = -coordinate_diff*v[:, a]
    return w


def certify_modes():
    for n in (3, 4, 6, 24):
        v, pairs = a_roots(n)
        w = a_three_form_field(pairs, n+1)
        verify(np.any(w), f"zero A{n} field")
        verify(np.all(w.sum(axis=1) == 0), f"A{n} 3-form not sum-zero")
        dot, fp, fpp, _ = hessian_data(v)
        hw = apply_scaled_hessian(v, w, dot, fp, fpp)
        lam = Fraction(-127*(n+1), 54)
        verify((lam*SCALE).denominator == 1, "mode scaling nonintegral")
        verify(np.array_equal(hw, (lam*SCALE).numerator*w),
               f"A{n} 3-form eigenvalue failed")
    print("PASS  Exact A_n 3-form eigenfield at n=3,4,6,24")

    for n in (4, 5, 6, 8, 24):
        v = d_roots(n)
        w = d_cubic_field(v)
        verify(np.any(w), f"zero D{n} cubic field")
        dot, fp, fpp, _ = hessian_data(v)
        hw = apply_scaled_hessian(v, w, dot, fp, fpp)
        lam = Fraction(702-127*n, 27)
        verify((lam*SCALE).denominator == 1, "D-mode scaling nonintegral")
        verify(np.array_equal(hw, (lam*SCALE).numerator*w),
               f"D{n} cubic eigenvalue failed")
    print("PASS  Exact D_n cubic eigenfield at n=4,5,6,8,24")

    # Explicitly refute the invalid zero-centroid-invariant assumption.
    v, pairs = a_roots(3)
    w = np.zeros_like(v)
    v0 = np.array([1, 1, 1, -3], dtype=np.int64)
    w[pairs.index((0, 1))] = v0
    w[pairs.index((0, 2))] = -v0
    dot, fp, fpp, _ = hessian_data(v)
    hw = apply_scaled_hessian(v, w, dot, fp, fpp)
    expected_sum = np.array([0, 340, -340, 0], dtype=np.int64)*SCALE//27
    verify(np.array_equal(hw.sum(axis=0), expected_sum),
           "A3 zero-centroid noninvariance counterexample")
    print("PASS  Exact A3 centroid-coupling counterexample")
    return True


def certify_derivative_jets():
    """Full seven-jet and vanishing antipodal-curvature identities on explicit A,D fields.

    For each jet set the relevant f'(s) or f''(s) to one and all others
    to zero. apply_scaled_hessian then computes precisely 4H(U) (the
    coefficient table is unscaled here), so no floating point enters.
    """
    cases=[]
    for n in (3,4,6,24):
        v,pairs=a_roots(n)
        w=a_three_form_field(pairs,n+1)
        coeff_fp={1:2*(n+1),3:-2*(n+1)}
        coeff_fpp={2:4*(n+1)}
        cases.append((f'A_{n}',v,w,coeff_fp,coeff_fpp))
    for n in (4,5,6,8,24):
        v=d_roots(n)
        w=d_cubic_field(v)
        coeff_fp={1:4*(n-1),3:-4*(n-1)}
        coeff_fpp={1:4,2:8*(n-2),3:4}
        cases.append((f'D_{n}',v,w,coeff_fp,coeff_fpp))
    for name,v,w,fpc,fppc in cases:
        dot=v@v.T
        d=2-dot
        mask=~np.eye(len(v),dtype=bool)
        for kind in ('fp','fpp'):
            for distance in (1,2,3,4):
                fp=np.zeros_like(dot,dtype=np.int64)
                fpp=np.zeros_like(dot,dtype=np.int64)
                values=fp if kind=='fp' else fpp
                values[(d==distance)&mask]=1
                h=apply_scaled_hessian(v,w,dot,fp,fpp)
                coefficient=(fpc if kind=='fp' else fppc).get(distance,0)
                assert np.array_equal(h,4*coefficient*w),(
                    name,kind,distance,'independent Hessian jet mismatch')
        print(f'PASS all eight independent Hessian derivative jets for {name}')
    return True


# Root constructors and exact generic Hessian for unit vectors V/sqrt(q).
# Scaling: (3456*q*q)*H(W) is integral on integral tangent velocities.


def eroots(kind):
  e8=[]
  for i in range(8):
   for j in range(i+1,8):
    for s1 in (-2,2):
     for s2 in (-2,2):
      v=[0]*8;v[i]=s1;v[j]=s2;e8.append(v)
  for signs in itertools.product((-1,1),repeat=8):
   if math.prod(signs)==1:e8.append(list(signs))
  v=np.array(e8,dtype=np.int64)
  if kind==6:v=v[v[:,0]+v[:,1]==0];v=v[v[:,1]+v[:,2]==0]
  if kind==7:v=v[v[:,0]+v[:,1]==0]
  return v


def roots(kind,n):
 if kind=='A':return a_roots(n)[0]
 if kind=='D':return d_roots(n)
 return eroots(n)


def kernel(v):
 N,amb=v.shape;q=int(np.sum(v[0]**2));assert np.all((v*v).sum(axis=1)==q)
 dot=v@v.T;dst=2-2*dot//q;mask=~np.eye(N,dtype=bool)
 FPmat=np.zeros((N,N),dtype=np.int64); FPPmat=np.zeros((N,N),dtype=np.int64)
 for s in (1,2,3,4):
  FPmat[(dst==s)&mask]=FP[s];FPPmat[(dst==s)&mask]=FPP[s]
 cw=(FPmat*dot).sum(axis=1)
 def app(W):
  W=np.asarray(W,dtype=np.int64)
  variation=W@v.T+v@W.T
  R=(FPPmat*variation)@v
  rd=(v*R).sum(axis=1)
  F=FPmat@W
  fd=(v*F).sum(axis=1)
  out=(4*q)*R -4*v*rd[:,None]+(2*q)*cw[:,None]*W -(2*q*q)*F+(2*q)*v*fd[:,None]
  assert np.all((v*out).sum(axis=1)==0)
  return out
 return app, q, dst


def dotall(a,b):return sum(int(x)*int(y) for x,y in zip(a.flat,b.flat))


def nat(kind,n):
 v=roots(kind,n);N=len(v);app,q,dst=kernel(v)
 e=v[0]; w0=q*e[None,:]-(v@e)[:,None]*v
 if not np.any(w0):return v,q,e,[],[],S.zeros(0,0),S.zeros(0,0),app
 basis=[w0];h0=app(w0)
 aa=dotall(w0,w0);bb=dotall(w0,h0)
 mu=S.Rational(bb,aa)
 w1_num=(mu.q*h0.astype(object)-mu.p*w0.astype(object)).reshape(N,v.shape[1]);gg=0
 for z in w1_num.flat:gg=math.gcd(gg,abs(int(z)))
 if gg:
  w1=np.array([[int(z)//gg for z in row] for row in w1_num],dtype=np.int64)
  basis.append(w1)
 hs=[app(w) for w in basis]
 Gram=S.Matrix([[dotall(bi,bj) for bj in basis] for bi in basis])
 Khat=S.Matrix([[dotall(bi,hj) for hj in hs] for bi in basis])
 assert Khat==Khat.T
 assert Gram.det()>0
 for j,hj in enumerate(hs):
  scalar=Gram.inv()*Khat[:,j]
  prediction=sum((int(0)*basis[0] for _ in []),np.zeros_like(basis[0],dtype=object))
  for bcoef,bvec in zip(scalar,basis):prediction+=bcoef*bvec.astype(object)
  assert np.array_equal(prediction,hj.astype(object)),f'NO closure {kind}{n} column {j} {scalar}'
 ctr=[dotall(w,np.broadcast_to(e,w.shape)) for w in basis]
 assert all(x==0 for x in ctr[1:]),(kind,n,ctr)
 return v,q,e,basis,ctr,Gram,Khat,app


spec=[
 ('A_1^24',2,[('A',1)]*24),('A_2^12',3,[('A',2)]*12),('A_3^8',4,[('A',3)]*8),('A_4^6',5,[('A',4)]*6),
 ('A_5^4 D_4',6,[('A',5)]*4+[('D',4)]),('D_4^6',6,[('D',4)]*6),('A_6^4',7,[('A',6)]*4),('A_7^2 D_5^2',8,[('A',7)]*2+[('D',5)]*2),
 ('A_8^3',9,[('A',8)]*3),('A_9^2 D_6',10,[('A',9)]*2+[('D',6)]),('D_6^4',10,[('D',6)]*4),
 ('A_11 D_7 E_6',12,[('A',11),('D',7),('E',6)]),('E_6^4',12,[('E',6)]*4),('A_12^2',13,[('A',12)]*2),('D_8^3',14,[('D',8)]*3),
 ('A_15 D_9',16,[('A',15),('D',9)]),('A_17 E_7',18,[('A',17),('E',7)]),('D_10 E_7^2',18,[('D',10)]+[('E',7)]*2),
 ('D_12^2',22,[('D',12)]*2),('D_16 E_8',30,[('D',16),('E',8)]),('E_8^3',30,[('E',8)]*3)]


# Independent 24-cross-polytope certificate.

def certify_cross_polytope():
 n=24;v=np.concatenate([np.eye(n,dtype=np.int64),-np.eye(n,dtype=np.int64)]);N=len(v)
 app,q,d=kernel(v); assert q==1
 seed=np.zeros_like(v,dtype=np.int64);seed[0,1]=1
 eigen=[0,7344,20736,86832]
 seq=[];W=seed
 for k in range(4):
  seq.append(int(N*(n-1)*W[0,1]))
  W=app(W)
 # annihilating polynomial p(H) seed
 W=seed.astype(object)
 for lam in eigen:
  W=lam*W-app(W)
 assert not np.any(W), 'crosspoly annihilator fails'
 mat=S.Matrix([[lam**k for lam in eigen] for k in range(4)])
 m=mat.inv()*S.Matrix(seq)
 print('PASS A1^24 cross-polytope exact spectrum:',dict(zip(eigen,m)))
 assert list(m)==[276,528,276,24]


# Root-line adjacency and odd/even transverse Hessian identities.

def certify_transverse_component(kind,n,h):
 v=roots(kind,n);N=len(v);q=int(v[0]@v[0]);assert N==n*h
 dot=v@v.T; dist=2-2*dot//q
 fp=np.zeros((N,N),dtype=np.int64);mask=~np.eye(N,dtype=bool)
 for a in (1,2,3,4):fp[(dist==a)&mask]=FP[a]
 # pair opposite root lines
 lines=[]; orient=[]; labels=[]; look={}
 for i,row in enumerate(v):
  vv=tuple(map(int,row));minus=tuple(map(int,-row)); canonical=min(vv,minus)
  idx=look.get(canonical)
  if idx is None:idx=len(lines);look[canonical]=idx;lines.append(i)
  labels.append(idx)
  orient.append(1 if vv==canonical else -1)
 L=len(lines);labels=np.array(labels);orient=np.array(orient)
 assert L==N//2
 reps=np.array([np.where((labels==k)&(orient==1))[0][0] for k in range(L)])
 vr=v[reps]
 Adj=np.array((abs(vr@vr.T)==q//2),dtype=np.int64)
 assert np.all(np.diag(Adj)==0)
 if kind=='A': deg=2*(n-1); eigen=[(n-3,n),(-2,(n+1)*(n-2)//2)] if n>1 else []
 elif kind=='D':deg=4*(n-2);eigen=[(2*(n-4),n-1),(-4,n*(n-3)//2),(0,n*(n-1)//2)]
 else:
  deg={6:20,7:32,8:56}[n];eigen={6:[(2,20),(-4,15)],7:[(4,27),(-4,35)],8:[(8,35),(-4,84)]}[n]
 assert np.all(Adj.sum(axis=1)==deg)
 assert sum(mult for eig,mult in eigen)==L-1
 # annihilating polynomial with all eigenvalues predicted (includes constant degree)
 PP=np.eye(L,dtype=np.int64)
 for eig in [deg]+sorted(set(mu for mu,mult in eigen if mult)):
  PP=PP@(Adj-int(eig)*np.eye(L,dtype=np.int64))
 assert np.all(PP==0),f'adj annihilator {kind}{n}'
 assert np.trace(Adj)==sum(mu*mult for mu,mult in [(deg,1)]+eigen)
 assert np.trace(Adj@Adj)==deg*deg+sum(mu**2*mult for mu,mult in eigen)
 diagcoef=4*h*FPP[2]+2*((fp[reps]*dot[reps]).sum(axis=1))//q
 assert np.all(diagcoef==diagcoef[0])
 Ke=np.zeros((L,L),dtype=np.int64);Ko=np.zeros((L,L),dtype=np.int64)
 for i,ind in enumerate(reps):
  sums_even=np.zeros(L,dtype=np.int64)
  sums_odd=np.zeros(L,dtype=np.int64)
  np.add.at(sums_even,labels,fp[ind])
  np.add.at(sums_odd,labels,fp[ind]*orient)
  Ke[i,:]=-2*sums_even
  Ko[i,:]=-2*sums_odd
 np.fill_diagonal(Ke,Ke.diagonal()+int(diagcoef[0]));np.fill_diagonal(Ko,Ko.diagonal()+int(diagcoef[0]))
 assert np.array_equal(Ke,Ke.T) and np.array_equal(Ko,Ko.T)
 ones=np.ones((L,L),dtype=np.int64)
 alpha=4*h*FPP[2]+2*((h-2)*(FP[1]-FP[3])+2*FP[2]-2*FP[4])
 beta=-2*(FP[1]+FP[3]-2*FP[2])
 residual=Ke-alpha*np.eye(L,dtype=np.int64)-beta*Adj
 assert np.all(residual@(L*np.eye(L,dtype=np.int64)-ones)==0),f'even mode failed {kind}{n} {np.max(abs(residual@(L*np.eye(L,dtype=np.int64)-ones)))}'
 if h>2:
  lamodd=-8128*h
  P=q*h*np.eye(L,dtype=np.int64)-2*(vr@vr.T)
  assert np.all(P@P==(q*h)*P),f'P not projection {kind}{n}'
  assert np.all((Ko-lamodd*np.eye(L,dtype=np.int64))@P==0),f'odd mode failed {kind}{n} max {np.max(abs((Ko-lamodd*np.eye(L,dtype=np.int64))@P))}'
 print('CHECKED',kind,n,'root-lines',L,'adj degree',deg,'even/odd exact',flush=True)


def certify_transverse_blocks():
    unique=sorted(set((kind,n,h) for name,h,comps in spec for kind,n in comps))
    for kind,n,h in unique:
        certify_transverse_component(kind,n,h)
    print('PASS transverse adjacency spectra and odd/even Hessian identities for all 25 component/rank pairs')


# The coupled natural/centroid matrices are computed from root coordinates,
# NOT from guessed trace/determinant formulas. Each Krylov span is verified
# invariant, and it contains the centroid-coupling direction; its orthogonal
# complement therefore cannot couple to the other components.


def certify_coupled_centroid_blocks():
 cache={}
 for name,h,comps in spec:
  K=len(comps)
  for ir,(kind,n) in enumerate(comps):
   if (kind,n) in comps[:ir]:continue
   if (kind,n) not in cache:
    t=time.monotonic();cache[kind,n]=nat(kind,n)
    print('natural',kind,n,'dimension',len(cache[kind,n][3]),'elapsed',round(time.monotonic()-t,3),flush=True)
   v,q,e,basis,ctr,G,Khat,app=cache[kind,n]
   ext=[h*dim for j,(kt,dim) in enumerate(comps) if j!=ir]
   m=len(basis); full=S.zeros(m+len(ext))
   for i in range(m):
    for j in range(m):full[i,j]=Khat[i,j]/S.Integer(3456*q*q)
   fp1,fp2,fp3,fp4=[S.Rational(-2,s**3) for s in (1,2,3,4)]
   fpp2=S.Rational(6,2**4)
   mu0=4*h*fpp2-2*(h-2)*(fp1+3*fp3)+2*(4*h-6)*fp2-4*fp4
   for s,Ns in enumerate(ext):
    for i,c in enumerate(ctr):
     full[i,m+s]=full[m+s,i]=-2*fp2*Ns*c
    for t,Nt in enumerate(ext):
     full[m+s,m+t]=q*(Ns*mu0*int(s==t)-2*fp2*Ns*Nt)
   npos,nneg,nzero=exact_inertia(full)
   assert (npos,nneg,nzero)==(full.rows,0,0),(name,kind,n,npos,nneg,nzero)
  print('PASS',name,flush=True)


# D_n exact whole-space inertia from the 42/45-dimensional B_{n-3}-fixed
# tangent representation. Stabilizer-fixed seed fields at one root generate the
# entire tangent module under signed permutations, so factors of the reduced
# characteristic polynomial annihilate the full Hessian. Transitive symmetry
# reduces whole-space power traces to two diagonal reduced-space moments.


def build_dn_fixed_reduction(n):
  # Stabilizer B_{n-3} fixes coordinates 0,1,2 pointwise and acts by signed permutations on coordinates >=3.
  # Orbits are signed/permuted triples (root support, component index); components in tail outside support vanish.
  v=d_roots(n); N=len(v)
  key_to_id={}; signs=[]; orb=[]; reps=[]; sizes=[]; repflat=[]
  for k, vv in enumerate(v):
   ids=np.flatnonzero(vv); a,b=map(int,ids);sa,sb=map(int,vv[ids]);
   for c in range(n):
    if c >=3 and c not in (a,b):
     orb.append(-1);signs.append(0);continue
    # map tail support indices to 3,4 so roots on same orbit
    tails=sorted(set(i for i in (a,b) if i>=3)); mp={p:3+t for t,p in enumerate(tails)}
    aa,bb=mp.get(a,a),mp.get(b,b)
    saa=1 if a>=3 else sa; sbb=1 if b>=3 else sb
    cc=mp.get(c,c)
    keys=[]
    for perm in itertools.permutations(range(3,3+len(tails))):
     pmp=dict(zip(range(3,3+len(tails)),perm))
     a1,b1=pmp.get(aa,aa),pmp.get(bb,bb)
     sa1,sb1=saa,sbb
     if a1>b1:a1,b1=b1,a1; sa1,sb1=sb1,sa1
     keys.append((a1,b1,sa1,sb1,pmp.get(cc,cc)))
    key=min(keys)
    oid=key_to_id.get(key)
    if oid is None:
      oid=len(reps);key_to_id[key]=oid;reps.append(key);sizes.append(0);repflat.append(k*n+c)
    sizes[oid]+=1;orb.append(oid);signs.append(int(vv[c]) if c>=3 else 1)
  orb=np.array(orb,dtype=np.int16); signs=np.array(signs,dtype=np.int8)
  O=len(reps)
  # tangent constraints for orbit distinct roots (only 0<=a,b<5 possible)
  rows={}
  for k,vv in enumerate(v):
   a,b=map(int,np.flatnonzero(vv));
   row=[0]*O
   for c in (a,b):
    j=k*n+c; idx=int(orb[j]);row[idx]+=int(vv[c])*int(signs[j])
   rows[tuple(row)]=1
  A=S.Matrix(list(rows))
  Z=S.Matrix.hstack(*A.nullspace()); b=Z.cols
  # Clear rational denominators
  for j in range(b):
   q=S.ilcm(*[t.q for t in Z[:,j]]);Z[:,j]=Z[:,j]*q
  zi=np.array(Z.tolist(),dtype=np.int64)
  dot=v@v.T; dst=2-dot; mask=~np.eye(N,dtype=bool)
  fp=np.zeros_like(dst,dtype=np.int64);fpp=np.zeros_like(dst,dtype=np.int64)
  for s in (1,2,3,4):
   fp[(dst==s)&mask]=FP[s]; fpp[(dst==s)&mask]=FPP[s]
  repflat=np.array(repflat); repk=repflat//n; repc=repflat %n
  ur, inv=np.unique(repk,return_inverse=True)
  vu=v[ur]; fu=fp[ur]; qu=fpp[ur]; cwu=(fu*dot[ur]).sum(axis=1)
  valid=orb>=0
  HZ=np.zeros((O,b), dtype=np.int64)
  for j in range(b):
   wflat=np.zeros(N*n,dtype=np.int64);wflat[valid]=zi[orb[valid],j]*signs[valid]
   w=wflat.reshape(N,n);wu=w[ur]
   variation=wu@v.T+vu@w.T
   R=(qu*variation)@v; rd=(vu*R).sum(axis=1)
   F=fu@w; fd=(vu*F).sum(axis=1)
   h=8*R-4*vu*rd[:,None]+4*cwu[:,None]*wu-8*F+4*vu*fd[:,None]
   HZ[:,j]=h[inv,repc]*signs[repflat]
  Gram=Z.T*S.diag(*sizes)*Z
  Kr=Z.T*S.diag(*sizes)*S.Matrix(HZ.tolist())
  if Kr!=Kr.T:
   raise ArithmeticError(f'D{n} reduced Hessian not symmetric')
  idx=list((Z.T).rref()[1]); Zinv=Z[idx,:].inv()
  Mat=Zinv*S.Matrix(HZ[idx,:].tolist())
  assert Gram*Mat==Kr
  assert b== (42 if n==4 else 45), (n,b)
  assert O== (60 if n==4 else 64), (n,O)
  # root0 (-e0-e1) first root, both tangent basis w1=(-1,1,0..), w2=e2
  seeds=[]
  for field in [np.array([-1,1]+[0]*(n-2)),np.array([0,0,1]+[0]*(n-3))]:
   wo=[0]*O
   for c,val in enumerate(field):
    if not val:continue
    i=int(orb[c]);wo[i]=int(val)*int(signs[c])
   wo=S.Matrix(wo)
   coeff=Zinv*wo[idx,:]
   assert Z*coeff==wo
   seeds.append(coeff)
  return Mat,Gram,seeds


def certify_dn_one(n):
    M, G, seeds = build_dn_fixed_reduction(n)
    z=S.symbols('z')
    factors=S.factor_list(M.charpoly(z).as_expr(), z)[1]
    # M acts on a full fixed space; its characteristic polynomial annihilates
    # the two seed tangent fields. Signed permutations of those fields span the
    # full D_n tangent module, proving no global eigenvalues were omitted.
    nf=len(factors)
    states=list(seeds)
    moments=[]
    N=2*n*(n-1)
    for k in range(nf):
        moments.append(N*(seeds[0].dot(G*states[0])/2
                       +(n-2)*seeds[1].dot(G*states[1])))
        states=[M*st for st in states]
    assert moments[0]==N*(n-1)
    powerseqs=[]
    for p,m in factors:
        poly=S.Poly(p,z).monic()
        deg=poly.degree()
        coeff=poly.all_coeffs()
        comp=S.zeros(deg)
        for j in range(1,deg):comp[j,j-1]=1
        for j in range(deg):comp[j,deg-1]=-coeff[deg-j]
        powerseqs.append([S.trace(comp**k) for k in range(nf)])
    Vand=S.Matrix([[powerseqs[j][k] for j in range(nf)] for k in range(nf)])
    assert Vand.det()!=0, f'D{n}: spectral factors not separable by moments'
    mult=Vand.inv()*S.Matrix(moments)
    negative=zero=positive=0
    for j,(p,_) in enumerate(factors):
        count=mult[j]
        assert count.is_integer and count>=0, (n,p,count)
        intervals=S.polys.polytools.intervals(p, eps=S.Rational(1,100))
        for (lo,hi),root_mult in intervals:
            if lo==0 and hi==0:zero+=int(count)*root_mult
            elif lo>0:positive+=int(count)*root_mult
            elif hi<0:negative+=int(count)*root_mult
            else:raise ArithmeticError(f'D{n}: nonseparated zero in root interval {lo,hi}')
    assert negative+zero+positive==N*(n-1)
    assert zero==n*(n-1)//2
    print(f'PASS D_{n:2d}: ({negative} negative, {zero} zero, {positive} positive),'
          f' {len(factors)} exact rational spectral factors, fixed dim {M.rows}')
    return negative

def certify_dn_family():
    expected={4:0,5:0,6:45,7:154,8:252,9:564,10:825,12:1562,16:5680,24:23184}
    observed={n:certify_dn_one(n) for n in expected}
    assert observed==expected, (observed,expected)
    return observed


# E6/E7 roots, all tangent fibers under the Weyl group, exact annihilator
# and exact projector trace: zero eigenspace equals global rotations.


R6=[26520576,25608192,20007936,16567296,14954496,6614016,3178496,2927616]
R7=[35471360,34745344,31943680,24792064,18898944,8203264,4767744,3288064]

def certify_exceptional_one(n):
 t=time.monotonic();v=eroots(n);N=len(v);q=8;G=v@v.T;D=2-G//4
 fp=np.zeros_like(D);qmat=np.zeros_like(D);mask=~np.eye(N,dtype=bool)
 for s in (1,2,3,4):
  fp[(D==s)&mask]=FP[s];qmat[(D==s)&mask]=FPP[s]
 cw=(fp*G).sum(axis=1)
 def app(W):
  U=np.asarray(W)
  J=U@v.T+v@U.T
  R=(qmat*J)@v
  rd=(v*R).sum(axis=1)
  F=fp@U;fd=(v*F).sum(axis=1)
  return 32*R-4*v*rd[:,None]+16*cw[:,None]*U-128*F+16*v*fd[:,None]
 # Weyl reflection orbit on roots by all root reflections
 index={tuple(row):k for k,row in enumerate(v)}
 seen={0};queue=[0]; t1=time.monotonic()
 while queue:
  i=queue.pop(); r=v[i]
  # reflect r through all root hyperplanes
  dot=v@r
  for y,dd in zip(v,dot):
   reflected=r-(int(dd)//4)*y
   j=index[tuple(reflected)]
   if j not in seen:seen.add(j);queue.append(j)
 assert len(seen)==N
 # find tangent basis from perpendicular roots
 bas=[]
 rank=1
 for row in v[G[0]==0]:
  newrank=S.Matrix([v[0]]+bas+[row]).rank()
  if newrank>rank:
   bas.append(row);rank=newrank
  if len(bas)==n-1:break
 assert len(bas)==n-1 and rank==n
 B=S.Matrix(np.array(bas,dtype=np.int64).T.tolist())
 Q=B.T*B
 assert Q.det()>0
 Rroots=R6 if n==6 else R7
 normprod=math.prod(Rroots)
 projK=S.zeros(n-1,n-1)
 for j,u0 in enumerate(bas):
  seed=np.zeros_like(v,dtype=object);seed[0]=u0.astype(object)
  # all eigenvalues nonnegative: p(A)=A product(A-aI)=0
  cur=app(seed)
  for root in Rroots:cur=app(cur)-root*cur
  assert np.all(cur==0),f'annihilator failed generator {j}'
  # projector onto zero eigenvalues using P_0(A) = prod( a I - A)/prod a
  cur=seed
  for root in Rroots:cur=root*cur-app(cur)
  block=B.T*S.Matrix([list(map(int,cur[0]))]).T
  projK[:,j]=block
 rankzero=S.simplify(N*S.trace(Q.inv()*projK)/normprod)
 print(f'PASS E_{n}: annihilator on all tangent fibers; nullity projector trace {rankzero}; elapsed {time.monotonic()-t:.2f}s')
 assert rankzero==n*(n-1)//2


def certify_e6_e7():
    certify_exceptional_one(6)
    certify_exceptional_one(7)
    return True


# All-Gaussian and completely-monotone polynomial-hook certificates:
# finite exact powers 0..511 plus exact dominant-node inequalities for k>=512.
# Quadratic field Q(sqrt(5)) is represented with rational pairs; signs have
# no floating-point components.


class Q5:
 __slots__=('a','b')
 def __init__(self,a=0,b=0):self.a=F(a);self.b=F(b)
 @staticmethod
 def cv(v):
  if isinstance(v,Q5):return v
  r=S.expand(S.radsimp(S.simplify(v)))
  bb=S.simplify(r.coeff(S.sqrt(5)))
  aa=S.simplify(r-bb*S.sqrt(5))
  assert aa.is_Rational and bb.is_Rational,(v,aa,bb)
  return Q5(F(int(aa.p),int(aa.q)),F(int(bb.p),int(bb.q)))
 def __add__(self,o):
  o=Q5.cv(o);return Q5(self.a+o.a,self.b+o.b)
 __radd__=__add__
 def __neg__(self):return Q5(-self.a,-self.b)
 def __sub__(self,o):return self+-Q5.cv(o)
 def __rsub__(self,o):return Q5.cv(o)+-self
 def __mul__(self,o):
  o=Q5.cv(o);return Q5(self.a*o.a+5*self.b*o.b,self.a*o.b+self.b*o.a)
 __rmul__=__mul__
 def inv(self):
  den=self.a*self.a-5*self.b*self.b
  assert den
  return Q5(self.a/den,-self.b/den)
 def __truediv__(self,o):return self*Q5.cv(o).inv()
 def __pow__(self,n):
  assert n>=0
  y=Q5(1);a=self
  while n:
   if n&1:y=y*a
   a=a*a;n//=2
  return y
 def sign(self):
  a,b=self.a,self.b
  if not b:return (a>0)-(a<0)
  if not a:return (b>0)-(b<0)
  if (a>0)==(b>0):return 1 if a>0 else -1
  mag=a*a-5*b*b
  if mag==0:return 0
  return (1 if mag>0 else -1) * (1 if a>0 else -1)
 def abs(self):return self if self.sign()>=0 else -self
 def __repr__(self):return f'({str(self.a)} + {str(self.b)}*sqrt(5))'


def gaussian_cert(K=512):
 s,z=S.symbols('s z')
 for name,d,N,nodes in CASES:
  t0=time.monotonic();active=nodes[:-1];m=len(nodes);t=2*m-2
  W={a:S.prod((a-b)**2 for b in active if b!=a) for a in active}
  w={a:S.cancel(1/((4-a)*W[a])) for a in active}
  ell={a:S.prod((s-b)/(a-b) for b in active if b!=a) for a in active}
  L={a:S.simplify(S.Rational(1,2)/(a-4)+sum((1/(a-b) for b in active if b!=a),S.Integer(0))) for a in active}
  Z={a:S.cancel((s-4)/(a-4)*ell[a]**2) for a in active}
  denom=S.simplify(sum(w.values()))
  # For each active jet, response q(s) for q=h' polynomial and kappa.
  responses=[]
  for a in active:
   for typ in (0,1):
    dk=S.cancel(w[a]/denom *(-2*L[a] if typ==0 else 1))
    q=Z[a]*(1-2*L[a]*(s-a) if typ==0 else s-a)-dk*sum((s-b)*Z[b] for b in active)
    responses.append((a,typ,dk,S.Poly(S.cancel(q),s)))
  # f'(4) separate for k=1; solve response constant f'(4)=1
  p4=S.prod((4-a)**2 for a in active)
  d4=S.cancel(-1/(p4*denom))
  q4=S.Poly(S.cancel(S.prod((s-a)**2 for a in active)/p4-d4*sum((s-b)*Z[b] for b in active)),s)
  normalized=[S.cancel(S.gegenbauer(j,S.Rational(d-2,2),z)/S.gegenbauer(j,S.Rational(d-2,2),1)) for j in range(1,t+1)]
  MM=S.Matrix([[S.Poly(normalized[j],z).nth(i) for j in range(t)] for i in range(1,t+1)])
  MI=MM.inv()
  def transform(q):
   integ=S.integrate(q.as_expr(),s)
   expr=S.Poly(S.expand(integ.subs(s,2-2*z)),z)
   ans=MI*S.Matrix([expr.nth(i) for i in range(1,t+1)])
   return [S.simplify(c) for c in ans]
  coeffs={(a,typ):[Q5.cv(u) for u in transform(q)] for a,typ,dk,q in responses}
  c4=[Q5.cv(u) for u in transform(q4)]
  kap={(a,typ):Q5.cv(dk) for a,typ,dk,q in responses}
  kap4=Q5.cv(d4)
  beta=[Q5.cv(4-a) for a in active]
  # each coefficient's jet response: index0 kappa, then 1..t Gegenbauer
  AA=[[kap[a,0]]+[coeffs[a,0][j] for j in range(t)] for a in active]
  BB=[[kap[a,1]]+[coeffs[a,1][j] for j in range(t)] for a in active]
  r4=[kap4]+c4
  positive=[False]*(t+1)
  for k in range(K):
   if k==0:vec=[Q5() for j in range(t+1)]
   elif k==1:vec=[-r4[j]+sum((-AA[a][j] for a in range(len(active))),Q5()) for j in range(t+1)]
   else:
    vec=[Q5() for j in range(t+1)]
    for a in range(len(active)):
     factor=k*beta[a]**(k-2)
     for j in range(t+1):
      vec[j]=vec[j]+factor*((k-1)*BB[a][j]-beta[a]*AA[a][j])
   for j,c in enumerate(vec):
    sg=c.sign()
    if sg<0:raise AssertionError(f'NEGATIVE Gaussian coefficient {name} j={j} k={k}: {c}')
    if sg>0:positive[j]=True
  assert all(positive),(name,positive)
  # Infinite tail is dominated by the smallest-distance node a0 (largest beta).
  rho=Q5(F(5,6));limit=K-1
  assert all((rho*beta[0]-b).sign()>=0 for b in beta[1:]),(name,beta)
  for j in range(t+1):
   b0=BB[0][j];a0=AA[0][j]
   rest=sum((BB[a][j].abs()+beta[a]*AA[a][j].abs()/limit for a in range(1,len(active))),Q5())
   if b0.sign()>0:
    main=b0-beta[0]*(a0 if a0.sign()>0 else Q5())/limit
    assert main.sign()>0,(name,j,'not dominated',main)
    assert (main-rho**(K-2)*rest).sign()>0,(name,j,'tail not certified')
   elif b0.sign()==0 and a0.sign()<0:
    main=-beta[0]*a0
    assert (main-limit*rho**(K-2)*rest).sign()>0,(name,j,'tail not certified constant leading')
   else:
    raise AssertionError((name,j,'leading node not positive',b0,a0))
  print(f'PASS Gaussian all-powers {name}: 0..{K-1} exact, k>={K} positive by dominant-node tail; elapsed {time.monotonic()-t0:.2f}s',flush=True)


CASES=[
 ('Icosahedron',3,12,[2-2/S.sqrt(5),2+2/S.sqrt(5),S.Integer(4)]),
 ('Gosset 56',7,56,[S.Rational(4,3),S.Rational(8,3),S.Integer(4)]),
 ('E8 roots',8,240,[S.Integer(1),S.Integer(2),S.Integer(3),S.Integer(4)]),
 ('552-point shell',23,552,[S.Rational(8,5),S.Rational(12,5),S.Integer(4)]),
 ('4600-point shell',23,4600,[S.Rational(4,3),S.Integer(2),S.Rational(8,3),S.Integer(4)]),
 ('Leech minimal shell',24,196560,[S.Integer(1),S.Rational(3,2),S.Integer(2),S.Rational(5,2),S.Integer(3),S.Integer(4)])]

# Inertia table reconciliation: the inputs are produced by the exact
# isolated blocks and checked coupled/transverse decompositions above.


def certify_full_24_atlas(an_indices, dn_indices):
    print("\n" + "=" * 76)
    print("[7/8 & 8/8] RECONCILING COMPLETE 24-NIEMEIER MORSE ATLAS & COXETER TRACE")
    print("=" * 76)
    fp1, fp2, fp3, fp4 = S.Rational(-2), S.Rational(-1, 4), S.Rational(-2, 27), S.Rational(-1, 32)
    fpp1, fpp2, fpp3 = S.Rational(6), S.Rational(3, 8), S.Rational(2, 27)

    def external_neg_count(kind, d_r, h):
        if d_r == 24:
            return 0
        trans_d = 24 - d_r
        neg = 0
        # 1. Odd transverse modes (Theorem 11.2): eigenvalue 2*h*(fp1 - fp3 + 2*fpp2) = -127*h/54 < 0 for h >= 3
        if h >= 3:
            lam_odd = 2 * h * (fp1 - fp3 + 2 * fpp2)
            assert lam_odd == S.Rational(-127 * h, 54) < 0
            neg += (d_r * (h - 2) // 2) * trans_d

        # 2. Even zero-mean transverse modes (Theorem 14.1) via root-line adjacency eigenvalues mu:
        def lam_even(mu):
            return 4 * h * fpp2 + 2 * ((h - 2) * (fp1 - fp3) + 2 * fp2 - 2 * fp4) - 2 * mu * (fp1 + fp3 - 2 * fp2)

        if kind == "A" and d_r >= 2:
            eigs_mu = [(d_r - 3, d_r), (-2, (d_r + 1) * (d_r - 2) // 2)]
        elif kind == "D":
            eigs_mu = [(2 * (d_r - 4), d_r - 1), (-4, d_r * (d_r - 3) // 2), (0, d_r * (d_r - 1) // 2)]
        elif kind == "E":
            eigs_mu = {
                6: [(2, 20), (-4, 15)],
                7: [(4, 27), (-4, 35)],
                8: [(8, 35), (-4, 84)],
            }[d_r]
        else:
            eigs_mu = []

        for mu, m_mu in eigs_mu:
            if m_mu > 0 and lam_even(mu) < 0:
                neg += m_mu * trans_d
        return neg

    atlas_spec = [
        ("Leech Lambda_24", None, 196560, [], (0, 276, 4520604)),
        ("A_1^24", 2, 48, [("A", 1)] * 24, (0, 276, 828)),
        ("A_2^12", 3, 72, [("A", 2)] * 12, (792, 276, 588)),
        ("A_3^8", 4, 96, [("A", 3)] * 8, (1352, 276, 580)),
        ("A_4^6", 5, 120, [("A", 4)] * 6, (1854, 276, 630)),
        ("A_5^4 D_4", 6, 144, [("A", 5)] * 4 + [("D", 4)], (2308, 276, 728)),
        ("D_4^6", 6, 144, [("D", 4)] * 6, (2280, 276, 756)),
        ("A_6^4", 7, 168, [("A", 6)] * 4, (2740, 276, 848)),
        ("A_7^2 D_5^2", 8, 192, [("A", 7)] * 2 + [("D", 5)] * 2, (2884, 276, 1256)),
        ("A_8^3", 9, 216, [("A", 8)] * 3, (3123, 276, 1569)),
        ("A_9^2 D_6", 10, 240, [("A", 9)] * 2 + [("D", 6)], (3617, 276, 1627)),
        ("D_6^4", 10, 240, [("D", 6)] * 4, (3996, 276, 1248)),
        ("A_11 D_7 E_6", 12, 288, [("A", 11), ("D", 7), ("E", 6)], (4518, 276, 1830)),
        ("E_6^4", 12, 288, [("E", 6)] * 4, (4680, 276, 1668)),
        ("A_12^2", 13, 312, [("A", 12)] * 2, (4442, 276, 2458)),
        ("D_8^3", 14, 336, [("D", 8)] * 3, (5700, 276, 1752)),
        ("A_15 D_9", 16, 384, [("A", 15), ("D", 9)], (6582, 276, 1974)),
        ("A_17 E_7", 18, 432, [("A", 17), ("E", 7)], (7271, 276, 2389)),
        ("D_10 E_7^2", 18, 432, [("D", 10)] + [("E", 7)] * 2, (7077, 276, 2583)),
        ("D_12^2", 22, 528, [("D", 12)] * 2, (8884, 276, 2984)),
        ("A_24", 25, 600, [("A", 24)], (12074, 276, 1450)),
        ("D_16 E_8", 30, 720, [("D", 16), ("E", 8)], (12960, 276, 3324)),
        ("E_8^3", 30, 720, [("E", 8)] * 3, (11088, 276, 5196)),
        ("D_24", 46, 1104, [("D", 24)], (23184, 276, 1932)),
    ]

    for name, h, N, comps, exp_inertia in atlas_spec:
        if h is None:
            # Leech minimal shell certified in Part 1
            n_neg, n_zer, n_pos = 0, 276, 23 * N - 276
            # Leech 11-design moments determine its six-distance valencies:
            # 1 and 3: 4600; 3/2 and 5/2: 47104; 2: 93150; 4: 1.
            # The following exact independent pair trace detects normalization slips.
            valencies={S.Integer(1):4600,S.Rational(3,2):47104,
                       S.Integer(2):93150,S.Rational(5,2):47104,
                       S.Integer(3):4600,S.Integer(4):1}
            assert 1+sum(valencies.values())==N
            assert S.Integer(1)+sum(c*(1-a/2)**2 for a,c in valencies.items())==S.Rational(N,24)
            assert S.Integer(1)+sum(c*(1-a/2)**4 for a,c in valencies.items())==S.Rational(3*N,24*26)
            tr_val=S.Rational(N,2)*sum(c*(8*(1-(1-a/2)**2)*S.Rational(6,a**4)
                            +92*(1-a/2)*S.Rational(-2,a**3)) for a,c in valencies.items())
            assert tr_val==S.Rational(22608148563,25)
        else:
            assert N == 24 * h
            assert sum(d_r for _, d_r in comps) == 24
            isol_neg = 0
            ext_neg = 0
            for kind, d_r in comps:
                if kind == "A" and d_r >= 2:
                    isol_neg += an_indices[d_r]
                elif kind == "D":
                    isol_neg += dn_indices[d_r]
                ext_neg += external_neg_count(kind, d_r, h)
            n_neg = isol_neg + ext_neg
            n_zer = 276
            n_pos = 23 * N - n_neg - n_zer
            # Verify Proposition 3.2 universal Coxeter trace identity
            tr_pair = 24 * h * (
                6 * (h - 2) * (fpp1 + fpp3)
                + 46 * (h - 2) * (fp1 - fp3)
                + (80 * h + 24) * fpp2
                - 46 * fp4
            )
            tr_formula = S.Rational(-23 * h * (416 * h - 2155), 18)
            assert tr_pair == tr_formula
            tr_val = tr_formula

        assert (n_neg, n_zer, n_pos) == exp_inertia
        print(f"  [PASS] {name:16s} | N={N:6d} | inertia=({n_neg:5d}, {n_zer:3d}, {n_pos:7d}) | trace={tr_val}")


# One authoritative main command. Missing modules, failed arithmetic,
# or an inconsistent atlas cause a nonzero exit status.
CHECKS=(
    ('sharp',certify_sharp_designs),
    ('gaussian',gaussian_cert),
    ('a3',certify_a3_counterexample),
    ('an',certify_an_family_and_a24),
    ('modes',certify_modes),
    ('jets',certify_derivative_jets),
    ('dn',certify_dn_family),
    ('exceptional',certify_e6_e7),
    ('crosspoly',certify_cross_polytope),
    ('transverse',certify_transverse_blocks),
    ('coupled',certify_coupled_centroid_blocks),
)

def main(argv=None):
    parser=argparse.ArgumentParser(description=__doc__,formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('--only',choices=[k for k,_ in CHECKS]+['atlas'])
    args=parser.parse_args(argv)
    if not __debug__:
        print('ERROR: Optimized Python disables assertions; proof checks require ordinary Python.',file=sys.stderr)
        return 2
    if args.only=='atlas':
        print('ERROR: full atlas must run all prerequisite checks; omit --only.',file=sys.stderr)
        return 2
    results={}
    checks=[(k,f) for k,f in CHECKS if args.only is None or args.only==k]
    start=time.monotonic()
    for key,func in checks:
        t=time.monotonic()
        print('\n'+'='*76+'\nRUNNING',key,flush=True)
        try:
            results[key]=func()
        except Exception as exc:
            print(f'FAILED {key}: {type(exc).__name__}: {exc}',file=sys.stderr,flush=True)
            print('COMPLETE 24-LATTICE CERTIFICATE: FAILED',file=sys.stderr)
            return 1
        print(f'COMPLETED {key} in {time.monotonic()-t:.2f}s',flush=True)
    if args.only is not None:
        print(f'PASS selected module {args.only}; full-atlas theorem NOT checked in this run')
        return 0
    try:
        certify_full_24_atlas(results['an'],results['dn'])
    except Exception as exc:
        print(f'FAILED 24-LATTICE RECONCILIATION: {type(exc).__name__}: {exc}',file=sys.stderr)
        return 1
    print('\n'+'='*76)
    print('COMPLETE 24-LATTICE EXACT COMPUTATIONAL CERTIFICATE: PASSED')
    print(f'ALL 11 CHECK GROUPS AND 24 ATLAS ROWS PASSED IN {time.monotonic()-start:.2f}s')
    print('Mathematical assumptions: established Weyl/representation decompositions')
    print('and the polynomial-hook spectral-gap theorem stated in the manuscript.')
    print('='*76)
    return 0

if __name__ == '__main__':
    # Colab/Jupyter executes pasted scripts as __main__ while supplying its own
    # kernel arguments (usually "-f /.../kernel-....json").  Those are not
    # arguments to the verifier.  Run the full suite without parsing them.
    # A real command-line invocation still uses strict argparse validation.
    notebook_launcher = any(
        marker in sys.argv[0]
        for marker in ('colab_kernel_launcher', 'ipykernel_launcher')
    )
    if notebook_launcher:
        status = main([])
        if status != 0:
            raise RuntimeError(f'Niemeier verification failed (status {status})')
    else:
        raise SystemExit(main())


