#!/usr/bin/env python3
"""Selected exact checks for SRFP311T1 archive record #129.
Run: python verify_orthogonal_decomposition.py (requires SymPy).
Checks the Leech interpolation certificate, arithmetic gap, spectral regrouping,
and graph extraction on planted superbases. Not a general decomposition solver,
full proof verification, or unconditional complexity certificate.
"""
from fractions import Fraction as F
from math import gcd
from functools import reduce
import sympy as S
from sympy.matrices.normalforms import hermite_normal_form


def poly_matrix(p, X):
    Y = S.zeros(X.rows)
    for c in p.all_coeffs():
        Y = Y*X + c*S.eye(X.rows)
    return Y


def spectral_regroup(G, X):
    n = G.rows
    assert G*X == X.T*G and all(a.q == 1 for a in X)
    t = S.Symbol('t')
    factors = [S.Poly(p, t, domain=S.QQ) for p, _ in S.factor_list(X.charpoly(t).as_expr(), t)[1]]
    f = reduce(lambda x,y:x*y, factors, S.Poly(1,t,domain=S.QQ))
    Q = []
    for p in factors:
        g = f.exquo(p)
        Q.append(poly_matrix(g*S.invert(g,p), X))
    m = len(Q)
    assert sum(Q, S.zeros(n)) == S.eye(n)
    assert all(q*q == q for q in Q)
    assert all(q*r == S.zeros(n) for i,q in enumerate(Q) for r in Q[:i])
    D = S.ilcm(1, *[a.q for q in Q for a in q])
    A = D*S.Matrix.hstack(*[S.Matrix(list(q)) for q in Q])
    H = hermite_normal_form(A.T.row_join(D*S.eye(m)).applyfunc(S.Integer))
    C = D*H.T.inv()
    assert all(a.q == 1 for a in C)
    assert all(a.q == 1 for a in A*C/D)
    edges = []
    for i in range(m):
        for j in range(i):
            d = reduce(gcd, [abs(int(C[i,k]-C[j,k])) for k in range(m)], 0)
            if d != 1:
                edges.append((i,j,d))
    unvisited = set(range(m)); groups=[]
    while unvisited:
        group={unvisited.pop()}; todo=list(group)
        while todo:
            i=todo.pop()
            new={b if a==i else a for a,b,d in edges if a==i or b==i}&unvisited
            unvisited-=new; group|=new; todo+=list(new)
        groups.append(group)
    P=[sum((Q[i] for i in group), S.zeros(n)) for group in groups]
    assert all(p*p==p and G*p==p.T*G and all(a.q==1 for a in p) for p in P)
    assert sum(P,S.zeros(n))==S.eye(n)
    assert all(p*q==S.zeros(n) for i,p in enumerate(P) for q in P[:i])
    return Q, P, edges, D



