#!/usr/bin/env python3
"""
Guideng Math Paper 22.  The Share of a Root.
Numerical verification of every statement.  Requires numpy only.

Conventions (as in Papers 4, 5, 17):
  a number of K is a real array of k = 1, 2, 4, 8 entries; the product is the doubling
      (a,b)(c,d) = (ac - conj(d) b,  da + b conj(c));
  a root is psi = (x, y); its cut is c(psi) = (|x|^2+|y|^2 ; |x|^2-|y|^2 , 2 x conj(y));
  X = (t; a, u) acts by  G(X)(x,y) = ((t+a)x + u y,  conj(u) x + (t-a) y).
"""
import numpy as np, sys

rng = np.random.default_rng(22)
TOL = 1e-9
NAME = {1: 'R', 2: 'C', 4: 'H', 8: 'O'}
results = []

def check(label, cond):
    results.append(bool(cond))
    print('[%s] %2d. %s' % ('ok' if cond else 'FAIL', len(results), label))

ok = lambda a, b: np.allclose(a, b, atol=TOL)

def conj(x):
    c = -x.copy(); c[0] = x[0]; return c

def mul(x, y):
    n = len(x)
    if n == 1: return x * y
    h = n // 2; a, b, c, d = x[:h], x[h:], y[:h], y[h:]
    return np.concatenate([mul(a, c) - mul(conj(d), b), mul(d, a) + mul(b, conj(c))])

asc = lambda a, b, c: mul(mul(a, b), c) - mul(a, mul(b, c))
re = lambda x: x[0]

def cut(p):
    k = len(p) // 2; x, y = p[:k], p[k:]
    return np.concatenate([[x @ x + y @ y, x @ x - y @ y], 2 * mul(x, conj(y))])

eta = lambda X, Y: X[0] * Y[0] - X[1:] @ Y[1:]
sig = lambda X: np.concatenate([[X[0]], -X[1:]])
flat = lambda X: np.concatenate([[-X[0]], X[1:]])

def G(X, k):
    def act(p):
        x, y = p[:k], p[k:]; t, a, u = X[0], X[1], X[2:]
        return np.concatenate([(t + a) * x + mul(u, y), mul(conj(u), x) + (t - a) * y])
    return np.column_stack([act(e) for e in np.eye(2 * k)])

def unit(v): return v / np.linalg.norm(v)

