"""Numerical checks for 'The Ledger of a Collision' (Paper 19).
Sections 3-6: a Euclidean space of dimension n with view e, cuts v + |v| e, even form eta.
Section 7: K = C, n = 4, roots in C^2, cut c(psi), action Gamma, placed roots of Paper 18.
Python 3 with numpy."""
import numpy as np
rng = np.random.default_rng(19)
ok = lambda a, b, tol=1e-8: np.allclose(a, b, rtol=0, atol=tol)
R = {}
def setup(n):
    eta = lambda x, y: x[0] * y[0] - x[1:] @ y[1:]
    cut = lambda v: np.concatenate([[np.linalg.norm(v)], v])
    return eta, cut
def two_cuts(K, eta, r):                      # a ledger of two cuts with cut sum K, at a random point of the sphere
    m = np.sqrt(eta(K, K)); o = K / m
    nv = r.normal(size=len(K)); nv = nv - eta(nv, o) * o; nv = nv / np.sqrt(-eta(nv, nv))
    return m / 2 * (o + nv), m / 2 * (o - nv), nv
def ledger(K, r_out, eta, cut, r):            # r_out cuts with cut sum K
    out = []; rest = K.copy()
    for _ in range(r_out - 2):
        v = r.normal(size=len(K) - 1); c = cut(v)
        c = c * 0.3 * eta(rest, rest) / (2 * eta(rest, c))      # keeps the remainder forward
        out.append(c); rest = rest - c
    a, b, _ = two_cuts(rest, eta, r); return out + [a, b]

for n in (3, 4, 5, 7):
    eta, cut = setup(n); tag = f'[n={n}] '
    # ---- Section 3: the ghost matrix
    cs = [cut(rng.normal(size=n - 1)) for _ in range(n + 3)]
    Gm = np.array([[eta(a, b) for b in cs] for a in cs]); ev = np.linalg.eigvalsh(Gm)
    R[tag + '3.1 ghost matrix: zero diagonal, entries >= 0, one positive and n-1 negative directions'] = (
        ok(np.diag(Gm), 0) and Gm.min() > -1e-12 and np.sum(ev > 1e-9) == 1 and np.sum(ev < -1e-9) == n - 1)
    R[tag + '3.1 the ghost terms of n+1 cuts have determinant zero; those of n cuts do not'] = (
        abs(np.linalg.det(Gm[:n + 1, :n + 1])) < 1e-8 and abs(np.linalg.det(Gm[:n, :n])) > 1e-8)
    r_ = max(2, n - 1); e2 = np.linalg.eigvalsh(Gm[:r_, :r_])
    R[tag + '3.1 fewer cuts than the dimension: one positive, the rest negative'] = np.sum(e2 > 1e-9) == 1 and np.sum(e2 < -1e-9) == r_ - 1
    # ---- Section 4: collisions
    ins = cs[:3]; K = sum(ins); m2 = eta(K, K); outs = ledger(K, 4, eta, cut, rng)
    R[tag + '4.1 three cuts in, four cuts out, one cut sum'] = ok(sum(outs), K) and all(ok(eta(c, c), 0) and c[0] > 0 for c in outs)
    pair = lambda L: sum(eta(L[i], L[j]) for i in range(len(L)) for j in range(i))
    R[tag + '4.2 the ghost terms of the in-ledger and of the out-ledger have the same sum, m^2/2'] = ok(pair(ins), m2 / 2) and ok(pair(outs), m2 / 2)
    R[tag + '4.2 every cut has the same total ghost with the in-ledger as with the out-ledger'] = all(
        ok(sum(eta(c, a) for a in ins), sum(eta(c, b) for b in outs)) for c in ins + outs + cs[4:6])
    k1, k2 = cs[0], cs[1]; K2 = k1 + k2; m = np.sqrt(eta(K2, K2)); k3, k4, n34 = two_cuts(K2, eta, rng)
    g = eta
    R[tag + '4.3 two in, two out: opposite pairs have equal ghosts; g12 = g13 + g14; m^2 = 2 g12'] = (
        ok(g(k1, k2), g(k3, k4)) and ok(g(k1, k3), g(k2, k4)) and ok(g(k1, k4), g(k2, k3)) and ok(g(k1, k2), g(k1, k3) + g(k1, k4)) and ok(m * m, 2 * g(k1, k2)))
    # ---- Section 5: the sphere of ledgers
    o = K2 / m; n12 = (k1 - k2) / m
    R[tag + '5.1 every two-cut ledger of K is (m/2)(o* +- n) with n a unit of the odd sector of o*'] = ok(eta(n12, o), 0) and ok(eta(n12, n12), -1) and ok(k1, m / 2 * (o + n12))
    cth = -eta(n12, n34)
    R[tag + '5.2 g13 = (m^2/2) sin^2(theta/2), g14 = (m^2/2) cos^2(theta/2)'] = ok(g(k1, k3), m * m / 4 * (1 - cth)) and ok(g(k1, k4), m * m / 4 * (1 + cth))
    gg, kk = K2[0], K2[1:]; e1 = kk / np.linalg.norm(kk); onE = True
    for c_ in (k1, k2, k3, k4):
        w = c_[1:] - kk / 2; par = w @ e1; perp2 = w @ w - par * par
        onE &= ok(par ** 2 / (gg / 2) ** 2 + perp2 / (m / 2) ** 2, 1) and ok(np.linalg.norm(c_[1:]) + np.linalg.norm(kk - c_[1:]), gg)
    R[tag + '5.3 ellipsoid: every corner lies on the ellipsoid with foci 0 and k, long axis the gross, short axes the rest gross'] = bool(onE) and ok(gg * gg, kk @ kk + m * m)
    # ---- Section 6: sub-ledgers
    X = lambda L, i, j: eta(sum(L[i:j]), sum(L[i:j]))
    R[tag + '6.1 mesh: X(i,j+1) - X(i,j) - X(i+1,j+1) + X(i+1,j) = 2 g_ij; forward sub-ledgers have X >= 0'] = (
        all(ok(X(cs, i, j + 1) - X(cs, i, j) - X(cs, i + 1, j + 1) + X(cs, i + 1, j), 2 * g(cs[i], cs[j])) for i in range(3) for j in range(i + 2, 6))
        and all(X(cs, i, j) > -1e-12 for i in range(6) for j in range(i + 1, 7)))
    chain = ins + [-c for c in outs]; x = [np.zeros(n)]
    for c in chain: x.append(x[-1] - c)
    R[tag + '6.2 closed chain: the corners close up and X_ij is the even square of the diagonal x_i - x_j'] = ok(x[-1], 0 * x[0]) and all(
        ok(X(chain, i, j), eta(x[i] - x[j], x[i] - x[j])) for i in range(7) for j in range(i + 1, 7))
    R[tag + '6.2 in a closed chain the X_ij have both signs'] = min(X(chain, i, j) for i in range(7) for j in range(i + 2, 7)) < -1e-9 < max(X(chain, i, j) for i in range(7) for j in range(i + 2, 7))

