"""Independent numerical controls for the released collision-free limit profiles."""
import json
from itertools import product
from math import erf, exp, factorial, fsum, log1p, prod, sqrt


def poisson(rate, n):
    return exp(-rate) * rate**n / factorial(n)


def tv_counts(left, right):
    # Direct TV on the product counts; the omitted mass is below 1e-16 here.
    ns = range(40)
    cells = [[(poisson(a,n),poisson(b,n)) for n in ns] for a,b in zip(left,right)]
    return fsum(abs(prod(s for s,_ in terms)-prod(j for _,j in terms))
                for terms in product(*cells))/2


def mixed_decision(information, r, weight):
    # Evaluate the same likelihood decision under each of the two experiments.
    q_rate = weight/r**2
    p_rate = (1-r)*q_rate
    correct_region = [0.,0.]
    for n in range(40):
        if r == 1 and n > 0:
            correct_region[0] += poisson(q_rate,n)
            continue
        drift = q_rate*r + (n*log1p(-r) if n else 0)
        for index,(rate,center) in enumerate(((q_rate,-information/2),(p_rate,information/2))):
            normal_cdf = (1+erf((-drift-center)/sqrt(2*information)))/2
            correct_region[index] += poisson(rate,n)*normal_cdf
    return correct_region[0]-correct_region[1]


def run():
    profiles = [([1.],[2.]),([0.,1.],[.5,1.5]),([0.,1.],[1.,1.])]
    coarse = [([2.5],[5.]),([2.],[4.5])]
    # First coarse profile has equal marks 1/2 in the limit; second has 5/9.
    return dict(marked=[round(tv_counts(p,q),9) for p,q in profiles],
                regrouped=[round(tv_counts(p,q),9) for p,q in coarse],
                mixed=[round(mixed_decision(.25,1/ell,.25),9) for ell in (1,2)])


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