"""Render equal-budget prompt-sampling development diagnostic."""
import json,html,datetime
from pathlib import Path
R=Path(__file__).resolve().parents[1];O=R/'results/l66';d=json.loads((O/'results.json').read_text());records=d['records'];names=['uniform','contrast','mixed'];labels={'uniform':'Uniform grid','contrast':'Contrast stratified','mixed':'Mixed grid + contrast'}
def tally(cond,name,key,metric):
 return sum((r['policies'][name]['budgets'][key] if key.isdigit() else r['policies'][name][key])[metric]['matched'] for r in records if r['condition']==cond)
rows=[];md=[]
for cond in ('separated','crossing'):
 for name in names:
  n5=tally(cond,name,'5','visible05');n10=tally(cond,name,'10','visible05');n20=tally(cond,name,'20','visible05');strict=tally(cond,name,'20','visible075');full=tally(cond,name,'20','full05');all_=tally(cond,name,'all_kept','visible05');row=(cond,labels[name],f'{n5}/6',f'{n10}/6',f'{n20}/6',f'{strict}/6',f'{full}/6',f'{all_}/6');rows.append('<tr>'+''.join('<td>'+x+'</td>' for x in row)+'</tr>');md.append('| '+' | '.join(row)+' |')
cards=[]
for r in records:
 scores=', '.join(f"{labels[k]} {r['policies'][k]['budgets']['20']['visible05']['matched']}/2" for k in names);cards.append(f"<article><h3>Pair {r['pair']} · {html.escape(r['condition'])}</h3><img src='{html.escape(r['image'])}' alt='Visible reference silhouettes, uniform top ten, contrast top ten, and oracle-point masks'><p>At top 20: {scores}. Oracle points: {r['oracle']['metrics']['visible05']['matched']}/2.</p></article>")
