#!/usr/bin/env python3
"""verify_dial_of_an_observer.py -- checks for Guideng Math Paper 25,
"The Dial of an Observer".  Needs numpy, scipy and mpmath.  Run: python3 verify_dial_of_an_observer.py
(about half a minute)."""
import math, cmath, itertools, time
from fractions import Fraction as Fr
import numpy as np
from scipy.spatial import cKDTree
t0 = time.time(); rng = np.random.default_rng(25); ALL = []
def check(name, ok):
    ALL.append(bool(ok)); print(('PASS  ' if ok else 'FAIL  ') + name)
def sieve(n):
    s = np.ones(n + 1, dtype=bool); s[:2] = False
    for i in range(2, math.isqrt(n) + 1):
        if s[i]: s[i*i::i] = False
    return s

# ---------------------------------------------------------------- Section 2: the real rung
def cut(p, q): return np.array([p*p + q*q, p*p - q*q, 2*p*q], float)       # c(psi) = (t; a, u)
def eta(X, Y): return X[0]*Y[0] - X[1]*Y[1] - X[2]*Y[2]
def observer(xi, h):                                                      # the observer placed at (xi, h)
    Gam = np.array([[xi*xi + h*h, xi], [xi, 1.0]])/h                      # Gamma(o) = [[t+a, u],[u, t-a]]
    return np.array([(Gam[0, 0] + Gam[1, 1])/2, (Gam[0, 0] - Gam[1, 1])/2, Gam[0, 1]])
def Gmat(o): return np.array([[o[0] - o[1], -o[2]], [-o[2], o[0] + o[1]]])   # adj Gamma(o)
def Mmat(G): a = math.sqrt(G[0, 0]); return np.array([[a, G[0, 1]/a], [0.0, 1/a]])   # M^T M = G, det M = 1
obs = [observer(0.0, 1.0)] + [observer(float(rng.uniform(-2, 2)), float(rng.uniform(0.3, 3))) for _ in range(40)]
ok = True
for o in obs:
    G = Gmat(o); ok &= abs(eta(o, o) - 1) < 1e-9 and abs(np.linalg.det(G) - 1) < 1e-9
    M = Mmat(G); ok &= np.allclose(M.T @ M, G) and abs(np.linalg.det(M) - 1) < 1e-9
    for _ in range(20):
        psi = rng.uniform(-3, 3, 2); ok &= abs(eta(o, cut(*psi)) - psi @ G @ psi) < 1e-8
check('Section 2: gross read by o is psi^T G_o psi, G_o = adj Gamma(o), det G_o = 1, G_o = M^T M', ok)

# ---------------------------------------------------------------- Section 3: the tie identity
ok = True
for o in obs:
    G = Gmat(o)
    for _ in range(20):
        psi, chi = rng.uniform(-3, 3, 2), rng.uniform(-3, 3, 2)
        g1, g2, s = psi @ G @ psi, chi @ G @ chi, psi @ G @ chi; d = psi[0]*chi[1] - psi[1]*chi[0]
        gam = eta(cut(*psi), cut(*chi))
        ok &= abs(gam - 2*d*d) < 1e-7 and abs(g1*g2 - (s*s + gam/2)) < 1e-7
        z, w = Mmat(G) @ psi, Mmat(G) @ chi                                # the angle seen by o
        th = math.acos(max(-1, min(1, (z @ w)/math.sqrt((z @ z)*(w @ w)))))
        ok &= abs(math.sin(th)**2 - gam/(2*g1*g2)) < 1e-7
check('Theorem 3.2: g g\' = s^2 + gamma/2, and sin^2(angle seen by o) = gamma/(2 g g\')', ok)

ok = True                                    # Proposition 3.4: an observer is two cuts
for o in obs:
    G = Gmat(o); Mi = np.linalg.inv(Mmat(G)); v_, w_ = Mi @ np.array([1.0, 0.0]), Mi @ np.array([0.0, 1.0])
    ok &= np.allclose(o, 0.5*(cut(*v_) + cut(*w_))) and abs(v_[0]*w_[1] - v_[1]*w_[0] - 1) < 1e-9
    for _ in range(10):
        psi = rng.uniform(-3, 3, 2)
        ok &= abs(psi @ G @ psi - ((psi[0]*v_[1] - psi[1]*v_[0])**2 + (psi[0]*w_[1] - psi[1]*w_[0])**2)) < 1e-7
