#!/usr/bin/env python3
"""SRFP311T1 single-file exact certificate for the universal D_n lowest-mode theorem.

Site companion for dn_lowest_mode.html / .pdf (November, 2026).
Python 3 and SymPy are required. No floating point is used in assertions.

Usage:
    python dn_lowest_mode.py
    python dn_lowest_mode.py --check rank
    python dn_lowest_mode.py --check positivity

The program checks exact finite identities and exact positivity coefficients;
the all-rank inference also invokes the degree <= 3 orbit-polynomial lemma
in the paper. Reproduction is not a substitute for independent peer review.
"""
import argparse
import time


# ---- Group irrep: original exact checker from verify_irrep_dimensions.py ----
def check_irrep():
    """Exact polynomial dimension check of the claimed W(B_n) decomposition."""
    import sympy as S
    n=S.symbols('n',integer=True,positive=True)
    C=lambda a,b:S.prod(a-j for j in range(b))/S.factorial(b)
    dims={
    'Rot':C(n,2), 'B2':C(n,2), 'B3':n-1,
    'B4':2*C(n,3), 'B5':C(n,3),
    'B6 Cubic':C(n,2)*(n-3), 'B7':C(n,2)*(n-3),
    'B8':C(n-1,2), 'B9':C(n,2),
    'B10':n*(n-1)*(n-4)/2,
    'Block 1':2*n,'Block 2':2*n*(n-2),
    }
    assert S.simplify(sum(dims.values())-2*n*(n-1)**2)==0
    print('PASS: total multiplicity polynomial equals 2*n*(n-1)^2 identically.')
    print('This dimension identity alone does not prove irreducibility.')

# ---- Group scalar: original exact checker from verify_scalar_gaps.py ----
def check_scalar():
    """Symbolically verify all eight scalar Gaussian gaps in the paper.

    All algebra is exact in Q[n,alpha,q], with q=e^{-alpha} substituted
    only AFTER symbolic cancellation. Positivity of the factorized formulas
    is proved in Lemma 4.1 of the accompanying manuscript.
    """
    import sympy as S
    n, alpha, q = S.symbols('n alpha q')
    u1, u2, u3, u4 = (-alpha*q**j for j in (1,2,3,4))
    a,b,c = (alpha**2*q**j for j in (1,2,3))
    delta=u1-u3
    cubic=4*(n-1)*delta + 8*(n-2)*b + 4*(a+c)
    values={
     'B2':4*delta+12*(a+c)+16*(n-3)*b,
     'B3':2*(n-2)*delta+6*(n-2)*(a+c)+16*b,
     'B4':4*(n-2)*delta+4*(u2-u4)+4*a+8*(n-3)*b+12*c,
     'B5':4*(n-2)*delta+4*(u2-u4)+16*a+8*(n-3)*b,
     'B7':4*(n-1)*delta+12*(a+c)+8*(n-4)*b,
     'B8':4*(n-1)*delta+4*(n-3)*(a+c)+16*b,
     'B9':4*(n-1)*delta+4*(n-1)*(a+c),
     'B10':4*n*u1-12*u2-4*(n-4)*u3-4*u4+8*(a+c)+8*(n-3)*b
    }
    formulas={
     'B2':(n-2)*(1-q*q)+2*alpha*(1+(n-4)*q+q*q),
     'B3':n*(1-q*q)/2+alpha*((3*n-8)*(1-q)**2+2*n*q)/2,
     'B4':(1-q)*(1-q*q-2*alpha*q),
     'B5':(1-q)*(1-q*q+3*alpha+alpha*q),
     'B7':2*alpha*(1-q)**2,
     'B8':alpha*(n-4)*(1-q)**2,
     'B9':alpha*(n-2)*(1-q)**2,
     'B10':(1-q)**2*(alpha+q-1)
    }
    for key, val in values.items():
        assert S.expand(val-cubic-4*alpha*q*formulas[key]) == 0, key
        print('PASS', key)
    print('PASS: eight scalar gap identities over Q[n,alpha,q].')

