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/l71';P=R/'results/r78';rows=json.loads((O/'results.json').read_text())['records'];groups={'synthetic separated':[r for r in rows if r['group']=='synthetic' and r['condition']=='separated'],'synthetic crossing':[r for r in rows if r['group']=='synthetic' and r['condition']=='crossing'],'real Menne':[r for r in rows if r['group']=='menne']}
def score(g,n,b):return sum(r['policies'][n]['matches'][b] for r in g)
fig,axes=plt.subplots(1,3,figsize=(12,3.8)); x=np.arange(4)
for ax,(name,items) in zip(axes,groups.items()):
 for off,n,col in [(-.18,'64','#367f70'),(.18,'256','#ca7754')]:ax.bar(x+off,[score(items,n,b) for b in ['10','30','60','all']],.36,label=n+' prompts',color=col)
 ax.set_title(name);ax.set_xticks(x,['10','30','60','All']);ax.set_xlabel('Candidates / field');ax.set_ylabel('Matched source shapes');ax.legend(fontsize=8)
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["references"] 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></tr>' for name,g in groups.items());sections=[]
for row in rows:
 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)};a=np.load(P/row['ref_archive']);rgb=np.asarray(Image.open(row['image']).convert('RGB'));out=Image.new('RGB',(1080,400),'white');draw=ImageDraw.Draw(out)
 for j,(title,ms) in enumerate([('Source reference shapes',a['refs_visible']),('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=Image.fromarray(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'scene-{row["index"]:02d}.png';out.save(O/pic);title=f"{row['group']} {row.get('condition') or row.get('image_id')}";sections.append(f'<h3>{html.escape(title)}</h3><p>Reference shapes: {row["references"]}. Top-30 matches: 64 prompts {row["policies"]["64"]["matches"]["30"]}, 256 prompts {row["policies"]["256"]["matches"]["30"]}.</p><img src="{pic}" alt="Reference and model mask comparison">')
(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>L71 dense diatom prompts</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:#eef5f1;padding:1em}}</style><a href="/results/board.html">Research board</a> · <a href="/results/r83/">Prior out-of-domain test</a><h1>L71: Does a denser prompt grid help diatoms?</h1><p class="box">Development replay on 24 previously examined scenes; not an independent benchmark or a claim of human-level segmentation. Three synthetic overlapping scenes are rendered from known source cutouts. The 18 real River Menne fields have incomplete source-region labels and do not establish overlap or partial-instance accuracy.</p><p>Grid points are image-only, with 64 nested in 256; the larger grid uses four times as many prompts. Area and quality filtering and order-dependent NMS are applied separately to each stream. At each review budget, one-to-one matching counts reference polygons at IoU ≥ 0.5. More raw prompts do not guarantee more kept matches.</p><img src="budget-comparison.png" alt="Bar chart comparing the number of matched diatom reference shapes"><table><thead><tr><th>Group</th><th>Fields</th><th>Reference shapes</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></tr></thead><tbody>{trs}</tbody></table><p>Unmatched proposals are not verified false positives. Synthetic visible source shapes are not expert-verified hidden boundaries; the images and cutouts are not independent specimens. The pretrained model's exposure to these sources is unknown. RGB source images and annotations are hash-verified; original focal provenance is inherited from earlier source records, where available. Point masks and suppression links are saved for every field.</p><p><a href="/research/L71.md">Research note</a> · <a href="protocol.json">Frozen protocol</a> · <a href="results.json">Field results and suppression links</a> · <a href="/research/l71_verify.py">Replay verifier</a></p><h2>Field comparisons</h2><p>Overlay drawing order can hide overlapping boundaries; each color is a separate mask.</p>{''.join(sections)}</html>''')
