import json
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/r88';S=R/'results/l75';base=json.loads((S/'results.json').read_text())['records'];neighbor=json.loads((O/'neighbor-results.json').read_text())['records'];names=['separated','crossing','near','partial'];fig,axes=plt.subplots(1,2,figsize=(10,4));xx=np.arange(4)
for ax,split in zip(axes,['development','holdout_source_fields']):
 pairs=[(a,b) for a,b in zip(base,neighbor) if a['split']==split]
 for off,kind,col in [(-.18,'baseline','#367f70'),(.18,'neighbor-negative','#ca7754')]:
  vals=[sum((a['scores']['quality']['30']['visible']['0.5']['matched'] if kind=='baseline' else b['scores']['quality']['30']['0.5']['matched']) for a,b in pairs if a['condition']==c) for c in names];ax.bar(xx+off,vals,.36,label=kind,color=col)
 ax.set_title('Development' if split=='development' else 'Source-field holdout');ax.set_xticks(xx,names,rotation=15);ax.set_ylabel('Top-30 visible matches (4 targets)');ax.set_ylim(0,4.5);ax.legend(fontsize=8)
fig.tight_layout();fig.savefig(O/'neighbor-comparison.png',dpi=140);plt.close(fig);sections=[]
for a,b in zip(base,neighbor):
 if a['split']!='holdout_source_fields' or a['condition']!='crossing':continue
 z0=np.load(S/a['archive']);z1=np.load(O/b['archive']);unpack=lambda z:np.unpackbits(z['mask_bits'])[:int(np.prod(z['mask_shape']))].reshape(z['mask_shape']).astype(bool);look0={str(k):v for k,v in zip(z0['ids'],unpack(z0))};look1={str(k):v for k,v in zip(z1['ids'],unpack(z1))};rgb=Image.open(S/a['image']).convert('RGBA');out=Image.new('RGB',(1080,400),'white');draw=ImageDraw.Draw(out)
 for j,(title,masks) in enumerate([('Rendered references',z0['refs_visible']),('Grid top 30',[look0[k] for k in a['rankings']['quality'][:30]]),('Neighbor top 30',[look1[k] for k in b['rankings']['quality'][:30]])]):
  tile=rgb.copy()
  for k,m in enumerate(masks):
   layer=Image.new('RGBA',tile.size,['#008a70','#cd603b','#7357b4','#c29d2a'][k%4]);layer.putalpha(Image.fromarray(m.astype('uint8')*95));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')
 pic=f'pair-{a["pair"]}-neighbor-comparison.png';out.save(O/pic);sections.append(f'<h3>Pair {a["pair"]}: crossing</h3><p>{b["refinement_count"]} two-point refinement queries; {b["fallback_count"]} single-point fallback queries.</p><img src="{pic}" alt="Source reference and two candidate streams">')
p=O/'index.html';page=p.read_text();needle='<h2>Holdout crossing and near-coincident fields</h2>';assert needle in page;section=f'''<h2>Automatic neighbor-negative prompts</h2><p>The neighbor policy used 128 checkerboard seed queries, then 128 refinement or single-point fallback queries. A refinement added a negative point from another eligible seed inside the first seed mask; the neighbor could be part of the same organism. Both methods use 256 mask queries and one image encoding per scene, but refinements use extra point coordinates and processing. Across all 16 scenes the policy issued {sum(x['refinement_count'] for x in neighbor)} two-point refinements and {sum(x['fallback_count'] for x in neighbor)} fallback queries; it retained {sum(x['kept'] for x in neighbor)} masks versus {sum(x['kept_candidates'] for x in base)} for the grid.</p><p>At top 30, quality-ranked results were unchanged: holdout crossings 0/4 and separated, near, and partial controls 4/4, 2/4, and 4/4 respectively. The neighbor strategy recovered 2/4 crossing shapes using all retained candidates, also unchanged. The smaller 2×2 spatial ranking fell from 3/4 to 2/4 for holdout near scenes. These examples do not support adopting this rule.</p><img src="neighbor-comparison.png" alt="Matched target counts for grid and neighbor-negative prompts"><p><a href="neighbor-protocol.json">Neighbor protocol</a> · <a href="neighbor-results.json">All neighbor masks, plans and scores</a> · <a href="/research/r88_neighbor_verify.py">Replay verifier</a></p>{''.join(sections)}''';page=page.replace(needle,section+needle);page=page.replace('<p>Next: compare an automatic neighbor-aware prompting policy against these fixed grids, using the same review and prompt budgets. Reference-guided prompts may only be a clearly marked diagnostic upper bound.</p>','<p>The fixed neighbor-aware comparison is complete. Further methods remain to be explored; reference-guided prompts may only be a clearly marked diagnostic upper bound.</p>');page=page.replace('In progress. These are','These are');p.write_text(page)
