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/r87';rows=json.loads((O/'support-results.json').read_text())['records'];sources=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'];names=['baseline','low_all','repeat_support','high_support'];labels=['Baseline','Admit all weak','Repeat support','High-quality support'];cols=['#367f70','#ca7754','#7059a5','#af9060'];fig,ax=plt.subplots(1,2,figsize=(11,4));ax[0].bar(labels,[sum(r['policies'][n]['scores']['30'] for r in rows) for n in names],color=cols);ax[0].set_ylim(0,32);ax[0].set_ylabel('Top-30 matched source polygons');ax[1].bar(labels,[sum(r['policies'][n]['kept'] for r in rows) for n in names],color=cols);ax[1].set_ylabel('Retained masks');
for a in ax:a.tick_params(axis='x',labelrotation=12)
fig.tight_layout();fig.savefig(O/'support-comparison.png',dpi=140);plt.close(fig);trs=''.join(f'<tr><th>{label}</th><td>{sum(r["policies"][name]["admitted"] for r in rows)}</td><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 label,name in zip(labels,names));sections=[]
for row,source,s,f in zip(rows,sources,sel,files):
 z=np.load(O/source['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)};rgb=Image.new('RGB',(512,512),'black');rgb.paste(Image.open(R/f['path']).convert('RGB').resize((512,384),Image.Resampling.LANCZOS),(0,64));out=Image.new('RGB',(1080,400),'white');draw=ImageDraw.Draw(out)
 for j,(title,ms) in enumerate([('Source polygons',z['refs']),('Baseline top 30',[lookup[k] for k in row['policies']['baseline']['ranking'][:30]]),('High support top 30',[lookup[k] for k in row['policies']['high_support']['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(s["filename"])}</h3><p>Source polygons: {row["references"]}; baseline and high-support top-30 matches: {row["policies"]["baseline"]["scores"]["30"]} / {row["policies"]["high_support"]["scores"]["30"]}. <a href="/{f["path"]}">Original image</a></p><img src="{pic}" alt="Source polygons and two candidate policies">')
(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>R87 fresh-image support replay</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> · <a href="/results/l74/">Development result</a><h1>R87: Does weak-mask support generalize to fresh images?</h1><p class="box">Sixteen image files selected before pixel inspection from the same public archive previously used in R84/R85. Source filenames previously seen in those experiments or shared across annotation splits were excluded, but sample and biological independence are unknown. This is a fresh-image development check, not an independent-source validation or a severe-overlap benchmark.</p><p>The earlier one-match improvement did <strong>not</strong> repeat here. Baseline and all three weak-mask admission rules matched 31 of 32 source polygons at a 30-candidate budget per field, and all matched 32/32 with at most 60 candidates per field. The high-quality-support rule retained 532 candidates versus 519 for baseline and 596 when all weak candidates were admitted.</p><img src="support-comparison.png" alt="Source matches and candidate counts for four support policies"><table><thead><tr><th>Policy</th><th>Admitted</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>Reference-free support requires another prompt mask at IoU ≥0.5; this does not prove identity and can connect distinct overlapping diatoms. Same-stream 0.8 IoU NMS still applies. Counts are one-to-one matches at IoU ≥0.5 against source polygons, which may omit objects. Unmatched predictions are not verified false positives. No genus/species accuracy or human-level segmentation claim is made.</p><p>The first run stopped after one field when a second image was 2592×1944 instead of 1600×1200. Both are 4:3; the rerun rasterized each source polygon at its actual native dimensions and used the same isotropic 512×384 resize and padding. The correction and restart are documented in the protocol.</p><p>Source: <a href="https://zenodo.org/records/21295927">Khanom public dataset, CC BY 4.0</a>. <a href="/research/R87.md">Research note</a> · <a href="selection.json">Selection</a> · <a href="protocol.json">Inference protocol</a> · <a href="support-protocol.json">Frozen support rules</a> · <a href="support-results.json">Support links and scores</a> · <a href="/research/r87_support_verify.py">Support verifier</a></p><h2>Field comparisons</h2>{''.join(sections)}</html>''')
