"""Image-only translation estimates with explicit, conservative abstention."""
import cv2
import numpy as np

def phase_displacement(reference,target):
 """Estimate reference→target XY displacement and raw phase response.

 Inputs are equal-size, finite numeric grayscale arrays. A raw phase response
 is not a calibrated probability and estimates do not prove real stage drift.
 """
 if not isinstance(reference,np.ndarray) or not isinstance(target,np.ndarray) or reference.ndim!=2 or reference.shape!=target.shape or min(reference.shape)<8:raise ValueError('Expected equal-sized 2D images')
 if not np.issubdtype(reference.dtype,np.number) or not np.issubdtype(target.dtype,np.number) or not np.isfinite(reference).all() or not np.isfinite(target).all():raise ValueError('Expected finite numeric inputs')
 h,w=reference.shape;window=cv2.createHanningWindow((w,h),cv2.CV_32F);shift,response=cv2.phaseCorrelate(reference.astype('float32'),target.astype('float32'),window)
 if not all(np.isfinite([*shift,response])):raise ValueError('Nonfinite phase correlation')
 return {'dx':float(shift[0]),'dy':float(shift[1]),'response':float(response)}

def accepted_shift(estimate,min_response=.1,max_shift=32.):
 """Return correction displacement or None; thresholds are heuristics."""
 if not isinstance(estimate,dict) or any(k not in estimate for k in ('dx','dy','response')):raise ValueError('Invalid estimate')
 values=[estimate['dx'],estimate['dy'],estimate['response']]
 if not all(isinstance(x,(int,float)) and np.isfinite(x) for x in values) or not np.isfinite(min_response) or not np.isfinite(max_shift) or max_shift<=0:raise ValueError('Invalid values')
 if estimate['response']<min_response or np.hypot(estimate['dx'],estimate['dy'])>max_shift:return None
 return (-estimate['dx'],-estimate['dy'])

def shift_mask(mask,dx,dy):
 """Translate binary candidate geometry without interpolating labels."""
 if not isinstance(mask,np.ndarray) or mask.ndim!=2 or mask.dtype!=np.bool_ or not np.isfinite([dx,dy]).all():raise ValueError('Invalid mask or shift')
 h,w=mask.shape;return cv2.warpAffine(mask.astype('uint8'),np.float32([[1,0,dx],[0,1,dy]]),(w,h),flags=cv2.INTER_NEAREST,borderMode=cv2.BORDER_CONSTANT)>0
