#!/usr/bin/env python3 """Cosine-kernel investigation for twin primes (exploratory, measured rung). Correct statement of the cosine (Ramanujan-sum) kernel as a twin-prime detector. For a prime p, the Ramanujan sum is c_p(n) = sum_{a=1}^{p-1} cos(2*pi*a*n/p) (the "cosine kernel") and it satisfies c_p(n) = p - 1 if p | n, else -1. Consequently the coprimality indicator is EXACTLY 1_{p ∤ n} = (p - 1 - c_p(n)) / p, i.e. the cosine kernel is the precise oscillatory term of the prime sieve. The twin sieve at scale z is the product over p <= z of 1_{p∤n} * 1_{p∤n+2}: I_z(n) = prod_{p<=z} (p-1-c_p(n))*(p-1-c_p(n+2)) / p^2 = 1 iff n and n+2 are coprime to every prime <= z = 0 otherwise. This is exact. The script verifies the two identities and measures how the Ramanujan cosine kernel localises twin primes versus alternative phase kernels (Dirichlet = cosine over ALL residues; Gaussian-smoothed phases). """ import json, math, time import numpy as np def sieve_primes(N): is_p = np.ones(N + 1, dtype=bool) is_p[:2] = False for i in range(2, int(N**0.5) + 1): if is_p[i]: is_p[i*i::i] = False return is_p def ramanujan_cp(p): """c_p(n) for n in 0..p-1 by direct cosine sum over coprime residues.""" c = np.zeros(p) for n in range(p): c[n] = round(sum(math.cos(2*math.pi*a*n/p) for a in range(1, p))) return c def cp_closed(n, p): """Closed form c_p(n) = p-1 if p|n else -1.""" return (p - 1) if (n % p == 0) else -1 def main(): N = 1_000_000 z = 200 t0 = time.time() is_p = sieve_primes(N) primes = np.flatnonzero(is_p) twin_positions = np.flatnonzero(is_p[3:N-1] & is_p[5:N+1]) + 3 small_primes = [p for p in primes if p <= z] print(f"sieve: {len(primes)} primes <= {N}; {len(twin_positions)} twin pairs; " f"{len(small_primes)} primes <= z={z}; {time.time()-t0:.1f}s") # 1. verify c_p(n) closed form and the coprimality identity for each small prime verifications = [] for p in small_primes: c = ramanujan_cp(p) ok_closed = all(c[n] == cp_closed(n, p) for n in range(p)) # 1_{p∤n} = (p-1 - c_p(n))/p ok_ind = all(((p - 1 - c[n]) == p) if (n % p != 0) else ((p - 1 - c[n]) == 0) for n in range(p)) verifications.append({"p": int(p), "c_p(n)=p-1 if p|n else -1": bool(ok_closed), "1_{p∤n}=(p-1-c_p(n))/p": bool(ok_ind)}) all_ok = all(v["c_p(n)=p-1 if p|n else -1"] and v["1_{p∤n}=(p-1-c_p(n))/p"] for v in verifications) print(f"cosine-kernel identities verified over {len(small_primes)} primes: {all_ok}") # 2. exact twin sieve via the cosine kernel (product form), computed by closed form n = np.arange(3, N + 1, dtype=np.int64) Iz = np.ones(N + 1) Iz[0:3] = 0.0 for p in small_primes: cpn = np.where(n % p == 0, p - 1, -1) cpn2 = np.where((n + 2) % p == 0, p - 1, -1) Iz[3:] *= ((p - 1 - cpn) / p) * ((p - 1 - cpn2) / p) Iz[3:] = (Iz[3:] >= 1.0 - 1e-12).astype(int) # exact 0/1 (floating product of exact rationals) # direct reference: n and n+2 coprime to all p<=z idx = np.arange(N + 1) ref = np.ones(N + 1, dtype=bool) for p in small_primes: ref &= ((idx % p) != 0) ref &= ((np.minimum(idx + 2, N) % p) != 0) agree = bool((Iz[3:N-1] == ref[3:N-1]).all()) print(f"I_z(n) equals direct twin-sieve indicator for all 3<=n<=N-2: {agree}") # 3. localization of the Ramanujan cosine sieve vs alternative kernels rng = np.random.default_rng(0) composite = np.flatnonzero(~is_p & (np.arange(N + 1) >= 6)) sample = rng.choice(composite, size=len(twin_positions), replace=False) pos = np.concatenate([twin_positions, sample]).astype(np.int64) def build_weight(p, kernel): """Sieve weight at positions `pos` for prime p with a given phase kernel. kernel(a, nv, p) -> array over nv of sum_a kernel(a,nv,p) [the c_p-like term].""" nn = pos total = np.ones(len(pos)) for q in small_primes: cq1 = kernel(q, nn) cq2 = kernel(q, nn + 2) total *= ((q - 1 - cq1) / q) * ((q - 1 - cq2) / q) return total # Ramanujan cosine kernel (closed form): c_p(n)=p-1 if p|n else -1 def k_ramanujan(q, nn): return np.where(nn % q == 0, q - 1, -1.0) # Dirichlet (all residues): S_p(n)=p if p|n else 0 def k_dirichlet(q, nn): return np.where(nn % q == 0, q, 0.0) # Gaussian-smoothed phases: sum_{a=1}^{q-1} exp(-a^2/2s^2) cos(2pi a n/q) def k_gaussian(q, nn): s = 2.0 acc = np.zeros(len(nn)) for a in range(1, q): acc += math.exp(-(a*a)/(2*s*s)) * np.cos(2*math.pi*a*nn/q) return acc w_ramanujan = build_weight(None, k_ramanujan) w_dirichlet = build_weight(None, k_dirichlet) w_gaussian = build_weight(None, k_gaussian) def localization(w): n_tw = len(twin_positions) tw = w[:n_tw]; ntw = w[n_tw:] return float((tw.mean() - ntw.mean()) / (tw.std() + ntw.std() + 1e-12)) loc_ramanujan = localization(w_ramanujan) loc_dirichlet = localization(w_dirichlet) loc_gaussian = localization(w_gaussian) print("kernel localization (higher = sharper twin separation):") print(f" ramanujan_cosine {loc_ramanujan:+.3f} (exact 0/1 twin sieve)") print(f" dirichlet_all_residues{loc_dirichlet:+.3f}") print(f" gaussian_smoothed {loc_gaussian:+.3f}") # 4. precision: among n where I_z=1 in [z+2, N], how many are actual twin primes pos = np.flatnonzero((Iz == 1) & (np.arange(N + 1) >= z + 2)) pos_twin = is_p[pos] & is_p[np.minimum(pos + 2, N)] precision = float(pos_twin.mean()) if len(pos) else float('nan') recall = float(Iz[twin_positions].mean()) print(f"twin-sieve precision over max set ({len(pos)} positions): {precision:.4%}; recall on twins: {recall:.4%}") out = { "N": N, "z": z, "num_primes": int(len(primes)), "num_twins": int(len(twin_positions)), "identities_verified": all_ok, "identity_details": verifications, "sieve_equals_direct_indicator": agree, "localization": {"ramanujan_cosine": loc_ramanujan, "dirichlet_all_residues": loc_dirichlet, "gaussian_smoothed": loc_gaussian}, "precision_recall": {"precision": precision, "recall": recall, "max_set_size": int(len(pos))}, "note": ("cosine (Ramanujan) kernel is the exact oscillatory term of the twin sieve; " "it is a 0/1 detector. Alternatives (Dirichlet, Gaussian) lose the indicator " "property. Measured rung; no proof of twin-prime infinitude."), } with open("outputs/kernel_results.json", "w") as f: json.dump(out, f, indent=2) print("wrote outputs/kernel_results.json") if __name__ == "__main__": main()