#!/usr/bin/env python3
"""Verification script for Paper 15, "A Root in Each Place".

Exact arithmetic throughout (sympy rationals and Fractions). Each check prints one line
named after the statement it checks.

A triple root is six numbers (psi_1, psi_2, psi_3), one root for each place.
A threefold is an alternating rule x(t,t',t'') on triple roots, kept as its 20 values
x(e_i,e_j,e_k), i<j<k. A product of roots is kept as P[i][j] = P(e_i,e_j) (Paper 13).
"""
from fractions import Fraction as Fr
import itertools as it
import sympy as sp

COMB = list(it.combinations(range(6), 3))            # 20 index triples i<j<k
CIDX = {c: n for n, c in enumerate(COMB)}
E = ((0, 1), (-1, 0))
def area(u, v): return u[0]*v[1] - u[1]*v[0]
def OmegaM():
    M = [[0]*6 for _ in range(6)]
    for p in range(3):
        M[2*p][2*p+1] = 1; M[2*p+1][2*p] = -1
    return M
OM = OmegaM()
def sgn_sort(t):
    """sort an index triple, return (sign, sorted) or (0, None) if an index repeats"""
    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
    if t[0] == t[1] or t[1] == t[2]: return 0, None
    return s, tuple(t)
def comp(x, i, j, k):
    """value x(e_i, e_j, e_k) of a threefold kept as 20 numbers"""
    s, t = sgn_sort((i, j, k))
    return 0 if s == 0 else s*x[CIDX[t]]
def unit(i):
    return tuple(1 if a == i else 0 for a in range(6))
def from_parts(P, s1, s2, s3):
    """the threefold of a product of roots and a root in each place.
    P[i][j] = P(e_i, e_j); p(a,b,c) = [P(a,b), c]."""
    x = [0]*20
    for n, (i, j, k) in enumerate(COMB):
        v = 0
        # product part: one index in each place
        if i < 2 and 2 <= j < 4 and k >= 4:
            v += area(P[i][j-2], unit(k)[4:6])
        # root parts
        def root_term(a, b, c):   # value of sum over the three turns, on basis roots a<b<c
            tot = 0
            for (u, w, r) in ((a, b, c), (b, c, a), (c, a, b)):
                ar = [OM[u][w] if u//2 == w//2 == p else 0 for p in range(3)]
                eu = unit(r)
                tot += (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])
            return tot
        v += root_term(i, j, k)
        x[n] = v
    return x
def rho(A):
    """20x20 matrix of the action (A.x)(t,t',t'') = -x(At,t',t'') - x(t,At',t'') - x(t,t',At'')"""
    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)):
                c = A[a][old]
                if c == 0: continue
                idx = [i, j, k]; idx[pos] = a
                s, t = sgn_sort(idx)
                if s: R[n][CIDX[t]] -= s*c
    return R
def trace_of(x):
    """(tr x)(e_c) = sum over places of x(e_{p,1}, e_{p,2}, e_c)"""
    return [sum(comp(x, 2*p, 2*p+1, c) for p in range(3)) for c in range(6)]
def sp6_basis():
    """the 21 matrices A with [[At,t']] + [[t,At']] = 0: A = Om^{-1} S, S symmetric"""
    W = [[-OM[i][j] for j in range(6)] for i in range(6)]      # inverse of Om
    out = []
    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
            out.append([[sum(W[a][b]*S[b][c] for b in range(6)) for c in range(6)] for a in range(6)])
    return out

names = ['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']
SY = sp.symbols(names)
def parts(v):
    P = tuple(tuple((v[4*i + 2*j], v[4*i + 2*j + 1]) for j in range(2)) for i in range(2))
    return P, (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
B6 = [sp.Matrix(A) for A in sp6_basis()]                       # 21 matrices
R14 = [DEC*sp.Matrix(rho([list(r) for r in A.tolist()]))*EMB for A in B6]
W = [[-OM[i][j] for j in range(6)] for i in range(6)]
def omega20():
    M = sp.zeros(20, 20)
    for n, (i, j, k) in enumerate(COMB):
        for m, (l, mm, nn) in enumerate(COMB):
            tot = 0
            for perm, 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)):
                tot += s*W[i][perm[0]]*W[j][perm[1]]*W[k][perm[2]]
            M[n, m] = tot
    return M
