"""Numerical checks for 'Always Whole'.
V is R^d with viewpoint e; T is the product formula of Paper III.
The three products are x.y = (ab + c<x',y'>) e + a y' + b x', c = -1 (turn), 0, +1 (ledger).
An n-step ledger is a vector of n non-negative weights; its product is cyclic convolution."""
import itertools
import numpy as np
rng = np.random.default_rng(6)
ok = lambda a, b: np.allclose(a, b, atol=1e-8)
R = {}

# ---------------------------------------------------------------- one formula, two slots
d = 5
T = lambda x, y, e: (x @ e) * y + (y @ e) * x - (x @ y) * e
unit = lambda v: v / np.linalg.norm(v)
mirror = lambda u, x: 2 * (u @ x) * u - x                      # reflection in the line of u
eta = lambda e, x, y: 2 * (x @ e) * (y @ e) - x @ y
e = np.eye(d)[0]; u = unit(rng.normal(size=d)); x = rng.normal(size=d)
R['reader slot: u is the number one in its own view'] = ok(T(u, x, u), x) and ok(T(u, u, u), u)
R['factor slot: u twice is the mirror in the line of u'] = ok(T(u, u, x), mirror(u, x))
R['each sees the same even part of the other square'] = ok(eta(e, u, u), eta(u, e, e)) and ok(eta(e, u, u), 2 * (u @ e) ** 2 - 1)

# ---------------------------------------------------------------- the loop
f = unit(np.concatenate([[0], rng.normal(size=d - 1)]))
loop = lambda s, f=f: np.cos(2 * np.pi * s) * e + np.sin(2 * np.pi * s) * f
def power(x, n, prod):
    z = e.copy()
    for _ in range(n): z = prod(z, x)
    return z
turn = lambda x, y: T(x, y, e)
s, r = rng.random(2)
R['steps add along the loop'] = ok(turn(loop(s), loop(r)), loop(s + r)) and ok(turn(loop(s), loop(s)), loop(2 * s))
good = True
for n in range(1, 9):
    for k in range(n):
        g = unit(np.concatenate([[0], rng.normal(size=d - 1)]))          # any perpendicular direction
        good &= ok(power(loop(k / n, g), n, turn), e)
    z = loop(rng.random()); good &= not ok(power(z, n, turn), e)         # a generic unit is not a root
R['n-th roots of the unit: units at angles 2 pi k/n, in every perpendicular direction'] = good
R['every point of the loop is the number one in its own view'] = all(
    ok(T(loop(t), loop(t), loop(t)), loop(t)) for t in [0, 1 / 7, 0.5, 1, 2, rng.random()])
R['the loop run once and run twice ends at the unit'] = ok(loop(1), e) and ok(loop(2), e)
proj = lambda x: x @ e                                                    # what the line of e reads
def congruent(theta):
    step = lambda x: turn(x, np.cos(theta) * e + np.sin(theta) * f)
    return all(ok(proj(step(loop(t))), proj(step(loop(-t)))) for t in rng.random(6))
R['the line follows a step exactly when it is no step or a half step'] = (
    congruent(0) and congruent(np.pi) and not congruent(2 * np.pi / 3) and not congruent(np.pi / 2))
n = 10 ** 6
R['the small step points along the perpendicular line'] = np.allclose((loop(1 / n) - e) * n / (2 * np.pi), f, atol=1e-5)

# ---------------------------------------------------------------- three products
def prod_c(c):
    def p(x, y):
        a, b = x @ e, y @ e; xp, yp = x - a * e, y - b * e
        return (a * b + c * (xp @ yp)) * e + a * yp + b * xp
    return p
Q, _ = np.linalg.qr(rng.normal(size=(d - 1, d - 1))); A = np.eye(d); A[1:, 1:] = Q   # isometry fixing e
y = rng.normal(size=d); g = unit(np.concatenate([[0], rng.normal(size=d - 1)]))
good = True
for c in (-1, 0, 1):
    p = prod_c(c)
    good &= ok(p(e, x), x) and ok(p(f, g), (c * (f @ g)) * e) and ok(A @ p(x, y), p(A @ x, A @ y))
    good &= ok(p(x, x) @ e, (x @ e) ** 2 + c * ((x @ x) - (x @ e) ** 2))