page='''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"><title>L66 · Recovering crossing masks</title><style>body{font:16px/1.5 system-ui;background:#f2f6f0;color:#203b34}main{max-width:1180px;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/L66.md">Research note</a> · <a href="/results/r76/">Earlier ranking test</a></nav><h1>Can image-driven prompts recover crossing masks?</h1><p class="notice"><strong>Synthetic development diagnostic.</strong> These six previously viewed scenes reuse three pairs of public cutouts and a single partly unannotated Academy background. The opaque crossing construction differs from microscopy. This is not independent validation, an estimate of false positives, or real-slide segmentation accuracy.</p><p>Three image-only policies each select 64 points from an earlier 256-point grid: a regular grid, points with high local contrast distributed across the image, and a mixture. The earlier detector-assisted ranking and quality/area filters are held fixed. Results reuse saved masks from the earlier 256-prompt inference; no runtime saving from 64 prompts has been measured.</p><div class="card"><div class="scroll"><table><tr><th>Arrangement</th><th>64-prompt policy</th><th>Visible top 5</th><th>Visible top 10</th><th>Visible top 20</th><th>Visible top 20 ≥0.75</th><th>Full top 20 ≥0.5</th><th>Visible all retained</th></tr>{ROWS}</table></div><p>Visible scores use mask IoU ≥0.5 unless another threshold is shown. The mixed set moves one additional crossing target into the first 20: 3/6 versus 2/6 for uniform and contrast. At top 10 all three remain at 2/6. Looking through every retained candidate yields 4/6 for mixed and contrast versus 3/6 uniform. These are tiny, previously examined development examples; they do not establish a reliable improvement.</p><p>Reference-derived oracle points matched 6/6 separated and 4/6 crossing targets. They use known target masks to place prompts, cannot be used by the automatic pipeline, and are a diagnostic rather than a mathematical upper bound.</p></div><h2>Scene silhouettes</h2><p>Each panel shows the visible synthetic references, the first ten uniform masks, the first ten contrast masks, and the two reference-derived oracle masks. Colors distinguish layers, not confirmed identities. The mixed ranking and full archives are in the results file. Original source RGB images are not redistributed here.</p>{CARDS}<p><a href="results.json">Scores, selected points and rankings</a> · <a href="protocol.json">Frozen protocol and hashes</a> · <a href="/research/l66_verify.py">Independent verifier</a> · <a href="/results/r76/">Source masks and provenance</a></p></main></html>'''.replace('{ROWS}',''.join(rows)).replace('{CARDS}',''.join(cards));(O/'index.html').write_text(page)
text=['# L66 · Counterfactual prompt selection for crossings','','[Visual comparison](/results/l66/) · [frozen protocol](/results/l66/protocol.json) · [all selected points, rankings and scores](/results/l66/results.json) · [independent verifier](/research/l66_verify.py) · [source prediction masks](/results/r76/)','','On the same six previously examined R38/R76 synthetic scenes, compare three frozen, image-only subsets of the 256 cached MobileSAM grid predictions. Each subset contains exactly 64 prompt positions: a regular 8×8 grid; four highest local-gray-contrast points per 128×128 cell; and 32 checkerboard uniform points followed by 32 spatially balanced contrast points. Local contrast is the standard deviation of a 32×32 image window; ties use fixed grid order. Each strategy uses the same quality and area filters, mask IoU ≥0.8 suppression, and the R41 detector/quality interleaved ranking. A detector was also run once per scene in the source experiment; candidate masks and detector outputs were reused.','','| Arrangement | 64-prompt policy | Visible top 5 | Visible top 10 | Visible top 20 | Visible top 20 ≥0.75 | Full top 20 ≥0.5 | Visible all retained |','|---|---|---:|---:|---:|---:|---:|---:|']+md
text+=['','Visible scores are one-to-one mask matches at IoU ≥0.5 unless specified. With 20 displayed proposals per crossing scene, the mixed policy matches 3/6 targets versus 2/6 for uniform or contrast; the extra match is a single target in crossing pair 2. At top 10, all match 2/6. All retained contrast and mixed candidates match 4/6 crossing targets versus 3/6 uniform, but inspecting all retained candidates requires 109, 98, and 95 candidates respectively across the three crossing scenes. The pair-2 second target remains below the top 20 even in mixed. On separated scenes, contrast and mixed match 6/6 versus 5/6 uniform; the same single target accounts for the difference. These are exploratory outcomes on three related pairs, not an estimate of generalizable improvement.','','Reference-derived oracle points, one inside each known visible mask, match 6/6 separated and 4/6 crossing targets at IoU ≥0.5; the scores agree with R38. Oracle prompts use the answers to locate points and cannot be used as an automatic method; they are not a mathematical upper bound. In crossing pairs 1 and 3, even those two oracle points do not yield a visible-mask match for one target. A mask covering half of each full target may reflect merging; the stored diagnostics do not establish identity, and prior NMS forces retained-pair IoUs below 0.8.','','The independent verifier rederived all 18 64-point sets from the source pixels, checked exact NMS aliases and rank order, recomputed 90 match/duplicate/coverage metric records, and checked oracle point coordinates and stored mask scores; it did not rerun model inference. Unit tests cover equal prompt budgets, deterministic cell distribution and bad inputs. All 256 source model masks and detector outputs are retained in R76, the new two-mask oracle archives are linked in the results, and source/image/weight hashes are frozen. Source RGB composites and source cutouts are currently in `/tmp` and can disappear; RGB cannot be reconstructed from stored masks if they are removed.','','The same public cutouts, synthetic occlusion, source background and model have been inspected before; unknown biological or model-training overlap, incomplete background labels, and the lack of independent real overlap masks preclude claims about human-level segmentation, false-positive rates or freshwater generalization. The cached replay does not measure 64-prompt inference time. Any prompt or ranking choice requires frozen testing on different samples and real expert-adjudicated overlaps before adoption.']
(R/'research/L66.md').write_text('\n'.join(text)+'\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']=='L66':t.update(status='review',summary='Mixed 64-point sampling moved one crossing match into top 20 (3/6 vs 2/6); all policies remain 2/6 at top 10. Synthetic development only.',result='/results/l66/')
p.write_text(json.dumps(board,indent=2)+'\n');p=R/'RESEARCH.md';s=p.read_text();s+='\n- **L66 · Equal-budget alternate prompts:** mixed grid/contrast sampling gained one crossing target at top 20 (3/6 vs 2/6), but none at top 10. [Results](/results/l66/) · [note](research/L66.md).\n';p.write_text(s)
