"""Generate visual research report from verified Cellpose-DINO experiment."""
import json,html,datetime
from pathlib import Path
R=Path(__file__).resolve().parents[1];O=R/'results/r78';d=json.loads((O/'results.json').read_text());records=d['records'];sources=json.loads((O/'source-audit.json').read_text());
def eval_group(group,n,metric):
 rows=[r for r in records if r['group']==group];cp=sum(r['scores'][n][metric]['matched'] for r in rows);ref=sum(r['reference_count'] for r in rows)
 if n=='all':return cp,None,ref,sum(r['candidate_count'] for r in rows)
 if group=='synthetic':sam=sum(r['prior_mobile_sam'][n][metric]['matched'] for r in rows)
 else:
  k={'visible05':'iou05','visible075':'iou075'}[metric];sam=sum(r['prior_mobile_sam']['combined'][n][k]['matched'] for r in rows)
 return cp,sam,ref,sum(min(int(n),r['candidate_count']) for r in rows)
rows=[];md=[]
for group,title in [('synthetic','Synthetic (6 scenes)'),('menne','River Menne (18 fields)')]:
 for n in ('5','10','20','all'):
  a,b,total,shown=eval_group(group,n,'visible05');a75,b75,_,_=eval_group(group,n,'visible075');row=[title,n,str(shown),f'{a}/{total}',f'{b}/{total}' if b is not None else 'not recorded',f'{a75}/{total}',f'{b75}/{total}' if b75 is not None else 'not recorded'];rows.append('<tr>'+''.join('<td>'+html.escape(v)+'</td>' for v in row)+'</tr>');md.append('| '+' | '.join(row)+' |')
cards=[]
for r in records:
 label=(f"Synthetic pair {r['pair']} · {r['condition']}" if r['group']=='synthetic' else f"River Menne · {r['slide']} · {r['image_id']}");cards.append(f"<article><h3>{html.escape(label)}</h3><img src='{html.escape(r['image'])}' alt='Reference masks and Cellpose masks at top ten and all candidates'><p>Reference regions: {r['reference_count']} · Cellpose masks: {r['candidate_count']} · top-ten visible matches ≥0.5: {r['scores']['10']['visible05']['matched']}/{r['reference_count']} · CPU inference {r['seconds_inference']:.1f}s.</p></article>")