AREA14 = -(EMB.T*omega20()*EMB)        # <x,y> = <P,Q> + 2 sum [psi_i, phi_i]
GRAM = sp.Matrix(21, 21, lambda a, b: (B6[a]*B6[b]).trace())
GI = GRAM.inv()
# mu(e_i, e_j) as a 21-vector: tr(mu(x,y) A) = kappa <A.x, y>, kappa fixed below
KAPPA = sp.Rational(-1, 2)
NA = [(R14[a].T*AREA14) for a in range(21)]                    # <A_a x, y> = x^T NA[a] y
MUC = [[GI*sp.Matrix([KAPPA*(NA[a][i, j] + NA[a][j, i])/2 for a in range(21)]) for j in range(14)] for i in range(14)]
def mu_matrix(xv, yv):
    """mu(x,y) as a 6x6 matrix, for coordinate vectors (lists) xv, yv"""
    M = sp.zeros(6, 6)
    for i in range(14):
        if xv[i] == 0: continue
        for j in range(14):
            if yv[j] == 0: continue
            cf = xv[i]*yv[j]
            for a in range(21):
                if MUC[i][j][a] != 0: M += cf*MUC[i][j][a]*B6[a]
    return M

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

def detquad(m, n):
    a = m[0][0]*m[1][1] - m[0][1]*m[1][0]; cc = 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, cc)
def 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, cc = detquad(m, n)
    return X, Y, (-a, -b, -cc)
Jm = sp.Matrix([[0, -1], [1, 0]]); Em = sp.Matrix(E); Hq = sp.Rational(1, 2)
def gam(Rd): return sp.Matrix([[Rd[0], Hq*Rd[1]], [Hq*Rd[1], Rd[2]]])
def rd(Rd, v): return Rd[0]*v[0]**2 + Rd[1]*v[0]*v[1] + Rd[2]*v[1]**2
def sqarea(v):                       # Gamma of the reader  alpha -> [v, alpha]^2
    w = Jm*sp.Matrix(v); return w*w.T
def Pap(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))
zero = sp.zeros
ar = area
P, s1, s2, s3 = parts(SY); S3 = [s1, s2, s3]
X, Y, Z = readers(P)
nP = sp.expand(X[0]*X[2] - Hq*Hq*X[1]**2)
xs = list(SY)

# ---------------------------------------------------------------- section 2
ok = all((OMs*A + A.T*OMs) == zero(6, 6) for A in B6) if (OMs := sp.Matrix(OM)) is not None else False
check("Definition 2.2: 21 changes of view of a triple root keep the summed area", ok and len(B6) == 21
      and sp.Matrix([list(A) for A in B6]).rank() == 21)
# blocks: A_ji = E A_ij^T E
bsym = sp.Matrix(2, 2, sp.symbols('b11 b12 b21 b22'))
def box_matrix(r, c, b):
    A = sp.zeros(6, 6); A[2*r:2*r+2, 2*c:2*c+2] = b; A[2*c:2*c+2, 2*r:2*r+2] = Em*b.T*Em
    return A
check("Definition 2.2: a box b between two places comes with E b^T E the other way",
      all((OMs*box_matrix(r, c, bsym) + box_matrix(r, c, bsym).T*OMs) == zero(6, 6) for r, c in ((0, 1), (0, 2), (1, 2))))
csym = sp.Matrix(2, 2, sp.symbols('c11 c12 c21 c22'))
C1 = box_matrix(0, 1, bsym)*box_matrix(1, 2, csym) - box_matrix(1, 2, csym)*box_matrix(0, 1, bsym)
C2 = box_matrix(0, 1, bsym)*box_matrix(0, 1, csym) - box_matrix(0, 1, csym)*box_matrix(0, 1, bsym)
blk6 = lambda M, a, b: M[2*a:2*a+2, 2*b:2*b+2]
check("Definition 2.2: two boxes with one place in common make a box between the other two; two boxes of the same places stay in those places",
      (blk6(C1, 0, 2) - bsym*csym).applyfunc(sp.expand) == sp.zeros(2, 2)
      and all(blk6(C1, a, b).applyfunc(sp.expand) == sp.zeros(2, 2) for a, b in ((0, 0), (1, 1), (2, 2), (0, 1), (1, 2)))
      and all(blk6(C2, a, b).applyfunc(sp.expand) == sp.zeros(2, 2) for a in range(3) for b in range(3) if (a, b) not in ((0, 0), (1, 1))))
def coords6(A):
    """coordinates of a 6x6 matrix of the 21 in the basis B6 (exact)"""
    S = (OMs*A)                                   # symmetric
    out = []
    for i in range(6):
        for j in range(i, 6):
            out.append(S[i, j])
    return out
assert all(coords6(B6[a]) == [1 if b == a else 0 for b in range(21)] for a in range(21))
def act6(A, xv):
    """action on a balanced threefold given by its 14 coordinates"""
    co = coords6(A); out = sp.zeros(14, 1); xm = sp.Matrix(xv)
    for a in range(21):
        if co[a] != 0: out += co[a]*(R14[a]*xm)
    return [sp.expand(t) for t in out]

