Skip to content
Permalink
Branch: master
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
87 lines (68 sloc) 2.41 KB
#!/usr/bin/env python
# Using Python 2.7
"""max_cut_cirq.py: Demo code for Cirq implementation of QAOA"""
# Copyright 2018, QC Ware Corp.
import numpy as np # need to be able to define matrices and vectors!
# non-quantum imports
import networkx as nx
import pylab as plt
import warnings
# Import the qcware platform
import qcware
warnings.filterwarnings("ignore")
# Seed numpy for replicability
np.random.seed(2019) # 2019 chosen arbitarily
# Number of vertices.
N_v = 4
print "\nNumber of vertices = {0}\n".format(N_v)
# Define an n-vertex graph.
# N_v-vertex complete graph (==K_{N_v})
my_graph = nx.complete_graph(N_v)
# Print the graph definition
print "Vertex set:"
print my_graph.nodes
print "\nEdge set:"
print my_graph.edges
# Prepare some settings for the drawings..
pos = nx.spring_layout(my_graph)
fig, ax = plt.subplots(1, 2, num=1)
ax[0].set_title("Original Graph")
ax[1].set_title("Max Cut Solution via QC")
ax[1].set_frame_on(False)
ax[1].axes.get_xaxis().set_visible(False)
ax[1].axes.get_yaxis().set_visible(False)
# Output our original graph so we know what we started with
nx.draw(my_graph, pos, ax=ax[0])
# Define the QUBO, Q, to be solved.
# Convert the graph to matrix format so that we can perform operations
adj = nx.adjacency_matrix(my_graph).todense()
# Convert the matrix to the appropriate QUBO format
adj = -(np.diag(np.squeeze((np.matrix(adj) * np.ones([adj.shape[0], 1])).A)) -
np.matrix(adj)).astype(int)
Q = adj
# Define the solver to be used
solver = 'google_qaoa_simulator'
try:
r = qcware.optimization.solve_binary(
'API_KEY', Q, solver=solver,
cirq_arguments_optimizer={'init_point': 4, 'number_iter': 1, 'kappa': 2},
cirq_step_sampling=False, cirq_n_samples=65)
if 'solution' in r:
print('Solution: ' + str(r['solution']))
else:
print('Error: ' + r['error'])
except Exception, e:
print('Unhandled exception occurred: ' + str(e))
# Make figure using solution results
max_cut_partition = r["solution"]
nx.draw_networkx_nodes(
my_graph, pos,
nodelist=[i for i in range(len(max_cut_partition)) if max_cut_partition[i] == 1],
node_color='r', ax=ax[1])
nx.draw_networkx_nodes(
my_graph, pos,
nodelist=[i for i in range(len(max_cut_partition)) if max_cut_partition[i] == 0],
node_color='b', ax=ax[1])
# Output our solution graph
nx.draw_networkx_edges(my_graph, pos, ax=ax[1])
plt.show(fig)
You can’t perform that action at this time.