"""Fixed-protocol geometric calibration; no simulation-field reads.""" from pathlib import Path from zipfile import ZipFile import argparse import hashlib import json import os import resource import signal import time import numpy as np from g1_registration_cost import geometry_only, register from s2_e1_supervisor import save ROOT = Path(os.environ.get('MELTMIND_G1_CALIBRATION_ROOT', 'artifacts/s2-g1-copy-calibration-2026-11-14')) def transformed(g, kind, rotation, translation): r = np.asarray(rotation, dtype=float) t = np.asarray(translation, dtype=float) if kind not in ('rigid', 'mirror', 'scale'): raise ValueError('Unknown synthetic relation') if not np.allclose(r.T @ r, np.eye(3), atol=1e-12, rtol=0) or abs(np.linalg.det(r)-1) > 1e-12: raise ValueError('Base rotation must be proper') a = r @ (np.diag([-1., 1., 1.]) if kind == 'mirror' else np.eye(3)) scale = 2. if kind == 'scale' else 1. # Translation is expressed in multiples of the original volume Rg. shift = t * float(g['rg']) return {'points': scale * g['points'] @ a.T + shift, 'boundary': g['boundary'].copy(), 'center': scale * g['center'] @ a.T + shift, 'rg': np.asarray(scale * float(g['rg']))} def check_contract(root): c = json.loads((root/'contract.json').read_text()) for path, digest in c['code_sha256'].items(): if hashlib.sha256(Path(path).read_bytes()).hexdigest() != digest: raise ValueError('Source changed after calibration freeze: '+path) for path, digest in c['input_sha256'].items(): if hashlib.sha256(Path(path).read_bytes()).hexdigest() != digest: raise ValueError('Calibration input changed: '+path) return c def load_geometry(case, contract, jobroot): cache = Path(contract['existing_registration_cache'])/(case+'.npz') if cache.exists(): with np.load(cache, allow_pickle=False) as z: if set(z.files) != {'points','boundary','center','rg'}: raise ValueError('Registration cache is not strictly geometry-only') g = {k: z[k].copy() for k in z.files} mode = 'existing_geometry_only_registration_cache' else: with ZipFile(contract['archive']) as z, z.open(case+'_sim.vtu') as stream: g = geometry_only(stream) mode = 'VTU_geometry_prefix_stop_before_field_associations' if not all(np.isfinite(v).all() for v in g.values()) or float(g['rg']) <= 0: raise ValueError('Nonfinite geometry or invalid Rg') dest = jobroot/(case+'.npz') if dest.exists(): raise FileExistsError('Never overwrite calibration geometry') np.savez_compressed(dest, **g) return g, mode def expired(*_): raise TimeoutError('Per-pair 1800 second wall-clock limit') def main(): ap = argparse.ArgumentParser();ap.add_argument('index', type=int);args = ap.parse_args() c = check_contract(ROOT) verification = json.loads(Path(c['archive_verification']).read_text()) stat = Path(c['archive']).stat() if (stat.st_size,stat.st_mtime_ns,stat.st_ino) != (verification['bytes'],verification['mtime_ns'],verification['inode']): raise ValueError('Archive identity changed') plan = json.loads((ROOT/'custodian/plan.json').read_text()) job = plan['jobs'][args.index] work = ROOT/'custodian/results'/f'job-{args.index:02d}' work.mkdir(parents=True, exist_ok=False) start = time.monotonic();geometry = {};modes = {} for case in sorted(set(job['cases'])): geometry[case], modes[case] = load_geometry(case, c, work) signal.signal(signal.SIGALRM, expired) for pair in job['pairs']: a = geometry[pair['a']] b = geometry[pair['b']] if pair['kind']=='natural_visual_rigid' else transformed(a, pair['kind'], pair['rotation'], pair['unit_translation']) begin = time.monotonic();signal.setitimer(signal.ITIMER_REAL, c['per_pair_wall_seconds']) try: routes = register(a, b, pair['source_sampling_prefix'], pair['target_sampling_prefix']) finally: signal.setitimer(signal.ITIMER_REAL, 0) if not all(np.isfinite(r['residual_max_two_way_area_pps_p95']) for r in routes): raise ValueError('Nonfinite registration residual') rga, rgb = float(a['rg']), float(b['rg']) save(work/(pair['id']+'.json'), {'pair':pair, 'routes':routes, 'wall_seconds':time.monotonic()-begin, 'source_rg':rga, 'target_rg':rgb, 'mean_rg':(rga+rgb)/2, 'rg_ratio':max(rga,rgb)/min(rga,rgb), 'simulation_labels_read':False, 'model_training':False, 'residual_definition':'Unchanged two-way area-PPS 2000 samples to full triangles P95, best start in each det branch'}) print(json.dumps({'pair_id':pair['id'],'kind':pair['kind'],'status':'RESIDUALS_COMPLETE'}),flush=True) save(work/'complete.json', {'index':args.index,'pairs':len(job['pairs']),'source_modes':modes, 'cpu_seconds':sum(resource.getrusage(resource.RUSAGE_SELF)[:2]),'wall_seconds':time.monotonic()-start, 'max_rss_bytes':resource.getrusage(resource.RUSAGE_SELF).ru_maxrss*1024,'all_pass':True}) if __name__=='__main__':main()