#!/usr/bin/env python3
"""Stage 3: one focused proof attempt -- type II (simultaneous) Hermite-Pade approximation to the
pair (e^z, arctan z) with a COMMON denominator polynomial, evaluated at z = 1.

Construction (indices n1, n2;  N = n1 + n2):
  find A(z) = sum_{j<=N} alpha_j z^j, alpha in Z^{N+1} primitive, with
      [z^k] (e^z A(z))      = 0   for k = N+1 .. N+n1
      [z^k] (arctan(z) A(z)) = 0   for k = N+1 .. N+n2
  B = Taylor truncation of e^z A to degree N, C = truncation of arctan(z) A to degree N.
  At z = 1:  R_e = A(1) e - B(1),  R_a = A(1) pi/4 - C(1)  and
      L = A(1)(e + pi) - (B(1) + 4 C(1)) = R_e + 4 R_a.
  B(1), C(1) are rational; D = common denominator, so D*L is an integer linear form in e + pi.
  An Apery-type certificate needs |D*L| -> 0 (Yu, Lemma 2.2 + Lemma 5.1).

All linear algebra is exact (FLINT integer nullspace). |L|, R_e, R_a are evaluated with mpmath at
high precision. Output: data/stage3_hermite_pade.jsonl.

Second experiment ("e-first"): Hermite's integer forms for e,  A_n = A(P_n) for
P_n(x) = x^n (1-x)^n / n!  (integer coefficients), satisfy |A_n e - S_n| -> 0. Any certificate
built on them needs ||A_n pi|| -> 0 (distance to nearest integer) -- we measure it.
"""
import sys, os, json, math, time
from fractions import Fraction
import flint, mpmath

HERE = os.path.dirname(os.path.abspath(__file__)); DATA = os.path.join(HERE, "..", "data")
mpmath.mp.dps = 3000
E, PI = mpmath.e, mpmath.pi

def t_coef(m):          # Taylor coefficient of arctan
    if m % 2 == 0: return Fraction(0)
    return Fraction((-1) ** ((m - 1) // 2), m)

def hp_type2(n1, n2):
    N = n1 + n2
    rows = []
    for k in range(N + 1, N + n1 + 1):     # e^z rows scaled by k!
        rows.append([math.factorial(k) // math.factorial(k - j) for j in range(N + 1)])
    for k in range(N + 1, N + n2 + 1):     # arctan rows scaled by lcm of denominators
        fr = [t_coef(k - j) for j in range(N + 1)]
        l = 1
        for f in fr: l = l * f.denominator // math.gcd(l, f.denominator)
        rows.append([int(f * l) for f in fr])
    M = flint.fmpz_mat(rows)
    X, nullity = M.nullspace()
    assert nullity >= 1
    alpha = [int(X[j, 0]) for j in range(N + 1)]
    g = 0
    for a in alpha: g = math.gcd(g, a)
    alpha = [a // g for a in alpha]
    if sum(alpha) < 0: alpha = [-a for a in alpha]
    A1 = sum(alpha)
    B1 = sum(Fraction(alpha[j], math.factorial(k - j)) for k in range(N + 1) for j in range(k + 1))
    C1 = sum(alpha[j] * t_coef(k - j) for k in range(N + 1) for j in range(k + 1))
    S = B1 + 4 * C1
    D = S.denominator
    Aint, Bint = D * A1, S.numerator          # integer form Aint (e+pi) - Bint
    g = math.gcd(Aint, Bint); A0, B0 = Aint // g, Bint // g
    Re = A1 * E - mpmath.mpf(B1.numerator) / B1.denominator
    Ra = A1 * PI / 4 - mpmath.mpf(C1.numerator) / C1.denominator
    L0 = A0 * (E + PI) - B0
    lg = lambda x: float(mpmath.log10(abs(x))) if x != 0 else float("-inf")
    return {"n1": n1, "n2": n2, "N": N, "nullity": nullity,
            "log10|A(1)|": lg(A1), "log10 D": math.log10(D), "log10|R_e|": lg(Re), "log10|4R_a|": lg(4 * Ra),
            "log10|L| (before clearing)": lg(Re + 4 * Ra), "log10|A0|": math.log10(abs(A0)) if A0 else None,
            "log10|primitive integer form|": lg(L0)}

def hermite_e_first(n):
    # P(x) = x^n (1-x)^n / n!  in Z[x];  A(P) = sum_j (-1)^j P^(j)(1)
    coeffs = [0] * (2 * n + 1)        # coefficients of x^n (1-x)^n
    for i in range(n + 1): coeffs[n + i] = (-1) ** i * math.comb(n, i)
    fac = math.factorial(n)
    P = [c // fac if c % fac == 0 else Fraction(c, fac) for c in coeffs]
    # P is integral since (1/n!) d^n preserves... here P itself = x^n(1-x)^n/n! is NOT integral;
    # use instead Q = d^n/dx^n [x^n (1-x)^n] / n! (Rodrigues / shifted Legendre) which is integral.
    poly = coeffs[:]
    for _ in range(n):
        poly = [k * poly[k] for k in range(1, len(poly))]
    Q = [c // fac for c in poly]; assert all(c % fac == 0 for c in poly)
    # A(Q) = sum_j (-1)^j Q^(j)(1);  S(0) = sum_j (-1)^j Q^(j)(0)
    def derivs_at(poly, x):
        out = []; p = poly[:]
        while p:
            out.append(sum(c * x ** k for k, c in enumerate(p)))
            p = [k * p[k] for k in range(1, len(p))]
        return out
    A = sum((-1) ** j * v for j, v in enumerate(derivs_at(Q, 1)))
    S0 = sum((-1) ** j * v for j, v in enumerate(derivs_at(Q, 0)))
    eform = A * E - S0                        # = int_0^1 Q(x) e^x dx
    frac = A * PI - mpmath.nint(A * PI)
    return {"n": n, "log10|A_n|": math.log10(abs(A)) if A else None,
            "log10|A_n e - S_n|": float(mpmath.log10(abs(eform))), "||A_n pi||": float(abs(frac))}

if __name__ == "__main__":
    out = os.path.join(DATA, "stage3_hermite_pade.jsonl")
    with open(out, "w") as f:
        for (n1, n2) in [(n, n) for n in range(2, 41, 2)] + [(n, 2 * n) for n in range(2, 21, 2)] + [(n, 4 * n) for n in range(1, 11)] + [(2 * n, n) for n in range(2, 21, 2)]:
            t0 = time.time(); r = hp_type2(n1, n2); r["sec"] = round(time.time() - t0, 2)
            f.write(json.dumps(r) + "\n"); f.flush(); print(json.dumps(r), flush=True)
        for n in range(1, 61):
            r = hermite_e_first(n); f.write(json.dumps({"e_first": r}) + "\n"); print(json.dumps(r), flush=True)
