QAOATester.cpp 12.7 KB
Newer Older
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
1
2
3
4
5
6
7
8
9
10
11
12
/*******************************************************************************
 * Copyright (c) 2020 UT-Battelle, LLC.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * and Eclipse Distribution License v1.0 which accompanies this
 * distribution. The Eclipse Public License is available at
 * http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution
 *License is available at https://eclipse.org/org/documents/edl-v10.php
 *
 * Contributors:
 *   Thien Nguyen - initial API and implementation
 *******************************************************************************/
13
#include <random>
14
#include <gtest/gtest.h>
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
15
16
17

#include "xacc.hpp"
#include "Algorithm.hpp"
18
19
#include "Observable.hpp"
#include "xacc_service.hpp"
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
20
#include "xacc_observable.hpp"
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
21
22
23

using namespace xacc;

24
TEST(QAOATester, checkSimple) {
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
25
  auto acc = xacc::getAccelerator("qpp");
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
26
  auto buffer = xacc::qalloc(2);
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
27

Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
28
  auto optimizer = xacc::getOptimizer("nlopt");
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
29
  auto qaoa = xacc::getService<Algorithm>("QAOA");
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
30
31
32
33
34
  // Create deuteron Hamiltonian
  auto H_N_2 = xacc::quantum::getObservable(
      "pauli", std::string("5.907 - 2.1433 X0X1 "
                           "- 2.1433 Y0Y1"
                           "+ .21829 Z0 - 6.125 Z1"));
35
36
37
38
39
  EXPECT_TRUE(qaoa->initialize({std::make_pair("accelerator", acc),
                                std::make_pair("optimizer", optimizer),
                                std::make_pair("observable", H_N_2),
                                // number of time steps (p) param
                                std::make_pair("steps", 2)}));
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
40
  qaoa->execute(buffer);
41
42

  // The optimal value (minimal energy) must be less than -1.74886
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
43
44
45
46
  // which is the result from VQE using a physical ansatz.
  // In QAOA, we don't have any physical constraints, hence,
  // it can find a solution that gives a lower cost function value.
  std::cout << "Opt-val = " << (*buffer)["opt-val"].as<double>() << "\n";
47
  EXPECT_LT((*buffer)["opt-val"].as<double>(), -1.54);
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
48
49
}

