"""Render L65 verified results and update project status."""
import json,html,datetime,statistics
from pathlib import Path
R=Path(__file__).resolve().parents[1];O=R/'results/l65';d=json.loads((O/'results.json').read_text());recs=d['records'];names=['baseline','quality','spatial','stability','diverse'];labels={'baseline':'R41 baseline','quality':'Quality only','spatial':'Spatial round robin','stability':'Prompt repeatability interleaved','diverse':'Rank + mask diversity'}
def summary(name,split,n):
 rows=[r['metrics'][name][str(n)] for r in recs if r['split']==split];return {'visible05':sum(x['visible05']['matched'] for x in rows),'visible075':sum(x['visible075']['matched'] for x in rows),'full05':sum(x['full05']['matched'] for x in rows),'near':sum(x['near_pairs_iou08'] for x in rows),'both':sum(x['masks_cover_both_full_half'] for x in rows)}
trs=[];notes=[]
for n in names:
 a=summary(n,'development',10);b=summary(n,'probe',10);trs.append(f"<tr><th>{labels[n]}</th><td>{a['visible05']}/8</td><td>{a['visible075']}/8</td><td>{a['full05']}/8</td><td>{b['visible05']}/4</td><td>{b['visible075']}/4</td><td>{b['full05']}/4</td></tr>");notes.append(f"| {labels[n]} | {a['visible05']}/8 | {a['visible075']}/8 | {a['full05']}/8 | {b['visible05']}/4 | {b['visible075']}/4 | {b['full05']}/4 |")
cards=[]
for r in recs:
 a=r['metrics']['baseline']['10']['visible05']['matched'];b=r['metrics'][d['selected_policy']]['10']['visible05']['matched'];cards.append(f"<article><h3>{html.escape(r['variant'])} · pair {r['pair']} · {r['split']}</h3><img src='{html.escape(r['image'])}' alt='Visible targets, baseline top ten and selected ranking top ten silhouettes'><p>Visible matches: baseline {a}/2, selected ranking {b}/2.</p></article>")