R['three products satisfy (R1), (R3), (R4); odd units square to c e'] = good
led = prod_c(1); dual = prod_c(0)
R['turn product is T; even part of the square is eta'] = ok(prod_c(-1)(x, y), turn(x, y)) and ok(turn(x, x) @ e, eta(e, x, x))
R['ledger product is T with eta in place of the inner product; even part of the square is |x|^2'] = (
    ok(led(x, y), (x @ e) * y + (y @ e) * x - eta(e, x, y) * e) and ok(led(x, x) @ e, x @ x))
P_, Q_, P2, Q2 = rng.random(4)
R['in the plane the ledger product is the ledger product of Paper II'] = ok(
    led(P_ * e + Q_ * f, P2 * e + Q2 * f), (P_ * P2 + Q_ * Q2) * e + (P_ * Q2 + Q_ * P2) * f)
phi = rng.normal(); boost = lambda t: np.cosh(t) * e + np.sinh(t) * f
good = True
for n in range(1, 8):
    good &= ok(power(boost(phi), n, led), boost(n * phi)) and ok(power(e + phi * f, n, dual), e + n * phi * f)
    good &= ok(power(f, n, led), e if n % 2 == 0 else f)
R['no loop along a boost or a motion: powers run off, forward roots of the unit are the unit'] = good

# ---------------------------------------------------------------- wholes
v = rng.normal(size=d); v -= (v @ e) * e; b = unit(v)
P, Qh = (e + b) / 2, (e - b) / 2
R['half cuts are wholes, blind to each other, and sum to the unit'] = (
    ok(led(P, P), P) and ok(led(Qh, Qh), Qh) and ok(led(P, Qh), 0 * e) and ok(P + Qh, e))
cut = v + np.linalg.norm(v) * e; opp = -v + np.linalg.norm(v) * e
R['a cut squares to itself times twice its hidden part; opposite cuts multiply to zero'] = (
    ok(led(cut, cut), 2 * np.linalg.norm(v) * cut) and ok(led(cut, opp), 0 * e))
R['the half step N = P - Q is a square root of the unit'] = ok(P - Qh, b) and ok(led(b, b), e)
def whole_residual(a, w): z = a * e + w; return np.linalg.norm(led(z, z) - z)
good = whole_residual(0.5, b / 2) < 1e-9 and whole_residual(1, 0 * e) < 1e-9 and whole_residual(0, 0 * e) < 1e-9
for _ in range(2000):                                   # a whole is 0, e, or a cut of hidden part 1/2
    a = rng.normal(); w = rng.normal() * b
    is_listed = (np.linalg.norm(w) < 1e-3 and min(abs(a), abs(a - 1)) < 1e-3) or (abs(a - .5) < 1e-3 and abs(np.linalg.norm(w) - .5) < 1e-3)
    good &= is_listed or whole_residual(a, w) > 1e-7
R['wholes of the ledger product: 0, e and the cuts of hidden part 1/2'] = good
good = all(np.linalg.norm(turn(a * e + w, a * e + w) - (a * e + w)) > 1e-7 or (np.linalg.norm(w) < 1e-3)
           for a, w in [(rng.normal(), rng.normal() * b) for _ in range(2000)])
R['wholes of the turn product lie on the line of e'] = good

