#!/usr/bin/env python3 """Unit tests for the settlement + streaming certificate (research/0023). Run: ../../../../.venv/bin/python3 tests/test_settlement.py """ from __future__ import annotations import os import sys from fractions import Fraction as Fr import sympy as sp HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.join(HERE, "..") sys.path.insert(0, os.path.join(ROOT, "src")) sys.path.insert(0, os.path.normpath(os.path.join(ROOT, "..", "0022", "src"))) from even_engine import EvenEngine # noqa: E402 from certify_stream import stream_Q # noqa: E402 A = sp.Rational(2583, 10000) eps_s = sp.Rational(3, 400) fails = 0 def check(name, cond, detail=""): global fails if not cond: fails += 1 print(f"[{'PASS' if cond else 'FAIL'}] {name} {detail}") # ---- arithmetic settlement ------------------------------------------------- check("eta = 25/861", sp.simplify(eps_s / A) == sp.Rational(25, 861)) check("1/A < 4", sp.Rational(1) / A < 4, f"1/A={sp.N(1/A,12)}") check("4A = 2583/2500", 4 * A == sp.Rational(2583, 2500)) check("4(A+eps_s)-1 = 79/1250", 4 * (A + eps_s) - 1 == sp.Rational(79, 1250)) check("omega = A-1/4 = 83/10000", A - sp.Rational(1, 4) == sp.Rational(83, 10000)) # ---- basis nesting and exact submatrix identity ---------------------------- k, eps = 12, Fr(1, 25) for d in (5, 7, 9): lo, hi = EvenEngine(k, eps, d, "float"), EvenEngine(k, eps, d + 2, "float") check(f"B({d}) prefix of B({d+2})", hi.B[:lo.n] == lo.B, f"n={lo.n}->{hi.n}") e0, e1 = EvenEngine(k, eps, 7, "exact"), EvenEngine(k, eps, 9, "exact") mism = sum(1 for i in range(e0.n) for j in range(e0.n) if e0.M1(i, j) != e1.M1(i, j) or e0.M2(i, j) != e1.M2(i, j)) check("exact Gram submatrix identity d7 in d9", mism == 0, f"mism={mism}") # ---- streaming evaluator against the dense exact form ---------------------- tau = 1 / A c = [Fr((7 * i + 3) % 11 - 5 * (i % 3), 13 + (i % 4)) for i in range(e0.n)] M1, M2 = e0.matrices() dense = sum(c[i] * (sum((M2[i][j] - tau * M1[i][j]) * c[j] for j in range(e0.n))) for i in range(e0.n)) stream, _ = stream_Q(e0, c, tau) check("stream_Q == dense exact form", stream == dense, f"{float(stream):+.6e}") # ---- certificate lift is exact -------------------------------------------- c_emb = c + [Fr(0)] * (e1.n - e0.n) lift, _ = stream_Q(e1, c_emb, tau) check("zero-padded Q identical at d+2", lift == dense) # ---- strict-weakness witness ---------------------------------------------- check("39/10 in (1/A, 4)", sp.Rational(1) / A < sp.Rational(39, 10) < 4) print("\nALL TESTS PASSED" if not fails else f"\n{fails} TEST(S) FAILED") raise SystemExit(1 if fails else 0)