"""Render the fixed overlap-deferral evaluation."""
import json,html,datetime
from pathlib import Path
R=Path(__file__).resolve().parents[1];O=R/'results/l69';d=json.loads((O/'results.json').read_text());records=d['records'];names=['sam','cellpose','sam_first','sam_first_08','sam_first_095','cp_first','cp_first_08','cp_first_095'];labels={'sam':'MobileSAM only','cellpose':'Cellpose only','sam_first':'SAM first, no deferral','sam_first_08':'SAM first, defer ≥0.8','sam_first_095':'SAM first, defer ≥0.95','cp_first':'Cellpose first, no deferral','cp_first_08':'Cellpose first, defer ≥0.8','cp_first_095':'Cellpose first, defer ≥0.95'}
def totals(method,n):
 x=[r['scores'][method][str(n)] for r in records];return {'n':sum(v['iou05']['candidate_count'] for v in x),'v05':sum(v['iou05']['matched'] for v in x),'v075':sum(v['iou075']['matched'] for v in x),'near':sum(v['near_pairs_iou08'] for v in x)}
rows=[];md=[]
for n in (5,10,20,'all'):
 for name in names:
  t=totals(name,n);row=[str(n),labels[name],str(t['n']),f"{t['v05']}/29",f"{t['v075']}/29",str(t['near'])];rows.append('<tr>'+''.join('<td>'+html.escape(v)+'</td>' for v in row)+'</tr>');md.append('| '+' | '.join(row)+' |')
cards=[]
for r in records:
 a=r['scores']['sam_first']['10']['iou05']['matched'];b=r['scores']['sam_first_08']['10']['iou05']['matched'];n=len(r['deferrals']['sam_first_08']);cards.append(f"<article><h3>{html.escape(r['slide'])} · field {r['image_id']}</h3><img src='{html.escape(r['image'])}' alt='Source reference, mixed baseline, two deferred rankings and postponed candidate masks'><p>SAM-first top ten: {a}/{r['reference_count']} matches before deferral; {b}/{r['reference_count']} after 0.8 deferral. {n} masks postponed, all preserved.</p></article>")