# ---- Group rank: original exact checker from verify_all_rank_blocks.py ----
def check_rank():
    """Independent all-integer checks of user-supplied D_n formula representatives.

    These checks verify finitely many ranks, NOT their all-rank symbolic proof.
    Uses no floating point.  The tangent Hessian is constructed from the
    second variation of the unordered-pair spherical energy.
    """
    import itertools

    def roots(n):
        R=[]; lookup={}
        for i in range(n):
            for j in range(i+1,n):
                for a,b in itertools.product((1,-1),repeat=2):
                    s=[0]*n; s[i]=a; s[j]=b
                    lookup[(i,j,a,b)]=len(R); R.append(s)
        return R,lookup

    def field(n,kind,R,lookup):
        v=[[0]*n for _ in R]
        def add(i,j,a,b,k,c):v[lookup[(i,j,a,b)]][k]+=c
        signs=list(itertools.product((1,-1),repeat=2))
        if kind=='B4':
            for a,b in signs:
                add(0,1,a,b,2,-a*b); add(0,2,a,b,1,a*b)
        elif kind=='B5':
            for a,b in signs:
                add(0,1,a,b,2,a*b); add(0,2,a,b,1,a*b); add(1,2,a,b,0,a*b)
        elif kind=='Cubic':
            for a,b in signs:
                add(0,3,a,b,1,a);add(0,2,a,b,1,-a)
                add(1,2,a,b,0,a);add(1,3,a,b,0,-a)
        elif kind in ('Rot','B2','B7','B9'):
            # Sign-character sector with support {0,1}; all fields integer.
            # A_k = sum_{a,b} a |x_0k^{ab}> otimes e1
            # B_k = sum_{a,b} a |x_1k^{ab}> otimes e0
            # C = sum_{a,b} ab |x_01^{ab}> otimes sqrt(2)u_01^{ab}.
            if kind in ('Rot','B2','B9'):
                for k in range(2,n):
                    for a,b in signs:
                        add(0,k,a,b,1,a)
                        add(1,k,a,b,0,(1 if kind=='B2' else -1)*a)
                if kind in ('Rot','B9'):
                    c=(-1 if kind=='Rot' else n-2)
                    for a,b in signs:
                        add(0,1,a,b,0,c*b)
                        add(0,1,a,b,1,-c*a)
            else:
                # B7=A_2-A_3+B_2-B_3 (symmetric under swapping 0,1)
                for a,b in signs:
                    add(0,2,a,b,1,a);add(0,3,a,b,1,-a)
                    add(1,2,a,b,0,a);add(1,3,a,b,0,-a)
        elif kind=='B3':
            # whole field multiplied by sqrt(2), preserving eigenvector property
            for j in range(1,n):
                for a,b in signs:
                    add(0,j,a,b,0,a);add(0,j,a,b,j,-b)
        elif kind=='B8':
            for a,b in signs:
                add(0,1,a,b,0,(n-4)*a);add(0,1,a,b,1,-(n-4)*b)
            for k in range(4,n):
                for a,b in signs:
                    add(0,k,a,b,0,-a);add(0,k,a,b,k,b)
                    add(1,k,a,b,1,a);add(1,k,a,b,k,-b)
        elif kind=='B10':
            for a,b in signs:
                add(1,3,a,b,0,n-4);add(2,3,a,b,0,-(n-4))
                for k in range(4,n):
                    add(1,k,a,b,0,-1);add(2,k,a,b,0,1)
        elif kind=='1a':
            for j in range(1,n):
                for a,b in signs:
                    add(0,j,a,b,0,-1);add(0,j,a,b,j,a*b)
        elif kind=='1b':
            for i in range(1,n):
                for j in range(i+1,n):
                    for a,b in signs:add(i,j,a,b,0,1)
        elif kind=='2a':
            for a,b in signs:
                add(0,1,a,b,0,1);add(0,1,a,b,1,-a*b)
                add(0,2,a,b,0,-1);add(0,2,a,b,2,a*b)
        elif kind=='2b':
            for k in range(3,n):
                for a,b in signs:
                    add(1,k,a,b,0,-1);add(2,k,a,b,0,1)
        else:raise KeyError(kind)
        assert all(sum(a*b for a,b in zip(r,vi))==0 for r,vi in zip(R,v))
        return v

    def hessian_twice(n,R,V,k,rows=None):
        """Return 2*H_{f'_d or f''_d}(V), exact integers; k = 0..7."""
        out=[[0]*n for _ in R]
        for i in (range(len(R)) if rows is None else rows):
            r=R[i]
            w=[0]*n
            for j,s in enumerate(R):
                if i==j:continue
                rs=sum(a*b for a,b in zip(r,s)); d=2-rs
                if k<4 and d==k+1:
                    for a in range(n):w[a]+=rs*V[i][a]-2*V[j][a]
                if k>=4 and d==k-3:
                    diff=[a-b for a,b in zip(r,s)]
                    dot=sum(diff[a]*(V[i][a]-V[j][a]) for a in range(n))
                    for a in range(n):w[a]+=2*diff[a]*dot
            rw=sum(a*b for a,b in zip(r,w))
            out[i]=[2*w[a]-r[a]*rw for a in range(n)]
        return out

    def scalar(kind,n):
        return {
          'Rot':[0]*8,
          'B2':[4,0,-4,0,12,16*(n-3),12,0],
          'B7':[4*(n-1),0,-4*(n-1),0,12,8*(n-4),12,0],
          'B9':[4*(n-1),0,-4*(n-1),0,4*(n-1),0,4*(n-1),0],
          'B4':[4*(n-2),4,-4*(n-2),-4,4,8*(n-3),12,0],
          'B5':[4*(n-2),4,-4*(n-2),-4,16,8*(n-3),0,0],
          'Cubic':[4*(n-1),0,-4*(n-1),0,4,8*(n-2),4,0],
          'B3':[2*(n-2),0,-2*(n-2),0,6*(n-2),16,6*(n-2),0],
          'B8':[4*(n-1),0,-4*(n-1),0,4*(n-3),16,4*(n-3),0],
          'B10':[4*n,-12,-4*(n-4),-4,8,8*(n-3),8,0],
        }[kind]

    def block(kind,n):
        if kind==1:
            a=[2*(n-2),0,-6*(n-2),-4,6*(n-2),8,2*(n-2),0]
            b=[-4*(n-4),-4*(n*n-7*n+13),-4*(3*n-8),-4,8,8*(n-3),8,0]
            c=[1,n-3,1,0,1,0,-1,0]
            # H(va) = a va -8c vb, H(vb) = b vb -2(n-2)c va
            return a,b,[8*t for t in c],[2*(n-2)*t for t in c]
        a=[4*n-6,0,-(4*n-10),-4,4*n-10,8,4*n-6,0]
        b=[12,4*(2*n-9),-(8*n-28),-4,8,8*(n-3),8,0]
        c=[1,-2,1,0,1,0,-1,0]
        # H(va) = a va -4c vb, H(vb) = b vb -2(n-3)c va
        return a,b,[4*t for t in c],[2*(n-3)*t for t in c]

    def assert_identity(actual,term1,c1,term2=None,c2=0,rows=None,maxcoord=None):
        for i in (range(len(actual)) if rows is None else rows):
            for a in range(len(actual[i]) if maxcoord is None else maxcoord):
                rhs=2*c1*term1[i][a]+(2*c2*term2[i][a] if term2 is not None else 0)
                if actual[i][a]!=rhs:
                    raise AssertionError((i,a,actual[i][a],rhs))

    def norm2(V):return sum(a*a for row in V for a in row)

    if True:
        for n in (5,6,7,8,9,10):
            R,I=roots(n)
            if n>=7:
                # Tail W(B_{n-4}) symmetry: 24 pairs among first 4 indices,
                # 8 mixed-root representatives (tail sign chosen +),
                # and one all-tail pair representative.
                rows=[I[(i,j,a,b)] for i in range(4) for j in range(i+1,4)
                      for a,b in itertools.product((1,-1),repeat=2)]
                rows += [I[(i,4,a,1)] for i in range(4) for a in (1,-1)]
                rows += [I[(4,5,1,1)]]
                maxcoord=7 # first 4 named positions, two tail root positions, one other
            else:
                rows=None;maxcoord=None
            print(f'n={n}: {len(R)} roots, {len(R)*(n-1)} tangent dimensions')
            for kind in ('Rot','B2','B3','B4','B5','Cubic','B7','B8','B9','B10'):
                v=field(n,kind,R,I)
                assert norm2(v)>0
                for k,ev in enumerate(scalar(kind,n)):
                    assert_identity(hessian_twice(n,R,v,k,rows),v,ev,rows=rows,maxcoord=maxcoord)
                print(f'  {kind:6s}: passed all 8 jet identities (integer arithmetic)')
            for kind in (1,2):
                va=field(n,str(kind)+'a',R,I)
                vb=field(n,str(kind)+'b',R,I)
                a,b,c,d=block(kind,n)
                assert sum(p*q for x,y in zip(va,vb) for p,q in zip(x,y))==0
                for k in range(8):
                    assert_identity(hessian_twice(n,R,va,k,rows),va,a[k],vb,c[k],rows=rows,maxcoord=maxcoord)
                    assert_identity(hessian_twice(n,R,vb,k,rows),vb,b[k],va,d[k],rows=rows,maxcoord=maxcoord)
                print(f'  block{kind}: passed 16 jet identities, norms={norm2(va)},{norm2(vb)}')
        print('PASS: exact identities n=5,6 and W(B_{n-4}) orbit representatives at n=7,8,9,10.')
        print('All-n certification uses a separate polynomial degree <= 3 lemma.')

