#!/usr/bin/env python3 """Exact finite demonstrations for v2_classical_review.md. Standard library only. Fractions certify the finite algebra; logarithms are evaluated in double precision with an explicit 2e-12 comparison tolerance. These are reproducible demonstrations, not formal verification of the proofs. """ from fractions import Fraction as F from itertools import product from math import log, exp, tanh, acosh, sqrt, comb, isclose from pathlib import Path import json import random OUT = Path(__file__).resolve().parent / "results" / "v2_classical_results.json" OUT.parent.mkdir(parents=True, exist_ok=True) RNG = random.Random(20261129) RESULTS = [] def record(name, **data): RESULTS.append({"name": name, "status": "pass", **data}) def fr(x): return str(x) if isinstance(x, F) else x def dist(weights): weights = list(map(F, weights)) return [v / sum(weights) for v in weights] def tv(p, q): return sum(abs(a - b) for a, b in zip(p, q)) / 2 def vecmul(p, K): return [sum(p[i] * K[i][j] for i in range(len(p))) for j in range(len(K[0]))] def matmul(A, B): return [[sum(A[i][k] * B[k][j] for k in range(len(B))) for j in range(len(B[0]))] for i in range(len(A))] def identity(n): return [[F(i == j) for j in range(n)] for i in range(n)] def transpose(A): return [list(row) for row in zip(*A)] def tr(A): return sum(A[i][i] for i in range(len(A))) def power(A, n): out = identity(len(A)) for _ in range(n): out = matmul(out, A) return out def adddiag(A, d): return [[A[i][j] + (d[i] if i == j else 0) for j in range(len(A))] for i in range(len(A))] def centered(A): c = tr(A) / len(A) return adddiag(A, [-c] * len(A)) def reverse_kernel(K, rx, ry): return [[K[rx[i]][ry[j]] for j in range(len(ry))] for i in range(len(rx))] def reverse_prob(p, r): return [p[r[i]] for i in range(len(r))] def jscore(a): a = float(a) def zlog(z): return 0.0 if z == 0 else z * log(z) return (zlog(1 + a) + zlog(1 - a)) / 2 def assert_close(x, y): assert isclose(float(x), float(y), rel_tol=2e-12, abs_tol=2e-12), (x, y) def binary_kernel(e): return [[F(1), F(0)], [e, 1 - e]] def budget_sharpness(): count = 0 for D, e in product([F(0), F(1, 5), F(3, 5), F(1)], [F(0), F(1, 5), F(2, 3), F(1)]): p = [(1 + D) / 2, (1 - D) / 2] q = p[::-1] K = binary_kernel(e) KR = reverse_kernel(K, [1, 0], [1, 0]) assert max(tv(a, b) for a, b in zip(K, KR)) == e observed = tv(vecmul(p, K), vecmul(q, KR)) assert observed == D + (1 - D) * e count += 1 record("sharp_overlap_budget_all_boundary_cases", rational_cases=count) def budget_random(): count = 0 rx, ry = [1, 0, 3, 2], [1, 0, 3, 2, 5, 4] largest_improvement = F(0) for _ in range(80): p = dist([RNG.randint(0, 9) for _ in range(4)]) K = [dist([RNG.randint(1, 9) for _ in range(6)]) for _ in range(4)] q, KR = reverse_prob(p, rx), reverse_kernel(K, rx, ry) D = tv(p, q) defect = [tv(a, b) for a, b in zip(K, KR)] e = max(defect) delta = tv(vecmul(p, K), vecmul(q, KR)) mu = [min(a, b) for a, b in zip(p, q)] assert sum(mu) == 1 - D assert delta <= D + sum(a * b for a, b in zip(mu, defect)) assert delta <= D + (1 - D) * e largest_improvement = max(largest_improvement, D * e) count += 1 record("overlap_bound_nonuniform_rational_kernels", rational_cases=count, maximal_additive_budget_improvement=fr(largest_improvement)) def stage_composition(): es = [F(1, 5), F(1, 3), F(1, 7)] D = F(2, 5) K = identity(2) remaining = F(1) for e in es: K = matmul(K, binary_kernel(e)) remaining *= 1 - e assert K == binary_kernel(1 - remaining) p = [(1 + D) / 2, (1 - D) / 2] delta = tv(vecmul(p, K), vecmul(p[::-1], reverse_kernel(K, [1, 0], [1, 0]))) assert delta == 1 - (1 - D) * remaining record("sharp_stage_composition", defects=list(map(fr, es)), source=fr(D), observed=fr(delta), joint_defect=fr(1 - remaining)) def endpoint_case(values, weights, lo, hi): a, w = list(map(F, values)), list(map(F, weights)) lo, hi = F(lo), F(hi) assert sum(w) == 1 b = sum(x * y for x, y in zip(a, w)) assert lo <= min(a) <= max(a) <= hi if lo == hi: ew = [F(1), F(0)] L = [w[:], w[:]] else: ew = [(hi - b) / (hi - lo), (b - lo) / (hi - lo)] L = [ [(hi - x) / (hi - b) * y for x, y in zip(a, w)] if b != hi else w[:], [(x - lo) / (b - lo) * y for x, y in zip(a, w)] if b != lo else w[:] ] assert all(sum(row) == 1 and min(row) >= 0 for row in L) ep = [(1 + lo) * ew[0], (1 + hi) * ew[1]] eq = [(1 - lo) * ew[0], (1 - hi) * ew[1]] tp = [(1 + x) * y for x, y in zip(a, w)] tq = [(1 - x) * y for x, y in zip(a, w)] assert vecmul(ep, L) == tp and vecmul(eq, L) == tq # Pair this fiber with its reflected fiber: each mixture mass is 1/2. P, Q = [x / 2 for x in tp + tq], [x / 2 for x in tq + tp] assert sum(P) == sum(Q) == 1 variance = sum(y * (x - b) ** 2 for x, y in zip(a, w)) upper = (b - lo) * (hi - b) endpoint_variance = ew[0] * (lo - b) ** 2 + ew[1] * (hi - b) ** 2 assert 0 <= variance <= upper == endpoint_variance target_js = sum(float(y) * jscore(x) for x, y in zip(a, w)) max_js = float(ew[0]) * jscore(lo) + float(ew[1]) * jscore(hi) assert jscore(b) <= target_js + 2e-12 <= max_js + 4e-12 return {"mean": fr(b), "score_bounds": [fr(lo), fr(hi)], "hidden_variance": fr(variance), "max_hidden_variance": fr(upper), "hidden_js": target_js - jscore(b), "max_hidden_js": max_js - jscore(b)} def endpoint_demos(): cases = [ endpoint_case([F(-1, 2), F(1, 4), F(3, 4)], [F(1, 4), F(1, 2), F(1, 4)], F(-3, 4), 1), endpoint_case([-1, 0, 1], [F(1, 4), F(1, 2), F(1, 4)], -1, 1), endpoint_case([F(1, 3), F(1, 3)], [F(1, 4), F(3, 4)], F(1, 3), F(2, 3)), endpoint_case([F(-1, 3)], [1], F(-1, 3), F(-1, 3)) ] record("complete_endpoint_experiment_simulation", cases=cases) def tv_not_sufficiency(): lo, b, hi = F(1, 10), F(3, 10), F(4, 5) weights = [(hi - b) / (hi - lo), (b - lo) / (hi - lo)] hidden_tv = weights[0] * abs(lo) + weights[1] * abs(hi) gap = float(weights[0]) * jscore(lo) + float(weights[1]) * jscore(hi) - jscore(b) assert hidden_tv == b and gap > 0 record("equal_prior_testing_can_miss_hidden_information", unchanged_tv=fr(b), positive_js_gap=gap) def saerin_envelope(): ps = pt = F(1, 2) u0, low, high = F(1, 2), F(1, 4), F(3, 4) def f(u): forward, backward = float(ps * u), float(pt * (1 - u)) return (forward - backward) * log(forward / backward) lower = 2 * f(u0) upper = f(low) + f(high) assert lower == 0 assert_close(upper, log(3) / 2) # Three-channel interpolation preserves aggregate rates, fills the interval. for t in [F(0), F(1, 5), F(2, 3), F(1)]: w = [1 - t, t / 2, t / 2] us = [u0, low, high] assert sum(x * y for x, y in zip(w, us)) == u0 sigma = 2 * sum(float(x) * f(y) for x, y in zip(w, us)) assert_close(sigma, float(t) * upper) record("saerin_sharp_hidden_dissipation_interval", aggregate_forward=1, aggregate_reverse=1, lower=lower, upper=upper, exact_upper="log(3)/2") def compensated_rates(): a0, kappa = 2.4, 1.0 Z = 2 + 2 * ((exp(a0 / 2) + exp(-a0 / 2)) / 2) pi1 = exp(-a0 / 2) / Z values = [] previous = -1 for a in [a0, 5.0, 10.0, 30.0]: rho = tanh(a0 / 2) / tanh(a / 2) up = 1 / (1 + exp(-a)) down = 1 / (1 + exp(a)) kp = kappa * rho * up + kappa * (1 - rho) / 2 km = kappa * rho * down + kappa * (1 - rho) / 2 assert_close(kp, kappa * (1 + tanh(a0 / 2)) / 2) assert_close(km, kappa * (1 - tanh(a0 / 2)) / 2) current = pi1 * kappa * rho * (up - exp(a0) * down) sigma = a * current assert sigma > previous previous = sigma values.append({"fuel_affinity": a, "sigma": sigma, "aggregate_rates": [kp, km]}) record("electrically_identical_fuel_completions", values=values) def fault_probe(): R, e, d = F(1), F(1, 10), F(1, 20) rad = min(R, e + d) x = [d, rad] A = [[F(1), F(-1)], [F(1), F(1)], [F(0), F(1)]] y = [F(0), -sum(A[1][i] * x[i] for i in range(2)), x[1]] c = F(0) # Plus truth: host 2 is bad. Minus truth: host 3 is bad. for sign, good in [(1, [0, 2]), (-1, [0, 1])]: truth = [sign * z for z in x] for host in good: assert abs(y[host] - sum(A[host][i] * truth[i] for i in range(2))) <= e assert abs(c - truth[0]) <= d assert abs(x[1] - (-x[1])) / 2 == rad estimate = sorted([c - y[0], y[1] - c, y[2]])[1] assert max(abs(estimate - rad), abs(estimate + rad)) == rad record("ilyunae_trusted_probe_sharp_lower_witness", prior_risk=fr(R), new_risk=fr(rad), common_reports=list(map(fr, y)), trusted_report=fr(c), estimator=fr(estimate)) def spectral_cycle(): Q = [[F(-4), F(3), F(1)], [F(1), F(-4), F(3)], [F(3), F(1), F(-4)]] B = centered(Q) hs = [F(1), F(2), F(3)] parity = {r: F(0) for r in range(1, 7)} restoration_cases = 0 for index, signs in enumerate(product([-1, 1], repeat=3)): ds = [signs[i] * hs[i] for i in range(3)] drift = F(index - 3, 7) measured = adddiag(Q, [z + drift for z in ds]) mu = sum(ds) / 3 centered_measured = centered(measured) contrast_sign = signs[0] * signs[1] * signs[2] for r in range(1, 7): restored = sum(F(comb(r, ell)) * mu ** (r - ell) * tr(power(centered_measured, ell)) for ell in range(r + 1)) assert restored == tr(power(adddiag(B, ds), r)) parity[r] += contrast_sign * restored restoration_cases += 1 assert all(parity[r] == 0 for r in range(1, 6)) cycle_sum = parity[6] / (2 ** 3 * 6 * hs[0] * hs[1] * hs[2]) assert cycle_sum == 28 wp = F(3) ** 3 discriminant = cycle_sum ** 2 - 4 * wp assert discriminant == 676 magnitude = 2 * acosh(float(cycle_sum) / (2 * sqrt(float(wp)))) assert_close(magnitude, 3 * log(3)) record("nyosha_restored_spectral_cycle_certificate", exact_control_cases=restoration_cases, lower_degree_contrasts_zero=True, cycle_sum=fr(cycle_sum), discriminant=fr(discriminant), affinity_magnitude=magnitude) def spectral_reversal(): Q = [[F(-4), F(3), F(1)], [F(1), F(-4), F(3)], [F(3), F(1), F(-4)]] count = 0 for d in product([F(-1, 3), F(0), F(2)], repeat=3): A, AR = adddiag(Q, d), adddiag(transpose(Q), d) # First n trace powers determine the characteristic polynomial. assert all(tr(power(A, r)) == tr(power(AR, r)) for r in range(1, 4)) count += 1 record("all_diagonal_controls_blind_to_stationary_reversal", rational_control_examples=count, forward_cycle_product=27, reverse_cycle_product=1) def projective_failure(): K = [[F(4, 5), F(1, 5)], [F(1, 5), F(4, 5)]] T = [[F(4, 5), F(2, 5)], [F(1, 10), F(4, 5)]] first = dist(T[0]) second_prefix = dist([T[0][i] * sum(T[i]) for i in range(2)]) assert first == [F(2, 3), F(1, 3)] assert second_prefix == [F(8, 11), F(3, 11)] h = [F(1), F(1, 2)] assert [sum(T[i][j] * h[j] for j in range(2)) for i in range(2)] == h corrected = [[T[i][j] * h[j] / h[i] for j in range(2)] for i in range(2)] assert corrected == K record("projective_failure_and_gradient_tilt_repair", first_horizon=list(map(fr, first)), second_prefix=list(map(fr, second_prefix)), corrected_chain_equals_reference=True) def driven_cycle(): # theta=log(2), reference clockwise/anticlockwise probabilities 1/2. L = [[F(0), F(4, 5), F(1, 5)], [F(1, 5), F(0), F(4, 5)], [F(4, 5), F(1, 5), F(0)]] sig = F(6, 5) * log(2) rates = [] for n in range(1, 6): kl = 0.0 mass = F(0) for start in range(3): for steps in product([-1, 1], repeat=n): path = [start] for step in steps: path.append((path[-1] + step) % 3) p = q = F(1, 3) for i in range(n): p *= L[path[i]][path[i+1]] q *= L[path[i+1]][path[i]] mass += p kl += float(p) * log(float(p / q)) assert mass == 1 assert_close(kl / n, sig) rates.append(kl / n) record("driven_nongradient_cycle_path_likelihood", horizon_rates=rates, exact_rate="6*log(2)/5", cycle_affinity="6*log(2)") def convex_witness(): m = F(1, 2) values = [] for i in range(-8, 9): x1, x2 = F(i, 8), m - F(i, 8) if abs(x2) <= 1: magnitude = (abs(x1) + abs(x2)) / 2 witness = (x1 + x2) / 2 assert magnitude >= witness == m / 2 values.append(magnitude) assert min(values) == m / 2 # Nonconvex pair +/- has positive magnitude but opposing every signed test. for f1, f2 in product([F(-1), F(-1, 3), F(0), F(2, 3), F(1)], repeat=2): expectations = [f1 / 2, -f1 / 2] assert min(expectations) <= 0 record("convex_witness_and_nonconvex_direction_obstruction", moment=fr(m), sharp_arrow=fr(m / 2), nonconvex_minimum_arrow="1/2", nonconvex_uniform_signed_advantage=0) def hidden_cycle_sensor(): edges = [(0, 1), (1, 2), (2, 3), (3, 0), (1, 2)] B = [[F((v == t) - (v == s)) for s, t in edges] for v in range(4)] slip = [F(0), F(1), F(0), F(0), F(-1)] q = [F(1, 2), F(0), F(1, 2), F(0), F(0)] fuel = [F(0), F(1), F(0), F(0), F(0)] dot = lambda x, y: sum(a * b for a, b in zip(x, y)) assert all(dot(row, slip) == 0 for row in B) assert dot(q, slip) == 0 assert dot(fuel, slip) == 1 phi, a, v = [F(2), F(-1), F(3), F(5)], F(3), F(2) gradient = [phi[t] - phi[s] for s, t in edges] A = [a * fuel[i] - v * q[i] + gradient[i] for i in range(5)] assert dot(A, slip) == a assert [A[i] - a * fuel[i] + v * q[i] for i in range(5)] == gradient record("cycle_sensor_obstruction_and_fuel_repair", invisible_charge=0, hidden_cycle_affinity=fr(a), repair="charge+fuel+endpoints") def main(): budget_sharpness() budget_random() stage_composition() endpoint_demos() tv_not_sufficiency() saerin_envelope() compensated_rates() fault_probe() spectral_cycle() spectral_reversal() projective_failure() driven_cycle() convex_witness() hidden_cycle_sensor() obj = {"status": "pass", "demonstrations": len(RESULTS), "random_seed": 20261129, "floating_tolerance": 2e-12, "dependencies": "Python standard library", "results": RESULTS} OUT.write_text(json.dumps(obj, indent=2) + "\n") print(json.dumps({"status": obj["status"], "demonstrations": len(RESULTS), "output": str(OUT)}, indent=2)) if __name__ == "__main__": main()