50
TEST(QAOATester, checkStandardParamterizedScheme) {
51
52
53
54
55
56
57
58
59
60
61
  auto acc = xacc::getAccelerator("qpp");
  auto buffer = xacc::qalloc(2);

  auto optimizer = xacc::getOptimizer("nlopt");
  auto qaoa = xacc::getService<Algorithm>("QAOA");
  // Create deuteron Hamiltonian
  auto H_N_2 = xacc::quantum::getObservable(
      "pauli", std::string("5.907 - 2.1433 X0X1 "
                           "- 2.1433 Y0Y1"
                           "+ .21829 Z0 - 6.125 Z1"));
  EXPECT_TRUE(
62
      qaoa->initialize({std::make_pair("accelerator", acc),
63
64
65
66
                        std::make_pair("optimizer", optimizer),
                        std::make_pair("observable", H_N_2),
                        // number of time steps (p) param
                        std::make_pair("steps", 4),
67
                        std::make_pair("parameter-scheme", "Standard")}));
68
69
  qaoa->execute(buffer);
  std::cout << "Opt-val = " << (*buffer)["opt-val"].as<double>() << "\n";
Mccaskey, Alex's avatar
Mccaskey, Alex committed
70
  EXPECT_LT((*buffer)["opt-val"].as<double>(), -1.58);
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
// Generate rando
auto random_vector(const double l_range, const double r_range,
                   const std::size_t size) {
  // Generate a random initial parameter set
  std::random_device rnd_device;
  std::mt19937 mersenne_engine{rnd_device()}; // Generates random integers
  std::uniform_real_distribution<double> dist{l_range, r_range};
  auto gen = [&dist, &mersenne_engine]() { return dist(mersenne_engine); };
  std::vector<double> vec(size);
  std::generate(vec.begin(), vec.end(), gen);
  return vec;
}

TEST(QAOATester, checkP1TriangleGraph) {
  auto acc = xacc::getAccelerator("aer", {{"sim-type", "statevector"}});
  auto optimizer = xacc::getOptimizer(
      "nlopt",
      {{"maximize", true}, {"initial-parameters", random_vector(-2., 2., 2)}});
  auto H = xacc::quantum::getObservable(
      "pauli", std::string("1.5 I - 0.5 Z0 Z1 - 0.5 Z0 Z2 - 0.5 Z1 Z2"));
  auto qaoa = xacc::getAlgorithm("QAOA", {{"accelerator", acc},
                                          {"optimizer", optimizer},
                                          {"observable", H},
                                          {"steps", 1},
                                          {"parameter-scheme", "Standard"}});
 auto all_betas =
      xacc::linspace(-xacc::constants::pi / 4., xacc::constants::pi / 4., 20);
  auto all_gammas = xacc::linspace(-xacc::constants::pi, xacc::constants::pi, 20);
  for (auto gamma : all_gammas) {
    for (auto beta : all_betas) {
      auto buffer = xacc::qalloc(3);
      auto cost =
          qaoa->execute(buffer, std::vector<double>{gamma, beta})[0];
      auto d = 1;
      auto e = 1;
      auto f = 1;
      auto theory = 3 * (.5 +
                         .25 * std::sin(4 * beta) * std::sin(gamma) *
                             (std::cos(gamma) + std::cos(gamma)) -
                         .25 * std::sin(2 * beta) * std::sin(2 * beta) *
                             (std::pow(std::cos(gamma), d + e - 2 * f)) *
                             (1 - std::cos(2 * gamma)));
      EXPECT_NEAR(cost, theory, 1e-3);
    }
  }
}

120
121
122
123
124
125
126
// Making sure that a set of Hadamards can be passed
// as the "initial-state" to the QAOA algorithm and 
// the proper result is returned
TEST(QAOATester, checkInitialStateConstruction) {
  auto acc = xacc::getAccelerator("qpp");
  auto buffer = xacc::qalloc(2);

127
  auto optimizer = xacc::getOptimizer("nlopt",  {{"initial-parameters", random_vector(-2., 2., 12)}});
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
  auto qaoa = xacc::getService<Algorithm>("QAOA");
  // Create deuteron Hamiltonian
  auto H_N_2 = xacc::quantum::getObservable(
      "pauli", std::string("5.907 - 2.1433 X0X1 "
                           "- 2.1433 Y0Y1"
                           "+ .21829 Z0 - 6.125 Z1"));

  auto provider = getIRProvider("quantum");
  auto initial_program = provider->createComposite("qaoaKernel");
  for (size_t i = 0; i < buffer->size(); i++) {
    initial_program->addInstruction(provider->createInstruction("H", { i }));
  }
  EXPECT_TRUE(
      qaoa->initialize({std::make_pair("accelerator", acc),
                        std::make_pair("optimizer", optimizer),
                        std::make_pair("observable", H_N_2),
                        // number of time steps (p) param
145
                        std::make_pair("steps", 6),
146
147
148
149
                        std::make_pair("initial-state", initial_program),
                        std::make_pair("parameter-scheme", "Standard")}));
  qaoa->execute(buffer);
  std::cout << "Opt-val = " << (*buffer)["opt-val"].as<double>() << "\n";
Mccaskey, Alex's avatar
Mccaskey, Alex committed
150
  EXPECT_LT((*buffer)["opt-val"].as<double>(), -1.5);
151
152
153
154
155
156
157
158
159
160
161
}


// Making sure that warm-starts can be initialized and run.
// TODO: Check that there are the same amount of either Rx or Rz
// gates as there are qubits. (Each qubit is assigned an Rx and Rz)
TEST(QAOATester, checkWarmStarts) {
  auto acc = xacc::getAccelerator("qpp");
  auto buffer = xacc::qalloc(3);
  int size = buffer->size();
  auto optimizer = xacc::getOptimizer("nlopt", {{"maximize",true},{"initial-parameters", random_vector(-2., 2., 2)}});
Santana, Anthony's avatar
Santana, Anthony committed
162
  auto qaoa = xacc::getService<Algorithm>("maxcut-qaoa");
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
  auto graph = xacc::getService<xacc::Graph>("boost-digraph");

  // Triangle graph
  for (int i = 0; i < 3; i++) {
    graph->addVertex();
  }
  graph->addEdge(0, 1);
  graph->addEdge(0, 2);
  graph->addEdge(1, 2);

  const bool initOk = qaoa->initialize(
      {std::make_pair("accelerator", acc),
       std::make_pair("optimizer", optimizer), 
       std::make_pair("graph", graph),
       // number of time steps (p) param
       std::make_pair("steps", 1),
       // "Standard" or "Extended"
       std::make_pair("initialization", "warm-start"),
       std::make_pair("parameter-scheme", "Standard")});
  qaoa->execute(buffer);
  std::cout << "Opt-val: " << (*buffer)["opt-val"].as<double>() << "\n";
  // EXPECT_LT(nbRxgates, buffer->size())
}

// Testing if a weighted graph can be constructed and passed
Santana, Anthony's avatar
Santana, Anthony committed
188
// to the maxcut-qaoa algorithm with the correct result returned.
189
190
191
192
193
194
TEST(QAOATester, checkWeightedQAOA) {
  auto acc = xacc::getAccelerator("qpp");
  auto buffer = xacc::qalloc(3);
  //   xacc::set_verbose(true);
  int size = buffer->size();
  auto optimizer = xacc::getOptimizer("nlopt", {{"maximize", true}, {"initial-parameters", random_vector(-2., 2., 2)}});
Santana, Anthony's avatar
Santana, Anthony committed
195
  auto qaoa = xacc::getService<Algorithm>("maxcut-qaoa");
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
  auto graph = xacc::getService<xacc::Graph>("boost-digraph");

  // Triangle graph
  for (int i = 0; i < 3; i++) {
    graph->addVertex();
  }
  graph->addEdge(0, 1, 0.15);
  graph->addEdge(0, 2, 0.85);

  const bool initOk = qaoa->initialize(
      {std::make_pair("accelerator", acc),
       std::make_pair("optimizer", optimizer), 
       std::make_pair("graph", graph),
       // number of time steps (p) param
       std::make_pair("steps", 1),
       // "Standard" or "Extended"
       std::make_pair("parameter-scheme", "Standard")});
  qaoa->execute(buffer);
  std::cout << "Min Val: " << (*buffer)["opt-val"].as<double>() << "\n";
}

TEST(QAOATester, checkMaxCut) {
  auto acc = xacc::getAccelerator("qpp");
  auto buffer = xacc::qalloc(3);
  //   xacc::set_verbose(true);
  auto optimizer = xacc::getOptimizer("nlopt", {{"maximize", true}, {"initial-parameters", random_vector(-2., 2., 2)}});
Santana, Anthony's avatar
Santana, Anthony committed
222
  auto qaoa = xacc::getService<Algorithm>("maxcut-qaoa");
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
  auto graph = xacc::getService<xacc::Graph>("boost-digraph");

  // Triangle graph
  for (int i = 0; i < 3; i++) {
    graph->addVertex();
  }
  graph->addEdge(0, 1);
  graph->addEdge(0, 2);
  graph->addEdge(1, 2);

  const bool initOk = qaoa->initialize(
      {std::make_pair("accelerator", acc),
       std::make_pair("optimizer", optimizer), 
       std::make_pair("graph", graph),
       // number of time steps (p) param
       std::make_pair("steps", 1),
       // "Standard" or "Extended"
       std::make_pair("parameter-scheme", "Standard")});
  qaoa->execute(buffer);
  std::cout << "Opt-val: " << (*buffer)["opt-val"].as<double>() << "\n";
  // EXPECT_NEAR((*buffer)["opt-val"].as<double>(), 2.0, 1e-3);
}

246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
TEST(QAOATester, checkMaxCutGrouping) {
  auto acc = xacc::getAccelerator("qpp", {{"shots", 8192}});
  auto buffer = xacc::qalloc(3);
  xacc::set_verbose(true);
  auto optimizer = xacc::getOptimizer(
      "nlopt", {{"ftol", 0.001},
                {"maximize", true},
                {"initial-parameters", random_vector(-2., 2., 2)}});
  auto qaoa = xacc::getService<Algorithm>("maxcut-qaoa");
  auto graph = xacc::getService<xacc::Graph>("boost-digraph");

  // Triangle graph
  for (int i = 0; i < 3; i++) {
    graph->addVertex();
  }
  graph->addEdge(0, 1);
  graph->addEdge(0, 2);
  graph->addEdge(1, 2);

  const bool initOk = qaoa->initialize(
      {std::make_pair("accelerator", acc),
       std::make_pair("optimizer", optimizer), 
       std::make_pair("graph", graph),
       // number of time steps (p) param
       std::make_pair("steps", 1),
       // "Standard" or "Extended"
       std::make_pair("parameter-scheme", "Standard")});
  qaoa->execute(buffer);
  buffer->print();
  std::cout << "Opt-val: " << (*buffer)["opt-val"].as<double>() << "\n";
  // There seems to be a local minima at 1.5 as well...
277
  EXPECT_NEAR((*buffer)["opt-val"].as<double>(), 2.0, 0.25);
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
}

TEST(QAOATester, checkP1TriangleGraphGroupingExpVal) {
  auto acc = xacc::getAccelerator("aer", {{"shots", 8192}});
  auto optimizer = xacc::getOptimizer(
      "nlopt",
      {{"maximize", true}, {"initial-parameters", random_vector(-2., 2., 2)}});
  auto H = xacc::quantum::getObservable(
      "pauli", std::string("1.5 I - 0.5 Z0 Z1 - 0.5 Z0 Z2 - 0.5 Z1 Z2"));
  auto qaoa = xacc::getAlgorithm("QAOA", {{"accelerator", acc},
                                          {"optimizer", optimizer},
                                          {"observable", H},
                                          {"steps", 1},
                                          {"parameter-scheme", "Standard"}});
  auto all_betas =
      xacc::linspace(-xacc::constants::pi / 4., xacc::constants::pi / 4., 20);
  auto all_gammas =
      xacc::linspace(-xacc::constants::pi, xacc::constants::pi, 20);
  for (auto gamma : all_gammas) {
    for (auto beta : all_betas) {
      auto buffer = xacc::qalloc(3);
      auto cost = qaoa->execute(buffer, std::vector<double>{gamma, beta})[0];
      auto d = 1;
      auto e = 1;
      auto f = 1;
      auto theory = 3 * (.5 +
                         .25 * std::sin(4 * beta) * std::sin(gamma) *
                             (std::cos(gamma) + std::cos(gamma)) -
                         .25 * std::sin(2 * beta) * std::sin(2 * beta) *
                             (std::pow(std::cos(gamma), d + e - 2 * f)) *
                             (1 - std::cos(2 * gamma)));
      // std::cout << "Cost = " << cost << "; expected = " << theory << "\n";
      EXPECT_NEAR(cost, theory, 0.1);
    }
  }
}

315
int main(int argc, char **argv) {
Nguyen, Thien Minh's avatar
Nguyen, Thien Minh committed
316
317
318
319
320
321
  xacc::Initialize(argc, argv);
  ::testing::InitGoogleTest(&argc, argv);
  auto ret = RUN_ALL_TESTS();
  xacc::Finalize();
  return ret;
}