File size: 10,093 Bytes
9552b49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
#!/usr/bin/env python3
"""Reproduce certificate-memory examples and deterministic lower-bound tables.

Exact checks use fractions.Fraction and explicit matrix identities. Floating
checks test the Gaussian-comparison and pair-trace formulas on finite examples;
they are diagnostics, not formal or interval proofs. The mathematical proofs
are in manuscript/chapters/04_certificates.tex.

Run from the release root:
    python experiments/certificate_experiments.py --output results/certificates

Dependencies: Python 3.10+ and NumPy. No network, data download, or optimizer.
"""

from __future__ import annotations

import argparse
import csv
import itertools
import json
import math
from fractions import Fraction as F
from pathlib import Path

import numpy as np


def eye(d: int):
    return [[F(i == j) for j in range(d)] for i in range(d)]


def diagonal_family(d: int, L: F):
    out = []
    for i in range(d):
        M = [[F(0) for _ in range(d)] for _ in range(d)]
        for j in range(d):
            M[j][j] = F(1) if i == j else L
        out.append(M)
    return out


def subtract(A, B):
    return [[a - b for a, b in zip(ar, br)] for ar, br in zip(A, B)]


def matvec(A, v):
    return [sum((a * x for a, x in zip(row, v)), F(0)) for row in A]


def determinant(A):
    a = [row[:] for row in A]
    d = len(a)
    result = F(1)
    for j in range(d):
        pivot = next((i for i in range(j, d) if a[i][j]), None)
        if pivot is None:
            return F(0)
        if pivot != j:
            a[j], a[pivot] = a[pivot], a[j]
            result = -result
        p = a[j][j]
        result *= p
        for i in range(j + 1, d):
            q = a[i][j] / p
            for k in range(j + 1, d):
                a[i][k] -= q * a[j][k]
            a[i][j] = F(0)
    return result


def rank(A):
    a = [row[:] for row in A]
    rows, cols = len(a), len(a[0])
    r = 0
    for j in range(cols):
        pivot = next((i for i in range(r, rows) if a[i][j]), None)
        if pivot is None:
            continue
        a[r], a[pivot] = a[pivot], a[r]
        p = a[r][j]
        a[r] = [x / p for x in a[r]]
        for i in range(rows):
            if i != r and a[i][j]:
                q = a[i][j]
                a[i] = [x - q * y for x, y in zip(a[i], a[r])]
        r += 1
        if r == rows:
            break
    return r


def exact_sign_checks():
    cases = 0
    slack_checks = 0
    for d in range(2, 9):
        L = F(d * d + 1)
        alpha = L / (L + d - 1)
        matrices = diagonal_family(d, L)
        for tail in itertools.product((-1, 1), repeat=d - 1):
            s = [F(1), *map(F, tail)]
            Y = [[alpha * si * sj for sj in s] for si in s]
            W_columns = []
            for i, M in enumerate(matrices):
                w = [sj / M[j][j] for j, sj in enumerate(s)]
                assert sum((sj * wj for sj, wj in zip(s, w)), F(0)) == 1 / alpha
                slack = subtract(M, Y)
                assert matvec(slack, w) == [F(0)] * d
                assert rank(slack) == d - 1
                assert determinant(slack) == 0
                W_columns.append(w)
                slack_checks += 1
            W = [[W_columns[j][i] for j in range(d)] for i in range(d)]
            predicted = math.prod(s) * (1 - 1 / L) ** (d - 1) * (1 + F(d - 1) / L)
            assert determinant(W) == predicted
            assert rank(W) == d
            assert rank(Y) == 1
            cases += 1
    return {"sign_classes_checked": cases, "exact_slack_identities": slack_checks}


def exact_continuum_checks():
    cases = 0
    L = F(4)
    for d in (2, 3, 5):
        matrices = diagonal_family(d, L)
        for t in (F(5), F(6), F(10), F(25, 2)):
            a = (t * t - L) / (t * t - 1)
            b = (L - 1) * t / (t * t - 1)
            assert b * b == (1 - a) * (L - a)
            assert a > L / (L + 1)
            E = eye(d)
            E[0][0] = E[1][1] = a
            E[0][1] = E[1][0] = b
            assert determinant(E) == (L + 1) * a - L > 0
            # Exact nullvectors of the first two rank-one block slacks.
            w1 = [b, 1 - a] + [F(0)] * (d - 2)
            w2 = [1 - a, b] + [F(0)] * (d - 2)
            assert matvec(subtract(matrices[0], E), w1) == [F(0)] * d
            assert matvec(subtract(matrices[1], E), w2) == [F(0)] * d
            vectors = [w1, w2]
            for i in range(2, d):
                wi = [F(j == i) for j in range(d)]
                assert matvec(subtract(matrices[i], E), wi) == [F(0)] * d
                vectors.append(wi)
            assert rank(vectors) == d
            cases += 1
    return {"exact_continuum_instances": cases}


