import json,collections
from pathlib import Path
import numpy as np
import matplotlib;matplotlib.use('Agg')
import matplotlib.pyplot as plt
R=Path(__file__).resolve().parents[1];O=R/'results/r90';d=json.loads((O/'results.json').read_text());groups={}
for split in ('development','source_field_holdout'):
 group=[l for r in d['records'] if r['split']==split for l in r['links']];groups[split]=collections.Counter((x['diagnostic_reference_category'],x['triage']) for x in group)
states=['compatible_evidence','lower_evidence','abstain_missing_evidence'];titles=['Compatible evidence','Lower evidence','Missing evidence'];colors=['#367f70','#ca7754','#7059a5'];fig,axes=plt.subplots(1,2,figsize=(10,4))
for ax,split in zip(axes,['development','source_field_holdout']):
 c=groups[split];x=np.arange(2);bottom=np.zeros(2)
 for state,title,col in zip(states,titles,colors):
  vals=[c['same_synthetic_source',state],c['unassigned_or_ambiguous',state]];ax.bar(x,vals,bottom=bottom,label=title,color=col);bottom+=vals
 ax.set_xticks(x,['Both same-source\nuniquely labeled','Unassigned or\nambiguous endpoint']);ax.set_title('Development' if split=='development' else 'Source-field holdout');ax.set_ylabel('Possible links');ax.legend(fontsize=7)
fig.tight_layout();fig.savefig(O/'evidence-distribution.png',dpi=140);plt.close(fig);controls=d['oracle_controls'];dif=next(x for x in controls if x['scenario']=='different_source');same=next(x for x in controls if x['scenario']=='same_source');assert dif['triage']=='compatible_evidence' and same['triage']=='compatible_evidence'
trs=[]
for split,c in groups.items():
 for category,label in [('same_synthetic_source','Both uniquely same-source'),('different_synthetic_sources','Uniquely different-source'),('unassigned_or_ambiguous','At least one unassigned/ambiguous')]:
  vals=[c[category,s] for s in states];trs.append(f'<tr><th>{split}</th><td>{label}</td><td>{vals[0]}</td><td>{vals[1]}</td><td>{vals[2]}</td></tr>')
(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>R90 evidence for focal links</title><style>body{{font:16px/1.55 system-ui;max-width:1050px;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}}</style><a href="/results/board.html">Research board</a> · <a href="/results/l77/">Prior association controls</a><h1>R90: Can orientation and focus distinguish possible links?</h1><p class="box">No safe identity rule was established. The labeled model-output sample contains no link whose endpoints uniquely match two different synthetic sources, and the sources and scenes were already viewed. These synthetic renderings do not establish real-slide performance.</p><p>We measured orientation from each candidate mask and a three-plane Laplacian-energy profile from its image pixels. A fixed screening rule calls evidence compatible when axial direction differs by at most 30° and profile cosine is at least 0.8; otherwise it marks lower or missing evidence. Every link remains present and uncommitted. Matching profiles and directions are not proof of specimen identity.</p><img src="evidence-distribution.png" alt="Evidence categories for same-source and uncertain synthetic links"><table><thead><tr><th>Source-field split</th><th>Reference-conditioned link category</th><th>Compatible</th><th>Lower</th><th>Missing</th></tr></thead><tbody>{''.join(trs)}</tbody></table><p>All 40 uniquely same-source endpoint links in these scenes met the screening criteria; none are uniquely labeled different-source. The other 590 links include unassigned or ambiguous candidates. Their unknown biological identity prevents a specificity or false-merge rate. Axis direction is omitted for nearly round masks; intensity profiles can mix objects, debris and registration errors.</p><h2>Known counterexample</h2><p>The two different-source masks shown below are oracle-constructed from synthetic source references, not model predictions. Their orientation differs by {dif['axis_difference_deg']:.2f}° and focus-profile cosine is {dif['focus_profile_cosine']:.3f}; both meet the screening criteria, as does the same-source control. Thus this simple evidence screen cannot by itself prevent a merge in the constructed case.</p><img src="/results/l77/oracle-counterexample.png" alt="Two known different overlapping synthetic source silhouettes"><p><a href="/research/R90.md">Research note</a> · <a href="protocol.json">Frozen exploratory protocol</a> · <a href="results.json">All candidate evidence and links</a> · <a href="/research/r90_verify.py">Replay verifier</a> · <a href="/results/l76/">Unlabeled Academy focal fields</a></p></html>''')
