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/r83';P=R/'results/l70';r=json.loads((O/'results.json').read_text())['records'];cp={x['filename']:x for x in json.loads((P/'results.json').read_text())['records']}
tot=lambda n,stage,k:sum(x['policies'][n]['stages'][stage][k] for x in r)
top=lambda n,k:sum(x['policies'][n]['top_matches_05'][str(k)] for x in r)
fig,ax=plt.subplots(figsize=(8,4));x=np.arange(4);a=[top('64',n) for n in (10,30,60,'all')];b=[top('256',n) for n in (10,30,60,'all')];ax.bar(x-.18,a,.36,label='64 prompts',color='#367f70');ax.bar(x+.18,b,.36,label='256 prompts',color='#ca7754');ax.set_xticks(x,['10','30','60','All']);ax.set(xlabel='Maximum candidates reviewed per field',ylabel='One-to-one matched shapes',title='Candidate matches across six human-cell fields');ax.set_ylim(0,50);ax.legend();fig.tight_layout();fig.savefig(O/'budget-comparison.png',dpi=140);plt.close(fig)
sections=[]
for row in r:
 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(i):m for i,m in zip(z['ids'],masks)};a=np.load(P/cp[row['filename']]['archive']);rgb=np.asarray(Image.open(R/'datasets/r82-revvity/images'/row['filename']).convert('RGB').resize((540,540),Image.Resampling.LANCZOS));out=Image.new('RGB',(1080,400),'white');d=ImageDraw.Draw(out)
 for j,(title,ms) in enumerate([('Source polygons',a['refs']),('64 prompts: top 30',[lookup[x] for x in row['policies']['64']['ranking'][:30]]),('256 prompts: top 30',[lookup[x] for x in row['policies']['256']['ranking'][:30]])]):
  tile=Image.fromarray(rgb).convert('RGBA')
  for i,m in enumerate(ms):
   layer=Image.new('RGBA',tile.size,['#008a70','#cd603b','#7357b4','#c29d2a'][i%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));d.text((j*360+5,10),title,fill='#203a38')
 pic=row['filename'][:-4]+'-comparison.png';out.save(O/pic);sections.append(f'<h3>{html.escape(row["filename"])}</h3><p>Top-30 matched: 64 prompts {row["policies"]["64"]["top_matches_05"]["30"]}, 256 prompts {row["policies"]["256"]["top_matches_05"]["30"]}; {len(row["reference_ids"])} coordinate-distinct reference shapes.</p><img src="{pic}" alt="Reference outlines and two prompt grid results">')
rows=''.join(f'<tr><th>{n} prompts</th><td>{tot(n,"raw","match_all_05")}</td><td>{tot(n,"eligible","match_all_05")}</td><td>{tot(n,"kept","match_all_05")}</td><td>{tot(n,"kept","candidate_count")}</td></tr>' for n in ('64','256'))
page=f'''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>R83 prompt coverage</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/l70/">Previous overlap test</a><h1>R83: Do prompts or filters lose overlapping cells?</h1><p class="box">Exploratory public <strong>human-cell</strong> fields, not diatoms. These six difficult fields were selected after annotation geometry was audited, and the 173 coordinate-distinct shapes are a sensitivity analysis, not adjudicated cell counts. This does not establish diatom or human-level performance.</p><p>The 256-point grid recovered {top('256','all')}/173 shapes after filtering versus {top('64','all')}/173 using an offset 64-point subgrid; it used four times as many prompts. At a fixed review budget of 30 candidates per field the scores were {top('256',30)}/173 and {top('64',30)}/173. Grids are not exact supersets of the earlier L70 8×8 grid.</p><img src="budget-comparison.png" alt="Bar chart comparing candidate matches at four review budgets"><h2>Where matches are lost</h2><p>Each stage shows maximum one-to-one matches at IoU ≥ 0.5 against all 173 distinct-coordinate references; raw matches are a diagnostic upper bound, with no ranking or operational review cost implied. Each stream's area/quality filters and within-stream IoU suppression are applied in that order. Stage match differences do not by themselves identify which exact objects were lost.</p><table><thead><tr><th>Grid</th><th>All raw</th><th>Eligible</th><th>After NMS</th><th>After NMS candidates</th></tr></thead><tbody>{rows}</tbody></table><p>One-to-one matching does not prove proposals are correct cells, unmatched proposals are not confirmed false positives, and scoring does not settle the identity of repeated source polygons. The fields and annotations were examined before this experiment. Source split group independence and model training overlap remain unknown. Preserve every raw mask and NMS link when moving this experiment to diatom scenes. Model input retains RGB but is downsampled to 540 pixels; full-size source images remain available. No user or expert review was required.</p><p><a href="/research/R83.md">Research note</a> · <a href="protocol.json">Predeclared protocol</a> · <a href="results.json">Results and suppression links</a> · <a href="/research/r83_verify.py">Replay verifier</a></p><h2>Field comparisons</h2>{''.join(sections)}</html>''';(O/'index.html').write_text(page)
