# Verification script for Paper 10, "Primes Are Loops".  Dependencies: numpy, mpmath, sympy.
# One PASS/FAIL line per check; NEG marks a negative test (a false variant must fail).
# Sums over the whole numbers are formed directly (numpy), never from closed forms of the
# statement under test; zeta and the type series off their range of convergence come from
# the Euler-Maclaurin continuation below, which does not use the mirror equations.
import math, cmath, itertools
from functools import reduce
import numpy as np, mpmath as mp
from sympy import symbols, factor_list, isprime, divisors, factorint, totient

mp.mp.dps = 25
results = []
def check(name, cond):
    results.append(bool(cond)); print(("PASS  " if cond else "FAIL  ") + name)

# ---- loops and ledgers
def conv(a, b):                      # the product of two n-step ledgers adds steps
    n = len(a); c = np.zeros(n, dtype=np.result_type(a, b))
    for i in range(n):
        if a[i] != 0: c += a[i] * np.roll(b, i)
    return c
def whole(n, d):                     # the whole of the sub-loop of d steps of the n-loop
    w = np.zeros(n); w[::n // d] = 1.0 / d; return w
def unit(n): return whole(n, 1)
def reading(w, j):                   # the net of w read on the loop run j times
    n = len(w); return sum(w[k] * cmath.exp(2j * math.pi * j * k / n) for k in range(n))
def mirror(w): return np.array([reading(w, j) for j in range(len(w))])
def total(w): return w.sum()
def gross(w): return np.abs(w).sum()
def sign(d):                         # +1/-1 by the number of different primes, 0 if one repeats
    f = factorint(d)
    return 0 if any(v > 1 for v in f.values()) else (-1) ** len(f)
def sieve(X):
    s = np.ones(X + 1, bool); s[:2] = False
    for i in range(2, int(X ** .5) + 1):
        if s[i]: s[i * i::i] = False
    return s
def typ(n): return 0 if n % 2 == 0 else (1 if n % 4 == 1 else -1)

# ---- sums over the whole numbers
def dsum(s, logs=0, N=10 ** 6):      # sum of (ln n)^logs n^-s, hidden part > 1: direct sum, tail by the integral
    k = np.arange(1, N + 1, dtype=float); L = math.log(N); s = complex(s)
    head = np.sum(np.log(k) ** logs * np.exp(-s * np.log(k)))
    if logs == 0: return head + N ** (1 - s) / (s - 1) - N ** (-s) / 2
    return head + N ** (1 - s) * L / (s - 1) + N ** (1 - s) / (s - 1) ** 2 - N ** (-s) * L / 2
def ordered_net(a, t, kind="two-step", N=10 ** 6):   # net in order: mean of two consecutive partial nets
    k = np.arange(1, N + 2, dtype=float)
    if kind == "type": k = 2 * k - 1                 # the odd numbers; the sign is the type
    v = np.where(np.arange(N + 1) % 2 == 0, 1.0, -1.0) * k ** -a * np.exp(-1j * t * np.log(k))
    return np.sum(v[:-1]) + v[-1] / 2
def hurwitz(s, x0, M=40, K=24):       # sum over n >= 0 of (n + x0)^-s, continued by Euler-Maclaurin
    with mp.workdps(70):             # extra digits: for negative hidden part the terms are large and cancel
        s = mp.mpmathify(s); x = M + mp.mpf(x0)
        S = mp.fsum((n + mp.mpf(x0)) ** (-s) for n in range(M)) + x ** (1 - s) / (s - 1) + x ** (-s) / 2
        term = s
        for k in range(1, K + 1):
            S += mp.bernoulli(2 * k) / mp.factorial(2 * k) * term * x ** (-s - 2 * k + 1)
            term *= (s + 2 * k - 1) * (s + 2 * k)
    return +S
def zeta_c(s): return hurwitz(s, 1)                  # zeta, continued
def L_c(s):                                          # the type series, continued
    s = mp.mpmathify(s)
    if s == 1: h = mp.mpf('1e-9'); return (L_c(1 + h) + L_c(1 - h)) / 2
    with mp.workdps(70): r = mp.mpf(4) ** (-s) * (hurwitz(s, mp.mpf(1) / 4) - hurwitz(s, mp.mpf(3) / 4))
    return +r
check("Continuation used below: agrees with direct sums at s = 2+3f and gives zeta(-3) = 1/120",
      abs(complex(zeta_c(mp.mpc(2, 3))) - dsum(2 + 3j)) < 1e-11 and abs(zeta_c(-3) - mp.mpf(1) / 120) < 1e-18
      and abs(complex(L_c(mp.mpc(2, 3))) - ordered_net(2.0, 3.0, "type")) < 1e-9)

# ---- Section 2
rng = np.random.default_rng(1); g = True
for n in (1, 2, 6, 12, 30):
    a, b = rng.normal(size=n), rng.normal(size=n)
    g &= all(abs(reading(conv(a, b), j) - reading(a, j) * reading(b, j)) < 1e-9 for j in range(n))
    g &= np.allclose(a, [sum(reading(a, j) * cmath.exp(-2j * math.pi * j * k / n) for j in range(n)) / n for k in range(n)])
    g &= all(abs(reading(whole(n, d), j) - (1 if j % d == 0 else 0)) < 1e-12
             for d in divisors(n) for j in range(n))
    g &= all(np.allclose(conv(whole(n, a_), whole(n, b_)), whole(n, math.lcm(a_, b_)))
             for a_ in divisors(n) for b_ in divisors(n))
check("Proposition 2.1: readings multiply and determine the ledger; reading of a whole; wholes join sub-loops", g)
def top(n):                          # one factor (unit - whole) for each prime factor, repeated primes repeated
    e = unit(n)
    for p, k in factorint(n).items():
        for _ in range(k): e = conv(e, unit(n) - whole(n, p))
    return e
a, b = rng.normal(size=12), rng.normal(size=12); pa, pb = np.abs(a), np.abs(b)
check("Setting, three readings: the total multiplies; the gross only satisfies G(w*w') <= G(w)G(w'), with equality for weights >= 0",
      abs(total(conv(a, b)) - total(a) * total(b)) < 1e-9 and gross(conv(a, b)) < gross(a) * gross(b) - 1e-3
      and abs(gross(conv(pa, pb)) - gross(pa) * gross(pb)) < 1e-9 and abs(total(a)) <= gross(a))
check("Setting: eta_12 has total 0 and gross 4/3; the reading at step 0 is the total",
      abs(total(top(12))) < 1e-12 and abs(gross(top(12)) - 4 / 3) < 1e-12 and abs(reading(a, 0) - total(a)) < 1e-12)
check("Setting: (whole of the full loop) * w = T(w) x that whole",
      np.allclose(conv(whole(12, 12), a), total(a) * whole(12, 12)))
check("NEG Setting: with the gross in place of the total this fails for a signed w",
      not np.allclose(conv(whole(12, 12), a), gross(a) * whole(12, 12)))

# ---- Section 3
def count_wholes(n):                 # every ledger equal to its own square has readings 0 or 1
    cnt = 0
    F = np.array([[cmath.exp(-2j * math.pi * j * k / n) for j in range(n)] for k in range(n)]) / n
    for J in itertools.product((0, 1), repeat=n):
        if not any(J): continue
        w = F @ np.array(J)
        if np.abs(w.imag).max() < 1e-9 and w.real.min() > -1e-9: cnt += 1
    return cnt
check("Theorem 3.2(A): the n-loop has one whole per sub-loop; two wholes iff n is prime (n<=13, exhaustive)",
      all(count_wholes(n) == len(divisors(n)) and ((count_wholes(n) == 2) == isprime(n)) for n in range(2, 14)))
check("Definition 3.1: the loop of one step has one whole, so 1 is not prime", count_wholes(1) == 1)
tt = symbols('t')
def paper1_no_zero_divisors(n):      # Paper 1's algebra with rational weights: law q_n does not factor
    m = 1 if n % 2 else 2
    fl = factor_list(sum(tt ** (m * j) for j in range(n)))[1]
    return len(fl) == 1 and fl[0][1] == 1
check("Theorem 3.2(B) (cited, Paper 11): Paper 1's algebra has no zero divisors iff n is prime (n<=60)",
      all(paper1_no_zero_divisors(n) == isprime(n) for n in range(2, 61)))

# ---- Section 4
g = True
for n in (2, 4, 6, 7, 8, 9, 12, 27, 30, 36, 60):
    eta = top(n)
    g &= np.allclose(eta, sum(sign(d) * whole(n, d) for d in divisors(n)))
    g &= np.allclose(conv(eta, eta), eta)
    g &= abs(eta[0] - float(totient(n)) / n) < 1e-12 and abs(total(eta)) < 1e-12 and gross(eta) > 0.5
    g &= all(abs(reading(eta, j) - (1 if math.gcd(j, n) == 1 else 0)) < 1e-9 for j in range(n))
check("Theorem 4.1: product with multiplicity = sum of signed wholes; own square; weight phi(n)/n; total 0 (incl. loops of 4, 8, 9, 27)", g)
check("Theorem 4.1(2): a repeated prime changes nothing, (unit - whole)^2 = unit - whole; eta_8 = eta_2-part, eta_27 = unit - whole_3",
      all(np.allclose(conv(unit(12) - whole(12, p), unit(12) - whole(12, p)), unit(12) - whole(12, p)) for p in (2, 3))
      and np.allclose(top(8), unit(8) - whole(8, 2)) and np.allclose(top(27), unit(27) - whole(27, 3)))
alt = sum((-1) ** sum(factorint(d).values()) * whole(12, d) for d in divisors(12))
check("NEG Theorem 4.1: giving the sub-loops of 4 and 12 a sign gives a different ledger",
      not np.allclose(alt, top(12)) and abs(alt[1] - top(12)[1]) > 0.05)
check("Theorem 4.1(5): for n prime it is unit - whole of the full loop, the process part",
      all(np.allclose(top(p), unit(p) - whole(p, p)) for p in (2, 3, 5, 7, 11, 13)))
check("Corollary 4.2(1): weight at step k = (1/n) sum over d | (n,k) of sign(n/d) d (n <= 40)",
      all(np.allclose(top(n), [sum(sign(n // d) * d for d in divisors(math.gcd(n, k))) / n for k in range(n)]) for n in range(2, 41)))
g = True
for n in range(2, 41):
    parts = [whole(n, n), top(n), unit(n) - whole(n, n) - top(n)]
    g &= all(np.allclose(conv(x, x), x) for x in parts)
    g &= all(np.allclose(conv(parts[i], parts[j]), 0) for i in range(3) for j in range(i))
    dims = [sum(1 for j in range(n) if abs(reading(x, j)) > 0.5) for x in parts]
    g &= dims == [1, int(totient(n)), n - int(totient(n)) - 1]
    g &= np.allclose(parts[2], 0) == isprime(n)
check("Corollary 4.2(2),(3): unit = whole + product + rest; dimensions 1, phi(n), n-phi(n)-1; rest zero iff n prime (n <= 40)", g)

# ---- Section 5
def mul(x, y, c): return (x[0] * y[0] + c * x[1] * y[1], x[0] * y[1] + x[1] * y[0])
def power(x, n, c): return reduce(lambda r, _: mul(r, x, c), range(n), (1, 0))
f = (0, 1)
def fpart(n, c): return power(f, n, c)[1]
check("Proposition 5.1: f^n = c^((n-1)/2) f for odd n and c^(n/2) e for even n (c = -1, 0, 1, 2, -3)",
      all(power(f, n, c) == ((0, c ** ((n - 1) // 2)) if n % 2 else (c ** (n // 2), 0))
          for c in (-1, 0, 1, 2, -3) for n in range(1, 24)))
check("Definition 5.2: in the turn product f^n is f (height), -f (width) or on the line",
      all(fpart(n, -1) == typ(n) for n in range(1, 200)))
def multiplies(c):
    return all(abs(fpart(m * n, c) - fpart(m, c) * fpart(n, c)) <= 1e-9 * max(1, abs(fpart(m * n, c)))
               for m in range(1, 14) for n in range(1, 14))
check("Theorem 5.3: type multiplies; the f-part multiplies when f squares to -e, 0, +e",
      multiplies(-1) and multiplies(0) and multiplies(1))
check("NEG Theorem 5.3: it does not multiply for c = 2 (the ledger product rescaled), -2, 1/2",
      not multiplies(2) and not multiplies(-2) and not multiplies(0.5))

# ---- Section 6
N = 400000; n = np.arange(1, N + 1, dtype=float)
line = np.where(n % 2 == 0, -np.where(n % 4 == 2, -1.0, 1.0) / n, 0.0)   # (-1)^(n+1) f^n / n, e-part
tyv = np.where(n % 4 == 1, 1.0, np.where(n % 4 == 3, -1.0, 0.0)) / n     # f-part
cl, ct = np.cumsum(line), np.cumsum(tyv)
aL, aT = (cl[-1] + cl[-3]) / 2, (ct[-1] + ct[-3]) / 2                    # mean of two partial sums
check("Theorem 6.1: line powers sum to (1/2) ln 2 and height/width powers to pi/4",
      abs(aL - math.log(2) / 2) < 1e-9 and abs(aT - math.pi / 4) < 1e-9)
check("Theorem 6.1: the series is a logarithm of the cut, Exp(series) = e + f; in natural order it converges",
      abs(cmath.exp(complex(aL, aT)) - (1 + 1j)) < 1e-8 and abs(complex(cl[-1], ct[-1]) - complex(aL, aT)) < 3e-6)
check("NEG Theorem 6.1: with height and width exchanged the outcome is the cut of -1, not of 1",
      abs(cmath.exp(complex(aL, -aT)) - (1 - 1j)) < 1e-8 and abs(cmath.exp(complex(aL, -aT)) - (1 + 1j)) > 1)
check("Proposition 6.2: tangent product, f^n = 0 for n >= 2 so the series is f, and Exp_0(f) = (e + f/m)^m = e + f",
      all(power(f, k, 0) == (0, 0) for k in range(2, 9))
      and all(max(abs(power((1, 1 / m), m, 0)[0] - 1), abs(power((1, 1 / m), m, 0)[1] - 1)) < 1e-9 for m in (1, 7, 1000)))
he = lambda X: np.sum(-1.0 / np.arange(2, X + 1, 2)); hf = lambda X: np.sum(1.0 / np.arange(1, X + 1, 2))
check("Proposition 6.2: ledger product, e + f is twice a half, (e+f)(e-f) = 0; partial sums of the series grow like (1/2) ln N",
      mul((1, 1), (1, -1), 1) == (0, 0) and mul((.5, .5), (.5, .5), 1) == (.5, .5)
      and all(abs(hf(X * X) - hf(X) - math.log(X) / 2) < 3e-3 and abs(he(X * X) - he(X) + math.log(X) / 2) < 3e-3 for X in (300, 1000)))

# ---- Section 7
def D(m): return (sum(1 for d in divisors(m) if d % 4 == 1), sum(1 for d in divisors(m) if d % 4 == 3))
def lprod(a, b): return (a[0] * b[0] + a[1] * b[1], a[0] * b[1] + a[1] * b[0])
def oddpart(m):
    while m % 2 == 0: m //= 2
    return m
check("Theorem 7.2: D(mn) = D(m) * D(n) if and only if m, n share no odd factor (m, n < 70)",
      all((D(a * b) == lprod(D(a), D(b))) == (math.gcd(oddpart(a), oddpart(b)) == 1) for a in range(1, 70) for b in range(1, 70)))
check("Theorem 7.2, examples: D(9) = (2,1), D(3)*D(3) = (2,2), D(2)*D(2) = D(4) = (1,0)",
      D(9) == (2, 1) and lprod(D(3), D(3)) == (2, 2) and lprod(D(2), D(2)) == D(4) == (1, 0))
check("Corollary 7.3: 2 is (1,0); height primes (2,0); width primes (1,1), balanced zeros of Paper 2 (p < 3000)",
      D(2) == (1, 0) and all(D(p) == ((2, 0) if p % 4 == 1 else (1, 1)) for p in range(3, 3000) if isprime(p)))
check("Corollary 7.3: prime powers, (k+1, 0) for height and (ceil, floor of (k+1)/2) for width primes (p < 60, k < 8)",
      all(D(p ** k) == ((k + 1, 0) if p % 4 == 1 else ((k + 2) // 2, (k + 1) // 2)) for p in range(3, 60) if isprime(p) for k in range(8)))
check("Corollary 7.3(4): an odd n >= 3 is prime iff the gross of D(n) is 2 (n < 3000)",
      all((sum(D(m)) == 2) == isprime(m) for m in range(3, 3000, 2)))
check("NEG Corollary 7.3(4): for even n it fails (D(2) has gross 1; D(6), D(10), D(12) have gross 2)",
      sum(D(2)) == 1 and all(sum(D(m)) == 2 for m in (6, 10, 12)))
M = 3000; r2 = [0] * (M + 1); R = math.isqrt(M)
for x in range(-R, R + 1):
    for y in range(-R, R + 1):
        if 0 < x * x + y * y <= M: r2[x * x + y * y] += 1
check("Theorem 7.4 (cited, Paper 11): whole points of squared size n = 4 x net of D(n) (n <= 3000)",
      all(r2[m] == 4 * (D(m)[0] - D(m)[1]) for m in range(1, M + 1)))
check("Theorem 7.4: 2 = cut(1) cut(-1) and cut(1)^2 = 2f",
      mul((1, 1), (1, -1), -1) == (2, 0) and mul((1, 1), (1, 1), -1) == (0, 2))

# ---- Section 8
X = 5 * 10 ** 6; isp = sieve(X); P = np.nonzero(isp)[0][1:].astype(float)   # odd primes
T = np.where(P % 4 == 1, 1.0, -1.0)
s = 2.0; odd = np.arange(1, 2 * 10 ** 6, 2, dtype=float)
Ps = np.sum(odd[odd % 4 == 1] ** -s); Qs = np.sum(odd[odd % 4 == 3] ** -s)
Gp = math.exp(-np.sum(np.log1p(-P ** -s))); Np_ = math.exp(-np.sum(np.log1p(-T * P ** -s)))
check("Theorem 8.2: at s = 2 the gross and the net are the products over odd primes",
      abs(Ps + Qs - Gp) < 2e-6 and abs(Ps - Qs - Np_) < 2e-6)
def small(p, s, K=60):               # the ledger of the powers of p
    t = 1 if p % 4 == 1 else -1
    return (sum(p ** (-k * s) for k in range(K) if t ** k == 1), sum(p ** (-k * s) for k in range(K) if t ** k == -1))
lhs = lprod(lprod(small(3, 2.0), small(5, 2.0)), small(7, 2.0))
sm = [a for a in (3 ** i * 5 ** j * 7 ** k for i in range(40) for j in range(30) for k in range(25)) if a < 10 ** 12]
rhs = (sum(a ** -2.0 for a in sm if a % 4 == 1), sum(a ** -2.0 for a in sm if a % 4 == 3))
check("Theorem 8.2: the ledger product of the ledgers of 3, 5, 7 is the ledger of the numbers built from them",
      abs(lhs[0] - rhs[0]) < 1e-10 and abs(lhs[1] - rhs[1]) < 1e-10)
check("NEG Theorem 8.2: with the type of 3 changed to height the net is no longer the product",
      abs(Ps - Qs - Np_ * (1 + 1 / 9) / (1 - 1 / 9)) > 0.1)
c4 = np.exp(np.cumsum(np.log(P / (P - T)))); c2 = np.exp(np.cumsum(np.log(P / (P + T))))
w4, w2 = c4[-1], c2[-1]
check("Theorem 8.3(2): in increasing order of p, product of p/(p - type) = pi/4 (primes below 5,000,000; numerical)",
      abs(w4 - math.pi / 4) < 3e-4 and abs(c4[len(P) // 10] - math.pi / 4) < 1e-3)
check("Theorem 8.3(3),(4): in increasing order, product of p/(p + type) = pi/2 (numerical); the ratio is 2",
      abs(w2 - math.pi / 2) < 6e-4 and abs(w2 / w4 - 2) < 2e-3)
check("Theorem 8.3(1): f^(p - type) = e and f^(p + type) = -e: whole loops and half loops",
      all(power(f, int(p - t), -1) == (1, 0) and power(f, int(p + t), -1) == (-1, 0) for p, t in zip(P[:300], T[:300])))
check("Theorem 8.3(4): the two products multiply to the gross at s = 2, which is pi^2/8; with the prime 2 entered the ratio is 8/3",
      abs(Gp - math.pi ** 2 / 8) < 1e-6 and abs(w4 * w2 - Gp) < 1e-4 and abs(Gp / (1 - 0.25) / (math.pi / 4) ** 2 - 8 / 3) < 1e-5)
check("NEG Theorem 8.3: with every prime rounded down (all counted as height) the product is not pi/4",
      math.exp(np.sum(np.log(P / (P - 1)))) > 5)
def other_order(x):                  # width primes up to x with height primes up to x^2
    return math.exp(np.sum(np.log(P[(T < 0) & (P <= x)] / (P[(T < 0) & (P <= x)] + 1)))
                    + np.sum(np.log(P[(T > 0) & (P <= x * x)] / (P[(T > 0) & (P <= x * x)] - 1))))
print("      other order, x = 1000, 2000: %.4f %.4f ; sqrt2 pi/4 = %.4f" % (other_order(1000), other_order(2000), math.sqrt(2) * math.pi / 4))
check("Remark 8.5 (numerical): taken in another order the product tends to sqrt2 x pi/4, not pi/4",
      all(abs(other_order(x) - math.sqrt(2) * math.pi / 4) < 2e-3 for x in (1000, 2000)) and abs(other_order(1000) - 1.1095) < 1e-4)
kk = np.arange(0, 10 ** 6, dtype=float)
term = lambda k, s: (4 * k + 1) ** -s - (4 * k + 3) ** -s
grid = [2.0, 1.5, 1.1, 1.01, 1.0]
check("Corollary 8.4, proof: the term of k = 0 decreases as s decreases to 1; every term of k >= 1 increases (k <= 2000)",
      all(term(0, grid[i]) > term(0, grid[i + 1]) for i in range(4))
      and all(np.all(term(kk[1:2001], grid[i]) < term(kk[1:2001], grid[i + 1])) for i in range(4)))
check("Corollary 8.4: the net, summed directly, tends to pi/4 as s -> 1 and is not 0",
      all(abs(np.sum(term(kk, 1 + d)) - math.pi / 4) < 0.4 * d + 1e-6 for d in (0.1, 0.01, 0.001)))
ho = lambda X, s: np.sum(np.arange(1, X + 1, 2, dtype=float) ** -s)
check("Corollary 8.4: the gross at s = 1 is unbounded: partial gross over odd n <= X grows like (1/2) ln X",
      all(abs(ho(X * X, 1.0) - ho(X, 1.0) - math.log(X) / 2) < 1e-3 for X in (300, 1000)) and ho(10 ** 6, 1.001) > 7)

# ---- Section 9
a, t = mp.mpf(2), mp.mpf(3); z = dsum(2 + 3j)
check("Theorem 9.2(1): the ledger {n^-a at motion -t ln n}, summed directly, has net zeta(a+tf) and gross zeta(a) (a=2, t=3)",
      abs(z - complex(mp.zeta(mp.mpc(a, t)))) < 1e-11 and abs(dsum(2) - math.pi ** 2 / 6) < 1e-11)
K = 2500; k = np.arange(1, K + 1, dtype=float); w = k ** -2.0; ph = 3.0 * np.log(k)
pairs = sum(float(np.sum(w[i] * w[i + 1:] * (1 - np.cos(ph[i + 1:] - ph[i])))) for i in range(K - 1))
check("Theorem 9.2(2): triangle equality, zeta(a)^2 - |zeta(a+tf)|^2 = 2 x ghost (double sum over pairs, truncated)",
      abs((math.pi ** 2 / 6) ** 2 - abs(z) ** 2 - 2 * pairs) < 4e-3)
PP = np.nonzero(isp)[0].astype(float); s9 = 2.5 + 7j; z9 = dsum(s9)
check("Theorem 9.2(3): the net is the product over all primes of 1/(1 - p^-s) (s = 2.5+7f)",
      abs(np.exp(-np.sum(np.log(1 - np.exp(-s9 * np.log(PP))))) - z9) < 1e-8)
kn = np.arange(1, 10 ** 6 + 1, dtype=float); en = kn ** -4.0
E, F = np.sum(en * np.cosh(-1.5 * np.log(kn))), np.sum(en * np.sinh(-1.5 * np.log(kn)))   # entries Exp_1(-s ln n)
check("Theorem 9.3: ledger product, entries summed: zeta(a+t) on one half and zeta(a-t) on the other (a=4, t=1.5)",
      abs(E + F - float(mp.zeta(5.5))) < 1e-9 and abs(E - F - float(mp.zeta(2.5))) < 1e-8)
check("Theorem 9.3: tangent product, entries summed: zeta(a) e + t zeta'(a) f (a=2, t=3)",
      abs(-3 * dsum(2, logs=1) - float(t * mp.zeta(a, derivative=1))) < 1e-9)
check("NEG Theorem 9.3: the turn net is neither of these", abs(z.imag - float(t * mp.zeta(a, derivative=1))) > 0.1)
X2 = 2 * 10 ** 6; mu = np.ones(X2 + 1, dtype=np.int8); lam = np.ones(X2 + 1, dtype=np.int8)   # signs; parity signs
for p in np.nonzero(isp[:X2 + 1])[0]:
    mu[p::p] *= -1; mu[p * p::p * p] = 0; q = int(p)
    while q <= X2:
        lam[q::q] *= -1; q *= int(p)
m1 = mu[1:10 ** 6 + 1]
ent = [(1.0, 1)]
for p in (2, 3, 5): ent = [(x * y, m * q) for (x, m) in ent for (y, q) in ((1.0, 1), (-1.0, p))]
check("Theorem 9.4(1): the list product of (e, -p^-s) for p = 2, 3, 5 has the entries sign(n) n^-s, n dividing 30",
      sorted(ent, key=lambda v: v[1]) == [(float(sign(m)), m) for m in divisors(30)])
Pm, Qm = np.sum(kn[m1 == 1] ** -2.0), np.sum(kn[m1 == -1] ** -2.0)
z2, z4 = math.pi ** 2 / 6, math.pi ** 4 / 90
check("Theorem 9.4(2): signed ledger at s = 2: net 1/zeta(2), gross zeta(2)/zeta(4), gross x net = 1/zeta(4)",
      abs(Pm - Qm - 1 / z2) < 2e-6 and abs(Pm + Qm - z2 / z4) < 2e-6 and abs((Pm + Qm) * (Pm - Qm) - 1 / z4) < 4e-6)
nS = np.sum(m1 * np.exp(-s9 * np.log(kn)))
check("Theorem 9.4(2): at s = 2.5+7f the net is 1/zeta(s), the gross zeta(a)/zeta(2a), and N(S) N(Z) = 1",
      abs(nS * z9 - 1) < 1e-7 and abs(np.sum(np.abs(m1) * kn ** -2.5) - dsum(2.5).real / dsum(5).real) < 1e-7)
check("Theorem 9.4(3): |zeta(s)| >= zeta(2a)/zeta(a) > 0, sums formed directly (a = 1.1, 1.5, 3; t = 0..40)",
      all(abs(dsum(complex(a_, t_), N=10 ** 5)) >= (dsum(2 * a_, N=10 ** 5) / dsum(a_, N=10 ** 5)).real - 1e-6
          for a_ in (1.1, 1.5, 3.0) for t_ in range(0, 41)))
grid9 = [(x + 0.5) / 8 for x in range(-104, 0)]                          # the line from -12.94 to -0.06
neg = [float(zeta_c(mp.mpf(x))) for x in grid9]
flips = [(grid9[i] + grid9[i + 1]) / 2 for i in range(len(grid9) - 1) if neg[i] * neg[i + 1] < 0]
check("Remark 9.5: on the line zeta < 0 for 0 < a < 1, zeta(0) = -1/2, and its zeros in (-13, 0) are -2, ..., -12, simple",
      all(ordered_net(x, 0.0).real > 0 and ordered_net(x, 0.0).real / (1 - 2 ** (1 - x)) < 0 for x in (0.1, 0.3, 0.5, 0.7, 0.9))
      and abs(zeta_c(0) + mp.mpf(1) / 2) < 1e-18 and flips == [-12.0, -10.0, -8.0, -6.0, -4.0, -2.0]
      and all(abs(zeta_c(-2 * j)) < 1e-18 and abs(zeta_c(-2 * j + mp.mpf('1e-6'))) > 1e-9 for j in range(1, 7)))

# ---- Section 10
eta_c = lambda s: (1 - mp.mpf(2) ** (1 - s)) * zeta_c(s)                 # with the continued zeta
check("Theorem 10.2(3): for a > 1 the net in order is (1 - 2^(1-s)) zeta(s), both sides summed directly (a=2, t=3)",
      abs(ordered_net(2.0, 3.0) - (1 - 2 ** (1 - (2 + 3j))) * z) < 1e-9)
check("Theorem 10.2(2),(4): the net in order exists for 0 < a <= 1 and is (1 - 2^(1-s)) x continued zeta (a = 0.1, 0.3, 0.5, 1)",
      all(abs(ordered_net(a_, t_) - complex(eta_c(mp.mpc(a_, t_)))) < tol and abs(ordered_net(a_, t_) - ordered_net(a_, t_, N=3 * 10 ** 5)) < tol
          for a_, t_, tol in ((0.1, 9.0, 1e-5), (0.3, 5.0, 1e-6), (0.5, 20.0, 1e-6), (1.0, 2.0, 1e-6))))
pg = lambda X, a_: np.sum(np.arange(1, X + 1, dtype=float) ** -a_)
check("Theorem 10.2(1): the gross is unbounded for a <= 1: partial gross grows like ln N at a = 1 and like 2 sqrt N at a = 1/2",
      abs(pg(10 ** 6, 1.0) - pg(10 ** 3, 1.0) - math.log(10 ** 3)) < 1e-3 and abs(pg(10 ** 6, 0.5) - pg(10 ** 4, 0.5) - 1800) < 0.01)
t1 = float(mp.zetazero(1).imag)
n5, n3, n7 = ordered_net(0.5, t1), ordered_net(0.3, t1), ordered_net(0.7, t1)
print("      first zero: t = %.6f ; |net| at a = 0.5, 0.3, 0.7: %.5f %.4f %.4f" % (t1, abs(n5), abs(n3), abs(n7)))
check("Example 10.4: at a = 1/2, t = 14.134725 the net in order is 0.00000: a balanced zero", abs(t1 - 14.134725) < 1e-6 and abs(n5) < 5e-6)
check("Example 10.4: at a = 0.3 and 0.7 with the same t the net has size 0.4446 and 0.3212",
      abs(abs(n3) - 0.4446) < 5e-5 and abs(abs(n7) - 0.3212) < 5e-5)
tb = 2 * math.pi / math.log(2)
check("Remark 10.5: at s = e + (2 pi/ln 2) f the net in order is 0 and zeta is not (size 1.351): hidden part 1 is excluded",
      abs(ordered_net(1.0, tb)) < 1e-9 and abs(abs(zeta_c(mp.mpc(1, tb))) - 1.351) < 1e-3)

# ---- Section 11
g = True; orders = {}
for n_ in (1, 2, 3, 4, 5, 8, 12, 15):
    w = np.random.default_rng(n_).normal(size=n_) + 1j * np.random.default_rng(n_ + 1).normal(size=n_)
    U = lambda v: mirror(v) / math.sqrt(len(v))
    pw = [w]
    for _ in range(4): pw.append(U(pw[-1]))
    g &= np.allclose(pw[2], w[(-np.arange(n_)) % n_]) and np.allclose(pw[4], w)
    g &= abs(np.linalg.norm(pw[1]) - np.linalg.norm(w)) < 1e-9
    orders[n_] = next(i for i in range(1, 5) if np.allclose(pw[i], w))
check("Theorem 11.2: mirror twice = n x the loop run backwards; four times = n^2; over sqrt n it keeps size (n = 1, 2, 3, 4, ...)", g)
check("Theorem 11.2: a quarter step exactly for n >= 3; for n = 2 a half step; for n = 1 the identity",
      orders == {1: 1, 2: 2, 3: 4, 4: 4, 5: 4, 8: 4, 12: 4, 15: 4})
def sub(n, d, s):
    w = np.zeros(n, complex); w[::n // d] = d ** (-s); return w
g = True
for n_ in (1, 2, 4, 7, 12, 30, 36):
    for s_ in (0.3, 0.5, 2.0, 0.5 + 3j, 0, -1.5 + 2j):
        for d in divisors(n_): g &= np.allclose(mirror(sub(n_, d, s_)), n_ ** (1 - s_) * sub(n_, n_ // d, 1 - s_))
        Z = sum(sub(n_, d, s_) for d in divisors(n_)); Z1 = sum(sub(n_, d, 1 - s_) for d in divisors(n_))
        g &= np.allclose(mirror(Z), n_ ** (1 - s_) * Z1)
check("Theorem 11.3: mirror of (d points, exponent s) = n^(1-s) (n/d points, exponent 1-s); Z_n(s) -> n^(1-s) Z_n(1-s) (n = 1, 2, 4, ...)", g)
check("Theorem 11.3(1): the mirror of a whole is n/d times the opposite whole",
      all(np.allclose(mirror(whole(n_, d)), (n_ // d) * whole(n_, n_ // d)) for n_ in (1, 2, 7, 12) for d in divisors(n_)))
check("NEG Theorem 11.3: exponent s does not go to exponent s", not np.allclose(mirror(sub(12, 3, 0.3)), 12 ** 0.7 * sub(12, 4, 0.3)))
def factor_size(n_, d, s_):          # size of the number by which mirror/sqrt n carries w_{d,s} to w_{n/d,1-s}
    m_ = mirror(sub(n_, d, s_)) / math.sqrt(n_); return abs(m_[0] / sub(n_, n_ // d, 1 - s_)[0])
check("Theorem 11.3(3): that factor has size 1 at hidden part 1/2, not at 0.3 for n >= 2, and always for n = 1",
      all(abs(factor_size(12, d, s_) - 1) < 1e-12 for d in (1, 3, 12) for s_ in (0.5, 0.5 + 3j))
      and all(abs(factor_size(n_, 1, 0.3 + 3j) - 1) > 0.1 for n_ in (2, 12)) and abs(factor_size(1, 1, 0.3 + 3j) - 1) < 1e-12)
ty4 = np.array([0, 1, 0, -1], complex)
check("Proposition 11.4: type is its own mirror on the four-step loop, factor 2f = cut(1)^2",
      np.allclose(mirror(ty4), 2j * ty4) and (1 + 1j) ** 2 == 2j)
check("NEG Proposition 11.4: the ledger (0,1,0,1) is not its own mirror", not np.allclose(mirror(np.array([0, 1, 0, 1.0])), 2j * np.array([0, 1, 0, 1.0])))
tys = lambda s: mp.sin(mp.pi * s / 2); lin = lambda s: mp.cos(mp.pi * s / 2)
check("Definition 11.5: f^s = line(s) e + type(s) f agrees with the powers of f at whole s, f^s f^r = f^(s+r), f^(1/2) = u(1/8)",
      all(abs(tys(m) - fpart(m, -1)) < 1e-20 and abs(lin(m) - power(f, m, -1)[0]) < 1e-20 for m in range(0, 30))
      and abs(mp.expj(mp.pi * 0.3 / 2) * mp.expj(mp.pi * 1.1 / 2) - mp.mpc(lin(1.4), tys(1.4))) < 1e-14
      and abs(mp.mpc(lin(0.5), tys(0.5)) - mp.expj(2 * mp.pi / 8)) < 1e-20)
check("Before Theorem 11.6: the net in order of the ordered ledger of the odd numbers is the continued type series (a = 0.3, 0.5, 1)",
      all(abs(ordered_net(a_, t_, "type") - complex(L_c(mp.mpc(a_, t_)))) < 1e-6 for a_, t_ in ((0.3, 5.0), (0.5, 20.0), (1.0, 2.0))))
pts = [mp.mpc(a_, t_) for a_ in (-2.5, -0.7, 0.3, 0.5, 0.8, 2.5, 3) for t_ in (-7, -1, 0, 2, 9)]
mL = lambda s: (2 / mp.pi) ** s * tys(s) * mp.gamma(s)
mZ = lambda s: 2 * mp.mpf(4) ** (-s) * (2 / mp.pi) ** s * lin(s) * mp.gamma(s)
rel = lambda x, y: abs(x - y) / (1 + abs(x))
check("Theorem 11.6 (cited): type series, L(1-s) = (2/pi)^s type(s) Gamma(s) L(s) at 35 exponents (own continuation)",
      all(rel(L_c(1 - s), mL(s) * L_c(s)) < 1e-15 for s in pts))
check("Theorem 11.6 (cited): zeta(1-s) = 2 4^-s (2/pi)^s line(s) Gamma(s) zeta(s) at 35 exponents (own continuation)",
      all(rel(zeta_c(1 - s), mZ(s) * zeta_c(s)) < 1e-15 for s in pts))
s0 = mp.mpc(0.3, 2)
check("NEG Theorem 11.6: exchanging the type part and the line part breaks both",
      abs(L_c(1 - s0) - (2 / mp.pi) ** s0 * lin(s0) * mp.gamma(s0) * L_c(s0)) > 1e-3
      and abs(zeta_c(1 - s0) - 2 * (2 * mp.pi) ** (-s0) * tys(s0) * mp.gamma(s0) * zeta_c(s0)) > 1e-3)
check("Corollary 11.7(1): type series is zero at 1-n for even n, zeta at 1-n for odd n >= 3, and not the other way",
      all(abs(L_c(1 - m)) < 1e-18 for m in (2, 4, 6, 8)) and all(abs(zeta_c(1 - m)) < 1e-18 for m in (3, 5, 7, 9))
      and all(abs(L_c(1 - m)) > 1e-3 for m in (3, 5, 7)) and all(abs(zeta_c(1 - m)) > 1e-3 for m in (2, 4, 6)))
check("Corollary 11.7(2): at s = 1 the mirror reads 1/2 = (2/pi)(pi/4): continued L(0) = 1/2, and L(1) summed in order = pi/4",
      abs(L_c(0) - mp.mpf(1) / 2) < 1e-20 and abs(ordered_net(1.0, 0.0, "type") - math.pi / 4) < 1e-9)
check("Corollary 11.7(3): both mirror factors have size 1 at hidden part 1/2",
      all(abs(abs(F_(mp.mpc(0.5, x))) - 1) < 1e-15 for x in (1, 5, 20, 50) for F_ in (mL, mZ)))
r0 = mp.findroot(lambda x: abs(mZ(mp.mpc(0.3, x))) - 1, 6.29)
check("Corollary 11.7(3) (numerical): off that line the size is not 1 in general, but it is 1 at single points (zeta factor near 0.3e + 6.2888f)",
      all(abs(abs(F_(mp.mpc(a_, 20))) - 1) > 0.2 for a_ in (0.3, 0.7) for F_ in (mL, mZ)) and abs(r0 - mp.mpf('6.2888')) < 1e-3)
strip = [mp.mpc(a_, t_) for a_ in (0.2, 0.35, 0.6, 0.9) for t_ in (3, 14, 21.5)]
check("Corollary 11.7(4): values at an exponent and at its mirror image differ by a finite non-zero factor, so zeros pair",
      all(rel(zeta_c(mp.mpc(1 - s.real, s.imag)), mp.conj(mZ(s) * zeta_c(s))) < 1e-15 and 1e-6 < abs(mZ(s)) < 1e6
          and rel(L_c(mp.mpc(1 - s.real, s.imag)), mp.conj(mL(s) * L_c(s))) < 1e-15 and 1e-6 < abs(mL(s)) < 1e6 for s in strip))
def squares(p):
    w = np.zeros(p)
    for k in range(p): w[k * k % p] += 1
    return w
g = True
for p in (q for q in range(3, 200) if isprime(q)):
    R_ = mirror(squares(p))
    g &= abs(R_[0] - p) < 1e-9 and all(min(abs(R_[j] - R_[1]), abs(R_[j] + R_[1])) < 1e-7 for j in range(1, p))
    g &= abs(abs(R_[1]) - math.sqrt(p)) < 1e-8 and abs(R_[1] ** 2 - (p if p % 4 == 1 else -p)) < 1e-7
check("Remark 11.8 (cited, Paper 11): squares ledger: total p, readings +-net elsewhere, net of size sqrt p, net^2 = +p (height) or -p (width)", g)

# ---- Section 13
zs = [float(mp.zetazero(j).imag) for j in range(1, 6)]
check("Conjecture 13.1 (numerical): at the first five zeros the net in order, summed directly, is 0; at hidden part 0.4 it is not",
      all(abs(ordered_net(0.5, t_)) < 2e-5 for t_ in zs) and all(abs(ordered_net(0.4, t_)) > 0.02 for t_ in zs))
tL = float(mp.findroot(lambda x: abs(L_c(mp.mpc(0.5, x))), 6.02, solver='secant', tol=1e-20, verify=False).real)
check("Conjecture 13.2 (numerical): the first balanced zero of the ordered ledger of the odd numbers: net 0 at 1/2 e + 6.0209489 f, not at hidden part 0.4",
      abs(tL - 6.0209489) < 1e-6 and abs(ordered_net(0.5, tL, "type")) < 1e-6 and abs(ordered_net(0.4, tL, "type")) > 0.02)
xs = np.arange(1, X2 + 1)
Mx = np.cumsum(mu[1:].astype(np.int64)); rM = np.abs(Mx) / np.sqrt(xs)
print("      signs: net at 2,000,000 = %d ; max |net|/sqrt x = %.4f at x = %d ; for x >= 2: %.4f at x = %d ; for x > 200: %.4f at x = %d"
      % (Mx[-1], rM.max(), xs[rM.argmax()], rM[1:].max(), xs[1:][rM[1:].argmax()], rM[200:].max(), xs[200:][rM[200:].argmax()]))
check("Remark 13.4 (numerical): net of the signs: at most sqrt x up to 2,000,000, equality only at x = 1; 0.8944 at x = 5; -247 at the end",
      rM.max() == 1.0 and rM.argmax() == 0 and np.sum(rM >= 1) == 1 and abs(rM[1:].max() - 0.8944) < 1e-4 and xs[1:][rM[1:].argmax()] == 5
      and Mx[4] == -2 and abs(rM[200:].max() - 0.4937) < 1e-4 and xs[200:][rM[200:].argmax()] == 201 and Mx[-1] == -247)
Lx = np.cumsum(lam[1:].astype(np.int64)); rL = np.abs(Lx) / np.sqrt(xs)
print("      parity: net at 2,000,000 = %d ; max |net|/sqrt x = %.4f at x = %d" % (Lx[-1], rL.max(), xs[rL.argmax()]))
check("Remark 13.5 (numerical): parity of the prime factors: largest ratio 1.3302 at x = 96,862; net -1234 at 2,000,000",
      abs(rL.max() - 1.3302) < 1e-4 and xs[rL.argmax()] == 96862 and Lx[-1] == -1234)
check("Remark 13.5: with weights n^-s the parity ledger has gross zeta(s) and net zeta(2s)/zeta(s) (s = 2, summed directly)",
      abs(np.sum(lam[1:10 ** 6 + 1] * kn ** -2.0) - z4 / z2) < 2e-6)

print("%d checks; %s" % (len(results), "all pass" if all(results) else "%d FAIL" % (len(results) - sum(results))))
