File size: 12,613 Bytes
66937d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Portable exact checks supplementing the sharp Lorentzian exchange proof.

Run from any directory:
    python /path/to/verify_sharp_exchange.py --output verification_sharp_results.json

Dependency: SymPy. The sibling verify_construction.py
supplies the explicit lower-bound family. This script is not a proof-assistant
formalization and finite checks do not replace the all-rank proof.
"""
import argparse
import itertools
import json
import math
import sys
from pathlib import Path
import sympy as sp

sys.dont_write_bytecode = True

from verify_construction import (
    coefficients,
    integer_example,
    quadratic_hessian,
    check_lorentzian_by_principal_minors,
)


def key(items):
    return tuple(sorted(items))


def weight_product(items, weights):
    ans = sp.Integer(1)
    for i in items:
        ans *= weights[i]
    return ans


def aggregate_coefficients(C, rank, weights, factor=True):
    """Normalized coefficients after z_i=a_i*x on A and z_j=y on B.

    A={0,...,r-1}, B={r,...,2r-2}, u=2r-1. Every basis is scanned.
    C includes all r-subsets; zero values are allowed.
    """
    A = set(range(rank))
    u = 2*rank-1
    h = [sp.Integer(0) for _ in range(rank+1)]
    g = [sp.Integer(0) for _ in range(rank)]
    for basis, coeff in C.items():
        selected_A = A.intersection(basis)
        j = len(selected_A)
        contribution = coeff*weight_product(selected_A, weights)
        if u in basis:
            g[j] += contribution
        else:
            h[j] += contribution
    h = [(sp.factor(z) if factor else z)*math.factorial(j)*math.factorial(rank-j) for j,z in enumerate(h)]
    g = [(sp.factor(z) if factor else z)*math.factorial(j)*math.factorial(rank-1-j) for j,z in enumerate(g)]
    return h, g


def check_endpoint_identities(C, rank, weights, h, g):
    A=set(range(rank)); B=set(range(rank,2*rank-1));u=2*rank-1
    prod=weight_product(A,weights)
    p=C[key(A)];q=C[key(B|{u})]
    c=[C[key(B|{i})] for i in sorted(A)]
    e=[C[key(A-{i}|{u})] for i in sorted(A)]
    expected=[
        math.factorial(rank)*p*prod,
        math.factorial(rank-1)*q,
        math.factorial(rank-1)*sum(weights[i]*c[i] for i in sorted(A)),
        math.factorial(rank-1)*prod*sum(e[i]/weights[i] for i in sorted(A)),
    ]
    actual=[h[rank],g[0],h[1],g[rank-1]]
    for got,want in zip(actual,expected):
        assert sp.expand(got-want)==0
    Q=[sp.factor(ci*ei) for ci,ei in zip(c,e)]
    return sp.factor(p*q), Q


def symbolic_checks():
    h0,h1,h2,g0,g1=sp.symbols('h0 h1 h2 g0 g1', nonnegative=True)
    M=sp.Matrix([[0,g1,g0],[g1,h2,h1],[g0,h1,h0]])
    expected=2*g0*g1*h1-g0**2*h2-g1**2*h0
    assert sp.expand(M.det()-expected)==0
    rows=[]
    for r in range(2,8):
        H=sp.symbols('H0:'+str(r+1),positive=True)
        G=sp.symbols('G0:'+str(r),positive=True)
        product_H=sp.prod(H[j+2]/H[j+1] for j in range(r-1))
        product_G=sp.prod(G[j+1]/G[j] for j in range(r-1))
        assert sp.cancel(product_H-H[r]/H[1])==0
        assert sp.cancel(product_G-G[r-1]/G[0])==0
        # Endpoint identities with independent basis-coefficient symbols and
        # independent positive external weights, not a particular family.
        allbases=list(itertools.combinations(range(2*r),r))
        C={S:sp.Symbol('c_'+ '_'.join(map(str,S))) for S in allbases}
        weights=dict(enumerate(sp.symbols('a0:'+str(r),positive=True)))
        h,g=aggregate_coefficients(C,r,weights,factor=False)
        check_endpoint_identities(C,r,weights,h,g)
        # This factorial identity is the source of the 1/r improvement.
        assert sp.Rational(math.factorial(r-1),math.factorial(r))==sp.Rational(1,r)
        rows.append({'rank':r,'basis_symbols_scanned':len(allbases),
                     'telescoping_identities_checked':2,
                     'weighted_endpoint_identities_checked':4,
                     'factorial_ratio':str(sp.Rational(1,r))})
    return {'generic_determinant_identity':str(expected),'ranks':rows}


def family_checks():
    rows=[]
    for r in range(2,8):
        s=sp.Rational(1,20);lam=sp.Rational(19,10)
        C=coefficients(r,s,lam)
        assert len(C)==math.comb(2*r,r)
        assert all(z>0 for z in C.values())
        weights={i:sp.Rational(i+2,i+1) for i in range(r)}
        h,g=aggregate_coefficients(C,r,weights)
        lhs,Q=check_endpoint_identities(C,r,weights,h,g)
        assert len(set(Q))==1
        determinants=[]
        for j in range(r-1):
            M=sp.Matrix([[0,g[j+1],g[j]],[g[j+1],h[j+2],h[j+1]],[g[j],h[j+1],h[j]]])
            det=sp.factor(M.det())
            assert det>0
            assert h[j+2]*g[j]<2*h[j+1]*g[j+1]
            determinants.append(det)
        assert h[r]*g[0] <2**(r-1)*h[1]*g[r-1]
        maxratio=sp.factor(lhs/max(Q));sumratio=sp.factor(lhs/sum(Q))
        # All Q_i coincide, so the squared root-sum is exactly r^2 Q_0.
        rootratio=sp.factor(lhs/(r*r*Q[0]))
        assert maxratio==r*lam**(r-1)
        assert sumratio==lam**(r-1)
        assert rootratio==lam**(r-1)/r
        # A fully rational, interior, explicitly near-optimal witness.
        N=100*r
        near_lam=2-sp.Rational(1,N);near_s=sp.Rational(1,2*N)
        assert 1<near_lam<2 and 0<near_s<2-near_lam
        near_C=coefficients(r,near_s,near_lam)
        A=set(range(r));B=set(range(r,2*r-1));u=2*r-1
        near_lhs=near_C[key(A)]*near_C[key(B|{u})]
        near_Q=[near_C[key(A-{i}|{u})]*near_C[key(B|{i})] for i in sorted(A)]
        assert len(set(near_Q))==1
        assert sp.factor(near_lhs/near_Q[0])==r*near_lam**(r-1)
        relative=sp.factor((near_lam/2)**(r-1))
        bernoulli=1-sp.Rational(r-1,2*N)
        assert relative>=bernoulli
        assert bernoulli>sp.Rational(199,200)
        rows.append({
            'rank':r,'bases_enumerated':len(C),
            'external_weights':[str(weights[i]) for i in range(r)],
            'positive_aggregate_determinants_checked':len(determinants),
            'weighted_endpoint_identities_checked':4,
            'max_ratio':str(maxratio),'sum_ratio':str(sumratio),'root_sum_ratio':str(rootratio),
            'sharp_universal_constants':{'max':r*2**(r-1),'sum':2**(r-1),'root_sum':str(sp.Rational(2**(r-1),r))},
            'near_optimal':{'N':N,'s':str(near_s),'lambda':str(near_lam),
                'bases_enumerated':len(near_C),'relative_to_each_optimal_constant':str(relative),
                'bernoulli_lower_bound':str(bernoulli),
                'relative_error_upper_bound':str(sp.Rational(r-1,2*N))},
        })
    return rows


def exhaustive_exchange_checks(C,n,rank,root_exact_for_unit=False):
    bases=[set(S) for S,c in C.items() if c>0]
    max_checks=sum_checks=root_checks=0
    distances={};radical_certificates={}
    worst_max=sp.Rational(0);worst_sum=sp.Rational(0)
    for S in bases:
        for T in bases:
            d=len(S-T)
            if d==0:continue
            lhs=C[key(S)]*C[key(T)]
            for u in sorted(T-S):
                Q=[C.get(key(S-{i}|{u}),0)*C.get(key(T-{u}|{i}),0) for i in sorted(S-T)]
                assert max(Q)>0
                assert lhs<=d*2**(d-1)*max(Q)
                assert lhs<=2**(d-1)*sum(Q)
                max_checks+=1;sum_checks+=1
                distances[str(d)]=distances.get(str(d),0)+1
                worst_max=max(worst_max,sp.factor(lhs/max(Q)))
                worst_sum=max(worst_sum,sp.factor(lhs/sum(Q)))
                if root_exact_for_unit:
                    assert lhs==1 and all(z in (0,1) for z in Q)
                    k=sum(z==1 for z in Q)
                    assert lhs<=sp.Rational(2**(d-1),d)*k*k
                else:
                    signature=(d,lhs,tuple(sorted(Q)))
                    if signature not in radical_certificates:
                        # Exact symbolic radicals and an exact sign decision.
                        # No floating point tolerance is used.
                        slack=sp.expand(sp.Rational(2**(d-1),d)*sum(sp.sqrt(z) for z in Q)**2-lhs)
                        assert slack.is_nonnegative is True, (signature,slack)
                        radical_certificates[signature]=str(slack)
                root_checks+=1
    ans={'positive_bases':len(bases),'ordered_basis_pair_exchange_triples':max_checks,
         'by_exchange_distance':distances,'exact_max_inequalities_checked':max_checks,
         'exact_sum_inequalities_checked':sum_checks,'exact_root_sum_inequalities_checked':root_checks,
         'largest_observed_max_ratio':str(worst_max),'largest_observed_sum_ratio':str(worst_sum)}
    if not root_exact_for_unit:
        ans['distinct_exact_radical_certificates']=len(radical_certificates)
        ans['exact_radical_slacks']=[{'distance':int(k[0]),'target':str(k[1]),'exchange_products':list(map(str,k[2])),'slack':v} for k,v in sorted(radical_certificates.items())]
    return ans


def graphic_k4():
    edges=list(itertools.combinations(range(4),2))
    C={}
    for S in itertools.combinations(range(len(edges)),3):
        parent=list(range(4))
        def find(i):
            while parent[i]!=i:i=parent[i]
            return i
        cycle=False
        for e in S:
            a,b=edges[e];ra,rb=find(a),find(b)
            if ra==rb:cycle=True;break
            parent[ra]=rb
        C[S]=sp.Integer(not cycle and len({find(i) for i in range(4)})==1)
    return C


def partition_pairs():
    C={}
    for S in itertools.combinations(range(6),3):
        C[S]=sp.Integer(all(sum(x//2==g for x in S)==1 for g in range(3)))
    return C


def zero_support_checks():
    rows=[]
    for name,C in [('K4 spanning-tree matroid',graphic_k4()),('three two-element partition classes',partition_pairs())]:
        minors=0
        for i in range(6):
            H=quadratic_hessian(C,(i,),6)
            minors+=check_lorentzian_by_principal_minors(H)
        result=exhaustive_exchange_checks(C,6,3,root_exact_for_unit=True)
        result.update({'name':name,'ground_elements':6,'rank':3,
            'zero_coefficients':sum(c==0 for c in C.values()),
            'exact_nontrivial_principal_minors_checked':minors})
        rows.append(result)
    return rows


def main(output):
    symbolic=symbolic_checks()
    family=family_checks()
    integer=exhaustive_exchange_checks(integer_example(),6,3)
    zero=zero_support_checks()
    result={
        'status':'all exact assertions passed',
        'verification_scope':{
            'proof_assistant_formalization':False,
            'all_rank_theorem_established_by':'the mathematical proof in the manuscript, not extrapolation from these checks',
            'exact_checks':'generic algebra identities; finite-rank weighted aggregation; rational sharpness identities; all integer-example max/sum/root-sum inequalities; zero-supported sample signatures and exchange inequalities',
            'numerical_only':'none in this verifier; radical signs are decided exactly',
            'universal_prerequisite_not_reproved_by_this_script':'Lorentzian closure under nonnegative linear substitutions',
        },
        'symbolic_checks':symbolic,
        'family_checks':family,
        'integer_cubic_exhaustive_exchange_checks':integer,
        'zero_supported_samples':zero,
        'summary':{
            'family_ranks':[r['rank'] for r in family],
            'basis_symbols_scanned_for_symbolic_endpoints':sum(r['basis_symbols_scanned'] for r in symbolic['ranks']),
            'family_bases_scanned_per_parameter_choice':sum(r['bases_enumerated'] for r in family),
            'weighted_aggregate_determinants_checked':sum(r['positive_aggregate_determinants_checked'] for r in family),
            'integer_cubic_exact_max_checks':integer['exact_max_inequalities_checked'],
            'integer_cubic_exact_sum_checks':integer['exact_sum_inequalities_checked'],
            'integer_cubic_exact_root_checks':integer['exact_root_sum_inequalities_checked'],
            'distinct_integer_radical_certificates':integer['distinct_exact_radical_certificates'],
            'zero_sample_exact_signature_minor_checks':sum(r['exact_nontrivial_principal_minors_checked'] for r in zero),
        },
    }
    output=Path(output);output.parent.mkdir(parents=True,exist_ok=True)
    output.write_text(json.dumps(result,indent=2)+'\n')
    print(json.dumps({'status':result['status'],'summary':result['summary'],
                      'integer_cubic':integer,'zero_supported_samples':zero},indent=2))


if __name__=='__main__':
    parser=argparse.ArgumentParser()
    parser.add_argument('--output',default='verification_sharp_results.json')
    main(parser.parse_args().output)