# verify_whole_roots.py -- checks for Paper 12, "Whole Roots".  Exact arithmetic
# (one floating-point check, marked).  X=(t;a,u), root psi=(x,y).
from fractions import Fraction as Fr
from math import gcd, isqrt, exp, pi, sqrt
from itertools import product, combinations
import random
random.seed(12); NCHK = [0]; FAILED = []
def ok(name, cond):
    NCHK[0] += 1; FAILED.extend([] if cond else [name]); print(("PASS  " if cond else "FAIL  ") + name)
def cut(p): x, y = p; return (x*x + y*y, x*x - y*y, 2*x*y)
def eta(X, Y): return X[0]*Y[0] - X[1]*Y[1] - X[2]*Y[2]
def inner(X, Y): return sum(a*b for a, b in zip(X, Y))
def sigma(X): return (X[0], -X[1], -X[2])
def Gam(X): t, a, u = X; return ((t + a, u), (u, t - a))
def unGam(m): return (Fr(m[0][0] + m[1][1], 2), Fr(m[0][0] - m[1][1], 2), Fr(m[0][1]))
def mm(A, B): return tuple(tuple(sum(A[i][k]*B[k][j] for k in range(2)) for j in range(2)) for i in range(2))
def tr(A): return ((A[0][0], A[1][0]), (A[0][1], A[1][1]))
def mv(A, v): return (A[0][0]*v[0] + A[0][1]*v[1], A[1][0]*v[0] + A[1][1]*v[1])
def det(A): return A[0][0]*A[1][1] - A[0][1]*A[1][0]
def trace(A): return A[0][0] + A[1][1]
def inv(A): d = det(A); return ((Fr(A[1][1], d), Fr(-A[0][1], d)), (Fr(-A[1][0], d), Fr(A[0][0], d)))
def lin(x, y, S): return ((x + y*S[0][0], y*S[0][1]), (y*S[1][0], x + y*S[1][1]))
def L(A, X): return unGam(mm(mm(A, Gam(X)), tr(A)))            # Lemma 2.2
def read(X, p): return inner(X, cut(p))
def point(f): A, B, C = f; return (Fr(A + C, 2), Fr(A - C, 2), Fr(B, 2))   # reader [A,B,C]
def form(X): return (int(X[0] + X[1]), int(2*X[2]), int(X[0] - X[1]))
I2 = ((1, 0), (0, 1)); NEG = ((-1, 0), (0, -1)); J = ((0, -1), (1, 0)); Ji = ((0, 1), (-1, 0))
T = ((1, 1), (0, 1)); Ti = ((1, -1), (0, 1)); M = ((1, 0), (0, -1)); T2 = mm(T, T)
def mpow(A, n): return I2 if n == 0 else mm(mpow(A, n - 1), A)
def word(gens, n): return I2 if n == 0 else mm(word(gens, n - 1), random.choice(gens))
SL = [word([J, T, Ti, Ji], random.randint(1, 9)) for _ in range(150)]
ROOTS = [(x, y) for x in range(-12, 13) for y in range(-12, 13)]
PTS = [(1, 0, 0), (3, 1, 1), (2, -1, 0), (0, 1, 0), (1, 2, 3), point((1, 1, 1)), point((1, 1, 6)), point((2, 1, 3))]
def is_sq(n): return n >= 0 and isqrt(n)**2 == n
def divs(n): return [d for d in range(1, n + 1) if n % d == 0]
def prime(p): return p > 1 and all(p % q for q in range(2, isqrt(p) + 1))
E3 = [(1, 0, 0), (0, 1, 0), (0, 0, 1)]

# ---- Section 2
ok("Lemma 2.1  master identity; det Gam(X) = eta(X,X)",
   all(Gam(cut(p)) == tuple(tuple(2*a*b for b in p) for a in p) for p in ROOTS[::7])
   and all(read(X, p) == inner(p, mv(Gam(X), p)) and det(Gam(X)) == eta(X, X) for X in PTS for p in ROOTS[::11]))
ok("Lemma 2.2  c(A psi) = L_A c(psi), products, even form scaled by det^2, transposed reading",
   all(cut(mv(A, p)) == L(A, cut(p)) for A in SL[:40] + [((2, 0), (0, 1)), M] for p in ROOTS[::37])
   and all(L(mm(A, B), X) == L(A, L(B, X)) for A in SL[:9] for B in SL[9:18] for X in PTS[:3])
   and all(eta(L(A, X), L(A, X)) == det(A)**2*eta(X, X) and read(L(A, X), (2, 3)) == read(X, mv(tr(A), (2, 3)))
           for A in SL[:40] + [((2, 0), (0, 1)), ((3, 1), (1, 2))] for X in PTS))
ok("Lemma 2.2  NEG (2x,y) keeps whole roots whole but not the even form", eta(L(((2, 0), (0, 1)), E3[0]), L(((2, 0), (0, 1)), E3[0])) == 4)
PLUS1 = {3: [1], 4: [1], 7: [1, 2, 4], 8: [1, 3], 15: [1, 2, 4, 8], 20: [1, 3, 7, 9],
         23: [1, 2, 3, 4, 6, 8, 9, 12, 13, 16, 18], 44: [1, 3, 5, 9, 15, 23, 25, 27, 31, 37]}
