#!/usr/bin/env python3
"""Verification script for Paper 14, "The Bracket of a Product".

Exact arithmetic throughout: sympy for identities in free symbols, Fractions for
the algebra of dimension 28. Each check prints one line named after the statement
it checks.

A product of roots is kept as P[i][j] = P(e_i, e_j), a root (Paper 13).
A reader [A,B,C] reads (x,y) as A x^2 + B x y + C y^2; its own turn is
S = J Gamma = [[-B/2, -C], [A, B/2]].
A change of view in each place, g = (A, B, C), acts on a product by
    (g.P)(psi,chi) = C P(psi,chi) - P(A psi,chi) - P(psi,B chi).
"""
from fractions import Fraction as Fr
from itertools import product as iproduct
import random
import sympy as sp

CHECKS = []
def check(label, ok, note=""):
    CHECKS.append(bool(ok))
    print(("PASS  " if ok else "FAIL  ") + label + (("  [" + note + "]") if note else ""))

E2 = ((1, 0), (0, 1))
def apply(P, s, t):
    return tuple(sum(P[i][j][k]*s[i]*t[j] for i in range(2) for j in range(2)) for k in range(2))
def block_from(fn):
    return tuple(tuple(tuple(fn(E2[i], E2[j])) for j in range(2)) for i in range(2))
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 three_readers(P):
    """left, right and product reader of a product of roots (Paper 13, Definition 5.1)"""
    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)
def padd(P, Q, s=1):
    return tuple(tuple(tuple(P[i][j][k] + s*Q[i][j][k] for k in range(2)) for j in range(2)) for i in range(2))
def pscale(c, P):
    return tuple(tuple(tuple(c*P[i][j][k] for k in range(2)) for j in range(2)) for i in range(2))
def joint(P, Q, half):
    """joint readers: X(P,Q) with X(P,P) = X_P, linear in each product"""
    RS, RP, RQ = three_readers(padd(P, Q)), three_readers(P), three_readers(Q)
    return tuple(tuple(half*(RS[r][t] - RP[r][t] - RQ[r][t]) for t in range(3)) for r in range(3))
def turn(Rd, half):
    A, B, C = Rd
    return ((-half*B, -C), (A, half*B))
def mv(M, v):
    return (M[0][0]*v[0] + M[0][1]*v[1], M[1][0]*v[0] + M[1][1]*v[1])
def mm(M, K):
    return tuple(tuple(M[i][0]*K[0][j] + M[i][1]*K[1][j] for j in range(2)) for i in range(2))
def madd(M, K, s=1):
    """M + s K"""
    return tuple(tuple(M[i][j] + s*K[i][j] for j in range(2)) for i in range(2))
def msub(M, K):
    """M - K"""
    return madd(M, K, -1)
def mscale(c, M):
    return tuple(tuple(c*M[i][j] for j in range(2)) for i in range(2))
def comm(M, K):
    return msub(mm(M, K), mm(K, M))
def act3(g, P):
    A, B, C = g
    def fn(s, t):
        u, v, w = mv(C, apply(P, s, t)), apply(P, mv(A, s), t), apply(P, s, mv(B, t))
        return (u[0] - v[0] - w[0], u[1] - v[1] - w[1])
    return block_from(fn)
def expand_block(P):
    return tuple(tuple(tuple(sp.expand(t) for t in P[i][j]) for j in range(2)) for i in range(2))
def expand_mat(M):
    return tuple(tuple(sp.expand(t) for t in row) for row in M)
H = sp.Rational(1, 2)
def bracket_odd(P, Q, w, half=H):
    X, Y, Z = joint(P, Q, half)
    return (mscale(w[0], turn(X, half)), mscale(w[1], turn(Y, half)), mscale(w[2], turn(Z, half)))

random.seed(14)
def rblock(lo=-3, hi=3):
    return tuple(tuple(tuple(random.randint(lo, hi) for _ in range(2)) for _ in range(2)) for _ in range(2))
def rsl(lo=-3, hi=3):
    p, q, r = (random.randint(lo, hi) for _ in range(3))
    return ((p, q), (r, -p))

a8 = sp.symbols('a0:8')
Pg = tuple(tuple(tuple(a8[4*i + 2*j + k] for k in range(2)) for j in range(2)) for i in range(2))
Xg, Yg, Zg = three_readers(Pg)
SX, SY, SZ = turn(Xg, H), turn(Yg, H), turn(Zg, H)
wa, wb, wc = sp.symbols('a b c')

