"""Render verified real-chain overlap experiment and update dashboard."""
import datetime,html,json
from pathlib import Path
R=Path(__file__).resolve().parents[1];O=R/'results/r81';d=json.loads((O/'results.json').read_text());records=d['records'];geometry=json.loads((O/'source-geometry.json').read_text());cp=json.loads((O/'cellpose.json').read_text());labels={'yolo':'Specialist YOLO only','cellpose':'Cellpose DINO only','yolo_first':'YOLO first, no deferral','yolo_first_08':'YOLO first, defer ≥0.8','yolo_first_095':'YOLO 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'};names=list(labels);ref_count=sum(r['reference_count'] for r in records);overlap_count=sum(len(r['overlap_reference_indices']) for r in records)
def total(name,budget):
 z=[r['scores'][name][str(budget)] for r in records];return {'shown':sum(x['all05']['candidate_count'] for x in z),'all05':sum(x['all05']['matched'] for x in z),'all075':sum(x['all075']['matched'] for x in z),'over05':sum(x['overlap05']['matched'] for x in z),'over075':sum(x['overlap075']['matched'] for x in z),'near':sum(x['near_pairs_iou08'] for x in z)}
rows=[];md=[]
for budget in (5,10,30,'all'):
 for name in names:
  q=total(name,budget);row=[str(budget),labels[name],str(q['shown']),f"{q['all05']}/{ref_count}",f"{q['all075']}/{ref_count}",f"{q['over05']}/{overlap_count}",f"{q['over075']}/{overlap_count}",str(q['near'])];rows.append('<tr>'+''.join('<td>'+html.escape(x)+'</td>' for x in row)+'</tr>');md.append('| '+' | '.join(row)+' |')
cards=[]
for r in records:
 y=r['scores']['yolo']['10'];c=r['scores']['cellpose']['10'];m=r['scores']['yolo_first']['10'];k=len(r['overlap_reference_indices']);cards.append(f"<article><h3>Field {r['image_id']} · {html.escape(r['group'])}</h3><img src='{html.escape(r['image'])}' alt='Source polygon reference and four segmentation candidate comparisons'><p>Projected-overlap subset at IoU ≥0.5, top ten: YOLO {y['overlap05']['matched']}/{k} · Cellpose {c['overlap05']['matched']}/{k} · mixed {m['overlap05']['matched']}/{k}. Total source polygons: {r['reference_count']}.</p></article>")
