Datasets:
Formats:
json
Languages:
English
Size:
1K - 10K
Tags:
matter-embryogenesis
developmental-fabrication
nanotechnology
self-assembly
materials-science
passive-networks
| import sys | |
| from pathlib import Path | |
| sys.path.insert(0, str(Path(__file__).resolve().parents[1]/'src')) | |
| import unittest | |
| import numpy as np | |
| from scipy.optimize import linprog | |
| from scipy.linalg import cho_solve | |
| from gauge_contracts import (RelativeEstimator, grid_edges, incidence, | |
| comparison_line_graph, exact_feasibility, robust_feasibility, | |
| uniform_reserve_yield, ratio_observation, projective_response_error, | |
| closure_bridge_is_needed) | |
| from contracts import laplacian, kron | |
| class GaugeTheoryTests(unittest.TestCase): | |
| def test_exact_reachability_and_minimum_material_against_linear_program(self): | |
| rng=np.random.default_rng(811) | |
| for _ in range(80): | |
| count=int(rng.integers(2,15)) | |
| x=rng.uniform(.2,2.,count);c=rng.uniform(0,1.5,count) | |
| tau=float(rng.uniform(.005,.15));cost=rng.uniform(.2,3.,count) | |
| A=np.zeros((2*count,count+1)) | |
| A[:count,:count]=np.eye(count);A[:count,-1]=-np.exp(tau) | |
| A[count:,:count]=-np.eye(count);A[count:,-1]=np.exp(-tau) | |
| lp=linprog(np.r_[cost,0.],A_ub=A,b_ub=np.zeros(2*count), | |
| bounds=list(zip(x,x+c))+[(0,None)],method='highs') | |
| lo,hi,y=exact_feasibility(x,c,tau) | |
| self.assertEqual(lp.success,y is not None) | |
| if y is not None: | |
| self.assertAlmostEqual(float(cost@y),lp.fun,places=8) | |
| self.assertTrue(np.all(y>=x-1e-12)) | |
| self.assertTrue(np.all(y<=x+c+1e-12)) | |
| def test_robust_finite_repair_under_adversarial_endpoints(self): | |
| rng=np.random.default_rng(812) | |
| for trial in range(500): | |
| x=rng.uniform(.65,1.35,8);initial=x.copy() | |
| eps=.006; tau=.04;beta=.005;hlo=.007;hhi=.012;cap=1.05 | |
| z=np.log(x)+rng.choice([-eps,eps],len(x)) | |
| cert=robust_feasibility(np.exp(z-eps),np.exp(z+eps), | |
| cap,tau,beta,eps,hhi) | |
| self.assertTrue(cert['feasible']) | |
| k=cert['scale_lower'];a=cert['a'];b=cert['b'] | |
| accepted=np.zeros(len(x),bool) | |
| bound=1+int(np.ceil(np.max(np.maximum(0,a*k-initial))/hlo)) | |
| for turn in range(bound+1): | |
| # Force delay at the lower threshold, then alternate endpoints. | |
| err=np.where(np.arange(len(x))%2==turn%2,eps,-eps) | |
| measured=np.log(x)+err | |
| # Exact endpoint equality can round by about 2e-16 in log. | |
| accepted |= (measured>=np.log(k)-(tau-beta)+eps-1e-13) & \ | |
| (measured<=np.log(k)+(tau-beta)-eps+1e-13) | |
| if accepted.all():break | |
| need=~accepted | |
| self.assertTrue(np.all(x[need]<a*k+1e-12)) | |
| x[need]+=rng.choice([hlo,hhi],int(need.sum())) | |
| self.assertTrue(np.all(x<=b*k+1e-12)) | |
| self.assertTrue(accepted.all()) | |
| self.assertTrue(np.all(x-initial<=cap+1e-12)) | |
| final=x*np.exp(rng.choice([-beta,beta],len(x))) | |
| self.assertLessEqual(np.max(np.abs(np.log(final/k))),tau+1e-12) | |
| def test_no_guard_band_is_honest_failure(self): | |
| result=robust_feasibility(np.array([1.]),np.array([1.]),1.,.02,.01,.01,.01) | |
| self.assertFalse(result['feasible']) | |
| def test_uniform_zero_tolerance_reduces_to_range_distribution(self): | |
| for n in [2,3,10]: | |
| for c in [.01,.3,.7]: | |
| r=c/2 | |
| expected=n*r**(n-1)-(n-1)*r**n | |
| self.assertAlmostEqual(uniform_reserve_yield(n,1,3,c,0),expected,places=14) | |
| def test_uniform_threshold_all_sizes(self): | |
| low,high,tau=.65,1.35,.04 | |
| critical=high*np.exp(-2*tau)-low | |
| for n in [1,10,1000,1000000]: | |
| self.assertEqual(uniform_reserve_yield(n,low,high,critical,tau),1.) | |
| self.assertLess(uniform_reserve_yield(1000,low,high,critical-.01,tau),1e-5) | |
| def test_common_gain_and_material_scale_cancel(self): | |
| rng=np.random.default_rng(813) | |
| coords,edges=grid_edges(4,3) | |
| x=rng.uniform(.3,2,len(coords));target=rng.uniform(.2,3,len(coords)) | |
| expected=incidence(len(coords),edges)@np.log(x) | |
| actual=ratio_observation(x,target,edges, | |
| np.exp(rng.uniform(-3,3,len(edges))),np.zeros(len(edges)), | |
| physical_scale=.017) | |
| np.testing.assert_allclose(actual,expected,atol=2e-15) | |
| def test_estimator_covariance_identity(self): | |
| coords,edges=grid_edges(3,3);est=RelativeEstimator(len(coords),edges,reference=0) | |
| A=cho_solve(est.factor,est.Bg.T.toarray()) | |
| np.testing.assert_allclose(A@A.T,est.covariance_unit,atol=2e-14) | |
| def test_gradient_bias_is_exactly_invisible_to_cycles(self): | |
| coords,edges=grid_edges(4,3);est=RelativeEstimator(len(coords),edges,reference=0) | |
| truth=np.sin(np.arange(len(coords)));truth-=truth[0] | |
| bias=.3*coords[:,0]/3 | |
| y=est.B@(truth+bias) | |
| fit=est.estimate(y) | |
| self.assertLess(np.linalg.norm(y-est.B@fit),1e-12) | |
| self.assertAlmostEqual(np.max(np.abs(fit-truth)),.3,places=12) | |
| def test_local_messages_have_valid_residual_error_bound(self): | |
| coords,edges=grid_edges(4,2);est=RelativeEstimator(len(coords),edges,reference=0) | |
| y=np.cos(np.arange(len(edges))) | |
| local,info=est.local_estimate(y,tolerance=1e-6) | |
| error=np.max(np.abs(local-est.estimate(y))) | |
| self.assertLessEqual(error,info['certified_numerical_radius']+1e-12) | |
| self.assertLessEqual(info['certified_numerical_radius'],1e-6) | |
| def test_reference_bridge_and_disconnection(self): | |
| coords,edges=grid_edges(3,2) | |
| nodes,pairs=comparison_line_graph(edges) | |
| ref_edge=int(np.flatnonzero(np.any(pairs==nodes-1,axis=1))[0]) | |
| self.assertTrue(closure_bridge_is_needed(nodes,pairs,ref_edge)) | |
| with self.assertRaises(ValueError): | |
| RelativeEstimator(nodes,np.delete(pairs,ref_edge,axis=0)) | |
| def test_probe_schedule_uses_disjoint_modules(self): | |
| coords,edges=grid_edges(4,3) | |
| nodes,pairs=comparison_line_graph(edges);est=RelativeEstimator(nodes,pairs) | |
| for color in np.unique(est.colors): | |
| touched=pairs[est.colors==color].ravel() | |
| self.assertEqual(len(touched),len(set(touched))) | |
| def test_full_four_port_operator_is_scale_invariant(self): | |
| coords,edges=grid_edges(4,3) | |
| g=1.+np.arange(len(edges))%3 | |
| D=kron(laplacian(len(coords),edges,g),[0,3,48,63]) | |
| self.assertLess(projective_response_error(.006*D,D),1e-12) | |
| perturbed=g.copy();perturbed[:10]*=.2 | |
| altered=kron(laplacian(len(coords),edges,perturbed),[0,3,48,63]) | |
| self.assertGreater(projective_response_error(altered,D),.04) | |
| if __name__=='__main__': | |
| unittest.main() | |