"""Lower bound for the gain coefficient G = lim (sum_{c in E} 1/c) log x using a_{y,2} on a grid.

For a >= 2 and 1 = th_0 < ... < th_J = 3/2, the odd m with x/(2^a th_{j+1}) < m <= x/(2^a th_j), F(m) <= x
number A(x/y_j, y_j, 2) - A(x/y_{j+1}, y_{j+1}, 2) with y_j = 2^a th_j, i.e. (h(y_j) - h(y_{j+1})) x/log x + o,
h(y) = a_{y,2}/y, and each n = 2^a m has 1/n >= th_j/x. Hence G >= sum_a sum_j th_j (h(y_j) - h(y_{j+1})).
Usage: python3 gain.py <Umax> <amax> <J>
"""
import sys
import numpy as np
import ay2

Umax, amax, J = int(float(sys.argv[1])), int(sys.argv[2]), int(sys.argv[3])
th = [1 + 0.5 * j / J for j in range(J + 1)]
ys = sorted({2 ** a * t for a in range(2, amax + 1) for t in th})
primes = ay2.primes_upto(Umax + 1)
cum = ay2.Cumul(primes)
F = ay2.F_table(int(Umax / 4), primes)
import math


def Ebound(x):
    """E(x) = sup_{t>=x} |Sigma(t) + gamma - log t| <= 1/(2 log x) + 2(log x + 1)/(x - 1) for x >= 319
    (Rosser-Schoenfeld 1962, Thm 6, for sum log p/p; the tail sum_{p>t} log p/(p(p-1)) <= 2(log t+1)/(t-1))."""
    assert x >= 319
    return 1 / (2 * math.log(x)) + 2 * (math.log(x) + 1) / (x - 1)


h, err, rnd = {}, {}, {}
for y in ys:
    N = int(Umax / y)
    a, Jv, eps, M = ay2.a_y2(y, N, F, cum)
    rJ, rE = ay2.rounding_bound(y, M, cum)
    assert eps - rE >= 0
    h[y] = a / y
    Cf = float(ay2.C)
    # |h(y) - computed| <= C (eps + rE) E(yN) / y  +  C rJ / y  (+ 1e-15 for the final float conversion)
    err[y] = Cf * (eps + rE) * Ebound(y * N) / y + Cf * rJ / y + 1e-15
    rnd[y] = Cf * rJ / y
tot, tot_err = 0.0, 0.0
for a in range(2, amax + 1):
    yy = [2 ** a * t for t in th]
    s = sum(th[j] * (h[yy[j]] - h[yy[j + 1]]) for j in range(J))
    e = th[0] * err[yy[0]] + sum((th[j] - th[j - 1]) * err[yy[j]] for j in range(1, J)) + th[J - 1] * err[yy[J]]
    tot += s
    tot_err += e
    print(f"a={a}: grid sum {s:.6f}  error <= {e:.6f}  (crude 1/x bound {h[yy[0]] - h[yy[J]]:.6f})")
print(f"max rounding part of an h error: {max(rnd.values()):.2e}")
print(f"G_grid = {tot:.6f}, total error <= {tot_err:.6f}, so G >= {tot - tot_err:.6f}")
