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

from plot_helpers import CO, bold_ticks


def fig7_1():
    # comparison of forward and centered difference approximations for f'(x)

    ### this requires the subaxis and parseArgs files

    x0 = 1
    exact = 0.5
    print(exact)

    np_ = 2000
    p = np.linspace(-18, 0, np_)
    h = np.zeros(np_)
    F = np.zeros(np_)
    C = np.zeros(np_)
    errF = np.zeros(np_)
    errC = np.zeros(np_)

    for k in range(np_):
        h[k] = 10 ** p[k]
        F[k] = (f(x0 + h[k]) - f(x0)) / h[k]
        C[k] = (f(x0 + h[k]) - f(x0 - h[k])) / (2 * h[k])
        errF[k] = abs(exact - F[k])
        errC[k] = abs(exact - C[k])

    plt.close("all")
    # get(gcf)
    fig, ax = plt.subplots(figsize=(8.8, 3.3))
    fig.subplots_adjust(left=0.10, right=0.98, bottom=0.24, top=0.98)
    ax.set_prop_cycle(cycler(color=CO))

    ax.loglog(h, errF, "b", markersize=7, linewidth=1.2)
    ax.loglog(h, errC, "r", markersize=7, linewidth=1.2)
    ax.legend(
        [" Forward", " Centered"],
        loc="lower left",
        prop={"size": 14, "weight": "bold"},
    )
    ax.loglog(h, errF, "b", markersize=7, linewidth=1.2)

    ax.grid(True)
    ax.set_xlabel("Stepsize (k)")
    ax.set_xlim(1e-18, 1)
    ax.set_ylim(1e-12, 1)
    ax.set_xticks([1e-18, 1e-15, 1e-12, 1e-9, 1e-6, 1e-3, 1])
    ax.set_yticks([1e-12, 1e-8, 1e-4, 1])
    ax.set_ylabel("Error")
    bold_ticks(ax, 14)
    plt.show()

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


def f(x):
    y = np.sqrt(x)
    return y


if __name__ == "__main__":
    fig7_1()
