#!/usr/bin/env python3
"""
Guideng Math Paper 23.  Whole Roots on the Circle.
Numerical verification of every statement.  Requires numpy only.

Conventions (Paper 12): a root is (x, y), real; its cut is c = (x^2+y^2 ; x^2-y^2 , 2xy);
G(X) = [[t+a, u], [u, t-a]], so G(c(psi)) = 2 psi psi^T and det G(X) = eta(X,X);
a change of view A acts on roots, and L_A on the space by G(L_A X) = A G(X) A^T.
"""
import numpy as np, math, sys, itertools

rng = np.random.default_rng(23)
results = []
def check(label, cond):
    results.append(bool(cond)); print('[%s] %2d. %s' % ('ok' if cond else 'FAIL', len(results), label))
ok = lambda a, b, tol=1e-8: np.allclose(a, b, rtol=1e-8, atol=tol)

cut = lambda p: np.array([p[0] ** 2 + p[1] ** 2, p[0] ** 2 - p[1] ** 2, 2 * p[0] * p[1]], float)
eta = lambda X, Y: X[0] * Y[0] - X[1] * Y[1] - X[2] * Y[2]
G = lambda X: np.array([[X[0] + X[1], X[2]], [X[2], X[0] - X[1]]])
unG = lambda g: np.array([(g[0, 0] + g[1, 1]) / 2, (g[0, 0] - g[1, 1]) / 2, g[0, 1]])
L = lambda A, X: unG(A @ G(X) @ A.T)
rest = lambda K: math.sqrt(max(eta(K, K), 0.0))
mark = lambda K: np.array([K[2], rest(K)]) / (K[0] - K[1])              # (xi, h)
point = lambda xi, h: unG(np.array([[xi * xi + h * h, xi], [xi, 1.0]]) / h)   # the observer at (xi, h)
e = np.array([1.0, 0.0, 0.0])
J = np.array([[0, -1], [1, 0]]); T = np.array([[1, 1], [0, 1]])
N = 14
prim = [(p, q) for q in range(0, N + 1) for p in range(-N, N + 1)
        if math.gcd(p, q) == 1 and (q > 0 or p == 1)]                    # one of each pair psi, -psi
det = lambda a, b: a[0] * b[1] - a[1] * b[0]
def word(n):
    A = np.eye(2, dtype=int)
    for _ in range(n): A = A @ [J, T, np.array([[1, -1], [0, 1]])][rng.integers(3)]
    return A

# ---------------------------------------------------------------- Theorem 3.2: the picture
r = [True] * 5
for _ in range(300):
    psi, chi = rng.normal(size=2), rng.normal(size=2); X, Y = cut(psi), cut(chi)
    r[0] &= ok(mark(X + 1e-15 * Y)[0], psi[0] / psi[1]) and ok(eta(X, X), 0, 1e-7)
    xi, h = rng.normal(), abs(rng.normal()) + 0.1; o = point(xi, h)
    r[1] &= ok(eta(o, o), 1) and o[0] > 0 and ok(mark(o), [xi, h]) and ok(mark(3.7 * o), [xi, h])
    A = rng.normal(size=(2, 2)); A = A / math.sqrt(abs(np.linalg.det(A)))
    if np.linalg.det(A) < 0: A = A @ np.diag([1, -1])
    z = complex(xi, h); w = (A[0, 0] * z + A[0, 1]) / (A[1, 0] * z + A[1, 1])
    r[2] &= ok(mark(L(A, o)), [w.real, w.imag]) and ok(L(A, X), cut(A @ psi))
    al, be = rng.uniform(0.1, 3), rng.uniform(0.1, 3); K = al * X + be * Y
    r1, r2 = psi[0] / psi[1], chi[0] / chi[1]; pl = mark(K)
    r[3] &= ok((pl[0] - (r1 + r2) / 2) ** 2 + pl[1] ** 2, ((r1 - r2) / 2) ** 2)
    # every point of the half-circle arises
    th = rng.uniform(0.05, np.pi - 0.05); target = np.array([(r1 + r2) / 2 + abs(r1 - r2) / 2 * np.cos(th), abs(r1 - r2) / 2 * np.sin(th)])
    o2 = point(*target); sol = np.linalg.lstsq(np.column_stack([X, Y]), o2, rcond=None)
    r[4] &= ok(np.column_stack([X, Y]) @ sol[0], o2, 1e-6) and sol[0].min() > 0
    # in the disc: the cut sum of gross 1 lies on the chord between the two cuts of gross 1
    d = lambda Z: Z[1:] / Z[0]
    r[3] &= ok(np.cross(np.append(d(K) - d(X), 0), np.append(d(Y) - d(X), 0))[2], 0)
