import numpy as np

from qiskit import Aer

from qiskit_aqua import run_algorithm
from qiskit_aqua.input import EnergyInput
from qiskit_aqua.translators.ising import clique
from qiskit_aqua.algorithms import ExactEigensolver

K = 3  # K means the size of the clique
np.random.seed(100)
num_nodes = 5
w = clique.random_graph(num_nodes, edge_prob=0.8, weight_range=10)
print(w) 

def brute_force():
    # brute-force way: try every possible assignment!
    def bitfield(n, L):
        result = np.binary_repr(n, L)
        return [int(digit) for digit in result]

    L = num_nodes  # length of the bitstring that represents the assignment
    max = 2**L
    has_sol = False
    for i in range(max):
        cur = bitfield(i, L)
        cur_v = clique.satisfy_or_not(np.array(cur), w, K)
        if cur_v:
            has_sol = True
            break
    return has_sol, cur

has_sol, sol = brute_force()
if has_sol:
    print("solution is ", sol)
else:
    print("no solution found for K=", K)

qubit_op, offset = clique.get_clique_qubitops(w, K)
algo_input = EnergyInput(qubit_op)
params = {
    'problem': {'name': 'ising'},
    'algorithm': {'name': 'ExactEigensolver'}
}
result = run_algorithm(params, algo_input)
x = clique.sample_most_likely(len(w), result['eigvecs'][0])
ising_sol = clique.get_graph_solution(x)
if clique.satisfy_or_not(ising_sol, w, K):
    print("solution is", ising_sol)
else:
    print("no solution found for K=", K)


algo = ExactEigensolver(algo_input.qubit_op, k=1, aux_operators=[])
result = algo.run()
x = clique.sample_most_likely(len(w), result['eigvecs'][0])
ising_sol = clique.get_graph_solution(x)
if clique.satisfy_or_not(ising_sol, w, K):
    print("solution is", ising_sol)
else:
    print("no solution found for K=", K)     

algorithm_cfg = {
    'name': 'VQE',
    'operator_mode': 'matrix'
}

optimizer_cfg = {
    'name': 'COBYLA'
}

var_form_cfg = {
    'name': 'RY',
    'depth': 5,
    'entanglement': 'linear'
}

params = {
    'problem': {'name': 'ising', 'random_seed': 10598},
    'algorithm': algorithm_cfg,
    'optimizer': optimizer_cfg,
    'variational_form': var_form_cfg
}
backend = Aer.get_backend('statevector_simulator')
result = run_algorithm(params, algo_input, backend=backend)
x = clique.sample_most_likely(len(w), result['eigvecs'][0])
ising_sol = clique.get_graph_solution(x)

if clique.satisfy_or_not(ising_sol, w, K):
    print("solution is", ising_sol)
else:
    print("no solution found for K=", K)