# ---- Section 8: one formula
for n in (4, 5, 7):
    eta, cut = setup(n); tag = f'[n={n}] '
    ins = [cut(rng.normal(size=n - 1)) for _ in range(3)]; outs = ledger(sum(ins), 3, eta, cut, rng)
    cs = ins + outs; eps = np.array([1, 1, 1, -1, -1, -1.]); N = 6
    Gm = np.array([[eta(a, b) for b in cs] for a in cs])
    R[tag + '8.1 compact form: the signs of a collision are a null vector of its ghost matrix'] = ok(Gm @ eps, 0 * eps)
    good = True
    for _ in range(20):
        S = rng.random(N) < 0.5; eS = eps * S; eC = eps * (~S)
        run = sum(e_ * c_ for e_, c_, s_ in zip(eps, cs, S) if s_) if S.any() else np.zeros(n)
        good &= ok(eta(run, run), eS @ Gm @ eS) and ok(eS @ Gm @ eS, eC @ Gm @ eC)
    R[tag + '8.1 full form: X_S = eps_S G eps_S for every part S of the cuts, and X_S = X of the rest'] = bool(good)
    S = np.array([0, 1, 0, 0, 1, 0], bool); i, j = 2, 5
    XS = lambda S_: (eps * S_) @ Gm @ (eps * S_)
    Si, Sj, Sij = S.copy(), S.copy(), S.copy(); Si[i] = True; Sj[j] = True; Sij[i] = Sij[j] = True
    R[tag + '8.1 adding two cuts to a part: X changes by 2 eps_i eps_j g_ij beyond the two single changes'] = ok(XS(Sij) - XS(Si) - XS(Sj) + XS(S), 2 * eps[i] * eps[j] * Gm[i, j])
    # the ledger alone is the collision: rebuild the cuts from the ghost matrix
    lam, U = np.linalg.eigh(Gm); keep = np.abs(lam) > 1e-9; d = int(keep.sum())
    order = np.argsort(-lam[keep]); lam_k = lam[keep][order]; U_k = U[:, keep][:, order]
    B = (np.sqrt(np.abs(lam_k))[:, None] * U_k.T)                    # d x N, first row the positive direction
    if B[0, 0] < 0: B = -B
    J = np.diag([1.0] + [-1.0] * (d - 1))
    R[tag + '8.2 a matrix with these signs is a ghost matrix: rebuilt cuts are forward, with the same ghost terms'] = (
        lam_k[0] > 0 and np.all(lam_k[1:] < 0) and d <= n and ok(B.T @ J @ B, Gm) and np.all(B[0] > 0) and ok(B @ eps, np.zeros(d)))
    C = np.array(cs).T; Lmap = np.linalg.lstsq(B.T, C.T, rcond=None)[0].T        # the map from rebuilt cuts to the cuts
    Eta = np.diag([1.0] + [-1.0] * (n - 1))
    R[tag + '8.2 and they differ from the cuts by a map that keeps the even form'] = ok(Lmap @ B, C) and ok(Lmap.T @ Eta @ Lmap, J)