cp_time=sum(x['seconds_inference'] for x in cp['records']);numlinks=sum(len(v) for r in records for v in r['deferrals'].values());
page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>R81 · Real diatom-chain overlaps</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/R81.md">Research note</a> · <a href="/results/l69/">Earlier deferral experiment</a></nav><h1>Real diatom-chain overlap comparison</h1><p class="notice"><strong>Previously examined marine data; training independence is uncertain.</strong> The specialist model is trained for Pseudo-nitzschia chains, and its model card does not unambiguously establish that these images were excluded from training. These narrow marine flow-cytometry crops differ from freshwater slide fields. Source polygon overlap does not prove physical occlusion.</p><p>The 12 source images contain 41 labeled polygons. We preselected a subset of 32 polygons sharing at least ten resized pixels with another labeled polygon. A reproduced specialist YOLO model and a Cellpose DINOv3 model generated candidates without using those labels; we compared fixed model interleavings and the previously specified deferral rules. Reference matching occurs afterward.</p><div class="card"><div class="scroll"><table><tr><th>Max masks per image</th><th>Ranking</th><th>Masks shown</th><th>All ≥0.5</th><th>All ≥0.75</th><th>Overlap subset ≥0.5</th><th>Overlap subset ≥0.75</th><th>Candidate pairs IoU ≥0.8</th></tr>{ROWS}</table></div><p>At ten masks per image, the marine specialist matched 41/41 source polygons at IoU ≥0.5, including 32/32 in the projected-overlap subset; at IoU ≥0.75 it matched 27/41 overall and 25/32 in that subset. Cellpose matched 1/32 overlap-subset polygons at 0.5. The specialist’s near-perfect 0.5 result is not evidence of performance on unseen samples or freshwater slides.</p><p><strong>The deferral rule was not exercised:</strong> none of the output pairs met either 0.8 or 0.95 cross-model threshold. Thus this result says nothing about whether deferral preserves heavily overlapping instances. At five masks, mixing displaced a useful specialist candidate in one field; by ten, the mixed list recovered the same source-match counts as the specialist.</p><p>The 21 source polygon pairs overlapping by at least ten pixels have median mask IoU {MEDIOU} and maximum {MAXIOU}; median shared area is {MEDFRAC}% of the smaller polygon. They are predominantly small projected overlaps, not a test of severe occlusion. The source does not state whether polygons are visible or amodal full masks.</p></div><h2>Inspect the chain fields</h2><p>Each field shows source polygons, specialist predictions, Cellpose predictions, YOLO-first mixed predictions and 0.8-deferred predictions at a ten-mask cap. Colors indicate overlay layers rather than verified identities.</p>{CARDS}<p>Cellpose inference took {TIME} CPU seconds across 12 fields, excluding setup and scoring; this is not a speed comparison. The specialist’s own detector NMS and Cellpose’s pixel-exclusive labels precede any combined ranking.</p><p><a href="results.json">All rankings, matches and diagnostic pairs</a> · <a href="source-geometry.json">Source overlap geometry</a> · <a href="source-audit.json">Source audit</a> · <a href="protocol.json">Frozen protocol</a> · <a href="/research/r81_verify.py">Independent verification</a> · <a href="/datasets/r81-chain/">Licensed original-source mirror</a></p><p>Source images and annotations: Patrick C. Daniel, <a href="https://huggingface.co/datasets/patcdaniel/pseudo-nitzschia-cell-segmentation">Pseudo-nitzschia Cell Segmentation</a>; specialist <a href="https://huggingface.co/patcdaniel/pseudo-nitzschia-yolo11s-seg">YOLO11s-seg model</a>, both tagged MIT by their publishers. Cellpose training data are described by its authors as CC BY-NC, and Meta DINOv3 has separate terms.</p></main></html>'''.replace('{ROWS}',''.join(rows)).replace('{CARDS}',''.join(cards)).replace('{MEDIOU}',f"{geometry['median_pair_iou']:.3f}").replace('{MAXIOU}',f"{geometry['max_pair_iou']:.3f}").replace('{MEDFRAC}',f"{100*geometry['median_fraction_smaller']:.1f}").replace('{TIME}',f'{cp_time:.1f}');(O/'index.html').write_text(page)
lines=['# R81 · Real annotated diatom-chain overlap comparison','','[Visual comparison](/results/r81/) · [frozen protocol](/results/r81/protocol.json) · [all rankings and scores](/results/r81/results.json) · [source overlap geometry](/results/r81/source-geometry.json) · [source audit](/results/r81/source-audit.json) · [independent verifier](/research/r81_verify.py) · [original source mirror](/datasets/r81-chain/)','','We replayed all 12 previously examined L41 marine Pseudo-nitzschia chain crops. Source polygons define 41 instances; 32 have at least ten shared pixels with another reference after the fixed long-side-768 resize. Matching the 32-instance subset is performed separately from matching all references. Reference polygon extent is unspecified: do not infer visible or amodal labels, physical occlusion or biological correctness. These are not freshwater slide fields.','','The specialist YOLO11s-seg checkpoint and its confidence/box-NMS settings reproduce L41’s per-scene candidate counts, overall IoU ≥0.5/0.75 scores, and subset ≥0.5 scores. L41 did not preserve raw masks, so exact historic mask pixels cannot be checked. The specialist may have been trained on these source images; published split group separation and model-card wording do not establish exclusion. Cellpose DINOv3 uses the R78 pinned model and fixed CPU settings. Both receive only RGB pixels. We test the same predeclared interleavings and 0.8/0.95 cross-model deferrals, without deleting any postprocessed prediction. YOLO’s own detector NMS and Cellpose pixel exclusivity precede these lists.','','| Max masks per image | Ranking | Masks shown | All ≥0.5 | All ≥0.75 | Overlap subset ≥0.5 | Overlap subset ≥0.75 | Candidate pairs IoU ≥0.8 |','|---:|---|---:|---:|---:|---:|---:|---:|']+md
lines+=['','At top ten, the specialist matches 41/41 source polygons at IoU ≥0.5 and 27/41 at ≥0.75; the separately scored overlap subset is 32/32 and 25/32 respectively. Cellpose matches 1/32 overlap references at ≥0.5. The specialist is specialized for this taxon and possible training leakage prevents an independent performance claim. At a five-mask cap, mixed ranking matches 35/41 overall versus 36/41 for specialist-only because a Cellpose candidate displaces a useful specialist mask in field 288. At ten masks the same 41/41 source count is restored, with five extra Cellpose masks across the dataset.','','No candidate pairs across the two models reach either deferral threshold, so **zero masks are deferred** in any of the four policy variants. This experiment does not test whether deferral protects or loses genuinely near-coincident instances. Among the 21 source polygon pairs sharing at least ten pixels, median pairwise IoU is '+f"{geometry['median_pair_iou']:.4f}"+' and maximum is '+f"{geometry['max_pair_iou']:.4f}"+'; the median shared fraction of the smaller polygon is '+f"{100*geometry['median_fraction_smaller']:.1f}%"+'. These projected overlaps are mostly small. A stricter overlap or amodal reference benchmark and independent freshwater slides remain necessary.','','An independent verifier reconstructed all polygons, reproduced overlap-subset membership, checked all saved masks/flow fields and 480 budget/policy records, independently optimized one-to-one matches and verified matched high-IoU pair diagnostics; it did not rerun model inference. Source-geometry aggregate statistics were separately recomputed. Model candidates after YOLO NMS and Cellpose label postprocessing, raw Cellpose flows, source polygons, confidence and candidate rankings are archived. Original 12 images, COCO annotations and split lists have a SHA-verified [local mirror](/datasets/r81-chain/) and can be restored to temporary input paths with `research/r81_restore_inputs.py`. Model weights and environments remain temporary.','','The source screening found no exact/coarse-perceptual cross-source flags against the R79/R80 fields, but cannot prove biological or training independence. Source polygons may omit objects, so unmatched predictions are not confirmed false positives. No freshwater, real severe-occlusion, species-identification or human-level claim follows. Source: Patrick C. Daniel, [Pseudo-nitzschia Cell Segmentation](https://huggingface.co/datasets/patcdaniel/pseudo-nitzschia-cell-segmentation), and [YOLO11s-seg model](https://huggingface.co/patcdaniel/pseudo-nitzschia-yolo11s-seg), tagged MIT by the publisher. Cellpose training data are described by its authors as CC BY-NC; Meta DINOv3 has separate terms.']
(R/'research/R81.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']=='R81':t.update(status='review',summary='Previously viewed marine chains: specialist 32/32 overlapping source polygons at IoU 0.5, 25/32 at 0.75; no deferral triggered, training exclusion unknown.',result='/results/r81/')
p.write_text(json.dumps(board,indent=2)+'\n');p=R/'RESEARCH.md';s=p.read_text();entry='- **R81 · Real marine-chain overlaps:** specialist matched 32/32 overlap-subset polygons at IoU 0.5, 25/32 at 0.75; overlap is small and no deferral triggered. [Results](/results/r81/) · [note](research/R81.md).';
if entry not in s:s+='\n'+entry+'\n'
p.write_text(s)
p=R/'results/performance/index.html';s=p.read_text();needle='<section class="panel gap"><h2>Current research</h2>';entry='<p><a href="/results/r81/">Real marine-chain overlap check</a> — specialist matched 32/32 overlap-subset polygons at IoU 0.5 and 25/32 at 0.75; source overlaps are small, prior data were viewed, and no deferral was triggered.</p>'
if entry not in s:s=s.replace(needle,needle+entry,1)
p.write_text(s)