# ================================================================ section 2
m11, m12, m21 = sp.symbols('m11 m12 m21'); n11, n12, n21 = sp.symbols('n11 n12 n21')
k11, k12, k21 = sp.symbols('k11 k12 k21')
gA, gB, gC = ((m11, m12), (m21, -m11)), ((n11, n12), (n21, -n11)), ((k11, k12), (k21, -k11))
r9 = sp.symbols('r1:10')
g1 = (gA, gB, gC)
g2 = (((r9[0], r9[1]), (r9[2], -r9[0])), ((r9[3], r9[4]), (r9[5], -r9[3])), ((r9[6], r9[7]), (r9[8], -r9[6])))
lhs = act3(tuple(comm(g1[s], g2[s]) for s in range(3)), Pg)
rhs = padd(act3(g1, act3(g2, Pg)), act3(g2, act3(g1, Pg)), -1)
check("Lemma 2.2: the three places act on products, and the action respects commutators",
      expand_block(lhs) == expand_block(rhs))
# the cube: p_ijk = k-th number of P(e_i, e_j); faces across each direction
xr, yr = sp.symbols('x y')
def rd(R): return R[0]*xr**2 + R[1]*xr*yr + R[2]*yr**2
Fi = lambda i: sp.Matrix(2, 2, lambda j, k: Pg[i][j][k])
Gj = lambda j: sp.Matrix(2, 2, lambda i, k: Pg[i][j][k])
Hk = lambda k: sp.Matrix(2, 2, lambda i, j: Pg[i][j][k])
check("Section 2 (cube): X(psi) = det(x F1 + y F2), Y(chi) = det(x G1 + y G2), Z(omega) = -det(x H2 - y H1)",
      sp.expand(rd(Xg) - (xr*Fi(0) + yr*Fi(1)).det()) == 0
      and sp.expand(rd(Yg) - (xr*Gj(0) + yr*Gj(1)).det()) == 0
      and sp.expand(rd(Zg) + (xr*Hk(1) - yr*Hk(0)).det()) == 0, "eight free numbers")

# ================================================================ section 3
J2 = joint(Pg, Pg, H)
check("Definition 3.1: the joint readers of a product with itself are its three readers",
      tuple(tuple(sp.expand(t) for t in r) for r in J2) == tuple(tuple(sp.expand(t) for t in r) for r in (Xg, Yg, Zg)))
g = (gA, gB, gC)
Jg = joint(act3(g, Pg), Pg, H)
ok = True
for place, (S0, G0) in enumerate(((SX, gA), (SY, gB), (SZ, gC))):
    ok &= expand_mat(mscale(2, turn(Jg[place], H))) == expand_mat(comm(G0, S0))
check("Lemma 3.2: each reader moves with its own place only", ok, "eight free numbers, nine free rates")
ok = True
for _ in range(6):
    P, Q = rblock(), rblock(); gg = (rsl(), rsl(), rsl())
    J1, J2_, J0 = joint(act3(gg, P), Q, H), joint(P, act3(gg, Q), H), joint(P, Q, H)
    for place in range(3):
        l = madd(turn(J1[place], H), turn(J2_[place], H))
        ok &= expand_mat(l) == expand_mat(comm(gg[place], turn(J0[place], H)))
check("Lemma 3.2: the same for two different products", ok)

# ================================================================ section 4
br = bracket_odd(Pg, Pg, (wa, wb, wc))
tri = act3(br, Pg)
common = block_from(lambda s, t: mv(SZ, apply(Pg, s, t)))
check("Theorem 4.1: [[P,P],P] = (c - a - b) S_Z P, for every product",
      expand_block(tri) == expand_block(pscale(wc - wa - wb, common)), "eight free numbers")
ok = True; nonzero = True
for _ in range(6):
    x, y, z = rblock(), rblock(), rblock()
    tot = padd(padd(act3(bracket_odd(x, y, (wa, wb, wc)), z), act3(bracket_odd(y, z, (wa, wb, wc)), x)),
               act3(bracket_odd(z, x, (wa, wb, wc)), y))
    vals = [sp.expand(t) for i in range(2) for j in range(2) for t in tot[i][j]]
    ok &= all(sp.expand(v.subs(wc, wa + wb)) == 0 for v in vals)
    nz = [v for v in vals if v != 0]
    nonzero &= len(nz) > 0 and all(sp.simplify(v/(wc - wa - wb)).free_symbols == set() for v in nz)
