"""Original exact pair-enumerated RANSAC-style line exercise, no random estimator."""
from fractions import Fraction as F
from itertools import combinations
import json

def validate(points,threshold):
 if type(points) is not list or not 2<=len(points)<=8 or any(type(p) is not tuple or len(p)!=2 or any(type(x) not in [int,F] or abs(x)>100 for x in p) for p in points) or type(threshold) not in [int,F] or not 0<=threshold<=20:raise ValueError('2..8 bounded exact point pairs, threshold0..20')

def ols(points):
 n=len(points);sx=sum(F(x) for x,y in points);sy=sum(F(y) for x,y in points);mx=sx/n;my=sy/n;den=sum((F(x)-mx)**2 for x,y in points)
 if den==0:raise ValueError('nonvertical slope model needs distinct x')
 slope=sum((F(x)-mx)*(F(y)-my) for x,y in points)/den;return slope,my-slope*mx

def run(points,threshold):
 validate(points,threshold);threshold=F(threshold);trials=[]
 for i,j in combinations(range(len(points)),2):
  x0,y0=map(F,points[i]);x1,y1=map(F,points[j]);dx=x1-x0;dy=y1-y0
  if dx==0:trials.append({'pair':[i,j],'status':'vertical_pair_skipped'});continue
  slope=dy/dx;intercept=y0-slope*x0;res=[abs(F(y)-slope*x-intercept) for x,y in points];inside=[k for k,r in enumerate(res) if r<=threshold]
  cross=[k for k,(x,y) in enumerate(points) if abs(dx*(y-y0)-dy*(x-x0))<=threshold*abs(dx)];assert inside==cross
  sse=sum(res[k]**2 for k in inside);trials.append({'pair':[i,j],'status':'valid','slope':str(slope),'intercept':str(intercept),'absolute_vertical_residuals':[str(r) for r in res],'inlier_indices':inside,'inlier_count':len(inside),'inlier_squared_residual_sum':str(sse)})
 valid=[r for r in trials if r['status']=='valid']
 if not valid:raise ValueError('no nonvertical candidate pair')
 best=min(valid,key=lambda r:(-r['inlier_count'],F(r['inlier_squared_residual_sum']),r['pair']));selected=[points[i] for i in best['inlier_indices']];m,c=ols(selected)
 # Independent closed form from raw sums, not centered sums.
 n=len(selected);sx=sum(F(x) for x,y in selected);sy=sum(F(y) for x,y in selected);sxx=sum(F(x)*x for x,y in selected);sxy=sum(F(x)*y for x,y in selected);oracle_m=(n*sxy-sx*sy)/(n*sxx-sx*sx);oracle_c=(sy-oracle_m*sx)/n;assert (m,c)==(oracle_m,oracle_c)
 return {'threshold':str(threshold),'all_pair_candidates':trials,'selected_candidate':best,'refit_slope':str(m),'refit_intercept':str(c),'refit_consensus_original_indices':best['inlier_indices'],'refit_residuals_all_points':[str(F(y)-m*x-c) for x,y in points]}

def demo():
 pts=[(0,0),(1,1),(2,2),(3,3),(4,4),(2,20)];out=run(pts,F(1,4));assert sum(r['status']=='valid' for r in out['all_pair_candidates'])==14 and len(out['all_pair_candidates'])==15 and out['selected_candidate']['inlier_count']==5 and (out['refit_slope'],out['refit_intercept'])==('1','0')
 m,c=ols(pts);sse=sum((F(y)-m*x-c)**2 for x,y in pts);assert (m,c,sse)==(1,3,270)
 edge=run([(0,0),(1,1),(2,F(9,4))],F(1,4));pair01=next(r for r in edge['all_pair_candidates'] if r['pair']==[0,1]);assert pair01['inlier_indices']==[0,1,2]
 competing=run([(0,0),(1,1),(2,2),(0,10),(1,10),(2,10)],0);assert competing['selected_candidate']['pair']==[0,1]
 wide=run(pts,20);assert wide['selected_candidate']['inlier_count']==6 and wide['refit_intercept']=='3'
 rejected=[]
 for label,p,t in [('insufficient',[(0,0)],0),('all_vertical',[(1,0),(1,1),(1,2)],0),('negative_threshold',pts,-1),('nonfinite_threshold',pts,float('inf')),('nonfinite_point',[(0,0),(1,float('nan'))],0),('bool_point',[(0,0),(True,1)],0)]:
  try:run(p,t)
  except ValueError:rejected.append(label)
  else:raise AssertionError('expected rejection')
 return {'authored_points':pts,'pair_enumeration_consensus':out,'all_points_OLS':{'slope':str(m),'intercept':str(c),'SSE':str(sse)},'threshold_equal_is_inlier':edge,'competing_lines_deterministic_tie':competing,'wide_threshold_keeps_all_refit_contaminated':wide,'invalid_cases_rejected':rejected,'scope':'original deterministic bounded pair enumeration RANSAC-style, vertical absolute residual not perpendicular distance; no random-success probability or sklearn execution, real sensor data, objective universal optimum or proof an outlier is invalid'}
if __name__=='__main__':print(json.dumps(demo(),ensure_ascii=True,indent=2))
