Files
MeltMind/tools/test_o1_partition.py

137 lines
7.2 KiB
Python

"""Synthetic acceptance for the fixed O1 geometry intervention; no real data."""
import itertools
import unittest
import numpy as np
from scipy.spatial.distance import pdist
from o1_partition import (Metis, canonical_mesh, graph, canonical_labels, quantize,
partition_metrics, match, diameter, shuffle_type, readout, objective,
interface_difference, common_roster, can_reserve, GeometryFailure, InputViolation)
def box(nx=8, ny=4, nz=4):
points = np.array(list(itertools.product(range(nx+1), range(ny+1), range(nz+1))), dtype=float)
lookup = {tuple(p): i for i, p in enumerate(points)}
tets = []
for low in itertools.product(range(nx), range(ny), range(nz)):
for perm in itertools.permutations(range(3)):
p = np.array(low); cell = [lookup[tuple(p)]]
for axis in perm:
p = p.copy(); p[axis] += 1; cell.append(lookup[tuple(p)])
tets.append(cell)
return points, np.array(tets), np.arange(len(points))*3+11, np.arange(len(tets))*7+5
class O1Acceptance(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.source = box(); cls.mesh = canonical_mesh(*cls.source)
cls.g = graph(cls.mesh); cls.engine = Metis()
cls.labels, cls.call = cls.engine.partition(cls.g, cls.mesh['raw_cells'], 0)
def test_same_seed_same_input_twice_exact(self):
again, receipt = self.engine.partition(self.g, self.mesh['raw_cells'], 0)
np.testing.assert_array_equal(self.labels, again)
self.assertEqual(self.call, receipt)
def test_fixed_ufactor_and_physical_volume_reachable(self):
self.assertEqual(self.call['options'][16], 50)
self.assertEqual(self.call['options'][11], 1)
m = partition_metrics(self.mesh, self.g, self.labels)
self.assertGreaterEqual(min(m['fractions']), .95/8)
self.assertLessEqual(max(m['fractions']), 1.05/8)
self.assertEqual(len(m['diameters']), 8)
def test_csr_and_raw_identity_ignore_traversal_order(self):
x, t, rn, rc = self.source
rng = np.random.default_rng(31)
no, co = rng.permutation(len(x)), rng.permutation(len(t))
inverse = np.empty(len(x), dtype=int); inverse[no] = np.arange(len(x))
moved = canonical_mesh(x[no], inverse[t[co, ::-1]], rn[no], rc[co])
changed = graph(moved)
for key in ['points', 'tets', 'raw_nodes', 'raw_cells', 'volume']:
np.testing.assert_array_equal(self.mesh[key], moved[key])
for key in ['xadj', 'adjncy', 'vwgt', 'adjwgt', 'edges', 'area', 'faces_raw']:
np.testing.assert_array_equal(self.g[key], changed[key])
labels, _ = self.engine.partition(changed, moved['raw_cells'], 0)
np.testing.assert_array_equal(self.labels, labels)
def test_numbering_invariance_and_interface_identity(self):
relabeled = np.array([4, 6, 0, 7, 1, 3, 2, 5])[self.labels]
np.testing.assert_array_equal(canonical_labels(relabeled, self.mesh['raw_cells']), self.labels)
self.assertEqual(interface_difference(self.labels, relabeled, self.g)['value'], 0)
b = self.mesh['points'][self.mesh['tets']].mean(axis=1)[:, :2]
a = readout(self.mesh['tets'], self.mesh['volume'], b, self.labels, len(self.mesh['points']))
c = readout(self.mesh['tets'], self.mesh['volume'], b, relabeled, len(self.mesh['points']))
np.testing.assert_array_equal(a, c)
def test_boundary_blending_matches_independent_sums(self):
t, v, labels = self.mesh['tets'], self.mesh['volume'], self.labels
b = np.column_stack((np.arange(len(t))*.01, np.arange(len(t))*.02))
out = readout(t, v, b, labels, len(self.mesh['points']))
for node in [0, 34, 100, len(out)-1]:
incident = np.flatnonzero(np.any(t == node, axis=1)); expected = np.zeros(2)
for k in incident:
r = np.flatnonzero(labels == labels[k])
expected += v[k]*np.average(b[r], weights=v[r], axis=0)
expected /= v[incident].sum()
np.testing.assert_allclose(out[node], expected, rtol=1e-14, atol=1e-14)
def test_quantization_positive_bounded_and_invalid_rejected(self):
a = np.array([1e-20, 1., 20.]); w, e = quantize(a)
self.assertGreater(w.min(), 0); self.assertLessEqual(int(w.astype(np.int64).sum()), 2*2**26)
self.assertGreaterEqual(e['L1'], 0)
with self.assertRaises(GeometryFailure): quantize(np.array([0., 1.]))
def test_exact_diameter_not_bounding_box(self):
points = np.array([[0,0,0],[1,0,0],[0,1,0],[0,0,1],[.1,.1,.1]], dtype=float)
d, n = diameter(points, block=2)
self.assertEqual(d, float(pdist(points).max()))
self.assertNotEqual(d, np.sqrt(3)); self.assertEqual(n, 4)
def test_whole_triples_shuffle_only_within_volume_strata(self):
n = 103; z = np.arange(n*3).reshape(n, 3); volume = np.repeat(np.arange(11)+1, 10)[:n]
raw = np.arange(n)[::-1]
a, perm = shuffle_type(z, volume, raw, 3)
b, p2 = shuffle_type(z, volume, raw, 3)
np.testing.assert_array_equal(a, z[perm]); np.testing.assert_array_equal(a, b)
np.testing.assert_array_equal(perm, p2)
for ids in np.array_split(np.lexsort((raw, volume)), 10):
self.assertEqual(set(ids), set(perm[ids]))
with self.assertRaises(InputViolation): shuffle_type(z, volume, raw, '3')
def test_true_constant_field_objective_and_readout(self):
z = np.ones((len(self.labels), 3))*.125
self.assertAlmostEqual(objective(z, self.mesh['volume'], self.labels), 0., places=25)
out = readout(self.mesh['tets'], self.mesh['volume'], z, self.labels, len(self.mesh['points']))
np.testing.assert_allclose(out, .125, atol=1e-15)
def test_physical_and_pair_matching_hard_limits(self):
m = dict(fractions=[.125]*8, cut_area=10., diameters=[2.]*8)
self.assertTrue(match(m, m)['passed'])
self.assertFalse(match(dict(m, cut_area=10.51), m)['passed'])
self.assertFalse(match(dict(m, diameters=[2.101]*8), m)['passed'])
self.assertFalse(match(dict(m, fractions=[.12]*8), m)['passed'])
a, b = dict(m, cut_area=10.49), dict(m, cut_area=9.51)
self.assertTrue(match(a, m)['passed']); self.assertTrue(match(b, m)['passed'])
self.assertFalse(match(a, b, mutual=True)['passed'])
def test_multicomponent_and_duplicate_tets_fail(self):
x, t, rn, rc = self.source
with self.assertRaises(GeometryFailure):
canonical_mesh(x, np.vstack([t, t[:1]]), rn, np.r_[rc, rc.max()+1])
x2 = np.vstack([x, x+100]); t2 = np.vstack([t, t+len(x)])
with self.assertRaisesRegex(GeometryFailure, 'MULTICOMPONENT_SCOPE'):
graph(canonical_mesh(x2, t2, np.arange(len(x2)), np.arange(len(t2))))
def test_full_component_intersection_and_budget_reservation(self):
parts = [{'case':'a','component_id':'X'},{'case':'b','component_id':'X'},{'case':'c','component_id':'Y'}]
rows, excluded = common_roster(parts, {'a':{'status':'PASS'},'b':{'status':'FAIL'},'c':{'status':'PASS'}})
self.assertEqual(rows, parts[2:]); self.assertEqual(excluded, ['X'])
self.assertTrue(can_reserve(36000, 3)); self.assertFalse(can_reserve(36000.1, 3))
self.assertFalse(can_reserve(float('nan'), 0))
if __name__ == '__main__': unittest.main(verbosity=2)