# ---------------------------------------------------------------- Sections 3, 4: one root
for k in (1, 2, 4, 8):
    nm = NAME[k]; r = {j: True for j in range(8)}
    for _ in range(60):
        psi, chi = rng.normal(size=2 * k), rng.normal(size=2 * k)
        X = cut(chi); t = X[0]; c = cut(psi); g = c[0]
        Pi = G(X, k) / (2 * t); part = Pi @ psi
        r[0] &= ok(Pi @ Pi, Pi) and ok(Pi, Pi.T)
        P = part @ part
        r[1] &= ok(P, (X @ c) / (2 * t)) and ok(P, g - eta(X, c) / (2 * t)) and -TOL <= P <= g + TOL
        Q = (sig(X) @ c) / (2 * t)
        r[2] &= ok(P + Q, g) and ok(G(X, k) / (2 * t) + G(sig(X), k) / (2 * t), np.eye(2 * k))
        if k < 8:
            row = mul(conj(chi[:k]), psi[:k]) + mul(conj(chi[k:]), psi[k:])
            r[3] &= ok(P, row @ row / (chi @ chi))
        n_, m_ = X[1:] / t, c[1:] / g; phi = np.arccos(np.clip(n_ @ m_, -1, 1))
        r[4] &= ok(P, g * np.cos(phi / 2) ** 2) and ok(Q, g * np.sin(phi / 2) ** 2)
        mir = psi @ G(flat(X), k) @ psi / (2 * t)
        r[5] &= ok(mir, -Q) and mir <= TOL
        r[6] &= ok(P - Q, (X[1:] @ c[1:]) / t) and ok((P + Q) ** 2, (P - Q) ** 2 + 4 * P * Q) \
                and ok(4 * P * Q, g * g * (1 - (n_ @ m_) ** 2))
        # two cuts: the spreads at X and at Y cannot both be small
        Y = cut(rng.normal(size=2 * k)); s = Y[0]; n2 = Y[1:] / s
        P2 = (Y @ c) / (2 * s); Q2 = g - P2
        bound = min(eta(X, Y), eta(X, sig(Y))) / (t * s)
        r[7] &= 4 * (P * Q + P2 * Q2) / g ** 2 >= bound - TOL
    check('%s  Theorem 3.2(a): G(X)/2t is a symmetric projection for a cut X' % nm, r[0])
    check('%s  Theorem 3.2(b): share = <X,c(psi)>/2t = |psi|^2 - ghost term/2t, between 0 and |psi|^2' % nm, r[1])
    check('%s  Theorem 3.2(c): share at X + share at the opposite cut = |psi|^2' % nm, r[2])
    if k < 8:
        check('%s  Theorem 3.2(d): share = |chi^dagger psi|^2 / |chi|^2' % nm, r[3])
    check('%s  Theorem 3.2(e): share = |psi|^2 cos^2(phi/2), opposite = |psi|^2 sin^2(phi/2)' % nm, r[4])
    e_out, e_in = np.linalg.norm(n_ - m_), np.linalg.norm(n_ + m_)      # last sample of the loop
    check('%s  Proposition 3.3: shares = |psi|^2 e\'^2/4, |psi|^2 e^2/4; ghost term = t|psi|^2 e^2/2; e^2+e\'^2 = 4' % nm,
          ok(P, g * e_in ** 2 / 4) and ok(Q, g * e_out ** 2 / 4) and ok(eta(X, c), t * g * e_out ** 2 / 2)
          and ok(e_out ** 2 + e_in ** 2, 4))
    check('%s  Theorem 4.2(a): mirror share = -(share at the opposite cut) <= 0' % nm, r[5])
    check('%s  Theorem 4.2(b): gross share = |psi|^2, net share = |psi|^2 cos phi, triangle equality, 4 spread = |psi|^4 sin^2 phi' % nm, r[6])
    check('%s  Theorem 4.3: 4(spread at X + spread at Y)/|psi|^4 >= min(ghost(X,Y), ghost(X,sigma Y))/(t t\')' % nm, r[7])
    # the bound is reached: the root whose cut bisects the two directions
    n1 = unit(rng.normal(size=k + 1)); n2 = unit(rng.normal(size=k + 1))
    m_ = unit(n1 + np.sign(n1 @ n2) * n2)
    lhs = 2 - (n1 @ m_) ** 2 - (n2 @ m_) ** 2
    check('%s  Theorem 4.3: the bound is reached on the bisector' % nm, ok(lhs, 1 - abs(n1 @ n2)))

# ---------------------------------------------------------------- Section 5: systems of cuts
for k in (1, 2, 4, 8):
    nm = NAME[k]; r = [True] * 3
    for _ in range(40):
        roots = [rng.normal(size=2 * k) for _ in range(5)]
        K = sum(cut(p) for p in roots); g = K[0]; m2 = eta(K, K)
        X = cut(rng.normal(size=2 * k)); t = X[0]; Pi = G(X, k) / (2 * t)
        r[0] &= ok(sum((Pi @ p) @ (Pi @ p) for p in roots), (X @ K) / (2 * t)) and m2 > -TOL
        kk = np.linalg.norm(K[1:]); P, Q = (g + kk) / 2, (g - kk) / 2
        Xbest = np.concatenate([[1.0], K[1:] / kk])
        r[1] &= ok((Xbest @ K) / 2, P) and ok((sig(Xbest) @ K) / 2, Q) and ok(P + Q, g) and ok(4 * P * Q, m2)
        r[2] &= Q - TOL <= (X @ K) / (2 * t) <= P + TOL
    check('%s  Theorem 5.2(a): the share of a system at X is <X,K>/2t; K is forward' % nm, r[0])
    check('%s  Theorem 5.2(b): largest and smallest shares P, Q: P+Q = gross, 4PQ = rest gross^2' % nm, r[1])
    check('%s  Theorem 5.2(b): every share lies between Q and P' % nm, r[2])

# ---------------------------------------------------------------- Section 6: two places
def place_one(x1, y1, x2, y2):          # columns (x1,y1), (x2,y2)
    return cut(np.concatenate([x1, y1])) + cut(np.concatenate([x2, y2]))
def place_two(x1, y1, x2, y2):          # rows, conjugated: (conj x1, conj x2), (conj y1, conj y2)
    return cut(np.concatenate([conj(x1), conj(x2)])) + cut(np.concatenate([conj(y1), conj(y2)]))

