"""High-precision verification of the exact hypothetical binomial-tail model.

Dependencies: pip install mpmath
The assumptions are NOT measured probabilities or evidence of divine inspiration.
"""
import mpmath as mp

mp.mp.dps = 90
V, L, G = 31102, 63779, 50
M = V * (V - 1) // 2
q = mp.mpf(1) / 100000
s = mp.mpf(9999) / 10000

# Evaluate P(X >= L) for X ~ Binomial(M,q) using its first term and
# successive ratios. This avoids calculating ~484 million summands.
log_pmf = (mp.loggamma(M + 1) - mp.loggamma(L + 1)
           - mp.loggamma(M - L + 1)
           + L * mp.log(q) + (M - L) * mp.log(1 - q))

r0 = mp.mpf(M - L) / (L + 1) * q / (1 - q)
term = mp.mpf(1)
sum_ratios = term
for k in range(L, L + 100):
    term *= mp.mpf(M - k) / (k + 1) * q / (1 - q)
    sum_ratios += term

# Because the successive ratios decrease with k, the omitted part is bounded.
remainder_upper_bound = term * r0 / (1 - r0)
log_tail_lo = log_pmf + mp.log(sum_ratios)
log_tail_hi = log_pmf + mp.log(sum_ratios + remainder_upper_bound)

log_preservation = L * G * mp.log(s)
log_combined_lo = log_tail_lo + log_preservation
log_combined_hi = log_tail_hi + log_preservation

def normalized(logp):
    e = int(mp.floor(logp / mp.log(10)))
    return mp.nstr(mp.exp(logp - e * mp.log(10)), 16), e

print('M:', M)
print('copying events:', L * G)
print('P(X >= L):', normalized(log_tail_lo))
print('preservation:', normalized(log_preservation))
print('combined:', normalized(log_combined_lo))
print('log10 combined lower bound:', mp.nstr(log_combined_lo / mp.log(10), 42))
print('log10 combined upper bound:', mp.nstr(log_combined_hi / mp.log(10), 42))
print('omitted tail multiplier <', mp.nstr(remainder_upper_bound, 7))
assert M == 483651651
assert L * G == 3188950
assert mp.mpf('6.87e-45987') < mp.exp(log_combined_lo)
assert mp.exp(log_combined_hi) < mp.mpf('6.88e-45987')
print('All numerical sanity checks passed.')
