"""Literal Python conversion of fig8_13.m."""

import matplotlib.pyplot as plt
import numpy as np


def E(v):
    nd = 6
    xd = np.zeros(nd)
    yd = np.zeros(nd)
    xd[0] = 0.1; xd[1] = 0.5; xd[2] = 1; xd[3] = 2; xd[4] = 5; xd[5] = 10
    yd[0] = 0.5; yd[1] = 1.8; yd[2] = 3.4; yd[3] = 6.1; yd[4] = 8.7; yd[5] = 11.1
    s = 0
    for i in range(nd):
        s = s + (v[0] * xd[i] / (v[1] + xd[i]) - yd[i]) ** 2
    return s


def fig8_13():
    #  data for regression
    nd = 6
    xd = np.zeros(nd)
    yd = np.zeros(nd)
    xd[0] = 0.1; xd[1] = 0.5; xd[2] = 1; xd[3] = 2; xd[4] = 5; xd[5] = 10
    yd[0] = 0.5; yd[1] = 1.8; yd[2] = 3.4; yd[3] = 6.1; yd[4] = 8.7; yd[5] = 11.1

    # find V1 and V2
    XD = np.zeros(nd)
    YD = np.zeros(nd)
    for i in range(nd):
        XD[i] = 1 / xd[i]
        YD[i] = 1 / yd[i]
    SX = np.sum(XD)
    SX2 = np.dot(XD, XD)
    SY = np.sum(YD)
    SXY = np.dot(XD, YD)
    D = nd * SX2 - SX ** 2
    V1 = (SX2 * SY - SX * SXY) / D
    V2 = (-SX * SY + nd * SXY) / D

    # determine resulting curve
    vv1 = 1 / V1
    vv2 = V2 / V1
    x = np.linspace(0, 10, 100)
    yy = np.zeros(100)
    for i in range(100):
        yy[i] = vv1 * x[i] / (vv2 + x[i])

    # find v1 and v2 using nonlinear regression
    # v2=1; v1=14*v2;
    # sol = minimize(E, [v1, v2], method='Nelder-Mead',
    #                options={'maxfev': 1000000, 'maxiter': 1000000, 'xatol': 1e-6})
    # v1=sol.x[0]
    # v2=sol.x[1]
    # x=np.linspace(0,10,100)
    # y=np.zeros(100)
    # for i in range(100):
    #     y[i]=v1*x[i]/(v2+x[i])

    plt.close("all")
    # get(gcf)
    # MATLAB Position [25 1115 658 230], scaled to fit the plot window.
    fig, ax = plt.subplots(figsize=(6.58, 3.0), 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],
    ])
    ax.set_prop_cycle(color=co)

    # ax.plot(x,y,'r',linewidth=3)
    ax.plot(x, yy, "r", linewidth=1.6)
    ax.plot(xd, yd, ".b", markersize=30)
    ax.axis([0, 10, 0, 12])
    ax.set_yticks([0, 3, 6, 9, 12])
    ax.set_frame_on(True)
    ax.grid(True)
    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")

    # fig.savefig('/Users/mark/Desktop/menten0.eps')
    plt.show()


if __name__ == "__main__":
    fig8_13()