# ---------------------------------------------------------------- section 3
check("Theorem 3.2: a product and a root in each place give a balanced threefold, one to one (8 + 6 = 14)",
      EMB.rank() == 14 and all(t == 0 for b in range(14) for t in trace_of(list(EMB[:, b]))))
full = sp.Matrix([[sum(comp(list(sp.eye(20)[:, n]), 2*p, 2*p+1, c) for p in range(3)) for n in range(20)] for c in range(6)])
check("Theorem 3.2: the balanced threefolds have dimension 14", 20 - full.rank() == 14)
check("Theorem 3.2: the changes of view keep the balanced threefolds",
      all((sp.Matrix(rho([list(r) for r in A.tolist()]))*EMB - EMB*R14[n]) == zero(20, 14) for n, A in enumerate(B6)))
a_ = sp.symbols('m11 m12 m21'); A2 = sp.Matrix([[a_[0], a_[1]], [a_[2], -a_[0]]])
ok = True
for place in range(3):
    A = sp.zeros(6, 6); A[2*place:2*place+2, 2*place:2*place+2] = A2
    Pn, t1, t2, t3 = parts(act6(A, xs))
    # Paper 14, Definition 2.1: C P - P(A.,.) - P(.,B.)
    def want(i, j):
        ei, ej = [(1, 0), (0, 1)][i], [(1, 0), (0, 1)][j]
        if place == 0: v = Pap(P, tuple(A2*sp.Matrix(ei)), ej); return (-v[0], -v[1])
        if place == 1: v = Pap(P, ei, tuple(A2*sp.Matrix(ej))); return (-v[0], -v[1])
        return tuple(A2*sp.Matrix(P[i][j]))
    ok &= all(sp.expand(Pn[i][j][k] - want(i, j)[k]) == 0 for i in range(2) for j in range(2) for k in range(2))
    for q_, (t_, s_) in enumerate(((t1, s1), (t2, s2), (t3, s3))):
        exp_ = A2*sp.Matrix(s_) if q_ == place else sp.Matrix(s_)*0
        ok &= all(sp.expand(t_[k] - exp_[k]) == 0 for k in range(2))
check("Proposition 3.3: a place acts on the product as in Paper 14 and on its own root as a change of view", ok)
BOXACT = {}
ok = True
for (r, c, k) in ((0, 1, 2), (0, 2, 1), (1, 2, 0)):
    Pn, t1, t2, t3 = parts(act6(box_matrix(r, c, bsym), xs)); T = [t1, t2, t3]
    # roots: place r gets b psi_c, place c gets E b^T E psi_r  (up to one sign each, found here)
    gr = [sp.Matrix(T[r]), sp.Matrix(T[c])]
    BOXACT[(r, c)] = (Pn, T)
    e1 = [sg for sg in (1, -1) if (gr[0] - sg*bsym*sp.Matrix(S3[c])).applyfunc(sp.expand) == zero(2, 1)]
    e2 = [sg for sg in (1, -1) if (gr[1] - sg*Em*bsym.T*Em*sp.Matrix(S3[r])).applyfunc(sp.expand) == zero(2, 1)]
    ok &= e1 == [-1] and e2 == [-1]              # the signs printed in the paper
    # the product comes only from the root of the third place, and that root only from the product
    third = S3[k]; others = [v_ for q_ in range(3) if q_ != k for v_ in S3[q_]]
    ok &= all(sp.diff(Pn[i][j][m], v_) == 0 for i in range(2) for j in range(2) for m in range(2)
              for v_ in list(SY[:8]) + others)
    ok &= all(sp.diff(T[k][m], v_) == 0 for m in range(2) for v_ in SY[8:])
    ok &= any(Pn[i][j][m] != 0 for i in range(2) for j in range(2) for m in range(2)) and any(t_ != 0 for t_ in T[k])
check("Proposition 3.4(a): each box carries the root of one of its places to the other, with the printed signs; and it trades the product against the third root", ok)

Pn, T = BOXACT[(0, 1)]
e1, e2 = (1, 0), (0, 1)
ok = True
for i in range(2):
    for j in range(2):
        ei, ej = (e1, e2)[i], (e1, e2)[j]
        coef = 2*ar(tuple(bsym*sp.Matrix(ej)), ei)            # 2 [b chi, psi]
        ok &= all(sp.expand(Pn[i][j][k] - coef*s3[k]) == 0 for k in range(2))
