File size: 11,370 Bytes
8e19377
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
#!/usr/bin/env python3
"""AËQIRION III: positive probe design and expressive-resource bounds.

All algebraic inequalities, tensor contractions, Walsh identities, gain-graph
ranks, and support-cover checks use exact Fraction/integer arithmetic. Optional
NumPy eigensolver experiments illustrate the proven spectral formulas; their
floating-point results are explicitly separated from exact verification.
"""
from __future__ import annotations

from fractions import Fraction as F
from itertools import product
import json
from math import sqrt
from pathlib import Path
import random


def parity(x):
    return 1 if x.bit_count() % 2 == 0 else -1


def cube_edges(n):
    return [(x, x ^ (1 << i)) for x in range(1 << n)
            for i in range(n) if x < (x ^ (1 << i))]


def dot(a, b):
    return sum((x * y for x, y in zip(a, b)), F(0))


def tensor(factors):
    out = [F(1)]
    for factor in factors:
        out = [a * b for a in out for b in factor]
    return out


def apply_h0(n, x):
    out = [n * a for a in x]
    for u, v in cube_edges(n):
        out[u] += x[v]
        out[v] += x[u]
    return out


def exact_walsh_checks():
    count = 0
    for n in range(1, 9):
        nv = 1 << n
        for mask in range(nv):
            w = [F((-1) ** ((x & mask).bit_count())) for x in range(nv)]
            actual = apply_h0(n, w)
            eigenvalue = 2 * (n - mask.bit_count())
            assert actual == [eigenvalue * a for a in w]
            count += 1
        chi = [F(parity(x)) for x in range(nv)]
        ones = [F(1)] * nv
        indicator = [F(parity(x) == 1) for x in range(nv)]
        # Unit-energy parity mask b=indicator/sqrt(N/2).  Its rank-one update
        # bb^T is rational, so its invariant 2D action is checked exactly.
        def augmented(x):
            update = dot(indicator, x) / (F(nv, 2))
            return [a + update * b for a, b in zip(apply_h0(n, x), indicator)]
        assert augmented(chi) == [(a + b) / 2 for a, b in zip(chi, ones)]
        assert augmented(ones) == [(a + b) / 2 + 2 * n * b
                                    for a, b in zip(chi, ones)]
        # Compression matrix [[1/2,1/2],[1/2,2n+1/2]] has trace2n+1, detn.
        assert F(1, 2) * (2 * n + F(1, 2)) - F(1, 4) == n
        assert dot(indicator, chi) ** 2 == F(nv, 2) * dot(indicator, indicator)
        count += 4
    return count