ok &= np.allclose(observer(0.0, 1.0), 0.5*(cut(1, 0) + cut(0, 1)))
check('Proposition 3.4: o = (c(v)+c(w))/2 with v, w joined, and o reads d(psi,v)^2 + d(psi,w)^2; e reads q^2 + p^2', ok)

# ---------------------------------------------------------------- Section 4: the dial
def circ(G, psi):
    z = Mmat(G) @ np.array(psi, float); zc = complex(z[0], z[1]); g = abs(zc)**2
    return zc*zc/(g + 1), 1/(g + 1), g
roots = [(p, q) for p in range(-7, 8) for q in range(0, 8) if math.gcd(p, q) == 1 and (q > 0 or p == 1)]
ok = True; ok2 = True; ok3 = True
for o in obs[:12]:
    G = Gmat(o); C = {r: circ(G, r) for r in roots}
    for i, a in enumerate(roots):
        for b in roots[i+1:]:
            (c1, r1, _), (c2, r2, _) = C[a], C[b]; d = a[0]*b[1] - a[1]*b[0]
            lhs = abs(c1 - c2)**2 - (r1 + r2)**2
            ok &= abs(lhs - 4*r1*r2*(d*d - 1)) < 1e-9
            ok2 &= (abs(lhs) < 1e-9) == (abs(d) == 1) and lhs > -1e-9
    # the circle of gross one of Paper 23, drawn in the disc centred at o
    h = 1/(o[0] - o[1]); xi = o[2]*h; zo = complex(xi, h)
    for (p, q) in roots[:60]:
        if q == 0: pts = [complex(x, 1.0) for x in (-1.0, 0.3, 2.0)]
        else:
            r = 1/(2*q*q); c = complex(p/q, r); pts = [c + r*cmath.exp(1j*t) for t in (0.3, 1.7, 4.0)]
        w = [(z - zo)/(z - zo.conjugate()) for z in pts]
        ax, ay, bx, by, cx, cy = w[0].real, w[0].imag, w[1].real, w[1].imag, w[2].real, w[2].imag
        dd = 2*(ax*(by-cy) + bx*(cy-ay) + cx*(ay-by))
        ux = ((ax*ax+ay*ay)*(by-cy) + (bx*bx+by*by)*(cy-ay) + (cx*cx+cy*cy)*(ay-by))/dd
        uy = ((ax*ax+ay*ay)*(cx-bx) + (bx*bx+by*by)*(ax-cx) + (cx*cx+cy*cy)*(bx-ax))/dd
        rad = abs(complex(ux, uy) - w[0])
        ok3 &= abs(rad - C[(p, q)][1]) < 1e-8 and abs(abs(complex(ux, uy)) + rad - 1) < 1e-8
ok5 = True                                  # points of the circle are observers who read gross one
for o in obs[:12]:
    G = Gmat(o); M = Mmat(G)
    for psi in roots[:40]:
        c0, r0, _ = circ(G, psi)
        for tt in (0.4, 2.0, 3.7, 5.5):
            w = c0 + r0*cmath.exp(1j*tt); n2 = abs(w)**2
            if n2 > 1 - 1e-6: continue
            t = (1 + n2)/(1 - n2); a_, u_ = 2*w.real/(1 - n2), 2*w.imag/(1 - n2)
            Gh = np.array([[t - a_, -u_], [-u_, t + a_]]); Gp = M.T @ Gh @ M
            ok5 &= abs(np.array(psi) @ Gp @ np.array(psi) - 1) < 1e-6
check('Theorem 4.2: Delta^2-(rho+rho\')^2 = 4 rho rho\' (d^2-1) at 12 observers', ok)
check('Theorem 4.2: circles never overlap and touch exactly when the roots are joined', ok2)
check('Theorem 4.2: the circle of radius 1/(g+1) is the circle of gross one of Paper 23 in the disc of o', ok3)
check('Theorem 4.2: every point of the circle of psi is an observer who reads psi with gross one', ok5)
ok = True; nn = 0
for o in obs[:8]:
    G = Gmat(o); M = Mmat(G)
    for Y in (3.0, 20.0, 150.0, 900.0):
        R = int(math.sqrt(Y*max(G[0, 0], G[1, 1]))) + 2
        L = [(p, q) for p in range(-R, R+1) for q in range(0, R+1) if math.gcd(p, q) == 1 and (q > 0 or p == 1)
             and np.array([p, q]) @ G @ np.array([p, q]) <= Y]
        if len(L) < 2: continue
        ang = lambda r: math.atan2(*(M @ np.array(r, float))[::-1]) % math.pi
        L.sort(key=ang)
        for a, b in zip(L, L[1:] + L[:1]):
            d = a[0]*b[1] - a[1]*b[0]
            sm = np.array([a[0] + b[0], a[1] + b[1]]) if d == 1 else np.array([a[0] - b[0], a[1] - b[1]])
            ok &= abs(d) == 1 and sm @ G @ sm > Y; nn += 1
