Implement Gre24 reproduction and freeze v5 preparation evidence

This commit is contained in:
Frank14f committed 2026-11-15 23:28:33 +08:00
1 parent baf2ac8145
commit 8409910b1e
49 files changed
+30910

No files matched your search

+199
View File
@@ -0,0 +1,199 @@
"""Gre24 fill-time reproduction; explicit R1 choices, no fitted state or labels.
Author method and our discretisation choices are kept distinct in receipts.
This module never changes the historical R2-G24 approximation.
"""
from itertools import combinations
import time
import numpy as np
from sklearn.neighbors import BallTree
from boundary_distance import SurfaceDistance
COLUMNS = ('Vf', 'grad_Vf_x', 'grad_Vf_y', 'grad_Vf_z', 'Di_star',
'grad_Di_x', 'grad_Di_y', 'grad_Di_z', 'Dw', 'Dw_star',
'grad_Dw_x', 'grad_Dw_y', 'grad_Dw_z',
'Sxx', 'Sxy', 'Sxz', 'Syy', 'Syz', 'Szz')
def mesh(points, tetra):
x = np.asarray(points, dtype=np.float64)
t = np.asarray(tetra)
if x.ndim != 2 or x.shape[1] != 3 or not np.isfinite(x).all():
raise ValueError('Invalid points')
if t.ndim != 2 or t.shape[1] != 4 or t.dtype.kind not in 'iu' or not len(t):
raise ValueError('Invalid tetrahedra')
if t.min() < 0 or t.max() >= len(x) or not np.array_equal(np.unique(t), np.arange(len(x))):
raise ValueError('Tet domain must explicitly contain every supplied node')
t = np.asarray(t, dtype=np.int32)
cells = x[t]
matrix = cells[:, 1:] - cells[:, :1]
volume = np.abs(np.linalg.det(matrix)) / 6
if not np.isfinite(volume).all() or np.any(volume <= 0):
raise ValueError('Nonpositive tetrahedron volume')
mass = np.bincount(t.ravel(), weights=np.repeat(volume / 4, 4), minlength=len(x))
hmax = max(float(np.linalg.norm(cells[:, i]-cells[:, j], axis=1).max())
for i, j in combinations(range(4), 2))
return dict(x=x, t=t, matrix=matrix, volume=volume, mass=mass,
centers=cells.mean(1), hmax=hmax)
def exterior_faces(tetra):
faces = np.sort(tetra[:, np.array([[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]])].reshape(-1, 3), axis=1)
faces, counts = np.unique(faces, axis=0, return_counts=True)
if np.any(counts > 2):
raise ValueError('Nonmanifold tetrahedron faces')
return faces[counts == 1]
def gate_nodes(x, raw_ids, gate, marked=None):
raw_ids = np.asarray(raw_ids)
if len(raw_ids) != len(x) or len(np.unique(raw_ids)) != len(x):
raise ValueError('Invalid original node IDs')
if marked is not None:
marked = np.asarray(marked, dtype=np.int64)
if not len(marked) or marked.min() < 0 or marked.max() >= len(x):
raise ValueError('Invalid explicit inlet node set')
return np.unique(marked), 'explicit_marked_nodes'
gate = np.asarray(gate, dtype=float)
if gate.shape != (3,) or not np.isfinite(gate).all():
raise ValueError('Invalid inlet location')
d2 = np.sum((x-gate)**2, axis=1)
tied = np.flatnonzero(d2 == d2.min())
return np.array([tied[np.argmin(raw_ids[tied])]]), 'nearest_tet_node_min_original_id_tie'
def solve_eikonal(g, sources, speed, max_iterations=100000):
from fimpy.solver import create_fim_solver
speed = np.broadcast_to(np.asarray(speed, dtype=float), (len(g['t']),))
if not np.isfinite(speed).all() or np.any(speed <= 0):
raise ValueError('Nonpositive or nonfinite cell speed; no epsilon replacement')
metric = speed[:, None, None]**2 * np.eye(3)[None]
# Preserve upstream SPD check rather than silently weakening its threshold.
solver = create_fim_solver(g['x'], g['t'], metric, precision=np.float64,
device='cpu', use_active_list=True)
phi = solver.comp_fim(np.asarray(sources, dtype=np.int32), np.zeros(len(sources)),
max_iterations=max_iterations)
if np.any(solver.active_list):
raise RuntimeError('tetFIM iteration limit with active nodes')
if not np.isfinite(phi).all() or np.any(phi < 0) or np.any(phi >= solver.undef_val):
raise ValueError('Nonfinite, negative or unreached eikonal node')
if np.any(phi[sources] != 0):
raise ValueError('Eikonal source values changed')
return phi.copy()
def cell_flow_speed(g, dw, wall_faces):
if not np.isfinite(dw).all() or np.any(dw < 0):
raise ValueError('Invalid wall field')
speed = dw[g['t']].mean(1)
zero = np.flatnonzero(np.all(dw[g['t']] == 0, axis=1))
if len(zero):
surface = SurfaceDistance(g['x'][wall_faces])
speed[zero] = surface.query(g['centers'][zero])
if not np.isfinite(speed).all() or np.any(speed <= 0):
raise ValueError('Nonpositive flow speed after declared all-wall supplement')
return speed, zero
def strict_volume_cdf(field, mass):
d = np.asarray(field, dtype=float); w = np.asarray(mass, dtype=float)
if d.ndim != 1 or w.shape != d.shape or not len(d) or not np.isfinite(d).all() or not np.isfinite(w).all() or np.any(w <= 0):
raise ValueError('Invalid lumped-volume CDF')
order = np.argsort(d, kind='stable')
prefix = np.r_[0., np.cumsum(w[order], dtype=np.float64)]
return prefix[np.searchsorted(d[order], d, side='left')] / w.sum()
def nodal_gradient(g, values, normalize=True):
v = np.asarray(values, dtype=float)
if v.shape != (len(g['x']),) or not np.isfinite(v).all():
raise ValueError('Invalid nodal scalar')
t = g['t']
cell_grad = np.linalg.solve(g['matrix'], (v[t[:, 1:]]-v[t[:, :1]])[..., None])[..., 0]
grad = np.zeros((len(v), 3))
for k in range(4):
np.add.at(grad, t[:, k], cell_grad*g['volume'][:, None])
grad /= 4*g['mass'][:, None]
if normalize:
norm = np.linalg.norm(grad, axis=1)
np.divide(grad, norm[:, None], out=grad, where=norm[:, None] > 0)
return grad
def spatial_moment(g, di, progress=lambda *a, **kw: None):
radius = 3*g['hmax']; centers = g['centers']; cell_di = di[g['t']].mean(1)
tree = BallTree(centers); result = np.empty((len(di), 6)); coincident = 0
for i, p in enumerate(g['x']):
ids = tree.query_radius(p[None], r=radius)[0]
delta = centers[ids]-p; dist = np.linalg.norm(delta, axis=1)
selected = (dist < radius) & (np.abs(cell_di[ids]-di[i]) < radius)
coincident += int(np.sum(selected & (dist == 0)))
selected &= dist > 0
ids = ids[selected]; delta = delta[selected]; dist = dist[selected]
if not len(ids):
raise ValueError(f'Empty moment neighbourhood at node {i}')
direction = delta/dist[:, None]
weight = g['volume'][ids]; weight = weight/weight.sum()
tensor = np.einsum('n,ni,nj->ij', weight, direction, direction)
result[i] = tensor[[0, 0, 0, 1, 1, 2], [0, 1, 2, 1, 2, 2]]
if i % 4096 == 0:
progress('SPATIAL_MOMENT', completed=i, total=len(di))
return result, dict(radius=radius, coincident_centers_excluded=coincident,
component_order=list(COLUMNS[13:]))
def features(points, tetra, raw_ids, gate, wall_faces=None, marked_gate=None,
progress=lambda *a, **kw: None):
start = time.process_time(); g = mesh(points, tetra)
faces = exterior_faces(g['t']) if wall_faces is None else np.asarray(wall_faces)
sources, gate_mode = gate_nodes(g['x'], raw_ids, gate, marked_gate)
wall = np.unique(faces)
timings = {}; tick = time.process_time()
def finish(name):
nonlocal tick
now = time.process_time(); timings[name] = now-tick; tick = now
progress('EIKONAL_DW'); dw = solve_eikonal(g, wall, 1.); finish('Dw')
progress('EIKONAL_DI'); di = solve_eikonal(g, sources, 1.); finish('Di')
progress('CELL_SPEED'); speed, zero = cell_flow_speed(g, dw, faces); finish('cell_speed')
progress('EIKONAL_DF'); df = solve_eikonal(g, sources, speed); finish('Df')
if dw.max() <= 0 or di.max() <= 0:
raise ValueError('Zero feature normalisation scale')
vf = strict_volume_cdf(df, g['mass']); dis = di/di.max(); dws = dw/dw.max()
grads = [nodal_gradient(g, a) for a in (vf, dis, dws)]; finish('gradients')
moment, moment_meta = spatial_moment(g, di, progress); finish('moment')
x = np.column_stack([vf, grads[0], dis, grads[1], dw, dws, grads[2], moment])
if x.shape != (len(points), 19) or not np.isfinite(x).all():
raise ValueError('Invalid final 19-column features')
metadata = dict(columns=list(COLUMNS), gate_mode=gate_mode, gate_nodes=sources.tolist(),
gate_raw_ids=np.asarray(raw_ids)[sources].tolist(),
wall_mode='tet_exterior_proxy' if wall_faces is None else 'explicit_supplied_wall_faces',
all_wall_tetrahedra=len(zero), all_wall_rule='centroid_triangle_distance_R1_supplement',
all_wall_volume_fraction=float(g['volume'][zero].sum()/g['volume'].sum()),
timings_cpu_seconds=timings, worker_cpu_seconds=time.process_time()-start,
volume=float(g['volume'].sum()), hmax=g['hmax'], moment=moment_meta,
speed_min=float(speed.min()), speed_max=float(speed.max()),
flow_distance_tied_nodes=int(len(df)-len(np.unique(df))),
zero_gradient_nodes=[int(np.sum(np.linalg.norm(v, axis=1) == 0)) for v in grads],
gate_mapping_distance=float(np.linalg.norm(g['x'][sources]-np.asarray(gate), axis=1).min()),
exterior_proxy_includes_gate=bool(np.any(np.isin(sources, wall))),
precision='float64', fim_device='cpu', max_iterations=100000)
return dict(features=x, Dw=dw, Di=di, Df=df, Vf=vf,
mass=g['mass'], all_wall_tet_ids=zero), metadata
def per_geometry_metrics(y, predicted):
y = np.asarray(y, dtype=float); predicted = np.asarray(predicted, dtype=float)
if y.ndim != 1 or predicted.shape != y.shape or not len(y) or not np.isfinite(y).all() or not np.isfinite(predicted).all() or np.any(y < 0):
raise ValueError('Invalid all-node score inputs')
rmse = float(np.sqrt(np.mean((predicted-y)**2)))
denom = dict(rms=float(np.sqrt(np.mean(y*y))), maximum=float(y.max()), mean=float(y.mean()))
return dict(nodes=len(y), rmse=rmse, denominators=denom,
undefined_metrics=[k for k, v in denom.items() if v <= 0],
**{'rrmse_'+k: rmse/v if v > 0 else None for k, v in denom.items()})
def appendix_summary(splits):
if len(splits) != 5 or any(not len(s) for s in splits):
raise ValueError('Five nonempty split score lists required')
rows = [dict(min=float(np.min(s)), median=float(np.median(s)), max=float(np.max(s))) for s in splits]
return dict(per_split=rows, mean_of_split_summaries={k:float(np.mean([r[k] for r in rows])) for k in rows[0]})
+205
View File
@@ -0,0 +1,205 @@
"""Gre24 fill-time reproduction; explicit R1 choices, no fitted state or labels.
Author method and our discretisation choices are kept distinct in receipts.
This module never changes the historical R2-G24 approximation.
"""
from itertools import combinations
import time
import numpy as np
from sklearn.neighbors import BallTree
from boundary_distance import SurfaceDistance
COLUMNS = ('Vf', 'grad_Vf_x', 'grad_Vf_y', 'grad_Vf_z', 'Di_star',
'grad_Di_x', 'grad_Di_y', 'grad_Di_z', 'Dw', 'Dw_star',
'grad_Dw_x', 'grad_Dw_y', 'grad_Dw_z',
'Sxx', 'Sxy', 'Sxz', 'Syy', 'Syz', 'Szz')
def mesh(points, tetra):
x = np.asarray(points, dtype=np.float64)
t = np.asarray(tetra)
if x.ndim != 2 or x.shape[1] != 3 or not np.isfinite(x).all():
raise ValueError('Invalid points')
if t.ndim != 2 or t.shape[1] != 4 or t.dtype.kind not in 'iu' or not len(t):
raise ValueError('Invalid tetrahedra')
if t.min() < 0 or t.max() >= len(x) or not np.array_equal(np.unique(t), np.arange(len(x))):
raise ValueError('Tet domain must explicitly contain every supplied node')
t = np.asarray(t, dtype=np.int32)
cells = x[t]
matrix = cells[:, 1:] - cells[:, :1]
volume = np.abs(np.linalg.det(matrix)) / 6
if not np.isfinite(volume).all() or np.any(volume <= 0):
raise ValueError('Nonpositive tetrahedron volume')
mass = np.bincount(t.ravel(), weights=np.repeat(volume / 4, 4), minlength=len(x))
hmax = max(float(np.linalg.norm(cells[:, i]-cells[:, j], axis=1).max())
for i, j in combinations(range(4), 2))
return dict(x=x, t=t, matrix=matrix, volume=volume, mass=mass,
centers=cells.mean(1), hmax=hmax)
def exterior_faces(tetra):
faces = np.sort(tetra[:, np.array([[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]])].reshape(-1, 3), axis=1)
faces, counts = np.unique(faces, axis=0, return_counts=True)
if np.any(counts > 2):
raise ValueError('Nonmanifold tetrahedron faces')
return faces[counts == 1]
def gate_nodes(x, raw_ids, gate, marked=None):
raw_ids = np.asarray(raw_ids)
if len(raw_ids) != len(x) or len(np.unique(raw_ids)) != len(x):
raise ValueError('Invalid original node IDs')
if marked is not None:
marked = np.asarray(marked, dtype=np.int64)
if not len(marked) or marked.min() < 0 or marked.max() >= len(x):
raise ValueError('Invalid explicit inlet node set')
return np.unique(marked), 'explicit_marked_nodes'
gate = np.asarray(gate, dtype=float)
if gate.shape != (3,) or not np.isfinite(gate).all():
raise ValueError('Invalid inlet location')
d2 = np.sum((x-gate)**2, axis=1)
tied = np.flatnonzero(d2 == d2.min())
return np.array([tied[np.argmin(raw_ids[tied])]]), 'nearest_tet_node_min_original_id_tie'
def solve_eikonal(g, sources, speed, max_iterations=100000, *, scale_override=None):
from fimpy.solver import create_fim_solver
speed = np.broadcast_to(np.asarray(speed, dtype=float), (len(g['t']),))
if not np.isfinite(speed).all() or np.any(speed <= 0):
raise ValueError('Nonpositive or nonfinite cell speed; no epsilon replacement')
# Claude1794756243: exact common change of coordinates/speed, phi unchanged.
scale = 1./float(speed.min()) if float(speed.min())**2 <= 1e-4 else 1.
if scale_override is not None:
scale=float(scale_override) # Synthetic invariance test only; worker never passes this.
if not np.isfinite(scale) or scale<=0:raise ValueError('Invalid coordinate/speed scale')
metric = (speed[:, None, None]*scale)**2 * np.eye(3)[None]
solver = create_fim_solver(g['x']*scale, g['t'], metric, precision=np.float64,
device='cpu', use_active_list=True)
phi = solver.comp_fim(np.asarray(sources, dtype=np.int32), np.zeros(len(sources)),
max_iterations=max_iterations)
if np.any(solver.active_list):
raise RuntimeError('tetFIM iteration limit with active nodes')
if not np.isfinite(phi).all() or np.any(phi < 0) or np.any(phi >= solver.undef_val):
raise ValueError('Nonfinite, negative or unreached eikonal node')
if np.any(phi[sources] != 0):
raise ValueError('Eikonal source values changed')
return phi.copy()
def cell_flow_speed(g, dw, wall_faces):
if not np.isfinite(dw).all() or np.any(dw < 0):
raise ValueError('Invalid wall field')
speed = dw[g['t']].mean(1)
zero = np.flatnonzero(np.all(dw[g['t']] == 0, axis=1))
if len(zero):
surface = SurfaceDistance(g['x'][wall_faces])
speed[zero] = surface.query(g['centers'][zero])
if not np.isfinite(speed).all() or np.any(speed <= 0):
raise ValueError('Nonpositive flow speed after declared all-wall supplement')
return speed, zero
def strict_volume_cdf(field, mass):
d = np.asarray(field, dtype=float); w = np.asarray(mass, dtype=float)
if d.ndim != 1 or w.shape != d.shape or not len(d) or not np.isfinite(d).all() or not np.isfinite(w).all() or np.any(w <= 0):
raise ValueError('Invalid lumped-volume CDF')
order = np.argsort(d, kind='stable')
prefix = np.r_[0., np.cumsum(w[order], dtype=np.float64)]
return prefix[np.searchsorted(d[order], d, side='left')] / w.sum()
def nodal_gradient(g, values, normalize=True):
v = np.asarray(values, dtype=float)
if v.shape != (len(g['x']),) or not np.isfinite(v).all():
raise ValueError('Invalid nodal scalar')
t = g['t']
cell_grad = np.linalg.solve(g['matrix'], (v[t[:, 1:]]-v[t[:, :1]])[..., None])[..., 0]
grad = np.zeros((len(v), 3))
for k in range(4):
np.add.at(grad, t[:, k], cell_grad*g['volume'][:, None])
grad /= 4*g['mass'][:, None]
if normalize:
norm = np.linalg.norm(grad, axis=1)
np.divide(grad, norm[:, None], out=grad, where=norm[:, None] > 0)
return grad
def spatial_moment(g, di, progress=lambda *a, **kw: None):
radius = 3*g['hmax']; centers = g['centers']; cell_di = di[g['t']].mean(1)
tree = BallTree(centers); result = np.empty((len(di), 6)); coincident = 0
for i, p in enumerate(g['x']):
ids = tree.query_radius(p[None], r=radius)[0]
delta = centers[ids]-p; dist = np.linalg.norm(delta, axis=1)
selected = (dist < radius) & (np.abs(cell_di[ids]-di[i]) < radius)
coincident += int(np.sum(selected & (dist == 0)))
selected &= dist > 0
ids = ids[selected]; delta = delta[selected]; dist = dist[selected]
if not len(ids):
raise ValueError(f'Empty moment neighbourhood at node {i}')
direction = delta/dist[:, None]
weight = g['volume'][ids]; weight = weight/weight.sum()
tensor = np.einsum('n,ni,nj->ij', weight, direction, direction)
result[i] = tensor[[0, 0, 0, 1, 1, 2], [0, 1, 2, 1, 2, 2]]
if i % 4096 == 0:
progress('SPATIAL_MOMENT', completed=i, total=len(di))
return result, dict(radius=radius, coincident_centers_excluded=coincident,
component_order=list(COLUMNS[13:]))
def features(points, tetra, raw_ids, gate, wall_faces=None, marked_gate=None,
progress=lambda *a, **kw: None):
start = time.process_time(); g = mesh(points, tetra)
faces = exterior_faces(g['t']) if wall_faces is None else np.asarray(wall_faces)
sources, gate_mode = gate_nodes(g['x'], raw_ids, gate, marked_gate)
wall = np.unique(faces)
timings = {}; tick = time.process_time()
def finish(name):
nonlocal tick
now = time.process_time(); timings[name] = now-tick; tick = now
progress('EIKONAL_DW'); dw = solve_eikonal(g, wall, 1.); finish('Dw')
progress('EIKONAL_DI'); di = solve_eikonal(g, sources, 1.); finish('Di')
progress('CELL_SPEED'); speed, zero = cell_flow_speed(g, dw, faces); finish('cell_speed')
progress('EIKONAL_DF'); df = solve_eikonal(g, sources, speed); finish('Df')
if dw.max() <= 0 or di.max() <= 0:
raise ValueError('Zero feature normalisation scale')
vf = strict_volume_cdf(df, g['mass']); dis = di/di.max(); dws = dw/dw.max()
grads = [nodal_gradient(g, a) for a in (vf, dis, dws)]; finish('gradients')
moment, moment_meta = spatial_moment(g, di, progress); finish('moment')
x = np.column_stack([vf, grads[0], dis, grads[1], dw, dws, grads[2], moment])
if x.shape != (len(points), 19) or not np.isfinite(x).all():
raise ValueError('Invalid final 19-column features')
metadata = dict(columns=list(COLUMNS), gate_mode=gate_mode, gate_nodes=sources.tolist(),
gate_raw_ids=np.asarray(raw_ids)[sources].tolist(),
wall_mode='tet_exterior_proxy' if wall_faces is None else 'explicit_supplied_wall_faces',
all_wall_tetrahedra=len(zero), all_wall_rule='centroid_triangle_distance_R1_supplement',
all_wall_volume_fraction=float(g['volume'][zero].sum()/g['volume'].sum()),
timings_cpu_seconds=timings, worker_cpu_seconds=time.process_time()-start,
volume=float(g['volume'].sum()), hmax=g['hmax'], moment=moment_meta,
speed_min=float(speed.min()), speed_max=float(speed.max()),
Df_coordinate_and_speed_scale=1./float(speed.min()) if float(speed.min())**2 <= 1e-4 else 1.,
scale_rule='only_if_min_f_squared_le_1e-4; x_and_f_times_reciprocal_min_f; phi_unchanged',
flow_distance_tied_nodes=int(len(df)-len(np.unique(df))),
zero_gradient_nodes=[int(np.sum(np.linalg.norm(v, axis=1) == 0)) for v in grads],
gate_mapping_distance=float(np.linalg.norm(g['x'][sources]-np.asarray(gate), axis=1).min()),
exterior_proxy_includes_gate=bool(np.any(np.isin(sources, wall))),
precision='float64', fim_device='cpu', max_iterations=100000)
return dict(features=x, Dw=dw, Di=di, Df=df, Vf=vf,
mass=g['mass'], all_wall_tet_ids=zero), metadata
def per_geometry_metrics(y, predicted):
y = np.asarray(y, dtype=float); predicted = np.asarray(predicted, dtype=float)
if y.ndim != 1 or predicted.shape != y.shape or not len(y) or not np.isfinite(y).all() or not np.isfinite(predicted).all() or np.any(y < 0):
raise ValueError('Invalid all-node score inputs')
rmse = float(np.sqrt(np.mean((predicted-y)**2)))
denom = dict(rms=float(np.sqrt(np.mean(y*y))), maximum=float(y.max()), mean=float(y.mean()))
return dict(nodes=len(y), rmse=rmse, denominators=denom,
undefined_metrics=[k for k, v in denom.items() if v <= 0],
**{'rrmse_'+k: rmse/v if v > 0 else None for k, v in denom.items()})
def appendix_summary(splits):
if len(splits) != 5 or any(not len(s) for s in splits):
raise ValueError('Five nonempty split score lists required')
rows = [dict(min=float(np.min(s)), median=float(np.median(s)), max=float(np.max(s))) for s in splits]
return dict(per_split=rows, mean_of_split_summaries={k:float(np.mean([r[k] for r in rows])) for k in rows[0]})
+131
View File
@@ -0,0 +1,131 @@
"""Independent Gre24 geometry/feature preparation; full tet nodes, no S2 mask."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import time
import traceback
from xml.etree import ElementTree as ET
from zipfile import ZipFile
import numpy as np
import yaml
from audit_samples import decode_array
from gre24_features import features
from s2_recovery_supervisor import save
def sha(path):
h=hashlib.sha256()
with Path(path).open('rb') as f:
for block in iter(lambda:f.read(2**20),b''):h.update(block)
return h.hexdigest()
def checked(root):
c=json.loads((root/'contract.json').read_text())
for p,h in c['code_sha256'].items():
if sha(p)!=h:raise ValueError('Pinned source changed: '+p)
st=Path(c['archive']).stat();a=c['archive_stat']
if (st.st_size,st.st_mtime_ns,st.st_ino)!=(a['bytes'],a['mtime_ns'],a['inode']):
raise ValueError('Immutable source archive changed')
return c
def read_geometry(archive,case):
cells={};points=None;stack=[]
with ZipFile(archive) as z:
config=yaml.safe_load(z.read(case+'.yml'))
with z.open(case+'_sim.vtu') as f:
for event,e in ET.iterparse(f,events=('start','end')):
if event=='start':
stack.append(e.tag)
if e.tag=='VTKFile':
if e.get('byte_order')!='LittleEndian' or e.get('compressor')!='vtkZLibDataCompressor':
raise ValueError('Unsupported VTU')
header=e.get('header_type','UInt32')
if e.tag in ('PointData','CellData'):
raise ValueError('Field section before complete geometry')
else:
if e.tag=='DataArray':
if stack[-2]=='Points':points=decode_array(e,header).copy()
elif stack[-2]=='Cells':cells[e.get('Name')]=decode_array(e,header).copy()
e.clear()
if points is not None and all(k in cells for k in ['connectivity','offsets','types']):break
stack.pop()
offsets=np.r_[0,cells['offsets']];indices=np.flatnonzero(cells['types']==10)
if not len(indices) or np.any(np.diff(offsets)[indices]!=4):raise ValueError('No valid tetrahedra')
raw_tet=cells['connectivity'][offsets[indices,None]+np.arange(4)]
raw_ids=np.unique(raw_tet);t=np.searchsorted(raw_ids,raw_tet)
types,counts=np.unique(cells['types'],return_counts=True)
return points[raw_ids],t,raw_ids,dict(raw_nodes=len(points),tet_nodes=len(raw_ids),
outside_tet_nodes=len(points)-len(raw_ids),raw_cell_types=dict(zip(map(str,types),map(int,counts))),
inlet_config=config,gate_source='YAML inlet_location; no explicit node/face markers in this source')
def read_targets(archive,case):
stack=[];count=None
with ZipFile(archive) as z,z.open(case+'_sim.vtu') as f:
for event,e in ET.iterparse(f,events=('start','end')):
if event=='start':
stack.append(e.tag)
if e.tag=='VTKFile':header=e.get('header_type','UInt32')
elif e.tag=='Piece':
if count is not None:raise ValueError('Multiple pieces')
count=int(e.get('NumberOfPoints'))
else:
if e.tag=='DataArray':
if stack[-2]=='PointData' and e.get('Name')=='Fill_time':
v=decode_array(e,header).copy()
if v.shape!=(count,):raise ValueError('Fill_time size mismatch')
return v
e.clear()
stack.pop()
raise ValueError('Missing Fill_time')
def worker(root,index):
c=checked(root);spec=c['parts'][index];case=spec['case'];dest=root/'parts'/case/'output'
dest.mkdir(parents=True,exist_ok=False)
start=time.process_time();wall=time.monotonic()
def progress(stage,**kw):
save(dest/'progress.json',dict(stage=stage,case=case,pid=os.getpid(),unix=time.time(),
CPU_s=time.process_time()-start,wall_s=time.monotonic()-wall,**kw))
try:
progress('READ_GEOMETRY')
x,t,raw,meta=read_geometry(c['archive'],case)
save(dest/'geometry-metadata.json',meta)
data,feature_meta=features(x,t,raw,meta['inlet_config']['inlet_location'],progress=progress)
progress('SAVE_FEATURES')
for name in ['features','Vf','Dw','Di','Df','mass','all_wall_tet_ids']:np.save(dest/(name+'.npy'),data[name])
np.save(dest/'raw_ids.npy',raw)
if c.get('feature_only_cost_test',False):
save(dest/'result.json',dict(status='PASS',case=case,index=index,geometry=meta,features=feature_meta,
output_sha256={p.name:sha(p) for p in dest.glob('*.npy')},
worker_cpu_seconds=time.process_time()-start,wall_seconds=time.monotonic()-wall,
decoded_labels=[],test_scores_computed=False,training=False,cost_test_only=True))
progress('PASS_COST_TEST_ONLY');return 0
progress('READ_FILL_TIME_AFTER_FEATURES_FIXED')
yall=read_targets(c['archive'],case);y=yall[raw]
if not np.isfinite(y).all() or np.any(y<0):raise ValueError('Invalid fill time on full tetrahedral domain')
outside=np.ones(len(yall),dtype=bool);outside[raw]=False;outside_y=yall[outside]
np.save(dest/'seconds.npy',y);np.save(dest/'target.npy',y/spec['t_scale_seconds'])
np.save(dest/'outside_tet_raw_ids.npy',np.flatnonzero(outside));np.save(dest/'outside_tet_fill_time.npy',outside_y)
outputs={p.name:sha(p) for p in dest.glob('*.npy')}
save(dest/'result.json',dict(status='PASS',case=case,index=index,geometry=meta,features=feature_meta,
t_scale_seconds=spec['t_scale_seconds'],time_scale_source=spec['time_scale_source'],
decoded_labels=['Fill_time'],outside_label_status=dict(nodes=len(outside_y),
finite=int(np.isfinite(outside_y).sum()),negative=int((outside_y<0).sum())),
output_sha256=outputs,worker_cpu_seconds=time.process_time()-start,wall_seconds=time.monotonic()-wall,
test_scores_computed=False,training=False))
progress('PASS');return 0
except Exception as exc:
save(dest/'failure.json',dict(status='FAILED',case=case,type=type(exc).__name__,message=str(exc),
traceback=traceback.format_exc(),worker_cpu_seconds=time.process_time()-start,
wall_seconds=time.monotonic()-wall,automatic_retry=False))
raise
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('root',type=Path);p.add_argument('index',type=int)
a=p.parse_args();raise SystemExit(worker(a.root,a.index))
+146
View File
@@ -0,0 +1,146 @@
"""Independent Gre24 geometry/feature preparation; full tet nodes, no S2 mask."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import time
import traceback
from xml.etree import ElementTree as ET
from zipfile import ZipFile
import numpy as np
import yaml
from audit_samples import decode_array
from gre24_features_v2 import features
from s2_recovery_supervisor import save
def sha(path):
h=hashlib.sha256()
with Path(path).open('rb') as f:
for block in iter(lambda:f.read(2**20),b''):h.update(block)
return h.hexdigest()
def checked(root):
c=json.loads((root/'contract.json').read_text())
for p,h in c['code_sha256'].items():
if sha(p)!=h:raise ValueError('Pinned source changed: '+p)
st=Path(c['archive']).stat();a=c['archive_stat']
if (st.st_size,st.st_mtime_ns,st.st_ino)!=(a['bytes'],a['mtime_ns'],a['inode']):
raise ValueError('Immutable source archive changed')
return c
def read_geometry(archive,case):
cells={};points=None;stack=[]
with ZipFile(archive) as z:
config=yaml.safe_load(z.read(case+'.yml'))
with z.open(case+'_sim.vtu') as f:
for event,e in ET.iterparse(f,events=('start','end')):
if event=='start':
stack.append(e.tag)
if e.tag=='VTKFile':
if e.get('byte_order')!='LittleEndian' or e.get('compressor')!='vtkZLibDataCompressor':
raise ValueError('Unsupported VTU')
header=e.get('header_type','UInt32')
if e.tag in ('PointData','CellData'):
raise ValueError('Field section before complete geometry')
else:
if e.tag=='DataArray':
if stack[-2]=='Points':points=decode_array(e,header).copy()
elif stack[-2]=='Cells':cells[e.get('Name')]=decode_array(e,header).copy()
e.clear()
if points is not None and all(k in cells for k in ['connectivity','offsets','types']):break
stack.pop()
offsets=np.r_[0,cells['offsets']];indices=np.flatnonzero(cells['types']==10)
if not len(indices) or np.any(np.diff(offsets)[indices]!=4):raise ValueError('No valid tetrahedra')
raw_tet=cells['connectivity'][offsets[indices,None]+np.arange(4)]
raw_ids=np.unique(raw_tet);t=np.searchsorted(raw_ids,raw_tet)
types,counts=np.unique(cells['types'],return_counts=True)
return points[raw_ids],t,raw_ids,dict(raw_nodes=len(points),tet_nodes=len(raw_ids),
outside_tet_nodes=len(points)-len(raw_ids),raw_cell_types=dict(zip(map(str,types),map(int,counts))),
inlet_config=config,gate_source='YAML inlet_location; no explicit node/face markers in this source')
def read_targets(archive,case):
stack=[];count=None
with ZipFile(archive) as z,z.open(case+'_sim.vtu') as f:
for event,e in ET.iterparse(f,events=('start','end')):
if event=='start':
stack.append(e.tag)
if e.tag=='VTKFile':header=e.get('header_type','UInt32')
elif e.tag=='Piece':
if count is not None:raise ValueError('Multiple pieces')
count=int(e.get('NumberOfPoints'))
else:
if e.tag=='DataArray':
if stack[-2]=='PointData' and e.get('Name')=='Fill_time':
v=decode_array(e,header).copy()
if v.shape!=(count,):raise ValueError('Fill_time size mismatch')
return v
e.clear()
stack.pop()
raise ValueError('Missing Fill_time')
def worker(root,index):
c=checked(root);spec=c['parts'][index];case=spec['case'];dest=root/'parts'/case/'output'
dest.mkdir(parents=True,exist_ok=False)
start=time.process_time();wall=time.monotonic()
def progress(stage,**kw):
save(dest/'progress.json',dict(stage=stage,case=case,pid=os.getpid(),unix=time.time(),
CPU_s=time.process_time()-start,wall_s=time.monotonic()-wall,**kw))
try:
progress('READ_GEOMETRY')
x,t,raw,meta=read_geometry(c['archive'],case)
save(dest/'geometry-metadata.json',meta)
if spec.get('reuse_feature_root'):
old=Path(spec['reuse_feature_root']);old_meta=json.loads((old/'result.json').read_text())
if sha(old/'result.json')!=spec['reuse_result_sha256'] or old_meta['case']!=case:
raise ValueError('Reused cost evidence changed')
if old_meta['features']['speed_min']**2<=1e-4:
raise ValueError('Old unscaled result is not eligible for exact reuse')
data={}
for name in ['features','Vf','Dw','Di','Df','mass','all_wall_tet_ids']:
if sha(old/(name+'.npy'))!=old_meta['output_sha256'][name+'.npy']:
raise ValueError('Reused feature changed')
data[name]=np.load(old/(name+'.npy'),allow_pickle=False)
if not np.array_equal(raw,np.load(old/'raw_ids.npy',allow_pickle=False)):
raise ValueError('Reused raw IDs changed')
feature_meta=dict(old_meta['features'],reused_from=str(old),Df_coordinate_and_speed_scale=1.)
else:
data,feature_meta=features(x,t,raw,meta['inlet_config']['inlet_location'],progress=progress)
progress('SAVE_FEATURES')
for name in ['features','Vf','Dw','Di','Df','mass','all_wall_tet_ids']:np.save(dest/(name+'.npy'),data[name])
np.save(dest/'raw_ids.npy',raw)
if c.get('feature_only_cost_test',False):
save(dest/'result.json',dict(status='PASS',case=case,index=index,geometry=meta,features=feature_meta,
output_sha256={p.name:sha(p) for p in dest.glob('*.npy')},
worker_cpu_seconds=time.process_time()-start,wall_seconds=time.monotonic()-wall,
decoded_labels=[],test_scores_computed=False,training=False,cost_test_only=True))
progress('PASS_COST_TEST_ONLY');return 0
progress('READ_FILL_TIME_AFTER_FEATURES_FIXED')
yall=read_targets(c['archive'],case);y=yall[raw]
if not np.isfinite(y).all() or np.any(y<0):raise ValueError('Invalid fill time on full tetrahedral domain')
outside=np.ones(len(yall),dtype=bool);outside[raw]=False;outside_y=yall[outside]
np.save(dest/'seconds.npy',y);np.save(dest/'target.npy',y/spec['t_scale_seconds'])
np.save(dest/'outside_tet_raw_ids.npy',np.flatnonzero(outside));np.save(dest/'outside_tet_fill_time.npy',outside_y)
outputs={p.name:sha(p) for p in dest.glob('*.npy')}
save(dest/'result.json',dict(status='PASS',case=case,index=index,geometry=meta,features=feature_meta,
t_scale_seconds=spec['t_scale_seconds'],time_scale_source=spec['time_scale_source'],
decoded_labels=['Fill_time'],outside_label_status=dict(nodes=len(outside_y),
finite=int(np.isfinite(outside_y).sum()),negative=int((outside_y<0).sum())),
output_sha256=outputs,worker_cpu_seconds=time.process_time()-start,wall_seconds=time.monotonic()-wall,
test_scores_computed=False,training=False))
progress('PASS');return 0
except Exception as exc:
save(dest/'failure.json',dict(status='FAILED',case=case,type=type(exc).__name__,message=str(exc),
traceback=traceback.format_exc(),worker_cpu_seconds=time.process_time()-start,
wall_seconds=time.monotonic()-wall,automatic_retry=False))
raise
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('root',type=Path);p.add_argument('index',type=int)
a=p.parse_args();raise SystemExit(worker(a.root,a.index))
+67
View File
@@ -0,0 +1,67 @@
"""Freeze authorised v5 fallback independently of all historical S2 splits."""
import json
from pathlib import Path
import time
from zipfile import ZipFile
import numpy as np
from gre24_prepare_v2 import sha
def main():
root=Path('artifacts/gre24-reproduction-2026-11-15/v5-protocol')
root.mkdir(exist_ok=False)
archive=Path('data.zip').resolve()
prior=json.loads(Path('artifacts/intake-2026-11-13/archive_verification.json').read_text())
st=archive.stat()
assert (st.st_size,st.st_mtime_ns,st.st_ino)==(prior['bytes'],prior['mtime_ns'],prior['inode'])
with ZipFile(archive) as z:
cases=sorted(n[:-4] for n in z.namelist() if n.endswith('.yml'))
assert len(cases)==624 and len(set(cases))==624
assert all(c+'_sim.vtu' in z.namelist() and c+'.log' in z.namelist() for c in cases)
settings_file=Path('artifacts/s2-e1-2026-11-14/log-flow-setting-check/fill-time-setting-context.json')
settings={r['member'][:-4]:r for r in json.loads(settings_file.read_text())}
inventory_file=Path('artifacts/intake-2026-11-13/geometry_log_census.json')
inventory={r['case']:r for r in json.loads(inventory_file.read_text())}
parts=[]
for case in cases:
s=settings[case];assert s['setting_before_filling_phase'] and s['setting']['seconds']>0
parts.append(dict(case=case,raw_nodes=inventory[case]['points'],t_scale_seconds=s['setting']['seconds'],
time_scale_source=dict(mode='t_set_substitute_Q_unavailable_declared_deviation',
setting=s['setting'],pre_solver_setting=True,source=str(settings_file),source_sha256=sha(settings_file))))
cost_root=Path('artifacts/gre24-reproduction-2026-11-15/v5-cost-test')
cost=json.loads((cost_root/'complete.json').read_text());assert cost['status']=='COMPLETE'
r=cost['records'][0];assert r['worker']['status']=='PASS'
p=next(p for p in parts if p['case']==r['case']);p.update(reuse_feature_root=str(Path(r['result_path']).parent),reuse_result_sha256=r['result_sha256'])
splits=[]
for index,seed in enumerate(range(2026111501,2026111506)):
order=np.random.Generator(np.random.PCG64(seed)).permutation(len(cases))
test=sorted(cases[i] for i in order[:312]);train=sorted(cases[i] for i in order[312:])
vi=np.random.Generator(np.random.PCG64(seed+1000)).permutation(len(train))[:32]
val=sorted(train[i] for i in vi);learning=sorted(set(train)-set(val))
assert len(learning)==280 and not set(train)&set(test)
splits.append(dict(index=index,seed=seed,train=train,test=test,fnn_validation=val,fnn_learning=learning,
fnn_validation_seed=seed+1000,validation_rounding='ceil(10percent training geometries)'))
(root/'splits.json').write_text(json.dumps(splits,indent=2)+'\n')
paths=['tools/gre24_features_v2.py','tools/gre24_prepare_v2.py','tools/run_gre24_protocol_preparation.py',
'tools/boundary_distance.py','tools/audit_samples.py','tools/s2_recovery_supervisor.py','tools/s2_recovery_monitoring.py']
contract=dict(version='Gre24-v5-fallback-R1-unit-scale-v2',dataset_version='v5',
authorizing_rulings=['1794755474.778649','1794755594.435869','1794756165.827889','1794756243.638289','1794756271.768399'],
archive=str(archive),archive_stat=prior,parts=parts,dispatch_order=list(range(624)),
worker_cpus=[8,10,12,14,16,18,20,22],coordinator_cpus=[30,31],
limits=dict(workers=8,total_worker_cpu_seconds=144000,per_part_cpu_seconds=1800,per_part_wall_seconds=1800,
per_part_rss_bytes=4*2**30,preparation_initial_cpu_reserve_seconds=60+cost['worker_cpu_seconds'],
total_disk_bytes=60*10**9,total_gpu_seconds=7200),
preparation_setup_reserve_note='60 CPU-s conservative allowance covers analytic tests; setup/library copy overhead separately recorded',
historical_cost_result=str(cost_root/'complete.json'),historical_cost_sha256=sha(cost_root/'complete.json'),
historical_cost_worker_cpu_seconds=cost['worker_cpu_seconds'],
code_sha256={p:sha(p) for p in paths},splits_sha256=sha(root/'splits.json'),
protocol='Five independent 312test/312train random geometry splits; NOT five-fold CV; v5 version deviation',
failure_policy='No replacement, no automatic retries; retain every requested case in coverage reporting',
data_domain='Every retained tet node including wall; original IDs/outside-tet labels separately retained',
features='Eq12 19 columns; no t_set feature; R1 discretisations and conditional exact unit change',
timestamp=time.time())
(root/'contract.json').write_text(json.dumps(contract,indent=2)+'\n')
print(json.dumps(dict(root=str(root),parts=624,contract_sha256=sha(root/'contract.json'),splits_sha256=sha(root/'splits.json'))))
if __name__=='__main__':main()
+99
View File
@@ -0,0 +1,99 @@
"""One guarded Gre24 preparation queue, preserving failed attempts and total CPU."""
import argparse
import fcntl
import json
import os
from pathlib import Path
import resource
import signal
import subprocess
import sys
import time
from gre24_prepare import checked,sha
from s2_recovery_supervisor import save,supervise,stop_group
def guard(root,index,slot):
c=checked(root);os.sched_setaffinity(0,[c['worker_cpus'][slot]])
part=c['parts'][index];dest=root/'parts'/part['case'];dest.mkdir(parents=True,exist_ok=True)
cap=c['limits']['per_part_cpu_seconds']
r=supervise([sys.executable,'tools/gre24_prepare.py',str(root),str(index)],dest,'worker',
dict(total_cpu_seconds=cap+1,job_cpu_seconds=cap,job_wall_seconds=c['limits']['per_part_wall_seconds'],
tree_rss_bytes=c['limits']['per_part_rss_bytes'],disk_bytes=2*2**30,max_processes=1),poll=.2)
result=dest/'output/result.json'
if r['status']=='PASS' and (not result.exists() or json.loads(result.read_text())['status']!='PASS'):
r.update(status='STOPPED_OR_FAILED',stop_reason='MISSING_COMPLETE_RESULT')
save(dest/'guard-result.json',dict(worker=r,index=index,case=part['case'],result_path=str(result) if result.exists() else None,
result_sha256=sha(result) if result.exists() else None,guard_cpu_seconds=sum(resource.getrusage(resource.RUSAGE_SELF)[:2])))
return 0 if r['status']=='PASS' else 1
def run(root):
with (root/'queue.lock').open('a') as lock:
fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
return run_locked(root)
def run_locked(root):
c=checked(root)
if (root/'queue-started.json').exists():raise FileExistsError('Never restart this queue')
os.sched_setaffinity(0,c['coordinator_cpus'])
save(root/'queue-started.json',dict(pid=os.getpid(),unix=time.time(),contract_sha256=sha(root/'contract.json')))
active={};done=[];next_i=0;reason=None;first=False;started=time.monotonic()
cap=c['limits']['total_worker_cpu_seconds'];per=c['limits']['per_part_cpu_seconds']
def interrupted(*_):
nonlocal reason
reason='COORDINATOR_INTERRUPTED'
signal.signal(signal.SIGTERM,interrupted);signal.signal(signal.SIGINT,interrupted)
env=dict(os.environ,OMP_NUM_THREADS='1',OPENBLAS_NUM_THREADS='1',MKL_NUM_THREADS='1',NUMEXPR_NUM_THREADS='1',CUDA_VISIBLE_DEVICES='')
try:
while active or (next_i<len(c['parts']) and reason is None):
for slot,item in list(active.items()):
if item['process'].poll() is None:continue
receipt=root/'parts'/c['parts'][item['index']]['case']/'guard-result.json'
if not receipt.exists():
reason='MISSING_GUARD_RECEIPT';raise RuntimeError(reason)
r=json.loads(receipt.read_text());done.append(r);item['log'].close();del active[slot]
print(json.dumps(dict(event='PREPARATION_TERMINAL',index=r['index'],case=r['case'],status=r['worker']['status'],completed=len(done))),flush=True)
spent=c['limits']['preparation_initial_cpu_reserve_seconds']+sum(r['worker']['cpu_seconds'] for r in done)
if not first and done and not active:
first=True;r=done[0];spec=c['parts'][r['index']]
projection=r['worker']['cpu_seconds']*sum(p['raw_nodes'] for p in c['parts'])/spec['raw_nodes']*1.25
save(root/'first-part-checkpoint.json',dict(first=r['case'],status=r['worker']['status'],
projected_preparation_cpu_seconds=projection,projection_is_heuristic=True,
total_worker_cap_seconds=cap,first_result_sha256=r.get('result_sha256')))
if r['worker']['status']!='PASS':reason='FIRST_PART_FAILED'
elif projection>cap:reason='FIRST_PART_PROJECTED_PREPARATION_OVER_TOTAL_CAP'
ceiling=len(c['parts']) if first else 1
while reason is None and len(active)<c['limits']['workers'] and next_i<ceiling:
# Reserve each active job's full cap plus one sampling margin.
if spent+(len(active)+1)*(per+2)>cap:
if not active:reason='REMAINING_CPU_INSUFFICIENT_FOR_ANOTHER_CAPPED_ATTEMPT'
break
slot=next(s for s in range(c['limits']['workers']) if s not in active)
index=c['dispatch_order'][next_i];dest=root/'parts'/c['parts'][index]['case'];dest.mkdir(parents=True,exist_ok=True)
log=(dest/'guard.log').open('x')
process=subprocess.Popen([sys.executable,__file__,str(root),'--guard',str(index),'--slot',str(slot)],
stdout=log,stderr=subprocess.STDOUT,env=env,start_new_session=True)
active[slot]=dict(process=process,log=log,index=index);next_i+=1
save(root/'progress.json',dict(completed=len(done),attempted=next_i,total=len(c['parts']),
active={str(k):v['index'] for k,v in active.items()},settled_worker_cpu_seconds=spent,
reserved_active_worker_cpu_seconds=len(active)*(per+2),stop_reason=reason,
first_part_checked=first,elapsed_seconds=time.monotonic()-started))
if active:time.sleep(.5)
finally:
for item in active.values():
stop_group(item['process'].pid);item['process'].wait();item['log'].close()
attempted={r['index'] for r in done}
save(root/'complete.json',dict(status='COMPLETE' if len(done)==len(c['parts']) else 'STOPPED',stop_reason=reason,
records=done,never_attempted=[i for i in c['dispatch_order'] if i not in attempted],
worker_cpu_seconds=sum(r['worker']['cpu_seconds'] for r in done),
initial_cpu_reserve_seconds=c['limits']['preparation_initial_cpu_reserve_seconds'],
coordinator_cpu_seconds=sum(resource.getrusage(resource.RUSAGE_SELF)[:2]),
accounting_complete=not active,wall_seconds=time.monotonic()-started))
return 0 if len(done)==len(c['parts']) else 1
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('root',type=Path);p.add_argument('--guard',type=int);p.add_argument('--slot',type=int,default=0)
a=p.parse_args();raise SystemExit(run(a.root) if a.guard is None else guard(a.root,a.guard,a.slot))
+99
View File
@@ -0,0 +1,99 @@
"""One guarded Gre24 preparation queue, preserving failed attempts and total CPU."""
import argparse
import fcntl
import json
import os
from pathlib import Path
import resource
import signal
import subprocess
import sys
import time
from gre24_prepare_v2 import checked,sha
from s2_recovery_supervisor import save,supervise,stop_group
def guard(root,index,slot):
c=checked(root);os.sched_setaffinity(0,[c['worker_cpus'][slot]])
part=c['parts'][index];dest=root/'parts'/part['case'];dest.mkdir(parents=True,exist_ok=True)
cap=c['limits']['per_part_cpu_seconds']
r=supervise([sys.executable,'tools/gre24_prepare_v2.py',str(root),str(index)],dest,'worker',
dict(total_cpu_seconds=cap+1,job_cpu_seconds=cap,job_wall_seconds=c['limits']['per_part_wall_seconds'],
tree_rss_bytes=c['limits']['per_part_rss_bytes'],disk_bytes=2*2**30,max_processes=1),poll=.2)
result=dest/'output/result.json'
if r['status']=='PASS' and (not result.exists() or json.loads(result.read_text())['status']!='PASS'):
r.update(status='STOPPED_OR_FAILED',stop_reason='MISSING_COMPLETE_RESULT')
save(dest/'guard-result.json',dict(worker=r,index=index,case=part['case'],result_path=str(result) if result.exists() else None,
result_sha256=sha(result) if result.exists() else None,guard_cpu_seconds=sum(resource.getrusage(resource.RUSAGE_SELF)[:2])))
return 0 if r['status']=='PASS' else 1
def run(root):
with (root/'queue.lock').open('a') as lock:
fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
return run_locked(root)
def run_locked(root):
c=checked(root)
if (root/'queue-started.json').exists():raise FileExistsError('Never restart this queue')
os.sched_setaffinity(0,c['coordinator_cpus'])
save(root/'queue-started.json',dict(pid=os.getpid(),unix=time.time(),contract_sha256=sha(root/'contract.json')))
active={};done=[];next_i=0;reason=None;first=False;started=time.monotonic()
cap=c['limits']['total_worker_cpu_seconds'];per=c['limits']['per_part_cpu_seconds']
def interrupted(*_):
nonlocal reason
reason='COORDINATOR_INTERRUPTED'
signal.signal(signal.SIGTERM,interrupted);signal.signal(signal.SIGINT,interrupted)
env=dict(os.environ,OMP_NUM_THREADS='1',OPENBLAS_NUM_THREADS='1',MKL_NUM_THREADS='1',NUMEXPR_NUM_THREADS='1',CUDA_VISIBLE_DEVICES='')
try:
while active or (next_i<len(c['parts']) and reason is None):
for slot,item in list(active.items()):
if item['process'].poll() is None:continue
receipt=root/'parts'/c['parts'][item['index']]['case']/'guard-result.json'
if not receipt.exists():
reason='MISSING_GUARD_RECEIPT';raise RuntimeError(reason)
r=json.loads(receipt.read_text());done.append(r);item['log'].close();del active[slot]
print(json.dumps(dict(event='PREPARATION_TERMINAL',index=r['index'],case=r['case'],status=r['worker']['status'],completed=len(done))),flush=True)
spent=c['limits']['preparation_initial_cpu_reserve_seconds']+sum(r['worker']['cpu_seconds'] for r in done)
if not first and done and not active:
first=True;r=done[0];spec=c['parts'][r['index']]
projection=r['worker']['cpu_seconds']*sum(p['raw_nodes'] for p in c['parts'])/spec['raw_nodes']*1.25
save(root/'first-part-checkpoint.json',dict(first=r['case'],status=r['worker']['status'],
projected_preparation_cpu_seconds=projection,projection_is_heuristic=True,
total_worker_cap_seconds=cap,first_result_sha256=r.get('result_sha256')))
if r['worker']['status']!='PASS':reason='FIRST_PART_FAILED'
elif projection>cap:reason='FIRST_PART_PROJECTED_PREPARATION_OVER_TOTAL_CAP'
ceiling=len(c['parts']) if first else 1
while reason is None and len(active)<c['limits']['workers'] and next_i<ceiling:
# Reserve each active job's full cap plus one sampling margin.
if spent+(len(active)+1)*(per+2)>cap:
if not active:reason='REMAINING_CPU_INSUFFICIENT_FOR_ANOTHER_CAPPED_ATTEMPT'
break
slot=next(s for s in range(c['limits']['workers']) if s not in active)
index=c['dispatch_order'][next_i];dest=root/'parts'/c['parts'][index]['case'];dest.mkdir(parents=True,exist_ok=True)
log=(dest/'guard.log').open('x')
process=subprocess.Popen([sys.executable,__file__,str(root),'--guard',str(index),'--slot',str(slot)],
stdout=log,stderr=subprocess.STDOUT,env=env,start_new_session=True)
active[slot]=dict(process=process,log=log,index=index);next_i+=1
save(root/'progress.json',dict(completed=len(done),attempted=next_i,total=len(c['parts']),
active={str(k):v['index'] for k,v in active.items()},settled_worker_cpu_seconds=spent,
reserved_active_worker_cpu_seconds=len(active)*(per+2),stop_reason=reason,
first_part_checked=first,elapsed_seconds=time.monotonic()-started))
if active:time.sleep(.5)
finally:
for item in active.values():
stop_group(item['process'].pid);item['process'].wait();item['log'].close()
attempted={r['index'] for r in done}
save(root/'complete.json',dict(status='COMPLETE' if len(done)==len(c['parts']) else 'STOPPED',stop_reason=reason,
records=done,never_attempted=[i for i in c['dispatch_order'] if i not in attempted],
worker_cpu_seconds=sum(r['worker']['cpu_seconds'] for r in done),
initial_cpu_reserve_seconds=c['limits']['preparation_initial_cpu_reserve_seconds'],
coordinator_cpu_seconds=sum(resource.getrusage(resource.RUSAGE_SELF)[:2]),
accounting_complete=not active,wall_seconds=time.monotonic()-started))
return 0 if len(done)==len(c['parts']) else 1
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('root',type=Path);p.add_argument('--guard',type=int);p.add_argument('--slot',type=int,default=0)
a=p.parse_args();raise SystemExit(run(a.root) if a.guard is None else guard(a.root,a.guard,a.slot))
+93
View File
@@ -0,0 +1,93 @@
"""Analytic acceptance for the new reproduction, independent of real labels."""
import unittest
from itertools import permutations
import numpy as np
from gre24_features import (mesh, exterior_faces, gate_nodes, solve_eikonal,
cell_flow_speed, strict_volume_cdf, nodal_gradient, spatial_moment,
per_geometry_metrics, appendix_summary, features)
def box(nx=5, ny=3, nz=3):
axes = [np.linspace(0, 2, nx), np.linspace(0, 1, 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):
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.array(t, dtype=np.int32)
class Gre24Checks(unittest.TestCase):
def test_planar_speed_two(self):
x,t=box();g=mesh(x,t);source=np.flatnonzero(x[:,0]==0)
phi=solve_eikonal(g,source,2.)
np.testing.assert_allclose(phi,x[:,0]/2,atol=1e-7,rtol=1e-7)
def test_strict_ties_volume_weights(self):
np.testing.assert_allclose(strict_volume_cdf([0,1,1,2],[1,1,1,1]),[0,.25,.25,.75])
np.testing.assert_allclose(strict_volume_cdf([0,1,1,2],[1,2,3,4]),[0,.1,.1,.6])
def test_rod_volume_mapping(self):
x,t=box(21,2,2);g=mesh(x,t)
f=strict_volume_cdf(x[:,0],g['mass'])
self.assertLessEqual(np.max(np.abs(f-x[:,0]/2)),1/20+1e-12)
def test_disk_ideal_volume_mapping(self):
# Annular volume quadrature of the analytic radial order, not a tetFIM claim.
edges=np.linspace(0,1,101);radius=(edges[:-1]+edges[1:])/2
mass=np.pi*np.diff(edges**2)
f=strict_volume_cdf(radius,mass)
self.assertLess(np.max(np.abs(f-radius**2)),.011)
def test_affine_gradient_and_constant(self):
x,t=box();g=mesh(x,t);a=np.array([2.,-3.,.7])
grad=nodal_gradient(g,x@a+4,normalize=False)
np.testing.assert_allclose(grad,np.tile(a,(len(x),1)),atol=1e-12)
np.testing.assert_array_equal(nodal_gradient(g,np.full(len(x),7.)),np.zeros_like(x))
def test_moment_rotation(self):
x,t=box(3,3,3);g=mesh(x,t);di=x[:,0]
s,_=spatial_moment(g,di)
theta=.37;rot=np.array([[np.cos(theta),-np.sin(theta),0],[np.sin(theta),np.cos(theta),0],[0,0,1.]])
sr,_=spatial_moment(mesh(x@rot.T,t),di)
def matrix(a):
return a[:,np.array([[0,1,2],[1,3,4],[2,4,5]])]
sm=matrix(s);np.testing.assert_allclose(np.trace(sm,axis1=1,axis2=2),1,atol=1e-12)
self.assertTrue(np.all(np.linalg.eigvalsh(sm)>=-1e-12))
np.testing.assert_allclose(matrix(sr),rot@sm@rot.T,atol=1e-12)
def test_all_wall_tet_supplement(self):
x=np.array([[0,0,0],[1,0,0],[0,1,0],[0,0,1.]])
t=np.array([[0,1,2,3]]);g=mesh(x,t)
speed,zero=cell_flow_speed(g,np.zeros(4),exterior_faces(t))
np.testing.assert_allclose(speed,[1/(4*np.sqrt(3))],atol=1e-12)
np.testing.assert_array_equal(zero,[0])
def test_gate_original_id_tie(self):
x=np.array([[-1.,0,0],[1.,0,0]])
ids,mode=gate_nodes(x,[17,3],[0,0,0]);np.testing.assert_array_equal(ids,[1])
def test_three_metrics_and_undefined(self):
r=per_geometry_metrics([1,3],[2,3])
np.testing.assert_allclose([r['rrmse_rms'],r['rrmse_maximum'],r['rrmse_mean']],
[1/np.sqrt(10),1/(3*np.sqrt(2)),1/(2*np.sqrt(2))])
z=per_geometry_metrics([0,0],[0,1]);self.assertIsNone(z['rrmse_rms'])
def test_split_then_average(self):
r=appendix_summary([[0,1,2],[10,20,30],[2,3,4],[0,0,100],[7,8,9]])
self.assertEqual(r['mean_of_split_summaries']['median'],6.4)
def test_complete_pipeline_and_fail_closed(self):
x,t=box();a,m=features(x,t,np.arange(len(x)),x[0])
self.assertEqual(a['features'].shape,(len(x),19))
self.assertGreater(m['all_wall_tetrahedra'],0)
self.assertTrue(np.isfinite(a['features']).all())
with self.assertRaises(ValueError):solve_eikonal(mesh(x,t),np.array([0]),0.)
if __name__=='__main__':unittest.main()
+39
View File
@@ -0,0 +1,39 @@
"""Accepted unit-change checks, with original eleven checks on new adapter."""
import json
from pathlib import Path
import resource
import time
import unittest
import numpy as np
import gre24_features_v2 as v2
import test_gre24_features as original
# Route the existing analytic tests to the new module without editing old evidence.
for name in ('mesh','exterior_faces','gate_nodes','solve_eikonal','cell_flow_speed','strict_volume_cdf',
'nodal_gradient','spatial_moment','per_geometry_metrics','appendix_summary','features'):
setattr(original,name,getattr(v2,name))
class ScaleChecks(unittest.TestCase):
def test_scale_invariance(self):
x,t=original.box();g=v2.mesh(x,t);src=np.flatnonzero(x[:,0]==0)
a=v2.solve_eikonal(g,src,2.,scale_override=1.)
b=v2.solve_eikonal(g,src,2.,scale_override=100.)
np.testing.assert_allclose(a,b,atol=1e-9,rtol=1e-9)
def test_tiny_speed_reaches_same_analytic_solution(self):
x,t=original.box();g=v2.mesh(x,t);src=np.flatnonzero(x[:,0]==0)
a=v2.solve_eikonal(g,src,.001)
np.testing.assert_allclose(a,x[:,0]/.001,atol=1e-6,rtol=1e-9)
if __name__=='__main__':
start=time.monotonic()
suite=unittest.TestSuite([unittest.defaultTestLoader.loadTestsFromTestCase(original.Gre24Checks),
unittest.defaultTestLoader.loadTestsFromTestCase(ScaleChecks)])
result=unittest.TextTestRunner(verbosity=2).run(suite)
usage=resource.getrusage(resource.RUSAGE_SELF)
Path('artifacts/gre24-reproduction-2026-11-15/synthetic-v2-receipt.json').write_text(json.dumps(dict(
tests=result.testsRun,failures=len(result.failures),errors=len(result.errors),passed=result.wasSuccessful(),
CPU_seconds=usage.ru_utime+usage.ru_stime,wall_seconds=time.monotonic()-start,peak_rss_bytes=usage.ru_maxrss*1024),indent=2))
raise SystemExit(0 if result.wasSuccessful() else 1)