def exact_resource_checks():
    rng = random.Random(1372026)
    general = rank_one = mixtures = blocks = support = 0
    sharp_examples = 0
    for n in range(2, 9):
        nv = 1 << n
        chi = [F(parity(x)) for x in range(nv)]
        for _ in range(20):
            b = [F(rng.randrange(0, 10), rng.randrange(1, 7)) for _ in range(nv)]
            assert dot(b, chi) ** 2 * 2 <= nv * dot(b, b)
            general += 1
            factors = [[F(rng.randrange(0, 10), rng.randrange(1, 6))
                        for _ in range(2)] for _ in range(n)]
            v = tensor(factors)
            assert dot(v, chi) ** 2 <= dot(v, v)
            rank_one += 1
        for rank in range(1, 6):
            for _ in range(8):
                terms = [tensor([[F(rng.randrange(0, 8), rng.randrange(1, 5))
                                  for _ in range(2)] for _ in range(n)])
                         for _ in range(rank)]
                b = [sum((term[x] for term in terms), F(0)) for x in range(nv)]
                assert dot(b, chi) ** 2 <= rank * dot(b, b)
                assert sum((dot(v, v) for v in terms), F(0)) <= dot(b, b)
                mixtures += 1
        # Any partition into k blocks, with a nonnegative factor per block,
        # has normalized parity overlap squared at most 2^-k.
        for k in range(1, n + 1):
            sizes = [1] * k
            for j in range(n - k):
                sizes[j % k] += 1
            for _ in range(8):
                factors = [[F(rng.randrange(0, 10), rng.randrange(1, 7))
                            for _ in range(1 << size)] for size in sizes]
                b = tensor(factors)
                assert dot(b, chi) ** 2 * (1 << k) <= nv * dot(b, b)
                blocks += 1
        # Exact sharpness of the overlap rank bound for R<=N/2: equal point
        # masses at R even vertices form a nonnegative CP-rank-R tensor.
        even = [x for x in range(nv) if parity(x) == 1]
        for rank in (1, min(3, len(even)), len(even)):
            b = [F(x in even[:rank]) for x in range(nv)]
            assert dot(b, chi) ** 2 == rank * dot(b, b)
            sharp_examples += 1
        for size in (1, 2, nv // 2):
            indices = rng.sample(range(nv), size)
            b = [F(rng.randrange(1, 8) if x in indices else 0) for x in range(nv)]
            assert dot(b, chi) ** 2 <= size * dot(b, b)
            support += 1
    return {"nonnegative_overlap": general, "coordinate_product_overlap": rank_one,
            "nonnegative_CP_mixture_overlap": mixtures,
            "block_product_overlap": blocks, "support_size_overlap": support,
            "rank_bound_sharp_overlap_examples": sharp_examples}


def exact_rectangle_checks():
    checks = 0
    for n in range(1, 9):
        # 0 fixes the bit to0, 1 to1, and2 allows both; each is a nonempty
        # support of one nonnegative one-coordinate factor.
        for pattern in product((0, 1, 2), repeat=n):
            free = pattern.count(2)
            if free:
                # Flipping one free coordinate changes parity within support.
                a = [0 if p == 2 else p for p in pattern]
                b = list(a)
                b[pattern.index(2)] = 1
                assert sum(a) % 2 != sum(b) % 2
            else:
                assert 2 ** free == 1
            checks += 1
    return checks


def matrix_rank(a):
    a = [list(map(F, row)) for row in a]
    if not a:
        return 0
    rank = 0
    for col in range(len(a[0])):
        pivot = next((j for j in range(rank, len(a)) if a[j][col]), None)
        if pivot is None:
            continue
        a[rank], a[pivot] = a[pivot], a[rank]
        value = a[rank][col]
        a[rank] = [v / value for v in a[rank]]
        for j in range(len(a)):
            if j != rank and a[j][col]:
                value = a[j][col]
                a[j] = [x - value * y for x, y in zip(a[j], a[rank])]
        rank += 1
        if rank == len(a):
            break
    return rank


def weighted_balanced(n, edges):
    values = [None] * n
    values[0] = F(1)
    changed = True
    balanced = True
    while changed:
        changed = False
        for u, v, alpha in edges:
            if values[u] is not None:
                proposed = -values[u] / alpha
                if values[v] is None:
                    values[v] = proposed
                    changed = True
                elif values[v] != proposed:
                    balanced = False
            elif values[v] is not None:
                values[u] = -alpha * values[v]
                changed = True
    assert all(x is not None for x in values)
    return balanced


def exact_gain_graph_checks():
    rng = random.Random(2262026)
    count = 0
    for n in range(2, 11):
        for rep in range(18):
            edges = [(i, i + 1, F(rng.randrange(1, 5), rng.randrange(1, 5)))
                     for i in range(n - 1)]
            for _ in range(rep % 4):
                u, v = rng.sample(range(n), 2)
                edges.append((u, v, F(rng.randrange(1, 5), rng.randrange(1, 5))))
            rows = []
            for u, v, alpha in edges:
                row = [F(0)] * n
                row[u], row[v] = F(1), alpha
                rows.append(row)
            assert matrix_rank(rows) == n - int(weighted_balanced(n, edges))
            count += 1
    return count


def numerical_spectral_checks():
    try:
        import numpy as np
    except ImportError:
        return {"status": "SKIPPED", "reason": "NumPy is optional for spectral illustrations"}
    rng = np.random.default_rng(12202026)
    cases = mixtures = pair_cases = 0
    curve = []
    worst_excess = 0.0
    for n in range(1, 8):
        nv = 1 << n
        q = n * np.eye(nv)
        for u, v in cube_edges(n):
            q[u, v] = q[v, u] = 1
        signs = np.array([parity(x) for x in range(nv)], dtype=float)
        even = (signs == 1).astype(float)
        odd = (signs == -1).astype(float)
        b_opt = even / np.linalg.norm(even)
        optimum = (2 * n) / (2 * n + 1 + sqrt(4 * n * n + 1))
        got = float(np.linalg.eigvalsh(q + np.outer(b_opt, b_opt))[0])
        assert abs(got - optimum) < 2e-11
        for _ in range(18):
            b = rng.uniform(0, 1, size=nv)
            b /= np.linalg.norm(b)
            val = float(np.linalg.eigvalsh(q + np.outer(b, b))[0])
            assert val <= optimum + 2e-11
            worst_excess = max(worst_excess, val - optimum)
            cases += 1
        # Total energy1, two positive rows: each parity indicator/sqrt(N).
        h = q + (np.outer(even, even) + np.outer(odd, odd)) / nv
        assert abs(float(np.linalg.eigvalsh(h)[0]) - 0.5) < 2e-11
        pair_cases += 1
        if n >= 2:
            for rank in (1, 2, 3):
                vectors = []
                for _ in range(2):
                    terms = []
                    for _ in range(rank):
                        v = np.array([1.0])
                        for _ in range(n):
                            v = np.kron(v, rng.uniform(0, 1, size=2))
                        terms.append(v)
                    b = sum(terms)
                    b /= np.linalg.norm(b)
                    vectors.append(b)
                h = q + sum(np.outer(b, b) for b in vectors)
                val = float(np.linalg.eigvalsh(h)[0])
                assert val <= 2 * rank / nv + 2e-11
                mixtures += 1
        curve.append({"dimension": n, "vertices": nv,
                      "optimal_one_positive_row": optimum,
                      "two_positive_rows_total_energy_one": 0.5,
                      "single_product_row_upper_bound": 1 / nv,
                      "eigensolver_parity_value": got})
    return {"status": "PASS", "arithmetic": "NumPy float64 symmetric eigensolver",
            "random_single_row_cases": cases, "CP_resource_spectral_cases": mixtures,
            "two_row_optimal_frame_cases": pair_cases,
            "maximum_observed_excess_over_optimum": worst_excess, "curve": curve}


def main():
    return {"status": "PASS", "exact_arithmetic": "integer/Fraction",
            "exact_walsh_and_optimal_invariant_space_checks": exact_walsh_checks(),
            "exact_resource_checks": exact_resource_checks(),
            "exact_parity_rectangle_support_checks": exact_rectangle_checks(),
            "exact_weighted_gain_graph_rank_checks": exact_gain_graph_checks(),
            "spectral_illustrations": numerical_spectral_checks(),
            "scope": ["Proofs, not random search, establish the universal optimum.",
                      "The unscaled baseline is all binary coordinate-fiber edge sums.",
                      "Total probe energy is squared Euclidean row norm, not runtime.",
                      "One dense mask may require exponentially many state accesses.",
                      "CP rank means nonnegative coordinatewise tensor rank."]}


if __name__ == '__main__':
    result = main()
    print(json.dumps(result, indent=2))