be1, be2 = tuple(bsym*sp.Matrix(e1)), tuple(bsym*sp.Matrix(e2))
w3 = [Pap(P, be1, e2)[k] - Pap(P, be2, e1)[k] for k in range(2)]
ok &= all(sp.expand(T[2][k] - w3[k]) == 0 for k in range(2))
check("Proposition 3.4(b),(c): the box of places 1, 2 turns the third root into a product and the product into a third root", ok)

# ---------------------------------------------------------------- section 4
ysym = sp.symbols(['Q%d%d%d' % (i, j, k) for i in range(2) for j in range(2) for k in range(2)] +
                  ['r1x', 'r1y', 'r2x', 'r2y', 'r3x', 'r3y'])
Q, r1, r2, r3 = parts(ysym)
PQ = ar(P[0][0], Q[1][1]) - ar(P[0][1], Q[1][0]) - ar(P[1][0], Q[0][1]) + ar(P[1][1], Q[0][0])   # Paper 14, Def 6.1
ar14 = sp.expand((sp.Matrix(xs).T*AREA14*sp.Matrix(ysym))[0])
check("Definition 4.1: <x,y> = <P,Q> + 2 sum of the areas of the roots, place by place",
      sp.expand(ar14 - PQ - 2*(ar(s1, r1) + ar(s2, r2) + ar(s3, r3))) == 0)
check("Definition 4.1: the area of two threefolds is kept by all 21 changes of view",
      all((R.T*AREA14 + AREA14*R) == zero(14, 14) for R in R14))
MU = mu_matrix(xs, xs).applyfunc(sp.expand)
blk = lambda M, a, b: M[2*a:2*a+2, 2*b:2*b+2]
check("Definition 4.2 (consistency of the construction): tr(mu(x,x) A) = -1/2 <A.x, x> for the 21 changes of view",
      all(sp.expand((MU*B6[a]).trace() + Hq*(sp.Matrix(act6(B6[a], xs)).T*AREA14*sp.Matrix(xs))[0]) == 0 for a in range(21)))
ok = (blk(MU, 0, 0) + Jm*(gam(X) + sqarea(s1))).applyfunc(sp.expand) == zero(2, 2)
ok &= (blk(MU, 1, 1) + Jm*(gam(Y) + sqarea(s2))).applyfunc(sp.expand) == zero(2, 2)
ok &= (blk(MU, 2, 2) - Jm*(gam(Z) - sqarea(s3))).applyfunc(sp.expand) == zero(2, 2)
check("Theorem 4.3(a): each place receives the own turn of its reader with the squared area of its root", ok)
M3 = sp.Matrix(2, 2, lambda i, j: ar(P[i][j], s3))                       # [P(e_i,e_j), psi_3]
N2 = sp.Matrix(2, 2, lambda i, k: Pap(P, [(1, 0), (0, 1)][i], s2)[k])    # P(e_i, psi_2)_k
N1 = sp.Matrix(2, 2, lambda j, k: Pap(P, s1, [(1, 0), (0, 1)][j])[k])    # P(psi_1, e_j)_k
ok = (blk(MU, 0, 1) - (-sp.Matrix(s1)*sp.Matrix(s2).T*Em + Jm*M3)).applyfunc(sp.expand) == zero(2, 2)
ok &= (blk(MU, 0, 2) - (-sp.Matrix(s1)*sp.Matrix(s3).T*Em + Jm*N2*Em)).applyfunc(sp.expand) == zero(2, 2)
ok &= (blk(MU, 1, 2) - (-sp.Matrix(s2)*sp.Matrix(s3).T*Em + Jm*N1*Em)).applyfunc(sp.expand) == zero(2, 2)
check("Theorem 4.3(b): each box receives the two roots of its places and the product with the third root put in", ok)
z8 = {v: 0 for v in SY[8:]}; zP = {v: 0 for v in SY[:8]}
MUp = MU.subs(z8)
check("Corollary 4.4: with no roots there are no boxes, and the places receive (-S_X, -S_Y, S_Z) as in Paper 14",
      all(blk(MUp, a, b) == zero(2, 2) for a in range(3) for b in range(3) if a != b)
      and (blk(MUp, 0, 0) + Jm*gam(X)).applyfunc(sp.expand) == zero(2, 2)
      and (blk(MUp, 1, 1) + Jm*gam(Y)).applyfunc(sp.expand) == zero(2, 2)
      and (blk(MUp, 2, 2) - Jm*gam(Z)).applyfunc(sp.expand) == zero(2, 2))
