File size: 7,553 Bytes
e3bdcca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Finite checks for coherent sparse-repair refusal. Synthetic, not hardware."""
from itertools import product, combinations
from fractions import Fraction
from math import comb, gcd
import json
from pathlib import Path
import numpy as np


def vectors(p,n):
    return np.array(list(product(range(p),repeat=n)),dtype=int)


def rank_mod(A,p):
    A=np.array(A,dtype=int).copy()%p
    m,n=A.shape
    row=0
    for j in range(n):
        pivot=next((i for i in range(row,m) if A[i,j]),None)
        if pivot is None: continue
        A[[row,pivot]]=A[[pivot,row]]
        A[row]=(A[row]*pow(int(A[row,j]),-1,p))%p
        for i in range(m):
            if i!=row and A[i,j]: A[i]=(A[i]-A[i,j]*A[row])%p
        row+=1
        if row==m: break
    return row


def rank_q(A):
    A=[[Fraction(int(x)) for x in row] for row in A]
    m=len(A); n=len(A[0]) if m else 0; row=0
    for j in range(n):
        pivot=next((i for i in range(row,m) if A[i][j]),None)
        if pivot is None: continue
        A[row],A[pivot]=A[pivot],A[row]
        den=A[row][j]
        A[row]=[x/den for x in A[row]]
        for i in range(row+1,m):
            if A[i][j]:
                a=A[i][j]; A[i]=[x-a*y for x,y in zip(A[i],A[row])]
        row+=1
        if row==m: break
    return row


def rank_z(A):
    """Exact integer elimination, normalizing rows by their gcd."""
    A=[[int(x) for x in row] for row in A]
    m=len(A); n=len(A[0]) if m else 0; row=0
    for j in range(n):
        pivot=next((i for i in range(row,m) if A[i][j]),None)
        if pivot is None: continue
        A[row],A[pivot]=A[pivot],A[row]
        den=A[row][j]
        for i in range(row+1,m):
            if A[i][j]:
                z=A[i][j]
                A[i]=[den*x-z*y for x,y in zip(A[i],A[row])]
                g=0
                for x in A[i]: g=gcd(g,abs(x))
                if g>1: A[i]=[x//g for x in A[i]]
        row+=1
        if row==m: break
    return row


def repair_distance(B,s,p):
    for k in range(B.shape[1]+1):
        for S in combinations(range(B.shape[1]),k):
            C=B[:,S]
            if rank_mod(C,p)==rank_mod(np.column_stack([C,s]),p): return k
    return None


def run():
    out={}
    B=np.array([[1,0,1,0,0,0],[0,1,1,0,0,0],
                [0,0,0,1,0,1],[0,0,0,0,1,1]],dtype=int)
    G=vectors(2,4)
    legal=np.array(sorted({(0,0,0,0),*[tuple(B[:,j]) for j in range(6)]}),dtype=int)
    evals=(-1.)**(legal@G.T%2)
    counts={}
    for D in range(1,5):
        deficient=0
        total=0
        for inds in combinations(range(16),D):
            total+=1
            if rank_q(evals[:,inds])<D: deficient+=1
        counts[str(D)]={'total_alphabets':total,'nonzero_refusal_alphabets':deficient}
    out['exact_rational_alphabet_scan']=counts
    A=np.array([[0,0,0,0],[1,0,0,0],[0,0,1,0],[1,0,1,0]])
    mu=np.full(4,.25)
    c=np.array([1.,-1.,-1.,1.])
    v=c/2
    probs=[]
    for s in G:
        state=np.sqrt(mu)*((-1.)**(A@s%2))
        prob=abs(np.vdot(v,state))**2
        probs.append({'s':s.tolist(),'distance':repair_distance(B,s,2),'prob':prob})
    out['binary_block_dictionary']={'B':B.tolist(),'rank':rank_mod(B,2),'legal_count':len(legal),'probabilities':probs}
    rng=np.random.default_rng(20261024)
    mu=rng.dirichlet(np.ones(4))
    Z=np.sum(1/mu)
    v=(c/np.sqrt(mu))/np.sqrt(Z)
    maxerr=0
    for s in G:
        state=np.sqrt(mu)*((-1.)**(A@s%2))
        prob=abs(np.vdot(v,state))**2
        predicted=(abs(np.prod(1-(-1.)**(np.array([s[0],s[2]]))))**2)/Z
        maxerr=max(maxerr,abs(prob-predicted))
    out['nonuniform_cube']={'mu':mu.tolist(),'Z':float(Z),'success_on_1111':float(16/Z),'uniform_success':1.0,'formula_max_error':maxerr}
    # Every nonzero 2-bit covector in each block: exact average success 4/9.
    nonzero=[a for a in vectors(2,2) if np.any(a)]
    alt=[s for s in G if np.any(s[:2]) and np.any(s[2:])]
    rates=[]
    for s in alt:
        rates.append(sum(int((a@s[:2])%2)*int((b@s[2:])%2) for a in nonzero for b in nonzero)/9)
    out['random_block_queries']={'alternatives':len(alt),'min_success':min(rates),'max_success':max(rates),'exact_rate':'4/9'}
    # General p uniform cube formula and one-sided soundness.
    p=3;n=3;t=2
    A=np.array([[e[0],e[1],0] for e in product((0,1),repeat=t)])
    v=np.array([(-1.)**sum(e) for e in product((0,1),repeat=t)])/2
    maxerr=0; maxlegal=0
    for s in vectors(p,n):
        state=np.exp(2j*np.pi*(A@s%p)/p)/2
        prob=abs(np.vdot(v,state))**2
        pred=float(np.prod(np.sin(np.pi*s[:t]/p)**2))
        maxerr=max(maxerr,abs(prob-pred))
        if np.count_nonzero(s)<=t-1: maxlegal=max(maxlegal,prob)
    out['ternary_cube']={'max_formula_error':maxerr,'max_legal_refusal_roundoff':maxlegal,'alternative_success_when_both_selected_nonzero':9/16}
    # A target-dependent optimum based on a general signed witness is Cauchy exact.
    c=np.array([1+2j,-2+1j,0.5-1j,-1j])
    mu=np.abs(c)/np.sum(np.abs(c))
    out['l1_witness_amplitudes']={'cauchy_gap':float(np.sum(np.abs(c)**2/mu)-np.sum(np.abs(c))**2)}
    identity_scans={}
    chars=vectors(2,4)
    for k,max_D in [(1,3),(2,7)]:
        legal=chars[np.count_nonzero(chars,axis=1)<=k]
        full=(-1)**((legal@chars.T)%2)
        by_D={}
        for D in range(1,max_D+1):
            deficient=0
            for inds in combinations(range(16),D):
                deficient+=int(rank_z(full[:,inds])<D)
            by_D[str(D)]={'total':comb(16,D),'rank_deficient':deficient}
        cube=np.array([list(e)+[0]*(4-k-1) for e in product((0,1),repeat=k+1)])
        cube_matrix=(-1)**((legal@cube.T)%2)
        identity_scans[str(k)]={'n':4,'k':k,'alphabets':by_D,'threshold_cube_modes':len(cube),'threshold_cube_rank':rank_z(cube_matrix)}
    out['identity_sparse_ball_exact_scans']=identity_scans
    prime_checks=[]
    for p in [2,3,5,7]:
        n=3;t=2
        A=np.array([[e[0],e[1],0] for e in product((0,1),repeat=t)])
        c=np.array([(-1.)**sum(e) for e in product((0,1),repeat=t)])
        mu=rng.dirichlet(np.ones(4)); Z=np.sum(1/mu)
        v=(c/np.sqrt(mu))/np.sqrt(Z)
        maxerr=0;maxlegal=0;tested=0
        for s in vectors(p,n):
            state=np.sqrt(mu)*np.exp(2j*np.pi*(A@s%p)/p)
            prob=abs(np.vdot(v,state))**2
            pred=float(np.prod(4*np.sin(np.pi*s[:t]/p)**2))/Z
            maxerr=max(maxerr,abs(prob-pred));tested+=1
            if np.count_nonzero(s)<=1:maxlegal=max(maxlegal,prob)
        prime_checks.append({'p':p,'n':n,'tested_all_syndromes':tested,'formula_max_error':maxerr,'legal_refusal_max_roundoff':maxlegal})
    out['all_small_prime_syndromes']=prime_checks
    assert all(counts[str(D)]['nonzero_refusal_alphabets']==0 for D in [1,2,3])
    assert counts['4']['nonzero_refusal_alphabets']==36
    assert all(row['rank_deficient']==0 for scan in identity_scans.values() for row in scan['alphabets'].values())
    assert all(scan['threshold_cube_rank']==scan['threshold_cube_modes']-1 for scan in identity_scans.values())
    assert all(row['prob']==0 for row in probs if row['distance']<=1)
    assert max(abs(rate-4/9) for rate in rates)<1e-12
    assert out['nonuniform_cube']['formula_max_error']<1e-12
    assert all(row['formula_max_error']<1e-12 and row['legal_refusal_max_roundoff']<1e-12 for row in prime_checks)
    assert abs(out['l1_witness_amplitudes']['cauchy_gap'])<1e-12
    Path('research/refusal_test_results.json').write_text(json.dumps(out,indent=2))
    print(json.dumps({k:v for k,v in out.items() if k!='binary_block_dictionary'},indent=2))

if __name__=='__main__': run()