"""Render verified equal-budget mixed-model candidate experiment."""
import json,html,datetime
from pathlib import Path
R=Path(__file__).resolve().parents[1];O=R/'results/r79';d=json.loads((O/'results.json').read_text());records=d['records'];labels={'sam':'MobileSAM only','cellpose':'Cellpose DINO only','sam_first':'Alternating · MobileSAM first','cp_first':'Alternating · Cellpose first'};names=list(labels)
rows=[];md=[]
for budget in ('5','10','20','all'):
 for name in names:
  values=[r['scores'][name][budget] for r in records];shown=sum(v['iou05']['candidate_count'] for v in values);lo=sum(v['iou05']['matched'] for v in values);hi=sum(v['iou075']['matched'] for v in values);near=sum(v['near_pairs_iou08'] for v in values);row=[budget,labels[name],str(shown),f'{lo}/29',f'{hi}/29',str(near)];rows.append('<tr>'+''.join('<td>'+html.escape(x)+'</td>' for x in row)+'</tr>');md.append('| '+' | '.join(row)+' |')
cards=[]
for r in records:
 scores=', '.join(f"{labels[k]} {r['scores'][k]['10']['iou05']['matched']}/{r['reference_count']}" for k in names);cards.append(f"<article><h3>{html.escape(r['slide'])} · field {r['image_id']}</h3><img src='{html.escape(r['image'])}' alt='Source references, MobileSAM, Cellpose, and both model interleavings'><p>Top-ten matches: {scores}. Source category: {html.escape(r['category'])}.</p></article>")
