#!/usr/bin/env python3
"""Supplementary exact-arithmetic checks for the ADE cubic spectral-frame paper.

Requires SymPy.  This script is NOT used in any proof in the paper.
It checks polynomial identities, the eight-term cyclic Hessian kernel,
the universal triangle census against explicit A_n and D_n roots,
and the full Riesz affine constant in general (d,h).
"""
from itertools import combinations
from math import factorial
import sys
import sympy as sp


def falling(x, k):
    return sp.prod(x - j for j in range(k))


def cumulants(frames):
    t = sp.Symbol('t')
    gen = sum(frames[k] * t**k / factorial(k) for k in range(5))
    series = sp.series(sp.log(gen), t, 0, 5).removeO().expand()
    return [sp.factor(factorial(k) * series.coeff(t, k)) for k in range(1, 5)]


def rooted_triangle_table(d, h):
    m0, b = (d - 4) * h + 6, 2 * h - 4
    u = m0 * b - 4 * (h - 2) * (h - 3)
    entries = [
        (2, 2, 2, 1), (2, 1, 1, b), (2, 0, 0, m0),
        (1, 1, 2, b), (1, 1, -1, b), (1, 1, 1, b*(h-3)),
        (1, 1, 0, b*(h-3)), (1, 0, 1, b*(h-3)),
        (1, 0, -1, b*(h-3)), (1, 0, 0, b*(m0-2*h+6)),
        (0, 0, 2, m0), (0, 0, -2, m0),
        (0, 0, 1, u), (0, 0, -1, u),
        (0, 0, 0, m0*m0 - 2*m0*(2*h-3) + 8*(h-2)*(h-3)),
    ]
    result = {}
    for a, b, c, value in entries:
        seen = {(a, b, c)}
        frontier = [(a, b, c)]
        while frontier:
            x, y, z = frontier.pop()
            for nxt in ((y, x, z), (-x, y, -z), (x, -y, -z)):
                if nxt not in seen:
                    seen.add(nxt)
                    frontier.append(nxt)
        for key in seen:
            if key in result:
                assert sp.simplify(result[key]-value) == 0
            result[key] = value
    assert sp.simplify(sum(result.values()) - (d*h)**2) == 0
    return result


def roots_A(n):
    out = []
    for i in range(n + 1):
        for j in range(n + 1):
            if i != j:
                out.append(tuple(int(k == i)-int(k == j) for k in range(n + 1)))
    return out


def roots_D(n):
    out = []
    for i, j in combinations(range(n), 2):
        for a in (-1, 1):
            for b in (-1, 1):
                out.append(tuple(a*int(k == i)+b*int(k == j) for k in range(n)))
    return out


def dot(v, w):
    return sum(a*b for a, b in zip(v, w))


def check_enumeration(roots, d, h):
    table = rooted_triangle_table(d, h)
    for x in roots:
        observed = {}
        for y in roots:
            for z in roots:
                key = (dot(x, y), dot(x, z), dot(y, z))
                observed[key] = observed.get(key, 0) + 1
        for key in set(observed) | set(table):
            assert observed.get(key, 0) == table.get(key, 0), (d, h, key)


def kernel(u, v, w, d, px, py, pz, qx, qy, qz):
    # x-y has p=px, y-z has p=py, z-x has p=pz.
    L = 1 - u*u - v*v - w*w + u*v*w
    return (
        64*(w-u*v)*(u-v*w)*(v-u*w)*qx*qy*qz
        -32*((v-u*w)*(1-u*u-w*w+u*v*w)*qx*qy*pz
             +(u-v*w)*(1-w*w-v*v+u*v*w)*qy*qz*px
             +(w-u*v)*(1-v*v-u*u+u*v*w)*qz*qx*py)
        -16*((u*L+v*w)*qx*py*pz
             +(w*L+u*v)*qy*pz*px+(v*L+u*w)*qz*px*py)
        -8*(d-3+u*u+v*v+w*w-u*v*w)*px*py*pz
    )


