Files
MeltMind/tools/multigate_features.py
T

357 lines
14 KiB
Python

"""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