#!/usr/bin/env python3
"""verify.py -- usage: python3 verify.py certificate.json

Checks a counterexample to the lower inequality  c_n ||A||_{H^4} <= ||A||_{H^1_*}
of Kovalev's Conjecture 6.1.  Standard library only; every decision is made in
exact integer / rational arithmetic.  See CERTIFICATE.md for the mathematics.
"""
import json
import sys
from fractions import Fraction as F


def fail(msg):
    print("FAILED: " + msg)
    sys.exit(1)


def frac(s):
    if not isinstance(s, str):
        fail("numbers must be strings 'p/q' or 'p'")
    return F(s)


def pi_upper():
    """Rational upper bound for pi from Machin's formula
    pi = 16 atan(1/5) - 4 atan(1/239), alternating series with decreasing terms:
    a partial sum ending on a + term is an upper bound for atan, ending on a
    - term is a lower bound."""
    def atan_inv(q, terms):
        return sum(F((-1) ** j, (2 * j + 1) * q ** (2 * j + 1)) for j in range(terms))
    up = 16 * atan_inv(5, 21) - 4 * atan_inv(239, 20)   # upper(atan 1/5), lower(atan 1/239)
    lo = 16 * atan_inv(5, 20) - 4 * atan_inv(239, 21)
    if not (F(3) < lo < up < F(22, 7)):
        fail("pi enclosure broken")
    return up


def integral_lower_bounds(k, r, N, P=96):
    """Rigorous rational lower bounds for
         I_u = int_0^1 (1-x^2)^h / (1-q x^2)^h     dx
         I_v = int_0^1 (1-x^2)^h / (1-q x^2)^(h+1) dx,   h = k/2, q = 1 - r^2.
    On [j/N,(j+1)/N] both 1-x^2 and 1-q x^2 are positive and decreasing, so the
    integrand is >= (numerator at right end)/(denominator at left end).
    Each term is additionally rounded DOWN to a multiple of 2^-P."""
    h = k // 2
    p, d = r.numerator, r.denominator
    N2 = N * N
    c = d * d - p * p              # q = c/d^2
    N2d2 = N2 * d * d
    d2h = (d * d) ** h
    su = sv = 0
    for j in range(N):
        a = N2 - (j + 1) * (j + 1)       # N^2 (1 - x_{j+1}^2)   >= 0
        D = N2d2 - c * j * j             # N^2 d^2 (1 - q x_j^2) > 0
        t = (a ** h * d2h) << P
        Dh = D ** h
        su += t // Dh                    # floor(2^P (1-x_{j+1}^2)^h/(1-q x_j^2)^h)
        sv += (t * d * d * N2) // (Dh * D)
    return F(su, N << P), F(sv, N << P)


def main():
    if len(sys.argv) != 2:
        fail("usage: python3 verify.py certificate.json")
    with open(sys.argv[1]) as fh:
        cert = json.load(fh)

    n = cert["n"]
    if not (isinstance(n, int) and not isinstance(n, bool) and n > 2):
        fail("need integer n > 2")
    rows = cert["A"]
    if not (isinstance(rows, list) and len(rows) == n and all(isinstance(R, list) and len(R) == n for R in rows)):
        fail("A must be an n x n list of lists")
    A = [[frac(x) for x in R] for R in rows]
    r = frac(cert["witness_r"])
    N = cert.get("riemann_steps", 2000000)
    if not (isinstance(N, int) and not isinstance(N, bool) and 1 <= N <= 20000000):
        fail("riemann_steps out of range")

    # ---- shape required by the dual-norm lemma -------------------------------
    k = n - 1
    if k % 2 != 0:
        fail("this verifier needs n odd (k = n-1 even) so the integrands are rational")
    if not (0 < r < 1):
        fail("need 0 < witness_r < 1")
    for i in range(n):
        for j in range(n):
            if i != j and A[i][j] != 0:
                fail("A must be diagonal")
    alpha, beta = A[0][0], A[1][1]
    if not (alpha > 0 and beta > 0):
        fail("diagonal entries must be positive")
    if any(A[i][i] != beta for i in range(1, n)):
        fail("A must be diag(alpha, beta, ..., beta)")

    # ---- ||A||_{H^4}: exact, for the matrix as given --------------------------
    # E_x |Ax|^4 = ((tr M)^2 + 2 tr(M^2)) / (n(n+2)),  M = A^T A.
    M = [[sum(A[l][i] * A[l][j] for l in range(n)) for j in range(n)] for i in range(n)]
    trM = sum(M[i][i] for i in range(n))
    trM2 = sum(M[i][j] * M[j][i] for i in range(n) for j in range(n))
    W = trM * trM + 2 * trM2          # = n(n+2) ||A||_{H^4}^4

    # ---- ||A||_{H^1_*} <= sqrt(pi) Gamma((n+1)/2) / (n Gamma(n/2)) ------------
    # holds provided alpha <= I_u and beta <= r I_v (CERTIFICATE.md, Lemma 2+3).
    Lu, Lv = integral_lower_bounds(k, r, N)
    if not (alpha <= Lu):
        fail("alpha is not certified <= I_u")
    if not (beta <= r * Lv):
        fail("beta is not certified <= r*I_v")

    # ---- final comparison -----------------------------------------------------
    # c_n ||A||_{H^4} = (2^{5/4}/sqrt(pi)) G (W)^{1/4} / n,  G = Gamma((n+1)/2)/Gamma(n/2)
    # ||A||_{H^1_*}  <= sqrt(pi) G / n
    # so  c_n||A||_{H^4} > ||A||_{H^1_*}  follows from  32 W > pi^4.
    pu = pi_upper()
    if not (32 * W > pu ** 4):
        fail("32*W > pi^4 not certified")

    ratio4_lower = 32 * W / pu ** 4
    print("n =", n)
    print("alpha = %s <= I_u lower bound ~ %.9f" % (alpha, float(Lu)))
    print("beta  = %s <= r*I_v lower bound ~ %.9f" % (beta, float(r * Lv)))
    print("exact n(n+2)||A||_H4^4 = W =", W)
    print("(c_n ||A||_H4 / ||A||_H1*)^4 >= 32W/pi^4 >= %s  (~%.8f, display only)" % (ratio4_lower.limit_denominator(10**12), float(ratio4_lower)))
    print("Lower inequality of Conjecture 6.1 fails for this A.")
    print("VERIFIED")
    sys.exit(0)


if __name__ == "__main__":
    try:
        main()
    except SystemExit:
        raise
    except Exception as e:  # malformed certificate etc.
        print("FAILED: %r" % (e,))
        sys.exit(1)
