File size: 13,553 Bytes
19591f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Independent exact-arithmetic checks of constructions and finite certificates.

Run: python verify.py
These tests validate code and finite instances; they are not a proof assistant
formalization of the universal theorems in the manuscript.
"""
from fractions import Fraction as F
from itertools import product
from pathlib import Path
from collections import Counter
import json
import random
import subprocess
import sys
import tempfile
import time

import selection

HERE = Path(__file__).resolve().parent
COUNTS = Counter()
RNG = random.Random(61492026)


def sq_distance(a,b):
    return sum((F(x)-F(y))**2 for x,y in zip(a,b))


def reference_moments(points,weights=None):
    p = [F(1,len(points))]*len(points) if weights is None else list(map(F,weights))
    mu = [sum(w*F(x[j]) for x,w in zip(points,p)) for j in range(len(points[0]))]
    # Pairwise-distance identity is independent of the selector's central-moment code.
    var = sum(p[i]*p[j]*sq_distance(points[i],points[j])
              for i in range(len(points)) for j in range(i))/1
    return mu,var


def count_error(points,weights,counts,n):
    assert all(isinstance(i,int) and 0 <= i < len(points) for i in counts)
    assert all(isinstance(v,int) and not isinstance(v,bool) and v > 0 for v in counts.values())
    assert sum(counts.values()) == n
    mu,var = reference_moments(points,weights)
    selected = [sum(v*F(points[i][j]) for i,v in counts.items())/n
                for j in range(len(mu))]
    return sq_distance(mu,selected),mu,var,selected


def reference_coefficient(rank,n):
    if rank == 0:
        return F(0)
    if n == 1:
        return F(1)
    if rank <= 2:
        return F(1,2*n-1)
    a = max(F(1,3),F(rank-1,2*rank))
    if n <= rank:
        return (F(n-2)+4*a)/(n*n)
    b = (F(rank-2)+4*a)/(rank*rank)
    return rank*b/(n*(1+b)-rank*b)


def check_output(points,n):
    out = selection.select((row for row in points),n)
    error,mu,var,h = count_error(points,None,out['counts'],n)
    assert [F(x) for x in out['mean']] == mu
    assert [F(x) for x in out['selected_mean']] == h
    assert F(out['variance']) == var
    assert F(out['squared_mean_error']) == error
    rank = out['resident_affine_rank']
    assert error <= reference_coefficient(rank,n)*var
    assert F(out['guaranteed_upper_coefficient']) == reference_coefficient(rank,n)
    assert F(out['full_data_loss_ratio']) == (1+error/var if var else 1)
    indices = out['compressed_indices']
    compressed = [[F(v) for v in row] for row in out['compressed_points']]
    weights = [F(v) for v in out['compressed_weights']]
    assert all(w>0 for w in weights) and sum(weights)==1
    assert compressed == [list(map(F,points[i])) for i in indices]
    cm,cv = reference_moments(compressed,weights)
    assert cm == mu and cv <= var
    assert cv == F(out['compressed_variance'])
    assert len(compressed) <= len(points[0])+1
    # The chosen output is at least as good as either computed certificate.
    assert error <= F(out['residual_rounding_bound'])
    COUNTS['full_dataset_outputs'] += 1
    COUNTS['selected_method_'+out['selected_method']] += 1
    for entry in out['construction_trace']:
        COUNTS['trace_'+entry['step']] += 1
    return out


def independent_rule_optimum(points,n,weights,rules):
    m=len(points)
    lower=rules.get('lower',[0]*m)
    upper=rules.get('upper',[n]*m)
    best=None
    feasible=0
    states=0
    # Cartesian tuples, unlike the implementation's recursive compositions.
    for counts in product(range(n+1),repeat=m):
        if sum(counts)!=n:
            continue
        states+=1
        if any(c<lo or c>hi for c,lo,hi in zip(counts,lower,upper)):
            continue
        ok=True
        for row in rules.get('linear',[]):
            lhs=sum(F(str(a))*c for a,c in zip(row['a'],counts))
            rhs=F(str(row['rhs']))
            if not {'<=':lhs<=rhs,'>=':lhs>=rhs,'==':lhs==rhs}[row['sense']]:
                ok=False
                break
        if not ok:
            continue
        feasible+=1
        e,*_=count_error(points,weights,{i:c for i,c in enumerate(counts) if c},n)
        if best is None or (e,counts)<best:
            best=(e,counts)
    return best,feasible,states


def main():
    started=time.monotonic()
    for rank in range(13):
        for n in range(1,81):
            c=selection.coefficient(rank,n)
            assert c==reference_coefficient(rank,n) and 0<=c<=F(1,n)
            if rank>=3 and n>rank:
                prev=selection.coefficient(rank,n-1)
                assert c==F(n-1)*prev/(n+prev)
            COUNTS['coefficient_identities']+=1

    for d in range(1,9):
        for case in range(3):
            points=[[F(RNG.randint(-9,9),RNG.randint(1,5)) for _ in range(d)]
                    for _ in range(d+5)]
            for n in sorted({1,2,3,d,d+1,d+4}):
                check_output(points,n)

    degenerate=[
        [[0]*8 for _ in range(7)],
        [[F(7,11),-2,3] for _ in range(4)],
        [[i,2*i+1,-3*i,4*i-2,0,1,2*i,7] for i in range(-3,4)],
        [[i,j,i+j,2*i-j,0,4,3*i,5*j] for i,j in [(0,0),(1,0),(0,1),(2,-1),(-3,2),(4,4)]],
        [[2**80+F(i,17),-2**75+F(i*i,29)] for i in range(7)],
    ]
    for points in degenerate:
        for n in (1,2,3,7,23):
            check_output(points,n)
            COUNTS['degenerate_or_large_exact_inputs']+=1

    # A deliberately hard residual case must use the direct fallback.
    fallback=[[F(0),F(0)] for _ in range(18)]+[[F(1,10),F(1)],[F(1,10),F(-1)]]
    result=check_output(fallback,10)
    assert result['selected_method']=='pair-padding-peeling'
    assert F(result['squared_mean_error'])==F(1,10000)
    COUNTS['forced_direct_fallback_cases']+=1

    # A billion requested copies must stay compact and avoid proportional loops.
    result=check_output([[0,0],[1,0],[0,1]],10**9)
    assert result['selected_method']=='floor-residual-atomic-selection'
    assert len(result['counts'])<=3 and sum(result['counts'].values())==10**9
    COUNTS['billion_budget_compact_fastpath_cases']+=1

    for m in range(2,10):
        for case in range(6):
            d=min(6,m)
            points=[[F(RNG.randint(-7,7),RNG.randint(1,4)) for _ in range(d)] for _ in range(m)]
            raw=[RNG.randint(1,17) for _ in range(m)]
            if case==0:
                raw[0]=10**8
            if case==1:
                raw[-1]=0
            weights=[F(v,sum(raw)) for v in raw]
            active=sum(w>0 for w in weights)
            for n in sorted({1,2,max(3,active-1),active+2}):
                counts,trace=selection.select_atomic(points,weights,n)
                error,_,var,_=count_error(points,weights,counts,n)
                assert error<=reference_coefficient(active-1,n)*var
                COUNTS['weighted_atomic_outputs']+=1
                rcounts,bound=selection.residual_candidate(points,weights,n)
                re,_,_,_=count_error(points,weights,rcounts,n)
                assert re<=bound
                residual=[n*p-int(n*p) for p in weights]
                k=sum(residual)
                assert k.denominator==1 and 0<=k<=active-1
                if not k:
                    assert re==bound==0
                COUNTS['fractional_residual_certificates']+=1

    rational_points=[[F(0),F(0)],[F(1,3),F(2,7)],[F(-5,11),F(3,2)]]
    rational_weights=[F(1,6),F(1,3),F(1,2)]
    for n in (6,12,24,60,126):
        counts,bound=selection.residual_candidate(rational_points,rational_weights,n)
        error,*_=count_error(rational_points,rational_weights,counts,n)
        assert error==bound==0
        COUNTS['exact_denominator_budgets']+=1

    for n in range(1,31):
        points=[[0],[1]]
        weights=[1-F(1,2*n),F(1,2*n)]
        counts,_=selection.select_atomic(points,weights,n)
        error,_,var,_=count_error(points,weights,counts,n)
        assert error/var==F(1,2*n-1)
        COUNTS['finite_line_sharpness_budgets']+=1

    for case in range(32):
        m=2+case%4
        n=1+case%5
        points=[[F(RNG.randint(-4,4),RNG.randint(1,3)) for _ in range(1+case%3)] for _ in range(m)]
        raw=[RNG.randint(1,8) for _ in range(m)]
        weights=[F(a,sum(raw)) for a in raw]
        mode=case%8
        if mode==0:
            rules={}
        elif mode==1:
            rules={'upper':[1]*m}
        elif mode==2:
            rules={'lower':[1]+[0]*(m-1)}
        elif mode==3:
            rules={'linear':[{'a':[i%2 for i in range(m)],'sense':'==','rhs':n//2}]}
        elif mode==4:
            rules={'linear':[{'a':[i+1 for i in range(m)],'sense':'<=','rhs':n+2}]}
        elif mode==5:
            rules={'linear':[{'a':['1/2']+[0]*(m-1),'sense':'>=','rhs':'1/2'}],
                   'upper':[2]*m}
        elif mode==6:
            rules={'lower':[n+1]+[0]*(m-1)}
        else:
            rules={'upper':[n]*(m-1)+[0],
                   'linear':[{'a':[i-2 for i in range(m)],'sense':'>=','rhs':-n}]}
        actual=selection.exact_rule_selection(points,n,weights,rules)
        best,feasible,states=independent_rule_optimum(points,n,weights,rules)
        assert actual['enumerated_states']==states and actual['feasible_states']==feasible
        if best is None:
            assert actual['status']=='INFEASIBLE'
            COUNTS['infeasible_rule_instances']+=1
        else:
            counts=tuple(actual['counts'].get(i,0) for i in range(m))
            assert actual['status']=='OPTIMAL'
            assert (F(actual['squared_mean_error']),counts)==best
            COUNTS['optimal_rule_instances']+=1
        COUNTS['independent_rule_comparisons']+=1

    # Exact rational Gram witness: a^2=5, b^2=9, tetrahedral inner products -1/3.
    p=[F(2,5)]+[F(3,20)]*4
    gram=[[F(0)]*5 for _ in range(5)]
    for i in range(1,5):
        for j in range(1,5):
            gram[i][j]=F(14 if i==j else 2)
    mean_norm=sum(p[i]*p[j]*gram[i][j] for i in range(5) for j in range(5))
    variance=sum(p[i]*gram[i][i] for i in range(5))-mean_norm
    values=[]
    for counts in product(range(4),repeat=5):
        if sum(counts)!=3:
            continue
        delta=[F(c,3)-w for c,w in zip(counts,p)]
        error=sum(delta[i]*delta[j]*gram[i][j] for i in range(5) for j in range(5))
        values.append(error)
    assert variance==F(33,5) and min(values)==F(61,45)
    assert min(values)/variance==F(61,297)>F(1,5)
    COUNTS['exact_rare_simplex_gram_witnesses']+=1

    tetra=[[0,0,0,0],[4,3,3,3],[4,3,-3,-3],[4,-3,3,-3],[4,-3,-3,3]]
    best,_,_=independent_rule_optimum(tetra,3,p,{})
    assert best[0]==F(916,225)
    assert reference_moments(tetra,p)[1]==F(501,25)
    assert best[0]/F(501,25)==F(916,4509)>F(1,5)
    finite=tetra[:1]*8+sum(([row]*3 for row in tetra[1:]),[])
    check_output(finite,3)
    COUNTS['rational_coordinate_rare_simplex_witnesses']+=1

    # Exact polynomial check that B_(4,n) exceeds 1/(2n-1).
    for n in range(2,101):
        k=4
        a=2*n*(k-2)-(k-3)
        delta=(k-3)*(2*n*(n-2)*(k-2)+(k-3))
        c=F(1,2*n-1)
        assert c<F(a,k*n*n)
        assert (k*n*n*c)**2-2*a*k*n*n*c+a*a-delta>0
        COUNTS['dimension_four_strict_separation_checks']+=1

    with tempfile.TemporaryDirectory() as directory:
        inp=Path(directory)/'input.json'
        inp.write_text('{"points":[[0.1000000000000000000000001,0.2],[0.3,-0.4],[0.5,0.6]],"n":7}')
        completed=subprocess.run([sys.executable,str(HERE/'selection.py'),str(inp)],
                                 check=True,text=True,capture_output=True)
        out=json.loads(completed.stdout)
        assert F(out['mean'][0])==F('0.9000000000000000000000001')/3
        COUNTS['exact_decimal_cli_checks']+=1
        inp.write_text('{"points":[[0],[1],[2]],"weights":["1/2","1/3","1/6"],"n":3,"rules":{"upper":[1,1,1]}}')
        completed=subprocess.run([sys.executable,str(HERE/'selection.py'),str(inp),'--exact'],
                                 check=True,text=True,capture_output=True)
        out=json.loads(completed.stdout)
        assert out['status']=='OPTIMAL' and out['counts']=={'0':1,'1':1,'2':1}
        COUNTS['weighted_constrained_cli_checks']+=1

    bad_calls=[
        lambda:selection.select([],2),
        lambda:selection.select([[1],[2,3]],2),
        lambda:selection.select([[0],[1]],True),
        lambda:selection.select([[0],[1]],0),
        lambda:selection.select_atomic([[0],[1]],[F(1,3),F(1,3)],2),
        lambda:selection.select_atomic([[0],[1]],[F(-1),F(2)],2),
        lambda:selection.exact_rule_selection([[0],[1]],3,rules={'linear':[{'a':[1,2],'sense':'!=','rhs':0}]}),
        lambda:selection.exact_rule_selection([[0],[1],[2]],20,max_states=5),
    ]
    for call in bad_calls:
        try:
            call()
        except ValueError:
            COUNTS['invalid_input_rejections']+=1
        else:
            raise AssertionError('Invalid input was accepted')

    result={'status':'PASS','arithmetic':'fractions.Fraction; exact comparisons',
            'seed':61492026,'counts':dict(sorted(COUNTS.items())),
            'wall_seconds':round(time.monotonic()-started,3),
            'independence':'Original-data variance uses pairwise distances; rule oracle uses Cartesian count tuples; rare-simplex certificate uses a rational Gram matrix.',
            'scope':'Implementation and finite certificates only; universal claims rely on the manuscript proofs. No claim of proof-assistant formalization.'}
    (HERE/'verification_results.json').write_text(json.dumps(result,indent=2)+'\n')
    print(json.dumps(result,indent=2))


if __name__=='__main__':
    main()