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

from plot_helpers import CO, bold_ticks


def fig7_3():
    # euler method for various M values
    # y' = ry(1-y) with y(0) = y0 '

    r = 10
    t0 = 0
    y0 = 0.01
    tmax = 1

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

    # calculate and plot exact solution
    tt = np.linspace(t0, tmax, 100)
    a0 = (1 - y0) / y0
    exact = np.zeros(100)
    for it in range(100):
        exact[it] = 1 / (1 + a0 * np.exp(-r * tt[it]))
    ax.plot(tt, exact, "r", linewidth=1.4)

    # calculate and plot using euler
    m = 4
    for im in range(3):
        t = np.linspace(t0, tmax, m + 1)
        h = t[1] - t[0]
        euler = [y0]
        y = y0
        for i in range(1, m + 1):
            yy = y + r * h * y * (1 - y)
            euler.append(yy)
            y = yy
        euler = np.asarray(euler)
        if im == 0:
            ax.plot(t, euler, "--ks", markersize=7, linewidth=1.1)
        elif im == 1:
            ax.plot(t, euler, "--m*", markersize=7, linewidth=1.1)
        else:
            ax.plot(t, euler, "--bo", markersize=7, linewidth=1.1)
        m = 4 * m

    ax.set_xlim(0, 1)
    ax.set_ylim(0, 1.05)
    # ax.legend([" Exact", " M = 4", " M = 16", " M = 64"], loc=2)
    ax.grid(True)
    # get(legend)
    # 'Position',[left, bottom, width, height]
    ax.legend(
        [" Exact", " M = 4", " M = 16", " M = 64"],
        loc="upper left",
        prop={"size": 14, "weight": "bold"},
    )

    ax.set_xlabel("t-axis")
    ax.set_ylabel("Solution")
    bold_ticks(ax, 14)
    for spine in ax.spines.values():
        spine.set_visible(True)
    plt.show()

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


if __name__ == "__main__":
    fig7_3()