check('Theorem 4.3: neighbours on the dial are joined and their sum has gross above Y (%d pairs, 8 observers)' % nn, ok)

# ---------------------------------------------------------------- Section 5: whole rays, chains, parity
def forms(D):
    out = []
    for A in range(1, int(math.sqrt(-D/3)) + 2):
        for B in range(-A, A + 1):
            if (B*B - D) % (4*A): continue
            C = (B*B - D)//(4*A)
            if C < A or (B < 0 and (A == C or -B == A)): continue
            if math.gcd(math.gcd(A, B), C) == 1: out.append((A, B, C))
    return out
ok = ok2 = ok3 = ok4 = True; n = 0; kinds = {}
for D in range(-3, -400, -1):
    if D % 4 not in (0, 1): continue
    for (A, B, C) in forms(D):
        Q = lambda p, q: A*p*p + B*p*q + C*q*q
        ev = sum(1 for k in ((1, 0), (0, 1), (1, 1)) if Q(*k) % 2 == 0)
        ok4 &= ev == (2 if D % 8 == 1 else 0 if D % 8 == 5 else 1)
        for p in range(-6, 7):
            for q in range(0, 7):
                if math.gcd(p, q) != 1 or (q == 0 and p != 1): continue
                x, y = next((r, s) for r in range(-40, 41) for s in range(-40, 41) if p*s - q*r == 1)
                S = Fr(2*A*p*x + B*(p*y + q*x) + 2*C*q*y, 2)
                ok &= Q(p, q)*Q(x, y) == S*S + Fr(-D, 4)                      # the chain identity
                a2, a1, a0 = Q(p, q), int(2*S), Q(x, y)                       # Q(chi_0 + k v)
                vals = [Q(x + k*p, y + k*q) for k in range(-6, 7)]
                ok2 &= all(v == a2*k*k + a1*k + a0 for k, v in zip(range(-6, 7), vals)) \
                       and a1*a1 - 4*a2*a0 == D and math.gcd(math.gcd(a2, a1), a0) == 1
                alleven = all(v % 2 == 0 for v in vals)
                ok3 &= alleven == (D % 8 == 1 and Q(p, q) % 2 == 1) \
                       and not any(all(v % pr == 0 for v in vals) for pr in (3, 5, 7, 11, 13))
                if alleven:                                                   # roots at d = 2 have odd value
                    ok3 &= all(Q(2*x + k*p, 2*y + k*q) % 2 == 1 for k in range(-5, 6, 2))
                n += 1
check('Theorem 5.3: Q(v) Q(chi) = S^2 + |D|/4 for joined roots (%d cases)' % n, ok)
check('Theorem 5.3: the chain is Q(v) k^2 + 2 S_0 k + Q(chi_0), whole, no common factor, number D', ok2)
check('Theorem 5.4: even kinds are 2, 0, 1 for D = 1, 5 (mod 8), D even', ok4)
check('Theorem 5.4: a chain is all even exactly when D = 1 (mod 8) and Q(v) is odd; no other fixed prime', ok3)

N6 = 10**6; pr6 = sieve(N6)
def dial(A, B, C, Y):
    D = B*B - 4*A*C; R = int(math.sqrt(4*C*Y/(-D))) + 2; S_ = int(math.sqrt(4*A*Y/(-D))) + 2
    p = np.arange(-R, R + 1, dtype=np.int64); q = np.arange(0, S_ + 1, dtype=np.int64)
    P, Qq = np.meshgrid(p, q, indexing='ij'); V = A*P*P + B*P*Qq + C*Qq*Qq
    m = (V <= Y) & (V > 0); m &= ~((Qq == 0) & (P <= 0)); m[m] = pr6[V[m]]
    m[m] = np.gcd(V[m], -D) == 1                       # a spoke: the value is a prime that does not divide D
    return P[m], Qq[m], V[m], D
