import itertools
import matplotlib.pyplot as plt
import networkx as nx
from qiskit_optimization import QuadraticProgram
from qiskit_optimization.converters import QuadraticProgramToQubo
from dwave.system import DWaveSampler, FixedEmbeddingComposite
import dimod
import dwave_networkx as dnx
from minorminer import find_embedding
import dwave.inspector

# select quadratic program to solve
qp = QuadraticProgram()
qp.read_from_lp_file("example.lp")
qubo = QuadraticProgramToQubo().convert(qp)
bqm_binary = dimod.as_bqm(qubo.objective.linear.to_array(), qubo.objective.quadratic.to_array(), dimod.BINARY)
print(qp)
print(bqm_binary)
bqm_ising = bqm_binary.to_ising()
print("Ising Model form coefficients:")
print(bqm_ising)

sampler_exact = dimod.ExactSolver()
sampleset = sampler_exact.sample(bqm_binary)
print(sampleset)

G = bqm_binary.to_networkx_graph()
P_16 = dnx.pegasus_graph(16)
embedding = find_embedding(G, P_16, timeout=60, tries=50)
P_16_sub = P_16.subgraph(list(itertools.chain(*embedding.values())))

plt.figure(figsize=(4,4)) 
dnx.draw_pegasus(P_16_sub, node_size=500, node_color='g')

structured_sampler = dimod.StructureComposite(DWaveSampler(), P_16.nodes, P_16.edges)
sampler = FixedEmbeddingComposite(structured_sampler, embedding=embedding)
res = sampler.sample(bqm_binary, label="example_qubo_3", num_reads=100)
res.to_pandas_dataframe()

dwave.inspector.show(res)

