"""Numerical checks for 'Two Roots Make a Translation'.
K is R, C, H or O (dimension k); V = R + R + K with eta(X,Y) = x0 y0 - <X',Y'>; roots are pairs in K^2.
G(X) is the action of Paper V, Gb(X) = G(X^flat); D = sum G(E_mu) d_mu, Dbar = sum Gb(E_mu) d_mu.
Fields are plane waves amp * exp(i <p,X>), so d_mu is i p_mu and every operator of the paper is a matrix
depending on p. An identity between such operators holds for all fields when it holds for all p."""
import numpy as np
rng = np.random.default_rng(9)
def conj(x):
    c = -x.copy(); c[0] = x[0]; return c
def mul(x, y):                                          # Cayley-Dickson product
    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))])
def expm(M):
    s = 10; A = M / 2 ** s; E = np.eye(len(M)); t = np.eye(len(M))
    for j in range(1, 20): t = t @ A / j; E = E + t
    for _ in range(s): E = E @ E
    return E
def close(u, w, tol=1e-9): return np.linalg.norm(u - w) <= tol * (np.linalg.norm(u) + np.linalg.norm(w) + 1)
def far(u, w): return np.linalg.norm(u - w) > 1e-3 * (np.linalg.norm(u) + np.linalg.norm(w))