check("Theorem 4.1: the identity for three different products holds exactly when c = a + b", ok and nonzero)
ok = True
for _ in range(6):
    x, y = rblock(), rblock(); gg = (rsl(), rsl(), rsl())
    b0 = bracket_odd(x, y, (wa, wb, wc))
    b1 = bracket_odd(act3(gg, x), y, (wa, wb, wc)); b2 = bracket_odd(x, act3(gg, y), (wa, wb, wc))
    for place in range(3):
        ok &= expand_mat(madd(b1[place], b2[place])) == expand_mat(comm(gg[place], b0[place]))
check("Theorem 4.1: one change of view and two products, for all weights", ok)

Pturn = block_from(lambda s, t: (s[0]*t[0] - s[1]*t[1], s[0]*t[1] + s[1]*t[0]))
Jm = ((0, -1), (1, 0)); Zm = ((0, 0), (0, 0))
gP, hP = act3((Jm, Zm, Zm), Pturn), act3((Zm, Jm, Zm), Pturn)
bj = bracket_odd(gP, hP, (1, 1, 2))
check("Corollary 4.3: two places commute, and are joined through a product",
      all(tuple(comm(x_, y_) for x_, y_ in zip((rsl(), Zm, Zm), (Zm, rsl(), Zm))) == (Zm, Zm, Zm) for _ in range(5))
      and bj == (Jm, Jm, mscale(2, Jm)), str(bj))

# ================================================================ section 5
nform = sp.expand(Xg[0]*Xg[2] - H*H*Xg[1]**2)
ok = True
for S0 in (SX, SY, SZ):
    ok &= expand_mat(mm(S0, S0)) == ((-nform, 0), (0, -nform))
check("Proposition 5.1: each part of [P,P] squares to minus the even form", ok)
tpar = sp.symbols('t')
Pt = padd(Pg, pscale(tpar, act3(g, Pg)))
Xt = three_readers(Pt)[0]
nt = sp.expand(Xt[0]*Xt[2] - H*H*Xt[1]**2)
check("Proposition 5.1: the even form of a product does not change under the three places",
      sp.expand(sp.diff(nt, tpar).subs(tpar, 0)) == 0)
ok = True
for c_ in (-1, 0, 1):
    P = block_from(lambda s, t: (s[0]*t[0] + c_*s[1]*t[1], s[0]*t[1] + s[1]*t[0]))
    ok &= three_readers(P) == ((1, 0, -c_),)*3
    b = bracket_odd(P, P, (1, 1, 2))
    ok &= b[0] == b[1] == ((0, c_), (1, 0)) and b[2] == ((0, 2*c_), (2, 0))
check("Example 5.2: the three products of Paper 6 are the three kinds: even form 1, 0, -1", ok)

# ================================================================ section 6: pairs of products
def frb(P): return tuple(tuple(tuple(Fr(t) for t in P[i][j]) for j in range(2)) for i in range(2))
def frm(M): return tuple(tuple(Fr(t) for t in row) for row in M)
ZB = frb(block_from(lambda s, t: (0, 0))); ZM = ((Fr(0), Fr(0)), (Fr(0), Fr(0)))
def area(u, v): return u[0]*v[1] - u[1]*v[0]
def omega(P, Q):
    """the area of two products"""
    return (area(P[0][0], Q[1][1]) - area(P[0][1], Q[1][0]) - area(P[1][0], Q[0][1]) + area(P[1][1], Q[0][0]))
HF = Fr(1, 2)
def big_bracket(u, v, w=(1, 1, 1, 1)):
    """elements u = (A, B, C, D, P, Q): four changes of view and a pair of products"""
    A, B, C, D, P, Q = u; A1, B1, C1, D1, P1, Q1 = v
    out_even = [comm(A, A1), comm(B, B1), comm(C, C1), comm(D, D1)]
    # even on odd
    def ev(gABC, Dm, P_, Q_):
        gp, gq = act3(gABC, P_), act3(gABC, Q_)
        return (padd(padd(gp, pscale(Dm[0][0], P_)), pscale(Dm[0][1], Q_)),
                padd(padd(gq, pscale(Dm[1][0], P_)), pscale(Dm[1][1], Q_)))
    p1, q1 = ev((A, B, C), D, P1, Q1)
    p2, q2 = ev((A1, B1, C1), D1, P, Q)
    out_P, out_Q = padd(p1, p2, -1), padd(q1, q2, -1)
    # odd with odd
    J1, J2_ = joint(P, Q1, HF), joint(Q, P1, HF)
    sgn = (-1, -1, 1)
    for place in range(3):
        T = msub(turn(J1[place], HF), turn(J2_[place], HF))
        out_even[place] = madd(out_even[place], mscale(w[place]*sgn[place], T))   # adds: -T, -T, +T
    s = omega(P, Q1) + omega(Q, P1)
    D2 = ((-s, 2*omega(P, P1)), (-2*omega(Q, Q1), s))
    out_even[3] = madd(out_even[3], mscale(w[3]*Fr(1, 4), D2))               # adds
    return (out_even[0], out_even[1], out_even[2], out_even[3], out_P, out_Q)
