File size: 13,243 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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
#!/usr/bin/env python3
"""Exact finite checks for marginal kernels and separable coding obstructions.

Only standard-library integers and fractions. These checks do not prove
all-dimension statements or literature priority; proofs are in the manuscript.
"""
from fractions import Fraction as F
from itertools import product, combinations
from math import prod
import json
import random


def points(shape):
    return list(product(*(range(q) for q in shape)))


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


def rank(rows):
    if not rows:
        return 0
    a = [list(map(F, row)) for row in rows]
    nr, nc = len(a), len(a[0])
    pivot = 0
    for j in range(nc):
        found = next((i for i in range(pivot, nr) if a[i][j]), None)
        if found is None:
            continue
        a[pivot], a[found] = a[found], a[pivot]
        value = a[pivot][j]
        a[pivot] = [x / value for x in a[pivot]]
        for i in range(pivot + 1, nr):
            if a[i][j]:
                factor = a[i][j]
                a[i] = [x - factor * y for x, y in zip(a[i], a[pivot])]
        pivot += 1
        if pivot == nr:
            break
    return pivot


def marginal_matrix(shape):
    xs = points(shape)
    rows = []
    descriptors = []
    for i in range(len(shape)):
        other = [j for j in range(len(shape)) if j != i]
        for assignment in product(*(range(shape[j]) for j in other)):
            row = [int(all(x[j] == a for j, a in zip(other, assignment))) for x in xs]
            rows.append(row)
            descriptors.append((i, other, assignment))
    return rows, descriptors


def matvec(a, x):
    return [dot(row, x) for row in a]


def transpose_matvec(a, x):
    return [sum((a[i][j] * x[i] for i in range(len(a))), F(0))
            for j in range(len(a[0]))]


def one_factor_basis(q):
    # Orthogonal integer Helmert contrasts; no square roots are approximated.
    out = [[F(1)] * q]
    for a in range(1, q):
        out.append([F(1 if x < a else -a if x == a else 0) for x in range(q)])
    for i, u in enumerate(out):
        for v in out[:i]:
            assert dot(u, v) == 0
    return out


def tensor_vector(shape, basis, labels):
    return [F(prod(basis[i][labels[i]][x[i]] for i in range(len(shape))))
            for x in points(shape)]


def center_coordinate(shape, values, coordinate):
    xs = points(shape)
    lookup = dict(zip(xs, values))
    out = []
    for x in xs:
        total = F(0)
        for a in range(shape[coordinate]):
            y = list(x)
            y[coordinate] = a
            total += lookup[tuple(y)]
        out.append(total / shape[coordinate])
    return out


def observable_from_marginals(shape, sums):
    """Reconstruct (I-P_K)z using inclusion-exclusion of averaging maps.

    The input consists only of actual codimension-one sums; no original z
    or hidden tensor coefficients are available to this decoder.
    """
    a, descriptions = marginal_matrix(shape)
    xs = points(shape)
    one_coordinate_averages = []
    for i in range(len(shape)):
        entries = {}
        for value, (coord, other, assignment) in zip(sums, descriptions):
            if coord == i:
                entries[assignment] = value / shape[i]
        other = [j for j in range(len(shape)) if j != i]
        one_coordinate_averages.append([entries[tuple(x[j] for j in other)] for x in xs])
    out = [F(0)] * len(xs)
    for size in range(1, len(shape) + 1):
        for subset in combinations(range(len(shape)), size):
            value = one_coordinate_averages[subset[0]]
            for i in subset[1:]:
                value = center_coordinate(shape, value, i)
            sign = 1 if size % 2 else -1
            out = [x + sign * y for x, y in zip(out, value)]
    assert matvec(a, out) == sums
    return out