def verify_leech():
    import sympy as S
    from fractions import Fraction as F

    s, z = S.symbols('s z')
    a = S.symbols('a1:11')
    kappa = S.symbols('kappa')
    h = sum(a[j-1]*s**j for j in range(1, 11))
    D = [S.Rational(i, 2) for i in (2, 3, 4, 5, 6, 8)]
    conditions = [S.diff(h,s).subs(s,t)+2/t**3 for t in D]
    conditions += [S.diff(h,s,2).subs(s,t)-6/t**4+kappa for t in D[:-1]]
    solutions = list(S.linsolve(conditions, (*a, kappa)))
    assert len(solutions)==1 and all(v.is_Rational for v in solutions[0])
    sol = dict(zip((*a,kappa), solutions[0]))
    assert all(S.simplify(expr.subs(sol)) == 0 for expr in conditions)
    h = S.expand(h.subs(sol))
    k = sol[kappa]
    assert k == S.Rational(803,648000)
    print('Hermite conditions: PASS')
    print('kappa =', k)
    print('h(s) =', h)
    # Gegenbauer parameter (d-2)/2 = 11 in dimension 24; normalize at 1.
    p = S.Poly(h.subs(s,2-2*z), z)
    c = {}
    for j in range(10,-1,-1):
        g = S.Poly(S.gegenbauer(j,11,z)/S.gegenbauer(j,11,1),z)
        c[j] = p.nth(j)/g.nth(j)
        p -= c[j]*g
    assert p.is_zero
    assert all(c[j] > 0 for j in range(1,11))
    for j in range(1,11):
        print(f'Gegenbauer coefficient {j}: {c[j]}')
    print('Gegenbauer positivity: PASS')
    # Exact equality with the ten published coefficients.
    table2 = {
        1: S.Rational(13387, 20250), 2: S.Rational(82874957, 74027520),
        3: S.Rational(1263988, 759375), 4: S.Rational(7267306757, 3207859200),
        5: S.Rational(200251547, 69710625), 6: S.Rational(216854833, 65664000),
        7: S.Rational(11338034, 3270375), 8: S.Rational(218696627, 73440000),
        9: S.Rational(2243788, 1038825), 10: S.Rational(298637911, 348840000),
    }
    assert all(c[j] == table2[j] for j in range(1, 11))
    print('Published Gegenbauer coefficient table: PASS')
    # Arithmetic constants in the local magic-function coercivity proof.
    magic_constant = F(2 * 196560, 24 * (24 + 2))
    assert magic_constant == 630 and magic_constant / 2 == 315
    print('Magic-function constants 630 and 315: PASS (scalar arithmetic)')
    unit = F(4*196560,24)*F(int(k.p),int(k.q))
    gap = unit/F(32**3)
    bare = F(1200199,196608000)
    hook = F(2869867,589824000)
    assert unit == F(73073,1800)
    assert gap == F(73073,58982400) == bare-hook
    assert gap/bare == F(730,3597)
    # Additional structural identity noted in the audit.
    assert h.coeff(s, 1) == -S.Rational(2869867, 36000) == -S.Rational(32**3, 2) * S.Rational(hook.numerator, hook.denominator)
    print('Linear coefficient / hook coupling identity: PASS')
    assert 24*(24**2-4)//3 == 4576
    assert 196560*23 == 4520880
    print('Unit-sphere gap:',unit)
    print('Rescaled gap:',gap)
    print('Inverse gap:',1/gap)
    print('Retained stiffness:',gap/bare)
    print('Rational identities: PASS')
    print('Scope: interpolation, positivity and scalar arithmetic only; no full Hessian or Fourier-function verification.')


import itertools
import random
import sympy as S
from sympy.polys.matrices import DomainMatrix

def rank(M):
    return DomainMatrix.from_Matrix(M).rank()


def norm2(X):
    return (X*X).trace()


def projector_checks(G, P):
    n=G.rows
    assert sum(P, S.zeros(n)) == S.eye(n)
    for i,p in enumerate(P):
        assert all(x.q == 1 for x in p)
        assert p*p == p and G*p == p.T*G
        assert all(p*q == S.zeros(n) for q in P[:i])


def graph_extract(G, B):
    n=G.rows; N=n*(n+1)//2
    assert len(B)==N+1 and sum(B,S.zeros(n))==S.zeros(n)
    V=S.Matrix.hstack(*[S.Matrix(list(b)) for b in B[1:]])
    assert rank(V)==N
    assert all(G*b==b.T*G and all(x.q==1 for x in b) for b in B)
    aug=DomainMatrix.from_Matrix(V.row_join(S.Matrix(list(S.eye(n))))).to_field()
    rr,pivots=aug.rref()
    assert pivots==tuple(range(N))
    a=[S.Integer(0)]+list(rr.to_Matrix()[:N,N])
    assert all(S.sympify(x).q==1 for x in a)
    adj=[set() for _ in B]
    for i in range(N+1):
        for j in range(i):
            w=-(B[i]*B[j]).trace()
            assert w>=0
            if w:
                assert abs(a[i]-a[j])<=1
                if a[i]==a[j]: adj[i].add(j); adj[j].add(i)
    groups=[]; left=set(range(N+1))
    while left:
        root=min(left); left.remove(root); C={root}; queue=[root]
        while queue:
            i=queue.pop(); new=adj[i]&left; left-=new; C|=new; queue.extend(new)
        groups.append(C)
    sums=[sum((B[i] for i in C),S.zeros(n)) for C in groups]
    # Suffixes in label order attain every edge minimum; check exact projectors.
    ordered=sorted(groups,key=lambda C:a[min(C)])
    for j in range(len(ordered)+1):
        P=sum((B[i] for C in ordered[j:] for i in C),S.zeros(n))
        assert P*P==P and G*P==P.T*G
        assert norm2(P-S.eye(n)/2)==S.Rational(n,4)
    return sums,groups