check('Theorem 3.2(a): the cut of (x, y) sits at x/y on the line', r[0])
check('Theorem 3.2(a): the rays of forward points with rest gross > 0 are the points above the line; observers one to one', r[1])
check('Theorem 3.2(b): a change of view moves the picture by xi + ih -> (a z + b)/(c z + d)', r[2])
check('Theorem 3.2(c): a system of two cuts lies on the half-circle on the two; in the disc, on the chord', r[3])
check('Theorem 3.2(c): every point of the half-circle is such a system', r[4])

# ---------------------------------------------------------------- Theorem 4.2: joined whole roots
check('Theorem 4.2(a): the ghost term of two whole cuts is 2 (ps - qr)^2',
      all(ok(eta(cut(a), cut(b)), 2 * det(a, b) ** 2) for a in prim for b in prim))
gh = sorted({round(eta(cut(a), cut(b))) for a in prim for b in prim if a != b})
check('Theorem 4.2(b): the least ghost term of two different whole cuts is 2; the values are 2 n^2', gh[0] == 2 and gh[:4] == [2, 8, 18, 32])
joined = [(a, b) for a in prim for b in prim if a < b and abs(det(a, b)) == 1]
good = True
for a, b in joined:
    M = np.array([[a[0], b[0]], [a[1], b[1]]]);  M = M if det(a, b) == 1 else M @ np.diag([1, -1])
    good &= round(np.linalg.det(M)) == 1 and ok(L(M, cut((1, 0))), cut(a)) and ok(L(M, cut((0, 1))), cut(b))
check('Theorem 4.2(c): every joined pair is the image of (1,0), (0,1) under a whole change of view (%d pairs)' % len(joined), good)
small = [p for p in prim if abs(p[0]) <= 6 and p[1] <= 6]; good = True
for a, b in joined:
    if a in small and b in small and max(abs(a[0]) + abs(b[0]), a[1] + b[1]) <= N:
        both = {c for c in prim if abs(det(a, c)) == 1 and abs(det(b, c)) == 1}
        norm = lambda c: c if (c[1] > 0 or (c[1] == 0 and c[0] > 0)) else (-c[0], -c[1])
        good &= both == {norm((a[0] + b[0], a[1] + b[1])), norm((a[0] - b[0], a[1] - b[1]))}
check('Theorem 4.2(d): exactly two whole roots are joined to both: the sum and the difference', good)
good = True
for a, b in joined[:400]:
    K1 = cut(a) + cut(b); good &= ok(rest(K1), 2)
ties = sorted({round(rest(cut(a) + cut(b))) for a in prim for b in prim if a != b})
check('Theorem 4.2(e): as a root in two places a pair has tie 2|ps - qr|; the least tie is 2, exactly for joined pairs', good and ties[:3] == [2, 4, 6])

# ---------------------------------------------------------------- Theorem 5.1: the bound
r = [True] * 2
for _ in range(20000):
    o = point(rng.normal(), abs(rng.normal()) + 0.05); X, Y = cut(rng.normal(size=2)), cut(rng.normal(size=2))
    r[0] &= eta(o, X) * eta(o, Y) >= eta(X, Y) / 2 - 1e-9
    K = X + Y; o2 = K / rest(K)                                   # the observer who reads no net
    r[1] &= ok(eta(o2, X) * eta(o2, Y), eta(X, Y) / 2) and ok(eta(o2, X), eta(o2, Y))
check('Theorem 5.1: gross(X) gross(Y) >= ghost term(X,Y)/2 for every observer', r[0])
check('Theorem 5.1: equality for the observer along the cut sum, who reads the two cuts as opposite and equal', r[1])

# ---------------------------------------------------------------- Theorem 5.3: touching circles
r = [True] * 3
for _ in range(4000):
    xi, h = rng.uniform(-3, 3), rng.uniform(0.01, 2.5); o = point(xi, h)
    p, q = prim[rng.integers(len(prim))]
    gross = eta(o, cut((p, q)))
    r[0] &= ok(gross, ((p - q * xi) ** 2 + q * q * h * h) / h)
    if q > 0:
        inside = (xi - p / q) ** 2 + (h - 1 / (2 * q * q)) ** 2 < (1 / (2 * q * q)) ** 2
        r[1] &= (gross < 1) == inside
    else:
        r[1] &= (gross < 1) == (h > 1)
    r[2] &= sum(eta(o, cut(c)) < 1 - 1e-12 for c in prim) <= 1