def badd(u, v, s=1):
    return tuple(madd(u[t], v[t], s) for t in range(4)) + (padd(u[4], v[4], s), padd(u[5], v[5], s))
def is_zero(u):
    return all(t == 0 for M in u[:4] for row in M for t in row) and \
           all(t == 0 for P in u[4:] for i in range(2) for j in range(2) for t in P[i][j])
def relem():
    return (frm(rsl()), frm(rsl()), frm(rsl()), frm(rsl()), frb(rblock()), frb(rblock()))
ok = True
for _ in range(40):
    u, v, w_ = relem(), relem(), relem()
    jac = badd(badd(big_bracket(big_bracket(u, v), w_), big_bracket(big_bracket(v, w_), u)),
               big_bracket(big_bracket(w_, u), v))
    ok &= is_zero(jac)
    ok &= is_zero(badd(big_bracket(u, v), big_bracket(v, u)))
check("Theorem 6.2: four places and the pairs of products form a Lie algebra", ok, "40 triples, exact")
# the four weights are forced equal
w4 = sp.symbols('w1:5')
eqs = []
for _ in range(30):
    u = (ZM, ZM, ZM, ZM, frb(rblock()), frb(rblock())); v = (ZM, ZM, ZM, ZM, frb(rblock()), frb(rblock()))
    z = (ZM, ZM, ZM, ZM, frb(rblock()), frb(rblock()))
    jac = badd(badd(big_bracket(big_bracket(u, v, w4), z, w4), big_bracket(big_bracket(v, z, w4), u, w4)),
               big_bracket(big_bracket(z, u, w4), v, w4))
    eqs += [sp.expand(t) for P in jac[4:] for i in range(2) for j in range(2) for t in P[i][j]]
sol = sp.solve([e for e in eqs if e != 0], w4, dict=True)
check("Theorem 6.2: the four weights are forced to be equal",
      len(sol) == 1 and all(sp.simplify(sol[0][w4[t]] - w4[3]) == 0 for t in range(3)), str(sol))
# basis, Killing form, signature
SLB = [((0, 1), (0, 0)), ((0, 0), (1, 0)), ((1, 0), (0, -1))]
basis = []
for place in range(4):
    for M in SLB:
        ev = [ZM, ZM, ZM, ZM]; ev[place] = frm(M); basis.append(tuple(ev) + (ZB, ZB))
for which in range(2):
    for i, j, k in iproduct(range(2), repeat=3):
        Pb = [[[Fr(0), Fr(0)] for _ in range(2)] for _ in range(2)]; Pb[i][j][k] = Fr(1)
        Pb = frb(Pb)
        basis.append((ZM, ZM, ZM, ZM) + ((Pb, ZB) if which == 0 else (ZB, Pb)))
def coords(u):
    c = []
    for M in u[:4]: c += [M[0][1], M[1][0], M[0][0]]
    for P in u[4:]: c += [P[i][j][k] for i in range(2) for j in range(2) for k in range(2)]
    return c
dim = len(basis)
ad = [[coords(big_bracket(basis[i], basis[j])) for j in range(dim)] for i in range(dim)]  # ad[i][j] = [e_i,e_j]
def kill(i, j):
    # trace of ad_i ad_j: sum_k ( [e_i,[e_j,e_k]] )_k
    tot = Fr(0)
    for k in range(dim):
        v = ad[j][k]
        for l in range(dim):
            if v[l]: tot += v[l]*ad[i][l][k]
    return tot