def nearest(A, B, C, Y, v, data):
    P, Qq, V, D = data; Qv = A*v[0]**2 + B*v[0]*v[1] + C*v[1]**2
    d = v[0]*Qq - v[1]*P; keep = (d != 0) & (V > 2)
    s2 = (d[keep].astype(float)**2)*(-D)/(4.0*Qv*V[keep])
    S2 = 2*A*v[0]*P + B*(v[0]*Qq + v[1]*P) + 2*C*v[1]*Qq; side = np.sign(d[keep])*np.sign(S2[keep])
    step = 2 if (D % 8 == 1 and Qv % 2 == 1) else 1
    floor = step*math.sqrt(-D)/(2*math.sqrt(Qv*Y)); res = []
    for sg in (1, -1):
        mm = side == sg; i = np.argmin(s2[mm])
        res.append((math.asin(math.sqrt(s2[mm][i]))/floor, abs(int(d[keep][mm][i]))))
    return Qv, step, res
FORMS = [(1, 0, 1), (1, 1, 2), (1, 1, 4), (2, 1, 2), (1, 0, 5), (2, 2, 3), (1, 1, 6), (2, 1, 3), (2, -1, 3),
         (1, 1, 10), (2, 1, 5), (3, 3, 4), (3, 1, 5)]
ok = True; lo, hi = 9.0, 0.0; twos = 0
print('      nearest spoke on each side, as a multiple of the floor, at Y = 10^6:')
for (A, B, C) in FORMS:
    data = dial(A, B, C, N6); row = []
    for v in [(1, 0), (0, 1), (1, 1), (1, -1), (2, 1), (1, 2)]:
        Qv, step, res = nearest(A, B, C, N6, v, data)
        ok &= all(r[1] == step and r[0] >= 1 - 1e-12 for r in res)
        lo = min(lo, res[0][0], res[1][0]); hi = max(hi, res[0][0], res[1][0]); twos += step == 2
        row.append('%d%s %.3f %.3f' % (Qv, '*' if step == 2 else ' ', res[0][0], res[1][0]))
    print('      (%d,%2d,%2d) D=%4d | ' % (A, B, C, data[3]) + ' | '.join(row))
print('      (value of v, * = step 2; 78 roots, %d of step 2; ratios from %.3f to %.3f)' % (twos, lo, hi))
check('Theorem 5.6 and Proposition 5.8: at 13 observers and 78 roots the nearest spoke has |d| = step, at or above the floor', ok)
check('Proposition 5.8: all 156 ratios lie between 1.000 and 1.220', 1.0 <= lo and hi <= 1.2205)

# ---------------------------------------------------------------- Section 6: the rungs
def conj(a):
    n = len(a)
    if n == 1: return a.copy()
    h = n//2; return np.concatenate([conj(a[:h]), -a[h:]])
def mul(a, b):
    n = len(a)
    if n == 1: return a*b
    h = n//2; a1, a2, b1, b2 = a[:h], a[h:], b[:h], b[h:]
    return np.concatenate([mul(a1, b1) - mul(conj(b2), a2), mul(b2, a1) + mul(a2, conj(b1))])
nrm = lambda a: float(a @ a)
defect = {}
for k, name in ((1, 'R'), (2, 'C'), (4, 'H'), (8, 'O')):
    worst = 0.0
    for _ in range(300):
        x, y, x2, y2 = [rng.integers(-5, 6, k).astype(float) for _ in range(4)]
        ip = mul(conj(x), x2) + mul(conj(y), y2); t = ip[0]; m2 = nrm(ip) - t*t
        T, A_, U = nrm(x) + nrm(y), nrm(x) - nrm(y), 2*mul(x, conj(y))
        T2, A2, U2 = nrm(x2) + nrm(y2), nrm(x2) - nrm(y2), 2*mul(x2, conj(y2))
        gam = T*T2 - A_*A2 - float(U @ U2)
        worst = max(worst, abs(T*T2 - (t*t + m2 + gam/2)))
    defect[name] = worst
check('Theorem 6.1: |psi|^2 |chi|^2 = t^2 + |m|^2 + gamma/2 on R, C, H', max(defect[n] for n in 'RCH') < 1e-9)
check('Theorem 6.1: the identity fails on O', defect['O'] > 1)