# ---------------------------------------------------------------- higher powers: the links x = x^(m+1)
good = True
tang = prod_c(0)
for m in range(1, 7):
    pw = lambda z, pr: power(z, m + 1, pr)
    for kk in range(m):                                                   # turn: the loop of m steps
        z = loop(kk / m); good &= ok(pw(z, turn), z)
    z = loop(rng.random()); good &= ok(pw(0 * e, turn), 0 * e) and not ok(pw(z, turn), z)
    vals = [0, 1] if m % 2 else [0, 1, -1]
    for al in (0, 1, -1):                                                 # ledger: signed wholes
        for be in (0, 1, -1):
            z = al * P + be * Qh
            good &= ok(pw(z, led), z) == (al in vals and be in vals)
    al, be = rng.normal(size=2); z = al * P + be * Qh; good &= not ok(pw(z, led), z)
    for a_ in (0, 1, -1):                                                 # tangent: on the line only
        good &= ok(pw(a_ * e, tang), a_ * e) == (a_ in vals)
    z = e + rng.normal() * b; good &= not ok(pw(z, tang), z)
R['links x = x^(m+1): loop of m steps (turn), signed wholes (ledger), line only (tangent)'] = good

# ---------------------------------------------------------------- wholes act as projections (Paper V)
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))])
good = True
for k in (1, 2, 4, 8):
    def act(X, p):
        xx, yy = p[:k], p[k:]; t, a, uu = X[0], X[1], X[2:]
        return np.concatenate([(t + a) * xx + mul(uu, yy), mul(conj(uu), xx) + (t - a) * yy])
    G = lambda X: np.column_stack([act(X, bb) for bb in np.eye(2 * k)])
    E = np.eye(k + 2)[0]
    ledV = lambda X, Y: X[0] * Y + Y[0] * X - (2 * X[0] * Y[0] - X @ Y) * E
    X, Y = rng.normal(size=k + 2), rng.normal(size=k + 2)
    good &= ok(G(X) @ G(Y) + G(Y) @ G(X), 2 * G(ledV(X, Y))) and ok(G(E), np.eye(2 * k))
    w = unit(rng.normal(size=k + 1)); half = np.concatenate([[.5], w / 2]); other = np.concatenate([[.5], -w / 2])
    good &= ok(G(half) @ G(half), G(half)) and ok(G(half) @ G(other), 0 * G(E)) and np.linalg.matrix_rank(G(half), tol=1e-8) == k
R['the action of Paper V turns the ledger product into composition; half cuts act as projections (R, C, H, O)'] = good
good = True; tilt = True
for k in (1, 2, 4, 8):                                  # the roots read one loop as a half step
    def act(X, p):
        xx, yy = p[:k], p[k:]; t, a, uu = X[0], X[1], X[2:]
        return np.concatenate([(t + a) * xx + mul(uu, yy), mul(conj(uu), xx) + (t - a) * yy])
    G = lambda X: np.column_stack([act(X, bb) for bb in np.eye(2 * k)])
    sq = 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:]))])
    O_, _ = np.linalg.qr(rng.normal(size=(k + 1, 2)))
    X, Y = np.concatenate([[0], O_[:, 0]]), np.concatenate([[0], O_[:, 1]])
    J = G(X) @ G(Y); I2 = np.eye(2 * k)
    Rs = lambda s_: np.cos(np.pi * s_) * I2 + np.sin(np.pi * s_) * J
    def turn_V(s_):                                     # turn of V by 2 pi s in the plane of X and Y
        c_, s2 = np.cos(2 * np.pi * s_), np.sin(2 * np.pi * s_)
        return np.eye(k + 2) + (c_ - 1) * (np.outer(X, X) + np.outer(Y, Y)) - s2 * (np.outer(Y, X) - np.outer(X, Y))
    p = rng.normal(size=2 * k); s1, s2_ = rng.random(2)
    good &= ok(J @ J, -I2) and ok(Rs(s1) @ Rs(s2_), Rs(s1 + s2_)) and ok(Rs(s1).T @ Rs(s1), I2)
    good &= ok(sq(Rs(s1) @ p), turn_V(s1) @ sq(p)) and ok(Rs(1), -I2) and ok(Rs(2), I2) and ok(sq(Rs(1) @ p), sq(p))
    if k >= 2:                                          # the loop run twice is deformed to no loop
        O3, _ = np.linalg.qr(rng.normal(size=(k + 1, 3)))
        X, Y, Z = (np.concatenate([[0], O3[:, i]]) for i in range(3))
        def Rt(tau, s_):
            Yt = np.cos(np.pi * tau) * Y + np.sin(np.pi * tau) * Z
            return np.cos(np.pi * s_) * I2 + np.sin(np.pi * s_) * (G(X) @ G(Yt))
        def tV(A_, B_, s_):
            c_, s2 = np.cos(2 * np.pi * s_), np.sin(2 * np.pi * s_)
            return np.eye(k + 2) + (c_ - 1) * (np.outer(A_, A_) + np.outer(B_, B_)) - s2 * (np.outer(B_, A_) - np.outer(A_, B_))
        Lt = lambda tau, s_: Rt(0, s_) @ Rt(tau, s_)
        for tau in (0, 0.3, 0.5, 0.8, 1):
            Yt = np.cos(np.pi * tau) * Y + np.sin(np.pi * tau) * Z
            tilt &= ok(Lt(tau, 0), I2) and ok(Lt(tau, 1), I2)
            tilt &= ok(sq(Lt(tau, s1) @ p), tV(X, Y, s1) @ tV(X, Yt, s1) @ sq(p))
        tilt &= ok(Lt(0, s1), Rt(0, 2 * s1)) and ok(Lt(1, s1), I2) and not ok(Lt(0.5, 0.5), I2)
