File size: 8,730 Bytes
1c1abed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations
import json
from itertools import combinations
import numpy as np
import pytest
from axiomesh.core import *
from axiomesh.esre_v01 import rank_mod, solve_affine


def chain(d, p=101):
    a, b = np.eye(d, dtype=np.int64), np.eye(d, dtype=np.int64)
    for j in range(d-1):
        (a if j % 2 == 0 else b)[j,j+1] = 1
    return np.eye(d, dtype=np.int64)[:1], {'a':a,'b':b}


@pytest.mark.parametrize('d', [2,3,4,7,12])
def test_closure_exact_and_frozen(d):
    p=101; q, ops=chain(d); c=close_operators(q,ops,p)
    assert c.rank==d
    assert c.row_operator_products==2*d
    assert c.depth==d-1
    x=np.arange(d, dtype=np.int64)**2 % p
    f=c.compile(c.basis @ x % p)
    for word in [(),('a',),('a','b'),('b','a','a','b')]:
        assert np.array_equal(f.run(word),q @ word_matrix(word,ops,p) @ x % p)
    for row,w in zip(c.basis,c.witnesses):
        assert np.array_equal(row,q[w.query] @ word_matrix(w.word,ops,p)%p)


@pytest.mark.parametrize('seed', range(10))
def test_random_closure(seed):
    rng=np.random.default_rng(seed); p=7; d=5
    q=rng.integers(p,size=(2,d)); ops={a:rng.integers(p,size=(d,d)) for a in ['a','b']}
    c=close_operators(q,ops,p); x=rng.integers(p,size=d); f=c.compile(c.basis@x%p)
    assert rank_mod(c.basis,p)==c.rank
    for t in ops.values():
        assert rank_mod(np.vstack([c.basis,c.basis@t%p]),p)==c.rank
    for _ in range(10):
        word=tuple(rng.choice(['a','b'],size=8))
        assert np.array_equal(f.run(word),q @ word_matrix(word,ops,p) @ x % p)


def test_static_recovery_is_not_future_recovery():
    q,ops=chain(3); m=Memory(np.eye(3,dtype=np.int64)[:2],np.array([3,4]),101)
    assert m.recall(q)[0]=='exact'
    c=close_operators(q,ops,101)
    cert=hole_certificate(c,m)
    assert cert['status']=='ambiguous' and len(cert['word'])==2
    v=np.array(cert['null_vector']); assert not np.any(m.matrix@v%101)
    assert int(q[0]@word_matrix(cert['word'],ops,101)@v)%101!=0
    assert weave(q,ops,m).status=='ambiguous'


def test_acquisition_lower_bound_and_transaction():
    p=101; q,ops=chain(8); x=np.arange(8,dtype=np.int64)
    m=Memory(q,q@x%p,p)
    calls=[]
    def oracle(row):
        calls.append(row)
        return int(row@x)%p
    with pytest.raises(RuntimeError):
        weave(q,ops,m,oracle=oracle,observation_budget=6)
    assert len(calls)==0
    result=weave(q,ops,m,oracle=oracle,observation_budget=7,erasure_budget=3)
    assert result.status=='committed' and result.acquisitions==7 and len(calls)==7
    assert len(result.capsule.shares)==11


@pytest.mark.parametrize('seed',range(5))
def test_all_erasures_within_radius(seed):
    p=17; y=np.random.default_rng(seed).integers(p,size=4)
    capsule=Capsule.encode(y,p,3)
    for removed in combinations(capsule.shares,3):
        status,out=capsule.erase(removed).recover()
        assert status=='exact' and np.array_equal(y,out)
    assert capsule.erase(list(capsule.shares)[:4]).recover()[0]=='ambiguous'


def test_one_corruption_bounded_distance():
    y=np.array([2,3,4]); c=Capsule.encode(y,17,2)
    for i in c.shares:
        bad=Capsule(c.p,c.rank,dict(c.shares));bad.shares[i]=(bad.shares[i]+1)%17
        assert bad.recover()[0]=='inconsistent'
        status,out=bad.correct(1)
        assert status=='exact_within_declared_radius' and np.array_equal(y,out)


def test_insufficient_error_radius():
    assert Capsule.encode(np.array([1,2]),17,1).correct(1)[0]=='uncertified_radius'


def test_inconsistent_memory_rejected():
    m=Memory(np.array([[1,0],[1,0]]),np.array([2,3]),7)
    assert m.recall(np.array([[1,0]]))[0]=='inconsistent'
    with pytest.raises(ValueError):
        m.acquire(np.eye(2,dtype=np.int64),lambda r:0,observation_budget=2)


def test_chart_overlap_and_transport():
    p=11; c1=np.array([[1,1,0],[0,1,0]]);c2=np.array([[0,1,1],[0,0,1]])
    shared,a,b=overlap(c1,c2,p)
    assert len(shared)==1
    assert np.array_equal(a@c1%p,b@c2%p)
    assert np.array_equal(shared,a@c1%p)


def test_emergence_requires_mixed_words():
    q,ops=chain(12)
    e=emergence_rank(q,[{'a':ops['a']},{'b':ops['b']}],101)
    assert e['isolated_ranks']==[2,1]
    assert e['isolated_union_rank']==2 and e['emergence_rank']==10


