import numpy as np
import pandas as pd
from skimage import io
import skimage.measure as measure
import os
from lpg_pca_impl import denoise


def getNoisedImage(originalImage, variance):
    # return random_noise(originalImage, mode='gaussian', var=variance)
    np.random.seed(42)
    noise = np.random.normal(size=originalImage.shape)
    noise = noise/np.sqrt(np.power(noise, 2).mean())
    noisedImage = originalImage + variance*noise
    return noisedImage


def clip(img):
    img = np.minimum(np.ones(img.shape), img)
    img = np.maximum(np.zeros(img.shape), img)
    return img


def readImg(path):
    return io.imread(path, as_gray=True).astype('float64')/255.0


def showImg(img, name):
    print(name)
    img = clip(img)
    io.imshow((img*255.0).astype('uint8'))


def saveImg(img, path):
    img = clip(img)
    io.imsave(path, (img*255.0).astype('uint8'))


def compare_psnr(img1, img2):
    return measure.compare_psnr(img1, img2)


def compare_ssim(img1, img2):
    return measure.compare_ssim(img1, img2)


def generate_images(img_name='mri'):
    experiments_folder = 'experiments'
    noise_variances = [10, 20, 30, 40]

    for noise_variance in noise_variances:
        corrected_noise_variance = noise_variance / 255.0

        original_img = readImg(os.path.join('images', img_name + '.png'))

        noised_img = getNoisedImage(original_img, corrected_noise_variance)

        noised_file_name = img_name + '_noised_' + str(noise_variance) + '.png'
        saveImg(noised_img, os.path.join(experiments_folder, noised_file_name))
        print(noised_file_name + ' started.')

        denoised_img = denoise(noised_img, noise_variance)

        denoised_file_name = img_name + '_denoised_' + str(noise_variance) + '.png'
        saveImg(denoised_img, os.path.join(experiments_folder, denoised_file_name))
        print(denoised_file_name + ' finished.')

        print("noised PSNR: " + str(compare_psnr(original_img, noised_img)) + ", SSIM: " + str(compare_ssim(original_img, noised_img)))
        print("denoised PSNR: " + str(compare_psnr(original_img, denoised_img)) + ", SSIM: " + str(compare_ssim(original_img, denoised_img)))


def generate_latex_tables():
    df = pd.read_csv('data.csv')
    df = df.round(2)

    image_texts = np.array([])

    temp_directory = os.path.join(os.path.dirname(__file__), 'temp')
    if not os.path.exists(temp_directory):
        os.makedirs(temp_directory)

    for image_name in list(set(df['image_name'])):
        image_df = df[df['image_name'] == image_name]
        image_df['denoise_lpg_pca'] = image_df['denoise_psnr_lpg_pca'].map(str) + '(' + image_df['denoise_ssim_lpg_pca'].map(str) + ')'
        image_df['denoise_mf'] = image_df['denoise_psnr_mf'].map(str) + '(' + image_df['denoise_ssim_mf'].map(str) + ')'
        image_df['denoise_nlm'] = image_df['denoise_psnr_nlm'].map(str) + '(' + image_df['denoise_ssim_nlm'].map(str) + ')'
        image_df['denoise_bm3d'] = image_df['denoise_psnr_bm3d'].map(str) + '(' + image_df['denoise_ssim_bm3d'].map(str) + ')'
        image_df = image_df[['sigma', 'denoise_lpg_pca', 'denoise_mf', 'denoise_nlm', 'denoise_bm3d']]
        image_df['sigma'] = image_df['sigma'].map(int)
        image_df.columns = ['sigma', 'LPG-PCA', 'MF', "NLM", 'BM3D']

        path = os.path.join(temp_directory, image_name + '.tex')
        image_df.to_latex(path, index=False, column_format='lrrrr')

        with open(path, 'r') as file:
            image_text = file.read()
            image_text = image_text.replace(' ', '').replace(r'\toprule', r'\toprule &&' + image_name + r'\\ \midrule')
            image_text = r'\noindent\begin{minipage}{.5\linewidth}' + '\n' + image_text + '\n' + r'\end{minipage}'
            image_text = image_text.replace('\n\n', '\n').replace('sigma&', '$\\sigma$&')
            image_texts = np.append(image_texts, image_text)

        os.remove(path)

    result = '\n'.join(image_texts)

    filename = 'tables.tex'
    with open(filename, "w+") as file:
        file.write(result)

    if(len(os.listdir(temp_directory))) == 0:
        os.rmdir(temp_directory)

