Files
MeltMind/tools/s1_scoring_io.py
T

56 lines
3.6 KiB
Python

"""Explicit input adapter and strict output serialization; no execution on import."""
from dataclasses import asdict, is_dataclass
import hashlib
import json
from pathlib import Path
import numpy as np
from s1_scoring import Part
def sha(path):return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def load_part(spec,root,o2_root):
"""Use only released sampled O2 and the unchanged ordered draw; never geometry."""
root=Path(root);o2_root=Path(o2_root)
draw_path=root/spec['anchor_file'];receipt_path=draw_path.parent/'receipt.json'
for path in [draw_path,receipt_path]:
relative=str(path.relative_to(root))
if sha(path)!=spec['input_sha256'][relative]:raise ValueError('Frozen draw input changed: '+relative)
folder=o2_root/'panel'/spec['job'];result=json.loads((folder/'result.json').read_text())
supervisor=json.loads((o2_root/'panel'/(spec['job']+'.supervisor.json')).read_text())
if supervisor['status']!='PASS' or result['status']!='COMPLETE' or result['case']!=spec['case']:raise ValueError('Unreleased numerical part')
if sha(folder/'nodes.npz')!=result['output_sha256']['nodes.npz']:raise ValueError('O2 nodes hash differs')
if result['draw_file_sha256']!=sha(draw_path):raise ValueError('O2 used different draws')
receipt=json.loads(receipt_path.read_text())
if any(receipt[k]!=spec[k] for k in ['case','source_key','numeric_prefix']):raise ValueError('Draw source identity differs')
with np.load(draw_path,allow_pickle=False) as z:draw={k:z[k] for k in ['unique_ids','unique_raw_ids','multiplicity','draw_to_unique']}
with np.load(folder/'nodes.npz',allow_pickle=False) as z:
if not np.array_equal(z['anchor_ids'],draw['unique_ids']) or not np.array_equal(z['raw_node_ids'],draw['unique_raw_ids']) or not np.array_equal(z['multiplicity'],draw['multiplicity']):raise ValueError('Node/draw identity mismatch')
rg=float(result['R_g_raw']);thickness=float(result['t_part'])
if not np.isfinite([rg,thickness]).all() or min(rg,thickness)<=0:raise ValueError('Invalid full-part scale')
if thickness!=spec['t_part']:raise ValueError('Thickness changed')
features=np.column_stack([z['distance']/thickness,z['gate_length']/rg,z['g'],z['gate_q'],z['edge_summary']])
eligible=z['eligible'];near=z['near_wall']
if not np.array_equal(near,(z['distance']>0)&(z['distance']/thickness<=.25)):raise ValueError('Near-wall mask differs')
if len(draw['draw_to_unique'])!=2000 or int(eligible.sum())!=result['n_ref']:raise ValueError('Frozen counts differ')
p=Part(spec['case'],spec['source_key'],spec['numeric_prefix'],draw['unique_ids'],features,draw['multiplicity'],eligible,near,draw['draw_to_unique'],receipt['positive_mass_fraction'],provenance='real')
p.validate();return p
def json_ready(value):
"""NA -> null. Tuple-key diagnostics become key/value records, not ambiguous strings."""
if is_dataclass(value):return json_ready(asdict(value))
if isinstance(value,np.ndarray):return json_ready(value.tolist())
if isinstance(value,np.generic):return json_ready(value.item())
if isinstance(value,float) and not np.isfinite(value):return None
if isinstance(value,dict):
if any(isinstance(k,tuple) for k in value):return [dict(key=json_ready(k),value=json_ready(v)) for k,v in value.items()]
return {str(k):json_ready(v) for k,v in value.items()}
if isinstance(value,(tuple,list)):return [json_ready(v) for v in value]
return value
def save_report(path,value):
with Path(path).open('x') as f:json.dump(json_ready(value),f,indent=2,allow_nan=False);f.write('\n')