def check_spectrum():
    reports = []
    count = 0
    for shape in ((2, 2), (3, 3), (4, 4), (2, 3, 4), (3, 3, 3)):
        a, _ = marginal_matrix(shape)
        basis = [one_factor_basis(q) for q in shape]
        null_count = 0
        spectral_multiplicity = {}
        for labels in product(*(range(q) for q in shape)):
            v = tensor_vector(shape, basis, labels)
            expected_eigenvalue = sum(q for q, label in zip(shape, labels) if label == 0)
            lhs = transpose_matvec(a, matvec(a, v))
            assert lhs == [expected_eigenvalue * x for x in v]
            spectral_multiplicity[expected_eigenvalue] = spectral_multiplicity.get(
                expected_eigenvalue, 0) + 1
            null_count += expected_eigenvalue == 0
            count += 1
        expected_nullity = prod(q - 1 for q in shape)
        actual_rank = rank(a)
        assert null_count == expected_nullity
        assert actual_rank == prod(shape) - expected_nullity
        assert min(e for e in spectral_multiplicity if e) == min(shape)
        reports.append({"shape": list(shape), "N": prod(shape),
                        "rank": actual_rank, "kernel_dimension": expected_nullity,
                        "gram_eigenvalues_and_multiplicities": spectral_multiplicity})
    return {"exact_eigenvector_cases": count, "shapes": reports}


def check_separable_channels():
    reports = []
    for shape in ((2, 2), (3, 3), (4, 4), (2, 3, 4), (3, 4, 4), (3, 3, 3)):
        a, _ = marginal_matrix(shape)
        xs = points(shape)
        for m in range(1, min(shape) + 1):
            stacked = []
            coordinate_ranks = []
            for q in shape:
                coordinate_ranks.append(rank([[(x + 1) ** j for x in range(q)]
                                              for j in range(m)]))
            for j in range(m):
                # All coordinate factors are strictly positive Vandermonde rows.
                mask = [prod((x[i] + 1) ** j for i in range(len(shape))) for x in xs]
                assert min(mask) > 0
                stacked.extend([[F(value) * weight for value, weight in zip(row, mask)]
                                for row in a])
            expected_nullity = prod(q - r for q, r in zip(shape, coordinate_ranks))
            actual_nullity = prod(shape) - rank(stacked)
            assert actual_nullity == expected_nullity
            assert expected_nullity == prod(max(q - m, 0) for q in shape)
            reports.append({"shape": list(shape), "channels": m,
                            "coordinate_ranks": coordinate_ranks,
                            "joint_nullity": actual_nullity})
        # Repeating a proportional channel adds no information.
        repeated = a + [[3 * x for x in row] for row in a]
        assert rank(repeated) == rank(a)
    # Highlighted strict obstructions and their exact endpoints.
    summary = {(tuple(r['shape']), r['channels']): r['joint_nullity'] for r in reports}
    assert summary[((3, 3), 2)] == 1 and summary[((3, 3), 3)] == 0
    assert summary[((4, 4), 3)] == 1 and summary[((4, 4), 4)] == 0
    assert summary[((2, 3, 4), 2)] == 0
    return {"stacked_rank_cases": len(reports),
            "proportional_channel_counterexamples": 6, "cases": reports}


