"""Numerical checks for 'The Square Root of a Cut'.
Elements of V are stored as (t, a, q_1..q_k): t on the line of e, (a, q) in the odd sector.
Roots are pairs (x, y) of elements of K = R^k with the Cayley-Dickson product."""
import numpy as np
rng = np.random.default_rng(23)
ok = lambda a, b: np.allclose(a, b, atol=1e-8)

def conj(x):
    c = -x.copy(); c[0] = x[0]; return c
def mul(x, y):                                   # Cayley-Dickson product, sizes 1, 2, 4, 8, 16
    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 c_(x, y):                                    # the square of the root (x, y)
    return np.concatenate([[x @ x + y @ y, x @ x - y @ y], 2 * mul(x, conj(y))])
def B_(p, r):                                    # pairing of two roots
    (x, y), (u, w) = p, r
    return np.concatenate([[x @ u + y @ w, x @ u - y @ w], mul(x, conj(w)) + mul(u, conj(y))])
eta = lambda X, Y: X[0] * Y[0] - X[1:] @ Y[1:]
is_cut = lambda X: ok(X[0], np.linalg.norm(X[1:])) and X[0] >= -1e-12
unitK = lambda k: (lambda v: v / np.linalg.norm(v))(rng.normal(size=k))

res = {}
# the ledger of the plane
p, q, phi = 1.3, -0.8, 0.9; P, Q = p * p, q * q; G, N = P + Q, P - Q
res['ledger: G^2 = N^2 + (2pq)^2, ghost = (pq)^2'] = ok(G * G, N * N + (2 * p * q) ** 2) and ok(P * Q, (p * q) ** 2)
res['ledger: boost acts on roots at half rate'] = ok((np.exp(phi / 2) * p) ** 2, np.exp(phi) * P) and ok((np.exp(-phi / 2) * q) ** 2, np.exp(-phi) * Q)
X3 = c_(np.array([p]), np.array([q]))
res['ledger state is the shadow of a cut one dimension up'] = is_cut(X3) and ok(X3[:2], [G, N]) and ok(X3[2] ** 2, 4 * P * Q)
res['whole-number roots give Pythagorean triples'] = all((a * a - b * b) ** 2 + (2 * a * b) ** 2 == (a * a + b * b) ** 2 for a, b in ((2, 1), (3, 2), (4, 1), (4, 3), (5, 2)))

for k in (1, 2, 4, 8):
    r = {}
    good = onto = fibre = neg = True
    for _ in range(100):
        x, y = rng.normal(size=k), rng.normal(size=k); X = c_(x, y)
        good &= is_cut(X) and ok(X[0], x @ x + y @ y)
        neg &= ok(c_(-x, -y), X)
        v = rng.normal(size=k + 1); t = np.linalg.norm(v); a, qq = v[0], v[1:]      # a random cut (t; a, q)
        x0 = np.zeros(k); x0[0] = np.sqrt((t + a) / 2); y0 = conj(qq) / (2 * x0[0])
        onto &= ok(c_(x0, y0), np.concatenate([[t], v]))
        x1 = unitK(k) * np.sqrt((t + a) / 2); y1 = conj(mul(conj(x1), qq)) / (2 * (x1 @ x1))   # another root of the same cut
        fibre &= ok(c_(x1, y1), np.concatenate([[t], v]))
    r['a root squares to a cut, hidden part |psi|^2'] = good
    r['every cut has a root'] = onto
    r['the roots of a cut form a sphere'] = fibre
    r['psi and -psi have the same square'] = neg
    x, y = rng.normal(size=k), rng.normal(size=k); X = c_(x, y); phi, al = 0.8, 0.55
    Xb = c_(np.exp(phi / 2) * x, np.exp(-phi / 2) * y)
    r['boost at half rate'] = ok(Xb[0], np.cosh(phi) * X[0] + np.sinh(phi) * X[1]) and ok(Xb[1], np.sinh(phi) * X[0] + np.cosh(phi) * X[1]) and ok(Xb[2:], X[2:])
    co, si = np.cos(al), np.sin(al); Xt = c_(co * x - si * y, si * x + co * y)
    r['turn at half rate'] = (ok(Xt[0], X[0]) and ok(Xt[1], np.cos(2 * al) * X[1] - np.sin(2 * al) * X[2])
                              and ok(Xt[2], np.sin(2 * al) * X[1] + np.cos(2 * al) * X[2]) and ok(Xt[3:], X[3:]))
    if k <= 4:
        u = unitK(k)
        r['unit multiplications turn q'] = ok(c_(mul(u, x), y)[2:], mul(u, X[2:])) and ok(c_(x, mul(u, y))[2:], mul(X[2:], conj(u))) and ok(c_(mul(u, x), y)[:2], X[:2])
    gu = unitK(k); Xg = c_(mul(gu, x), mul(conj(gu), y))
    r['(gx, conj(g) y) turns q to g q g'] = ok(Xg[:2], X[:2]) and ok(Xg[2:], mul(mul(gu, X[2:]), gu)) and ok(np.linalg.norm(Xg[2:]), np.linalg.norm(X[2:]))
    if k > 1:   # infinitesimally, q -> g q + q g for imaginary g; with commutators these span all rotations of q
        gens = [np.column_stack([mul(E_, b_) + mul(b_, E_) for b_ in np.eye(k)]) for E_ in np.eye(k)[1:]]
        span = list(gens)
        for _ in range(3):
            span += [A_ @ B2 - B2 @ A_ for A_ in span[:40] for B2 in gens]
            span = span[:400]
        r['the maps q -> g q g generate all rotations of q'] = np.linalg.matrix_rank(np.array([m_.ravel() for m_ in span])) == k * (k - 1) // 2
    psi, chi = (x, y), (rng.normal(size=k), rng.normal(size=k))
    r['pairing: symmetric, B(psi,psi) = square'] = ok(B_(psi, chi), B_(chi, psi)) and ok(B_(psi, psi), X)
    r['pairing is the polarization of the square'] = ok(2 * B_(psi, chi), c_(psi[0] + chi[0], psi[1] + chi[1]) - X - c_(*chi))
    Lb = np.eye(k + 2); Lb[0, 0] = Lb[1, 1] = np.cosh(phi); Lb[0, 1] = Lb[1, 0] = np.sinh(phi)
    sc = lambda s: (np.exp(phi / 2) * s[0], np.exp(-phi / 2) * s[1])
    r['pairing commutes with the boost'] = ok(B_(sc(psi), sc(chi)), Lb @ B_(psi, chi))
    if k <= 2:
        w = mul(x, chi[1]) - mul(y, chi[0])
        r['ghost term of two roots = 2|x y2 - y x2|^2'] = ok(eta(X, c_(*chi)), 2 * (w @ w))
    for name, v_ in r.items(): res[f'k={k} (dimension {k + 2}): {name}'] = v_
x, y = rng.normal(size=16), rng.normal(size=16)
res['k=16: the rule fails'] = not is_cut(c_(x, y))

bad = [k for k, v in res.items() if not v]
for k, v in res.items(): print(('PASS  ' if v else 'FAIL  ') + k)
print('ALL PASS' if not bad else 'SOME FAILED')