page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>L69 · Preserving overlapping alternatives</title><style>body{font:16px/1.5 system-ui;background:#f2f6f0;color:#203b34}main{max-width:1280px;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/L69.md">Research note</a> · <a href="/results/r79/">Earlier mixed-model test</a></nav><h1>Can we postpone similar masks without losing them?</h1><p class="notice"><strong>Exploratory development results.</strong> These 18 River Menne fields were previously examined and their source annotations omit many fragments and dense aggregates. No real-overlap or human-level accuracy can be inferred. Candidate similarity does not prove the masks represent the same organism.</p><p>We replayed the earlier MobileSAM and Cellpose lists. A fixed rule moves a mask later if it overlaps a previously retained mask from the other model at the stated threshold. All postponed masks remain available; links record the algorithmic reason, not specimen identity. Both model starting orders and two thresholds were predeclared.</p><div class="card"><div class="scroll"><table><tr><th>Max masks per field</th><th>Ranking</th><th>Masks shown</th><th>Source matches ≥0.5</th><th>Source matches ≥0.75</th><th>Pairs with mutual IoU ≥0.8</th></tr>{ROWS}</table></div><p>At ten masks per field, either 0.8-deferred mixed ranking matches 17 of 29 source regions, versus 16 for the unchanged mixed list and 15 for MobileSAM. Both mixed lists display 95 masks in total; the ≥0.8 pair count falls from 13 to 11. The change recovers one known match in field 3275. The stricter 0.95 rule produces the same top-ten match count in this small set.</p><p><strong>Important limitation:</strong> A real second instance can overlap another by more than 0.8. Postponing it can hide it beyond a review limit even though the full archive retains it. <a href="/results/r71/">Controlled geometry examples</a> demonstrate this failure. The source annotations here cannot test it, and no actual review time or false-positive rate was measured.</p></div><h2>Field comparisons</h2><p>From left: source references, SAM-first mixed top ten, 0.8-deferred top ten, 0.95-deferred top ten, and all masks deferred by the 0.8 rule. Colors distinguish layers rather than confirmed identities.</p>{CARDS}<p><a href="results.json">Full rankings, direct deferral links and assignments</a> · <a href="protocol.json">Frozen policy and inputs</a> · <a href="/research/l69_verify.py">Independent verification</a> · <a href="/results/r79/">Original masks and provenance</a></p><p>Source imagery and labels: Kloster, Burfeid-Castellanos &amp; Beszteri, <a href="https://doi.org/10.5281/zenodo.7079005">River Menne dataset</a>, CC BY 4.0. Cellpose training data are described by its authors as CC BY-NC; Meta DINOv3 has separate terms.</p></main></html>'''.replace('{ROWS}',''.join(rows)).replace('{CARDS}',''.join(cards));(O/'index.html').write_text(page)
lines=['# L69 · Defer high-overlap alternatives without deleting them','','[Visual comparisons](/results/l69/) · [frozen protocol](/results/l69/protocol.json) · [all rankings, deferral links and scores](/results/l69/results.json) · [independent verifier](/research/l69_verify.py) · [source masks](/results/r79/)','','Replay all 18 R79 River Menne fields. For each fixed mixed-model order, defer a candidate when its mask IoU is ≥0.8 or ≥0.95 with the first earlier nondeferred candidate from the other model; preserve relative order within the primary and deferred lists, append all deferred candidates, and record a direct link. Within-model candidates are not compared for this rule. Both starting orders, both thresholds, budgets and scoring were specified before this experiment. No source labels influence ranking. A link records an algorithmic decision only, never same/different specimen identity.','','| Max masks per field | Ranking | Masks shown | Source matches ≥0.5 | Source matches ≥0.75 | Pairs with mutual IoU ≥0.8 |','|---:|---|---:|---:|---:|---:|']+md
lines+=['','At a ten-mask-per-field cap, deferral at either threshold yields 17/29 source matches for both model starting orders, versus 16/29 for the same unmodified interleavings and 15/29 for MobileSAM alone. Each mixed ranking shows 95 masks across all fields; 0.8 deferral reduces pairwise IoU ≥0.8 counts from 13 to 11. The extra match occurs in field 3275, where the nondeferred alternative and postponed mask overlap at IoU 0.982 and a SAM target becomes visible within the budget. At budgets of 20 or all candidates, all mixed variants match 17/29 because every mask is retained. Actual annotation time and false-positive rates were not measured.','','**High-overlap instances can be distinct.** The [R71 near-coincident synthetic control](/results/r71/) contains two exact distinct masks at IoU 0.882. A unit test confirms the 0.8 rule can defer the second correct instance past a finite display budget. Thus this is an experimental prioritization policy with an explicit recall risk, not a rule for deleting masks or deciding biological identity. The stricter 0.95 rule reduces, but does not eliminate, that risk. Earlier MobileSAM within-grid NMS and Cellpose’s pixel-exclusive labels can still remove or preclude genuine alternatives before this ranking; the prior raw masks and all available links remain in R79/R78.','','The verifier independently replayed all mask permutations, 21 direct deferral links across the four policy variants, one-to-one assignments and 576 per-field/budget/policy score records. Unit tests cover genuine near-coincident instance preservation, within-model behavior and invalid inputs. No inference was rerun. The source fields and their prior model results were already viewed, and labels exclude fragments/dense aggregates. These outcomes do not establish real-overlap accuracy, review time, false positives, species identification, sample independence or human-level performance. Assignments represent one maximum-cardinality, maximum-total-IoU solution; target identity can vary in ties.','','Promising next step: freeze the rule and assess it on different source groups, including genuine overlapping/partial instance references, before considering adoption. Preserve original RGB/focal planes and both original and deferred candidates for future scientist feedback. Data source: Kloster, Burfeid-Castellanos & Beszteri, [River Menne dataset](https://doi.org/10.5281/zenodo.7079005), CC BY 4.0. Cellpose training data are described by its authors as CC BY-NC; Meta DINOv3 has separate terms.']
(R/'research/L69.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']=='L69':t.update(status='review',summary='Cross-model overlap deferral yields 17/29 top-ten source matches vs 16/29 unchanged mix, while retaining all candidates; real overlap risk remains.',result='/results/l69/')
p.write_text(json.dumps(board,indent=2)+'\n');p=R/'RESEARCH.md';s=p.read_text();entry='- **L69 · Deferring cross-model alternatives:** 17/29 top-ten source matches vs 16/29 unchanged mix; all candidates preserved, but genuine overlaps can be delayed. [Results](/results/l69/) · [note](research/L69.md).';
if entry not in s:s+='\n'+entry+'\n'
p.write_text(s)
