import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

pd.set_option('display.max_rows', None)
pd.set_option('display.max_columns', None)
pd.set_option('display.width', None)
pd.set_option('display.max_colwidth', -1)

df = pd.read_csv("../../Data/Processed/iriscost.csv")

df.columns = ['Spec', "CostValues"]

df.head(1)

df['Spec']

def check_lowest_cost(df):
    """
    Checks the configs which attained the lowest sost
    """
    cost = []
    lowest_cost = []
    for i in range(df.shape[0]):
        data = [float(x.replace("[", "").replace("]", "")) for x in df['CostValues'][i].split(',')]
        lowest_cost.append(data[len(data) - 1])
        
    lowest_cost = sorted(lowest_cost)[:10]
    for m in lowest_cost:
        for i in range(df.shape[0]):
            data = df['CostValues'][i].split(',')
            data = [float(x.replace("[", "").replace("]", "")) for x in data]
            if float(m) == float(data[len(data) - 1]):
                print("{} : Cost: {}".format(df["Spec"][i], data[len(data) - 1]))
        cost.append(data[len(data) - 1])
    #df['CostValues'] = []
    #df.to_excel("n.xlsx")
    # print(df.head(80))
    

check_lowest_cost(df)

# Plotting all 
for i in range(df.shape[0]):
    fig = plt.figure()
    data = df['CostValues'][i].split(',')
    data = [float(x.replace("[", "").replace("]", "")) for x in data]
    plt.plot(range(0, len(data), 1), data)
    plt.xlabel('Steps')
    plt.ylabel('Cost value')
    plt.title(str(df['Spec'][i]))
    plt.show()
    path = '../../Output/Figures/{}.jpeg'.format(df['Spec'][i].replace("(", "").replace("FeatureMap", "").replace(")", "").replace(",", "").replace("=", "").replace(" ", "").replace("_", ""))
    # fig.savefig(path)

def plot_individual_optimizers(Optimizers):
    for opt in Optimizers:
        max_iter = 0
        fig = plt.figure(figsize=(20,20))
        for i in range(df.shape[0]):
            if df['Spec'][i].__contains__(opt):
                data = [float(x.replace("[", "").replace("]", "")) for x in df['CostValues'][i].split(',')]
                if len(data) >= max_iter:
                    max_iter = len(data)

        for i in range(df.shape[0]):
            if df['Spec'][i].__contains__(opt):
                data = df['CostValues'][i].split(',')
                data = [float(x.replace("[", "").replace("]", "")) for x in data]
                if max_iter >= len(data):
                    temp = np.full((max_iter, ), data[len(data) -1])
                    temp[:len(data)] = data
                    data = temp                    
                plt.plot(range(0, len(data), 1), data, label='{}'.format(df['Spec'][i].replace("(", "").replace("FeatureMap", "").replace(")", "").replace(",", "").replace("=", "").replace(" ", "").replace("_", "")))
        plt.xlabel('Steps')
        plt.ylabel('Cost value')
        plt.title(opt)
        plt.legend()
        plt.show()


plot_individual_optimizers(["COBYLA", "SPSA", "ADAM"])

def plot_increase_vdepth(optimizer, featuremap, reps, checking):
    points = []
    for i in range(df.shape[0]):
        title = str(df['Spec'][i])
        if title.split("(")[0] == featuremap and str(title).__contains__(optimizer) and str(title).__contains__("reps={}".format(reps)):
            points.append(float(df['CostValues'][i].split(',')[-1].replace("[", "").replace("]", "")))
    fig = plt.figure()
    plt.plot(range(0, len(points), 1), points)
    plt.xlabel(checking)
    plt.ylabel('Cost value')
    plt.title("{} {} featuremap {} fdepth".format(optimizer, featuremap, reps))
    plt.show()

def plot_increase_fdepth(optimizer, featuremap, fdepth, checking):
    points = []
    for i in range(df.shape[0]):
        title = str(df['Spec'][i])
        if title.split("(")[0] == featuremap and str(title).__contains__(optimizer) and str(title).__contains__("vdepth {}".format(fdepth)):
            points.append(float(df['CostValues'][i].split(',')[-1].replace("[", "").replace("]", "")))
    fig = plt.figure()
    plt.plot(range(0, len(points), 1), points)
    plt.xlabel(checking)
    plt.ylabel('Cost value')
    plt.title("{} {} featuremap {} vdepth".format(optimizer, featuremap, fdepth))
    plt.show()

plot_increase_vdepth("SPSA", "PauliFeatureMap", 1, "fdepth")

plot_increase_fdepth("SPSA", "PauliFeatureMap", 1, "vdepth")

for opt in ['SPSA', "COBYLA", "ADAM"]:
    for fmap in ['ZZFeatureMap', 'ZFeatureMap', "PauliFeatureMap"]:
        for fdepth in [1, 2, 4]:
            plot_increase_vdepth(opt, fmap, fdepth, "vdepth")

for opt in ['SPSA', "COBYLA", "ADAM"]:
    for fmap in ['ZZFeatureMap', 'ZFeatureMap', "PauliFeatureMap"]:
        for fdepth in [1, 3, 5]:
            plot_increase_fdepth(opt, fmap, fdepth, "fdepth")

