#!/usr/bin/env python3 """Unit tests for the exact capped numerator (capped_numerator.py). Control A: with the cap made inert the corrections vanish and J_cap equals J_0. Control B: J_0 from the machinery equals the engine's exact c^T M2 c. Control C: at small k the exact J_cap equals a brute-force quadrature of the capped marginal. """ from __future__ import annotations import os import random import sys from fractions import Fraction as Fr from itertools import permutations from math import factorial import numpy as np HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, os.path.join(HERE, "..", "src")) sys.path.insert(0, os.path.join(HERE, "..", "..", "..", "lib", "maynard")) from even_engine import EvenEngine # noqa: E402 from capped_numerator import (signature_G, signature_T, sig_square, # noqa: E402 sig_GT, sig_T2, correction, correction_laplace, J0_machinery) def msym(points, nu): n = points.shape[1] seen = set() tot = np.zeros(points.shape[0]) lam = list(nu) + [0] * (n - len(nu)) for perm in set(permutations(lam)): if perm in seen: continue seen.add(perm) term = np.ones(points.shape[0]) for i, a in enumerate(perm): if a: term = term * points[:, i] ** a tot += term return tot def eval_F(points, terms, U): s = points.sum(axis=1) out = np.zeros(points.shape[0]) for (c, a, lam) in terms: out = out + float(c) * (U - s) ** a * msym(points, lam) return out def caps(k, B1, B3): c = [Fr(0)] for m in range(1, k + 2): c.append(B1 if m <= 2 else B3) return c def brute(k, terms, U, ell, d, c, N=200000, ng=64, seed=5): rng = np.random.default_rng(seed) E = rng.exponential(1.0, size=(N, k)) X = float(ell) * E[:, :k - 1] / E.sum(axis=1, keepdims=True) s = X.sum(axis=1) H = float(U) - s big = X > float(d) R = (X * big).sum(axis=1) r = big.sum(axis=1) cap = np.array([float(c[min(int(rr), len(c) - 1)]) for rr in r]) legal = R <= cap nxt = np.array([float(c[min(int(rr) + 1, len(c) - 1)]) for rr in r]) h = np.where(legal, np.minimum(H, np.maximum(float(d), nxt - R)), 0.0) h = np.clip(h, 0.0, H) nodes, wts = np.polynomial.legendre.leggauss(ng) tn = 0.5 * (nodes + 1.0) wt = 0.5 * wts full = np.concatenate([np.repeat(X, ng, axis=0), (h[:, None] * tn[None, :]).reshape(-1, 1)], axis=1) Ff = eval_F(full, terms, float(U)).reshape(N, ng) fib = (Ff * wt[None, :]).sum(axis=1) * h vol = float(ell) ** (k - 1) / factorial(k - 1) return k * float((fib ** 2).mean() * vol) def main(): ok = True k, eps, dg = 4, Fr(1, 5), 3 U = 1 + eps ell = 1 - eps d = Fr(3, 10) B1, B3 = Fr(1, 2), Fr(3, 5) c = caps(k, B1, B3) e = EvenEngine(k, eps, dg, "exact") random.seed(4) cvec = [Fr(random.randint(-3, 3), random.randint(1, 3)) for _ in range(e.n)] terms = [(cvec[i], e.B[i][0], tuple(e.B[i][1])) for i in range(e.n)] LG = signature_G(terms) LT = signature_T(terms) sigG2 = sig_square(LG) sigGT = sig_GT(LG, LT) sigT2 = sig_T2(LT) # control B J0 = J0_machinery(k, d, U, ell, sigG2) M2 = sum(cvec[i] * sum(e.M2(i, j) * cvec[j] for j in range(e.n)) for i in range(e.n)) good = (J0 == M2) ok &= good print(f"control B: J0 machinery = {float(J0):.10f} engine M2 = {float(M2):.10f}" f" {'OK' if good else 'MISMATCH'}") # control A: huge caps -> corrections vanish cbig = caps(k, Fr(10), Fr(10)) EC = correction("C", k, d, U, ell, cbig, sigG2, sigGT, sigT2) ED = correction("D", k, d, U, ell, cbig, sigG2, sigGT, sigT2) EE = correction("E", k, d, U, ell, cbig, sigG2, sigGT, sigT2) good = (EC == 0 and ED == 0 and EE == 0) ok &= good print(f"control A: inert cap corrections = {float(EC)},{float(ED)},{float(EE)}" f" {'OK' if good else 'MISMATCH'}") # control C: real cap vs brute force EC = correction("C", k, d, U, ell, c, sigG2, sigGT, sigT2) ED = correction("D", k, d, U, ell, c, sigG2, sigGT, sigT2) EE = correction("E", k, d, U, ell, c, sigG2, sigGT, sigT2) Jcap = J0 + k * (EC + ED + EE) bf = brute(k, terms, U, ell, d, c) rel = abs(float(Jcap) - bf) / abs(bf) if bf else abs(float(Jcap)) good = rel < 0.02 ok &= good print(f"control C: J_cap exact = {float(Jcap):.8e} brute = {bf:.8e}" f" rel={rel:.4f} {'OK' if good else 'MISMATCH'}") # control D: the Laplace (radial-transform) path equals the occurrence path okD = True for K in ("C", "D", "E"): a = correction(K, k, d, U, ell, c, sigG2, sigGT, sigT2) b = correction_laplace(K, k, d, U, ell, c, sigG2, sigGT, sigT2) okD &= (a == b) print(f"control D: region {K}: occurrence={float(a):+.10e} " f"laplace={float(b):+.10e} {'OK' if a == b else 'MISMATCH'}") ok &= okD print("ALL PASS" if ok else "FAILURES PRESENT") return 0 if ok else 1 if __name__ == "__main__": raise SystemExit(main())