"""Taylor versus Padé approximation, for the post taylor-vs-pade.qmd.

Builds the degree-6 Taylor polynomial and the [3/3] Padé approximant of exp(x) and log(1+x) from the
same seven Taylor coefficients, draws the two figures of the post into img/, and prints and checks
every number the post quotes.

Run from anywhere:  python3 taylor-vs-pade.py
The Padé coefficients are computed exactly with fractions and compared with scipy.interpolate.pade.
"""
import math
import os
from fractions import Fraction as Fr

import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from scipy.interpolate import pade

HERE = os.path.dirname(os.path.abspath(__file__))
IMG = os.path.join(HERE, "..", "img")
os.makedirs(IMG, exist_ok=True)

# Same Palatino clone with old-style numerals as the web pages (falls back to DejaVu if not installed).
plt.rcParams.update({
    "font.family": ["Pagella Book Figures", "DejaVu Sans"],
    "mathtext.fontset": "custom",
    "mathtext.rm": "Pagella Book Figures",
    "mathtext.it": "Pagella Book Figures:italic",
    "mathtext.bf": "Pagella Book Figures:bold",
    "mathtext.sf": "Pagella Book Figures",
    "mathtext.cal": "Pagella Book Figures:italic",
    "mathtext.fallback": "cm",
    "font.size": 16,
    "axes.titlesize": 17,
})
C_TRUE, C_TAY, C_PADE = "black", "#d55e00", "#0072b2"

checks = 0


def check(name, got, want, tol=None):
    """Stop if a number quoted in the post is not what the computation gives.

    By default the quoted number must be the computed one rounded to the digits it is quoted with.
    """
    global checks
    if tol is None:
        digits = len(repr(float(want)).split(".")[1])
        ok = abs(got - want) <= 0.5*10**-digits + 1e-12
    else:
        ok = abs(got - want) <= tol
    print(f"{'ok ' if ok else 'BAD'} {name:<46s} {got:.6g}   (post: {want})")
    if not ok:
        raise SystemExit(f"check failed: {name}")
    checks += 1


# ---------------------------------------------------------------- exact Padé from Taylor coefficients
def pade_exact(c, L, M):
    """[L/M] Padé of sum c_k x^k with exact fractions. Returns (a, b), b[0] = 1.

    The denominator solves sum_{j=0}^{M} b_j c_{k-j} = 0 for k = L+1..L+M,
    and the numerator is a_k = sum_{j=0}^{min(k,M)} b_j c_{k-j} for k = 0..L.
    """
    c = [Fr(x) for x in c]
    cc = lambda k: c[k] if k >= 0 else Fr(0)
    # M x M system for b_1..b_M
    A = [[cc(k - j) for j in range(1, M + 1)] for k in range(L + 1, L + M + 1)]
    rhs = [-cc(k) for k in range(L + 1, L + M + 1)]
    n = M
    for i in range(n):                       # Gauss-Jordan with exact arithmetic
        p = next(r for r in range(i, n) if A[r][i] != 0)
        A[i], A[p], rhs[i], rhs[p] = A[p], A[i], rhs[p], rhs[i]
        for r in range(n):
            if r != i and A[r][i] != 0:
                f = A[r][i] / A[i][i]
                A[r] = [x - f*y for x, y in zip(A[r], A[i])]
                rhs[r] -= f*rhs[i]
    b = [Fr(1)] + [rhs[i] / A[i][i] for i in range(n)]
    a = [sum(b[j]*cc(k - j) for j in range(min(k, M) + 1)) for k in range(L + 1)]
    return a, b


def poly(coef, x):
    return sum(float(ck)*x**k for k, ck in enumerate(coef))


c_exp = [Fr(1, math.factorial(k)) for k in range(7)]
c_log = [Fr(0)] + [Fr((-1)**(k + 1), k) for k in range(1, 7)]

a_e, b_e = pade_exact(c_exp, 3, 3)
a_l, b_l = pade_exact(c_log, 3, 3)
print("exp [3/3]  P:", [str(x) for x in a_e], " Q:", [str(x) for x in b_e])
print("log [3/3]  P:", [str(x) for x in a_l], " Q:", [str(x) for x in b_l])
assert a_e == [1, Fr(1, 2), Fr(1, 10), Fr(1, 120)] and b_e == [1, Fr(-1, 2), Fr(1, 10), Fr(-1, 120)]
assert a_l == [0, 1, 1, Fr(11, 60)] and b_l == [1, Fr(3, 2), Fr(3, 5), Fr(1, 20)]
assert a_e == [b*(-1)**k for k, b in enumerate(b_e)]          # Q(x) = P(-x)
checks += 3

