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

from splineA import splineA


def fig5_21():
    a = 0
    b = 1
    nx = 15
    n = 400
    x = np.linspace(a, b, n)

    # 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] = fc(xd[ix], ix + 1)
    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], iy + 1)
    n = 400
    xs = np.linspace(a, b, n)
    ys = splineA(xds, yds, xs)

    plt.close("all")
    # get(gcf)
    fig, ax = plt.subplots(figsize=(9.0, 3.2))
    fig.subplots_adjust(left=0.05, 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.set_yticks([0, 1])
    ax.set_xticks([0, 0.5, 1])
    ax.set_xlim(0, 1)
    ax.set_ylim(-0.3, 1.1)
    ax.grid(True)
    ax.set_xlabel("x-axis")
    # ax.set_ylabel("y-axis")
    ax.legend(
        [" Spline", " Cheb"],
        loc="upper left",
        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/bump.eps')


def fc(x, i):
    g = 0
    if i == 5:
        g = 1
    return g


def f(x, i):
    g = 0
    if i == 12:
        g = 1
    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_21()
