forked from quantumlib/Cirq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqaoa.py
168 lines (140 loc) · 8.3 KB
/
qaoa.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# pylint: disable=wrong-or-nonexistent-copyright-notice
"""Runs the Quantum Approximate Optimization Algorithm on Max-Cut.
=== EXAMPLE OUTPUT ===
Example QAOA circuit:
0 1 2 3 4 5
│ │ │ │ │ │
H H H H H H
│ │ │ │ │ │
ZZ──────────ZZ^(-4/13) │ │ │ │
┌ │ │ │ │ │ │ ┐
│ ZZ──────────┼───────────ZZ^(-4/13) │ │ │ │
│ │ ZZ──────────┼───────────ZZ^(-4/13) │ │ │
└ │ │ │ │ │ │ ┘
┌ │ │ │ │ │ │ ┐
│ ZZ──────────┼───────────┼───────────┼───────────ZZ^(-4/13) │ │
│ │ ZZ──────────┼───────────┼───────────┼───────────ZZ^(-4/13) │
└ │ │ │ │ │ │ ┘
Rx(0.151π) Rx(0.151π) ZZ──────────┼───────────ZZ^(-4/13) │
│ │ │ │ │ │
ZZ──────────ZZ^-0.941 ZZ──────────┼───────────┼───────────ZZ^(-4/13)
│ │ │ ZZ──────────ZZ^(-4/13) │
┌ │ │ │ │ │ │ ┐
│ │ │ Rx(0.151π) ZZ──────────┼───────────ZZ^(-4/13) │
│ │ │ │ │ Rx(0.151π) │ │
└ │ │ │ │ │ │ ┘
ZZ──────────┼───────────ZZ^-0.941 Rx(0.151π) │ Rx(0.151π)
┌ │ │ │ │ │ │ ┐
│ ZZ──────────┼───────────┼───────────┼───────────ZZ^-0.941 │ │
│ │ ZZ──────────┼───────────ZZ^-0.941 │ │ │
└ │ │ │ │ │ │ ┘
Rx(-0.448π) ZZ──────────┼───────────┼───────────┼───────────ZZ^-0.941
│ │ ZZ──────────┼───────────ZZ^-0.941 │
│ │ │ │ │ │
│ Rx(-0.448π) ZZ──────────┼───────────┼───────────ZZ^-0.941
│ │ │ ZZ──────────ZZ^-0.941 │
┌ │ │ │ │ │ │ ┐
│ │ │ Rx(-0.448π) ZZ──────────┼───────────ZZ^-0.941 │
│ │ │ │ │ Rx(-0.448π) │ │
└ │ │ │ │ │ │ ┘
│ │ │ Rx(-0.448π) │ Rx(-0.448π)
│ │ │ │ │ │
M('m')──────M───────────M───────────M───────────M───────────M
│ │ │ │ │ │
Optimizing objective function ...
The largest cut value found was 7.
The largest possible cut has size 7.
The approximation ratio achieved is 1.0.
"""
import itertools
import numpy as np
import networkx
import scipy.optimize
import cirq
def main(repetitions=10, maxiter=50, use_boolean_hamiltonian_gate=False):
# Set problem parameters
n = 6
p = 2
# Generate a random 3-regular graph on n nodes
graph = networkx.random_regular_graph(3, n)
# Make qubits
qubits = cirq.LineQubit.range(n)
# Print an example circuit
betas = np.random.uniform(-np.pi, np.pi, size=p)
gammas = np.random.uniform(-np.pi, np.pi, size=p)
circuit = qaoa_max_cut_circuit(qubits, betas, gammas, graph, use_boolean_hamiltonian_gate)
print('Example QAOA circuit:')
print(circuit.to_text_diagram(transpose=True))
# Create variables to store the largest cut and cut value found
largest_cut_found = None
largest_cut_value_found = 0
# Initialize simulator
simulator = cirq.Simulator()
# Define objective function (we'll use the negative expected cut value)
def f(x):
# Create circuit
betas = x[:p]
gammas = x[p:]
circuit = qaoa_max_cut_circuit(qubits, betas, gammas, graph, use_boolean_hamiltonian_gate)
# Sample bitstrings from circuit
result = simulator.run(circuit, repetitions=repetitions)
bitstrings = result.measurements['m']
# Process bitstrings
nonlocal largest_cut_found
nonlocal largest_cut_value_found
values = cut_values(bitstrings, graph)
max_value_index = np.argmax(values)
max_value = values[max_value_index]
if max_value > largest_cut_value_found:
largest_cut_value_found = max_value
largest_cut_found = bitstrings[max_value_index]
mean = np.mean(values)
return -mean
# Pick an initial guess
x0 = np.random.uniform(-np.pi, np.pi, size=2 * p)
# Optimize f
print('Optimizing objective function ...')
scipy.optimize.minimize(f, x0, method='Nelder-Mead', options={'maxiter': maxiter})
# Compute best possible cut value via brute force search
all_bitstrings = np.array(list(itertools.product(range(2), repeat=n)))
all_values = cut_values(all_bitstrings, graph)
max_cut_value = np.max(all_values)
# Print the results
print(f'The largest cut value found was {largest_cut_value_found}.')
print(f'The largest possible cut has size {max_cut_value}.')
print(f'The approximation ratio achieved is {largest_cut_value_found / max_cut_value}.')
def rzz(rads):
"""Returns a gate with the matrix exp(-i Z⊗Z rads)."""
return cirq.ZZPowGate(exponent=2 * rads / np.pi, global_shift=-0.5)
def qaoa_max_cut_unitary(
qubits, betas, gammas, graph, use_boolean_hamiltonian_gate
): # Nodes should be integers
if use_boolean_hamiltonian_gate:
booleans = [f"x{i} ^ x{j}" for i, j in sorted(graph.edges)]
param_names = [f"x{i}" for i in range(len(qubits))]
for beta, gamma in zip(betas, gammas):
yield cirq.BooleanHamiltonianGate(param_names, booleans, 2.0 * gamma).on(*qubits)
yield cirq.rx(2 * beta).on_each(*qubits)
else:
for beta, gamma in zip(betas, gammas):
yield (rzz(-0.5 * gamma).on(qubits[i], qubits[j]) for i, j in graph.edges)
yield cirq.rx(2 * beta).on_each(*qubits)
def qaoa_max_cut_circuit(
qubits, betas, gammas, graph, use_boolean_hamiltonian_gate
): # Nodes should be integers
return cirq.Circuit(
# Prepare uniform superposition
cirq.H.on_each(*qubits),
# Apply QAOA unitary
qaoa_max_cut_unitary(qubits, betas, gammas, graph, use_boolean_hamiltonian_gate),
# Measure
cirq.measure(*qubits, key='m'),
)
def cut_values(bitstrings, graph):
mat = networkx.adjacency_matrix(graph, nodelist=sorted(graph.nodes))
vecs = (-1) ** bitstrings
vals = 0.5 * np.sum(vecs * (mat @ vecs.T).T, axis=-1)
vals = 0.5 * (graph.size() - vals)
return vals
if __name__ == '__main__':
main()