[((11, 4, 11, 22), 'numpy.random.seed', 'np.random.seed', ({(11, 19, 11, 21): '(42)'}, {}), '(42)', True, 'import numpy as np\n'), ((12, 12, 12, 54), 'numpy.random.normal', 'np.random.normal', (), '', True, 'import numpy as np\n'), ((40, 11, 40, 43), 'skimage.measure.compare_psnr', 'measure.compare_psnr', ({(40, 32, 40, 36): 'img1', (40, 38, 40, 42): 'img2'}, {}), '(img1, img2)', True, 'import skimage.measure as measure\n'), ((44, 11, 44, 43), 'skimage.measure.compare_ssim', 'measure.compare_ssim', ({(44, 32, 44, 36): 'img1', (44, 38, 44, 42): 'img2'}, {}), '(img1, img2)', True, 'import skimage.measure as measure\n'), ((73, 9, 73, 32), 'pandas.read_csv', 'pd.read_csv', ({(73, 21, 73, 31): '"""data.csv"""'}, {}), "('data.csv')", True, 'import pandas as pd\n'), ((76, 18, 76, 30), 'numpy.array', 'np.array', ({(76, 27, 76, 29): '[]'}, {}), '([])', True, 'import numpy as np\n'), ((19, 21, 19, 39), 'numpy.ones', 'np.ones', ({(19, 29, 19, 38): 'img.shape'}, {}), '(img.shape)', True, 'import numpy as np\n'), ((20, 21, 20, 40), 'numpy.zeros', 'np.zeros', ({(20, 30, 20, 39): 'img.shape'}, {}), '(img.shape)', True, 'import numpy as np\n'), ((62, 23, 62, 58), 'lpg_pca_impl.denoise', 'denoise', ({(62, 31, 62, 41): 'noised_img', (62, 43, 62, 57): 'noise_variance'}, {}), '(noised_img, noise_variance)', False, 'from lpg_pca_impl import denoise\n'), ((78, 34, 78, 59), 'os.path.dirname', 'os.path.dirname', ({(78, 50, 78, 58): '__file__'}, {}), '(__file__)', False, 'import os\n'), ((79, 11, 79, 41), 'os.path.exists', 'os.path.exists', ({(79, 26, 79, 40): 'temp_directory'}, {}), '(temp_directory)', False, 'import os\n'), ((80, 8, 80, 35), 'os.makedirs', 'os.makedirs', ({(80, 20, 80, 34): 'temp_directory'}, {}), '(temp_directory)', False, 'import os\n'), ((92, 15, 92, 64), 'os.path.join', 'os.path.join', ({(92, 28, 92, 42): 'temp_directory', (92, 44, 92, 63): "image_name + '.tex'"}, {}), "(temp_directory, image_name + '.tex')", False, 'import os\n'), ((102, 8, 102, 23), 'os.remove', 'os.remove', ({(102, 18, 102, 22): 'path'}, {}), '(path)', False, 'import os\n'), ((111, 8, 111, 32), 'os.rmdir', 'os.rmdir', ({(111, 17, 111, 31): 'temp_directory'}, {}), '(temp_directory)', False, 'import os\n'), ((54, 31, 54, 72), 'os.path.join', 'os.path.join', ({(54, 44, 54, 52): '"""images"""', (54, 54, 54, 71): "img_name + '.png'"}, {}), "('images', img_name + '.png')", False, 'import os\n'), ((59, 28, 59, 78), 'os.path.join', 'os.path.join', ({(59, 41, 59, 59): 'experiments_folder', (59, 61, 59, 77): 'noised_file_name'}, {}), '(experiments_folder, noised_file_name)', False, 'import os\n'), ((65, 30, 65, 82), 'os.path.join', 'os.path.join', ({(65, 43, 65, 61): 'experiments_folder', (65, 63, 65, 81): 'denoised_file_name'}, {}), '(experiments_folder, denoised_file_name)', False, 'import os\n'), ((100, 26, 100, 60), 'numpy.append', 'np.append', ({(100, 36, 100, 47): 'image_texts', (100, 49, 100, 59): 'image_text'}, {}), '(image_texts, image_text)', True, 'import numpy as np\n'), ((110, 11, 110, 37), 'os.listdir', 'os.listdir', ({(110, 22, 110, 36): 'temp_directory'}, {}), '(temp_directory)', False, 'import os\n'), ((25, 11, 25, 40), 'skimage.io.imread', 'io.imread', (), '', False, 'from skimage import io\n'), ((13, 26, 13, 44), 'numpy.power', 'np.power', ({(13, 35, 13, 40): 'noise', (13, 42, 13, 43): '(2)'}, {}), '(noise, 2)', True, 'import numpy as np\n')]