def scan(Y, dirs, half=False):
    R = math.isqrt(Y) + 1; pr = sieve(Y + 2); pr[2] = False      # spokes: the gross is an odd prime
    best = {v: (9.0, None, None) for v in dirs}; count = 0; pts = []
    rc = np.arange(-R - 1, R + 1) + (0.5 if half else 0.0)
    B, C, Dd = np.meshgrid(rc, rc, rc, indexing='ij')
    for a in rc:
        Nn = a*a + B*B + C*C + Dd*Dd; Ni = np.rint(Nn).astype(np.int64); m = (Nn <= Y) & (Nn > 0); m[m] = pr[Ni[m]]
        if not m.any(): continue
        b, c, d, n = B[m], C[m], Dd[m], Nn[m]; count += len(n)
        pts.append(np.stack([np.full(len(n), a), b, c, d], 1)/np.sqrt(n)[:, None])
        for v in dirs:
            h = sum(t*t for t in v); dot = v[0]*a + v[1]*b + v[2]*c + v[3]*d; W = h*n - dot*dot; good = W > 1e-9
            if good.any():
                s = W[good]/(h*n[good]); i = np.argmin(s)
                if s[i] < best[v][0]: best[v] = (float(s[i]), float(W[good][i]), int(round(n[good][i])))
    return count, best, np.concatenate(pts)
def least_width(v, half=False, box=4):
    h = sum(t*t for t in v); g = 1e9; r = [t + (0.5 if half else 0) for t in range(-box - 1, box + 1)]
    for w in itertools.product(r, repeat=4):
        W = h*sum(t*t for t in w) - sum(a*b for a, b in zip(v, w))**2
        if W > 1e-9: g = min(g, W)
    return g
Y = 1000
DIRS = [(1, 0, 0, 0), (1, 1, 0, 0), (1, 1, 1, 0), (1, 1, 1, 1), (2, 1, 0, 0), (2, 1, 1, 0), (2, 1, 1, 1), (2, 2, 1, 0), (3, 1, 0, 0)]
count, best, pts = scan(Y, DIRS)
print('      C rung: %d whole roots of odd prime gross at most %d' % (count, Y))
ok = True; widths = []
for v in DIRS:
    h = sum(t*t for t in v); g = least_width(v); s, W, n = best[v]; widths.append(int(g))
    ok &= W == g
    print('      v=%s gross %2d least width %d | nearest spoke: width %d, gross %d, angle/floor %.3f'
          % (v, h, g, W, n, math.asin(math.sqrt(s))/math.sqrt(g/(h*Y))))
check('Proposition 6.4: least widths 1,1,2,3,1,2,3,2,1 for the nine roots', widths == [1, 1, 2, 3, 1, 2, 3, 2, 1])
check('Proposition 6.4: at Y = 1000 the nearest spoke has the least width, for all nine', ok)
check('Proposition 6.4: at the axis the nearest spokes have gross 677 = 26^2 + 1', best[(1, 0, 0, 0)][2] == 677)
ok = True                                                     # the six rows around the axis
for k in range(1, 30):
    for w in [(k, 1, 0, 0), (k, -1, 0, 0), (k, 0, 1, 0), (k, 0, -1, 0), (k, 0, 0, 1), (k, 0, 0, -1)]:
        x, y = complex(w[0], w[1]), complex(w[2], w[3])       # the root (x, y) over C; v = (1, 0)
        m = x.imag; gam2 = abs(y)**2                          # <v,chi> = x: unseen part Im x; gamma/2 = |y|^2
        ok &= (m*m + gam2 == 1) and ((gam2 == 0) == (w[1] != 0)) and sum(t*t for t in w) == k*k + 1
check('Proposition 6.4: the six rows of width 1 at the axis: two unseen (gamma = 0), four seen (m = 0), gross k^2+1', ok)
count2, best2, _ = scan(Y, [(1, 0, 0, 0)], half=True)
check('Remark 6.5: with half-whole roots the least width at the axis is 3/4 and the nearest gross is 757 = 27^2+27+1',
      least_width((1, 0, 0, 0), half=True) == 0.75 and best2[(1, 0, 0, 0)][1] == 0.75 and best2[(1, 0, 0, 0)][2] == 757)

# the count of chance
c = rng.normal(size=(400000, 4)); c /= np.linalg.norm(c, axis=1)[:, None]
dd, _ = cKDTree(pts).query(c); ang = 2*np.arcsin(dd/2)
inside = count*(4/3*math.pi*Y**-1.5)/(2*math.pi**2)
print('      C rung, Y = 1000: forced cap at an axis %.4f holds %.2f spokes by count; largest empty cap at 400000 random centres %.4f'
      % (1/math.sqrt(Y), inside, ang.max()))
