"""Numerical checks for 'The Point of View as an Input'.
Each entry checks one statement of the paper on random inputs, in several dimensions."""
import numpy as np
rng = np.random.default_rng(11)
ok = lambda a, b: np.allclose(a, b, atol=1e-8)

def T(x, y, e):                       # product of x and y in the view of e
    return (x @ e) * y + (y @ e) * x - (x @ y) * e
def unit(n):
    v = rng.normal(size=n); return v / np.linalg.norm(v)
def odd(n, e):                        # random element orthogonal to e
    v = rng.normal(size=n); return v - (v @ e) * e
def boost(e, b, phi):
    n = len(e)
    return (np.eye(n) + (np.cosh(phi) - 1) * (np.outer(e, e) + np.outer(b, b))
            + np.sinh(phi) * (np.outer(e, b) + np.outer(b, e)))

all_ok = True
for n in (2, 3, 4, 7):
    e = unit(n); r = {}
    x, y, z = (rng.normal(size=n) for _ in range(3))
    a, b_ = x @ e, y @ e; xo, yo = x - a * e, y - b_ * e
    sig = lambda v, c: 2 * (v @ c) * c - v
    # the product
    r['identity, commutative'] = ok(T(x, e, e), x) and ok(T(x, y, e), T(y, x, e))
    r['graded form of the product'] = ok(T(x, y, e), (a * b_ - xo @ yo) * e + a * yo + b_ * xo)
    r['parity is an automorphism'] = ok(sig(T(x, y, e), e), T(sig(x, e), sig(y, e), e))
    if n == 2:
        c = lambda v: complex(v[0], v[1])
        r['plane: equals z w conj(e)'] = ok(c(T(x, y, e)), c(x) * c(y) * c(e).conjugate())
    # squaring is mirroring
    f = unit(n); g = odd(n, e); g /= np.linalg.norm(g)
    r['square formula'] = ok(T(x, x, e), 2 * a * x - (x @ x) * e)
    r['unit square = mirror of e in the line of f'] = ok(T(f, f, e), sig(e, f))
    r['orthogonal iff square is -e'] = ok(T(g, g, e), -e) and ok(T(e, e, g), -g) and not ok(T(f, f, e), -e)
    # associativity
    g2 = odd(n, e); g2 -= (g2 @ g) * g
    if n >= 3:
        g2 /= np.linalg.norm(g2)
        r['not associative for n>=3'] = ok(T(T(g, g, e), g2, e), -g2) and ok(T(g, T(g, g2, e), e), 0 * g)
    else:
        r['associative in the plane'] = ok(T(T(x, y, e), z, e), T(x, T(y, z, e), e))
    x2 = T(x, x, e)
    r['Jordan identity'] = ok(T(x2, T(x, y, e), e), T(x, T(x2, y, e), e))
    fb = sig(f, e); o = lambda p, q: T(p, q, e)
    r['change of view'] = ok(T(x, y, f), o(o(x, fb), y) + o(o(y, fb), x) - o(o(x, y), fb))
    # the cut
    eta = lambda p, q: T(p, q, e) @ e
    r['even form'] = ok(eta(x, y), a * b_ - xo @ yo)
    cut = lambda v: v + np.linalg.norm(v) * e
    vs = [odd(n, e) for _ in range(5)]; cs = [cut(v) for v in vs]
    r['cut: even square zero, square = 2|v|v'] = all(ok(eta(c, c), 0) and ok(T(c, c, e), 2 * np.linalg.norm(v) * v) for c, v in zip(cs, vs))
    # ledgers and the ghost term
    gam = lambda v, w: np.linalg.norm(v) * np.linalg.norm(w) - v @ w
    K = sum(cs); G = K @ e; N = K - G * e
    pairs = sum(gam(vs[j], vs[k]) for j in range(5) for k in range(j + 1, 5))
    r['cut sum = gross e + net'] = ok(G, sum(np.linalg.norm(v) for v in vs)) and ok(N, sum(vs))
    r['ghost term = even part of product of cuts'] = all(ok(gam(vs[j], vs[k]), eta(cs[j], cs[k])) for j in range(5) for k in range(5))
    r['triangle equality'] = ok(G * G, N @ N + 2 * pairs) and pairs >= -1e-12
    r['ghost term zero for same direction'] = ok(gam(vs[0], 2.5 * vs[0]), 0) and ok(gam(vs[0], -2 * vs[0]), 4 * (vs[0] @ vs[0]))
    r['balanced zero reads on own line'] = ok(cut(vs[0]) + cut(-vs[0]), 2 * np.linalg.norm(vs[0]) * e)
    # boosts
    b = odd(n, e); b /= np.linalg.norm(b); phi = 0.7; L = boost(e, b, phi)
    r['boost preserves even form'] = ok(eta(L @ x, L @ y), eta(x, y))
    Lc = [L @ c for c in cs]
    r['boost maps cuts to cuts'] = all(ok(c @ e, np.linalg.norm(c - (c @ e) * e)) for c in Lc)
    K2 = sum(Lc); G2 = K2 @ e; N2 = K2 - G2 * e
    r['gross^2 - net^2 invariant'] = ok(G2 * G2 - N2 @ N2, G * G - N @ N)
    r['boost on the two cut rays'] = ok(L @ (e + b), np.exp(phi) * (e + b)) and ok(L @ (e - b), np.exp(-phi) * (e - b))
    # boosted points of view
    P = lambda p, q, o_: eta(p, o_) * q + eta(q, o_) * p - (2 * eta(p, o_) * eta(q, o_) - eta(p, q)) * o_
    o2 = L @ e; v = vs[1]
    r['observer product at e'] = ok(P(x, y, e), T(x, y, e))
    r['boost carries the product'] = ok(L @ T(x, y, e), P(L @ x, L @ y, o2))
    r['mixing between views'] = ok(eta(v, o2), -np.sinh(phi) * (v @ b)) and ok(eta(L @ v, o2), 0)
    Li = np.linalg.inv(L); go = lambda p, q: 2 * eta(p, o2) * eta(q, o2) - eta(p, q)
    r['observer is Euclidean in its own view'] = ok(go(x, y), (Li @ x) @ (Li @ y))
    etaf = lambda p, q: 2 * (p @ f) * (q @ f) - p @ q
    r['turned view has a different cone'] = not ok(etaf(cs[0], cs[0]), 0)
    # one reflection
    def refl(g, nv):                  # matrix of the reflection in the line of nv for the form g
        return np.column_stack([2 * g(c, nv) * nv / g(nv, nv) - c for c in np.eye(n)])
    dot = lambda p, q: p @ q
    Se = refl(dot, e); So = refl(eta, o2); Bo = refl(eta, e + o2) @ refl(eta, e)
    r['even form = inner product with one side reflected'] = ok(eta(x, y), x @ (Se @ y))
    r['boost = two reflections'] = ok(Bo, L) and ok(Bo @ e, o2) and ok(Bo @ x, x + 2 * eta(x, e) * o2 - eta(x, e + o2) / (1 + eta(e, o2)) * (e + o2))
    r['observer geometry = two reflections'] = ok(go(x, y), eta(x, So @ y)) and ok(go(x, y), x @ (Se @ So @ y)) and ok(go(x, y), (np.linalg.inv(Bo) @ x) @ (np.linalg.inv(Bo) @ y))
    r['the two reflections cancel at o = e'] = ok(Se @ refl(eta, e), np.eye(n))
    # the reading: gross, net and rest gross
    m = np.sqrt(eta(K, K)); nrm = np.linalg.norm
    ang = lambda p, q: np.arccos(np.clip(p @ q / (nrm(p) * nrm(q)), -1, 1))
    r['m^2 = 2 sum of ghosts = 4 sum |v||w| sin^2(theta/2)'] = ok(m * m, 2 * pairs) and ok(m * m, 4 * sum(
        nrm(vs[j]) * nrm(vs[k]) * np.sin(ang(vs[j], vs[k]) / 2) ** 2 for j in range(5) for k in range(j + 1, 5)))
    Go = eta(K, o2); No = K - Go * o2
    ws = [c - eta(c, o2) * o2 for c in cs]
    r['every observer keeps a ledger of the same cuts'] = all(ok(eta(c, o2), np.sqrt(go(w, w))) and ok(eta(w, o2), 0) for c, w in zip(cs, ws)) and ok(No, sum(ws))
    r['full form for the observer'] = ok(Go * Go, go(No, No) + m * m) and ok(G * G, N @ N + m * m)
    os_ = K / m; ph = np.arccosh(G / m)
    r['compact form: the observer with no net reads gross = m (rest gross)'] = ok(eta(os_, os_), 1) and ok(K - eta(K, os_) * os_, 0 * K) and ok(eta(K, os_), m)
    r['gross = m cosh, net = m sinh'] = ok(G, m * np.cosh(ph)) and ok(nrm(N), m * np.sinh(ph))
    u = N / nrm(N); pp, qq = (G + nrm(N)) / 2, (G - nrm(N)) / 2
    r['every forward element is two cuts, m = 2 sqrt(pq)'] = ok(cut(pp * u) + cut(-qq * u), K) and ok(m, 2 * np.sqrt(pp * qq))
    r['two cuts at an angle'] = ok(np.sqrt(eta(cs[0] + cs[1], cs[0] + cs[1])), 2 * np.sqrt(nrm(vs[0]) * nrm(vs[1])) * np.sin(ang(vs[0], vs[1]) / 2))
    r['no rest gross for one ray'] = ok(eta(cut(vs[0]) + cut(3 * vs[0]), cut(vs[0]) + cut(3 * vs[0])), 0)
    r['change of observer keeps the reading'] = ok(eta(L @ K, L @ o2), Go) and ok(L @ K - eta(L @ K, L @ o2) * (L @ o2), L @ No) and ok(eta(L @ K, L @ K), m * m)
    r['gross >= rest gross, equal exactly at no net'] = G >= m and pp + qq >= 2 * np.sqrt(pp * qq)
    if n in (3, 4):                   # Hermitian two-by-two matrices (real symmetric for n=3)
        Qb = np.linalg.qr(np.column_stack([e] + [rng.normal(size=n) for _ in range(n - 1)]))[0].T
        Qb[0] = e                     # orthonormal basis with first vector e
        sg = [np.eye(2), np.diag([1.0, -1.0]), np.array([[0, 1], [1, 0]]), np.array([[0, -1j], [1j, 0]])][:n]
        Mx = lambda v_: sum((Qb[i] @ v_) * sg[i] for i in range(n))
        det = lambda A: np.linalg.det(A).real
        r['matrices: even square = determinant, 2<x,e> = trace'] = ok(eta(x, x), det(Mx(x))) and ok(2 * (x @ e), np.trace(Mx(x)).real)
        r['matrices: cuts have determinant zero'] = all(ok(det(Mx(c)), 0) for c in cs)
        ev = np.linalg.eigvalsh(Mx(K))
        r['matrices: two cuts = spectral theorem'] = ok(sorted(ev), sorted([2 * pp, 2 * qq])) and ok(m * m, det(Mx(K))) and ok(G, np.trace(Mx(K)).real / 2)
        r['matrices: symmetrized product has odd squares +e'] = ok((Mx(x) @ Mx(y) + Mx(y) @ Mx(x)) / 2, Mx((x @ e) * y + (y @ e) * x - eta(x, y) * e))
    bad = [k for k, v_ in r.items() if not v_]
    all_ok &= not bad
    print(f"n={n}: {len(r)} checks, " + ("all pass" if not bad else f"FAILED {bad}"))
print("ALL PASS" if all_ok else "SOME FAILED")
