"""Compare frozen linear-head training on paired renderer alternatives."""
import ctypes,hashlib,json,os,signal,time
from pathlib import Path
import numpy as np,torch
from PIL import Image
from torchvision.models import resnet18
from run_field import embedding
R=Path(__file__).resolve().parents[1];O=R/'results/r112/design/transmission-study';P=R/'results/r112/design/synthetic-training-pilot';L=R/'results/r112/design/linear-training-pilot';W=Path('/tmp/resnet18-f37072fd.pth')
def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def main():
 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);q=json.loads((O/'protocol.json').read_text());assert not (O/'results.json').exists()
 for f,h in q['inputs_sha256'].items():assert sha(R/f)==h
 assert sha(W)==q['encoder_sha256'];m=json.loads((O/'manifest.json').read_text());assert m['protocol_sha256']==sha(O/'protocol.json');p=json.loads((P/'protocol.json').read_text());old=json.loads((P/'results.json').read_text());prior=json.loads((L/'results.json').read_text());assert old['protocol_sha256']==sha(P/'protocol.json') and old['features_sha256']==sha(P/'features.npz');z=np.load(P/'features.npz');a=z['training'];v=z['validation'];records={x['scene_id']:x for x in m['records']};model=resnet18(weights=None);model.load_state_dict(torch.load(W,map_location='cpu',weights_only=True));model.fc=torch.nn.Identity();model.eval();new=[];start=time.monotonic()
 for i,r in enumerate(p['training']):
  scene=records[r['scene_id']];file=O/scene['image'];assert sha(file)==scene['image_sha256'];image=Image.open(file).convert('L');box=old['training_geometry'][i]['roi_xyxy'];crop=image.crop(tuple(box));new.append(embedding(model,crop))
  if (i+1)%50==0:print('features',i+1,'/',len(p['training']),'elapsed',round(time.monotonic()-start,1),flush=True)
 new=np.stack(new);labels=p['label_order'];y=torch.tensor([labels.index(r['species']) for r in p['training']],dtype=torch.long);vt=torch.tensor([labels.index(r['species']) for r in p['validation']],dtype=torch.long);n=len(y);weights=1/torch.bincount(y,minlength=len(labels)).float()[y];weights/=weights.sum();V=torch.from_numpy(v);out={};params={}
 for name,views in [('transmission_only',[new]),('real_plus_transmission',[a[:,0],new])]:
  x=torch.from_numpy(np.stack(views,axis=1));head=torch.nn.Linear(512,len(labels));torch.nn.init.zeros_(head.weight);torch.nn.init.zeros_(head.bias);optim=torch.optim.Adam(head.parameters(),lr=.05);losses=[]
  for step in range(300):
   optim.zero_grad();loss=torch.nn.functional.cross_entropy(head(x).reshape(-1,len(labels)),y[:,None].expand(-1,len(views)).reshape(-1),reduction='none').reshape(n,len(views)).mean(1);objective=(loss*weights).sum()+.0001*head.weight.square().sum();objective.backward();optim.step()
   if step in (0,49,99,199,299):losses.append(float(objective.detach()))
  with torch.no_grad():logits=head(V);pred=logits.argmax(1);out[name]={'correct':int((pred==vt).sum()),'predictions':[labels[j] for j in pred.tolist()],'logits':logits.tolist(),'loss_checkpoints':losses};params[name+'_weight']=head.weight.detach().numpy();params[name+'_bias']=head.bias.detach().numpy()
 np.savez_compressed(O/'features-and-heads.npz',transmission_features=new,**params);result={'format':'r112-transmission-comparison-v1','protocol_sha256':sha(O/'protocol.json'),'render_manifest_sha256':sha(O/'manifest.json'),'script_sha256':sha(__file__),'data_sha256':sha(O/'features-and-heads.npz'),'baseline_counts':{k:v['correct'] for k,v in prior['records'].items()},'alternative':out,'warning':q['limits']};(O/'results.json').write_text(json.dumps(result,indent=2)+'\n');print('baseline',result['baseline_counts'],'alternative',{k:v['correct'] for k,v in out.items()},flush=True)
if __name__=='__main__':main()
