"""cert.py generalized to z in {2, 3, 5} (P^-(n) > z): enclosures of a_{y,z}, and merge families.

Certified lower bound for G (Section 3 of the paper) with interval arithmetic.

Everything that is not an exact integer is carried as an enclosure [lo, hi]:
* per-segment quantities (segments [b_k, b_{k+1}] between consecutive primes, b_0 = 1) are computed with
  arb (python-flint, 96-bit ball arithmetic) and stored as float enclosures (mid +- rad, widened);
* the per-y sums use float interval arithmetic in which every IEEE operation (+, -, *, /, all correctly
  rounded) is followed by an outward widening of 4u|value| + 1e-300, u = 2^-53;
* long sums of lower ends / upper ends use math.fsum (correctly rounded), widened by 2u|sum| + n*1e-300.

For y = num/40 and N = floor(U0/y), V = yN, the odd n <= N with U_n = max(y n, F(n)) < V give
  J/y        = sum_n int_{U_n}^{V} g(u) du/u^2,          g(u) = (Sigma(u) + gamma - log u) Pi(u),
  (1/2-eps)/y = sum_n int_{U_n}^{V} Pi(u) du/u^2.
Split each integral into the part of the segment containing U_n and whole segments above it:
  sum_n int_{U_n}^V f = sum_k c_k * seg_k(f) + c_top * top(f) + sum_n part_n(f),
with c_k = #{n : U_n in a segment below k}. On a segment, Sigma and Pi are constant and log u lies
between the logs of the segment ends, which encloses part_n; for U_n < SMALL the part is computed in arb.
Then a_{y,2} = (C/2)(1 - gamma + log(y/2)) + C (J + Q), |Q| <= eps * E(yN), E from Rosser-Schoenfeld.

Usage: python3 cert.py <U0> <amax> <J>      (run with: uv run --no-project --with python-flint --with numpy)
"""
import math
import sys
import time

import flint
import numpy as np

import ay2

flint.ctx.prec = 96
arb = flint.arb
U_ = 2.0 ** -53
TINY = 1e-300
SMALL = 10 ** 4


def widen(lo, hi, k=4):
    return lo - (np.abs(lo) * (k * U_) + TINY), hi + (np.abs(hi) * (k * U_) + TINY)


def iv_mul(alo, ahi, blo, bhi):
    c = [alo * blo, alo * bhi, ahi * blo, ahi * bhi]
    return widen(np.minimum.reduce(c), np.maximum.reduce(c))


def iv_add(alo, ahi, blo, bhi):
    return widen(alo + blo, ahi + bhi)


def iv_sum(lo, hi):
    slo, shi = math.fsum(lo.tolist()), math.fsum(hi.tolist())
    n = len(lo)
    return slo - (abs(slo) * 2 * U_ + n * TINY), shi + (abs(shi) * 2 * U_ + n * TINY)


def encl(x):
    """float enclosure of an arb ball."""
    m, r = float(x.mid()), float(x.rad())
    w = r * (1 + 4 * U_) + abs(m) * 2 * U_ + TINY
    return m - w, m + w


def precompute(primes):
    """arb enclosures for every segment k = [b_k, b_{k+1}] (b_0 = 1, b_k = p_k):
    S_k, Pi_k (constant on the segment), log b_k, segK_k = int g/u^2, segP_k = int Pi/u^2."""
    K = len(primes)
    out = {name: (np.empty(K), np.empty(K)) for name in ("S", "Pi", "logb", "segK", "segP")}
    g = arb.const_euler()
    S, Pi, lb, b = arb(0), arb(1), arb(0), 1
    for k, p in enumerate(primes.tolist()):
        lp = arb(p).log()
        ib, ip = arb(1) / b, arb(1) / p
        inv = ib - ip
        il = (lb + 1) * ib - (lp + 1) * ip
        vals = {"S": S, "Pi": Pi, "logb": lb, "segK": Pi * ((S + g) * inv - il), "segP": Pi * inv}
        for name, v in vals.items():
            lo, hi = encl(v)
            out[name][0][k], out[name][1][k] = lo, hi
        S += lp / (p - 1)
        Pi *= 1 - ip
        lb, b = lp, p
    return out


