"""Render matched-prompt decoder comparison and update research status."""
import json,datetime,html
from pathlib import Path
R=Path(__file__).resolve().parents[1];O=R/'results/l67';d=json.loads((O/'results.json').read_text());records=d['records'];mask=json.loads((O/'paired-mask-audit.json').read_text());conditional=json.loads((O/'conditional-audit.json').read_text());source=json.loads((O/'source-audit.json').read_text());labels={'original':'Base decoder','adapted':'Freshwater-adapted decoder'};rows=[];md=[]
for condition in ('separated','crossing'):
 for points in ('uniform64','grid256'):
  for model in ('original','adapted'):
   key=points+'_'+model;rs=[r['results'][key] for r in records if r['condition']==condition];top=[r['budgets']['10'] for r in rs];a=sum(x['visible05']['matched'] for x in top);b=sum(x['visible075']['matched'] for x in top);c=sum(x['full05']['matched'] for x in top);all_=sum(x['all_kept']['visible05']['matched'] for x in rs);n=sum(x['all_kept']['n'] for x in rs);row=[condition,'64' if points=='uniform64' else '256',labels[model],f'{a}/6',f'{b}/6',f'{c}/6',f'{all_}/6',str(n)];rows.append('<tr>'+''.join('<td>'+x+'</td>' for x in row)+'</tr>');md.append('| '+' | '.join(row)+' |')
cards=[]
for r in records:
 x=r['results'];a=x['grid256_original']['budgets']['10']['visible05']['matched'];b=x['grid256_adapted']['budgets']['10']['visible05']['matched'];cards.append(f"<article><h3>Pair {r['pair']} · {html.escape(r['condition'])}</h3><img src='{html.escape(r['image'])}' alt='Visible reference masks, original decoder top ten proposals, adapted decoder top ten proposals'><p>256 prompts, visible IoU ≥0.5: original {a}/2, adapted {b}/2 at top ten.</p></article>")
