xacc-py.cpp 30.5 KB
Newer Older
1
2
3
4
5
6
/*******************************************************************************
 * Copyright (c) 2018 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
7
8
 * http://www.eclipse.org/legal/epl-v10.html and the Eclipse Distribution
 *License is available at https://eclipse.org/org/documents/edl-v10.php
9
10
11
12
 *
 * Contributors:
 *   Alexander J. McCaskey - initial API and implementation
 *******************************************************************************/
13
#include "XACC.hpp"
14
#include "IRGenerator.hpp"
15
16
#include "IRProvider.hpp"
#include "InstructionIterator.hpp"
17
#include "AcceleratorBuffer.hpp"
18
#include "AcceleratorDecorator.hpp"
19
#include "InstructionParameter.hpp"
Mccaskey, Alex's avatar
Mccaskey, Alex committed
20
21
#include "DWGraph.hpp"
#include "EmbeddingAlgorithm.hpp"
22
#include "PauliOperator.hpp"
23

24
#include <pybind11/complex.h>
25
#include <pybind11/numpy.h>
26
27
28
29
30
31
32
33
#include <pybind11/stl.h>
#include <pybind11/stl_bind.h>
#include <pybind11/eigen.h>
#include <pybind11/iostream.h>
#include <pybind11/operators.h>

namespace py = pybind11;
using namespace xacc;
34
using namespace xacc::quantum;
35

36
// `boost::variant` as an example -- can be any `std::variant`-like container
37
38
namespace pybind11 {
namespace detail {
39
40
41
42
43
44
45
template <typename... Ts>
struct type_caster<Variant<Ts...>> : variant_caster<Variant<Ts...>> {};

// Specifies the function used to visit the variant -- `apply_visitor` instead
// of `visit`
template <> struct visit_helper<Variant> {
  template <typename... Args>
46
47
  static auto call(Args &&... args) -> decltype(mpark::visit(args...)) {
    return mpark::visit(args...);
48
49
50
  }
};

51
template <typename... Ts>
52
53
struct type_caster<mpark::variant<Ts...>>
    : variant_caster<mpark::variant<Ts...>> {};
54
55
56

// Specifies the function used to visit the variant -- `apply_visitor` instead
// of `visit`
57
template <> struct visit_helper<mpark::variant> {
58
  template <typename... Args>
59
60
  static auto call(Args &&... args) -> decltype(mpark::visit(args...)) {
    return mpark::visit(args...);
61
62
63
64
  }
};
} // namespace detail
} // namespace pybind11
65

66
67
class PyAccelerator : public xacc::Accelerator {
public:
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
  /* Inherit the constructors */
  using Accelerator::Accelerator;

  const std::string name() const override {
    PYBIND11_OVERLOAD_PURE(const std::string, xacc::Accelerator, name);
  }

  const std::string description() const override { return ""; }

  void initialize() override { return; }

  AcceleratorType getType() override {
    return Accelerator::AcceleratorType::qpu_gate;
  }

  std::vector<std::shared_ptr<IRTransformation>>
  getIRTransformations() override {
    return {};
  }

  bool isValidBufferSize(const int n) override { return true; }

  /* Trampoline (need one for each virtual function) */
  void execute(std::shared_ptr<xacc::AcceleratorBuffer> buf,
               std::shared_ptr<xacc::Function> f) override {
    PYBIND11_OVERLOAD_PURE(void, xacc::Accelerator, execute, buf, f);
  }

  std::vector<std::shared_ptr<AcceleratorBuffer>>
  execute(std::shared_ptr<AcceleratorBuffer> buffer,
          const std::vector<std::shared_ptr<Function>> functions) override {
    return {};
  }

  std::shared_ptr<AcceleratorBuffer>
  createBuffer(const std::string &varId) override {
    return std::make_shared<AcceleratorBuffer>(varId, 100);
  }

  std::shared_ptr<AcceleratorBuffer> createBuffer(const std::string &varId,
                                                  const int size) override {
    return std::make_shared<AcceleratorBuffer>(varId, size);
  }
111
112
};

