from collections import OrderedDict
import time
import logging, warnings

from qiskit.optimization.algorithms import CplexOptimizer
from qiskit.optimization.algorithms.optimization_algorithm import OptimizationResultStatus

from random_lp.lp_random_gen import create_models
from utilities.helpers import create_qaoa_meo

logger = logging.getLogger()
logger.setLevel(logging.INFO)
warnings.filterwarnings("ignore", category=DeprecationWarning)


DIR = 'TEST_DATA' + "/" + time.strftime("%d_%m_%Y")
DIR

qps = create_models([DIR + "/DENSE/", DIR + "/SPARSE/"])
print(qps.keys())

cplex = CplexOptimizer()
qaoa = create_qaoa_meo()

max_qubits = qaoa.min_eigen_solver.quantum_instance.backend.configuration().to_dict()['n_qubits']
max_qubits

results = OrderedDict()
for qp_name, qp in qps.items() :
    print(qp_name)
    print("number of qubits: ", qp.qubo.get_num_vars())
    if qp.qubo.get_num_vars() > max_qubits:
        print("Too many qubits!")
        break
        
    
    res = qaoa.solve(qp)
    results[qp_name] = res
    if res.status == OptimizationResultStatus.SUCCESS:
        print("success")
        cres  = cplex.solve(qp)
        if res.fval != cres.fval:
            print("\n optimal value QAOA   "+str(res.fval) + "  ,  cplex:"+ str(cres.fval))
    else:
        print(res.status)

