# verify_law_of_squares.py -- checks for Paper 11, "The Law of Squares".
# Exact arithmetic; floating point only where a net is evaluated.
# A ledger on the M-loop is a list of M weights; the product adds steps.
import math, cmath, itertools, random
import numpy as np
from fractions import Fraction as Fr
random.seed(11); count = 0; fails = []
def check(name, cond):
    global count; count += 1
    if not cond: fails.append(name)
    print(("PASS  " if cond else "FAIL  ") + name)
def isprime(n): return n > 1 and all(n % d for d in range(2, int(n**.5) + 1))
def primes(a, b): return [n for n in range(a, b) if isprime(n)]
def divs(n): return [d for d in range(1, n + 1) if n % d == 0]
def pf(n):                              # prime factors, with repeats
    r = []; d = 2
    while n > 1:
        while n % d == 0: r.append(d); n //= d
        d += 1
    return r
def phi(n): return sum(1 for k in range(n) if math.gcd(k, n) == 1)
def sign(b): f = pf(b); return 0 if len(set(f)) < len(f) else (-1)**len(f)
def returns(p, c):                      # runs after which "run p times" returns on the c-loop
    return next(f for f in range(1, c + 1) if pow(p, f, c) == 1 % c)
def mul(a, b, M, mod=None):
    r = [0]*M
    for i, x in enumerate(a):
        if x:
            for j, y in enumerate(b): r[(i + j) % M] += x*y
    return [x % mod for x in r] if mod else r
def add(a, b): return [x + y for x, y in zip(a, b)]
def sc(c, a): return [c*x for x in a]
def red(a, p): return [x % p for x in a]
def pt(k, M): return [1 if j == k % M else 0 for j in range(M)]
def run(a, j, M):                       # run the loop j times
    r = [0]*M
    for k, x in enumerate(a): r[j*k % M] += x
    return r
