"""Render source-separated fixed-ranking development results."""
import json,datetime,html
from pathlib import Path
R=Path(__file__).resolve().parents[1];O=R/'results/r76';d=json.loads((O/'results.json').read_text());records=d['records'];audit=json.loads((O/'source-audit.json').read_text());names=['baseline','stability'];labels={'baseline':'R41 baseline','stability':'Repeatability interleave'}
def counts(condition,method,n):
 x=[r['metrics'][method][str(n)] for r in records if r['condition']==condition];return tuple(sum(y[key]['matched'] for y in x) for key in ('visible05','visible075','full05'))
rows=[];md=[]
for cond in ('separated','crossing'):
 for method in names:
  for n in (5,10,20):
   a,b,c=counts(cond,method,n);rows.append(f"<tr><td>{cond}</td><td>{labels[method]}</td><td>{n}</td><td>{a}/6</td><td>{b}/6</td><td>{c}/6</td></tr>");md.append(f"| {cond} | {labels[method]} | {n} | {a}/6 | {b}/6 | {c}/6 |")
cards=[]
for r in records:
 b=r['metrics']['baseline']['10']['visible05']['matched'];s=r['metrics']['stability']['10']['visible05']['matched'];full=r['metrics']['all_kept']['visible05']['matched'];cards.append(f"<article><h3>Pair {r['pair']} · {html.escape(r['condition'])}</h3><img src='{html.escape(r['image'])}' alt='Visible reference masks, baseline top ten candidate masks, repeatability top ten candidate masks'><p>Visible targets at IoU ≥0.5: baseline {b}/2; repeatability {s}/2; all retained {full}/2. {r['eligible']} eligible grid masks, {r['kept']} retained after suppression.</p></article>")
