#!/usr/bin/env python3
"""Verification script for Paper 13, "Readers Multiply".

Exact whole-number arithmetic throughout (the symbolic checks use sympy).
Each check prints one line named after the statement it checks.

A reader [A,B,C] reads the root (x,y) as A x^2 + B x y + C y^2; its even form
is n = A C - B^2/4, kept here as N = 4 n = 4 A C - B^2.
A product of roots is kept as eight numbers P[i][j][k]:
    P(psi,chi)_k = sum_ij P[i][j][k] psi_i chi_j .
"""
from itertools import product as iproduct
from math import gcd
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 ""))

# ---------------------------------------------------------------- basics
def read(X, psi):
    A, B, C = X; x, y = psi
    return A*x*x + B*x*y + C*y*y
def N4(X):
    A, B, C = X
    return 4*A*C - B*B
def area(psi, chi):
    return psi[0]*chi[1] - psi[1]*chi[0]
def mirror(X):
    return (X[0], -X[1], X[2])
def primitive(X):
    return gcd(gcd(abs(X[0]), abs(X[1])), abs(X[2])) == 1
def one(N):
    e = N % 2
    return (1, e, (N + e)//4)
def reduce(X):
    a, b, c = X
    while True:
        if b > a or b <= -a:
            k = (b + a - 1)//(2*a) if b > a else -((-b + a)//(2*a))
            # shear (x,y)->(x-k y,y): b -> b-2ak
            b, c = b - 2*a*k, a*k*k - b*k + c
            continue
        if a > c:
            a, b, c = c, -b, a
            continue
        if a == c and b < 0:
            b = -b
        return (a, b, c)
def reduced_readers(N):
    out = []
    a = 1
    while 3*a*a <= N:
        for b in range(-a + 1, a + 1):
            if (b*b + N) % (4*a):
                continue
            c = (b*b + N)//(4*a)
            if c < a or (a == c and b < 0):
                continue
            if gcd(gcd(a, abs(b)), c) == 1:
                out.append((a, b, c))
        a += 1
    return out
def compose_reader(X, M):
    """the reader psi -> X(M psi), M = ((m00,m01),(m10,m11))"""
    (p, q), (r, s) = M
    A, B, C = X
    return (read(X, (p, r)), 2*A*p*q + B*(p*s + q*r) + 2*C*r*s, read(X, (q, s)))
def mat_mul(M, K):
    return tuple(tuple(sum(M[i][t]*K[t][j] for t in range(2)) for j in range(2)) for i in range(2))
def mat_inv(M):
    (p, q), (r, s) = M
    d = p*s - q*r
    assert d in (1, -1)
    return ((s*d, -q*d), (-r*d, p*d))
def mat_vec(M, v):
    return (M[0][0]*v[0] + M[0][1]*v[1], M[1][0]*v[0] + M[1][1]*v[1])

# ---------------------------------------------------------------- products of roots
E2 = ((1, 0), (0, 1))
def apply(P, psi, chi):
    return tuple(sum(P[i][j][k]*psi[i]*chi[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):
    """coefficients of det(m x + n y) for 2x2 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: area factor of chi -> P(psi,chi); columns P(psi,e1), P(psi,e2)
    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])
    # product reader: zeta(w) = -det( [w, P(e_i,e_j)] ), [w,v] = p v1 - q v0
    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 pull_back(P, G, H, K=E2):
    """the product (psi,chi) -> K P(G psi, H chi)"""
    return block_from(lambda s, t: mat_vec(K, apply(P, mat_vec(G, s), mat_vec(H, t))))

def shared_middle_product(a, a2, b, c):
    return block_from(lambda s, t: (s[0]*t[0] - c*s[1]*t[1],
                                    a*s[0]*t[1] + a2*s[1]*t[0] + b*s[1]*t[1]))
def complete(r, s):
    """a whole matrix of determinant one with first column (r,s)"""
    u0, v0, r0, u1, v1, r1 = 1, 0, r, 0, 1, s
    while r1:
        k = r0//r1
        u0, v0, r0, u1, v1, r1 = u1, v1, r1, u0 - k*u1, v0 - k*v1, r0 - k*r1
    u0, v0 = u0*r0, v0*r0                     # r0 = +-1, and r u0 + s v0 = 1
    assert r*u0 + s*v0 == 1
    return ((r, -v0), (s, u0))
def multiply(X, Y):
    """Corollary 6.5: a reader Z and a whole product P with
    X(psi) Y(chi) = Z(P(psi,chi)), by changes of view and one shared-middle product."""
    assert N4(X) == N4(Y)
    a = X[0]
    H = None
    for bound in range(1, 60):
        for r, s in iproduct(range(-bound, bound + 1), repeat=2):
            if gcd(abs(r), abs(s)) == 1 and gcd(read(Y, (r, s)), a) == 1:
                H = complete(r, s); break
        if H: break
    Y1 = compose_reader(Y, H)
    a2 = Y1[0]
    # shears to a shared middle: b = X[1] mod 2a, b = Y1[1] mod 2a2
    b = next(t for t in range(X[1], X[1] + 4*a*a2 + 1, 2*a) if (t - Y1[1]) % (2*a2) == 0)
    k, l = (b - X[1])//(2*a), (b - Y1[1])//(2*a2)
    Tk, Tl = ((1, k), (0, 1)), ((1, l), (0, 1))
    Xs, Ys = compose_reader(X, Tk), compose_reader(Y1, Tl)
    assert Xs[:2] == (a, b) and Ys[:2] == (a2, b)
    assert Xs[2] % a2 == 0 and Ys[2] == a*(Xs[2]//a2)
    c = Xs[2]//a2
    Z = (a*a2, b, c)
    P = pull_back(shared_middle_product(a, a2, b, c), mat_inv(Tk), mat_inv(mat_mul(H, Tl)))
    return Z, P

BOX = list(iproduct(range(-3, 4), repeat=4))

# ================================================================ section 2
x, y, z, w, p, q = sp.symbols('x y z w p q')
A_, B_, C_ = sp.symbols('A B C')
Xs_ = A_*x**2 + B_*x*y + C_*y**2
S = sp.Matrix([[-B_/2, -C_], [A_, B_/2]])                     # J Gamma(X)
psi = sp.Matrix([x, y])
Spsi = S*psi
ok = True
for (x_, y_, z_, w_) in BOX:
    led = (x_*w_, -y_*z_)
    net, gross = sum(led), sum(abs(t) for t in led)
    hidden = x_*w_ + y_*z_                       # third entry of beta(psi,chi)
    Jpsi = (-y_, x_)                             # the quarter turn of psi
    ok &= area((x_, y_), (z_, w_)) == net == Jpsi[0]*z_ + Jpsi[1]*w_
    if x_*w_ > 0 and y_*z_ > 0:
        ok &= hidden == gross
check("Definition 2.1: the area is the determinant of the box and the net of the ledger (xw, -yz)", ok)
check("Lemma 2.2: the reading is the area of a root and its own turn",
      sp.expand(x*Spsi[1] - y*Spsi[0] - Xs_) == 0)

# ================================================================ section 3
ok = True
for e in (0, 1):
    h = (4*A_*C_ - B_**2 + e)/4
    Cx = S + sp.Rational(e, 2)*sp.eye(2)
    ok &= sp.simplify(Cx*Cx - e*Cx + h*sp.eye(2)) == sp.zeros(2)
    om = (p*sp.eye(2) + q*Cx)*psi
    ok &= sp.expand(Xs_.subs({x: om[0], y: om[1]}, simultaneous=True)
                    - (p**2 + e*p*q + h*q**2)*Xs_) == 0
check("Proposition 3.1: C^2 = eps C - h, and the reading law of the whole own numbers", ok)

FORMS = {N: reduced_readers(N) for N in
         (3, 4, 7, 8, 11, 12, 15, 16, 20, 23, 27, 28, 31, 39, 44, 47, 56, 63, 71, 84, 87, 92, 108)}
def own_product(X):
    A, B, C = X; e = B % 2
    Cx = (((e - B)//2, -C), (A, (e + B)//2))
    return block_from(lambda s, t: tuple(s[0]*t[k] + s[1]*mat_vec(Cx, t)[k] for k in range(2)))
ok = True; cnt = 0
for N, fs in FORMS.items():
    for X in fs:
        assert (X[1] - N) % 2 == 0
        P = own_product(X)
        ok &= three_readers(P) == (one(N), X, X)
        for (p_, q_, x_, y_) in BOX:
            ok &= read(X, apply(P, (p_, q_), (x_, y_))) == read(one(N), (p_, q_))*read(X, (x_, y_))
            cnt += 1
check("Theorem 3.2: the own product is whole and its three readers are one, X, X", ok,
      "%d readers, %d readings" % (sum(map(len, FORMS.values())), cnt))

# ================================================================ section 4
u = A_*x*z + B_/2*(x*w + y*z) + C_*y*w          # <X, beta(psi,chi)>
v = x*w - y*z                                   # the area of psi and chi
ok = sp.expand(u**2 + (A_*C_ - B_**2/4)*v**2 - Xs_*Xs_.subs({x: z, y: w}, simultaneous=True)) == 0
for e in (0, 1):
    h = (4*A_*C_ - B_**2 + e)/4
    U = u - sp.Rational(e, 2)*v
    ok &= sp.expand(U**2 + e*U*v + h*v**2 - Xs_*Xs_.subs({x: z, y: w}, simultaneous=True)) == 0
check("Theorem 4.1: X(psi) X(chi) = one read at (pairing - eps area/2, area)", ok)
def mirror_product(X):
    A, B, C = X; e = B % 2
    def raw(s, t):
        ar = area(s, t)
        return ((2*A*s[0]*t[0] + B*(s[0]*t[1] + s[1]*t[0]) + 2*C*s[1]*t[1] - e*ar)//2, ar)
    Mm = ((1, 0), (0, -1))
    return block_from(lambda s, t: mat_vec(Mm, raw(s, mat_vec(Mm, t))))
ok = True
for N, fs in FORMS.items():
    for X in fs:
        P = mirror_product(X)
        rX, rY, rZ = three_readers(P)
        ok &= (rX, rY) == (X, mirror(X)) and rZ == mirror(one(N)) and reduce(rZ) == one(N)
        ok &= all(isinstance(t, int) for i in range(2) for j in range(2) for t in P[i][j])
check("Theorem 4.1: the mirror product is whole; its readers are X, its mirror, and the class of one", ok)

# ================================================================ section 5
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)
om = apply(Pg, (x, y), (z, w))
lhs = sp.expand(read(Xg, (x, y))*read(Yg, (z, w)))
check("Theorem 5.2(c): left reading times right reading = product reading, for every product",
      sp.expand(read(Zg, om) - lhs) == 0, "eight free numbers")
check("Theorem 5.2(b): the three readers have one even form, for every product",
      sp.expand(N4(Xg) - N4(Yg)) == 0 and sp.expand(N4(Xg) - N4(Zg)) == 0)
ok = True
for c_ in (-1, 0, 1):   # Paper 6: (x,y)(z,w) = (xz + c yw, xw + yz); turn -1, tangent 0, ledger +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
check("Example 5.3: the three products of Paper 6 have the readers [1,0,1], [1,0,0], [1,0,-1]", ok)

# every whole product with entries up to 2
tot = inside = bad_form = bad_id = nonprim = 0
SAMPLE = [((1, 0), (0, 1)), ((1, 2), (-1, 1)), ((2, -1), (1, 3)), ((0, 1), (1, 1))]
by_form = {}
by_readers = {}
for ent in iproduct(range(-2, 3), repeat=8):
    P = tuple(tuple(tuple(ent[4*i + 2*j + k] for k in range(2)) for j in range(2)) for i in range(2))
    X, Y, Z = three_readers(P)
    tot += 1
    if not (N4(X) == N4(Y) == N4(Z)):
        bad_form += 1
    for s, t in SAMPLE:
        if read(X, s)*read(Y, t) != read(Z, apply(P, s, t)):
            bad_id += 1
    if N4(X) > 0 and X[0] > 0 and Y[0] > 0 and primitive(X) and primitive(Y):
        inside += 1
        if not (primitive(Z) and Z[0] > 0):
            nonprim += 1
        by_form.setdefault(N4(X), []).append((reduce(X), reduce(Y), reduce(Z)))
        by_readers.setdefault((X, Y), []).append((P, Z))
check("Theorem 5.2: all %d whole products with entries up to 2" % tot, bad_form == 0 and bad_id == 0)
check("Definition 7.3: the product reader is primitive and inside the cone when the other two are",
      nonprim == 0, "%d products" % inside)

Jm = sp.Matrix([[0, -1], [1, 0]])
def own_turn(Rd):
    return Jm*sp.Matrix([[Rd[0], sp.Rational(1, 2)*Rd[1]], [sp.Rational(1, 2)*Rd[1], Rd[2]]])
SX, SY, SZ = own_turn(Xg), own_turn(Yg), own_turn(Zg)
def Pvec(s, t):
    return sp.Matrix(apply(Pg, tuple(s), tuple(t)))
ps, ch = sp.Matrix([x, y]), sp.Matrix([z, w])
ok = (Pvec(SX*ps, ch) - SZ*Pvec(ps, ch)).applyfunc(sp.expand) == sp.zeros(2, 1)
ok &= (Pvec(ps, SY*ch) - SZ*Pvec(ps, ch)).applyfunc(sp.expand) == sp.zeros(2, 1)
check("Theorem 5.4: every product carries the own turns of its readers", ok, "eight free numbers")
r_, s_ = sp.symbols('r s')
lhs = Pvec((p*sp.eye(2) + q*SX)*ps, (r_*sp.eye(2) + s_*SY)*ch)
rhs = (p*sp.eye(2) + q*SZ)*(r_*sp.eye(2) + s_*SZ)*Pvec(ps, ch)
check("Corollary 5.5: every product is a product of own numbers",
      (lhs - rhs).applyfunc(sp.expand) == sp.zeros(2, 1))

# ================================================================ section 6
a_, a2_, b_, c_ = sp.symbols('a a2 b c')
U = x*z - c_*y*w; V = a_*x*w + a2_*y*z + b_*y*w
check("Theorem 6.3: the shared-middle product",
      sp.expand(a_*a2_*U**2 + b_*U*V + c_*V**2
                - (a_*x**2 + b_*x*y + a2_*c_*y**2)*(a2_*z**2 + b_*z*w + a_*c_*w**2)) == 0)
Psm = block_from(lambda s, t: (s[0]*t[0] - c_*s[1]*t[1], a_*s[0]*t[1] + a2_*s[1]*t[0] + b_*s[1]*t[1]))
check("Theorem 6.3: its three readers are [a,b,a'c], [a',b,ac], [aa',b,c]",
      tuple(tuple(sp.expand(t) for t in r) for r in three_readers(Psm))
      == ((a_, b_, a2_*c_), (a2_, b_, a_*c_), (a_*a2_, b_, c_)))
# roots as own numbers: r + s f with f^2 = -n
f = sp.symbols('f')
def red_f(expr, n):
    return sp.expand(sp.rem(sp.expand(expr), f**2 + n, f))
n_sm = a_*a2_*c_ - b_**2/4
PhiX = a_*x + (b_/2 + f)*y; PhiY = a2_*z + (b_/2 + f)*w; PhiZ = a_*a2_*U + (b_/2 + f)*V
ok = red_f(PhiX*PhiY - PhiZ, n_sm) == 0
nA = A_*C_ - B_**2/4
Phi = A_*x + (B_/2 + f)*y
size = sp.expand(Phi.subs(f, 0)**2 + nA*sp.diff(Phi, f)**2)
ok &= sp.expand(size - A_*Xs_) == 0
for e in (0, 1):
    Cx = S + sp.Rational(e, 2)*sp.eye(2)
    cp = Cx*psi
    ok &= red_f(Phi.subs({x: cp[0], y: cp[1]}, simultaneous=True) - (sp.Rational(e, 2) + f)*Phi, nA) == 0
check("Proposition 6.4: roots as own numbers; the shared-middle product is their product", ok)

ok = True; pairs = 0; ids = 0
TABLE = {}
for N, fs in FORMS.items():
    for X, Y in iproduct(fs, repeat=2):
        Z, P = multiply(X, Y)
        ok &= N4(Z) == N and primitive(Z) and three_readers(P) == (X, Y, Z)
        for (x_, y_, z_, w_) in BOX[::5]:
            ok &= read(X, (x_, y_))*read(Y, (z_, w_)) == read(Z, apply(P, (x_, y_), (z_, w_)))
            ids += 1
        TABLE[(X, Y)] = reduce(Z); pairs += 1
check("Lemmas 6.1, 6.2 and Corollary 6.5: a whole product for every pair of readers", ok,
      "%d pairs at %d even forms, %d readings" % (pairs, len(FORMS), ids))

# ================================================================ section 7
ok = True
for N, fs in FORMS.items():
    E1 = one(N)
    assert reduce(E1) in fs
    E1 = reduce(E1)
    for X in fs:
        ok &= TABLE[(X, E1)] == X and TABLE[(X, reduce(mirror(X)))] == E1
        for Y in fs:
            ok &= TABLE[(X, Y)] in fs and TABLE[(X, Y)] == TABLE[(Y, X)]
            for W in fs:
                ok &= TABLE[(TABLE[(X, Y)], W)] == TABLE[(X, TABLE[(Y, W)])]
check("Theorem 7.4: commuting, unit, mirror as inverse, and brackets may be moved", ok,
      "class counts " + ",".join(str(len(FORMS[N])) for N in FORMS))
# independence of the choices: other readers of the same classes
ok = True; trials = 0
VIEWS = [((1, 1), (0, 1)), ((0, -1), (1, 0)), ((2, 1), (1, 1)), ((1, -2), (1, -1)), ((3, 2), (1, 1))]
for N in (15, 20, 23, 31, 39, 47, 71, 84):
    fs = FORMS[N]
    for X, Y in iproduct(fs, repeat=2):
        for G, H in iproduct(VIEWS, repeat=2):
            Z, _ = multiply(compose_reader(X, G), compose_reader(Y, H))
            ok &= reduce(Z) == TABLE[(X, Y)]; trials += 1
check("Definition 7.3: the class of the product does not depend on the readers chosen", ok,
      "%d choices" % trials)
ok = True; cnt = 0; forms_seen = 0
for N, trip in by_form.items():
    if N not in FORMS:
        FORMS[N] = reduced_readers(N)
        for X, Y in iproduct(FORMS[N], repeat=2):
            TABLE[(X, Y)] = reduce(multiply(X, Y)[0])
    forms_seen += 1
    for rx, ry, rz in trip:
        ok &= TABLE[(rx, ry)] == rz; cnt += 1
check("Definition 7.3: in every whole product the product reader is in the product class", ok,
      "%d products at %d even forms" % (cnt, forms_seen))

def minors(P):
    c = [P[0][0], P[0][1], P[1][0], P[1][1]]
    return {(i + 1, j + 1): area(c[i], c[j]) for i in range(4) for j in range(i + 1, 4)}
m = minors(Pg)
ok = tuple(sp.expand(t) for t in Xg) == tuple(sp.expand(t) for t in (m[1, 2], m[1, 4] - m[2, 3], m[3, 4]))
ok &= tuple(sp.expand(t) for t in Yg) == tuple(sp.expand(t) for t in (m[1, 3], m[1, 4] + m[2, 3], m[2, 4]))
ok &= sp.expand(m[1, 2]*m[3, 4] - m[1, 3]*m[2, 4] + m[1, 4]*m[2, 3]) == 0
check("Remark 7.6: the left and right readers are the six areas; their relation is the even form", ok)
ok = True; ok71 = True; groups = 0; compared = 0
from fractions import Fraction
def frac_inv(M):
    (a0, b0), (c0, d0) = M
    d = Fraction(a0*d0 - b0*c0)
    return ((d0/d, -b0/d), (-c0/d, a0/d))
def Lmap(P):   # chi -> P(e1,chi), columns P(e1,e1), P(e1,e2)
    return ((P[0][0][0], P[0][1][0]), (P[0][0][1], P[0][1][1]))
for (X, Y), lst in by_readers.items():
    groups += 1
    for P, Z in lst:
        g = 0
        for t in minors(P).values():
            g = gcd(g, abs(t))
        ok71 &= g == 1
    P0, Z0 = lst[0]
    Li = frac_inv(Lmap(P0))
    for P1, Z1 in lst[1:]:
        K = mat_mul(Lmap(P1), Li)
        whole = all(t.denominator == 1 for row in K for t in row)
        K = tuple(tuple(int(t) for t in row) for row in K)
        ok &= whole and K[0][0]*K[1][1] - K[0][1]*K[1][0] == 1
        ok &= pull_back(P0, E2, E2, K) == P1 and compose_reader(Z1, K) == Z0
        if Z1 == Z0 and N4(Z0) not in (3, 4):
            ok &= K in (((1, 0), (0, 1)), ((-1, 0), (0, -1)))
        compared += 1
check("Lemma 7.1: the six areas of a whole product with primitive readers have no common factor", ok71)
check("Theorem 7.2: whole products with the same left and right readers differ by a whole change of view",
      ok, "%d pairs of readers, %d comparisons" % (groups, compared))
ok = True; trip = 0
for N in (23, 39, 47, 71, 84):
    for X, Y, W in iproduct(FORMS[N], repeat=3):
        U, P1 = multiply(X, Y); V, P2 = multiply(U, W)
        U1, P3 = multiply(Y, W); V1, P4 = multiply(X, U1)
        e1 = (1, 0)
        A = tuple(zip(*[apply(P2, apply(P1, e1, e1), t) for t in E2]))
        A1 = tuple(zip(*[apply(P4, e1, apply(P3, e1, t)) for t in E2]))
        K = mat_mul(A1, frac_inv(A))
        whole = all(t.denominator == 1 for row in K for t in row)
        K = tuple(tuple(int(t) for t in row) for row in K)
        ok &= whole and K[0][0]*K[1][1] - K[0][1]*K[1][0] == 1 and compose_reader(V1, K) == V
        for s3 in [((1, 2), (-1, 1), (2, 1)), ((0, 1), (3, -1), (1, 1))]:
            ok &= mat_vec(K, apply(P2, apply(P1, s3[0], s3[1]), s3[2])) == apply(P4, s3[0], apply(P3, s3[1], s3[2]))
        trip += 1
check("Theorem 7.4(d): the two bracketings differ by a whole change of view", ok, "%d triples" % trip)
Prev = block_from(lambda s, t: (-2*s[0]*t[0] - s[1]*t[0] + 3*s[1]*t[1], s[0]*t[1] + s[1]*t[0]))
okr = three_readers(Prev) == ((-2, -1, -3), (-2, 1, -3), (1, 1, 6))
Pa_ = block_from(lambda s, t: (2*s[0]*t[0] - s[0]*t[1] - 3*s[1]*t[1], s[0]*t[1] + s[1]*t[0]))
Kneg = ((-1, -1), (0, 1))                    # (p,q) -> (-p-q, q): determinant -1, keeps [1,1,6]
okr &= pull_back(Pa_, E2, E2, Kneg) == Prev and compose_reader((1, 1, 6), Kneg) == (1, 1, 6)
for (x_, y_, z_, w_) in BOX:
    okr &= read((1, 1, 6), apply(Prev, (x_, y_), (z_, w_))) == read((2, 1, 3), (x_, y_))*read((2, -1, 3), (z_, w_))
check("Remark 7.6: the caution; a rule with the right equation and readers -X2, -X2'", okr)

# Lemma 6.1 by the construction of its proof
def crt_pair(res, mods):
    xx, mm_ = 0, 1
    for r_, m_ in zip(res, mods):
        while xx % m_ != r_ % m_:
            xx += mm_
        mm_ *= m_
    return xx
def prime_factors(m):
    out = []; d = 2
    while d*d <= m:
        if m % d == 0:
            out.append(d)
            while m % d == 0: m //= d
        d += 1
    if m > 1: out.append(m)
    return out
ok61 = True; n61 = 0
for N, fs in FORMS.items():
    for X in fs:
        for m in (2, 3, 6, 30, 210, 23, 46, 2*3*5*7*11*13, X[0]*X[2], X[0]*(X[0] + X[1] + X[2]) or 1):
            ps = prime_factors(abs(m))
            if not ps:
                psi0 = (1, 0)
            else:
                cand = [next(c_ for c_ in ((1, 0), (0, 1), (1, 1)) if read(X, c_) % r_) for r_ in ps]
                psi0 = (crt_pair([c_[0] for c_ in cand], ps), crt_pair([c_[1] for c_ in cand], ps))
                g_ = gcd(psi0[0], psi0[1]); psi0 = (psi0[0]//g_, psi0[1]//g_)
            G_ = complete(*psi0)
            ok61 &= gcd(compose_reader(X, G_)[0], abs(m)) == 1 and compose_reader(X, G_)[0] == read(X, psi0)
            n61 += 1
check("Lemma 6.1: the construction of the proof gives a first number without common factor", ok61, "%d cases" % n61)

def normal_form_product(X, Y):
    """the classical normal-form product: products of the lattice generators, brought to a
    triangular basis"""
    N = N4(X); e = N % 2; h = (N + e)//4
    mul = lambda u, v: (u[0]*v[0] - h*u[1]*v[1], u[0]*v[1] + u[1]*v[0] + e*u[1]*v[1])
    gx = [(X[0], 0), ((X[1] - e)//2, 1)]; gy = [(Y[0], 0), ((Y[1] - e)//2, 1)]
    cols = [mul(gx[i], gy[j]) for i in range(2) for j in range(2)]
    g = 0
    for c_ in cols: g = gcd(g, abs(c_[1]))
    # a combination with second entry g
    b2 = (0, 0)
    for c_ in cols:
        if c_[1] == 0: continue
        if b2[1] == 0: b2 = c_ if c_[1] > 0 else (-c_[0], -c_[1]); continue
        # extended gcd of b2[1], c_[1]
        u0, v0, r0, u1, v1, r1 = 1, 0, b2[1], 0, 1, c_[1]
        while r1:
            k = r0//r1
            u0, v0, r0, u1, v1, r1 = u1, v1, r1, u0 - k*u1, v0 - k*v1, r0 - k*r1
        if r0 < 0: u0, v0, r0 = -u0, -v0, -r0
        b2 = (u0*b2[0] + v0*c_[0], r0)
    assert b2[1] == g
    h11 = 0
    for c_ in cols: h11 = gcd(h11, abs(c_[0] - (c_[1]//g)*b2[0]))
    H = ((h11, b2[0] % h11), (0, g))
    Hi = frac_inv(H)
    B = [mat_vec(Hi, c_) for c_ in cols]
    assert all(t.denominator == 1 for c_ in B for t in c_)
    B = [tuple(int(t) for t in c_) for c_ in B]
    return ((B[0], B[1]), (B[2], B[3])), H
ok = True; cnt = 0
for N, fs in FORMS.items():
    for X, Y in iproduct(fs, repeat=2):
        P, H = normal_form_product(X, Y)
        rX, rY, rZ = three_readers(P)
        ok &= (rX, rY) == (X, Y) and N4(rZ) == N and H[0][0]*H[1][1] == X[0]*Y[0]
        ok &= reduce(rZ) == TABLE[(reduce(X), reduce(Y))]; cnt += 1
check("Section 8: the classical normal-form product has left and right readers X, Y",
      ok, "%d pairs" % cnt)

def classes_reading(m, N, bound=None):
    out = set()
    for X in FORMS[N]:
        r = int((4*m/ (3 if N >= 3 else 1))**0.5) + 2
        hit = False
        for xx in range(-r - 2, r + 3):
            for yy in range(0, r + 3):
                if read(X, (xx, yy)) == m:
                    hit = True; break
            if hit: break
        if hit: out.add(X)
    return out
ok = True; okc = True; cnt = 0; cntc = 0
PR = [t for t in range(2, 120) if all(t % d for d in range(2, int(t**0.5) + 1))]
for N in (23, 31, 39, 47, 71, 87):
    fs = FORMS[N]
    pick = {pp: classes_reading(pp, N) for pp in PR if N % pp}
    pick = {pp: s for pp, s in pick.items() if s}
    for pp, qq in iproduct(sorted(pick)[:9], repeat=2):
        if pp > qq: continue
        got = classes_reading(pp*qq, N)
        want = {TABLE[(X, Y)] for X in pick[pp] for Y in pick[qq]}
        ok &= want <= got
        if pp != qq:
            okc &= want == got; cntc += 1
        cnt += 1
check("Theorem 7.5: the classes two primes pick multiply to classes that read the product", ok,
      "%d pairs of primes" % cnt)
check("Theorem 7.5 (converse, distinct primes, as far as computed): no other class reads it", okc, "%d pairs" % cntc)

# ================================================================ section 8
X1, X2, X2m = (1, 1, 6), (2, 1, 3), (2, -1, 3)
fs = FORMS[23]
ok = fs == [X1, X2, X2m] or set(fs) == {X1, X2, X2m}
t = TABLE
ok &= t[(X2, X2)] == X2m and t[(X2, X2m)] == X1 and t[(X2m, X2m)] == X2 and t[(X1, X2)] == X2
check("Theorem 8.1(a): three classes at even form 23/4, and they run a loop of three steps", ok)
Pa = block_from(lambda s, t: (2*s[0]*t[0] - s[0]*t[1] - 3*s[1]*t[1], s[0]*t[1] + s[1]*t[0]))
Pb = block_from(lambda s, t: (s[0]*t[0] - s[0]*t[1] - s[1]*t[0] - 2*s[1]*t[1],
                              s[0]*t[0] + s[0]*t[1] + s[1]*t[0] - s[1]*t[1]))
ok = True
for (x_, y_, z_, w_) in BOX:
    ok &= read(X1, apply(Pa, (x_, y_), (z_, w_))) == read(X2, (x_, y_))*read(X2m, (z_, w_))
    ok &= read(X2m, apply(Pb, (x_, y_), (z_, w_))) == read(X2, (x_, y_))*read(X2, (z_, w_))
ra, rb = three_readers(Pa), three_readers(Pb)
print("      readers of the first product :", ra)
print("      readers of the second product:", rb)
check("Theorem 8.1(b): the two explicit products at the border", ok)
Mm = ((1, 0), (0, -1))
rc = three_readers(pull_back(Pb, Mm, Mm, Mm))
check("Theorem 8.1(b): their three readers, and those of the mirror of the second",
      ra == (X2, X2m, X1) and rb == (X2, X2, X2m) and rc == (X2m, X2m, X2))
ok = compose_reader(X2, ((0, -1), (1, 0))) == (3, -1, 2)
Zs, _ = multiply((2, 1, 3), (3, -1, 2))
ok &= compose_reader((2, 1, 3), ((1, 1), (0, 1))) == (2, 5, 6) and compose_reader((3, -1, 2), ((1, 1), (0, 1))) == (3, 5, 4)
ok &= reduce((6, 5, 2)) == X2m
check("Theorem 8.1(a), Figure 4: [2,1,3] and [3,-1,2] meet at b = 5, and [6,5,2] is in the mirror class", ok)
check("Theorem 8.1(c): 2 and 3 by X2, 6 = X1(0,1), 8 = X1(1,1)",
      read(X2, (1, 0)) == 2 and read(X2, (0, 1)) == 3 and read(X1, (0, 1)) == 6 and read(X1, (1, 1)) == 8)
print("      area example: P(psi,e1), P(psi,e2) for psi=(1,1):",
      apply(Pa, (1, 1), (1, 0)), apply(Pa, (1, 1), (0, 1)), " X2(1,1) =", read(X2, (1, 1)))


# ================================================================ section 10: the product in one line
import random, math
random.seed(13)
def xgcd(a, b):
    if b == 0: return (abs(a), (1 if a >= 0 else -1), 0)
    g, u, v = xgcd(b, a % b); return g, v, u - (a//b)*v
def col_echelon(Am):
    """whole column steps: returns (U, r) with U whole of determinant +-1, Am U in column echelon
    form, its first r columns not zero and the rest zero; the last columns of U span the whole
    solutions of Am v = 0"""
    rows, n = len(Am), len(Am[0]); A = [list(r_) for r_ in Am]
    U = [[int(i == j) for j in range(n)] for i in range(n)]; col = 0
    for row in range(rows):
        piv = None
        for j in range(col, n):
            if A[row][j] != 0:
                if piv is None: piv = j
                else:
                    a_, b_ = A[row][piv], A[row][j]; g, u, v = xgcd(a_, b_)
                    for Mx in (A, U):
                        for i in range(len(Mx)):
                            p_, q_ = Mx[i][piv], Mx[i][j]
                            Mx[i][piv] = u*p_ + v*q_; Mx[i][j] = (-b_//g)*p_ + (a_//g)*q_
        if piv is not None:
            for Mx in (A, U):
                for i in range(len(Mx)): Mx[i][col], Mx[i][piv] = Mx[i][piv], Mx[i][col]
            col += 1
    return U, col
def gram4(X, Y, sign=-1):
    """4 x the symmetric array of the reader of boxes  tr(Xi^T G(X) Xi G(Y)) + sign 2n det Xi,
    in the entries (Xi00, Xi01, Xi10, Xi11); whole numbers"""
    A, B, C = X; A2, B2, C2 = Y; N = N4(X)
    GX = [[2*A, B], [B, 2*C]]; GY = [[2*A2, B2], [B2, 2*C2]]                 # twice the arrays
    G = [[GX[i][k]*GY[j][l] for k in range(2) for l in range(2)] for i in range(2) for j in range(2)]
    JJ = [[0, 0, 0, 1], [0, 0, -1, 0], [0, -1, 0, 0], [1, 0, 0, 0]]          # v^T JJ v = 2 det Xi
    return [[G[i][j] + sign*N*JJ[i][j] for j in range(4)] for i in range(4)]
def box_read(X, Y, v, sign=-1):
    G = gram4(X, Y, sign); t = sum(v[i]*G[i][j]*v[j] for i in range(4) for j in range(4))
    assert t % 4 == 0
    return t//4
def P_of_box(P, v):
    c = [P[0][0], P[0][1], P[1][0], P[1][1]]
    return tuple(sum(v[i]*c[i][k] for i in range(4)) for k in range(2))
def own_turn2(X):                      # twice the own turn S_X = J Gamma(X), whole
    A, B, C = X; return [[-B, -2*C], [2*A, B]]
def what_is_left(X, Y, sign=-1):
    """divide the whole boxes by the whole null boxes: a whole map rho (2 x 4) onto the whole
    roots, the reader Z left on them, and whether rho is direct (left reader +X)"""
    G = gram4(X, Y, sign); U, r = col_echelon(G)
    assert r == 2
    Ui = sp.Matrix(U).inv(); rho = [[int(Ui[i, j]) for j in range(4)] for i in range(2)]
    u = [[U[i][j] for i in range(4)] for j in range(2)]
    g = lambda a_, b_: sum(u[a_][i]*G[i][j]*u[b_][j] for i in range(4) for j in range(4))
    Z = (g(0, 0), 2*g(0, 1), g(1, 1)); assert all(t % 4 == 0 for t in Z); Z = tuple(t//4 for t in Z)
    Prho = tuple(tuple((rho[0][2*i + j], rho[1][2*i + j]) for j in range(2)) for i in range(2))
    return Z, rho, Prho

# Lemma 10.2: a reader of boxes that reads every box of products as zero is a multiple of the area
m11, m12, m21, m22 = sp.symbols('m11 m12 m21 m22'); mm = [m11, m12, m21, m22]
qs = sp.symbols('q0:10'); mons = [mm[i]*mm[j] for i in range(4) for j in range(i, 4)]
qgen = sum(c_*t_ for c_, t_ in zip(qs, mons))
on_products = sp.Poly(sp.expand(qgen.subs({m11: x*z, m12: x*w, m21: y*z, m22: y*w}, simultaneous=True)), x, y, z, w)
sol = sp.solve(on_products.coeffs(), qs, dict=True)[0]
left = sp.expand(qgen.subs(sol)); free = [c_ for c_ in qs if left.has(c_)]
check("Lemma 10.2: readers of boxes that vanish on all boxes of products are the multiples of the area",
      len(free) == 1 and sp.expand(left - free[0]*sp.expand(left.coeff(free[0]))) == 0
      and sp.expand(left.coeff(free[0]) - left.coeff(free[0]).coeff(m11*m22)*(m11*m22 - m12*m21)) == 0)

# Theorem 10.3, as identities in free symbols
A2_, B2_, C2_, n_ = sp.symbols('A2 B2 C2 n')
Xi = sp.Matrix([[m11, m12], [m21, m22]]); Jm = sp.Matrix([[0, -1], [1, 0]])
GXs = sp.Matrix([[A_, B_/2], [B_/2, C_]]); GYs = sp.Matrix([[A2_, B2_/2], [B2_/2, C2_]])
SXs, SYs = Jm*GXs, Jm*GYs
pair = lambda M1, M2: (M1.adjugate()*M2).trace()
Lop = lambda M1: SXs*M1; Rop = lambda M1: M1*SYs.T
tens = (Xi.T*GXs*Xi*GYs).trace()
prod_box = sp.Matrix([[x*z, x*w], [y*z, y*w]])
ok = sp.expand(tens.subs({m11: x*z, m12: x*w, m21: y*z, m22: y*w}, simultaneous=True)
               - Xs_*(A2_*z**2 + B2_*z*w + C2_*w**2)) == 0
check("Theorem 10.3(a): the box of products psi chi^T is read as X(psi) Y(chi)", ok and prod_box.det() == 0)
Xi2 = sp.Matrix(2, 2, sp.symbols('k11 k12 k21 k22'))
ok = sp.expand(tens - pair(Xi, Lop(Rop(Xi)))) == 0
ok &= sp.expand(pair(Lop(Xi), Xi2) + pair(Xi, Lop(Xi2))) == 0 and sp.expand(pair(Rop(Xi), Xi2) + pair(Xi, Rop(Xi2))) == 0
ok &= (Lop(Rop(Xi)) - Rop(Lop(Xi))).expand() == sp.zeros(2)
nX = A_*C_ - B_**2/4; nY = A2_*C2_ - B2_**2/4
ok &= (Lop(Lop(Xi)) + nX*Xi).expand() == sp.zeros(2) and (Rop(Rop(Xi)) + nY*Xi).expand() == sp.zeros(2)
ok &= sp.expand(pair(Xi, Xi) - 2*Xi.det()) == 0
check("Theorem 10.3, proof: tr = <<Xi, LR Xi>>; L and R are skew for the pairing of boxes, commute, and square to -n", ok)
# the trace of LR is zero
basis = [sp.Matrix(2, 2, [int(i == k) for i in range(4)]) for k in range(4)]
trLR = sum(Lop(Rop(bk))[k // 2, k % 2] for k, bk in enumerate(basis))
check("Theorem 10.3, proof: LR has trace zero", sp.expand(trLR) == 0)

# Theorem 10.3 and 10.4 on all pairs of reduced readers at the 23 even forms, after random changes of view
def rand_view():
    G = ((1, 0), (0, 1))
    for _ in range(4):
        k = random.randint(-2, 2); G = mat_mul(G, ((1, k), (0, 1)))
        if random.random() < 0.5: G = mat_mul(G, ((0, -1), (1, 0)))
    return G
st = dict(pairs=0, null=True, sings=True, zp=True, whole=True, kills=True, onto=True, direct=0, indirect=0,
          left=True, cls=True, prim=True, mirror_cls=True, zeta=True, other=True)
tsym = sp.Symbol('t')
for N, fs in FORMS.items():
    for X0 in fs:
        for Y0 in fs:
            X, Y = compose_reader(X0, rand_view()), compose_reader(Y0, rand_view())
            st['pairs'] += 1; G = gram4(X, Y); Gm = sp.Matrix(G)
            # (b) the null boxes: rank 2, and they are the boxes with S_X N = - N S_Y^T, the boxes S_X Xi - Xi S_Y^T
            SX, SY = sp.Matrix(own_turn2(X))/2, sp.Matrix(own_turn2(Y))/2
            nullv = Gm.nullspace(); st['null'] &= len(nullv) == 2
            for nv in nullv:
                Nb = sp.Matrix(2, 2, list(nv)); st['null'] &= (SX*Nb + Nb*SY.T) == sp.zeros(2)
            imgs = [SX*bk - bk*SY.T for bk in basis]
            st['null'] &= sp.Matrix([list(im) for im in imgs]).rank() == 2 and all(Gm*sp.Matrix(4, 1, list(im)) == sp.zeros(4, 1) for im in imgs)
            # (c) exactly two multiples of the area give null boxes
            JJ = sp.Matrix([[0, 0, 0, 1], [0, 0, -1, 0], [0, -1, 0, 0], [1, 0, 0, 0]])
            if st['pairs'] % 9 == 0:
                tensG = sp.Matrix(gram4(X, Y, 0)); dett = sp.factor((tensG + 2*tsym*JJ).det())
                st['sings'] &= sp.expand(dett - 16*(tsym**2 - sp.Rational(N, 2)**2)**2) == 0
            # (e) whole on whole boxes
            st['whole'] &= all(G[i][j] % 2 == 0 for i in range(4) for j in range(4)) and all(G[i][i] % 4 == 0 for i in range(4))
            # (d) every product with these left and right readers: Z(P(Xi)) = (X.Y)(Xi)
            Z, P = multiply(X, Y)
            for _ in range(6):
                v = [random.randint(-6, 6) for _ in range(4)]
                st['zp'] &= read(Z, P_of_box(P, v)) == box_read(X, Y, v)
            st['kills'] &= all(P_of_box(P, list(sp.Matrix(4, 1, list(nv))*sp.ilcm(*[t_.q for t_ in nv]))) == (0, 0) for nv in nullv)
            # Theorem 10.4: what is left
            Zr, rho, Prho = what_is_left(X, Y)
            lam, rhoR, zeta = three_readers(Prho)
            if lam == X and rhoR == Y: st['direct'] += 1
            elif lam == tuple(-t_ for t_ in X) and rhoR == tuple(-t_ for t_ in Y): st['indirect'] += 1
            else: st['left'] = False
            st['prim'] &= primitive(Zr) and N4(Zr) == N and Zr[0] > 0
            if lam == X:
                st['cls'] &= reduce(Zr) == TABLE[(X0, Y0)]; st['zeta'] &= zeta == Zr
            else:
                st['mirror_cls'] &= reduce(mirror(Zr)) == TABLE[(X0, Y0)]
            # the other choice of the two roots that span what is left: exchange them
            Zx = (Zr[2], Zr[1], Zr[0]); Px = tuple(tuple((Prho[i][j][1], Prho[i][j][0]) for j in range(2)) for i in range(2))
            lx_, rx_, zx_ = three_readers(Px)
            st['mirror_cls'] &= (lx_, rx_) == (tuple(-t_ for t_ in lam), tuple(-t_ for t_ in rhoR)) and zx_ == Zx
            st['mirror_cls'] &= (reduce(mirror(Zx)) if lam == X else reduce(Zx)) == TABLE[(X0, Y0)]
            for _ in range(4):
                v = [random.randint(-6, 6) for _ in range(4)]
                st['onto'] &= read(Zr, tuple(sum(rho[i][j]*v[j] for j in range(4)) for i in range(2))) == box_read(X, Y, v)
            # Corollary 10.5: the other sign
            Zo, rho_o, Po = what_is_left(X, Y, +1); lam_o = three_readers(Po)[0]
            want = TABLE[(reduce(mirror(X0)), Y0)]
            lo, ro, _zo = three_readers(Po); negY = tuple(-t_ for t_ in Y); negX = tuple(-t_ for t_ in X)
            st['other'] &= (lo, ro) in ((X, negY), (negX, Y))                  # the left and right readers have opposite signs
            st['other'] &= primitive(Zo) and N4(Zo) == N and (reduce(Zo) == want if lo == X else reduce(mirror(Zo)) == want)
            for _ in range(3):
                v = [random.randint(-6, 6) for _ in range(4)]; mv = [v[0], v[1], -v[2], -v[3]]
                st['other'] &= box_read(X, Y, v, +1) == box_read(mirror(X), Y, mv, -1)
npairs = st['pairs']
check("Theorem 10.3(b): the null boxes are a plane: the boxes with S_X N = -N S_Y^T, which are the boxes S_X Xi - Xi S_Y^T", st['null'], "%d pairs of readers" % npairs)
check("Theorem 10.3(c): tr + t det has null boxes exactly for t = -2n and t = +2n", st['sings'])
check("Theorem 10.3(d): Z(P(Xi)) = (X.Y)(Xi) for the whole product of Corollary 6.5, and P is zero on the null boxes", st['zp'] and st['kills'], "%d pairs" % npairs)
check("Theorem 10.3(e): X.Y is whole on whole boxes", st['whole'])
check("Theorem 10.4(a,b): dividing by the whole null boxes gives a whole product with readers X, Y or -X, -Y", st['left'],
      "%d direct, %d not" % (st['direct'], st['indirect']))
check("Theorem 10.4(b): what is left is a whole primitive reader of the same even form, and reads rho(Xi) as (X.Y)(Xi)", st['prim'] and st['onto'])
check("Theorem 10.4(b): direct: it is the product reader, and its class is the product class of the table", st['cls'] and st['zeta'])
check("Theorem 10.4(c): with the two roots exchanged the readers are -X, -Y and the mirror of what is left is in the product class", st['mirror_cls'])
check("Corollary 10.5: the other sign is (X'.Y) at the mirrored box; its readers are X, -Y, and what is left is in the class of X' times Y", st['other'])

# Proposition 10.6: testing a reader H
st = dict(n=0, dim=True, c=True, form=True, cls=True, one=True, lam=True)
for N in (23, 39, 47, 56, 71, 84, 87):
    fs = FORMS[N]
    for X0 in fs:
        for Y0 in fs:
            Z, P = multiply(X0, Y0)
            for H in fs:
                st['n'] += 1
                # whole K with S_H K = K S_Z  (twice the own turns, whole)
                SH, SZ = own_turn2(H), own_turn2(Z)
                rowsK = []
                for i in range(2):
                    for j in range(2):
                        coef = [0]*4                                   # unknowns K00,K01,K10,K11
                        for k in range(2):
                            coef[2*k + j] += SH[i][k]                  # (S_H K)_ij
                            coef[2*i + k] -= SZ[k][j]                  # (K S_Z)_ij
                        rowsK.append(coef)
                U, r = col_echelon(rowsK); st['dim'] &= r == 2
                K1 = ((U[0][2], U[1][2]), (U[2][2], U[3][2])); K2 = ((U[0][3], U[1][3]), (U[2][3], U[3][3]))
                # [K1 w, K2 w] = c Z(w)
                rd_ = detquad(((K1[0][0], K2[0][0]), (K1[1][0], K2[1][0])), ((K1[0][1], K2[0][1]), (K1[1][1], K2[1][1])))
                c_ = rd_[0]//Z[0]; st['c'] &= c_ in (1, -1) and rd_ == tuple(c_*t_ for t_ in Z)
                if c_ == -1: K1, K2 = K2, K1
                F = detquad(K1, K2)                                    # lambda = det(s K1 + t K2)
                st['form'] &= primitive(F) and N4(F) == N and F[0] > 0
                st['cls'] &= TABLE[(reduce(F), reduce(Z))] == H
                st['one'] &= (reduce(F)[0] == 1) == (reduce(Z) == H)
                # lambda: H(b(Xi)) = det K (X.Y)(Xi) for b = K P
                s_, t_ = random.randint(-3, 3), random.randint(-3, 3)
                K = tuple(tuple(s_*K1[i][j] + t_*K2[i][j] for j in range(2)) for i in range(2))
                v = [random.randint(-5, 5) for _ in range(4)]
                st['lam'] &= read(H, mat_vec(K, P_of_box(P, v))) == read(F, (s_, t_))*box_read(X0, Y0, v)
check("Proposition 10.6(a): H(K P(Xi)) = det K (X.Y)(Xi) for the whole K with S_H K = K S_Z, a plane of them", st['dim'] and st['lam'], "%d triples X, Y, H" % st['n'])
check("Proposition 10.6(b): det on those K is a whole primitive reader F of the same even form, [K1 w, K2 w] = +-Z(w), and F times the product class is the class of H", st['c'] and st['form'] and st['cls'])
check("Proposition 10.6(c): det K = 1 has a whole solution exactly when H is in the product class", st['one'])

# Proposition 10.7: on the cone
ok = True; ranks = set()
for _ in range(80):
    def cone_reader():
        while True:
            al, be = random.randint(-6, 6), random.randint(-6, 6)
            if gcd(abs(al), abs(be)) == 1: break
        sg = random.choice((1, -1)); return (sg*al*al, sg*2*al*be, sg*be*be), (al, be), sg
    (X, lx, sx), (Y, ly, sy) = cone_reader(), cone_reader()
    ok &= N4(X) == 0 and primitive(X); ranks.add(sp.Matrix(gram4(X, Y)).rank())
    v = [random.randint(-6, 6) for _ in range(4)]
    lin = lx[0]*v[0]*ly[0] + lx[0]*v[1]*ly[1] + lx[1]*v[2]*ly[0] + lx[1]*v[3]*ly[1]
    ok &= box_read(X, Y, v) == sx*sy*lin*lin
check("Proposition 10.7: on the cone X.Y is plus or minus the square of one whole reading of the box; three null directions", ok and ranks == {1})

# Remark 10.8: outside the cone (checked, not proved)
def rho_step(F, D):
    a_, b_, c_ = F; s_ = math.isqrt(D); m_ = abs(c_)
    if m_ > s_:
        r_ = (-b_) % (2*m_)
        if r_ > m_: r_ -= 2*m_
    else:
        r_ = (-b_) % (2*m_); r_ += ((s_ - r_)//(2*m_))*(2*m_)
    return (c_, r_, (r_*r_ - D)//(4*c_))
def cycle(F, D):
    red = lambda Fx: 0 < Fx[1] < math.sqrt(D) and math.sqrt(D) - Fx[1] < 2*abs(Fx[0]) < math.sqrt(D) + Fx[1]
    while not red(F): F = rho_step(F, D)
    out = [F]; Gf = rho_step(F, D)
    while Gf != F: out.append(Gf); Gf = rho_step(Gf, D)
    return frozenset(out)
def united(F1, F2):                         # the classical composition, written independently of this paper
    a1, b1, c1 = F1; a2, b2, c2 = F2; D = b1*b1 - 4*a1*c1
    g, u1, u2 = xgcd(a1, a2); e, v1, v2 = xgcd(g, (b1 + b2)//2)
    a3 = a1*a2//(e*e); b3 = ((v1*u1*a1*b2 + v1*u2*a2*b1 + v2*(b1*b2 + D)//2)//e) % (2*abs(a3))
    return (a3, b3, (b3*b3 - D)//(4*a3))
def outside(D, box=12):
    out = []
    for a_ in range(-box, box + 1):
        for b_ in range(-box, box + 1):
            if a_ and (b_*b_ - D) % (4*a_) == 0:
                c_ = (b_*b_ - D)//(4*a_)
                if c_ and gcd(gcd(abs(a_), abs(b_)), abs(c_)) == 1: out.append((a_, b_, c_))
    return out
st = dict(n=0, prim=True, reads=True, cls=True, other=True, flips=0)
for D in (5, 8, 12, 21, 28, 40, 60, 65, 136, 229, 316, 321):
    fs = outside(D)
    for _ in range(60):
        X, Y = random.choice(fs), random.choice(fs); st['n'] += 1
        Zr, rho, Prho = what_is_left(X, Y); lam = three_readers(Prho)[0]
        if lam != X:                                  # make it direct: exchange the two roots that span what is left
            assert lam == tuple(-t_ for t_ in X); st['flips'] += 1
            rho = [rho[1], rho[0]]; Zr = (Zr[2], Zr[1], Zr[0])
        st['prim'] &= primitive(Zr) and Zr[1]**2 - 4*Zr[0]*Zr[2] == D
        v = [random.randint(-6, 6) for _ in range(4)]
        st['reads'] &= read(Zr, tuple(sum(rho[i][j]*v[j] for j in range(4)) for i in range(2))) == box_read(X, Y, v)
        st['cls'] &= cycle(Zr, D) == cycle(united(X, Y), D)
        Zo, rho_o, Po = what_is_left(X, Y, +1)
        if three_readers(Po)[0] != X: Zo = (Zo[2], Zo[1], Zo[0])   # choose the two roots so that the left reader is +X
        st['other'] &= cycle(Zo, D) == cycle(united(mirror(X), Y), D)
check("Remark 10.8 (outside the cone, as far as computed): what is left is whole, primitive, of the same even form, and reads rho(Xi) as (X.Y)(Xi)",
      st['prim'] and st['reads'], "%d pairs at 12 even forms" % st['n'])
check("Remark 10.8 (outside the cone, as far as computed): made direct, its class is that of the classical composition; the other sign gives X' times Y",
      st['cls'] and st['other'], "%d exchanged to make them direct" % st['flips'])

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