def test_partial_execution():
    p=7; m=Memory(np.array([[1,0]]),np.array([3]),p)
    ops={'reset':np.zeros((2,2),dtype=np.int64),'swap':np.array([[0,1],[1,0]])}
    q=np.array([[1,0]])
    assert execute_partial(m,ops,q,())['output']==[3]
    assert execute_partial(m,ops,q,('swap',))['status']=='ambiguous'
    assert execute_partial(m,ops,q,('reset','swap'))['output']==[0]


def test_json_roundtrip_and_no_source_state():
    p=101;q,ops=chain(4);x=np.arange(4,dtype=np.int64)
    c=close_operators(q,ops,p);f=c.compile(c.basis@x%p)
    capsule=Capsule.encode(f.seed,p,2).erase([1,2])
    obj={'program':f.json_object(include_seed=False),'memory':capsule.json_object()}
    assert 'seed' not in obj['program']
    out=json.loads(json.dumps(obj)); status,y=Capsule.from_json(out['memory']).recover()
    g=FrozenModel.from_json(out['program'],seed=y)
    assert status=='exact' and np.array_equal(f.run(('a','b')),g.run(('a','b')))


def test_empty_actions():
    q=np.eye(4,dtype=np.int64)[:2]; c=close_operators(q,{},7)
    assert c.rank==2 and c.row_operator_products==0


def test_zero_observable():
    q=np.zeros((1,3),dtype=np.int64);m=Memory(np.zeros((0,3),dtype=np.int64),np.array([],dtype=np.int64),7)
    assert weave(q,{'a':np.eye(3,dtype=np.int64)},m).status=='zero_observable'


def test_product_budget():
    q,ops=chain(4)
    with pytest.raises(RuntimeError):close_operators(q,ops,101,product_budget=2)


@pytest.mark.parametrize('badp',[0,1,4,100])
def test_invalid_prime(badp):
    with pytest.raises(ValueError):close_operators(np.eye(2,dtype=np.int64),{},badp)


def test_shape_errors_and_singular():
    with pytest.raises(ValueError):inverse(np.zeros((2,2),dtype=np.int64),7)
    with pytest.raises(ValueError):close_operators(np.eye(2,dtype=np.int64),{'a':np.zeros((1,2),dtype=np.int64)},7)
    with pytest.raises(ValueError):coordinates(np.array([[0,1]]),np.array([[1,0]]),7)
    with pytest.raises(ValueError):Memory(np.eye(2,dtype=np.int64),np.array([1]),7)
    with pytest.raises(ValueError):Capsule.encode(np.ones(5,dtype=np.int64),5)


def test_budget():
    b=Budget(10);b.charge('closure',4);b.charge('memory',3)
    assert b.remaining==3
    with pytest.raises(RuntimeError):b.charge('too much',4)
    with pytest.raises(RuntimeError):b.charge('negative',-1)


def test_affine_embedding_matches_group():
    from axiomesh.esre_v01 import CentralExtension
    p=17;w=np.array([[0,3],[-3,0]])%p;group=CentralExtension(w,p)
    q,ops=affine_extension_operators(w,p);x=np.array([4,5]);z=7;h=np.r_[x,z,1]
    word=('+0','+1','-0','-1')
    actions=[]
    for action in word:
        u=np.zeros(2,dtype=np.int64);u[int(action[1:])]=1 if action[0]=='+' else -1
        actions.append((u,0))
    state=(x,z)
    for action in actions:state=group.multiply(state,action)
    assert int((q@word_matrix(word,ops,p)@h%p)[0])==state[1]


@pytest.mark.parametrize('d',[3,5,8,12])
def test_minimal_fractal_tether(d):
    p=101;q,ops=chain(d);x=np.arange(d,dtype=np.int64)**3%p
    parent=Memory(np.eye(d,dtype=np.int64),x,p)
    split=split_with_tether(q,ops,parent,[['a'],['b']])
    assert split.tether_symbols==d-2
    assert split.parent_rank==d and split.child_union_rank==2
    restored=FractalSplit.from_json(json.loads(json.dumps(split.json_object()))).reunify()
    assert restored.status=='committed'
    for word in [(),('a','b','a','b'),('b','a')]:
        assert np.array_equal(restored.offspring.run(word),q@word_matrix(word,ops,p)@x%p)
    if d>2:
        pieces=split.children
        child_mem=Memory(np.vstack([m.matrix for m in pieces]),np.concatenate([m.rhs for m in pieces]),p)
        assert weave(q,ops,child_mem).status=='ambiguous'


def test_split_rejects_missing_cover_or_unidentified_parent():
    q,ops=chain(3);m=Memory(q,np.array([2]),101)
    with pytest.raises(ValueError):split_with_tether(q,ops,m,[['a']])
    with pytest.raises(ValueError):split_with_tether(q,ops,m,[['a'],['b']])


@pytest.mark.parametrize('depth',[0,1,2,3])
def test_recursive_fracture(depth):
    p=101;d=7;q=np.eye(d,dtype=np.int64)[:1];ops={}
    for j in range(d-1):
        t=np.eye(d,dtype=np.int64);t[j,j+1]=1;ops[f't{j}']=t
    x=np.arange(d,dtype=np.int64)**2%p
    tree=fractalize(q,ops,Memory(np.eye(d,dtype=np.int64),x,p),max_depth=depth)
    tree=json.loads(json.dumps(tree))
    result=regenerate_tree(tree)
    assert result.status=='committed'
    word=tuple(reversed(list(ops)))
    assert np.array_equal(result.offspring.run(word),q@word_matrix(word,ops,p)@x%p)