"""Numerical checks for 'The Root and Its Ray' (Paper 18).
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 5, Gb(X) = G(X^flat) its mirror.  A placed root is (psi, mu); it is at the point x if mu = G(sigma x) psi.
Python 3 with numpy."""
import numpy as np
rng = np.random.default_rng(21)
ok = lambda a, b, tol=1e-8: np.allclose(a, b, rtol=0, 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))])
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 run(k):
    n = k + 2; E = np.eye(n); R = {}
    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 np.eye(2 * k)])
    flat = lambda X: np.concatenate([[-X[0]], X[1:]]); sig = lambda X: np.concatenate([[X[0]], -X[1:]])
    Gb = lambda X: G(flat(X)); eta = lambda X, Y: X[0] * Y[0] - X[1:] @ Y[1:]
    cut = lambda p: np.concatenate([[p[:k] @ p[:k] + p[k:] @ p[k:], p[:k] @ p[:k] - p[k:] @ p[k:]], 2 * mul(p[:k], conj(p[k:]))])
    mu = lambda x, p: G(sig(x)) @ p                       # the mirror root that the point x makes of the root p
    psi = rng.normal(size=2 * k); x = rng.normal(size=n); c = cut(psi)
    R['1 sliding the point along the root\'s own cut changes nothing'] = ok(mu(x + 1.7 * c, psi), mu(x, psi))
    M = np.column_stack([mu(E[i], psi) for i in range(n)])      # y -> mu(y, psi)
    sv = np.linalg.svd(M)[1]; rank = int(np.sum(sv > 1e-9))
    R['2 and every other move of the point changes it (kernel is the one line of the cut)'] = (rank == n - 1 == k + 1) and ok(M @ c, 0 * psi)
    Xa, Ya = rng.normal(size=n), rng.normal(size=n); th = 0.4
    S = 0.25 * (Gb(Xa) @ G(Ya) - Gb(Ya) @ G(Xa)); Sp = 0.25 * (G(Xa) @ Gb(Ya) - G(Ya) @ Gb(Xa))
    Lam = np.column_stack([eta(Ya, b) * Xa - eta(Xa, b) * Ya for b in E]).T
    Rm, Rp, L = expm(th * S), expm(th * Sp), expm(th * Lam)
    R['3 a change of view carries the placed root to the placed root: root by R, mirror root by R\', point by L'] = (
        ok(mu(L @ x, Rm @ psi), Rp @ mu(x, psi), 1e-7) and ok(cut(Rm @ psi), L @ c, 1e-7))
    a = rng.normal(size=n)
    R['4 a translation of the point is linear on placed roots: mu -> mu + G(sigma a) psi'] = ok(mu(x + a, psi), mu(x, psi) + G(sig(a)) @ psi)
    R['5 the pairing of the root with its mirror root is the phase eta(cut, x) of Paper 8'] = ok(psi @ mu(x, psi), eta(c, x))
    # recover the light ray from the pair
    sol = np.linalg.lstsq(M, mu(x, psi), rcond=None)[0]; d = x - sol
    R['6 the placed root gives back the point up to its cut: a light ray'] = ok(M @ sol, mu(x, psi)) and ok(d - (d @ c) / (c @ c) * c, 0 * d, 1e-7)
    # which mirror roots occur: codimension k-1; the K-valued pairing
    pair = lambda p, q: mul(conj(p[:k]), q[:k]) + mul(conj(p[k:]), q[k:])
    im = max(np.linalg.norm(pair(psi, mu(rng.normal(size=n), psi))[1:]) for _ in range(5))
    R['7 the mirror roots that occur form a space of dimension k+1 (k-1 conditions)'] = (rank == k + 1)
    R['7b those conditions are: the K-valued pairing of root and mirror root is real'] = bool(im < 1e-8)
    # points and graphs
    d1 = rng.normal(size=n); kc = cut(rng.normal(size=2 * k))
    rk = lambda y: np.linalg.matrix_rank(G(sig(y)), tol=1e-9)
    R['8 two points share a placed root exactly when their difference has no even square; then they share k dimensions'] = (
        rk(d1) == 2 * k and rk(kc) == k and rk(-kc) == k and ok(G(sig(d1)) @ Gb(sig(d1)), -eta(d1, d1) * np.eye(2 * k)))
    # the invariant number of two pairs
    psi2 = rng.normal(size=2 * k); x2 = rng.normal(size=n)
    om = lambda p, m_, q, m2: p @ m2 - m_ @ q
    w0 = om(psi, mu(x, psi), psi2, mu(x2, psi2))
    w_t = om(psi, mu(x + a, psi), psi2, mu(x2 + a, psi2))
    w_v = om(Rm @ psi, Rp @ mu(x, psi), Rm @ psi2, Rp @ mu(x2, psi2))
    R['9 omega = <psi,mu\'> - <mu,psi\'> is unchanged by translations and by changes of view'] = ok(w0, w_t) and ok(w0, w_v, 1e-7)
    R['9b it is <psi, G(sigma(x\'-x)) psi\'>, and vanishes when the two rays meet'] = ok(w0, psi @ G(sig(x2 - x)) @ psi2) and ok(om(psi, mu(x, psi), psi2, mu(x + 0.3 * c, psi2)) - 0.3 * (psi @ G(sig(c)) @ psi2), 0) and ok(om(psi, mu(x, psi), psi2, mu(x, psi2)), 0)
    return R
