import json,collections,html
from pathlib import Path
import numpy as np
from PIL import Image,ImageDraw
import matplotlib;matplotlib.use('Agg')
import matplotlib.pyplot as plt
R=Path(__file__).resolve().parents[1];O=R/'results/r89';rows=json.loads((O/'results.json').read_text())['records'];conds=['separated_split','crossing_split','crossing_same','crossing_drift'];keys=['middle256','middle4','focal'];titles=['Middle 256','Middle 4×64','Focal 3×64 + middle 64'];colors=['#367f70','#7059a5','#ca7754'];groups=collections.defaultdict(list)
for r in rows:groups[(r['split'],r['condition'])].append(r)
fig,axes=plt.subplots(1,2,figsize=(11,4));x=np.arange(4)
for ax,split in zip(axes,['development','source_field_holdout']):
 for i,(name,title,col) in enumerate(zip(keys,titles,colors)):ax.bar(x+(i-1)*.25,[sum(r['scores'][name]['30']['matched'] for r in groups[split,c]) for c in conds],.25,label=title,color=col)
 ax.set_title('Development' if split=='development' else 'Source-field holdout');ax.set_xticks(x,['separated\nsplit focus','crossing\nsplit focus','crossing\nsame focus','crossing\nwith drift']);ax.set_ylim(0,4.5);ax.set_ylabel('Top-30 synthetic-silhouette matches');ax.legend(fontsize=7)
fig.tight_layout();fig.savefig(O/'comparison.png',dpi=140);plt.close(fig)
tr=''.join('<tr><th>'+('Development' if s=='development' else 'Source-field holdout')+'</th><td>'+c+'</td>'+''.join(f'<td>{sum(r["scores"][k]["30"]["matched"] for r in groups[s,c])}/4</td>' for k in keys)+'</tr>' for s in ['development','source_field_holdout'] for c in conds)
counts=collections.Counter(link['evaluation'] for r in rows for link in r['links']);sections=[]
for r in rows:
 z=np.load(O/r['archive']);m=np.unpackbits(z['mask_bits'])[:int(np.prod(z['mask_shape']))].reshape(z['mask_shape']).astype(bool);lookup={str(k):v for k,v in zip(z['ids'],m)};orig=[Image.open(O/x['file']).convert('RGBA') for x in r['images']];out=Image.new('RGB',(1230,360),'white');draw=ImageDraw.Draw(out)
 for j,(title,img,masks) in enumerate([('Plane 0',orig[0],[]),('Middle source silhouettes',orig[1],z['refs'][1]),('Plane 2',orig[2],[]),('Focal top 15 on middle',orig[1],[lookup[k] for k in r['rankings']['focal'][:15]])]):
  tile=img.copy()
  for i,mask in enumerate(masks):
   layer=Image.new('RGBA',tile.size,['#008a70','#cd603b','#7357b4','#c29d2a'][i%4]);layer.putalpha(Image.fromarray(mask.astype('uint8')*95));tile=Image.alpha_composite(tile,layer)
  out.paste(tile.convert('RGB').resize((300,300)),(j*307+3,40));draw.text((j*307+5,10),title,fill='#203a38')
 pic=r['archive'].replace('.npz','-comparison.png');out.save(O/pic);co=collections.Counter(v['evaluation'] for v in r['links']);sections.append(f'<section><h3>Pair {r["pair"]} · {html.escape(r["split"])} · {r["condition"]}</h3><p>Top-30 silhouette matches: middle {r["scores"]["middle256"]["30"]["matched"]}/2; middle four-stream {r["scores"]["middle4"]["30"]["matched"]}/2; focal {r["scores"]["focal"]["30"]["matched"]}/2. Adjacent-plane links: same source {co["same_synthetic_source"]}, different sources {co["different_synthetic_sources"]}, unassigned/ambiguous {co["unassigned_or_ambiguous"]}.</p><img src="{pic}" alt="Three focal-plane proxy images, source silhouettes and focal candidate overlays"></section>')
page=f'''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>R89 focal synthetic controls</title><style>body{{font:16px/1.55 system-ui;max-width:1100px;margin:2em auto;padding:0 1em;color:#18342f}}img{{max-width:100%}}a{{color:#006b59}}table{{border-collapse:collapse}}td,th{{border:1px solid #b8ccc0;padding:.5em;text-align:left}}.box{{background:#fff2d6;padding:1em}}section{{border-top:1px solid #ccc}}</style><a href="/results/board.html">Research board</a> · <a href="/results/l76/">Real focal field inspector</a><h1>R89: Does focal diversity separate synthetic source shapes?</h1><p class="box">This first phase uses additive grayscale cutouts with Gaussian blur and a small injected drift, not calibrated microscope optics or physical occlusion. Source fields and backgrounds were previously examined; source-field holdout does not establish independent organisms. The score matches synthetic source silhouettes and does not measure real visible or hidden diatom boundaries.</p><p>Each method uses 256 point-mask queries per scene. Middle 256 has one image encoding; focal and middle-only four-stream control each have four encodings. The focal stream uses 64 queries at each of three focal planes plus 64 more on the middle. The four-stream control uses four disjoint grids on the middle plane. Streams are interleaved without cross-plane deletion; repeated masks are not treated as verified distinct objects.</p><img src="comparison.png" alt="Bar chart of synthetic source-silhouette matches at top 30"><table><thead><tr><th>Source fields</th><th>Condition</th><th>Middle 256</th><th>Middle four-stream</th><th>Focal four-stream</th></tr></thead><tbody>{tr}</tbody></table><p>Each row covers four synthetic shapes from two pairs, with one-to-one IoU ≥0.5. Split-focus scenes deliberately make different source layers sharper at opposing planes, which favors focal methods. The fixed two-plane shift affects the entire rendered image; no registration is applied. A candidate is compared with the source silhouette at that candidate’s own plane. Real background is unlabelled; unmatched proposals are not confirmed false positives.</p><h2>Cross-plane associations</h2><p>Candidate pairs from adjacent planes with IoU ≥0.5 are kept as links, never collapsed. Only endpoints that each match exactly one synthetic silhouette at IoU ≥0.5 receive a source label; all other links are unassigned or ambiguous. Across these scenes: {counts['same_synthetic_source']} links have the same synthetic source, {counts['different_synthetic_sources']} link different sources, and {counts['unassigned_or_ambiguous']} are unassigned/ambiguous. These are conditional diagnostics on pairwise links, not validated complete tracks or a real-world association error rate.</p><p>Next: test explicit occlusion order and source-pair cases under an optical proxy, and inspect track fragmentation. Those steps remain part of R89; this first phase alone does not complete the research item.</p><p><a href="/research/R89.md">Research plan and notes</a> · <a href="protocol.json">Frozen protocol</a> · <a href="results.json">All masks, ranks, links and scores</a> · <a href="/research/r89_verify.py">Replay verifier</a></p><h2>Scene comparisons</h2><p>Focal candidates from different planes are overlaid on the middle image for spatial context; inspect the source images before interpreting focus.</p>{''.join(sections)}</html>''';(O/'index.html').write_text(page)
