"""Receipt for "Unified Field Theory": exact reader.
Exact arithmetic in Q(sqrt 5) (sympy, expand-canonical), integers and Fractions; seeded finite trials use random.Random(35).
Angles and logs are handled as symbols (theta, u, log Phi) or as rational multiples of pi; no floating point enters a verdict.
Prints PASS/FAIL/INFO lines, a count line and RESULT PASS|FAIL; exits nonzero on any FAIL.
Usage: python3 check_uft.py [results.json]"""
from __future__ import annotations

import json
import random
import sys
from fractions import Fraction as F
from math import gcd

import sympy as sp

sys.dont_write_bytecode = True
if hasattr(sys.stdout, "reconfigure"):
    sys.stdout.reconfigure(newline="\n")  # the receipt is LF-terminated on every platform
OK = True
LABELS = []


def line(label, cond):
    global OK
    cond = bool(cond)
    OK = OK and cond
    LABELS.append((label, cond))
    print(("PASS " if cond else "FAIL ") + label)


def info(label):
    print("INFO " + label)


s5 = sp.sqrt(5)
Phi = (1 + s5) / 2
I2 = sp.eye(2)
I4 = sp.eye(4)
Z2 = sp.zeros(2, 2)


def ex(M):
    return M.applyfunc(lambda e: sp.expand(sp.radsimp(sp.expand(e))))


def zero(M):
    return all(sp.simplify(e) == 0 for e in sp.Matrix(M))


def eq(A, B):
    return zero(A - B)


def dsum(A, B):
    n, m = A.shape[0], B.shape[0]
    M = sp.zeros(n + m, n + m)
    M[:n, :n] = A
    M[n:, n:] = B
    return M


def comm(A, B):
    return A * B - B * A


def inertia(M):
    """(positive, negative, zero) eigenvalue counts of a real symmetric matrix, exact, by Descartes on the characteristic polynomial (all roots real)."""
    lam = sp.symbols("lam")
    p = sp.Poly(M.charpoly(lam).as_expr(), lam)
    c = p.all_coeffs()
    z = 0
    while c and c[-1] == 0:
        c.pop()
        z += 1

    def changes(cs):
        cs = [x for x in cs if x != 0]
        return sum(1 for a, b in zip(cs, cs[1:]) if a * b < 0)

    pos = changes(c)
    c_neg = [x * (-1) ** (len(c) - 1 - i) for i, x in enumerate(c)]
    neg = changes(c_neg)
    return (pos, neg, z)


def sym(M):
    return M == M.T


# ----------------------------------------------------------------------------------------------------------
# model: every object is a word in the two root matrices; parameters allow one-fault mutations
# ----------------------------------------------------------------------------------------------------------
Q0 = sp.Matrix([[1, 1], [1, 0]])
Om0 = sp.Matrix([[0, 1], [-1, 0]])
BASE = dict(Q=Q0, Om=Om0, Gmode="comm", Gcorner=None, tail=I2, Chat_tail=None, Jpos="lower", Lmode="cosh", c=1, p=137, Pi=None, U=None, chi=sp.Rational(-3, 7))


def build(P):
    Q, Om = P["Q"], P["Om"]
    C1 = -Om
    G = comm(Q, Om) if P["Gmode"] == "comm" else Q * Om
    G = ex(G)
    if P["Gcorner"] is not None:
        G = sp.Matrix([[P["Gcorner"], 1], [1, 2]])
    H = ex(G / s5)
    S = ex(H * C1)
    eta = dsum(G, P["tail"])
    Chat_tail = C1 if P["Chat_tail"] is None else P["Chat_tail"]
    Chat = dsum(Z2, Chat_tail) if not P.get("Chat_both") else dsum(C1, C1)
    B = dsum(S, Z2) * P.get("Bsign", 1)
    J = dsum(Z2, C1) if P["Jpos"] == "lower" else dsum(C1, Z2)
    if P["Lmode"] == "cosh":
        L = ex(s5 / 2 * I2 + S / 2)
    else:
        L = ex(I2 + S / 2)
    return dict(Q=Q, Om=Om, C1=C1, G=G, H=H, S=S, eta=eta, Chat=Chat, B=B, J=J, L=L)


def rand_pi(rng, singular=False):
    while True:
        Pi = sp.Matrix(4, 4, lambda i, j: rng.randint(-4, 4))
        if singular:
            Pi[3, :] = Pi[0, :] + Pi[1, :]
            return Pi
        if Pi.det() != 0:
            return Pi


def frame_stress(F, eta_):
    """T_AB = F_AC eta^CD F_BD - 1/4 eta_AB F_CD F^CD in frame indices."""
    ei_ = eta_.inv()
    F2 = sum(F[a, b] * (ei_ * F * ei_)[a, b] for a in range(4) for b in range(4))
    return (F * ei_ * F.T - sp.Rational(1, 4) * eta_ * F2).applyfunc(sp.simplify)


def frame_star(F, eta_):
    """Hodge dual of a frame 2-form for the reference eta_: (*F)_AB = 1/2 sqrt|det eta_| eps_ABCD F^CD."""
    ei_ = eta_.inv()
    Fu = ei_ * F * ei_
    v = sp.sqrt(abs(eta_.det()))
    return sp.Matrix(4, 4, lambda a, b: sp.simplify(v * sum(sp.LeviCivita(a, b, c, d) * Fu[c, d] for c in range(4) for d in range(4)) / 2))


