#!/usr/bin/env python3
"""Verification script for Paper 16, "From the Cut Square to the 3x3 Box".

Exact arithmetic in free symbols (sympy), except one floating-point illustration, which is labelled.
Each check prints one line named after the statement it checks.
"""
import sympy as sp, itertools as it, time, sys
def cd_table(k):
    """Doubling of a number system: constants M[i][j][l] of e_i e_j = sum_l M[i][j][l] e_l, and the signs of the conjugate"""
    if k == 1: return [[[1]]], [1]
    M0, c0 = cd_table(k//2); h = k//2
    M = [[[0]*k for _ in range(k)] for _ in range(k)]; c = c0 + [-1]*h
    for i in range(h):
        for j in range(h):
            for l in range(h):
                M[i][j][l] += M0[i][j][l]                    # (a,0)(c,0) = (ac,0)
                M[h+i][h+j][l] -= c0[j]*M0[j][i][l]          # (0,b)(0,d) = (-conj(d) b, 0)
                M[i][h+j][h+l] += M0[j][i][l]                # (a,0)(0,d) = (0, d a)
                M[h+i][j][h+l] += c0[j]*M0[i][j][l]          # (0,b)(c,0) = (0, b conj(c))
    return M, c
class K:
    def __init__(s, k):
        s.k = k; s.M, s.c = cd_table(k)
        s.terms = [[(i, j, s.M[i][j][l]) for i in range(k) for j in range(k) if s.M[i][j][l]] for l in range(k)]
    def mul(s, a, b): return [sum(m*a[i]*b[j] for i, j, m in s.terms[l]) for l in range(s.k)]
    def conj(s, a): return [s.c[i]*a[i] for i in range(s.k)]
    def nrm(s, a): return sum(t*t for t in a)
    def re(s, a): return a[0]
    def add(s, a, b, t=1): return [a[i] + t*b[i] for i in range(s.k)]
    def sc(s, r, a): return [r*t for t in a]
# a 3x3 box: (d, o) with d = three diagonal numbers and o = (a1,a2,a3) the hidden links,
# a1 between lines 2,3; a2 between 3,1; a3 between 1,2:  [[d1,a3,conj a2],[conj a3,d2,a1],[a2,conj a1,d3]]
def N3(F, d, o):
    return d[0]*d[1]*d[2] - sum(d[i]*F.nrm(o[i]) for i in range(3)) + 2*F.re(F.mul(F.mul(o[0], o[1]), o[2]))
def sharp(F, d, o):
    dd = [d[1]*d[2] - F.nrm(o[0]), d[2]*d[0] - F.nrm(o[1]), d[0]*d[1] - F.nrm(o[2])]
    oo = [F.add(F.conj(F.mul(o[(i+1) % 3], o[(i+2) % 3])), F.sc(d[i], o[i]), -1) for i in range(3)]
    return dd, oo
def T3(F, d, o, d2, o2):
    return sum(d[i]*d2[i] for i in range(3)) + 2*sum(o[i][t]*o2[i][t] for i in range(3) for t in range(F.k))
def symbox(F, name):
    d = list(sp.symbols('%s1:4' % name)); o = [list(sp.symbols('%s%d_0:%d' % (name.lower(), i+1, F.k))) for i in range(3)]
    return d, o
def exp_all(v): return [sp.expand(t) for t in v]

# =====================================================================================
# checks
# =====================================================================================
import sys
CHECKS = []
def check(label, ok, note=""):
    CHECKS.append(bool(ok))
    print(("PASS  " if ok else "FAIL  ") + label + (("  [" + note + "]") if note else ""), flush=True)
H = sp.Rational(1, 2)
SYSTEMS = [(1, "real"), (2, "complex"), (4, "quaternion"), (8, "octonion")]

# ---------------------------------------------------------------- Part I, section 3: the 2x2 box
x, y = sp.symbols('x y', real=True)
there, seen, hid = x**2 + y**2, x**2 - y**2, 2*x*y                 # the cut of the root (x,y), Paper 4
Gm = sp.Matrix([[there + seen, hid], [hid, there - seen]])
Pl, Ql = x**2, y**2                                                # the ledger of Paper 2
check("Proposition 3.2: the box of a cut is 2 psi psi^T; its diagonal is the ledger doubled; hidden^2 = 4 x ghost",
      Gm == 2*sp.Matrix([x, y])*sp.Matrix([[x, y]]) and sp.expand(Gm[0, 0] - 2*Pl) == 0 and sp.expand(Gm[1, 1] - 2*Ql) == 0
      and sp.expand(there - (Pl + Ql)) == 0 and sp.expand(seen - (Pl - Ql)) == 0 and sp.expand(hid**2 - 4*(Pl*Ql)) == 0)
T_, A_, U_ = sp.symbols('T A U', real=True)
Hm = sp.Matrix([[T_ + A_, U_], [U_, T_ - A_]]); Fl = Hm - T_*sp.eye(2)
okf = (Fl*Fl - (A_**2 + U_**2)*sp.eye(2)).applyfunc(sp.expand) == sp.zeros(2) and sp.expand(Hm.det() - (T_**2 - A_**2 - U_**2)) == 0
for k, nm in SYSTEMS:                      # the flip over the four number systems: F = [[s, a], [conj a, -s]]
    F = K(k); a = list(sp.symbols('a0:%d' % k)); s_ = sp.Symbol('s'); ab = F.conj(a); one = [1] + [0]*(k - 1)
    d11 = F.add(F.sc(s_*s_, one), F.mul(a, ab)); d12 = F.add(F.sc(s_, a), F.sc(s_, a), -1)
    okf &= exp_all(d11) == exp_all(F.sc(s_*s_ + F.nrm(a), one)) and all(sp.expand(t) == 0 for t in d12)
check("Proposition 3.3: a box is there x 1 plus a flip; the flip squares to seen^2 + hidden^2 over the four number systems; determinant = even form", okf)
ok2a = True
for k, nm in SYSTEMS:
    F = K(k); u = list(sp.symbols('u0:%d' % k)); v = list(sp.symbols('v0:%d' % k))
    ok2a &= sp.expand(F.nrm(F.mul(u, v)) - F.nrm(u)*F.nrm(v)) == 0 and exp_all(F.conj(F.mul(u, v))) == exp_all(F.mul(F.conj(v), F.conj(u)))
check("Lemma 2.2(a): sizes multiply, and the conjugate of a product is the product of the conjugates in the other order", ok2a, "four number systems, free symbols")
ok = True
for k, nm in SYSTEMS:
    F = K(k); u = list(sp.symbols('u0:%d' % k)); v = list(sp.symbols('v0:%d' % k))
    ok &= sp.expand(F.nrm(F.mul(u, v)) - F.nrm(u)*F.nrm(v)) == 0                        # sizes multiply
    corner = F.mul(u, F.conj(v))                                                        # x conj(y)
    ok &= sp.expand(F.nrm(u)*F.nrm(v) - F.nrm(corner)) == 0                             # determinant of the cut is zero
    ok &= exp_all(F.conj(F.mul(u, F.conj(v)))) == exp_all(F.mul(v, F.conj(u)))          # the two corners are conjugates
check("Theorem 3.4: over the four number systems the cut of a root is a box with conjugate corners and even form zero", ok)
F2 = K(2); xp, xpp, yp, ypp = sp.symbols("x1 x2 y1 y2")        # u = x' + i x'', v = y' + i y''
cz = F2.mul([xp, xpp], F2.conj([yp, ypp]))                      # the corner u conj(v)
check("Theorem 3.4(d): for a complex root the corner is (x'y' + x''y'') - i [psi', psi'']",
      sp.expand(cz[0] - (xp*yp + xpp*ypp)) == 0 and sp.expand(cz[1] + (xp*ypp - yp*xpp)) == 0)
hh = sp.symbols('h')
check("Remark 3.5: a corner h i and its partner -h i multiply to the real square h^2 (Paper 1)",
      K(2).mul([0, hh], [0, -hh]) == [hh**2, 0])
p_, q_, r_, tau = sp.symbols('p q r tau', real=True)
c_, s_ = (1 - tau**2)/(1 + tau**2), 2*tau/(1 + tau**2)
Rm = sp.Matrix([[c_, s_], [-s_, c_]]); Bx = sp.Matrix([[p_, r_], [r_, q_]])
Bt = (Rm*Bx*Rm.T).applyfunc(sp.simplify)
num = sp.numer(sp.together(Bt[0, 1]))
check("Theorem 3.6: a turn of view changes the hidden part to a multiple of r(c^2 - s^2) - cs(p - q), which some turn makes zero",
      sp.expand(num - sp.expand((r_*((1 - tau**2)**2 - 4*tau**2) - 2*tau*(1 - tau**2)*(p_ - q_)))) == 0
      or sp.expand(num + sp.expand((r_*((1 - tau**2)**2 - 4*tau**2) - 2*tau*(1 - tau**2)*(p_ - q_)))) == 0)
check("Theorem 3.6: a turn keeps the trace, the sum of squares and the even form of the box",
      sp.simplify(Bt.trace() - Bx.trace()) == 0 and sp.simplify(Bt.det() - Bx.det()) == 0
      and sp.simplify((Bt*Bt).trace() - (Bx*Bx).trace()) == 0)
lam = sp.symbols('lam')
check("Theorem 3.6: with nothing hidden the two readings are there +- sqrt(seen^2 + hidden^2)",
      sp.expand((lam - T_)**2 - (A_**2 + U_**2) - (Hm - lam*sp.eye(2)).det()) == 0)

# ---------------------------------------------------------------- Part I, section 4: the 3x3 box
def jordan_mat(F, d, o):
    """the 3x3 box as a matrix of numbers of the system"""
    z = [0]*F.k; e = lambda r: [r] + [0]*(F.k - 1)
    return [[e(d[0]), o[2], F.conj(o[1])], [F.conj(o[2]), e(d[1]), o[0]], [o[1], F.conj(o[0]), e(d[2])]]
def mmul(F, X, Y):
    return [[[sum(F.mul(X[i][j], Y[j][l])[t] for j in range(3)) for t in range(F.k)] for l in range(3)] for i in range(3)]
def mjord(F, X, Y):
    XY, YX = mmul(F, X, Y), mmul(F, Y, X)
    return [[[H*(XY[i][l][t] + YX[i][l][t]) for t in range(F.k)] for l in range(3)] for i in range(3)]
def mtrace(F, X): return sum(X[i][i][0] for i in range(3))
ok_cof = ok_sh = ok_tr = ok_cub = ok_cyc = True
for k, nm in SYSTEMS:
    F = K(k); d, o = symbox(F, 'A')
    dd, oo = sharp(F, d, o); n3 = sp.expand(N3(F, d, o))
    ok_cof &= sp.expand(T3(F, dd, oo, d, o) - 3*n3) == 0
    ok_cof &= all(sp.expand(dd[i] - (d[(i+1) % 3]*d[(i+2) % 3] - F.nrm(o[i]))) == 0 for i in range(3))
    d2, o2 = sharp(F, dd, oo)
    ok_sh &= all(sp.expand(d2[i] - n3*d[i]) == 0 for i in range(3)) and \
             all(sp.expand(o2[i][t] - n3*o[i][t]) == 0 for i in range(3) for t in range(k))
    M = jordan_mat(F, d, o); M2 = mjord(F, M, M); M3 = mjord(F, M2, M)
    tr1, tr2, tr3 = mtrace(F, M), mtrace(F, M2), mtrace(F, M3)
    ok_tr &= sp.expand(tr2 - T3(F, d, o, d, o)) == 0 and sp.expand(6*n3 - (tr1**3 - 3*tr1*tr2 + 2*tr3)) == 0
    S2 = sum(dd)
    ok_tr &= sp.expand(2*S2 - (tr1**2 - tr2)) == 0
    for i in range(3):
        for l in range(3):
            for t in range(k):
                unit = (n3 if (i == l and t == 0) else 0)
                ok_cub &= sp.expand(M3[i][l][t] - tr1*M2[i][l][t] + S2*M[i][l][t] - unit) == 0
    a, b, c = o
    ok_cyc &= sp.expand(F.re(F.mul(F.mul(a, b), c)) - F.re(F.mul(a, F.mul(b, c)))) == 0
    ok_cyc &= sp.expand(F.re(F.mul(F.mul(a, b), c)) - F.re(F.mul(F.mul(c, a), b))) == 0
ok_der = True
for k, nm in SYSTEMS:
    F = K(k); d, o = symbox(F, 'A'); e, p = symbox(F, 'B')
    dd, oo = sharp(F, d, o); ee, pp = sharp(F, e, p)
    lhs = N3(F, [d[i] + e[i] for i in range(3)], [F.add(o[i], p[i]) for i in range(3)])
    ok_der &= sp.expand(lhs - N3(F, d, o) - T3(F, dd, oo, e, p) - T3(F, d, o, ee, pp) - N3(F, e, p)) == 0
check("Lemma 4.2(b): N(A + B) = N(A) + T(A#, B) + T(A, B#) + N(B)", ok_der, "four number systems, free symbols")
check("Lemma 4.2(a): the even form by cofactors; the diagonal of the cofactor box is the three 2x2 even forms", ok_cof, "four number systems, free symbols")
check("Theorem 4.3: the cofactor box of the cofactor box is the even form times the box", ok_sh, "four number systems, free symbols")
import random
F16 = K(16); e16 = lambda i: [1 if j == i else 0 for j in range(16)]
d16 = [0, 0, 0]; o16 = [F16.add(e16(3), e16(10)), F16.add(e16(6), e16(15), -1), [0]*16]
dd16, oo16 = sharp(F16, d16, o16); d2_16, o2_16 = sharp(F16, dd16, oo16)
check("Theorem 4.3: at 16 numbers the identity fails: for d = 0, a1 = e3 + e10, a2 = e6 - e15, a3 = 0 the even form is 0 and the double cofactor box has diagonal (0, 0, 4)",
      N3(F16, d16, o16) == 0 and d2_16 == [0, 0, 4])
check("Proposition 4.4(a): the trace of the square is the sum of squares; the even form and the sum of 2x2 even forms from the traces of powers", ok_tr)
check("Proposition 4.4(b): the box satisfies its own cubic equation, with the products taken symmetrically", ok_cub, "four number systems, free symbols")
check("Lemma 2.2(b): the real part of a product of three numbers does not depend on the brackets or on turning the three round", ok_cyc)
# corner turn, step 1: the phase.  For any number w:  a1 -> w a1 w,  a2 -> conj(w) a2,  a3 -> a3 conj(w)
ok = True
for k, nm in SYSTEMS:
    F = K(k); d, o = symbox(F, 'A'); a1, a2, a3 = o; w = list(sp.symbols('w0:%d' % k)); wb = F.conj(w); n2 = F.nrm(w)
    waw = F.mul(F.mul(w, a1), w)
    ok &= exp_all(waw) == exp_all(F.mul(w, F.mul(a1, w)))                                        # w a w needs no brackets
    ok &= exp_all(F.mul(waw, F.mul(wb, a2))) == exp_all(F.sc(n2, F.mul(w, F.mul(a1, a2))))       # Lemma 2.2(c)
    ok &= exp_all(F.mul(F.mul(a3, wb), w)) == exp_all(F.sc(n2, a3))
    new = [waw, F.mul(wb, a2), F.mul(a3, wb)]
    ok &= sp.expand(F.re(F.mul(F.mul(new[0], new[1]), new[2])) - n2**2*F.re(F.mul(F.mul(a1, a2), a3))) == 0
    ok &= sp.expand(F.nrm(waw) - n2**2*F.nrm(a1)) == 0 and sp.expand(F.nrm(new[1]) - n2*F.nrm(a2)) == 0
check("Lemma 2.2(c) and Lemma 4.6, the phase: w a1 w, conj(w) a2, a3 conj(w) keep the real part of the product of the three links and their sizes (for |w| = 1)", ok,
      "four number systems, free symbols")
# corner turn, step 2: a real turn of lines 1 and 2 by (c,s)
ok = True
for k, nm in SYSTEMS:
    F = K(k); d, o = symbox(F, 'A'); M = jordan_mat(F, d, o)
    R = [[c_, s_, 0], [-s_, c_, 0], [0, 0, 1]]
    RM = [[[sum(R[i][j]*M[j][l][t] for j in range(3)) for t in range(k)] for l in range(3)] for i in range(3)]
    M1 = [[[sum(RM[i][j][t]*R[l][j] for j in range(3)) for t in range(k)] for l in range(3)] for i in range(3)]
    d1 = [M1[i][i][0] for i in range(3)]; o1 = [M1[1][2], M1[2][0], M1[0][1]]
    ok &= sp.simplify(sum(d1) - sum(d)) == 0
    ok &= sp.simplify(T3(F, d1, o1, d1, o1) - T3(F, d, o, d, o)) == 0
    ok &= sp.simplify(N3(F, d1, o1) - N3(F, d, o)) == 0
    # the other two links are turned into each other and keep the sum of their squares
    ok &= sp.simplify(F.nrm(o1[0]) + F.nrm(o1[1]) - F.nrm(o[0]) - F.nrm(o[1])) == 0
check("Lemma 4.6, the turn: a real turn of two lines keeps the trace, the sum of squares and the even form, and the squares of the other two links together", ok,
      "four number systems, free symbols and a free turn")
# illustration in floating point: corner turns, always at the largest link
import math
def corner_turn(F, d, o, m):
    """remove the link o[m]: relabel the lines so that it is a3, phase, turn of lines 1 and 2, relabel back"""
    k = F.k; sh = (m - 2) % 3
    d = [d[(i + sh) % 3] for i in range(3)]; o = [o[(i + sh) % 3] for i in range(3)]
    r = math.sqrt(F.nrm(o[2]))
    if r > 0:
        w = [t/r for t in o[2]]
        o = [F.mul(F.mul(w, o[0]), w), F.mul(F.conj(w), o[1]), [r] + [0.0]*(k - 1)]
        th = 0.5*math.atan2(2*r, d[0] - d[1]); c, s = math.cos(th), math.sin(th)
        M = jordan_mat(F, d, o); R = [[c, s, 0], [-s, c, 0], [0, 0, 1]]
        RM = [[[sum(R[a][j]*M[j][b][t] for j in range(3)) for t in range(k)] for b in range(3)] for a in range(3)]
        M = [[[sum(RM[a][j][t]*R[b][j] for j in range(3)) for t in range(k)] for b in range(3)] for a in range(3)]
        d = [M[i][i][0] for i in range(3)]; o = [M[1][2], M[2][0], M[0][1]]
    return [d[(i - sh) % 3] for i in range(3)], [o[(i - sh) % 3] for i in range(3)]
def corner_run(k, steps=14, seed=3):
    rnd = random.Random(seed); F = K(k)
    d = [rnd.uniform(-1, 1) for _ in range(3)]; o = [[rnd.uniform(-1, 1) for _ in range(k)] for _ in range(3)]
    tr0, T0, N0, S0 = sum(d), T3(F, d, o, d, o), N3(F, d, o), sum(sharp(F, d, o)[0])
    hid2 = lambda o: sum(F.nrm(a) for a in o)
    h0 = hid2(o); worst = rate = inv = 0.0
    for _ in range(steps):
        m = max(range(3), key=lambda i: F.nrm(o[i])); before = hid2(o); link = F.nrm(o[m])
        d, o = corner_turn(F, d, o, m)
        worst = max(worst, abs((before - hid2(o)) - link))
        if before > 1e-10: rate = max(rate, hid2(o)/before)      # above the rounding level
        inv = max(inv, abs(sum(d) - tr0), abs(T3(F, d, o, d, o) - T0), abs(N3(F, d, o) - N0), abs(sum(sharp(F, d, o)[0]) - S0))
    res = max(abs(t**3 - tr0*t*t + S0*t - N0) for t in d)
    return h0, hid2(o), worst, rate, inv, res
ok = True; notes = []
for k, nm in SYSTEMS:
    h0, h1, worst, rate, inv, res = corner_run(k)
    ok &= h1 < 1e-25 and worst < 1e-12 and rate < 2/3 + 1e-9 and inv < 1e-12 and res < 1e-12
    notes.append("%s %.0e -> %.0e" % (nm, h0, h1))
check("Theorem 4.7, illustration in floating point: corner turns at the largest link remove the hidden part and end on the three roots of the cubic", ok,
      "hidden^2: " + "; ".join(notes))
# a box with cofactor box zero: the cut of a triple root (real, complex, quaternion)
ok = True
for k, nm in SYSTEMS[:3]:
    F = K(k); u = [list(sp.symbols('u%d_0:%d' % (i, k))) for i in range(3)]
    d = [F.nrm(u[i]) for i in range(3)]
    o = [F.mul(u[1], F.conj(u[2])), F.mul(u[2], F.conj(u[0])), F.mul(u[0], F.conj(u[1]))]
    dd, oo = sharp(F, d, o)
    ok &= all(sp.expand(t) == 0 for t in dd) and all(sp.expand(t) == 0 for v in oo for t in v) and sp.expand(N3(F, d, o)) == 0
F = K(8); e8 = lambda i: [1 if j == i else 0 for j in range(8)]; u = [e8(1), e8(2), e8(4)]
d = [F.nrm(u[i]) for i in range(3)]; o = [F.mul(u[1], F.conj(u[2])), F.mul(u[2], F.conj(u[0])), F.mul(u[0], F.conj(u[1]))]
check("Proposition 4.8(b),(c): three numbers of R, C, H make a box with cofactor box zero; over the octonions u = (e1, e2, e4) does not, and has even form -4",
      ok and N3(F, d, o) == -4 and any(t != 0 for v in sharp(F, d, o)[1] for t in v))
okd = True
for k, nm in SYSTEMS:                      # three numbers with the first one real: u = (r, conj(a3)/r, a2/r), times r
    F = K(k); r_ = sp.Symbol('r'); a2s = list(sp.symbols('p0:%d' % k)); a3s = list(sp.symbols('q0:%d' % k))
    u = [[r_*r_] + [0]*(k - 1), F.conj(a3s), a2s]                              # r u
    d = [F.nrm(u[i])/r_**2 for i in range(3)]
    o = [F.sc(1/r_**2, v) for v in (F.mul(u[1], F.conj(u[2])), F.mul(u[2], F.conj(u[0])), F.mul(u[0], F.conj(u[1])))]
    dd, oo = sharp(F, d, o)
    okd &= all(sp.simplify(t) == 0 for t in dd) and all(sp.simplify(t) == 0 for v in oo for t in v)
    okd &= sp.simplify(d[0] - r_**2) == 0 and all(sp.simplify(o[2][t] - a3s[t]) == 0 and sp.simplify(o[1][t] - a2s[t]) == 0 for t in range(k))
check("Proposition 4.8(d): three numbers of which one is real make a cut over all four number systems, with the links a2, a3 and the line d1 free", okd)

# ---------------------------------------------------------------- Part II, section 5: two numbers and two boxes
def quartic(F, al, be, dA, oA, dB, oB):
    sA, sB = sharp(F, dA, oA), sharp(F, dB, oB)
    return 8*T3(F, sA[0], sA[1], sB[0], sB[1]) - 8*al*N3(F, dA, oA) - 8*be*N3(F, dB, oB) - 2*(T3(F, dA, oA, dB, oB) - al*be)**2
Ps = [[[sp.Symbol('P%d%d%d' % (i, j, k)) for k in range(2)] for j in range(2)] for i in range(2)]
Sr = [sp.symbols('s%dx s%dy' % (p, p)) for p in (1, 2, 3)]
def detquad(m, n):
    a = m[0][0]*m[1][1] - m[0][1]*m[1][0]; c = n[0][0]*n[1][1] - n[0][1]*n[1][0]
    b = m[0][0]*n[1][1] + n[0][0]*m[1][1] - m[0][1]*n[1][0] - n[0][1]*m[1][0]; return (a, b, c)
def readers(P):
    L = [[[P[i][j][k] for j in range(2)] for k in range(2)] for i in range(2)]; X = detquad(L[0], L[1])
    R = [[[P[i][j][k] for i in range(2)] for k in range(2)] for j in range(2)]; Y = detquad(R[0], R[1])
    m = [[P[i][j][1] for j in range(2)] for i in range(2)]; n = [[-P[i][j][0] for j in range(2)] for i in range(2)]
    a, b, c = detquad(m, n); return X, Y, (-a, -b, -c)
rdr = lambda R, v: R[0]*v[0]**2 + R[1]*v[0]*v[1] + R[2]*v[1]**2
Xr, Yr, Zr = readers(Ps); nP = Xr[0]*Xr[2] - sp.Rational(1, 4)*Xr[1]**2
Pap = lambda s, t: tuple(sum(Ps[i][j][k]*s[i]*t[j] for i in range(2) for j in range(2)) for k in range(2))
ar = lambda u, v: u[0]*v[1] - u[1]*v[0]
n15 = sp.expand(nP + rdr(Xr, Sr[0]) + rdr(Yr, Sr[1]) - rdr(Zr, Sr[2]) + 2*ar(Pap(Sr[0], Sr[1]), Sr[2]))   # Paper 15, Theorem 4.5
F1 = K(1)
def tables_of(P, S):
    """Theorem 5.2: the fourteen numbers of Paper 15, seen from the basis roots of each place"""
    al, be = P[0][0][0], P[1][1][1]
    dA = [P[0][1][1], P[1][0][1], P[1][1][0]]; oA = [[S[0][0]], [S[1][0]], [-S[2][1]]]
    dB = [P[1][0][0], P[0][1][0], P[0][0][1]]; oB = [[S[0][1]], [S[1][1]], [S[2][0]]]
    return al, be, dA, oA, dB, oB
q15 = sp.expand(quartic(F1, *tables_of(Ps, Sr)))
check("Theorem 5.2: the fourteen numbers of Paper 15 are two numbers and two 3x3 boxes, and the quartic of the boxes is 8 n(x)",
      sp.expand(q15 - 8*n15) == 0, "fourteen free symbols")
Qs = [[[sp.Symbol('Q%d%d%d' % (i, j, k)) for k in range(2)] for j in range(2)] for i in range(2)]
Rr = [sp.symbols('r%dx r%dy' % (p, p)) for p in (1, 2, 3)]
al, be, dA, oA, dB, oB = tables_of(Ps, Sr); al2, be2, dA2, oA2, dB2, oB2 = tables_of(Qs, Rr)
om = al*be2 - al2*be + T3(F1, dA, oA, dB2, oB2) - T3(F1, dA2, oA2, dB, oB)
PQ = ar(Ps[0][0], Qs[1][1]) - ar(Ps[0][1], Qs[1][0]) - ar(Ps[1][0], Qs[0][1]) + ar(Ps[1][1], Qs[0][0])
a15 = PQ + 2*sum(ar(Sr[p], Rr[p]) for p in range(3))                                                    # Paper 15, Definition 4.1
check("Theorem 5.2: the area of two threefolds of Paper 15 is the pairing of the boxes",
      sp.expand(om - a15) == 0, "fourteen and fourteen free symbols")
F2c = K(2); p1, p2, q1, q2 = sp.symbols('p1 p2 q1 q2'); z2 = [0, 0]
qc = sp.expand(quartic(F2c, 0, 0, [0, 0, 0], [[p1, p2], z2, z2], [0, 0, 0], [[q1, q2], z2, z2]))
check("Remark 6.1: over the complex numbers, one link a and its partner b alone have quartic 8 (Im(a conj b))^2, the area of Theorem 3.4(d); over the reals it is zero",
      sp.expand(qc - 8*(p2*q1 - p1*q2)**2) == 0 and sp.expand(quartic(K(1), 0, 0, [0, 0, 0], [[p1], [0], [0]], [0, 0, 0], [[q1], [0], [0]])) == 0)
al0, be0, dA0, oA0, dB0, oB0 = tables_of(Ps, [(0, 0)]*3)
As = [dA0[1]*dA0[2], dA0[2]*dA0[0], dA0[0]*dA0[1]]; Bs = [dB0[1]*dB0[2], dB0[2]*dB0[0], dB0[0]*dB0[1]]
c53 = 8*sum(As[i]*Bs[i] for i in range(3)) - 8*al0*dA0[0]*dA0[1]*dA0[2] - 8*be0*dB0[0]*dB0[1]*dB0[2] \
      - 2*(sum(dA0[i]*dB0[i] for i in range(3)) - al0*be0)**2
check("Corollary 5.3: with nothing hidden, the quartic is 8 n(P) of the product of roots, by the formula with A#_i = A_j A_k",
      sp.expand(c53 - 8*nP) == 0, "eight free symbols")
ok = all(8 + 6*k == 2 + 2*(3 + 3*k) for k, _ in SYSTEMS)
check("Definition 5.1 (arithmetic): two numbers and two boxes are 8 + 6k numbers: 14, 20, 32, 56", ok)

# ---------------------------------------------------------------- Lemma 2.2(d): the doubling stops multiplying sizes at 16
F16 = K(16); u16 = [0]*16; v16 = [0]*16; u16[3] = 1; u16[10] = 1; v16[6] = 1; v16[15] = -1
check("Lemma 2.2(d): at 16 numbers sizes no longer multiply: u = e3 + e10 and v = e6 - e15 have size 2 and product zero",
      F16.nrm(u16) == 2 and F16.nrm(v16) == 2 and all(t == 0 for t in F16.mul(u16, v16)))
print("\n%d checks; %s" % (len(CHECKS), "all pass" if all(CHECKS) else "FAILURES"))