"""Numerical checks for 'The Opposite Cut'.
V elements are (t, a, u_1..u_k); roots are (x, y) in K^2 stored as one real vector of length 2k.
K is R, C, H or O, realised by the Cayley-Dickson product on R^k."""
import numpy as np
rng = np.random.default_rng(41)
ok = lambda a, b: np.allclose(a, b, atol=1e-6)
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))])
def expm(M):                                   # matrix exponential by scaling and squaring
    s = max(0, int(np.ceil(np.log2(max(1.0, np.linalg.norm(M)))))) + 6
    A = M / 2 ** s; E = np.eye(len(M)); term = np.eye(len(M))
    for j in range(1, 20):
        term = term @ A / j; E = E + term
    for _ in range(s): E = E @ E
    return E

def run(k, full=True):
    n = k + 2; r = {}
    sp = lambda p: (p[:k], p[k:])
    c_ = lambda p: (lambda x, y: np.concatenate([[x @ x + y @ y, x @ x - y @ y], 2 * mul(x, conj(y))]))(*sp(p))
    def beta(p, q):
        (x, y), (u, w) = sp(p), sp(q)
        return np.concatenate([[x @ u + y @ w, x @ u - y @ w], mul(x, conj(w)) + mul(u, conj(y))])
    def act(X, p):
        x, y = sp(p); 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])
    flat = lambda X: np.concatenate([[-X[0]], X[1:]])          # X^flat = (-t; a, u)
    sig = lambda X: np.concatenate([[X[0]], -X[1:]])           # mirror in the line of e
    eta = lambda X, Y: X[0] * Y[0] - X[1:] @ Y[1:]
    G = lambda X: np.column_stack([act(X, b) for b in np.eye(2 * k)])
    Gb = lambda X: G(flat(X))
    I = np.eye(2 * k)
    p, q = rng.normal(size=2 * k), rng.normal(size=2 * k); X, Y, Z, W = (rng.normal(size=n) for _ in range(4))
    # the action
    r['Clifford relations'] = ok(Gb(X) @ G(Y) + Gb(Y) @ G(X), -2 * eta(X, Y) * I) and ok(G(X) @ Gb(Y) + G(Y) @ Gb(X), -2 * eta(X, Y) * I)
    if not full: return r
    r['action is symmetric; transpose of the pairing'] = ok(G(X), G(X).T) and ok(p @ act(X, q), X @ beta(p, q))
    # a root and its cut
    C = c_(p); t = C[0]
    r['own cut fixes the root, opposite cut annihilates it'] = ok(act(C, p), 2 * (p @ p) * p) and ok(act(flat(C), p), 0 * p)
    r['root splits along b: c = |x|^2(e+b) + |y|^2(e-b) + u'] = ok(C[:2], (p[:k] @ p[:k]) * np.array([1, 1]) + (p[k:] @ p[k:]) * np.array([1, -1]))
    # a cut halves the roots
    Pm, Qm = G(C) / (2 * t), -Gb(C) / (2 * t)
    r['cut gives two complementary projections of rank k'] = (ok(Pm @ Pm, Pm) and ok(Qm @ Qm, Qm) and ok(Pm @ Qm, 0 * I)
                                                               and ok(Pm + Qm, I) and np.linalg.matrix_rank(Pm, tol=1e-8) == k)
    w1 = Pm @ q; w0 = Qm @ q; Cop = np.concatenate([[t], -C[1:]])
    r['fixed half = roots of multiples of the cut'] = ok(c_(w1), (w1 @ w1) / t * C) and ok(c_(w0), (w0 @ w0) / t * Cop)
    # the ghost is the angle between halves
    v2 = rng.normal(size=k + 1); Y2 = np.concatenate([[np.linalg.norm(v2)], v2]); s2 = Y2[0]
    PY = G(Y2) / (2 * s2); gh = eta(C, Y2); phi = np.arccos(C[1:] @ v2 / (t * s2))
    r['ghost term = 2ts sin^2(angle between halves), angle = half the angle between cuts'] = (
        ok(Pm @ PY @ Pm, (1 - gh / (2 * t * s2)) * Pm) and ok(gh, 2 * t * s2 * np.sin(phi / 2) ** 2)
        and ok((PY @ w1) @ (PY @ w1), np.cos(phi / 2) ** 2 * (w1 @ w1)))
    # changes of view built from the action
    S = lambda X, Y: 0.25 * (Gb(X) @ G(Y) - Gb(Y) @ G(X))
    S1 = lambda X, Y: 0.25 * (G(X) @ Gb(Y) - G(Y) @ Gb(X))
    Lt = lambda X, Y: np.column_stack([eta(Y, b) * X - eta(X, b) * Y for b in np.eye(n)])   # Lambda-tilde
    Lam = lambda X, Y: Lt(X, Y).T
    Sxy, S1xy = S(X, Y), S1(X, Y)
    r['S = (1/2) Gb(X)G(Y) + (1/2)eta, and S^T = -S\'' ] = ok(Sxy, 0.5 * Gb(X) @ G(Y) + 0.5 * eta(X, Y) * I) and ok(Sxy.T, -S1xy)
    Lz = Lt(X, Y) @ Z
    r['intertwining relations'] = ok(G(Z) @ Sxy - S1xy @ G(Z), G(Lz)) and ok(Gb(Z) @ S1xy - Sxy @ Gb(Z), Gb(Lz))
    r['Lambda formula'] = ok(Lam(X, Y) @ W, (X @ W) * sig(Y) - (Y @ W) * sig(X))
    g = np.diag([1.0] + [-1.0] * (n - 1)); L = Lam(X, Y)
    r['Lambda preserves the ghost infinitesimally'] = ok(L.T @ g + g @ L, 0 * g)
    r['pairing is compatible with S and Lambda'] = ok(beta(Sxy @ p, q) + beta(p, Sxy @ q), L @ beta(p, q))
    r['commutator formula'] = ok(Sxy @ S(W, Z) - S(W, Z) @ Sxy, -S(Lt(X, Y) @ W, Z) - S(W, Lt(X, Y) @ Z))
    # s is a Lie algebra homomorphism: check on Lambda(X,Y), Lambda(W,Z)
    E = np.eye(n); pairs = [(i, j) for i in range(n) for j in range(i + 1, n)]
    Lb = np.array([Lam(E[i], E[j]).ravel() for i, j in pairs]).T
    Sb = [S(E[i], E[j]) for i, j in pairs]
    def s_of(M):
        co = np.linalg.lstsq(Lb, M.ravel(), rcond=None)[0]
        return sum(c * m for c, m in zip(co, Sb)), ok(Lb @ co, M.ravel())
    L2 = Lam(W, Z); sc, fit = s_of(L @ L2 - L2 @ L)
    r['the Lambda(X,Y) span all infinitesimal changes of view'] = np.linalg.matrix_rank(Lb) == n * (n - 1) // 2
    r['s is a homomorphism'] = fit and ok(Sxy @ S(W, Z) - S(W, Z) @ Sxy, sc)
    # finite changes of view
    M = 0.6 * L; sM = 0.6 * Sxy
    r['exp(s(M)) and exp(M) form a root transformation'] = ok(c_(expm(sM) @ p), expm(M) @ C) and ok(expm(M).T @ g @ expm(M), g) and (expm(M)[0, 0] > 0)
    # the ledger of orderings
    Po, Qo = Gb(X) @ G(Y), Gb(Y) @ G(X); D = eta(X, Y) ** 2 - eta(X, X) * eta(Y, Y)
    r['orderings: gross is a number, net is 4S, ghost is a number, triangle equality'] = (
        ok(Po + Qo, -2 * eta(X, Y) * I) and ok(Po - Qo, 4 * S(X, Y)) and ok(Po @ Qo, eta(X, X) * eta(Y, Y) * I)
        and ok(Qo @ Po, Po @ Qo) and ok((Po + Qo) @ (Po + Qo), (Po - Qo) @ (Po - Qo) + 4 * Po @ Qo)
        and ok(S(X, Y) @ S(X, Y), 0.25 * D * I))
    Yperp = Y - eta(X, Y) / eta(X, X) * X
    r['orders agree on one line, are opposite when perpendicular for eta'] = (
        ok(Gb(X) @ G(3 * X), Gb(3 * X) @ G(X)) and not ok(Po, Qo)
        and ok(Gb(X) @ G(Yperp), -Gb(Yperp) @ G(X)) and not ok(Po, -Qo))
    E_ = np.eye(n); kinds = True
    cutX = E_[0] + E_[1]                                                       # a cut: eta = 0
    for A_, B_, kind in ((E_[1], E_[2], 'turn'), (E_[0], E_[1], 'boost'), (cutX, E_[2], 'neither')):
        A_, B_ = 1.3 * A_ + 0.2 * B_, 0.7 * B_                                 # not orthonormal on purpose
        Dk = eta(A_, B_) ** 2 - eta(A_, A_) * eta(B_, B_); Sk = S(A_, B_); Lk = Lt(A_, B_); th = 0.83
        kinds &= ok(Sk @ Sk, 0.25 * Dk * I) and ok(Lk @ Lk @ A_, Dk * A_) and ok(Lk @ Lk @ B_, Dk * B_)
        w_ = 0.5 * np.sqrt(abs(Dk))
        if kind == 'turn':
            kinds &= Dk < 0 and ok(expm(th * Sk), np.cos(w_ * th) * I + np.sin(w_ * th) / w_ * Sk)
            kinds &= ok(expm(th * Lk) @ A_, np.cos(2 * w_ * th) * A_ + np.sin(2 * w_ * th) / (2 * w_) * (Lk @ A_))
            kinds &= ok(expm(2 * np.pi / w_ * Sk), I) and ok(expm(np.pi / w_ * Sk), -I) and ok(expm(np.pi / w_ * Lk), np.eye(n))
        elif kind == 'boost':
            kinds &= Dk > 0 and ok(expm(th * Sk), np.cosh(w_ * th) * I + np.sinh(w_ * th) / w_ * Sk)
            kinds &= ok(expm(th * Lk) @ A_, np.cosh(2 * w_ * th) * A_ + np.sinh(2 * w_ * th) / (2 * w_) * (Lk @ A_))
        else:
            kinds &= ok(Dk, 0) and ok(expm(th * Sk), I + th * Sk) and not ok(Sk, 0 * I)
    r['three kinds of change of view by the sign of D; roots move at half the rate'] = kinds
    # graded Jacobi identity for the full algebra
    SL = lambda a: (sum(c * m for c, m in zip(a, Sb)), (Lb @ a).reshape(n, n))
    def br(A, B):
        (a, X_, p_), (b, Y_, q_) = A, B
        (Sa, La), (Sb_, Lb_) = SL(a), SL(b)
        co = np.linalg.lstsq(Lb, (La @ Lb_ - Lb_ @ La).ravel(), rcond=None)[0]
        return (co, La @ Y_ - Lb_ @ X_ + beta(p_, q_), Sa @ q_ - Sb_ @ p_)
    z = np.zeros
    rand = lambda par: (rng.normal(size=len(pairs)), rng.normal(size=n), z(2 * k)) if par == 0 else (z(len(pairs)), z(n), rng.normal(size=2 * k))
    jac = True
    for pa in (0, 1):
        for pb in (0, 1):
            for pc in (0, 1):
                A, B, Cc = rand(pa), rand(pb), rand(pc); sg = -1 if (pa and pb) else 1
                t1, t2, t3 = br(A, br(B, Cc)), br(br(A, B), Cc), br(B, br(A, Cc))
                jac &= all(ok(x1, x2 + sg * x3) for x1, x2, x3 in zip(t1, t2, t3))
    r['graded Jacobi identity for the full algebra'] = jac
    # one action, one reflection (version 3)
    refl = lambda Y_, Z_: 2 * eta(Z_, Y_) / eta(Y_, Y_) * Y_ - Z_                 # reflection in the line of Y for eta
    r['sandwich: G(Y) Gb(Z) G(Y) = -eta(Y,Y) G(reflection of Z in Y), and with G, Gb exchanged'] = (
        ok(G(Y) @ Gb(Z) @ G(Y), -eta(Y, Y) * G(refl(Y, Z))) and ok(Gb(X) @ G(Z) @ Gb(X), -eta(X, X) * Gb(refl(X, Z))))
    r['one action is one reflection: c(G(Y)psi) = 2 eta(Y, sigma c) Y - eta(Y,Y) sigma c'] = (
        ok(c_(G(Y) @ p), 2 * eta(Y, sig(C)) * Y - eta(Y, Y) * sig(C)) and ok(c_(G(Y) @ p), eta(Y, Y) * refl(Y, sig(C))))
    r['a cut acting sends every root to a root of that cut'] = ok(c_(G(Y2) @ p), 2 * (Y2 @ C) * Y2)
    r['two actions are two reflections'] = ok(c_(Gb(X) @ G(Y) @ p), eta(X, X) * eta(Y, Y) * refl(sig(X), refl(sig(Y), C)))
    r['two actions = a number + a change of view'] = ok(Gb(X) @ G(Y), -eta(X, Y) * I + 2 * S(X, Y))
    wdir = rng.normal(size=k + 1); wdir /= np.linalg.norm(wdir); bw = np.concatenate([[0], wdir]); e_ = E_[0]; ph = 0.7
    ob = lambda f: np.cosh(f) * e_ + np.sinh(f) * bw                              # the observer at rapidity f along bw
    boost = lambda f: np.eye(n) + (np.cosh(f) - 1) * (np.outer(e_, e_) + np.outer(bw, bw)) + np.sinh(f) * (np.outer(e_, bw) + np.outer(bw, e_))
    r['an observer acts as exp(phi G(b)), covering the boost to twice its rapidity'] = ok(G(ob(ph)), expm(ph * G(bw))) and ok(c_(G(ob(ph)) @ p), boost(2 * ph) @ C)
    r['the boost from e to o is covered by the action of the observer half way'] = (
        ok(c_(G(ob(ph / 2)) @ p), boost(ph) @ C) and ok(G(ob(ph / 2)), G(e_ + ob(ph)) / np.sqrt(2 + 2 * np.cosh(ph)))
        and ok(G(ob(ph / 2)) @ G(ob(ph / 2)), G(ob(ph))))
    u1 = np.concatenate([[0], rng.normal(size=k + 1)]); u1 /= np.linalg.norm(u1)
    u2 = np.concatenate([[0], rng.normal(size=k + 1)]); u2 -= (u2 @ u1) * u1; u2 /= np.linalg.norm(u2); al = 0.4
    At = Gb(u1) @ G(np.cos(al) * u1 + np.sin(al) * u2)
    rot = np.eye(n) + (np.cos(2 * al) - 1) * (np.outer(u1, u1) + np.outer(u2, u2)) + np.sin(2 * al) * (np.outer(u2, u1) - np.outer(u1, u2))
    r['two odd units at angle alpha act as a turn of the cuts by 2 alpha'] = ok(c_(At @ p), rot @ C) or ok(c_(At @ p), rot.T @ C)
    return r

allok = True
for k in (1, 2, 4, 8):
    r = run(k); bad = [n_ for n_, v in r.items() if not v]; allok &= not bad
    print(f'k={k} (dimension {k+2}): {len(r)} checks, ' + ('all pass' if not bad else f'FAILED {bad}'))
print('k=16: Clifford relations hold:', run(16, full=False)['Clifford relations'])
print('ALL PASS' if allok else 'SOME FAILED')
