import json,html,datetime
from pathlib import Path
R=Path(__file__).resolve().parents[1];O=R/'results/l70';cp=json.loads((O/'results.json').read_text())['records'];rs=json.loads((O/'sam-results.json').read_text())['records']
def total(method,tag,n,t):return sum(r['scores'][method][tag][n][t]['matched'] for r in rs)
def denom(tag):return sum(r['scores']['sam'][tag]['all']['0.5']['reference_count'] for r in rs)
rows=''.join('<tr><th>'+title+'</th>'+''.join(f'<td>{total(name,"geometry_collapsed",n,"0.5")}/{denom("geometry_collapsed")}</td>' for n in ('10','30','all'))+f'<td>{total(name,"severe_nonidentical","all","0.5")}/{denom("severe_nonidentical")}</td></tr>' for name,title in [('sam','MobileSAM'),('cellpose','Cellpose-DINO'),('sam_first','Alternating, SAM first'),('sam_first_08','Alternating + defer at 0.8'),('sam_first_095','Alternating + defer at 0.95')])
fields=''.join(f'<section><h2>{html.escape(c["filename"])}</h2><p>Source IDs {c["references"]}; distinct coordinate groups {c["collapsed_references"]}; Cellpose candidates {c["candidates"]}; SAM candidates after eligibility and within-stream suppression {s["kept_sam"]}. Geometry-collapsed matches at IoU 0.5: SAM {s["scores"]["sam"]["geometry_collapsed"]["all"]["0.5"]["matched"]}, Cellpose {s["scores"]["cellpose"]["geometry_collapsed"]["all"]["0.5"]["matched"]}, combined {s["scores"]["sam_first"]["geometry_collapsed"]["all"]["0.5"]["matched"]}.</p><img src="{s["image"]}" alt="Reference masks, MobileSAM masks, and combined candidates"><p><a href="{c["image"]}">Compare Cellpose masks</a> · <a href="/datasets/r82-revvity/images/{c["filename"]}">Original source image</a></p></section>' for c,s in zip(cp,rs))
page=f'''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>L70: overlap stress test</title><style>body{{font:16px/1.55 system-ui;max-width:1100px;margin:2em auto;padding:0 1em;color:#18342f}}.box{{background:#eef5f1;padding:1em;border-radius:8px}}img{{max-width:100%}}a{{color:#006b59}}table{{border-collapse:collapse}}th,td{{border:1px solid #b8ccc0;padding:.5em;text-align:left}}section{{border-top:1px solid #b8ccc0;margin-top:2em}}</style><p><a href="/results/board.html">Research board</a> · <a href="/results/progress.html">Progress</a></p><h1>L70: Can proposal policies retain heavily overlapping objects?</h1><p class="box"><strong>Completed exploratory stress test:</strong> these are human cancer cells, not diatoms. They test overlap machinery only; they do not measure diatom accuracy or human-level proficiency. Six fields were selected for difficult annotation geometry before image download, after their annotations had been audited.</p><p>At an intersection-over-union (IoU) threshold of 0.5, the combined candidate stream matched {total('sam_first','geometry_collapsed','all','0.5')}/{denom('geometry_collapsed')} coordinate-distinct source polygons versus {total('sam','geometry_collapsed','all','0.5')} for MobileSAM and {total('cellpose','geometry_collapsed','all','0.5')} for Cellpose. This is exploratory and deliberately hard, not an unbiased estimate. Cellpose cannot represent a shared pixel in two labels.</p><h2>Matches under a review budget</h2><p>One-to-one maximum-cardinality matching; top N means at most N candidates per image. Each severe reference has a nonidentical partner covering at least half of the smaller reference, computed on original-resolution source polygons. Severity is scored separately, so its counts are not additive.</p><table><thead><tr><th>Proposal policy</th><th>Top 10</th><th>Top 30</th><th>All candidates</th><th>Severe subset, all</th></tr></thead><tbody>{rows}</tbody></table><p>Threshold 0.75: combined {total('sam_first','geometry_collapsed','all','0.75')}/{denom('geometry_collapsed')}, MobileSAM {total('sam','geometry_collapsed','all','0.75')}, Cellpose {total('cellpose','geometry_collapsed','all','0.75')}. At 0.8 deferral produced {sum(len(r['deferrals']['08']) for r in rs)} link(s) and made no change to the displayed aggregate matches. Deferral preserves all candidates but may postpone real overlapping instances.</p><h2>Annotation and data limits</h2><p>Source annotations contain 205 IDs; 32 pairs in one selected field have exactly identical coordinate sequences. We retain all source IDs. As published, combined all-candidate matching is {total('sam_first','published','all','0.5')}/{denom('published')}; collapsing identical coordinates mechanically gives {total('sam_first','geometry_collapsed','all','0.5')}/{denom('geometry_collapsed')}. This sensitivity analysis does not decide whether identical polygons represent duplicate labels or distinct cells. The source provides one polygon field per instance; the exact interpretation of visible versus inferred hidden boundary is not established by this audit.</p><p>The source paper reports expert-validated cell and overlap polygons; the dataset card states CC BY-NC 4.0. Five difficult fields have distinct filename prefixes plus one repetition-rich field, but group names are only a proxy for sample origin. The train/validation annotations share 12 of 13 filename prefixes, including every selected prefix, so the split does not establish specimen independence. The training history of the available checkpoints is unknown. Unmatched proposals are not verified false positives. We used original RGB resized to 540 × 540; originals and all prompt masks are preserved.</p><p><a href="https://arxiv.org/html/2508.01928v1">Dataset paper</a> · <a href="https://huggingface.co/datasets/YaroslavPrytula/Revvity-25">Dataset and license</a> · <a href="/research/L70.md">Research note</a> · <a href="selection.json">Selection</a> · <a href="split-audit.json">Split audit</a> · <a href="sam-protocol.json">SAM protocol</a> · <a href="sam-results.json">Full scores and candidate ranks</a> · <a href="results.json">Cellpose scores</a> · <a href="image-manifest.json">Image hashes</a></p><h2>Field comparisons</h2><p>Colored overlays are separate instance masks; overlapping colors and the order of drawing can hide boundaries. Images are exploratory examples, not expert judgments.</p>{fields}</html>'''
(O/'index.html').write_text(page);(O/'progress.json').write_text(json.dumps({'phase':'completed','completed':6,'total':6,'updated_utc':datetime.datetime.now(datetime.timezone.utc).isoformat(),'note':'All six Cellpose and MobileSAM fields processed; checkpoint is not a live process monitor.'},indent=2)+'\n')
