"""Replay fixed linear-head training from the stored features and compare weights."""
import json
from pathlib import Path
import numpy as np,torch
R=Path(__file__).resolve().parents[1];P=R/'results/r112/design/synthetic-training-pilot';O=R/'results/r112/design/linear-training-pilot';torch.set_num_threads(2);p=json.loads((P/'protocol.json').read_text());z=np.load(P/'features.npz');weights=np.load(O/'linear-heads.npz');a=z['training'];labels=p['label_order'];y=torch.tensor([labels.index(x['species']) for x in p['training']],dtype=torch.long);class_size=torch.bincount(y,minlength=10).float();w=1/class_size[y];w/=w.sum();maxdelta=0.
for name,views in [('real',[0]),('synthetic',[2]),('real_plus_synthetic',[0,2]),('real_plus_transformed',[0,1])]:
 x=torch.from_numpy(a[:,views,:].copy());head=torch.nn.Linear(512,10);torch.nn.init.zeros_(head.weight);torch.nn.init.zeros_(head.bias);opt=torch.optim.Adam(head.parameters(),lr=.05)
 for step in range(300):
  opt.zero_grad();loss=torch.nn.functional.cross_entropy(head(x).reshape(-1,10),y[:,None].expand(-1,len(views)).reshape(-1),reduction='none').reshape(len(y),len(views)).mean(1);objective=(loss*w).sum()+.0001*head.weight.square().sum();objective.backward();opt.step()
 for k,t in [('weight',head.weight),('bias',head.bias)]:
  delta=float(np.max(np.abs(t.detach().numpy()-weights[name+'_'+k])));maxdelta=max(maxdelta,delta);assert delta<1e-6
print(json.dumps({'arms_retrained':4,'steps_per_arm':300,'maximum_parameter_absolute_difference':maxdelta,'limitations':'Same runtime and algorithm; does not validate feature extractor, labels, sample independence, task performance or physical realism.'},indent=2))