def check_scalar_completion():
    rng = random.Random(20102026)
    completed = probe_count = orthogonality_checks = null_probe_tests = 0
    examples = []
    for shape in ((2, 2), (3, 3), (4, 4), (2, 3, 4), (3, 3, 3)):
        a, _ = marginal_matrix(shape)
        basis = [one_factor_basis(q) for q in shape]
        hidden = [tensor_vector(shape, basis, labels)
                  for labels in product(*(range(1, q) for q in shape))]
        expected_d = prod(q - 1 for q in shape)
        assert len(hidden) == expected_d
        for i, u in enumerate(hidden):
            assert matvec(a, u) == [0] * len(a)
            for v in hidden[:i]:
                assert dot(u, v) == 0
                orthogonality_checks += 1
        for repetition in range(4):
            z = [F(rng.randrange(1, 100), rng.randrange(1, 20))
                 for _ in range(prod(shape))]
            sums = matvec(a, z)
            visible = observable_from_marginals(shape, sums)
            for h in hidden:
                assert dot(h, visible) == 0
            total = sum(sums[:prod(shape) // shape[0]], F(0))
            assert total == sum(z, F(0))
            out = list(visible)
            for h in hidden:
                alpha = F(1, 1 + max(map(abs, h)))
                mask = [1 + alpha * x for x in h]
                assert min(mask) > 0 and max(mask) < 2
                assert sum(mask, F(0)) == prod(shape)
                measured = dot(mask, z)
                coefficient = (measured - total) / (alpha * dot(h, h))
                out = [x + coefficient * y for x, y in zip(out, h)]
                probe_count += 1
            assert out == z
            completed += 1
            # Omitting one orthogonal completion leaves a concrete positive
            # indistinguishable pair, illustrating the general rank lower bound.
            omitted = repetition % len(hidden)
            delta = min(z) / (2 * max(map(abs, hidden[omitted])))
            alternative = [x + delta * y for x, y in zip(z, hidden[omitted])]
            assert min(alternative) > 0 and alternative != z
            assert matvec(a, alternative) == sums
            for i, h in enumerate(hidden):
                if i != omitted:
                    assert dot(h, alternative) == dot(h, z)
            null_probe_tests += 1
        examples.append({"shape": list(shape), "necessary_and_sufficient_extra_scalars": expected_d})
    return {"positive_tensor_reconstructions": completed,
            "positive_mask_scalar_probes": probe_count,
            "orthogonality_checks": orthogonality_checks,
            "missing_probe_nonuniqueness_examples": null_probe_tests,
            "dimensions": examples}


def check_bounded_fourier_completion():
    """Exact fourth-root-of-unity cases of the general Fourier construction.

    Shapes use only 2 and 4, so real/imaginary character values are integers;
    no trigonometric approximation or complex floating point is involved.
    """
    reports = []
    noise_equalities = 0
    rho = F(1, 2)
    roots = ((1, 0), (0, 1), (-1, 0), (0, -1))
    for shape in ((2, 2), (4, 4), (2, 4, 4), (4, 4, 4)):
        xs = points(shape)
        a, _ = marginal_matrix(shape)
        contrasts = []
        for frequency in product(*(range(1, q) for q in shape)):
            conjugate = tuple((-k) % q for k, q in zip(frequency, shape))
            if frequency > conjugate:
                continue
            real, imag = [], []
            for x in xs:
                phase = sum((4 // q) * k * xi for q, k, xi in zip(shape, frequency, x)) % 4
                re, im = roots[phase]
                real.append(F(re))
                imag.append(F(im))
            contrasts.append(real)
            if frequency != conjugate:
                contrasts.append(imag)
        assert len(contrasts) == prod(q - 1 for q in shape)
        for i, h in enumerate(contrasts):
            assert matvec(a, h) == [0] * len(a)
            assert dot(h, h) in (prod(shape), F(prod(shape), 2))
            for other in contrasts[:i]:
                assert dot(h, other) == 0
        z = [F(2 + (i * 7) % 23, 5) for i in range(prod(shape))]
        visible = observable_from_marginals(shape, matvec(a, z))
        total = sum(z, F(0))
        reconstructed = list(visible)
        for h in contrasts:
            mask = [1 + rho * x for x in h]
            assert min(mask) >= F(1, 2) and max(mask) <= F(3, 2)
            coefficient = (dot(mask, z) - total) / (rho * dot(h, h))
            reconstructed = [x + coefficient * y for x, y in zip(reconstructed, h)]
        assert reconstructed == z
        # Single-coordinate noise on a non-self-conjugate mode attains the
        # uniform sqrt(2/N)/rho bound. Binary-only shapes have the stronger one.
        target = min(contrasts, key=lambda h: dot(h, h))
        epsilon = F(1, 1000)
        perturbation = [epsilon * x / (rho * dot(target, target)) for x in target]
        actual_error_squared = dot(perturbation, perturbation)
        exact_bound_squared = epsilon ** 2 / (rho ** 2 * dot(target, target))
        assert actual_error_squared == exact_bound_squared
        if dot(target, target) == F(prod(shape), 2):
            assert actual_error_squared == 2 * epsilon ** 2 / (rho ** 2 * prod(shape))
        noise_equalities += 1
        reports.append({"shape": list(shape), "positive_probes": len(contrasts),
                        "minimum_contrast_norm_squared": str(dot(target, target)),
                        "recovered_exactly": True})
    return {"exact_fourier_cases": len(reports),
            "sharp_noise_equalities": noise_equalities, "cases": reports}


def run():
    return {"status": "PASS", "arithmetic": "exact integers/Fractions",
            "spectrum": check_spectrum(),
            "separable_channels": check_separable_channels(),
            "scalar_completion": check_scalar_completion(),
            "bounded_fourier_completion": check_bounded_fourier_completion(),
            "scope": "Finite checks support proofs; no priority or physical-sensor optimality claim."}


if __name__ == '__main__':
    print(json.dumps(run(), indent=2, sort_keys=True))