import json,html
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/l78';S=R/'results/r79';CP=R/'results/r78';rows=json.loads((O/'menne-results.json').read_text())['records'];fig,ax=plt.subplots(figsize=(7,4));labels=['IoU ≥0.5','IoU ≥0.75'];x=np.arange(2)
for off,name,col in [(-.18,'baseline','#367f70'),(.18,'adapted','#ca7754')]:ax.bar(x+off,[sum(r['results'][name]['scores']['quality']['30'][t]['matched'] for r in rows) for t in ('0.5','0.75')],.36,label=name,color=col)
ax.set_xticks(x,labels);ax.set_ylim(0,29);ax.set_ylabel('Matched source regions (29 total)');ax.set_title('Previously examined River Menne fields · top 30');ax.legend();fig.tight_layout();fig.savefig(O/'menne-summary.png',dpi=140);plt.close(fig);sections=[]
for r in rows:
 a=np.load(S/r['source_sam_archive']);b=np.load(O/r['adapted_archive']);unpack=lambda z:np.unpackbits(z['mask_bits'])[:int(np.prod(z['mask_shape']))].reshape(z['mask_shape']).astype(bool);m0=unpack(a);m1=unpack(b);map0={str(k):v for k,v in zip(a['ids'],m0)};map1={str(k):v for k,v in zip(b['ids'],m1)};refs=np.load(CP/r['source_reference_archive'])['refs_visible'];rgb=Image.open(R/'datasets/l78-menne/images'/f"{r['image_id']}.tif").convert('RGBA');out=Image.new('RGB',(1080,400),'white');draw=ImageDraw.Draw(out)
 for j,(title,ms) in enumerate([('Published source regions',refs),('Original top 30',[map0[k] for k in r['results']['baseline']['rankings']['quality'][:30]]),('Point-trained top 30',[map1[k] for k in r['results']['adapted']['rankings']['quality'][:30]])]):
  tile=rgb.copy()
  for k,mask in enumerate(ms):
   layer=Image.new('RGBA',tile.size,['#008a70','#cd603b','#7357b4','#c29d2a'][k%4]);layer.putalpha(Image.fromarray(mask.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"menne-{r['image_id']}-comparison.png";out.save(O/pic);a0=r['results']['baseline']['scores']['quality']['30']['0.5']['matched'];a1=r['results']['adapted']['scores']['quality']['30']['0.5']['matched'];sections.append(f'<section><h3>Field {r["image_id"]} · {html.escape(r["slide"])}</h3><p>Source regions {r["references"]}; top-30 IoU ≥0.5 matches original {a0}, adapted {a1}. <a href="/datasets/l78-menne/images/{r["image_id"]}.tif">Original source field</a></p><img src="{pic}" alt="Source regions and candidate masks from both decoders"></section>')
(O/'menne.html').write_text(f'''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>L78 Menne source replay</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}}.box{{background:#fff2d6;padding:1em}}section{{border-top:1px solid #ccc}}</style><a href="/results/l78/">L78 synthetic decoder experiment</a> · <a href="/results/board.html">Research board</a><h1>L78: Does the point-trained decoder transfer to River Menne fields?</h1><p class="box">Eighteen previously examined fields from a different public dataset. Published regions exclude many fragments and aggregates and do not establish a real heavy-overlap benchmark. Former train/test labels do not make these fields newly held out; sample independence and base-model training exposure are unknown.</p><p>At a top-30 budget with the same 64 automatic point prompts, the original and adapted decoders matched 15 and 14 of 29 source regions at IoU ≥0.5. At IoU ≥0.75 they matched 12 and 14. This mixed, small development result does not establish a reliable gain or species accuracy.</p><img src="menne-summary.png" alt="Chart of matched source regions at two IoU thresholds"><p>Both decoders use the same native field, point locations, quality ≥0.6, area 300–50,000 and IoU 0.8 NMS. Baseline cached masks were reproduced for the first 12 prompts per field. Unmatched predictions are not established false positives; only source regions are scored. Exact original field files are mirrored with source SHA-256.</p><p>Source: Kloster et al., <a href="https://doi.org/10.5281/zenodo.7079005">River Menne dataset</a>, CC BY 4.0. <a href="/research/L78.md">Research note</a> · <a href="menne-protocol.json">Frozen replay protocol</a> · <a href="menne-results.json">Field-level results</a> · <a href="menne-input-manifest.json">Source file hashes</a> · <a href="/research/l78_menne_verify.py">Replay verifier</a></p><h2>Field comparisons</h2>{''.join(sections)}</html>''')