def h_enclosure(num, U0, F, b40, b, pre, primes, z=2):
    """Enclosure of h(y) = a_{y,2}/y for y = num/40, N = floor(U0/y)."""
    y = arb(num) / 40
    N = (U0 * 40) // num
    V40 = num * N                          # 40 V, exact
    n = np.arange(1, N + 1, 2, dtype=np.int64)
    for q in (3, 5):
        if z >= q:
            n = n[n % q != 0]          # P^-(n) > z  (n = 1 kept)
    U40 = np.maximum(num * n, 40 * F[n])   # 40 U_n, exact integers
    keep = U40 < V40
    n, U40 = n[keep], U40[keep]
    seg = np.searchsorted(b40, U40, side="right") - 1    # U_n in [b_seg, b_seg+1)
    iV = int(np.searchsorted(b40, np.int64(V40), side="right") - 1)
    M = len(n)
    # c_k for k <= iV: number of n with seg < k
    cnt = np.bincount(seg, minlength=iV + 1)[: iV + 1]
    c = np.concatenate(([0], np.cumsum(cnt)[:-1])).astype(np.float64)   # exact (< 2^53)
    out = {}
    g = arb.const_euler()
    V = arb(V40) / 40
    logV = V.log()
    for f in ("K", "P"):
        slo, shi = pre["seg" + f]
        # whole segments 0..iV-1
        lo, hi = iv_mul(c[:iV], c[:iV], slo[:iV], shi[:iV])
        tot = iv_sum(lo, hi)
        # top segment [b_iV, V]
        k = iV
        Sl, Pl = pre["S"], pre["Pi"]
        S_top = arb(Sl[0][k]) .union(arb(Sl[1][k]))
        P_top = arb(Pl[0][k]).union(arb(Pl[1][k]))
        bk = arb(int(b[k]))
        lbk = bk.log()
        if f == "K":
            top = P_top * ((S_top + g) * (1 / bk - 1 / V) - ((lbk + 1) / bk - (logV + 1) / V))
        else:
            top = P_top * (1 / bk - 1 / V)
        tlo, thi = encl(top * int(c[k]) if k < len(c) else top * 0)
        tot = widen(tot[0] + tlo, tot[1] + thi)
        # partial segments, one per n
        e40 = np.where(seg < iV, b40[np.minimum(seg + 1, len(b40) - 1)], V40).astype(np.float64)
        Uf = U40.astype(np.float64)                    # exact (< 2^53)
        # w = 1/U - 1/e = 40 (e40 - U40) / (U40 e40)
        dlo, dhi = widen(e40 - Uf, e40 - Uf)          # exact difference of integers < 2^53, widened anyway
        plo, phi = iv_mul(Uf, Uf, e40, e40)
        wlo, whi = widen(40 * dlo / phi, 40 * dhi / plo)
        Pilo, Pihi = pre["Pi"][0][seg], pre["Pi"][1][seg]
        if f == "P":
            qlo, qhi = iv_mul(Pilo, Pihi, wlo, whi)
        else:
            # S + gamma - log u in [S + gamma - log(end), S + gamma - log b_seg]
            glo, ghi = float(encl(g)[0]), float(encl(g)[1])
            ltop = np.where(seg < iV, pre["logb"][1][np.minimum(seg + 1, len(b) - 1)], encl(logV)[1])
            lbot = pre["logb"][0][seg]
            dglo, dghi = widen(glo - ltop, ghi - lbot)
            alo, ahi = iv_add(pre["S"][0][seg], pre["S"][1][seg], dglo, dghi)
            mlo, mhi = iv_mul(Pilo, Pihi, wlo, whi)
            qlo, qhi = iv_mul(mlo, mhi, alo, ahi)
        small = Uf < 40 * SMALL
        # exact arb for small U_n
        for idx in np.nonzero(small)[0].tolist():
            Ua = arb(int(U40[idx])) / 40
            s = int(seg[idx])
            ea = V if s == iV else arb(int(b[s + 1]))
            Sa = arb(pre["S"][0][s]).union(arb(pre["S"][1][s]))
            Pa = arb(pre["Pi"][0][s]).union(arb(pre["Pi"][1][s]))
            if f == "K":
                val = Pa * ((Sa + g) * (1 / Ua - 1 / ea) - ((Ua.log() + 1) / Ua - (ea.log() + 1) / ea))
            else:
                val = Pa * (1 / Ua - 1 / ea)
            qlo[idx], qhi[idx] = encl(val)
        part = iv_sum(qlo, qhi)
        out[f] = widen(tot[0] + part[0], tot[1] + part[1])
    # J = y * K-sum, eps = 1/2 - y * P-sum   (to arb)
    Ksum = arb(out["K"][0]).union(arb(out["K"][1]))
    Psum = arb(out["P"][0]).union(arb(out["P"][1]))
    J = y * Ksum
    Piz = arb(1)
    Sigz = arb(0)
    for q in (2, 3, 5):
        if q <= z:
            Piz *= 1 - arb(1) / q
            Sigz += arb(q).log() / (q - 1)
    eps = Piz - y * Psum
    C = 1 / (1 - (-g).exp())
    yN = y * N
    L = yN.log()
    Ebound = 1 / (2 * L) + 2 * (L + 1) / (yN - 1)     # Rosser-Schoenfeld, valid for yN >= 319
    assert float(yN.lower()) >= 319
    assert y >= z
    a = C * Piz * (1 - g + y.log() - Sigz) + C * J
    a = a + (C * eps.upper() * Ebound).upper() * arb(0, 1)   # |Q| <= eps E(yN)
    return a / y, a, J, eps, M


