from qiskit.optimization import QuadraticProgram
from qiskit.optimization.algorithms import MinimumEigenOptimizer

from dwave.plugins.qiskit import DWaveMinimumEigensolver
from dwave.system import DWaveCliqueSampler, LeapHybridSampler

import numpy as np

A = np.array([[0,1,2,3,4,1],
              [2,1,4,1,0,2],
              [1,5,2,3,1,1],
              [0,0,1,2,2,0]])
m, n = A.shape
c =  np.array([-1,2,-2,2,1,1])
b = np.array([6,8,5,2])

solution = np.array([2,0,0,0,1,2])

print(all(A.dot(solution) == b))

model = QuadraticProgram("Integer Test")
lowerbound = 0
upperbound = 7 

# add variables
x = [model.integer_var(lowerbound = lowerbound, upperbound = upperbound, name = 'x'+str(j)) for j in range(n)]

# add linear constraints
for i in range(m):
    model.linear_constraint(linear=A[i], sense='==', rhs=b[i], name='A'+str(i)+'eq'+'b'+str(i))
    
# add linear objective function

model.minimize(linear = c)

print(model.export_as_lp_string())

# Use D-Wave QPU as a minimum eigen solver
# See https://github.com/dwavesystems/dwave-qiskit-plugin
num_reads = 1000
cliqueSampler = DWaveCliqueSampler()
dwave_solver_clique = DWaveMinimumEigensolver(sampler = cliqueSampler, num_reads = num_reads)
optimizer = MinimumEigenOptimizer(dwave_solver_clique)


result = optimizer.solve(model) # Problem ID : f684f451-2f9d-4ebd-ad84-983ac989838b

print(result)

result.min_eigen_solver_result.sampleset.to_pandas_dataframe()

dwave_solver_hybrid = DWaveMinimumEigensolver(sampler =  LeapHybridSampler())
optimizer = MinimumEigenOptimizer(dwave_solver_hybrid)

result = optimizer.solve(model) # Problem ID : cef4cc6d-8686-4491-8eb7-3fdbba3b7ec2

print(result)

result.min_eigen_solver_result.sampleset.to_pandas_dataframe()

