from tsp_qaoa import test_solution
from qiskit.visualization import plot_histogram
import networkx as nx
import numpy as np
import json
import csv
# Array of JSON Objects

header = ['instance','p','distance', 'mean']
length_p = 3
length_instances = 2


with open('qaoa_multiple_p_distance.csv', 'w', encoding='UTF8') as f:
    writer = csv.writer(f)

    # write the header
    writer.writerow(header)
    
    
    instance_index = 0
    for instance in range(length_instances):
        instance_index += 1
        first_p = False
        UNIFORM_CONVERGENCE_P = []
        UNIFORM_CONVERGENCE_SAMPLE = []
        for p in range(length_p):
            p = p+1
            if first_p == False:
                print("Vuelve a llamar a test_solution")
                job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution(p=p)
                first_p = True
            else:
                job_2, G, UNIFORM_CONVERGENCE_SAMPLE = test_solution(grafo=G, p=p)

            # Sort the JSON data based on the value of the brand key
            UNIFORM_CONVERGENCE_SAMPLE.sort(key=lambda x: x["mean"])
            convergence_min = UNIFORM_CONVERGENCE_SAMPLE[0]
            UNIFORM_CONVERGENCE_P.append({
                "mean":convergence_min["mean"],
                "probabilities": convergence_min["probabilities"]
            })
        
        cauchy_function_nk = UNIFORM_CONVERGENCE_P[len(UNIFORM_CONVERGENCE_P) - 1]
        p_index = 0
        for p_state in UNIFORM_CONVERGENCE_P:
            p_index += 1
            print(p_index)
            mean = p_state["mean"]
            print(p_state)
            print(mean)
            distance_p_cauchy_function_nk = np.max(np.abs(cauchy_function_nk["probabilities"] - p_state["probabilities"]))
            writer.writerow([instance_index, p_index, distance_p_cauchy_function_nk, mean])
        
    
    
    

