Elyxune-Sharp-Exchange-Laws / verification /verify_sharp_exchange.py
PureOne's picture
Add Elyxune sharp exchange research dataset
66937d8 verified
Raw History Blame Contribute Delete
12.6 kB
#!/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)