129 lines
6.2 KiB
Python
129 lines
6.2 KiB
Python
"""Analytical conservation, symmetry, geometric boundaries and I/O tests."""
|
|
from itertools import permutations
|
|
import os
|
|
from pathlib import Path
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
import numpy as np
|
|
from scipy.sparse.linalg import cg
|
|
from s3b_graph import fill_events, edge_geometry, distal_regions, NumericalFailure
|
|
from s3b_runtime import reserve_ok
|
|
|
|
|
|
class GraphTests(unittest.TestCase):
|
|
def test_chain_analytical_times_and_conservation(self):
|
|
a,r,s=fill_events(np.array([[0,1],[1,2]]),np.array([2.,3.]),np.array([2.,3.,5.]),0)
|
|
np.testing.assert_allclose(a,[0,3,8],rtol=1e-10,atol=1e-12)
|
|
self.assertEqual(s['status'],'COMPLETE');self.assertEqual(r.sum(),0)
|
|
|
|
def test_symmetric_fork_keeps_ties(self):
|
|
a,_,s=fill_events(np.array([[0,1],[0,2]]),np.ones(2),np.ones(3),0)
|
|
np.testing.assert_allclose(a,[0,2,2]);self.assertEqual(s['events'],1)
|
|
|
|
def test_asymmetric_fork_and_multiple_wet_inflows(self):
|
|
# First branch (g=3) fills at4/3, then remaining1/3 fills underQ=1.
|
|
a,_,_=fill_events(np.array([[0,1],[0,2]]),np.array([3.,1.]),np.ones(3),0)
|
|
np.testing.assert_allclose(a,[0,4/3,2])
|
|
# Diamond: two tied unit-capacity branches, then jointly feed last node.
|
|
a,_,_=fill_events(np.array([[0,1],[0,2],[1,3],[2,3]]),np.ones(4),np.ones(4),0)
|
|
np.testing.assert_allclose(a,[0,2,2,3])
|
|
|
|
def test_Q_and_uniform_conductance_scaling(self):
|
|
e=np.array([[0,1],[0,2],[1,3],[2,3]]);g=np.array([1.,2.,3.,4.]);m=np.ones(4)
|
|
a,_,_=fill_events(e,g,m,0)
|
|
b,_,_=fill_events(e,g*7,m,0)
|
|
c,_,_=fill_events(e,g,m,0,Q=5)
|
|
np.testing.assert_allclose(a,b,rtol=1e-10)
|
|
np.testing.assert_allclose(a,5*c,rtol=1e-10)
|
|
|
|
def test_permutation_and_edge_order(self):
|
|
e=np.array([[0,1],[0,2],[1,3],[2,3]]);g=np.ones(4);m=np.ones(4)
|
|
a,_,_=fill_events(e,g,m,0)
|
|
old_to_new=np.array([2,3,1,0]);nm=np.empty_like(m);nm[old_to_new]=m
|
|
b,_,_=fill_events(old_to_new[e[::-1]],g[::-1],nm,int(old_to_new[0]))
|
|
np.testing.assert_allclose(a,b[old_to_new],atol=1e-12)
|
|
|
|
def test_blocked_is_not_full_and_zero_mass_not_removed(self):
|
|
a,r,s=fill_events(np.array([[0,1],[1,2]]),np.array([1.,0.]),np.array([1.,2.,4.]),0)
|
|
self.assertEqual(s['status'],'BLOCKED');self.assertEqual(s['remaining_volume'],4)
|
|
self.assertTrue(np.isnan(a[2]));self.assertEqual(r[2],4)
|
|
_,r,s=fill_events(np.array([[0,1]]),np.array([0.]),np.ones(2),0)
|
|
self.assertEqual(s['events'],0);self.assertEqual(r.sum(),1)
|
|
|
|
def test_bad_pressure_is_numerical_not_blocked(self):
|
|
def broken(a,b,**kw):return np.zeros_like(b),1
|
|
with self.assertRaises(NumericalFailure):
|
|
fill_events(np.array([[0,1]]),np.ones(1),np.ones(2),0,solver=broken)
|
|
|
|
def test_solver_tolerance_not_silently_repaired(self):
|
|
def biased(a,b,**kw):
|
|
p,info=cg(a,b,**kw);return p*1.01,info
|
|
with self.assertRaises(NumericalFailure):
|
|
fill_events(np.array([[0,1]]),np.ones(1),np.ones(2),0,solver=biased)
|
|
|
|
def test_single_all_wall_tet_stays_zero(self):
|
|
x=np.array([[0.,0,0],[1,0,0],[0,1,0],[0,0,1]])
|
|
t=np.array([[0,1,2,3]]);f=np.array([[0,1,2],[0,1,3],[0,2,3],[1,2,3]])
|
|
e=np.array([[0,1],[0,2],[0,3],[1,2],[1,3],[2,3]])
|
|
v=edge_geometry(x,t,f,np.zeros(4),e,np.ones(4)/24)
|
|
np.testing.assert_array_equal(v['conductance'],0)
|
|
self.assertAlmostEqual(v['edge_volume'].sum(),1/6)
|
|
_,_,s=fill_events(e,v['conductance'],v['mass'],0)
|
|
self.assertEqual(s['status'],'BLOCKED');self.assertAlmostEqual(s['remaining_volume'],1/8)
|
|
|
|
def test_cross_cube_midpoint_positive_wall_edges_exact_zero(self):
|
|
x=np.array([[i&1,(i>>1)&1,(i>>2)&1] for i in range(8)],float)
|
|
t=[]
|
|
for p in permutations([1,2,4]): t.append([0,p[0],p[0]+p[1],7])
|
|
t=np.array(t)
|
|
from s2_models.features import mesh_geometry
|
|
_,_,_,vol,m,e,_=mesh_geometry(x,t)
|
|
fs=np.sort(np.concatenate([t[:,[0,1,2]],t[:,[0,1,3]],t[:,[0,2,3]],t[:,[1,2,3]]]),axis=1)
|
|
unique,count=np.unique(fs,axis=0,return_counts=True);f=unique[count==1]
|
|
v=edge_geometry(x,t,f,np.zeros(8),e,m)
|
|
diagonal=np.flatnonzero((e==[0,7]).all(axis=1))[0]
|
|
self.assertAlmostEqual(v['midpoint'][diagonal],.5)
|
|
self.assertGreater(v['conductance'][diagonal],0)
|
|
np.testing.assert_array_equal(v['conductance'][v['boundary_edges']],0)
|
|
self.assertAlmostEqual(v['edge_volume'].sum(),1)
|
|
|
|
def test_strict_median_layer_and_original_graph(self):
|
|
d=np.array([0.,1.,1.,2.,2.]);m=np.ones(5);ids=np.arange(5)
|
|
e=np.array([[0,1],[0,2],[1,2],[1,3],[2,4]])
|
|
r=distal_regions(d,m,e,ids)
|
|
self.assertEqual(r['threshold'],1);self.assertEqual(r['status'],'VALID')
|
|
self.assertEqual([v['local_ids'] for v in r['regions']],[[3],[4]])
|
|
# Original edge3-4 must connect even if a future solver gives itg=0.
|
|
r=distal_regions(d,m,np.vstack([e,[3,4]]),ids)
|
|
self.assertEqual(r['status'],'NO_USABLE_DISTAL_PAIR')
|
|
|
|
def test_full_job_reservation(self):
|
|
self.assertTrue(reserve_ok(9000,1800,10800))
|
|
self.assertFalse(reserve_ok(9000.01,1800,10800))
|
|
|
|
def test_prediction_cannot_open_label_or_other_data(self):
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
root=Path(tmp);(root/'geometry').write_text('ok');(root/'full-node-labels.npz').write_text('secret')
|
|
(root/'out').mkdir()
|
|
script="""from pathlib import Path
|
|
from s3b_runtime import restrict_prediction_io
|
|
import sys
|
|
r=Path(sys.argv[1]);restrict_prediction_io([r/'geometry'],r/'out')
|
|
assert (r/'geometry').read_text()=='ok'
|
|
try:(r/'full-node-labels.npz').read_bytes()
|
|
except PermissionError:pass
|
|
else:raise AssertionError('label read permitted')
|
|
try:(r/'geometry').write_text('changed')
|
|
except PermissionError:pass
|
|
else:raise AssertionError('source write permitted')
|
|
(r/'out'/'receipt').write_text('barrier passed')
|
|
"""
|
|
env=dict(os.environ,PYTHONPATH=str(Path(__file__).resolve().parent))
|
|
subprocess.run([sys.executable,'-c',script,tmp],env=env,check=True)
|
|
self.assertEqual((root/'out'/'receipt').read_text(),'barrier passed')
|
|
|
|
|
|
if __name__=='__main__': unittest.main(verbosity=2)
|