# ---- Group positivity: original exact checker from verify_gaussian_positivity.py ----
def check_positivity():
    """Exact audit of the proposed D_n Gaussian shifted-block inequalities.

    This verifies the algebraic consequences of the user-supplied block formulas,
    NOT that those formulas represent the full D_n Hessian for all n.
    Requires sympy. All coefficient checks use exact integers/rationals.
    """
    from collections import defaultdict
    from fractions import Fraction
    from math import factorial
    import sympy as S

    alpha, q, n, m = S.symbols('alpha q n m')
    u, v, w, z = [-alpha*q**d for d in (1,2,3,4)]
    A, B, C = [alpha**2*q**d for d in (1,2,3)]
    lam = 4*(n-1)*(u-w)+4*(A+C)+8*(n-2)*B

    block1 = S.Matrix([
        [2*(n-2)*u -6*(n-2)*w -4*z +6*(n-2)*A+8*B+2*(n-2)*C,
         -4*S.sqrt(n-2)*(u+(n-3)*v+w+A-C)],
        [-4*S.sqrt(n-2)*(u+(n-3)*v+w+A-C),
         -4*(n-4)*u -4*(n*n-7*n+13)*v -4*(3*n-8)*w -4*z
           +8*A+8*(n-3)*B+8*C]])
    block2 = S.Matrix([
        [(4*n-6)*u-(4*n-10)*w-4*z+(4*n-10)*A+8*B+(4*n-6)*C,
         -2*S.sqrt(2*(n-3))*(u-2*v+w+A-C)],
        [-2*S.sqrt(2*(n-3))*(u-2*v+w+A-C),
         12*u+4*(2*n-9)*v-(8*n-28)*w-4*z
           +8*A+8*(n-3)*B+8*C]])

    def as_terms(expr, factor):
        # Turn the (positive-scaled) entries/determinants into Z[m,alpha,q].
        poly = S.Poly(S.expand(S.cancel(expr).subs(n, m+5)*factor),alpha,q,m)
        result=[]
        for (degree_a, degree_q, degree_m), coeff in poly.terms():
            assert coeff.q == 1, (degree_a,degree_q,degree_m,coeff)
            assert degree_a <=2
            result.append((degree_a,degree_q,degree_m,int(coeff)))
        return result

    def falling(k,r):
        return factorial(k)//factorial(k-r)

    def coeff_at(terms, shift, dm, k):
        # k! times Taylor coefficient of m**dm * exp(shift*alpha) * expr.
        ans=0
        for pa,pq,pm,c in terms:
            if pm==dm and k>=pa:
                j=shift-pq
                assert j>=0
                ans += c*falling(k,pa)*j**(k-pa)
        return ans

    def tail_bounds(terms,shift,dm,k=12):
        # Largest exponent J and its exact contribution, versus termwise abs sum.
        triples=[(shift-pq,pa,c) for pa,pq,pm,c in terms if pm==dm]
        J=max(j for j,p,c in triples)
        lead=sum(c*falling(k,p)*J**(k-p) for j,p,c in triples if j==J)
        remainder=sum(abs(c)*falling(k,p)*j**(k-p)
                      for j,p,c in triples if j<J and k>=p)
        assert lead>0 and lead>remainder, (dm,J,lead,remainder)
        # P_J(k) = sum_p c_{J,p} k_falling_p / J**p is positive and
        # nondecreasing on [12,infinity) when all c_{J,p>=1} >= 0.
        assert all(c>=0 for j,p,c in triples if j==J and p>=1)
        return J,lead,remainder

    print('Exact Gaussian positivity audit: every test uses integer arithmetic.')
    print('name    m^d  first strictly positive Taylor index   leading J   exact abs-tail ratio at k=12')
    for num,block in ((1,block1),(2,block2)):
        shifted=(block-lam*S.eye(2)).applyfunc(lambda x:S.cancel(x/(4*alpha*q)))
        for title,expr,shift,factor in (
            ('11',shifted[0,0],3,2),
            ('22',shifted[1,1],3,1),
            ('det',S.cancel(shifted.det()),6,2)):
            terms=as_terms(expr,factor)
            assert max(pq for pa,pq,dm,c in terms)<=shift
            for dm in sorted({dm for pa,pq,dm,c in terms}):
                small=[coeff_at(terms,shift,dm,k) for k in range(12)]
                assert all(x>=0 for x in small), (num,title,dm,small)
                pos=[k for k,x in enumerate(small) if x>0]
                assert pos
                J,lead,rem=tail_bounds(terms,shift,dm)
                print(f'{num}{title:>3}     {dm:<2}    {pos[0]:>3}                               '
                      f'{J:>2}       {Fraction(rem,lead)}')

    print('CERTIFIED (conditional on correct Hessian block formulas):')
    print('  For each shifted 2x2 block and every n>=5, alpha>0,')
    print('  both diagonal entries and determinant are strictly positive.')
    print('Proof of tail: for k>=12, lower j<J terms have absolute ratio')
    print('  at successive k <= ((J-1)/J)*((k+1)/(k-1)) <= 65/66 < 1.')
    print('  The leading J-exponential contribution is positive and')
    print('  nondecreasing after division by J**k.')


def main():
    parser = argparse.ArgumentParser(description="Exact D_n spectral theorem verification")
    parser.add_argument('--check', choices=['all','irrep','scalar','rank','positivity'],
                        default='all', help='select exact verification group')
    args=parser.parse_args()
    groups=[('irrep',check_irrep),('scalar',check_scalar),('rank',check_rank),
            ('positivity',check_positivity)]
    run = groups if args.check=='all' else [g for g in groups if g[0]==args.check]
    started = time.perf_counter()
    print('SRFP311T1 | Universal D_n lowest mode | exact master verifier')
    for name,func in run:
        print('\n===== GROUP:',name,'=====')
        func()
    print('\nPASS:',len(run),'of',len(run),'requested exact verification groups completed')
    print('Elapsed wall time: %.2f s'%(time.perf_counter()-started))

if __name__ == '__main__':
    main()