check('Proposition 6.6: at Y = 1000 on the C rung chance leaves an empty cap wider than the forced one', ang.max() > 1/math.sqrt(Y))
pr = sieve(20000); P = np.nonzero(pr)[0]
NR = 8*int(((P % 4) == 1).sum()); NC = int(sum(8*(p + 1) for p in P if p > 2)); NH = int(sum(16*(p**3 + 1) for p in P if p > 2))
Yc = 20000.0; est = [4*Yc/math.log(Yc), 4*Yc**2/math.log(Yc), 4*Yc**4/math.log(Yc)]
print('      spokes at Y = 20000: R %d (4Y/lnY = %.0f), C %d (4Y^2/lnY = %.3g), H %.4g (4Y^4/lnY = %.3g)' % (NR, est[0], NC, est[1], NH, est[2]))
check('Proposition 6.6: the counts 4Y/lnY, 4Y^2/lnY, 4Y^4/lnY hold within 15% at Y = 20000',
      all(abs(a/b - 1) < 0.15 for a, b in zip((NR, NC, NH), est)))
CK = {'R': (4/math.pi, 1), 'C': (8/(3*math.pi), 2), 'H': (64/(35*math.pi), 4)}
cross = {}
for name, (ck, k) in CK.items():
    f = lambda L: ck*math.exp(L/2)/L - math.log(4*math.exp(k*L)/L)       # L = ln Y
    a, b = 3.0, 40.0
    for _ in range(80):
        mid = (a + b)/2; a, b = (mid, b) if f(mid) < 0 else (a, mid)
    cross[name] = math.exp(a)
print('      forced cap holds as many spokes as ln(count) at Y = %.3g (R), %.3g (C), %.3g (H)' % (cross['R'], cross['C'], cross['H']))
check('Remark 6.7: the crossings are near 1.4e3, 9e4 and 2e6', 1.0e3 < cross['R'] < 2.0e3 and 5e4 < cross['C'] < 2e5 and 1e6 < cross['H'] < 4e6)

# ---------------------------------------------------------------- Section 7: the count at an observer
def mu(n):
    r = 1; p = 2
    while p*p <= n:
        if n % p == 0:
            n //= p
            if n % p == 0: return 0
            r = -r
        p += 1
    return -r if n > 1 else r
def L_all(Yv, a0, a1):
    R = math.isqrt(int(Yv)); a = np.arange(-R, R + 1); A, B = np.meshgrid(a, a, indexing='ij'); m = (A*A + B*B <= Yv) & ((A != 0) | (B != 0))
    th = np.arctan2(B[m], A[m]); return int(((th >= a0) & (th < a1)).sum())
ok = True
for Yv in (500, 3000, 20000):
    for (a0, a1) in ((0.1, 0.9), (-1.3, 2.2), (0.0, math.pi/2)):
        R = math.isqrt(Yv); a = np.arange(-R, R + 1); A, B = np.meshgrid(a, a, indexing='ij'); m = (A*A + B*B <= Yv) & (np.gcd(A, B) == 1)
        th = np.arctan2(B[m], A[m]); ok &= int(((th >= a0) & (th < a1)).sum()) == sum(mu(k)*L_all(Yv/(k*k), a0, a1) for k in range(1, R + 1))
check('Proposition 7.1: whole roots in an arc of the dial of e = sum over k of mu(k) L(Y/k^2)', ok)

# the modes of the dial of e, and of the cut at infinity
def B_all(Yv, m):
    R = math.isqrt(int(Yv)); a = np.arange(-R, R + 1); A, B = np.meshgrid(a, a, indexing='ij'); k = (A*A + B*B <= Yv) & ((A != 0) | (B != 0))
    return float(np.cos(4*m*np.arctan2(B[k], A[k])).sum())
ok = True
for Yv in (300, 2500, 12000):
    R = math.isqrt(Yv); a = np.arange(-R, R + 1); A, B = np.meshgrid(a, a, indexing='ij'); k = (A*A + B*B <= Yv) & (np.gcd(A, B) == 1)
    for m in (1, 2, 3):
        ok &= abs(float(np.cos(4*m*np.arctan2(B[k], A[k])).sum()) - sum(mu(j)*B_all(Yv/(j*j), m) for j in range(1, R + 1))) < 1e-6
check('Theorem 7.3: at e, the mode over whole roots = sum mu(k) (mode over all pairs up to Y/k^2)', ok)
def Mert(n): return sum(mu(j) for j in range(1, int(n) + 1))
ok = True
for Nn in (30, 97, 240):
    for m in (1, 2, 6, 12):
        direct = sum(cmath.exp(2j*math.pi*m*p/q) for q in range(1, Nn + 1) for p in range(q) if math.gcd(p, q) == 1)
        ok &= abs(direct - sum(d*Mert(Nn/d) for d in range(1, m + 1) if m % d == 0)) < 1e-6