page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>R79 · Combining segmentation candidates</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/R79.md">Research note</a> · <a href="/results/r78/">Cellpose comparison</a></nav><h1>Can the two models complement each other?</h1><p class="notice"><strong>Development evidence only.</strong> The 18 River Menne fields were previously examined and selected. The source omits many fragments and dense aggregates; unmatched predictions are not established false positives. These reference regions do not establish real overlap accuracy, biological independence, or Academy-slide performance.</p><p>We reproduced the earlier MobileSAM candidate counts and matching scores, then alternated its ranking with Cellpose’s saved ranking in both starting orders. No cross-model masks were suppressed. Reference masks are used only for one-to-one scoring. A displayed budget is a maximum per field, so methods may show different total mask counts when fewer masks exist.</p><div class="card"><div class="scroll"><table><tr><th>Max masks per field</th><th>Candidate list</th><th>Total 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 alternating order matched 16 of 29 source regions versus 15 for MobileSAM and 9 for Cellpose. The mixed list showed 95 masks in total versus MobileSAM’s 69 and had 13 high-overlap candidate pairs versus 5. A high-overlap pair can be a duplicate or two overlapping specimens; it is not an identity label.</p><p>The SAM-first list gains one match in each of fields 10718 and 9633, but loses one in field 3275 at the ten-mask cap. At 20 or all candidates, the combined lists match 17/29 versus 15/29 for MobileSAM. Those extra candidates increase inspection burden and do not measure review time or false-positive rate.</p></div><h2>Field comparisons</h2><p>From left: source references, MobileSAM, Cellpose, SAM-first interleaving and Cellpose-first interleaving. Each prediction panel shows at most ten masks. Colors distinguish display layers rather than confirmed specimen identities.</p>{CARDS}<p><a href="results.json">All rankings and one-to-one assignments</a> · <a href="reproduction.json">MobileSAM replay and archived masks</a> · <a href="protocol.json">Frozen policy and inputs</a> · <a href="/research/r79_verify.py">Independent verification</a></p><p>River Menne imagery and source annotations: Kloster, Burfeid-Castellanos &amp; Beszteri, <a href="https://doi.org/10.5281/zenodo.7079005">dataset</a>, CC BY 4.0. Cellpose-DINO’s training data are described as CC BY-NC by its authors; Meta DINOv3 has separate terms.</p></main></html>'''.replace('{ROWS}',''.join(rows)).replace('{CARDS}',''.join(cards));(O/'index.html').write_text(page)
lines=['# R79 · Cellpose and MobileSAM candidate complementarity','','[Visual comparison](/results/r79/) · [frozen policy](/results/r79/protocol.json) · [MobileSAM reproduction and archives](/results/r79/reproduction.json) · [rankings and assignments](/results/r79/results.json) · [independent verifier](/research/r79_verify.py)','','On all 18 previously examined R44/R78 River Menne fields, reproduce the original detector + MobileSAM 64-grid pipeline and combine its candidates with the existing R78 Cellpose DINOv3 candidates. The fixed policies are each model alone and round-robin interleaving beginning with either model. No reference labels enter proposal generation or ranking, and no cross-model NMS or identity assumption removes overlapping candidates. Score one-to-one source COCO polygons at equal per-field maximum display budgets; fields with fewer candidates show fewer masks.','','| Max masks per field | Candidate list | Total masks shown | Source matches ≥0.5 | Source matches ≥0.75 | Pairs with mutual IoU ≥0.8 |','|---:|---|---:|---:|---:|---:|']+md
lines+=['','At top ten, both mixed orders match 16/29 source regions versus 15/29 for MobileSAM alone and 9/29 for Cellpose alone. SAM-first gains one match in each of fields 10718 and 9633 but loses one in field 3275 when interleaved masks push a useful SAM proposal below the budget. At top 20 or all candidates both mixed orders match 17/29 versus 15/29 for MobileSAM. At the 10-mask cap, mixed shows 95 masks across the 18 fields versus 69 for SAM and has 13 mask pairs at mutual IoU ≥0.8 versus 5; such pairs are not automatically duplicates and high overlap can also represent distinct instances. Matched annotation IDs in the JSON are one maximum-cardinality, maximum-total-IoU assignment; target-level set differences can depend on assignment ties.','','The earlier R44 run did not save its masks. This replay reproduces the detector/grid/combined counts and all recorded per-field match counts, candidate counts and matched IoUs at budgets 5/10/20 for both thresholds, plus detector-only scores. It cannot prove pixel-identical inference to the old unsaved masks. We retained 1,152 raw point-prompt masks, five detector masks, their quality/filter metadata, all 21 grid-suppression links and complete rankings. R78 retains the Cellpose label maps and flow fields. The original RGB fields and reference polygons, input/model hashes and source IDs are linked in the protocol; the downloaded source images are currently temporary.','','An independent verifier rederived grid eligibility, NMS aliases, detector-supported rankings, both interleavings, every assignment and 288 budget/field/list metric records. It checked maximum-cardinality/IoU totals and near-overlap counts separately; it did not rerun the original historical inference. The comparison policies were frozen before inference and scoring; the scoring-script checksum was recorded after scoring began. The 18 fields and model results had already been examined, source labels exclude fragments and dense aggregates, and sample/model-training independence is unknown. Unmatched candidates are not established false positives; the experiment does not measure real full-overlap accuracy, review time, species identification or human-level segmentation.','','The result suggests exploring mixed candidate streams while addressing ranking and review burden; test any frozen choice on truly independent, exhaustively labeled real partial/overlapping fields before adoption. Data: 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/R79.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']=='R79':t.update(status='review',summary='Mixed CP-DINO/MobileSAM candidates: 16/29 top-ten source matches vs 15/29 SAM, with more masks and high-overlap pairs; development only.',result='/results/r79/')
p.write_text(json.dumps(board,indent=2)+'\n');p=R/'RESEARCH.md';s=p.read_text();entry='- **R79 · Mixed model candidates:** Interleaving Cellpose and MobileSAM yielded 16/29 top-ten Menne source matches vs 15/29 SAM, with higher candidate burden. [Results](/results/r79/) · [note](research/R79.md).';
if entry not in s:s+='\n'+entry+'\n'
p.write_text(s)
