"""Independent spot checks of the depletion, moment and coding examples."""
import json
from math import comb, exp, expm1, log, log1p, log2, prod, sqrt
from fractions import Fraction as F


def late_profile(n):
    # The elementary early prefix can have far more steps than a loop can visit.
    step = n ** -3
    count = round((-log(n) / 4) / log1p(-step))
    q0 = exp(count * log1p(-step))
    late = int(8 * sqrt(n))
    b = .5 / n
    weight = comb(n, 2) * q0 ** 2 * b ** 2 * expm1(2 * late * log1p(-b)) / expm1(2 * log1p(-b))
    return dict(N=n, q0=round(q0, 12), late_mass=round(weight, 12),
                canonical_late_affinity=round(exp(-weight / 2), 12))


def run():
    n = 10
    b, d = F(1, 1000), F(9, 100)
    B, C = 3000*b + 34*d, 3000*b*b + 34*d*d
    fine = comb(n, 2) * (b*b + (1-b)**6000 * d*d)
    coarse = comb(n, 2) * (C/B)**2
    t = F(1, 100)
    one, two = (t,t,4*t), (0*t,3*t,3*t)
    assert sum(one)==sum(two) and sum(i*i for i in one)==sum(i*i for i in two)
    assert prod(1-i for i in one)-prod(1-i for i in two)==-4*t**3
    a0 = 2.5 / (2*(1+sqrt(.5))**2)
    a1 = .5
    return dict(late=[late_profile(n) for n in (64, 1024, 262144)],
                single_step_tv=round(.8 * -expm1(-.8), 12),
                single_step_canonical_tv=round(-expm1(-.8**2/2), 12),
                equal_B_C_survival_gap=str(-4*t**3),
                large_hazard_masses=[round(float(x),12) for x in (fine,coarse)],
                packing_separation=round(exp(-2.5)*-expm1(-(a1-a0)/8),12),
                packing_bits_per_cell=round(1+.25*log2(.25)+.75*log2(.75),12))


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