R['roots read one loop as -1 and return after two; their cut turns once per loop (R, C, H, O)'] = good
R['the loop run twice is deformed through closed loops into no loop (C, H, O)'] = tilt

# ---------------------------------------------------------------- the ledger of a loop
def conv(a, b):
    n = len(a); z = np.zeros(n)
    for i in range(n):
        for j in range(n): z[(i + j) % n] += a[i] * b[j]
    return z
gross = lambda w: w.sum()
net = lambda w: sum(w[k] * np.exp(2j * np.pi * k / len(w)) for k in range(len(w)))
good = True; good_tri = True
for n in range(2, 9):
    a, b_ = rng.random(n), rng.random(n); ab = conv(a, b_)
    good &= ok(gross(ab), gross(a) * gross(b_)) and ok(net(ab), net(a) * net(b_))
    ghost = sum(a[j] * a[k] * (1 - np.cos(2 * np.pi * (j - k) / n)) for j in range(n) for k in range(j + 1, n))
    good_tri &= ok(gross(a) ** 2, abs(net(a)) ** 2 + 2 * ghost)
R['gross and net of an n-step ledger are multiplicative'] = good
R['triangle equality for an n-step ledger'] = good_tri
R['n = 2 is the ledger of Paper II'] = ok(conv(np.array([P_, Q_]), np.array([P2, Q2])), [P_ * P2 + Q_ * Q2, P_ * Q2 + Q_ * P2])
def cpow(w, m):
    z = np.zeros(len(w)); z[0] = 1
    for _ in range(m): z = conv(z, w)
    return z
good = True
for n in range(2, 8):
    one = np.eye(n)[0]
    for m in range(1, 7):
        for k in range(n):
            good &= ok(cpow(np.eye(n)[k], m), one) == ((m * k) % n == 0)       # loop points
        for _ in range(300):                                                    # no root carries a ghost
            w = rng.random(n) * (rng.random(n) < 0.6); w = w / max(w.sum(), 1e-12)
            if np.count_nonzero(w) > 1: good &= not ok(cpow(w, m), one)
