#!/usr/bin/env python3 """Unit tests for the exact capped-moment identity (research/0025). Control 1: with delta = U and B = 0 the cap is inert and the capped integral must equal Lemma 4.19 (eprint 2026/1893) exactly. Control 2: for small n a direct Monte-Carlo estimate of the same integral must agree to Monte-Carlo accuracy. Control 3: monotonicity in the cap budget B_r. """ from __future__ import annotations import os import sys from fractions import Fraction as Fr 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")) from capped_moment import (capped_integral, uncapped_integral, mult, # noqa: E402 expand) def msym(points, nu): """m_nu at rows of points (N,n), brute force over distinct monomials.""" from itertools import permutations 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 mc_integral(n, e, nu, U, delta, Bfun, N=400000, seed=7): rng = np.random.default_rng(seed) E = rng.exponential(1.0, size=(N, n + 1)) T = U * E[:, :n] / E.sum(axis=1, keepdims=True) s = T.sum(axis=1) big = T > delta R = (T * big).sum(axis=1) r = big.sum(axis=1) cap = np.array([Bfun(int(rr)) for rr in r], dtype=float) f = (U - s) ** e * msym(T, nu) vol = U ** n / factorial(n) return float((f * (cap >= R)).mean() * vol) def main(): U = Fr(1) ok = True # control 1 print("control 1: inert cap == Lemma 4.19") for nu in [(2,), (2, 2), (4, 2), (2, 2, 2)]: for e in (0, 1, 2): a = capped_integral(4, e, nu, U, U, lambda r: Fr(0)) b = uncapped_integral(4, e, nu, U) if a != b: print(" MISMATCH", nu, e, a, b) ok = False print(" PASS" if ok else " FAIL") # control 2 print("control 2: exact vs Monte-Carlo (n=3, U=1, delta=3/10)") delta = Fr(3, 10) B = [Fr(0), Fr(1, 2), Fr(1, 2), Fr(3, 5), Fr(3, 5)] for nu in [(2,), (2, 2), (3,)]: for e in (0, 1): ex = float(capped_integral(3, e, nu, U, delta, lambda r, B=B: B[min(r, len(B) - 1)])) mc = mc_integral(3, e, nu, float(U), float(delta), lambda r, B=B: float(B[min(r, len(B) - 1)])) rel = abs(ex - mc) / abs(ex) if ex else abs(mc) good = rel < 0.02 ok &= good print(f" nu={nu} e={e}: exact={ex:.8f} mc={mc:.8f} " f"rel={rel:.4f} {'OK' if good else 'MISMATCH'}") # control 3 print("control 3: monotone in the budget") base = capped_integral(3, 0, (2,), U, delta, lambda r: Fr(0)) more = capped_integral(3, 0, (2,), U, delta, lambda r: Fr(1, 2)) good = more > base ok &= good print(f" B=0: {float(base):.6f} B=1/2: {float(more):.6f} " f"{'OK' if good else 'MISMATCH'}") print("ALL PASS" if ok else "FAILURES PRESENT") return 0 if ok else 1 if __name__ == "__main__": sys.exit(main())