Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
01c1cc53fc | ||
|
|
91aeb2aed7 | ||
|
|
3db1079fd7 |
No files matched your search
@@ -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**.
|
||||
@@ -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