Files
MeltMind/tools/test_phase2_b1213.py

106 lines
7.3 KiB
Python

import unittest
import numpy as np
from scipy.sparse import csr_matrix
from phase2_b12_math import paths,junction_depth,edge_geometry
from phase2_h1_topology import events
from phase2_b1213_gate import decision,coverage
from phase2_b1213_features import g_metrics
from o1_partition import readout,Metis
from gre24_models import xgb_model
def adjacency(n,edges,length=1.):
e=np.array(edges);return csr_matrix((np.full(2*len(e),length),(np.r_[e[:,0],e[:,1]],np.r_[e[:,1],e[:,0]])),shape=(n,n))
class Acceptance(unittest.TestCase):
def test_unrelated_junction_and_multiple_sources(self):
a=adjacency(8,[(0,1),(1,2),(1,3),(4,5),(5,6),(5,7)]);h=a.copy();h.data[:]=2
df=np.array([0,1,2,2,0,1,2,2.])
_,owner,e,_=paths(df,np.arange(8),[0,4],a,h)
j,r,_=junction_depth(df,np.ones(8),np.arange(8),a,[0,4],owner)
np.testing.assert_array_equal(owner,[0]*4+[4]*4)
np.testing.assert_array_equal(j,[0,0,1,1,0,0,1,1]);self.assertEqual(r['significant_events'],2)
def test_invalid_thickness_propagates_without_invented_values(self):
a=adjacency(4,[(0,1),(1,2),(2,3)]);h=a.copy();h.data[:]=2
for i in [1,2]:
for k in range(h.indptr[i],h.indptr[i+1]):
if h.indices[k] in [1,2]:h.data[k]=0
_,owner,e,_=paths(np.arange(4),np.arange(4),[0],a,h)
np.testing.assert_array_equal(owner,[0]*4);self.assertTrue(np.isnan(e[2:]).all())
def test_field_engineering_error_never_becomes_missing(self):
import tempfile
from pathlib import Path
from unittest.mock import patch
from phase2_b1213_gate import field
from o1_partition import InputViolation
with tempfile.TemporaryDirectory() as tmp:
root=Path(tmp);d=root/'parts/0000';d.mkdir(parents=True)
c=dict(kind='B12',parts=[dict(case='synthetic',component_id='g',nodes=4)],extra_columns=3)
with patch('phase2_b1213_gate.b12',side_effect=InputViolation('synthetic hash corruption')):
with self.assertRaises(InputViolation):field(root,c,0)
self.assertTrue((d/'failure.json').exists());self.assertFalse((d/'result.json').exists());self.assertFalse((d/'extra.npy').exists())
def test_field_defined_missing_keeps_full_shape(self):
import tempfile,json
from pathlib import Path
from unittest.mock import patch
from phase2_b1213_gate import field
from o1_partition import GeometryFailure
with tempfile.TemporaryDirectory() as tmp:
root=Path(tmp);d=root/'parts/0000';d.mkdir(parents=True)
c=dict(kind='B13',parts=[dict(case='synthetic',component_id='g',nodes=4)],extra_columns=2)
with patch('phase2_b1213_gate.b13',side_effect=GeometryFailure('MULTICOMPONENT_SCOPE')):field(root,c,0)
e=np.load(d/'extra.npy');self.assertEqual(e.shape,(4,2));self.assertTrue(np.isnan(e).all())
self.assertEqual(json.loads((d/'result.json').read_text())['status'],'SCIENTIFIC_MISSING')
def test_constant_thickness_and_missing_root(self):
a=adjacency(4,[(0,1),(1,2),(2,3)]);h=a.copy();h.data[:]=2
parent,owner,extra,r=paths(np.arange(4),np.arange(4),[0],a,h)
np.testing.assert_array_equal(parent,[-1,0,1,2]);np.testing.assert_array_equal(owner,[0]*4)
self.assertTrue(np.isnan(extra[0,0]));np.testing.assert_allclose(extra[1:,0],2);np.testing.assert_allclose(extra[:,1],[0,.25,.5,.75])
j,_,_=junction_depth(np.arange(4),np.ones(4),np.arange(4),a,[0],owner);np.testing.assert_array_equal(j,[0]*4)
def test_plateau_ties_and_unknown_component(self):
a=adjacency(6,[(0,1),(0,2),(1,3),(2,3),(4,5)]);h=a.copy();h.data[:]=2
parent,owner,e,r=paths(np.array([0,1,1,1,0,1]),np.arange(6),[0],a,h)
self.assertEqual(parent[3],1);np.testing.assert_array_equal(parent[4:],[-2,-2]);self.assertTrue(np.isnan(e[4:]).all())
self.assertEqual(r['reachable_nodes'],4)
def test_flat_plateau(self):
a=adjacency(4,[(0,1),(1,2),(2,3)]);h=a.copy();h.data[:]=1
p,owner,e,r=paths(np.zeros(4),np.arange(4),[0],a,h)
np.testing.assert_array_equal(p,[-1,0,1,2]);j,_,_=junction_depth(np.zeros(4),np.ones(4),np.arange(4),a,[0],owner);np.testing.assert_array_equal(j,0)
def test_Y_and_compound_event(self):
a=adjacency(6,[(0,1),(1,2),(2,3),(2,4),(2,5)]);h=a.copy();h.data[:]=2;df=np.array([0,1,2,3,3,3.])
_,owner,_,_=paths(df,np.arange(6),[0],a,h);j,r,_=junction_depth(df,np.ones(6),np.arange(6),a,[0],owner)
np.testing.assert_array_equal(j,[0,0,0,1,1,1]);self.assertEqual(r['significant_events'],1)
old=events(df,np.ones(6),np.arange(6),np.column_stack([np.arange(6),np.zeros((6,2))]),a)
self.assertEqual(r['significant_events'],len(old['events']))
def test_edge_inner_distance_positive_at_wall(self):
x=np.array([[0,0,0],[1,0,0],[0,1,0],[0,0,1.]])
a,h=edge_geometry(x,np.array([[0,1,2,3]]),np.array([1/6]),np.array([.25]))
np.testing.assert_allclose(h.data,.5)
_,_,e,_=paths(np.array([0,1,1,1]),np.arange(4),[0],a,h);self.assertTrue(np.all(np.isfinite(e[1:])))
def test_g_readout_mass_and_permutation(self):
t=np.array([[0,3*k+1,3*k+2,3*k+3] for k in range(8)]);v=np.arange(1,9,dtype=float);labels=np.arange(8)
x=np.arange(50,dtype=float).reshape(25,2)/50;b=x[t].mean(1)
u=readout(t,v,b,labels,25);permutation=np.array([5,3,1,7,0,2,6,4]);uu=readout(t,v,b,permutation,25)
np.testing.assert_allclose(u,uu);m=np.bincount(t.ravel(),weights=np.repeat(v/4,4),minlength=25)
np.testing.assert_allclose((m[:,None]*u).sum(0),(m[:,None]*x).sum(0))
np.testing.assert_allclose(readout(t,v,np.ones((8,2))*3,labels,25),3)
np.testing.assert_allclose(u[0],np.average(b,axis=0,weights=v));np.testing.assert_allclose(u[1],b[0])
def test_g_single_arm_gate(self):
edges=np.array([(i,i+1) for i in range(7)]);g=dict(adjacency=adjacency(8,edges),edges=edges,area=np.ones(7));m=dict(volume=np.ones(8));labels=np.arange(8)
self.assertTrue(g_metrics(m,g,labels)['passed']);m['volume'][0]=2;self.assertFalse(g_metrics(m,g,labels)['passed'])
self.assertEqual(Metis().options(0)[8],0)
def test_final_gate_strict_boundaries(self):
self.assertEqual(decision({'high':-.001},{'high':1}),'EXPAND_THIS_FIXED_RECIPE')
self.assertEqual(decision({'high':.0009},{'high':-.01}),'EXPAND_THIS_FIXED_RECIPE')
self.assertEqual(decision({'high':.001},{'high':-.01}),'PRUNE_THIS_FIXED_RECIPE')
self.assertEqual(decision({'high':0},{'high':0}),'PRUNE_THIS_FIXED_RECIPE')
self.assertEqual(decision({'high':None},{'high':-.01}),'PARK_UNDEFINED')
def test_component_complete_coverage(self):
rows=[dict(case='a',component_id='g'),dict(case='b',component_id='g'),dict(case='c',component_id='h')]
results={k:dict(status='GEOMETRY_COMPLETE') for k in ['a','b','c']};results['b']['status']='SCIENTIFIC_MISSING'
c=coverage(rows,results);self.assertEqual(c['fraction'],.5);self.assertEqual(c['valid_parts'],2)
def test_native_nan_fixed_regressor(self):
x=np.arange(100,dtype=np.float32).reshape(20,5);x[:5,-1]=np.nan;y=np.arange(20,dtype=np.float32)
m=xgb_model(0,1);m.fit(x,y,sample_weight=np.ones(20));self.assertEqual(m.get_booster().num_boosted_rounds(),100);self.assertTrue(np.isfinite(m.predict(x)).all())
if __name__=='__main__':unittest.main()