"""python variants_419.py BOOK_FILES SOURCE_CACHE OUTPUT; SOURCE_CACHE includes hashed inputs from fetch_415.py."""
from pathlib import Path
from PIL import Image
import numpy as np,json,sys
from scipy import ndimage as nd
from scipy.optimize import minimize
from branch_399 import r,project,source,measure
from grid_397 import get
def rd(f):
 im=Image.open(f).convert('RGBA');im=Image.alpha_composite(Image.new('RGBA',im.size,'white'),im).convert('L');return np.array(im)
def resize(a,w,h):
 return np.asarray(Image.fromarray(a.astype('float32')).resize((w,h),Image.Resampling.BOX),float)
def otsu(a):
 z=np.bincount(a.ravel(),minlength=256).astype(float);z/=z.sum();m=np.cumsum(z);u=np.cumsum(z*np.arange(256));v=(u[-1]*m-u)**2/np.maximum(1.e-14,m*(1-m));return int(v.argmax())
def sample(a,p,x,y):
 cx,cy,w,h=p;return nd.map_coordinates(a,[cy+(y-99.5)*h/200,cx+(x-99.5)*w/200],order=1,mode='constant',prefilter=False)
def align(a,ref,side,init,flip=False):
 y,x=np.indices((200,200));valid=(y>=40)&(y<113)&(x>=25)&(x<175)
 M=valid & ((x<99) if side=='left' else ((x>=99) if side=='right' else (x>=0)));Mx=M&(x%2==0)&(y%2==0)
 def coords(p,s):return sample(a,p,(199-x[s] if flip else x[s]),y[s])
 def loss(p,s):return -r(coords(p,s),ref[s])
 p=np.array(init);best=[]
 # Integer-pixel screens for cropping differences: boxes use broad source-only starting estimates.
 for s in (.90,1.,1.10):
  for dx in (-12,0,12):
   for dy in (-12,0,12):
    q=p*np.array([1,1,s,s])+[dx,dy,0,0];best.append((loss(q,Mx),q))
 best=sorted(best,key=lambda x:x[0])[:4];out=[]
 for _,q in best:
  z=minimize(lambda t:loss(t,Mx),q,method='Nelder-Mead',options={'initial_simplex':np.vstack((q,q+np.diag([3.,3.,8.,9.]))),'maxiter':250,'xatol':.012,'fatol':.000001});out.append((z.fun,z.x))
 _,q=min(out,key=lambda t:t[0]);z=minimize(lambda t:loss(t,M),q,method='Nelder-Mead',options={'initial_simplex':np.vstack((q,q+np.diag([.6,.6,1.8,1.8]))),'maxiter':150,'xatol':.008,'fatol':.0000005});q=z.x;Y,X=np.indices((252,252));tar=sample(a,q,199-(X-26) if flip else X-26,Y-26)
 pred=coords(q,valid);sam=np.zeros_like(ref);sam[valid]=pred;opp=valid&~M
 return tar,{'p':q.tolist(),'train_r':-float(z.fun),'other_r':r(sam[opp],ref[opp]) if opp.any() else None}
def grid(d):
 a=get(d);g=json.loads((d/'grid_397_results.json').read_text())['whole'];st=50/9;ix=np.arange(g['x']['center_phase'],a.shape[1]-.5,st);iy=np.arange(g['y']['center_phase'],a.shape[0]-.5,st);v=a[np.ix_(np.rint(iy).astype(int),np.rint(ix).astype(int))];y,x=np.meshgrid((iy+.5)*220/a.shape[0],(ix+.5)*220/a.shape[1],indexing='ij');return v,x,y
def masks(x,y):
 return {'root':(x>=90)&(x<130)&(y>=173),'crown':(y>=10)&(y<173),'top_tips':(y<29),'left_tips':(x<40)&(y>=29)&(y<150),'right_tips':(x>=180)&(y>=29)&(y<150),'L':(x<90)&(y>=10)&(y<173),'R':(x>=130)&(y>=10)&(y<173)}
def footprint(z,v,m,t):
 a=(z>=t)&m;b=(v>=t)&m;n=int(a.sum());N=int(b.sum());both=int((a&b).sum());pos=np.argwhere(a);width=max((np.ptp(pos[pos[:,0]==i,1])+1 for i in set(pos[:,0])),default=0);return {'n':n,'actual':N,'intersection':both,'union':n+N-both,'iou':both/max(1,n+N-both),'f1':2*both/max(1,n+N),'span':int(width),'lastrow':int(pos[:,0].max()) if n else None}
def render(a,p,x,y):
 ink=project(nd.gaussian_filter(a,p['sig']),p['p'],x,y);co=p['coef'];return co[0]+co[1]*ink+sum(c*np.maximum(ink-t,0) for c,t in zip(co[2:],np.arange(1,8)/8))
def main(d,s,o):
 v,x,y=grid(d);ms=masks(x,y);models=json.loads((d/'tone_406_results.json').read_text())['correct'];reference=source(s/'originalTreeImage.jpg',False);ref=reference[26:-26,26:-26];cfg={'hd_latest':('hd0.png','ink',(139,219,280,287)),'hd_first':('hd1.png','ink',(140,220,282,285)),'photo_otsu':('oak0.jpeg','otsu',(139,216,281,286)),'photo_gray':('oak0.jpeg','gray',(139,216,281,286)),'thesis_gray':('thesis-000.png','gray',(139,133,280,277)),'thesis_otsu':('thesis-002.png','ink',(139,133,280,277)),'small':('originalTreeImageMirrored183x191NearestNeighbor.png','small',(140,145,280,285))}
 templates={'github':reference[:,::-1]};aligns={};work={};out={}
 for n,(f,kind,init) in cfg.items():
  orig=rd(s/f)
  if kind=='small':orig=orig[:,::-1]
  th=otsu(orig);g=(orig<=th).astype(float) if kind=='otsu' else 1-orig/255.;g=resize(g,280,round(g.shape[0]*280/g.shape[1]));aa,fit=align(g,ref,'full',init);templates[n]=aa[:,::-1];als={'full':fit}
  for tr in ['left','right']:_,fit2=align(g,ref,tr,fit['p']);als[tr]=fit2
  _,als['wrong_reflection']=align(g,ref,'full',init,True);als['otsu_input_threshold']=th;aligns[n]=als
 for n,a in templates.items():
  out[n]={}
  for tr in ['L','R']:
   z=render(a,models[tr]['tone'],x,y);row=out[n][tr]={}
   for k,m in ms.items():
    row[k]={'r':r(z[m],v[m]),'rmse':float(np.sqrt(np.mean((z[m]-v[m])**2))),'thresholds':{str(t):footprint(z,v,m,t) for t in (12,20,30)}}
    if k in ['L','R']:row[k]['loop']=measure(z,v,m,20)
   work[n+'_'+tr]=z
  print(n,round(aligns.get(n,{}).get('full',{}).get('train_r',1),3),[(tr,out[n][tr]['root']['thresholds']['20']['span'],round(out[n][tr]['root']['thresholds']['20']['iou'],3),round(out[n][tr]['crown']['r'],3)) for tr in 'LR'],flush=True)
 result={'align':aligns,'evaluations':out,'observed_root':{str(t):footprint(v,v,ms['root'],t) for t in (12,20,30)}};(o/'variants_419_results.json').write_text(json.dumps(result,separators=(',',':'))+'\n');np.savez_compressed(o/'predictions.npz',v=v,x=x,y=y,**work)
if __name__=='__main__':main(*map(Path,sys.argv[1:]))