def typ(N, a): return 0 if gcd(a, N) != 1 else (1 if a % N in PLUS1[N] else -1)     # the printed table
def typ5(a): return 0 if a % 5 == 0 else (1 if a % 5 in (1, 4) else -1)
ok("Section 2  the printed types multiply; (N1) the 4-loop type is the height/width type",
   all(typ(N, a*b) == typ(N, a)*typ(N, b) for N in PLUS1 for a in range(1, 60) for b in range(1, 60))
   and all(typ5(a*b) == typ5(a)*typ5(b) for a in range(1, 30) for b in range(1, 30))
   and all(typ(4, a) == (0 if a % 2 == 0 else 1 if a % 4 == 1 else -1) for a in range(1, 50)))
ok("Section 2  (N3) type +1 iff -N is a square on the loop of 4p steps (primes < 400)",
   all((typ(N, p) == 1) == any((b*b + N) % (4*p) == 0 for b in range(2*p)) for N in PLUS1 for p in range(2, 400) if prime(p) and N % p))

# ---- Section 3
R = 40; CUTS = {}
for p in product(range(-R, R + 1), repeat=2): CUTS.setdefault(cut(p), []).append(p)
B0 = R*R//4
CONE = [(t, a, u) for t in range(B0 + 1) for a in range(-t, t + 1) for u in range(-t, t + 1) if t*t == a*a + u*u]
def cont(X): return gcd(gcd(abs(X[0]), abs(X[1])), abs(X[2]))
def crit(X):
    if X == (0, 0, 0): return True
    d = cont(X); u0 = X[2]//d
    return (u0 % 2 == 0 and is_sq(d)) or (u0 % 2 == 1 and d % 2 == 0 and is_sq(d//2))
ok("Theorem 3.2(a)  whole cut iff (t+a)/2, (t-a)/2 are whole squares [%d cone points]" % len(CONE),
   all(((X[0] - X[1]) % 2 == 0 and is_sq((X[0] + X[1])//2) and is_sq((X[0] - X[1])//2)) == (X in CUTS) for X in CONE))
ok("Theorem 3.2(b)  d X0 is a whole cut iff (u0 even, d square) or (u0 odd, d twice a square)",
   all(crit(X) == (X in CUTS) for X in CONE) and all(X[0] % 2 == 1 and (X[1] + X[2]) % 2 == 1 for X in CONE[1:] if cont(X) == 1))
ok("Theorem 3.2(c)  a non-zero whole cut has exactly the two whole roots psi, -psi",
   all(len(v) == 2 and v[0] == (-v[1][0], -v[1][1]) for X, v in CUTS.items() if X != (0, 0, 0)))
ok("Theorem 3.2  NEG (5;4,3) and (3;3,0) are on the cone and are not whole cuts",
   (5, 4, 3) in CONE and (5, 4, 3) not in CUTS and (3, 3, 0) not in CUTS and cut((3, 1)) == (10, 8, 6))
def lead(x, y): return x > y > 0 and gcd(x, y) == 1 and (x + y) % 2 == 1
ok("Corollary 3.3  primitive triples with u even = cuts of leading roots",
   {X for X in CONE[1:] if cont(X) == 1 and X[1] > 0 and X[2] > 0 and X[2] % 2 == 0}
   == {X for X in (cut((x, y)) for x in range(1, R) for y in range(1, x) if lead(x, y)) if X[0] <= B0})
ok("Remark 3.4  c(x+y, x-y) = 2 (t;u,a)", all(cut((x + y, x - y)) == tuple(2*c for c in (cut((x, y))[0], cut((x, y))[2], cut((x, y))[1])) for x, y in ROOTS[::9]))

# ---- Section 4
def as_word(A):                      # division with remainder on the first column
    A = [list(r) for r in A]; W = I2
    while A[1][0] != 0:
        k = A[0][0]//A[1][0]
        A = [[A[1][0], A[1][1]], [-(A[0][0] - k*A[1][0]), -(A[0][1] - k*A[1][1])]]; W = mm(mm(W, ((1, k), (0, 1))), J)
    return mm(mm(W, ((A[0][0], 0), (0, A[0][0]))), ((1, A[0][0]*A[0][1]), (0, 1)))
ALL6 = [((p, q), (r, t)) for p, q, r, t in product(range(-6, 7), repeat=4) if p*t - q*r == 1]
ok("Theorem 4.2(b)  every whole change of view with entries up to 6 [%d of them] is a word in J and T" % len(ALL6), all(as_word(A) == A for A in ALL6))
ok("Theorem 4.2(c)  L_A = identity only for A = +-1; L_J = sigma", all(all(L(A, X) == X for X in PTS) == (A in (I2, NEG)) for A in SL) and all(L(J, X) == sigma(X) for X in PTS))
ok("Theorem 4.2(d)  JT != TJ; one cut goes to (1;-1,0) or to (2;0,2)", mm(J, T) != mm(T, J) and L(mm(J, T), (1, 1, 0)) == (1, -1, 0) and L(mm(T, J), (1, 1, 0)) == (2, 0, 2))
def whole_pt(X): return all(Fr(c).denominator == 1 for c in (X[0] + X[1], X[0] - X[1], 2*X[2]))
def whole_co(X): return all(Fr(c).denominator == 1 for c in X)
def mod2(A): return tuple(c % 2 for r in A for c in r)
GRID = [point(f) for f in product(range(-3, 4), repeat=3)]
ok("Proposition 4.4(a)  L_A keeps whole points, and points with whole Gam", all(whole_pt(L(A, X)) and (X[2].denominator > 1 or L(A, X)[2].denominator == 1) for A in SL[:40] for X in GRID))
ok("Proposition 4.4(b)  whole coordinates kept iff A = identity or swap mod 2; six patterns mod 2",
   all(all(whole_co(L(A, X)) for X in E3) == (mod2(A) in ((1, 0, 0, 1), (0, 1, 1, 0))) for A in SL) and len({mod2(A) for A in SL}) == 6)
ok("Proposition 4.4  NEG the unit shear sends e to (3/2;1/2,1)", L(T, E3[0]) == (Fr(3, 2), Fr(1, 2), 1))
def to_e(X):                         # J and T^2 only: reach |u| <= t+a <= t-a
    A, u, C = X[0] + X[1], X[2], X[0] - X[1]
    while A > C or abs(u) > A:
        if A > C: A, u, C = C, -u, A
        else:
            k = round(Fr(-u, 2*A)) or (-1 if u > 0 else 1); C += 4*k*u + 4*k*k*A; u += 2*k*A
    return (Fr(A + C, 2), Fr(A - C, 2), u)
OBS = [(t, a, u) for t in range(1, 60) for a in range(-t, t + 1) for u in range(-t, t + 1) if t*t - a*a - u*u == 1]
ok("Theorem 4.6(a)  every observer with whole coordinates is e moved by J and T^2 [%d]" % len(OBS), all(to_e(o) == E3[0] for o in OBS))
QT = [q for q in product(range(-2, 3), repeat=4) if q[0]*q[3] - q[1]*q[2] == 1 and q[0]**2 + q[1]**2 == 1 == q[2]**2 + q[3]**2 and q[0]*q[2] + q[1]*q[3] == 0]
ok("Theorem 4.6(b)  the whole maps fixing e are the 4 quarter turns", len(QT) == 4)
def D_of(A): return trace(A)**2 - 4
def net_of(A): return tuple(tuple(A[i][j] - inv(A)[i][j] for j in range(2)) for i in range(2))
ok("Theorem 4.7(a)  ledger of A and its inverse: gross tr, net squared tr^2-4",
   all(all(A[i][j] + inv(A)[i][j] == trace(A)*I2[i][j] for i in range(2) for j in range(2)) and mm(net_of(A), net_of(A)) == ((D_of(A), 0), (0, D_of(A))) for A in SL))
UNIT = [X for X in product(range(-5, 6), repeat=3) if abs(eta(X, X)) == 1]; good = True
for _ in range(400):
    X, Y = random.choice(UNIT), random.choice(UNIT)
    if eta(X, X)*eta(Y, Y) == 1:
        P = mm(Gam((-X[0], X[1], X[2])), Gam(Y)); Q = mm(Gam((-Y[0], Y[1], Y[2])), Gam(X))
        good &= det(P) == 1 and mm(P, Q) == I2 and trace(P) == -2*eta(X, Y) and D_of(P) == 4*(eta(X, Y)**2 - 1)
ok("Theorem 4.7(a)  the two orderings of Paper 5 are inverse; tr = -2 eta(X,Y), tr^2-4 = 4D", good)
WP1 = [point(f) for f in product(range(-6, 7), repeat=3) if abs(4*f[0]*f[2] - f[1]**2) == 4]
def ordering(X, Y): return mm(Gam((-X[0], X[1], X[2])), Gam(Y))
ok("Theorem 4.7(a)  for whole points of equal even form +-1 the ordering is whole of determinant one [%d points]" % len(WP1),
   all(det(ordering(X, Y)) == 1 and all(Fr(c).denominator == 1 for r in ordering(X, Y) for c in r) for X in WP1 for Y in WP1 if eta(X, X) == eta(Y, Y)))
ok("Theorem 4.7(a)  NEG even forms -1/4 and -4: [0,1,0] and [1,0,-4] give determinant one but a matrix that is not whole",
   eta(point((0, 1, 0)), point((0, 1, 0)))*eta(point((1, 0, -4)), point((1, 0, -4))) == 1 and det(ordering(point((0, 1, 0)), point((1, 0, -4)))) == 1
   and any(Fr(c).denominator != 1 for r in ordering(point((0, 1, 0)), point((1, 0, -4))) for c in r))
def order(A): return next((n for n in range(1, 13) if mpow(A, n) == I2), None)
ok("Theorem 4.7(b)  turns, and only turns, have finite order: 3, 4 or 6",
   all((D_of(A) < 0 or A in (I2, NEG)) == (order(A) is not None) for A in SL) and {order(A) for A in SL if D_of(A) < 0} <= {3, 4, 6})
def keeps_line(A): return any(gcd(x, y) == 1 and mv(A, (x, y))[0]*y == mv(A, (x, y))[1]*x for x in range(-60, 61) for y in range(0, 61))
SM = [A for A in SL if max(abs(c) for r in A for c in r) < 30 and A not in (I2, NEG)][:50]; Bo = ((2, 1), (1, 1))
ok("Theorem 4.7(c,d)  a line of whole roots is kept iff shear; T^n steps; boost hidden parts t(n+1) = 7 t(n) - t(n-1)",
   all(keeps_line(A) == (D_of(A) == 0) for A in SM) and all(mv(mpow(T, n), (0, 1)) == (n, 1) for n in range(20))
   and all(cut(mv(mpow(Bo, n + 1), (1, 0)))[0] + cut(mv(mpow(Bo, n - 1), (1, 0)))[0] == 7*cut(mv(mpow(Bo, n), (1, 0)))[0] for n in range(1, 10)))
def fixed(A): return unGam(tuple(tuple(c/2 for c in r) for r in mm(net_of(A), J)))
ok("Proposition 4.8  X_A is whole, fixed by L_A, with even form -(tr^2-4)/4",
   all(whole_pt(fixed(A)) and L(A, fixed(A)) == fixed(A) and 4*eta(fixed(A), fixed(A)) == -D_of(A) for A in SL))
ok("Proposition 4.8  NEG the fixed reader of J is moved by T", L(T, fixed(J)) != fixed(J))

# ---- Section 5
U = [((2, -1), (1, 0)), ((2, 1), (1, 0)), ((1, 2), (0, 1))]
ok("Theorem 5.1  U1 = T^2 J, U2 = T^2 J M (det -1, square of trace 6), U3 = T^2",
   U == [mm(T2, J), mm(mm(T2, J), M), T2] and D_of(U[0]) == 0 and det(U[1]) == -1 and trace(mm(U[1], U[1])) == 6)
def parent(x, y): return ((x - 2*y, y), 2) if x > 3*y else ((y, x - 2*y), 1) if x > 2*y else ((y, 2*y - x), 0)
good = True; cnt = 0
for x in range(2, 300):
    for y in range(1, x):
        if lead(x, y) and (x, y) != (2, 1):
            cnt += 1; q, j = parent(x, y); good &= lead(*q) and mv(U[j], q) == (x, y) and sum(q) < x + y
            good &= not any(lead(*mv(inv(U[i]), (x, y))) for i in range(3) if i != j)
ok("Theorem 5.1  every leading root but (2,1) has exactly one parent, of smaller sum [%d roots]" % cnt, good)
seen = {(2, 1)}; front = [(2, 1)]; norep = True
for _ in range(7):
    front = [mv(V, r) for r in front for V in U]; norep &= len(set(front)) == len(front) and not (set(front) & seen); seen |= set(front)
ok("Theorem 5.1  seven levels: %d leading roots, none twice; maps of the space whole" % len(seen),
   norep and len(seen) == 3280 and all(lead(*r) for r in seen) and all(whole_co(L(V, X)) and eta(L(V, X), L(V, X)) == eta(X, X) for V in U for X in E3))
S13 = {(2, 1)}
for _ in range(8): S13 |= {mv(V, r) for r in S13 for V in (U[0], U[2])}
ok("Remark 5.2  NEG without the middle branch (5,2), cut (29;21,20), is not reached", (5, 2) not in S13 and mv(U[1], (2, 1)) == (5, 2))

# ---- Section 6
def values(X, N, Rr): return {v for v in (read(X, p) for p in product(range(-Rr, Rr + 1), repeat=2)) if abs(v) <= N}
small = [A for A in SL if max(abs(c) for r in A for c in r) < 4][:5]
ok("Proposition 6.2  readers of one class read the same numbers", all(values(X, 60, 40) == values(L(A, X), 60, 160) for X in [E3[0], (3, 1, 1), point((1, 1, 6))] for A in small))
Xa, Xb = (3, -2, 0), point((2, 2, 3))
ok("Proposition 6.2  NEG two readers of even form 5 read different numbers (1 and 2)",
   eta(Xa, Xa) == 5 == eta(Xb, Xb) and 1 in values(Xa, 9, 9) and 1 not in values(Xb, 9, 9) and 2 in values(Xb, 9, 9) and 2 not in values(Xa, 9, 9))
ok("Theorem 6.3  inside: positive, = eta(sigma X, c psi); on the cone: 2<chi,psi>^2; outside: both signs",
   all(read(X, p) > 0 and read(X, p) == eta(sigma(X), cut(p)) for X in [E3[0], (3, 1, 1), point((1, 1, 1)), point((2, 1, 3))] for p in ROOTS if p != (0, 0))
   and all(read(cut(c), p) == 2*inner(c, p)**2 for c in ROOTS[::31] for p in ROOTS[::17])
   and read(E3[1], (1, 1)) == 0 and all(read((1, 2, 0), p) != 0 for p in ROOTS if p != (0, 0)) and {1, -1} <= values((1, 2, 0), 3, 5) | values(E3[1], 3, 5))
def reduced(D):                      # reduced primitive readers [A,B,C] with 4AC - B^2 = -D
    return [(A, B, (B*B - D)//(4*A)) for A in range(1, isqrt(-D//3) + 1) for B in range(-A, A + 1) if (B*B - D) % (4*A) == 0
            and (B*B - D)//(4*A) >= A and gcd(gcd(A, B), (B*B - D)//(4*A)) == 1 and not (B < 0 and (A == (B*B - D)//(4*A) or -B == A))]
def reduce(f):
    A, B, C = f
    while A > C or (A == C and B < 0) or B > A or B <= -A:
        if A > C or (A == C and B < 0): A, B, C = C, -B, A
        else: k = (A - B)//(2*A); C = A*k*k + B*k + C; B += 2*k*A
    return (A, B, C)
TABLE = {-3: 1, -4: 1, -7: 1, -8: 1, -11: 1, -12: 1, -15: 2, -16: 1, -19: 1, -20: 2, -23: 3, -24: 2, -28: 1, -31: 3, -32: 2, -39: 4, -44: 3}
RED = {D: reduced(D) for D in TABLE}
ok("Theorem 6.4  moved readers reduce back; 3A^2 <= 4 eta; the table inside the cone",
   all(reduce(form(L(A, point(f)))) == f and 3*f[0]**2 <= -D for D in RED for f in RED[D] for A in SL[:12]) and all(len(RED[D]) == TABLE[D] for D in TABLE))
ok("Theorem 6.4  NEG no change of view with entries up to 4 relates two reduced readers (even forms 5, 23/4)",
   not any(form(L(((p, q), (r, s)), point(f))) == g for D in (-20, -23) for f, g in combinations(RED[D], 2)
           for p, q, r, s in product(range(-4, 5), repeat=4) if p*s - q*r == 1))
def cycles(D):                       # outside the cone: cycles of reduced readers, D = -4 eta > 0
    s = isqrt(D); red = {(a, B, -(D - B*B)//(4*a)) for B in range(1, s + 1) if (D - B*B) % 4 == 0 for A in divs((D - B*B)//4) for a in (A, -A)
                         if abs(s - 2*A) < B and gcd(gcd(A, B), (D - B*B)//(4*A)) == 1}
    def nxt(f):
        C = f[2]; Bp = (-f[1]) % (2*abs(C))
        while Bp <= s - 2*abs(C): Bp += 2*abs(C)
        while Bp > s: Bp -= 2*abs(C)
        return (C, Bp, (Bp*Bp - D)//(4*C))
    seen = set(); n = 0
    for f in sorted(red):
        n += f not in seen
        while f not in seen: seen.add(f); f = nxt(f)
    return n
ok("Theorem 6.4  the table outside the cone", [cycles(D) for D in (5, 8, 12, 13, 17, 21, 24, 28, 40, 60)] == [1, 1, 2, 1, 1, 2, 2, 2, 2, 4])
ok("Proposition 6.5  exactly one reduced reader reads 1: [1,0,n] or [1,1,(4n+1)/4]", all([f for f in RED[D] if f[0] == 1] == [(1, D % 2, (D % 2 - D)//4)] for D in RED))
def classes_reading(D, n): return {f for f in RED[D] if any(f[0]*x*x + f[1]*x*y + f[2]*y*y == n for x in range(-40, 41) for y in range(-40, 41))}
def mirror(f): return reduce((f[0], -f[1], f[2]))
good = True
for D in (-15, -20, -23, -31, -39, -44):
    for p in range(2, 120):
        if prime(p) and D % p:
            cl = classes_reading(D, p)
            good &= (len(cl) > 0) == any((b*b - D) % (4*p) == 0 for b in range(2*p)) and (not cl or cl == {min(cl), mirror(min(cl))})
ok("Propositions 6.6, 6.7  a prime is read iff -4 eta is a square on the 4p-loop, by one class and its mirror", good)
ok("Proposition 6.7  NEG 5 has type -1 on the 23-loop and is not read", typ(23, 5) == -1 and not classes_reading(-23, 5))

# ---- Section 7
def own(X): return mm(J, Gam(X))
ok("Theorem 7.1  S_X^2 = -eta; reading of (x+yS_X)psi = (x^2 + eta y^2) reading of psi",
   all(trace(own(X)) == 0 and mm(own(X), own(X)) == ((-eta(X, X), 0), (0, -eta(X, X))) for X in PTS)
   and all(read(X, mv(lin(x, y, own(X)), p)) == (x*x + eta(X, X)*y*y)*read(X, p) for X in PTS for x in range(-3, 4) for y in range(-3, 4) for p in ROOTS[::41]))
ok("Theorem 7.1  NEG fails with the own turn of another reader", read(Xa, mv(lin(1, 1, own(Xb)), (1, 0))) != 6*read(Xa, (1, 0)))
def fixers(X): return sorted(A for A in (((p, q), (r, s)) for p, q, r, s in product(range(-8, 9), repeat=4) if p*s - q*r == 1) if L(A, X) == X)
def units(X):                        # (m + 2y S^T)/2 with m^2 + 4 eta y^2 = 4
    S = tr(own(X))
    return sorted(tuple(tuple(int(Fr(m*I2[i][j], 2) + y*S[i][j]) for j in range(2)) for i in range(2))
                  for y in range(-9, 10) for m in range(-40, 41) if m*m + 4*eta(X, X)*y*y == 4)
ok("Corollary 7.2  fixers = own numbers of size one: 6, 4, 2, 2, 2 of them; outside the cone they are boosts",
   all(fixers(X) == units(X) and len(units(X)) == w for X, w in [(point((1, 1, 1)), 6), (E3[0], 4), (point((1, 1, 2)), 2), (Xa, 2), (point((2, 1, 3)), 2)])
   and ((2, 3), (1, 2)) in fixers((1, 2, 0)) and set(fixers((1, 2, 0))) <= set(units((1, 2, 0))) and all(D_of(A) > 0 for A in fixers((1, 2, 0)) if A not in (I2, NEG)))
def Xc(c): return (Fr(1 - c, 2), Fr(1 + c, 2), 0)
def prodc(z, w, c): return (z[0]*w[0] + c*z[1]*w[1], z[0]*w[1] + z[1]*w[0])
ok("Theorem 7.3  own numbers of X_c = product with constant c; readings multiply; X_c = e, h+, b for c = -1, 0, 1",
   all(eta(Xc(c), Xc(c)) == -c and mv(lin(z[0], z[1], own(Xc(c))), w) == prodc(z, w, c) and read(Xc(c), prodc(z, w, c)) == read(Xc(c), z)*read(Xc(c), w)
       for c in range(-7, 8) for z in ROOTS[::53] for w in ROOTS[::37]) and [Xc(-1), Xc(0), Xc(1)] == [E3[0], (Fr(1, 2), Fr(1, 2), 0), E3[1]])
def beta(p, q): return (p[0]*q[0] + p[1]*q[1], p[0]*q[0] - p[1]*q[1], p[0]*q[1] + q[0]*p[1])
ok("Proposition 7.4  triangle equality of two readings",
   all(read(X, p)*read(X, q) == inner(X, beta(p, q))**2 + eta(X, X)*eta(cut(p), cut(q))/2 and eta(cut(p), cut(q)) == 2*(p[0]*q[1] - p[1]*q[0])**2
       for X in PTS for p in ROOTS[::43] for q in ROOTS[::47]))
def prodV(X, Y, c): return (X[0]*Y[0] + c*(X[1]*Y[1] + X[2]*Y[2]), X[0]*Y[1] + Y[0]*X[1], X[0]*Y[2] + Y[0]*X[2])
ok("Remark 7.5  NEG no product of the space keeps the even form 5; ledger squares have even form 25",
   all(any(eta(prodV(P, Q, c), prodV(P, Q, c)) != 5 for P, Q in ((Xa, Xa), (Xa, Xb), (Xb, Xb))) for c in (-1, 0, 1)) and eta(prodV(Xb, Xb, 1), prodV(Xb, Xb, 1)) == 25)

# ---- Section 8
def counts(f, N):
    A, B, C = f; D = B*B - 4*A*C; r = [0]*(N + 1)
    for x in range(-isqrt(4*N*C//(-D)) - 2, isqrt(4*N*C//(-D)) + 3):
        for y in range(-isqrt(4*N*A//(-D)) - 2, isqrt(4*N*A//(-D)) + 3):
            v = A*x*x + B*x*y + C*y*y
            if 0 < v <= N: r[v] += 1
    return r
NM = 400; RC = {D: {f: counts(f, NM) for f in RED[D]} for D in (-3, -4, -7, -8, -15, -20, -23)}
def net(N, n): return sum(typ(N, d) for d in divs(n))
for D in RC:
    w = {-3: 6, -4: 4}.get(D, 2)
    ok("Theorem 8.1  even form %s, %d class(es): count = %d x net on the loop of %d steps, m <= %d" % (Fr(-D, 4), len(RED[D]), w, -D, NM),
       all(sum(RC[D][f][n] for f in RED[D]) == w*net(-D, n) for n in range(1, NM + 1)))
ok("Theorem 8.1  NEG the wrong loop (4 for even form 2) and the wrong weight (2 for e) fail",
   any(RC[-8][(1, 0, 2)][n] != 2*net(4, n) for n in range(1, NM)) and any(RC[-4][(1, 0, 1)][n] != 2*net(4, n) for n in range(1, NM)))
def leg(N, a): return 0 if a % N == 0 else (1 if pow(a, (N - 1)//2, N) == 1 else -1)
def netq(N, n): return sum(leg(N, d) for d in divs(n))
def netd(N, n, k): return net(N, n//k) if n % k == 0 else 0
NB = 2000; c11 = counts((1, 1, 3), NB); c19 = counts((1, 1, 5), NB); c3 = counts((1, 0, 3), NB); c3b = counts((2, 2, 2), NB); c4 = counts((1, 0, 4), NB); c4b = counts((2, 0, 2), NB)
ok("Remark 8.3  even forms 11/4 and 19/4: one class, count = 2 x net on the loop of 11, of 19 steps, m <= %d" % NB,
   reduced(-11) == [(1, 1, 3)] and reduced(-19) == [(1, 1, 5)] and all(c11[n] == 2*netq(11, n) and c19[n] == 2*netq(19, n) for n in range(1, NB + 1)))
ok("Remark 8.3  even forms 3 and 4: every reader's count is a ledger typed on the loop of 3, of 4 steps, m <= %d" % NB,
   all(c3[n] == 2*net(3, n) + 4*netd(3, n, 4) and c3b[n] == 6*netd(3, n, 2) and c4b[n] == 4*netd(4, n, 2)
       and c4[n] == (2*net(4, n) if n % 2 else 0 if n % 4 else 4*netd(4, n, 4)) for n in range(1, NB + 1)))
ok("Remark 8.3  NEG at even form 3 the equation of Theorem 8.1 fails at m = 2", c3[2] != 2*sum(leg(3, d)*(1 if d % 2 else 0) for d in divs(2)))
def two(N, n): return sum(typ(N, d)*typ5(n//d) for d in divs(n))
ok("Proposition 8.2  two-loop ledgers at even forms 5 and 15/4, m <= %d; primes at 1,9 / 3,7 on the 20-loop" % NM,
   all(RC[-20][(1, 0, 5)][n] == net(20, n) + two(4, n) and RC[-20][(2, 2, 3)][n] == net(20, n) - two(4, n)
       and RC[-15][(1, 1, 4)][n] == net(15, n) + two(3, n) and RC[-15][(2, 1, 2)][n] == net(15, n) - two(3, n) for n in range(1, NM + 1))
   and all((RC[-20][(1, 0, 5)][p] > 0) == (p % 20 in (1, 9)) and (RC[-20][(2, 2, 3)][p] > 0) == (p % 20 in (3, 7)) for p in range(3, NM) if prime(p) and p != 5))

# ---- Section 9
X1, X2, X2m = (1, 1, 6), (2, 1, 3), (2, -1, 3)
ok("Theorem 9.1(a)  three classes at 23/4; every class at a smaller even form is its own mirror",
   sorted(RED[-23]) == [X1, X2m, X2] and mirror(X2) == X2m and all(mirror(f) == f for D in range(-3, -23, -1) if D % 4 < 2 for f in reduced(D)))
def by_one(p): return any(is_sq(4*p - 23*y*y) and (isqrt(4*p - 23*y*y) - y) % 2 == 0 for y in range(isqrt(4*p//23) + 1))
PM = 120000; sv = bytearray([1])*(PM + 1); sv[0] = sv[1] = 0
for i in range(2, isqrt(PM) + 1):
    if sv[i]: sv[i*i::i] = bytearray(len(sv[i*i::i]))
PR = [p for p in range(2, PM + 1) if sv[p]]
PLUS = [p for p in PR if typ(23, p) == 1]; MINUS = [p for p in PR if typ(23, p) == -1]; ONE = [p for p in PLUS if by_one(p)]; ONES = set(ONE)
ok("Theorem 9.1(b)  type +1 primes below 400: read on (4,0,0) or (0,2,2) whole roots; type -1: on none",
   all((RC[-23][X1][p], RC[-23][X2][p], RC[-23][X2m][p]) in ((4, 0, 0), (0, 2, 2)) and (RC[-23][X1][p] > 0) == by_one(p) for p in PLUS if p < NM)
   and all(RC[-23][f][p] == 0 for f in RED[-23] for p in MINUS if p < NM))
ok("Theorem 9.1(c)  2, 13, 59 have type +1; 13 and 59 at one loop point; X1 reads 59 at (5,2), not 2, not 13",
   typ(23, 2) == typ(23, 13) == typ(23, 59) == 1 and 59 % 23 == 13 and read(point(X1), (5, 2)) == 59 and not by_one(2) and not by_one(13))
bad = []
for n in range(1, 1001):
    sT = set(); sF = set(); found = False
    for p in PLUS:
        mine, other = (sT, sF) if p in ONES else (sF, sT); mine.add(p % n)
        if p % n in other: found = True; break
    if not found: bad.append(n)
ok("Proposition 9.2  every loop of up to 1000 steps has a point with a prime read by X1 and one not read", bad == [])
ok("Proposition 9.2  X1 reads %d of the %d primes of type +1 below %d; first 59, 101, 167, 173, 211, 223" % (len(ONE), len(PLUS), PM),
   len(ONE) == 1858 and len(PLUS) == 5628 and ONE[:6] == [59, 101, 167, 173, 211, 223] and [p for p in PLUS if p not in ONES][:7] == [2, 3, 13, 29, 31, 41, 47])
def sols(p, c2): return sum(1 for x in range(p) if (x*x*x - c2*x*x - x - 1) % p == 0)
ok("Theorem 9.3(a)  primes below 3000: x^3 = x+1 has 3 / 0 / 1 solutions for X1 / the others / type -1",
   all(sols(p, 0) == (3 if p in ONES else 0) for p in PLUS if p < 3000) and all(sols(p, 0) == 1 for p in MINUS if p < 3000))
NN = 3000; pol = [1] + [0]*NN
for n in range(1, NN + 1):
    for st in (n, 23*n):
        for k in range(NN, st - 1, -1): pol[k] -= pol[k - st]
a = [0] + pol[:NN]; r0 = counts(X1, NN); r1 = counts(X2, NN)
ok("Theorem 9.3(b)  r1 - r2 = 2a for m <= 3000; r1 = (S+4a)/3, r2 = (S-2a)/3, multiples of 23 included; a(p) = 2, -1, 0; a multiplies",
   all(r0[n] - r1[n] == 2*a[n] for n in range(1, NN + 1)) and all(3*r0[n] == 2*net(23, n) + 4*a[n] and 3*r1[n] == 2*net(23, n) - 2*a[n] for n in range(1, NN + 1))
   and all(a[p] == (2 if p in ONES else -1) for p in PLUS if p < 3000) and all(a[p] == 0 for p in MINUS if p < 3000)
   and all(a[m*n] == a[m]*a[n] for m in range(1, 54) for n in range(1, 54) if gcd(m, n) == 1))
ok("Theorem 9.3  NEG a(m) does not repeat on the loop of 23 nor of 552 steps", any(a[n] != a[n + 23] for n in range(1, 500)) and any(a[n] != a[n + 552] for n in range(1, 2000)))
R44 = {f: counts(f, 2000) for f in RED[-44]}
ok("Proposition 9.4  even form 11: three classes with whole coordinates; 47 read, 3 not; least whole even form",
   sorted(RED[-44]) == [(1, 0, 11), (3, -2, 4), (3, 2, 4)] and reduce(form((4, -1, 2))) == (3, -2, 4) and reduce(form((4, -1, -2))) == (3, 2, 4)
   and 47 % 44 == 3 and typ(44, 3) == 1 and read((6, -5, 0), (6, 1)) == 47 and R44[(1, 0, 11)][3] == 0
   and all(mirror(f) == f for n in range(1, 11) for f in reduced(-4*n)))
ok("Proposition 9.4  type +1 primes below 2000: read by (6;-5,0) iff x^3 = x^2+x+1 has three solutions",
   all((R44[(1, 0, 11)][p] > 0) == (sols(p, 1) == 3) for p in PR if p < 2000 and typ(44, p) == 1))

# ---- Section 10 (total dimension 4; complex numbers with whole coordinates are exact in floats here)
def cutC(p): x, y = p; u = 2*x*y.conjugate(); return tuple(round(v) for v in (abs(x)**2 + abs(y)**2, abs(x)**2 - abs(y)**2, u.real, u.imag))
def eta4(X): return X[0]**2 - X[1]**2 - X[2]**2 - X[3]**2
GI = [complex(p, q) for p in range(-4, 5) for q in range(-4, 5)]; TAL = {}
for p in product(GI, repeat=2): TAL.setdefault(cutC(p), []).append(p)
def ggcd(p, q):
    while q != 0: k = p/q; p, q = q, p - complex(round(k.real), round(k.imag))*q
    return p
def kk(X): w = complex(X[2]//2, X[3]//2); return isqrt(round(abs(ggcd(ggcd(complex((X[0] + X[1])//2), complex((X[0] - X[1])//2)), ggcd(w, w.conjugate())))**2))
CONE4 = [(t, a_, u1, u2) for t in range(1, 17) for a_ in range(-t, t + 1) if (t - a_) % 2 == 0 for u1 in range(-t, t + 1) if u1 % 2 == 0
         for u2 in range(-t, t + 1) if u2 % 2 == 0 and t*t == a_*a_ + u1*u1 + u2*u2]
ok("Theorem 10.1  the cut k c(psi0) has 4 x net of the type ledger of k whole roots [%d cone points]" % len(CONE4),
   all(len(TAL.get(X, [])) == 4*net(4, kk(X)) for X in CONE4) and all(eta4(X) == 0 and (X[0] - X[1]) % 2 == 0 and X[2] % 2 == 0 == X[3] % 2 for X in TAL))
ok("Theorem 10.1  NEG (3;3,0,0) has no whole root, (5;5,0,0) has 8", (3, 3, 0, 0) not in TAL and len(TAL[(5, 5, 0, 0)]) == 8)
def gam4(X): return ((X[0] + X[1], complex(X[2], X[3])), (complex(X[2], -X[3]), X[0] - X[1]))
def L4(A, X): m = mm(mm(A, gam4(X)), tuple(tuple(complex(A[j][i]).conjugate() for j in range(2)) for i in range(2))); return ((m[0][0].real + m[1][1].real)/2, (m[0][0].real - m[1][1].real)/2, m[0][1].real, m[0][1].imag)
Tc = ((1, 1j), (0, 1)); AC = [word([J, T, Tc, Ti, ((1, -1j), (0, 1))], random.randint(1, 6)) for _ in range(30)]
SAMP = [(x, y) for x in GI[::7] for y in GI[::5]][:40]
ok("Proposition 10.2  c(A psi) = L_A c(psi), even form kept; shears along 1 and i commute, not with J; i moves no cut",
   all(tuple(float(v) for v in cutC(mv(A, p))) == L4(A, cutC(p)) for A in AC for p in SAMP) and all(eta4(L4(A, X)) == eta4(X) for A in AC for X in [(1, 0, 0, 0), (2, 1, -1, 3)])
   and mm(T, Tc) == mm(Tc, T) and mm(Tc, J) != mm(J, Tc) and all(cutC((1j*p[0], 1j*p[1])) == cutC(p) for p in SAMP))

Di = mm(mm(mm(mm(mm(((1, -1j), (0, 1)), J), Tc), J), ((1, -1j), (0, 1))), J)
ok("Proposition 10.2  diag(i,-i) is a word in J and the shear along i; L_A = identity on a spanning set only for +-1 among the samples",
   Di in (((1j, 0), (0, -1j)), ((-1j, 0), (0, 1j)))
   and all(all(L4(A, X) == tuple(float(v) for v in X) for X in [(1, 0, 0, 0), (0, 1, 0, 0), (0, 0, 1, 0), (0, 0, 0, 1)]) == (A in (I2, NEG)) for A in AC + [Di, I2, NEG]))

# ---- Section 12
def theta(X, s): return sum(exp(-pi*s*float(read(X, p))) for p in product(range(-60, 61), repeat=2))
ok("Proposition 12.1  (floating point) Theta(1/(eta s)) = s sqrt(eta) Theta(s)",
   all(abs(theta(X, 1/(float(eta(X, X))*s)) - s*sqrt(float(eta(X, X)))*theta(X, s)) < 1e-9 for X in [E3[0], Xa, point(X2), point(X1)] for s in (0.3, 0.45, 0.8)))
ok("Proposition 12.1  NEG fails with the wrong even form in the exchange", abs(theta(Xa, 1/(4*0.45)) - 0.45*sqrt(5)*theta(Xa, 0.45)) > 1e-3)
print("%d checks; %s" % (NCHK[0], "all pass" if not FAILED else "FAILED: %s" % FAILED))