def whole(d, M): return [Fr(1, d) if k % (M//d) == 0 else Fr(0) for k in range(M)]
def power(a, e, M, mod=None):
    r = pt(0, M)
    for _ in range(e): r = mul(r, a, M, mod)
    return r
def loopM(n): return n if n % 2 else 2*n
def subloops(n): return [c for c in divs(loopM(n)) if (c > 1 if n % 2 else c > 2)]
def toA(a, n):                          # normal form in A_n: apply the law q_n = 0
    M = loopM(n); m = M//n; a = list(a)
    for k in range(M - 1, m*(n - 1) - 1, -1):
        c, a[k] = a[k], 0
        for j in range(1, n): a[k - m*j] -= c
    return a[:m*(n - 1)]
def qlaw(n): m = loopM(n)//n; return [1 if k % m == 0 else 0 for k in range(m*(n - 1) + 1)]
def piece(c, M):                        # the signed whole eta_c
    r = whole(M//c, M)
    for p in set(pf(c)): r = mul(r, add(pt(0, M), sc(-1, whole(M*p//c, M))), M)
    return r
def rnd(M, r=5): return [random.randint(-r, r) for _ in range(M)]
def pmul(a, b, mod=None):               # laws: lists of weights, lowest power first
    r = [0]*(len(a) + len(b) - 1)
    for i, x in enumerate(a):
        for j, y in enumerate(b): r[i + j] += x*y
    return red(r, mod) if mod else r
def law(c):                             # law of piece c: prod (t^b - 1)^sign(c/b), b | c
    num = [1]; den = [1]; q = []
    for b in divs(c):
        f = [-1] + [0]*(b - 1) + [1]
        if sign(c//b) == 1: num = pmul(num, f)
        if sign(c//b) == -1: den = pmul(den, f)
    while len(num) >= len(den):         # exact division; den has leading weight 1
        k = num[-1]; q.insert(0, k)
        for i in range(len(den)): num[len(num) - len(den) + i] -= k*den[i]
        num.pop()
    return q
def squares(p): return [sum(1 for k in range(p) if k*k % p == s) for s in range(p)]
def ty(a, p):                           # square type of a on the p-loop, by brute force
    return 0 if a % p == 0 else (1 if any((k*k - a) % p == 0 for k in range(1, p)) else -1)
def ty4(a): return 0 if a % 2 == 0 else (1 if a % 4 == 1 else -1)     # height +1, width -1
def u(x): return cmath.exp(2j*math.pi*x)
def rd(w, j): M = len(w); return sum(w[k]*u(j*k/M) for k in range(M))    # a reading

# ---- Setting; pieces
g = True
for M in (5, 6, 8, 12):
    x, y = rnd(M), rnd(M)
    g &= all(abs(rd(mul(x, y, M), j) - rd(x, j)*rd(y, j)) < 1e-8 for j in range(M))
    g &= all(abs(rd(whole(d, M), j) - (j % d == 0)) < 1e-9 for d in divs(M) for j in range(M))
check("Proposition 2.1: readings multiply; the whole of d steps reads [d divides j]", g)
g = True
for M in list(range(2, 31)) + [36, 60]:
    E = {c: piece(c, M) for c in divs(M)}; s = [Fr(0)]*M
    for c in E:
        s = add(s, E[c]); mob = [Fr(0)]*M
        for b in divs(c): mob = add(mob, sc(sign(c//b), whole(M//b, M)))
        g &= mob == E[c] and E[c][0] == Fr(phi(c), M) and mul(E[c], E[c], M) == E[c]
        g &= all(mul(E[c], E[d], M) == [0]*M for d in E if d != c)
    g &= s == pt(0, M)
check("Theorem 3.3: signed wholes eta_c, zero products, sum the unit, signs, phi(c)/M", g)
g = True
for n in range(2, 41):
    M = loopM(n); s = [Fr(0)]*M; q = [1]
    for c in subloops(n): s = add(s, piece(c, M)); q = pmul(q, law(c))
    g &= s == add(pt(0, M), sc(-1, whole(n, M))) and q == qlaw(n) and len(law(n)) == phi(n) + 1
    g &= (len(subloops(n)) == 1) == isprime(n)
    g &= len(subloops(n)) == (len(divs(n)) - 1 if n % 2 else len(divs(2*n)) - 2)
check("Theorem 3.4: A_n = sum of pieces, q_n = product of laws, one piece iff n prime", g)
a4, b4 = [1, 0, 1, 0, 0, 0, 0, 0], [1, 0, 0, 0, 1, 0, 0, 0]
check("Theorem 3.4 NEG: zero divisors for n = 4: (1 + t^2)(1 + t^4) = 0",
      not any(toA(mul(a4, b4, 8), 4)) and any(toA(a4, 4)) and any(toA(b4, 4)))
g = True
for M in (6, 8, 12, 30):
    D = divs(M); E = [piece(c, M) for c in D]; cnt = 0
    for bits in itertools.product((0, 1), repeat=len(D)):
        s = [sum(b*e[k] for b, e in zip(bits, E)) for k in range(M)]
        if any(s) and min(s) >= 0: cnt += 1; g &= any(s == whole(d, M) for d in D)
    g &= cnt == len(D)
check("Proposition 3.5: signed wholes with no negative weight are the wholes of sub-loops", g)
# ---- symmetries
g = True
for n in range(2, 21):
    M = loopM(n); J = [j for j in range(1, M) if math.gcd(j, M) == 1]; img = set()
    types = [(M//n)*(k + 1) - 1 for k in range(n)]
    for j in J:
        x, y = rnd(M), rnd(M); img.add(tuple(toA(run(pt(1, M), j, M), n)))
        g &= run(mul(x, y, M), j, M) == mul(run(x, j, M), run(y, j, M), M)
        g &= not any(toA(run(mul(qlaw(n) + [0]*(M - len(qlaw(n))), x, M), j, M), n))
        g &= sorted(j*e % M for e in types) == sorted(types)
        g &= all(run(run(x, j, M), k, M) == run(x, j*k % M, M) for k in J)
    g &= len(img) == len(J) == phi(M)
check("Theorem 4.2: runs respect products and the law, permute types, commute", g)
check("Theorem 4.2 NEG: a run sharing a factor with the loop length collapses two points",
      run(pt(1, 6), 2, 6) == run(pt(4, 6), 2, 6))
def all_sym(n):
    cs = subloops(n)
    return math.prod(phi(c) for c in cs) * 2**sum(1 for c in cs if c % 2 and 2*c in cs)
check("Remark 4.3: A_15: 64 symmetries, 8 runs; A_6: 64 and 4; equal counts iff n prime",
      all_sym(15) == 64 and phi(15) == 8 and all_sym(6) == 64 and phi(12) == 4
      and all((all_sym(n) == phi(loopM(n))) == isprime(n) for n in range(2, 61)))
nt = lambda a: [a[0], -a[1]]
check("Remark 4.3 NEG: on the 2-loop t -> -t respects products and is not a run",
      nt(mul([3, 5], [-2, 7], 2)) == mul(nt([3, 5]), nt([-2, 7]), 2) and nt([0, 1]) == [0, -1])
# ---- a prime as a symmetry
g = all(power(x, p, M, p) == red(run(x, p, M), p)
        for M in range(2, 25) for p in (2, 3, 5, 7, 11) for x in [rnd(M, 9)])
check("Theorem 5.1: reduced by p, the p-th power is the loop run p times (M <= 24)", g)
x7 = lambda M: [1, 1] + [0]*(M - 2)
neg = sum(1 for M in (7, 12, 15) for p in (3, 5, 7) for j in range(M)
          if j != p % M and power(x7(M), p, M, p) == red(run(x7(M), j, M), p))
check("Theorem 5.1 NEG: no other run does this; the powers 4 and 6 are not runs",
      neg == 0 and all(power(x7(11), m, 11, m) != red(run(x7(11), m, 11), m) for m in (4, 6)))
def cycles(M, p, cs):                   # cycles of the run on the sub-loops cs
    seen = set(); r = 0
    for k in range(M):
        if M//math.gcd(k, M) in cs and k not in seen:
            r += 1
            while k not in seen: seen.add(k); k = k*p % M
    return r
def signed_wholes(n, p):                # count x with x*x = x in A_n reduced by p
    M = loopM(n); dim = (M//n)*(n - 1); r = 0
    for x in itertools.product(range(p), repeat=dim):
        xx = list(x) + [0]*(M - dim)
        r += red(toA(mul(xx, xx, M), n), p) == list(x)
    return r
g = True
CASES = [(3, 2), (5, 2), (7, 2), (9, 2), (15, 2), (4, 3), (5, 3), (7, 3), (3, 5), (4, 5)]
for n, p in CASES:
    r = sum(phi(c)//returns(p, c) for c in subloops(n))
    g &= signed_wholes(n, p) == 2**r and r == cycles(loopM(n), p, subloops(n))
check("Theorem 5.2: A_n/p has sum of phi(c)/f_c pieces = cycles of the run (10 cases)", g)
check("Theorem 5.2(4): n = 2: two pieces for a height prime (5), one for a width prime (3)",
      signed_wholes(2, 5) == 4 and signed_wholes(2, 3) == 2 and [phi(4)//returns(p, 4) for p in (5, 3)] == [2, 1])
check("Theorem 5.2 NEG: for n = 15, p = 2 there are 4 pieces, not phi(15)/f = 2",
      sum(phi(c)//returns(2, c) for c in subloops(15)) == 4 and phi(15)//returns(2, 15) == 2)
def pdivmod(a, b, p):                   # division of laws with weights reduced by p
    a = a[:]; q = [0]*max(1, len(a) - len(b) + 1); inv = pow(b[-1], p - 2, p)
    while len(a) >= len(b):
        c = a[-1]*inv % p; d = len(a) - len(b); q[d] = c
        for i, y in enumerate(b): a[i + d] = (a[i + d] - c*y) % p
        while a and a[-1] == 0: a.pop()
    return q, a
def pgcd(a, b, p):
    while b: a, b = b, pdivmod(a, b, p)[1]
    return a
def piece_dims(f, p):                   # dimensions of the pieces of a law without repeats
    f = red(f, p); out = []; d = 1; h = [0, 1]
    while len(f) - 1 >= 2*d:
        hp = [1]
        for _ in range(p): hp = pdivmod(pmul(hp, h, p), f, p)[1]
        h = hp; diff = red(h + [0]*(2 - len(h)), p); diff[1] = (diff[1] - 1) % p
        while diff and diff[-1] == 0: diff.pop()
        gg = pgcd(f, diff, p) if diff else f
        k = (len(gg) - 1)//d; out += [d]*k
        if k: f = pdivmod(f, gg, p)[0]; h = pdivmod(h, f, p)[1] if len(f) > 1 else [0]
        d += 1
    return sorted(out + ([len(f) - 1] if len(f) > 1 else []))
g = True; cases = 0
for n, p in itertools.product(range(2, 31), (2, 3, 5, 7, 11, 13)):
    if loopM(n) % p:
        want = sorted(sum(([returns(p, c)]*(phi(c)//returns(p, c)) for c in subloops(n)), []))
        g &= sorted(sum((piece_dims(law(c), p) for c in subloops(n)), [])) == want; cases += 1
check("Theorem 5.2: the pieces over the c-loop have dimension f_c, by factoring (%d cases)" % cases, g)
g = True
for c1, p, b in itertools.product((1, 2, 3, 4, 5, 7, 9), (2, 3, 5), (1, 2)):
    if c1 % p:
        r = [1]
        for _ in range(phi(p**b)): r = pmul(r, law(c1), p)
        g &= red(law(c1*p**b), p) == r
for n, p in itertools.product(range(2, 31), (2, 3, 5)):
    M = loopM(n); a = max(k for k in range(9) if M % p**k == 0); r = [1]
    for c1 in divs(M//p**a):
        for _ in range(sum(phi(p**b) for b in range(a + 1) if c1*p**b in subloops(n))):
            r = pmul(r, law(c1), p)
    g &= a == 0 or r == qlaw(n)
check("Theorem 5.3: p dividing the loop: laws repeat phi(p^b) times; q_n as stated", g)
y = add(pt(2, 6), sc(-1, pt(0, 6)))
check("Theorem 5.3 NEG: (t^2 - 1)^3 = 0 on the 6-loop reduced by 3, a non-zero ledger",
      not any(power(y, 3, 6, 3)) and any(red(y, 3)))
# ---- types
def fpart(a, c):                        # f-part of the a-th power of f when f*f = c e
    x = (1, 0)
    for _ in range(a): x = (x[1]*c, x[0])
    return x[1]
check("Proposition 6.3(1): the a-th power of f is f, -f or on the line; this type multiplies",
      all(fpart(a, -1) == ty4(a) for a in range(1, 80))
      and all(ty4(a*b) == ty4(a)*ty4(b) for a in range(1, 50) for b in range(1, 50)))
def run_type(a, p):
    g0 = toA(squares(p), p); ga = toA(run(squares(p), a, p), p)
    return 1 if ga == g0 else (-1 if ga == sc(-1, g0) else None)
check("Proposition 6.3(2): a run sends the squares ledger to +g or -g as a is a square or not",
      all(run_type(a, p) == ty(a, p) for p in primes(3, 50) for a in range(1, p)))
check("Proposition 6.3 NEG: not with the state part kept; not on the 15-loop",
      run(squares(7), 3, 7) != sc(-1, squares(7)) and run_type(2, 15) is None)
R12 = range(1, 12)
multc = lambda c: all(fpart(a*b, c) == fpart(a, c)*fpart(b, c) for a in R12 for b in R12)
check("Proposition 6.4: f-part of f^a multiplies for c = -1, 0, 1", all(map(multc, (-1, 0, 1))))
check("Proposition 6.4 NEG: not for c = 2, -2, 3", not any(map(multc, (2, -2, 3))))
g = True
for M in (5, 7, 11, 13):                # prime loops: the types are the powers of one rule
    r = next(a for a in range(2, M) if returns(a, M) == M - 1)
    dl = {pow(r, k, M): k for k in range(M - 1)}
    for e in range(M - 1):
        th = lambda a: u(e*dl[a % M]/(M - 1))
        led = [0] + [th(k).conjugate() for k in range(1, M)]
        for a in range(1, M):
            g &= all(abs(x - th(a)*y) < 1e-9 for x, y in zip(run(led, a, M), led))
            g &= abs(rd(led, a) - th(a)*rd(led, 1)) < 1e-9
check("Theorem 6.5: the ledger with the mirrored type as weights is stepped by every run", g)
led8 = [0, 1, 0, -1, 0, 1, 0, -1]        # the 4-loop type, as a type on the loop of 8 steps
check("Theorem 6.5 NEG: for j sharing a factor with M the reading need not be type(j) x net",
      run(led8, 3, 8) == sc(-1, led8) and abs(rd(led8, 2)) > 1 and abs(rd(led8, 1)) < 1e-9)
def ledger(S, step, K):                 # weight a^-2 at the point step(a) of a K-loop
    w = [Fr(0)]*K
    for a in S:
        if step(a) is not None: w[step(a) % K] += Fr(1, a*a)
    return w
P = [2, 3, 5, 7, 11, 13]; S = [1]
for p in P: S = [a*p**e for a in S for e in range(4)]
def factors(step, K):
    prod = [Fr(1)] + [Fr(0)]*(K - 1)
    for p in P: prod = mul(prod, ledger([p**e for e in range(4)], step, K), K)
    return ledger(S, step, K) == prod
dl = {pow(3, k, 7): k for k in range(6)}
t4 = lambda a: None if a % 2 == 0 else (0 if a % 4 == 1 else 1)
t7 = lambda K: (lambda a: None if a % 7 == 0 else dl[a % 7] % K)
check("Theorem 6.7: ledger of whole numbers at their types = ledger product over primes",
      factors(t4, 2) and factors(t7(2), 2) and factors(t7(3), 3) and factors(t7(6), 6))
check("Theorem 6.7 NEG: a rule that adds, or the 4-loop type with 5 moved, does not factor",
      not factors(lambda a: a % 3, 3) and not factors(lambda a: 1 if a == 5 else t4(a), 2))
distinct = lambda a: len(set(pf(a))) % 2
check("Theorem 6.7 (converse): the parity of the number of different primes factors, yet 4 is not placed at 2 x 2",
      factors(distinct, 2) and distinct(4) != (2*distinct(2)) % 2)
check("Remark 6.8: the parity of the number of prime factors factors; M and 2M share a step of the M-loop and are placed opposite (M <= 300)",
      factors(lambda a: len(pf(a)) % 2, 2) and all(len(pf(M)) % 2 != len(pf(2*M)) % 2 for M in range(2, 301)))
check("Section 6: the squares ledger has total p, the ledger of the type has total 0 (p < 60)",
      all(sum(squares(p)) == p and sum(ty(k, p) for k in range(p)) == 0 for p in primes(3, 60)))
# ---- the law of squares
PR = primes(3, 60)
check("Lemma 7.1: a^((p-1)/2) is the square type of a, weights reduced by p",
      all((pow(a, (p - 1)//2, p) - ty(a, p)) % p == 0 for p in PR for a in range(1, p)))
check("Theorem 7.2: -1 is a square on the p-loop iff p is a height prime (p < 1000)",
      all(ty(-1, p) == ty4(p) for p in primes(3, 1000)))
g = all(toA(mul(squares(p), run(squares(p), p - 1, p), p), p) == [p] + [0]*(p - 2)
        and toA(mul(squares(p), squares(p), p), p) == [ty4(p)*p] + [0]*(p - 2) for p in PR)
check("Theorem 7.3: g times its mirror image is p, and g*g = p* in A_p", g)
check("Theorem 7.3 NEG: with the state part kept, g*g is not a whole number",
      mul(squares(7), squares(7), 7) != [-7] + [0]*6)
g = True
for p, q in itertools.permutations(PR[:8], 2):
    gl = squares(p); A = toA(gl, p); lhs = red(toA(power(gl, q, p), p), q)
    g &= lhs == red(toA(run(gl, q, p), p), q) == red(sc(ty(q, p), A), q)
    g &= lhs == red(sc(ty(ty4(p)*p, q), A), q)
check("Theorem 7.4 (proof): reduced by q: g^q = g run q times = type_p(q) g = type_q(p*) g", g)
pairs = list(itertools.permutations(primes(3, 300), 2))
check("Theorem 7.4: q is a square on the p-loop iff p* is one on the q-loop (below 300)",
      all(ty(q, p) == ty(ty4(p)*p, q) for p, q in pairs))
check("Theorem 7.4: the two readings differ exactly when both are width primes",
      all(ty(q, p)*ty(p, q) == (-1 if ty4(p) == ty4(q) == -1 else 1) for p, q in pairs))
gl = squares(7)
check("Theorem 7.4 NEG: false without the star (3, 7); false for (3, 5); fails for q = 9",
      ty(7, 3) != ty(3, 7) and ty(5, 3)*ty(3, 5) != -1
      and red(toA(power(gl, 9, 7), 7), 9) != red(toA(run(gl, 9, 7), 7), 9))
cutp = lambda e, p: red(toA(power([1, 1, 0, 0], e, 4, p), 2), p)   # (1+i)^e in A_2
g = True
for p in primes(3, 400):
    ex = (p - 1)//2 if p % 4 == 1 else (p + 1)//2
    g &= cutp(p, p) == [1, ty4(p) % p] and (u(p/8).real > 0) == (ty(2, p) == 1)
    g &= ex % 2 == 0 and ty(2, p) == (-1)**(ex//2) == (1 if p % 8 in (1, 7) else -1)
check("Theorem 7.5: (1+i)^p = cut of the type of p; 2 a square iff p is 1, 7 on the 8-loop", g)
check("Theorem 7.5 NEG: '2 is a square iff p is a height prime' fails at 5; fails for p = 9",
      ty(2, 5) == -1 and cutp(9, 9) != [1, 1])
ty8 = lambda b: 0 if b % 2 == 0 else (1 if b % 8 in (1, 7) else -1)
def TN(N, b, s=1):                      # the stated product of types; s = 1 for -N, 0 for +N
    q = [x for x in pf(N) if x > 2]; a = pf(N).count(2); w = sum(1 for x in q if x % 4 == 3)
    return ty4(b)**(s + w) * ty8(b)**a * math.prod(ty(b, x) for x in q)
P3 = primes(3, 300)
check("Corollary 7.6(1): type_p(-N) and type_p(N) are the stated products, N <= 150",
      all(ty(-N, p) == TN(N, p) and ty(N, p) == TN(N, p, 0)
          for N in range(1, 151) for p in P3 if N % p))
def tauN(N, p): return 1 if any((k*k + N) % (4*p) == 0 for k in range(4*p)) else -1
def tau_formula(N, b):
    if N % 4 == 3: return math.prod(ty(b, x) for x in pf(N))
    return 0 if b % 2 == 0 else TN(N, b)
g = True
for N in [n for n in range(3, 151) if n % 4 in (0, 3)]:
    seen = {}
    for p in primes(2, 300):
        if N % p:
            g &= tauN(N, p) == tau_formula(N, p) and seen.setdefault(p % N, tauN(N, p)) == tauN(N, p)
    g &= all(tau_formula(N, b*c) == tau_formula(N, b)*tau_formula(N, c)
             and (tau_formula(N, b) == 0) == (math.gcd(b, N) > 1) for b in range(1, 40) for c in range(1, 40))
TABLE = {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]}
g &= all([b for b in range(1, N) if tau_formula(N, b) == 1] == pts for N, pts in TABLE.items())
check("Corollary 7.6(2): tau_N is a type on the N-loop for N at 0 or 3 of the 4-loop, N <= 150", g)
def on_loop(N, L):                      # is 'is -N a square on the p-loop' decided by p on the L-loop
    d = {}
    return all(d.setdefault(p % L, ty(-N, p)) == ty(-N, p) for p in P3 if N % p)
check("Corollary 7.6 NEG: for N = 5, 6, 13 the N-loop does not decide; the 4N-loop does",
      not any(on_loop(N, N) for N in (5, 6, 13)) and all(on_loop(N, 4*N) for N in (5, 6, 13)))
g = all(abs(sum(u(k*k/n) for k in range(n)) - z) < 1e-8 and abs(rd(squares(n), 1) - z) < 1e-8
        for n in range(1, 60) for z in [math.sqrt(n)*[1 + 1j, 1, 0, 1j][n % 4]])
check("Proposition 7.7: net of the squares ledger = diagonal sum of the mirror", g)
# ---- where the road stops
def cubic(a, b, p):                     # number of pieces of t^3 + a t + b = 0 reduced by p
    return {0: 1, 1: 2, 3: 3}[sum(1 for x in range(p) if (x**3 + a*x + b) % p == 0)]
def decided(a, b, M):
    d = {}
    return all(d.setdefault(p % M, cubic(a, b, p)) == cubic(a, b, p)
               for p in primes(5, 2500) if M % p)
check("Proposition 8.2: t^3 = 3t - 1 lies in the 9-loop: decided by the step of p there",
      decided(-3, 1, 9))
check("Proposition 8.2 NEG: t^3 = 2 is decided by no loop of up to 120 steps; 7 and 31",
      not any(decided(0, -2, M) for M in range(1, 121))
      and cubic(0, -2, 7) == 1 and cubic(0, -2, 31) == 3 and 31 % 24 == 7)
# ---- counting whole points
N = 500; th = [sum(1 for x in range(-30, 31) if x*x == n) for n in range(N + 1)]
def conv(a, b): return [sum(a[i]*b[n - i] for i in range(n + 1)) for n in range(N + 1)]
r = {1: th}
for k in range(2, 9): r[k] = conv(r[k - 1], th)
R = range(1, N + 1)
check("Proposition 9.2: the line: 2 x net of the divisors at the parity of their prime factors",
      all(r[1][n] == 2*sum((-1)**len(pf(d)) for d in divs(n)) for n in R))
check("Theorem 9.3: the plane: 4 x net of the divisors at their height/width types",
      all(r[2][n] == 4*sum(ty4(d) for d in divs(n)) for n in R)
      and all(r[2][p] == (8 if p % 4 == 1 else 0) for p in primes(3, N)))
check("Theorem 9.4: 8 x sum of divisors not divisible by 4; 16 x sum of (-1)^(n+d) d^3",
      all(r[4][n] == 8*sum(d for d in divs(n) if d % 4) for n in R)
      and all(r[8][n] == 16*sum((-1)**(n + d)*d**3 for d in divs(n)) for n in R))
check("Theorem 9.4 NEG: not 8 x all divisors (n = 4), not 16 x all cubes (n = 2)",
      r[4][4] != 8*7 and r[8][2] != 16*9)
mult = lambda k: all(r[k][a*b]*2*k == r[k][a]*r[k][b]
                     for a in range(2, 23) for b in range(2, 23) if math.gcd(a, b) == 1)
check("Corollary 9.5: count / (number of units) multiplies in dimensions 1, 2, 4, 8",
      all(mult(k) for k in (1, 2, 4, 8)) and [r[k][1] for k in (1, 2, 4, 8)] == [2, 4, 8, 16])
check("Corollary 9.5 NEG: it does not multiply in dimensions 3, 5, 6, 7",
      not any(mult(k) for k in (3, 5, 6, 7)))
# ---- Remark on larger systems; evidence for the conjectures
def par(pa, L): return [sum(1 for y in range(-30, 31) if (y - pa) % 2 == 0 and y*y == n) for n in range(L + 1)]
def convL(a, b): return [sum(a[i]*b[n - i] for i in range(n + 1)) for n in range(len(a))]
L = 4*40; ev, od = par(0, L), par(1, L); ev4 = convL(convL(ev, ev), convL(ev, ev))
od4 = convL(convL(od, od), convL(od, od))
h24 = [ev4[4*n] + od4[4*n] for n in range(41)]
o240 = [convL(ev4, ev4)[4*n] + convL(od4, od4)[4*n] + 14*convL(ev4, od4)[4*n] for n in range(41)]
check("Remark 9.6: 24 units: 24 x sum of odd divisors; 240 units: 240 x sum of d^3 (n <= 40)",
      all(h24[n] == 24*sum(d for d in divs(n) if d % 2) for n in range(1, 41))
      and all(o240[n] == 240*sum(d**3 for d in divs(n)) for n in range(1, 41)))
tab = {}                                # octonions: e_a e_(a+1) = e_(a+3), indices 1..7 round a loop
for a in range(7):
    i, j, k = a + 1, (a + 1) % 7 + 1, (a + 3) % 7 + 1
    for x, y, z in ((i, j, k), (j, k, i), (k, i, j)): tab[(x, y)] = (z, 1); tab[(y, x)] = (z, -1)
def omul(x, y):
    r = [0]*8
    for a, xa in x:
        for b, yb in y:
            z, s = (b, 1) if a == 0 else (a, 1) if b == 0 else (0, -1) if a == b else tab[(a, b)]
            r[z] += s*xa*yb
    return tuple(r)
lines = [frozenset({a + 1, (a + 1) % 7 + 1, (a + 3) % 7 + 1}) for a in range(7)]
quads = [frozenset({0}) | l for l in lines] + [frozenset(range(1, 8)) - l for l in lines]
def units(sw):                          # doubled coordinates; sw exchanges the roles of 1 and e_sw
    f = lambda x: sw if x == 0 else (0 if x == sw else x); U = set()
    for a in range(8):
        for s in (2, -2): U.add(tuple(s if j == a else 0 for j in range(8)))
    for q in quads:
        q = sorted(f(x) for x in q)
        for sg in itertools.product((1, -1), repeat=4):
            U.add(tuple(sg[q.index(j)] if j in q else 0 for j in range(8)))
    return U
def closed(U):
    sp = [[(a, v) for a, v in enumerate(x) if v] for x in U]
    return all(not any(v % 2 for v in z) and tuple(v//2 for v in z) in U
               for x in sp for y in sp for z in [omul(x, y)])
check("Remark 9.6: 240 half points; closed under the product after exchanging 1 and e_a, a = 1..7",
      all(len(units(a)) == 240 and closed(units(a)) for a in range(1, 8)))
check("Remark 9.6 NEG: the first natural set of 240 half points is not closed", not closed(units(0)))
g = True
for n in range(3, 40, 2):               # kinds of ledgers under the mirror / sqrt(n)
    U = np.array([[u(j*k/n) for k in range(n)] for j in range(n)])/math.sqrt(n); ev_ = np.linalg.eigvals(U)
    kinds = [int(sum(abs(ev_ - z) < 1e-6)) for z in (1, 1j, -1, -1j)]; m = n//4
    g &= kinds == ([m + 1, m, m, m] if n % 4 == 1 else [m + 1, m + 1, m + 1, m])
    g &= kinds[0] + kinds[2] == (n + 1)//2
check("Conjecture 11.1 (evidence): the four kinds number m+1, m, m, m or m+1, m+1, m+1, m (n < 40)", g)
N = 400; th = th[:N + 1]; rk = [1] + [0]*N; good = []
for k in range(1, 25):
    rk = conv(rk, th)
    if all(rk[a*b]*2*k == rk[a]*rk[b] for a in range(2, 20) for b in range(2, 20) if math.gcd(a, b) == 1):
        good.append(k)
check("Conjecture 11.3 (evidence): among dimensions up to 24, count/units multiplies only in 1, 2, 4, 8",
      good == [1, 2, 4, 8])
print("%d checks; %s" % (count, "all pass" if not fails else "FAILED: " + "; ".join(fails)))