res = {}
for k in (1, 2, 4, 8):
    for name, v in run(k).items(): res.setdefault(name, []).append(bool(v))

# 7c: uniform form of the k-1 conditions
def run2(k):
    n = k + 2; E = np.eye(n)
    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 np.eye(2 * k)])
    sig = lambda X: np.concatenate([[X[0]], -X[1:]])
    cut = lambda p: np.concatenate([[p[:k] @ p[:k] + p[k:] @ p[k:], p[:k] @ p[:k] - p[k:] @ p[k:]], 2 * mul(p[:k], conj(p[k:]))])
    psi = rng.normal(size=2 * k); c = cut(psi)
    M = np.column_stack([G(sig(E[i])) @ psi for i in range(n)])
    U, s, _ = np.linalg.svd(G(c)); half = U[:, :k]                 # the half of the roots with this cut
    T = half - np.outer(psi, psi @ half) / (psi @ psi)             # ... orthogonal to psi itself
    perp = ok(T.T @ M, 0 * (T.T @ M), 1e-7)
    full = np.linalg.matrix_rank(np.column_stack([M, T]), tol=1e-8) == 2 * k and np.linalg.matrix_rank(T, tol=1e-8) == k - 1
    return perp and full
res['7c the mirror roots that occur are exactly those orthogonal to the other roots of the same cut'] = [bool(run2(k)) for k in (1, 2, 4, 8)]


# ---------------- items 2 and 3
def liedim(gens, cap=80):
    basis = []; 
    def add(M):
        v = M.ravel()
        for b in basis: v = v - (v @ b) * b
        nv = np.linalg.norm(v)
        if nv > 1e-8: basis.append(v / nv); return True
        return False
    mats = []
    for g_ in gens:
        if add(g_): mats.append(g_)
    i = 0
    while i < len(mats) and len(mats) <= cap:
        for j in range(i):
            C = mats[i] @ mats[j] - mats[j] @ mats[i]
            if add(C): mats.append(C / max(1, np.linalg.norm(C)))
        i += 1
    return len(mats)