check('Theorem 7.3: at the cut at infinity, the mode m is the sum over d | m of d M(N/d)', ok)

import mpmath as mp
YMAX = 4*10**7; RM = math.isqrt(YMAX); NB = 40000; u0, u1 = math.log(50.0), math.log(YMAX); du = (u1 - u0)/NB
Hm = {m: np.zeros(NB + 1) for m in (0, 1, 2, 3)}
for a in range(2, RM + 1):                    # roots with a > b > 0; the rest by the eight symmetries
    bmax = min(a - 1, math.isqrt(YMAX - a*a))
    if bmax < 1: continue
    b = np.arange(1, bmax + 1); b = b[np.gcd(a, b) == 1]; th = np.arctan2(b, a)
    idx = np.ceil((np.log(a*a + b*b) - u0)/du).astype(int); idx[idx < 0] = 0
    for m in Hm: np.add.at(Hm[m], idx, np.cos(4*m*th) if m else 1.0)
uu = u0 + du*np.arange(NB + 1); YY = np.exp(uu)
Am = {m: 8*np.cumsum(Hm[m]) + 4*(YY >= 1) + 4*((-1)**m)*(YY >= 2) for m in Hm}
total = int(round(Am[0][-1])); Am[0] = Am[0] - 6/math.pi*YY
check('Proposition 7.4: 76394288 pairs without common factor with p^2+q^2 <= 4 x 10^7', total == 76394288)
rms = [math.sqrt(np.mean(Am[m][(YY >= lo) & (YY < 4*lo)]**2))/(2*lo)**0.25 for m in Am for lo in (1e3, 1e4, 1e5, 1e6, 1e7)]
print('      size of the modes over Y^(1/4), by band: from %.2f to %.2f' % (min(rms), max(rms)))
check('Proposition 7.4: every mode stays between 1.6 and 3.0 times Y^(1/4) over the bands from 10^3 to 4 x 10^7', 1.6 < min(rms) and max(rms) < 3.0)
def a_m(m, n):
    s = 0.0
    for a in range(1, math.isqrt(n) + 1):
        b = math.isqrt(n - a*a)
        if b*b == n - a*a: s += math.cos(4*m*math.atan2(b, a))
    return s
def Zm(m, s, N=60):                           # the sum over all pairs, continued to every s
    if m == 0: return 4*mp.zeta(s)*mp.dirichlet(s, [0, 1, 0, -1])
    tot = mp.mpf(0)
    for n in range(1, N + 1):
        a = a_m(m, n)
        if a: x = mp.pi*n; tot += a*(x**(-s)*mp.gammainc(s + 2*m, x) + x**(s - 1)*mp.gammainc(1 - s + 2*m, x))
    return 4*tot*mp.pi**s/mp.gamma(s + 2*m)
ok = abs(Zm(1, mp.mpf(3)) - 4*sum(a_m(1, n)/n**3 for n in range(1, 4000))) < 1e-5
sel = YY >= 2000; us = uu[sel]; win = np.hanning(sel.sum())
def height(m, om): return abs(2*np.sum(Am[m][sel]*np.exp(-us/4)*win*np.exp(-1j*om*us))/np.sum(win))
worst = 0.0
print('      beats at half the zeros: rate, then predicted / measured height for the count and the modes 1, 2, 3')
for kz in range(1, 7):
    z = mp.zetazero(kz); dz = mp.zeta(z, derivative=1); row = []
    for m in (0, 1, 2, 3):
        pred = float(2*abs(Zm(m, z/2))/(abs(z)*abs(dz))); obs_ = height(m, float(z.imag)/2)
        worst = max(worst, abs(pred - obs_)); row.append('%.2f / %.2f' % (pred, obs_))
    print('      %6.3f | ' % (float(z.imag)/2) + ' | '.join(row))
check('Proposition 7.4: the continued sum agrees with the plain sum where both converge', ok)
check('Proposition 7.4: 24 beats at half the first six zeros, measured height within 0.015 of 2|Z_m(rho/2)|/|rho zeta\'(rho)|', worst < 0.015)

