Nhairun-Exact-Complexity / code /verify_broadening.py
PureOne's picture
Release Nhairun Delta research dataset, manuscript revision 3
1263695 verified
Raw History Blame Contribute Delete
7.67 kB
#!/usr/bin/env python3
"""Finite exact audits for the scalar strengthening and matching approximation."""
from fractions import Fraction as F
from itertools import permutations,product
from pathlib import Path
import json,random
from scalar_ordering import (build_scalar_reduction,endpoint,raw_residual,
interpolate_consecutive,determinant_mod,coefficient_oracle,next_prime,
approximate_scalar_order,degree_bound)
CHECKS={}
def check(condition,label):
if not condition:raise AssertionError(label)
CHECKS[label]=CHECKS.get(label,0)+1
def scalar_case(values,rho):
m=build_scalar_reduction(values,rho)
n,N=m['n'],m['N']
check(all(abs(t)<F(1,2) for t in m['centers']),'scalar_bounded_centers')
sums=[]
for mask in range(1<<N):
sums.append(sum(m['weights'][i] for i in range(N) if mask>>i&1))
check(len(set(sums))==len(sums),'rational_subset_weight_injectivity')
min_abs=None;zeros=0;canonical_count=0;count=0
selected=[]
for order in permutations(range(N)):
count+=1
digits=[0]*n
positions=[[] for _ in range(n)]
for p,j in enumerate(order):
digits[j//2]+=m['weights'][p]
positions[j//2].append(p)
control=sum(a*b for a,b in zip(m['markers'],digits))
canonical=all(pos==[2*i,2*i+1] for i,pos in enumerate(positions))
required=m['target']//m['Q']
check((control==required)==canonical,'marker_control_equivalence')
res=raw_residual(m,order)
perturbation=sum(m['weights'][p]*(m['data'][j//2] if j%2==0 else -m['data'][j//2]) for p,j in enumerate(order))
check(abs(perturbation)<=m['D'],'data_term_dominance_bound')
if not canonical:
check(abs(res)>=m['Q']-m['D'],'noncanonical_integer_separation')
else:
canonical_count+=1
signs=[]
for i in range(n):
signs.append(1 if order[2*i+1]%2==0 else -1)
check(res==m['H']*sum(s*a for s,a in zip(signs,values)),'canonical_scalar_partition_identity')
zeros+=res==0
min_abs=abs(res) if min_abs is None else min(min_abs,abs(res))
if count%max(1,(__import__('math').factorial(N)//24))==0:selected.append(order)
# Add all canonical orientations so perturbation checks include actual
# zero-error YES witnesses, rather than only generic sampled orders.
for signs in product([-1,1],repeat=n):
order=[]
for i,sign in enumerate(signs):
order.extend([2*i+1,2*i] if sign==1 else [2*i,2*i+1])
selected.append(tuple(order))
expected=any(sum(s*a for s,a in zip(signs,values))==0 for signs in product([-1,1],repeat=n))
check((zeros>0)==expected,'scalar_partition_decision_equivalence')
for order in selected:
state=F(0)
for j in order:
state=rho*state+(1-rho)*m['centers'][j]
check(abs(state)<F(1,2),'scalar_all_checked_prefixes_bounded')
check(state==F(raw_residual(m,order),rho.denominator**(N-1)*m['R']),'scalar_recurrence_integer_identity')
# A uniform center perturbation realizes a near-worst-case total shift.
eta=m['gap']/4
perturbed=[t+eta for t in m['centers']]
actual=endpoint(perturbed,order,rho)
check(abs(actual-state)<=eta,'scalar_perturbation_lipschitz_bound')
if state==0:
check(actual*actual<=m['gap']**2/16,'robust_yes_margin')
else:
check(actual*actual>=9*m['gap']**2/16,'robust_no_margin')
return dict(values=values,rho=str(rho),orders=count,canonical_orders=canonical_count,
zero_orders=zeros,partition_exists=expected,minimum_absolute_integer_residual=str(min_abs),
centers=[str(t) for t in m['centers']],normalizer=str(m['R']),
guaranteed_endpoint_gap=str(m['gap']),maximum_center_encoding_bits=max(max(abs(t.numerator).bit_length(),t.denominator.bit_length()) for t in m['centers']))
def matching_audits():
rng=random.Random(93811)
interpolation=[]
for degree in range(13):
p=next_prime(1000+degree)
coefficients=[rng.randrange(p) for _ in range(degree+1)]
values=[sum(c*pow(x,j,p) for j,c in enumerate(coefficients))%p for x in range(degree+1)]
check(interpolate_consecutive(values,p)==coefficients,'finite_field_interpolation')
for n in range(1,5):
for trial in range(6):
costs=[[None if rng.randrange(8)==0 else rng.randrange(5) for _ in range(n)] for _ in range(n)]
attainable={sum(costs[i][j] for i,j in enumerate(order)) for order in permutations(range(n)) if all(costs[i][j] is not None for i,j in enumerate(order))}
p=next_prime(8*n**3*(degree_bound(costs)+1)+1)
observed=coefficient_oracle(costs,p,rng)
check(observed<=attainable,'matching_oracle_no_false_positives')
# The fixed seed is an implementation audit, not a proof that
# every random labeling succeeds.
check(observed==attainable,'matching_oracle_observed_full_support')
# Equal edge labels can erase all genuine matchings by cancellation.
check(determinant_mod([[1,1],[1,1]],101)==0,'determinant_cancellation_witness')
return dict(interpolation_degrees_tested=13,matching_instances=24)
def approximate_audits():
configurations=[
([F(-1),F(0),F(1)],F(1,2),F(0),F(0),F(1,2)),
([F(-1,2),F(1,4),F(3,4)],F(2,3),F(1,4),F(-1,4),F(1,2)),
([F(-3,4),F(-1,4),F(1,4),F(3,4)],F(1,2),F(0),F(0),F(1,2)),
([F(-1),F(1,3),F(2,3),F(1)],F(9,10),F(-1,2),F(1,2),F(1,2)),
([F(-1,2),F(1,2),F(3,4)],F(1,3),F(1),F(-1),F(1,4)),
([F(0),F(0),F(0)],F(1,2),F(0),F(0),F(1,2))]
results=[]
for i,(centers,rho,initial,target,eps) in enumerate(configurations):
optimum=min((endpoint(centers,order,rho,initial)-target)**2 for order in permutations(range(len(centers))))
out=approximate_scalar_order(centers,rho,eps,F(1,16),initial,target,random.Random(451+i))
check(sorted(out['order'])==list(range(len(centers))),'approximation_feasible_permutation')
check(out['objective']==(endpoint(centers,out['order'],rho,initial)-target)**2,'approximation_exact_output_certificate')
check(out['objective']<=optimum+eps,'observed_additive_approximation_guarantee')
check(out['statistics']['degree']<=32*len(centers)/eps+len(centers),'rounded_degree_bound')
results.append(dict(centers=list(map(str,centers)),rho=str(rho),initial=str(initial),target=str(target),epsilon=str(eps),order=out['order'],objective=str(out['objective']),exact_optimum=str(optimum),statistics=out['statistics']))
return results
def main():
cases=[(v,rho) for rho in [F(1,2),F(1,3),F(2,3),F(9,10)] for v in [[1,2,3],[1,1,3]]]
cases.extend([(v,F(1,2)) for v in [[1,2,3,4],[1,2,4,8]]])
result=dict(arithmetic='Exact integers, rational fractions, and exact finite-field arithmetic; no floating-point proof decisions.',scalar_cases=[scalar_case(v,rho) for v,rho in cases],matching_audits=matching_audits(),approximation_cases=approximate_audits())
result['assertions']=CHECKS
result['assertions_total']=sum(CHECKS.values())
result['scalar_orders_total']=sum(case['orders'] for case in result['scalar_cases'])
result['baseline_assertions_retained']=344707
result['combined_assertions']=344707+result['assertions_total']
Path(__file__).with_name('broadening_verification_results.json').write_text(json.dumps(result,indent=2)+'\n')
print(json.dumps({key:result[key] for key in ['assertions_total','scalar_orders_total','baseline_assertions_retained','combined_assertions']},indent=2))
if __name__=='__main__':main()