K = [[kill(i, j) for j in range(dim)] for i in range(dim)]
def signature(Kin):
    Kc = [row[:] for row in Kin]; n = len(Kc); pos = neg = 0; used = [False]*n
    for _ in range(n):
        piv = next((i for i in range(n) if not used[i] and Kc[i][i] != 0), None)
        if piv is None:
            pr = next(((i, j) for i in range(n) for j in range(n)
                       if not used[i] and not used[j] and i != j and Kc[i][j] != 0), None)
            if pr is None: break
            i, j = pr
            for t in range(n): Kc[i][t] += Kc[j][t]
            for t in range(n): Kc[t][i] += Kc[t][j]
            piv = i
        d = Kc[piv][piv]; used[piv] = True
        pos += d > 0; neg += d < 0
        for i in range(n):
            if used[i] or Kc[i][piv] == 0: continue
            f = Kc[i][piv]/d
            for t in range(n): Kc[i][t] -= f*Kc[piv][t]
            for t in range(n): Kc[t][i] -= f*Kc[t][piv]
    return pos, neg
# the bracket is linear in each entry, so the identity of three elements is checked on the basis:
# ad[e_i, e_j] = [ad e_i, ad e_j] for every pair
def adm(v):   # matrix of ad_v from coordinates v
    return [[sum(v[i]*ad[i][k][l] for i in range(dim) if v[i]) for k in range(dim)] for l in range(dim)]
ADM = [[[ad[i][k][l] for k in range(dim)] for l in range(dim)] for i in range(dim)]   # ADM[i][l][k]
def matmul(M, N_):
    cols = list(zip(*N_))
    return [[sum(x*y for x, y in zip(row, col) if x and y) for col in cols] for row in M]
okJ = True
for i in range(dim):
    for j in range(i, dim):
        okJ &= ad[i][j] == [-t for t in ad[j][i]]
        left = adm(ad[i][j])
        MN, NM = matmul(ADM[i], ADM[j]), matmul(ADM[j], ADM[i])
        okJ &= all(left[r][c] == MN[r][c] - NM[r][c] for r in range(dim) for c in range(dim))
check("Theorem 6.2: the identity of three elements on every pair of the 28 basis elements", okJ, "406 pairs, exact")
pos, neg = signature(K)
check("Theorem 6.2: dimension 28; the trace form is not degenerate, with signature (16,12)",
      dim == 28 and (pos, neg) == (16, 12), "dimension %d, signature (%d,%d)" % (dim, pos, neg))
ok = True
for _ in range(10):
    P = frb(rblock())
    X, Y, Z = three_readers(P)
    b = big_bracket((ZM, ZM, ZM, ZM, P, ZB), (ZM, ZM, ZM, ZM, ZB, P))
    ok &= b[0] == mscale(-1, turn(X, HF)) and b[1] == mscale(-1, turn(Y, HF)) and b[2] == turn(Z, HF)
    ok &= b[3] == ZM and is_zero(big_bracket((ZM, ZM, ZM, ZM, P, ZB), (ZM, ZM, ZM, ZM, P, ZB)))
    ok &= omega(P, P) == 0
check("Corollary 6.3: [(P,0),(0,P)] is the three own turns of P, and nothing in the fourth place", ok)
Pt = frb(block_from(lambda s, t: (s[0]*t[0] - s[1]*t[1], s[0]*t[1] + s[1]*t[0])))   # complex multiplication
Jf = frm(((0, -1), (1, 0)))
bt = big_bracket((ZM, ZM, ZM, ZM, Pt, ZB), (ZM, ZM, ZM, ZM, ZB, Pt))
check("Corollary 6.3, sign certificate: for the turn product [(P,0),(0,P)] = (-J, -J, J, 0)",
      bt[:4] == (mscale(-1, Jf), mscale(-1, Jf), Jf, ZM), str(tuple(tuple(tuple(int(t) for t in r) for r in M) for M in bt[:4])))
# the fourth place is the pairing of Paper 5: pairs P(x)u
ok = True
for _ in range(10):
    P, Q = frb(rblock()), frb(rblock()); u = (Fr(random.randint(-3, 3)), Fr(random.randint(-3, 3)))
    v = (Fr(random.randint(-3, 3)), Fr(random.randint(-3, 3)))
    b = big_bracket((ZM, ZM, ZM, ZM, pscale(u[0], P), pscale(u[1], P)), (ZM, ZM, ZM, ZM, pscale(v[0], Q), pscale(v[1], Q)))
    Jn = joint(P, Q, HF); ar = area(u, v)
    ok &= b[0] == mscale(-ar, turn(Jn[0], HF)) and b[1] == mscale(-ar, turn(Jn[1], HF)) and b[2] == mscale(ar, turn(Jn[2], HF))
    # beta(u,v) = (t;a,u) with Gamma = [[u0 v0 *2 ...]]: reader [2 u0 v0, 2(u0 v1 + u1 v0), 2 u1 v1]
    beta_reader = (2*u[0]*v[0], 2*(u[0]*v[1] + u[1]*v[0]), 2*u[1]*v[1])
    Sb = turn(beta_reader, HF)
    SbT = ((Sb[0][0], Sb[1][0]), (Sb[0][1], Sb[1][1]))
    ok &= b[3] == mscale(Fr(1, 4)*omega(P, Q), SbT)
