"""Numerical checks for 'The Small Step'.
V is R^d with viewpoint e. The product with square c is
    x . y = (ab + c<x',y'>) e + a y' + b x',
c = -1 the turn product, c = 0 the tangent product, c = +1 the ledger product."""
import numpy as np
rng = np.random.default_rng(7)
ok = lambda a, b, tol=1e-8: np.allclose(a, b, rtol=0, atol=tol)      # absolute tolerance only
R = {}
d = 5; e = np.eye(d)[0]; f = np.eye(d)[1]
def prod(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
turn, tang, led = prod(-1), prod(0), prod(1)
def power(x, n, pr):                                   # x^n by repeated squaring (powers stay in a plane)
    r = e.copy()
    while n:
        if n & 1: r = pr(r, x)
        x = pr(x, x); n >>= 1
    return r
odd = lambda: (lambda v: v - (v @ e) * e)(rng.normal(size=d))
v, w = odd(), odd(); b = v / np.linalg.norm(v)

# ---------------------------------------------------------------- the small step
R['the products differ only by c<v,w>e'] = all(
    ok(prod(c)(e + v, e + w), e + v + w + c * (v @ w) * e) and
    ok(prod(c)(2 * e + v, 3 * e + w) - tang(2 * e + v, 3 * e + w), c * (v @ w) * e) for c in (-1, 0, 1, 0.37, -2.5))
th = 1.234; n = 2 ** 22
R['one step, three outcomes: circle, line, boost'] = (
    ok(power(e + th * b / n, n, turn), np.cos(th) * e + np.sin(th) * b, 1e-5)
    and all(ok(power(e + th * b / m, m, tang), e + th * b) for m in (1, 2, 7, 1000))
    and ok(power(e + th * b / n, n, led), np.cosh(th) * e + np.sinh(th) * b, 1e-5))
c_ = 0.6; R['outcome for a general square c'] = (
    ok(power(e + th * b / n, n, prod(c_)), np.cosh(np.sqrt(c_) * th) * e + np.sinh(np.sqrt(c_) * th) / np.sqrt(c_) * b, 1e-5)
    and ok(power(e + th * b / n, n, prod(-c_)), np.cos(np.sqrt(c_) * th) * e + np.sin(np.sqrt(c_) * th) / np.sqrt(c_) * b, 1e-5))

good = True
for c in (-1, 0, 1, 0.5, -2.0):                                         # the second order decides
    for t_ in (1e-2, 1e-3):
        good &= np.linalg.norm(power(e + t_ * b / n, n, prod(c)) - (e + t_ * b + 0.5 * c * t_ ** 2 * e)) < 5 * t_ ** 3 + 1e-9
R['outcome = e + theta b + (c theta^2 / 2) e to second order, for every c'] = good

# ---------------------------------------------------------------- the derivative
co = rng.normal(size=7); P = np.polynomial.Polynomial(co)
def peval(coef, x, pr):
    r = 0 * e; pw = e.copy()
    for cc in coef: r = r + cc * pw; pw = pr(pw, x)
    return r
a, h = 0.7, 0.4; x = a * e + h * b
R['tangent product: value on the line, derivative on the odd part'] = ok(peval(co, x, tang), P(a) * e + P.deriv()(a) * h * b)
R['ledger product: half sum and half difference across the two halves'] = ok(
    peval(co, x, led), 0.5 * (P(a + h) + P(a - h)) * e + 0.5 * (P(a + h) - P(a - h)) * b)
R['turn product: the complex value'] = ok(peval(co, x, turn), P(a + 1j * h).real * e + P(a + 1j * h).imag * b)
from math import factorial
good = True
for c in (-1, 1, 0.3, -1.7, 0):
    ev = sum(c ** j * h ** (2 * j) * P.deriv(2 * j)(a) / factorial(2 * j) for j in range(4))
    od = sum(c ** j * h ** (2 * j) * P.deriv(2 * j + 1)(a) / factorial(2 * j + 1) for j in range(4))
    good &= ok(peval(co, x, prod(c)), ev * e + od * h * b)
R['general formula for a polynomial in the product with square c'] = good
good = True
for hh in (1e-2, 1e-3):
    xl = a * e + hh * b; el = (peval(co, xl, led) @ b) / hh - P.deriv()(a); et = (peval(co, xl, turn) @ b) / hh - P.deriv()(a)
    lead = P.deriv(3)(a) * hh ** 2 / 6
    good &= abs(el - lead) < 10 * hh ** 4 and abs(et + lead) < 10 * hh ** 4
R['common boundary: both sides tend to the derivative, with opposite leading errors'] = good
co2 = rng.normal(size=4); Q = np.polynomial.Polynomial(co2)
px, qx = peval(co, x, tang), peval(co2, x, tang)
R['product rule is multiplicativity in the tangent product'] = ok(tang(px, qx), (P * Q)(a) * e + (P * Q).deriv()(a) * h * b)
R['chain rule is substitution in the tangent product'] = ok(peval(co, qx, tang), P(Q(a)) * e + P.deriv()(Q(a)) * Q.deriv()(a) * h * b)

# ---------------------------------------------------------------- halving and pi
half = lambda z: (e + z) / np.linalg.norm(e + z)                        # the unit along the diagonal of e and z
good = True
for _ in range(20):
    t = rng.uniform(-3, 3); z = np.cos(t) * e + np.sin(t) * b; hz = half(z)
    good &= ok(turn(hz, hz), z) and ok(hz @ e, np.sqrt((1 + z @ e) / 2)) and ok(np.linalg.norm(hz), 1)
R['the half of a unit is a square root of it; its even part is sqrt((1+c)/2)'] = good
z = f.copy(); G = []; cs = [z @ e]; good = ok(turn(f, f), -e); mono = True; path_ok = True
for k in range(1, 27):
    if k <= 10:                                                         # the path really runs from e to -e in equal steps
        pts = [power(z, j, turn) for j in range(2 ** k + 1)]
        steps = [q - p for p, q in zip(pts, pts[1:])]
        path_ok &= ok(pts[-1], -e) and ok([np.linalg.norm(s_) for s_ in steps], np.linalg.norm(z - e))
        path_ok &= ok(sum(steps), -2 * e)
        if k <= 6:                                                      # triangle equality of Paper III for this ledger
            gam = sum(np.linalg.norm(p) * np.linalg.norm(q) - p @ q for i, p in enumerate(steps) for q in steps[i + 1:])
            path_ok &= ok(sum(np.linalg.norm(s_) for s_ in steps) ** 2, 4 + 2 * gam)
    G.append(2 ** k * np.linalg.norm(z - e)); z = half(z); cs.append(z @ e)
    if 1 < k <= 20: mono &= G[-1] > G[-2]                             # strictly, while above rounding
R['halving gives a path of 2^k equal steps from e to -e with net 2'] = good and path_ok
R['the gross increases and converges'] = mono and abs(G[-1] - G[-2]) < 1e-12
PI = G[-1]
R['the limit is pi'] = ok(PI, np.pi, 1e-9)
R['gross = 2 / product of even parts (each halving multiplies net/gross by the next even part)'] = all(
    ok(G[k - 1], 2 / np.prod(cs[1:k + 1])) for k in range(1, 20))
R['net over gross of the half step: 2/pi = product of the even parts of the successive roots'] = ok(np.prod(cs[1:]), 2 / np.pi, 1e-9)
R['even parts obey c -> sqrt((1+c)/2) from 0'] = ok(cs[1], np.sqrt(0.5)) and ok(cs[2], np.sqrt(2 + np.sqrt(2)) / 2) and all(
    ok(cs[j + 1], np.sqrt((1 + cs[j]) / 2)) for j in range(20))
R['1 - c halves at least at every step'] = all(1 - cs[j + 1] <= (1 - cs[j]) / 2 + 1e-15 for j in range(20))
table = {1: (2.8284271, 2.0000000), 2: (3.0614675, 2.6862915), 3: (3.1214452, 2.8717099), 4: (3.1365485, 2.9189682), 5: (3.1403312, 2.9308399)}
R['the printed table of gross and ghost, and the ghost limit (pi^2 - 4)/2'] = all(
    abs(G[k - 1] - g_) < 5e-8 and abs((G[k - 1] ** 2 - 4) / 2 - gh_) < 5e-8 for k, (g_, gh_) in table.items()) and (
    abs((G[-1] ** 2 - 4) / 2 - 2.9348022) < 5e-8 and abs(np.pi ** 2 / 8 - 1 - (np.pi ** 2 / 4 - 2) / 2) < 1e-12)
z = f.copy(); good = True
for k in range(1, 9):                                                   # a step is the net of two steps of the next level
    zn = half(z); a1 = zn - e; a2 = turn(zn, zn) - zn
    good &= ok(a1 + a2, z - e) and ok(np.linalg.norm(z - e) / (np.linalg.norm(a1) + np.linalg.norm(a2)), half(zn) @ e)
    z = zn
R['each halving: two equal steps whose net is the old step; net/gross of the pair is the next even part'] = good
lam_ = 0.37; Dl = lambda x_: (x_ @ e) * e + lam_ * (x_ - (x_ @ e) * e); x1, y1 = rng.normal(size=d), rng.normal(size=d)
R['shrinking the odd sector by lambda turns square c into c lambda^2'] = all(
    ok(prod(c)(Dl(x1), Dl(y1)), Dl(prod(c * lam_ ** 2)(x1, y1))) for c in (-1, 1, 0.5))
z = f.copy()
for k in range(1, 22): z = half(z)
R['the scaled small step tends to pi f'] = ok(2 ** 22 * (z - e), np.pi * f, 1e-5)
R['pi of motion is the half step; 2 pi of motion is the full loop'] = (
    ok(power(e + np.pi * f / n, n, turn), -e, 1e-5) and ok(power(e + 2 * np.pi * f / n, n, turn), e, 1e-5)
    and ok(power(e + np.pi / 2 * f / n, n, turn), f, 1e-5))
z = f.copy()
for k in range(1, 14): z = half(z)                                      # z is now a 2^14-th root of -e
quarter = power(z, 2 ** 13, turn); full = power(z, 2 ** 15, turn); st = np.linalg.norm(z - e)
R['quarter step: net sqrt 2, gross pi/2; full loop: net 0, gross 2 pi, all ghost'] = (
    ok(quarter, f) and ok(np.linalg.norm(quarter - e), np.sqrt(2)) and ok(2 ** 13 * st, np.pi / 2, 1e-7)
    and ok(full, e) and ok(2 ** 15 * st, 2 * np.pi, 1e-7))

# ---------------------------------------------------------------- three ledgers: 2 < pi < 4
z = f.copy(); good = True
for k in range(1, 11):
    pts = [power(z, j, turn) for j in range(2 ** k + 1)]; steps = [q - p for p, q in zip(pts, pts[1:])]
    g2 = np.linalg.norm(sum(steps)); gk = sum(np.linalg.norm(s_) for s_ in steps)
    g4 = sum(abs(s_ @ e) + abs(s_ @ f) for s_ in steps)
    good &= ok(g2, 2) and ok(g4, 4) and 2 < gk < np.pi < 4
    z = half(z)
tail = np.prod(cs[2:]); bound = 1 - 2 * (1 - cs[2])                  # c_3 c_4 ... >= 1 - 2(1 - c_3) > 0.84
R['three ledgers of the half step: gross 2, G_k and exactly 4 at every refinement'] = good
R['bound chain for pi < 4: c_3 c_4 ... >= 1 - 2(1 - c_3) > 0.84, so pi < 3.4'] = (
    tail >= bound > 0.84 and ok(PI, 2 * np.sqrt(2) / tail, 1e-12) and 2 * np.sqrt(2) / bound < 3.4)

# ---------------------------------------------------------------- pi in the three products
good = True; b2 = np.eye(d)[2]
for r_ in (0.3, 1.0, np.pi / 2, 2.0):
    for c, Ofun in ((-1, np.sin), (0, lambda t_: t_), (1, np.sinh)):
        ring = [power(e + r_ * (np.cos(a_) * f + np.sin(a_) * b2) / 2 ** 20, 2 ** 20, prod(c))
                          for a_ in np.linspace(0, 2 * np.pi, 41)]
        circ = sum(np.linalg.norm(q - p) for p, q in zip(ring, ring[1:])) / (40 * np.sin(np.pi / 40) / np.pi)  # polygon -> circle
        good &= ok(circ / (2 * r_), np.pi * Ofun(r_) / r_, 1e-4) and ok([p @ e for p in ring], ring[0] @ e, 1e-5)
R['circumference/diameter = pi sin r/r, pi, pi sinh r/r in the three products (equator measured: 2)'] = good

# ---------------------------------------------------------------- velocity and the two readers
U = lambda t: np.cos(t) * e + np.sin(t) * f; t0 = 0.77; dl = 1e-6
vel = (U(t0 + dl) - U(t0 - dl)) / (2 * dl)
R['velocity is the quarter step ahead, perpendicular to the state'] = (
    ok(vel, U(t0 + np.pi / 2), 1e-6) and ok(vel, turn(f, U(t0)), 1e-6) and ok(vel @ U(t0), 0, 1e-6))
good = True
for dim in (2, 4, 8):                                                   # exact, any dimension, any two units
    for _ in range(50):
        uu, vv = rng.normal(size=dim), rng.normal(size=dim); uu /= np.linalg.norm(uu); vv /= np.linalg.norm(vv)
        gam = 1 - uu @ vv
        good &= ok(gam, 0.5 * np.linalg.norm(vv - uu) ** 2) and ok(uu @ (vv - uu), -gam)
R['exact: ghost of two units = half the squared distance = minus what the reader at u sees'] = good
good = True
for dlt in (1e-1, 1e-2, 1e-3):
    ghost = 1 - U(t0) @ U(t0 + dlt)                                     # ghost term of the two states
    good &= abs(ghost - dlt ** 2 / 2) < dlt ** 4 and ok((U(t0 + dlt) - U(t0)) @ U(t0), -ghost)
R['the reader on the point sees the motion only through the ghost, at second order'] = good
good = True
for dlt in (0.4, 0.1, 0.02, -0.1, -0.4):                                 # signed motion: use |delta|
    arc, chord = abs(dlt), np.linalg.norm(U(t0 + dlt) - U(t0))
    good &= abs((arc - chord) - abs(dlt) ** 3 / 24) < abs(dlt) ** 5
R['gross minus net of a short arc is motion^3 / 24'] = good

# ---------------------------------------------------------------- the roots (K = C): half the motion
k_ = 2
def cmul(x_, y_): return np.array([x_[0] * y_[0] - x_[1] * y_[1], x_[0] * y_[1] + x_[1] * y_[0]])
cconj = lambda x_: np.array([x_[0], -x_[1]])
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 + cmul(uu, yy), cmul(cconj(uu), xx) + (t_ - a_) * yy])
Gm = lambda X: np.column_stack([act(X, bb) for bb in np.eye(2 * k_)])
J = Gm(np.eye(4)[1]) @ Gm(np.eye(4)[2]); I4 = np.eye(4)
Rr = lambda th_: np.cos(th_ / 2) * I4 + np.sin(th_ / 2) * J              # roots, for motion th_ of the space
psi = rng.normal(size=4); m_ = 4000
pts = [Rr(2 * np.pi * j / m_) @ psi for j in range(m_ + 1)]
gross_root = sum(np.linalg.norm(q - p) for p, q in zip(pts, pts[1:]))
sqC = lambda p: np.concatenate([[p[:2] @ p[:2] + p[2:] @ p[2:], p[:2] @ p[:2] - p[2:] @ p[2:]], 2 * cmul(p[:2], cconj(p[2:]))])
th_ = 0.9; c0, c1 = sqC(psi), sqC(Rr(th_) @ psi)                         # the cut turns by th_ in the plane of E1, E2
rot = np.eye(4); rot[1:3, 1:3] = [[np.cos(th_), np.sin(th_)], [-np.sin(th_), np.cos(th_)]]
turns = ok(c1, rot @ c0) or ok(c1, rot.T @ c0)
R['2 pi of motion carries a root to its negative; its path has net 2|psi| and gross pi|psi|'] = (
    turns and ok(J @ J, -I4) and ok(Rr(2 * np.pi), -I4) and ok(Rr(4 * np.pi), I4) and ok(np.linalg.norm(pts[-1] - pts[0]), 2 * np.linalg.norm(psi))
    and ok(gross_root, np.pi * np.linalg.norm(psi), 1e-5))