for k in (1, 2, 4, 8):
    nm = NAME[k]; r = [True] * 4
    for _ in range(100):
        x1, y1, x2, y2 = (rng.normal(size=k) for _ in range(4))
        K1, K2 = place_one(x1, y1, x2, y2), place_two(x1, y1, x2, y2)
        r[0] &= ok(K1[0], K2[0])
        r[1] &= ok(eta(K1, K1), 2 * eta(cut(np.concatenate([x1, y1])), cut(np.concatenate([x2, y2]))))
        r[2] &= ok(eta(K1, K1), eta(K2, K2))
        lam = rng.normal(size=k)                               # a product: second column = first times lam
        Kp = place_one(x1, y1, mul(x1, lam), mul(y1, lam))
        r[3] &= ok(eta(Kp, Kp), 0)
    check('%s  Theorem 6.2(a): the two places read the same gross' % nm, r[0])
    check('%s  Theorem 6.2(b): tie^2 = 2 x ghost term of the two columns' % nm, r[1])
    if k < 8:
        check('%s  Theorem 6.2(c): the two places read the same tie' % nm, r[2])
        check('%s  Theorem 6.2(d): a product is untied' % nm, r[3])
    else:
        check('O  Theorem 6.2(c) fails: the two places read different ties', not r[2])

# the octonion defect, three forms
r = [True] * 4; best = 0.0
for _ in range(300):
    x1, y1, x2, y2 = (rng.normal(size=8) for _ in range(4))
    K1, K2 = place_one(x1, y1, x2, y2), place_two(x1, y1, x2, y2); D = eta(K1, K1) - eta(K2, K2)
    r[0] &= ok(D, 8 * (re(mul(mul(conj(x1), x2), mul(conj(y2), y1))) - re(mul(mul(x2, conj(y2)), mul(y1, conj(x1))))))
    r[1] &= ok(D, 8 * re(mul(asc(x1, y1, y2), conj(x2)))) and ok(D, 8 * re(mul(x1, asc(y1, y2, x2))))
    X, Y = np.concatenate([x1, y1]), np.concatenate([x2, y2]); XY = mul(X, Y)
    r[2] &= ok(D, -4 * (XY @ XY - (X @ X) * (Y @ Y)))
    F = lambda a, b, c, d: re(mul(asc(a, b, c), conj(d)))
    r[3] &= ok(F(x1, y1, y2, x2), -F(y1, x1, y2, x2)) and ok(F(x1, y1, y2, x2), -F(x1, y2, y1, x2)) \
            and ok(F(x1, y1, y2, x2), -F(x1, y1, x2, y2)) and ok(F(x1, y1, y2, x2), -F(x2, y1, y2, x1))
    best = max(best, abs(D) / K1[0] ** 2)
check('O  Theorem 6.3: defect = 8 Re((conj x1 x2)(conj y2 y1)) - 8 Re((x2 conj y2)(y1 conj x1))', r[0])
check('O  Theorem 6.3: defect = 8 Re([x1,y1,y2] conj x2) = 8 Re(x1 [y1,y2,x2])', r[1])
check('O  Theorem 6.3: defect = -4(|XY|^2 - |X|^2|Y|^2), columns as numbers of the doubling', r[2])
check('O  Theorem 6.3: the form is alternating in the four entries', r[3])
h = lambda: np.concatenate([rng.normal(size=4), np.zeros(4)])
a_, b_, c_, d_ = h(), h(), h(), h()
check('O  Theorem 6.3: no defect when the four entries lie in one copy of H',
      ok(eta(place_one(a_, b_, c_, d_), place_one(a_, b_, c_, d_)), eta(place_two(a_, b_, c_, d_), place_two(a_, b_, c_, d_))))
print('      largest |defect| / gross^2 met on random roots: %.4f' % best)

