"""Find 2016 tree patch across original 58 LP2 JPEGs. python tree_search_371.py EVIDENCE CARRIER OUTPUT."""
from pathlib import Path
from PIL import Image
from scipy.signal import fftconvolve
import numpy as np,json,gzip,sys,hashlib
def boxsum(a,h,w):
 z=np.pad(a.cumsum(0).cumsum(1),((1,0),(1,0)));return z[h:,w:]-z[:-h,w:]-z[h:,:-w]+z[:-h,:-w]
def scores(a,q,floor=.015):
 h,w=q.shape;m=q-q.mean();power=max(float((m*m).sum()),1e-12);s=boxsum(a,h,w);v=np.maximum(boxsum(a*a,h,w)-s*s/q.size,0)
 num=fftconvolve(a,m[::-1,::-1],mode='valid')
 return np.divide(num,np.sqrt(power*np.maximum(v,1e-12)),out=np.full_like(num,-1),where=v>q.size*floor**2)
def prep(q):return np.asarray(q,dtype=float)/255.
def top(s):
 y,x=np.unravel_index(s.argmax(),s.shape);return float(s[y,x]),int(x),int(y)
def main(d,c,o):
 img=Image.open(c).convert('L').crop((190,305,365,471))
 man={f['file']:f['sha256'] for f in json.loads((d/'jpeg_source_manifest.json').read_bytes())['files']}
 qs={}
 for width in (55,70,85,100,115,130,145):
  q=prep(img.resize((width,round(width*166/175)),Image.Resampling.BILINEAR))
  qs[width]=(q,q[:,::-1])
 pages=[]
 for i in range(58):
  f=d/f'{17+i:02}.jpg';assert hashlib.sha256(f.read_bytes()).hexdigest()==man[f.name];a=1-prep(Image.open(f).convert('L').resize((240,360),Image.Resampling.BOX))
  rec={'upright':None,'mirrored':None}
  for w,(q,m) in qs.items():
   for lab,qq in [('upright',q),('mirrored',m)]:
    r,x,y=top(scores(a,qq));v=rec[lab]
    if v is None or r>v['r']:rec[lab]={'r':round(r,7),'left_top_width_at_tenth_scale':[x,y,w]}
  pages.append({'page':i,**rec})
 # Known inserted result and direct sample check of normalized coefficient.
 rng=np.random.default_rng(371);a=rng.uniform(0,.16,(240,200));q=qs[85][0];q=(q-q.min())/np.ptp(q);a[51:51+len(q),43:128]=.1+.6*q
 s=scores(a,q);r,x,y=top(s);assert (x,y)==(43,51) and r>.99999
 direct=float(np.corrcoef(a[20:20+len(q),15:15+q.shape[1]].ravel(),q.ravel())[0,1]);assert abs(s[20,15]-direct)<1e-8
 out={'pages':pages,'top_upright':sorted(pages,key=lambda v:-v['upright']['r'])[:6],'top_mirrored':sorted(pages,key=lambda v:-v['mirrored']['r'])[:4],'control_location':[x,y],'control_r':round(r,6),'widths_tenth_page_px':list(qs),'contrast_floor_std':.015,'scale':'2,400 wide originals reduced to 240px; bottom and right boundaries included; scores do not use known p32 box.'}
 o.write_bytes(gzip.compress((json.dumps(out,sort_keys=True,separators=(',',':'))+'\n').encode(),mtime=0))
if __name__=='__main__':main(*map(Path,sys.argv[1:]))
