Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
01c1cc53fc | ||
|
|
91aeb2aed7 | ||
|
|
3db1079fd7 |
No files matched your search
@@ -1,19 +0,0 @@
|
||||
# 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,56 @@
|
||||
# New Windows Complex-Geometry Test Set — Selection Rule (`WIN-TEST-SELECT-v1`)
|
||||
|
||||
- **Date:** 2026-11-23
|
||||
- **Authors:** AGY (draft v0/v1), Claude (review & rulings), source check on Gre24 §2 / Zenodo v5
|
||||
- **Stage boundary:** **Test-only.** No part in this set ever enters training, standardization, clock fitting, or hyperparameter tuning. Nothing runs until Yanqi confirms `N` (`10–20`) and the frozen manifest SHA-256 is recorded.
|
||||
|
||||
## 1. Source Pool, Feasibility Gate & Shared Mesh Recipe
|
||||
- **Source pool:** Public ABC CAD dataset starting from declared chunk slice `0000–0009`, canonically sorted by 8-digit ABC ID and hashed (`SHA-256`) before sampling. Strictly exclude all 624 Greif v5, 629 Greif v4, and 196 Zenodo `17831586` parts (matched by ABC ID and 24-char family prefix).
|
||||
- If too few candidates pass the frozen gates, extend strictly by the declared next chunk slices (`0010–0019`, `0020–0029`, …); **never** loosen any threshold after inspecting candidates.
|
||||
- **Hard geometry/mesh feasibility gate** (logged with explicit reason codes `DISCONNECTED`, `NON_MANIFOLD`, `OUT_OF_SCALE`, `TOO_THIN`, `MESH_FAIL`; never silently dropped):
|
||||
- Single connected watertight manifold solid (`connected_components == 1`, positive volume).
|
||||
- Physical scale within Greif's moldable envelope: bounding-box max `20–250 mm`, volume `1–300 cm³`, median interior wall thickness `2·P50(Dw_int) ∈ [0.8, 6.0] mm`, minimum thickness `>= 0.5 mm`.
|
||||
- **Single shared BDF mesh:** Generate the tetrahedral mesh **once** with a fixed Greif-like-density recipe (`5,000 <= N_nodes <= 120,000`, all positive tet volumes) and export as BDF. Moldex3D **imports that exact BDF** (as in Run 02) so models and Moldex3D share one mesh and the v3.1 element→original-ID mapping applies unchanged. Record the meshing recipe and every BDF SHA-256 in the frozen manifest.
|
||||
|
||||
## 2. Gate-Placement Rule (Source-Verified)
|
||||
- **Reference check:** Greif et al. (§2, OPUS 113920) and the Zenodo v5 data card (`18598121`) document a single uniformly random exterior surface node on the Gmsh surface mesh, with **no published seed, sampling weights, or thickness filter**.
|
||||
- **Adopted rule (same rule, not a value-wise replica):**
|
||||
- Collect all exterior surface nodes of the shared tet mesh (no thickness restriction, matching Greif's documented distribution), sort them canonically by original node ID (lexicographic `(x, y, z)` tie-break), and draw **1 node** uniformly with `PCG64(SeedSequence([2026112301, abc_id]))`.
|
||||
- Label in manifest: `"uniformly random exterior surface node (fixed seed, no thickness filter); same rule as Greif et al. §2 / v5 data card, not a value-wise replica"`.
|
||||
|
||||
## 3. Measurable Geometry-Only Complexity Criteria (Zero Labels)
|
||||
Computed strictly on the shared tet mesh + assigned gate using `gre24_features_v2` `Dw`, `Di`, `Df` only. Quantile anchors are computed from **Greif fold-0 learning** only (never test) and frozen before scoring any candidate:
|
||||
- **C1 (Thickness contrast — ribs/steps/bosses):** `R_th = P90(Dw_int) / P10(Dw_int) >= max(2.5, P75_Greif_learn(R_th))` on interior nodes / tet centroids.
|
||||
- **C2 (Path tortuosity — bends/baffles/folded shells):** `τ_path = max(Di) / ||x(argmax Di) - x_gate||_2 >= max(1.35, P75_Greif_learn(τ_path))`.
|
||||
- **C3 (Multi-branch / multi-tip structure):** `N_branch >= 2` distinct local maxima of `Di` separated by geodesic distance `>= 0.25 · max(Di)` (or `>= 2` superlevel components of `Di` at `0.75 · max(Di)`).
|
||||
- **C4 (Topology or flow-vs-geometry divergence):** surface Euler genus `g >= 1` (through-hole/loop) **or** `1 - Spearman(Di, Df) >= P75_Greif_learn`.
|
||||
- **Eligibility:** candidate must satisfy **at least 2 of C1–C4**.
|
||||
|
||||
## 4. Geometry-Only Near-Duplicate Exclusion
|
||||
Checked against **all** Greif v5 (624) + v4 (629) + Zenodo `17831586` (196) parts **and** against already-selected Windows test parts (enforcing distinct families):
|
||||
- **Stage 1 (fast rigid + scale-invariant screen):** volume-weighted inertia ratios `(λ₂/λ₁, λ₃/λ₁)`, fill ratio `V / V_OBB`, isoperimetric ratio `A³ / V²`, genus `g`, and 20-bin Osada D2 pairwise-distance histogram on `4,096` deterministically sampled surface points (normalized to `Rg = 1`). Any pair with `L1(D2) < 0.12`, inertia-ratio `L∞ < 0.10`, and equal genus enters Stage 2.
|
||||
- **Stage 2 (aligned geometric overlap):** align normalized (`Rg = 1`) 4,096-point clouds across all 24 PCA axis/sign symmetries + bounded ICP; compute symmetric Chamfer `d_CD` and 95th-percentile Hausdorff `d_H95`.
|
||||
- **Hard rejection:** reject if `d_CD < 0.05 Rg` or `d_H95 < 0.12 Rg` (log borderline `0.05 <= d_CD < 0.08 Rg` for geometry-only inspection); also reject any shared Onshape/ABC document family ID.
|
||||
|
||||
## 5. Anti-Cherry-Picking Draw Protocol (`N = 10–20` Parts)
|
||||
- **Fixed seed & strict queue order:** permute the hashed ABC pool **once** with `PCG64(SeedSequence(2026112301))`. Walk strictly in order with **zero backtracking or manual swaps**.
|
||||
- **Balanced stratification (4 equal quotas, e.g., 4×4 for `N = 16`, 3×4 for `N = 12`, 5×4 for `N = 20`):**
|
||||
1. High thickness contrast (`C1`, `g = 0`)
|
||||
2. Topological loops/holes (`g >= 1` + `C2` or `C4`)
|
||||
3. Multi-branch / high tortuosity (`C2` + `C3`)
|
||||
4. Combined high complexity (`>= 3` of `C1–C4`)
|
||||
- Extra matches for a full stratum are logged (`STRATUM_FULL`) and skipped. Pre-draw a deterministic **5-part backup queue** in strict order solely to replace any part that fails Moldex3D convergence (`SOLVER_FAIL`, logged).
|
||||
|
||||
## 6. Windows Test Recipe, Host & Reporting Rules
|
||||
- **Screening host:** Horsea (public ABC download); Windows runs Moldex3D only on the frozen BDF manifest.
|
||||
- **Process recipe ("Windows test recipe", not "same condition"):** Single condition at `270 °C` melt, `45 °C` mold, V/P setting recorded explicitly, substituted material `Celstran PP-GF30-03`, unless Yanqi requests a second condition.
|
||||
- *Flow / injection-time rule:* Greif et al. (§2) lets Moldflow auto-select flow rate from the geometry, so a single fixed `0.05 s` for every part would not match. Use **Moldex3D's automatic injection-time setting if available**; otherwise use a single fixed rule written down in the manifest before solving. Record each part's actual fill time.
|
||||
- **Freeze & single-read evaluation:** Hash the final manifest (`N` BDF meshes, gate coordinates/node IDs, stratum tags, backup queue, exclusion log, meshing & Windows test recipes) before any Moldex3D solve or model forward pass. Read each Moldex3D output **once** at evaluation; **normalised arrival time** is the primary comparison.
|
||||
- **Mandatory reporting label:** `"complex-part test set (≥ 2 of C1–C4), Windows test recipe, cross-solver, material substituted"`. Report **per-stratum** and overall results; do **not** compare averages directly against Greif averages because this test set is harder by construction.
|
||||
|
||||
## 7. Pre-Screening Assignment, Backup & Solve/Eval Binding Rules (Frozen Before Screening)
|
||||
1. **Multi-stratum assignment:** Assign each eligible part to the **first stratum**, in the fixed precedence order **(4) ≥ 3 criteria → (2) topology → (3) multi-branch → (1) thickness contrast**, that both matches and still has an open primary slot (`< 3`). Record both `matched_strata` and `assigned_stratum`. If all matching strata are full, log `STRATUM_FULL` and skip.
|
||||
2. **Per-stratum backups (8 total):** After the 12 primary parts (`3 × 4` strata), continue walking the exact same shuffled queue and record the next **2 eligible parts per stratum** (same `4 → 2 → 3 → 1` first-open-slot rule on backup slots `< 2`). A part that fails meshing or Moldex3D solving is replaced **only** by the next unused backup of the **same stratum**, with the failure reason logged. Retain all screening rejections and skips; never change thresholds after screening starts.
|
||||
3. **Gate-to-inlet-face mapping (778 lesson):** The manifest freezes the gate as an original node ID. After each solve, MeltWin records the inlet faces Moldex3D actually assigned and maps them to original tet IDs. Gate elements are **only** the tets owning an inlet face (as in v3.1), and verification confirms the chosen gate node lies on those inlet faces.
|
||||
4. **Injection time fallback:** MeltWin first checks whether Moldex3D's automatic injection time works on a new part's first run. If not, use a pre-fixed power law `fill_time = a · V^b` fitted on Greif fold-0 **learning** parts (LOG fill time vs part volume), frozen with its SHA-256 before any solve.
|
||||
5. **Blind recipe time vs actual fill time at scoring:** Models receive only the pre-solve **recipe time**. Moldex3D's actual solved fill time is **never** used to decode predictions and is reported separately. Primary comparison: **normalised arrival time** (each field divided by its own end), plus **last-1 % location**.
|
||||
@@ -1,356 +0,0 @@
|
||||
"""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
|
||||
@@ -1,258 +0,0 @@
|
||||
"""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)
|
||||
@@ -0,0 +1,142 @@
|
||||
"""CPU-only synthetic unit tests for WIN-TEST-SELECT-v1.1 + §7 rules."""
|
||||
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 win_test_select_rules as sel
|
||||
|
||||
|
||||
def box_mesh(nx=4, ny=4, nz=4, sx=2.0, sy=1.0, sz=0.5):
|
||||
axes = [np.linspace(0, sx, nx), np.linspace(0, sy, ny), np.linspace(0, sz, 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 holed_ring_mesh():
|
||||
"""3x3x1 voxel grid with center cell removed -> watertight genus-1 tet mesh."""
|
||||
nx, ny, nz = 4, 4, 2
|
||||
axes = [np.linspace(0, 3, nx), np.linspace(0, 3, ny), np.linspace(0, 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):
|
||||
if i == 1 and j == 1:
|
||||
continue
|
||||
for perm in permutations(range(3)):
|
||||
v = np.array([i, j, 0])
|
||||
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)
|
||||
|
||||
|
||||
class TestWinTestSelectRules(unittest.TestCase):
|
||||
def test_pool_permutation_and_uniform_gate_draw_deterministic(self):
|
||||
pool = [f'{i:08d}' for i in range(50)]
|
||||
q1, sha1 = sel.permute_pool(pool)
|
||||
q2, sha2 = sel.permute_pool(list(reversed(pool)))
|
||||
self.assertEqual(sha1, sha2)
|
||||
self.assertEqual(q1, q2)
|
||||
self.assertNotEqual(q1, pool)
|
||||
|
||||
x, t = box_mesh(3, 3, 3)
|
||||
faces = sel.exterior_faces(t)
|
||||
raw = np.arange(1000, 1000 + len(x))
|
||||
l1, r1 = sel.draw_gate_node(x, raw, faces, 12345)
|
||||
l2, r2 = sel.draw_gate_node(x, raw, faces, 12345)
|
||||
self.assertEqual((l1, r1), (l2, r2))
|
||||
self.assertIn(l1, set(np.unique(faces)))
|
||||
|
||||
def test_euler_genus_box_and_holed_ring(self):
|
||||
_, t_box = box_mesh(3, 3, 3)
|
||||
self.assertEqual(sel.surface_euler_genus(sel.exterior_faces(t_box)), 0)
|
||||
_, t_ring = holed_ring_mesh()
|
||||
self.assertEqual(sel.surface_euler_genus(sel.exterior_faces(t_ring)), 1)
|
||||
|
||||
def test_stratum_precedence_and_per_stratum_backups(self):
|
||||
def make_rec(cid, c1=False, c2=False, c3=False, c4=False, g=0):
|
||||
cnt = int(c1) + int(c2) + int(c3) + int(c4)
|
||||
return dict(abc_id=cid, metrics=dict(C1=c1, C2=c2, C3=c3, C4=c4, genus=g,
|
||||
criteria_count=cnt, eligible=(cnt >= 2)))
|
||||
|
||||
# Build queue containing overlapping parts matching multiple strata + rejections.
|
||||
recs = [dict(abc_id='bad0', reject_reason='NON_MANIFOLD')]
|
||||
# 6 parts matching S4, S2, S3 (g=1, C1+C2+C3+C4) -> first 3 fill S4, next 3 spill to S2!
|
||||
for i in range(6):
|
||||
recs.append(make_rec(f'multi_{i}', c1=True, c2=True, c3=True, c4=True, g=1))
|
||||
# 5 parts matching S3 & S1 (g=0, C1+C2+C3 -> also S4, but S4 already full -> S3 gets 3, S1 gets 2)
|
||||
for i in range(5):
|
||||
recs.append(make_rec(f'g0_{i}', c1=True, c2=True, c3=True, c4=False, g=0))
|
||||
# 2 parts matching only S1 (C1+C2, g=0) -> 1 completes S1 primary (12/12!), 1 goes to S1 backup
|
||||
for i in range(2):
|
||||
recs.append(make_rec(f's1_{i}', c1=True, c2=True, c3=False, c4=False, g=0))
|
||||
# Now backups for all 4 strata (2 each):
|
||||
for i in range(10):
|
||||
recs.append(make_rec(f'bk_all_{i}', c1=True, c2=True, c3=True, c4=True, g=1))
|
||||
for i in range(3):
|
||||
recs.append(make_rec(f'bk_s1_{i}', c1=True, c2=True, c3=False, c4=False, g=0))
|
||||
|
||||
res = sel.assign_queue(recs)
|
||||
self.assertTrue(res['complete'])
|
||||
for s in (1, 2, 3, 4):
|
||||
self.assertEqual(len(res['primary'][s]), 3)
|
||||
self.assertEqual(len(res['backup'][s]), 2)
|
||||
# First 3 multi_* went to S4 (highest priority), next 3 spilled to S2 (second priority).
|
||||
self.assertEqual([r['abc_id'] for r in res['primary'][4]], ['multi_0', 'multi_1', 'multi_2'])
|
||||
self.assertEqual([r['abc_id'] for r in res['primary'][2]], ['multi_3', 'multi_4', 'multi_5'])
|
||||
self.assertEqual([r['abc_id'] for r in res['primary'][3]], ['g0_0', 'g0_1', 'g0_2'])
|
||||
self.assertEqual([r['abc_id'] for r in res['primary'][1]], ['g0_3', 'g0_4', 's1_0'])
|
||||
|
||||
def test_near_duplicate_rigid_scale_invariance_and_separation(self):
|
||||
x, t = box_mesh(4, 3, 3, sx=3.0, sy=1.2, sz=0.5)
|
||||
f = sel.exterior_faces(t)
|
||||
d_orig = sel.stage1_descriptor(x, t, f, n_samples=1024)
|
||||
# Rigid rotation + uniform scaling + translation -> must be caught as near-duplicate!
|
||||
theta = 0.73
|
||||
rot = np.array([[np.cos(theta), -np.sin(theta), 0.0],
|
||||
[np.sin(theta), np.cos(theta), 0.0],
|
||||
[0.0, 0.0, 1.0]])
|
||||
x_rot = (x * 3.7) @ rot.T + np.array([12.0, -5.0, 4.0])
|
||||
d_rot = sel.stage1_descriptor(x_rot, t, f, n_samples=1024)
|
||||
self.assertTrue(sel.stage1_flagged(d_orig, d_rot))
|
||||
ov_dup = sel.stage2_overlap(d_orig['cloud'], d_rot['cloud'], max_pts=256)
|
||||
self.assertEqual(ov_dup['decision'], 'REJECT_NEAR_DUPLICATE')
|
||||
|
||||
# Distinct genus-1 ring -> rejected at Stage 1 (genus differs), and high overlap distance if Stage 2 run.
|
||||
xr, tr = holed_ring_mesh()
|
||||
d_ring = sel.stage1_descriptor(xr, tr, sel.exterior_faces(tr), n_samples=1024)
|
||||
self.assertFalse(sel.stage1_flagged(d_orig, d_ring))
|
||||
ov_diff = sel.stage2_overlap(d_orig['cloud'], d_ring['cloud'], max_pts=256)
|
||||
self.assertEqual(ov_diff['decision'], 'PASS')
|
||||
|
||||
def test_power_law_fallback_fit(self):
|
||||
vols = np.array([10.0, 25.0, 50.0, 120.0, 250.0])
|
||||
times = 0.015 * (vols ** 0.42)
|
||||
fit = sel.fit_power_law_fill_time(vols, times)
|
||||
self.assertAlmostEqual(fit['a'], 0.015, places=10)
|
||||
self.assertAlmostEqual(fit['b'], 0.42, places=10)
|
||||
self.assertEqual(len(fit['sha256']), 64)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main(verbosity=2)
|
||||
@@ -0,0 +1,362 @@
|
||||
"""Deterministic rules for WIN-TEST-SELECT-v1.1 + §7 (Horsea geometry screening).
|
||||
|
||||
Pure NumPy/stdlib implementation of the frozen selection logic:
|
||||
- Pool hashing and PCG64(SeedSequence(2026112301)) queue permutation
|
||||
- Uniform exterior surface gate draw (no thickness restriction, Gre24 §2 rule)
|
||||
- Geometry-only C1-C4 complexity metrics (interior Dw contrast, tortuosity,
|
||||
multi-branch superlevel/maxima, Euler genus and Di-vs-Df Spearman divergence)
|
||||
- Stage 1 global descriptor screen + Stage 2 24-symmetry PCA + bounded ICP
|
||||
near-duplicate check (symmetric Chamfer & 95th-percentile Hausdorff in Rg)
|
||||
- §7 multi-stratum precedence (4 -> 2 -> 3 -> 1) with 3 primary + 2 backup/stratum
|
||||
- §7.4 power-law fallback fit (fill_time = a * V^b) on learning parts only.
|
||||
|
||||
Code and synthetic CPU tests only; no real data reads or GPU/solver calls.
|
||||
"""
|
||||
import hashlib
|
||||
from itertools import permutations, product
|
||||
import json
|
||||
import numpy as np
|
||||
|
||||
SCREEN_SEED = 2026112301
|
||||
STRATA_ORDER = (4, 2, 3, 1)
|
||||
PRIMARY_PER_STRATUM = 3
|
||||
BACKUP_PER_STRATUM = 2
|
||||
|
||||
|
||||
def permute_pool(abc_ids, seed=SCREEN_SEED):
|
||||
"""Canonically sort ABC IDs, compute pool SHA-256, and permute once with PCG64."""
|
||||
canonical = sorted({str(x) for x in abc_ids})
|
||||
if not canonical:
|
||||
raise ValueError('Empty ABC candidate pool')
|
||||
pool_bytes = ('\n'.join(canonical) + '\n').encode('utf-8')
|
||||
pool_sha = hashlib.sha256(pool_bytes).hexdigest()
|
||||
rng = np.random.Generator(np.random.PCG64(np.random.SeedSequence(int(seed))))
|
||||
order = rng.permutation(len(canonical))
|
||||
return [canonical[int(i)] for i in order], pool_sha
|
||||
|
||||
|
||||
def exterior_faces(tetra):
|
||||
t = np.asarray(tetra, dtype=np.int64)
|
||||
faces = np.sort(t[:, 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 surface_euler_genus(faces):
|
||||
"""Compute surface Euler genus g = 1 - (V - E + F) / 2 for a single closed manifold."""
|
||||
f = np.asarray(faces, dtype=np.int64)
|
||||
if f.ndim != 2 or f.shape[1] != 3 or not len(f):
|
||||
raise ValueError('Invalid exterior triangle faces')
|
||||
verts = np.unique(f)
|
||||
edges = np.sort(np.vstack([f[:, [0, 1]], f[:, [1, 2]], f[:, [2, 0]]]), axis=1)
|
||||
edges, ecounts = np.unique(edges, axis=0, return_counts=True)
|
||||
if np.any(ecounts != 2):
|
||||
raise ValueError('Surface is not a closed watertight 2-manifold')
|
||||
chi = len(verts) - len(edges) + len(f)
|
||||
if (2 - chi) % 2 != 0:
|
||||
raise ValueError(f'Odd Euler characteristic {chi}')
|
||||
return int((2 - chi) // 2)
|
||||
|
||||
|
||||
def draw_gate_node(points, raw_ids, faces, abc_id_int, seed=SCREEN_SEED):
|
||||
"""Uniform random exterior surface node (no thickness filter, fixed seed)."""
|
||||
x = np.asarray(points, dtype=np.float64)
|
||||
raw = np.asarray(raw_ids, dtype=np.int64)
|
||||
surf_nodes = np.unique(np.asarray(faces, dtype=np.int64))
|
||||
if len(surf_nodes) == 0:
|
||||
raise ValueError('No exterior surface nodes')
|
||||
keys = [(int(raw[i]), float(x[i, 0]), float(x[i, 1]), float(x[i, 2]), int(i)) for i in surf_nodes]
|
||||
keys.sort()
|
||||
ordered = np.array([k[4] for k in keys], dtype=np.int64)
|
||||
rng = np.random.Generator(np.random.PCG64(np.random.SeedSequence([int(seed), int(abc_id_int)])))
|
||||
chosen_local = int(ordered[int(rng.integers(0, len(ordered)))])
|
||||
return chosen_local, int(raw[chosen_local])
|
||||
|
||||
|
||||
def _spearman(a, b):
|
||||
def _rank(v):
|
||||
order = np.argsort(v, kind='mergesort')
|
||||
ranks = np.empty(len(v), dtype=np.float64)
|
||||
sorted_v = v[order]
|
||||
i = 0
|
||||
while i < len(v):
|
||||
j = i + 1
|
||||
while j < len(v) and sorted_v[j] == sorted_v[i]:
|
||||
j += 1
|
||||
ranks[order[i:j]] = 0.5 * (i + j - 1)
|
||||
i = j
|
||||
return ranks
|
||||
|
||||
ra, rb = _rank(np.asarray(a, dtype=np.float64)), _rank(np.asarray(b, dtype=np.float64))
|
||||
ra -= ra.mean()
|
||||
rb -= rb.mean()
|
||||
denom = float(np.linalg.norm(ra) * np.linalg.norm(rb))
|
||||
return float(np.dot(ra, rb) / denom) if denom > 0 else 1.0
|
||||
|
||||
|
||||
def _superlevel_components(tetra, field, threshold):
|
||||
active = np.flatnonzero(field >= threshold)
|
||||
if len(active) == 0:
|
||||
return 0
|
||||
active_set = set(int(i) for i in active)
|
||||
parent = {i: i for i in active_set}
|
||||
|
||||
def find(u):
|
||||
while parent[u] != u:
|
||||
parent[u] = parent[parent[u]]
|
||||
u = parent[u]
|
||||
return u
|
||||
|
||||
for tet in np.asarray(tetra, dtype=np.int64):
|
||||
in_act = [int(v) for v in tet if int(v) in active_set]
|
||||
if len(in_act) >= 2:
|
||||
r0 = find(in_act[0])
|
||||
for v in in_act[1:]:
|
||||
rv = find(v)
|
||||
if rv != r0:
|
||||
parent[rv] = r0
|
||||
return len({find(u) for u in active_set})
|
||||
|
||||
|
||||
def complexity_metrics(points, tetra, dw, di, df, gate_local_idx, *, anchors):
|
||||
"""Compute geometry-only C1-C4 metrics and boolean eligibility against frozen anchors."""
|
||||
x = np.asarray(points, dtype=np.float64)
|
||||
t = np.asarray(tetra, dtype=np.int64)
|
||||
dw = np.asarray(dw, dtype=np.float64)
|
||||
di = np.asarray(di, dtype=np.float64)
|
||||
df = np.asarray(df, dtype=np.float64)
|
||||
faces = exterior_faces(t)
|
||||
genus = surface_euler_genus(faces)
|
||||
|
||||
# Interior Dw on non-wall nodes (fallback to tet-mean Dw if all nodes lie on wall).
|
||||
dw_int = dw[dw > 0]
|
||||
if len(dw_int) < 10:
|
||||
dw_int = dw[t].mean(axis=1)
|
||||
dw_int = dw_int[dw_int > 0]
|
||||
if len(dw_int) == 0:
|
||||
raise ValueError('No positive interior Dw values')
|
||||
p10, p50, p90 = np.quantile(dw_int, [0.10, 0.50, 0.90])
|
||||
r_th = float(p90 / p10) if p10 > 0 else float('inf')
|
||||
|
||||
far_idx = int(np.argmax(di))
|
||||
euclid = float(np.linalg.norm(x[far_idx] - x[int(gate_local_idx)]))
|
||||
di_max = float(di[far_idx])
|
||||
if euclid <= 0 or di_max <= 0:
|
||||
raise ValueError('Degenerate gate-to-farthest distance')
|
||||
tau_path = di_max / euclid
|
||||
|
||||
n_branch = _superlevel_components(t, di, 0.75 * di_max)
|
||||
rho_flow = 1.0 - _spearman(di, df)
|
||||
|
||||
c1 = r_th >= max(2.5, float(anchors['p75_r_th']))
|
||||
c2 = tau_path >= max(1.35, float(anchors['p75_tau_path']))
|
||||
c3 = n_branch >= 2
|
||||
c4 = (genus >= 1) or (rho_flow >= float(anchors['p75_rho_flow']))
|
||||
n_passed = int(c1) + int(c2) + int(c3) + int(c4)
|
||||
return dict(
|
||||
r_th=r_th, median_thickness=float(2.0 * p50), tau_path=tau_path,
|
||||
n_branch=int(n_branch), genus=genus, rho_flow=float(rho_flow),
|
||||
C1=bool(c1), C2=bool(c2), C3=bool(c3), C4=bool(c4),
|
||||
criteria_count=n_passed, eligible=(n_passed >= 2),
|
||||
)
|
||||
|
||||
|
||||
def matched_strata(metrics):
|
||||
"""Return all matched strata (1..4) for an eligible part."""
|
||||
if not metrics['eligible']:
|
||||
return []
|
||||
hits = []
|
||||
if metrics['C1'] and metrics['genus'] == 0:
|
||||
hits.append(1)
|
||||
if metrics['genus'] >= 1 and (metrics['C2'] or metrics['C4']):
|
||||
hits.append(2)
|
||||
if metrics['C2'] and metrics['C3']:
|
||||
hits.append(3)
|
||||
if metrics['criteria_count'] >= 3:
|
||||
hits.append(4)
|
||||
return sorted(hits)
|
||||
|
||||
|
||||
def assign_queue(records, *, primary_per_stratum=PRIMARY_PER_STRATUM, backup_per_stratum=BACKUP_PER_STRATUM):
|
||||
"""Apply §7.1 (4->2->3->1 first-open-slot) and §7.2 (3 primary + 2 backup per stratum)."""
|
||||
primary = {s: [] for s in (1, 2, 3, 4)}
|
||||
backup = {s: [] for s in (1, 2, 3, 4)}
|
||||
log = []
|
||||
|
||||
def primary_complete():
|
||||
return all(len(primary[s]) >= primary_per_stratum for s in (1, 2, 3, 4))
|
||||
|
||||
def all_complete():
|
||||
return primary_complete() and all(len(backup[s]) >= backup_per_stratum for s in (1, 2, 3, 4))
|
||||
|
||||
for rec in records:
|
||||
if all_complete():
|
||||
break
|
||||
cid = rec['abc_id']
|
||||
if rec.get('reject_reason'):
|
||||
log.append(dict(abc_id=cid, status='REJECTED', reason=rec['reject_reason']))
|
||||
continue
|
||||
hits = matched_strata(rec['metrics'])
|
||||
if not hits:
|
||||
log.append(dict(abc_id=cid, status='REJECTED', reason='NO_STRATUM_MATCH', matched_strata=[]))
|
||||
continue
|
||||
# Walk fixed precedence 4 -> 2 -> 3 -> 1 on primary slots first; once a stratum's primary
|
||||
# slots are full AND all 12 primary slots are filled (or per-stratum once primary complete),
|
||||
# fill backup slots in exact same queue order.
|
||||
assigned = None
|
||||
slot_type = None
|
||||
if not primary_complete():
|
||||
for s in STRATA_ORDER:
|
||||
if s in hits and len(primary[s]) < primary_per_stratum:
|
||||
assigned, slot_type = s, 'primary'
|
||||
primary[s].append(dict(abc_id=cid, stratum=s, matched_strata=hits, slot=len(primary[s]) + 1))
|
||||
break
|
||||
else:
|
||||
for s in STRATA_ORDER:
|
||||
if s in hits and len(backup[s]) < backup_per_stratum:
|
||||
assigned, slot_type = s, 'backup'
|
||||
backup[s].append(dict(abc_id=cid, stratum=s, matched_strata=hits, slot=len(backup[s]) + 1))
|
||||
break
|
||||
if assigned is None:
|
||||
log.append(dict(abc_id=cid, status='SKIPPED', reason='STRATUM_FULL', matched_strata=hits))
|
||||
else:
|
||||
log.append(dict(abc_id=cid, status='SELECTED', slot_type=slot_type,
|
||||
assigned_stratum=assigned, matched_strata=hits))
|
||||
return dict(primary=primary, backup=backup, log=log, complete=all_complete())
|
||||
|
||||
|
||||
def sample_surface_points(points, faces, n_samples=4096, seed=SCREEN_SEED):
|
||||
"""Deterministic area-weighted surface point cloud normalized to center=0, Rg=1."""
|
||||
x = np.asarray(points, dtype=np.float64)
|
||||
tris = x[np.asarray(faces, dtype=np.int64)]
|
||||
areas = 0.5 * np.linalg.norm(np.cross(tris[:, 1] - tris[:, 0], tris[:, 2] - tris[:, 0]), axis=1)
|
||||
if np.any(areas < 0) or areas.sum() <= 0:
|
||||
raise ValueError('Invalid surface area')
|
||||
probs = areas / areas.sum()
|
||||
rng = np.random.Generator(np.random.PCG64(np.random.SeedSequence(int(seed))))
|
||||
tri_idx = rng.choice(len(tris), size=int(n_samples), p=probs)
|
||||
u = np.sqrt(rng.random(int(n_samples)))
|
||||
v = rng.random(int(n_samples))
|
||||
chosen = tris[tri_idx]
|
||||
pts = (1.0 - u)[:, None] * chosen[:, 0] + (u * (1.0 - v))[:, None] * chosen[:, 1] + (u * v)[:, None] * chosen[:, 2]
|
||||
center = pts.mean(axis=0)
|
||||
centered = pts - center
|
||||
rg = float(np.sqrt(np.mean(np.sum(centered ** 2, axis=1))))
|
||||
if rg <= 0 or not np.isfinite(rg):
|
||||
raise ValueError('Degenerate surface cloud Rg')
|
||||
return centered / rg, float(areas.sum())
|
||||
|
||||
|
||||
def stage1_descriptor(points, tetra, faces, *, n_samples=4096, seed=SCREEN_SEED):
|
||||
"""Fast scale- and rigid-motion-invariant Stage 1 descriptor."""
|
||||
x = np.asarray(points, dtype=np.float64)
|
||||
t = np.asarray(tetra, dtype=np.int64)
|
||||
cells = x[t]
|
||||
vol = np.abs(np.linalg.det(cells[:, 1:] - cells[:, :1])) / 6.0
|
||||
total_vol = float(vol.sum())
|
||||
centers = cells.mean(axis=1)
|
||||
com = np.sum(centers * vol[:, None], axis=0) / total_vol
|
||||
rel = centers - com
|
||||
cov = np.einsum('n,ni,nj->ij', vol / total_vol, rel, rel)
|
||||
evals, evecs = np.linalg.eigh(cov)
|
||||
evals = np.maximum(evals[::-1], 0.0)
|
||||
evecs = evecs[:, ::-1]
|
||||
ratios = np.array([evals[1] / evals[0], evals[2] / evals[0]], dtype=np.float64) if evals[0] > 0 else np.zeros(2)
|
||||
proj = (x - com) @ evecs
|
||||
obb_vol = float(np.prod(proj.max(axis=0) - proj.min(axis=0)))
|
||||
fill_ratio = total_vol / obb_vol if obb_vol > 0 else 0.0
|
||||
cloud, area = sample_surface_points(x, faces, n_samples=n_samples, seed=seed)
|
||||
iso = float((area ** 3) / (total_vol ** 2))
|
||||
rng = np.random.Generator(np.random.PCG64(np.random.SeedSequence([int(seed), 2])))
|
||||
i1 = rng.integers(0, len(cloud), size=20000)
|
||||
i2 = rng.integers(0, len(cloud), size=20000)
|
||||
dists = np.linalg.norm(cloud[i1] - cloud[i2], axis=1)
|
||||
hist, _ = np.histogram(dists, bins=20, range=(0.0, 4.0))
|
||||
d2 = hist.astype(np.float64) / max(hist.sum(), 1)
|
||||
return dict(inertia_ratios=ratios, fill_ratio=fill_ratio, isoperimetric=iso,
|
||||
genus=surface_euler_genus(faces), d2=d2, cloud=cloud)
|
||||
|
||||
|
||||
def stage1_flagged(desc_a, desc_b):
|
||||
if desc_a['genus'] != desc_b['genus']:
|
||||
return False
|
||||
l1_d2 = float(np.abs(desc_a['d2'] - desc_b['d2']).sum())
|
||||
linf_inertia = float(np.abs(desc_a['inertia_ratios'] - desc_b['inertia_ratios']).max())
|
||||
return (l1_d2 < 0.12) and (linf_inertia < 0.10)
|
||||
|
||||
|
||||
def _nn_dists(a, b, chunk=256):
|
||||
out = np.empty(len(a), dtype=np.float64)
|
||||
b2 = np.sum(b * b, axis=1)[None, :]
|
||||
for lo in range(0, len(a), chunk):
|
||||
sub = a[lo:lo + chunk]
|
||||
d2 = np.maximum(np.sum(sub * sub, axis=1)[:, None] + b2 - 2.0 * (sub @ b.T), 0.0)
|
||||
out[lo:lo + chunk] = np.sqrt(d2.min(axis=1))
|
||||
return out
|
||||
|
||||
|
||||
def stage2_overlap(cloud_a, cloud_b, *, icp_iters=5, max_pts=512):
|
||||
"""24-symmetry PCA alignment + bounded ICP; returns (d_CD, d_H95, decision)."""
|
||||
a = np.asarray(cloud_a[:max_pts], dtype=np.float64)
|
||||
b = np.asarray(cloud_b[:max_pts], dtype=np.float64)
|
||||
_, va = np.linalg.eigh(a.T @ a / len(a))
|
||||
_, vb = np.linalg.eigh(b.T @ b / len(b))
|
||||
a_pca = a @ va[:, ::-1]
|
||||
b_pca = b @ vb[:, ::-1]
|
||||
best_cd, best_h95 = float('inf'), float('inf')
|
||||
best_aligned = a_pca
|
||||
# Test all 24 proper rotations of principal axes (permutations x signs with det = +1).
|
||||
for perm in permutations(range(3)):
|
||||
pmat = np.eye(3)[:, list(perm)]
|
||||
for signs in product((-1.0, 1.0), repeat=3):
|
||||
rmat = pmat * np.asarray(signs)[None, :]
|
||||
if np.linalg.det(rmat) < 0:
|
||||
continue
|
||||
cand = a_pca @ rmat
|
||||
da = _nn_dists(cand, b_pca)
|
||||
db = _nn_dists(b_pca, cand)
|
||||
cd = 0.5 * (float(da.mean()) + float(db.mean()))
|
||||
if cd < best_cd:
|
||||
best_cd = cd
|
||||
best_h95 = max(float(np.quantile(da, 0.95)), float(np.quantile(db, 0.95)))
|
||||
best_aligned = cand
|
||||
# Bounded rigid ICP refinement from best symmetry orientation.
|
||||
cur = best_aligned.copy()
|
||||
for _ in range(icp_iters):
|
||||
d2 = np.maximum(np.sum(cur * cur, axis=1)[:, None] + np.sum(b_pca * b_pca, axis=1)[None, :] - 2.0 * (cur @ b_pca.T), 0.0)
|
||||
nn_idx = np.argmin(d2, axis=1)
|
||||
tgt = b_pca[nn_idx]
|
||||
c_cur, c_tgt = cur.mean(axis=0), tgt.mean(axis=0)
|
||||
u, _, vt = np.linalg.svd((cur - c_cur).T @ (tgt - c_tgt))
|
||||
r = u @ vt
|
||||
if np.linalg.det(r) < 0:
|
||||
u[:, -1] *= -1.0
|
||||
r = u @ vt
|
||||
cur = (cur - c_cur) @ r + c_tgt
|
||||
da = _nn_dists(cur, b_pca)
|
||||
db = _nn_dists(b_pca, cur)
|
||||
d_cd = 0.5 * (float(da.mean()) + float(db.mean()))
|
||||
d_h95 = max(float(np.quantile(da, 0.95)), float(np.quantile(db, 0.95)))
|
||||
if d_cd < 0.05 or d_h95 < 0.12:
|
||||
decision = 'REJECT_NEAR_DUPLICATE'
|
||||
elif d_cd < 0.08:
|
||||
decision = 'BORDERLINE_LOG'
|
||||
else:
|
||||
decision = 'PASS'
|
||||
return dict(d_CD=d_cd, d_H95=d_h95, decision=decision)
|
||||
|
||||
|
||||
def fit_power_law_fill_time(volumes, fill_times):
|
||||
"""§7.4 fallback: OLS fit of log(t) = log(a) + b*log(V) on Greif fold-0 learning parts."""
|
||||
v = np.asarray(volumes, dtype=np.float64)
|
||||
t = np.asarray(fill_times, dtype=np.float64)
|
||||
if v.ndim != 1 or t.shape != v.shape or len(v) < 2 or not np.isfinite(v).all() or not np.isfinite(t).all() or np.any(v <= 0) or np.any(t <= 0):
|
||||
raise ValueError('Positive finite volumes and fill_times required')
|
||||
lv, lt = np.log(v), np.log(t)
|
||||
slope, intercept = np.polyfit(lv, lt, 1)
|
||||
a, b = float(np.exp(intercept)), float(slope)
|
||||
payload = dict(a=a, b=b, n_learning_parts=len(v))
|
||||
payload['sha256'] = hashlib.sha256(json.dumps(payload, sort_keys=True).encode('utf-8')).hexdigest()
|
||||
return payload
|
||||
Reference in new issue
Block a user