minwhole=min(x['whole_image_dct_hash_distance'] for x in audit['comparisons']);mincrop=min(x['crop_min_8_orientation_dct_hash_distance'] for x in audit['comparisons'])
page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>R76 · Frozen ranking on different cutouts</title><style>body{font:16px/1.5 system-ui;background:#f2f6f0;color:#203b34}main{max-width:1150px;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/R76.md">Research note</a> · <a href="/results/l65/">Prior ranking test</a></nav><h1>Does the ranking help with different cutouts?</h1><p class="notice"><strong>This is a synthetic development test, not independent real-slide validation.</strong> The selected public cutouts and layouts were used in earlier experiments. Each pair is tested twice on the same, incompletely labeled Academy background; unknown training overlap and biological relationships remain. The synthetic occlusion is opaque.</p><p>We froze the earlier experiment’s selected repeatability ranking and replayed the same non-oracle grid proposals and detector-supported baseline on three pairs of different source cutouts. Each target is scored at most once, against visible or full synthetic masks, after predictions are ranked.</p><div class="card"><div class="scroll"><table><tr><th>Arrangement</th><th>Ranking</th><th>Masks per scene</th><th>Visible IoU ≥ 0.5</th><th>Visible IoU ≥ 0.75</th><th>Full IoU ≥ 0.5</th></tr>{ROWS}</table></div><p>The repeatability ranking did not improve on baseline at any tested budget. With ten masks per scene, both found 6/6 separated targets and 2/6 crossing targets. Considering every retained mask found 4/6 crossing targets, showing both a ranking limitation and a proposal limitation on this toy set.</p><p>In crossing pair 2, the two individual visible-reference matches first appeared at baseline ranks 85 and 46; repeatability placed them at ranks 74 and 61. These ranks use known reference masks after prediction; they are not an automatic method for finding a diatom.</p></div><h2>Source comparison</h2><p>All six input image hashes differ from the earlier six, and annotations were checked against their recorded hashes. A coarse DCT-hash comparison of all 36 cross-group image pairs found minimum distances of {WHOLE}/63 bits for whole images and {CROP}/63 for normalized masked crops under eight orientations. This is only a screening check; different hashes do not prove different specimens, independent samples or absence from training.</p><h2>Scene silhouettes</h2><p>Panels show visible synthetic references, the first ten baseline masks, and the first ten repeatability-ranked masks. Colors distinguish layers rather than specimen identity; source RGB images are not redistributed on this site.</p>{CARDS}<p><a href="results.json">Complete results and rankings</a> · <a href="protocol.json">Frozen protocol</a> · <a href="source-audit.json">Source similarity audit</a> · <a href="/research/r76_verify.py">Independent verifier</a> · <a href="/results/r38/">Original synthetic-scene study</a></p></main></html>'''.replace('{ROWS}',''.join(rows)).replace('{WHOLE}',str(minwhole)).replace('{CROP}',str(mincrop)).replace('{CARDS}',''.join(cards));(O/'index.html').write_text(page)
notes=['# R76 · Fixed repeatability ranking on different source cutouts','','[Visual report](/results/r76/) · [frozen protocol](/results/r76/protocol.json) · [all results and rankings](/results/r76/results.json) · [source similarity audit](/results/r76/source-audit.json) · [independent verifier](/research/r76_verify.py)','','The L65-selected prompt-repeatability interleave was frozen before replay against the same R41 baseline. We used all three previously examined R38 public cutout pairs, each separated and centered crossing, in their original placements and opaque layer order on one Academy background. The 256 grid prompts and detector support are image-derived, not reference-derived. MobileSAM candidates are filtered by quality ≥0.6 and area 300–50,000 pixels; exact-mask IoU ≥0.8 NMS precedes ranking. All raw candidate masks, prompts, detector masks, IDs, NMS aliases, original full and visible synthetic references, hashes and scores are archived. Full reference masks are not model predictions.','','| Arrangement | Ranking | Budget per scene | Visible IoU ≥0.5 | Visible IoU ≥0.75 | Full IoU ≥0.5 |','|---|---|---:|---:|---:|---:|']+md
notes+=['','At all fixed budgets, both policies match all 6 separated targets but just 2/6 crossing targets. All retained masks together match 4/6 crossing targets, identical to all eligible masks. For crossing pair 2, the first masks matching the two individual visible targets occur at baseline ranks 85 and 46, and repeatability ranks 74 and 61; these are posthoc reference-derived ranks. The other two crossing scenes each have one visible target with no matching retained or eligible mask at IoU ≥0.5. Repeatability interleaving adds no matching target here and its selected development advantage did not generalize to these previously viewed cutouts. At top 10, two crossing predictions cover at least half of each full target; this diagnostic is not by itself proof of a merged instance. With IoU≥0.8 NMS, no retained pair can reach the same threshold, so zero near-duplicate pairs is a construction artifact.','','The six actual R38 input image and annotation hashes match their archived source protocol and differ byte-for-byte from all six R41/L65 input image hashes. The DCT-hash screen compared all 36 between-group whole-image pairs and masked normalized crops, allowing eight orientations for crops. Minimum whole-image distance was 24/63 bits and minimum crop distance 12/63; no cross-group crop score was ≤8. This is a coarse screening threshold, not proof that no specimens, acquisition fields, or taxa overlap, nor that model training is separate. These images and their R38 experiments were previously viewed, and related arrangements share sources and background.','','The verifier reconstructed all six RGB composites and reference masks from source files, confirmed frozen input/output hashes and archived mask filters, independently replayed all NMS aliases and rankings, and recomputed all 48 metric records. It does not independently rerun neural inference. The original source RGB images and composites are retained in `/tmp` under the prior source-access arrangement; those paths are temporary and may disappear. Only reference/prediction silhouettes and mask archives are served here because source redistribution terms were not specified. The archived masks and source hashes alone cannot recreate RGB if those temporary files disappear.','','No real-slide segmentation accuracy, biological independence, false-positive rate, human-level proficiency, or species identification claim follows. The direct next step is to address both missing proposals and poor rank on difficult crossings with models or image features that provide distinct shape evidence, keeping multiple hypotheses and testing on distinct real overlapping masks when suitable reference material is available.']
(R/'research/R76.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 t in board['tasks']:
 if t['id']=='R76':t.update(status='review',summary='On 3 previously viewed distinct-hash synthetic pairs, both rankings matched 6/6 separated and 2/6 crossing targets at top 10; no repeatability gain.',result='/results/r76/')
p.write_text(json.dumps(board,indent=2)+'\n');p=R/'RESEARCH.md';s=p.read_text();s+='\n- **R76 · Frozen ranker on different cutouts:** both rankers matched 6/6 separated and 2/6 crossing targets at top 10; [results](/results/r76/) · [note](research/R76.md).\n';p.write_text(s)