# ---------------------------------------------------------------- Section 7: the ghost lines
for k in (1, 2):
    nm = NAME[k]; r = [True] * 5
    for _ in range(200):
        x1, y1, x2, y2 = (rng.normal(size=k) for _ in range(4))
        K1 = place_one(x1, y1, x2, y2)
        big = np.concatenate([x1, x2, y1, y2])                  # one root over the doubled system
        c = cut(big); inside, outside = c[:2 + k], c[2 + k:]
        det = mul(x1, y2) - mul(x2, y1)
        r[0] &= ok(inside, K1)
        r[1] &= ok(outside, -2 * det)
        r[2] &= ok(eta(c, c), 0)
        r[3] &= ok(outside @ outside, eta(K1, K1))
        kk = np.linalg.norm(K1[1:]); P, Q = (K1[0] + kk) / 2, (K1[0] - kk) / 2
        gs = (outside @ outside) / K1[0] ** 2
        r[4] &= ok(gs, 4 * P * Q / (P + Q) ** 2) and -TOL <= gs <= 1 + TOL
    check('%s  Theorem 7.2(a): the part inside the space of place one is its cut sum' % nm, r[0])
    check('%s  Theorem 7.2(a): the part on the %d ghost line(s) is -2 det M' % (nm, k), r[1])
    check('%s  Theorem 7.2(b): the cut over the doubled system is whole (rest gross 0)' % nm, r[2])
    check('%s  Theorem 7.2(c): tie = length along the ghost lines = 2|det M|' % nm, r[3])
    check('%s  Theorem 7.2(d): ghost share = tie^2/gross^2 = 4PQ/(P+Q)^2, between 0 and 1' % nm, r[4])

# more places: r = 2^(N-1) columns over K, read as one root over a system of r k numbers
import itertools
def more_places(k, r, flips):
    good = [True] * 3
    for _ in range(60):
        xs = [rng.normal(size=k) for _ in range(r)]; ys = [rng.normal(size=k) for _ in range(r)]
        K1 = sum(cut(np.concatenate([x, y])) for x, y in zip(xs, ys))
        f = lambda v, j: conj(v) if flips[j] else v
        big = np.concatenate([f(x, j) for j, x in enumerate(xs)] + [f(y, j) for j, y in enumerate(ys)])
        c = cut(big); inside, outside = c[:2 + k], c[2 + k:]
        good[0] &= ok(inside, K1); good[1] &= ok(eta(c, c), 0); good[2] &= ok(outside @ outside, eta(K1, K1))
    return all(good)
for k, r in ((1, 2), (1, 4), (1, 8), (2, 2), (2, 4)):
    found = [fl for fl in itertools.product((0, 1), repeat=r) if more_places(k, r, fl)]
    N = {2: 2, 4: 3, 8: 4}[r]
    check('%s  Theorem 7.4: a root in %d places is one root over %s; space %d -> %d, %d ghost lines; entries conjugated: %s'
          % (NAME[k], N, NAME[k * r], k + 2, k * r + 2, k * r - k, ''.join(map(str, found[0])) if found else 'none'),
          len(found) > 0)

# H: the two forms of place one are not those of one root over O
def forms(fun, dim):                     # symmetric arrays S_j with p^T S_j p = j-th number of fun(p)
    E = np.eye(dim); f0 = [fun(e) for e in E]; out = []
    nn = len(f0[0])
    S = np.zeros((nn, dim, dim))
    for i in range(dim):
        S[:, i, i] = f0[i]
        for j in range(i):
            v = (fun(E[i] + E[j]) - f0[i] - f0[j]) / 2
            S[:, i, j] = v; S[:, j, i] = v
    return S
two_places_H = lambda m: place_one(m[0:4], m[4:8], m[8:12], m[12:16])
one_root_O = lambda p: cut(p)[:6]
S1, S2 = forms(two_places_H, 16), forms(one_root_O, 16)
inv = lambda S: all(ok(S[j] @ S[j], np.eye(16)) for j in range(1, 6)) and \
                all(ok(S[i] @ S[j] + S[j] @ S[i], 0) for i in range(1, 6) for j in range(1, i)) and ok(S[0], np.eye(16))
prod = lambda S: np.trace(S[1] @ S[2] @ S[3] @ S[4] @ S[5])
check('H  Proposition 7.5(a): in both readings the five forms square to one and anticommute', inv(S1) and inv(S2))
check('H  Proposition 7.5(a): trace of the product of the five is +-16 for two places, 0 for one root over O',
      ok(abs(prod(S1)), 16) and ok(prod(S2), 0))
