File size: 16,281 Bytes
ea14529
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
#!/usr/bin/env python3
"""Finite certificates for strengthened hyperfield aggregation theorems.

Exact rational, exact algebraic, formal-polynomial, and numerical checks are
distinguished in the output. These computations supplement the written proofs;
they do not establish any universal assertion by numerical extrapolation.
Requires Python 3 and mpmath 1.3.0 for the explicitly numerical checks.
"""
from __future__ import annotations

import argparse
from collections import Counter
from fractions import Fraction as Q
from functools import lru_cache
from itertools import combinations, combinations_with_replacement, product
import json
from math import isqrt
from pathlib import Path
import random


def rational_string(x):
    x = Q(x)
    return str(x.numerator) if x.denominator == 1 else f"{x.numerator}/{x.denominator}"


def multiply(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 transpose(a):
    return [list(row) for row in zip(*a)]


def congruence(a, l):
    return multiply(transpose(l), multiply(a, l))


def matrix_equal(a, b):
    return a == b


def products_for_quartet(a, quartet):
    i, j, k, l = quartet
    return [a[i][j] * a[k][l], a[i][k] * a[j][l], a[i][l] * a[j][k]]


def all_matrix_quartets(a):
    for quartet in combinations_with_replacement(range(len(a)), 4):
        yield quartet, products_for_quartet(a, quartet)


def check_matrix_exact(a, parameter):
    assert parameter in (1, 2)
    count = 0
    smallest = None
    for quartet, terms in all_matrix_quartets(a):
        if parameter == 1:
            margin = sum(terms) - 2 * max(terms)
        else:
            x, y, z = terms
            margin = 2 * (x*y + x*z + y*z) - x*x - y*y - z*z
        assert margin >= 0, (parameter, quartet, terms, margin)
        smallest = margin if smallest is None else min(smallest, margin)
        count += 1
    return dict(quartet_count=count,
                minimum_exact_polynomial_margin=rational_string(smallest))


def determinant_magnitudes(columns):
    return [[abs(u[0]*v[1] - u[1]*v[0]) for v in columns] for u in columns]


def rational_matrices():
    rng = random.Random(186741)
    cases = []
    sources = [
        [(1, 0), (0, 1), (1, 1), (1, -1), (0, 0), (1, 0)],
        [(1, 0), (0, 1), (2, 1), (3, 2), (-2, 3), (1, 0)],
        [(0, 0), (1, 2), (2, 4), (1, -1), (3, 1), (0, 1)],
    ]
    for trial in range(8):
        columns = sources[trial % len(sources)]
        l1 = [[Q(rng.choice([0, 0, 1, 2, 3]), rng.choice([1, 2, 3]))
               for _ in range(4)] for _ in range(6)]
        l2 = [[Q(rng.choice([0, 1, 2, 3]), rng.choice([1, 2]))
               for _ in range(3)] for _ in range(4)]
        if trial == 0:
            for row in l1:
                row[-1] = Q(0)
        cases.append((columns, l1, l2))
    return cases


def exact_congruence_checks(cases):
    out = []
    for trial, (columns, l1, l2) in enumerate(cases, 1):
        minors = determinant_magnitudes(columns)
        for q in (1, 2):
            a = [[Q(x)**q for x in row] for row in minors]
            source = check_matrix_exact(a, q)
            h1 = congruence(a, l1)
            h2 = congruence(h1, l2)
            direct = congruence(a, multiply(l1, l2))
            assert matrix_equal(h2, direct)
            assert all(x >= 0 for row in h2 for x in row)
            out.append(dict(trial=trial, input_parameter=q,
                            source_check=source,
                            first_substitution=check_matrix_exact(h1, q),
                            composed_substitution=check_matrix_exact(h2, q),
                            nonzero_diagonal_after_first=sum(h1[i][i] > 0 for i in range(4)),
                            exact_composition_identity=True,
                            arithmetic="exact rational"))
    return out


def polynomial_add(a, b):
    out = Counter(a)
    out.update(b)
    return {k: v for k, v in out.items() if v}


def polynomial_multiply(a, b):
    out = Counter()
    for m, c in a.items():
        for n, d in b.items():
            out[tuple(sorted(m+n))] += c*d
    return dict(out)


def formal_tensor_factorizations():
    n = 3
    def asym(i, j):
        return "A" + str(min(i, j)) + str(max(i, j))
    def entry(a, b):
        out = Counter()
        for i, j in product(range(n), repeat=2):
            out[tuple(sorted((asym(i, j), f"L{i}{a}", f"L{j}{b}")))] += 1
        return dict(out)
    pairings = [((0, 1), (2, 3)), ((0, 2), (1, 3)), ((0, 3), (1, 2))]
    out = []
    for pairing in pairings:
        (a, b), (c, d) = pairing
        lhs = polynomial_multiply(entry(a, b), entry(c, d))
        rhs = Counter()
        for indices in product(range(n), repeat=4):
            i, j, k, l = indices
            rhs[tuple(sorted((asym(indices[a], indices[b]),
                              asym(indices[c], indices[d]),
                              f"L{i}0", f"L{j}1", f"L{k}2", f"L{l}3")))] += 1
        assert lhs == dict(rhs)
        out.append(dict(pairing=pairing, expanded_monomials=len(lhs),
                        total_summands=sum(lhs.values()), status="identity verified"))
    return dict(arithmetic="exact commutative polynomial identities",
                source_indices=n, target_indices=4, factorizations=out)


def numerical_congruence_checks(cases):
    import mpmath as mp
    mp.mp.dps = 90
    def m(x):
        x = Q(x)
        return mp.mpf(x.numerator) / x.denominator
    samples = ["0.25", "0.5", "1", "1.5", "2", "3", "4", "8"]
    out = []
    for trial, (columns, l1, l2) in enumerate(cases, 1):
        minors = determinant_magnitudes(columns)
        ml1 = [[m(x) for x in row] for row in l1]
        ml2 = [[m(x) for x in row] for row in l2]
        for qs in samples:
            q = mp.mpf(qs)
            p = max(q, mp.mpf(1))
            a = [[m(x)**q for x in row] for row in minors]
            h1 = congruence(a, ml1)
            h2 = congruence(h1, ml2)
            hd = congruence(a, multiply(ml1, ml2))
            for row1, row2 in zip(h2, hd):
                for x, y in zip(row1, row2):
                    assert abs(x-y) <= mp.mpf("1e-78") * max(abs(x), abs(y), 1)
            for stage, h in (("first", h1), ("composed", h2)):
                count = 0
                smallest = mp.mpf(1)
                for quartet, terms in all_matrix_quartets(h):
                    roots = [x**(1/p) for x in terms]
                    scale = max(roots)
                    rel = mp.mpf(0) if not scale else (sum(roots)-2*scale)/scale
                    assert rel >= -mp.mpf("1e-76"), (trial, qs, stage, quartet, rel)
                    smallest = min(smallest, rel)
                    count += 1
                out.append(dict(trial=trial, input_parameter=qs,
                                output_parameter=mp.nstr(p, 15), stage=stage,
                                quartet_count=count,
                                minimum_relative_root_polygon_slack=mp.nstr(smallest, 30),
                                precision_decimal_digits=90,
                                arithmetic="high-precision numerical; not an exact certificate"))
    return out


def minimal_threshold_certificate():
    columns = [(1, 0), (0, 1), (1, 64), (64, -1)]
    mm = determinant_magnitudes(columns)
    input_lengths = [mm[0][1]*mm[2][3], mm[0][2]*mm[1][3], mm[0][3]*mm[1][2]]
    assert input_lengths == [4097, 4096, 1]
    assert sum(input_lengths)-2*max(input_lengths) == 0
    assert mm[0][2] == mm[1][3] == 64
    assert mm[0][3] == mm[1][2] == 1
    output_root_lengths = [4*4097, 81**2, 81**2]
    defect = max(output_root_lengths) - sum(output_root_lengths[1:])
    assert output_root_lengths == [16388, 6561, 6561]
    assert defect == 3266
    return dict(input_parameter="1/2", columns=columns,
                input_root_product_lengths=input_lengths,
                normalized_output_products=["2*sqrt(4097)", "81", "81"],
                output_root_product_lengths=output_root_lengths,
                exact_output_root_defect=defect,
                input_support="U_(2,4); all six minors nonzero",
                arithmetic="exact integers and stated algebraic square roots")


def strong_relation_products(coeff, d, n):
    for raw_i in combinations(range(n), d-1):
        i = frozenset(raw_i)
        for raw_j in combinations(range(n), d+1):
            j = frozenset(raw_j)
            yield i, j, [coeff[i | {a}]*coeff[j - {a}] for a in sorted(j-i)]


def weak_relation_products(coeff, d, n):
    for cc in combinations(range(n), d-2):
        c = frozenset(cc)
        for i, j, k, l in combinations(sorted(set(range(n))-c), 4):
            yield c, (i, j, k, l), [coeff[c | {i, j}]*coeff[c | {k, l}],
                                    coeff[c | {i, k}]*coeff[c | {j, l}],
                                    coeff[c | {i, l}]*coeff[c | {j, k}]]


def two_peak_coefficients(d, n, peak1, peak2, default):
    c = set(range(6, d+3))
    u, v = frozenset(c | {0, 2, 4}), frozenset(c | {1, 3, 5})
    coeff = {frozenset(s): Q(default) for s in combinations(range(n), d)}
    coeff[u], coeff[v] = Q(peak1), Q(peak2)
    return coeff, c


def two_peak_weak_checks():
    out = []
    for d, n in ((3, 6), (4, 7), (5, 8), (4, 8)):
        coeff, _ = two_peak_coefficients(d, n, 2, 2, 1)
        count = 0
        types = Counter()
        for _, _, terms in weak_relation_products(coeff, d, n):
            assert sum(terms)-2*max(terms) >= 0
            types[tuple(sorted(terms))] += 1
            count += 1
        strong_failures = 0
        for _, _, terms in strong_relation_products(coeff, d, n):
            strong_failures += sum(terms)-2*max(terms) < 0
        assert strong_failures > 0
        out.append(dict(rank=d, ground_size=n, weak_relations=count,
                        root_product_patterns={str(tuple(rational_string(t) for t in k)): v
                                               for k, v in types.items()},
                        failed_strong_relations=strong_failures,
                        arithmetic="exact rational root products"))
    return dict(instances=out,
                universal_output_products=["(1+2^q)^2", "4", "4"],
                necessary_output_parameter="p >= 2*log_2((1+2^q)/2)",
                qualification="The universal formula requires the written symbolic proof.")


@lru_cache(maxsize=None)
def sqrt_interval(x, digits=80):
    x = Q(x)
    scale = 10**digits
    k = isqrt((x.numerator*scale*scale)//x.denominator)
    lo = Q(k, scale)
    hi = lo if lo*lo == x else Q(k+1, scale)
    assert lo*lo <= x <= hi*hi
    return lo, hi


def two_peak_strong_checks():
    out = []
    for d, n in ((3, 6), (4, 7), (5, 8), (4, 8), (5, 9)):
        roots, _ = two_peak_coefficients(d, n, 2, Q(3, 2), 1)
        weak_count = genuine_count = taut_count = 0
        root_patterns = Counter()
        for _, _, terms in strong_relation_products(roots, d, n):
            assert sum(terms)-2*max(terms) >= 0
            root_patterns[tuple(sorted(terms))] += 1
            if len(terms) == 2:
                taut_count += 1
            else:
                genuine_count += 1
        for _, _, terms in weak_relation_products(roots, d, n):
            assert sum(terms)-2*max(terms) >= 0
            weak_count += 1
        integer, c = two_peak_coefficients(d, n, 23, 14, 6)
        smallest = None
        strict_count = 0
        for i, j, terms in strong_relation_products(integer, d, n):
            if len(terms) == 2:
                assert terms[0] == terms[1]
                continue
            largest = max(range(len(terms)), key=terms.__getitem__)
            intervals = [sqrt_interval(t) for t in terms]
            certified_margin = sum(lo for k, (lo, hi) in enumerate(intervals)
                                   if k != largest) - intervals[largest][1]
            assert certified_margin > 0, (d, n, i, j, terms)
            smallest = certified_margin if smallest is None else min(smallest, certified_margin)
            strict_count += 1
        g = {str(i+1)+str(j+1): integer[frozenset(c | {i, j, 4})]
                                    + integer[frozenset(c | {i, j, 5})]
             for i, j in combinations(range(4), 2)}
        assert g["13"] == 29 and g["24"] == 20
        assert all(g[t] == 12 for t in ("12", "14", "23", "34"))
        products_out = [g["13"]*g["24"], g["12"]*g["34"], g["14"]*g["23"]]
        assert products_out == [580, 144, 144]
        squared_excess = products_out[0] - 24**2
        assert squared_excess == 4
        out.append(dict(rank=d, ground_size=n, weak_relation_count=weak_count,
                        strong_genuine_relation_count=genuine_count,
                        strong_tautological_relation_count=taut_count,
                        strong_root_peak_values=["2", "3/2"],
                        strict_integer_coefficient_values=[6, 14, 23],
                        strict_integer_input_relations_certified=strict_count,
                        exact_minimum_root_margin_lower_bound=rational_string(smallest),
                        output_coefficients={k: rational_string(v) for k, v in g.items()},
                        output_products=[int(x) for x in products_out],
                        exact_squared_output_excess=int(squared_excess),
                        arithmetic="exact rational root products and rational square-root intervals"))
    return dict(instances=out,
                universal_two_peak_output_products=["(1+2^q)*(1+(3/2)^q)", "4", "4"],
                necessary_output_parameter="p >= log_2(((1+2^q)*(1+(3/2)^q))/4)",
                exact_boundary_q2_output_products=["65/4", "4", "4"],
                boundary_q2_necessary_output_parameter="p >= log_2(65/16) > 2",
                qualification="Universal validity requires the written all-rank proof.")


def source_size_relation_counts():
    out = []
    for d in range(2, 7):
        for corank in (0, 1, 2, 3):
            n = d+corank
            counts = Counter()
            for i in combinations(range(n), d-1):
                for j in combinations(range(n), d+1):
                    counts[len(set(j)-set(i))] += 1
            largest = max(counts, default=0)
            assert largest <= corank+1
            if corank <= 1:
                assert largest <= 2
            if corank <= 2:
                assert largest <= 3
            out.append(dict(rank=d, ground_size=n, corank=corank,
                            strong_term_counts=dict(sorted(counts.items())),
                            maximum_summands=largest))
    return dict(arithmetic="exact finite combinatorial enumeration", instances=out)


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--output", type=Path,
                        default=Path(__file__).with_name("strengthened_verification_results.json"))
    args = parser.parse_args()
    cases = rational_matrices()
    result = dict(
        title="Strengthened aggregation reproducibility certificates",
        scope="Finite checks supplement the self-contained mathematical proofs.",
        exact_quadratic_congruence=exact_congruence_checks(cases),
        formal_tensor_factorizations=formal_tensor_factorizations(),
        numerical_quadratic_congruence=numerical_congruence_checks(cases),
        exact_minimal_threshold=minimal_threshold_certificate(),
        exact_two_peak_weak=two_peak_weak_checks(),
        exact_two_peak_strong=two_peak_strong_checks(),
        exact_corank_relation_counts=source_size_relation_counts(),
    )
    args.output.parent.mkdir(parents=True, exist_ok=True)
    args.output.write_text(json.dumps(result, indent=2)+"\n")
    print(json.dumps(dict(output=str(args.output.resolve()),
                          exact_congruence_instances=len(result["exact_quadratic_congruence"]),
                          numerical_congruence_instances=len(result["numerical_quadratic_congruence"]),
                          weak_two_peak_instances=len(result["exact_two_peak_weak"]["instances"]),
                          strong_two_peak_instances=len(result["exact_two_peak_strong"]["instances"]),
                          status="all checks passed"), indent=2))


if __name__ == "__main__":
    main()