363 lines
15 KiB
Python
363 lines
15 KiB
Python
"""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
|