# the count of free ghost terms
def free(N_):
    eps = np.array([1.0] * (N_ // 2) + [-1.0] * (N_ - N_ // 2)); pairs = [(a, b) for a in range(N_) for b in range(a)]
    M = np.zeros((N_, len(pairs)))
    for c_, (a, b) in enumerate(pairs): M[a, c_] = eps[b]; M[b, c_] = eps[a]
    return len(pairs) - np.linalg.matrix_rank(M)
R['8.3 free ghost terms of a collision of N cuts = N(N-3)/2, the number of diagonals (N = 4..8)'] = all(free(N_) == N_ * (N_ - 3) // 2 for N_ in range(4, 9))

# ---- Section 7: roots, K = C
eta, _ = setup(4)
vec = lambda H: np.array([(H[0, 0] + H[1, 1]).real / 2, (H[0, 0] - H[1, 1]).real / 2, H[0, 1].real, H[0, 1].imag])   # Gamma(X) -> X
Gam = lambda X: np.array([[X[0] + X[1], X[2] + 1j * X[3]], [X[2] - 1j * X[3], X[0] - X[1]]])
sig = lambda X: np.concatenate([[X[0]], -X[1:]])
c = lambda p: vec(2 * np.outer(p, p.conj()))                    # the cut of a root: Gamma(c(psi)) = 2 psi psi^dagger
area = lambda p, q: p[0] * q[1] - p[1] * q[0]
ps = [rng.normal(size=2) + 1j * rng.normal(size=2) for _ in range(6)]
R['7.1 c(psi) = (|x|^2+|y|^2; |x|^2-|y|^2, 2 x conj y) is a cut, and Gamma(sigma c(psi)) psi = 0'] = all(
    ok(c(p), [abs(p[0]) ** 2 + abs(p[1]) ** 2, abs(p[0]) ** 2 - abs(p[1]) ** 2, (2 * p[0] * p[1].conj()).real, (2 * p[0] * p[1].conj()).imag])
    and ok(eta(c(p), c(p)), 0) and ok(Gam(sig(c(p))) @ p, 0) for p in ps)
R['7.1 ghost of two cuts = 2 |area of the two roots|^2'] = all(ok(eta(c(ps[i]), c(ps[j])), 2 * abs(area(ps[i], ps[j])) ** 2) for i in range(6) for j in range(i))
# a collision of two and two, by roots
k1, k2 = c(ps[0]), c(ps[1]); k3, k4, _ = two_cuts(k1 + k2, eta, rng)
def root(k):
    w, v = np.linalg.eigh(Gam(k) / 2); return v[:, 1] * np.sqrt(w[1])
L = [ps[0], ps[1], root(k3), root(k4)]; kk = [k1, k2, k3, k4]; G2 = lambda i, j: eta(kk[i], kk[j])
PT = abs(area(L[0], L[1])) ** 4 / abs(area(L[0], L[1]) * area(L[1], L[2]) * area(L[2], L[3]) * area(L[3], L[0]))
R['7.2 the squared size of A12^4/(A12 A23 A34 A41) is g12^4/(g12 g23 g34 g41)'] = ok(PT ** 2, G2(0, 1) ** 4 / (G2(0, 1) * G2(1, 2) * G2(2, 3) * G2(3, 0)))
# a closed chain of six cuts and the box of four placed roots
Hin = sum(np.outer(p, p.conj()) for p in ps[:3]); r = np.random.default_rng(7)
def inside(M):
    z = r.normal(size=2) + 1j * r.normal(size=2); return z / np.sqrt(np.real(z.conj() @ np.linalg.inv(M) @ z))
l4 = 0.6 * inside(Hin); M2 = Hin - np.outer(l4, l4.conj()); l5 = inside(M2); M3 = M2 - np.outer(l5, l5.conj())
w, v = np.linalg.eigh(M3); l6 = v[:, 1] * np.sqrt(w[1])
rs = ps[:3] + [l4, l5, l6]; sgn = [1, 1, 1, -1, -1, -1]; ch = [s * c(p) for s, p in zip(sgn, rs)]
x = [np.zeros(4)]
for cc in ch: x.append(x[-1] - cc)
R['7.3 three cuts in and three out close up'] = ok(w[0], 0) and ok(x[-1], 0 * x[0])
Z = lambda i, at: np.concatenate([rs[i], Gam(sig(x[at])) @ rs[i]])          # the placed root of psi_i at the corner x_at
R['7.3 each root is at both corners of its edge'] = all(ok(Z(i, i), Z(i, i + 1)) for i in range(6))
good = True
for i in range(6):
    for j in range(i + 2, 6):
        if (i - 1) % 6 == j: continue
        a, b = (i - 1) % 6, (j - 1) % 6
        box = np.linalg.det(np.array([Z(a, i), Z(i, i), Z(b, j), Z(j, j)]).T)
        good &= ok(box, area(rs[a], rs[i]) * area(rs[b], rs[j]) * eta(x[j] - x[i], x[j] - x[i]))
        good &= ok(np.linalg.det(Gam(sig(x[j] - x[i]))), eta(x[j] - x[i], x[j] - x[i]))
R['7.4 the box of four placed roots = area * area * even square of the diagonal (nine diagonals)'] = bool(good)

# ---- Theorem 5.2(3): the bowtie, for three numbers
def crosses(P):                                  # does the closed figure P0 P1 P2 P3 cross itself
    o = lambda a, b, c: np.sign((b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]))
    x = lambda p, q, r, s: o(p, q, r) != o(p, q, s) and o(r, s, p) != o(r, s, q)
    return x(P[0], P[1], P[2], P[3]) or x(P[1], P[2], P[3], P[0])
eta, cut = setup(3); one = same = alt = True
for _ in range(2000):
    c1, c2 = cut(rng.normal(size=2)), cut(rng.normal(size=2)); Kb = c1 + c2
    c3, c4, _n = two_cuts(Kb, eta, rng); v1, v2, v3, v4 = c1[1:], c2[1:], c3[1:], c4[1:]; kk = Kb[1:]
    fig = lambda seq: np.cumsum([np.zeros(2)] + seq[:3], axis=0)
    side = lambda p: np.sign(kk[0] * p[1] - kk[1] * p[0])
    xa, xb = crosses(fig([v1, v2, -v3, -v4])), crosses(fig([v1, v2, -v4, -v3]))
    one &= (xa != xb)
    same &= (xa == (side(v4) == side(v1))) and (xb == (side(v3) == side(v1)))
    alt &= not crosses(fig([v1, -v3, v2, -v4])) and not crosses(fig([v1, -v4, v2, -v3]))
R['5.4 bowtie (n=3): exactly one of the two orders of the cuts coming out crosses itself'] = bool(one)
R['5.4 bowtie (n=3): it is the one whose fourth corner is on the same side of the net as the first corner'] = bool(same)
R['5.4 bowtie (n=3): the alternating orders never cross'] = bool(alt)

bad = [k for k, v in R.items() if not v]
for k, v in R.items(): print(('ok   ' if v else 'FAIL ') + k)
print(f'{len(R)} checks:', 'ALL PASS' if not bad else 'FAILURES')