def preds(P, trials=40):
    """The predicates of the audit. Each returns bool."""
    o = build(P)
    Q, Om, C1, G, S, eta, Chat, B, J, L = (o[k] for k in "Q Om C1 G S eta Chat B J L".split())
    r = {}
    r["Q2"] = eq(Q * Q, Q + I2)
    r["Om2"] = eq(Om * Om, -I2)
    r["G2"] = eq(G * G, 5 * I2)
    r["sig"] = sym(eta) and inertia(eta) == (3, 1, 0)
    r["Chat"] = Chat == -Chat.T and Chat.rank() == 2
    r["seam"] = zero(comm(s5 * B, J))
    r["stab"] = all(zero(X.T * Y + Y * X) for X in (B, J) for Y in (eta, Chat))
    if eta.det() == 0:
        r["stress"] = False  # no inverse reference, no stress to read
    else:
        Tf = frame_stress(Chat, eta)
        Tm = (eta.inv() * Tf).applyfunc(sp.simplify)
        r["stress"] = zero(Tf - sp.Rational(1, 2) * dsum(-eta[:2, :2], eta[2:, 2:])) and sp.simplify(Tm.trace()) == 0 and zero(Tm * Tm - sp.Rational(1, 4) * I4)
    r["fieldseam"] = eta.det() != 0 and zero(eta.inv() * Chat - J) and zero(eta.inv() * frame_star(Chat, eta) - B)
    r["return"] = eq(L * L, Q * Q)
    r["kappa"] = F(P["c"]) == 1  # kappa = c pi / log Phi: the phase angle at lambda = log Phi is 2 c pi, exactly one turn iff c = 1
    r["prime"] = sp.isprime(P["p"]) and gcd(4, P["p"]) == 1
    r["crt"] = len({(137 // 137 * 0 + P["p"] * q + 4 * s) % (4 * P["p"]) for q in range(4) for s in range(P["p"])}) == 4 * P["p"]
    # recognition: U keeps G, keeps every line, moves every vector
    Uv = P["U"] if P["U"] is not None else -I2
    v1, v2 = sp.symbols("v1 v2", real=True)
    v = sp.Matrix([v1, v2])
    keeps_G = eq(Uv.T * G * Uv, G)
    w = Uv * v
    keeps_line = sp.expand(v1 * w[1] - v2 * w[0]) == 0
    moves = any(sp.simplify(e) != 0 for e in (Uv - I2))
    r["recog"] = keeps_G and keeps_line and moves
    rng = random.Random(35)
    ok = True
    for _ in range(trials):
        Pi = P["Pi"] if P["Pi"] is not None else rand_pi(rng)
        g = Pi.T * eta * Pi
        if not (sym(g) and inertia(g) == (3, 1, 0)):
            ok = False
            break
    r["gsig"] = ok
    okf = True
    rng = random.Random(35)
    for _ in range(trials):
        Pi = P["Pi"] if P["Pi"] is not None else rand_pi(rng)
        f = P["chi"] * (Pi.T * Chat * Pi)
        if not (f == -f.T and f.rank() == 2):
            okf = False
            break
    r["fnz"] = okf
    return r


# ----------------------------------------------------------------------------------------------------------
print("# A. The root")
Q, Om, C1 = Q0, Om0, -Om0
G = ex(comm(Q, Om))
H = ex(G / s5)
S = ex(H * C1)
line("A1 Q^2 = Q + I", eq(Q * Q, Q + I2))
line("A2 Omega^2 = -I, C1 = -Omega, C1^2 = -I", eq(Om * Om, -I2) and eq(C1 * C1, -I2))
line("A3 G = [Q, Omega] = [[-2, 1], [1, 2]]", G == sp.Matrix([[-2, 1], [1, 2]]))
line("A4 G^2 = 5 I, tr G = 0, det G = -5", eq(G * G, 5 * I2) and G.trace() == 0 and G.det() == -5)
line("A5 G is symmetric of signature (1, 1)", sym(G) and inertia(G) == (1, 1, 0))
line("A6 Omega G = -G Omega (G anticommutes with Omega)", eq(Om * G, -G * Om))
line("A7 H = G/sqrt5: H^2 = I, H^T G H = G", eq(H * H, I2) and eq(H.T * G * H, G))
line("A8 S = H C1 = Omega H = (2Q - I)/sqrt5, S^2 = I", eq(S, Om * H) and eq(S, (2 * Q - I2) / s5) and eq(S * S, I2))
line("A9 S^T G + G S = 0 and H S H = -S", zero(S.T * G + G * S) and eq(H * S * H, -S))
phi, phib = Phi, 1 - Phi
v_plus, v_minus = sp.Matrix([Phi, 1]), sp.Matrix([-1, Phi])
line("A10 the null lines of G are (Phi, 1) and (-1, Phi)", sp.simplify((v_plus.T * G * v_plus)[0]) == 0 and sp.simplify((v_minus.T * G * v_minus)[0]) == 0)
line("A11 these are the eigenlines of Q, eigenvalues Phi and 1 - Phi", eq(Q * v_plus, Phi * v_plus) and eq(Q * v_minus, (1 - Phi) * v_minus))
line("A12 Phi^2 = Phi + 1, Phi (1 - Phi) = -1, Phi - 1/Phi = 1, Phi + 1/Phi = sqrt5", sp.expand(Phi**2 - Phi - 1) == 0 and sp.expand(Phi * (1 - Phi) + 1) == 0 and sp.simplify(Phi - 1 / Phi) == 1 and sp.simplify(Phi + 1 / Phi - s5) == 0)
line("A13 S^n = S^(n mod 2) for n = 0..12, so exp(sS) = cosh s I + sinh s S", all(eq(S**n, S if n % 2 else I2) for n in range(13)))
sh = sp.symbols("s", real=True)
Ls = lambda t: sp.cosh(t) * I2 + sp.sinh(t) * S
line("A14 L_s^T G L_s = G for all s (symbolic)", all(sp.simplify(e) == 0 for e in (Ls(sh).T * G * Ls(sh) - G).applyfunc(lambda x: sp.simplify(sp.expand(x.rewrite(sp.exp))))))
line("A15 H L_s H = L_{-s} for all s (symbolic)", all(sp.simplify(e) == 0 for e in (H * Ls(sh) * H - Ls(-sh)).applyfunc(lambda x: sp.simplify(x.rewrite(sp.exp)))))
lg = sp.log(Phi)
cL = sp.simplify(sp.cosh(lg).rewrite(sp.exp)); sL = sp.simplify(sp.sinh(lg).rewrite(sp.exp))
line("A16 cosh log Phi = sqrt5/2 and sinh log Phi = 1/2", sp.simplify(cL - s5 / 2) == 0 and sp.simplify(sL - sp.Rational(1, 2)) == 0)
L = ex(s5 / 2 * I2 + S / 2)
line("A17 L = L_{log Phi} = (Q + 2I)/sqrt5", eq(L, (Q + 2 * I2) / s5))
line("A18 L^2 = Q^2 (return) and L^T G L = G", eq(L * L, Q * Q) and eq(L.T * G * L, G))
line("A19 L^2 = L_{2 log Phi} = cosh(2 log Phi) I + sinh(2 log Phi) S, with cosh = 3/2, sinh = sqrt5/2", sp.simplify(sp.cosh(2 * lg).rewrite(sp.exp) - sp.Rational(3, 2)) == 0 and sp.simplify(sp.sinh(2 * lg).rewrite(sp.exp) - s5 / 2) == 0 and eq(sp.Rational(3, 2) * I2 + s5 / 2 * S, Q * Q))

beta = sp.simplify(sp.tanh(lg).rewrite(sp.exp))
dop = sp.sqrt((1 + beta) / (1 - beta))
line("A20 on the light lines L acts by Phi and 1/Phi and L^2 by Phi^2 and 1/Phi^2; the velocity of L is tanh log Phi = 1/sqrt5, and the light Doppler factor sqrt((1 + v)/(1 - v)) at v = 1/sqrt5 is exactly Phi", eq(L * v_plus, Phi * v_plus) and eq(L * v_minus, v_minus / Phi) and eq(L * L * v_plus, Phi**2 * v_plus) and eq(L * L * v_minus, v_minus / Phi**2) and sp.simplify(beta - 1 / s5) == 0 and sp.simplify(dop - Phi) == 0)

print("# B. The reference")
eta = dsum(G, I2)
line("B1 eta^ = G (+) I_2 = [[-2,1,0,0],[1,2,0,0],[0,0,1,0],[0,0,0,1]]", eta == sp.Matrix([[-2, 1, 0, 0], [1, 2, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]))
line("B2 sig eta^ = (3, 1), det eta^ = -5", inertia(eta) == (3, 1, 0) and eta.det() == -5)
line("B3 the sign of the G corner decides the signature: corner +2 gives (4, 0), corner -2 gives (3, 1)", inertia(dsum(sp.Matrix([[2, 1], [1, 2]]), I2)) == (4, 0, 0) and inertia(eta) == (3, 1, 0))
Lh = lambda t: dsum(Ls(t), I2)
line("B4 the boost L_s (+) I_2 keeps eta^ for all s (symbolic)", all(sp.simplify(sp.expand(e.rewrite(sp.exp))) == 0 for e in (Lh(sh).T * eta * Lh(sh) - eta)))

print("# C. One coframe, two reads")
Chat = dsum(Z2, C1)
chi = sp.symbols("chi", real=True)
Pis = sp.Matrix(4, 4, lambda i, j: sp.Symbol("P%d%d" % (i, j)))
g_sym = Pis.T * eta * Pis
f_sym = chi * Pis.T * Chat * Pis
line("C1 Chat = 0 (+) C1 is antisymmetric of rank 2; g(Pi) is symmetric and f(Pi) = chi Pi^T Chat Pi antisymmetric for generic Pi and generic chi (symbolic)", Chat == -Chat.T and Chat.rank() == 2 and sp.expand(g_sym - g_sym.T) == sp.zeros(4, 4) and sp.expand(f_sym + f_sym.T) == sp.zeros(4, 4))
line("C2 g(Pi) = Pi^T eta^ Pi, f(Pi) = chi_cal Pi^T Chat Pi; at Pi = I, g = eta^ and f = chi_cal Chat", (I4.T * eta * I4) == eta and (chi * I4.T * Chat * I4) == chi * Chat)
rng = random.Random(35)
N = 500
okg = okf = oki = True
chis = [sp.Rational(-3, 7), sp.Rational(5, 2), sp.Integer(1), sp.Integer(-1)]
for n in range(N):
    Pi = rand_pi(rng)
    cx = chis[n % 4]
    g = Pi.T * eta * Pi
    f = cx * (Pi.T * Chat * Pi)
    okg &= (inertia(g) == (3, 1, 0)) and g.det() == -5 * Pi.det() ** 2
    okf &= (f == -f.T) and f.rank() == 2
    oki &= (f * g.inv() * f == -(cx**2) * (Pi.T * dsum(Z2, I2) * Pi))
line("C3 Sylvester: for %d seeded invertible integer coframes Pi, sig g(Pi) = (3, 1) and det g = -5 (det Pi)^2" % N, okg)
line("C4 for the same %d coframes and the nonzero constants chi in {-3/7, 5/2, 1, -1}, f = chi Pi^T Chat Pi is antisymmetric of rank 2" % N, okf)
line("C5 for the same %d coframes and the same chi, f g^-1 f = -chi^2 Pi^T (0 (+) I_2) Pi (the two reads close on one plane)" % N, oki)
line("C6 Chat eta^-1 Chat = -(0 (+) I_2) as an identity of blocks (symbolic)", eq(Chat * eta.inv() * Chat, -dsum(Z2, I2)))
A_s = Lh(sh)
rng = random.Random(35)
okC7 = all(sp.simplify(e.rewrite(sp.exp)) == 0 for e in (A_s.T * Chat * A_s - Chat))
for _ in range(20):
    Pi = rand_pi(rng)
    gA = (A_s * Pi).T * eta * (A_s * Pi)
    fA = (A_s * Pi).T * Chat * (A_s * Pi)
    okC7 &= all(sp.simplify(e.rewrite(sp.exp)) == 0 for e in (gA - Pi.T * eta * Pi)) and all(sp.simplify(e.rewrite(sp.exp)) == 0 for e in (fA - Pi.T * Chat * Pi))
line("C7 a frame change by the boost A = L_s (+) I_2 keeps both reads: g(A Pi) = g(Pi) and f(A Pi) = f(Pi) for all s (symbolic) and 20 seeded coframes", okC7)
th = sp.symbols("theta", real=True)
Rth = sp.cos(th) * I2 + sp.sin(th) * C1
Ah = dsum(I2, Rth)
line("C8 a frame change by the rotation I_2 (+) e^{theta C1} keeps eta^ and Chat for all theta (symbolic)", all(sp.simplify(e) == 0 for e in (Ah.T * eta * Ah - eta)) and all(sp.simplify(e) == 0 for e in (Ah.T * Chat * Ah - Chat)))
line("C9 the hypothesis chi != 0 is needed: for chi = 0, f(Pi) = 0 and rank f = 0, so the rank-2 statement holds exactly for chi in R minus {0}", (0 * (Pi.T * Chat * Pi)).rank() == 0 and all((c * (Pi.T * Chat * Pi)).rank() == 2 for c in chis))

print("# D. The seam and its two curvature reads")
B = dsum(S, Z2)
J = dsum(Z2, C1)
line("D1 [sqrt5 B, J_Sigma] = 0 with B = S (+) 0 and J_Sigma = 0 (+) C1", zero(comm(s5 * B, J)))
line("D2 B and J_Sigma both lie in the stabiliser of eta^: X^T eta^ + eta^ X = 0", zero(B.T * eta + eta * B) and zero(J.T * eta + eta * J))
line("D3 B and J_Sigma both lie in the stabiliser of Chat: X^T Chat + Chat X = 0", zero(B.T * Chat + Chat * B) and zero(J.T * Chat + Chat * J))
line("D4 B and J_Sigma are linearly independent, B^2 = S^2 (+) 0 and J_Sigma^2 = 0 (+) (-I)", sp.Matrix([list(B), list(J)]).rank() == 2 and eq(B * B, dsum(I2, Z2)) and eq(J * J, dsum(Z2, -I2)))
u, a_, b_ = sp.symbols("u a b", positive=True)
sPhi = lg / (2 * sp.pi)  # the seam scale s_Phi
kap = sp.pi / lg
omega_coeff = 2 * sPhi  # omega = 2 s_Phi d tau ^ d chi_seam
R_coeff = sp.Rational(1, 2) * omega_coeff
F_coeff = kap * omega_coeff
line("D5 s_Phi = log Phi/(2 pi), omega = 2 s_Phi d tau ^ d chi_seam; R = (1/2) B omega has component s_Phi B; F = kappa_Phi J_Sigma omega has component kappa_Phi 2 s_Phi J_Sigma = J_Sigma, kappa_Phi = pi / log Phi", sp.simplify(R_coeff - sPhi) == 0 and sp.simplify(F_coeff - 1) == 0)
tt, xx = sp.symbols("tau chi_seam")
flux_omega = sp.integrate(sp.integrate(omega_coeff, (tt, 0, a_)), (xx, 0, b_))
lam_ab = sPhi * a_ * b_
line("D6 the flux of omega over [0,a] x [0,b] is 2 s_Phi a b; with lambda = s_Phi a b the flux of R is lambda B and the flux of F is 2 kappa lambda J_Sigma = a b J_Sigma", sp.simplify(flux_omega - 2 * lam_ab) == 0 and sp.simplify(R_coeff * a_ * b_ - lam_ab) == 0 and sp.simplify(F_coeff * a_ * b_ - 2 * kap * lam_ab) == 0 and sp.simplify(2 * kap * lam_ab - a_ * b_) == 0)
ang = sp.simplify(2 * kap * u)
line("D7 the phase read rotates by the angle 2 kappa lambda = 2 pi lambda / log Phi: exp(2 kappa lambda C1) = cos(2 pi lambda/log Phi) I + sin(2 pi lambda/log Phi) C1", sp.simplify(ang - 2 * sp.pi * u / lg) == 0)
u_half = lg / 2
u_one = lg
u_two = 2 * lg
a_half = sp.simplify(2 * kap * u_half)
a_one = sp.simplify(2 * kap * u_one)
a_two = sp.simplify(2 * kap * u_two)
line("D8 phase angle at lambda = (log Phi)/2, log Phi, 2 log Phi is pi, 2 pi, 4 pi", a_half == sp.pi and a_one == 2 * sp.pi and a_two == 4 * sp.pi)
U_half = sp.cos(a_half) * I2 + sp.sin(a_half) * C1
U_one = sp.cos(a_one) * I2 + sp.sin(a_one) * C1
U_two = sp.cos(a_two) * I2 + sp.sin(a_two) * C1
line("D9 at lambda = (log Phi)/2 the phase read is U_pi = -I; at lambda = log Phi and 2 log Phi it is I", U_half == -I2 and U_one == I2 and U_two == I2)
line("D10 at lambda = log Phi the axial read is L = (Q + 2I)/sqrt5; at lambda = 2 log Phi it is L^2 = Q^2: the joint return is (Q^2, I) at lambda = 2 log Phi", all(sp.simplify(e.rewrite(sp.exp)) == 0 for e in (Ls(u_one) - (Q + 2 * I2) / s5)) and all(sp.simplify(e.rewrite(sp.exp)) == 0 for e in (Ls(u_two) - Q * Q)))
k_ = sp.symbols("k", positive=True)
sol = sp.solve(sp.Eq(2 * k_ * lg, 2 * sp.pi), k_)
line("D11 kappa is the unique positive constant for which the phase read completes one turn at lambda = log Phi: kappa = pi / log Phi", len(sol) == 1 and sp.simplify(sol[0] - kap) == 0)
cR, cF = R_coeff, F_coeff  # constant coefficients of R and F on d tau ^ d chi_seam
AR, AF = cR * tt, cF * tt  # A_R = s_Phi B tau d chi_seam, A_F = (2 kappa s_Phi) J tau d chi_seam: coefficient of d chi_seam
line("D12 local connections A_R = s_Phi B tau d chi_seam and A_F = 2 kappa_Phi s_Phi J_Sigma tau d chi_seam satisfy dA = R and dA = F: d(c tau d chi_seam) = c d tau ^ d chi_seam, so d/d tau of the coefficient equals the 2-form coefficient", sp.simplify(sp.diff(AR, tt) - R_coeff) == 0 and sp.simplify(sp.diff(AF, tt) - F_coeff) == 0 and sp.simplify(2 * kap * sPhi - F_coeff) == 0)
def edge_int(coef):
    # boundary of [0,a] x [0,b] counter-clockwise in (tau, chi_seam); A = coef * tau d chi_seam
    right = sp.integrate(coef * a_, (xx, 0, b_))   # tau = a, chi from 0 to b
    left = sp.integrate(coef * 0, (xx, b_, 0))      # tau = 0, chi from b to 0
    return sp.simplify(right + left)                # the two d tau edges carry d chi_seam = 0
line("D13 the boundary integral of A_R over the rectangle is lambda B and of A_F is a b J_Sigma (Stokes, by the four edge integrals)", sp.simplify(edge_int(cR) - lam_ab) == 0 and sp.simplify(edge_int(cF) - a_ * b_) == 0)
line("D14 B and J_Sigma commute, so the holonomies of the two connections around the rectangle are e^{lambda B} = L_lambda (+) I_2 and e^{a b J_Sigma} = I_2 (+) (cos(ab) I + sin(ab) C1), with no path-ordering term; the phase angle is the area ab", zero(comm(B, J)) and sp.simplify(sp.simplify(2 * kap * lam_ab) - a_ * b_) == 0)

print("# E. The recognition test and the reader")
v1, v2 = sp.symbols("v1 v2", real=True)
v = sp.Matrix([v1, v2])
Sig = lambda A: A.T * G * A - G
SigR = ex(sp.simplify(Sig(Rth)))
SigR = SigR.applyfunc(sp.simplify)
info("Sigma_G(e^{theta C1}) = " + str(SigR.applyfunc(sp.factor).tolist()))
line("E1 Sigma_G(I) = 0 and Sigma_G(-I) = 0", zero(Sig(I2)) and zero(Sig(-I2)))
line("E2 Sigma_G(C1) != 0 and Sigma_G(-C1) != 0 (a quarter turn does not keep G)", not zero(Sig(C1)) and not zero(Sig(-C1)))
a2, b2 = sp.symbols("a2 b2", real=True)
eqs = [sp.Eq(a2 - 2 * b2 + 2, 0), sp.Eq(2 * a2 + b2 - 1, 0)]
sol_ab = sp.solve(eqs, [a2, b2], dict=True)
ent = [sp.simplify(e) for e in SigR]
lin_ok = (sp.simplify(ent[0] - (sp.sin(2 * th) - 2 * sp.cos(2 * th) + 2)) == 0 and sp.simplify(ent[1] - (2 * sp.sin(2 * th) + sp.cos(2 * th) - 1)) == 0)
line("E3 Sigma_G(e^{theta C1}) = 0 iff (sin 2theta, cos 2theta) = (0, 1): the two independent entries are linear in (sin 2theta, cos 2theta) with the unique solution (0, 1), so Sigma_G = 0 iff theta is a multiple of pi", lin_ok and sol_ab == [{a2: 0, b2: 1}])
vanish = all(sp.simplify(sp.Matrix(SigR).subs(th, k * sp.pi)) == sp.zeros(2, 2) for k in range(-3, 4))
line("E4 Sigma_G(e^{theta C1}) = 0 at theta = k pi for k = -3..3 (including the full turns, where U = I)", vanish)
Uth = lambda t: sp.cos(t) * I2 + sp.sin(t) * C1
line("E5 U_pi = e^{pi C1} = cos pi I + sin pi C1 = -I", Uth(sp.pi) == -I2)
w = Uth(th) * v
line("E6 U_theta v is parallel to v for all v iff sin theta = 0: det[v, U_theta v] = sin(theta)(v1^2 + v2^2)", sp.simplify(sp.expand(v1 * w[1] - v2 * w[0]) - sp.sin(th) * (v1**2 + v2**2)) == 0)
line("E7 (U_pi - I) v = -2 v for all v, so U_pi v = v only for v = 0", sp.expand(((Uth(sp.pi) - I2) * v + 2 * v)[0]) == 0 and sp.expand(((Uth(sp.pi) - I2) * v + 2 * v)[1]) == 0)
rec = lambda U: eq(U.T * G * U, G) and sp.expand(v1 * (U * v)[1] - v2 * (U * v)[0]) == 0 and any(sp.simplify(e) != 0 for e in (U - I2))
line("E8 reader table: I is blank (keeps G, moves nothing), -I is recognition (keeps G, keeps every line, moves every vector), +-C1 is refusal (does not keep G, moves lines)", (not rec(I2)) and rec(-I2) and (not rec(C1)) and (not rec(-C1)) and eq(I2.T * G * I2, G) and not eq(C1.T * G * C1, G) and sp.simplify(v1 * (C1 * v)[1] - v2 * (C1 * v)[0] - (v1**2 + v2**2)) == 0)
kk = sp.symbols("k", integer=True)
Uk = sp.cos(kk * sp.pi) * I2 + sp.sin(kk * sp.pi) * C1
ok_form = sp.simplify(sp.cos(kk * sp.pi) - (-1) ** kk) == 0 and sp.simplify(sp.sin(kk * sp.pi)) == 0
m_ = sp.symbols("m", integer=True)
ok_parity = sp.simplify(((-1) ** (2 * m_)) - 1) == 0 and sp.simplify(((-1) ** (2 * m_ + 1)) + 1) == 0
line("E9 symbolic, for theta = k pi with k an integer: U = (-1)^k I (cos k pi = (-1)^k, sin k pi = 0), which keeps G and every line; it moves every vector iff (-1)^k != 1 iff k is odd; with E3 (Sigma_G = 0 iff theta in pi Z) and E6 (epsilon = sin theta) recognition holds exactly for theta = pi mod 2 pi, where U = -I", ok_form and ok_parity and sp.simplify(sp.sin(kk * sp.pi)) == 0)

line("E11 Sigma_G(C1) = Sigma_G(-C1) = -2 G: with the reference G held, the quarter turns fail the test and are typed refusal", eq(Sig(C1), -2 * G) and eq(Sig(-C1), -2 * G))

print("# F. The phase address")
line("F1 137 is prime, gcd(4, 137) = 1, 548 = 4 * 137", sp.isprime(137) and gcd(4, 137) == 1 and 548 == 4 * 137)
addr = {(q, s): (137 * q + 4 * s) % 548 for q in range(4) for s in range(137)}
line("F2 (q, s) -> A = 137 q + 4 s mod 548 is a bijection of Z/4 x Z/137 onto Z/548 (all 548 values distinct)", len(set(addr.values())) == 548 and set(addr.values()) == set(range(548)))
line("F3 phi(q, s) = 2 pi (q/4 + s/137) = (2 pi/548)(137 q + 4 s) as a rational identity on all 548 pairs", all(F(q, 4) + F(s, 137) == F(137 * q + 4 * s, 548) for q in range(4) for s in range(137)))
line("F4 phi(q + 1, s) = phi(q, s) + pi/2 (mod 2 pi) for all (q, s)", all((F(q + 1, 4) + F(s, 137) - (F(q, 4) + F(s, 137)) - F(1, 4)) % 1 == 0 for q in range(4) for s in range(137)))
line("F5 137 = 1 mod 4, so q = A mod 4 and s = (A - 137 q)/4 mod 137", 137 % 4 == 1 and all(addr[(q, s)] % 4 == q for q in range(4) for s in range(137)) and all(((A - 137 * (A % 4)) // 4) % 137 == s for (q, s), A in addr.items()))
line("F9 phi : Z/4 + Z/137 -> R/2 pi Z is well defined and injective: shifting a representative (q -> q + 4 or s -> s + 137) changes phi by a multiple of 2 pi, and the 548 values 2 pi A/548 are pairwise distinct mod 2 pi", all((F(q + 4, 4) + F(s, 137) - F(q, 4) - F(s, 137)).denominator == 1 and (F(q, 4) + F(s + 137, 137) - F(q, 4) - F(s, 137)).denominator == 1 for q in range(4) for s in range(137)) and len({(F(q, 4) + F(s, 137)) % 1 for q in range(4) for s in range(137)}) == 548)
line("F8 a replacement of 137 by 136 breaks the bijection (gcd(4, 136) = 4)", len({(136 * q + 4 * s) % 544 for q in range(4) for s in range(136)}) < 544)


print("# K. Field equations: Einstein-Maxwell in this frame")
chi_, al_, kE = sp.symbols("chi alpha kappa_E", positive=True)
Fk = chi_ * Chat
Tk = frame_stress(Fk, eta)
Tkm = (eta.inv() * Tk).applyfunc(sp.simplify)
line("K1 the electromagnetic stress of f = chi Pi^T Chat Pi is T = (chi^2/2) Pi^T(-G (+) I_2)Pi: in frame indices T = (chi^2/2)(-G (+) I_2), mixed T = (chi^2/2)(-I_2 (+) I_2), traceless (symbolic chi)", zero(Tk - chi_**2 / 2 * dsum(-G, I2)) and zero(Tkm - chi_**2 / 2 * dsum(-I2, I2)) and sp.simplify(Tkm.trace()) == 0)
line("K2 Rainich's algebraic condition: (T^A_B)^2 = (chi^4/4) times the identity", zero(Tkm * Tkm - chi_**4 / 4 * I4))
X2 = sp.Matrix(4, 4, lambda i, j: sp.Symbol("x%d%d" % (i, j)) if i < j else 0)
X2 = X2 - X2.T
sFk = frame_star(Fk, eta)
line("K3 the Hodge star of eta^ squares to -1 on every 2-form (symbolic), and *f lies on the gravity block: *Chat = sqrt5 (C1 (+) 0)", zero(frame_star(frame_star(X2, eta), eta) + X2) and zero(sFk - chi_ * s5 * dsum(C1, Z2)))
Fal = sp.cos(al_) * Fk + sp.sin(al_) * sFk
line("K4 the phase turns and gravity holds: T(cos a f + sin a *f) = T(f) for every angle a (symbolic); at a = pi the field is -f and T is unchanged", zero(frame_stress(Fal, eta) - Tk) and zero(Fal.subs(al_, sp.pi) + Fk))
Yk = sp.Matrix(4, 4, lambda i, j: sp.Symbol("y%d%d" % (i, j)))
solk = sp.solve(list(Yk.T * eta + eta * Yk) + list(Yk.T * Chat + Chat * Yk), list(Yk), dict=True)[0]
Yks = Yk.subs(solk)
freek = sorted(Yks.free_symbols, key=str)
basisk = [Yks.subs({v: (1 if v == w else 0) for v in freek}) for w in freek]
Bk, Jk = dsum(S, Z2), dsum(Z2, C1)
line("K5 the turns that keep both eta^ and Chat are exactly span{B, J_Sigma}: the solution space of X^T eta^ + eta^ X = 0 = X^T Chat + Chat X has dimension 2 and is spanned by B and J_Sigma", len(freek) == 2 and sp.Matrix([list(b) for b in basisk] + [list(Bk), list(Jk)]).rank() == 2)
t_, rho_, th_, ph_ = Xc = sp.symbols("t rho theta phi", real=True)
r_ = sp.symbols("r", positive=True)
Nk = sp.Matrix([[1 / sp.sqrt(2), 1 / sp.sqrt(10)], [0, 2 / sp.sqrt(10)]])
Pik = dsum(Nk, I2) * sp.diag(r_ * sp.cosh(rho_), r_, r_, r_ * sp.sin(th_))
gk = (Pik.T * eta * Pik).applyfunc(sp.simplify)
fk = (chi_ * Pik.T * Chat * Pik).applyfunc(sp.simplify)
gBR = sp.diag(-r_**2 * sp.cosh(rho_)**2, r_**2, r_**2, r_**2 * sp.sin(th_)**2)
volL, volS = r_**2 * sp.cosh(rho_), r_**2 * sp.sin(th_)
line("K6 on 0 < theta < pi the coframe Pi = (N (+) I_2) diag(r cosh rho, r, r, r sin theta), with det Pi = r^4 cosh rho sin theta/sqrt5, N = [[1/sqrt2, 1/sqrt10], [0, 2/sqrt10]], gives g = Pi^T eta^ Pi = r^2(-cosh^2 rho dt^2 + drho^2) + r^2(dtheta^2 + sin^2 theta dphi^2), a Lorentzian plane times a sphere, both of radius r, and f = chi Pi^T Chat Pi = -chi r^2 sin theta dtheta ^ dphi", zero(Nk.T * G * Nk - sp.diag(-1, 1)) and sp.simplify(Pik.det() - r_**4 * sp.cosh(rho_) * sp.sin(th_) / s5) == 0 and zero(gk - gBR) and zero(fk - (-chi_ * volS) * (sp.Matrix(4, 4, lambda i, j: 1 if (i, j) == (2, 3) else (-1 if (i, j) == (3, 2) else 0)))))


def Zk(e):
    return sp.simplify(sp.simplify(sp.expand(sp.sympify(e).rewrite(sp.exp))).subs(sp.Abs(sp.sin(th_)), sp.sin(th_)))


gki = gk.inv()
Gamk = [[[Zk(sum(gki[a, d] * (sp.diff(gk[d, b], Xc[c]) + sp.diff(gk[d, c], Xc[b]) - sp.diff(gk[b, c], Xc[d])) for d in range(4)) / 2) for c in range(4)] for b in range(4)] for a in range(4)]


def Riemk(a, b, c, d):  # R^a_{bcd}
    return Zk(sp.diff(Gamk[a][b][d], Xc[c]) - sp.diff(Gamk[a][b][c], Xc[d]) + sum(Gamk[a][c][e] * Gamk[e][b][d] - Gamk[a][d][e] * Gamk[e][b][c] for e in range(4)))


Ricc = sp.Matrix(4, 4, lambda b, d: Zk(sum(Riemk(a, b, a, d) for a in range(4))))
Rsc = Zk(sum(gki[a, b] * Ricc[a, b] for a in range(4) for b in range(4)))
Eink = (Ricc - Rsc * gk / 2).applyfunc(Zk)
F2k = Zk(sum(fk[a, b] * (gki * fk * gki)[a, b] for a in range(4) for b in range(4)))
Tco = (fk * gki * fk.T - gk * F2k / 4).applyfunc(Zk)
rsol = sp.solve(sp.Eq(1 / r_**2, kE * chi_**2 / 2), r_)
line("K7 Einstein-Maxwell, gravity: the scalar curvature is 0, the mixed Einstein tensor is (1/r^2)(-1, -1, 1, 1) and the mixed stress (chi^2/2)(-1, -1, 1, 1), so G_mu nu = kappa_E T_mu nu holds exactly when r^2 = 2/(kappa_E chi^2), its one positive solution", Rsc == 0 and (gki * Eink).applyfunc(Zk) == sp.diag(-1, -1, 1, 1) / r_**2 and (gki * Tco).applyfunc(Zk) == chi_**2 / 2 * sp.diag(-1, -1, 1, 1) and (Eink - kE * Tco).subs(r_, sp.sqrt(2 / (kE * chi_**2))).applyfunc(Zk) == sp.zeros(4) and len(rsol) == 1 and sp.simplify(rsol[0]**2 - 2 / (kE * chi_**2)) == 0)


def d2k(Fm):
    return [Zk(sp.diff(Fm[b, c], Xc[a]) + sp.diff(Fm[c, a], Xc[b]) + sp.diff(Fm[a, b], Xc[c])) for a in range(4) for b in range(4) for c in range(4)]


dgk = sp.sqrt(-gk.det())
Fupk = gki * fk * gki
sfk = sp.Matrix(4, 4, lambda a, b: Zk(dgk * sum(sp.LeviCivita(a, b, c, d) * Fupk[c, d] for c in range(4) for d in range(4)) / 2))
flux = sp.integrate(sp.integrate(fk[2, 3], (th_, 0, sp.pi)), (ph_, 0, 2 * sp.pi))
line("K8 Einstein-Maxwell, electromagnetism: df = 0 and d*f = 0, with *f = -chi r^2 cosh rho dt ^ drho on the Lorentzian plane; the flux of f through the sphere is -4 pi chi r^2", all(e == 0 for e in d2k(fk)) and all(e == 0 for e in d2k(sfk)) and sp.simplify(sp.simplify(Zk(sfk[0, 1] + chi_ * volL).rewrite(sp.cos))) == 0 and sp.simplify(flux + 4 * sp.pi * chi_ * r_**2) == 0)
Pikin = Pik.inv()


def Omegak(c, d):
    return (Pik * sp.Matrix(4, 4, lambda a, b: Riemk(a, b, c, d)) * Pikin).applyfunc(Zk)


planes = [(c, d) for c in range(4) for d in range(c + 1, 4)]
Om01, Om23 = Omegak(0, 1), Omegak(2, 3)
line("K9 the curvature 2-form of the solution in the frame of eta^ is -(1/r^2)(B (x) vol_plane + J_Sigma (x) vol_sphere): it takes values only in span{B, J_Sigma}, with equal weight, none on the mixed planes; and f = -chi vol_sphere, so its J_Sigma part is Omega_J = -(1/r^2) J_Sigma vol_sphere = (1/(chi r^2)) J_Sigma f", (Om01 + Bk * volL / r_**2).applyfunc(Zk) == sp.zeros(4) and (Om23 + Jk * volS / r_**2).applyfunc(Zk) == sp.zeros(4) and all(Omegak(c, d) == sp.zeros(4) for c, d in planes if (c, d) not in [(0, 1), (2, 3)]) and Zk(fk[2, 3] + chi_ * volS) == 0 and (Om23 - Jk * fk[2, 3] / (chi_ * r_**2)).applyfunc(Zk) == sp.zeros(4))
line("K10 the seam is the field: raised once, f is chi J_Sigma and its dual is chi B, (eta^-1 f)^A_B = chi J_Sigma and (eta^-1 *f)^A_B = chi B in the frame", zero(eta.inv() * Fk - chi_ * Jk) and zero(eta.inv() * sFk - chi_ * Bk))
q_, m_, g_, tau_ = sp.symbols("q m g tau", positive=True)
Uv = sp.Matrix(sp.symbols("u0:4"))
expJ = lambda a: dsum(I2, sp.cos(a) * I2 + sp.sin(a) * C1)
line("K11 the Lorentz force m DU/dtau = q chi J_Sigma U keeps eta(U, U), since U^T eta J_Sigma U = 0 for every U; in a parallel frame U(tau) = exp(tau q chi J_Sigma / m) U(0), a turn at the cyclotron rate q chi/m", sp.expand((Uv.T * eta * Jk * Uv)[0]) == 0 and zero(sp.diff(expJ(q_ * chi_ * tau_ / m_), tau_) - (q_ * chi_ / m_) * Jk * expJ(q_ * chi_ * tau_ / m_)) and zero(expJ(0) - I4))
expB = lambda a: dsum(sp.cosh(a) * I2 + sp.sinh(a) * S, I2)
Mqg = expJ(q_ * tau_) * expB(g_ * tau_)
line("K12 a duality turn of the field turns the force between rotation and boost, eta^-1(cos a f + sin a *f) = chi(cos a J_Sigma + sin a B); a charge q with magnetic charge g feels chi(q J_Sigma + g B), and since [J_Sigma, B] = 0 its transport exp(tau(q J_Sigma + g B)) = exp(tau q J_Sigma) exp(tau g B) is a turn times a boost", zero(eta.inv() * Fal - chi_ * (sp.cos(al_) * Jk + sp.sin(al_) * Bk)) and zero(Jk * Bk - Bk * Jk) and zero(sp.diff(Mqg, tau_) - (q_ * Jk + g_ * Bk) * Mqg) and zero(Mqg.subs(tau_, 0) - I4))
th0_ = sp.symbols("theta_0", positive=True)
Omq = q_ * chi_ / (m_ * sp.cos(th0_))
Tq = sp.sqrt(1 + r_**2 * sp.sin(th0_)**2 * Omq**2) / r_
pathq = {t_: Tq * tau_, rho_: 0, th_: th0_, ph_: Omq * tau_}
xd = [sp.diff(pathq[v], tau_) for v in Xc]
xdd = [sp.diff(pathq[v], tau_, 2) for v in Xc]
at = {rho_: 0, th_: th0_}
fmq = (gki * fk).subs(at)
eqq = [sp.simplify(xdd[a] + sum(Gamk[a][b][c].subs(at) * xd[b] * xd[c] for b in range(4) for c in range(4)) - q_ / m_ * sum(fmq[a, b] * xd[b] for b in range(4))) for a in range(4)]
nq = sp.simplify(sum(gk.subs(at)[a, b] * xd[a] * xd[b] for a in range(4) for b in range(4)))
line("K13 a charged worldline in the solution of K6-K9: for 0 < theta_0 < pi with cos theta_0 != 0, at rest at the centre of the plane, rho = 0, and circling the latitude theta_0 of the sphere at the rate dphi/dtau = q chi/(m cos theta_0), with dt/dtau = sqrt(1 + r^2 sin^2 theta_0 (dphi/dtau)^2)/r; all four equations x'' + Gamma x' x' = (q/m) f x' hold exactly and u.u = -1", all(e == 0 for e in eqq) and nq == -1)
Rsp = lambda a: sp.cos(a / 2) * I2 + sp.sin(a / 2) * C1
vph = sp.symbols("varphi", real=True)
line("K14 spin one half: the spinor turn R(phi) = exp((phi/2) C1) squares to the vector turn, R(phi)^2 = exp(phi C1); a full turn gives R(2 pi) = -I = U_pi and only R(4 pi) = I", zero(Rsp(vph) ** 2 - (sp.cos(vph) * I2 + sp.sin(vph) * C1)) and Rsp(2 * sp.pi) == -I2 and Rsp(4 * sp.pi) == I2)

# Spin: the Dirac algebra of the root (K15-K20); Riemann's reader on the seam (K21-K22)
kpr = sp.kronecker_product
zx = lambda M: all(sp.simplify(sp.expand(sp.sympify(e).rewrite(sp.exp))) == 0 for e in sp.Matrix(M))
acom = lambda A_, B_: A_ * B_ + B_ * A_
x1_, x2_, x3_ = sp.symbols("x1 x2 x3")
Xsym = sp.Matrix([[x1_, x2_], [x2_, x3_]])
Xs1 = Xsym.subs(sp.solve(list(S.T * Xsym + Xsym * S), [x1_, x2_, x3_], dict=True)[0])
evS = [w for _, _, ws in S.eigenvects() for w in ws]
line("K15 the Dirac algebra of the plane is in the root: C1^2 = -I, H^2 = I, C1 H + H C1 = 0, a Clifford pair of signature (1,1) whose chirality is C1 H = -S; the symmetric forms kept by every exp(t S) are exactly the multiples of G, and the two eigenlines of S are the light lines of G",
     eq(C1 * C1, -I2) and eq(H * H, I2) and zero(acom(C1, H)) and eq(C1 * H, -S) and len(Xs1.free_symbols) == 1 and zero(Xs1 - G * Xs1[0, 1]) and len(evS) == 2 and all(sp.simplify((w.T * G * w)[0]) == 0 for w in evS))
Linv = L.inv()
line("K16 L is the spin lift of the boost Q^2: conjugation by L turns the Clifford pair by a boost of rapidity 2 log Phi, L C1 L^-1 = (3/2) C1 - (sqrt5/2) H, L H L^-1 = -(sqrt5/2) C1 + (3/2) H, with cosh(2 log Phi) = 3/2, sinh(2 log Phi) = sqrt5/2; L^2 = Q^2 has eigenvalues Phi^2, Phi^-2; -L gives the same boost",
     eq(L * C1 * Linv, sp.Rational(3, 2) * C1 - s5 / 2 * H) and eq(L * H * Linv, -s5 / 2 * C1 + sp.Rational(3, 2) * H) and zx(sp.Matrix([sp.cosh(2 * lg) - sp.Rational(3, 2), sp.sinh(2 * lg) - s5 / 2]))
     and eq(L * L, Q * Q) and sorted(sp.simplify(e - Phi**2) == 0 or sp.simplify(e - Phi**-2) == 0 for e in (Q * Q).eigenvals()) == [True, True] and eq((-L) * C1 * (-L).inv(), L * C1 * Linv))
Gam = [kpr(C1, I2), kpr(H, I2), kpr(-S, H), kpr(-S, S)]
eta_o = sp.diag(-1, 1, 1, 1)
Ninv4 = dsum(Nk, I2).inv()
Gh = [ex(sum((Ninv4[b, a] * Gam[b] for b in range(4)), sp.zeros(4))) for a in range(4)]
line("K17 real Dirac matrices from the root: Gamma = (C1 x I, H x I, -S x H, -S x S) satisfy Gamma_a Gamma_b + Gamma_b Gamma_a = 2 diag(-1,1,1,1)_ab; taken through the frame N + I_2 of K6 they satisfy the same relation with 2 eta^_ab: the metric is the Clifford square of the root",
     eq(Nk.T * G * Nk, sp.diag(-1, 1)) and all(eq(acom(Gam[i], Gam[j]), 2 * eta_o[i, j] * I4) for i in range(4) for j in range(4)) and all(eq(acom(Gh[i], Gh[j]), 2 * eta[i, j] * I4) for i in range(4) for j in range(4)))
Bb, Jb = Gam[0] * Gam[1], Gam[2] * Gam[3]
vol4 = Gam[0] * Gam[1] * Gam[2] * Gam[3]
line("K18 the boost bivector is Gamma_0 Gamma_1 = -S x I and the rotation bivector Gamma_2 Gamma_3 = I x C1; their product is the volume element -S x C1, which squares to -I like the star of K3, and multiplying by it exchanges them, (Gamma_2 Gamma_3) w = -Gamma_0 Gamma_1, (Gamma_0 Gamma_1) w = Gamma_2 Gamma_3; the spin lifts are exp((phi/2) Gamma_2 Gamma_3) = I x R(phi), -I at phi = 2 pi, and exp(-(log Phi) Gamma_0 Gamma_1) = L x I",
     eq(Bb, kpr(-S, I2)) and eq(Jb, kpr(I2, C1)) and eq(vol4, Bb * Jb) and eq(vol4, kpr(-S, C1)) and eq(vol4 * vol4, -I4) and eq(Jb * vol4, -Bb) and eq(Bb * vol4, Jb)
     and eq(sp.cos(vph / 2) * I4 + sp.sin(vph / 2) * Jb, kpr(I2, Rsp(vph))) and eq(Jb * Jb, -I4) and eq(Bb * Bb, I4) and zx(sp.cosh(lg) * I4 - sp.sinh(lg) * Bb - kpr(L, I2)))
Xc4 = sp.Matrix(4, 4, sp.symbols("y0:16"))
solc = sp.solve([e for Gm in Gam for e in (Xc4 * Gm - Gm * Xc4)], list(Xc4), dict=True)[0]
Xcs = Xc4.subs(solc)
line("K19 the only real matrices that commute with all four Gamma are the multiples of I: no real phase J with J^2 = -I acts on the spinors of the frame, so the charge phase is carried on the complex spinor C (x) R^4, outside the real algebra of the metric",
     len(Xcs.free_symbols) == 1 and zero(Xcs - Xcs[0, 0] * I4))
Gup = [eta_o[a, a] * Gam[a] for a in range(4)]
rep = lambda Xm: sum(((eta_o * Xm)[a, b] * Gup[a] * Gup[b] for a in range(4) for b in range(4)), sp.zeros(4)) / 4
Jo = dsum(Z2, C1)
Fo = chi_ * eta_o * Jo  # f in the orthonormal frame: (Nk + I)^T (chi Chat)(Nk + I) = chi Chat, raised once chi J
Sv, Uvv = sp.Matrix(sp.symbols("s0:4")), sp.Matrix(sp.symbols("w0:4"))
gy_ = sp.symbols("g_s")
Fm = chi_ * Jo
bmt = lambda gg: (q_ / m_) * (gg / 2 * Fm * Sv + (1 - gg / 2) * Uvv * (Sv.T * eta_o * Fm * Uvv)[0])
nS = lambda X_, Y_: (X_.T * eta_o * Y_)[0]
Ssym = sp.Matrix(4, 4, lambda a, b: sp.Symbol("S%d%d" % (min(a, b), max(a, b))))
Aant = sp.Matrix(4, 4, lambda a, b: 0 if a == b else (1 if a < b else -1) * sp.Symbol("A%d%d" % (min(a, b), max(a, b))))
dsq = sum((Gup[a] * Gup[b] * (Ssym[a, b] + Aant[a, b] / 2) for a in range(4) for b in range(4)), sp.zeros(4))
dsq_split = sum((eta_o[a, b] * Ssym[a, b] for a in range(4) for b in range(4)), 0) * I4 + sum((Gup[a] * Gup[b] * Aant[a, b] for a in range(4) for b in range(4)), sp.zeros(4)) / 2
Ut_ = sp.cos(q_ * chi_ * tau_ / m_) * I2 + sp.sin(q_ * chi_ * tau_ / m_) * C1
line("K20 g = 2 from the Dirac square: rep(X) = (1/4) X_ab Gamma^a Gamma^b is the spinor generator of a frame turn X, [rep X, Gamma_c] = Gamma_d X^d_c, and exp(2 pi rep J_Sigma) = -I; writing D_a D_b = S_ab + (1/2)[D_a, D_b], the Clifford relation gives (Gamma^a D_a)^2 = eta^ab S_ab + (1/2) Gamma^a Gamma^b [D_a, D_b], so with [D_a, D_b] = i q f_ab the Pauli term is (1/2) f_ab Gamma^a Gamma^b = 2 rep(chi J_Sigma), twice the field's own spin generator; the spin equation dS/dtau = (q/m)[(g/2) F S + (1 - g/2) U (S.F U)] keeps S.U, d(S.U)/dtau = (q/m)(1 - g/2)(1 + U.U)(S.F U), zero on U.U = -1 for every g; with g = 2 it is the Lorentz force equation, so S and U turn by the same exp(tau q chi J_Sigma/m) and eta(S, U) is kept",
     all(eq(rep(Jo) * Gam[c] - Gam[c] * rep(Jo), sum((Gam[d] * Jo[d, c] for d in range(4)), sp.zeros(4))) for c in range(4)) and zx(sp.cos(sp.pi) * I4 + sp.sin(sp.pi) * 2 * rep(Jo) + I4) and eq(4 * rep(Jo) * rep(Jo), -I4)
     and zero(dsq - dsq_split) and eq(sum((Fo[a, b] * Gup[a] * Gup[b] for a in range(4) for b in range(4)), sp.zeros(4)) / 2, 2 * rep(chi_ * Jo)) and sp.expand(nS(bmt(gy_), Uvv) + nS(Sv, (q_ / m_) * Fm * Uvv) - (q_ / m_) * (1 - gy_ / 2) * (1 + nS(Uvv, Uvv)) * nS(Sv, Fm * Uvv)) == 0 and zero(bmt(2) - (q_ / m_) * Fm * Sv)
     and zero(dsum(I2, Ut_).T * eta * dsum(I2, Ut_) - eta) and zero(sp.diff(dsum(I2, Ut_), tau_) - (q_ * chi_ / m_) * Jo * dsum(I2, Ut_)))
t_r, l_r, v_r, x_r, z_r = sp.symbols("t lambda v x z", positive=True)
n_r = sp.symbols("n", positive=True, integer=True)
rho_r = lambda tt, ll: sp.cos(tt * ll / 2) * I2 + sp.sin(tt * ll / 2) * C1
Ax_r = lambda ll: sp.cosh(ll) * I2 + sp.sinh(ll) * S
tPhi = 4 * kap
psi1 = -sp.pi * n_r**2 * sp.exp(-sp.pi * n_r**2 * x_r)  # one term of psi'(x)
riem_x = 4 * sp.diff(x_r**sp.Rational(3, 2) * psi1, x_r) * x_r**sp.Rational(-1, 4)
K_r = 4 * sp.exp(-l_r / 4) * sp.diff(sp.exp(3 * l_r / 2) * psi1.subs(x_r, sp.exp(l_r)), l_r)
line("K21 Riemann's reader is the seam's phase: rho_t(lambda) = exp((t lambda/2) C1) = R(t lambda), the spin turn of K14, with (1/2) tr rho_t = cos(t lambda/2); the substitution x = e^lambda carries Riemann's integrand 4 (x^{3/2} psi'(x))' x^{-1/4} dx to K(lambda) d lambda term by term; the seam's phase holonomy exp(2 kappa_Phi lambda C1) is rho_t(lambda) at t_Phi = 4 kappa_Phi = 4 pi/log Phi; the mirror H reverses both reads, H rho_t H = rho_{-t} = rho_t^T and H exp(lambda S) H = exp(-lambda S)",
     eq(rho_r(t_r, l_r), Rsp(t_r * l_r)) and sp.simplify(rho_r(t_r, l_r).trace() / 2 - sp.cos(t_r * l_r / 2)) == 0 and sp.simplify((riem_x.subs(x_r, sp.exp(l_r)) * sp.exp(l_r) - K_r).rewrite(sp.exp)) == 0
     and zx(sp.cos(2 * kap * l_r) * I2 + sp.sin(2 * kap * l_r) * C1 - rho_r(tPhi, l_r)) and eq(H * rho_r(t_r, l_r) * H, rho_r(-t_r, l_r)) and eq(rho_r(-t_r, l_r), rho_r(t_r, l_r).T) and zx(H * Ax_r(l_r) * H - Ax_r(-l_r)))
Tc = 2 * lg
uPhi, upi = l_r / (2 * lg), l_r / lg
chi_ax = lambda w: (Phi - w) / (w - (1 - s5) / 2)
Ml = Ax_r(l_r)
mob_r = (Ml[0, 0] * z_r + Ml[0, 1]) / (Ml[1, 0] * z_r + Ml[1, 1])
line("K22 the seam is a 2:1 period adapter: with u_Phi = lambda/(2 log Phi) and u_pi = lambda/log Phi = 2 u_Phi, the axial read exp(lambda S) is L, L^2 = Q^2, L^3 at u_pi = 1, 2, 3 and Q^{2k} at u_Phi = k, and the phase read is (1/2) tr rho_{t_Phi} = cos(2 pi u_pi); on Riemann's cells lambda = v + k T_Phi, T_Phi = 2 log Phi, the phase read returns to the cell, rho_{t_Phi}(v + k T_Phi) = rho_{t_Phi}(v), while the axial read advances, exp((v + k T_Phi) S) = exp(v S) Q^{2k}, Q^{2k} != I (k = 1, 2, 3); projectively exp(lambda S) moves the Linear Infinity coordinate by 2 lambda, chi_ax(exp(lambda S) z) = exp(-2 lambda) chi_ax(z)",
     sp.simplify(upi - 2 * uPhi) == 0 and zx(Ax_r(lg) - L) and zx(Ax_r(2 * lg) - Q * Q) and zx(Ax_r(3 * lg) - L**3) and all(zx(Ax_r(k * Tc) - (Q * Q)**k) for k in (1, 2))
     and sp.simplify((rho_r(tPhi, l_r).trace() / 2 - sp.cos(2 * sp.pi * upi)).rewrite(sp.exp)) == 0
     and all(zx(rho_r(tPhi, v_r + k * Tc) - rho_r(tPhi, v_r)) and zx(Ax_r(v_r + k * Tc) - Ax_r(v_r) * (Q * Q)**k) and not eq((Q * Q)**k, I2) for k in (1, 2, 3))
     and sp.simplify((chi_ax(mob_r) - sp.exp(-2 * l_r) * chi_ax(z_r)).rewrite(sp.exp)) == 0)

# Charged spin on the solution (K23-K26)
n_q, G_N, al_ = sp.symbols("n G alpha", positive=True)
kE_ = sp.symbols("kappa_E", positive=True)
AN = chi_ * r_**2 * (sp.cos(th_) - 1)
AS = chi_ * r_**2 * (sp.cos(th_) + 1)
fsph = sp.simplify(fk[2, 3])  # the d theta ^ d phi component of f
r2E = 2 / (kE_ * chi_**2)
n_E = sp.simplify((2 * q_ * chi_ * r_**2).subs(r_**2, r2E))
line("K23 Dirac quantization on the solution: A_+- = chi r^2 (cos theta -+ 1) d phi satisfy dA_+- = f and vanish at their poles; A_+ - A_- = -2 chi r^2 d phi, so a field of charge q is single valued on both patches exactly when n = 2 q chi r^2 is an integer; with r^2 = 2/(kappa_E chi^2) this reads n = 4q/(kappa_E chi), r^2 = kappa_E n^2/(8 q^2), the flux of f is -2 pi n/q, and for kappa_E = 8 pi G, q^2 = 4 pi alpha, r^2 = G n^2/(4 alpha)",
     sp.simplify(sp.diff(AN, th_) - fsph) == 0 and sp.simplify(sp.diff(AS, th_) - fsph) == 0 and AN.subs(th_, 0) == 0 and AS.subs(th_, sp.pi) == 0 and sp.simplify(AN - AS + 2 * chi_ * r_**2) == 0
     and sp.simplify(n_E - 4 * q_ / (kE_ * chi_)) == 0 and sp.simplify(r2E.subs(chi_, 4 * q_ / (kE_ * n_q)) - kE_ * n_q**2 / (8 * q_**2)) == 0
     and sp.simplify(-4 * sp.pi * chi_ * r_**2 - (-2 * sp.pi * (2 * q_ * chi_ * r_**2) / q_)) == 0 and sp.simplify((kE_ * n_q**2 / (8 * q_**2)).subs({kE_: 8 * sp.pi * G_N, q_: sp.sqrt(4 * sp.pi * al_)}) - G_N * n_q**2 / (4 * al_)) == 0)
# the Dirac operator of the solution from its orthonormal coframe and spin connection
eo = sp.diag(r_ * sp.cosh(rho_), r_, r_, r_ * sp.sin(th_))
Eo = eo.inv()
om = [[[sp.simplify(sum(eo[a, nu] * (sp.diff(Eo[nu, b], Xc[mu]) + sum(Gamk[nu][mu][la] * Eo[la, b] for la in range(4))) for nu in range(4))) for b in range(4)] for a in range(4)] for mu in range(4)]
Sig = [sum((sum(eta_o[a, c2] * om[mu][c2][b] for c2 in range(4)) * Gup[a] * Gup[b] for a in range(4) for b in range(4)), sp.zeros(4)) / 4 for mu in range(4)]
compat = all(eq(Sig[mu] * Gup[c2] - Gup[c2] * Sig[mu], -sum((om[mu][c2][d] * Gup[d] for d in range(4)), sp.zeros(4))) for mu in range(4) for c2 in range(4))
Asym = chi_ * r_**2 * sp.cos(th_)
psi4 = sp.Matrix([sp.Function("f%d" % i)(*Xc) for i in range(4)])
Dfull = lambda P_: sum((Gup[a] * Eo[mu, a] * (sp.diff(P_, Xc[mu]) + Sig[mu] * P_ - (sp.I * q_ * Asym * P_ if mu == 3 else sp.zeros(4, 1))) for a in range(4) for mu in range(4) if Eo[mu, a] != 0), sp.zeros(4, 1))
Dpl = lambda P_: sum((Gup[a] * Eo[a, a] * (sp.diff(P_, Xc[a]) + Sig[a] * P_) for a in (0, 1)), sp.zeros(4, 1))
Dsp = lambda P_: (sp.diff(P_, th_) + sp.cot(th_) / 2 * P_) / r_
Dsph = lambda P_: kpr(I2, H) * Dsp(P_) + kpr(I2, S) * (sp.diff(P_, ph_) - sp.I * q_ * Asym * P_) / (r_ * sp.sin(th_))
chP = kpr(-S, I2)
zcol = lambda M: all(sp.simplify(e) == 0 for e in M)
line("K24 the Dirac operator of the solution separates: built from the coframe diag(r cosh rho, r, r, r sin theta) with the Gamma of K17, its spin connection Sigma_mu = (1/4) omega_mu ab Gamma^a Gamma^b keeps every Gamma, [Sigma_mu, Gamma^c] = -omega_mu^c_d Gamma^d; in the gauge A = chi r^2 cos theta d phi, D = D_plane + (-S x I)(I x D_sphere) with D_sphere = (1/r)[H (d_theta + (1/2) cot theta) + S (d_phi - i q A_phi)/sin theta]; D^2 = D_plane^2 + I x D_sphere^2 and D_plane anticommutes with -S x I, so a sphere mode with D_sphere^2 = -mu^2 gives on the Lorentzian plane a Dirac field of mass M, M^2 = m^2 + mu^2",
     compat and zcol(Dfull(psi4) - Dpl(psi4) - chP * Dsph(psi4)) and zcol(Dfull(Dfull(psi4)) - Dpl(Dpl(psi4)) - Dsph(Dsph(psi4))) and zcol(Dpl(chP * psi4) + chP * Dpl(psi4)) and eq(chP * chP, I4))
# the sphere operator on f(theta) e^{i m phi} w_+-, w_+- the chirality vectors of -i C1
wp, wm = sp.Matrix([1, -sp.I]), sp.Matrix([1, sp.I])
kp_, km_ = (-2 - sp.I) / s5, (-2 + sp.I) / s5
az, mz = sp.symbols("a m_z", real=True)
Fth = sp.Function("F")(th_)
L2 = lambda F_, sg: sp.diff(F_, th_) + sp.cot(th_) / 2 * F_ + sg * (mz - az * sp.cos(th_)) / sp.sin(th_) * F_
D2op = lambda P_: (H * (sp.diff(P_, th_) + sp.cot(th_) / 2 * P_) + S * (sp.diff(P_, ph_) - sp.I * az * sp.cos(th_) * P_) / sp.sin(th_)) / r_
eimp = sp.exp(sp.I * mz * ph_)
sh_, ch_ = sp.symbols("s c", positive=True)
dth = lambda F_: (ch_ * sp.diff(F_, sh_) - sh_ * sp.diff(F_, ch_)) / 2
Lsc = lambda F_, sg: dth(F_) + (ch_**2 - sh_**2) / (4 * sh_ * ch_) * F_ + sg * (mz - az * (ch_**2 - sh_**2)) / (2 * sh_ * ch_) * F_
zr = lambda F_, e: sp.simplify(sp.simplify(sp.powsimp(sp.expand(e / F_), force=True)).subs(ch_, sp.sqrt(1 - sh_**2))) == 0  # e / F_ is rational in s, c
p_z, n_z = sp.symbols("p n_z", nonnegative=True, integer=True)
sub0 = {az: n_z / 2, mz: (n_z - 1) / sp.Integer(2) - p_z}
V0 = sh_**p_z * ch_**(n_z - 1 - p_z)
Fbad = sh_**(mz - az - sp.Rational(1, 2)) * ch_**(-mz - az - sp.Rational(1, 2))
cnt = lambda tot: sum(1 for p in range(-3, tot + 4) if p >= 0 and tot - p >= 0)
line("K25 the sphere's zero modes: with -i C1 w_+- = +- w_+-, D_sphere(F e^{i m phi} w_+-) = (1/r)(L_-+ F) e^{i m phi} H w_+-, L_+- = d_theta + (1/2) cot theta +- (m - a cos theta)/sin theta, a = q chi r^2 = n/2, and H w_+ = k w_-, H w_- = k' w_+ with k k' = 1; for n >= 1 the n spinors s^p c^{n-1-p} e^{i m phi} w_-, m = (n-1)/2 - p, p = 0..n-1 (s = sin theta/2, c = cos theta/2) solve D_sphere psi = 0, while on w_+ the only solution s^{m-a-1/2} c^{-m-a-1/2} has exponents summing to -n-1 and is never smooth: the kernel has dimension n and one chirality (counted for n = 1..8), the index n, the lowest Landau level; this is the sector q chi > 0, and for q chi < 0 the chiralities exchange, since L_-(m, a) = L_+(-m, -a)",
     (-sp.I * C1 * wp - wp) == sp.zeros(2, 1) and (-sp.I * C1 * wm + wm) == sp.zeros(2, 1) and zero(H * wp - kp_ * wm) and zero(H * wm - km_ * wp) and sp.simplify(kp_ * km_ - 1) == 0
     and all(zero(sp.expand(D2op(Fth * eimp * w) - (L2(Fth, sg) * eimp / r_) * (H * w))) for w, sg in ((wp, -1), (wm, 1)))
     and zr(V0, Lsc(V0, 1).subs(sub0)) and zr(Fbad, Lsc(Fbad, -1)) and sp.simplify((mz - az - sp.Rational(1, 2)) + (-mz - az - sp.Rational(1, 2)) + 2 * az + 1) == 0
     and all(cnt(nn - 1) == nn and cnt(-nn - 1) == 0 for nn in range(1, 9)) and sp.simplify(L2(Fth, -1) - L2(Fth, 1).subs({mz: -mz, az: -az}, simultaneous=True)) == 0)
A2c = lambda mm: 2 * az + 2 * mm + 3
B2c = lambda mm: -(2 * az - 2 * mm + 3)
F1s = sh_**(az + sp.Rational(1, 2) - mz) * ch_**(az + sp.Rational(1, 2) + mz)
F2s = F1s * (A2c(mz) * sh_**2 + B2c(mz) * ch_**2)
def smooth_count(level, nn):
    aa = sp.Rational(nn, 2); good = 0
    for j in range(-6, nn + 8):
        mm = aa + sp.Rational(1, 2) - j  # m in a + 1/2 + Z
        pe, qe = aa + sp.Rational(1, 2) - mm, aa + sp.Rational(1, 2) + mm
        terms = [(pe, qe, 1)] if level == 1 else [(pe + 2, qe, A2c(mm).subs(az, aa)), (pe, qe + 2, B2c(mm).subs(az, aa))]
        live = [(x, y) for x, y, k in terms if k != 0]
        if live and all(x >= 0 and y >= 0 for x, y in live):
            good += 1
    return good
kk = sp.symbols("k", positive=True)
line("K26 the next two levels: on w_+ the spinors s^{a+1/2-m} c^{a+1/2+m} e^{i m phi} satisfy L_+ L_- F = -(n+1) F, and s^{a+1/2-m} c^{a+1/2+m}((n+2m+3) s^2 - (n-2m+3) c^2) e^{i m phi} satisfy L_+ L_- F = -2(n+2) F, so D_sphere^2 = -k(k+n)/r^2 at k = 1, 2, with n+2 and n+4 smooth states (counted for n = 1..8); since n = 2 q chi r^2, k(k+n)/r^2 = 2 k q chi + k^2/r^2, the Landau level 2kq chi plus the curvature k^2/r^2 = k^2 kappa_E chi^2/2, in the ratio k/n",
     zr(F1s, Lsc(Lsc(F1s, -1), 1) + (2 * az + 1) * F1s) and zr(F1s, Lsc(Lsc(F2s, -1), 1) + 2 * (2 * az + 2) * F2s)
     and all(smooth_count(1, nn) == nn + 2 and smooth_count(2, nn) == nn + 4 for nn in range(1, 9))
     and sp.simplify((kk * (kk + n_q) / r_**2).subs(n_q, 2 * q_ * chi_ * r_**2) - (2 * kk * q_ * chi_ + kk**2 / r_**2)) == 0
     and sp.simplify((kk**2 / r_**2).subs(r_**2, r2E) - kk**2 * kE_ * chi_**2 / 2) == 0 and sp.simplify((kk**2 / r_**2) / (2 * kk * q_ * chi_) - kk / (2 * q_ * chi_ * r_**2)) == 0)

print("# H. Unified: one source")
words = {
    "G": (G, lambda Q, Om: Q * Om - Om * Q),
    "H": (H, lambda Q, Om: (Q * Om - Om * Q) / s5),
    "S": (S, lambda Q, Om: (Q * Om - Om * Q) / s5 * (-Om)),
    "eta^": (eta, lambda Q, Om: dsum(Q * Om - Om * Q, I2)),
    "Chat": (Chat, lambda Q, Om: dsum(Z2, -Om)),
    "B": (B, lambda Q, Om: dsum((Q * Om - Om * Q) / s5 * (-Om), Z2)),
    "J_Sigma": (J, lambda Q, Om: dsum(Z2, -Om)),
    "L": (L, lambda Q, Om: s5 / 2 * I2 + (Q * Om - Om * Q) / s5 * (-Om) / 2),
    "U_pi": (-I2, lambda Q, Om: (-Om) * (-Om)),
}
NINE = ["G", "H", "S", "eta^", "Chat", "B", "J_Sigma", "L", "U_pi"]
Q_alt, Om_alt = sp.Matrix([[2, 1], [1, 1]]), sp.Matrix([[0, 2], [-1, 0]])


def audit_words(ws):
    """names: the table holds exactly the nine names; root: each word at (Q, Omega) equals its matrix; read: each word applied to (Q', Omega')
    equals the definition recomputed by build() on that pair and differs from its root value."""
    r = {"names": sorted(ws) == sorted(NINE)}
    o = build(dict(BASE, Q=Q_alt, Om=Om_alt))
    ref = dict(G=o["G"], H=o["H"], S=o["S"], **{"eta^": o["eta"]}, Chat=o["Chat"], B=o["B"], J_Sigma=o["J"], L=o["L"], U_pi=o["C1"] * o["C1"])
    r["root"] = r["names"] and all(eq(ex(ws[n][1](Q, Om)), ws[n][0]) for n in NINE)
    r["read"] = r["names"] and all(eq(ex(ws[n][1](Q_alt, Om_alt)), ref[n]) and not eq(ex(ws[n][1](Q_alt, Om_alt)), ws[n][0]) for n in NINE)
    return r


w_ok = audit_words(words)
line("H1 the word table holds exactly the nine names %s, and each is a word in Q, Omega, I and the scalars sqrt5, 1/2 that equals its matrix at the root (U_pi built as C1^2 = (-Omega)(-Omega))" % ", ".join(sorted(words)), w_ok["names"] and w_ok["root"])
line("H2 the registered words read their root: applied to (Q', Omega') = ([[2,1],[1,1]], [[0,2],[-1,0]]) each of the nine equals the definition recomputed on that pair and differs from its root value", w_ok["names"] and w_ok["read"])

print("# I. Register and audit")
NIDS = ["N%d" % i for i in range(1, 12)]
CLAIMS = {  # claim -> (statement, the line that certifies it)
    "Q2": ("Q^2 = Q + I", "A1"), "Om2": ("Omega^2 = -I", "A2"), "Gcomm": ("G = [Q, Omega] = [[-2,1],[1,2]]", "A3"), "G2": ("G^2 = 5I", "A4"),
    "L": ("L = (Q + 2I)/sqrt5", "A17"), "light": ("L acts on the light lines by Phi and 1/Phi; velocity 1/sqrt5, Doppler factor Phi", "A20"), "L2": ("L^2 = Q^2", "A18"),
    "sigG": ("sig G = (1, 1)", "A5"), "null": ("null lines of G: (Phi, 1), (-1, Phi)", "A10"), "eig": ("these are the eigenlines of Q", "A11"), "sigeta": ("sig eta^ = (3, 1)", "B2"),
    "reads": ("g = Pi^T eta^ Pi, f = chi_cal Pi^T Chat Pi", "C2"), "gsig": ("sig g(Pi) = (3, 1)", "C3"), "frank": ("f antisymmetric of rank 2 for chi_cal != 0", "C4"), "fgf": ("f g^-1 f = -chi_cal^2 Pi^T (0 + I_2) Pi", "C5"), "chi0": ("rank f = 0 at chi_cal = 0", "C9"),
    "seam": ("[sqrt5 B, J_Sigma] = 0", "D1"), "stabeta": ("B, J_Sigma stabilise eta^", "D2"), "stabC": ("B, J_Sigma stabilise Chat", "D3"), "retph": ("phase read -I at lambda = (log Phi)/2 and I at lambda = log Phi, 2 log Phi", "D9"), "retax": ("axial read L at lambda = log Phi and L^2 = Q^2 at lambda = 2 log Phi", "D10"), "conn": ("dA_R = R, dA_F = F", "D12"), "hol": ("boundary integrals equal the fluxes", "D13"), "noord": ("holonomy = exp of the flux, no ordering term", "D14"),
    "Sig": ("Sigma_G(U_theta) = 0 iff theta in pi Z", "E3"), "Upi": ("U_pi = -I", "E5"), "eps": ("epsilon_v(U_theta) = sin theta", "E6"), "Delta": ("(U_pi - I) v = -2 v", "E7"), "rec": ("recognition iff theta = pi mod 2 pi", "E9"), "quarter": ("Sigma_G(+-C1) = -2G: refusal", "E11"),
    "crt": ("Z/4 + Z/137 = Z/548", "F2"), "phi": ("phi = (2 pi/548)(137 q + 4 s)", "F3"), "inv": ("q = A mod 4, s = (A - 137 q)/4 mod 137", "F5"), "phiwd": ("phi into R/2piZ well defined, injective", "F9"),     "stress": ("T = (chi^2/2) Pi^T(-G + I_2)Pi, traceless", "K1"), "rainich": ("(T^A_B)^2 = (chi^4/4) 1", "K2"), "star": ("** = -1 on 2-forms", "K3"),
    "phase": ("T is unchanged by every duality turn of f; the half turn gives -f", "K4"), "symm": ("the turns keeping eta^ and Chat are exactly span{B, J_Sigma}", "K5"),
    "frame": ("the coframe of the Lorentzian plane times the sphere, and f on the sphere", "K6"), "einstein": ("G = kappa_E T iff r^2 = 2/(kappa_E chi^2)", "K7"),
    "maxwell": ("df = 0, d*f = 0", "K8"), "curv": ("curvature -(1/r^2)(B vol + J_Sigma vol); f = -chi vol_sphere, Omega_J = J_Sigma f/(chi r^2)", "K9"),
    "fieldseam": ("raised once, f = chi J_Sigma and *f = chi B", "K10"), "lorentz": ("m DU/dtau = q chi J_Sigma U keeps eta(U,U); turn at rate q chi/m", "K11"),
    "dyon": ("duality turns the force between J_Sigma and B; q J_Sigma + g B is a turn times a boost", "K12"), "orbit": ("rest at the centre, latitude circle at q chi/(m cos theta_0)", "K13"),
    "spin": ("R(phi)^2 = exp(phi C1), R(2 pi) = -I = U_pi, R(4 pi) = I", "K14"),
    "dirac2": ("(C1, H) is a Clifford pair with chirality -S; G is the form kept by exp(t S); the eigenlines of S are the light lines", "K15"),
    "liftL": ("L is the spin lift of the boost Q^2 (rapidity 2 log Phi); -L gives the same boost", "K16"),
    "gamma": ("real Dirac matrices from the root; their Clifford square is eta^", "K17"),
    "bivec": ("boost and rotation bivectors -S x I, I x C1; volume element squares to -I and exchanges them; spin lifts I x R(phi), L x I", "K18"),
    "charge": ("the commutant of the real Gamma is R I: the charge phase is complex", "K19"),
    "g2": ("Pauli term = 2 rep(f): g = 2; spin and velocity turn together", "K20"),
    "quant": ("Dirac quantization: n = 2 q chi r^2 in Z; n = 4q/(kappa_E chi), r^2 = kappa_E n^2/(8 q^2)", "K23"),
    "separate": ("the Dirac operator of the solution separates; a sphere mode mu gives a plane field of mass^2 m^2 + mu^2", "K24"),
    "zeromodes": ("n sphere zero modes of one chirality: index n, the lowest Landau level", "K25"),
    "levels": ("levels k(k+n)/r^2 at k = 1, 2 with n+2, n+4 states; = 2kq chi + k^2/r^2", "K26"),
    "reader": ("rho_t(lambda) = R(t lambda); seam phase = rho_{t_Phi}; H reverses both reads", "K21"),
    "adapter": ("u_pi = 2 u_Phi; phase returns to Riemann's cell, axial read advances by Q^2", "K22"),
    }
REG = [
    dict(id="D1", demand="Root", status="closed-exact", relation=["Q2", "Om2", "Gcomm", "G2", "L", "L2", "light"], falsifier=["N1", "N3"], certs=["A1", "A2", "A3", "A4", "A9", "A17", "A18", "A19", "A20"]),
    dict(id="D2", demand="Lorentzian reference", status="closed-exact", relation=["sigG", "null", "eig", "sigeta"], falsifier=["N1"], certs=["A5", "A10", "A11", "B1", "B2", "B3", "B4"]),
    dict(id="D3", demand="Coframe reads", status="closed-exact", relation=["reads", "gsig", "frank", "fgf", "chi0"], falsifier=["N2"], certs=["C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9"]),
    dict(id="D4", demand="Seam and curvature reads", status="closed-exact", relation=["seam", "stabeta", "stabC", "retph", "retax", "conn", "hol", "noord", "reader", "adapter"], falsifier=["N4", "N7"], certs=["D1", "D2", "D3", "D5", "D6", "D8", "D9", "D10", "D11", "D12", "D13", "D14", "K21", "K22"]),
    dict(id="D5", demand="Recognition reader", status="closed-exact", relation=["Sig", "Upi", "eps", "Delta", "rec", "quarter"], falsifier=["N5", "N6"], certs=["E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9", "E11"]),
    dict(id="D6", demand="Phase address", status="closed-exact", relation=["crt", "phi", "inv", "phiwd"], falsifier=["N8"], certs=["F1", "F2", "F3", "F4", "F5", "F8", "F9"]),
    dict(id="D7", demand="Field equations, motion and spin", status="closed-exact", relation=["stress", "rainich", "star", "phase", "symm", "frame", "einstein", "maxwell", "curv", "fieldseam", "lorentz", "dyon", "orbit", "spin", "dirac2", "liftL", "gamma", "bivec", "charge", "g2", "quant", "separate", "zeromodes", "levels"], falsifier=["N11"], certs=["K1", "K2", "K3", "K4", "K5", "K6", "K7", "K8", "K9", "K10", "K11", "K12", "K13", "K14", "K15", "K16", "K17", "K18", "K19", "K20", "K23", "K24", "K25", "K26"]),
]
status = {l.split()[0]: ok for l, ok in LABELS}


def audit_register(reg, status):
    ids = [e["id"] for e in reg]
    r = {}
    r["ids"] = ids == ["D%d" % i for i in range(1, 8)]
    r["status"] = all(e["status"] == "closed-exact" for e in reg)
    r["falsifier"] = all(e["falsifier"] and all(n in NIDS for n in e["falsifier"]) for e in reg)
    r["relation"] = all(e["relation"] and all(c in CLAIMS for c in e["relation"]) for e in reg)
    r["covers"] = all(set(e["certs"]) >= {CLAIMS[c][1] for c in e["relation"] if c in CLAIMS} for e in reg)
    r["certs"] = all(e["certs"] and len(set(e["certs"])) == len(e["certs"]) and all(status.get(c, False) for c in e["certs"]) for e in reg)
    return r


for e in REG:
    info("%s %s: %s" % (e["id"], e["demand"], "; ".join("%s [%s]" % CLAIMS.get(c, (c, "not a claim")) for c in e["relation"])))
reg_ok = audit_register(REG, status)
line("I1 the register has exactly the demand ids D1..D7 in order, each entry has status closed-exact, a preserved relation made of claims from the claim table, and a falsifier drawn from N1..N11 (%s)" % ", ".join(sorted(reg_ok)), reg_ok["ids"] and reg_ok["status"] and reg_ok["falsifier"] and reg_ok["relation"])
line("I2 every certificate line cited by an entry is unique within the entry, exists in this receipt and passes, and the entry cites the line named by each claim of its relation", reg_ok["certs"] and reg_ok["covers"])
cited = {c for e in REG for c in e["certs"]}
info("lines not cited by any entry (supporting lines): " + ", ".join(sorted(k for k in status if k not in cited and k[0] in "ABCDEF")))
line("I3 closed: every demand has an entry whose certificates all pass; unified: H1 holds (one root, nine words); exact: every verdict above is an identity in Q(sqrt5), in integers or in Fractions, or a seeded finite trial marked as one", all(reg_ok.values()) and status["H1"])

print("# J. Negative controls: one-fault mutations of the instance")
base_p = preds(BASE, trials=12)
line("J0 the unmutated instance passes all %d predicates of the audit (%s)" % (len(base_p), ", ".join(sorted(base_p))), all(base_p.values()))
mut = [
    ("M1 Omega replaced by [[0,1],[1,0]] (Omega^2 = +I)", dict(Om=sp.Matrix([[0, 1], [1, 0]])), "Om2"),
    ("M2 G replaced by the product Q Omega in place of the commutator", dict(Gmode="prod"), "G2"),
    ("M3 the G corner -2 replaced by +2", dict(Gcorner=2), "sig"),
    ("M4 the tail I_2 of eta^ replaced by -I_2", dict(tail=-I2), "sig"),
    ("M5 the tail of eta^ removed (replaced by 0)", dict(tail=Z2), "sig"),
    ("M6 Chat given a symmetric tail I_2", dict(Chat_tail=I2), "Chat"),
    ("M7 J_Sigma moved to the first block (C1 (+) 0)", dict(Jpos="upper"), "seam"),
    ("M8 L replaced by I + S/2", dict(Lmode="bad"), "return"),
    ("M9 the modulus 137 replaced by 136", dict(p=136), "crt"),
    ("M10 kappa replaced by pi/(2 log Phi) (one half turn at lambda = log Phi)", dict(c=F(1, 2)), "kappa"),
    ("M11 a singular coframe Pi (row 4 = row 1 + row 2)", dict(Pi=rand_pi(random.Random(7), singular=True)), "gsig"),
    ("M12 the recognition reader U = -I replaced by U = C1", dict(U=C1), "recog"),
    ("M13 Q replaced by [[1,1],[1,1]] (Q^2 = 2Q)", dict(Q=sp.Matrix([[1, 1], [1, 1]])), "Q2"),
    ("M14 the calibration constant chi_cal = 0 (f = 0)", dict(chi=sp.Integer(0)), "fnz"),
    ("M15 kappa replaced by 2 pi/log Phi (two turns at lambda = log Phi)", dict(c=2), "kappa"),
    ("M16 the modulus 137 replaced by the composite 135 (gcd(4, 135) = 1, so the address stays a bijection)", dict(p=135), "prime"),
    ("M24 the tail I_2 of eta^ replaced by diag(1, 2)", dict(tail=sp.diag(1, 2)), "stab"),
    ("M31 Chat given a field on both blocks, C1 (+) C1", dict(Chat_tail=None, Chat_both=True), "stress"),
    ("M32 the seam boost B replaced by -B", dict(Bsign=-1), "fieldseam"),
]
for name, change, target in mut:
    P = dict(BASE)
    P.update(change)
    try:
        r = preds(P, trials=12)
        failed = sorted(k for k, vv in r.items() if not vv)
    except Exception as e:  # a mutation that breaks the build also fails the audit
        failed = ["build:" + type(e).__name__]
    line("J %s: the audit fails %s; target %s %s" % (name, "{" + ", ".join(failed) + "}", target, "is among them" if target in failed else "IS NOT FAILED"), target in failed)
line("J14 each of the %d predicates of the audit is the target of at least one control" % len(base_p), {t for _, _, t in mut} >= set(base_p))
import copy
regmut = [
    ("M17 the register replaced by seven entries X0..X6 each citing A1 four times", [dict(id="X%d" % i, demand="x", status="closed-exact", relation="x", falsifier=["N1"], certs=["A1", "A1", "A1", "A1"]) for i in range(7)], "ids"),
    ("M18 the status of D3 lowered to declared placement", [dict(e, status="declared placement") if e["id"] == "D3" else e for e in REG], "status"),
    ("M19 the falsifier of D5 emptied", [dict(e, falsifier=[]) if e["id"] == "D5" else e for e in REG], "falsifier"),
    ("M20 D4 made to cite a line that does not exist (D99)", [dict(e, certs=e["certs"] + ["D99"]) if e["id"] == "D4" else e for e in REG], "certs"),
    ("M21 D6 dropped, six entries", [e for e in REG if e["id"] != "D6"], "ids"),
    ("M23 the citations of D6 replaced by A1 alone", [dict(e, certs=["A1"]) if e["id"] == "D6" else e for e in REG], "covers"),
    ("M22 the preserved relation of D2 emptied", [dict(e, relation=[]) if e["id"] == "D2" else e for e in REG], "relation"),
    ("M25 the preserved relation of D2 replaced by the statement 0 = 1", [dict(e, relation=["0 = 1"]) if e["id"] == "D2" else e for e in REG], "relation"),
    ("M30 D4 stops citing D9 (the phase factor of the joint return)", [dict(e, certs=[c for c in e["certs"] if c != "D9"]) if e["id"] == "D4" else e for e in REG], "covers"),
    ("M26 D2 stops citing A10 and A11 (the null and eigenline lines)", [dict(e, certs=[c for c in e["certs"] if c not in ("A10", "A11")]) if e["id"] == "D2" else e for e in REG], "covers"),
]
for name, reg, target in regmut:
    r = audit_register(reg, status)
    failed = sorted(k for k, vv in r.items() if not vv)
    line("J %s: the register audit fails {%s}; target %s %s" % (name, ", ".join(failed), target, "is among them" if target in failed else "IS NOT FAILED"), target in failed)

w_lit = dict(words)
w_lit["G"] = (G, lambda Q, Om: sp.Matrix([[-2, 1], [1, 2]]))
w_less = {k: v for k, v in words.items() if k != "U_pi"}
wordmut = [
    ("M27 the registered word for G replaced by its literal matrix", w_lit, "read"),
    ("M28 the word table emptied", {}, "names"),
    ("M29 the word U_pi removed from the table", w_less, "names"),
]
for name, ws, target in wordmut:
    r = audit_words(ws)
    failed = sorted(k for k, vv in r.items() if not vv)
    line("J %s: the word audit fails {%s}; target %s %s" % (name, ", ".join(failed), target, "is among them" if target in failed else "IS NOT FAILED"), target in failed)

n_pass = sum(1 for _, c in LABELS if c)
n_fail = sum(1 for _, c in LABELS if not c)
print("COUNT PASS=%d FAIL=%d" % (n_pass, n_fail))
print("RESULT " + ("PASS" if OK else "FAIL"))
if len(sys.argv) > 1:
    sec = {}
    for l, c in LABELS:
        sec.setdefault(l[0], [0, 0])[0 if c else 1] += 1
    json.dump(dict(pass_=n_pass, fail=n_fail, sections=sec, result="PASS" if OK else "FAIL"), open(sys.argv[1], "w"), indent=1)
sys.exit(0 if OK else 1)
