"""python transfercut_426.py BOOK_FILES CACHE OUT. Exploratory: learn a horizontal input truncation on one tree, then predict a different target without moving its crown."""
from variants_419 import *
from scipy.optimize import minimize
def main(d,s,o):
 a=source(s/'originalTreeImage.jpg',True);v55,x55,y55=grid(d);ms=masks(x55,y55)
 cfg={'p32':('49.jpg',(640,2020,1770,3200)),'poster':('notice_2016_363.jpg',(190,305,365,471))}
 prev=json.loads((d/'donor_394_results.json').read_text())['results'];p55=json.loads((d/'tone_406_results.json').read_text())['correct'];y,x=np.indices((165,165));out={'models':{},'selected':{},'cross':{}}
 grids={};maps={}
 for k,(f,bx) in cfg.items():
  raw=rd(d/f)[bx[1]:bx[3],bx[0]:bx[2]];V=resize(raw if k=='poster' else 255-raw,165,165);p0=np.array(prev[k]['original_mirrored']['p']);cx,cy,w,h=p0
  # Prior full fit defines broad training box only. Optimize anew on the crown, excluding outer twigs and entire lower trunk.
  M=(abs(x-cx)<.39*w)&(y>=cy-.35*h)&(y<cy+.12*h);best=None
  for sig in (2,3,4,5,6,7,9):
   aa=nd.gaussian_filter(a,sig);X=x[M];Y=y[M];vv=V[M];fn=lambda p:-r(project(aa,p,X,Y),vv)
   rr=minimize(fn,p0,method='Nelder-Mead',options={'initial_simplex':np.vstack((p0,p0+np.diag([1,1,2,2]))),'xatol':.015,'fatol':.000001,'maxiter':200})
   if best is None or rr.fun<best[0]:best=(rr.fun,rr.x,sig)
  loss,p,sg=best;z=project(nd.gaussian_filter(a,sg),p,x,y);gain,off=np.linalg.lstsq(np.column_stack([z[M],np.ones(M.sum())]),V[M],rcond=None)[0];cx,cy,w,h=p;root=(abs(x-cx)<.25*w)&(y>cy+.36*h)&(y<cy+.69*h);grids[k]=(V,root)
  maps[k]=lambda dsrc,p=p,g=gain,b=off,sg=sg:project(nd.gaussian_filter(dsrc,sg),p,x,y)*g+b
  out['models'][k]={'p':p.tolist(),'sigma':sg,'gain':gain,'offset':off,'crown_r':-loss,'root_n':int(root.sum())}
 for tr in 'LR':
  k='p55'+tr;grids[k]=(v55,ms['root']);maps[k]=lambda a,tr=tr:render(a,p55[tr]['tone'],x55,y55)
 refy=np.indices(a.shape)[0]-26;cuts=range(175,201);scores={}
 for b in cuts:
  bb=a.copy();bb[refy>=b]=0
  scores[b]={}
  for k,fn in maps.items():
   V,M=grids[k];pr=fn(bb);scores[b][k]={'r':r(V[M],pr[M]),'rmse':float(np.sqrt(np.mean((V[M]-pr[M])**2)))}
   if k.startswith('p55'):scores[b][k].update(footprint(pr,V,M,20))
 for k in maps:
  hit=min(cuts,key=lambda b:scores[b][k]['rmse']);out['selected'][k]=hit
  out['cross'][k]={'at_own':hit,'on_other_targets':scores[hit],'uncut':scores[200]}
 out['all_cuts']=scores;(o/'transfercut_426_results.json').write_text(json.dumps(out,indent=2)+'\n')
 print(out['models']);print('cuts',out['selected'])
 for k in maps:
  print(k,[(dst,round(v['rmse'],3),round(out['cross'][k]['uncut'][dst]['rmse'],3)) for dst,v in out['cross'][k]['on_other_targets'].items()])
if __name__=='__main__':main(*map(Path,sys.argv[1:]))