check('Theorem 5.3(a): gross of (p,q) read by the observer at (xi,h) is ((p - q xi)^2 + q^2 h^2)/h', r[0])
check('Theorem 5.3(a): gross < 1 exactly inside the circle of diameter 1/q^2 touching the line at p/q (h > 1 for (1,0))', r[1])
check('Theorem 5.3(b): no observer reads two different whole roots with gross below 1', r[2])
good = [True] * 4; n_touch = 0
for a in small:
    for b in small:
        if a >= b: continue
        # do the two circles touch?
        if a[1] > 0 and b[1] > 0:
            dist2 = (a[0] / a[1] - b[0] / b[1]) ** 2 + (1 / (2 * a[1] ** 2) - 1 / (2 * b[1] ** 2)) ** 2
            touch = ok(dist2, (1 / (2 * a[1] ** 2) + 1 / (2 * b[1] ** 2)) ** 2)
        else:
            c = a if a[1] > 0 else b; touch = (c[1] == 1)
        good[0] &= touch == (abs(det(a, b)) == 1)
        if touch:
            n_touch += 1; o = (cut(a) + cut(b)) / 2
            good[1] &= ok(eta(o, o), 1) and ok(eta(o, cut(a)), 1) and ok(eta(o, cut(b)), 1)
            g = G(o); good[2] &= ok(g, np.round(g)) and ok(np.linalg.det(g), 1)
            ones = [c for c in prim if abs(eta(o, cut(c)) - 1) < 1e-9]
            good[3] &= sorted(ones) == sorted([a, b]) and all(eta(o, cut(c)) > 1 - 1e-9 for c in prim)
check('Theorem 5.3(c): two circles touch exactly when the roots are joined', good[0])
check('Theorem 5.3(c): they touch at half the cut sum, an observer who reads both with gross 1 (%d touching pairs)' % n_touch, good[1])
check('Theorem 5.4(a): the touching point is a whole observer: G(o) is whole with determinant 1', good[2])
check('Theorem 5.4(a): it reads exactly those two whole roots with gross 1 and every other with more', good[3])

# ---------------------------------------------------------------- Theorem 5.4: whole observers, fixed points
r = [True] * 4
for _ in range(300):
    A = word(rng.integers(1, 9)); a, b = tuple(A[:, 0]), tuple(A[:, 1])
    o = L(A, e)
    r[0] &= ok(o, (cut(a) + cut(b)) / 2) and abs(det(a, b)) == 1
    Ai = np.round(np.linalg.inv(A)).astype(int)
    Q = A @ J @ Ai                                               # a whole quarter turn
    XQ = unG((Q - np.round(np.linalg.inv(Q))) @ J / 2)
    r[1] &= ok(L(Q, o), o) and ok(XQ * o[0], o * XQ[0]) and round(np.trace(Q)) == 0
    R = A @ np.array([[0, -1], [1, 1]]) @ Ai                     # a whole turn of order three on the space
    XR = unG((R - np.round(np.linalg.inv(R))) @ J / 2); XR = XR if XR[0] > 0 else -XR
    c3 = (b[0] - a[0], b[1] - a[1])
    g3 = [eta(XR, cut(c)) for c in (a, b, c3)]
    r[2] &= ok(L(R, XR), XR) and abs(round(np.trace(R))) == 1 and ok(g3[0], g3[1]) and ok(g3[1], g3[2]) and ok(eta(XR, XR), 0.75)
    oc = XR / rest(XR); r[3] &= ok(eta(oc, cut(a)), 2 / math.sqrt(3))
check('Theorem 5.4(a): every whole observer L_A e is half the cut sum of the columns of A, a joined pair', r[0])
check('Theorem 5.4(b): it is the fixed point of the whole quarter turn A J A^-1 (trace 0)', r[1])
check('Theorem 5.4(c): the whole turn of trace +-1 fixes the point that reads the three roots of a triangle equally; even form 3/4', r[2])
check('Theorem 5.4(c): the observer there reads each of the three with gross 2/sqrt 3', r[3])

