"""Compare known-position species features across fixed synthetic signal gains."""
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
from r112_weak_scenes import transform,place
R=Path(__file__).resolve().parents[1];S=R/'results/r112/weak-development-v1';P=R/'results/r112/design/species-retention-corrected';O=R/'results/r112/design/species-gain-study';D=R/'results/r112/species-depth';H=D/'mask-hypotheses';CL=R/'results/pilot/ude-adaptation-within-genus/centroid-pilot/prototypes.npz';W=Path('/tmp/resnet18-f37072fd.pth');T=R/'results/pilot/ude-adaptation-within-genus/heldout-protocol.json'
def sha(p):
 h=hashlib.sha256()
 with open(p,'rb') as f:
  for b in iter(lambda:f.read(1048576),b''):h.update(b)
 return h.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);p=json.loads((O/'protocol.json').read_text());assert sha(P/'results.json')==p['prior_results_sha256'] and sha(S/'manifest.json')==p['weak_scenes_sha256'] and sha(T)==p['classifier_protocol_sha256'] and sha(CL)==p['classifier_prototypes_sha256'] and sha(W)==p['classifier_encoder_sha256'];old=json.loads((P/'results.json').read_text());assert len(old['records'])==59;scenes={r['id']:r for r in json.loads((S/'manifest.json').read_text())['records']};labels=json.loads(T.read_text())['label_order'];cent=np.load(CL)['generic'];model=resnet18(weights=None);model.load_state_dict(torch.load(W,map_location='cpu',weights_only=True));model.fc=torch.nn.Identity();model.eval();cache={};scene_records={};rows=[];features=[];start=time.monotonic()
 for i,r in enumerate(old['records']):
  scene=scenes[r['scene_id']];ident=scene['id'];idx=r['instance_index'];obj=scene['instances'][idx];assert obj['annotation_id']==r['annotation_id'];bg=R/scene['background']['path'];assert sha(bg)==scene['background']['sha256'];background=np.asarray(Image.open(bg).convert('L'));sx,sy=scene['background_um_per_pixel_xy'];archive=S/scene['mask_archive'];assert sha(archive)==scene['mask_archive_sha256'];z=np.load(archive);shape=tuple(z['support_shape']);supports=np.unpackbits(z['support_bits'])[:np.prod(shape)].reshape(shape).astype(bool);target=supports[idx];assert target.any();
  if ident not in cache:
   variants={};scene_info={}
   for gain in p['gains']:
    canvas=background.copy()
    for j,x in enumerate(scene['instances']):
     sp=D/x['source_original'];mp=H/x['source_mask_center'];assert sha(sp)==x['source_original_sha256'] and sha(mp)==x['source_mask_center_sha256'];im=np.asarray(Image.open(sp).convert('L'));mask=np.asarray(Image.open(mp).convert('L'))>0;transformed,tm,dims=transform(im,mask,sx,sy,x['rotation_ccw_degrees']);assert dims==x['resampled_dimensions_px'];support=place(canvas,transformed,tm,x['center_xy'],x['opacity'],x['contrast']*gain,x['source_background_median']);assert np.array_equal(support,supports[j])
    if gain==1.:assert sha(S/scene['image'])==scene['image_sha256'] and np.array_equal(canvas,np.asarray(Image.open(S/scene['image']).convert('L')))
    filename=f"{ident}-gain{int(gain)}.png";path=O/filename;Image.fromarray(canvas).save(path);scene_info[str(int(gain))]={'image':filename,'sha256':sha(path)};variants[str(int(gain))]=canvas
   cache[ident]=variants;scene_records[ident]=scene_info
  variants=cache[ident];x0,y0,x1,y1=r['roi_xyxy'];stage={};vecs=[]
  for gain in p['gains']:
   key=str(int(gain));canvas=variants[key];crop=Image.fromarray(canvas[y0:y1,x0:x1]);feature=embedding(model,crop);scores=cent@feature;prediction=labels[int(np.argmax(scores))];new_extreme=((canvas==0)|(canvas==255))&~((background==0)|(background==255));path=O/f"{r['annotation_id']}-gain{key}-crop.png";crop.save(path);record={'image':path.name,'image_sha256':sha(path),'prediction':prediction,'matches_source_name':prediction==r['source_species'],'scores':[float(x) for x in scores],'target_support_pixels':int(target.sum()),'new_boundary_pixels_within_target_support':int((new_extreme&target).sum())};stage[key]=record;vecs.append(feature)
  assert stage['1']['prediction']==r['stages']['composite']['prediction'] and stage['1']['image_sha256']==r['stages']['composite']['image_sha256'];features.append(np.stack(vecs));rows.append({'annotation_id':r['annotation_id'],'source_species':r['source_species'],'source_slide_group':r['source_slide_group'],'scene_id':ident,'instance_index':idx,'roi_xyxy':r['roi_xyxy'],'in_frame_fraction':r['in_frame_fraction'],'synthetic_overlap_pixels':r['synthetic_overlap_pixels'],'original_source_prediction':r['stages']['original']['prediction'],'original_source_match':r['stages']['original']['matches_source_name'],'source_original_crop':'../species-retention-corrected/'+r['stages']['original']['image'],'variants':stage});(O/'partial.json').write_text(json.dumps({'records':rows},indent=2)+'\n')
  if (i+1)%10==0:print(i+1,'/',len(old['records']),'unique scenes',len(cache),'elapsed',round(time.monotonic()-start,1),flush=True)
 np.savez_compressed(O/'features.npz',features=np.stack(features),annotation_ids=np.array([r['annotation_id'] for r in rows]));result={'format':'r112-species-gain-study-v1','protocol_sha256':sha(O/'protocol.json'),'script_sha256':sha(__file__),'features_sha256':sha(O/'features.npz'),'labels':labels,'scene_variants':scene_records,'records':rows,'warning':'Previously viewed development samples; classifier is closed set, source labels/supports and physical realism unverified. Scores and saturation proxies are not Academy performance or ground-truth quality.'};(O/'results.json').write_text(json.dumps(result,indent=2)+'\n');print('done',len(rows),'cases',len(cache),'scenes',flush=True)
if __name__=='__main__':main()
