import json,html
from pathlib import Path
import numpy as np
from PIL import Image,ImageDraw
import matplotlib;matplotlib.use('Agg')
import matplotlib.pyplot as plt
R=Path(__file__).resolve().parents[1];O=R/'results/r84';rows=json.loads((O/'results.json').read_text())['records'];sel=json.loads((O/'selection.json').read_text())['records'];files=json.loads((O/'image-manifest.json').read_text())['files'];groups={'Gomphonema source folder':[r for r in rows if r['species_from_folder']=='gomphonema'],'Pinnularia source folder':[r for r in rows if r['species_from_folder']=='pinnularia'],'All selected fields':rows}
def score(group,n,b,t='.5'):return sum(r['policies'][n]['scores'][b]['0.5' if t=='.5' else '0.75']['matched'] for r in group)
fig,ax=plt.subplots(figsize=(8,4));x=np.arange(4)
for off,n,col in [(-.18,'64','#367f70'),(.18,'256','#ca7754')]:ax.bar(x+off,[score(rows,n,b) for b in ['10','30','60','all']],.36,label=n+' prompts',color=col)
ax.set_xticks(x,['10','30','60','All']);ax.set(xlabel='Candidate budget per field',ylabel='Matched source polygons',title='New source: matches at IoU 0.5');ax.set_ylim(0,32);ax.legend();fig.tight_layout();fig.savefig(O/'budget-comparison.png',dpi=140);plt.close(fig)
trs=''.join(f'<tr><th>{name}</th><td>{len(g)}</td><td>{sum(r["reference_count"] for r in g)}</td><td>{score(g,"64","10")}</td><td>{score(g,"256","10")}</td><td>{score(g,"64","30")}</td><td>{score(g,"256","30")}</td><td>{score(g,"64","all")}</td><td>{score(g,"256","all")}</td><td>{sum(r["policies"]["64"]["kept"] for r in g)} / {sum(r["policies"]["256"]["kept"] for r in g)}</td></tr>' for name,g in groups.items()); sections=[]
for row,s,f in zip(rows,sel,files):
 z=np.load(O/row['archive']);masks=np.unpackbits(z['mask_bits'])[:int(np.prod(z['mask_shape']))].reshape(z['mask_shape']).astype(bool);lookup={str(k):m for k,m in zip(z['ids'],masks)};orig=Image.open(R/f['path']).convert('RGB').resize((512,384),Image.Resampling.LANCZOS);rgb=Image.new('RGB',(512,512),'black');rgb.paste(orig,(0,64));out=Image.new('RGB',(1080,400),'white');draw=ImageDraw.Draw(out)
 for j,(title,ms) in enumerate([('Published source polygons',z['refs']),('64 prompts: top 30',[lookup[i] for i in row['policies']['64']['ranking'][:30]]),('256 prompts: top 30',[lookup[i] for i in row['policies']['256']['ranking'][:30]])]):
  tile=rgb.convert('RGBA')
  for k,m in enumerate(ms):
   layer=Image.new('RGBA',tile.size,['#008a70','#cd603b','#7357b4','#c29d2a'][k%4]);layer.putalpha(Image.fromarray(m.astype('uint8')*95));tile=Image.alpha_composite(tile,layer)
  out.paste(tile.convert('RGB').resize((350,350)),(j*360+5,35));draw.text((j*360+5,10),title,fill='#203a38')
 pic=f'field-{row["index"]:02d}.png';out.save(O/pic);sections.append(f'<h3>{html.escape(row["filename"])}</h3><p>{row["reference_count"]} source polygons; top-30 matches 64 prompts {row["policies"]["64"]["scores"]["30"]["0.5"]["matched"]}, 256 prompts {row["policies"]["256"]["scores"]["30"]["0.5"]["matched"]}. <a href="/{f["path"]}">Original image</a></p><img src="{pic}" alt="Reference polygons and two candidate mask streams">')
(O/'index.html').write_text(f'''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>R84 new-source diatom replay</title><style>body{{font:16px/1.55 system-ui;max-width:1100px;margin:2em auto;padding:0 1em;color:#18342f}}img{{max-width:100%}}a{{color:#006b59}}table{{border-collapse:collapse}}td,th{{border:1px solid #b8ccc0;padding:.5em;text-align:left}}.box{{background:#fff2d6;padding:1em}}</style><a href="/results/board.html">Research board</a> · <a href="/results/l71/">Previous diatom development replay</a><h1>R84: Dense prompts on a new diatom source</h1><p class="box"><strong>Overlap gap:</strong> None of the 29 selected source polygons overlap each other by 10 or more rasterized pixels. This experiment cannot establish overlap segmentation or human-level performance.</p><p>In 16 fields selected from a previously unexamined public archive, the 64- and 256-prompt grids each matched 24/29 source polygons at a budget of 30 candidates per field (IoU ≥ 0.5). With all kept candidates the dense grid matched 28/29 versus 24/29, while keeping 599 vs 219 candidates. These are source-polygon matches, not a false-positive rate or a claim that every cell was annotated.</p><img src="budget-comparison.png" alt="Chart of source polygons matched by two grid sizes at four review budgets"><table><thead><tr><th>Group</th><th>Fields</th><th>Source polygons</th><th>64 top 10</th><th>256 top 10</th><th>64 top 30</th><th>256 top 30</th><th>64 all</th><th>256 all</th><th>Kept 64 / 256</th></tr></thead><tbody>{trs}</tbody></table><p>At IoU ≥ 0.75, all-candidate matches were {score(rows,'64','all','.75')}/29 for 64 prompts and {score(rows,'256','all','.75')}/29 for 256 prompts. Four times the prompts and order-dependent filtering change computational and review costs.</p><h2>Source and selection limitations</h2><p>The <a href="https://zenodo.org/records/21295927">Khanom source dataset</a> reports two species and CC BY 4.0. The supplied COCO category names are blank, so the table uses archive folders, not verified species identifications. Sixteen fields were selected before viewing image pixels: up to eight from each largest test annotation file, with multiple source polygons prioritized and filenames occurring in corresponding training or validation annotations excluded. This enriched selection is not representative of population performance.</p><p>The complete Gomphonema annotation lists share filenames across splits; repeated archive members have identical CRCs. Selected filenames were excluded from these cross-split overlaps, but related images, specimens and slide origins could still recur. Checkpoint training overlap and biological independence are unknown. There is no expert verification of species or whether every object is labeled. Image input is isotropically reduced to 512×384 within a padded 512×512 canvas. Original RGB images and source archive are preserved.</p><p><a href="/research/R84.md">Research note</a> · <a href="selection.json">Predeclared selection</a> · <a href="protocol.json">Protocol</a> · <a href="annotation-audit.json">Split audit</a> · <a href="overlap-audit.json">Overlap audit</a> · <a href="archive-integrity.json">Archive hashes</a> · <a href="results.json">Results and suppression links</a> · <a href="/research/r84_verify.py">Verifier</a></p><h2>Field comparisons</h2><p>Images show source references and the top 30 masks from each candidate stream. Colored overlay drawing order can obscure boundaries.</p>{''.join(sections)}</html>''')
