"""Return multiple phase-correlation peaks rather than forcing a translation."""
import cv2
import numpy as np

def translation_hypotheses(reference,target,max_shift=128,max_hypotheses=64,min_relative=.25,window='none',radius=3):
 """Explore positive local peaks in bounded circular phase correlation.

 Returned scores are *relative peak heights*, not calibrated probabilities.
 Circular assumptions, cropping, texture repetition, low signal and focus
 changes can all produce misleading or missing peaks. Nothing is aligned or
 discarded by this function; callers must retain unregistered inputs.
 """
 if not isinstance(reference,np.ndarray) or not isinstance(target,np.ndarray) or reference.ndim!=2 or reference.shape!=target.shape or not np.issubdtype(reference.dtype,np.number) or not np.issubdtype(target.dtype,np.number):raise ValueError('Expected matching numeric grayscale arrays')
 h,w=reference.shape
 if not np.isfinite(reference).all() or not np.isfinite(target).all() or type(max_shift) is not int or max_shift<1 or max_shift>=min(h,w)//2 or type(max_hypotheses) is not int or max_hypotheses<1 or not 0<=min_relative<=1 or window not in ('none','hann') or type(radius) is not int or radius<1:raise ValueError('Invalid input or configuration')
 if np.ptp(reference)==0 or np.ptp(target)==0:return {'status':'unidentifiable_constant','peaks':[],'surface':np.zeros((2*max_shift+1,2*max_shift+1),dtype='float32'),'total_peaks':0}
 a=reference.astype('float32');b=target.astype('float32');a-=a.mean();b-=b.mean()
 if window=='hann':
  win=cv2.createHanningWindow((w,h),cv2.CV_32F);a*=win;b*=win
 fa=np.fft.fft2(a);fb=np.fft.fft2(b);cross=fb*np.conj(fa);magnitude=np.abs(cross);peak_mag=float(magnitude.max())
 if peak_mag<=0:return {'status':'unidentifiable_spectrum','peaks':[],'surface':np.zeros((2*max_shift+1,2*max_shift+1),dtype='float32'),'total_peaks':0}
 cross=np.divide(cross,magnitude,out=np.zeros_like(cross),where=magnitude>peak_mag*1e-8);surface=np.fft.fftshift(np.fft.ifft2(cross).real);cy,cx=h//2,w//2;region=surface[cy-max_shift:cy+max_shift+1,cx-max_shift:cx+max_shift+1].astype('float32');maxval=float(region.max())
 if maxval<=0:return {'status':'no_positive_peak','peaks':[],'surface':region,'total_peaks':0}
 # Maximum filtering identifies local maxima; equal adjacent plateaus are
 # greedily collapsed by Euclidean separation below.
 kernel=np.ones((radius*2+1,radius*2+1),'uint8');maximum=cv2.dilate(region,kernel);ys,xs=np.where((region>=maximum-1e-12)&(region>=maxval*min_relative));items=sorted(((float(region[y,x]),int(x-max_shift),int(y-max_shift)) for y,x in zip(ys,xs)),key=lambda q:(-q[0],q[1]*q[1]+q[2]*q[2],q[2],q[1]));kept=[]
 for score,dx,dy in items:
  if all((dx-p['dx'])**2+(dy-p['dy'])**2>radius**2 for p in kept):kept.append({'dx':dx,'dy':dy,'score':score,'relative_score':score/maxval})
 total=len(kept);return {'status':'peaks_found','peaks':kept[:max_hypotheses],'surface':region,'total_peaks':total}
