Datasets:
Modalities:
Text
Formats:
json
Languages:
English
Size:
< 1K
Tags:
mathematics
information-theory
renyi-entropy
shannon-entropy
hidden-markov-models
bernoulli-convolutions
Download tests/test_veloryn.py from PureOne/VELORYN-Boundary-Kernel-Entropy: direct link, hf CLI and curl.
- Browser
- Download file 11.7 kB
-
https://huggingface.co/datasets/PureOne/VELORYN-Boundary-Kernel-Entropy/resolve/main/tests/test_veloryn.py
- Command line
-
hf download hf://datasets/PureOne/VELORYN-Boundary-Kernel-Entropy/tests/test_veloryn.py
-
curl -L -o test_veloryn.py https://huggingface.co/datasets/PureOne/VELORYN-Boundary-Kernel-Entropy/resolve/main/tests/test_veloryn.py
11.7 kB
| import json | |
| import random | |
| import unittest | |
| from decimal import Decimal,localcontext | |
| from fractions import Fraction as Q | |
| from pathlib import Path | |
| from veloryn import Field,Source,collision_matrix,target_mass,ResourceLimit | |
| from veloryn.arithmetic import ReturnCone,Interval,sqrt_interval | |
| from veloryn.numerics import log_bounds,spectral_bounds,matmul | |
| from veloryn.entropy import renyi_interval,shannon_interval | |
| from veloryn.examples import fair,markov,periodic,mixture,variable,hidden | |
| from reference import distributions,moment_matrix,aggregate,paths | |
| COUNTS={"exact_moment_matrix_entries":0,"exact_target_masses":0, | |
| "matrix_inequality_entries":0,"retained_true_return_steps":0, | |
| "numerical_log_enclosures":0,"spectral_enclosures":0} | |
| def dec(x): | |
| x=Q(x) | |
| return Decimal(x.numerator)/Decimal(x.denominator) | |
| class ArithmeticTests(unittest.TestCase): | |
| def test_exact_fields(self): | |
| for f in [Field("integer"),Field("integer",3),Field("phi"),Field("salem")]: | |
| v=f.zero | |
| # beta^degree + sum f_i beta^i = 0, verified in integer coordinates. | |
| powers=[f.digit(1)] | |
| for _ in range(f.degree): | |
| powers.append(f.step(powers[-1])) | |
| result=list(powers[-1]) | |
| for i,c in enumerate(f.polynomial): | |
| result=[a+c*b for a,b in zip(result,powers[i])] | |
| self.assertEqual(tuple(result),v) | |
| def test_logarithms(self): | |
| with localcontext() as ctx: | |
| ctx.prec=100 | |
| for x in [Q(1),Q(2),Q(1,3),Q(10**50),Q(1,2**500),Q(2**500+1),Q(17,19)]: | |
| for tol in [Q(1,100),Q(1,10**15),Q(1,2**150)]: | |
| lo,hi=log_bounds(x,tol) | |
| self.assertLessEqual(hi-lo,tol) | |
| self.assertLessEqual(dec(lo),dec(x).ln()) | |
| self.assertGreaterEqual(dec(hi),dec(x).ln()) | |
| COUNTS["numerical_log_enclosures"]+=1 | |
| def test_return_gates_do_not_prune_true_bridges(self): | |
| for model in ["integer","phi","salem"]: | |
| src=fair(model) | |
| for n in range(1,8): | |
| gate=ReturnCone(src.field,src.digits,n) | |
| records=[] | |
| for path,end,p in paths(src,n,0): | |
| target,units=src.path_map(path) | |
| records.append((target,units)) | |
| for x,ux in records: | |
| for y,uy in records: | |
| if x!=y: | |
| continue | |
| carry=src.field.zero | |
| for t,(a,b) in enumerate(zip(ux,uy),1): | |
| carry=src.field.step(carry,tuple(v-w for v,w in zip(a,b))) | |
| self.assertTrue(gate.allows(carry,t)) | |
| COUNTS["retained_true_return_steps"]+=1 | |
| def test_spectral_roots(self): | |
| cases=[([[Q(1,2)]],Q(1,2)), | |
| ([[0,Q(1,2)],[Q(1,8),0]],Q(1,4)), | |
| ([[Q(1,2),Q(1,4)],[0,Q(1,4)]],Q(1,2)), | |
| ([[Q(1,4),0,0],[0,0,Q(1,2)],[0,Q(1,8),0]],Q(1,4)), | |
| ([[Q(1,3),Q(1,7),0],[0,Q(1,3),Q(1,7)],[0,0,Q(1,3)]],Q(1,3))] | |
| for matrix,root in cases: | |
| result=spectral_bounds(matrix,Q(1,10**18)) | |
| self.assertLessEqual(result['lower'],root) | |
| self.assertGreaterEqual(result['upper'],root) | |
| self.assertLessEqual(result['upper']-result['lower'],Q(1,10**18)*result['lower']) | |
| COUNTS['spectral_enclosures']+=1 | |
| class CompilerTests(unittest.TestCase): | |
| def test_all_kernel_entries_against_exhaustive(self): | |
| sources=[fair(),fair('salem'),fair('integer'),markov(),markov('salem'), | |
| periodic(),mixture(),variable(),variable('salem'),hidden()] | |
| for src in sources: | |
| for n in range(1,6): | |
| for q in [2,3]: | |
| if src.states==3 and n>4 and q==3: | |
| continue | |
| with self.subTest(field=src.field.name,states=src.states,clock=src.kmax,n=n,q=q): | |
| matrix,diag=collision_matrix(src,n,q) | |
| expected=moment_matrix(src,n,q) | |
| self.assertEqual(matrix,expected) | |
| self.assertFalse(diag['truncated']) | |
| COUNTS['exact_moment_matrix_entries']+=src.states**2 | |
| for q in [4,5]: | |
| for n in [1,2,3]: | |
| src=fair() | |
| self.assertEqual(collision_matrix(src,n,q)[0],moment_matrix(src,n,q)) | |
| COUNTS['exact_moment_matrix_entries']+=1 | |
| def test_masses_against_exhaustive(self): | |
| for src in [fair(),fair('salem'),markov(),variable(),hidden(),mixture()]: | |
| for n in range(1,5): | |
| distribution=aggregate(src,n) | |
| cond=distributions(src,n) | |
| seen=set() | |
| for a in range(src.states): | |
| for path,b,p in paths(src,n,a): | |
| target,_=src.path_map(path) | |
| mass,_=target_mass(src,path,start=a,end=b) | |
| self.assertEqual(mass,cond[a][(b,target[0],target[1])]) | |
| COUNTS['exact_target_masses']+=1 | |
| if target not in seen: | |
| seen.add(target) | |
| self.assertEqual(target_mass(src,path)[0],distribution[target]) | |
| COUNTS['exact_target_masses']+=1 | |
| def test_matrix_sandwich(self): | |
| for src in [fair(),markov(),periodic(),variable(),mixture(),hidden()]: | |
| for n in range(1,4): | |
| for m in range(1,4): | |
| for q in [0,2,3,4]: | |
| a=moment_matrix(src,n,q) | |
| b=moment_matrix(src,m,q) | |
| c=moment_matrix(src,n+m,q) | |
| product=matmul(a,b) | |
| factor=Q(src.states*src.split_bound(n))**(q-1) | |
| for i in range(src.states): | |
| for j in range(src.states): | |
| lo,hi=(product[i][j],factor*product[i][j]) if q>1 else (factor*product[i][j],product[i][j]) | |
| self.assertLessEqual(lo,c[i][j]) | |
| self.assertGreaterEqual(hi,c[i][j]) | |
| COUNTS['matrix_inequality_entries']+=1 | |
| def test_scalar_iid_inequality_really_fails(self): | |
| src=markov('integer') | |
| c1=sum(p*p for p in aggregate(src,1).values()) | |
| c2=sum(p*p for p in aggregate(src,2).values()) | |
| self.assertEqual(c1,Q(17,25)) | |
| self.assertEqual(c2,Q(11,25)) | |
| self.assertLess(c2,c1*c1) | |
| self.assertEqual(c1*c1-c2,Q(14,625)) | |
| def test_clock_is_part_of_equality(self): | |
| src=Source(Field('phi'),1,[(0,0,1,1,Q(1,2)),(0,0,1,2,Q(1,2))],[1]) | |
| self.assertEqual(collision_matrix(src,1,2)[0],[[Q(1,2)]]) | |
| self.assertEqual(target_mass(src,(0,))[0],Q(1,2)) | |
| self.assertEqual(target_mass(src,(1,))[0],Q(1,2)) | |
| def test_nonconstant_algebraic_digits(self): | |
| src=Source(Field('phi'),1,[(0,0,(1,2),1,Q(1,3)),(0,0,(-2,1),2,Q(2,3))],[1]) | |
| for n in range(1,5): | |
| self.assertEqual(collision_matrix(src,n,2)[0],moment_matrix(src,n,2)) | |
| def test_all_zero_digits_with_variable_clocks(self): | |
| src=Source(Field('salem'),1,[(0,0,0,1,Q(1,2)),(0,0,0,2,Q(1,2))],[1]) | |
| for n in range(1,6): | |
| self.assertEqual(collision_matrix(src,n,2)[0],moment_matrix(src,n,2)) | |
| def test_varied_rational_hidden_sources(self): | |
| rng=random.Random(77191) | |
| for index in range(24): | |
| f=Field(["integer","phi","salem"][index%3]) | |
| s=1+index%3 | |
| edges=[] | |
| for a in range(s): | |
| for end,p in [(a,Q(1,4)),(a,Q(1,4)),((a+1)%s,Q(1,2))]: | |
| digit=tuple(rng.randrange(-2,3) for _ in range(f.degree)) | |
| clock=rng.randrange(1,4) | |
| edges.append((a,end,digit,clock,p)) | |
| src=Source(f,s,edges,[Q(1,s)]*s) | |
| self.assertTrue(src.stationary) | |
| for n,q in [(3,2),(2,3)]: | |
| actual,_=collision_matrix(src,n,q) | |
| self.assertEqual(actual,moment_matrix(src,n,q)) | |
| COUNTS['exact_moment_matrix_entries']+=s*s | |
| def test_weighted_duplicate_edges_are_merged(self): | |
| src=Source(Field('phi'),1,[(0,0,1,1,Q(1,3)),(0,0,1,1,Q(2,3)),(0,0,9,1,0)],[1]) | |
| self.assertEqual(collision_matrix(src,4,3)[0],[[Q(1)]]) | |
| self.assertEqual(target_mass(src,(0,0,0,0))[0],1) | |
| def test_full_support_initial_law_does_not_enter_kernels(self): | |
| a=markov() | |
| b=Source(a.field,a.states,a.edges,[Q(1,2),Q(1,2)]) | |
| self.assertFalse(b.stationary) | |
| self.assertEqual(collision_matrix(a,6,2)[0],collision_matrix(b,6,2)[0]) | |
| def test_three_state_rational_spectral_certificate(self): | |
| matrix=[[Q(1,2),Q(1,4),0],[0,Q(1,3),Q(1,6)],[0,0,Q(1,5)]] | |
| result=spectral_bounds(matrix,Q(1,10**20)) | |
| self.assertLessEqual(result['lower'],Q(1,2)) | |
| self.assertGreaterEqual(result['upper'],Q(1,2)) | |
| COUNTS['spectral_enclosures']+=1 | |
| def test_budget_never_returns_a_truncated_certificate(self): | |
| with self.assertRaises(ResourceLimit): | |
| collision_matrix(fair('salem'),10,2,max_states=1) | |
| with self.assertRaises(ResourceLimit): | |
| target_mass(markov(),(0,0,0,0),max_states=1) | |
| class EntropyTests(unittest.TestCase): | |
| def test_injective_binary_model(self): | |
| with localcontext() as ctx: | |
| ctx.prec=80 | |
| for n in [4,8,16]: | |
| for q in [2,3,4]: | |
| result=renyi_interval(fair('integer'),n,q) | |
| lo,hi=result['interval_nats_per_branch'] | |
| truth=Decimal(2).ln() | |
| self.assertLessEqual(dec(lo),truth) | |
| self.assertGreaterEqual(dec(hi),truth) | |
| def test_phase_and_mixture(self): | |
| for n in [3,4,7]: | |
| for src in [periodic(),mixture()]: | |
| result=renyi_interval(src,n,2) | |
| self.assertEqual(result['interval_nats_per_branch'],(Q(0),Q(0))) | |
| src=mixture() | |
| n=5 | |
| matrix,_=collision_matrix(src,n,3) | |
| self.assertEqual(matrix,[[Q(1,2**(2*n)),0],[0,1]]) | |
| def test_seeded_shannon_reproducible(self): | |
| src=variable() | |
| first=shannon_interval(src,4,8,seed=17) | |
| second=shannon_interval(src,4,8,seed=17) | |
| self.assertEqual(first,second) | |
| self.assertEqual(first['sampled_quantity'],'H(X_n,Z_n | Z_0)/n') | |
| self.assertIn('pseudorandom',first['sampling_mode']) | |
| def test_validation(self): | |
| with self.assertRaises(ValueError): | |
| collision_matrix(fair(),2,1) | |
| with self.assertRaises(ValueError): | |
| collision_matrix(fair(),True,2) | |
| with self.assertRaises(ValueError): | |
| Field('not_a_field') | |
| with self.assertRaises(ValueError): | |
| Source(Field('phi'),1,[(0,0,0,0,1)],[1]) | |
| with self.assertRaises(ValueError): | |
| Source(Field('phi'),1,[(0,0,0,1,Q(1,2))],[1]) | |
| src=Source(Field('phi'),2,[(0,1,0,1,1),(1,0,1,1,1)],[Q(1,3),Q(2,3)]) | |
| with self.assertRaises(ValueError): | |
| shannon_interval(src,2,2) | |
| with self.assertRaises(ValueError): | |
| log_bounds(0) | |
| with self.assertRaises(ValueError): | |
| target_mass(fair(),(0,),start=True) | |
| def tearDownModule(): | |
| # The runner consumes these exact assertion counts; tests are not proof assistants. | |
| path=Path(__file__).resolve().parents[1]/'evidence'/'audit_counts.json' | |
| path.write_text(json.dumps(COUNTS,indent=2)+'\n',encoding='utf-8') | |
| if __name__=='__main__': | |
| unittest.main() | |