File size: 9,837 Bytes
5fe5e69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Exact contact-collar certificate construction and verification.
Python standard library only. No optimizer or earlier verifier is imported.
The output certifies the listed templates, not all unconditional bodies.
"""
from __future__ import annotations
import argparse, itertools as it, json, math, time
from collections import Counter
from fractions import Fraction as F
from functools import lru_cache
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
ST=Counter()
def require(ok:bool,msg:str)->None:
    if not ok: raise ValueError(msg)
def dot(a,b): return sum((x*y for x,y in zip(a,b)),F(0))
def solve(a,b):
    """Gauss-Jordan solve over Q; None means a singular square system."""
    n=len(b);z=[[F(x) for x in r]+[F(y)] for r,y in zip(a,b)]
    for k in range(n):
        p=next((j for j in range(k,n) if z[j][k]),None)
        if p is None:return None
        z[k],z[p]=z[p],z[k];h=z[k][k];z[k]=[x/h for x in z[k]]
        for j in range(n):
            if j!=k and z[j][k]:
                h=z[j][k];z[j]=[x-h*y for x,y in zip(z[j],z[k])]
    return tuple(z[j][-1] for j in range(n))
@lru_cache(None)
def restricted_vertices(rows,k):
    ans=set()
    for inds in it.combinations(range(len(rows)),k):
        ST['restricted_linear_systems']+=1
        x=solve([rows[i] for i in inds],[1]*k)
        if x and all(t>0 for t in x) and all(dot(r,x)<=1 for r in rows):ans.add(x)
    return tuple(sorted(ans))
def orthant_vertices(rows):
    """Complete vertices of {x>=0 : rows*x<=1}, including cut-plane vertices."""
    n=len(rows[0]);ans={(F(0),)*n}
    for support_mask in range(1,1<<n):
        s=[i for i in range(n) if support_mask>>i&1];k=len(s)
        rr=tuple(sorted({tuple(r[i] for i in s) for r in rows if any(r[i] for i in s)}))
        if len(rr)<k:continue
        for x in restricted_vertices(rr,k):
            v=[F(0)]*n
            for i,t in zip(s,x):v[i]=t
            ans.add(tuple(v))
    return tuple(sorted(ans))
def orbit(v):
    s=[i for i,x in enumerate(v) if x]
    for signs in it.product((-1,1),repeat=len(s)):
        w=list(v)
        for i,t in zip(s,signs):w[i]*=t
        yield tuple(w)
def signed_rows(rows):
    return tuple(sorted({z for a in rows for z in orbit(a)}))
def expand_pairs(pairs):
    ans=[]
    for d in pairs:
        h=max(map(abs,d));require(h>0,'zero direction')
        for s in (1,-1):ans.append(tuple(F(s*x,h) for x in d))
    require(len(set(ans))==len(ans),'duplicate normalized direction')
    return tuple(ans)
def make_certificate(label,rows,positive_vertices,pairs,save_landings=False):
    n=len(rows[0]);D=expand_pairs(pairs);rows=tuple(tuple(map(F,r)) for r in rows)
    vertices=tuple(positive_vertices)
    require(all(dot(a,v)<=1 for a in rows for v in vertices),'infeasible input point')
    require(all(any(v[i]>=1 for v in vertices) for i in range(n)),'axis intercept lower bound')
    g_candidates=[]
    for v in vertices:
        for a in rows:
            value=dot(a,v)
            if value<1:g_candidates.append(1-value)
            else:g_candidates.extend(2*a[i]*v[i] for i in range(n) if a[i]*v[i]>0)
    g=min(g_candidates);require(g>0,'nonpositive slack gap')
    A=max(sum(a,F(0)) for a in rows)
    B=max(dot(a,tuple(map(abs,d))) for a in rows for d in D)
    witness=[];margins=[];point_count=0
    for v0 in vertices:
        active=[a for a in rows if dot(a,v0)==1]
        if not active:continue
        for v in orbit(v0):
            best=None;bm=None
            for di,d in enumerate(D):
                margin=min(-sum((ai*(dj if vj>0 else -dj if vj<0 else abs(dj)) for ai,vj,dj in zip(a,v,d)),F(0)) for a in active)
                ST['active_row_margin_tests']+=len(active)
                if bm is None or margin>bm:bm=margin;best=di
            require(bm is not None and bm>0,f'uncovered point in {label}: {v}')
            margins.append(bm);witness.append((v,best));point_count+=1
    a=min(margins)
    eta=min(F(1,2),g/F(2*(n+1)))
    tau=eta/(a+B);radius=tau*a/(3*A);beta_lower=3*radius
    core=1-2*A*radius
    require(core>0,'invalid inner core')
    saved=[]
    for v,di in witness:
        w=tuple(x+tau*y for x,y in zip(v,D[di]))
        require(all(dot(r,tuple(map(abs,w)))<=core for r in rows),'uniform-step landing failed')
        ST['uniform_core_landings']+=1;ST['absolute_row_core_checks']+=len(rows)
        if save_landings:saved.append({'point':list(map(str,v)),'direction_index':di,'landing':list(map(str,w))})
    cert={'label':label,'dimension':n,'positive_rows':[[str(x) for x in r] for r in rows],
          'positive_generators':[[str(x) for x in v] for v in vertices],
          'directions':[[str(x) for x in d] for d in D],
          'direction_count':len(D),'signed_boundary_points_checked':point_count,
          'g':str(g),'a':str(a),'A':str(A),'B':str(B),'eta':str(eta),'tau':str(tau),
          'closed_Hausdorff_radius':str(radius),'blocking_slack_lower_bound':str(beta_lower),
          'open_Hausdorff_radius':str(beta_lower/2),'inner_core_factor':str(core)}
    if save_landings:cert['landings']=saved
    ST['certificates']+=1
    return cert

def model_certificate():
    j=json.loads((ROOT/'data/cyclic_discovery.json').read_text())
    rows=tuple(tuple(F(x,j['rhs']) for x in r) for r in j['positive_rows'])
    pos=orthant_vertices(rows)
    require(set(pos)=={tuple(map(F,v)) for v in j['positive_orthant_vertices']},'discovery vertex list mismatch')
    cert=make_certificate('irregular cyclic five-body',rows,pos,j['opposite_pair_representatives'],True)
    # Verify all extreme perturbations of every saved boundary point. This is
    # a stress check; the continuum theorem, not this finite set, covers all L.
    D=[tuple(map(F,d)) for d in cert['directions']];h=F(cert['closed_Hausdorff_radius']);t=F(cert['tau']);core=F(cert['inner_core_factor'])
    for rec in cert['landings']:
        v=tuple(map(F,rec['point']));d=D[rec['direction_index']]
        for s in it.product((-1,1),repeat=5):
            w=tuple(v[i]+h*s[i]+t*d[i] for i in range(5))
            require(all(dot(r,tuple(map(abs,w)))<=core for r in rows),'perturbed landing failed')
            ST['perturbed_vertex_landings']+=1;ST['perturbed_absolute_row_checks']+=len(rows)
    # A deliberate corruption must be rejected at a recorded witness.
    rec=next(r for r in cert['landings'] if any(F(x) for x in r['point']))
    v=tuple(map(F,rec['point']));d=D[rec['direction_index']]
    bad=tuple(v[i]-t*d[i] for i in range(5))
    require(any(dot(r,tuple(map(abs,bad)))>1 for r in rows),'mutation was not rejected')
    cert['opposite_direction_mutation_rejected']=True
    (ROOT/'data/cyclic_certificate.json').write_text(json.dumps(cert,indent=2)+'\n')
    return cert

def legacy_atlas():
    j=json.loads((ROOT/'data/legacy_catalogue.json').read_text());out=[]
    require(len(j['representatives'])==180 and len(j['certificates'])==360,'catalogue length')
    for k,c in enumerate(j['certificates']):
        h=tuple(c['facets']);unit=tuple(tuple(F((m>>i)&1) for i in range(5)) for m in h)
        pv=orthant_vertices(unit)
        if c['body']=='P':rows=unit;points=pv
        else:
            rows=tuple(v for v in pv if any(v));points=unit
        cert=make_certificate(f"{c['body']}_{c['index']:03d}",rows,points,c['pairs'])
        cert.update({'legacy_index':c['index'],'legacy_body':c['body'],'support_masks':list(h),'orbit_size':c['orbit_size']})
        out.append(cert)
        if (k+1)%60==0:print(f'Exact atlas: {k+1}/360',flush=True)
    (ROOT/'data/robust_atlas_360.json').write_text(json.dumps(out,indent=2)+'\n')
    return out

def integer_cube_check():
    # Complete n=2,N=14 cube representative of the integer finite-level test.
    n,N=2,14;threshold=(4*n-3)*N;margin=4*(n-1)*N
    normals=[z for z in it.product(range(-N,N+1),repeat=n) if sum(map(abs,z))==N]
    directions=list(it.product((-N,N),repeat=n));count=0
    for y in it.product(range(-N,N+1),repeat=n):
        near=[z for z in normals if N*N-sum(a*b for a,b in zip(z,y))<=threshold]
        require(any(all(sum(a*b for a,b in zip(z,d))<=-margin for z in near) for d in directions),'integer cube certificate failed')
        count+=1
    return {'dimension':n,'N':N,'grid_points':count,'normal_grid_points':len(normals),'point_normal_incidence_tests':count*len(normals),'status':'PASS','scope':'one cube template, not the universal finite statement'}

def main():
    p=argparse.ArgumentParser();p.add_argument('--skip-atlas',action='store_true');args=p.parse_args();start=time.perf_counter()
    model=model_certificate();atlas=[] if args.skip_atlas else legacy_atlas();ic=integer_cube_check()
    report={'status':'PASS','arithmetic':'integers and fractions.Fraction only','stats':dict(ST),'model_direction_count':model['direction_count'],
            'model_closed_radius':model['closed_Hausdorff_radius'],'model_open_radius':model['open_Hausdorff_radius'],
            'model_margin':model['a'],'model_positive_generators':len(model['positive_generators']),
            'atlas_certificates':len(atlas),'integer_cube_test':ic,'unrestricted_5d_theorem_proved':False,
            'universal_integer_level_completed':None,'elapsed_seconds':round(time.perf_counter()-start,3)}
    if atlas:
        h=min(F(c['closed_Hausdorff_radius']) for c in atlas)
        report.update({'atlas_minimum_closed_radius':str(h),'atlas_direction_count_distribution':dict(sorted(Counter(c['direction_count'] for c in atlas).items())),
                       'atlas_minimum_radius_labels':[c['label'] for c in atlas if F(c['closed_Hausdorff_radius'])==h],
                       'atlas_labeled_instances':sum(c['orbit_size'] for c in atlas)})
    (ROOT/'verification/primary_report.json').write_text(json.dumps(report,indent=2)+'\n');print(json.dumps(report,indent=2))
if __name__=='__main__':main()