"""Recompute source-name scores and replay selected frozen-encoder features."""
import ctypes,hashlib,json,os,signal
from pathlib import Path
import numpy as np,torch
from torchvision.models import resnet18
from diatom_pilot.ude_scaleup_dataset import UDEScaleupDataset
from run_field import embedding
R=Path(__file__).resolve().parents[1];O=R/'results/r112/species-scaleup/real-crop-baseline';W=Path('/tmp/resnet18-f37072fd.pth');sha=lambda p:hashlib.sha256(Path(p).read_bytes()).hexdigest();parent=os.getppid();assert ctypes.CDLL(None,use_errno=True).prctl(1,signal.SIGTERM)==0
if parent!=os.getppid():raise RuntimeError('launcher exited')
torch.set_num_threads(2);p=json.loads((O/'protocol.json').read_text());r=json.loads((O/'results.json').read_text());assert sha(O/'protocol.json')==r['protocol_sha256'] and sha(R/'research/r112_scaleup_real_baseline.py')==r['script_sha256'] and sha(W)==p['encoder_sha256'] and sha(O/'training-features.npz')==r['training_feature_sha256'] and sha(O/'tuning-features.npz')==r['tuning_feature_sha256'] and sha(O/'models.npz')==r['models_sha256']
for f,h in p['inputs_sha256'].items():assert sha(R/f)==h
train=UDEScaleupDataset('training');tune=UDEScaleupDataset('tuning');a=np.load(O/'training-features.npz');v=np.load(O/'tuning-features.npz');z=np.load(O/'models.npz');assert a['annotation_ids'].tolist()==[x['annotation_id'] for x in train.entries] and v['annotation_ids'].tolist()==[x['annotation_id'] for x in tune.entries];assert not {x['source_site_component'] for x in train.entries}&{x['source_site_component'] for x in tune.entries};A=a['features'];V=v['features'];assert A.shape==(2830,512) and V.shape==(604,512) and np.isfinite(A).all() and np.isfinite(V).all() and np.allclose(np.linalg.norm(A,axis=1),1,atol=1e-5) and np.allclose(np.linalg.norm(V,axis=1),1,atol=1e-5);labels=r['labels'];assert len(labels)==80 and set(labels)=={x['source_species'] for x in train.entries}=={x['source_species'] for x in tune.entries};cent=[]
for name in labels:
 avg=A[[x['source_species']==name for x in train.entries]].mean(0);cent.append(avg/np.linalg.norm(avg))
cent=np.stack(cent);assert np.allclose(cent,z['centroids'],atol=1e-6);scores={'centroid':V@cent.T,'linear':V@z['linear_weight'].T+z['linear_bias']};counts={}
for name,score in scores.items():
 saved=r['methods'][name];assert np.allclose(score,saved['scores'],atol=2e-5);order=np.argsort(-score,axis=1,kind='stable');pred=[labels[i] for i in order[:,0]];top5=[[labels[i] for i in row[:5]] for row in order];assert pred==saved['predictions'] and top5==saved['top5_names'];truth=[x['source_species'] for x in tune.entries];genera=[x['source_genus'] for x in tune.entries];stats={'top1':sum(x==y for x,y in zip(pred,truth)),'top5':sum(x in y for x,y in zip(truth,top5)),'genus':sum(r['genera'][x]==y for x,y in zip(pred,genera))};assert all(saved[k]==v for k,v in stats.items());counts[name]=stats
 for label in labels:
  ix=[i for i,x in enumerate(truth) if x==label];expected={'count':len(ix),'top1':sum(pred[i]==label for i in ix),'top5':sum(label in top5[i] for i in ix),'genus':sum(r['genera'][pred[i]]==genera[i] for i in ix)};assert saved['per_source_name'][label]==expected
model=resnet18(weights=None);model.load_state_dict(torch.load(W,map_location='cpu',weights_only=True));model.fc=torch.nn.Identity();model.eval();replayed={}
for name,d,arr in [('training',train,A),('tuning',tune,V)]:
 ix=[0,len(d)//3,2*len(d)//3,len(d)-1]
 for i in ix:assert np.allclose(embedding(model,d[i]['image']),arr[i],atol=1e-6)
 replayed[name]=ix
out={'format':'r112-scaleup-real-verify-v1','scored_tuning_crops':len(tune),'training_crops':len(train),'source_name_strings':len(labels),'counts':counts,'feature_indices_replayed':replayed,'checks':'All input hashes, location separation, stored feature normalization, class centroids, predicted names and every aggregate/per-name metric reconstructed; eight encoder embeddings replayed. Linear-head optimization was not rerun. Check-partition pixels were not used here. This does not validate taxonomy, true biological independence, segmentation or Academy performance.'};(O/'verify.json').write_text(json.dumps(out,indent=2)+'\n');print(json.dumps(out,indent=2))