page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>L65 · Rank overlap proposals</title><style>body{font:16px/1.5 system-ui;background:#f2f6f0;color:#203b34}main{max-width:1160px;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/L65.md">Research note</a> · <a href="/results/r75/">Source experiment</a></nav><h1>Can ranking surface more overlapping instances?</h1><p class="notice"><strong>Development diagnostic only.</strong> All six opaque synthetic scenes were examined before this experiment. The same six source objects appear in two backgrounds; the small pair-3 probe was held out of policy selection but is not independent or a real-slide test. Matches use known reference masks after ranking.</p><p>Five predeclared rules rearrange exactly the same masks retained by the earlier overlap suppression. None uses reference masks to calculate candidate features or removes a proposal. We select one rule from four development scenes using visible-mask matches at a budget of ten, then show it on two pair-grouped probe scenes.</p><div class="card"><div class="scroll"><table><tr><th>Ranking</th><th>Dev visible ≥0.5</th><th>Dev visible ≥0.75</th><th>Dev full ≥0.5</th><th>Probe visible ≥0.5</th><th>Probe visible ≥0.75</th><th>Probe full ≥0.5</th></tr>{ROWS}</table></div><p>Prompt-repeatability interleaving was selected: it lifted a single visible target into the top ten in development (3/8 → 4/8), with no gain on the two probe scenes (1/4). This does not establish a reliable improvement. At twenty candidates, the unselected diversity rule matched 2/4 probe targets; this is an exploratory secondary result, not a prespecified winner.</p><p>All near-duplicate counts at IoU ≥0.8 are zero by construction: these masks had already passed suppression at that threshold. Distinct, high-overlap instances may have been removed before ranking; the originals remain available in <a href="/results/r75/">R75</a>. A full-mask match can also reward duplicate or merged predictions.</p></div><h2>How the rules work</h2><p>Quality uses the model score. Spatial round robin cycles through cells containing mask centers. Repeatability interleaves the baseline with a heuristic based on how often nearby grid prompts produce masks suppressed in favor of each kept mask, normalized by the number of grid points inside it. Diversity trades off the original rank with dissimilarity to selected masks. None is an identity decision or a calibrated probability.</p><h2>Scenes</h2><p>Silhouettes show the visible target shapes and the first ten masks under the baseline and chosen rule. Colors do not identify specimens.</p>{CARDS}<p><a href="results.json">Full metrics, rankings and runtime</a> · <a href="protocol.json">Frozen protocol</a> · <a href="/research/l65_verify.py">Independent verifier</a> · <a href="/results/r75/">Preserved raw candidate archives and source provenance</a></p></main></html>'''.replace('{ROWS}',''.join(trs)).replace('{CARDS}',''.join(cards));(O/'index.html').write_text(page)
text=['# L65 · Reference-free ranking of overlap proposals','','[Visual result and scene silhouettes](/results/l65/) · [frozen protocol](/results/l65/protocol.json) · [rankings and all scores](/results/l65/results.json) · [independent verifier](/research/l65_verify.py) · [source masks](/results/r75/)','','We tested five fixed, reference-free reorderings of the same NMS-retained R75 grid masks: original R41 detector/quality alternating order; raw model quality; round robin across 4×4 mask-centroid cells; baseline interleaved with a direct-alias repeatability heuristic; and greedy rank/mask-IoU diversity. All are permutations: none discards another mask. Repeatability is `(1 + number of directly suppressed masks) / (1 + number of all grid points inside the retained mask)`; this is not a probability and can be biased by size, geometry or NMS. Full definitions and fixed ties are in the protocol.','','Pairs 1 and 2, both layouts, are development; pair 3, both layouts, is a tiny grouped probe. All scenes had been inspected previously, so neither partition is independent. We selected the development top-10 visible IoU ≥0.5 winner, breaking ties by ≥0.75 and then predetermined rule order. References never enter candidate features. Probe outcomes follow that fixed selection; all other policy outcomes are explicitly secondary.','','| Ranking (10 per scene) | Dev visible ≥0.5 | Dev visible ≥0.75 | Dev full ≥0.5 | Probe visible ≥0.5 | Probe visible ≥0.75 | Probe full ≥0.5 |','|---|---:|---:|---:|---:|---:|---:|']+notes
text+=['','The selected **repeatability interleave** improves development from 3/8 to 4/8 visible matches by advancing one existing mask, with no gain in the 1/4 probe result. The same visible target and candidate are matched by both methods on the alternate pair-3 probe; neither matches a target in original pair 3 at budget 10. At budget 20 the unselected diversity rule obtains 2/4 visible probe matches versus 1/4 baseline; this is an exploratory secondary observation, not a selected or validated gain. The selected ranking does not generate any new masks.','','All tested candidate sets have zero pairwise mask IoU ≥0.8 because prior NMS already suppressed such pairs. This is not evidence of proper overlap separation: an actual distinct, near-coincident instance could already be missing. At top 10, two development masks and one probe mask cover at least half of each full synthetic target; such coverage does not identify a merge and full-mask scores may be misleading. Original raw masks, images/scene provenance, model scores, points, and aliases remain in R75. The silhouette panels show only the top 10 and are not predictions of specimen identity.','','An independent verifier reimplemented every ranking and checked all 90 per-scene/budget scores, near-overlap and union-coverage diagnostics, grouping, selection and input/image hashes. Unit tests check deterministic permutations and edge cases. Ranking timing excludes model inference and is stored per scene; it is not end-to-end performance.','','The data reuse six previously viewed objects across two opaque synthetic composites on partly unannotated backgrounds; methods were chosen in the context of earlier experiments. No false-positive rate, confidence interval, real freshwater performance, or human-level segmentation can be inferred. Preserve suppressed alternatives for later reference; evaluate ranking and separate-instance evidence on a genuinely new pair-grouped public benchmark and real, independently adjudicated overlaps before adopting a rule.']
(R/'research/L65.md').write_text('\n'.join(text)+'\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']=='L65':t.update(status='review',summary='Reference-free ranker gained one development match (4/8 vs 3/8), no gain on tiny 1/4 pair-grouped probe; not independent.',result='/results/l65/')
p.write_text(json.dumps(board,indent=2)+'\n');p=R/'RESEARCH.md';s=p.read_text();s+='\n- **L65 · Overlap proposal ranking:** Repeatability interleaving gained one of eight development targets but not the tiny grouped probe; [results](/results/l65/) · [note](research/L65.md).\n';p.write_text(s)
