import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import FancyArrowPatch


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

    plt.close('all')
    # get(gcf)
    # MATLAB Position [8 1148 685 164]: preserve the 685 x 164 pixel size.
    fig, ax = plt.subplots(figsize=(6.85, 1.64), 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([0, 5], [0, 0], 'k', linewidth=2)
    arrow = FancyArrowPatch((4.1, 0), (4.5, 0), arrowstyle='-|>',
                            mutation_scale=12, linewidth=1, color='k')
    ax.add_patch(arrow)
    yf = -0.22
    ax.text(0.29, yf, r'$1-\varepsilon$', fontsize=16, clip_on=False)
    ax.text(0.83, yf, r'$1-\varepsilon/2$', fontsize=16, clip_on=False)
    ax.text(1.63, yf, r'$1$', fontsize=16, clip_on=False)
    ax.text(2.65, yf, r'$1+\varepsilon$', fontsize=16, clip_on=False)
    ax.text(3.82, yf, r'$1+2\varepsilon$', fontsize=16, clip_on=False)
    ax.text(1.95 + 2.5, yf + 0.05, r'$x$', fontsize=16, clip_on=False)

    L = 2
    R = 4
    dx = 0.2
    dl = (4 - 0.5) / 6
    lw = 1.5
    lw2 = 2
    dy = 0.07
    x1 = 0.5
    x2 = x1 + dl
    x3 = x2 + dl
    x4 = x3 + 2*dl
    x5 = x4 + 2*dl
    ax.plot([x1, x1], [-dy, dy], 'k', linewidth=lw)
    ax.plot([x2, x2], [-dy, dy], 'k', linewidth=lw)
    ax.plot([x3, x3], [-dy, dy], 'k', linewidth=lw)
    ax.plot([x4, x4], [-dy, dy], 'k', linewidth=lw)
    ax.plot([x5, x5], [-dy, dy], 'k', linewidth=lw)

    x = 0.5 + dl/2
    ny = 5
    ax.plot([x, x], [-2*dy, ny*dy], '--r', linewidth=lw2)
    ax.text(x + dl/2 - 0.03, 0.23, 'I', color='red', fontsize=16,
            clip_on=False)
    x = x + dl
    ax.plot([x, x], [-2*dy, ny*dy], '--r', linewidth=lw2)
    ax.text(x + 1.5*dl/2 - 0.1, 0.23, 'II', color='red', fontsize=16,
            clip_on=False)
    x = x + 1.5*dl
    ax.plot([x, x], [-2*dy, ny*dy], '--r', linewidth=lw2)
    ax.text(x + dl - 0.1, 0.23, 'III', color='red', fontsize=16,
            clip_on=False)
    x = x + 2*dl
    ax.plot([x, x], [-2*dy, ny*dy], '--r', linewidth=lw2)

    ax.axis([0.2, 4.5, -2*dy, 2*dy])

    ax.set_frame_on(True)
    ax.grid(True)
    ax.set_aspect('equal', adjustable='box')
    ax.axis('off')
    ax.tick_params(labelsize=16)
    for label in ax.get_xticklabels() + ax.get_yticklabels():
        label.set_fontweight('bold')

    # exportgraphics(gca,'/Users/mark/Desktop/floats.eps')
    # exportgraphics(gca,'/Users/mark/Desktop/floats2.eps','ContentType','vector')

    plt.show()


if __name__ == '__main__':
    fig1_5()