def exact_examples():
    N = [[F(4, 5), F(3, 5)], [F(3, 5), F(4, 5)]]
    S = [[F(3, 5), F(2, 5)], [F(2, 5), F(3, 5)]]
    assert determinant(N) == F(7, 25)
    assert determinant(S) == F(1, 5)
    for M in ([[F(4), F(0)], [F(0), F(1)]], [[F(1), F(0)], [F(0), F(4)]]):
        assert determinant(subtract(M, N)) == F(7, 25)
    eps, L, d = F(1, 10), F(100), 4
    alpha_eps = 1 / (1 / (1 - eps) + F(d - 1) / (L - eps))
    ratio = eps + d * alpha_eps
    assert alpha_eps == F(333, 380)
    assert ratio == F(137, 38)
    assert alpha_eps / (eps * ratio) == F(333, 137)
    return {
        "nonassociativity_determinants": [str(determinant(N)), str(determinant(S))],
        "sharp_d4_floor_ratio_exact": str(ratio),
        "sharp_d4_floor_ratio_decimal": float(ratio),
        "sharp_d4_radius_ratio_decimal": math.sqrt(float(ratio)),
    }


def bound_table():
    rows = []
    for d in (16, 32, 64, 128, 256, 512):
        L = d ** 3
        alpha = F(L, L + d - 1)
        for c_string in ("1.1", "1.25", "1.5", "2", "4"):
            c = F(c_string)
            beta = alpha * d / c
            if beta > 1:
                b = float(beta)
                log2_lower = ((b - 1) - math.log(b)) / (2 * math.log(2))
            else:
                log2_lower = 0.0
            ratio = c / alpha
            radius = None
            hamming_sum = None
            log2_hamming = None
            if ratio < 2:
                # Avoid floating-point floor ambiguity: q*d >= k iff
                # (ratio-1)^2 >= 4(k/d)(1-k/d), for 0<=k<=d/2.
                r2 = (ratio - 1) ** 2
                radius = max(k for k in range(d // 2 + 1) if F(4 * k * (d - k), d * d) <= r2)
                hamming_sum = sum(math.comb(d, k) for k in range(radius + 1))
                log2_hamming = d - 1 - math.log2(hamming_sum)
            rows.append({
                "d": d, "L": L, "c": c_string, "alpha_exact": str(alpha),
                "beta_exact": str(beta), "log2_mgf_lower": log2_lower,
                "hamming_radius_exact": radius,
                "hamming_ball_size_exact": hamming_sum,
                "log2_hamming_lower": log2_hamming,
                "log2_combined_lower": max(0.0, log2_lower, log2_hamming or 0.0),
                "interpretation": "Proved formula evaluated; logarithms are floating-point, not interval rounded",
            })
    return rows


def floating_checks():
    rng = np.random.default_rng(20261020)
    mgf_cases = 0
    max_log_mgf_excess = -math.inf
    pair_cases = 0
    max_pair_residual = 0.0
    for d in range(2, 11):
        signs = np.array(list(itertools.product((-1.0, 1.0), repeat=d)))
        for _ in range(8):
            A = rng.normal(size=(d, d))
            E = A @ A.T
            E *= d / np.trace(E)
            t = 0.4 / d
            q = np.einsum("bi,ij,bj->b", signs, E, signs)
            actual = float(np.mean(np.exp(t * q)))
            eigenvalues = np.linalg.eigvalsh(E)
            determinant_bound = float(np.prod(1 - 2 * t * eigenvalues) ** -0.5)
            trace_bound = (1 - 2 * t * d) ** -0.5
            assert actual <= determinant_bound + 1e-11
            assert determinant_bound <= trace_bound + 1e-11
            max_log_mgf_excess = max(max_log_mgf_excess, math.log(actual) - math.log(determinant_bound))
            mgf_cases += 1
            u, v = rng.normal(size=(2, d))
            u /= np.linalg.norm(u)
            v /= np.linalg.norm(v)
            D = np.outer(u, u) - np.outer(v, v)
            positive_trace = np.maximum(np.linalg.eigvalsh(D), 0).sum()
            formula = math.sqrt(max(0.0, 1 - float(u @ v) ** 2))
            max_pair_residual = max(max_pair_residual, abs(float(positive_trace) - formula))
            assert abs(float(positive_trace) - formula) < 1e-10
            pair_cases += 1
    return {
        "enumerated_mgf_cases": mgf_cases,
        "pair_trace_cases": pair_cases,
        "max_log_mgf_excess": max_log_mgf_excess,
        "max_pair_identity_residual": max_pair_residual,
        "status": "Finite float64 diagnostics; not interval certificates or universal proof",
    }


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output", type=Path, default=Path("results/certificates"))
    args = parser.parse_args()
    args.output.mkdir(parents=True, exist_ok=True)
    report = {
        "schema": "EVE-OQAIVAEI-certificate-checks-1",
        "seed": 20261020,
        "exact_sign_checks": exact_sign_checks(),
        "exact_continuum_checks": exact_continuum_checks(),
        "exact_examples": exact_examples(),
        "floating_diagnostics": floating_checks(),
        "claim_boundary": "Reproduces finite identities and analytic lower-bound tables; no external scientific experiment or historical novelty certification",
    }
    (args.output / "certificate_report.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
    rows = bound_table()
    (args.output / "menu_bounds.json").write_text(json.dumps(rows, indent=2) + "\n", encoding="utf-8")
    with (args.output / "menu_bounds.csv").open("w", newline="", encoding="utf-8") as stream:
        writer = csv.DictWriter(stream, fieldnames=rows[0].keys())
        writer.writeheader()
        writer.writerows(rows)
    print(json.dumps(report, indent=2))
    print(f"Saved {len(rows)} lower-bound rows to {args.output}")


if __name__ == "__main__":
    main()