File size: 11,129 Bytes
639016c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import unittest, itertools, math
from fractions import Fraction as F
import numpy as np
from scipy.special import logsumexp
from infinite_players.temporal import lag_moments, reaction_interval
from infinite_players.evidence_tree import EvidenceTree, paired_emission_factors, forward_log_likelihoods
from infinite_players.memory_contract import confusability_graph, exact_coloring, retrospective_memory_lower_bits
from infinite_players.fidelity import solve_fiber, policy_iteration, project_improvement, semantic_law, signature_residual
from infinite_players.arena import make_arena,calibration_fixture
from infinite_players.promotion import budget,audit_gain

class TemporalTests(unittest.TestCase):
    def test_aligned_variance(self):self.assertAlmostEqual(lag_moments(80,0,.45,.72)[1],80*(1-.45**2))
    def test_lag_one_independent(self):self.assertAlmostEqual(lag_moments(80,1,.45,.72)[1],80*(1-(.45*.72)**2))
    def test_zero_persistence(self):self.assertEqual(lag_moments(20,3,.6,0), (0.,20.,1.))
    def test_no_signal(self):self.assertEqual(lag_moments(20,4,0,.8),(0.,20.,1.))
    def test_deterministic_gate(self):self.assertAlmostEqual(lag_moments(20,4,.5,1)[1],15.)
    def test_invalid_parameters(self):
        for args in ((0,1,.2,.3),(2,-1,.2,.3),(2,1,2,.3)):
            with self.assertRaises(ValueError):lag_moments(*args)
    def test_clock_gauge(self):
        self.assertAlmostEqual(.12+.03,.09+.06)
        self.assertTrue(np.allclose(reaction_interval(.15,.02,.04),(.11,.13)))
    def test_impossible_clock(self):
        with self.assertRaises(ValueError):reaction_interval(.01,.02,.03)

class TreeTests(unittest.TestCase):
    def setUp(self):
        self.rng=np.random.default_rng(12)
        self.f=self.rng.uniform(.01,.8,(13,4,2,2));self.ids=[f"e{i}" for i in range(13)]
        self.tree=EvidenceTree(self.f,self.ids,model_id="fixed")
    def test_forward_equivalence(self):
        self.assertTrue(np.allclose(self.tree.log_likelihoods([.3,.7]),forward_log_likelihoods(self.f,[.3,.7]),atol=1e-12))
    def test_boundary_equivalence(self):
        terminal=np.array([.1,.9]);init=[.8,.2]
        self.assertTrue(np.allclose(self.tree.log_likelihoods(init,terminal),forward_log_likelihoods(self.f,init,terminal)))
    def test_local_replacement(self):
        fnew=self.f.copy();fnew[7]*=.3
        self.tree.replace("e7",fnew[7],model_id="fixed",revision_id="r1")
        self.assertEqual(self.tree.last_update_compositions,4)
        self.assertTrue(np.allclose(self.tree.log_likelihoods([.5,.5]),forward_log_likelihoods(fnew,[.5,.5])))
    def test_replacement_not_double_count(self):
        old=self.tree.posterior([.5,.5])
        self.tree.replace("e7",self.f[7],model_id="fixed",revision_id="identity")
        np.testing.assert_allclose(old,self.tree.posterior([.5,.5]),atol=1e-14)
    def test_duplicate_id(self):
        with self.assertRaises(ValueError):EvidenceTree(self.f,["x"]*13,model_id="m")
    def test_invalid_replace_atomic(self):
        old=self.tree.posterior([.5,.5]).copy()
        with self.assertRaises(ValueError):self.tree.replace("e1",-self.f[1],model_id="fixed",revision_id="bad")
        np.testing.assert_array_equal(old,self.tree.posterior([.5,.5]));self.assertEqual(len(self.tree.revisions),0)
    def test_generated_evidence_rejected(self):
        with self.assertRaises(ValueError):self.tree.replace("e1",self.f[1],model_id="fixed",revision_id="bad",source_kind="imagined_rollout")
    def test_catalog_change_rejected(self):
        with self.assertRaises(ValueError):self.tree.replace("e1",self.f[1],model_id="new",revision_id="bad")
    def test_duplicate_revision(self):
        self.tree.replace("e1",self.f[1],model_id="fixed",revision_id="r")
        with self.assertRaises(ValueError):self.tree.replace("e2",self.f[2],model_id="fixed",revision_id="r")
    def test_all_impossible(self):
        with self.assertRaises(ValueError):self.tree.posterior([.5,.5],probe=np.zeros(4))
    def test_rare_probe(self):
        p=self.tree.posterior([.5,.5],probe=np.array([1e-250,2e-250,0,0]))
        q=self.tree.posterior([.5,.5],probe=np.array([1,2,0,0]))
        np.testing.assert_allclose(p,q,atol=1e-12)
    def test_long_underflow_control(self):
        f=np.broadcast_to(np.eye(2)*.01,(1024,2,2,2)).copy()
        t=EvidenceTree(f,[str(i) for i in range(1024)],model_id="small")
        np.testing.assert_allclose(t.posterior([.5,.5]),[.5,.5]);self.assertTrue(np.all(np.isfinite(t.log_likelihoods([.5,.5]))))
    def test_scalar_root_not_sufficient(self):
        a=np.array([[[[1.,0],[0,0]]]]);b=np.array([[[[0.,1],[0,0]]]])
        x=EvidenceTree(a,["x"],model_id="m");y=EvidenceTree(b,["x"],model_id="m")
        np.testing.assert_array_equal(x.log_likelihoods([1,0]),y.log_likelihoods([1,0]))
        self.assertNotEqual(x.log_likelihoods([1,0],[1,0])[0],y.log_likelihoods([1,0],[1,0])[0])
    def test_world_symmetry(self):
        hyp=list(itertools.product([-1,1],repeat=2))
        factors=paired_emission_factors([1,1,-1],[1,1,-1],hyp)
        t=EvidenceTree(factors,["a","b","c"],model_id="m")
        p=t.posterior([.5,.5]);self.assertAlmostEqual(p[:2].sum(),.5)
        post=t.posterior([.5,.5],probe=[0,1,0,1]);self.assertGreater(post[3],.5)

