from pathlib import Path

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


def fig4_9(image_filename="p17.jpg"):
    # read in image and calculate svd
    image_path = Path(__file__).resolve().parent / image_filename
    x = np.asarray(Image.open(image_path).convert("L"))
    A = x.astype(float)
    U, S, Vh = np.linalg.svd(A, full_matrices=False)
    sigma = S.copy()
    V = Vh.T
    ss = A.shape
    print(f"ss = {ss}")

    # determine singular values
    rs = min(ss[0], ss[1])
    print(f"rs = {rs}")
    id_values = np.zeros(rs)
    sigmas = np.zeros(rs)
    E = np.zeros(rs)
    for i in range(rs):
        id_values[i] = i + 1
        sigmas[i] = sigma[i]
        E[i] = sigmas[i] / sigmas[0]

    id_values = np.arange(1, ss[1] + 1)
    err = sigmas[0 : ss[1]] / sigmas[0]

    plt.close("all")
    # get(gcf)
    fig, ax = plt.subplots(figsize=(6.58, 2.30))
    fig.subplots_adjust(top=0.97, bottom=0.23, right=0.98, left=0.10)
    co = [
        (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(cycler(color=co))

    ax.semilogy(id_values, err, "r", linewidth=1.5)
    ax.set_yticks([1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1])
    ax.set_xlabel("k-axis", fontsize=14)
    ax.set_ylabel("Error", fontsize=14)
    ax.grid(True, which="major")
    ax.grid(False, which="minor", axis="y")
    for spine in ax.spines.values():
        spine.set_visible(True)
    ax.tick_params(labelsize=14)
    for label in ax.get_xticklabels() + ax.get_yticklabels():
        label.set_fontweight("bold")
    ax.xaxis.label.set_fontweight("bold")
    ax.yaxis.label.set_fontweight("bold")

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


if __name__ == "__main__":
    fig4_9()
