Quantum Annealing Optimization API
import networkx as nx
n = 6
g = nx.star_graph(n-1)
seed = 1967
positions = nx.spring_layout(g, seed=seed)
nx.draw(g, with_labels=True, pos=positions)
qo = QuantumAnnealer(g, task='minimum_vertex_cover')
qo.execute()
nodes = qo.results()
nodes
sub = g.subgraph(nodes)
nx.draw(g, pos=positions, with_labels=True)
nx.draw(sub, pos=positions, node_color="r", edge_color="r")
assert set(nodes) == set([0])
Using a BinaryQuadraticModel
For more flexibility, you can formulate your task as a quadratic unconstrained binary optimization problem (QUBO) and supply that to QuantumAnnealer
instead. Here, we will solve the same minimum vertex cover problem by formulating it as a QUBO expressed as a Python dictionary. See this reference for more details on how to formulate problems as binary quadratic models.
cost = dict(g.nodes(data=None, default=1))
scale = max(cost.values())
Q = {(node, node): min(-cost[node] / scale, 0.0) for node in g}
Q.update({edge: 2.0 for edge in g.edges}) # use 2.0 as "tuning" LaGrange value for this problem
# solve qubo
independent_set = QuantumAnnealer(qubo=Q).execute().results()
# nodes NOT in the independent set comprise the minimum vertex cover
solution_nodes = [v for v in g if v not in independent_set]
assert set(solution_nodes) == set([0])
# plot solution as graph
sub = g.subgraph(solution_nodes)
nx.draw(g, pos=positions, with_labels=True)
nx.draw(sub, pos=positions, node_color="r", edge_color="r")