Files
MeltMind/tools/s2_models/features.py
T

170 lines
7.9 KiB
Python

"""Array-only R2-G24 graph approximation. No dataset access or learned state."""
from itertools import combinations, product
import numpy as np
from scipy.sparse import coo_matrix
from scipy.sparse.csgraph import dijkstra
from scipy.spatial import cKDTree
def finite_array(value, shape=None, name="array"):
a = np.asarray(value, dtype=np.float64)
if not np.isfinite(a).all() or (shape is not None and a.shape != shape):
raise ValueError(f"invalid {name}: expected finite {shape}, got {a.shape}")
return a
def mesh_geometry(points, tets):
x = finite_array(points, name="points")
t = np.asarray(tets)
if x.ndim != 2 or x.shape[1] != 3 or not len(x):
raise ValueError("points must be nonempty (N,3)")
if t.ndim != 2 or t.shape[1] != 4 or not len(t) or t.dtype.kind not in "iu":
raise ValueError("tets must be nonempty integer (M,4)")
if t.min() < 0 or t.max() >= len(x):
raise ValueError("tet node outside points")
cells = x[t]
matrices = cells[:, 1:] - cells[:, :1]
volumes = np.abs(np.linalg.det(matrices)) / 6
if not np.isfinite(volumes).all() or np.any(volumes <= 0):
raise ValueError("degenerate tetrahedron")
mass = np.bincount(t.ravel(), weights=np.repeat(volumes / 4, 4), minlength=len(x))
if np.any(mass <= 0):
raise ValueError("unused mesh node")
edges = np.unique(np.sort(np.concatenate([t[:, [i, j]] for i, j in combinations(range(4), 2)]), axis=1), axis=0)
lengths = np.linalg.norm(x[edges[:, 1]] - x[edges[:, 0]], axis=1)
return x, t, matrices, volumes, mass, edges, lengths
def graph_distances(points, tets, wall_distance, gate, *, exclude_wall_edges=True):
x, t, matrices, vol, mass, edges, lengths = mesh_geometry(points, tets)
dw = finite_array(wall_distance, (len(x),), "wall distance")
gate = finite_array(gate, (3,), "gate")
if np.any(dw < 0):
raise ValueError("negative wall distance")
# argmin returns the first node in original ascending node-ID order.
source = int(np.argmin(np.linalg.norm(x - gate, axis=1)))
keep = (dw[edges].sum(axis=1) > 0) if exclude_wall_edges else np.ones(len(edges), dtype=bool)
e, length = edges[keep], lengths[keep]
def solve(cost):
graph = coo_matrix((np.tile(cost, 2), (np.r_[e[:, 0], e[:, 1]], np.r_[e[:, 1], e[:, 0]])), shape=(len(x), len(x))).tocsr()
out = dijkstra(graph, directed=False, indices=source)
if not np.isfinite(out).all():
raise ValueError("unreachable tet node after graph-edge rule")
return out
di = solve(length)
# Unrestricted geodesic is a separate N/E base input, not flow distance.
if not exclude_wall_edges:
return di, source
df = solve(length / dw[e].mean(axis=1))
return di, df, source
def relative_flow_volume(flow_distance, lumped_mass):
"""Strict front CDF: sum masses with D_f[j] < D_f[i]; ties share a value."""
d = finite_array(flow_distance, name="flow distance")
m = finite_array(lumped_mass, d.shape, "lumped mass")
if d.ndim != 1 or not len(d) or np.any(m <= 0):
raise ValueError("invalid volume CDF inputs")
order = np.argsort(d, kind="stable")
prefix = np.r_[0., np.cumsum(m[order])]
return prefix[np.searchsorted(d[order], d, side="left")] / m.sum()
def p1_nodal_gradient(points, tets, values, *, normalize=True):
"""Volume-average constant cell P1 gradients, then unit-normalise at nodes.
An exactly zero averaged gradient stays zero; no epsilon direction is invented.
"""
x, t, matrices, volumes, mass, _, _ = mesh_geometry(points, tets)
v = finite_array(values, (len(x),), "P1 nodal values")
cell_grad = np.linalg.solve(matrices, (v[t[:, 1:]] - v[t[:, :1]])[..., None])[..., 0]
grad = np.zeros((len(x), 3))
for k in range(4):
np.add.at(grad, t[:, k], cell_grad * volumes[:, None])
grad /= (4 * 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(points, tets, injection_distance):
"""Volume-weighted unit-direction moment with two strict neighbourhood tests.
Claude 1794667074.550589: exclude coincident cell centres before normalising
volumes. Trace is one. Empty neighbourhoods fail closed.
"""
x, t, _, volumes, _, _, lengths = mesh_geometry(points, tets)
di = finite_array(injection_distance, (len(x),), "injection distance")
radius = 3 * lengths.max()
centers = x[t].mean(axis=1)
cell_di = di[t].mean(axis=1)
tree = cKDTree(centers)
result = np.empty((len(x), 3, 3))
# One query at a time avoids storing all node/cell neighbourhoods together.
for i, point in enumerate(x):
ids = np.asarray(tree.query_ball_point(point, radius), dtype=np.int64)
distance = np.linalg.norm(centers[ids] - point, axis=1)
ids = ids[(np.abs(cell_di[ids] - di[i]) < radius) & (distance < radius) & (distance > 0)]
if not len(ids):
raise ValueError(f"empty spatial-moment neighbourhood at node {i}")
delta = centers[ids] - point
delta /= np.linalg.norm(delta, axis=1)[:, None]
weight = volumes[ids] / volumes[ids].sum()
result[i] = np.einsum("j,ja,jb->ab", weight, delta, delta)
return result, float(radius)
R2_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", "t_set")
def r2_features(points, tets, wall_distance, gate, t_set):
x, t, _, _, mass, _, _ = mesh_geometry(points, tets)
dw = finite_array(wall_distance, (len(x),), "wall distance")
ts = float(t_set)
if not np.isfinite(ts) or ts <= 0:
raise ValueError("missing/nonpositive t_set")
di, df, source = graph_distances(x, t, dw, gate)
if di.max() <= 0 or dw.max() <= 0:
raise ValueError("zero normalisation scale")
di_star, dw_star = di / di.max(), dw / dw.max()
vf = relative_flow_volume(df, mass)
moment, radius = spatial_moment(x, t, di)
sym = moment[:, [0, 0, 0, 1, 1, 2], [0, 1, 2, 1, 2, 2]]
features = np.column_stack([vf, p1_nodal_gradient(x, t, vf), di_star,
p1_nodal_gradient(x, t, di_star), dw, dw_star,
p1_nodal_gradient(x, t, dw_star), sym, np.full(len(x), ts)])
finite_array(features, (len(x), len(R2_COLUMNS)), "R2 inputs")
return {"features": features, "columns": R2_COLUMNS, "Di": di, "Df": df,
"Vf": vf, "S": moment, "radius": radius, "gate_node": source}
BASE_COLUMNS = ("x_star", "y_star", "z_star", "d_over_t", "gate_distance_over_Rg",
"geodesic_over_Rg", "Rg", "volume", "t_part", "t_set")
def base_features(points, wall_distance, geodesic_distance, gate, center, rg, volume, t_part, t_set):
x = finite_array(points, name="points")
if x.ndim != 2 or x.shape[1] != 3 or not len(x):
raise ValueError("invalid node coordinates")
dw = finite_array(wall_distance, (len(x),), "wall distance")
dg = finite_array(geodesic_distance, (len(x),), "geodesic")
gate, center = finite_array(gate, (3,), "gate"), finite_array(center, (3,), "center")
scales = finite_array([rg, volume, t_part, t_set], (4,), "physical scales")
if np.any(scales <= 0) or np.any(dw < 0) or np.any(dg < 0):
raise ValueError("nonpositive scale or negative distance")
return np.column_stack([(x-center)/rg, dw/t_part, np.linalg.norm(x-gate, axis=1)/rg,
dg/rg, np.tile(scales, (len(x), 1))])
def histgbrt_grid():
"""Twelve unfitted estimators' configurations; never launches fits."""
return [dict(learning_rate=lr, max_leaf_nodes=leaf, max_iter=n, min_samples_leaf=20,
random_state=0, early_stopping=False)
for lr, leaf, n in product((.05, .1), (31, 63), (200, 500, 1000))]