#!/usr/bin/env python3 """Numerical verification harness for research programme 0002. Every verification script imports this module. It provides * integer-sqrt helpers that are exact for numpy int64 arrays (no float drift), * the spiral maps of papers 0002.1 and 0002.2, * the arithmetic helpers (admissible set, Liouville, Omega, digit imbalance), * a `Check` recorder that prints PASS / FAIL / INFO lines and writes JSON evidence. Conventions (shared by all scripts): * a slot is a positive integer n; a *twin bond* is the pair (n, n+2); * `A_P` (the twin-admissible set at level z) = { n odd : gcd(n(n+2), P) = 1 }, P = prod of the odd primes <= z (2 is handled by the parity of n); * `k(n) = (isqrt(n-1)+1)//2` is the Ulam ring index; * `Theta_n = sum_{j<=n} arctan(1/sqrt j)`, `Psi_n = arctan(1/sqrt n)`. Nothing here proves anything: these are finite computations. The theorems are proved in the papers; this folder checks every number the papers quote. """ from __future__ import annotations import json import math import os import sys import time from dataclasses import dataclass, field import numpy as np # -------------------------------------------------------------------------- # exact integer square root for numpy integer arrays # -------------------------------------------------------------------------- def isqrt_arr(m): """Exact floor(sqrt(m)) for int64 arrays and scalars (float seed + integer correction).""" m = np.asarray(m, dtype=np.int64) r = np.maximum(np.sqrt(m.astype(np.float64)).astype(np.int64) - 1, 0) while True: rr = r + 1 bad = rr * rr <= m if not bad.any(): return r r = np.where(bad, rr, r) def isqrt_int(n: int) -> int: return math.isqrt(n) # -------------------------------------------------------------------------- # paper 0002.1 -- the Ulam spiral # -------------------------------------------------------------------------- ULAM_CORNERS = ((0, 0), (1, 0), (1, 1), (0, 1), (-1, 1), (-1, 0), (-1, -1), (0, -1), (1, -1)) def ulam_xy(m): """Ulam map u(n) = (x, y); scalar (int) or int64-array in, same type out. Ring k = (isqrt(n-1)+1)//2 holds (2k-1)^2 < n <= (2k+1)^2. m = n - (2k-1)^2 in [1, 8k]; the four edges are traversed in the order right (up), top (left), left (down), bottom (right). """ scalar = np.isscalar(m) or (isinstance(m, np.ndarray) and m.ndim == 0) n = np.asarray(m, dtype=np.int64) k = (isqrt_arr(n - 1) + 1) // 2 mm = n - (2 * k - 1) ** 2 x = np.where(mm <= 2 * k, k, np.where(mm <= 4 * k, 3 * k - mm, np.where(mm <= 6 * k, -k, mm - 7 * k))) y = np.where(mm <= 2 * k, mm - k, np.where(mm <= 4 * k, k, np.where(mm <= 6 * k, 5 * k - mm, -k))) x = np.where(n == 1, 0, x) y = np.where(n == 1, 0, y) if scalar: return int(x), int(y) return x, y def ulam_ring(n): """Ring index k(n); scalar or array.""" scalar = np.isscalar(n) or (isinstance(n, np.ndarray) and n.ndim == 0) a = (isqrt_arr(np.asarray(n, dtype=np.int64) - 1) + 1) // 2 return int(a) if scalar else a def ulam_edge_id(n): """(ring, edge index in {0,1,2,3}) for the Ulam map.""" x, y = ulam_xy(n) k = np.maximum(np.abs(x), np.abs(y)) e = np.where(x == k, 0, np.where(y == k, 1, np.where(x == -k, 2, 3))) return k.astype(np.int64), e.astype(np.int64) def ulam_psi(n, dps: int | None = None): """Co-rotation phase Psi(n) = arg u(n+2) - arg u(n), wrapped to (-pi, pi]. `dps=None` uses float64; `dps=k` uses mpmath at k digits (slow, scalar only). """ if dps is not None: from mpmath import mp, atan2, mpf, pi with mp.workdps(dps): x1, y1 = ulam_xy(int(n)) x2, y2 = ulam_xy(int(n) + 2) d = atan2(mpf(y2), mpf(x2)) - atan2(mpf(y1), mpf(x1)) return float((d + pi) % (2 * pi) - pi) n = np.asarray(n, dtype=np.int64) x1, y1 = ulam_xy(n) x2, y2 = ulam_xy(n + 2) d = np.arctan2(y2, x2) - np.arctan2(y1, x1) return (d + np.pi) % (2 * np.pi) - np.pi # -------------------------------------------------------------------------- # paper 0002.2 -- the Theodorus (square-root) spiral # -------------------------------------------------------------------------- def theodorus_w(N: int): """w_0..w_N in mpmath at the current working precision (|w_n| = 1, arg = Theta_n).""" from mpmath import mp, mpc, sqrt, mpf W = [mpc(1, 0)] for n in range(1, N + 1): W.append(W[-1] * (1 + 1j / sqrt(n)) / sqrt(1 + mpf(1) / n)) return W def theodorus_theta(n): """Theta_n = sum_{j<=n} arctan(1/sqrt j), mpmath at current precision.""" from mpmath import mp, atan, sqrt return mp.fsum([atan(1 / sqrt(j)) for j in range(1, n + 1)]) def theodorus_theta_np(M: int) -> np.ndarray: """float64 array Theta_1..Theta_M by cumulative summation (Theta_0 = 0 prepended).""" j = np.arange(1, M + 1, dtype=np.float64) return np.concatenate(([0.0], np.cumsum(np.arctan(1.0 / np.sqrt(j))))) def C_series(K: int = 151): """Partial sum S_K of C = sum_{k>=0} (-1)^k/(2k+1) zeta(k+1/2) (mpmath). S_150 and S_151 bracket the limit; their midpoint is the running estimate. """ from mpmath import mp, zeta, mpf return mp.fsum([((-1) ** k / (2 * k + 1)) * zeta(mpf(2 * k + 1) / 2) for k in range(K)]) def C_bracket(): """(S_150, S_151, midpoint) -- the verified bracket for the Theodorus constant.""" lo, hi = C_series(150), C_series(151) return lo, hi, (lo + hi) / 2 # -------------------------------------------------------------------------- # arithmetic helpers (papers 0002.3, 0002.4) # -------------------------------------------------------------------------- def spf_table(N: int) -> np.ndarray: """Smallest-prime-factor table up to N (exact; used for Omega and lambda).""" spf = np.arange(N + 1, dtype=np.int64) for i in range(2, math.isqrt(N) + 1): if spf[i] == i: spf[i * i:: i] = np.minimum(spf[i * i:: i], i) return spf def omega_table(N: int) -> np.ndarray: """Omega(n) = number of prime factors with multiplicity, n <= N.""" spf = spf_table(N) Om = np.zeros(N + 1, dtype=np.int64) for m in range(2, N + 1): Om[m] = Om[m // spf[m]] + 1 return Om def lambda_table(N: int) -> np.ndarray: """Liouville lambda(n) = (-1)^Omega(n), n <= N.""" Om = omega_table(N) return np.where(Om % 2 == 0, 1, -1).astype(np.int64) def prime_mask(N: int) -> np.ndarray: is_p = np.ones(N + 1, dtype=bool) is_p[:2] = False for i in range(2, math.isqrt(N) + 1): if is_p[i]: is_p[i * i:: i] = False return is_p def odd_primes_upto(z: int): return [p for p in range(3, z + 1, 2) if all(p % q for q in range(3, math.isqrt(p) + 1, 2))] def primorial(z: int) -> int: P = 1 for p in odd_primes_upto(z): P *= p return P def admissible_mask(n: np.ndarray, Q) -> np.ndarray: """Boolean mask of the twin-admissible openers: n odd and gcd(n(n+2), prod Q) = 1.""" ok = (n % 2 == 1) for q in Q: ok &= (n % q != 0) & ((n + 2) % q != 0) return ok def digits_base(n: int, b: int): d = [] while n: d.append(n % b) n //= b return d or [0] def digit_imbalance(n: int, b: int) -> float: """D_b(n) = (s_b(n) - ((b-1)/2) L_b(n)) / sqrt(L_b(n)).""" d = digits_base(n, b) L = len(d) return (sum(d) - (b - 1) / 2 * L) / math.sqrt(L) # -------------------------------------------------------------------------- # check recorder # -------------------------------------------------------------------------- @dataclass class Check: """Records PASS/FAIL/INFO checks and writes them as JSON evidence.""" script: str paper: str results: list = field(default_factory=list) t0: float = field(default_factory=time.time) def record(self, name: str, ok, detail: str = "", info: bool = False): status = "INFO" if info else ("PASS" if ok else "FAIL") self.results.append({"check": name, "status": status, "detail": str(detail)[:400], "ok": bool(ok)}) marker = {"PASS": " PASS", "FAIL": " FAIL", "INFO": " INFO"}[status] print(f"{marker} {name}" + (f" [{detail}]" if detail else ""), flush=True) return ok def close(self, outdir: str): n_pass = sum(1 for r in self.results if r["status"] == "PASS") n_fail = sum(1 for r in self.results if r["status"] == "FAIL") n_info = sum(1 for r in self.results if r["status"] == "INFO") payload = {"script": self.script, "paper": self.paper, "seconds": round(time.time() - self.t0, 2), "n_pass": n_pass, "n_fail": n_fail, "n_info": n_info, "results": self.results} os.makedirs(outdir, exist_ok=True) path = os.path.join(outdir, self.script.replace(".py", "") + ".json") with open(path, "w") as f: json.dump(payload, f, indent=2) print(f" ---- {n_pass} passed, {n_fail} failed, {n_info} info " f"({payload['seconds']}s) -> {os.path.basename(path)}", flush=True) return n_fail def run(paper: str, fn): """Standard entry point: banner, checks, JSON evidence, non-zero exit on FAIL.""" script = os.path.basename(sys.argv[0]) chk = Check(script=script, paper=paper) outdir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "evidence") print(f"== {script} (paper {paper}) ==", flush=True) fn(chk) fails = chk.close(outdir) sys.exit(1 if fails else 0)