R['roots of the whole in an n-step ledger are single loop points'] = good
good = True
for n in range(2, 13):
    chars = np.array([[np.exp(2j * np.pi * j * k / n) for k in range(n)] for j in range(n)])
    found = set()
    for J in itertools.product([0, 1], repeat=n):                               # every idempotent of the loop algebra
        w = (np.array(J) @ chars.conj()) / n
        if np.abs(w.imag).max() < 1e-9 and w.real.min() > -1e-9 and sum(J) > 0:
            found.add(tuple(np.round(w.real, 9)))
    expect = set()
    for dd in range(1, n + 1):
        if n % dd == 0:
            w = np.zeros(n); w[::n // dd] = 1 / dd; expect.add(tuple(np.round(w, 9)))
    good &= found == expect and all(ok(conv(np.array(w), np.array(w)), w) for w in expect)
R['wholes of an n-step ledger: equal weights on a sub-loop of d steps, d dividing n'] = good

# ---------------------------------------------------------------- Paper I as the process part
def polymod(p, q):
    p = np.array(p, float)
    while len(p) >= len(q):
        if abs(p[-1]) > 1e-12: p[len(p) - len(q):] -= p[-1] * np.array(q, float)
        p = p[:-1]
    return np.concatenate([p, np.zeros(len(q) - 1 - len(p))])
good = True
for n in (3, 5, 7, 9):
    eps = np.ones(n) / n; a, b_ = rng.normal(size=n), rng.normal(size=n); q = np.ones(n)   # q_n = 1 + t + ... + t^(n-1)
    good &= ok(conv(eps, eps), eps) and ok(conv(eps, a), gross(a) * eps)                  # state part: the gross
    good &= ok(polymod(np.polymul(a[::-1], b_[::-1])[::-1], q), polymod(conv(a, b_), q))  # A_n is the rest
    good &= ok(polymod(a - gross(a) * eps, q), polymod(a, q)) and ok(polymod(eps, q), 0)
    L = rng.random(n); cube = np.full(n, L[0])
    good &= ok(polymod(cube, q), 0) and not ok(polymod(L, q), 0)                          # hypercube test of Paper I
R['odd n: the n-step loop algebra is (gross) + A_n with zero mixing; a box is a multiple of the whole iff it is a cube'] = good
good = True
for n in (2, 4, 6):
    N = 2 * n; epsS = np.zeros(N); epsS[::2] = 1 / n; g_ = np.eye(N)[1]; geps = conv(g_, epsS)
    a = rng.normal(size=N)
    good &= ok(conv(epsS, epsS), epsS) and ok(conv(geps, geps), epsS)                     # a two-step ledger inside
    good &= ok(conv(epsS, a), a[::2].sum() * epsS + a[1::2].sum() * geps)
    q = np.zeros(2 * n - 1); q[::2] = 1                                                   # q_n = 1 + t^2 + ... + t^(2n-2)
    good &= ok(polymod(epsS, q), 0) and ok(polymod(a - conv(epsS, a), q), polymod(a, q))
R['even n: the 2n-step loop algebra is (a two-step ledger) + A_n'] = good
good = True
for n in range(2, 13):                                  # the unit cube as a process
    loop_len, steps = (n, sum(range(n))) if n % 2 else (2 * n, sum(2 * k + 1 for k in range(n)))
    good &= steps % loop_len == 0 and steps // loop_len == n // 2
    prod = np.eye(loop_len)[0]
    for k in range(n): prod = conv(prod, np.eye(loop_len)[k if n % 2 else 2 * k + 1])
    good &= ok(prod, np.eye(loop_len)[0])
R['the product of the n length types is the unit after floor(n/2) full loops'] = good

# ---------------------------------------------------------------- Encapsulation Domains
good = True
for n in (2, 3, 6):
    r_ = rng.random(n); r_ /= r_.sum(); a, b_ = rng.random(n), rng.random(n); b_ *= gross(a) / gross(b_)
    good &= ok(gross(conv(r_, a)), gross(a)) and ok(gross(conv(r_, a)), gross(conv(r_, b_)))
R['ledger model: a step of gross one keeps the gross; equal gross stays equal'] = good
good = True
for k in (2, 4):
    sq = 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:]))])
    p = rng.normal(size=2 * k); h = unit(rng.normal(size=k)); gg = unit(rng.normal(size=k))
    p2 = np.concatenate([mul(p[:k], h), mul(p[k:], h)])                                   # same cut, different root
    step = lambda p: np.concatenate([mul(gg, p[:k]), p[k:]])
    good &= ok(sq(p), sq(p2)) and ok(sq(step(p)), sq(step(p2))) and ok(sq(step(p))[0], sq(p)[0]) and not ok(p, p2)