MUr = MU.subs(zP)
check("Corollary 4.4: with no product, two roots still make a box, and a root alone gives a shear in its place",
      all((blk(MUr, a, b) + sp.Matrix(S3[a])*sp.Matrix(S3[b]).T*Em) == zero(2, 2) for a, b in ((0, 1), (0, 2), (1, 2)))
      and all(sp.expand((blk(MUr, a, a)*blk(MUr, a, a))[i, j]) == 0 for a in range(3) for i in range(2) for j in range(2)))

ex = {v: 0 for v in SY}
ex.update({SY[4*1 + 2*1 + 0]: -1, SY[8]: 1, SY[10]: 1, SY[13]: 1})     # P(e2,e2) = (-1,0); psi1 = psi2 = (1,0); psi3 = (0,1)
MUx = MU.subs(ex)
check("Corollary 4.4(c): a box can cancel with all three roots present (the example), while the other boxes do not",
      blk(MUx, 0, 1) == zero(2, 2) and blk(MUx, 0, 2) != zero(2, 2) and blk(MUx, 1, 2) != zero(2, 2))
Pw = (((-1, 2), (-2, 0)), ((-2, 1), (1, 1)))
Xw = readers(Pw)[0]
check("Question 10.2: for whole numbers 4 n(x) is whole and n(x) need not be: the example has reader [4,-1,-3], n = -49/4",
      Xw == (4, -1, -3) and sp.Rational(Xw[0]*Xw[2]) - sp.Rational(Xw[1]**2, 4) == sp.Rational(-49, 4)
      and all(sp.denom(c_) == 1 for c_ in sp.Poly(4*sp.expand(nP + rd(X, s1) + rd(Y, s2) - rd(Z, s3)
              + 2*ar(Pap(P, s1, s2), s3)), *SY).coeffs()))

# ---------------------------------------------------------------- section 5: the algebra of dimension 52
# basis: 0..2 the fourth place (e, f, h); 3..23 the 21 changes of view; 24..37 (x,0); 38..51 (0,x)
DIM = 52
def to_frac(M): return [[Fr(int(sp.numer(t)), int(sp.denom(t))) for t in row] for row in M.tolist()]
R14f = [to_frac(R) for R in R14]
AR = to_frac(AREA14)
MUCf = [[[Fr(int(sp.numer(t)), int(sp.denom(t))) for t in MUC[i][j]] for j in range(14)] for i in range(14)]
# commutators of the 21
C6 = {}
for a in range(21):
    for b in range(21):
        co = coords6(B6[a]*B6[b] - B6[b]*B6[a])
        C6[(a, b)] = {c: Fr(int(co[c])) for c in range(21) if co[c] != 0}
SL = {(0, 1): {2: Fr(1)}, (1, 0): {2: Fr(-1)}, (2, 0): {0: Fr(2)}, (0, 2): {0: Fr(-2)}, (2, 1): {1: Fr(-2)}, (1, 2): {1: Fr(2)}}
DM = [((0, 1), (0, 0)), ((0, 0), (1, 0)), ((1, 0), (0, -1))]          # e, f, h as 2x2
def bracket_basis(i, j, w1=Fr(1), w2=Fr(1)):
    out = {}
    def add(k, v):
        if v != 0: out[k] = out.get(k, 0) + v
    ti = 0 if i < 3 else 1 if i < 24 else 2
    tj = 0 if j < 3 else 1 if j < 24 else 2
    if ti == 0 and tj == 0:
        for k, v in SL.get((i, j), {}).items(): add(k, v)
    elif ti == 1 and tj == 1:
        for k, v in C6[(i - 3, j - 3)].items(): add(3 + k, v)
    elif ti == 0 and tj == 2:                 # fourth place on a pair: D.(x0,x1)
        l, c = divmod(j - 24, 14); D = DM[i]
        for l2 in range(2): add(24 + 14*l2 + c, Fr(D[l2][l]))
    elif ti == 2 and tj == 0:
        for k, v in bracket_basis(j, i, w1, w2).items(): add(k, -v)
    elif ti == 1 and tj == 2:
        l, c = divmod(j - 24, 14)
        for r in range(14): add(24 + 14*l + r, R14f[i - 3][r][c])
    elif ti == 2 and tj == 1:
        for k, v in bracket_basis(j, i, w1, w2).items(): add(k, -v)
    elif ti == 2 and tj == 2:
        l, c = divmod(i - 24, 14); l2, c2 = divmod(j - 24, 14)
        # [(x,y),(x',y')] = ( mu(x,y') - mu(y,x') ; 1/4 [[-s, 2<x,x'>],[-2<y,y'>, s]] )
        if l != l2:
            sg = 1 if l == 0 else -1
            for a in range(21): add(3 + a, w1*sg*MUCf[c][c2][a])
            s_ = AR[c][c2]                    # <x,y'> or <y,x'>
            add(2, -w2*Fr(1, 4)*s_)           # h coefficient: D = [[-s/4, .],[., s/4]]
        elif l == 0:
            add(0, w2*Fr(1, 2)*AR[c][c2])     # e coefficient: upper right 2<x,x'>/4
        else:
            add(1, -w2*Fr(1, 2)*AR[c][c2])    # f coefficient: lower left -2<y,y'>/4
    return out
