"""Sum sqrt(PQ) over count histories. Only zero, one or two deaths can contribute."""
import json
from math import exp, expm1, log1p, sqrt, fsum
from intervalles17 import blocks, canonical, leading


def affinity(h, word, selection):
    n = h*h
    b = 1/(n*sqrt(h))
    mass = [1.]
    for rates in blocks(h,word,selection):
        a = rates[0]*b
        c = rates[1]*b if len(rates)==2 else 0.
        log_u = log1p(-a)+log1p(-c)
        hit = -expm1(log_u)
        after = [0.] * min(n+1,len(mass)+len(rates))
        for dead, weight in enumerate(mass):
            s = n-dead
            p0 = (1-s*a)*(1-s*c)
            after[dead] += weight*sqrt(p0*exp(s*log_u))
            if s:
                p1 = s*a*(1-(s-1)*c)+(1-s*a)*s*c
                q1 = s*hit*exp((s-1)*log_u)
                after[dead+1] += weight*sqrt(p1*q1)
            if s>=2 and c:
                p2 = s*(s-1)*a*c
                q2 = s*(s-1)/2*hit**2*exp((s-2)*log_u)
                after[dead+2] += weight*sqrt(p2*q2)
        mass = after
    return fsum(mass)


def run():
    h = 5
    worst = {key:dict(error=-1) for key in ("history_to_leading","canonical_to_leading","history_to_canonical")}
    for word in range(1<<h):
        for query in range(1<<h):
            base = leading(h,query.bit_count(),(word&query).bit_count())
            prof = canonical(h,word,query)
            observed = affinity(h,word,query)
            for key,gap in zip(worst,(abs(observed-base),abs(prof-base),abs(observed-prof))):
                if gap>worst[key]["error"]:
                    worst[key]=dict(error=gap,word=word,mask=query)
    for rec in worst.values():
        rec["error"]=round(rec["error"],12)
    sizes = []
    for h in (9,16,36,64,144):
        for bit,selected in ((0,0),(1,0),(0,1),(1,1)):
            word=bit*((1<<h)-1)
            query=selected*((1<<h)-1)
            base=leading(h,h*selected,h*bit*selected)
            real=affinity(h,word,query)
            sizes.append(dict(h=h,bit=bit,selected=selected,history=round(real,12),
                              canonical=round(canonical(h,word,query),12),leading=round(base,12),
                              scaled_signed_error=round(sqrt(h)*(real-base),10)))
    return dict(h_exhaustive=5,comparisons=1024,worst=worst,fixed_designs=sizes)


if __name__=="__main__":
    print(json.dumps(run(),indent=2))
