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

from splineA import splineA


def fig5_20():
    a = 0
    b = 1
    nx = 25

    # exact
    n = 1000
    x = np.linspace(a, b, n)
    ye = np.zeros(n)
    for ie in range(n):
        ye[ie] = f(x[ie])

    # cheb
    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 = np.zeros(n)
    for ii in range(n):
        for k in range(nx):
            p[ii] = p[ii] + yd[k] * ell(k, x[ii], xd)

    # spline
    xds = np.linspace(a, b, nx)
    yds = np.zeros(nx)
    for iy in range(nx):
        yds[iy] = f(xds[iy])
    n = 400
    xs = np.linspace(a, b, n)
    ys = splineA(xds, yds, xs)
    # ys = nspline(xds,yds,xs);

    plt.close("all")
    # get(gcf)
    fig, ax = plt.subplots(figsize=(9.0, 3.2))
    fig.subplots_adjust(left=0.08, right=0.98, bottom=0.22, 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(xs, ys, "r", linewidth=1.6)
    ax.plot(x, p, "b", linewidth=1.6)
    ax.plot(x, ye, "--k", linewidth=1.8)
    ax.set_yticks([-1, 0, 1])
    ax.set_xticks([0, 0.5, 1])
    ax.set_xlim(0, 1)
    ax.set_ylim(-1.4, 1.3)
    ax.grid(True)
    ax.set_xlabel("x-axis")
    ax.set_ylabel("y-axis")
    ax.legend(
        [" Spline", " Cheb", " Exact"],
        loc="lower 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/tanh.eps')


def f(x):
    g = np.tanh(100 * (x - 0.3))
    return g


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_20()
