Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
01c1cc53fc | ||
|
|
91aeb2aed7 | ||
|
|
3db1079fd7 |
No files matched your search
@@ -1,30 +0,0 @@
|
||||
# Transolver-Greif Adapter (`TRANSOLVER-ADAPTER-1122`)
|
||||
|
||||
Code-only Transolver (Wu et al., ICML 2024) adapter aligned with the frozen grouped Greif v5 comparison protocol (`18e0e729`). No real data read, no GPU run, no push to `main`.
|
||||
|
||||
## Files
|
||||
- `tools/track_b_transolver_greif_adapter.py`: `GreifTransolver`, `TransolverBlock`, `PhysicsAttention`, `make_greif_transolver`, and pure-array input helpers.
|
||||
- `tools/test_track_b_transolver_greif.py`: CPU-only synthetic tet-mesh unit tests.
|
||||
|
||||
## Protocol Alignment
|
||||
- **Inputs:** Exact 19 `COLUMNS` from `track_b_gino_greif_adapter.py` (no extra `xyz` channels), standardized in FP64 on each fold's learning split only (`phase2_h2_data.standardization`), cast to FP32, plus strictly positive FP32 nodal `mass` and optional `component_ids`.
|
||||
- **Target & Decode:** Exact `phase2_residual_math` FP64 volume-clock prior `c * Vf`, signed unclamped FP32 `residual_target`, and `decode_seconds`. Readout head final layer is zero-initialized so epoch 0 starts at `c * Vf`.
|
||||
- **Loss & Schedule:** Reuses `phase2_h2_model.{weighted_loss, optimizer, lr_epoch}` (node-equal FP32 MSE, AdamW `wd=1e-4` on >=2D non-bias, 10-epoch warmup + 190-epoch cosine, grad clip 1.0, TF32 off).
|
||||
- **Folds:** Unchanged grouped folds 0/1 (`((0,0),(0,1),(1,0),(1,1))`, family isolation, `no_validation_selection=True`).
|
||||
|
||||
## Parameter Counts
|
||||
| Model | Config | Parameters |
|
||||
| --- | --- | ---: |
|
||||
| `H2Geo` (reference) | `C=64, 4 GeoBlocks` | 195,077 |
|
||||
| `GreifTransolver` (`default`) | `C=64, L=6, H=4, G=64, mlp_ratio=2` | 197,913 |
|
||||
| `GreifTransolver` (`wide` flag) | `C=96, L=4, H=4, G=64, mlp_ratio=2` | 293,937 |
|
||||
|
||||
## Design Assumptions
|
||||
1. **Mass-weighted slice pooling (`mass_weighted=True`, default):** Nodal mass is normalized per connected component (`m / sum(m)`) before slice pooling so attention tokens are invariant to global mass units and reflect tet volume measure. `mass_weighted=False` reproduces unweighted Transolver.
|
||||
2. **Per-component isolation & chunking:** Slices are pooled per physical connected component (matching `H2Geo.global_message`) in `NODE_CHUNK=8192` chunks with optional block gradient checkpointing to bound VRAM on 30K–100K+ node tet meshes.
|
||||
3. **Slice denominator & temperature stability:** Per-head temperature is clamped to `[0.1, 5.0]` and normalized slice denominators add `1e-6` (`1e-5` unweighted) to prevent FP32 division instability.
|
||||
|
||||
## Open Items for MeltSol / MeltAssist
|
||||
1. **Execution binding & worker:** This branch provides only the model adapter and CPU synthetic tests; MeltSol should wire `GreifTransolver` into a guarded fold-0/1 worker/entry (same `first`-epoch cost gate and <= 40,000 GPU-s GPU3 cap as planned) for MeltAssist review.
|
||||
2. **Checkpoint / VRAM profiling on real meshes:** Verify `NODE_CHUNK=8192` and `checkpoint_blocks=True` peak VRAM on the largest Greif learning part during the first measured epoch.
|
||||
3. **Optional ablation:** Confirm whether only `default` (197.9K, `mass_weighted=True`) runs in the primary <= 40,000 GPU-s slot, leaving `wide` and `mass_weighted=False` out of scope.
|
||||
@@ -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,155 +0,0 @@
|
||||
"""CPU-only synthetic tests for track_b_transolver_greif_adapter (no real data, no GPU)."""
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import phase2_h2_model as h2
|
||||
import track_b_gino_greif_adapter as gino
|
||||
import track_b_transolver_greif_adapter as tv
|
||||
|
||||
|
||||
def synthetic_tet_part(seed, nx=4, ny=4, nz=3, second_component=False):
|
||||
"""Build a synthetic 3D tet mesh with lumped positive nodal masses and 19 features."""
|
||||
rng = np.random.default_rng(seed)
|
||||
xs, ys, zs = np.meshgrid(np.linspace(0.0, 1.0, nx), np.linspace(0.0, 0.8, ny), np.linspace(0.0, 0.4, nz), indexing='ij')
|
||||
pts = np.column_stack([xs.ravel(), ys.ravel(), zs.ravel()])
|
||||
pts += rng.normal(0.0, 0.01, size=pts.shape)
|
||||
n0 = len(pts)
|
||||
idx = np.arange(n0).reshape(nx, ny, nz)
|
||||
tets = []
|
||||
for i in range(nx - 1):
|
||||
for j in range(ny - 1):
|
||||
for k in range(nz - 1):
|
||||
c = [idx[i + a, j + b, k + c_] for a in (0, 1) for b in (0, 1) for c_ in (0, 1)]
|
||||
for t in ((0, 1, 3, 7), (0, 1, 5, 7), (0, 4, 5, 7), (0, 2, 3, 7), (0, 2, 6, 7), (0, 4, 6, 7)):
|
||||
tets.append([c[p] for p in t])
|
||||
tets = np.asarray(tets, dtype=np.int64)
|
||||
comp = np.zeros(n0, dtype=np.int64)
|
||||
if second_component:
|
||||
pts2 = pts[:12] + np.array([2.0, 0.0, 0.0])
|
||||
pts = np.vstack([pts, pts2])
|
||||
extra = np.array([[n0 + i, n0 + i + 1, n0 + i + 2, n0 + i + 3] for i in range(0, 9, 3)], dtype=np.int64)
|
||||
tets = np.vstack([tets, extra])
|
||||
comp = np.concatenate([comp, np.ones(len(pts2), dtype=np.int64)])
|
||||
n = len(pts)
|
||||
mass = np.zeros(n, dtype=np.float64)
|
||||
v0, v1, v2, v3 = pts[tets[:, 0]], pts[tets[:, 1]], pts[tets[:, 2]], pts[tets[:, 3]]
|
||||
vol = np.abs(np.einsum('ij,ij->i', v1 - v0, np.cross(v2 - v0, v3 - v0))) / 6.0
|
||||
vol = np.maximum(vol, 1e-6)
|
||||
for corner in range(4):
|
||||
np.add.at(mass, tets[:, corner], vol / 4.0)
|
||||
mass = np.maximum(mass, 1e-7)
|
||||
vf = np.clip(np.argsort(np.argsort(pts[:, 0])).astype(np.float64) / max(n - 1, 1), 0.0, 1.0)
|
||||
feats = rng.normal(0.0, 1.0, size=(n, len(tv.COLUMNS))).astype(np.float64)
|
||||
feats[:, 0] = vf
|
||||
target_star = np.clip(0.95 * vf + 0.05 * rng.normal(size=n), 0.0, None)
|
||||
return dict(points=pts, tets=tets, mass=mass, features=feats, Vf=vf, target_star=target_star, component_ids=comp)
|
||||
|
||||
|
||||
class TestTransolverGreifAdapter(unittest.TestCase):
|
||||
def setUp(self):
|
||||
torch.set_num_threads(1)
|
||||
self.parts = [synthetic_tet_part(10 + i, second_component=(i == 1)) for i in range(2)]
|
||||
self.stats = tv.standardize_learning_arrays([p['features'] for p in self.parts])
|
||||
self.clock = tv.learning_clock([0.96, 1.02], ['fam_a', 'fam_b'])
|
||||
|
||||
def test_interface_and_parameter_counts(self):
|
||||
self.assertEqual(len(tv.COLUMNS), 19)
|
||||
self.assertEqual(tv.COLUMNS, gino.COLUMNS)
|
||||
h2_params = tv.count_parameters(h2.H2Geo())
|
||||
default_params = tv.count_parameters(tv.make_greif_transolver('default'))
|
||||
wide_params = tv.count_parameters(tv.make_greif_transolver('wide'))
|
||||
unweighted_params = tv.count_parameters(tv.make_greif_transolver('default', mass_weighted=False))
|
||||
self.assertEqual(h2_params, 195077)
|
||||
self.assertEqual(default_params, 197913)
|
||||
self.assertEqual(wide_params, 293937)
|
||||
self.assertEqual(unweighted_params, default_params)
|
||||
|
||||
def test_zero_init_starts_at_exact_volume_clock_prior(self):
|
||||
torch.manual_seed(0)
|
||||
model = tv.make_greif_transolver('default')
|
||||
p = self.parts[0]
|
||||
x, m, comp = tv.prepare_inputs(p['features'], p['mass'], self.stats, p['component_ids'])
|
||||
pred = model(x, m, comp, checkpoint_blocks=False)
|
||||
self.assertEqual(pred.shape, (len(p['mass']),))
|
||||
self.assertEqual(pred.dtype, torch.float32)
|
||||
self.assertTrue(torch.allclose(pred, torch.zeros_like(pred), atol=0.0))
|
||||
decoded = tv.decode_seconds(pred.detach().numpy(), p['Vf'], self.clock, t_set=2.5)
|
||||
expected = tv.prior(p['Vf'], self.clock) * 2.5
|
||||
np.testing.assert_allclose(decoded, expected, rtol=0.0, atol=1e-12)
|
||||
|
||||
def test_forward_backward_step_and_multicomponent(self):
|
||||
torch.manual_seed(7)
|
||||
model = tv.make_greif_transolver('default')
|
||||
opt = tv.optimizer(model)
|
||||
total_nodes = sum(len(p['mass']) for p in self.parts)
|
||||
for p in self.parts:
|
||||
x, m, comp = tv.prepare_inputs(p['features'], p['mass'], self.stats, p['component_ids'])
|
||||
target = torch.from_numpy(tv.residual_target(p['target_star'], p['Vf'], self.clock, fit_dtype='float32'))
|
||||
opt.zero_grad(set_to_none=True)
|
||||
pred = model(x, m, comp, node_chunk=17, checkpoint_blocks=True)
|
||||
loss = tv.weighted_loss(pred, target, len(self.parts), len(m), total_nodes)
|
||||
self.assertTrue(bool(torch.isfinite(loss)))
|
||||
loss.backward()
|
||||
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0, error_if_nonfinite=True)
|
||||
opt.step()
|
||||
self.assertTrue(all(bool(torch.isfinite(v).all()) for v in model.parameters()))
|
||||
# After 1 step, head output moves away from zero and gradients reached encoder + physics slices.
|
||||
self.assertGreater(float(model.head[-1].weight.detach().abs().max()), 0.0)
|
||||
x, m, comp = tv.prepare_inputs(self.parts[1]['features'], self.parts[1]['mass'], self.stats, self.parts[1]['component_ids'])
|
||||
out = model(x, m, comp, checkpoint_blocks=False)
|
||||
out.sum().backward()
|
||||
self.assertGreater(float(model.encoder[0].weight.grad.abs().max()), 0.0)
|
||||
self.assertGreater(float(model.blocks[0].attn.in_project_slice.weight.grad.abs().max()), 0.0)
|
||||
|
||||
def test_determinism_chunk_invariance_and_mass_scale_invariance(self):
|
||||
p = self.parts[1]
|
||||
x, m, comp = tv.prepare_inputs(p['features'], p['mass'], self.stats, p['component_ids'])
|
||||
target = torch.from_numpy(tv.residual_target(p['target_star'], p['Vf'], self.clock, fit_dtype='float32'))
|
||||
|
||||
def run_once(chunk, mass_scale=1.0):
|
||||
torch.manual_seed(1234)
|
||||
model = tv.make_greif_transolver('default')
|
||||
opt = tv.optimizer(model)
|
||||
for _ in range(2):
|
||||
opt.zero_grad(set_to_none=True)
|
||||
pred = model(x, m * mass_scale, comp, node_chunk=chunk, checkpoint_blocks=False)
|
||||
loss = tv.weighted_loss(pred, target, 1, len(m), len(m))
|
||||
loss.backward()
|
||||
opt.step()
|
||||
model.eval()
|
||||
with torch.no_grad():
|
||||
return model(x, m * mass_scale, comp, node_chunk=chunk, checkpoint_blocks=False)
|
||||
|
||||
a = run_once(chunk=tv.NODE_CHUNK)
|
||||
b = run_once(chunk=tv.NODE_CHUNK)
|
||||
c = run_once(chunk=13)
|
||||
d = run_once(chunk=tv.NODE_CHUNK, mass_scale=1e-4)
|
||||
self.assertTrue(torch.equal(a, b))
|
||||
self.assertTrue(torch.allclose(a, c, atol=1e-6, rtol=1e-5))
|
||||
self.assertTrue(torch.allclose(a, d, atol=1e-6, rtol=1e-5))
|
||||
|
||||
def test_input_guards(self):
|
||||
model = tv.make_greif_transolver('default')
|
||||
p = self.parts[0]
|
||||
x, m, comp = tv.prepare_inputs(p['features'], p['mass'], self.stats, p['component_ids'])
|
||||
with self.assertRaises(ValueError):
|
||||
model(x[:, :18], m, comp)
|
||||
with self.assertRaises(ValueError):
|
||||
model(x.double(), m, comp)
|
||||
bad_m = m.clone()
|
||||
bad_m[0] = 0.0
|
||||
with self.assertRaises(ValueError):
|
||||
model(x, bad_m, comp)
|
||||
bad_x = x.clone()
|
||||
bad_x[0, 0] = float('nan')
|
||||
with self.assertRaises(ValueError):
|
||||
model(bad_x, m, comp)
|
||||
|
||||
|
||||
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)
|
||||
@@ -1,204 +0,0 @@
|
||||
"""Transolver (Wu et al., ICML 2024) adapter for grouped Greif fill-time comparison.
|
||||
|
||||
Pure unstructured-node Physics-Attention model matching H2Geo and GreifGINO:
|
||||
exact 19 standardized FP32 inputs, positive nodal mass, FP64 volume-clock
|
||||
residual target/decode, and zero-initialized readout starting at the c*Vf prior.
|
||||
Code only: no real-data I/O, no GPU launch, no external checkpoint access.
|
||||
"""
|
||||
import math
|
||||
import numpy as np
|
||||
import torch
|
||||
from torch import nn
|
||||
from torch.utils.checkpoint import checkpoint
|
||||
|
||||
from phase2_h2_model import lr_epoch, optimizer, weighted_loss
|
||||
from phase2_residual_math import decode_seconds, learning_clock, prior, residual_target
|
||||
from track_b_gino_greif_adapter import COLUMNS
|
||||
|
||||
NODE_CHUNK = 8192
|
||||
TEMP_MIN = 0.1
|
||||
TEMP_MAX = 5.0
|
||||
MASS_EPS = 1e-6
|
||||
UNWEIGHTED_EPS = 1e-5
|
||||
VARIANTS = {
|
||||
'default': dict(dim=64, depth=6, heads=4, slices=64, mlp_ratio=2),
|
||||
'wide': dict(dim=96, depth=4, heads=4, slices=64, mlp_ratio=2),
|
||||
}
|
||||
|
||||
|
||||
def count_parameters(model):
|
||||
return sum(p.numel() for p in model.parameters())
|
||||
|
||||
|
||||
def standardize_learning_arrays(feature_arrays):
|
||||
"""FP64 online population mean/std over learning parts only (matches phase2_h2_data)."""
|
||||
n = 0
|
||||
mean = np.zeros(len(COLUMNS), dtype=np.float64)
|
||||
m2 = np.zeros(len(COLUMNS), dtype=np.float64)
|
||||
for arr in feature_arrays:
|
||||
x = np.asarray(arr, dtype=np.float64)
|
||||
if x.ndim != 2 or x.shape[1] != len(COLUMNS) or len(x) == 0 or not np.isfinite(x).all():
|
||||
raise ValueError('Invalid learning feature array')
|
||||
k = len(x)
|
||||
avg = x.mean(axis=0)
|
||||
delta = avg - mean
|
||||
m2 += np.square(x - avg).sum(axis=0) + delta * delta * (n * k / (n + k))
|
||||
mean += delta * (k / (n + k))
|
||||
n += k
|
||||
if n == 0:
|
||||
raise ValueError('Empty learning set')
|
||||
std = np.sqrt(m2 / n)
|
||||
scale = np.where(std == 0.0, 1.0, std)
|
||||
return dict(mean=mean.tolist(), scale=scale.tolist(), population_std=std.tolist(), nodes=n)
|
||||
|
||||
|
||||
def prepare_inputs(features, mass, stats, component_ids=None):
|
||||
"""Standardize 19 columns in FP64 -> FP32 and validate positive mass and components."""
|
||||
feat = np.asarray(features, dtype=np.float64)
|
||||
m = np.asarray(mass, dtype=np.float64)
|
||||
if feat.ndim != 2 or feat.shape[1] != len(COLUMNS) or len(feat) == 0:
|
||||
raise ValueError('Expected nonempty (N, 19) feature matrix matching COLUMNS')
|
||||
if m.shape != (len(feat),) or not np.isfinite(m).all() or np.any(m <= 0):
|
||||
raise ValueError('Expected finite strictly positive nodal mass')
|
||||
x = ((feat - np.asarray(stats['mean'], np.float64)) / np.asarray(stats['scale'], np.float64)).astype(np.float32)
|
||||
if not np.isfinite(x).all():
|
||||
raise ValueError('Nonfinite standardized features')
|
||||
if component_ids is None:
|
||||
comp = np.zeros(len(feat), dtype=np.int64)
|
||||
else:
|
||||
comp = np.asarray(component_ids, dtype=np.int64)
|
||||
if comp.shape != (len(feat),):
|
||||
raise ValueError('component_ids shape mismatch')
|
||||
return torch.from_numpy(x), torch.from_numpy(m.astype(np.float32)), torch.from_numpy(comp)
|
||||
|
||||
|
||||
class PhysicsAttention(nn.Module):
|
||||
"""Chunked multi-head Physics-Attention over learned slices (Wu et al., ICML 2024)."""
|
||||
|
||||
def __init__(self, dim=64, heads=4, slices=64, mass_weighted=True):
|
||||
super().__init__()
|
||||
if dim % heads != 0 or slices <= 0:
|
||||
raise ValueError('dim must be divisible by heads and slices > 0')
|
||||
self.dim = dim
|
||||
self.heads = heads
|
||||
self.head_dim = dim // heads
|
||||
self.slices = slices
|
||||
self.mass_weighted = bool(mass_weighted)
|
||||
self.scale = self.head_dim ** -0.5
|
||||
|
||||
self.in_project_x = nn.Linear(dim, dim)
|
||||
self.in_project_fx = nn.Linear(dim, dim)
|
||||
self.in_project_slice = nn.Linear(self.head_dim, slices)
|
||||
nn.init.orthogonal_(self.in_project_slice.weight)
|
||||
self.temperature = nn.Parameter(torch.full((1, heads, 1), 0.5))
|
||||
self.to_q = nn.Linear(self.head_dim, self.head_dim, bias=False)
|
||||
self.to_k = nn.Linear(self.head_dim, self.head_dim, bias=False)
|
||||
self.to_v = nn.Linear(self.head_dim, self.head_dim, bias=False)
|
||||
self.to_out = nn.Linear(dim, dim)
|
||||
|
||||
def forward(self, h, m, components, node_chunk):
|
||||
out = h.new_zeros(h.shape)
|
||||
temp = torch.clamp(self.temperature, min=TEMP_MIN, max=TEMP_MAX)
|
||||
eps = MASS_EPS if self.mass_weighted else UNWEIGHTED_EPS
|
||||
for ids in components:
|
||||
m_comp = m[ids]
|
||||
m_sum = m_comp.sum()
|
||||
if not bool(torch.isfinite(m_sum)) or float(m_sum) <= 0.0:
|
||||
raise ValueError('Invalid component mass sum')
|
||||
m_norm = m_comp / m_sum
|
||||
num = h.new_zeros((self.heads, self.slices, self.head_dim))
|
||||
den = h.new_zeros((self.heads, self.slices))
|
||||
chunks = []
|
||||
for lo in range(0, len(ids), node_chunk):
|
||||
hi = lo + node_chunk
|
||||
ix = ids[lo:hi]
|
||||
hh = h[ix]
|
||||
x_mid = self.in_project_x(hh).view(-1, self.heads, self.head_dim)
|
||||
fx_mid = self.in_project_fx(hh).view(-1, self.heads, self.head_dim)
|
||||
w = torch.softmax(self.in_project_slice(x_mid) / temp, dim=-1)
|
||||
weight = w * m_norm[lo:hi, None, None] if self.mass_weighted else w
|
||||
num = num + torch.einsum('nhg,nhd->hgd', weight, fx_mid)
|
||||
den = den + weight.sum(dim=0)
|
||||
chunks.append((ix, w))
|
||||
if not bool(torch.isfinite(den).all()):
|
||||
raise ValueError('Nonfinite physics-slice denominator')
|
||||
tokens = num / (den.unsqueeze(-1) + eps)
|
||||
q, k, v = self.to_q(tokens), self.to_k(tokens), self.to_v(tokens)
|
||||
attn = torch.softmax(torch.matmul(q, k.transpose(-2, -1)) * self.scale, dim=-1)
|
||||
z = torch.matmul(attn, v)
|
||||
for ix, w in chunks:
|
||||
desliced = torch.einsum('nhg,hgd->nhd', w, z).reshape(-1, self.dim)
|
||||
out.index_copy_(0, ix, self.to_out(desliced))
|
||||
return out
|
||||
|
||||
|
||||
class TransolverBlock(nn.Module):
|
||||
def __init__(self, dim=64, heads=4, slices=64, mlp_ratio=2, mass_weighted=True):
|
||||
super().__init__()
|
||||
self.attn_norm = nn.LayerNorm(dim)
|
||||
self.attn = PhysicsAttention(dim=dim, heads=heads, slices=slices, mass_weighted=mass_weighted)
|
||||
self.ffn_norm = nn.LayerNorm(dim)
|
||||
self.ffn = nn.Sequential(nn.Linear(dim, dim * mlp_ratio), nn.GELU(), nn.Linear(dim * mlp_ratio, dim))
|
||||
|
||||
def forward(self, h, m, components, node_chunk):
|
||||
h = h + self.attn(self.attn_norm(h), m, components, node_chunk)
|
||||
return h + self.ffn(self.ffn_norm(h))
|
||||
|
||||
|
||||
class GreifTransolver(nn.Module):
|
||||
"""Per-part Transolver residual regressor aligned with H2Geo and GreifGINO."""
|
||||
|
||||
def __init__(self, dim=64, depth=6, heads=4, slices=64, mlp_ratio=2, mass_weighted=True):
|
||||
super().__init__()
|
||||
self.dim = dim
|
||||
self.depth = depth
|
||||
self.heads = heads
|
||||
self.slices = slices
|
||||
self.mlp_ratio = mlp_ratio
|
||||
self.mass_weighted = bool(mass_weighted)
|
||||
self.encoder = nn.Sequential(nn.Linear(len(COLUMNS), dim), nn.GELU(), nn.Linear(dim, dim))
|
||||
self.blocks = nn.ModuleList([
|
||||
TransolverBlock(dim=dim, heads=heads, slices=slices, mlp_ratio=mlp_ratio, mass_weighted=mass_weighted)
|
||||
for _ in range(depth)
|
||||
])
|
||||
self.head = nn.Sequential(nn.Linear(dim + len(COLUMNS), 64), nn.GELU(), nn.Linear(64, 1))
|
||||
nn.init.zeros_(self.head[-1].weight)
|
||||
nn.init.zeros_(self.head[-1].bias)
|
||||
|
||||
def forward(self, x, m, component_ids=None, *, node_chunk=NODE_CHUNK, checkpoint_blocks=True):
|
||||
if x.ndim != 2 or x.shape[1] != len(COLUMNS) or len(x) == 0:
|
||||
raise ValueError('Expected nonempty (N, 19) FP32 features')
|
||||
if x.dtype != torch.float32 or m.dtype != torch.float32:
|
||||
raise ValueError('Only FP32 features and mass are supported')
|
||||
if m.shape != (len(x),) or not bool(torch.isfinite(x).all()) or not bool(torch.isfinite(m).all()) or bool((m <= 0).any()):
|
||||
raise ValueError('Invalid features or nonpositive nodal mass')
|
||||
if component_ids is None:
|
||||
components = [torch.arange(len(x), device=x.device, dtype=torch.long)]
|
||||
else:
|
||||
if component_ids.shape != (len(x),) or component_ids.dtype not in (torch.int32, torch.int64):
|
||||
raise ValueError('component_ids must be 1D integer tensor matching nodes')
|
||||
components = [torch.nonzero(component_ids == c, as_tuple=True)[0] for c in torch.unique(component_ids)]
|
||||
h = self.encoder(x)
|
||||
for block in self.blocks:
|
||||
def run(v, b=block):
|
||||
return b(v, m, components, node_chunk)
|
||||
if checkpoint_blocks and self.training and torch.is_grad_enabled():
|
||||
h = checkpoint(run, h, use_reentrant=False, preserve_rng_state=False)
|
||||
else:
|
||||
h = run(h)
|
||||
outputs = [self.head(torch.cat((h[lo:lo + node_chunk], x[lo:lo + node_chunk]), dim=-1))[:, 0]
|
||||
for lo in range(0, len(x), node_chunk)]
|
||||
return torch.cat(outputs)
|
||||
|
||||
|
||||
def make_greif_transolver(variant='default', *, mass_weighted=True):
|
||||
if variant not in VARIANTS:
|
||||
raise ValueError(f'Unknown variant: {variant}')
|
||||
return GreifTransolver(**VARIANTS[variant], mass_weighted=mass_weighted)
|
||||
|
||||
|
||||
__all__ = [
|
||||
'COLUMNS', 'NODE_CHUNK', 'VARIANTS', 'GreifTransolver', 'PhysicsAttention', 'TransolverBlock',
|
||||
'count_parameters', 'decode_seconds', 'learning_clock', 'lr_epoch', 'make_greif_transolver',
|
||||
'optimizer', 'prepare_inputs', 'prior', 'residual_target', 'standardize_learning_arrays', 'weighted_loss',
|
||||
]
|
||||
@@ -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