import numpy as np
import matplotlib.pyplot as plt
from cycler import cycler


def fig5_17():
    a = -1
    b = 1

    # exact
    n = 2000
    x = np.linspace(a, b, n)
    ye = np.zeros(n)
    for ie in range(n):
        ye[ie] = 1 / (1 + 25 * x[ie] ** 2)

    # interpolation points
    nx = 17
    xd = np.zeros(nx)
    yd = np.zeros(nx)
    for ix in range(nx):
        cc = (2 * (ix + 1) - 1) * np.pi / (2 * nx)
        xd[ix] = 0.5 * (a + b + (b - a) * np.cos(cc))
        yd[ix] = f(xd[ix])

    # p_n(x)
    p = np.zeros(n)
    for ii in range(n):
        for k in range(nx):
            p[ii] = p[ii] + yd[k] * ell(k, x[ii], xd)

    plt.close("all")
    # get(gcf)
    fig, ax = plt.subplots(figsize=(9.0, 3.2))
    fig.subplots_adjust(left=0.08, right=0.97, bottom=0.21, top=0.97)
    co = np.array([
        [0, 0, 1],
        [0, 0.5, 0],
        [1, 0, 0],
        [0, 0.75, 0.75],
        [0.75, 0, 0.75],
        [0.75, 0.75, 0],
        [0.25, 0.25, 0.25],
    ])
    ax.set_prop_cycle(cycler(color=co))

    ax.plot(x, ye, "--r", linewidth=2)
    ax.plot(x, p, "b", linewidth=1.6)
    ax.set_yticks([0, 1])
    ax.set_xlim(-1, 1)
    ax.set_ylim(-0.15, 1.05)
    for i in range(nx):
        ax.plot([xd[i], xd[i]], [-0.05, 0], "k", linewidth=2.1)
    ax.grid(True)
    ax.set_xlabel("x-axis")
    ax.set_ylabel("y-axis")
    ax.legend(
        [" Runge", " Cheb"],
        loc="upper right",
        prop={"size": 14, "weight": "bold"},
    )

    ax.tick_params(labelsize=14)
    for label in ax.get_xticklabels() + ax.get_yticklabels():
        label.set_fontweight("bold")
    for spine in ax.spines.values():
        spine.set_visible(True)
    plt.show()

    # plt.savefig('/Users/mark/Desktop/cheb.eps')


def f(x):
    g = 1 / (1 + 25 * x ** 2)
    return g


# ell_i(x) function
def ell(i, x, xd):
    n2 = xd.size
    p = 1.0
    for j in range(n2):
        if j != i:
            p = p * (x - xd[j]) / (xd[i] - xd[j])
    return p


if __name__ == "__main__":
    fig5_17()