# ---------------------------------------------------------------- Section 6: how evenly the whole cuts are spaced
def signs(n):                                    # the signs mu(1..n) of Paper 10, by a sieve
    mu = np.ones(n + 1, dtype=int); pr = np.ones(n + 1, dtype=bool); mu[0] = 0
    for p in range(2, n + 1):
        if pr[p]:
            pr[2 * p::p] = False; mu[p::p] *= -1; mu[p * p::p * p] = 0
    return mu
NMAX = 3000; Mnet = np.cumsum(signs(NMAX))       # Mnet[x] = net of the signs up to x
def order(Nn):                                   # the whole roots (p,q), 0 < p <= q <= Nn, in order of mark
    a, b, c, d = 0, 1, 1, Nn; out = []
    while c <= Nn:
        k = (Nn + b) // d; a, b, c, d = c, d, k * c - a, k * d - b; out.append((a, b))
    return out
Nn = 60; W = order(Nn); inf = cut((1, 0))
check('Theorem 6.2(a): q <= N exactly when the ghost term with the cut of (1,0) is at most 2 N^2',
      sorted(W) == sorted((p, q) for q in range(1, Nn + 1) for p in range(1, q + 1) if math.gcd(p, q) == 1)
      and all(ok(eta(inf, cut(w)), 2 * w[1] ** 2) for w in W))
good = True
for _ in range(300):
    a, b = rng.normal(size=2), rng.normal(size=2); X, Y = cut(a), cut(b)
    good &= ok((a[0] / a[1] - b[0] / b[1]) ** 2, 2 * eta(X, Y) / (eta(X, inf) * eta(Y, inf)))
check('Theorem 6.2(b): (distance of two marks)^2 = 2 ghost(X,Y) / (ghost(X,inf) ghost(Y,inf))', good)
check('Theorem 6.2(c): neighbours in the order are joined, their sum is outside the order, and the gap is 1/(q q\')',
      all(abs(det(W[i], W[i + 1])) == 1 and W[i][1] + W[i + 1][1] > Nn
          and ok(W[i + 1][0] / W[i + 1][1] - W[i][0] / W[i][1], 1 / (W[i][1] * W[i + 1][1])) for i in range(len(W) - 1)))
fs = (lambda x: x * x, lambda x: math.cos(7 * x), lambda x: math.exp(-x), lambda x: 1.0 if x <= 0.37 else 0.0)
check('Theorem 6.3(a): a sum over the whole roots of order N = sum_k M(N/k) (sum over all roots (j,k), j <= k)',
      all(ok(sum(f(p / q) for p, q in W), sum(Mnet[Nn // k] * sum(f(j / k) for j in range(1, k + 1)) for k in range(1, Nn + 1))) for f in fs))
good = ok(len(W), sum(Mnet[Nn // k] * k for k in range(1, Nn + 1)))
for x in rng.uniform(0, 1, 60):
    good &= ok(sum(1 for p, q in W if p / q <= x) - len(W) * x, -sum(Mnet[Nn // k] * ((k * x) % 1.0) for k in range(1, Nn + 1)), 1e-7)
check('Theorem 6.3(b): the miscount up to x is  - sum_k M(N/k) frac(k x)', good)
def misplaced(Nn):
    W = order(Nn); A = len(W); d = np.array([p / q for p, q in W]) - np.arange(1, A + 1) / A
    return A, np.abs(d).sum(), (d * d).sum()
Nn = 40; A, _, s2 = misplaced(Nn)
fr = sum(Mnet[Nn // a] * Mnet[Nn // b] * math.gcd(a, b) ** 2 / (a * b) for a in range(1, Nn + 1) for b in range(1, Nn + 1))
check('Theorem 6.3(c): sum of squared misplacements = (1/12A)(sum_{a,b} M(N/a) M(N/b) gcd(a,b)^2/(ab) - 1)', ok(s2, (fr - 1) / (12 * A)))
good = True
print('        N    whole cuts   total misplacement   / sqrt N    net of the signs M(N)')
for Nn in (100, 300, 1000, 3000):
    A, s1, s2 = misplaced(Nn); good &= s1 < math.sqrt(Nn)
    print('    %5d   %9d   %10.3f          %6.3f      %4d' % (Nn, A, s1, s1 / math.sqrt(Nn), Mnet[Nn]))
check('Section 6: the total misplacement is below sqrt N for N = 100, 300, 1000, 3000', good)

print('\n%d checks, %d passed' % (len(results), sum(results)))
sys.exit(0 if all(results) else 1)
