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/opaque';rows=json.loads((O/'results.json').read_text())['records'];conds=['separated_split','crossing_front0','crossing_front1','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=(12,4));x=np.arange(5)
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','front 0','front 1','same focus','drift'],rotation=20);ax.set_ylim(0,4.5);ax.set_ylabel('Top-30 visible-support matches');ax.legend(fontsize=7)
fig.tight_layout();fig.savefig(O/'comparison.png',dpi=140);plt.close(fig)
trs=''.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 visible references',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);sections.append(f'<section><h3>Pair {r["pair"]} · {html.escape(r["split"])} · {r["condition"]}</h3><p>Front source {r["front_source"]}; occluded fractions {100*r["occluded_fraction"][0]:.1f}% and {100*r["occluded_fraction"][1]:.1f}%. Top-30 visible-reference matches: middle {r["scores"]["middle256"]["30"]["matched"]}/2; middle four-stream {r["scores"]["middle4"]["30"]["matched"]}/2; focal {r["scores"]["focal"]["30"]["matched"]}/2.</p><img src="{pic}" alt="Synthetic focal planes, visible references and focal candidates"></section>')
(O/'index.html').write_text(f'''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>R89 opaque focal 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/r89/">Additive focal control</a><h1>R89: Reversing synthetic front and back layers</h1><p class="box">These 20 scenes use opaque compositing and Gaussian blur of previously examined cutouts on real background crops. This is a controlled proxy, not calibrated microscope optics or real diatom occlusion. The source-field holdout does not establish biological independence.</p><p>Each scene uses the same 256 point-mask query budget for all three methods. The middle-only grid encodes one image; the four-stream middle and focal controls each encode four images. Split-focus conditions deliberately place the source layers at opposite focal peaks, and source-specific visible supports are known because they were rendered.</p><img src="comparison.png" alt="Bar chart of visible-reference matches"><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>{trs}</tbody></table><p>Four visible source masks per condition per split; one-to-one matching at IoU ≥0.5, with 30 candidates per scene. Focal candidates are scored against the rendered support on their own plane. The rendered back-layer mask excludes the overlapping front support; this does not establish a real diatom boundary or reconstruct invisible full geometry.</p><p>Across all scenes, adjacent-plane candidate overlaps at IoU ≥0.5 yielded {counts['same_synthetic_source']} links with two uniquely same-source endpoints, {counts['different_synthetic_sources']} with two uniquely different-source endpoints, and {counts['unassigned_or_ambiguous']} links with an unassigned or ambiguous endpoint. Labels are reference-assisted after inference, and these conditional links are not complete tracks or a real-world accuracy rate.</p><p>Source attribution, raw grayscale planes, images, full and visible support masks, point masks and suppression links are preserved. Background structures have no labels, so unmatched masks are not verified false positives. No species or human-level performance claim follows.</p><p><a href="/research/R89.md">Research note</a> · <a href="protocol.json">Frozen protocol</a> · <a href="results.json">All masks, ranks and scores</a> · <a href="/research/r89_opaque_verify.py">Replay verifier</a></p><h2>Scene comparisons</h2><p>Focal candidates from multiple planes are overlaid on the middle plane for context.</p>{''.join(sections)}</html>''')
