"""Original exact bilinear coordinate contract, not an ONNX runtime implementation."""
from fractions import Fraction as F
import math,json

def coord(i,n,m,mode):
 if mode=='half_pixel':v=F(2*i+1,2)*F(n,m)-F(1,2)
 elif mode=='align_corners':v=F(i*(n-1),m-1)
 else:raise ValueError('mode')
 return max(F(0),min(F(n-1),v))
def validate(a,shape):
 if not isinstance(a,list) or not 2<=len(a)<=6 or any(not isinstance(r,list) or not 2<=len(r)<=6 for r in a) or len({len(r) for r in a})!=1 or any(type(v) not in [int,float] or not math.isfinite(v) or abs(v)>100 for r in a for v in r):raise ValueError('finite rectangular2..6')
 if not isinstance(shape,tuple) or len(shape)!=2 or any(type(v)!=int or not 2<=v<=8 for v in shape):raise ValueError('output axes2..8; singleton rejected')
def resize(a,shape,mode):
 validate(a,shape);h,w=len(a),len(a[0]);out=[];trace=[]
 for i in range(shape[0]):
  row=[]
  for j in range(shape[1]):
   y=coord(i,h,shape[0],mode);x=coord(j,w,shape[1],mode);y0=int(y);x0=int(x);y1=min(y0+1,h-1);x1=min(x0+1,w-1);dy=y-y0;dx=x-x0
   pts=[(y0,x0),(y0,x1),(y1,x0),(y1,x1)];weights=[(1-dy)*(1-dx),(1-dy)*dx,dy*(1-dx),dy*dx];v=sum(t*F(a[r][c]) for (r,c),t in zip(pts,weights));assert sum(weights)==1;row.append(v);trace.append({'output':[i,j],'input_coordinate_clamped':[str(y),str(x)],'corners':pts,'weights':[str(v) for v in weights],'value':str(v)})
  out.append(row)
 return out,trace
def separate(a,shape,mode):
 def line(v,t):
  k=int(t);q=min(k+1,len(v)-1);return F(v[k])+(F(v[q])-F(v[k]))*(t-k)
 horizontal=[[line(row,coord(j,len(row),shape[1],mode)) for j in range(shape[1])] for row in a]
 return [[line([row[j] for row in horizontal],coord(i,len(a),shape[0],mode)) for j in range(shape[1])] for i in range(shape[0])]
def demo():
 a=[[0,9,1],[6,2,8],[3,7,4]];result={};plane=[[0,10],[20,30]];checks=0
 for mode in ['half_pixel','align_corners']:
  out,trace=resize(a,(4,5),mode);assert out==separate(a,(4,5),mode);checks+=20;result[mode]={'values':[[str(v) for v in r] for r in out],'all_coordinate_weight_rows':trace}
  p,_=resize(plane,(4,4),mode)
  for i in range(4):
   for j in range(4):assert p[i][j]==10*coord(j,2,4,mode)+20*coord(i,2,4,mode)
  result[mode]['plane_at_1_1']=str(p[1][1]);assert resize(a,(3,3),mode)[0]==a and all(v==7 for r in resize([[7,7],[7,7]],(5,6),mode)[0] for v in r)
 assert result['half_pixel']['plane_at_1_1']=='15/2' and result['align_corners']['plane_at_1_1']=='10'
 rejects=[]
 for label,fn in [('singleton_out',lambda:resize(a,(1,4),'align_corners')),('bool_shape',lambda:resize(a,(True,4),'half_pixel')),('ragged',lambda:resize([[1,2],[3]],(4,4),'half_pixel')),('nonfinite',lambda:resize([[1,2],[3,float('inf')]],(4,4),'half_pixel')),('bad_mode',lambda:resize(a,(4,4),'other')),('budget',lambda:resize(a,(9,4),'half_pixel')),('singleton_input',lambda:resize([[1,2]],(4,4),'half_pixel'))]:
  try:fn()
  except ValueError:rejects.append(label)
  else:raise AssertionError(label)
 return {'original_nonplanar':a,'modes':result,'nonplanar_four_weight_vs_separable_cells':checks,'plane_closed_form_cells':32,'invalid_cases_rejected':rejects,'scope':'Own clamped-edge gray2D subset, axes>=2, exact Fraction. Not whole ONNX/Pillow/OpenCV, no antialias or recovered detail or library benchmark.'}
if __name__=='__main__':print(json.dumps(demo(),indent=2))
