import numpy as np
import matplotlib.pyplot as plt


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

    # compute the values of the ratio
    n = 8000
    exs = np.linspace(-18, -10, n)
    k = np.empty(n + 1)
    y = np.empty(n + 1)
    J = 1
    for i in range(1, n + 1):
        k[i] = 10**exs[i - 1]
        y[i] = (np.sqrt(16 + k[i]) - 4) / k[i]
        if y[i] == 0:
            J = i
    print(J)
    print(k[J] / np.finfo(float).eps)

    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.semilogx(k[1:J + 1], np.zeros(J), 'b-', linewidth=2)

    # plot the results
    JJ = J
    for i in range(1, n + 1):
        found_increase = False
        for j in range(J + 1, n + 1):
            if y[j] > y[j - 1]:
                JJ = j - 1
                found_increase = True
                break
        # Stop once no later increase remains; the final segment is plotted below.
        if not found_increase:
            break
        ax.semilogx(k[J:JJ + 1], y[J:JJ + 1], 'b-', linewidth=1.8)
        J = JJ + 1
        ax.semilogx(k[JJ:JJ + 2], y[JJ:JJ + 2], 'b--', linewidth=1)
        if k[JJ] > 1e11:
            break
    print(JJ)

    ax.semilogx(k[JJ:n + 1], y[JJ:n + 1], 'b-', linewidth=1.8)
    ax.axis([1e-18, 1e-10, -0.02, 0.1875])
    ax.set_yticks([0, 0.0625, 0.1250, 0.1875])
    ax.set_yticklabels(['0 ', '1/16 ', '1/8 ', '3/16 '])
    ax.set_xticks([1e-18, 1e-14, 1e-10, 1e-6, 1e-2])
    ax.grid(True)
    ax.set_xlabel('k-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/sqrtA.eps')

    plt.show()


if __name__ == '__main__':
    fig1_8()