class MemoryTests(unittest.TestCase):
    def test_one_bit_full_record_memory(self):
        rows=list(itertools.product([0,1],repeat=4));g=confusability_graph(rows)
        k,c=exact_coloring(g);self.assertEqual(k,16)
    def test_future_query_subset(self):
        rows=np.array(list(itertools.product([0,1],repeat=3)))
        k,_=exact_coloring(confusability_graph(rows[:,:1]));self.assertEqual(k,2)
    def test_support_changes_graph(self):
        g=confusability_graph([[0,1],[1,0]],[[1,0],[0,1]])
        self.assertFalse(g[0,1]);self.assertEqual(exact_coloring(g)[0],1)
    def test_odd_cycle_coloring(self):
        g=np.zeros((5,5),bool)
        for i in range(5):g[i,(i+1)%5]=g[(i+1)%5,i]=True
        self.assertEqual(exact_coloring(g)[0],3)
    def test_lossy_bound_endpoints(self):
        self.assertEqual(retrospective_memory_lower_bits(128,0),128)
        self.assertEqual(retrospective_memory_lower_bits(128,.5),0)
        self.assertGreater(retrospective_memory_lower_bits(128,.01),117)
    def test_invalid_graph(self):
        with self.assertRaises(ValueError):exact_coloring([[1]])