# ---------------------------------------------------------------- moving roots (R, C, H, O)
def conjg(x_):
    c2 = -x_.copy(); c2[0] = x_[0]; return c2
def mulK(x_, y_):
    m = len(x_)
    if m == 1: return x_ * y_
    h_ = m // 2; a1, b1, c1, d1 = x_[:h_], x_[h_:], y_[:h_], y_[h_:]
    return np.concatenate([mulK(a1, c1) - mulK(conjg(d1), b1), mulK(d1, a1) + mulK(b1, conjg(c1))])
wave = True; carried = True
for kk in (1, 2, 4, 8):
    nn = kk + 2
    def actK(X, p):
        xx, yy = p[:kk], p[kk:]; t_, a_, uu = X[0], X[1], X[2:]
        return np.concatenate([(t_ + a_) * xx + mulK(uu, yy), mulK(conjg(uu), xx) + (t_ - a_) * yy])
    GK = lambda X: np.column_stack([actK(X, bb) for bb in np.eye(2 * kk)])
    flat = lambda X: np.concatenate([[-X[0]], X[1:]]); etaK = lambda X, Y: X[0] * Y[0] - X[1:] @ Y[1:]
    E_ = np.eye(nn); I_ = np.eye(2 * kk)
    for _ in range(5):                                                  # symbol of the two operators on a mode with wave vector kv
        kv = rng.normal(size=nn)
        wave &= ok(GK(flat(kv)) @ GK(kv), -etaK(kv, kv) * I_)
    wave &= all(ok(GK(flat(E_[m_])) @ GK(E_[n_]) + GK(flat(E_[n_])) @ GK(E_[m_]), -2 * etaK(E_[m_], E_[n_]) * I_)
                for m_ in range(nn) for n_ in range(nn))             # so the mixed derivatives combine to minus the wave operator
    psi0 = rng.normal(size=2 * kk); xx, yy = psi0[:kk], psi0[kk:]
    Kc = np.concatenate([[xx @ xx + yy @ yy, xx @ xx - yy @ yy], 2 * mulK(xx, conjg(yy))])     # the cut of psi0
    gfun = lambda s_: np.sin(1.3 * s_) + 0.5 * s_ ** 2
    field = lambda X: gfun(etaK(Kc, X)) * psi0
    X0 = rng.normal(size=nn); hh = 1e-5
    Dpsi = sum(GK(E_[m_]) @ (field(X0 + hh * E_[m_]) - field(X0 - hh * E_[m_])) / (2 * hh) for m_ in range(nn))
    vhat = Kc[1:] / np.linalg.norm(Kc[1:])
    carried &= np.linalg.norm(Dpsi) < 1e-6 * max(1, np.linalg.norm(psi0) ** 3) * 100 and ok(etaK(Kc, Kc), 0)
    carried &= ok(etaK(Kc, X0), Kc[0] * (X0[0] - vhat @ X0[1:]))
    h2 = 1e-3; second = lambda m_: (field(X0 + h2 * E_[m_]) - 2 * field(X0) + field(X0 - h2 * E_[m_])) / h2 ** 2
    box = second(0) - sum(second(m_) for m_ in range(1, nn))
    carried &= np.linalg.norm(box) < 1e-4 * (1 + np.linalg.norm(Kc) ** 3) * (1 + np.linalg.norm(psi0))
    other = lambda X: gfun(etaK(Kc + 0.3 * E_[2], X)) * psi0            # not along its own cut: does not solve it
    Dbad = sum(GK(E_[m_]) @ (other(X0 + hh * E_[m_]) - other(X0 - hh * E_[m_])) / (2 * hh) for m_ in range(nn))
    carried &= np.linalg.norm(Dbad) > 1e-3
R['the action with derivatives factors the wave operator (R, C, H, O)'] = wave
R['a root carried along its own cut solves the first-order equation; another direction does not'] = carried

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')
