"""Write human-readable R75 results from verified machine records."""
import json,html,datetime
from pathlib import Path
R=Path(__file__).resolve().parents[1];O=R/'results/r75';d=json.loads((O/'results.json').read_text());aud=json.loads((O/'assignment-audit.json').read_text());records=d['records'];esc=html.escape
keys=['top10_kept','top10_plus_direct_aliases','all_kept','all_eligible_raw']
totals={k:{'n':sum(r['methods'][k]['n'] for r in records),'visible05':sum(r['methods'][k]['visible05']['matched'] for r in records),'visible075':sum(r['methods'][k]['visible075']['matched'] for r in records),'full05':sum(r['methods'][k]['full05']['matched'] for r in records)} for k in keys}
headers=['First 10 retained','First 10 + their suppressed alternatives','All retained','All eligible raw']
rows=''.join(f"<tr><th>{name}</th><td>{totals[k]['n']}</td><td>{totals[k]['visible05']}/12</td><td>{totals[k]['visible075']}/12</td><td>{totals[k]['full05']}/12</td></tr>" for k,name in zip(keys,headers))
cards=[]
for r,check in zip(records,aud['records']):
 a=r['methods']['top10_kept'];b=r['methods']['top10_plus_direct_aliases'];pair=check['methods']['top10_plus_direct_aliases']['full05']['prediction_pair_iou'];extra=f"<p>Best assigned pair of full-shape matches overlaps at IoU {pair:.3f}; the two predictions are nearly identical.</p><img src='{esc(check['full_assignment_image'])}' alt='Full references, matched predictions, and pixel differences'>" if pair is not None else ''
 cards.append(f"<article><h3>{esc(r['variant'])} · crossing {r['pair']}</h3><img src='{esc(r['image'])}' alt='Visible and full target shapes, the first ten retained masks, and their suppressed alternatives'><p>Visible matches: {a['visible05']['matched']}/2 from {a['n']} masks; with alternatives: {b['visible05']['matched']}/2 from {b['n']} masks. Full-shape matches: {a['full05']['matched']}/2 → {b['full05']['matched']}/2.</p>{extra}</article>")
page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>R75 · Do suppressed alternatives recover crossings?</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/R75.md">Research note</a> · <a href="/results/l63/">Inspect real-field alternatives</a></nav><h1>Do suppressed alternatives recover crossings?</h1><p class="notice"><strong>Controlled development test, not a real-slide accuracy estimate.</strong> Six previously inspected synthetic opaque crossings reuse three object pairs and two backgrounds. Matching is performed after prediction using the known target masks. Extra masks may be duplicates, unions, debris, or background; the source backgrounds are incompletely annotated.</p><p>We replayed 256 model-generated grid proposals for each scene. Quality and area filtering, overlap suppression, and a detector/quality ranking follow the previously used R41 procedure. The comparison adds every proposal suppressed by the first ten retained masks. A match uses one-to-one target assignment with mask IoU thresholds; the full-shape target is the inferred object before synthetic occlusion, whereas the visible target excludes covered pixels.</p><div class="card"><div class="scroll"><table><tr><th>Candidate set</th><th>Candidate masks across 6 scenes</th><th>Visible IoU ≥ 0.5</th><th>Visible IoU ≥ 0.75</th><th>Full IoU ≥ 0.5</th></tr>{ROWS}</table></div><p>Adding alternatives increased the inspection set from 60 to 485 masks without increasing visible-mask matches (4/12). Three additional full-mask matches appear, but in all three scenes the two assigned predictions overlap each other at IoU above 0.95. That score can be inflated by near-duplicate masks and does not establish two separated instances.</p><p>Looking through every retained proposal instead of only the top ten raises visible matches from 4 to 8 of 12, at 204 masks. This is a posthoc upper bound for this candidate pool, not an automatic way to choose those masks.</p></div><h2>Scene-by-scene silhouettes</h2><p>The first two panels are visible and full targets; the next two show the first ten retained candidates and their direct suppressed alternatives. Colors distinguish display layers, not confirmed specimen identity. Source image pixels are not redistributed here.</p>{CARDS}<p><a href="results.json">Results and candidate rankings</a> · <a href="assignment-audit.json">Assignment audit</a> · <a href="protocol.json">Frozen protocol and input hashes</a> · <a href="/research/r75_verify.py">Independent verification script</a>. Per-scene archives contain all 256 generated masks, reference masks and prompt positions.</p></main></html>'''.replace('{ROWS}',rows).replace('{CARDS}',''.join(cards));(O/'index.html').write_text(page)
lines=['# R75 · Suppressed alternatives in synthetic crossings','','[Visual comparisons](/results/r75/) · [frozen protocol](/results/r75/protocol.json) · [machine results](/results/r75/results.json) · [assignment audit](/results/r75/assignment-audit.json) · [independent verifier](/research/r75_verify.py)','','Six previously examined R41 synthetic crossing scenes: three pairs of annotated cutouts on two Academy backgrounds. Each scene uses 256 grid-point prompts and MobileSAM. Apply the existing quality ≥0.6 and area 300–50,000 filters, greedy IoU ≥0.8 mask suppression, then the R41 detector-supported/quality alternating ranking. The target masks are used solely for posthoc scoring. We compare the first ten retained, the first ten plus every directly suppressed proposal, the full retained set, and all quality/area-eligible raw candidates. The candidate-count cost includes duplicates.','','| Candidate set, across six scenes | Candidate masks | Visible IoU ≥0.5 | Visible IoU ≥0.75 | Full IoU ≥0.5 |','|---|---:|---:|---:|---:|']
for k,name in zip(keys,headers):
 t=totals[k];lines.append(f"| {name} | {t['n']} | {t['visible05']}/12 | {t['visible075']}/12 | {t['full05']}/12 |")