page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>L67 · Adapted decoder under identical prompts</title><style>body{font:16px/1.5 system-ui;background:#f2f6f0;color:#203b34}main{max-width:1180px;margin:auto;padding:20px}article,.card{background:white;padding:16px;margin:12px 0;border:1px solid #d4ded6}img{max-width:100%}.notice{background:#fff2d6;padding:14px}th,td{padding:8px;text-align:left;border-bottom:1px solid #d4ded6}.scroll{overflow:auto}a{color:#126d55}</style><main><nav><a href="/results/board.html">Research board</a> · <a href="/research/L67.md">Research note</a> · <a href="/results/r54/">Decoder training and prior comparison</a></nav><h1>Does the freshwater-adapted decoder recover more instances?</h1><p class="notice"><strong>Exploratory synthetic scenes, not independent real-slide validation.</strong> Three previously examined cutout pairs share one partly unannotated Academy background; the crossing images use opaque synthetic layering. Source relationships and model-training overlap remain uncertain.</p><p>We compared the original MobileSAM decoder with an existing decoder adapted on synthetic freshwater images and reference-derived boxes. Both received the same automatic grid-point prompts and shared original-model detector masks for ranking. The 64-point test is a subset of the 256 predictions; no separate 64-point inference was timed. Each target is matched at most once to a predicted mask.</p><div class="card"><div class="scroll"><table><tr><th>Arrangement</th><th>Grid prompts</th><th>Decoder</th><th>Visible top 10 ≥0.5</th><th>Visible top 10 ≥0.75</th><th>Full top 10 ≥0.5</th><th>Visible all retained ≥0.5</th><th>All retained masks</th></tr>{ROWS}</table></div><p>At every tested budget of five, ten or twenty masks per scene, both decoders matched the same number of targets. With 256 grid points and ten displayed masks, each matched 6/6 separated and 2/6 crossing targets. Looking through every retained mask increased both crossing scores to 4/6, requiring 274 original or 282 adapted masks across three scenes. Matching all retained candidates is a reference-based diagnostic, not automatic selection.</p><p>On the eight targets both models matched at top ten across the six scenes, the adapted model’s assigned mask IoU increased on six and decreased on two; the mean change was +0.0045. This posthoc comparison excludes missed targets, and one target used different matched prompt IDs. It is not evidence of general improvement.</p><p>The outputs differ: median mask IoU between the 1,536 same-point original/adapted prediction pairs was 0.936. Agreement is not accuracy. Both methods use each decoder’s own quality score at the same threshold; those scores may not be calibrated to one another.</p></div><h2>Scene silhouettes</h2><p>From left: visible reference, original decoder top ten, adapted decoder top ten. Colors distinguish overlapping display layers rather than confirmed identities.</p>{CARDS}<p><a href="results.json">All point sets, rankings and scores</a> · <a href="protocol.json">Frozen protocol</a> · <a href="source-audit.json">Source similarity screening</a> · <a href="paired-mask-audit.json">Same-prompt mask audit</a> · <a href="conditional-audit.json">Matched-target boundary audit</a> · <a href="central-reproduction.json">Base-model reproduction</a></p><p>The adapted decoder was trained using derivatives of Hüseyin Gündüz’s <a href="https://www.kaggle.com/datasets/huseyingunduz/diatom-dataset">Diatom Dataset</a>, CC BY-NC-SA 4.0; see <a href="/experiments/checkpoints/r54-freshwater-decoder.README.md">checkpoint provenance</a>. Source RGB composites are not redistributed on this page.</p></main></html>'''.replace('{ROWS}',''.join(rows)).replace('{CARDS}',''.join(cards));(O/'index.html').write_text(page)
lines=['# L67 · Freshwater-adapted decoder on matched point prompts','','[Visual comparison](/results/l67/) · [protocol](/results/l67/protocol.json) · [all scores, rankings and aliases](/results/l67/results.json) · [source screening](/results/l67/source-audit.json) · [paired-mask audit](/results/l67/paired-mask-audit.json) · [conditional target audit](/results/l67/conditional-audit.json) · [central base-model reproduction](/results/l67/central-reproduction.json)','','Compare the base MobileSAM decoder and existing R54 freshwater-adapted decoder on the same six previously examined R38/R76 separated and opaque crossing scenes. No model was trained on these scenes in this experiment. Both use the same 256 image-only grid point locations, frozen encoder and prompt encoder, and cached base-model detector masks for ranking. The 64-point subset is reanalyzed from the same 256 outputs; it was not independently timed. The adapted decoder had been trained using reference-derived box prompts, so transfer to point prompts is an empirical question. Both outputs undergo the same numerical quality ≥0.6, area 300–50,000, IoU ≥0.8 NMS and detector-supported/quality interleaving; quality score calibration may differ.','','| Arrangement | Prompts | Decoder | Visible top 10 ≥0.5 | Visible top 10 ≥0.75 | Full top 10 ≥0.5 | Visible all retained ≥0.5 | Retained masks |','|---|---:|---|---:|---:|---:|---:|---:|']+md
lines+=['','The two decoders have identical visible/full match counts at all tested budgets (5, 10 and 20 per scene) in both 64- and 256-point conditions. At 256 points, top 10 matches are 6/6 separated and 2/6 crossing; all retained crossing masks match 4/6, at a review burden of 274 base or 282 adapted masks across three scenes. This is a posthoc pool bound, not a way to select the correct masks. No new target recovery was established.','','The models are not identical: the median same-prompt mask IoU across all 1,536 pairs is 0.936 (10th percentile 0.746), and no pair is pixel-identical. Same-prompt agreement measures similarity, not correctness. As a posthoc conditional boundary diagnostic, of the eight visible targets both decoders matched at top 10 in the 256-point condition, adapted IoU increased on six and decreased on two, with mean change +0.0045. This excludes four missed targets and one paired assignment uses a different prompt; it does not establish better expected accuracy.','','The original decoder was rerun for original grid indices 0–11 and 108–143 on each scene: all 288 masks were pixel-identical to the stored baseline with quality differences ≤1e-6. The remaining cached masks were not rerun. An independent verifier checked input and output hashes, eligibility, NMS aliases, rankings and 120 metric records; it did not independently rerun adapted inference. All 1,536 adapted masks, qualities, prompt coordinates and exact suppression aliases are preserved; original masks and detector support are retained in R76.','','A source audit compared all 96 pairs of actual R54 training images versus R38 test images. No exact file SHA-256 matched; the minimum coarse 63-bit DCT hash distance was 22 for whole images and 14 for masked normalized cutouts across eight orientations. This screen does not prove distinct biological specimens, acquisition samples or absence from base-model training. The six tests share three cutout pairs, one previously examined partially unannotated Academy background and synthetic opaque compositing. The source RGB files remain under `/tmp` and are temporary.','','The R54 decoder was adapted from derivatives of Hüseyin Gündüz’s [Diatom Dataset](https://www.kaggle.com/datasets/huseyingunduz/diatom-dataset), CC BY-NC-SA 4.0; see [checkpoint provenance](/experiments/checkpoints/r54-freshwater-decoder.README.md). Base-model and other source-image terms also apply. These results do not establish real-overlap or freshwater accuracy, false positives, downstream genus/species performance, or human-level segmentation. Do not promote the adapted decoder solely on this small synthetic comparison; keep both checkpoints and evaluate distinct-instance generation and calibrated ranking on truly independent public and real overlap cases.']
(R/'research/L67.md').write_text('\n'.join(lines)+'\n');p=R/'research/board.json';board=json.loads(p.read_text());board['updated']=datetime.date.today().isoformat()
for t in board['tasks']:
 if t['id']=='L67':t.update(status='review',summary='Original and adapted decoders matched the same targets at all budgets on 6 related synthetic scenes; boundaries differed.',result='/results/l67/')
p.write_text(json.dumps(board,indent=2)+'\n');p=R/'RESEARCH.md';s=p.read_text();s+='\n- **L67 · Matched point-prompt decoder test:** freshwater-adapted decoder changed boundaries but did not improve target counts on six synthetic scenes. [Results](/results/l67/) · [note](research/L67.md).\n';p.write_text(s)
