"""Research checks of conservation, causality, reconstruction and analytical limits.""" import sys,unittest,math from pathlib import Path sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'src')) import numpy as np from genome import compile_target,evaluate,make_target from local_growth import Config,simulate,diffusion_step from theory import * from functionality import conductance class ModelChecks(unittest.TestCase): def test_closed_transport_mass_and_positive(self): rng=np.random.default_rng(42);c=rng.random((9,7,5));p=rng.uniform(.01,1,c.shape) after=diffusion_step(c,p,.3,.1) self.assertAlmostEqual(c.sum(),after.sum(),places=11) self.assertGreaterEqual(after.min(),c.min()-1e-14) self.assertLessEqual(after.max(),c.max()+1e-14) def test_nonperiodic_compilation_exact(self): a=np.random.default_rng(4).integers(0,3,(5,7,3));g,_=compile_target(a) xyz=np.moveaxis(np.indices(a.shape),0,-1) np.testing.assert_array_equal(evaluate(g,xyz),a) def test_noiseless_growth_and_local_counter_inheritance(self): g={'op':'braced_shell','n':5} cfg=Config(n=5,dim=3,steps=600,initial_error=0,birth=0,transduction_error=0,seed=3) r,a=simulate(g,cfg) self.assertEqual(r['material_fidelity'],1.) np.testing.assert_array_equal(a['counters'],np.moveaxis(np.indices((5,)*3),0,-1)) self.assertLess(abs(r['mass_balance_residual']),1e-8) def test_seed_stops_inside_larger_vessel(self): g={'op':'paired_path','n':4} r,a=simulate(g,Config(n=7,dim=2,steps=300,seed=10)) expected=np.zeros((7,7),bool);expected[:4,:4]=True np.testing.assert_array_equal(a['state']>0,expected) def test_last_operation_floor(self): self.assertAlmostEqual(raw_error(0,0,1,100,.03),.03) self.assertEqual(min_wait(.1,.01,.1,.02,.01),math.inf) def test_bound_controls_actual_tail(self): for b in [5,10,31,100,500]: for p in [.01,.06,.13]: self.assertLessEqual(exact_module_failure(b,.2,p),math.exp(-b*kl_bernoulli(.2,p))+1e-15) def test_closure_cycle_detected(self): self.assertEqual(topo_order(['grow','repair','close'],[('grow','repair'),('repair','close')]),['grow','repair','close']) with self.assertRaises(ValueError):topo_order(['a','b'],[('a','b'),('b','a')]) def test_resistor_known_uniform_slab(self): # n parallel chains of n-1 unit resistances. self.assertAlmostEqual(conductance(np.full((7,7),2)),7/6,places=10) def test_common_mode_is_not_corrected_by_local_spec(self): g={'op':'paired_path','n':5} cfg=Config(n=5,dim=2,steps=800,initial_error=0,birth=0, transduction_error=0,common_mode=1,seed=2) r,a=simulate(g,cfg) self.assertEqual(r['completed_fraction'],1.) self.assertLess(r['material_fidelity'],.1) if __name__=='__main__':unittest.main(verbosity=2)