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'];shift=json.loads((O/'shifted-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,shift) if a['split']==split]
 for off,kind,col in [(-.18,'baseline','#367f70'),(.18,'shifted','#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 matches (4 targets)');ax.set_ylim(0,4.5);ax.legend()
fig.tight_layout();fig.savefig(O/'shifted-comparison.png',dpi=140);plt.close(fig);sections=[]
for a,b in zip(base,shift):
 if a['split']!='holdout_source_fields' or a['condition'] not in ('crossing','near'):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);m0=unpack(z0);m1=unpack(z1);look0={str(k):v for k,v in zip(z0['ids'],m0)};look1={str(k):v for k,v in zip(z1['ids'],m1)};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([('Visible references',z0['refs_visible']),('Baseline top 30',[look0[k] for k in a['rankings']['quality'][:30]]),('Shifted 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"]}-{a["condition"]}-comparison.png';out.save(O/pic);sections.append(f'<h3>Pair {a["pair"]} · {a["condition"]}</h3><p>Top-30 baseline {a["scores"]["quality"]["30"]["visible"]["0.5"]["matched"]}/2; shifted {b["scores"]["quality"]["30"]["0.5"]["matched"]}/2.</p><img src="{pic}" alt="Rendered reference and both candidate streams">')
(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>R88 crossing proposal diagnosis</title><style>body{{font:16px/1.55 system-ui;max-width:1000px;margin:2em auto;padding:0 1em;color:#18342f}}img{{max-width:100%}}a{{color:#006b59}}.box{{background:#fff2d6;padding:1em}}</style><p><a href="/results/board.html">Research board</a> · <a href="/results/l75/">Source scenes</a></p><h1>R88: Where do crossing proposals fail?</h1><p class="box">In progress. These are opaque synthetic scenes from previously viewed diatom cutouts, not real overlapping specimens or a human-level assessment. The source-field holdout does not establish biological independence.</p><p>In two source-field holdout crossings, the original 256-point grid produced raw masks sufficient to match 2/4 visible reference shapes at IoU 0.5; both matches survived filtering but were ranked below the first 30 candidates. The other two shapes had best individual raw-mask IoUs of 0.488 and 0.496. Individual best scores can share a candidate and are not a multi-instance result.</p><p>Shifting every point by eight pixels while keeping 256 prompts, filters and ranking fixed did not improve those holdout crossings: both grids matched 0/4 at top 30 and 2/4 with all retained candidates. In the holdout near-coincident scenes, quality-ranked top-30 matches fell from 2/4 to 1/4. The alternative is a grid-sensitivity control, not a neighbor-aware method.</p><img src="shifted-comparison.png" alt="Bar chart comparing top-30 matches for the baseline and shifted grids"><p>One-to-one visible-mask matching at IoU ≥0.5; four targets per condition and split. Raw masks, candidate rankings and suppression links are preserved. Source reference shapes are rendered from opaque cutouts, and background objects are not fully labeled. No false-positive, species or hidden-contour claim follows.</p><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><a href="protocol.json">Stage-diagnostic protocol</a> · <a href="diagnostic.json">Stage results</a> · <a href="shifted-protocol.json">Shifted-grid protocol</a> · <a href="shifted-results.json">Shifted-grid results</a> · <a href="/research/r88_shifted_verify.py">Shifted-grid verifier</a> · <a href="/research/R88.md">Research note</a></p><h2>Holdout crossing and near-coincident fields</h2>{''.join(sections)}</html>''')