def make_table(w1=Fr(1), w2=Fr(1)):
    return [[bracket_basis(i, j, w1, w2) for j in range(DIM)] for i in range(DIM)]
TAB = make_table()
def br_vec(u, v, T=None):
    T = T or TAB; out = {}
    for i, a in u.items():
        for j, b in v.items():
            for k, c in T[i][j].items():
                out[k] = out.get(k, 0) + a*b*c
    return {k: v_ for k, v_ in out.items() if v_ != 0}
def jacobi_ok(T, triples):
    for (i, j, k) in triples:
        tot = {}
        for (p, q, r) in ((i, j, k), (j, k, i), (k, i, j)):
            for m, c in br_vec(T[p][q], {r: Fr(1)}, T).items():
                tot[m] = tot.get(m, 0) + c
        if any(v != 0 for v in tot.values()): return False
    return True
import itertools
anti = all(TAB[i][j] == {k: -v for k, v in TAB[j][i].items()} for i in range(DIM) for j in range(DIM))
alltriples = list(itertools.combinations(range(DIM), 3))
okJ = jacobi_ok(TAB, alltriples)
check("Theorem 5.1(a): the bracket is antisymmetric and the identity of three elements holds on the whole basis",
      anti and okJ, "%d triples of the 52 basis elements, exact" % len(alltriples))
# the ratio of the two weights is forced
w1s, w2s = sp.symbols('w1 w2')
import random
random.seed(15)
odd_tr = [tuple(random.sample(range(24, 52), 3)) for _ in range(40)]
def jac_sym(i, j, k):
    T1 = lambda p, q: bracket_basis(p, q, w1s, w2s)
    tot = {}
    for (p, q, r) in ((i, j, k), (j, k, i), (k, i, j)):
        for m, c in T1(p, q).items():
            for n_, d in bracket_basis(m, r, w1s, w2s).items():
                tot[n_] = tot.get(n_, 0) + c*d
    return [sp.expand(v) for v in tot.values() if sp.expand(v) != 0]
eqs = [e for tr in odd_tr for e in jac_sym(*tr)]
sol = sp.solve(eqs, [w1s], dict=True)
check("Theorem 5.1(b): the two parts of the bracket of two pairs must have equal weights",
      len(eqs) > 0 and sol == [{w1s: w2s}], "%d equations, solution %s" % (len(eqs), sol))