def tree_superbase(n, seed):
    rng=random.Random(seed); U=S.eye(n)
    for _ in range(3*n):
        i,j=rng.sample(range(n),2); U[i,:]+=rng.choice([-1,1])*U[j,:]
    G=U.T*U; J=U.inv(); E=[]
    for i in range(n):
        for j in range(i,n):
            b=S.zeros(n); b[i,j]=b[j,i]=1; E.append(J*b*U)
    # Assign orthogonal lattice basis vectors to oriented edges of a tree.
    # Reduced incidence is unimodular by leaf elimination.
    N=len(E); B=[S.zeros(n) for _ in range(N+1)]; incidence=S.zeros(N+1,N)
    for k,e in enumerate(E,1):
        parent=rng.randrange(k); sign=rng.choice([-1,1])
        B[k]+=sign*e; B[parent]-=sign*e
        incidence[k,k-1]=sign; incidence[parent,k-1]=-sign
    assert abs(incidence[1:,:].det())==1
    sums,groups=graph_extract(G,B)
    P=[J*S.diag(*[int(i==j) for j in range(n)])*U for i in range(n)]
    projector_checks(G,P)
    M=S.Matrix.hstack(*[S.Matrix(list(x)) for x in sums]); T=S.Matrix.hstack(*[S.Matrix(list(x)) for x in P])
    assert rank(M)==rank(T)==rank(M.row_join(T))==n
    assert len(groups)==n+1
    print(f'Graph rank {n}, lift {N}, components {len(groups)}: exact planted-algebra match PASS')


def gap_check():
    n=2; G=S.eye(n); I=S.eye(n); count=0; projectors=[]
    for a,b,c in itertools.product(range(-3,4),repeat=3):
        X=S.Matrix([[a,b],[b,c]])
        f=(X*X-X).trace(); assert f>=0 and f%2==0
        assert (f==0)==(X*X==X)
        assert norm2(X-I/2)==S.Rational(n,4)+f
        if f==0: projectors.append(X)
        if X.trace()==1:
            assert norm2(X-I/2)==S.Rational(1,2)+f
            if f: assert norm2(X-I/2)>=S.Rational(5,2)
        count+=1
    assert len(projectors)==4
    for A in [S.diag(1,-1), S.Matrix([[2,3],[3,-2]])]:
        target=I/2+A/(8*n*(1+norm2(A)))
        vals=[]
        for a,b,c in itertools.product(range(-3,4),repeat=3):
            X=S.Matrix([[a,b],[b,c]]); vals.append((norm2(X-target),X))
        best=min(x[0] for x in vals)
        assert all(X*X==X for val,X in vals if val==best)
    print(f'Arithmetic gap and trace-one identity: {count} exact symmetric integer candidates PASS')
    print('Perturbed target: bounded exhaustive checks PASS (not a general CVP proof)')


def regroup_check():
    G=S.eye(4); X=S.diag(S.Matrix([[0,1],[1,0]]),S.Matrix([[0,2],[2,0]]))
    Q,P,edges,D=spectral_regroup(G,X)
    projector_checks(G,P)
    assert len(Q)==4 and len(P)==2
    assert sorted(p.trace() for p in P)==[2,2]
    # Compare all subsets of rational primary idempotents with the graph output.
    allowed=[]
    for b in itertools.product([0,1],repeat=len(Q)):
        q=sum((v*x for v,x in zip(b,Q)),S.zeros(4))
        if all(x.q==1 for x in q): allowed.append(q)
    expected=[sum((v*x for v,x in zip(b,P)),S.zeros(4)) for b in itertools.product([0,1],repeat=len(P))]
    assert len(allowed)==len(expected) and all(any(a==b for b in expected) for a in allowed)
    _,P,_,_=spectral_regroup(S.eye(2),S.Matrix([[0,1],[1,1]])); assert P==[S.eye(2)]
    print('Spectral regrouping: all 16 subset candidates checked; irreducible-field counterexample PASS')

if __name__=='__main__':
    verify_leech()
    gap_check(); regroup_check()
    for n in (2,3,4,6,8): tree_superbase(n,20261203+n)
    print('PASS. Scope: finite arithmetic and planted-superbase tests only; no complexity or general construction claim.')