lines+=['','Expanding the first ten increased review candidates from 60 to 485 (42–120 per scene) and did not change visible-mask matches. The apparent three-match full-mask gain occurs in the alternate scenes: the respective assigned prediction pairs have IoU 0.980, 0.952 and 0.989, so near-duplicate predictions can score against two overlapping full references. The apparent gain is not evidence of separation. The model outputs do not identify whether masks are visible or full extent; the two scoring conventions show different behavior. The 4→8 visible match increase from using all retained proposals is a posthoc candidate-pool upper bound, not a usable ranked prediction or evidence that review would discover the right masks.','','Across the six scenes 1,536 generated masks were retained in the archives; 829 passed the fixed filter, of which 204 survived NMS. The remaining raw masks were preserved too. Independent verification recomputed input/output hashes, eligible sets, exact suppression decisions and maximum-cardinality matches; an additional assignment audit records matched mask IDs, pair IoUs and target-exclusive region coverage. The stored source model, point, filter and scene provenance permit reproduction. Each scene page includes silhouette images and a comparison of the matched full-mask pair when applicable.','','The scenes share six previously used objects, two backgrounds, and an opaque synthetic rendering; the underlying sources and scene layouts are not independent. Background annotations are incomplete, so the number of unmatched masks is not a false-positive estimate. No conclusion about freshwater masks, human-level segmentation, biological frequency of suppression errors, review time or real-world overlap recall follows. These mask-IoU diagnostics do not establish species identity.','','**Next:** Prioritize research on ranking or proposing multiple distinct shapes without requiring a person to inspect hundreds of aliases; investigate overlap-aware matching and explicit separate-instance evidence. Freeze any ranking before testing on independent specimens and evaluate both visible and full extent, preserving raw pixels and avoiding leakage. Retain raw suppressed masks as a safety net, not a suggested default workload.']
(R/'research/R75.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']=='R75':t.update(status='review',summary='Six synthetic crossings: expanding first 10 to 485 total masks gave no visible-mask gain; near-duplicate pairs inflated full-mask scores.',result='/results/r75/')
p.write_text(json.dumps(board,indent=2)+'\n')
p=R/'RESEARCH.md';s=p.read_text();s+='\n- **R75 · Synthetic suppression audit:** 60 top-ranked candidates expanded to 485 without visible-match improvement; near-identical masks inflated full-shape matches. [Results](/results/r75/) · [note](research/R75.md).\n';p.write_text(s)