# the [1/1] hand examples
a, b = pade_exact(c_log, 1, 1)
assert a == [0, 1] and b == [1, Fr(1, 2)]                      # 2x/(2+x)
a, b = pade_exact(c_exp, 1, 1)
assert a == [1, Fr(1, 2)] and b == [1, Fr(-1, 2)]              # (1+x/2)/(1-x/2)
checks += 2

# scipy agrees with the exact coefficients
for c, (a, b) in [(c_exp, (a_e, b_e)), (c_log, (a_l, b_l))]:
    p, q = pade([float(x) for x in c], 3)
    s = q.coeffs[-1]
    assert np.allclose(p.coeffs[::-1]/s, [float(x) for x in a]) and np.allclose(q.coeffs[::-1]/s, [float(x) for x in b])
    checks += 1

T_exp = lambda x: poly(c_exp, x)
R_exp = lambda x: poly(a_e, x)/poly(b_e, x)
T_log = lambda x: poly(c_log, x)
R_log = lambda x: poly(a_l, x)/poly(b_l, x)

# ---------------------------------------------------------------- numbers quoted in the post
print("\n[1/1] hand example, log(1+x) at x = 1")
check("ln 2", math.log(2), 0.693)
check("degree-2 Taylor at 1", 1 - 1/2, 0.5)
check("[1/1] Pade 2x/(2+x) at 1", 2/3, 0.667)
check("Taylor-2 error at 1 (%)", 100*(math.log(2) - 0.5)/math.log(2), 28.0, tol=0.5)
check("[1/1] error at 1 (%)", 100*(math.log(2) - 2/3)/math.log(2), 4.0, tol=0.5)

print("\nlog(1+x)")
check("Taylor-6 at x=2", T_log(2), -5.6)
check("Taylor-6 at x=3", T_log(3), -85.65)
check("Pade at x=2", R_log(2), 1.098)
check("ln 3", math.log(3), 1.099)
check("Pade at x=3", R_log(3), 1.384)
check("ln 4", math.log(4), 1.386)
check("Pade at x=10", R_log(10), 2.33)
check("ln 11", math.log(11), 2.40)
check("Pade error at x=10 (%)", 100*(math.log(11) - R_log(10))/math.log(11), 3.0, tol=0.5)
check("Taylor/true at x=3", abs(T_log(3))/math.log(4), 61.8, tol=0.05)
check("Taylor/true at x=-4 for exp", T_exp(-4)/math.exp(-4), 117.7, tol=0.05)
check("Pade vs Taylor error ratio at x=1", (T_exp(1)-math.e)/(R_exp(1)-math.e), -8.07, tol=0.005)
check("Pade limit x->inf = 11/3", float(a_l[3]/b_l[3]), 3.667)
check("Pade at x=100", R_log(100), 3.44)
check("ln 101", math.log(101), 4.62)
poles = np.sort(np.roots([float(x) for x in b_l[::-1]]).real)
zeros = np.sort(np.roots([float(x) for x in a_l[::-1]]).real)
assert np.all(np.abs(np.roots([float(x) for x in b_l[::-1]]).imag) < 1e-12)
check("log pole 1", poles[0], -8.873)
check("log pole 2", poles[1], -2.0)
check("log pole 3", poles[2], -1.127)
check("log zero 1", zeros[0], -4.136)
check("log zero 2", zeros[1], -1.319)
check("log zero 3", zeros[2], 0.0)
check("poles -2 and -5 +- sqrt(15)", poles[2], -5 + math.sqrt(15), tol=1e-12)
check("zeros (-30 +- 4 sqrt(15))/11", zeros[1], (-30 + 4*math.sqrt(15))/11, tol=1e-12)

