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


def fig5_11():
    # plots the B-spline function

    x0 = -3.0
    x1 = 3.0
    nx = 201
    x = np.linspace(x0, x1, nx)

    exact = np.zeros(nx)
    for ix in range(nx):
        exact[ix] = bspline(x[ix])

    plt.close("all")
    # get(gcf)
    fig, ax = plt.subplots(figsize=(9.0, 3.2))
    fig.subplots_adjust(left=0.05, right=0.99, bottom=0.18, top=0.98)
    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, exact, "b", linewidth=2)
    ax.plot([-1, -1], [0, bspline(-1)], "--b", linewidth=2)
    ax.plot([0, 0], [0, bspline(0)], "--b", linewidth=2)
    ax.plot([1, 1], [0, bspline(1)], "--b", linewidth=2)
    ax.set_xlim(x0, x1)
    ax.set_ylim(0, 0.8)

    ax.plot([-2, -2], [0, 0.02], "k", linewidth=1)
    ax.plot([2, 2], [0, 0.02], "k", linewidth=1)
    ax.set_xticks(np.arange(-3, 4))
    ax.set_xticklabels([" ", " ", " ", " ", " ", " ", " "])

    ax.set_yticks([-10])
    # ax.set_yticklabels(["0", "1/3", "2/3"])
    ax.tick_params(labelsize=14)
    for label in ax.get_xticklabels() + ax.get_yticklabels():
        label.set_fontweight("bold")
    plt.show()


# Calculate the value of a cubic B-spline at point x
def bspline(x):
    x = abs(x)
    if x > 2:
        y = 0
    else:
        if x > 1:
            y = (2 - x) ** 3 / 6
        else:
            y = 2 / 3 - x ** 2 * (1 - x / 2)
    return y


if __name__ == "__main__":
    fig5_11()