def run3(k):
    n = k + 2; E = np.eye(n); R = {}; I2 = np.eye(2 * k); Z0 = np.zeros((2 * k, 2 * k))
    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 np.eye(2 * k)])
    flat = lambda X: np.concatenate([[-X[0]], X[1:]]); sig = lambda X: np.concatenate([[X[0]], -X[1:]])
    Gb = lambda X: G(flat(X)); eta = lambda X, Y: X[0] * Y[0] - X[1:] @ Y[1:]
    cut = lambda p: np.concatenate([[p[:k] @ p[:k] + p[k:] @ p[k:], p[:k] @ p[:k] - p[k:] @ p[k:]], 2 * mul(p[:k], conj(p[k:]))])
    W = np.block([[Z0, I2], [-I2, Z0]])                    # omega(Z,Z') = <psi,mu'> - <mu,psi'>
    graph = lambda x: np.vstack([I2, G(sig(x))])           # the pairs at the point x
    half = lambda c: np.linalg.svd(G(c))[0][:, :k]         # the roots whose cut is along c
    # ---- item 2
    x = rng.normal(size=n); x2 = rng.normal(size=n); psi = rng.normal(size=2 * k); psi2 = rng.normal(size=2 * k)
    c, c2 = cut(psi), cut(psi2)
    R['2a the placed roots at one point: dimension 2k, and omega vanishes on them (half of the 4k)'] = ok(graph(x).T @ W @ graph(x), 0 * I2)
    ray = lambda x_, c_: graph(x_) @ half(c_)             # all roots riding the ray x + s c
    R['2b the placed roots on one light ray: dimension k'] = np.linalg.matrix_rank(ray(x, c), tol=1e-9) == k and ok(ray(x, c), ray(x + 0.8 * c, c))
    meet = x + 0.7 * c - 1.3 * c2                           # a second ray through a point of the first
    R['2c two rays meet exactly when omega vanishes between their placed roots (k x k numbers)'] = (
        ok(ray(x, c).T @ W @ ray(meet, c2), np.zeros((k, k))) and np.linalg.norm(ray(x, c).T @ W @ ray(x2, c2)) > 1e-3)
    # every pair = a root, a ray, and a twist
    mu = rng.normal(size=2 * k)                             # an arbitrary mirror root
    M = np.column_stack([G(sig(E[i])) @ psi for i in range(n)])
    Hc = half(c); T = Hc - np.outer(psi, psi @ Hc) / (psi @ psi); T = np.linalg.svd(T)[0][:, :k - 1] if k > 1 else np.zeros((2 * k, 0))
    A = np.column_stack([M, T]); sol = np.linalg.lstsq(A, mu, rcond=None)[0]
    R['2d every placed root is a root, a light ray and a twist among the other roots of its cut (k-1 numbers)'] = (
        ok(A @ sol, mu) and np.linalg.matrix_rank(A, tol=1e-8) == 2 * k and ok(T.T @ M, 0 * (T.T @ M)))
    a = rng.normal(size=n); tw = T.T @ mu
    R['2e the twist is unchanged by translations'] = ok(T.T @ (mu + G(sig(a)) @ psi), tw)
    # is the split (ray, twist) kept by changes of view?
    def split_ok(Xa, Ya):
        S = 0.25 * (Gb(Xa) @ G(Ya) - Gb(Ya) @ G(Xa)); Sp = 0.25 * (G(Xa) @ Gb(Ya) - G(Ya) @ Gb(Xa))
        Rm, Rp = expm(0.4 * S), expm(0.4 * Sp)
        p2 = Rm @ psi; c_ = cut(p2); H2 = half(c_); T2 = H2 - np.outer(p2, p2 @ H2) / (p2 @ p2)
        M2 = np.column_stack([G(sig(E[i])) @ p2 for i in range(n)])
        # image of a twist-free pair must be twist-free; image of pure twist must be pure twist
        return ok(T2.T @ (Rp @ (M @ rng.normal(size=n))), 0 * T2[0], 1e-6), (k == 1 or np.linalg.matrix_rank(np.column_stack([M2, Rp @ T]), tol=1e-7) == 2 * k and np.linalg.norm(M2.T @ (Rp @ T) - M2.T @ T2 @ np.linalg.lstsq(T2, Rp @ T, rcond=None)[0]) < 1e-6)
    r1 = split_ok(E[1], E[2]); r2 = split_ok(E[0], E[1])
    R['2f placed roots without twist stay twist-free under every change of view'] = r1[0] and r2[0]
    R['2g a pure twist stays a pure twist under turns'] = bool(r1[1])
    R['2h ... and under boosts'] = bool(r2[1])
    # ---- item 3
    Ta = lambda a_: np.block([[Z0, Z0], [G(sig(a_)), Z0]])        # translation
    Mb = lambda b_: np.block([[Z0, G(b_)], [Z0, Z0]])             # the mirror of a translation
    gens = [Ta(E[i]) for i in range(n)] + [Mb(E[i]) for i in range(n)]
    dim = liedim(gens, cap=(n + 1) * (n + 2) // 2 + 5)
    R[f'3a translations and their mirrors generate (n+1)(n+2)/2 moves of the space'] = (dim == (n + 1) * (n + 2) // 2)
    R['3b every one of them keeps omega'] = all(ok(g_.T @ W + W @ g_, 0 * W) for g_ in gens)
    C = Ta(E[0]) @ Mb(E[0]) - Mb(E[0]) @ Ta(E[0])
    R['3c translation and its own mirror bracket to the change of scale'] = ok(C, np.block([[-I2, Z0], [Z0, I2]]))
    Xa, Ya = E[1], E[2] if n > 2 else E[0]
    C2 = Ta(sig(Xa)) @ Mb(Ya) - Mb(Ya) @ Ta(sig(Xa)) - (Ta(sig(Ya)) @ Mb(Xa) - Mb(Xa) @ Ta(sig(Ya)))
    S = 0.25 * (Gb(Xa) @ G(Ya) - Gb(Ya) @ G(Xa)); Sp = 0.25 * (G(Xa) @ Gb(Ya) - G(Ya) @ Gb(Xa))
    V = np.block([[S, Z0], [Z0, Sp]])
    cc = (C2.ravel() @ V.ravel()) / (V.ravel() @ V.ravel())
    R['3d two different ones bracket to a change of view of Paper 5'] = ok(C2, cc * V) and abs(cc) > 1e-6
    a3, b3 = rng.normal(size=n), rng.normal(size=n); Sf = lambda X_, Y_: 0.5 * Gb(X_) @ G(Y_) + 0.5 * eta(X_, Y_) * I2
    Spf = lambda X_, Y_: 0.5 * G(X_) @ Gb(Y_) + 0.5 * eta(X_, Y_) * I2
    R['3d2 [T_a, M_b] = eta(a,b) diag(-1,1) + 2 diag(S(b^flat,a^flat), S\'(b^flat,a^flat))'] = ok(
        Ta(a3) @ Mb(b3) - Mb(b3) @ Ta(a3), eta(a3, b3) * np.block([[-I2, Z0], [Z0, I2]]) + 2 * np.block([[Sf(flat(b3), flat(a3)), Z0], [Z0, Spf(flat(b3), flat(a3))]]))
    # action of the mirror move on points
    b = 0.3 * rng.normal(size=n); g1 = expm(Mb(b)) @ graph(x); N = g1[2 * k:] @ np.linalg.inv(g1[:2 * k])
    Bs = np.column_stack([G(sig(E[i])).ravel() for i in range(n)]); xs = np.linalg.lstsq(Bs, N.ravel(), rcond=None)[0]
    inv = lambda y: y / eta(y, y)
    R['3e the mirror move carries points to points'] = ok(Bs @ xs, N.ravel())
    cand = {'+': inv(inv(x) + b), '-': inv(inv(x) - b)}
    R['3f on points it is: turn inside out, translate by b, turn inside out'] = ok(xs, cand['+'])
    def point(g_, y):
        gg = g_ @ graph(y); N_ = gg[2 * k:] @ np.linalg.inv(gg[:2 * k]); return np.linalg.lstsq(Bs, N_.ravel(), rcond=None)[0]
    y1 = rng.normal(size=n); y2 = y1 + 0.5 * c
    d_ = point(expm(Mb(b)), y1) - point(expm(Mb(b)), y2)
    R['3g it keeps "no even square between two points" (light stays light)'] = abs(eta(d_, d_)) < 1e-7
    # one fraction: a product of all five kinds of move
    Xa_, Ya_ = rng.normal(size=n), rng.normal(size=n); a_ = 0.4 * rng.normal(size=n); b_ = 0.2 * rng.normal(size=n)
    Sg = 0.25 * (Gb(Xa_) @ G(Ya_) - Gb(Ya_) @ G(Xa_)); Spg = 0.25 * (G(Xa_) @ Gb(Ya_) - G(Ya_) @ Gb(Xa_))
    gmove = expm(Ta(a_)) @ expm(0.3 * np.block([[Sg, Z0], [Z0, Spg]])) @ expm(Mb(b_)) @ expm(0.2 * np.block([[-I2, Z0], [Z0, I2]])) @ expm(Ta(-0.5 * a_))
    A_, B_, C_, D_ = gmove[:2 * k, :2 * k], gmove[:2 * k, 2 * k:], gmove[2 * k:, :2 * k], gmove[2 * k:, 2 * k:]
    def frac(y):
        Xy = G(sig(y)); N_ = (C_ + D_ @ Xy) @ np.linalg.inv(A_ + B_ @ Xy)
        sol = np.linalg.lstsq(Bs, N_.ravel(), rcond=None)[0]; return sol, np.linalg.norm(Bs @ sol - N_.ravel())
    y1_ = rng.normal(size=n); y2_ = y1_ + 0.6 * c; (z1, r1_), (z2, r2_) = frac(y1_), frac(y2_)
    R['F1 one fraction: a product of all kinds of move carries points to points by (C + D X)(A + B X)^-1'] = r1_ < 1e-7 and r2_ < 1e-7 and ok(point(gmove, y1_), z1)
    R['F2 and keeps light between two points'] = abs(eta(z1 - z2, z1 - z2)) < 1e-7
    Lg = expm(0.3 * np.column_stack([eta(Ya_, b0) * Xa_ - eta(Xa_, b0) * Ya_ for b0 in E]).T)
    R['F3 the rows of the table: translation, change of view, scale, mirror'] = (
        ok(point(expm(Ta(a_)), x), x + a_) and ok(point(expm(0.3 * np.block([[Sg, Z0], [Z0, Spg]])), x), Lg @ x)
        and ok(point(expm(0.2 * np.block([[-I2, Z0], [Z0, I2]])), x), np.exp(0.4) * x) and ok(point(expm(Mb(b_)), x), inv(inv(x) + b_)))
    scale = expm(0.3 * np.block([[-I2, Z0], [Z0, I2]]))
    R['3h the change of scale multiplies points by a number'] = ok(point(scale, x), np.exp(0.6) * x)
    return R
for k in (1, 2, 4, 8):
    for name, v in run3(k).items(): res.setdefault(name, []).append(bool(v))

# the twist and the observer: K = C, psi = (1,0), twist tau = (i,0), boost by theta in the plane of e and E_2
def boost_example(th):
    k, n = 2, 4; E = np.eye(n)
    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 np.eye(2 * k)])
    flat = lambda X: np.concatenate([[-X[0]], X[1:]]); sig = lambda X: np.concatenate([[X[0]], -X[1:]]); Gb = lambda X: G(flat(X))
    S = 0.25 * (Gb(E[0]) @ G(E[2]) - Gb(E[2]) @ G(E[0])); Sp = 0.25 * (G(E[0]) @ Gb(E[2]) - G(E[2]) @ Gb(E[0]))
    R, Rp = expm(th * S), expm(th * Sp); psi = np.array([1., 0, 0, 0]); tau = np.array([0., 1, 0, 0])
    p2 = R @ psi; ip2 = np.array([-p2[1], p2[0], -p2[3], p2[2]])
    return ok(Rp @ tau, ip2 / np.cosh(th) + G(sig(np.tanh(th) * E[3])) @ p2)
res['T  boost by theta: the twist becomes twist / cosh(theta) and the ray is displaced by tanh(theta), sideways'] = [boost_example(0.3), boost_example(0.8), boost_example(-1.1), boost_example(2.0)]

expected = {'7b': [True, True, True, False], '2h': [True, False, False, False]}
allok = True
for name, v in res.items():
    want = expected.get(name.split()[0], [True] * 4); good = (v == want); allok &= good
    note = '' if want == [True] * 4 else '   (as stated: ' + ', '.join(f'{a}: {"holds" if b else "fails"}' for a, b in zip('RCHO', want)) + ')'
    print(('ok   ' if good else 'FAIL ') + name + note)
print('sizes of the moves of the space in dimensions 3, 4, 6, 10:', [(k + 3) * (k + 4) // 2 for k in (1, 2, 4, 8)])
print(f'{len(res)} checks in each of the four number systems:', 'ALL PASS' if allok else 'FAILURES')
