import json,html,collections
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/l72';rows=json.loads((O/'results.json').read_text())['records'];groups=collections.defaultdict(list)
for r in rows:groups[r['group'].strip()].append(r)
names=['synthetic separated','synthetic crossing','menne','new source gomphonema','new source pinnularia'];policies=['quality','spatial2','spatial4'];labels=['quality','2×2 bins','4×4 bins'];colors=['#367f70','#ca7754','#7059a5'];fig,ax=plt.subplots(figsize=(10,4.3));x=np.arange(len(names));
for i,(p,label,color) in enumerate(zip(policies,labels,colors)):ax.bar(x+(i-1)*.24,[sum(r['scores'][p]['30'] for r in groups[n]) for n in names],.24,label=label,color=color)
ax.set_xticks(x,['synthetic\nseparated','synthetic\ncrossing','Menne','new source\nGomphonema','new source\nPinnularia']);ax.set_ylabel('Matched source shapes, top 30');ax.legend();fig.tight_layout();fig.savefig(O/'ranking-comparison.png',dpi=140);plt.close(fig)
trs=''.join(f'<tr><th>{html.escape(n)}</th><td>{sum(r["references"] for r in groups[n])}</td>'+''.join(f'<td>{sum(r["scores"][p][b] for r in groups[n])}</td>' for b in ('10','30') for p in policies)+'</tr>' for n in names);sections=[]
for row in [r for r in rows if r['group'].strip()=='synthetic crossing']:
 l71=json.loads((R/'results/l71/results.json').read_text())['records'][row['index']];z=np.load(R/'results/l71'/row['candidate_archive']);masks=np.unpackbits(z['mask_bits'])[:int(np.prod(z['mask_shape']))].reshape(z['mask_shape']).astype(bool);lookup={str(i):m for i,m in zip(z['ids'],masks)};refs=np.load(R/'results/r78'/l71['ref_archive'])['refs_visible'];rgb=np.asarray(Image.open(l71['image']).convert('RGB'));out=Image.new('RGB',(1080,400),'white');draw=ImageDraw.Draw(out)
 for j,(title,ms) in enumerate([('Synthetic visible references',refs),('Quality ranking: top 30',[lookup[k] for k in row['rankings']['quality'][:30]]),('2×2 bins: top 30',[lookup[k] for k in row['rankings']['spatial2'][:30]])]):
  tile=Image.fromarray(rgb).convert('RGBA')
  for k,m in enumerate(ms):
   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'crossing-{row["index"]}.png';out.save(O/pic);sections.append(f'<h3>Synthetic crossing {row["index"]}</h3><p>Top-30 quality {row["scores"]["quality"]["30"]}/2; 2×2 bins {row["scores"]["spatial2"]["30"]}/2.</p><img src="{pic}" alt="Reference and candidate masks under two rankings">')
(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>L72 spatial ranking</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:#eef5f1;padding:1em}}</style><a href="/results/board.html">Research board</a><h1>L72: Does spatial ranking help the review budget?</h1><p class="box">Development analysis on 40 already examined real and synthetic fields. These results do not measure human-level overlap segmentation or species accuracy.</p><p>Within each fixed spatial grid, candidate points are visited round-robin across bins, with quality order retained inside each bin. No source labels were used for ranking; all kept candidates remain in the list. This replay starts <em>after</em> the earlier same-stream IoU suppression, so alternatives suppressed at that stage remain in the separate raw-mask archives.</p><p>For the three synthetic crossing fields, a 2×2 grid matches 3/6 visible source shapes at a per-field budget of 30 candidates, compared with 2/6 for quality. On the new-source fields, all three methods have the same top-30 count; some smaller-budget comparisons get worse. These are small, related, already-viewed examples, so the method is only a lead.</p><img src="ranking-comparison.png" alt="Chart comparing ranking strategies across five source groups"><table><thead><tr><th>Group</th><th>Source shapes</th><th>Quality 10</th><th>2×2 10</th><th>4×4 10</th><th>Quality 30</th><th>2×2 30</th><th>4×4 30</th></tr></thead><tbody>{trs}</tbody></table><p>Counts are one-to-one source-polygon matches at IoU ≥ 0.5. Candidate spatial bins depend on point coordinates, not specimen identity; real overlap labels remain scarce. The same-stream suppression step can remove real alternatives and is not proven safe by this ranking test. No precision, species or generalization claim is supported.</p><p><a href="/research/L72.md">Research note</a> · <a href="protocol.json">Frozen protocol</a> · <a href="results.json">All ranks and field scores</a> · <a href="/research/l72_verify.py">Replay verifier</a></p><h2>Crossing comparisons</h2>{''.join(sections)}</html>''')
