import json,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/l75';rows=json.loads((O/'results.json').read_text())['records'];names=['separated','crossing','near','partial'];fig,axes=plt.subplots(1,2,figsize=(10,4));x=np.arange(4)
for ax,split in zip(axes,['development','holdout_source_fields']):
 for dx,b,col in [(-.18,'30','#367f70'),(.18,'all','#ca7754')]:
  vals=[sum(r['scores']['quality'][b]['visible']['0.5']['matched'] for r in rows if r['split']==split and r['condition']==cond) for cond in names];ax.bar(x+dx,vals,.36,label='top 30' if b=='30' else 'all',color=col)
 ax.set_title('Development' if split=='development' else 'Source-field holdout');ax.set_xticks(x,names,rotation=15);ax.set_ylim(0,4.5);ax.set_ylabel('Visible-reference matches (4 targets)');ax.legend()
fig.tight_layout();fig.savefig(O/'visible-matches.png',dpi=140);plt.close(fig)
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)};rgb=Image.open(O/r['image']).convert('RGB');out=Image.new('RGB',(1080,400),'white');d=ImageDraw.Draw(out)
 for j,(name,ms) in enumerate([('Source composite',[]),('Rendered visible references',z['refs_visible']),('Quality ranking · top 30',[lookup[k] for k in r['rankings']['quality'][:30]])]):
  tile=rgb.convert('RGBA')
  for k,mask in enumerate(ms):
   layer=Image.new('RGBA',tile.size,['#008a70','#cd603b','#7357b4','#c29d2a'][k%4]);layer.putalpha(Image.fromarray(mask.astype('uint8')*95));tile=Image.alpha_composite(tile,layer)
  out.paste(tile.convert('RGB').resize((350,350)),(j*360+5,35));d.text((j*360+5,10),name,fill='#203a38')
 pic=r['image'].replace('.png','-comparison.png');out.save(O/pic);q=r['scores']['quality']['30']['visible']['0.5'];a=r['scores']['quality']['all']['visible']['0.5'];sections.append(f'<h3>Pair {r["pair"]} · {html.escape(r["split"])} · {r["condition"]}</h3><p>Visible matches: top 30 {q["matched"]}/{q["reference_count"]}, all {a["matched"]}/{a["reference_count"]}. Rear object occluded: {100*r["occluded_fraction"][0]:.1f}% of in-frame shape; rear shape clipped: {100*r["frame_clipped_fraction"][0]:.1f}% of source silhouette.</p><img src="{pic}" alt="Synthetic composite, reference polygons and candidate masks">')
(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>L75 severe synthetic occlusion</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}}.box{{background:#fff2d6;padding:1em}}</style><a href="/results/board.html">Research board</a><h1>L75: Can we recover two diatoms under severe occlusion?</h1><p class="box">Sixteen synthetic scenes use opaque cutouts from eight previously viewed public-image fields on an Academy background. They are not physical microscope simulations or real overlapping specimens. The source-field holdout uses different files, but biological independence and model training exposure are unknown.</p><p>The holdout source-field pairs produced 4/4 visible matches at IoU ≥0.5 for separated scenes and 4/4 for edge-clipped scenes, but 0/4 for crossings at a 30-candidate budget; all retained candidates recovered 2/4 crossing shapes. These are four related rendered targets per condition, not estimates of real-slide recall.</p><img src="visible-matches.png" alt="Synthetic visible-reference matches for development and source-field holdout"><p>Near and crossing arrangements use two source shapes on the same canvas; the back reference is the visible portion after the front opaque layer. Full-in-frame source silhouettes and clipped fractions are separately stored; these are not observed hidden biological contours. Both point grids and ranking are image-only, not reference-derived. IoU matching is one-to-one; source references with fewer than 50 visible pixels are excluded from visible scores and recorded. All 32 references in these scenes exceed that threshold.</p><p>The <a href="assignment-audit.json">assignment audit</a> records predicted-mask overlap and each match’s coverage of the other visible target. Since IoU ≥0.8 NMS was applied, the absence of retained prediction pairs at that threshold is a construction artifact, not proof that the predictions represent distinct organisms. Background objects are unannotated, so unmatched masks are not confirmed false positives. No species classification or expert-level claim follows.</p><p><a href="/research/L75.md">Research note</a> · <a href="protocol.json">Frozen protocol and source hashes</a> · <a href="results.json">All scores and candidate ranks</a> · <a href="/research/l75_verify.py">Replay verifier</a> · <a href="assignment-audit.json">Assignment audit</a></p><h2>Scene comparisons</h2>{''.join(sections)}</html>''')
