"""Verify and publish the frozen preliminary source-crop comparison."""
import collections,hashlib,html,json
from pathlib import Path
import numpy as np
R=Path(__file__).resolve().parents[1];O=R/'results/r112/design/synthetic-training-pilot';D=R/'results/r112/species-depth'
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
p=json.loads((O/'protocol.json').read_text());r=json.loads((O/'results.json').read_text());assert r['protocol_sha256']==sha(O/'protocol.json') and r['features_sha256']==sha(O/'features.npz') and r['script_sha256']==sha(R/'research/r112_training_pilot.py')
for f,h in p['inputs_sha256'].items():assert sha(R/f)==h
z=np.load(O/'features.npz');t=z['training'];v=z['validation'];assert t.shape==(len(p['training']),3,512) and v.shape==(len(p['validation']),512);assert np.isfinite(t).all() and np.isfinite(v).all() and np.allclose(np.linalg.norm(t,axis=2),1,atol=1e-5) and np.allclose(np.linalg.norm(v,axis=1),1,atol=1e-5)
unit=lambda x:x/np.linalg.norm(x,axis=-1,keepdims=True)
inputs={'real':t[:,0],'synthetic':t[:,2],'real_plus_synthetic':(t[:,0]+t[:,2])/2,'real_plus_transformed':(t[:,0]+t[:,1])/2};cnt={};rows=[]
for k,x in inputs.items():
 c=unit(np.stack([x[[a['species']==label for a in p['training']]].mean(axis=0) for label in p['label_order']])); assert np.allclose(c,z['centroid_'+k],atol=1e-6)
 cnt[k]=0
 for i,case in enumerate(r['validation']):
  assert {k:case[k] for k in p['validation'][i]}==p['validation'][i] and sha(D/case['local_file'])==case['sha256'];scores=c@v[i];out=case['outputs'][k];assert np.allclose(scores,out['scores'],atol=1e-6) and out['prediction']==p['label_order'][np.argmax(scores)] and out['correct']==(out['prediction']==case['species']);cnt[k]+=out['correct']
assert cnt==r['counts'];assert not {x['source_slide'] for x in p['training']} & {x['source_slide'] for x in p['validation']};assert not {x['annotation_id'] for x in p['training']} & {x['annotation_id'] for x in p['validation']}
summary={'training_sources':len(t),'validation_crops':len(v),'validation_slide_groups':len({x['source_slide'] for x in p['validation']}),'source_rectangle_clipped':sum(x['source_rectangle_clipped'] for x in r['training_geometry']),'counts':cnt,'checks':'Input hashes, feature shapes and normalization, source-slide separation, saved centroids and every validation prediction reconstructed. Does not validate species labels, sample independence, model features or biological accuracy.'};(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(cnt[k])+'/50</td><td>'+str(2*cnt[k])+'%</td></tr>' for k in titles)
per=''
for species in p['label_order']:
 cases=[x for x in r['validation'] if x['species']==species]; per+='<tr><th>'+e(species)+'</th>'+''.join('<td>'+str(sum(x['outputs'][k]['correct'] for x in cases))+'/5</td>' for k in titles)+'</tr>'
for x in r['validation']:
 pred=''.join('<li>'+e(titles[k])+': '+e(x['outputs'][k]['prediction'])+(' ✓' if x['outputs'][k]['correct'] else '')+'</li>' for k in titles)
 rows.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="Validation source crop"></a><div><h3>'+e(x['species'])+'</h3><p>Source annotation '+e(x['annotation_id'])+'; filename group '+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>Synthetic training comparison</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}article h3{margin:0}article ul{margin:0}@media(max-width:600px){article{display:block}}</style><body><main><nav><a href="/results/r112/">Synthetic training project</a> · <a href="/results/r112/weak-development-v1/">Synthetic scenes</a></nav><h1>Do synthetic crops improve species identification?</h1><p class="notice"><strong>Preliminary comparison, not an Academy accuracy estimate.</strong> Only ten source-named species are possible; there is no unknown option. Labels and masks have not been checked by a scientist. Five crops per species come from the same filename-derived slide group, and different slide names do not prove independent biological samples. The validation crops are now used; candidate test crops were not evaluated.</p><p>We used 153 distinct development specimens to build a frozen generic ResNet-18 feature centroid for each class. Synthetic crops use the known insertion rectangle in a generated scene, so this experiment does not test automatic detection or segmentation. The original Academy background can contain unlabeled diatoms. Each mixed method uses the same source specimens and equal weight for both views.</p><table><tr><th>Reference images</th><th>Exact source-name matches</th><th>Fraction</th></tr>'''+table+'''</table><p>Real + synthetic gained one match over real alone; this is too small and the sample too correlated to establish an improvement. Synthetic alone scored lower. The transformed control helps separate the effects of adding a second view from adding scene context, but these differences also include resampling, clipping and background changes. None establishes species-level performance on microscope scans.</p><h2>By source-named species</h2><table><tr><th>Species</th>'''+''.join('<th>'+e(titles[k])+'</th>' for k in titles)+'</tr>'+per+'''</table><p><a href="protocol.json">Frozen protocol and selected source IDs</a> · <a href="results.json">Predictions and scores</a> · <a href="verify.log">Verification</a> · <a href="/research/R112_DESIGN.md">Research notes</a></p><h2>Validation crops and predictions</h2><p>Click any crop to inspect it. A check mark means the prediction matches the source dataset name, not that an expert confirmed it.</p>'''+''.join(rows)+'''</main></body></html>''';(O/'index.html').write_text(page);print(json.dumps(summary,indent=2))
