#!/usr/bin/env python3
"""Verification script for Paper 17, "The Four Rungs".

Exact arithmetic throughout.  All tensors are whole numbers; they are held in float64, where whole numbers
below 2^53 and their sums and products are exact (the largest number met is printed and checked), and ranks
and characteristic polynomials are computed by python-flint over the whole numbers.
Default: the real, complex and quaternion rungs (seconds).  With --octonion also the last rung (about 6 minutes).
Each check prints one line named after the statement it checks.
"""
import numpy as np, sys, time, math, itertools as it
from fractions import Fraction
import flint
CHECKS = []
def check(label, ok, note=""):
    CHECKS.append(bool(ok))
    print(("PASS  " if ok else "FAIL  ") + label + (("  [" + note + "]") if note else ""), flush=True)
NAMES = {1: "real", 2: "complex", 4: "quaternion", 8: "octonion"}
BIG = [0.0]
def seen(*arrs):
    for a in arrs: BIG[0] = max(BIG[0], float(np.abs(a).max()))

# the four numbers (alpha, beta, a, b): quartic, cubic, reader; whole changes of view act on the root (X, Y) of the cubic
def qs(al, be, a, b): return 6*a*a*b*b - 8*al*a**3 - 8*be*b**3 + 12*al*be*a*b - 2*al*al*be*be
def cubic(al, be, a, b): return (al, 3*b, 3*a, be)                              # al X^3 + 3b X^2 Y + 3a X Y^2 + be Y^3
def point(c): return (c[0], c[3], c[2]//3, c[1]//3)
def cval(c, X, Y): return c[0]*X**3 + c[1]*X*X*Y + c[2]*X*Y*Y + c[3]*Y**3
def disc(p, q, r, s): return q*q*r*r - 4*p*r**3 - 4*q**3*s - 27*p*p*s*s + 18*p*q*r*s
def reader(al, be, a, b): return (b*b - al*a, a*b - al*be, a*a - be*b)
def shear(c, m): p, q, r, s = c; return (p, q + 3*p*m, r + 2*q*m + 3*p*m*m, s + r*m + q*m*m + p*m**3)      # X -> X + mY
def turn(c): p, q, r, s = c; return (s, -r, q, -p)                                                           # (X, Y) -> (-Y, X)
def shearR(R, m): A, B, C = R; return (A, B + 2*A*m, C + B*m + A*m*m)
def turnR(R): A, B, C = R; return (C, -B, A)

def paper15_bracket():
    """the bracket of Paper 15, Definition 4.2, on its fourteen numbers (P000..P111, then a root in each place),
    built as in the script of Paper 15: threefolds on the triple root, mu fixed by tr(mu(x,y) A) = -1/2 <A.x, y>.
    Returns M[i][j] = the 14x14 matrix of mu(e_i, e_j) acting on the fourteen numbers (exact)."""
    import sympy as sp
    COMB = list(it.combinations(range(6), 3)); CIDX = {c: n for n, c in enumerate(COMB)}
    area = lambda u, v: u[0]*v[1] - u[1]*v[0]
    OM = [[0]*6 for _ in range(6)]
    for p in range(3): OM[2*p][2*p+1] = 1; OM[2*p+1][2*p] = -1
    def sgn_sort(t):
        t = list(t); s = 1
        for a in range(3):
            for b in range(2 - a):
                if t[b] > t[b+1]: t[b], t[b+1] = t[b+1], t[b]; s = -s
        return (0, None) if t[0] == t[1] or t[1] == t[2] else (s, tuple(t))
    unit = lambda i: tuple(1 if a == i else 0 for a in range(6))
    def from_parts(P, s1, s2, s3):
        x = [0]*20
        for n, (i, j, k) in enumerate(COMB):
            v = 0
            if i < 2 and 2 <= j < 4 and k >= 4: v += area(P[i][j-2], unit(k)[4:6])
            for (u, w, r) in ((i, j, k), (j, k, i), (k, i, j)):
                ar = [OM[u][w] if u//2 == w//2 == p else 0 for p in range(3)]; eu = unit(r)
                v += (ar[1] - ar[2])*area(s1, eu[0:2]) + (ar[2] - ar[0])*area(s2, eu[2:4]) + (ar[0] - ar[1])*area(s3, eu[4:6])
            x[n] = v
        return x
    def rho(A):
        R = [[0]*20 for _ in range(20)]
        for n, (i, j, k) in enumerate(COMB):
            for a in range(6):
                for (pos, old) in ((0, i), (1, j), (2, k)):
                    if A[a][old] == 0: continue
                    idx = [i, j, k]; idx[pos] = a; s, t = sgn_sort(idx)
                    if s: R[n][CIDX[t]] -= s*A[a][old]
        return R
    W = [[-OM[i][j] for j in range(6)] for i in range(6)]; B6 = []
    for i in range(6):
        for j in range(i, 6):
            S = [[0]*6 for _ in range(6)]; S[i][j] = S[j][i] = 1
            B6.append(sp.Matrix([[sum(W[a][b]*S[b][c] for b in range(6)) for c in range(6)] for a in range(6)]))
    SY = sp.symbols(['P%d%d%d' % (i, j, k) for i in range(2) for j in range(2) for k in range(2)] + ['s1x', 's1y', 's2x', 's2y', 's3x', 's3y'])
    parts = lambda v: (tuple(tuple((v[4*i + 2*j], v[4*i + 2*j + 1]) for j in range(2)) for i in range(2)), (v[8], v[9]), (v[10], v[11]), (v[12], v[13]))
    EMB = sp.Matrix(20, 14, lambda r, c: sp.diff(sp.Matrix(from_parts(*parts(SY)))[r], SY[c])); DEC = (EMB.T*EMB).inv()*EMB.T
    R14 = [DEC*sp.Matrix(rho(A.tolist()))*EMB for A in B6]
    om20 = sp.zeros(20, 20)
    for n, (i, j, k) in enumerate(COMB):
        for m, (l, mm, nn) in enumerate(COMB):
            om20[n, m] = sum(s*W[i][p[0]]*W[j][p[1]]*W[k][p[2]] for p, s in (((l, mm, nn), 1), ((mm, nn, l), 1), ((nn, l, mm), 1), ((mm, l, nn), -1), ((l, nn, mm), -1), ((nn, mm, l), -1)))
    AREA = -(EMB.T*om20*EMB); GI = sp.Matrix(21, 21, lambda a, b: (B6[a]*B6[b]).trace()).inv()
    NA = [R14[a].T*AREA for a in range(21)]
    M = [[None]*14 for _ in range(14)]
    for i in range(14):
        for j in range(14):
            cf = GI*sp.Matrix([sp.Rational(-1, 2)*(NA[a][i, j] + NA[a][j, i])/2 for a in range(21)])
            M[i][j] = sum((cf[a]*R14[a] for a in range(21) if cf[a] != 0), sp.zeros(14, 14))
    return M

def cd_table(k):
    """doubling (Paper 16, Definition 2.1): constants M[i,j,l] of e_i e_j = sum_l M[i,j,l] e_l"""
    if k == 1: return np.ones((1, 1, 1)), np.array([1.0])
    M0, c0 = cd_table(k//2); h = k//2
    M = np.zeros((k, k, k)); c = np.concatenate([c0, -np.ones(h)])
    for i in range(h):
        for j in range(h):
            M[i, j, :h] += M0[i, j]; M[h+i, h+j, :h] -= c0[j]*M0[j, i]; M[i, h+j, h:] += M0[j, i]; M[h+i, j, h:] += c0[j]*M0[i, j]
    return M, c

def build(k):
    """two numbers and two boxes over the number system of k numbers: x = (alpha, beta, A, B), A = (d1,d2,d3; a1,a2,a3)"""
    M, c = cd_table(k); nJ = 3 + 3*k; n = 2 + 2*nJ
    w = np.concatenate([np.ones(3), 2*np.ones(3*k)])                              # T(A,C) = sum w_m A_m C_m
    sl = lambda i: slice(3 + k*i, 3 + k*(i+1))
    n3 = np.zeros((nJ, nJ, nJ)); n3[0, 1, 2] = 1                                  # N(A) = n3 A A A
    for i in range(3):
        for t in range(k): n3[i, 3+k*i+t, 3+k*i+t] -= 1
    n3[sl(0), sl(1), sl(2)] += 2*np.einsum('ijl,lr->ijr', M, M[:, :, 0])          # 2 Re((a1 a2) a3)
    c3 = sum(np.transpose(n3, p) for p in it.permutations(range(3)))              # 6 x the symmetric form of N
    iA = slice(2, 2+nJ); iB = slice(2+nJ, n)
    U = np.zeros((n, n, n, n))                                                    # q(x) = U x x x x, not yet symmetric
    U[iA, iA, iB, iB] += 2*np.einsum('mnp,mrs,m->nprs', c3, c3, 1/w)              # 8 T(A#, B#)
    E = np.zeros((n, n)); E[iA, iB] = np.diag(w); E[0, 1] = -1                    # T(A,B) - alpha beta
    U -= 2*np.einsum('ab,cd->abcd', E, E)
    Q4 = sum(np.transpose(U, p) for p in it.permutations(range(4)))               # 24 Q
    cA = np.zeros((n, n, n)); cA[iA, iA, iA] = c3; cB = np.zeros((n, n, n)); cB[iB, iB, iB] = c3
    for pos in range(4):                                                          # -8 alpha N(A) - 8 beta N(B)
        for idx, cc in ((0, cA), (1, cB)):
            t = np.zeros((n, n, n, n)); ix = [slice(None)]*4; ix[pos] = idx; t[tuple(ix)] = -8*cc; Q4 += t
    O = np.zeros((n, n)); O[0, 1] = 1; O[1, 0] = -1                               # the pairing omega
    for m in range(nJ): O[2+m, 2+nJ+m] = w[m]; O[2+nJ+m, 2+m] = -w[m]
    return dict(k=k, n=n, nJ=nJ, w=w, c3=c3, Q4=Q4, O=O)

def rung(k):
    t0 = time.time(); nm = NAMES[k]; B = build(k); n, nJ, w, c3, Q4, O = B['n'], B['nJ'], B['w'], B['c3'], B['Q4'], B['O']
    rng = np.random.default_rng(100 + k); I = np.eye(n); t = 6 + 3*k
    N = lambda A: np.einsum('mpr,m,p,r->', c3, A, A, A)/6
    sh = lambda A: np.einsum('mpr,p,r->m', c3, A, A)/(2*w)
    cr = lambda A, C: np.einsum('mpr,p,r->m', c3, A, C)/w
    T = lambda A, C: np.sum(w*A*C)
    def q_boxes(x):
        al, be, A, Bx = x[0], x[1], x[2:2+nJ], x[2+nJ:]
        return 8*T(sh(A), sh(Bx)) - 8*al*N(A) - 8*be*N(Bx) - 2*(T(A, Bx) - al*be)**2
    xs = [rng.integers(-3, 4, size=n).astype(float) for _ in range(6)]
    check("Definition 2.2 (%s): the four-form Q gives back the quartic of the boxes, q(x) = Q(x,x,x,x); %d numbers" % (nm, n),
          all(np.einsum('abcd,a,b,c,d->', Q4, x, x, x, x) == 24*q_boxes(x) for x in xs) and n == 8 + 6*k and n == 2*t - 4)
    # tau: omega(tau(x,y,z), w) = Q(x,y,z,w).   T2 = 48 tau
    Oi = np.linalg.inv(O); T2 = np.rint(2*np.einsum('xyzw,wa->xyza', Q4, Oi))
    ok_tau = np.abs(np.einsum('xyza,aw->xyzw', T2, O) - 2*Q4).max() == 0
    L = np.einsum('xz,ya->xyza', O, I) + np.einsum('yz,xa->xyza', O, I)             # omega(x,z) y + omega(y,z) x
    # the weight: mu_c(x,y) z = c tau(x,y,z) + L.  "mu_c(x,y) keeps q" is linear in c; one sample fixes c
    x, y, a = xs[0], xs[1], xs[2]
    dq = lambda Mat: np.einsum('ebcd,e,b,c,d->', Q4, Mat @ a, a, a, a)
    t1 = dq(np.einsum('xyza,x,y->az', T2, x, y)); t2 = dq(np.einsum('xyza,x,y->az', L, x, y))     # t1 is 48 times the tau part: whole
    seen(np.array([t1, t2])); c = Fraction(int(-48*t2), int(t1))
    check("Theorem 3.2(b) (%s): mu_c(x,y) can keep q for one weight only, and that weight is c = 6" % nm, ok_tau and t1 != 0 and c == 6, "c = %s" % c)
    Mu = T2 + 8*L                                                                   # 8 mu,  [x,y,z,a] = (8 mu(x,y) z)_a
    seen(Q4, T2, Mu)
    check("Theorem 3.2(a) (%s): every mu(x,y) keeps the pairing omega" % nm,
          max(np.abs(Mu[i, j] @ O + O @ Mu[i, j].T).max() for i in range(n) for j in range(n)) == 0)
    Q2 = Q4.reshape(n, n**3); worst = 0
    for xi in range(n):
        for yi in range(xi, n):
            G = (Mu[xi, yi] @ Q2).reshape(n, n, n, n)                               # sum_e (mu e_a)_e Q[e,b,c,d]
            S = G + G.transpose(1, 0, 2, 3) + G.transpose(1, 2, 0, 3) + G.transpose(1, 2, 3, 0)
            worst = max(worst, np.abs(S).max()); seen(G)
    check("Theorem 3.2(b) (%s): with c = 6 every mu(x,y) keeps the quartic q: Q(mu a,b,c,d) + ... = 0 on all basis elements" % nm, worst == 0,
          "%d pairs (x,y), each a table of %d^4 whole numbers" % (n*(n+1)//2, n))
    ok = True
    for x in xs:
        al, be, A, Bx = x[0], x[1], x[2:2+nJ], x[2+nJ:]; kap = T(A, Bx) - al*be
        lhs = np.einsum('xyza,x,y,z->a', Mu, x, x, x)/8
        rhs = np.concatenate([[-12*N(Bx) + 6*kap*al, 12*N(A) - 6*kap*be], 12*cr(Bx, sh(A)) - 12*be*sh(Bx) - 6*kap*A, -12*cr(A, sh(Bx)) + 12*al*sh(A) + 6*kap*Bx])
        ok &= np.abs(lhs - rhs).max() == 0
        Mx = np.einsum('xyza,x,y->az', Mu, x, x)/8
        ok &= np.abs(Mx @ (Mx @ x) + 18*q_boxes(x)*x).max() == 0
    check("Theorem 3.4 (%s): mu(x,x)x in the words of boxes, and mu(x,x) mu(x,x) x = -18 q(x) x (whole sample points; proved in the text)" % nm, ok)
    # Jacobi for three odd elements
    Bt = 16*np.einsum('xy,za->xyza', O, I) - 8*np.einsum('yz,xa->xyza', O, I) - 8*np.einsum('zx,ya->xyza', O, I) + Mu.transpose(2, 0, 1, 3) - Mu.transpose(1, 2, 0, 3)
    check("Theorem 4.2 (%s): the identity behind the Jacobi identity of three odd elements, on all basis triples" % nm, np.abs(Bt).max() == 0)
    # the changes of view
    pairs = [(i, j) for i in range(n) for j in range(i, n)]
    F = np.array([Mu[i, j].T.ravel() for i, j in pairs])
    rk = flint.fmpz_mat(F.shape[0], F.shape[1], [int(v) for v in F.ravel()]).rank()
    pm = 2**31 - 1; ia = np.array([p[0] for p in pairs]); ib = np.array([p[1] for p in pairs]); off = (ia != ib); Oi2 = np.rint(2*Oi); rows = []
    for r in range(len(pairs) + 40):
        x = rng.integers(-2, 3, size=n).astype(float); u = Oi2.T @ np.einsum('abcd,b,c,d->a', Q4, x, x, x); rows.append(u[ia]*x[ib] + off*u[ib]*x[ia])
    rows = np.array(rows); seen(rows)
    bound = len(pairs) - flint.nmod_mat(rows.shape[0], rows.shape[1], [int(v) % pm for v in rows.ravel()], pm).rank()
    dk = {1: 21, 2: 35, 4: 66, 8: 133}[k]
    check("Theorem 4.3(a) (%s): the mu(x,y) span %d changes of view, and no more than %d keep omega and q; algebra 3 + %d + 2 x %d = %d" % (nm, dk, dk, dk, n, 3 + dk + 2*n),
          rk == dk and bound == dk and 3 + dk + 2*n == {1: 52, 2: 78, 4: 133, 8: 248}[k], "exact rank %d, bound %d" % (rk, bound))
    # trace rule
    TR = (Mu.reshape(n*n, n*n) @ Mu.transpose(3, 2, 0, 1).reshape(n*n, n*n)).reshape(n, n, n, n)      # tr(8mu(x,y) 8mu(l,m))
    OM = (Mu.reshape(n**3, n) @ O).reshape(n, n, n, n).transpose(2, 3, 0, 1)*8                          # 8 omega(8mu(l,m) x, y)
    seen(TR, OM)
    check("Theorem 4.3(b) (%s): tr(mu(x,y) X) = -(2k+8) omega(Xx, y) for every X = mu(z,w)" % nm, np.abs(TR + (2*k + 8)*OM).max() == 0, "-(2k+8) = %d" % (-(2*k + 8)))
    # signature
    tab = flint.nmod_mat(F.shape[1], F.shape[0], [int(v) % pm for v in F.T.ravel()], pm).rref()[0].tolist(); piv = []
    for row in tab:
        cc = next((cc for cc, v in enumerate(row) if int(v) != 0), None)
        if cc is None: break
        piv.append(cc)
    mats = [Mu[pairs[p][0], pairs[p][1]].T for p in piv]
    Gm = np.array([[np.sum(a*b.T) for b in mats] for a in mats]); seen(Gm)
    co = [int(v) for v in flint.fmpz_mat(len(piv), len(piv), [int(v) for v in Gm.ravel()]).charpoly().coeffs()]
    sg = [v for v in co if v != 0]; pos = sum(1 for a, b in zip(sg, sg[1:]) if (a > 0) != (b > 0)); neg = len(piv) - pos
    exp = {1: (12, 9), 2: (18, 17), 4: (30, 36), 8: (54, 79)}[k]
    check("Theorem 4.4 (%s): the trace form on the changes of view has signature %s; the invariant form of the algebra (%d,%d)" % (nm, str(exp), 2 + exp[0] + n, 1 + exp[1] + n),
          len(piv) == dk and co[0] != 0 and (pos, neg) == exp, "characteristic polynomial of a %d x %d table of whole numbers, by sign changes" % (dk, dk))
    # the bottom rung
    D = [0, 1, 2, 3, 4, 2+nJ, 3+nJ, 4+nJ]; rest = [i for i in range(n) if i not in D]; sub = Mu[np.ix_(D, D)]
    closed = np.abs(sub[:, :, D][:, :, :, rest]).max() == 0
    F8 = np.array([sub[i, j][np.ix_(D, D)].ravel() for i in range(8) for j in range(i, 8)])
    r8 = flint.fmpz_mat(F8.shape[0], F8.shape[1], [int(v) for v in F8.ravel()]).rank()
    check("Theorem 5.1 (%s): with no links the bracket stays with no links and spans 9 changes of view: Paper 14, 3 + 9 + 16 = 28" % nm, closed and r8 == 9)
    # the line: the trace rule at the bottom, and the rung of four numbers
    s8 = sub[:, :, D][:, :, :, D]; O8 = O[np.ix_(D, D)]
    TR8 = np.einsum('xyza,lmaz->xylm', s8, s8); OM8 = 8*np.einsum('lmxa,ay->xylm', s8, O8)
    check("Theorem 6.4 (%s): at the bottom, with the trace taken over the eight numbers, the factor of the trace rule is -8" % nm, np.abs(TR8 + 8*OM8).max() == 0)
    S = np.zeros((4, n)); S[0, 0] = S[1, 1] = 1; S[2, 2:5] = 1; S[3, 2+nJ:5+nJ] = 1          # alpha, beta, a, b
    M4 = np.einsum('ix,jy,xyza->ijza', S, S, Mu); im = np.einsum('ijza,lz->ijla', M4, S); co = im[..., [0, 1, 2, 2+nJ]]
    up = [(i, j) for i in range(4) for j in range(i, 4)]
    rK = flint.fmpz_mat(10, n*n, [int(v) for i, j in up for v in M4[i, j].ravel()]).rank()
    rS = flint.fmpz_mat(10, 16, [int(v) for i, j in up for v in co[i, j].ravel()]).rank()
    check("Theorem 6.2(a) (%s): the same in every place: the bracket stays there and spans 3 changes of view; algebra 3 + 3 + 8 = 14" % nm,
          np.abs(im - co @ S).max() == 0 and rK == 3 and rS == 3)
    O4 = S @ O @ S.T; TR4 = np.einsum('ijlm,pqml->ijpq', co, co); OM4 = 8*np.einsum('pqir,rj->ijpq', co, O4)
    tri = next(c for c in it.combinations(up, 3) if flint.fmpz_mat(3, 16, [int(v) for i, j in c for v in co[i, j].ravel()]).rank() == 3)
    G3 = [[int(TR4[p + q]) for q in tri] for p in tri]
    check("Theorem 6.2(b) (%s): on the four numbers the factor of the trace rule is -20/3, and the trace form on the 3 changes of view has signature (2,1): the form of the algebra (8,6)" % nm,
          np.abs(3*TR4 + 20*OM4).max() == 0 and flint.fmpz_mat(3, 3, sum(G3, [])).det() < 0 and max(G3[i][i] for i in range(3)) > 0, "table %s" % G3)
    ok = True
    for _ in range(20):
        pt = [int(v) for v in rng.integers(-4, 5, size=4)]; x = S.T @ np.array(pt, float); qq = qs(*pt); XY = [int(v) for v in rng.integers(-3, 4, size=2)]
        tp = [int(v) for v in np.einsum('xyza,x,y,z->a', Mu, x, x, x)[[0, 1, 2, 2+nJ]]]                 # 48 tau(x,x,x)
        R = reader(*pt); r = R[0]*XY[0]**2 + R[1]*XY[0]*XY[1] + R[2]*XY[1]**2
        ok &= q_boxes(x) == qq and 27*qq == 2*disc(*cubic(*pt)) and 2*(4*R[0]*R[2] - R[1]**2) == qq
        al, be, a, b = pt; ar = lambda u, v: u[0]*v[1] - u[1]*v[0]                                      # Paper 13, Definition 5.1: the product reader
        ok &= ar(XY, (b, a))**2 - ar(XY, (al, b))*ar(XY, (a, be)) == R[0]*XY[1]**2 - R[1]*XY[0]*XY[1] + R[2]*XY[0]**2
        ok &= cval(cubic(*tp), *XY)**2 + 1152*qq*cval(cubic(*pt), *XY)**2 == 9216*r**3
    check("Theorem 6.2(c), Theorem 6.3(a) (%s): q is 2/27 of the discriminant of the cubic and 8 times the even form of the reader, which is the product reader of Paper 13 at the turned root; (cubic of tau(x,x,x))^2 + (q/2)(cubic of x)^2 = 4 (reading)^3" % nm, ok)
    if k == 1:      # Corollary 5.2(a): through the dictionary of Paper 16, Theorem 5.2
        M15 = paper15_bracket(); dic = [(0, 1), (7, 1), (3, 1), (5, 1), (6, 1), (8, 1), (10, 1), (13, -1), (4, 1), (2, 1), (1, 1), (9, 1), (11, 1), (12, 1)]
        ok = all(int(Mu[r1, r2, r3, r4])*s1*s2*s3 == 32*s4*M15[i1][i2][i4, i3]
                 for r1, (i1, s1) in enumerate(dic) for r2, (i2, s2) in enumerate(dic) for r3, (i3, s3) in enumerate(dic) for r4, (i4, s4) in enumerate(dic))
        check("Corollary 5.2(a) (R): the bracket is exactly 4 times the bracket of Paper 15, Definition 4.2, on all fourteen basis elements", ok)
    check("exactness (%s): every whole number in the tensors and tables is below 2^53" % nm, BIG[0] < 2**53, "largest %d; %.0f s" % (BIG[0], time.time() - t0))

ks = [1, 2, 4] + ([8] if '--octonion' in sys.argv else [])
for k in ks: rung(k)
check("Theorem 4.5 (arithmetic): t = 6 + 3k = 9, 12, 18, 30; 2t - 4 = 8 + 6k; trace form of the fourth place 8 + 2(8 + 6k) = 4t",
      all(8 + 2*(8 + 6*k) == 4*(6 + 3*k) and 2*(6 + 3*k) - 4 == 8 + 6*k for k in (1, 2, 4, 8)))
rows = {4: (4, 3, 14), 6: (8, 9, 28), 9: (14, 21, 52), 12: (20, 35, 78), 18: (32, 66, 133), 30: (56, 133, 248)}
check("Theorem 6.4 (arithmetic): on the six rungs t = 4, 6, 9, 12, 18, 30 the count is 2t - 4, the algebra is 2(t+1)(5t-6)/(t+6), the factor is -2(t+6)/3",
      all(n == 2*t - 4 and 3 + dk + 2*n == d and d*(t + 6) == 2*(t + 1)*(5*t - 6) for t, (n, dk, d) in rows.items())
      and all(Fraction(2*(t + 6), 3) == f for t, f in ((4, Fraction(20, 3)), (6, 8), (9, 10), (12, 12), (18, 16), (30, 24))))
# the triangle: three numbers up to order and a common factor; a line is (l1,l2,l3) with l1 a + l2 b + l3 c = 0
cross = lambda u, v: (u[1]*v[2] - u[2]*v[1], u[2]*v[0] - u[0]*v[2], u[0]*v[1] - u[1]*v[0])
same = lambda p, q: cross(p, q) == (0, 0, 0)
perms = lambda c: sorted(set(it.permutations(c)))
on = lambda l, p: sum(a*b for a, b in zip(l, p)) == 0
cyc = lambda c: [c, (c[2], c[0], c[1]), (c[1], c[2], c[0])]
corners = lambda c: [cross(u, v) for u, v in it.combinations(cyc(c), 2)]
rung_line, P14 = (2, 2, -1), (-2, 4, 4)
ok = all(on(rung_line, (-6, t + 6, 2*t)) for t in (4, 6, 9, 12, 18, 30)) and len(perms(rung_line)) == 3
ok &= all(any(same(p, q) for q in perms(P14)) for p in corners(rung_line)) and len({tuple(sorted(Fraction(v, sum(p)) for v in p)) for p in corners(rung_line)}) == 1
ok &= all(sum(Fraction(p[i], sum(p)) for p in corners(rung_line)) == 1 for i in range(3))          # the centre is (1,1,1)
ok &= all(any(same(p, q) for q in perms((-2, 2, 2))) for p in corners((1, 1, 0))) and len(perms((1, 1, 0))) == 3
ok &= (1, 2, 0) in perms((2, 1, 0)) and len(perms((2, 1, 0))) == 6 and all(any(same(p, q) for q in perms((-2, 1, 4))) for c in ((2, 1, 0), (1, 2, 0)) for p in corners(c))
ok &= all(sum(on(l, q) for l in perms(rung_line)) == 2 and sum(on(l, q) for l in perms((2, 1, 0))) == 2 for q in perms(P14))
check("Theorem 6.5: the six rungs lie on c = 2(a+b); that line and its two mirror images are a triangle with all three corners at Paper 14's point (-2,4,4); the lines b=2, b=4, b=1 likewise, with corners (-2,2,2) and (-2,1,4)", ok)
# whole points with q = 46 (even form 23/4)
rng0 = np.random.default_rng(7); ok = True
for _ in range(300):
    pt = tuple(int(v) for v in rng0.integers(-5, 6, size=4)); m = int(rng0.integers(-3, 4)); c = cubic(*pt)
    ok &= all(v % 3 == 0 for cc in (shear(c, m), turn(c)) for v in cc[1:3])
    ok &= qs(*point(shear(c, m))) == qs(*pt) == qs(*point(turn(c))) and reader(*point(shear(c, m))) == shearR(reader(*pt), m) and reader(*point(turn(c))) == turnR(reader(*pt))
check("Theorem 6.3(b): a whole change of view of the root carries whole points to whole points, keeps q and carries the reader along", ok)
red = [(A, B, C) for A in range(1, 4) for B in range(-A + 1, A + 1) for C in range(A, 8) if 4*A*C - B*B == 23 and not (A == C and B < 0)]
found = {R: [p for p in it.product(range(-6, 7), repeat=4) if reader(*p) == R] for R in red}
def inside(R):                         # (cubic)^2 <= (reading)^3 / n at (1,0), (0,1), (1,1), (1,-1) bounds the four numbers
    A, B, C = R; f = lambda v: math.isqrt(4*v**3//23); al, be, s, d = f(A), f(C), f(A + B + C), f(A - B + C)
    return max(al, be, (s + d + 2*al)//6, (s + d + 2*be)//6) <= 6
check("Theorem 6.3(b): the reduced readers of even form 23/4 are [1,1,6], [2,1,3], [2,-1,3]; each is the reader of exactly one whole point and its negative",
      red == [(1, 1, 6), (2, -1, 3), (2, 1, 3)] and all(inside(R) for R in red)
      and found == {(1, 1, 6): [(0, -5, 1, 1), (0, 5, -1, -1)], (2, -1, 3): [(-1, -2, 1, 1), (1, 2, -1, -1)], (2, 1, 3): [(-1, 2, 1, -1), (1, -2, -1, 1)]},
      str({R: v[-1] for R, v in found.items()}))
# the number systems seen from one another (Section 7)
def seen_from():
    rg = np.random.default_rng(17); ri = lambda n: rg.integers(-5, 6, size=n).astype(float)
    T = {k: cd_table(k) for k in (1, 2, 4, 8, 16)}
    def ml(k): M = T[k][0]; return lambda x, y: np.einsum('ijl,i,j->l', M, x, y)
    up = lambda a, n: np.concatenate([a, np.zeros(n - len(a))])                  # a number of a smaller system, as (a, 0, ...)
    okA = okB = okC = True; zero = {}
    for h in (1, 2, 4, 8):
        k = 2*h; m, m0, c0 = ml(k), ml(h), T[h][1]; l = np.zeros(k); l[h] = 1; E = np.eye(h)
        for i in range(h):
            okA &= np.array_equal(m(l, up(E[i], k)) - m(up(E[i], k), l), m(up(c0*E[i] - E[i], k), l))
            for j in range(h):
                A, B = up(E[i], k), up(E[j], k)
                okB &= np.array_equal(m(m(A, B), l) - m(A, m(B, l)), m(up(m0(E[i], E[j]) - m0(E[j], E[i]), k), l))
        z = True
        for _ in range(200):
            a, b, cc, d = ri(h), ri(h), ri(h), ri(h); x, y = np.concatenate([a, b]), np.concatenate([cc, d])
            lhs = m(x, y) @ m(x, y) - (x @ x)*(y @ y)
            rhs = 2*m0(m0(d, a), m0(cc, c0*b))[0] - 2*m0(m0(a, cc), m0(c0*b, d))[0]
            okC &= lhs == rhs; z &= lhs == 0
        zero[h] = bool(z)
    check("Lemma 7.1 and Theorem 7.2(a): l a - a l = (conj(a) - a) l, on all units, for the doublings of the four number systems", okA)
    check("Theorem 7.2(b): (ab) l - a(b l) = (ab - ba) l, on all pairs of units, for the doublings of the four number systems", okB)
    check("Theorem 7.2(c): |xy|^2 - |x|^2|y|^2 = 2Re((da)(c conj b)) - 2Re((ac)(conj b d)); it is zero from R, C, H and not from O",
          okC and zero == {1: True, 2: True, 4: True, 8: False}, str(zero))
    rows = {}
    for k in (1, 2, 4, 8, 16):
        m, c = ml(k), T[k][1]; E = np.eye(k)
        own = bool(np.all(c == 1)); com = all(np.array_equal(m(E[i], E[j]), m(E[j], E[i])) for i in range(k) for j in range(k))
        ass = all(np.array_equal(m(m(E[i], E[j]), E[r]), m(E[i], m(E[j], E[r]))) for i in range(k) for j in range(k) for r in range(k))
        siz = all((lambda x, y: m(x, y) @ m(x, y) == (x @ x)*(y @ y))(ri(k), ri(k)) for _ in range(200))
        rows[k] = (own, com, ass, siz)
    check("Theorem 7.2, the table: own conjugate, commutes, associates, sizes multiply are lost one doubling apart",
          rows == {1: (True, True, True, True), 2: (False, True, True, True), 4: (False, False, True, True),
                   8: (False, False, False, True), 16: (False, False, False, False)})
    ok = True
    for k in (2, 4, 8):                                                          # seen from the real numbers
        m = ml(k); E = np.eye(k)
        ok &= all(np.array_equal(m(E[0], E[i]), m(E[i], E[0])) for i in range(k))
        ok &= all(np.array_equal(m(E[0], m(E[i], E[j])), m(m(E[0], E[i]), E[j])) and np.array_equal(m(m(E[i], E[0]), E[j]), m(E[i], m(E[0], E[j])))
                  and np.array_equal(m(m(E[i], E[j]), E[0]), m(E[i], m(E[j], E[0]))) for i in range(k) for j in range(k))
    check("Proposition 7.3(a): seen from the real numbers nothing fails", ok)
    ok = True
    for k in (4, 8):                                                             # seen from the complex numbers
        m, c = ml(k), T[k][1]; E = np.eye(k); Cb = [E[0], E[1]]
        for z in Cb:
            for w in Cb:
                ok &= all(np.array_equal(m(z, m(w, E[i])), m(m(z, w), E[i])) and np.array_equal(m(m(z, E[i]), w), m(z, m(E[i], w))) for i in range(k))
            ok &= all(np.array_equal(m(z, E[i]), m(E[i], c*z)) for i in range(2, k))
            for i in range(k):
                for j in range(k):
                    xp, yp = E[i].copy(), E[j].copy(); xp[:2] = 0; yp[:2] = 0; P = m(xp, yp); P[:2] = 0
                    ok &= np.array_equal(m(m(z, E[i]), E[j]) - m(z, m(E[i], E[j])), m(c*z - z, P))
    check("Proposition 7.3(b): seen from the complex numbers, H and O are numbers over C from both sides, z x = x conj(z) outside C, "
          "and (zx)y - z(xy) = (conj(z) - z) times the part of x'y' outside C", ok)
    m, m0 = ml(8), ml(4); E = np.eye(8); E4 = np.eye(4); l = E[4]; ok = True       # seen from the quaternions
    for i in range(4):
        for j in range(4):
            com = up(m0(E4[i], E4[j]) - m0(E4[j], E4[i]), 8)
            for r in range(8):
                d = up(E[r][4:], 8)
                ok &= np.array_equal(m(m(E[i], E[j]), E[r]) - m(E[i], m(E[j], E[r])), m(m(d, com), l))
    check("Proposition 7.3(c): seen from the quaternions, (ab)x - a(bx) = (d(ab - ba)) l for x = (c, d) in O", ok)
seen_from()
if '--octonion' not in sys.argv: print("      (the octonion rung was not run; use --octonion, about 6 minutes)")
print("\n%d checks; %s" % (len(CHECKS), "all pass" if all(CHECKS) else "FAILURES"))