sc=eval_group('synthetic','10','visible05');real=eval_group('menne','10','visible05');t=sum(x['seconds_inference'] for x in records);flags=len(sources['flagged_pairs']);
page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>R78 · Cellpose DINOv3 comparison</title><style>body{font:16px/1.5 system-ui;background:#f2f6f0;color:#203b34}main{max-width:1200px;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/R78.md">Research note</a> · <a href="/results/performance/">Performance monitor</a></nav><h1>Cellpose DINOv3 on diatom controls</h1><p class="notice"><strong>Exploratory development comparison.</strong> The six synthetic scenes reuse three cutout pairs and an opaque rendering. The 18 River Menne fields were deliberately selected and previously examined; source labels omit many fragments and dense aggregates. Their historical “held-out” names no longer indicate an untouched test. Model-training and biological-sample independence are unknown.</p><p>We ran Cellpose’s DINOv3-ViT-B microscopy model with its standard automatic settings, then ranked its nonoverlapping label masks by mean predicted cell score. The earlier MobileSAM comparison used 256 grid points for synthetic scenes and detector/grid proposals for Menne. Models, computations, candidate counts, ranking scores, and output formats differ; this is not a controlled latency comparison. Matching uses reference masks after inference.</p><div class="card"><div class="scroll"><table><tr><th>Data</th><th>Max masks per scene</th><th>Cellpose masks shown</th><th>Cellpose IoU ≥0.5</th><th>MobileSAM IoU ≥0.5</th><th>Cellpose IoU ≥0.75</th><th>MobileSAM IoU ≥0.75</th></tr>{ROWS}</table></div><p>At a ten-mask budget, Cellpose matched {SC}/{SCT} synthetic visible targets and {RC}/{RCT} River Menne source regions; the previously recorded MobileSAM pipelines matched {SS}/{SCT} and {RS}/{RCT}, respectively. The references describe only labeled regions, so unmatched predictions cannot be treated as false positives.</p><p>Cellpose returns one integer label per pixel. It can separate visible, nonoverlapping regions but a single result cannot assign the same pixel to two full overlapping specimens. Full-shape overlap, partial-object recall, taxa, and human-level accuracy are not established.</p></div><h2>Inspect the fields</h2><p>Panels show reference shapes, Cellpose’s first ten masks, and all masks. Synthetic panels are silhouettes; Menne panels overlay the original field. Colors distinguish display layers, not confirmed biological identities.</p>{CARDS}<p>Cellpose inference took {SECONDS} CPU seconds over 24 fields, excluding model initialization and score/plot processing. This is not a latency comparison against earlier runs.</p><p><a href="results.json">All scores and candidate ordering</a> · <a href="protocol.json">Frozen protocol and pinned model</a> · <a href="source-audit.json">Source screening</a> · <a href="/research/r78_verify.py">Independent verifier</a></p><p>Model: <a href="https://huggingface.co/mouseland/cellpose-sam">Cellpose DINOv3 checkpoint</a>; <a href="https://cellpose.readthedocs.io/en/latest/models.html">official model documentation</a>. River Menne data: Kloster, Burfeid-Castellanos &amp; Beszteri, <a href="https://doi.org/10.5281/zenodo.7079005">dataset</a>, CC BY 4.0. The Cellpose project states its training data are CC BY-NC; Meta DINOv3 has separate terms.</p></main></html>'''.replace('{ROWS}',''.join(rows)).replace('{CARDS}',''.join(cards)).replace('{SC}',str(sc[0])).replace('{SS}',str(sc[1])).replace('{SCT}',str(sc[2])).replace('{RC}',str(real[0])).replace('{RS}',str(real[1])).replace('{RCT}',str(real[2])).replace('{SECONDS}',f'{t:.1f}');(O/'index.html').write_text(page)
notes=['# R78 · Cellpose DINOv3 microscopy instance segmentation','','[Visual comparison](/results/r78/) · [frozen protocol](/results/r78/protocol.json) · [all scores and raw-flow archives](/results/r78/results.json) · [source similarity audit](/results/r78/source-audit.json) · [independent verifier](/research/r78_verify.py)','','We tested the official Cellpose `cpdino-vitb` DINOv3-ViT-B checkpoint with Cellpose 4.2.1.1 on CPU, using the publisher’s default automatic 2D settings. Exact model revision, DINO source commit, file hashes, dependencies, thresholds and all 24 image hashes were frozen before inference. The 343,599,997-byte checkpoint matched its published LFS SHA-256. No user feedback, reference masks or diatom-specific training were used for inference. Cellpose returns a pixel-exclusive label image; its outputs were ranked by mean per-pixel cellprob logit, not by reference matching. All label maps, flows, cellprob fields, source references and rankings were saved.','','All six R76 synthetic scenes and 18 R44 River Menne fields were already examined. The latter are selected source regions with incomplete annotations: partial valves and dense aggregates may be excluded. Historical development/held-out labels are consumed; model-training and biological-sample independence are unknown. We compare with recorded MobileSAM grid256 for synthetic scenes and detector+grid for Menne; inference costs, proposal generation and ranking differ. At most N predictions per image are scored at equal display budgets. Visible-mask matching is one-to-one, with references used posthoc.','','| Data | Max masks per scene | Cellpose masks shown | Cellpose IoU ≥0.5 | MobileSAM IoU ≥0.5 | Cellpose IoU ≥0.75 | MobileSAM IoU ≥0.75 |','|---|---:|---:|---:|---:|---:|---:|']+md
notes+=['',f"At top ten Cellpose matches {sc[0]}/{sc[2]} visible synthetic references and {real[0]}/{real[2]} Menne source regions; the recorded MobileSAM baselines match {sc[1]}/{sc[2]} and {real[1]}/{real[2]}. Counting unmatched predictions as false positives is invalid because the source references are incomplete. Inference on 24 512px fields took {t:.1f} seconds on this CPU, excluding initialization and scoring; prior MobileSAM runs used different settings, so this is not a speed comparison.",'','A Cellpose label image assigns each pixel to at most one instance, so it cannot directly represent two full masks that overlap in projection. This is consequential for the project objective even if it provides useful visible-mask candidates. The 24 selected fields are not an independent benchmark or evidence of human-level segmentation, and neither the unlabeled portions nor source regions establish species identity. The input audit flagged '+str(flags)+' perceptually similar image pairs; all flagged pairs were related synthetic images sharing the same background. No pHash threshold proves distinct specimens or excludes model-training leakage.','','An independent verifier checks source hashes, label-map/flow archives, mean-score ranking and one-to-one match counts against reconstructed references for all 24 fields; it does not rerun model inference. Original Menne imagery is CC BY 4.0 and displayed with overlays. Synthetic source image pixels remain in temporary storage and are shown only as silhouettes. Raw RGB provenance is preserved, but these temporary files can disappear.','','Cellpose code/model card is BSD-3-Clause; the project notes that its training data are CC BY-NC. Meta DINOv3 terms apply separately; the user reported permission to experiment. Sources: [Cellpose model documentation](https://cellpose.readthedocs.io/en/latest/models.html), [model repository](https://huggingface.co/mouseland/cellpose-sam), [Cellpose repository](https://github.com/MouseLand/cellpose), and Kloster, Burfeid-Castellanos & Beszteri, [River Menne dataset](https://doi.org/10.5281/zenodo.7079005) (CC BY 4.0). The model has not been validated for diatom species or occluded specimens.']
(R/'research/R78.md').write_text('\n'.join(notes)+'\n');p=R/'research/board.json';board=json.loads(p.read_text());board['updated']=datetime.date.today().isoformat()
for q in board['tasks']:
 if q['id']=='R78':q.update(status='review',summary=f"Cellpose DINOv3: {sc[0]}/{sc[2]} synthetic and {real[0]}/{real[2]} Menne top-ten matches; not independent overlap accuracy.",result='/results/r78/')
p.write_text(json.dumps(board,indent=2)+'\n');p=R/'RESEARCH.md';s=p.read_text();s+=f"\n- **R78 · Cellpose DINOv3:** top-ten {sc[0]}/{sc[2]} synthetic and {real[0]}/{real[2]} real Menne source-region matches; outputs cannot express shared full-mask pixels. [Results](/results/r78/) · [note](research/R78.md).\n";p.write_text(s)