def run(k):
    n = k + 2; I = np.eye(2 * k); E = np.eye(n); R = {}; rv = lambda m: rng.normal(size=m)
    def act(X, 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])
    G = lambda X: np.column_stack([act(X, b) for b in I])
    sg = np.array([1.0] + [-1.0] * (n - 1)); sig = lambda X: sg * X; flat = lambda X: -sig(X)
    Gb = lambda X: G(flat(X)); eta = lambda X, Y: X @ sig(Y)
    def beta(p, q):                                     # the pairing of Paper V, by its formula
        x, y, x1, y1 = p[:k], p[k:], q[:k], q[k:]
        return np.concatenate([[x @ x1 + y @ y1, x @ x1 - y @ y1], mul(x, conj(y1)) + mul(x1, conj(y))])
    cut = lambda p: beta(p, p)
    GE = [G(E[m]) for m in range(n)]; GbE = [Gb(E[m]) for m in range(n)]
    B = lambda e: np.column_stack([beta(e, b) for b in I])            # psi -> beta(eps, psi)
    M = lambda e: np.column_stack([g @ e for g in GE])                # W   -> Gamma(W) eps
    Mb = lambda e: np.column_stack([g @ e for g in GbE])              # W   -> Gammabar(W) eps
    S = lambda X, Y: (Gb(X) @ G(Y) - Gb(Y) @ G(X)) / 4
    Lam = lambda X, Y: np.outer(sig(Y), X) - np.outer(sig(X), Y)
    # the action of a constant root eps on plane waves of covector p (a factor i is kept explicit)
    QA = lambda e, p: 1j * Gb(p) @ M(e) @ np.diag(sg)                 # field of the space -> root field
    Qpsi = lambda e, p: B(e).astype(complex)                          # root field -> field of the space
    tr = lambda Y, p: 1j * (Y @ p)                                    # translation along Y: (Y.d)
    eps, eps2 = rv(2 * k), rv(2 * k); c = cut(eps); p = rv(n); X, Y, Z = rv(n), rv(n), rv(n); q = rv(2 * k)

    # ---- inputs
    R['transpose: <psi,G(X)chi> = <X,beta(psi,chi)>'] = close(B(eps), M(eps).T) and close(q @ G(X) @ eps, X @ beta(q, eps))
    R['Lemma 2.1: 2 G(sigma beta(eps,chi)) eps + G(sigma c(eps)) chi = 0'] = close(2 * G(sig(beta(eps, q))) @ eps + G(sig(c)) @ q, 0 * q)
    R['NEG the same without the mirror'] = far(2 * G(beta(eps, q)) @ eps + G(c) @ q, 0 * q)
    R['Lemma 2.2: three factors'] = close(G(X) @ Gb(Y) @ G(Z) + G(Z) @ Gb(Y) @ G(X), -2 * eta(X, Y) * G(Z) - 2 * eta(Y, Z) * G(X) + 2 * eta(X, Z) * G(Y))

    # ---- the field of the space falls out
    unit = lambda v_: v_ / np.linalg.norm(v_)
    K = cut(unit(rv(2 * k))); pK = sig(K); a = unit(G(K) @ rv(2 * k))   # a root of the half of K, carried along K
    img = B(a).T                                                      # rows beta(eps_j, a)
    R['a root carried along K solves the law of motion'] = close(G(pK) @ a, 0 * a) and np.linalg.norm(a) > 1e-3
    rank = lambda A_: np.linalg.matrix_rank(A_, tol=1e-9 * np.linalg.norm(A_))
    R['Theorem 3.2: the fields beta(eps,a) fill {Y: eta(K,Y)=0}, of dimension k+1, and contain K'] = (
        rank(img) == k + 1 and close(img @ pK, np.zeros(2 * k)) and rank(np.vstack([img, K])) == k + 1)
    Xa = np.column_stack([G(E[m]) @ a for m in range(n)])               # X -> Gamma(X) a
    R['Theorem 3.2: the only X with G(X)a = 0 are the multiples of the opposite cut'] = (
        rank(Xa) == n - 1 and close(Xa @ pK, 0 * a) and np.linalg.norm(pK) > 1e-3)
    Yout = rv(n)
    R['NEG a Y with eta(K,Y) not zero is not reached'] = rank(np.vstack([img, Yout])) == k + 2
    R['NEG a root outside the half of K gives fields with divergence'] = np.abs(B(rv(2 * k)).T @ pK).max() > 1e-3
    R['they obey the wave equation and have no divergence'] = abs(eta(pK, pK)) < 1e-9 * K[0] ** 2 and close(img @ pK, np.zeros(2 * k))

    # ---- the action of a root, for arbitrary fields (arbitrary p)
    Gbsc = Gb(sig(c)); Dsym = 1j * sum(p[m] * GE[m] for m in range(n))
    lhs = QA(eps, p) @ Qpsi(eps, p)
    R['Theorem 4.2(1): eps.eps.psi = (c.d)psi + (1/2) Gb(sigma c) D psi'] = close(lhs, tr(c, p) * I + 0.5 * Gbsc @ Dsym)
    R['NEG without the second term'] = far(lhs, tr(c, p) * I)
    R['NEG along the opposite cut'] = far(lhs, tr(sig(c), p) * I + 0.5 * Gbsc @ Dsym)
    lhsA = Qpsi(eps, p) @ QA(eps, p)
    rhsA = tr(c, p) * E - 1j * np.outer(sig(p), sig(c)) - 1j * np.outer(c, p)
    R['Theorem 4.2(2): eps.eps.A = (c.d)A - sigma grad eta(c,A) - (div A) c'] = close(lhsA, rhsA)
    R['NEG without the gradient'] = far(lhsA, tr(c, p) * E - 1j * np.outer(c, p))
    box = -eta(p, p)                                                  # the wave operator on a plane wave
    R['Theorem 4.3: D(eps.A) = -G(sigma box A) eps and div(eps.psi) = <eps, D psi>'] = (
        close(Dsym @ QA(eps, p), -box * M(eps) @ np.diag(sg)) and close(1j * p @ Qpsi(eps, p), eps @ Dsym))
    R['Proposition 4.4: a gradient sigma grad f goes to -(box f) eps'] = close(QA(eps, p) @ (1j * sig(p)), -box * eps)
    R['Proposition 6.1: eps.A = 2 s(curl A) eps - (div A) eps, and a gradient has no curl'] = (
        close(QA(eps, p), 1j * np.column_stack([(2 * S(p, sig(E[m])) - p[m] * I) @ eps for m in range(n)])) and close(Lam(p, sig(sig(p))), 0 * E))

    # ---- on solutions: psi carried along K (p = sigma K, amplitude in the half of K), A with eta(K,A)=0
    Ysol = rv(n); Ysol = Ysol - (Ysol @ pK) / (E[0] @ pK) * E[0]
    a1 = QA(eps, pK) @ Ysol; A1 = Qpsi(eps, pK) @ a
    R['Theorem 5.1: solutions go to solutions'] = close(G(pK) @ a1, 0 * a1) and abs(A1 @ pK) < 1e-9 * np.linalg.norm(A1) * np.linalg.norm(pK) and np.linalg.norm(a1) > 1e-6
    R['Theorem 5.1: on solutions eps.eps.psi = (c.d) psi'] = close(QA(eps, pK) @ A1, tr(c, pK) * a) and abs(tr(c, pK)) > 1e-6
    grad_part = -1j * sig(pK) * eta(c, Ysol)
    R['Theorem 5.1: on solutions eps.eps.A = (c.d) A - sigma grad eta(c,A), and the gradient is not seen'] = (
        close(Qpsi(eps, pK) @ a1, tr(c, pK) * Ysol + grad_part) and close(QA(eps2, pK) @ grad_part, 0 * a))
    R['NEG eps.eps.A = (c.d) A without the gradient'] = far(Qpsi(eps, pK) @ a1, tr(c, pK) * Ysol)
    b12 = beta(eps, eps2); s12 = QA(eps, pK) @ Qpsi(eps2, pK) @ a + QA(eps2, pK) @ Qpsi(eps, pK) @ a
    d12 = QA(eps, pK) @ Qpsi(eps2, pK) @ a - QA(eps2, pK) @ Qpsi(eps, pK) @ a
    R['Theorem 5.2: both orders added give twice the translation along beta(eps1,eps2)'] = close(s12, 2 * tr(b12, pK) * a)
    R['NEG the difference of the two orders is not that translation'] = far(d12, 2 * tr(b12, pK) * a)
    R['the difference of the two orders vanishes on solutions (only for the reals)'] = close(d12, 0 * d12, 1e-9) == (k == 1)

    curl = lambda Yv: 1j * Lam(pK, sig(Yv))                         # C(A) on a plane wave of covector pK
    Y2 = Ysol + 0.7 * sig(pK); Y3 = Ysol + 0.7 * (rv(n) - (rv(n) @ pK) / (E[0] @ pK) * E[0])
    Y3 = Y3 - (Y3 @ pK) / (E[0] @ pK) * E[0]
    R['Theorem 11.1: fields with the same curl are carried to the same root field, and differ by a gradient'] = (
        close(curl(Ysol), curl(Y2)) and close(QA(eps, pK) @ Ysol, QA(eps, pK) @ Y2))
    R['NEG fields with different curls are told apart by some root'] = far(curl(Ysol), curl(Y3)) and any(
        far(QA(I[j], pK) @ Ysol, QA(I[j], pK) @ Y3) for j in range(2 * k))

    # ---- the ghost between two cuts
    v, w = K[1:], c[1:]
    q2 = QA(eps, pK) @ Qpsi(eps, pK) @ a
    R['Theorem 7.1: on a root carried along K, eps.eps is the ghost term of the two cuts times the derivative'] = (
        close(q2, 1j * (np.linalg.norm(v) * np.linalg.norm(w) - v @ w) * a) and close(eta(K, c), np.linalg.norm(v) * np.linalg.norm(w) - v @ w))
    e_in = unit(G(K) @ rv(2 * k)); e_out = unit(G(sig(K)) @ rv(2 * k))
    R['Theorem 7.1: a root of the same half does nothing, and the field it makes is a gradient along K'] = (
        close(QA(e_in, pK) @ Qpsi(e_in, pK) @ a, 0 * a) and rank(np.vstack([beta(e_in, a), K])) == 1)
    wo = cut(e_out)[1:]
    R['Theorem 7.1: a root of the opposite half moves the carried root, with the largest ghost 2|v||w|'] = close(
        QA(e_out, pK) @ Qpsi(e_out, pK) @ a, 2j * np.linalg.norm(v) * np.linalg.norm(wo) * a) and np.linalg.norm(wo) > 1e-3

    # ---- the mirror action
    em = rv(2 * k); cm = cut(em); QAm = 1j * G(p) @ Mb(em) @ np.diag(sg); Qchim = np.diag(sg) @ B(em)
    Dbsym = 1j * sum(p[m] * GbE[m] for m in range(n))
    R['Theorem 8.1: the mirror action squares to the translation along the opposite cut, plus (1/2) G(c) Dbar chi'] = close(QAm @ Qchim, tr(sig(cm), p) * I + 0.5 * G(cm) @ Dbsym)
    R['NEG along the cut itself'] = far(QAm @ Qchim, tr(cm, p) * I + 0.5 * G(cm) @ Dbsym)
    R['Theorem 8.1: on a field of the space the mirror action gives the same three terms with the opposite cut'] = close(
        Qchim @ QAm, tr(sig(cm), p) * E - 1j * np.outer(sig(p), cm) - 1j * np.outer(sig(cm), p))

    # ---- changes of view (finite), Paper VIII Theorem 7.1
    Xc, Yc = rv(n), rv(n); th = 0.37; Rt = expm(th * S(Xc, Yc)); Rp = expm(-th * S(Xc, Yc).T); L = expm(th * Lam(Xc, Yc))
    pL = np.linalg.inv(L).T @ p
    R['Theorem 9.1: a change of view carries the action to the action'] = (
        close(Qpsi(Rt @ eps, pL) @ Rt, L @ Qpsi(eps, p)) and close(QA(Rt @ eps, pL) @ L, Rt @ QA(eps, p)) and close(L.T @ np.diag(sg) @ L, np.diag(sg)))
    R['NEG with the constant root turned as a mirror root'] = far(Qpsi(Rp @ eps, pL) @ Rt, L @ Qpsi(eps, p))
    R['NEG G(A) without the mirror is not carried'] = far(1j * Gb(pL) @ M(Rt @ eps) @ L, Rt @ (1j * Gb(p) @ M(eps)))

    # ---- the pair of constant m, with a field of the space of rate m
    m = 1.3; u = rv(n - 1); u /= np.linalg.norm(u); pm = m * np.concatenate([[np.cosh(0.6)], np.sinh(0.6) * u])     # eta(p,p) = m^2
    def Q(e, F):
        Yv, av, bv = F; W = M(e) @ (sg * Yv)
        return (B(e) @ av + (1j / m) * sig(pm) * (e @ bv), 1j * Gb(pm) @ W, m * W)
    def solves(F):
        Yv, av, bv = F
        return abs(pm @ Yv) < 1e-9 * (1 + np.linalg.norm(Yv)) and close(1j * G(pm) @ av, m * bv) and close(1j * Gb(pm) @ bv, m * av)
    a0 = rv(2 * k).astype(complex); Y0 = rv(n); Y0 = (Y0 - (Y0 @ pm) / (pm @ pm) * pm).astype(complex)
    F0 = (Y0, a0, 1j * G(pm) @ a0 / m); F1 = Q(eps, F0); F2 = Q(eps, F1); P = tr(c, pm)
    R['Theorem 10.1: with a constant m, solutions go to solutions'] = solves(F0) and solves(F1) and abs(eta(pm, pm) - m * m) < 1e-9
    R['Theorem 10.1: eps.eps.A = (c.d) A exactly, with no gradient left'] = close(F2[0], P * F0[0])
    R['Theorem 10.1: eps.eps.psi = (c.d)psi - (m/2) G(c) chi + m <eps,chi> eps'] = close(F2[1], P * F0[1] - 0.5 * m * G(c) @ F0[2] + m * (eps @ F0[2]) * eps)
    R['G(c(eps)) = 2 |eps><eps| (only for the reals)'] = close(G(c), 2 * np.outer(eps, eps)) == (k == 1)
    rho = eps @ eps; Pc = G(c) / (2 * rho); Pe = np.outer(eps, eps) / rho; Ob = Pc - Pe
    R['Proposition 10.2: the obstruction is m |eps|^2 times an orthogonal projection of rank k-1 inside the half of the cut of eps'] = (
        close(F2[1], P * F0[1] - m * rho * Ob @ F0[2]) and close(Ob @ Ob, Ob) and close(Ob, Ob.T) and round(np.trace(Ob)) == k - 1 and
        close(Pc @ Ob, Ob) and close(Ob @ eps, 0 * eps))
    R['Theorem 10.1: the action closes on the pair without further fields (only for the reals)'] = (close(F2[1], P * F0[1]) and close(F2[2], P * F0[2])) == (k == 1)
    return R

results = {}
for k in (1, 2, 4, 8):
    for name, val in run(k).items(): results.setdefault(name, []).append(bool(val))
for name, vals in results.items(): print(('PASS ' if all(vals) else 'FAIL ') + name + f'  [{len(vals)} number systems]')
print(len(results), 'checks;', 'all pass' if all(all(v) for v in results.values()) else 'SOME CHECKS FAIL')