check("Proposition 6.4: for pairs P(x)u the bracket is area(u,v) x joint readers + area(P,Q) x pairing of u,v", ok)

# ================================================================ section 7
okg = True; diag = []
for place in range(4):
    hi = 3*place + 2                     # the diagonal element of this place
    assert basis[hi][place] == frm(((1, 0), (0, -1)))
    vals = {}; d_ = []
    for j in range(dim):
        cj = ad[hi][j]
        assert all(cj[k] == 0 for k in range(dim) if k != j)
        vals[cj[j]] = vals.get(cj[j], 0) + 1; d_.append(cj[j])
    diag.append(d_)
    okg &= vals == {Fr(2): 1, Fr(-2): 1, Fr(1): 8, Fr(-1): 8, Fr(0): 10}
check("Theorem 7.1: each place grades the algebra in degrees -2..2 with counts 1, 8, 10, 8, 1", okg)
central = [j for j in range(dim) if all(diag[p][j] == 0 for p in range(4))]
check("Theorem 7.1: the four diagonal elements commute, and only they commute with all four",
      central == [2, 5, 8, 11], str(central))
check("Remark 7.2: the trace form is 24 = 4t on the diagonal element of each place, and 12 on (e,f)",
      all(K[3*p + 2][3*p + 2] == 24 and K[3*p][3*p + 1] == 12 for p in range(4)))
Z0s = block_from(lambda s, t: (0, 0)); ZMs = ((0, 0), (0, 0))
HF = sp.Rational(1, 2)
xs = (ZMs, ZMs, ZMs, ZMs, Pg, Z0s)
vv4 = (ZMs, ZMs, ZMs, ((0, 0), (1, 0)), Z0s, Z0s)
EM = lambda M: tuple(tuple(sp.expand(t) for t in r) for r in M)
oks = True
for step in range(1, 5):
    vv4 = big_bracket(xs, vv4)
    if step == 1:    # (0, -P)
        oks &= all(EM(M) == ZMs for M in vv4[:4]) and expand_block(vv4[4]) == expand_block(Z0s) \
               and expand_block(vv4[5]) == expand_block(pscale(-1, Pg))
    if step == 2:    # (S_X, S_Y, -S_Z, 0)
        oks &= EM(vv4[0]) == EM(SX) and EM(vv4[1]) == EM(SY) and EM(vv4[2]) == EM(mscale(-1, SZ)) \
               and EM(vv4[3]) == ZMs \
               and all(expand_block(B) == expand_block(Z0s) for B in vv4[4:])
    if step == 3:    # (3 S_Z P, 0)
        oks &= all(EM(M) == ZMs for M in vv4[:4]) and expand_block(vv4[5]) == expand_block(Z0s) \
               and expand_block(vv4[4]) == expand_block(pscale(3, common))
check("Proposition 7.3: the four steps pass through (0,-P), (S_X,S_Y,-S_Z,0) and (3 S_Z P,0)", oks,
      "eight free numbers")
okf = all(sp.expand(t) == 0 for M in vv4[:3] for r in M for t in r)
okf &= all(sp.expand(t) == 0 for B in vv4[4:] for i in range(2) for j in range(2) for t in B[i][j])
okf &= sp.expand(vv4[3][0][0]) == 0 and sp.expand(vv4[3][1][0]) == 0
okf &= sp.expand(vv4[3][0][1] + 6*nform) == 0
HF = Fr(1, 2)
check("Proposition 7.3: four steps with a product carry f to -6 n(P) e", okf, "eight free numbers")
t_ = 6
check("Section 7: the count of UBR at t = 6: n = 2t - 4 = 8, 12 + 16 = 28",
      2*t_ - 4 == 8 and 4*t_ - 8 == 16 and 3 + 9 == 12 and 12 + 16 == dim)

print("\n%d checks; %s" % (len(CHECKS), "all pass" if all(CHECKS) else "FAILURES"))
