Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a13521afcc |
No files matched your search
@@ -0,0 +1,19 @@
|
||||
# Multi-Gate Feature Builder (`MULTIGATE-FEATURES-1122`)
|
||||
|
||||
Extends the frozen 19-column `tools/gre24_features_v2.py` builder to $K \ge 1$ gates without modifying `gre24_features_v2.py`. Code and synthetic CPU tests only; no real data, no GPU, no push to `main`.
|
||||
|
||||
## Files
|
||||
- `tools/multigate_features.py`: multi-gate feature builder (`features`, `pack_multigate_features`) plus pure-NumPy geometry/gradient/moment helpers for minimal CPU test environments.
|
||||
- `tools/test_multigate_features.py`: CPU synthetic tet-mesh tests (K=1 byte-identity, two-gate mirror symmetry, single-gate perturbation locality, K=3 packing, fail-closed guards).
|
||||
|
||||
## Semantics & Compatibility
|
||||
- **Production default (`backend='production'`):** delegates directly to `gre24_features_v2.{mesh, exterior_faces, gate_nodes, solve_eikonal, cell_flow_speed, strict_volume_cdf, nodal_gradient, spatial_moment}` in the exact same call order (fails closed if `fimpy`/`sklearn`/`scipy` are unavailable). For `K=1`, `features`, `Dw`, `Di`, `Df`, `Vf`, `mass`, and `all_wall_tet_ids` are **byte-identical** to `gre24_features_v2.features`.
|
||||
- **Multi-gate outputs:**
|
||||
- `Di_per_gate`, `Df_per_gate`: `(N, K)` raw geometric and wall-weighted flow arrival distances per gate.
|
||||
- `Di_per_gate_star = Di_per_gate / Di.max()`, `Df_per_gate_star = Df_per_gate / Df.max()`: common-scale normalized per-gate channels preserving cross-gate ordering and symmetry.
|
||||
- `Di = min_k Di_per_gate`, `Df = min_k Df_per_gate`, `Vf = strict_volume_cdf(Df, mass)`: base 19 columns computed from `(Df, Di, Dw)`.
|
||||
- `nearest_gate_di`, `nearest_gate_df` (`nearest_gate` alias): `int64` in `0..K-1` (smallest-index tie-break), plus `gate_tie_mask_di` / `gate_tie_mask_df` for exact symmetry/weld-front ties.
|
||||
- **Perturbation locality:** moving gate $k$ leaves `Dw`, other gates' `Di_per_gate[:, j]` / `Df_per_gate[:, j]` ($j \ne k$), and `Di` / `Df` / `nearest_gate` outside gate $k$'s old/new arrival basin byte-identical. (`Vf` is a global volume CDF over `Df` and therefore updates globally wherever the sorted volume rank shifts.)
|
||||
|
||||
## Verification on Horsea
|
||||
Run `python -B tools/test_multigate_features.py` in the Horsea `fimpy`/`sklearn`/`scipy` environment: `test_single_gate_byte_identical_production_when_deps_available` automatically runs live against `gre24_features_v2.features` and asserts exact `.tobytes()` equality.
|
||||
@@ -0,0 +1,356 @@
|
||||
"""Multi-gate extension of the frozen 19-column Gre24 feature builder.
|
||||
|
||||
Preserves exact byte-for-byte identity with tools/gre24_features_v2.py when K=1
|
||||
under the production fimpy/BallTree/SurfaceDistance backend. Code only: no real
|
||||
data reads, no GPU launches, and never modifies tools/gre24_features_v2.py.
|
||||
"""
|
||||
from itertools import combinations
|
||||
import time
|
||||
import numpy as np
|
||||
|
||||
COLUMNS = (
|
||||
'Vf', 'grad_Vf_x', 'grad_Vf_y', 'grad_Vf_z', 'Di_star',
|
||||
'grad_Di_x', 'grad_Di_y', 'grad_Di_z', 'Dw', 'Dw_star',
|
||||
'grad_Dw_x', 'grad_Dw_y', 'grad_Dw_z',
|
||||
'Sxx', 'Sxy', 'Sxz', 'Syy', 'Syz', 'Szz',
|
||||
)
|
||||
|
||||
|
||||
def _load_production_module():
|
||||
import gre24_features_v2 as g24
|
||||
return g24
|
||||
|
||||
|
||||
def mesh_numpy(points, tetra):
|
||||
x = np.asarray(points, dtype=np.float64)
|
||||
t = np.asarray(tetra)
|
||||
if x.ndim != 2 or x.shape[1] != 3 or not np.isfinite(x).all():
|
||||
raise ValueError('Invalid points')
|
||||
if t.ndim != 2 or t.shape[1] != 4 or t.dtype.kind not in 'iu' or not len(t):
|
||||
raise ValueError('Invalid tetrahedra')
|
||||
if t.min() < 0 or t.max() >= len(x) or not np.array_equal(np.unique(t), np.arange(len(x))):
|
||||
raise ValueError('Tet domain must explicitly contain every supplied node')
|
||||
t = np.asarray(t, dtype=np.int32)
|
||||
cells = x[t]
|
||||
matrix = cells[:, 1:] - cells[:, :1]
|
||||
volume = np.abs(np.linalg.det(matrix)) / 6
|
||||
if not np.isfinite(volume).all() or np.any(volume <= 0):
|
||||
raise ValueError('Nonpositive tetrahedron volume')
|
||||
mass = np.bincount(t.ravel(), weights=np.repeat(volume / 4, 4), minlength=len(x))
|
||||
hmax = max(float(np.linalg.norm(cells[:, i] - cells[:, j], axis=1).max())
|
||||
for i, j in combinations(range(4), 2))
|
||||
return dict(x=x, t=t, matrix=matrix, volume=volume, mass=mass,
|
||||
centers=cells.mean(1), hmax=hmax)
|
||||
|
||||
|
||||
def exterior_faces_numpy(tetra):
|
||||
faces = np.sort(tetra[:, np.array([[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]])].reshape(-1, 3), axis=1)
|
||||
faces, counts = np.unique(faces, axis=0, return_counts=True)
|
||||
if np.any(counts > 2):
|
||||
raise ValueError('Nonmanifold tetrahedron faces')
|
||||
return faces[counts == 1]
|
||||
|
||||
|
||||
def gate_nodes_numpy(x, raw_ids, gate, marked=None):
|
||||
raw_ids = np.asarray(raw_ids)
|
||||
if len(raw_ids) != len(x) or len(np.unique(raw_ids)) != len(x):
|
||||
raise ValueError('Invalid original node IDs')
|
||||
if marked is not None:
|
||||
marked = np.asarray(marked, dtype=np.int64)
|
||||
if not len(marked) or marked.min() < 0 or marked.max() >= len(x):
|
||||
raise ValueError('Invalid explicit inlet node set')
|
||||
return np.unique(marked), 'explicit_marked_nodes'
|
||||
gate = np.asarray(gate, dtype=float)
|
||||
if gate.shape != (3,) or not np.isfinite(gate).all():
|
||||
raise ValueError('Invalid inlet location')
|
||||
d2 = np.sum((x - gate) ** 2, axis=1)
|
||||
tied = np.flatnonzero(d2 == d2.min())
|
||||
return np.array([tied[np.argmin(raw_ids[tied])]]), 'nearest_tet_node_min_original_id_tie'
|
||||
|
||||
|
||||
def _triangle_distance_squared(point, triangles):
|
||||
a, b, c = triangles[:, 0], triangles[:, 1], triangles[:, 2]
|
||||
ab, ac = b - a, c - a
|
||||
q = point - a
|
||||
normal = np.cross(ab, ac)
|
||||
n2 = np.einsum('ij,ij->i', normal, normal)
|
||||
good = n2 > 0
|
||||
denom = np.where(good, n2, 1.0)
|
||||
u = np.einsum('ij,ij->i', np.cross(q, ac), normal) / denom
|
||||
v = np.einsum('ij,ij->i', np.cross(ab, q), normal) / denom
|
||||
inside = good & (u >= 0) & (v >= 0) & (u + v <= 1)
|
||||
plane = np.einsum('ij,ij->i', q, normal) ** 2 / denom
|
||||
result = np.where(inside, plane, np.inf)
|
||||
for first, second in [(a, b), (b, c), (c, a)]:
|
||||
edge = second - first
|
||||
length2 = np.einsum('ij,ij->i', edge, edge)
|
||||
alpha = np.clip(np.einsum('ij,ij->i', point - first, edge) / np.where(length2 > 0, length2, 1.0), 0.0, 1.0)
|
||||
residual = point - (first + alpha[:, None] * edge)
|
||||
result = np.minimum(result, np.einsum('ij,ij->i', residual, residual))
|
||||
return np.maximum(result, 0.0)
|
||||
|
||||
|
||||
def cell_flow_speed_numpy(g, dw, wall_faces):
|
||||
if not np.isfinite(dw).all() or np.any(dw < 0):
|
||||
raise ValueError('Invalid wall field')
|
||||
speed = dw[g['t']].mean(1)
|
||||
zero = np.flatnonzero(np.all(dw[g['t']] == 0, axis=1))
|
||||
if len(zero):
|
||||
triangles = g['x'][wall_faces]
|
||||
speed[zero] = np.array([
|
||||
float(np.sqrt(_triangle_distance_squared(p, triangles).min()))
|
||||
for p in g['centers'][zero]
|
||||
], dtype=np.float64)
|
||||
if not np.isfinite(speed).all() or np.any(speed <= 0):
|
||||
raise ValueError('Nonpositive flow speed after declared all-wall supplement')
|
||||
return speed, zero
|
||||
|
||||
|
||||
def strict_volume_cdf_numpy(field, mass):
|
||||
d = np.asarray(field, dtype=float)
|
||||
w = np.asarray(mass, dtype=float)
|
||||
if d.ndim != 1 or w.shape != d.shape or not len(d) or not np.isfinite(d).all() or not np.isfinite(w).all() or np.any(w <= 0):
|
||||
raise ValueError('Invalid lumped-volume CDF')
|
||||
order = np.argsort(d, kind='stable')
|
||||
prefix = np.r_[0., np.cumsum(w[order], dtype=np.float64)]
|
||||
return prefix[np.searchsorted(d[order], d, side='left')] / w.sum()
|
||||
|
||||
|
||||
def nodal_gradient_numpy(g, values, normalize=True):
|
||||
v = np.asarray(values, dtype=float)
|
||||
if v.shape != (len(g['x']),) or not np.isfinite(v).all():
|
||||
raise ValueError('Invalid nodal scalar')
|
||||
t = g['t']
|
||||
cell_grad = np.linalg.solve(g['matrix'], (v[t[:, 1:]] - v[t[:, :1]])[..., None])[..., 0]
|
||||
grad = np.zeros((len(v), 3))
|
||||
for k in range(4):
|
||||
np.add.at(grad, t[:, k], cell_grad * g['volume'][:, None])
|
||||
grad /= 4 * g['mass'][:, None]
|
||||
if normalize:
|
||||
norm = np.linalg.norm(grad, axis=1)
|
||||
np.divide(grad, norm[:, None], out=grad, where=norm[:, None] > 0)
|
||||
return grad
|
||||
|
||||
|
||||
def spatial_moment_numpy(g, di, progress=lambda *a, **kw: None):
|
||||
radius = 3 * g['hmax']
|
||||
centers = g['centers']
|
||||
cell_di = di[g['t']].mean(1)
|
||||
result = np.empty((len(di), 6))
|
||||
coincident = 0
|
||||
for i, p in enumerate(g['x']):
|
||||
delta = centers - p
|
||||
dist = np.linalg.norm(delta, axis=1)
|
||||
selected = (dist < radius) & (np.abs(cell_di - di[i]) < radius)
|
||||
coincident += int(np.sum(selected & (dist == 0)))
|
||||
selected &= dist > 0
|
||||
ids = np.flatnonzero(selected)
|
||||
if not len(ids):
|
||||
raise ValueError(f'Empty moment neighbourhood at node {i}')
|
||||
direction = delta[ids] / dist[ids, None]
|
||||
weight = g['volume'][ids]
|
||||
weight = weight / weight.sum()
|
||||
tensor = np.einsum('n,ni,nj->ij', weight, direction, direction)
|
||||
result[i] = tensor[[0, 0, 0, 1, 1, 2], [0, 1, 2, 1, 2, 2]]
|
||||
if i % 4096 == 0:
|
||||
progress('SPATIAL_MOMENT', completed=i, total=len(di))
|
||||
return result, dict(radius=radius, coincident_centers_excluded=coincident,
|
||||
component_order=list(COLUMNS[13:]))
|
||||
|
||||
|
||||
def _normalize_gates(gates, marked_gates):
|
||||
if gates is None:
|
||||
if marked_gates is None:
|
||||
raise ValueError('Either gates or marked_gates is required')
|
||||
marked_list = list(marked_gates)
|
||||
if not marked_list:
|
||||
raise ValueError('At least one gate is required')
|
||||
return [None] * len(marked_list), marked_list
|
||||
arr = np.asarray(gates, dtype=np.float64)
|
||||
if arr.ndim == 1:
|
||||
if arr.shape != (3,):
|
||||
raise ValueError('Single gate coordinate must have shape (3,)')
|
||||
arr = arr[None, :]
|
||||
elif arr.ndim != 2 or arr.shape[1] != 3 or len(arr) == 0:
|
||||
raise ValueError('gates must have shape (K, 3) with K >= 1')
|
||||
if not np.isfinite(arr).all():
|
||||
raise ValueError('Nonfinite gate coordinates')
|
||||
gate_list = [arr[k] for k in range(len(arr))]
|
||||
if marked_gates is None:
|
||||
marked_list = [None] * len(gate_list)
|
||||
else:
|
||||
marked_list = list(marked_gates)
|
||||
if len(marked_list) != len(gate_list):
|
||||
raise ValueError('marked_gates length must match gates')
|
||||
return gate_list, marked_list
|
||||
|
||||
|
||||
def _nearest_and_ties(per_gate, tie_rtol=1e-12):
|
||||
# np.argmin breaks exact ties by smallest gate index (deterministic).
|
||||
nearest = np.argmin(per_gate, axis=1).astype(np.int64)
|
||||
if per_gate.shape[1] == 1:
|
||||
return nearest, np.zeros(len(per_gate), dtype=bool)
|
||||
min_vals = per_gate[np.arange(len(per_gate)), nearest]
|
||||
tol = tie_rtol * max(float(min_vals.max()), 1.0)
|
||||
close_count = np.sum(per_gate <= min_vals[:, None] + tol, axis=1)
|
||||
return nearest, close_count > 1
|
||||
|
||||
|
||||
def features(points, tetra, raw_ids, gates, wall_faces=None, marked_gates=None,
|
||||
progress=lambda *a, **kw: None, *, backend='production', eikonal_solver=None):
|
||||
"""Compute 19 base columns + multi-gate arrival channels for K >= 1 gates.
|
||||
|
||||
When backend='production' (default) and K=1, delegates directly to
|
||||
gre24_features_v2 primitives in identical order for byte-identical output.
|
||||
"""
|
||||
if backend == 'production':
|
||||
g24 = _load_production_module()
|
||||
mesh_fn = g24.mesh
|
||||
ext_fn = g24.exterior_faces
|
||||
gate_fn = g24.gate_nodes
|
||||
speed_fn = g24.cell_flow_speed
|
||||
cdf_fn = g24.strict_volume_cdf
|
||||
grad_fn = g24.nodal_gradient
|
||||
moment_fn = g24.spatial_moment
|
||||
solver_fn = g24.solve_eikonal if eikonal_solver is None else eikonal_solver
|
||||
elif backend == 'numpy':
|
||||
if eikonal_solver is None:
|
||||
raise ValueError("backend='numpy' requires an explicit eikonal_solver callable")
|
||||
mesh_fn = mesh_numpy
|
||||
ext_fn = exterior_faces_numpy
|
||||
gate_fn = gate_nodes_numpy
|
||||
speed_fn = cell_flow_speed_numpy
|
||||
cdf_fn = strict_volume_cdf_numpy
|
||||
grad_fn = nodal_gradient_numpy
|
||||
moment_fn = spatial_moment_numpy
|
||||
solver_fn = eikonal_solver
|
||||
else:
|
||||
raise ValueError(f'Unknown backend: {backend}')
|
||||
|
||||
gate_list, marked_list = _normalize_gates(gates, marked_gates)
|
||||
n_gates = len(gate_list)
|
||||
start = time.process_time()
|
||||
g = mesh_fn(points, tetra)
|
||||
faces = ext_fn(g['t']) if wall_faces is None else np.asarray(wall_faces)
|
||||
per_gate_sources = []
|
||||
per_gate_modes = []
|
||||
for gate_pt, marked in zip(gate_list, marked_list):
|
||||
src, mode = gate_fn(g['x'], raw_ids, gate_pt, marked)
|
||||
per_gate_sources.append(src)
|
||||
per_gate_modes.append(mode)
|
||||
wall = np.unique(faces)
|
||||
|
||||
timings = {}
|
||||
tick = time.process_time()
|
||||
def finish(name):
|
||||
nonlocal tick
|
||||
now = time.process_time()
|
||||
timings[name] = now - tick
|
||||
tick = now
|
||||
|
||||
progress('EIKONAL_DW')
|
||||
dw = solver_fn(g, wall, 1.)
|
||||
finish('Dw')
|
||||
|
||||
progress('EIKONAL_DI')
|
||||
di_list = [solver_fn(g, src, 1.) for src in per_gate_sources]
|
||||
finish('Di')
|
||||
|
||||
progress('CELL_SPEED')
|
||||
speed, zero = speed_fn(g, dw, faces)
|
||||
finish('cell_speed')
|
||||
|
||||
progress('EIKONAL_DF')
|
||||
df_list = [solver_fn(g, src, speed) for src in per_gate_sources]
|
||||
finish('Df')
|
||||
|
||||
di_per_gate = np.column_stack(di_list)
|
||||
df_per_gate = np.column_stack(df_list)
|
||||
# Preserve exact array identity for K=1.
|
||||
di = di_list[0] if n_gates == 1 else di_per_gate.min(axis=1)
|
||||
df = df_list[0] if n_gates == 1 else df_per_gate.min(axis=1)
|
||||
|
||||
if dw.max() <= 0 or di.max() <= 0 or df.max() <= 0:
|
||||
raise ValueError('Zero feature normalisation scale')
|
||||
|
||||
vf = cdf_fn(df, g['mass'])
|
||||
dis = di / di.max()
|
||||
dws = dw / dw.max()
|
||||
grads = [grad_fn(g, a) for a in (vf, dis, dws)]
|
||||
finish('gradients')
|
||||
|
||||
moment, moment_meta = moment_fn(g, di, progress)
|
||||
finish('moment')
|
||||
|
||||
x = np.column_stack([vf, grads[0], dis, grads[1], dw, dws, grads[2], moment])
|
||||
if x.shape != (len(points), 19) or not np.isfinite(x).all():
|
||||
raise ValueError('Invalid final 19-column features')
|
||||
|
||||
di_per_gate_star = di_per_gate / di.max()
|
||||
df_per_gate_star = df_per_gate / df.max()
|
||||
nearest_gate_di, gate_tie_mask_di = _nearest_and_ties(di_per_gate)
|
||||
nearest_gate_df, gate_tie_mask_df = _nearest_and_ties(df_per_gate)
|
||||
|
||||
all_sources = np.unique(np.concatenate(per_gate_sources))
|
||||
raw_arr = np.asarray(raw_ids)
|
||||
gate_dists = [
|
||||
float(np.linalg.norm(g['x'][src] - np.asarray(pt), axis=1).min()) if pt is not None else 0.0
|
||||
for src, pt in zip(per_gate_sources, gate_list)
|
||||
]
|
||||
metadata = dict(
|
||||
columns=list(COLUMNS),
|
||||
backend=backend,
|
||||
num_gates=n_gates,
|
||||
gate_modes=per_gate_modes,
|
||||
gate_nodes=[src.tolist() for src in per_gate_sources],
|
||||
gate_raw_ids=[raw_arr[src].tolist() for src in per_gate_sources],
|
||||
gate_mapping_distances=gate_dists,
|
||||
nearest_gate_tie_break='smallest_gate_index',
|
||||
wall_mode='tet_exterior_proxy' if wall_faces is None else 'explicit_supplied_wall_faces',
|
||||
all_wall_tetrahedra=len(zero),
|
||||
all_wall_volume_fraction=float(g['volume'][zero].sum() / g['volume'].sum()),
|
||||
timings_cpu_seconds=timings,
|
||||
worker_cpu_seconds=time.process_time() - start,
|
||||
volume=float(g['volume'].sum()),
|
||||
hmax=g['hmax'],
|
||||
moment=moment_meta,
|
||||
speed_min=float(speed.min()),
|
||||
speed_max=float(speed.max()),
|
||||
exterior_proxy_includes_gate=bool(np.any(np.isin(all_sources, wall))),
|
||||
precision='float64',
|
||||
)
|
||||
arrays = dict(
|
||||
features=x,
|
||||
Dw=dw,
|
||||
Di=di,
|
||||
Df=df,
|
||||
Vf=vf,
|
||||
mass=g['mass'],
|
||||
all_wall_tet_ids=zero,
|
||||
Di_per_gate=di_per_gate,
|
||||
Df_per_gate=df_per_gate,
|
||||
Di_per_gate_star=di_per_gate_star,
|
||||
Df_per_gate_star=df_per_gate_star,
|
||||
nearest_gate_di=nearest_gate_di,
|
||||
nearest_gate_df=nearest_gate_df,
|
||||
nearest_gate=nearest_gate_df,
|
||||
gate_tie_mask_di=gate_tie_mask_di,
|
||||
gate_tie_mask_df=gate_tie_mask_df,
|
||||
)
|
||||
return arrays, metadata
|
||||
|
||||
|
||||
def pack_multigate_features(arrays):
|
||||
"""Stack base 19 columns + per-gate normalized Di/Df + nearest_gate index."""
|
||||
base = np.asarray(arrays['features'], dtype=np.float64)
|
||||
di_g = np.asarray(arrays['Di_per_gate_star'], dtype=np.float64)
|
||||
df_g = np.asarray(arrays['Df_per_gate_star'], dtype=np.float64)
|
||||
ng = np.asarray(arrays['nearest_gate'], dtype=np.float64)[:, None]
|
||||
k = di_g.shape[1]
|
||||
cols = (
|
||||
COLUMNS
|
||||
+ tuple(f'Di_gate{i}_star' for i in range(k))
|
||||
+ tuple(f'Df_gate{i}_star' for i in range(k))
|
||||
+ ('nearest_gate',)
|
||||
)
|
||||
return np.column_stack([base, di_g, df_g, ng]), cols
|
||||
@@ -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)
|
||||
Reference in new issue
Block a user