"""Check 3: prime counting stays inside the bound the Riemann Hypothesis predicts.

Schoenfeld (1976): RH is TRUE if and only if, for every x >= 2657,
    | pi(x) - li(x) |  <  sqrt(x) * ln(x) / (8 * pi)
where pi(x) counts the primes up to x and li(x) is the logarithmic integral (the smooth estimate).

Between two neighbouring primes p_k < p_{k+1}, pi(x) = k is constant while li(x) only increases,
so the biggest gap |k - li(x)| on that stretch is at one of its two ends. Checking both ends of every
stretch therefore checks EVERY real x up to the limit, not just samples. li is built by integrating
1/ln(t) exactly between consecutive primes (Simpson's rule, error far below 1e-6).
"""
import sys, json, math, time
import numpy as np
import mpmath as mp


def main():
    X = int(sys.argv[1]) if len(sys.argv) > 1 else 10 ** 8
    t0 = time.time()
    sieve = np.ones(X + 1, dtype=bool); sieve[:2] = False
    for i in range(2, int(X ** 0.5) + 1):
        if sieve[i]: sieve[i * i::i] = False
    p = np.nonzero(sieve)[0].astype(np.float64)              # p_1 = 2, p_2 = 3, ...
    # li(p_k) = li(2) + integral_2^{p_k} dt / ln t, Simpson on each gap with 4 panels
    a, b = p[:-1], p[1:]
    h = (b - a) / 4
    f = lambda t: 1.0 / np.log(t)
    seg = h / 3 * (f(a) + 4 * f(a + h) + 2 * f(a + 2 * h) + 4 * f(a + 3 * h) + f(b))
    li = np.concatenate([[float(mp.li(2))], float(mp.li(2)) + np.cumsum(seg)])
    k = np.arange(1, len(p) + 1, dtype=np.float64)           # pi(p_k) = k
    bound = lambda x: np.sqrt(x) * np.log(x) / (8 * np.pi)
    # left end of stretch [p_k, p_{k+1}): x = p_k, pi = k ; right end: x -> p_{k+1}, pi still k
    mask = p[:-1] >= 2657
    left = np.abs(k[:-1] - li[:-1]) / bound(p[:-1])
    right = np.abs(k[:-1] - li[1:]) / bound(p[:-1])            # bound grows with x, so using the left-end bound is the stricter test
    worst = np.maximum(left, right)[mask]
    i = int(np.argmax(worst)); xs = p[:-1][mask]
    # spot-check our li against mpmath at a few points
    checks = []
    for j in [1000, 100000, len(p) // 2, len(p) - 1]:
        checks.append([int(p[j]), float(li[j]), float(mp.li(p[j]))])
    # samples for a chart: pi(x) - li(x) and the RH bound, on a log-spaced grid
    grid = np.unique(np.logspace(np.log10(2657), np.log10(X), 400).astype(np.int64))
    idx = np.searchsorted(p, grid, side='right') - 1
    samples = [[int(x), float(k[j] - li[j] - (li[j + 1] - li[j]) * 0), float(bound(x))] for x, j in zip(grid, idx) if j + 1 < len(p)]
    out = {"X": X, "primes_up_to_X": int(len(p)), "pi_X": int(len(p)), "li_X": float(mp.li(X)),
           "stretches_checked": int(mask.sum()), "violations": int((worst >= 1).sum()),
           "worst_fraction_of_bound": float(worst[i]), "worst_at_x": int(xs[i]),
           "li_spot_checks": checks, "seconds": round(time.time() - t0, 1)}
    json.dump({**out, "samples": samples}, open("check3_result.json", "w"))
    print(json.dumps(out, indent=1))


if __name__ == "__main__":
    main()
