import json
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/r86';rows=json.loads((O/'results.json').read_text())['records'];names=['baseline','lower_area','lower_quality','lower_both'];label=['Baseline','Lower area','Lower quality','Both lower'];fig,axes=plt.subplots(1,2,figsize=(10,4));axes[0].bar(label,[sum(r['policies'][n]['scores']['30'] for r in rows) for n in names],color=['#367f70','#ca7754','#7059a5','#af9060']);axes[0].set_ylim(0,70);axes[0].set_ylabel('Top-30 matched source polygons');axes[1].bar(label,[sum(r['policies'][n]['kept'] for r in rows) for n in names],color=['#367f70','#ca7754','#7059a5','#af9060']);axes[1].set_ylabel('Retained candidate masks');fig.tight_layout();fig.savefig(O/'filter-comparison.png',dpi=140);plt.close(fig)
case=next(r for r in rows if r['oracle_assignments_if_gap']);src=json.loads((R/'results/l71/results.json').read_text())['records'][case['index']];z=np.load(R/'results/l71'/src['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(R/'results/r78'/src['ref_archive']);rgb=np.asarray(Image.open(src['image']).convert('RGB'));failed=next(x for x in case['oracle_assignments_if_gap'] if not x['eligible_baseline']);out=Image.new('RGB',(1080,400),'white');draw=ImageDraw.Draw(out)
for j,(title,ms) in enumerate([('Source polygons',a['refs_visible']),('Baseline: top 30',[lookup[k] for k in case['policies']['baseline']['ranking'][:30]]),('Low-quality recovered mask',[lookup[failed['candidate_id']]])]):
 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')
out.save(O/'filter-miss.png');trs=''.join(f'<tr><th>{name}</th><td>{sum(r["policies"][name]["kept"] for r in rows)}</td>'+''.join(f'<td>{sum(r["policies"][name]["scores"][b] for r in rows)}</td>' for b in ('10','30','60','all'))+'</tr>' for name in names)
(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>R86 candidate filter audit</title><style>body{{font:16px/1.55 system-ui;max-width:1050px;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><h1>R86: Did eligibility filters remove useful masks?</h1><p class="box">Development replay on 40 already viewed fields; source annotations are incomplete and no severe real overlap is established. This is not a species, precision or human-level assessment.</p><p>The one raw-mask match absent after baseline eligibility had quality {failed['quality']:.3f}, area {failed['area']} pixels and IoU {failed['iou']:.3f} with its source polygon. Lowering the fixed quality cutoff from 0.60 to 0.45 recovered one source match across these fields: top 30 increased 52 to 53 of 70 source polygons. Retained candidates increased from 1,343 to 1,575. This is an exploratory lead, not evidence about unseen slides.</p><img src="filter-comparison.png" alt="Matched source polygons and retained candidate counts under four filters"><table><thead><tr><th>Filter</th><th>Retained</th><th>Top 10</th><th>Top 30</th><th>Top 60</th><th>All</th></tr></thead><tbody>{trs}</tbody></table><p>Baseline requires area 300–50,000 and quality ≥0.60. Lower-area uses minimum 75, lower-quality uses ≥0.45, and both combines the two. All variants use the same 0.8 within-stream IoU suppression and quality ranking. Lowering the area cutoff did not improve total matching and reduced the top-30 count. One-to-one matching is measured at IoU 0.5; unmatched proposals are not verified false positives.</p><h2>One diagnostic field</h2><p>The reference-to-mask correspondence was identified using ground truth after inference. The recovered mask is one possible raw-oracle assignment; it was not used to define the filter.</p><img src="filter-miss.png" alt="Reference polygons, baseline candidate masks and one previously filtered mask"><p><a href="/research/R86.md">Research note</a> · <a href="protocol.json">Frozen protocol</a> · <a href="results.json">All field scores and filter links</a> · <a href="/research/r86_verify.py">Replay verifier</a> · <a href="/results/l73/">Prior suppression audit</a></p></html>''')
