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/l77';d=json.loads((O/'results.json').read_text());rows=d['scenes'];policies=['separate','pairwise','components','mutual07','margin'];titles=['Separate','Pairwise only','All components','Mutual best','Mutual + margin'];cols=['#367f70','#61a68c','#ca7754','#7059a5','#af9060'];clean=[r for r in rows if r['variant']=='clean'];fig,ax=plt.subplots(1,2,figsize=(11,4));ax[0].bar(titles,[sum(r['methods'][p]['metrics']['component_count'] for r in clean) for p in policies],color=cols);ax[0].set_ylabel('Candidate groups (36 clean scenes)');ax[1].bar(titles,[sum(sum(r['methods'][p]['metrics']['components_per_source'].values()) for r in clean) for p in policies],color=cols);ax[1].set_ylabel('Groups with uniquely matched source');
for a in ax:a.tick_params(axis='x',labelrotation=15)
fig.tight_layout();fig.savefig(O/'association-comparison.png',dpi=140);plt.close(fig)
tr=[]
for split in ('development','source_field_holdout'):
 a=[r for r in clean if r['split']==split]
 for p,title in zip(policies,titles):
  metrics=[r['methods'][p]['metrics'] for r in a];tr.append(f'<tr><th>{html.escape(split)}</th><td>{title}</td><td>{sum(x["component_count"] for x in metrics)}</td><td>{sum(x["source_coverage"] for x in metrics)}/36</td><td>{sum(sum(x["components_per_source"].values()) for x in metrics)}</td><td>{sum(x["components_with_both_unique_sources"] for x in metrics)}</td><td>{sum(x["components_with_unassigned_or_ambiguous"] for x in metrics)}</td></tr>')
z=np.load(R/'results/r89/pair-2-crossing_split.npz');source=Image.open(R/'results/r89/pair-2-crossing_split-z1.png').convert('RGBA');out=Image.new('RGB',(1080,400),'white');draw=ImageDraw.Draw(out)
for j,(title,ms) in enumerate([('Source 0 (oracle)',[z['refs'][0,0]]),('Source 1 (oracle)',[z['refs'][1,1]]),('Both source silhouettes',[z['refs'][0,0],z['refs'][1,1]])]):
 tile=source.copy()
 for k,m in enumerate(ms):
  layer=Image.new('RGBA',tile.size,['#008a70','#cd603b'][k%2]);layer.putalpha(Image.fromarray(m.astype('uint8')*105));tile=Image.alpha_composite(tile,layer)
 out.paste(tile.convert('RGB').resize((350,350)),(j*360+5,35));draw.text((j*360+5,10),title,fill='#203a38')
out.save(O/'oracle-counterexample.png');cal=d['oracle_calibration'];assert cal[0]['scenario']=='different_source' and cal[1]['scenario']=='same_source'
page=f'''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>L77 cross-plane association</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}}.wrap{{overflow:auto}}</style><a href="/results/board.html">Research board</a> · <a href="/results/r89/opaque/">Source focal scenes</a><h1>L77: Can cross-plane links avoid merging different objects?</h1><p class="box">Development replay on previously viewed synthetic scenes; source-reference identity is applied only after grouping for diagnostics. Results do not measure real-slide or human-level accuracy. Candidate masks, images and possible links are retained under every policy.</p><p>Across 36 clean scenes, treating every qualifying IoU ≥0.5 edge as a transitive grouping reduced 1,080 candidate groups to 533. The stricter mutual-best rule produced 712 groups, while requiring an additional 0.1 margin produced 866. Many groups contain unassigned or ambiguous candidates, so a lower group count is not evidence of correct specimen counts.</p><img src="association-comparison.png" alt="Candidate groups and source-conditioned fragments across five policies"><div class="wrap"><table><thead><tr><th>Source-field split</th><th>Policy</th><th>Groups</th><th>Sources covered</th><th>Source-labeled fragments</th><th>Groups with both unique labels</th><th>Groups with uncertain candidates</th></tr></thead><tbody>{''.join(tr)}</tbody></table></div><p>Per scene, the same first 30 focal candidates were used in every clean policy. The 36-source denominator per split is two source supports across 18 related proxy scenes; it is not 36 independent diatoms. A candidate is assigned a reference source only when it matches exactly one generated silhouette at IoU ≥0.5 on its own plane. The absence of observed groups with two uniquely labeled sources cannot establish safety: most candidates remain unassigned or ambiguous, and a group containing them can still hide a merge.</p><h2>A constructed failure of IoU-only grouping</h2><p>As a separate calibration, the two masks below are generated directly from known synthetic references, with source identities supplied by construction. They are not model predictions. The two different source silhouettes have IoU {cal[0]['edge_iou']:.3f} on adjacent planes. Connected components, mutual-best at 0.7, and the additional-margin rule all merge them into one group; leaving the pair as an uncommitted link preserves the possibility that they are distinct.</p><img src="oracle-counterexample.png" alt="Two overlapping synthetic source silhouettes showing an ambiguous cross-plane match"><p>The injected exact duplicate variant adds three candidate copies per scene; the missing-middle variant removes the middle-plane candidates. Their budgets therefore differ from clean scenes, while all policies within a variant see exactly the same candidates. Full results include per-scene ranks, groups, links and conditional labels. No unassigned candidate is called a false positive, and no proxy result establishes species identity.</p><p><a href="/research/L77.md">Research note</a> · <a href="protocol.json">Frozen protocol</a> · <a href="results.json">All scene variants, associations and scores</a> · <a href="/research/l77_verify.py">Replay verifier</a> · <a href="/results/r89/">Additive source scenes</a></p></html>''';(O/'index.html').write_text(page)