113
PYBIND11_MODULE(_pyxacc, m) {
114
115
116
117
  m.doc() =
      "Python bindings for XACC. XACC provides a plugin infrastructure for "
      "programming, compiling, and executing quantum kernels in a language and "
      "hardware agnostic manner.";
118

119
120
121
122
123
124
125
126
  py::class_<xacc::InstructionParameter>(
      m, "InstructionParameter",
      "The InstructionParameter provides a variant structure "
      "to provide parameters to XACC Instructions at runtime. "
      "This type can be an int, double, float, string, or complex value.")
      .def(py::init<int>(), "Construct as an int.")
      .def(py::init<double>(), "Construct as a double.")
      .def(py::init<std::string>(), "Construct as a string.")
127
      .def(py::init<std::complex<double>>(), "Construct as a complex double.");
128
129
130
131

  py::class_<xacc::Instruction, std::shared_ptr<xacc::Instruction>>(
      m, "Instruction", "")
      .def("nParameters", &xacc::Instruction::nParameters, "")
132
133
134
135
136
137
138
139
      .def("toString",
           (const std::string (xacc::Instruction::*)()) &
               xacc::Instruction::toString,
           "")
      .def("toString",
           (const std::string (xacc::Instruction::*)(const std::string &)) &
               xacc::Instruction::toString,
           "")
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
      .def("isEnabled", &xacc::Instruction::isEnabled, "")
      .def("isComposite", &xacc::Instruction::isComposite, "")
      .def("bits", &xacc::Instruction::bits, "")
      .def("getParameter", &xacc::Instruction::getParameter, "")
      .def("getParameters", &xacc::Instruction::getParameters, "")
      .def("setParameter", &xacc::Instruction::setParameter, "")
      .def("mapBits", &xacc::Instruction::mapBits, "")
      .def("name", &xacc::Instruction::name, "")
      .def("description", &xacc::Instruction::description, "");

  py::class_<xacc::Function, std::shared_ptr<xacc::Function>>(m, "Function", "")
      .def("nInstructions", &xacc::Function::nInstructions, "")
      .def("getInstruction", &xacc::Function::getInstruction, "")
      .def("getInstructions", &xacc::Function::getInstructions, "")
      .def("removeInstruction", &xacc::Function::removeInstruction, "")
      .def("replaceInstruction", &xacc::Function::replaceInstruction, "")
      .def("insertInstruction", &xacc::Function::insertInstruction, "")
      .def("addInstruction", &xacc::Function::addInstruction, "")
      .def("addParameter", &xacc::Function::addParameter, "")
159
      .def("nParameters", &xacc::Function::nParameters, "")
160
161
162
163
      .def("eval", &xacc::Function::operator(), "")
      .def("name", &xacc::Function::name, "")
      .def("description", &xacc::Function::description, "")
      .def("nParameters", &xacc::Function::nParameters, "")
164
165
166
167
168
169
170
      .def("toString",
           (const std::string (xacc::Function::*)()) & xacc::Function::toString,
           "")
      .def("toString",
           (const std::string (xacc::Function::*)(const std::string &)) &
               xacc::Function::toString,
           "")
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
      .def("enabledView", &xacc::Function::enabledView, "")
      .def("enable", &xacc::Function::enable, "")
      .def("getParameter", &xacc::Function::getParameter, "")
      .def("getParameters", &xacc::Function::getParameters, "")
      .def("setParameter", &xacc::Function::setParameter, "")
      .def("depth", &xacc::Function::depth, "")
      .def("persistGraph", &xacc::Function::persistGraph, "")
      .def("mapBits", &xacc::Function::mapBits, "");

  // Expose the IR interface
  py::class_<xacc::IR, std::shared_ptr<xacc::IR>>(
      m, "IR",
      "The XACC Intermediate Representation, "
      "serves as a container for XACC Functions.")
      .def("getKernels", &xacc::IR::getKernels, "Return the kernels in this IR")
      .def("addKernel", &xacc::IR::addKernel, "");
187

188
189
190
191
  py::class_<xacc::InstructionIterator>(m, "InstructionIterator", "")
      .def(py::init<std::shared_ptr<xacc::Function>>())
      .def("hasNext", &xacc::InstructionIterator::hasNext, "")
      .def("next", &xacc::InstructionIterator::next, "");
192

193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
  py::class_<xacc::IRPreprocessor, std::shared_ptr<xacc::IRPreprocessor>>(
      m, "IRPreprocesor", "")
      .def("process", &xacc::IRPreprocessor::process, "");

  py::class_<xacc::IRTransformation, std::shared_ptr<xacc::IRTransformation>>(
      m, "IRTransformation", "")
      .def("transform", &xacc::IRTransformation::transform, "");

  py::class_<xacc::AcceleratorBufferPostprocessor,
             std::shared_ptr<xacc::AcceleratorBufferPostprocessor>>(
      m, "AcceleratorBufferPostprocessor", "")
      .def("process", &xacc::AcceleratorBufferPostprocessor::process, "");

  py::class_<xacc::IRGenerator, std::shared_ptr<xacc::IRGenerator>>(
      m, "IRGenerator", "")
      .def("generate",
           (std::shared_ptr<xacc::Function>(xacc::IRGenerator::*)(
               std::vector<xacc::InstructionParameter>)) &
               xacc::IRGenerator::generate,
           py::return_value_policy::reference, "")
      .def("generate",
           (std::shared_ptr<xacc::Function>(xacc::IRGenerator::*)(
               std::map<std::string, xacc::InstructionParameter>)) &
               xacc::IRGenerator::generate,
217
218
           py::return_value_policy::reference, "")
      .def("analyzeResults", &xacc::IRGenerator::analyzeResults, "");
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260

  // Expose the Kernel
  py::class_<xacc::Kernel<>, std::shared_ptr<xacc::Kernel<>>>(
      m, "Kernel",
      "The XACC Kernel is the "
      "executable functor that executes XACC IR on the desired Accelerator.")
      .def("getIRFunction", &xacc::Kernel<>::getIRFunction,
           py::return_value_policy::reference,
           "Return the IR Function instance this Kernel wraps.")
      .def("execute",
           (void (xacc::Kernel<>::*)(std::shared_ptr<xacc::AcceleratorBuffer>,
                                     std::vector<xacc::InstructionParameter>)) &
               xacc::Kernel<>::operator(),
           "Execute this Kernel with the given set of "
           "InstructionParamters. This set can be empty "
           "if there are no parameters.");

  py::class_<xacc::KernelList<>>(
      m, "KernelList",
      "The XACC KernelList is a vector of "
      "Kernels that provides a operator() implementation to execute multiple "
      "kernels at once.")
      .def(
          "execute",
          (std::vector<std::shared_ptr<xacc::AcceleratorBuffer>>(
              xacc::KernelList<>::*)(std::shared_ptr<xacc::AcceleratorBuffer>,
                                     std::vector<xacc::InstructionParameter>)) &
              xacc::KernelList<>::operator(),
          "Execute a list of Kernels at once.")
      .def("__getitem__",
           [](const xacc::KernelList<> &kl, int i) -> xacc::Kernel<> {
             if (i >= kl.size())
               throw py::index_error();
             return kl[i];
           })
      .def("__setitem__",
           [](xacc::KernelList<> &kl, size_t i, xacc::Kernel<> v) {
             if (i >= kl.size())
               throw py::index_error();
             kl[i] = v;
           })
      .def("__len__", &xacc::KernelList<>::size)
261
262
263
264
265
266
      .def(
          "__iter__",
          [](const xacc::KernelList<> &kl) {
            return py::make_iterator(kl.begin(), kl.end());
          },
          py::keep_alive<0, 1>())
267
268
269
270
271
272
273
274
275
276
277
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
      .def("__getitem__",
           [](xacc::KernelList<> &s, py::slice slice) -> xacc::KernelList<> * {
             size_t start, stop, step, slicelength;
             if (!slice.compute(s.size(), &start, &stop, &step, &slicelength))
               throw py::error_already_set();
             xacc::KernelList<> *seq =
                 new xacc::KernelList<>(s.getAccelerator());
             for (size_t i = 0; i < slicelength; ++i) {
               (*seq).push_back(s[start]);
               start += step;
             }
             return seq;
           });

  // Expose the Accelerator
  py::class_<xacc::Accelerator, std::shared_ptr<xacc::Accelerator>,
             PyAccelerator>
      acc(m, "Accelerator",
          "Accelerator wraps the XACC C++ Accelerator class "
          "and provides a mechanism for creating buffers of qubits. Execution "
          "is handled by the XACC Kernels.");
  acc.def(py::init<>())
      .def("name", &xacc::Accelerator::name,
           "Return the name of this Accelerator.")
      .def("createBuffer",
           (std::shared_ptr<xacc::AcceleratorBuffer>(xacc::Accelerator::*)(
               const std::string &, const int)) &
               xacc::Accelerator::createBuffer,
           py::return_value_policy::reference,
           "Return a newly created register of qubits of the given size.")
      .def(
          "createBuffer",
          (std::shared_ptr<xacc::AcceleratorBuffer>(xacc::Accelerator::*)(
              const std::string &)) &
              xacc::Accelerator::createBuffer,
          py::return_value_policy::reference,
          "Return a newly allocated register of all qubits on the Accelerator.")
      .def("execute",
           (void (xacc::Accelerator::*)(std::shared_ptr<AcceleratorBuffer>,
Mccaskey, Alex's avatar
Mccaskey, Alex committed
306
307
308
309
310
311
312
313
                                        const std::shared_ptr<Function>)) &
               xacc::Accelerator::execute,
           "Execute the Function with the given AcceleratorBuffer.")
      .def("execute",
           (std::vector<std::shared_ptr<AcceleratorBuffer>>(
               xacc::Accelerator::*)(
               std::shared_ptr<AcceleratorBuffer>,
               const std::vector<std::shared_ptr<Function>>)) &
314
               xacc::Accelerator::execute,
315
           "Execute the Function with the given AcceleratorBuffer.")
316
317
318
      .def("initialize", &xacc::Accelerator::initialize, "")
      .def("getOneBitErrorRates", &xacc::Accelerator::getOneBitErrorRates, "")
      .def("getTwoBitErrorRates", &xacc::Accelerator::getTwoBitErrorRates, "");
319
320
321
322
323
324

  py::enum_<Accelerator::AcceleratorType>(acc, "AcceleratorType")
      .value("qpu_aqc", Accelerator::AcceleratorType::qpu_aqc)
      .value("qpu_gate", Accelerator::AcceleratorType::qpu_gate)
      .export_values();

325
326
327
  py::class_<xacc::AcceleratorDecorator, xacc::Accelerator,
             std::shared_ptr<xacc::AcceleratorDecorator>>
      accd(m, "AcceleratorDecorator", "");
328
  accd.def("setDecorated", &xacc::AcceleratorDecorator::setDecorated, "");
329

330
331
332
333
334
335
336
337
338
339
  // Expose the AcceleratorBuffer
  py::class_<xacc::AcceleratorBuffer, std::shared_ptr<xacc::AcceleratorBuffer>>(
      m, "AcceleratorBuffer",
      "The AcceleratorBuffer models a register of qubits.")
      .def(py::init<const std::string &, const int>())
      .def("getExpectationValueZ",
           &xacc::AcceleratorBuffer::getExpectationValueZ,
           "Return the expectation value with respect to the Z operator.")
      .def("resetBuffer", &xacc::AcceleratorBuffer::resetBuffer,
           "Reset this buffer for use in another computation.")
Mccaskey, Alex's avatar
Mccaskey, Alex committed
340
      .def("size", &xacc::AcceleratorBuffer::size, "")
341
342
343
344
      .def("appendMeasurement",
           (void (xacc::AcceleratorBuffer::*)(const std::string &)) &
               xacc::AcceleratorBuffer::appendMeasurement,
           "Append the measurement string")
345
346
      .def("getMeasurements",
           &xacc::AcceleratorBuffer::getMeasurements,
347
348
349
350
351
352
           "Return observed measurement bit strings")
      .def("computeMeasurementProbability",
           &xacc::AcceleratorBuffer::computeMeasurementProbability,
           "Compute the probability of a given bit string")
      .def("getMeasurementCounts",
           &xacc::AcceleratorBuffer::getMeasurementCounts,
353
354
355
356
357
358
           "Return the mapping of measure bit strings to their counts.")
      .def("getChildren",
           (std::vector<std::shared_ptr<AcceleratorBuffer>>(
               xacc::AcceleratorBuffer::*)(const std::string)) &
               xacc::AcceleratorBuffer::getChildren,
           "")
359
      .def("nChildren", &xacc::AcceleratorBuffer::nChildren, "")
360
361
362
363
364
      .def("getChildren",
           (std::vector<std::shared_ptr<AcceleratorBuffer>>(
               xacc::AcceleratorBuffer::*)()) &
               xacc::AcceleratorBuffer::getChildren,
           "")
365
366
367
368
369
370
      .def("getChildrenNames", &xacc::AcceleratorBuffer::getChildrenNames, "")
      .def("listExtraInfoKeys", &xacc::AcceleratorBuffer::listExtraInfoKeys, "")
      .def("getInformation",
           (std::map<std::string, ExtraInfo>(xacc::AcceleratorBuffer::*)()) &
               xacc::AcceleratorBuffer::getInformation,
           "")
371
372
373
374
      .def("addExtraInfo",
           (void (xacc::AcceleratorBuffer::*)(const std::string, ExtraInfo)) &
               xacc::AcceleratorBuffer::addExtraInfo,
           "")
375
376
377
378
      .def("getInformation",
           (ExtraInfo(xacc::AcceleratorBuffer::*)(const std::string)) &
               xacc::AcceleratorBuffer::getInformation,
           "")
Mccaskey, Alex's avatar
Mccaskey, Alex committed
379
      .def("appendChild", &xacc::AcceleratorBuffer::appendChild, "")
380
      .def("hasExtraInfoKey", &xacc::AcceleratorBuffer::hasExtraInfoKey, "")
381
382
383
      .def("name", &xacc::AcceleratorBuffer::name, "")
      .def("getAllUnique", &xacc::AcceleratorBuffer::getAllUnique,
           "Return all unique information with the provided string name")
384
385
      .def("__repr__", &xacc::AcceleratorBuffer::toString, "")
      .def("__str__", &xacc::AcceleratorBuffer::toString, "")
386
387
388
389
390
      .def("getChildren",
           (std::vector<std::shared_ptr<AcceleratorBuffer>>(
               xacc::AcceleratorBuffer::*)(const std::string, ExtraInfo)) &
               xacc::AcceleratorBuffer::getChildren,
           "");
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412

  // Expose the Compiler
  py::class_<xacc::Compiler, std::shared_ptr<xacc::Compiler>>(
      m, "Compiler",
      "The XACC Compiler takes as input quantum kernel source code, "
      "and compiles it to the XACC intermediate representation.")
      .def("name", &xacc::Compiler::name, "Return the name of this Compiler.")
      .def("compile",
           (std::shared_ptr<xacc::IR>(xacc::Compiler::*)(
               const std::string &, std::shared_ptr<xacc::Accelerator>)) &
               xacc::Compiler::compile,
           "Compile the "
           "given source code against the given Accelerator.")
      .def("compile",
           (std::shared_ptr<xacc::IR>(xacc::Compiler::*)(const std::string &)) &
               xacc::Compiler::compile,
           "Compile the "
           "given source code.")
      .def("translate", &xacc::Compiler::translate,
           "Translate the given IR Function instance to source code in this "
           "Compiler's language.");

413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
  py::class_<Term>(m, "Term").def("coeff", &Term::coeff).def("ops",&Term::ops);
  py::class_<PauliOperator>(m, "PauliOperator")
      .def(py::init<>())
      .def(py::init<std::complex<double>>())
      .def(py::init<double>())
      .def(py::init<std::string>())
      .def(py::init<std::map<int, std::string>>())
      .def(py::init<std::map<int, std::string>, double>())
      .def(py::init<std::map<int, std::string>, std::complex<double>>())
      .def(py::init<std::map<int, std::string>, std::string>())
      .def(py::init<std::map<int, std::string>, std::complex<double>,
                    std::string>())
      .def(py::self + py::self)
      .def(py::self += py::self)
      .def(py::self *= py::self)
      .def(py::self *= double())
      .def(py::self * py::self)
      .def(py::self *= std::complex<double>())
      .def(py::self -= py::self)
      .def(py::self - py::self)
      .def("__eq__", &PauliOperator::operator==)
      .def("__repr__", &PauliOperator::toString)
      .def("eval", &PauliOperator::eval)
      .def("toBinaryVectors", &PauliOperator::toBinaryVectors)
      .def("toXACCIR", &PauliOperator::toXACCIR)
      .def("fromXACCIR", &PauliOperator::fromXACCIR)
      .def("fromString", &PauliOperator::fromString)
      .def("nTerms", &PauliOperator::nTerms)
      .def("isClose", &PauliOperator::isClose)
      .def("commutes", &PauliOperator::commutes)
      .def("__len__", &PauliOperator::nTerms)
      .def("nQubits", &PauliOperator::nQubits)
      .def("computeActionOnKet", &PauliOperator::computeActionOnKet)
      .def("computeActionOnBra", &PauliOperator::computeActionOnBra)
      .def("__iter__",
           [](PauliOperator &op) {
             return py::make_iterator(op.begin(), op.end());
           },
           py::keep_alive<0, 1>());
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
  // Expose the Program object
  py::class_<xacc::Program>(
      m, "Program",
      "The Program is the primary entrypoint for compilation and execution in "
      "XACC. Clients provide quantum kernel source "
      "code and the Accelerator instance, and the Program handles compiling "
      "the code and provides Kernel instances to execute.")
      .def(py::init<std::shared_ptr<xacc::Accelerator>, const std::string &>(),
           "The constructor")
      .def(py::init<std::shared_ptr<xacc::Accelerator>,
                    std::shared_ptr<xacc::IR>>(),
           "The constructor")
      .def("build",
           (void (xacc::Program::*)(const std::string &)) &
               xacc::Program::build,
           "Compile this program with the given Compiler name.")
      .def("build", (void (xacc::Program::*)()) & xacc::Program::build,
           "Compile this program.")
      .def("getKernel",
           (xacc::Kernel<>(xacc::Program::*)(const std::string &)) &
               xacc::Program::getKernel<>,
           py::return_value_policy::reference,
           "Return a Kernel representing the source code.")
      .def("getKernels", &xacc::Program::getRuntimeKernels,
           "Return all Kernels.")
      .def("nKernels", &xacc::Program::nKernels,
           "Return the number of kernels compiled by this program");

  // Expose XACC API functions
  m.def("Initialize", (void (*)(std::vector<std::string>)) & xacc::Initialize,
        "Initialize the framework. Can provide a list of strings to model "
        "command line arguments. For instance, "
        "to print the XACC help message, pass ['--help'] to this function, or "
        "to set the compiler to use, ['--compiler','scaffold'].");
  m.def("Initialize", (void (*)()) & xacc::Initialize,
        "Initialize the framework. Use this if there are no command line "
        "arguments to pass.");
489
490
  m.def("PyInitialize", &xacc::PyInitialize,
        "Initialize the framework from Python.");
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
  // m.def("help", )
  m.def("getAccelerator",
        (std::shared_ptr<xacc::Accelerator>(*)(const std::string &)) &
            xacc::getAccelerator,
        py::return_value_policy::reference,
        "Return the accelerator with given name.");
  m.def("getCompiler",
        (std::shared_ptr<xacc::Compiler>(*)(const std::string &)) &
            xacc::getCompiler,
        py::return_value_policy::reference,
        "Return the Compiler of given name.");
  m.def("getIRPreprocessor",
        (std::shared_ptr<xacc::IRPreprocessor>(*)(const std::string &)) &
            xacc::getService<IRPreprocessor>,
        py::return_value_policy::reference,
        "Return the IRPreprocessor of given name.");
  m.def("getIRTransformation",
        (std::shared_ptr<xacc::IRTransformation>(*)(const std::string &)) &
            xacc::getService<IRTransformation>,
        py::return_value_policy::reference,
        "Return the IRTransformation of given name.");
  m.def("getIRGenerator",
        (std::shared_ptr<xacc::IRGenerator>(*)(const std::string &)) &
            xacc::getService<IRGenerator>,
        py::return_value_policy::reference,
        "Return the IRGenerator of given name.");
517
  m.def("getConnectivity",
518
        [](const std::string acc) -> std::vector<std::pair<int,int>> {
519
          auto a = xacc::getAccelerator(acc);
520
          return a->getAcceleratorConnectivity();
521
        });
522
523
  m.def("translate", &xacc::translate,
        "Translate the provided IR Function to the given language.");
524
  m.def("setOption", [](const std::string s, InstructionParameter p) {
525
    xacc::setOption(s, p.toString());
526
  });
527
528
529
530
  m.def(
      "info", [](const std::string s) { xacc::info(s); }, "");
  m.def(
      "error", [](const std::string s) { xacc::error(s); }, "");
531
  m.def("setOption", &xacc::setOption, "Set an XACC framework option.");
532
533
534
535
536
537
538
  m.def(
      "setOptions",
      [](std::map<std::string, std::string> options) {
        for (auto &kv : options)
          xacc::setOption(kv.first, kv.second);
      },
      "Set a number of options at once.");
539
540
541
542
543
544
  m.def("getAcceleratorDecorator",
        [](const std::string name, std::shared_ptr<Accelerator> acc) {
          auto accd = xacc::getService<AcceleratorDecorator>(name);
          accd->setDecorated(acc);
          return accd;
        });
545
546
547
548
549
550
551
  m.def(
      "setOptions",
      [](std::map<std::string, InstructionParameter> options) {
        for (auto &kv : options)
          xacc::setOption(kv.first, kv.second.toString());
      },
      "Set a number of options at once.");
552
  m.def("unsetOption", &xacc::unsetOption, "");
553
554
555
556
557
558
559
560
561
562
563
564
  m.def("getOption",
        (const std::string (*)(const std::string &)) & xacc::getOption,
        "Get an XACC framework option.");
  m.def("hasAccelerator", &xacc::hasAccelerator,
        "Does XACC have the given Accelerator installed?");
  m.def("hasCompiler", &xacc::hasCompiler,
        "Does XACC have the given Accelerator installed?");
  m.def("optionExists", &xacc::optionExists, "Set an XACC framework option.");
  m.def("setIsPyApi", &xacc::setIsPyApi,
        "Indicate that this is using XACC via the Python API.");
  m.def("optimizeFunction", &xacc::optimizeFunction,
        "Run an optimizer on the given function.");
Mccaskey, Alex's avatar
Mccaskey, Alex committed
565
566
567
  m.def("analyzeBuffer",
        (void (*)(std::shared_ptr<AcceleratorBuffer>)) & xacc::analyzeBuffer,
        "Analyze the AcceleratorBuffer to produce problem-specific results.");
568
  m.def("getCache", &xacc::getCache, "");
Mccaskey, Alex's avatar
Mccaskey, Alex committed
569
570
  m.def(
      "appendCache",
571
      (void (*)(const std::string, const std::string, InstructionParameter &,const std::string)) &
Mccaskey, Alex's avatar
Mccaskey, Alex committed
572
573
          xacc::appendCache,
      "");
574
  m.def("Finalize", &xacc::Finalize, "Finalize the framework");
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
  m.def(
      "loadBuffer",
      [](const std::string json) {
        std::istringstream s(json);
        auto buffer = std::make_shared<AcceleratorBuffer>();
        buffer->load(s);
        return buffer;
      },
      "");
  m.def(
      "compileKernel",
      [](std::shared_ptr<Accelerator> acc, const std::string &src,
         const std::string &compilerName = "") -> std::shared_ptr<Function> {
        if (!compilerName.empty())
          xacc::setOption("compiler", compilerName);
        xacc::Program p(acc, src);
        p.build();
        return p.getRuntimeKernels()[0].getIRFunction();
      },
      py::arg("acc"), py::arg("src"), py::arg("compilerName") = std::string(""),
      py::return_value_policy::move, "");

  m.def(
      "functionToInstruction",
      [](std::shared_ptr<Function> f) {
        return std::dynamic_pointer_cast<Instruction>(f);
      },
      py::return_value_policy::copy);
603
604
605

  py::module gatesub =
      m.def_submodule("gate", "Gate model quantum computing data structures.");
606
607
608
609
610
611
612
613
614
615
616
617
  gatesub.def(
      "create",
      [](const std::string &name, std::vector<int> qbits,
         std::vector<InstructionParameter> params =
             std::vector<InstructionParameter>{})
          -> std::shared_ptr<Instruction> {
        return xacc::getService<IRProvider>("gate")->createInstruction(
            name, qbits, params);
      },
      "Convenience function for creating a new GateInstruction.",
      py::arg("name"), py::arg("qbits"),
      py::arg("params") = std::vector<InstructionParameter>{});
618
619
620
621
622
623
624
625
626
627
628
  gatesub.def(
      "createFunction",
      [](const std::string &name, std::vector<int> qbits,
         std::vector<InstructionParameter> params =
             std::vector<InstructionParameter>{}) -> std::shared_ptr<Function> {
        return xacc::getService<IRProvider>("gate")->createFunction(name, qbits,
                                                                    params);
      },
      "Convenience function for creating a new GateFunction.", py::arg("name"),
      py::arg("qbits"),
      py::arg("params") = std::vector<InstructionParameter>{});
629
630
631
632
633
634
  gatesub.def(
      "createIR",
      []() -> std::shared_ptr<IR> {
        return xacc::getService<IRProvider>("gate")->createIR();
      },
      "Convenience function for creating a new GateIR.");
635
636
637
638
639
640
641
642
643
644
645

  gatesub.def(
      "getState",
      [](std::shared_ptr<Accelerator> acc, std::shared_ptr<Function> f) {
        auto results = acc->getAcceleratorState(f);
        Eigen::VectorXcd ret =
            Eigen::Map<Eigen::VectorXcd>(results.data(), results.size());
        return ret;
      },
      "Compute and return the state after execution of the given program on "
      "the given accelerator.");
646
647
648
649
650
651
652
653
654
655
656
657

  py::module aqcsub =
      m.def_submodule("dwave", "Gate model quantum computing data structures.");
  aqcsub.def(
      "create",
      [](const std::string &name, std::vector<int> qbits,
         std::vector<InstructionParameter> params =
             std::vector<InstructionParameter>{})
          -> std::shared_ptr<Instruction> {
        return xacc::getService<IRProvider>("dwave")->createInstruction(
            name, qbits, params);
      },
Mccaskey, Alex's avatar
Mccaskey, Alex committed
658
659
      "Convenience function for creating a new DWInstruction.", py::arg("name"),
      py::arg("qbits"),
660
661
662
663
664
665
      py::arg("params") = std::vector<InstructionParameter>{});
  aqcsub.def(
      "createFunction",
      [](const std::string &name, std::vector<int> qbits,
         std::vector<InstructionParameter> params =
             std::vector<InstructionParameter>{}) -> std::shared_ptr<Function> {
Mccaskey, Alex's avatar
Mccaskey, Alex committed
666
667
        return xacc::getService<IRProvider>("dwave")->createFunction(
            name, qbits, params);
668
669
670
671
672
673
674
675
676
677
      },
      "Convenience function for creating a new DWFunction.", py::arg("name"),
      py::arg("qbits"),
      py::arg("params") = std::vector<InstructionParameter>{});
  aqcsub.def(
      "createIR",
      []() -> std::shared_ptr<IR> {
        return xacc::getService<IRProvider>("dwave")->createIR();
      },
      "Convenience function for creating a new DWIR.");
Mccaskey, Alex's avatar
Mccaskey, Alex committed
678
679
680
681
682
683

  aqcsub.def(
      "embed",
      [](std::shared_ptr<Function> f, std::shared_ptr<Accelerator> acc,
         const std::string algo) -> std::map<int, std::vector<int>> {
        auto a = xacc::getService<xacc::quantum::EmbeddingAlgorithm>(algo);
684
685
686
687
688
689
690
691
692
693
694
695
696
        auto hardwareconnections = acc->getAcceleratorConnectivity();
        std::set<int> nUniqueBits;
        for (auto& edge : hardwareconnections) {
            nUniqueBits.insert(edge.first);
            nUniqueBits.insert(edge.second);
        }

        int nBits = *std::max_element(nUniqueBits.begin(), nUniqueBits.end()) + 1;

        auto hardware = std::make_shared<AcceleratorGraph>(nBits);
        for (auto& edge : hardwareconnections) {
            hardware->addEdge(edge.first, edge.second);
        }
Mccaskey, Alex's avatar
Mccaskey, Alex committed
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728

        int maxBitIdx = 0;
        for (auto inst : f->getInstructions()) {
          if (inst->name() == "dw-qmi") {
            auto qbit1 = inst->bits()[0];
            auto qbit2 = inst->bits()[1];
            if (qbit1 > maxBitIdx) {
              maxBitIdx = qbit1;
            }
            if (qbit2 > maxBitIdx) {
              maxBitIdx = qbit2;
            }
          }
        }

        auto problemGraph = std::make_shared<xacc::quantum::DWGraph>(maxBitIdx+1);
        for (auto inst : f->getInstructions()) {
          if (inst->name() == "dw-qmi") {
            auto qbit1 = inst->bits()[0];
            auto qbit2 = inst->bits()[1];
            if (qbit1 == qbit2) {
              problemGraph->setVertexProperties(qbit1, 1.0);
            } else {
              problemGraph->addEdge(qbit1, qbit2, 1.0);
            }
          }
        }


        return a->embed(problemGraph, hardware);
      },
      "");
729
}