R['root model: roots with one cut keep one cut after a turn; the hidden part is kept'] = good

# ---------------------------------------------------------------- further cases
good = ok(turn(loop(s), loop(s)), mirror(loop(s), e))                    # half-angle corollary
xp = rng.normal() * e + rng.normal() * f                                  # a step keeps the size, in the plane of the loop
good &= all(ok(np.linalg.norm(turn(xp, loop(t))), np.linalg.norm(xp)) for t in rng.random(5))
good &= ok(power(-e, 4, led), e) and ok(power(-b, 4, led), e) and not ok(power(-b, 3, led), e)
good &= ok(power(-e, 4, dual), e) and not ok(power(-e, 3, dual), e)
e2, f2 = np.eye(2); T2 = lambda x_, y_: T(x_, y_, e2)                     # d = 2
for n in range(1, 7):
    for k in range(n):
        z = np.cos(2 * np.pi * k / n) * e2 + np.sin(2 * np.pi * k / n) * f2; p_ = e2.copy()
        for _ in range(n): p_ = T2(p_, z)
        good &= ok(p_, e2)
ghost6 = lambda w: sum(w[j] * w[k] * (1 - np.cos(2 * np.pi * (j - k) / 6)) for j in range(6) for k in range(j + 1, 6))
good &= ok(ghost6(np.eye(6)[2] * 0.7), 0) and ghost6(np.array([.5, 0, 0, .5, 0, 0])) > 0.1
for n in (2, 4, 6):                                                       # even n: a cube is a multiple of the half step
    N = 2 * n; epsS = np.zeros(N); epsS[::2] = 1 / n; half_step = conv(np.eye(N)[1], epsS)
    box = np.zeros(N); box[1::2] = 0.8; good &= ok(box, 0.8 * n * half_step)
R['further cases: half angle, size kept, negative roots, d = 2, ghost zero, even-n cube'] = good

# ---- the total (version 2): signed weights; total, gross, and the split of an Encapsulation Domain
good = True
for n in (3, 4, 5, 8, 9):
    conv = lambda a, b: np.array([sum(a[i] * b[(k - i) % n] for i in range(n)) for k in range(n)])
    w, w2 = rng.normal(size=n), rng.normal(size=n); T = lambda x: x.sum(); G = lambda x: np.abs(x).sum()
    eps = np.ones(n) / n; one = np.zeros(n); one[0] = 1
    good &= ok(T(conv(w, w2)), T(w) * T(w2)) and G(conv(w, w2)) <= G(w) * G(w2) + 1e-12 and abs(T(w)) <= G(w)
    good &= ok(conv(eps, w), T(w) / n * np.ones(n)) and ok(conv(one - eps, w), w - T(w) / n) and ok(T(conv(one - eps, w)), 0)
    v = rng.normal(size=n); v += (1 - T(v)) / n                      # an element of total one
    good &= ok(T(conv(v, w)), T(w))
    pos = np.abs(w); good &= ok(T(pos), G(pos))                      # for a ledger the total is the gross
R['the total multiplies, the gross does not; state part = total/n, process part = deviations of total zero'] = good
R['NEG the gross of a signed element is not its total, and does not multiply'] = (
    not ok(np.abs(np.array([6, -1, -1, -1, -1, -1, -1]) / 7).sum(), 0) and ok(np.array([6, -1, -1, -1, -1, -1, -1]).sum(), 0)
    and not ok(np.abs(np.convolve([1, -1], [1, 1])).sum(), 4))
R['modulo 2^k the whole of the full loop exists exactly for odd n'] = all(
    (any((n * x) % 2 ** k == 1 for x in range(2 ** k))) == (n % 2 == 1) for n in range(1, 13) for k in (3, 6))

for name, val in R.items(): print(('PASS ' if val else 'FAIL ') + name)
print('all checks pass' if all(R.values()) else 'SOME CHECKS FAIL')
