"""verify_box_and_e8.py -- checks for Sections 6 and 7 of Paper IV, version 2.
Section 6 (the 2x2 box, K = C): 20,000 random roots, exact Gaussian-integer arithmetic.
Section 7 (E8 as Hurwitz pairs, K = H): all 240 roots, exact rational arithmetic.
Usage: python3 verify_box_and_e8.py    (last line: "all checks passed: True")"""
import random, itertools
from fractions import Fraction as F
rng = random.Random(20261120)
ok = True

# ---------- Section 6: the box over C, exact over the Gaussian integers ----------
def box(t, a, u):                      # Phi(t; a, u) = [[t+a, u], [conj u, t-a]]
    return [[t + a, u], [u.conjugate(), t - a]]
def det(M): return M[0][0] * M[1][1] - M[0][1] * M[1][0]
def mul(A, B): return [[sum(A[i][k] * B[k][j] for k in range(2)) for j in range(2)] for i in range(2)]
def dag(A): return [[A[j][i].conjugate() for j in range(2)] for i in range(2)]
def gi(): return complex(rng.randint(-50, 50), rng.randint(-50, 50))
def nrm(z): return z.real**2 + z.imag**2               # exact on Gaussian integers (no square root)
def sq(x, y): return (nrm(x) + nrm(y), nrm(x) - nrm(y), 2 * x * y.conjugate())
def eta(X, Y): return X[0]*Y[0] - X[1]*Y[1] - (X[2] * Y[2].conjugate()).real

c1 = c2 = c3 = c4 = True
for _ in range(20000):
    x, y, x1, y1 = gi(), gi(), gi(), gi()
    t, a, u = sq(x, y)
    M = box(t, a, u)
    P = [[2*x*x.conjugate(), 2*x*y.conjugate()], [2*y*x.conjugate(), 2*y*y.conjugate()]]
    c1 &= M == P                                         # Phi(sq psi) = 2 psi psi^dagger
    X = (gi().real, gi().real, gi())
    c2 &= det(box(*X)) == X[0]**2 - X[1]**2 - nrm(X[2])   # det = eta(X, X)
    Y = sq(x1, y1)
    c3 &= eta((t, a, u), Y) == 2 * nrm(x*y1 - y*x1)   # ghost of two roots = 2 |det[psi chi]|^2
    # SL(2, Z[i]) element acting: sq(A psi) = A sq(psi) A^dagger, det preserved
    q, r = complex(rng.randint(-3, 3), rng.randint(-3, 3)), complex(rng.randint(-3, 3), rng.randint(-3, 3))
    A = mul([[1 + 0j, q], [0j, 1 + 0j]], [[1 + 0j, 0j], [r, 1 + 0j]])   # a product of two shears, det 1
    Ax, Ay = A[0][0]*x + A[0][1]*y, A[1][0]*x + A[1][1]*y
    lhs = box(*sq(Ax, Ay)); rhs = mul(mul(A, M), dag(A))
    c4 &= lhs == rhs and det(lhs) == det(M) == 0
print("box: Phi(sq psi) = 2 psi psi^dagger on 20,000 Gaussian-integer roots:", c1)
print("box: det Phi(X) = eta(X, X):", c2)
print("box: eta(sq psi, sq chi) = 2 |x y1 - y x1|^2:", c3)
print("box: sq(A psi) = A sq(psi) A^dagger for unimodular A, and det stays 0:", c4)
ok &= c1 and c2 and c3 and c4

# ---------- Section 7: E8 as Hurwitz pairs ----------
def qm(a, b):
    a0, a1, a2, a3 = a; b0, b1, b2, b3 = b
    return (a0*b0 - a1*b1 - a2*b2 - a3*b3, a0*b1 + a1*b0 + a2*b3 - a3*b2,
            a0*b2 - a1*b3 + a2*b0 + a3*b1, a0*b3 + a1*b2 - a2*b1 + a3*b0)
def cj(a): return (a[0], -a[1], -a[2], -a[3])
def nm(a): return sum(v*v for v in a)
def hurwitz(a): return all(v.denominator == 1 for v in a) or all(v.denominator == 2 for v in a)
def even_ideal(a): return hurwitz(a) and nm(a) % 2 == 0      # (1+i)H = Hurwitz elements of even norm

roots = set()
for i, j in itertools.combinations(range(8), 2):
    for si in (1, -1):
        for sj in (1, -1):
            v = [F(0)] * 8; v[i] = F(si); v[j] = F(sj); roots.add(tuple(v))
for s in itertools.product((1, -1), repeat=8):
    if s.count(-1) % 2 == 0:
        roots.add(tuple(F(z, 2) for z in s))
units = [u for u in itertools.product([F(z, 2) for z in range(-2, 3)], repeat=4) if nm(u) == 1 and hurwitz(u)]
e1 = len(roots) == 240 and len(units) == 24
e2 = all(hurwitz(r[:4]) and hurwitz(r[4:]) and even_ideal(tuple(p - q for p, q in zip(r[:4], r[4:]))) for r in roots)
fib = {}
for r in roots:
    x, y = r[:4], r[4:]
    c = (nm(x) + nm(y), nm(x) - nm(y)) + tuple(2 * v for v in qm(x, cj(y)))
    fib.setdefault(c, set()).add(r)
expected = set()
for k in range(5):
    for s in (2, -2):
        v = [F(0)] * 5; v[k] = F(s); expected.add((F(2),) + tuple(v))
e3 = set(fib) == expected and all(len(f) == 24 for f in fib.values())
e4 = all(c[0]**2 == c[1]**2 + sum(v*v for v in c[2:]) for c in fib)
e5 = all({tuple(qm(r[:4], g)) + tuple(qm(r[4:], g)) for g in units} == f for f in fib.values() for r in [next(iter(f))])
print("E8: 240 roots, 24 Hurwitz units:", e1)
print("E8: every root is a pair of Hurwitz quaternions with difference in (1+i)H:", e2)
print("E8: the square of the 240 roots is exactly the 10 cuts (2; +-2 e_k), 24 roots over each:", e3)
print("E8: each image is a cut:", e4)
print("E8: each fibre is one orbit of right multiplication by the 24 Hurwitz units:", e5)
ok &= e1 and e2 and e3 and e4 and e5
print("all checks passed:", ok)
