Add multi-gate feature builder, CPU synthetic tests, and README (MULTIGATE-FEATURES-1122)

This commit is contained in:
AGY committed 2026-11-22 14:44:46 +00:00
1 parent 591299e0b2
commit a13521afcc
3 files changed
+633

No files matched your search

+258
View File
@@ -0,0 +1,258 @@
"""CPU-only synthetic tet-mesh tests for tools/multigate_features.py (no real data, no GPU)."""
import heapq
import importlib.util
from itertools import permutations
from pathlib import Path
import sys
import unittest
import numpy as np
sys.path.insert(0, str(Path(__file__).resolve().parent))
import multigate_features as mg
def _box_half_tets(nx, ny, nz, x_bounds, y_bounds, z_bounds):
axes = [
np.linspace(x_bounds[0], x_bounds[1], nx),
np.linspace(y_bounds[0], y_bounds[1], ny),
np.linspace(z_bounds[0], z_bounds[1], nz),
]
x = np.stack(np.meshgrid(*axes, indexing='ij'), axis=-1).reshape(-1, 3)
ids = np.arange(len(x)).reshape(nx, ny, nz)
t = []
for i in range(nx - 1):
for j in range(ny - 1):
for k in range(nz - 1):
for perm in permutations(range(3)):
v = np.array([i, j, k])
row = [ids[tuple(v)]]
for a in perm:
v = v.copy()
v[a] += 1
row.append(ids[tuple(v)])
t.append(row)
return x, np.asarray(t, dtype=np.int32)
def symmetric_box_mesh(nx_half=5, ny=3, nz=3, half_len=1.0, half_w=0.5, half_h=0.5):
"""Build a 3D tet mesh that is strictly mirror-symmetric under x -> -x."""
xp, tp = _box_half_tets(nx_half, ny, nz, (0.0, half_len), (-half_w, half_w), (-half_h, half_h))
on_plane = np.isclose(xp[:, 0], 0.0, atol=1e-12)
off_plane = np.flatnonzero(~on_plane)
xm = xp[off_plane].copy()
xm[:, 0] = -xm[:, 0]
points = np.vstack([xp, xm])
# Mirror map on node indices: involution mirror[mirror[i]] == i.
n_pos = len(xp)
mirror = np.arange(len(points), dtype=np.int64)
old_to_mirrored = np.arange(n_pos, dtype=np.int64)
for idx_new, idx_old in enumerate(off_plane):
mapped = n_pos + idx_new
old_to_mirrored[idx_old] = mapped
mirror[idx_old] = mapped
mirror[mapped] = idx_old
tm = old_to_mirrored[tp]
# Swap two vertices so reflected tets keep positive orientation (abs det handles both).
tm[:, [1, 2]] = tm[:, [2, 1]]
tetra = np.vstack([tp, tm]).astype(np.int32)
return points, tetra, mirror
def tet_edge_dijkstra_solver(g, sources, speed):
"""Deterministic mirror-symmetric pure-NumPy tet-edge shortest-path solver for CPU tests."""
x = g['x']
t = g['t']
n = len(x)
spd = np.broadcast_to(np.asarray(speed, dtype=np.float64), (len(t),))
if not np.isfinite(spd).all() or np.any(spd <= 0):
raise ValueError('Nonpositive or nonfinite cell speed')
edge_speed_sum = {}
edge_count = {}
for cell_idx, tet in enumerate(t):
s_val = float(spd[cell_idx])
for a, b in ((0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)):
u, v = int(tet[a]), int(tet[b])
key = (u, v) if u < v else (v, u)
edge_speed_sum[key] = edge_speed_sum.get(key, 0.0) + s_val
edge_count[key] = edge_count.get(key, 0) + 1
adj = [[] for _ in range(n)]
for (u, v), s_sum in edge_speed_sum.items():
length = float(np.linalg.norm(x[u] - x[v]))
w = length / (s_sum / edge_count[(u, v)])
adj[u].append((v, w))
adj[v].append((u, w))
dist = np.full(n, np.inf, dtype=np.float64)
heap = []
for src in np.asarray(sources, dtype=np.int64):
dist[src] = 0.0
heapq.heappush(heap, (0.0, int(src)))
while heap:
d, u = heapq.heappop(heap)
if d > dist[u]:
continue
for v, w in adj[u]:
nd = d + w
if nd < dist[v]:
dist[v] = nd
heapq.heappush(heap, (nd, v))
if not np.isfinite(dist).all():
raise ValueError('Unreached node in synthetic solver')
return dist
def _single_gate_reference_numpy(points, tetra, raw_ids, gate, solver_fn):
"""Exact line-for-line mirror of gre24_features_v2.features using injected solver."""
g = mg.mesh_numpy(points, tetra)
faces = mg.exterior_faces_numpy(g['t'])
sources, _ = mg.gate_nodes_numpy(g['x'], raw_ids, gate, None)
wall = np.unique(faces)
dw = solver_fn(g, wall, 1.)
di = solver_fn(g, sources, 1.)
speed, zero = mg.cell_flow_speed_numpy(g, dw, faces)
df = solver_fn(g, sources, speed)
vf = mg.strict_volume_cdf_numpy(df, g['mass'])
dis = di / di.max()
dws = dw / dw.max()
grads = [mg.nodal_gradient_numpy(g, a) for a in (vf, dis, dws)]
moment, _ = mg.spatial_moment_numpy(g, di)
x = np.column_stack([vf, grads[0], dis, grads[1], dw, dws, grads[2], moment])
return dict(features=x, Dw=dw, Di=di, Df=df, Vf=vf, mass=g['mass'], all_wall_tet_ids=zero)
class TestMultigateFeatures(unittest.TestCase):
def test_single_gate_byte_identical_numpy_backend(self):
pts, tet, _ = symmetric_box_mesh(nx_half=4, ny=3, nz=3)
raw_ids = np.arange(100, 100 + len(pts), dtype=np.int64)
gate = np.array([-1.0, 0.0, 0.0])
ref = _single_gate_reference_numpy(pts, tet, raw_ids, gate, tet_edge_dijkstra_solver)
out, meta = mg.features(pts, tet, raw_ids, [gate], backend='numpy', eikonal_solver=tet_edge_dijkstra_solver)
self.assertEqual(meta['num_gates'], 1)
self.assertEqual(out['features'].shape, (len(pts), 19))
for key in ('features', 'Dw', 'Di', 'Df', 'Vf', 'mass', 'all_wall_tet_ids'):
self.assertEqual(out[key].dtype, ref[key].dtype, msg=key)
self.assertEqual(out[key].shape, ref[key].shape, msg=key)
self.assertEqual(out[key].tobytes(), ref[key].tobytes(), msg=f'Not byte-identical on {key}')
self.assertEqual(out['Di_per_gate'][:, 0].tobytes(), ref['Di'].tobytes())
self.assertEqual(out['Df_per_gate'][:, 0].tobytes(), ref['Df'].tobytes())
np.testing.assert_array_equal(out['nearest_gate'], np.zeros(len(pts), dtype=np.int64))
self.assertFalse(bool(out['gate_tie_mask_df'].any()))
def test_single_gate_byte_identical_production_when_deps_available(self):
has_prod = all(importlib.util.find_spec(m) is not None for m in ('fimpy', 'sklearn', 'scipy'))
pts, tet, _ = symmetric_box_mesh(nx_half=3, ny=3, nz=3)
raw_ids = np.arange(len(pts), dtype=np.int64)
gate = np.array([-1.0, 0.0, 0.0])
if not has_prod:
# Verify production default fails closed when fimpy/sklearn/scipy are absent.
with self.assertRaises(ModuleNotFoundError):
mg.features(pts, tet, raw_ids, [gate], backend='production')
return
import gre24_features_v2 as g24
ref, _ = g24.features(pts, tet, raw_ids, gate)
out, _ = mg.features(pts, tet, raw_ids, [gate], backend='production')
for key in ('features', 'Dw', 'Di', 'Df', 'Vf', 'mass', 'all_wall_tet_ids'):
self.assertEqual(out[key].tobytes(), ref[key].tobytes(), msg=f'Production K=1 mismatch on {key}')
def test_two_symmetric_gates_produce_symmetric_fields(self):
pts, tet, mirror = symmetric_box_mesh(nx_half=5, ny=3, nz=3, half_len=1.0)
self.assertTrue(np.array_equal(mirror[mirror], np.arange(len(pts))))
raw_ids = np.arange(len(pts), dtype=np.int64)
gates = np.array([[-1.0, 0.0, 0.0], [1.0, 0.0, 0.0]])
out, meta = mg.features(pts, tet, raw_ids, gates, backend='numpy', eikonal_solver=tet_edge_dijkstra_solver)
self.assertEqual(meta['num_gates'], 2)
# Scalar fields are mirror-even.
for key in ('Dw', 'Di', 'Df', 'Vf'):
np.testing.assert_allclose(out[key][mirror], out[key], atol=1e-12, rtol=1e-12, err_msg=key)
# Per-gate distances swap gate 0 <-> gate 1 under reflection.
np.testing.assert_allclose(out['Di_per_gate'][mirror, 0], out['Di_per_gate'][:, 1], atol=1e-12, rtol=1e-12)
np.testing.assert_allclose(out['Df_per_gate'][mirror, 0], out['Df_per_gate'][:, 1], atol=1e-12, rtol=1e-12)
np.testing.assert_allclose(out['Di_per_gate_star'][mirror, 0], out['Di_per_gate_star'][:, 1], atol=1e-12, rtol=1e-12)
np.testing.assert_allclose(out['Df_per_gate_star'][mirror, 0], out['Df_per_gate_star'][:, 1], atol=1e-12, rtol=1e-12)
# Base 19 columns: Vf (0), Di_star (4), Dw (8), Dw_star (9) even; gradients reflect x -> -x.
x19 = out['features']
for col in (0, 4, 8, 9):
np.testing.assert_allclose(x19[mirror, col], x19[:, col], atol=1e-12, rtol=1e-12)
for gstart in (1, 5, 10):
np.testing.assert_allclose(x19[mirror, gstart], -x19[:, gstart], atol=1e-11, rtol=1e-11)
np.testing.assert_allclose(x19[mirror, gstart + 1:gstart + 3], x19[:, gstart + 1:gstart + 3], atol=1e-11, rtol=1e-11)
# Spatial moment tensor parity under x -> -x: Sxx(13), Syy(16), Syz(17), Szz(18) even; Sxy(14), Sxz(15) odd.
for col in (13, 16, 17, 18):
np.testing.assert_allclose(x19[mirror, col], x19[:, col], atol=1e-11, rtol=1e-11)
for col in (14, 15):
np.testing.assert_allclose(x19[mirror, col], -x19[:, col], atol=1e-11, rtol=1e-11)
# Nearest gate swaps 0 <-> 1 off symmetry plane; symmetry plane is marked tied.
on_plane = np.isclose(pts[:, 0], 0.0, atol=1e-12)
self.assertTrue(bool(out['gate_tie_mask_df'][on_plane].all()))
self.assertTrue(bool(out['gate_tie_mask_di'][on_plane].all()))
off = ~on_plane
np.testing.assert_array_equal(out['nearest_gate_df'][mirror[off]], 1 - out['nearest_gate_df'][off])
np.testing.assert_array_equal(out['nearest_gate_di'][mirror[off]], 1 - out['nearest_gate_di'][off])
def test_moving_one_gate_changes_only_affected_region(self):
pts, tet, _ = symmetric_box_mesh(nx_half=7, ny=3, nz=3, half_len=2.0)
raw_ids = np.arange(len(pts), dtype=np.int64)
g0 = np.array([-2.0, 0.0, 0.0])
g1_old = np.array([2.0, 0.0, 0.0])
g1_new = np.array([1.5, 0.0, 0.0])
out_old, _ = mg.features(pts, tet, raw_ids, [g0, g1_old], backend='numpy', eikonal_solver=tet_edge_dijkstra_solver)
out_new, _ = mg.features(pts, tet, raw_ids, [g0, g1_new], backend='numpy', eikonal_solver=tet_edge_dijkstra_solver)
# Unmoved gate channel and wall fields are byte-identical everywhere.
self.assertEqual(out_old['Dw'].tobytes(), out_new['Dw'].tobytes())
self.assertEqual(out_old['Di_per_gate'][:, 0].tobytes(), out_new['Di_per_gate'][:, 0].tobytes())
self.assertEqual(out_old['Df_per_gate'][:, 0].tobytes(), out_new['Df_per_gate'][:, 0].tobytes())
# Outside the affected basin of gate 1 (nodes owned by gate 0 in both runs),
# minimum arrival distances and nearest-gate index are byte-identical.
unaffected_di = (out_old['nearest_gate_di'] == 0) & (out_new['nearest_gate_di'] == 0)
unaffected_df = (out_old['nearest_gate_df'] == 0) & (out_new['nearest_gate_df'] == 0)
self.assertGreater(int(unaffected_di.sum()), 10)
self.assertGreater(int(unaffected_df.sum()), 10)
self.assertEqual(out_old['Di'][unaffected_di].tobytes(), out_new['Di'][unaffected_di].tobytes())
self.assertEqual(out_old['Df'][unaffected_df].tobytes(), out_new['Df'][unaffected_df].tobytes())
np.testing.assert_array_equal(out_old['nearest_gate_di'][unaffected_di], out_new['nearest_gate_di'][unaffected_di])
np.testing.assert_array_equal(out_old['nearest_gate_df'][unaffected_df], out_new['nearest_gate_df'][unaffected_df])
# Inside gate 1's affected region, distances and Vf genuinely change.
affected_df = ~unaffected_df
self.assertGreater(int(affected_df.sum()), 10)
self.assertGreater(float(np.max(np.abs(out_old['Df'][affected_df] - out_new['Df'][affected_df]))), 1e-3)
self.assertGreater(float(np.max(np.abs(out_old['Vf'] - out_new['Vf']))), 1e-3)
def test_three_gates_packing_marked_gates_and_guards(self):
pts, tet, _ = symmetric_box_mesh(nx_half=4, ny=3, nz=3, half_len=1.0)
raw_ids = np.arange(len(pts), dtype=np.int64)
gates = [[-1.0, 0.0, 0.0], [0.0, 0.5, 0.0], [1.0, 0.0, 0.0]]
out, meta = mg.features(pts, tet, raw_ids, gates, backend='numpy', eikonal_solver=tet_edge_dijkstra_solver)
self.assertEqual(meta['num_gates'], 3)
packed, cols = mg.pack_multigate_features(out)
self.assertEqual(packed.shape, (len(pts), 19 + 2 * 3 + 1))
self.assertEqual(len(cols), 26)
self.assertTrue(np.isfinite(packed).all())
# Vf is monotone non-decreasing with Df_min.
order = np.argsort(out['Df'], kind='stable')
self.assertTrue(bool(np.all(np.diff(out['Vf'][order]) >= -1e-15)))
# Explicit marked_gates works without coordinates.
out_m, meta_m = mg.features(pts, tet, raw_ids, None, marked_gates=[[0], [len(pts) - 1]],
backend='numpy', eikonal_solver=tet_edge_dijkstra_solver)
self.assertEqual(meta_m['num_gates'], 2)
self.assertEqual(out_m['Di_per_gate'].shape, (len(pts), 2))
# Fail-closed validation checks.
with self.assertRaises(ValueError):
mg.features(pts, tet, raw_ids, [], backend='numpy', eikonal_solver=tet_edge_dijkstra_solver)
with self.assertRaises(ValueError):
mg.features(pts, tet, raw_ids, [[np.nan, 0.0, 0.0]], backend='numpy', eikonal_solver=tet_edge_dijkstra_solver)
with self.assertRaises(ValueError):
mg.features(pts, tet, raw_ids, gates, backend='numpy', eikonal_solver=None)
if __name__ == '__main__':
unittest.main(verbosity=2)