def check_kernel():
    u,v,w,d = sp.symbols('u v w d')
    px,py,pz,qx,qy,qz = sp.symbols('px py pz qx qy qz')
    gram = sp.Matrix([[1,u,v],[u,1,w],[v,w,1]])
    eye = sp.eye(3)
    e = [eye[:,i] for i in range(3)]
    project = [eye - e[i]*gram[i,:] for i in range(3)]
    bxy = 4*qx*e[1]*gram[0,:]-2*px*eye
    byz = 4*qy*e[2]*gram[1,:]-2*py*eye
    bzx = 4*qz*e[0]*gram[2,:]-2*pz*eye
    direct = sp.trace(project[0]*bxy*project[1]*byz*project[2]*bzx*project[0])
    direct += (d-3)*(-2*px)*(-2*py)*(-2*pz)
    assert sp.expand(direct-kernel(u,v,w,d,px,py,pz,qx,qy,qz)) == 0


def check_ADE():
    n = sp.Symbol('n')
    nA = [falling(n+1,2*k) for k in range(5)]
    nD = [factorial(k)*sum(sp.Rational(2**(k-j),factorial(j)*factorial(k-2*j))
                              * falling(n,2*k-2*j) for j in range(k//2+1))
          for k in range(5)]
    for name, frames, r, h, S in [
        ('A',nA,n,n+1,sp.Rational(1,8)*n*(n+1)*(n-1)*(n*n+4*n+15)),
        ('D',nD,n,2*n-2,2*n*(n-1)*(n-2)*(n*n-4*n+12)),
    ]:
        L = cumulants(frames)
        rhs = [r*h, -2*r*h*(2*h-3), 8*r*h*(5*h*h-17*h+15)]
        assert all(sp.factor(L[k]-rhs[k]) == 0 for k in range(3)), name
        assert sp.factor(L[3]+320*S+8*r*h*(79*h**3-474*h*h+890*h-510)) == 0, name
    for frames, r, h, k3 in [
        ([1,72,2160,25920,51840],6,12,8640),
        ([1,126,7560,196560,1814400],7,18,24576),
        ([1,240,30240,1814400,47174400],8,30,96768),
    ]:
        L = cumulants(frames)
        S = sp.Rational(r*h*k3, 64)
        assert L[0] == r*h
        assert L[1] == -2*r*h*(2*h-3)
        assert L[2] == 8*r*h*(5*h*h-17*h+15)
        assert L[3]+320*S == -8*r*h*(79*h**3-474*h*h+890*h-510)


def check_C_riesz():
    d, h = sp.symbols('d h')
    T = rooted_triangle_table(d,h)
    p = lambda s: -sp.Rational(2,s**3)
    q = lambda s: sp.Rational(6,s**4)
    cyclic = sum(count*kernel(sp.Rational(a,2),sp.Rational(b,2),sp.Rational(c,2),
                            d,p(2-a),p(2-c),p(2-b),q(2-a),q(2-c),q(2-b))
                 for (a,b,c),count in T.items() if a!=2 and b!=2 and c!=2)
    c0 = 2*(h-2)*(p(1)-p(3))-2*p(4)+4*h*q(2)
    delta = q(1)-2*q(2)+q(3)
    M0 = (d-4)*h+6
    alpha = 4*(2*(h-2)*(p(1)**2+p(3)**2)+M0*p(2)**2+p(4)**2+h*(4*q(2)**2-p(2)**2))
    beta = 4*(3*(q(1)**2+q(3)**2)+2*(p(1)*q(1)-p(3)*q(3))-
              p(1)**2-p(3)**2-8*q(2)**2+2*p(2)**2)
    tau1, tau2 = sp.Rational(3,2)*(h-2), sp.Rational(1,4)*(h-2)*(h+6)
    P = d*h*(d**3*h**3-12*d**2*h**2*(2*h-3)
             +4*d*h*(52*h*h-172*h+147)-8*(79*h**3-474*h*h+890*h-510))
    C = d*h*((d-1)*c0**3+12*c0*c0*delta*tau1+48*c0*delta**2*tau2
        +3*((d-1)*c0*alpha+(c0*beta+4*delta*alpha)*tau1+4*delta*beta*tau2)
        +cyclic)+delta**3*P/5
    proposed = (
        d**3*(608350000*h**3+2519424*h**2)
        +d**2*(-14600400000*h**3+21952668096*h**2-87130080*h)
        +d*(126274606976*h**3-417147648496*h**2+357303728300*h-1455560925)
        -389655077376*h**3+2325460399008*h**2
        -3284545014960*h+354020805477
    )
    assert sp.cancel(C-d*h*proposed/20155392) == 0
    print('Universal Riesz cubic polynomial: verified exactly')


def check_direct_hessians():
    """Independent full-matrix checks, using exact rational entry assembly.

    The matrix is represented in ambient R^d coordinates at each root;
    zero normal directions do not contribute to traces.  This is slower
    than the symbolic checks, and is run only with --operators.
    """
    import numpy as np
    for n, expected in [
        (4, (sp.Rational(15659,6), sp.Rational(194812105,1296),
             sp.Rational(2787706311547,279936))),
        (5, (sp.Rational(53090,9), sp.Rational(368155595,972),
             sp.Rational(6063758417755,209952))),
    ]:
        roots = [sp.Matrix(v) for v in roots_D(n)]
        size, h = len(roots), 2*n-2
        prime = lambda j: -sp.Rational(2, j**3)
        second = lambda j: sp.Rational(6, j**4)
        delta = second(1)-2*second(2)+second(3)
        c0 = 2*(h-2)*(prime(1)-prime(3))-2*prime(4)+4*h*second(2)
        eye = sp.eye(n)
        projectors = [eye-sp.Rational(1,2)*a*a.T for a in roots]
        full = sp.zeros(size*n, size*n)
        for i, a in enumerate(roots):
            px, Ax = projectors[i], sp.zeros(n,n)
            for j, b in enumerate(roots):
                ab = dot(list(a), list(b))
                if ab == 1:
                    vec = px*b
                    Ax += sp.Rational(1,2)*vec*vec.T
                if i == j:
                    continue
                s = 2-ab
                block = px*(2*second(s)*b*a.T-2*prime(s)*eye)*projectors[j]
                for k in range(n):
                    for ell in range(n):
                        full[i*n+k,j*n+ell] = block[k,ell]
            block = c0*px+4*delta*Ax
            for k in range(n):
                for ell in range(n):
                    full[i*n+k,i*n+ell] = block[k,ell]
        assert full == full.T
        scale = sp.Integer(13824)
        integer_matrix = full*scale
        assert all(z.q == 1 for z in integer_matrix)
        A = np.array(integer_matrix).astype(object)
        A2 = A@A
        A3 = A2@A
        obtained = (
            sp.Rational(sum(A[i,i] for i in range(size*n)), scale),
            sp.Rational(sum(A2[i,i] for i in range(size*n)), scale**2),
            sp.Rational(sum(A3[i,i] for i in range(size*n)), scale**3),
        )
        assert obtained == expected, (n,obtained,expected)
        print(f'Full rational {size*n}x{size*n} D{n} Hessian: all three traces verified')


def main():
    check_ADE()
    print('ADE frame cumulants, neighbor spectra: verified exactly')
    check_enumeration(roots_A(5),5,6)
    check_enumeration(roots_D(4),4,6)
    check_enumeration(roots_D(6),6,10)
    print('Rooted Gram-triangle census for A5, D4, D6: verified exactly')
    check_kernel()
    print('All eight terms of cyclic Hessian kernel: verified symbolically')
    check_C_riesz()
    if '--operators' in sys.argv:
        check_direct_hessians()
    print('ALL EXACT CHECKS PASSED')


if __name__ == '__main__':
    main()
