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]