"""Reconstruct predictions and selected composites of the fixed comparison."""
import hashlib,json
from pathlib import Path
import numpy as np
from PIL import Image
from diatom_pilot.ude_scaleup_dataset import UDEScaleupDataset
from r112_scaleup_synthetic_compare import render,sha
R=Path(__file__).resolve().parents[1];D=R/'results/r112/species-scaleup';O=D/'synthetic-crop-comparison';B=D/'real-crop-baseline'
p=json.loads((O/'protocol.json').read_text());r=json.loads((O/'results.json').read_text());base=json.loads((B/'results.json').read_text())
assert r['protocol_sha256']==sha(O/'protocol.json') and r['script_sha256']==sha(R/'research/r112_scaleup_synthetic_compare.py')
for f,h in p['inputs_sha256'].items():assert sha(R/f)==h
assert r['synthetic_features_sha256']==sha(O/'synthetic-features.npz') and r['models_sha256']==sha(O/'models.npz')
train=UDEScaleupDataset('training',include_unverified_masks=True);tune=UDEScaleupDataset('tuning'); features=np.load(O/'synthetic-features.npz');v=np.load(B/'tuning-features.npz');models=np.load(O/'models.npz');assert features['annotation_ids'].tolist()==[x['annotation_id'] for x in train.entries] and np.isfinite(features['features']).all() and features['features'].shape==(2830,512)
assert len(r['composites'])==len(train) and [x['annotation_id'] for x in r['composites']]==features['annotation_ids'].tolist()
labels=base['labels'];truth=[x['source_species'] for x in tune.entries];genera=base['genera'];counts={}
for name in ('synthetic','mixed'):
 scores=v['features']@models[name+'_weight'].T+models[name+'_bias'];order=np.argsort(-scores,axis=1,kind='stable');pred=[labels[i] for i in order[:,0]];top5=[[labels[i] for i in row[:5]] for row in order];m=r['methods'][name];assert pred==m['predictions'] and top5==m['top5_names'];counts[name]={'top1':sum(a==b for a,b in zip(pred,truth)),'top5':sum(a in b for a,b in zip(truth,top5)),'genus':sum(genera[a]==x['source_genus'] for a,x in zip(pred,tune.entries))};assert all(m[k]==value for k,value in counts[name].items())
for i in (0,19,39,79):
 row=r['composites'][i];bgpath=R/row['background_path'];assert sha(bgpath)==row['background_sha256'];im,settings=render(train[i],np.asarray(Image.open(bgpath).convert('L')),row['background_scale_um_px'],row['seed']);assert all(settings[k]==row[k] for k in settings);assert np.array_equal(np.asarray(im),np.asarray(Image.open(R/row['example']))) and sha(R/row['example'])==row['example_sha256']
output={'format':'r112-scaleup-synthetic-comparison-verify-v1','results_sha256':sha(O/'results.json'),'counts':counts,'checked_composite_indices':[0,19,39,79],'checks':'Input and result hashes, all feature rows, labels, every prediction, top-five and genus score recomputed; four composite examples exactly reconstructed. Training optimization and all embeddings were not replayed. Check-partition pixels were not read. This does not validate masks, taxonomy, optics or Academy field performance.'};(O/'verify.json').write_text(json.dumps(output,indent=2)+'\n');print(json.dumps(output,indent=2))