def main():
    """usage: cert_z.py U0 z y0num y1num J coef
    Certified lower bound of coef * sum_{j<J} y_j (h(y_j) - h(y_{j+1})), y_j = (y0num + j (y1num - y0num)/J)/40,
    h(y) = a_{y,z}/y. (For a merge family {k d} -> d with gain c/d per d in (x/y_{j+1}, x/y_j], use coef = c.)"""
    U0, z, y0, y1, Jg = int(float(sys.argv[1])), int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]), int(sys.argv[5])
    coef = arb(sys.argv[6])
    t0 = time.time()
    primes = ay2.primes_upto(U0 + 2000)
    b = np.concatenate(([1], primes)).astype(np.int64)
    b40 = 40 * b
    pre = precompute(primes)
    print(f"precompute {len(primes)} primes: {time.time() - t0:.0f}s", flush=True)
    F = ay2.F_table(int(U0 * 40 / y0) + 1, primes)
    assert (y1 - y0) % Jg == 0
    nums = [y0 + j * (y1 - y0) // Jg for j in range(Jg + 1)]
    H = {}
    for num in nums:
        hy, a, J, eps, M = h_enclosure(num, U0, F, b40, b, pre, primes, z)
        H[num] = hy
        print(f"y={num / 40:g}: h width {float(hy.rad()):.2e}  M={M}", flush=True)
    ys = [arb(n) / 40 for n in nums]
    lower = ys[0] * H[nums[0]].lower() + sum((ys[j] - ys[j - 1]) * H[nums[j]].lower() for j in range(1, Jg)) \
        - ys[Jg - 1] * H[nums[Jg]].upper()
    G = (coef * lower).lower()
    print(f"family z={z} y in [{y0 / 40:g},{y1 / 40:g}] coef={sys.argv[6]}: lower bound {G.str(8)} (arb endpoint)")
    print(f"total time {time.time() - t0:.0f}s")


if __name__ == "__main__":
    main()
