"""Gre24 fill-time reproduction; explicit R1 choices, no fitted state or labels. Author method and our discretisation choices are kept distinct in receipts. This module never changes the historical R2-G24 approximation. """ from itertools import combinations import time import numpy as np from sklearn.neighbors import BallTree from boundary_distance import SurfaceDistance 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 mesh(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(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(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 solve_eikonal(g, sources, speed, max_iterations=100000): from fimpy.solver import create_fim_solver speed = np.broadcast_to(np.asarray(speed, dtype=float), (len(g['t']),)) if not np.isfinite(speed).all() or np.any(speed <= 0): raise ValueError('Nonpositive or nonfinite cell speed; no epsilon replacement') metric = speed[:, None, None]**2 * np.eye(3)[None] # Preserve upstream SPD check rather than silently weakening its threshold. solver = create_fim_solver(g['x'], g['t'], metric, precision=np.float64, device='cpu', use_active_list=True) phi = solver.comp_fim(np.asarray(sources, dtype=np.int32), np.zeros(len(sources)), max_iterations=max_iterations) if np.any(solver.active_list): raise RuntimeError('tetFIM iteration limit with active nodes') if not np.isfinite(phi).all() or np.any(phi < 0) or np.any(phi >= solver.undef_val): raise ValueError('Nonfinite, negative or unreached eikonal node') if np.any(phi[sources] != 0): raise ValueError('Eikonal source values changed') return phi.copy() def cell_flow_speed(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): surface = SurfaceDistance(g['x'][wall_faces]) speed[zero] = surface.query(g['centers'][zero]) 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(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(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(g, di, progress=lambda *a, **kw: None): radius = 3*g['hmax']; centers = g['centers']; cell_di = di[g['t']].mean(1) tree = BallTree(centers); result = np.empty((len(di), 6)); coincident = 0 for i, p in enumerate(g['x']): ids = tree.query_radius(p[None], r=radius)[0] delta = centers[ids]-p; dist = np.linalg.norm(delta, axis=1) selected = (dist < radius) & (np.abs(cell_di[ids]-di[i]) < radius) coincident += int(np.sum(selected & (dist == 0))) selected &= dist > 0 ids = ids[selected]; delta = delta[selected]; dist = dist[selected] if not len(ids): raise ValueError(f'Empty moment neighbourhood at node {i}') direction = delta/dist[:, 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 features(points, tetra, raw_ids, gate, wall_faces=None, marked_gate=None, progress=lambda *a, **kw: None): start = time.process_time(); g = mesh(points, tetra) faces = exterior_faces(g['t']) if wall_faces is None else np.asarray(wall_faces) sources, gate_mode = gate_nodes(g['x'], raw_ids, gate, marked_gate) 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 = solve_eikonal(g, wall, 1.); finish('Dw') progress('EIKONAL_DI'); di = solve_eikonal(g, sources, 1.); finish('Di') progress('CELL_SPEED'); speed, zero = cell_flow_speed(g, dw, faces); finish('cell_speed') progress('EIKONAL_DF'); df = solve_eikonal(g, sources, speed); finish('Df') if dw.max() <= 0 or di.max() <= 0: raise ValueError('Zero feature normalisation scale') vf = strict_volume_cdf(df, g['mass']); dis = di/di.max(); dws = dw/dw.max() grads = [nodal_gradient(g, a) for a in (vf, dis, dws)]; finish('gradients') moment, moment_meta = spatial_moment(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') metadata = dict(columns=list(COLUMNS), gate_mode=gate_mode, gate_nodes=sources.tolist(), gate_raw_ids=np.asarray(raw_ids)[sources].tolist(), wall_mode='tet_exterior_proxy' if wall_faces is None else 'explicit_supplied_wall_faces', all_wall_tetrahedra=len(zero), all_wall_rule='centroid_triangle_distance_R1_supplement', 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()), flow_distance_tied_nodes=int(len(df)-len(np.unique(df))), zero_gradient_nodes=[int(np.sum(np.linalg.norm(v, axis=1) == 0)) for v in grads], gate_mapping_distance=float(np.linalg.norm(g['x'][sources]-np.asarray(gate), axis=1).min()), exterior_proxy_includes_gate=bool(np.any(np.isin(sources, wall))), precision='float64', fim_device='cpu', max_iterations=100000) return dict(features=x, Dw=dw, Di=di, Df=df, Vf=vf, mass=g['mass'], all_wall_tet_ids=zero), metadata def per_geometry_metrics(y, predicted): y = np.asarray(y, dtype=float); predicted = np.asarray(predicted, dtype=float) if y.ndim != 1 or predicted.shape != y.shape or not len(y) or not np.isfinite(y).all() or not np.isfinite(predicted).all() or np.any(y < 0): raise ValueError('Invalid all-node score inputs') rmse = float(np.sqrt(np.mean((predicted-y)**2))) denom = dict(rms=float(np.sqrt(np.mean(y*y))), maximum=float(y.max()), mean=float(y.mean())) return dict(nodes=len(y), rmse=rmse, denominators=denom, undefined_metrics=[k for k, v in denom.items() if v <= 0], **{'rrmse_'+k: rmse/v if v > 0 else None for k, v in denom.items()}) def appendix_summary(splits): if len(splits) != 5 or any(not len(s) for s in splits): raise ValueError('Five nonempty split score lists required') rows = [dict(min=float(np.min(s)), median=float(np.median(s)), max=float(np.max(s))) for s in splits] return dict(per_split=rows, mean_of_split_summaries={k:float(np.mean([r[k] for r in rows])) for k in rows[0]})