"""Optimal within-cell decoder after both first contacts. Rational Bernstein certificates."""
from fractions import Fraction as F
from faces25 import constraints,load,table

SEGMENTS=[[(F(1,5),F(3,5),'first'),(F(3,5),F(3,4),'last')],
          [(F(3,19),F(9,19),'first'),(F(9,19),F(1,2),'middle'),(F(1,2),F(5,8),'last')]]

def formula(profile,section,h):
    if section=='first':
        if profile==0:x=[24-40*h,12+40*h,15+20*h];den=96
        else:x=[312-152*h,36+152*h,45+76*h];den=288
        return x,den,[4*h+3,5-4*h,4],12,[3,4,10]
    if section=='middle':
        return [78-58*h,18+10*h,9+17*h],24*(3-h),[4*h+3,4-8*h,5],4*(3-h),[1,4,10]
    if profile==0:x=[0,4*h,3*h];den=4*(1+h)
    else:x=[20*(1+h),28*h,21*h];den=24*(1+h)
    return x,den,[5-4*h,8*h-4,3],4*(1+h),[1,3,10]

def inequalities(profile,h):
    laws=table(load('commun23')['controls'][profile]['target'])
    j=next(i for i in (0,1) if laws[2][i])
    laws[2][j]-=h;laws[2][2]+=h
    return [(a+[-1],c) for a,c in constraints(laws)]+[([1,0,0],1),([-1,0,0],0),([0,1,0],1),([0,-1,0],0)]

def test(profile,section,h):
    x,den,w,wd,active=formula(profile,section,h);rows=inequalities(profile,h)
    slacks=[rhs*den-sum(a*b for a,b in zip(row,x)) for row,rhs in rows]
    assert den>0 and wd>0 and all(slacks[i]==0 for i in active)
    assert [sum(z*rows[i][0][j] for z,i in zip(w,active)) for j in range(3)]==[0,0,-wd]
    return [*slacks,*w,den,wd]

def study():
    result=[]
    for profile,parts in enumerate(SEGMENTS):
        for l,r,name in parts:
            a,b,c=[test(profile,name,h) for h in (l,(l+r)/2,r)]
            coefficients=[[x,2*y-F(x+z)/2,z] for x,y,z in zip(a,b,c)]
            assert min(min(v) for v in coefficients)>=0
            h=(l+r)/2;x,den,*_=formula(profile,name,h)
            result.append(dict(profile=profile,section=name,interval=[l,r],midpoint=h,
                               sample=[F(z)/den for z in x],bernstein=coefficients))
    return result
if __name__=='__main__':
    import json
    print(json.dumps(study(),default=str))
