"""Independently reconstruct post-hoc choice and metrics from saved masks."""
import json
from pathlib import Path
import numpy as np
from PIL import Image
from r112_scaleup_synthetic_compare import sha
R=Path(__file__).resolve().parents[1];O=R/'results/r112/source-mask-polygon-proxy';src=json.loads((O/'results.json').read_text());r=json.loads((O/'medoid-exploration.json').read_text());assert r['source_results_sha256']==sha(O/'results.json') and r['script_sha256']==sha(R/'research/r112_polygon_proxy_medoid.py');names=['center','minus','plus'];rows=[]
def iou(a,b):
 n=int((a|b).sum());return float((a&b).sum()/n) if n else 0.
for x,y in zip(src['records'],r['records']):
 assert x['id']==y['id'] and x['triage']==y['triage'];m=[np.asarray(Image.open(O/x['images'][k]['file']).convert('L'))>0 for k in names];ref=np.asarray(Image.open(O/x['images']['reference']['file']).convert('L'))>0;matrix=np.array([[iou(a,b) for b in m] for a in m]);scores=[float(matrix[i].sum()-matrix[i,i]) for i in range(3)];choice=max(range(3),key=lambda i:(scores[i],-i));chosen=names[choice];gated=chosen if x['triage']=='needs-inspection' else 'center';assert np.allclose(y['candidate_agreement_sums'],scores) and y['chosen']==chosen and y['gated_choice']==gated and abs(y['center_reference_iou']-iou(m[0],ref))<1e-12 and abs(y['chosen_reference_iou']-iou(m[choice],ref))<1e-12 and abs(y['gated_reference_iou']-iou(m[names.index(gated)],ref))<1e-12;rows.append(y)
assert len(rows)==29
for group in ('all','consistent-unverified','needs-inspection'):
 sub=[x for x in rows if group=='all' or x['triage']==group];counts={'cases':len(sub),'medoid_not_center':sum(x['chosen']!='center' for x in sub),'center_iou_ge_0_5':sum(x['center_reference_iou']>=.5 for x in sub),'medoid_iou_ge_0_5':sum(x['chosen_reference_iou']>=.5 for x in sub),'center_iou_ge_0_75':sum(x['center_reference_iou']>=.75 for x in sub),'medoid_iou_ge_0_75':sum(x['chosen_reference_iou']>=.75 for x in sub),'gated_iou_ge_0_5':sum(x['gated_reference_iou']>=.5 for x in sub),'gated_iou_ge_0_75':sum(x['gated_reference_iou']>=.75 for x in sub),'medoid_strictly_better':sum(x['chosen_reference_iou']>x['center_reference_iou']+1e-9 for x in sub),'medoid_strictly_worse':sum(x['chosen_reference_iou']<x['center_reference_iou']-1e-9 for x in sub)};assert r['counts'][group]==counts
out={'format':'r112-polygon-proxy-medoid-verify-v1','results_sha256':sha(O/'medoid-exploration.json'),'cases':len(rows),'checks':'Recomputed every proposal-pair IoU, medoid and gated selection, polygon IoUs and aggregate counts from saved mask pixels. Original model inference and biological correctness were not independently validated. Both heuristics were selected post hoc.'};(O/'medoid-verify.json').write_text(json.dumps(out,indent=2)+'\n');print(json.dumps(out,indent=2))
