"""Illustrate candidate-pair prompt locations relative to synthetic supports."""
import collections,html,json
from pathlib import Path
import numpy as np
from PIL import Image,ImageDraw
R=Path(__file__).resolve().parents[1];O=R/'results/l87';S=R/'results/l75';rows=json.loads((O/'results.json').read_text())['records'];orig={(r['pair'],r['condition']):r for r in json.loads((R/'results/r99/results.json').read_text())['records']};table=[];cards=[]
for x in rows:
 counts=collections.Counter(i['category'] for i in x['items']);table.append(f'<tr><td>{x["pair"]} {html.escape(x["condition"])}</td><td>{counts["different"]}</td><td>{counts["same"]}</td><td>{counts["one"]}</td><td>{counts["neither"]}</td></tr>');r=orig[x['pair'],x['condition']];rgb=Image.open(S/r['source_image']).convert('RGBA');refs=np.load(S/x['source_archive'])['refs_visible'];panel=Image.new('RGB',(1040,560),'white');d=ImageDraw.Draw(panel);d.text((8,4),'Original synthetic image',fill='#203a38');d.text((528,4),'Inserted supports + candidate point pairs',fill='#203a38');panel.paste(rgb.convert('RGB'),(4,30));tile=rgb
 for i,ref in enumerate(refs):
  lay=Image.new('RGBA',tile.size,('#008a70','#cd603b')[i]);lay.putalpha(Image.fromarray(ref.astype('uint8')*100));tile=Image.alpha_composite(tile,lay)
 panel.paste(tile.convert('RGB'),(524,30));d=ImageDraw.Draw(panel)
 for i,p in enumerate(r['plans']):
  ax,ay=p['a_point'];bx,by=p['b_point'];color='#e100b5' if x['pairs'][i]['informative'] else '#ffbf00';d.line((524+ax,30+ay,524+bx,30+by),fill=color,width=2)
  for px,py in ((ax,ay),(bx,by)):d.ellipse((524+px-3,30+py-3,524+px+3,30+py+3),fill=color,outline='black')
 name=f"pair-{x['pair']}-{x['condition']}.png";panel.save(O/name);cards.append(f'<section><h2>Pair {x["pair"]}: {html.escape(x["condition"])}</h2><p>{counts["different"]} directed prompts had points in different inserted supports; {counts["neither"]} had neither point in them. Purple = pair on both distinct inserted supports; yellow = other candidate pair. The points may land on other real-looking organisms in the background.</p><a href="{name}"><img loading="lazy" src="{name}" alt="Original composite and candidate point pairs over inserted supports"></a></section>')
(O/'index.html').write_text('''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>L87 prompt location diagnosis</title><style>body{font:16px/1.5 system-ui;color:#18342f;max-width:1200px;margin:2em auto;padding:0 1em}a{color:#006b59}img{max-width:100%;height:auto}table{border-collapse:collapse}td,th{border:1px solid #bbc;padding:.4em}.warn{background:#fff2d6;padding:1em}section{border-top:1px solid #ccd}</style><a href="/results/board.html">Research board</a> · <a href="/results/r99/">Automatic prompting experiment</a><h1>L87: Where did competing points land?</h1><p class="warn">This is a posthoc, reference-assisted diagnosis. The inserted supports are known only because these are synthetic scenes. The method cannot use these labels on an unknown slide. Outside the two inserted supports does not mean background or a false positive: the Academy background contains other unlabeled structures and diatoms.</p><p>Each R99 candidate pair yields two directed prompts. Classify each prompt by whether its positive and negative points land on different inserted visible supports, the same support, exactly one inserted support, or neither. Of 486 directed prompts, <strong>4</strong> had points on different inserted supports and <strong>482</strong> had neither point on those supports. There were no prompts with exactly one point or both on the same inserted support. The four informative directions correspond to two reciprocal candidate pairs, both in already inspected development scenes.</p><p>In the crossing pair, one of two intended target masks matched its visible support at IoU ≥0.5 with either positive-only or negative prompts. In the near-overlap pair, both intended target masks matched with both methods. This is a selection conditioned on reference labels after the run; two examples cannot establish reliability. The former-holdout crossing scenes had no candidate pair whose two points landed on the distinct inserted supports.</p><p>The diagnosis reveals a limitation of the control: a low match count against only two inserted supports does not tell us whether the candidate generator is bad at finding diatoms elsewhere in the same busy image. It also suggests that this particular refinement was seldom directed at the two annotated targets; a clean-background control alongside a separately labeled busy-field benchmark would separate these effects.</p><table><tr><th>Scene</th><th>Different supports</th><th>Same support</th><th>One point on support</th><th>Neither point on support</th></tr>'''+''.join(table)+'''</table><p>All source/archive hashes, point categories, intended-target IoUs and reciprocal pair matches were reconstructed; the one-to-one matcher is shared and model inference was not rerun. The figures add colored points to the original synthetic input for inspection and are not new inference.</p><p><a href="protocol.json">Frozen diagnostic</a> · <a href="results.json">All categories and scores</a> · <a href="verify.log">Verification</a> · <a href="/research/L87.md">Research note</a></p>'''+''.join(cards)+'</html>')