# other observers: the count mode
def count_mode(G11, G12, G22, YM, NBm=30000):
    v0, v1 = math.log(50.0), math.log(YM); dv = (v1 - v0)/NBm; Hc = np.zeros(NBm + 1)
    det = G11*G22 - G12*G12; qmax = int(math.sqrt(YM*G11/det)) + 1
    for q in range(0, qmax + 1):
        disc = (G12*q)**2 - G11*(G22*q*q - YM)
        if disc < 0: continue
        p = np.arange(math.ceil((-G12*q - math.sqrt(disc))/G11), math.floor((-G12*q + math.sqrt(disc))/G11) + 1)
        if q == 0: p = p[p > 0]
        p = p[np.gcd(p, q) == 1]
        if len(p) == 0: continue
        g = G11*p*p + 2*G12*p*q + G22*q*q; g = g[g > 0]
        idx = np.ceil((np.log(g) - v0)/dv).astype(int); idx[idx < 0] = 0; np.add.at(Hc, idx[idx <= NBm], 2.0)
    return v0 + dv*np.arange(NBm + 1), np.cumsum(Hc)
def height_of(uv, Sv, om):
    k = np.exp(uv) >= 2000; wv = np.hanning(k.sum()); return abs(2*np.sum(Sv[k]*np.exp(-uv[k]/4)*wv*np.exp(-1j*om*uv[k]))/np.sum(wv))
uv, Nv = count_mode(1.0, 0.5, 2.0, 2*10**7); Sv = Nv - (2*math.pi/math.sqrt(7))*(6/math.pi**2)*np.exp(uv)
worst = 0.0; row = []
for kz in (1, 2, 3):
    z = mp.zetazero(kz)
    pred = float(2*abs(2*mp.zeta(z/2)*mp.dirichlet(z/2, [0, 1, 1, -1, 1, -1, -1]))/(abs(z)*abs(mp.zeta(z, derivative=1))))
    ob = height_of(uv, Sv, float(z.imag)/2); worst = max(worst, abs(pred - ob)); row.append('%.3f / %.3f' % (pred, ob))
print('      observer of value p^2+pq+2q^2: %d pairs with value <= 2 x 10^7; beats ' % int(Nv[-1]) + ', '.join(row))
check('Proposition 7.4 (iv): at the observer of number -7 the three beats are within 0.01 of the predicted heights',
      worst < 0.01 and int(Nv[-1]) == 28874336)
xi_, h_ = 0.3183, 0.7778
uv, Nv = count_mode(1/h_, -xi_/h_, (xi_*xi_ + h_*h_)/h_, 10**7); Sv = Nv - 6/math.pi*np.exp(uv)
spec = np.array([height_of(uv, Sv, o_) for o_ in np.arange(3, 20, 0.05)]); h1 = height_of(uv, Sv, float(mp.zetazero(1).imag)/2)
print('      observer placed at (0.3183, 0.7778): %d pairs; beat at 7.067 of height %.3f; median height over all rates %.3f' % (int(Nv[-1]), h1, np.median(spec)))
check('Proposition 7.4 (iv): at an observer off every whole ray the beat at half the first zero stands out', h1 > 3*np.median(spec))

# Theorem 7.6: the expansion of the sum over whole roots
def Xi(s): return mp.pi**(-s/2)*mp.gamma(s/2)*mp.zeta(s)
def E_direct(x, y, s, Rr=400):
    tot = mp.mpf(0)
    for q in range(0, Rr + 1):
        for p in (range(1, 2) if q == 0 else range(-Rr, Rr + 1)):
            if math.gcd(p, q) == 1: tot += (y/((p - q*x)**2 + (q*y)**2))**s
    return tot
def E_exp(x, y, s, Nt=12):
    tot = y**s + Xi(2*s - 1)/Xi(2*s)*y**(1 - s)
    for n in range(1, Nt + 1):
        sg = sum(mp.mpf(d)**(1 - 2*s) for d in range(1, n + 1) if n % d == 0)
        tot += 2*mp.sqrt(y)/Xi(2*s)*mp.mpf(n)**(s - mp.mpf(1)/2)*sg*mp.besselk(s - mp.mpf(1)/2, 2*mp.pi*n*y)*2*mp.cos(2*mp.pi*n*x)
    return tot
ok = all(abs(E_direct(x_, y_, mp.mpf(3)) - E_exp(x_, y_, mp.mpf(3))) < 1e-5 for (x_, y_) in ((0.0, 1.0), (0.3183, 0.7778), (0.5, math.sqrt(7)/2)))
z1 = mp.zetazero(1); ok &= abs(Xi(z1 - 1) - Xi(2 - z1)) < 1e-15 and abs(Xi(z1 - 1)) > 1e-6
check('Theorem 7.6: the sum over whole roots has the expansion used, with every term over Xi(2s), and Xi(rho-1) is not zero', ok)

print('\n%d checks, %s  (%.0f s)' % (len(ALL), 'all pass' if all(ALL) else 'FAILURES', time.time() - t0))