r = [True] * 3
for _ in range(200):
    x1, y1, b, d = (rng.normal(size=4) for _ in range(4))
    c = cut(np.concatenate([x1, b, y1, d])); inside, outside = c[:6], c[6:]
    Kin = cut(np.concatenate([x1, y1])) + sig(cut(np.concatenate([conj(d), -conj(b)])))
    r[0] &= ok(inside, Kin)
    r[1] &= ok(outside @ outside, eta(Kin, Kin)) and ok(eta(c, c), 0)
    r[2] &= ok(outside, 2 * (mul(b, y1) - mul(d, x1)))
check('H  Proposition 7.5(b): a root over O is a cut plus an opposite cut inside the space of H', r[0])
check('H  Proposition 7.5(b): its length along the four ghost lines is the rest gross of that pair', r[1])
check('H  Proposition 7.5(b): the part on the ghost lines is 2(b y1 - d x1)', r[2])

# ---------------------------------------------------------------- Section 8: agreement (C)
def obs(nv):                              # G(X)/t - 1 for X = (1; n): the projection less its opposite
    a, u1, u2 = nv; return np.array([[a, u1 + 1j * u2], [u1 - 1j * u2, -a]])
def proj(nv): return (np.eye(2) + obs(nv)) / 2
def joint(M, n1, n2): return np.linalg.norm(proj(n1) @ M @ proj(n2).T) ** 2
def agree(M, n1, n2):
    return joint(M, n1, n2) + joint(M, -n1, -n2) - joint(M, n1, -n2) - joint(M, -n1, n2)
Mt = np.array([[0, 1], [-1, 0]]) / np.sqrt(2)       # gross 1, ghost share 1
r = [True] * 3
for _ in range(100):
    n1, n2 = unit(rng.normal(size=3)), unit(rng.normal(size=3))
    r[0] &= ok(agree(Mt, n1, n2), np.real(np.trace(Mt.conj().T @ obs(n1) @ Mt @ obs(n2).T)))
    r[1] &= ok(agree(Mt, n1, n2), -n1 @ n2)
    p, q = rng.normal(size=2) + 1j * rng.normal(size=2), rng.normal(size=2) + 1j * rng.normal(size=2)
    Mp = np.outer(p, q); Mp /= np.linalg.norm(Mp)    # a product: untied
    a1, a2, b1, b2 = (unit(rng.normal(size=3)) for _ in range(4))
    S = agree(Mp, a1, b1) - agree(Mp, a1, b2) + agree(Mp, a2, b1) + agree(Mp, a2, b2)
    r[2] &= abs(S) <= 2 + TOL
check('C  Proposition 8.2(a): agreement = sum of four joint shares with signs = Re tr(M^dagger A M B^T)', r[0])
check('C  Proposition 8.2(b): for the fully tied root the agreement of X=(1;n), Y=(1;m) is -<n,m>', r[1])
check('C  Proposition 8.2(c): for an untied root the four-cut combination is at most 2', r[2])
ang = lambda th: np.array([np.cos(th), np.sin(th), 0.0])
a1, a2, b1, b2 = ang(0), ang(np.pi / 2), ang(np.pi / 4), ang(3 * np.pi / 4)
S = agree(Mt, a1, b1) - agree(Mt, a1, b2) + agree(Mt, a2, b1) + agree(Mt, a2, b2)
grid = np.linspace(0, 2 * np.pi, 33)
best = max(abs(-np.cos(a - b) + np.cos(a - b2) - np.cos(a2 - b) - np.cos(a2 - b2))
           for a in grid for a2 in grid for b in grid for b2 in grid)
check('C  Proposition 8.2(d): the fully tied root reaches 2 sqrt 2 and a search finds nothing larger',
      ok(abs(S), 2 * np.sqrt(2)) and best <= 2 * np.sqrt(2) + TOL)

# ---------------------------------------------------------------- Section 9: the counts
herm = lambda N, k: N + k * N * (N - 1) // 2          # N x N arrays equal to their conjugate transpose
one = [herm(2, k) for k in (1, 2, 4, 8)]; two = [herm(4, k) for k in (1, 2, 4, 8)]
check('Proposition 9.1: one place 3, 4, 6, 10 = k+2; squared 9, 16, 36, 100; two places 10, 16, 28, 52; equal only for C',
      one == [3, 4, 6, 10] and [v * v for v in one] == [9, 16, 36, 100] and two == [10, 16, 28, 52]
      and [v * v == w for v, w in zip(one, two)] == [False, True, False, False])

print('\n%d checks, %d passed' % (len(results), sum(results)))
sys.exit(0 if all(results) else 1)