# restriction to products and places is the algebra of Paper 14
prod_idx = [24 + c for c in range(8)] + [38 + c for c in range(8)]
place_idx = [0, 1, 2] + [3 + a for a in range(21) if all(B6[a][i, j] == 0 for i in range(6) for j in range(6) if i//2 != j//2)]
sub = set(prod_idx + place_idx)
check("Theorem 5.1(c): the four places and the pairs of products are closed",
      len(place_idx) == 12 and all(set(TAB[i][j]) <= sub for i in sub for j in sub))
# ... and on them the bracket is that of Paper 14, Theorem 6.2: joint readers, signs included
def joint_readers(P_, Q_):
    PS = tuple(tuple(tuple(P_[i][j][k] + Q_[i][j][k] for k in range(2)) for j in range(2)) for i in range(2))
    RS, RP, RQ = readers(PS), readers(P_), readers(Q_)
    return [tuple(Hq*(RS[r][t] - RP[r][t] - RQ[r][t]) for t in range(3)) for r in range(3)]
xP = list(SY[:8]) + [0]*6; yQ = list(ysym[:8]) + [0]*6
MPQ = mu_matrix(xP, yQ).applyfunc(sp.expand)
JR = joint_readers(P, Q)
ok = all(blk(MPQ, a, b) == zero(2, 2) for a in range(3) for b in range(3) if a != b)
ok &= (blk(MPQ, 0, 0) + Jm*gam(JR[0])).applyfunc(sp.expand) == zero(2, 2)
ok &= (blk(MPQ, 1, 1) + Jm*gam(JR[1])).applyfunc(sp.expand) == zero(2, 2)
ok &= (blk(MPQ, 2, 2) - Jm*gam(JR[2])).applyfunc(sp.expand) == zero(2, 2)
ok &= sp.expand((sp.Matrix(xP).T*AREA14*sp.Matrix(yQ))[0] - PQ) == 0
check("Theorem 5.1(c): on two products mu is (-S_X(P,Q), -S_Y(P,Q), S_Z(P,Q)) and the area is <P,Q>: the bracket of Paper 14", ok)
# deterministic weights test on the whole table
def weights_pass(w1, w2):
    T = make_table(Fr(w1), Fr(w2))
    return jacobi_ok(T, alltriples)
check("Theorem 5.1(b): on the whole table, weights (3,3) pass and (1,2), (2,1), (1,0), (0,1) fail",
      weights_pass(3, 3) and not any(weights_pass(*w_) for w_ in ((1, 2), (2, 1), (1, 0), (0, 1))))
# trace form
def kill(i, j):
    tot = Fr(0)
    for k in range(DIM):
        for l, c in TAB[j][k].items():
            tot += c*TAB[i][l].get(k, 0)
    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
pos, neg = signature(K)
check("Theorem 5.2: dimension 52; the trace form is not degenerate, with signature (28,24)",
      (pos, neg) == (28, 24), "signature (%d,%d)" % (pos, neg))
# four commuting diagonal elements: h of the fourth place and of the three places
def h_place(p):
    A = sp.zeros(6, 6); A[2*p, 2*p] = 1; A[2*p+1, 2*p+1] = -1
    co = coords6(A); return {3 + a: Fr(int(co[a])) for a in range(21) if co[a] != 0}
HS = [{2: Fr(1)}] + [h_place(p) for p in range(3)]
wts = []; diag_ok = True
for i in range(DIM):
    w_ = []
    for h in HS:
        v = br_vec(h, {i: Fr(1)})
        diag_ok &= set(v) <= {i}
        w_.append(v.get(i, Fr(0)))
    wts.append(tuple(w_))
central = [i for i in range(DIM) if all(t == 0 for t in wts[i])]
nonzero = [wts[i] for i in range(DIM) if any(wts[i])]
check("Theorem 5.2: four commuting diagonal elements; only four basis elements commute with all; 48 distinct weights",
      diag_ok and len(central) == 4 and len(set(nonzero)) == 48 == len(nonzero))
def ideal_dim(i):
    """dimension of the ideal generated by basis element i, as a linear span (exact elimination)"""
    rows = {}                                  # pivot index -> reduced vector (dict)
    def reduce(v):
        v = dict(v)
        while v:
            p = min(v)
            if p not in rows: return v
            f = v[p]/rows[p][p]
            for k_, c_ in rows[p].items():
                nv = v.get(k_, 0) - f*c_
                if nv == 0: v.pop(k_, None)
                else: v[k_] = nv
        return v
    queue = [{i: Fr(1)}]
    while queue:
        v = reduce(queue.pop())
        if not v: continue
        rows[min(v)] = v
        for b in range(DIM):
            w_ = br_vec(v, {b: Fr(1)})
            if w_: queue.append(w_)
    return len(rows)
check("Theorem 5.2: the ideal generated by each basis element, as a linear span, has dimension 52",
      all(ideal_dim(i) == DIM for i in range(DIM)))
vals = {}
for i in range(DIM): vals[wts[i][0]] = vals.get(wts[i][0], 0) + 1
check("Theorem 6.1: the fourth place grades the algebra in degrees -2..2 with counts 1, 14, 22, 14, 1",
      vals == {Fr(2): 1, Fr(-2): 1, Fr(1): 14, Fr(-1): 14, Fr(0): 22}, str({int(k): v for k, v in vals.items()}))
check("Theorem 6.1 (arithmetic only): the counts of the branching rule at t = 9: 2t - 4 = 14, 3 + 21 + 28 = 52",
      2*9 - 4 == 14 and 3 + 21 + 2*14 == DIM)
check("Remark 6.2: the trace form on the diagonal element of the fourth place is 4t = 36",
      K[2][2] == 36, str(K[2][2]))

# ---------------------------------------------------------------- sections 4 and 7: the four steps and the even form of a threefold
def sym_bracket(u, v):
    """bracket for vectors with symbolic coefficients (dicts index -> expression)"""
    out = {}
    for i, a in u.items():
        for j, b in v.items():
            for k, c in TAB[i][j].items():
                out[k] = out.get(k, 0) + a*b*sp.Rational(c.numerator, c.denominator)
    return {k: sp.expand(v_) for k, v_ in out.items() if sp.expand(v_) != 0}
xhat = {24 + c: SY[c] for c in range(14)}
v = {1: sp.Integer(1)}                         # f of the fourth place
for _ in range(4): v = sym_bracket(xhat, v)
q4 = v.get(0, 0)
t3 = ar(Pap(P, s1, s2), s3)                    # [P(psi1,psi2), psi3]
cands = [nP, rd(X, s1), rd(Y, s2), rd(Z, s3), t3]
cs = sp.symbols('k0:5')
sol = sp.solve(sp.Poly(sp.expand(q4 - sum(c*t for c, t in zip(cs, cands))), *SY).coeffs(), cs, dict=True)
print("      four steps: [x,[x,[x,[x,f]]]] = (", " + ".join("%s*%s" % (sol[0][c], nm) for c, nm in zip(cs, ["n(P)", "X(psi1)", "Y(psi2)", "Z(psi3)", "[P(psi1,psi2),psi3]"])), ") e") if sol else print("      no fit")
check("Theorem 7.1: four steps with a threefold carry f to a multiple of e, and nothing else", set(v) <= {0} and bool(sol))
nx = sp.expand(nP + rd(X, s1) + rd(Y, s2) - rd(Z, s3) + 2*t3)
check("Theorem 7.1: the multiple is -6 n(x), n(x) = n(P) + X(psi1) + Y(psi2) - Z(psi3) + 2 [P(psi1,psi2),psi3]",
      sp.expand(q4 + 6*nx) == 0)
check("Theorem 4.5: the bracket of a threefold with itself squares to minus its even form, on the triple root",
      (MU*MU + nx*sp.eye(6)).applyfunc(sp.expand) == zero(6, 6))
check("Theorem 4.5: the even form of a threefold is kept by all 21 changes of view",
      all(sp.expand(sum(sp.diff(nx, SY[i])*act6(B6[a], xs)[i] for i in range(14))) == 0 for a in range(21)))
ef = lambda G: sp.expand(G.det())
check("Question 10.1: the readers of the three places have even forms n(P)+X(psi1), n(P)+Y(psi2), n(P)-Z(psi3)",
      sp.expand(ef(gam(X) + sqarea(s1)) - nP - rd(X, s1)) == 0 and sp.expand(ef(gam(Y) + sqarea(s2)) - nP - rd(Y, s2)) == 0
      and sp.expand(ef(gam(Z) - sqarea(s3)) - nP + rd(Z, s3)) == 0)
# Conjecture 8.1: counts, and the splitting by characters for k = 1, 2
xx, yy, zz = sp.symbols('xx yy zz')
wts6 = [xx, 1/xx, yy, 1/yy, zz, 1/zz]
two = lambda t_: t_ + 1/t_
e3 = sp.expand(sum(a_*b_*c_ for a_, b_, c_ in itertools.combinations(wts6, 3)))
cube = sp.expand(two(xx)*two(yy)*two(zz)); six = sum(wts6)
# the fourteen: rates under the diagonal elements of the three places, read off the algebra
char14 = sp.expand(sum(xx**int(wts[i][1])*yy**int(wts[i][2])*zz**int(wts[i][3]) for i in range(24, 38)))
okc = sp.expand(char14 - cube - six) == 0                         # 14 = product + a root in each place
okc &= sp.expand(e3 - cube - 2*six) == 0                          # 20 = product + two roots in each place
sym2c = sp.expand(sum(a_*b_ for a_, b_ in itertools.combinations_with_replacement(wts6, 2)))
three = lambda t_: t_**2 + 1 + t_**-2
okc &= sp.expand(sym2c - three(xx) - three(yy) - three(zz) - two(xx)*two(yy) - two(xx)*two(zz) - two(yy)*two(zz)) == 0
for k_, t_, extra, g0, g in ((1, 9, 0, 21, 52), (2, 12, 2, 35, 78), (4, 18, 9, 66, 133), (8, 30, 28, 133, 248)):
    okc &= 8 + 6*k_ == 2*t_ - 4 and 9 + extra + 12*k_ == g0 and 3 + g0 + 2*(8 + 6*k_) == g
check("Conjecture 8.1: the rates of the fourteen (from the algebra) are a product plus a root in each place; 20 = 8 + 12; 21 = places + boxes; the counts for k = 1, 2, 4, 8", okc)
# self-test of the checker: a changed constant must be caught
T2 = [[dict(d) for d in row] for row in TAB]
i_, j_ = next((i, j) for i in range(24, 38) for j in range(38, 52) if TAB[i][j])
k_ = next(iter(T2[i_][j_])); T2[i_][j_][k_] += 1; T2[j_][i_][k_] -= 1
check("Self-test: the check of Theorem 5.1(a) fails when one constant is changed", not jacobi_ok(T2, alltriples))

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