"""Exact bounds on a variable-marginal approximation and a perturbed boundary reader."""
from fractions import Fraction as F
from itertools import product
from math import prod
import json
from jeu24 import load,table
from deficience21 import tv
from cellules22 import experiment
from transport24 import decode


def best_mass(law,u,v):
    slopes=[u,1-u,-v,v-1];origins=[F(0),F(0),v,1-v]
    knots={F(0),F(1)}|{(target-c)/w for target,c,w in zip(law,origins,slopes) if w and 0<=(target-c)/w<=1}
    return min((tv(law,[c+w*z for c,w in zip(origins,slopes)]),z) for z in knots)


def flexible(depth):
    target=table(load('commun23')['controls'][1]['target'])
    def score(u,v):
        pairs=[best_mass(row,u,v) for row in target]
        return (max(s for s,m in pairs),u,v,[m for s,m in pairs])
    best=score(F(1),F(6,25));boxes=[(F(0),F(0))];history=[]
    for level in range(depth+1):
        width=F(1,2**level);active=[];lower=best[0]
        for u,v in boxes:
            z=score(u+width/2,v+width/2);best=min(best,z)
            lb=max(F(0),z[0]-width/2)
            if lb<=best[0]:active.append((u,v,lb))
        keep=[(u,v) for u,v,lb in active if lb<=best[0]]
        lower=min([best[0]]+[lb for u,v,lb in active])
        history.append(dict(level=level,boxes=len(boxes),keep=len(keep),lower=lower,upper=best[0]))
        boxes=[(u+i*width/2,v+j*width/2) for u,v in keep for i,j in product(range(2),repeat=2)]
    return dict(history=history,best=best,target=target)


def boundary():
    rows=[]
    for h in [F(0)]+[F(1,10*2**k) for k in range(1,9)]:
        rates=[F(1,10)-h,F(1,45),F(1,15)]
        a0=prod(1-z for z in rates)**10;b0=prod(1-10*z for z in rates)
        a,b=[a0,1-a0],[b0,1-b0];u0=F(9,10)**10
        s,t=experiment(a,b,[[u0,1-u0],[F(0),F(1)]],[[F(0),F(1)],[F(0),F(1)]])
        k=decode(a,b,*t);B=tv(t[1],t[2]);assert B==h*F(70,27)*u0 and B/2<=k['value']<=B
        rows.append(dict(h=h,value=k['value'],slope=k['value']/h if h else None,source=s,target=t))
    return rows
if __name__=='__main__':print(json.dumps(dict(flexible=flexible(24),boundary=boundary()),default=str))