print("\nexp(x)")
check("e^-4", math.exp(-4), 0.0183)
check("Taylor-6 at -4", T_exp(-4), 2.156)
check("Pade at -4", R_exp(-4), 0.01299)
check("Pade at -4 = 1/77", R_exp(-4), 1/77, tol=1e-12)
check("Pade at 4", R_exp(4), 77.0)
check("e^4", math.exp(4), 54.60)
check("Taylor-6 at 4", T_exp(4), 48.56)
check("Taylor rel. error at 1 (%)", 100*abs(T_exp(1) - math.e)/math.e, 0.0083)
check("Pade rel. error at 1 (%)", 100*abs(R_exp(1) - math.e)/math.e, 0.0010)
check("Taylor rel. error at 3 (%)", 100*abs(T_exp(3) - math.exp(3))/math.exp(3), 3.35)
check("Pade rel. error at 3 (%)", 100*abs(R_exp(3) - math.exp(3))/math.exp(3), 3.13)
rq = np.roots([float(x) for x in b_e[::-1]])
real_pole = rq[np.abs(rq.imag) < 1e-12].real[0]
check("exp real pole", real_pole, 4.644)
cpx = rq[np.abs(rq.imag) > 1e-12]
check("exp complex pole, real part", cpx[0].real, 3.678)
check("exp complex pole, |imag part|", abs(cpx[0].imag), 3.509)
# crossover on x > 0 where the Padé error overtakes the Taylor error
xs = np.linspace(0.2, 4.5, 400001)       # below 0.2 both errors sit at round-off
d = np.abs(R_exp(xs) - np.exp(xs)) - np.abs(T_exp(xs) - np.exp(xs))
xc = xs[np.argmax(d > 0)]
check("crossover x", xc, 3.06)
xs = np.linspace(-4, -0.2, 400001)
assert np.all(np.abs(R_exp(xs) - np.exp(xs)) < np.abs(T_exp(xs) - np.exp(xs)))   # Pade better on [-4, 0)
checks += 1
check("Pade limit x->-inf", float(a_e[3]/b_e[3]), -1.0)
zs = np.roots([float(x) for x in a_e[::-1]])
check("exp real zero", zs[np.abs(zs.imag) < 1e-12].real[0], -4.644)
check("Pade at -5", R_exp(-5), -0.0059)
check("e^-5", math.exp(-5), 0.0067)
check("Taylor-6 at -5", T_exp(-5), 9.4)

print("\ntime delay, [1/1] Pade of exp(-s tau) on s = i omega, omega tau = 1")
wt = 1.0
R11 = (1 - 1j*wt/2)/(1 + 1j*wt/2)
check("|[1/1]|", abs(R11), 1.0)
check("phase of [1/1] (rad)", np.angle(R11), -0.927)
check("|1 - i omega tau| (Taylor)", abs(1 - 1j*wt), 1.414)
check("phase of 1 - i omega tau (rad)", np.angle(1 - 1j*wt), -0.785)
check("trapezoidal: |(1+z/2)/(1-z/2)| at z=-10", abs((1 - 5)/(1 + 5)), 0.667)
check("explicit Euler: |1+z| at z=-10", abs(1 - 10), 9.0)
check("exact e^z at z=-10", math.exp(-10), 4.5e-5)

# ---------------------------------------------------------------- figures
def two_panel(x, f, T, R, ylim, name, fname, xmark=None, xerr=None):
    xe = x if xerr is None else xerr
    fig, (ax, bx) = plt.subplots(1, 2, figsize=(15.5, 6.0))
    ax.plot(x, f(x), color=C_TRUE, lw=2.6, label=f"true {name}")
    ax.plot(x, T(x), color=C_TAY, lw=2.2, ls="--", label="Taylor, degree 6")
    ax.plot(x, R(x), color=C_PADE, lw=2.2, label="Padé [3/3]")
    ax.set_ylim(*ylim)
    ax.set_xlabel("$x$")
    ax.set_title("the curves")
    ax.grid(True, alpha=0.3)
    ax.legend(loc="upper left", frameon=False)
    with np.errstate(divide="ignore", invalid="ignore"):
        bx.semilogy(xe, np.abs(T(xe) - f(xe)), color=C_TAY, lw=2.2, ls="--", label="Taylor, degree 6")
        bx.semilogy(xe, np.abs(R(xe) - f(xe)), color=C_PADE, lw=2.2, label="Padé [3/3]")
    if xmark is not None:
        bx.axvline(xmark, color="grey", lw=1.2, ls=":")
    bx.set_ylim(1e-12, 1e4)
    bx.set_xlabel("$x$")
    bx.set_title("absolute error (log scale)")
    bx.grid(True, which="major", alpha=0.3)
    fig.tight_layout()
    out = os.path.join(IMG, fname)
    fig.savefig(out, dpi=150, bbox_inches="tight")
    plt.close(fig)
    print("wrote", out)


x = np.linspace(-4, 4, 2001)
x = x[np.abs(x - real_pole) > 1e-3]
two_panel(x, np.exp, T_exp, R_exp, (-5, 60), "$e^x$", "fig-tp-exp.png")

x = np.linspace(-0.99, 3.0, 2001)
xe = np.linspace(-0.99, 10.0, 4001)
two_panel(x, np.log1p, T_log, R_log, (-4, 3), r"$\ln(1+x)$", "fig-tp-log.png", xmark=1.0, xerr=xe)

print(f"\nall {checks} checks passed")
