"""python figure_410.py OUT. Original samples and quantitative predictions from the saved replay, with no inpainting."""
import numpy as np,sys,json
from pathlib import Path
from PIL import Image,ImageDraw,ImageFont
def main(o):
 w=np.load(o/'branch_work.npz');v=w['v'];z=np.load(o/'tone_work.npz');F='/usr/share/fonts/truetype/dejavu/DejaVuSans';font=lambda n,b=False:ImageFont.truetype(F+('-Bold' if b else '')+'.ttf',n)
 def txt(d,x,y,s,n=16,b=False):d.text((x,y),s,fill='#193631',font=font(n,b))
 def patch(a,scale=4):
  return Image.fromarray((255-np.clip(a*scale,0,255)).astype('uint8')).convert('RGB')
 def make(title,sub):
  c=Image.new('RGB',(890,493),'#f5f3ea');dr=ImageDraw.Draw(c);txt(dr,24,13,title,24,1);txt(dr,24,54,sub,15);return c,dr
 c,p=make('Can one side of the tree predict the other?','Same scale and contrast in every panel. Teal marks the observed side used to fit each prediction.')
 for i,(name,a,mask) in enumerate([('Printed page 55',v,None),('Fitted on the left',z['Ltone'],w['L']),('Fitted on the right',z['Rtone'],w['R'])]):
  ar=np.array(patch(a)).astype(float)
  if mask is not None:ar[mask]=.72*ar[mask]+.28*np.array([45,146,138])
  im=Image.fromarray(ar.astype('uint8')).resize((264,268),Image.Resampling.NEAREST);x=23+i*286;c.paste(im,(x,125));txt(p,x,93,name,17,1)
 txt(p,23,410,'The crown transfers; the base does not.',18,1);txt(p,23,447,'Both models draw a wide flared foot. The surviving printed outline ends in a much narrower base.',15);c.save(o/'branch_panel_410.png',optimize=True)
 c,p=make('Two trees share a measurable printing grid','All 75 original book pages were scanned at native resolution. Each bar is the best 600 × 600 window.')
 raw=json.loads((o/'gridscan_408_results.json').read_text());rows={x['archive']:x for x in raw['pages']}
 for j,i in enumerate(raw['ranking'][:6]):
  q=rows[i];y=105+j*48;x=230;s=q['best_600_score'];lab={72:'LP2 p55 · outline',49:'LP2 p32 · blur'}.get(i,'Archive '+f'{i:02}');txt(p,26,y,lab,17,j<2);p.rectangle((x,y+2,x+int(855*s),y+24),fill='#30695f' if j<2 else '#aaa89a');txt(p,x+int(855*s)+10,y,f'{s:.3f}',16)
 txt(p,25,421,'The two highest-scoring windows fall on the trees, without using a tree template.',17,1);txt(p,25,456,'Score: strength at the common spacing after subtracting nearby frequencies, on both axes.',14);c.save(o/'grid_ranking_408.png',optimize=True)
if __name__=='__main__':main(Path(sys.argv[1]))