class FidelityTests(unittest.TestCase):
    def setUp(self):self.mdp,self.anchor,self.k=make_arena(81)
    def test_anchor_feasible(self):self.assertLess(signature_residual(self.mdp,self.anchor,self.k),1e-12)
    def test_lp_optimum_dominates_anchor(self):
        pi,v,a=policy_iteration(self.mdp,self.k)
        self.assertGreaterEqual(np.min(v-self.mdp.evaluate(self.anchor)[0]),-1e-10)
        self.assertLess(signature_residual(self.mdp,pi,self.k),1e-10)
    def test_whole_semantic_law(self):
        pi,_,_=policy_iteration(self.mdp,self.k)
        for horizon in range(1,6):np.testing.assert_allclose(semantic_law(self.mdp,pi,horizon),semantic_law(self.mdp,self.anchor,horizon),atol=1e-12)
    def test_class_only_does_not_protect_path(self):
        pi,_,_=policy_iteration(self.mdp,self.k,"class")
        law=semantic_law(self.mdp,pi,5);ref=semantic_law(self.mdp,self.anchor,5)
        self.assertGreater(np.abs(law-ref).sum()/2,.1)
    def test_projection_monotonic(self):
        pi,h=project_improvement(self.mdp,self.anchor,self.k,steps=12)
        self.assertTrue(all(x['minimum_value_gain']>=-1e-9 for x in h))
        self.assertLess(signature_residual(self.mdp,pi,self.k),1e-9)
    def test_projection_identity(self):
        _,q=self.mdp.evaluate(self.anchor)
        for s in range(self.mdp.S):
            D=self.mdp.signature(s);d=(np.eye(self.mdp.A)-np.linalg.pinv(D)@D)@q[s]
            np.testing.assert_allclose(D@d,0,atol=1e-12)
            self.assertAlmostEqual(float(q[s]@d),float(d@d),places=10)
    def test_zero_headroom(self):
        mdp,a,k=make_arena(82,no_headroom=True);pi,v,_=policy_iteration(mdp,k)
        np.testing.assert_allclose(v,mdp.evaluate(a)[0],atol=1e-11)
    def test_calibration_opens_fiber(self):
        d0,d1,k,r=calibration_fixture()
        robust,_=solve_fiber(r,np.vstack([d0,d1]),np.tile(k,2))
        calibrated,_=solve_fiber(r,d0,k)
        np.testing.assert_allclose(robust,[1,0,0]);np.testing.assert_allclose(calibrated,[0,.5,.5])
        self.assertAlmostEqual(r@calibrated,.85)
    def test_other_world_no_unlock(self):
        d0,d1,k,r=calibration_fixture();p,_=solve_fiber(r,d1,k);self.assertAlmostEqual(r@p,.4)
    def test_lp_dual(self):
        pi,v,a=policy_iteration(self.mdp,self.k)
        self.assertTrue(all(x['primal_residual']<1e-9 and x['dual_violation']<1e-9 and abs(x['duality_gap'])<1e-9 for x in a['lp_audits']))
    def test_impossible_target(self):
        with self.assertRaises(ValueError):solve_fiber([1,2],[[1,1],[0,0]],[1,.2])
    def test_law_probability(self):self.assertAlmostEqual(semantic_law(self.mdp,self.anchor,5).sum(),1.)

class PromotionTests(unittest.TestCase):
    def test_lifetime_budget(self):self.assertAlmostEqual(sum(budget(.05,j) for j in range(1,1000)),.05*(1-1/1000))
    def test_zero_not_promoted(self):self.assertFalse(audit_gain(np.zeros(100),version=1)['promoted'])
    def test_positive_promoted(self):self.assertTrue(audit_gain(np.ones(100),version=1)['promoted'])
    def test_bad_samples(self):
        with self.assertRaises(ValueError):audit_gain([2],version=1)
    def test_invalid_version(self):
        with self.assertRaises(ValueError):budget(.05,0)


class IntegrationTests(unittest.TestCase):
    def test_environment_authorization(self):
        from infinite_players.arena import ArenaEnvironment
        env=ArenaEnvironment(make_arena(2)[0]);self.assertEqual(env.reset()['tick'],0)
        with self.assertRaises(ValueError):env.step(99)
    def test_environment_step(self):
        from infinite_players.arena import ArenaEnvironment
        env=ArenaEnvironment(make_arena(3)[0]);obs,r,d,i=env.step(1);self.assertEqual(obs['tick'],1);self.assertIn(r,(0.,1.))
    def test_fixture_decoder_rejects_synthetic_as_human(self):
        from infinite_players.demo import decode_fixture_record
        with self.assertRaises(ValueError):decode_fixture_record([{'event_id':'a','source_kind':'human_record','tick':1,'action_signal':1,'context_signal':1}])
    def test_record_order(self):
        from infinite_players.demo import decode_fixture_record
        e=[{'event_id':str(i),'source_kind':'synthetic_fixture','tick':0,'action_signal':1,'context_signal':1} for i in range(2)]
        with self.assertRaises(ValueError):decode_fixture_record(e)
    def test_pipeline(self):
        import tempfile
        from pathlib import Path
        from infinite_players.demo import run
        with tempfile.TemporaryDirectory() as d:
            c=run(Path(d),steps=5)
            self.assertLess(c['evaluation']['path_TV_h6'],1e-10)
            self.assertGreaterEqual(c['evaluation']['normalized_descendant_value'],c['evaluation']['normalized_anchor_value']-1e-10)
            self.assertEqual(c['source_events'],32)

if __name__=='__main__':unittest.main()