"""Recompute saved head outputs and publish development comparisons."""
import collections,hashlib,html,json
from pathlib import Path
import numpy as np
R=Path(__file__).resolve().parents[1];P=R/'results/r112/design/synthetic-training-pilot';O=R/'results/r112/design/linear-training-pilot';sha=lambda p:hashlib.sha256(p.read_bytes()).hexdigest()
q=json.loads((O/'protocol.json').read_text());r=json.loads((O/'results.json').read_text());p=json.loads((P/'protocol.json').read_text());assert r['protocol_sha256']==sha(O/'protocol.json') and r['script_sha256']==sha(R/'research/r112_linear_pilot.py') and r['heads_sha256']==sha(O/'linear-heads.npz') and q['features_sha256']==sha(P/'features.npz') and q['prior_protocol_sha256']==sha(P/'protocol.json') and q['prior_results_sha256']==sha(P/'results.json');v=np.load(P/'features.npz')['validation'];heads=np.load(O/'linear-heads.npz');labels=r['labels'];assert labels==p['label_order'];counts={};case_outputs={};
for name in q['methods']:
 logits=v@heads[name+'_weight'].T+heads[name+'_bias'];saved=r['records'][name];assert np.allclose(logits,saved['logits'],atol=2e-5);pred=[labels[i] for i in logits.argmax(axis=1)];assert pred==saved['predictions'];counts[name]=sum(x==z['species'] for x,z in zip(pred,p['validation']));assert counts[name]==saved['correct'];case_outputs[name]=pred
base=case_outputs['real'];mix=case_outputs['real_plus_synthetic'];gain=sum(b!=x['species'] and m==x['species'] for x,b,m in zip(p['validation'],base,mix));lost=sum(b==x['species'] and m!=x['species'] for x,b,m in zip(p['validation'],base,mix));summary={'validation_cases':len(v),'source_filename_groups':len({x['source_slide'] for x in p['validation']}),'matches':counts,'mixed_vs_real_gained':gain,'mixed_vs_real_lost':lost,'checks':'Head weights, all saved logits and predictions and per-arm counts reconstructed from frozen stored features. Training, embedding extraction, source labels, sample independence and biological performance not independently validated.'};(O/'verify.log').write_text(json.dumps(summary,indent=2)+'\n')
e=html.escape;titles={'real':'Real source crops','synthetic':'Synthetic crops only','real_plus_synthetic':'Real + synthetic','real_plus_transformed':'Real + transformed control'}
table=''.join('<tr><th>'+e(titles[k])+'</th><td>'+str(counts[k])+'/50</td></tr>' for k in titles)
per=''
for species in labels:
 ix=[i for i,x in enumerate(p['validation']) if x['species']==species];per+='<tr><th>'+e(species)+'</th>'+''.join('<td>'+str(sum(case_outputs[k][i]==species for i in ix))+'/5</td>' for k in titles)+'</tr>'
cards=[]
for i,x in enumerate(p['validation']):
 pred=''.join('<li>'+e(titles[k])+': '+e(case_outputs[k][i])+(' ✓' if case_outputs[k][i]==x['species'] else '')+'</li>' for k in titles);cards.append('<article><a href="/results/r112/species-depth/'+e(x['local_file'])+'"><img loading="lazy" src="/results/r112/species-depth/'+e(x['local_file'])+'" alt="Source crop"></a><div><h3>'+e(x['species'])+'</h3><p>Annotation '+e(x['annotation_id'])+' · '+e(x['source_slide'])+'</p><ul>'+pred+'</ul></div></article>')
page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Learned species head: development test</title><style>body{font:16px/1.5 system-ui;color:#193b37;background:#f2f6f2;margin:0}main{max-width:1100px;margin:auto;padding:24px}a{color:#076c59}.notice{background:#fff8df;border-left:5px solid #b88418;padding:15px}table{border-collapse:collapse;background:white;max-width:100%;display:block;overflow:auto}td,th{border:1px solid #cbd8d1;padding:8px;text-align:left}article{display:flex;gap:20px;background:white;border:1px solid #d0ddd5;margin:12px 0;padding:14px}article img{width:180px;height:180px;object-fit:contain;background:#eee}@media(max-width:600px){article{display:block}}</style><body><main><nav><a href="/results/r112/">Synthetic training</a> · <a href="/results/r112/design/synthetic-training-pilot/">Earlier centroid comparison</a></nav><h1>Does synthetic imagery help a learned species head?</h1><p class="notice"><strong>Development comparison, not an independent test or Academy accuracy.</strong> The same 50 validation crops were used in an earlier experiment and that result motivated this follow-up. Each species has five crops from one filename group; biological independence and source names are unverified. The classifier has no unknown option and does not locate diatoms.</p><p>Four linear classification heads were trained separately on frozen generic ResNet-18 features from the same 153 development source specimens. Synthetic views are rectangles located using the known generator coordinates; transformed views control for resampling and an additional image per source. Optimizer settings and comparison arms were frozen before this run; the image encoder was not trained.</p><table><tr><th>Head training images</th><th>Source-name matches</th></tr>'''+table+'''</table><p>The mixed head matched two more names than real-only; '''+str(gain)+''' cases changed from incorrect to matching and '''+str(lost)+''' from matching to incorrect. With just ten potentially correlated slide-name groups this is insufficient evidence of a general gain. The synthetic-only head was weaker than real-only. No result establishes segmentation, unseen-species rejection or performance on Academy scans.</p><h2>By source name</h2><table><tr><th>Species</th>'''+''.join('<th>'+e(titles[k])+'</th>' for k in titles)+'</tr>'+per+'''</table><p><a href="protocol.json">Predeclared protocol</a> · <a href="results.json">Predictions and scores</a> · <a href="verify.log">Verification</a></p><h2>Individual crops</h2><p>A check means a prediction matches the source name, not that a scientist confirmed it.</p>'''+''.join(cards)+'''</main></body></html>''';(O/'index.html').write_text(page);print(json.dumps(summary,indent=2))
