import numpy as np
import matplotlib.pyplot as plt


def fig1_7():
    """Literal Python conversion of fig1_7.m."""

    #  this file includes horner, estrin, and even/odd separation methods
    #  it only plots results for horner

    #  poly coeffs
    a = np.zeros(10)
    a[9] = 1
    a[8] = -8
    a[7] = +28
    a[6] = -56
    a[5] = +70
    a[4] = -56
    a[3] = +28
    a[2] = -8
    a[1] = +1

    d = 0.02
    nx = 1000
    x = np.linspace(1 - d, 1 + d, nx)
    horner = np.empty(nx)
    estrin = np.empty(nx)
    y = np.empty(nx)
    yy = np.empty(nx)
    separ = np.empty(nx)
    for i in range(nx):
        b = a[9]
        for ii in range(1, 9):
            b = a[9 - ii] + x[i]*b
        horner[i] = b
        e1 = a[1] + a[2]*x[i] + (a[3] + a[4]*x[i])*x[i]**2
        e2 = ((a[5] + a[6]*x[i] + (a[7] + a[8]*x[i])*x[i]**2)
              * x[i]**4 + a[9]*x[i]**8)
        estrin[i] = e1 + e2
        y[i] = (x[i]**8 - 8*x[i]**7 + 28*x[i]**6 - 56*x[i]**5
                + 70*x[i]**4 - 56*x[i]**3 + 28*x[i]**2 - 8*x[i] + 1)
        yy[i] = (x[i] - 1)**8
        z = x[i]**2
        separ[i] = (a[1] + a[3]*z + a[5]*z**2 + a[7]*z**3 + a[9]*z**4
                    + x[i]*(a[2] + a[4]*z + a[6]*z**2 + a[8]*z**3))

    plt.close('all')
    # get(gcf)
    # MATLAB Position [25 1115 658 230]: preserve the 658 x 230 pixel size.
    fig, ax = plt.subplots(figsize=(6.58, 2.30), dpi=100, layout='constrained')
    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]
    ])
    plt.rcParams['axes.prop_cycle'] = plt.cycler(color=co)

    ax.plot(x, horner, 'r', linewidth=1)
    ax.plot(x, yy, '--b', linewidth=2.5)
    ax.grid(True)
    ax.set_frame_on(True)
    legend = ax.legend([' Using Horner', ' Using (1.3)'], loc='upper center',
                       fontsize=14)
    for text in legend.get_texts():
        text.set_fontweight('bold')
    ax.axis([1 - d, 1 + d, -2e-14, 4e-14])
    ax.set_xticks([0.98, 0.99, 1, 1.01, 1.02])
    ax.set_xlabel('x-axis', fontsize=14, fontweight='bold')
    ax.set_ylabel('y-axis', fontsize=14, fontweight='bold')
    ax.tick_params(labelsize=14)
    for label in ax.get_xticklabels() + ax.get_yticklabels():
        label.set_fontweight('bold')

    # exportgraphics(gcf,'/Users/mark/Desktop/horn.eps')

    plt.show()


if __name__ == '__main__':
    fig1_7()
