extensions.rst 73.7 KB
Newer Older
1
2
3
4
5
Extensions
==========
Here we detail concrete implementations of various XACC interfaces as well as any
input parameters they expose.

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
Compilers
---------

xasm
++++
The XASM Compiler is the default compiler in XACC. It is the closest language to the underlying 
XACC IR data model. The XASM compiler provides a quantum assembly like language with support 
for custom Instructions and Composite Instruction generators as part of the language. Instructions 
are provided to the language via the usual XACC service registry. Most common digital gates are provided 
by default, and it is straightforward to add new Instructions. 



quilc
++++++
XACC provides a Compiler implementation that delegates to the Rigetti-developed 
quilc compiler. This is acheieved through the ``rigetti/quilc`` Docker image and 
the internal XACC REST client API. The Quilc Compiler implementation makes direct 
REST POSTs and GETs to the users local Docker Engine. Therefore, 
in order to use this Compiler, you must pull down this image. 

.. code:: bash 

   $ docker pull rigetti/quilc 

With that image pulled, you can now use the Quilc compiler via the usual XACC API calls. 

.. code:: cpp

   auto compiler = xacc::getCompiler("quilc");
   auto ir = compiler->compile(R"##(H 0
   CNOT 0 1
   )##");
   std::cout << ir->getComposites()[0]->toString() << "\n";

or in Python

.. code:: python

   compiler = xacc.getCompiler('quilc')
   ir = compiler.compile('''__qpu__ void ansatz(qbit q, double x) {
       X 0
       CNOT 1 0
       RY(x) 1
   }''')

Note that you can structure your input to the compiler as a typical XACC kernel source string 
or as a raw Quil string. 

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
Optimizers
----------
XACC provides implementations for the ``Optimizer`` that delegate to NLOpt and MLPack. Here we demonstrate
the various ways to configure these optimizers for a number of different solver types.

In addition to the enumerated parameters below, all ``Optimizers`` expose an ``initial-parameters`` key
that must be a list or vector of doubles with size equal to the number of parameters. By default, ``[0.,0.,...,0.,0.]`` is used.

MLPack
++++++
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
| ``mlpack-optimizer``   | Optimizer Parameter    |                  Parameter Description                          | default | type   |
+========================+========================+=================================================================+=========+========+
|        adam            | mlpack-step-size       | Step size for each iteration.                                   | .5      | double |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|                        | mlpack-beta1           | Exponential decay rate for the first moment estimates.          | .7      | double |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|                        | mlpack-beta2           | Exponential decay rate for the weighted infinity norm estimates.| .999    | double |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|                        | mlpack-max-iter        | Maximum number of iterations allowed                            | 500000  | int    |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|                        | mlpack-tolerance       | Maximum absolute tolerance to terminate algorithm.              | 1e-4    | double |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|                        | mlpack-eps             | Value used to initialize the mean squared gradient parameter.   | 1e-8    | double |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|        l-bfgs          |        None            |                                                                 |         |        |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|        adagrad         | mlpack-step-size       | Step size for each iteration.                                   | .5      | double |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|                        | mlpack-max-iter        | Maximum number of iterations allowed                            | 500000  | int    |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|                        | mlpack-tolerance       | Maximum absolute tolerance to terminate algorithm.              | 1e-4    | double |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|                        | mlpack-eps             | Value used to initialize the mean squared gradient parameter.   | 1e-8    | double |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|        adadelta        | mlpack-step-size       | Step size for each iteration.                                   | .5      | double |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|                        | mlpack-max-iter        | Maximum number of iterations allowed                            | 500000  | int    |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|                        | mlpack-tolerance       | Maximum absolute tolerance to terminate algorithm.              | 1e-4    | double |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|                        | mlpack-eps             | Value used to initialize the mean squared gradient parameter.   | 1e-8    | double |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|                        | mlpack-rho             | Smoothing constant.                                             | .95     | double |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|        cmaes           | mlpack-cmaes-lambda    | The population size.                                            | 0       | int    |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|                        |mlpack-cmaes-upper-bound| Upper bound of decision variables.                              | 10.     | duoble |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|                        |mlpack-cmaes-lower-bound| Lower bound of decision variables.                              | -10.0   | double |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|                        | mlpack-max-iter        | Maximum number of iterations allowed                            | 500000  | int    |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|                        | mlpack-tolerance       | Maximum absolute tolerance to terminate algorithm.              | 1e-4    | double |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|        gd              | mlpack-step-size       | Step size for each iteration.                                   | .5      | double |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|                        | mlpack-max-iter        | Maximum number of iterations allowed                            | 500000  | int    |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|                        | mlpack-tolerance       | Maximum absolute tolerance to terminate algorithm.              | 1e-4    | double |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|        momentum-sgd    | mlpack-step-size       | Step size for each iteration.                                   | .5      | double |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|                        | mlpack-max-iter        | Maximum number of iterations allowed                            | 500000  | int    |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|                        | mlpack-tolerance       | Maximum absolute tolerance to terminate algorithm.              | 1e-4    | double |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|                        | mlpack-momentum        | Maximum absolute tolerance to terminate algorithm.              | .05     | double |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|   momentum-nesterov    | mlpack-step-size       | Step size for each iteration.                                   | .5      | double |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|                        | mlpack-max-iter        | Maximum number of iterations allowed                            | 500000  | int    |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|                        | mlpack-tolerance       | Maximum absolute tolerance to terminate algorithm.              | 1e-4    | double |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|                        | mlpack-momentum        | Maximum absolute tolerance to terminate algorithm.              | .05     | double |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|        sgd             | mlpack-step-size       | Step size for each iteration.                                   | .5      | double |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|                        | mlpack-max-iter        | Maximum number of iterations allowed                            | 500000  | int    |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|                        | mlpack-tolerance       | Maximum absolute tolerance to terminate algorithm.              | 1e-4    | double |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|        rms-prop        | mlpack-step-size       | Step size for each iteration.                                   | .5      | double |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|                        | mlpack-max-iter        | Maximum number of iterations allowed                            | 500000  | int    |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|                        | mlpack-tolerance       | Maximum absolute tolerance to terminate algorithm.              | 1e-4    | double |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|                        | mlpack-alpha           | Smoothing constant                                              | .99     | double |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|                        | mlpack-eps             | Value used to initialize the mean squared gradient parameter.   | 1e-8    | double |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+

149
Various examples of using the mlpack optimizer:
150
151
152

.. code:: cpp

153
   // sgd with defaults
154
   auto optimizer = xacc::getOptimizer("mlpack", {std::make_pair("mlpack-optimizer", "sgd")});
155
156
157
158
159
160
161
   // default adam
   optimizer = xacc::getOptimizer("mlpack")
   // adagrad with 30 max iters and .01 step size
   auto optimizer = xacc::getOptimizer("mlpack", {std::make_pair("mlpack-optimizer", "adagrad"),
                                                  std::make_pair("mlpack-step-size", .01),
                                                  std::make_pair("mlpack-max-iter", 30)});

162
163
164
165
166
167

or in Python

.. code:: python

   optimizer = xacc.getOptimizer('mlpack', {'mlpack-optimizer':'sgd'})
168
169
170
171
172
173
   // default adam
   optimizer = xacc.getOptimizer("mlpack")
   // adagrad with 30 max iters and .01 step size
   optimizer = xacc.getOptimizer("mlpack", {'mlpack-optimizer':'adagrad',
                                            'mlpack-step-size':.01,
                                            'mlpack-max-iter':30})
174
175
NLOpt
+++++
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
| ``nlopt-optimizer``    | Optimizer Parameter    |                  Parameter Description                          | default | type   |
+========================+========================+=================================================================+=========+========+
|        cobyla          | nlopt-ftol             | Maximum absolute tolerance to terminate algorithm.              | 1e-6    | double |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|                        | nlopt-maxeval          | Maximum number of iterations allowed                            | 1000    | int    |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|        l-bfgs          | nlopt-ftol             | Maximum absolute tolerance to terminate algorithm.              |   1e-6  | double |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|                        | nlopt-maxeval          | Maximum number of iterations allowed                            | 1000    | int    |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|      nelder-mead       | nlopt-ftol             | Maximum absolute tolerance to terminate algorithm.              | 1e-6    | double |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
|                        | nlopt-maxeval          | Maximum number of iterations allowed                            | 1000    | int    |
+------------------------+------------------------+-----------------------------------------------------------------+---------+--------+
191
192
193

Accelerators
------------
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
Here we detail all available XACC ``Accelerators`` and their exposed input parameters.

IBM
+++
The IBM Accelerator by default targets the remote ``ibmq_qasm_simulator``. You can point to a
different backend in two ways:

.. code:: cpp

   auto ibm_valencia = xacc::getAccelerator("ibm:ibmq_valencia");
   ... or ...
   auto ibm_valencia = xacc::getAccelerator("ibm", {std::make_pair("backend", "ibmq_valencia")});

in Python

.. code:: python

211
   ibm_valencia = xacc.getAccelerator('ibm:ibmq_valencia');
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
   ... or ...
   ibm_valencia = xacc.getAccelerator('ibm', {'backend':'ibmq_valencia')});

You can specify the number of shots in this way as well

.. code:: cpp

   auto ibm_valencia = xacc::getAccelerator("ibm:ibmq_valencia", {std::make_pair("shots", 2048)});

or in Python

.. code:: Python

   ibm_valencia = xacc.getAccelerator('ibm:ibmq_valencia', {'shots':2048)});

In order to target the remote backend (for ``initialize()`` or ``execute()``) you must provide
228
your IBM credentials to XACC. To do this add the following to a plain text file ``$HOME/.ibm_config``
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
261
262
263
264
265
266
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342

.. code:: bash

   key: YOUR_KEY_HERE
   hub: HUB
   group: GROUP
   project: PROJECT

You can also create this file using the ``xacc`` Python module

.. code:: bash

   $ python3 -m xacc -c ibm -k YOUR_KEY --group GROUP --hub HUB --project PROJECT --url URL
   [ for public API ]
   $ python3 -m xacc -c ibm -k YOUR_KEY

where you provide URL, HUB, PROJECT, GROUP, and YOUR_KEY.

Aer
+++
The Aer Accelerator provides a great example of contributing plugins or extensions to core C++ XACC interfaces
from Python. To see how this is done, checkout the code `here <https://github.com/eclipse/xacc/blob/master/python/plugins/aer/aer_accelerator.py>`_.
This Accelerator connects the XACC IR infrastructure with the ``qiskit-aer`` simulator, providing a
robust simulator that can mimic noise models published by IBM backends. Note to use these noise models you must
have setup your ``$HOME/.ibm_config`` file (see above discussion on IBM Accelerator).

.. code:: python

   aer = xacc.getAccelerator('aer')
   ... or ...
   aer = xacc.getAccelerator('aer', {'shots':8192})
   ... or ...
   # For ibmq_johannesburg-like readout error
   aer = xacc.getAccelerator('aer', {'shots':2048, 'backend':'ibmq_johannesburg', 'readout_error':True})
   ... or ...
   # For all ibmq_johannesburg-like errors
   aer = xacc.getAccelerator('aer', {'shots':2048, 'backend':'ibmq_johannesburg',
                                    'readout_error':True,
                                    'thermal_relaxation':True,
                                    'gate_error':True})

You can also use this simulator from C++, just make sure you load the Python external language plugin.

.. code:: cpp

   xacc::Initialize();
   xacc::external::load_external_language_plugins();
   auto accelerator = xacc::getAccelerator("aer", {std::make_pair("shots", 8192),
                                                   std::make_pair("readout_error", true)});
   .. run simulation

   xacc::external::unload_external_language_plugins();
   xacc::Finalize();

QCS
+++
XACC provides support for the Rigetti QCS platform through the QCS Accelerator implementation. This
Accelerator requires a few extra third-party libraries that you will need to install in order
to get QCS support. Specifically we need ``libzmq``, ``cppzmq``, ``msgpack-c``, and ``uuid-dev``.
Note that more than likely this will only be built on the QCS Centos 7 VM, so the following
instructions are specifically for that OS.

.. code:: bash

   $ git clone https://github.com/zeromq/libzmq
   $ cd libzmq/ && mkdir build && cd build
   $ cmake .. -DCMAKE_INSTALL_PREFIX=~/.zmq
   $ make -j12 install

   $ cd ../..
   $ git clone https://github.com/zeromq/cppzmq
   $ cd cppzmq/ && mkdir build && cd build/
   $ cmake .. -DCMAKE_INSTALL_PREFIX=~/.zmq -DCMAKE_PREFIX_PATH=~/.zmq
   $ make -j12 install

   $ cd ../..
   $ git clone https://github.com/msgpack/msgpack-c/
   $ cd msgpack-c/ && mkdir build && cd build
   $ cmake .. -DCMAKE_INSTALL_PREFIX=~/.zmq
   $ make -j12 install
   $ cd ../..

   $ sudo yum install uuid-dev devtoolset-8-gcc devtoolset-8-gcc-c++
   $ scl enable devtoolset-8 -- bash

   [go to your xacc build directory]
   cmake .. -DUUID_LIBRARY=/usr/lib64/libuuid.so.1
   make install

There is no further configuration for using the QCS platform.

To use the QCS Accelerator targeting something like ``Aspen-4-2Q-A`` (for example, replace with your lattice):

.. code:: cpp

   auto qcs = xacc::getAccelerator("qcs:Aspen-4-2Q-A", {std::make_pair("shots", 10000)});

or in Python

.. code:: python

   qcs = xacc.getAccelerator('qcs:Aspen-4-2Q-A', {'shots':10000)});

For now you must manually map your ``CompositeInstruction`` to the correct physical bits
provided by your lattice. To do so, run

.. code:: python

   qpu = xacc.getAccelerator('qcs:Aspen-4-2Q-A')
   [given CompositeInstruction f]
   f.defaultPlacement(qpu)
   [or manually]
   f.mapBits([5,9])

343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
IonQ
++++
The IonQ Accelerator by default targets the remote ``simulator`` backend. You can point to the physical
QPU in two ways:

.. code:: cpp

   auto ionq = xacc::getAccelerator("ionq:qpu");
   ... or ...
   auto ionq = xacc::getAccelerator("ionq", {std::make_pair("backend", "qpu")});

in Python

.. code:: python

   ionq = xacc.getAccelerator('ionq:qpu');
   ... or ...
   ionq = xacc.getAccelerator('ionq', {'backend':'qpu')});

You can specify the number of shots in this way as well

.. code:: cpp

   auto ionq = xacc::getAccelerator("ionq", {std::make_pair("shots", 2048)});

or in Python

.. code:: Python

   ionq = xacc.getAccelerator('ionq', {'shots':2048)});

In order to target the simulator or QPU (for ``initialize()`` or ``execute()``) you must provide
your IonQ credentials to XACC. To do this add the following to a plain text file ``$HOME/.ionq_config``

.. code:: bash

   key: YOUR_KEY_HERE
   url: https://api.ionq.co/v0
381
382
383

DWave
+++++
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
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
452
The DWave Accelerator by default targets the remote ``DW_2000Q_VFYC_2_1`` backend. You can point to a
different backend in two ways:

.. code:: cpp

   auto dw = xacc::getAccelerator("dwave:DW_2000Q");
   ... or ...
   auto dw = xacc::getAccelerator("dwave", {std::make_pair("backend", "DW_2000Q")});

in Python

.. code:: python

   dw = xacc.getAccelerator('dwave:DW_2000Q');
   ... or ...
   dw = xacc.getAccelerator('dwave', {'backend':'DW_2000Q')});

You can specify the number of shots in this way as well

.. code:: cpp

   auto dw = xacc::getAccelerator("dwave", {std::make_pair("shots", 2048)});

or in Python

.. code:: Python

   dw = xacc.getAccelerator('dwave', {'shots':2048)});

In order to target the remote backend (for ``initialize()`` or ``execute()``) you must provide
your DWave credentials to XACC. To do this add the following to a plain text file ``$HOME/.dwave_config``

.. code:: bash

   key: YOUR_KEY_HERE
   url: https://cloud.dwavesys.com

You can also create this file using the ``xacc`` Python module

.. code:: bash

   $ python3 -m xacc -c dwave -k YOUR_KEY

where you provide YOUR_KEY.

DWave Neal
++++++++++
The DWave Neal Accelerator provides another example of contributing plugins or extensions to core C++ XACC interfaces
from Python. To see how this is done, checkout the code `here <https://github.com/eclipse/xacc/blob/master/python/plugins/dwave/dwave_neal_accelerator.py>`_.
This Accelerator connects the XACC IR infrastructure with the ``dwave-neal`` simulator, providing a local
simulator that can mimic DWave QPU execution.

.. code:: python

   aer = xacc.getAccelerator('dwave-neal')
   ... or ...
   aer = xacc.getAccelerator('dwave-neal', {'shots':2000})

You can also use this simulator from C++, just make sure you load the Python external language plugin.

.. code:: cpp

   xacc::Initialize();
   xacc::external::load_external_language_plugins();
   auto accelerator = xacc::getAccelerator("dwave-neal", {std::make_pair("shots", 8192)});
   .. run simulation

   xacc::external::unload_external_language_plugins();
   xacc::Finalize();
453

Nguyen, Thien's avatar
Nguyen, Thien committed
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
QuaC
++++
The `QuaC <https://github.com/ORNL-QCI/QuaC/tree/xacc-integration>`_ accelerator is a pulse-level accelerator (simulation only) that can execute quantum circuits at both gate and pulse (analog) level.

To use this accelerator, you need to build and install QuaC (see `here <https://github.com/ORNL-QCI/QuaC/tree/xacc-integration#build-xacc-quac-accelerator-plugin>`_ for instructions.) 

In pulse mode, you need to provide the QuaC accelerator a dynamical system model 
which can be constructed from an OpenPulse-format Hamiltonian JSON:

.. code:: python

   hamiltonianJson = {
      "description": "Hamiltonian of a one-qubit system.\n",
      "h_str": ["-0.5*omega0*Z0", "omegaa*X0||D0"],
      "osc": {},
      "qub": {
         "0": 2
      },
      "vars": {
         "omega0": 6.2831853,
         "omegaa": 0.0314159
      } 
   }
   # Create a pulse system model object 
   model = xacc.createPulseModel()
   # Load the Hamiltonian JSON (string) to the system model
   loadResult = model.loadHamiltonianJson(json.dumps(hamiltonianJson))

The QuaC simulator can then be requested by

.. code:: python

   qpu = xacc.getAccelerator('QuaC', {'system-model': model.name()})

Pulse-level instructions can be constructed manually (assigning sample points)

.. code:: python

   pulseData = np.ones(pulseLength)
   # Register the pulse named 'square' as an XACC instruction
   xacc.addPulse('square', pulseData) 
   provider = xacc.getIRProvider('quantum')
   squarePulseInst = provider.createInstruction('square', [0])
   squarePulseInst.setChannel('d0')
   # This instruction can be added to any XACC quantum Composite Instruction
   prog.addInstruction(squarePulseInst)

or automatically (converting from quantum gates to pulses). 
To use automatic gate-to-pulse functionality, we need to load a pulse library to the accelerator as follows:

.. code:: python

   # Load the backend JSON file which contains a pulse library
   backendJson = open('backends.json', 'r').read()
   qpu.contributeInstructions(backendJson) 

For more information, please check out these `examples <https://github.com/ORNL-QCI/QuaC/tree/xacc-integration/xacc_examples/python>`_.
511

512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
Qrack
+++++
The `vm6502q/qrack <https://github.com/vm6502q/qrack>`_ simulator-based accelerator provides optional OpenCL-based GPU acceleration, as well as a novel simulator optimization layer.

.. code:: cpp

   auto qrk = xacc::getAccelerator("qrack", {std::make_pair("shots", 2048)});

By default, it selects initialization parameters that are commonly best for a wide range of use cases. However, it is highly configurable through a number of exposed parameters:

+-----------------------------+------------------------------------------------------------------------+-------------+--------------------------+
|  Initialization Parameter   |                  Parameter Description                                 |    type     |         default          |
+=============================+========================================================================+=============+==========================+
|    shots                    | Number of iterations to repeat the circuit for                         |    int      | -1 (Z-expectation only)  |
+-----------------------------+------------------------------------------------------------------------+-------------+--------------------------+
|    use_opencl               | Use OpenCL acceleration if available, (otherwise native C++11)         |    bool     | true                     |
+-----------------------------+------------------------------------------------------------------------+-------------+--------------------------+
|    use_qunit                | Turn on the novel optimization layer, (otherwise "Schrödinger method") |    bool     | true                     |
+-----------------------------+------------------------------------------------------------------------+-------------+--------------------------+
|    device_id                | The (Qrack) device ID number of the OpenCL accelerator to use          |    int      | -1 (auto-select)         |
+-----------------------------+------------------------------------------------------------------------+-------------+--------------------------+
|    do_normalize             | Enable small norm probability amplitude flooring and normalization     |    bool     | true                     |
+-----------------------------+------------------------------------------------------------------------+-------------+--------------------------+
|    zero_threshold           | Norm threshold for clamping probability amplitudes to 0                |    double   | 1e-14/1e-30 float/double |
+-----------------------------+------------------------------------------------------------------------+-------------+--------------------------+

538
539
Algorithms
----------
Mccaskey, Alex's avatar
Mccaskey, Alex committed
540
541
542
XACC exposes hybrid quantum-classical Algorithm implementations for the variational quantum eigensolver (VQE), data-driven
circuit learning (DDCL), and chemistry reduced density matrix generation (RDM).

543
544
VQE
+++
Mccaskey, Alex's avatar
Mccaskey, Alex committed
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
The VQE Algorithm requires the following input information:

+------------------------+-----------------------------------------------------------------+--------------------------------------+
|  Algorithm Parameter   |                  Parameter Description                          |             type                     |
+========================+=================================================================+======================================+
|    observable          | The hermitian operator, vqe computes ground eigenvalue of this  | std::shared_ptr<Observable>          |
+------------------------+-----------------------------------------------------------------+--------------------------------------+
|    ansatz              | The unmeasured, parameterized quantum circuit                   | std::shared_ptr<CompositeInstruction>|
+------------------------+-----------------------------------------------------------------+--------------------------------------+
|    optimizer           | The classical optimizer to use                                  | std::shared_ptr<Optimizer>           |
+------------------------+-----------------------------------------------------------------+--------------------------------------+
|    accelerator         | The Accelerator backend to target                               | std::shared_ptr<Accelerator>         |
+------------------------+-----------------------------------------------------------------+--------------------------------------+

This Algorithm will add ``opt-val`` (``double``) and ``opt-params`` (``std::vector<double>``) to the provided ``AcceleratorBuffer``.
The results of the algorithm are therefore retrieved via these keys (see snippet below). Note you can
control the initial VQE parameters with the ``Optimizer`` ``initial-parameters`` key (by default all zeros).

.. code:: cpp

   #include "xacc.hpp"
   #include "xacc_observable.hpp"

   int main(int argc, char **argv) {
     xacc::Initialize(argc, argv);

     // Get reference to the Accelerator
     // specified by --accelerator argument
     auto accelerator = xacc::getAccelerator();

     // Create the N=2 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 optimizer = xacc::getOptimizer("nlopt",
                            {std::make_pair("initial-parameters", {.5})});

     // JIT map Quil QASM Ansatz to IR
     xacc::qasm(R"(
    .compiler xasm
    .circuit deuteron_ansatz
    .parameters theta
    .qbit q
    X(q[0]);
    Ry(q[1], theta);
    CNOT(q[1],q[0]);
    )");
    auto ansatz = xacc::getCompiled("deuteron_ansatz");

    // Get the VQE Algorithm and initialize it
    auto vqe = xacc::getAlgorithm("vqe");
    vqe->initialize({std::make_pair("ansatz", ansatz),
                   std::make_pair("observable", H_N_2),
                   std::make_pair("accelerator", accelerator),
                   std::make_pair("optimizer", optimizer)});

    // Allocate some qubits and execute
    auto buffer = xacc::qalloc(2);
    vqe->execute(buffer);

    auto ground_energy = (*buffer)["opt-val"].as<double>();
    auto params = (*buffer)["opt-params"].as<std::vector<double>>();
  }

In Python:

.. code:: python

   import xacc

   # Get access to the desired QPU and
   # allocate some qubits to run on
   qpu = xacc.getAccelerator('tnqvm')
   buffer = xacc.qalloc(2)

   # Construct the Hamiltonian as an XACC-VQE PauliOperator
   ham = xacc.getObservable('pauli', '5.907 - 2.1433 X0X1 - 2.1433 Y0Y1 + .21829 Z0 - 6.125 Z1')


   xacc.qasm('''.compiler xasm
   .circuit ansatz2
   .parameters t0
   .qbit q
   X(q[0]);
   Ry(q[1],t0);
   CX(q[1],q[0]);
   ''')
   ansatz2 = xacc.getCompiled('ansatz2')

   opt = xacc.getOptimizer('nlopt', {'initial-parameters':[.5]})

   # Create the VQE algorithm
   vqe = xacc.getAlgorithm('vqe', {
                        'ansatz': ansatz2,
                        'accelerator': qpu,
                        'observable': ham,
                        'optimizer': opt
                        })
   vqe.execute(buffer)
   energy = buffer['opt-val']
   params = buffer['opt-params']

649
650
651

DDCL
++++
Mccaskey, Alex's avatar
Mccaskey, Alex committed
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
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
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
The DDCL Algorithm implements the following algorithm - given a target probability distribution,
propose a parameterized quantum circuit and train (minimize loss) the circuit to reproduce
that given target distribution. We design DDCL to be extensible in loss function computation and
gradient computation strategies.

The DDCL Algorithm requires the following input information:

+------------------------+-----------------------------------------------------------------+--------------------------------------+
|  Algorithm Parameter   |                  Parameter Description                          |             type                     |
+========================+=================================================================+======================================+
|    target_dist         | The target probability distribution to reproduce                | std::vector<double>                  |
+------------------------+-----------------------------------------------------------------+--------------------------------------+
|    ansatz              | The unmeasured, parameterized quantum circuit                   | std::shared_ptr<CompositeInstruction>|
+------------------------+-----------------------------------------------------------------+--------------------------------------+
|    optimizer           | The classical optimizer to use, can be gradient based           | std::shared_ptr<Optimizer>           |
+------------------------+-----------------------------------------------------------------+--------------------------------------+
|    accelerator         | The Accelerator backend to target                               | std::shared_ptr<Accelerator>         |
+------------------------+-----------------------------------------------------------------+--------------------------------------+
|    loss                | The loss strategy to use                                        |          std::string                 |
+------------------------+-----------------------------------------------------------------+--------------------------------------+
|    gradient            | The gradient strategy to use                                    |  std::string                         |
+------------------------+-----------------------------------------------------------------+--------------------------------------+

As of this writing, loss can take ``js`` and ``mmd`` values for Jansen-Shannon divergence and Maximum Mean Discrepancy, respectively.
More are being added. Also, gradient can take ``js-parameter-shift`` and ``mmd-parameter-shift`` values. These gradient
strategies will shift each parameter by plus or minus pi over 2.

.. code:: cpp

   #include "xacc.hpp"

   int main(int argc, char **argv) {
     xacc::Initialize(argc, argv);

     xacc::external::load_external_language_plugins();
     xacc::set_verbose(true);

     // Get reference to the Accelerator
     auto accelerator = xacc::getAccelerator("aer");

     auto optimizer = xacc::getOptimizer("mlpack");
     xacc::qasm(R"(
    .compiler xasm
    .circuit qubit2_depth1
    .parameters x
    .qbit q
    U(q[0], x[0], -pi/2, pi/2 );
    U(q[0], 0, 0, x[1]);
    U(q[1], x[2], -pi/2, pi/2);
    U(q[1], 0, 0, x[3]);
    CNOT(q[0], q[1]);
    U(q[0], 0, 0, x[4]);
    U(q[0], x[5], -pi/2, pi/2);
    U(q[1], 0, 0, x[6]);
    U(q[1], x[7], -pi/2, pi/2);
    )");
     auto ansatz = xacc::getCompiled("qubit2_depth1");

     std::vector<double> target_distribution {.5, .5, .5, .5};

     auto ddcl = xacc::getAlgorithm("ddcl");
     ddcl->initialize({std::make_pair("ansatz", ansatz),
                   std::make_pair("target_dist", target_distribution),
                   std::make_pair("accelerator", accelerator),
                   std::make_pair("loss", "js"),
                   std::make_pair("gradient", "js-parameter-shift"),
                   std::make_pair("optimizer", optimizer)});

     // Allocate some qubits and execute
     auto buffer = xacc::qalloc(2);
     ddcl->execute(buffer);

     // Print the result
     std::cout << "Loss: " << buffer["opt-val"].as<double>()
            << "\n";

     xacc::external::unload_external_language_plugins();
     xacc::Finalize();
   }

or in Python

.. code:: python

   import xacc
   # Get the QPU and allocate a single qubit
   qpu = xacc.getAccelerator('aer')
   qbits = xacc.qalloc(1)

   # Get the MLPack Optimizer, default is Adam
   optimizer = xacc.getOptimizer('mlpack')

   # Create a simple quantum program
   xacc.qasm('''
   .compiler xasm
   .circuit foo
   .parameters x,y,z
   .qbit q
   Ry(q[0], x);
   Ry(q[0], y);
   Ry(q[0], z);
   ''')
   f = xacc.getCompiled('foo')

   # Get the DDCL Algorithm, initialize it
   # with necessary parameters
   ddcl = xacc.getAlgorithm('ddcl', {'ansatz': f,
                                  'accelerator': qpu,
                                  'target_dist': [.5,.5],
                                  'optimizer': optimizer,
                                  'loss': 'js',
                                  'gradient': 'js-parameter-shift'})
   # execute
   ddcl.execute(qbits)

   print(qbits.keys())
   print(qbits['opt-val'])
   print(qbits['opt-params'])

771
772
773
774
Rotoselect
++++++++++
The ``Rotoselect`` Quantum Circuit Structure Learning Algorithm (`Ostaszewski et al. (2019) <https://arxiv.org/abs/1905.09692>`_) requires the following input information:

775
776
777
778
779
780
781
782
783
784
785
786
+------------------------+------------------------------------------------------------------------+------------------------------------------+
|  Algorithm Parameter   |                  Parameter Description                                 |             type                         |
+========================+========================================================================+==========================================+
|    observable          | The hermitian operator, Rotoselect computes ground eigenvalue of this  | std::shared_ptr<Observable>/Observable*  |
+------------------------+------------------------------------------------------------------------+------------------------------------------+
|    layers              | Number of circuit layers. Each layer consists of parametrized          | int                                      |
|                        | single-qubit rotations followed by a ladder of controlled-Z gates.     |                                          |
+------------------------+------------------------------------------------------------------------+------------------------------------------+
|    iterations          | The number of training iterations                                      | int                                      |
+------------------------+------------------------------------------------------------------------+------------------------------------------+
|    accelerator         | The Accelerator backend to target                                      | std::shared_ptr<Accelerator>/Accelerator*|
+------------------------+------------------------------------------------------------------------+------------------------------------------+
787

Mccaskey, Alex's avatar
Mccaskey, Alex committed
788
This ``Rotoselect`` algorithm is designed to learn a good circuit structure
789
790
791
(generators of rotation are selected from the set of Pauli gates)
at fixed depth (``layers``) to minimize the cost function (``observable``).
This Algorithm will add ``opt-val`` (``double``) to the provided ``AcceleratorBuffer``.
Mccaskey, Alex's avatar
Mccaskey, Alex committed
792
The result of the algorithm is therefore retrieved via this key (see snippet below).
793
794
795
796
797
798
799
800
801
802

.. code:: cpp
  #include "xacc.hpp"
  #include "xacc_observable.hpp"
  #include "xacc_service.hpp"

  int main(int argc, char **argv) {
    xacc::Initialize(argc, argv);
    // Use the Qpp simulator as the accelerator
    auto acc = xacc::getAccelerator("qpp");
Mccaskey, Alex's avatar
Mccaskey, Alex committed
803
804

    // In this example, we try to find the ground state energy of the 5-qubit Heisenberg model on a
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
    // 1D lattice with periodic boundary conditions.
    auto buffer = xacc::qalloc(5);
    // The corresponding Hamiltonian is:
    // Note: we set all scalar params to 1.0 for simplicity.
    auto observable = xacc::quantum::getObservable(
        "pauli",
        std::string("X0 X1 + X1 X2 + X2 X3 + X3 X4 + X4 X0 + "
                    "Y0 Y1 + Y1 Y2 + Y2 Y3 + Y3 Y4 + Y4 Y0 +"
                    "Z0 Z1 + Z1 Z2 + Z2 Z3 + Z3 Z4 + Z4 Z0 + "
                    "Z0 + Z1 + Z2 + Z3 + Z4"));

    auto rotoselect = xacc::getService<xacc::Algorithm>("rotoselect");
    // We train the circuit that has 6 layers for 1000 iterations.
    // Note: we can repeat this training multiple times to collect the mean and standard deviation
    // as reported in https://arxiv.org/abs/1905.09692
    rotoselect->initialize({
                            std::make_pair("accelerator", acc),
                            std::make_pair("observable", observable),
                            std::make_pair("layers", 6),
                            std::make_pair("iterations", 1000),
                          });
Mccaskey, Alex's avatar
Mccaskey, Alex committed
826

827
828
829
830
831
    rotoselect->execute(buffer);
    // Expected value ~ -8.4 -> -8.5
    // Ref: FIG. 2 of https://arxiv.org/abs/1905.09692
    std::cout << "Energy: " << (*buffer)["opt-val"].as<double>() << "\n";
  }
Mccaskey, Alex's avatar
Mccaskey, Alex committed
832

833

834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
RBM Classification
++++++++++++++++++
The ``rbm_classification`` algorithm provides an implementation that trains a
restricted boltzmann machine via sampling of a quantum annealer for the purpose of
classification. (`Caldeira et al. (2019) <https://arxiv.org/abs/1911.06259>`_)
It exposes the following input information:

+------------------------+------------------------------------------------------------------------+------------------------------------------+
|  Algorithm Parameter   |                  Parameter Description                                 |             type                         |
+========================+========================================================================+==========================================+
|    nv                  | The number of visible units                                            | int                                      |
+------------------------+------------------------------------------------------------------------+------------------------------------------+
|    nh                  | The number of hidden units                                             | int                                      |
+------------------------+------------------------------------------------------------------------+------------------------------------------+
|    batch-size          | The batch size, defaults to 1                                          | int                                      |
+------------------------+------------------------------------------------------------------------+------------------------------------------+
|    n-gibbs-steps       | The number of gibbs steps to use in post-processing of dwave data      | int                                      |
+------------------------+------------------------------------------------------------------------+------------------------------------------+
|    train-steps         | Hard-code the number of training iterations/steps, by default this is  | int                                      |
|                        | set to -1, meaning unlimited iterations                                |                                          |
+------------------------+------------------------------------------------------------------------+------------------------------------------+
|    epochs              | The number of training epochs, defaults to 1                           | int                                      |
+------------------------+------------------------------------------------------------------------+------------------------------------------+
|    train-file          | The location (relative to pwd) of the training data (as npy file)      | string                                   |
+------------------------+------------------------------------------------------------------------+------------------------------------------+
|  expectation-strategy  | Strategy to use in computing model expectation values, can be gibbs,   | string                                   |
|                        | quantum-annealing, discriminative, or cd                               |                                          |
+------------------------+------------------------------------------------------------------------+------------------------------------------+
|    backend             | The desired quantum-annealing backend (defaults to dwave-neal), can be | string                                   |
|                        | any of the available D-Wave backends, must be provided as dwave:BEND   |                                          |
+------------------------+------------------------------------------------------------------------+------------------------------------------+
|    shots               | The number of samples to draw from the dwave backend                   | int                                      |
+------------------------+------------------------------------------------------------------------+------------------------------------------+
|    embedding           | The minor graph embedding to use, if not provided, one will be         |                                          |
|                        | computed and used for subsequent calls to the dwave backend.           | map<int, vector<int>>                    |
+------------------------+------------------------------------------------------------------------+------------------------------------------+

Example usage in Python:

.. code:: python

    import xacc

    # Create the RBM Classification algorithm
    algo = xacc.getAlgorithm('rbm-classification',
                {
                'nv':64,
                'nh':64,
                'train-file':'sg_train_64bits.npy',
                'expectation-strategy':'quantum-annealing',
                'backend':'dwave:DW_2000Q_5',
                'shots':100,
                })

    qbits = xacc.qalloc()
    algo.execute(qbits)

    # get the trained RBM weights
    # for further use and post-processing
    w = qbits['w']
    bv = qbits['bv']
    bh = qbits['bh']

Mccaskey, Alex's avatar
Mccaskey, Alex committed
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
Quantum Process Tomography
++++++++++++++++++++++++++
The ``qpt`` algorithm provides an implementation of Algorithm that uses linear
inversion to compute the chi process matrix for a desired circuit.

+------------------------+------------------------------------------------------------------------+------------------------------------------+
|  Algorithm Parameter   |                  Parameter Description                                 |             type                         |
+========================+========================================================================+==========================================+
|    circuit             | The circuit to characterize                                            | pointer-like CompositeInstruction        |
+------------------------+------------------------------------------------------------------------+------------------------------------------+
|    accelerator         | The backend quantum computer to use                                    | pointer-like Accelerator                 |
+------------------------+------------------------------------------------------------------------+------------------------------------------+
|    qubit-map           | The physical qubits to map the logical circuit onto                    | vector<int>                              |
+------------------------+------------------------------------------------------------------------+------------------------------------------+


.. code:: cpp

   #include "xacc.hpp"

   int main(int argc, char **argv) {
     xacc::Initialize(argc, argv);
     auto acc = xacc::getAccelerator("ibm::ibmq_poughkeepsie");

     auto compiler = xacc::getCompiler("xasm");
     auto ir = compiler->compile(R"(__qpu__ void f(qbit q) {
         H(q[0]);
     })", nullptr);
     auto h = ir->getComposite("f");

     auto qpt = xacc::getAlgorithm("qpt", {
                             std::make_pair("circuit", h),
                             std::make_pair("accelerator", acc)
                             });

     auto buffer = xacc::qalloc(1);
     qpt->execute(buffer);

     auto chi_real = (*buffer)["chi-real"];
     auto chi_imag = (*buffer)["chi-imag"];

   }

or in Python

.. code:: python

   import xacc
   # Choose the QPU on which to
   # characterize the process matrix for a Hadamard
   qpu = xacc.getAccelerator('ibm:ibmq_poughkeepsie')

   # Create the CompositeInstruction containing a
   # single Hadamard instruction
   provider = xacc.getIRProvider('quantum')
   circuit = provider.createComposite('U')
   hadamard = provider.createInstruction('H', [0])
   circuit.addInstruction(hadamard)

   # Create the Algorithm, give it the circuit
   # to characterize and the backend to target
   qpt = xacc.getAlgorithm('qpt', {'circuit':circuit, 'accelerator':qpu})

   # Allocate a qubit, this will
   # store our tomography results
   buffer = xacc.qalloc(1)

   # Execute
   qpt.execute(buffer)

   # Compute the fidelity with respect to
   # the ideal hadamard process
   F = qpt.calculate('fidelity', buffer, {'chi-theoretical-real':[0., 0., 0., 0., 0., 1., 0., 1., 0., 0., 0., 0., 0., 1., 0., 1.]})
   print('\nFidelity: ', F)

Nguyen, Thien's avatar
Nguyen, Thien committed
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
QAOA
++++
The QAOA Algorithm requires the following input information:

+------------------------+-----------------------------------------------------------------+--------------------------------------+
|  Algorithm Parameter   |                  Parameter Description                          |             type                     |
+========================+=================================================================+======================================+
|    observable          | The hermitian operator represents the cost Hamiltonian.         | std::shared_ptr<Observable>          |
+------------------------+-----------------------------------------------------------------+--------------------------------------+
|    optimizer           | The classical optimizer to use                                  | std::shared_ptr<Optimizer>           |
+------------------------+-----------------------------------------------------------------+--------------------------------------+
|    accelerator         | The Accelerator backend to target                               | std::shared_ptr<Accelerator>         |
+------------------------+-----------------------------------------------------------------+--------------------------------------+
|    steps               | The number of timesteps. Corresponds to 'p' in the literature.  | int                                  |
|                        | This is optional, default = 1 if not provided.                  |                                      |
+------------------------+-----------------------------------------------------------------+--------------------------------------+

This Algorithm will add ``opt-val`` (``double``) and ``opt-params`` (``std::vector<double>``) to the provided ``AcceleratorBuffer``.
The results of the algorithm are therefore retrieved via these keys (see snippet below). Note you can
control the initial QAOA parameters with the ``Optimizer`` ``initial-parameters`` key (by default all zeros).

.. code:: cpp

   #include "xacc.hpp"
   #include "xacc_observable.hpp"
   #include "xacc_service.hpp"
   #include <random>

   // Use XACC built-in QAOA to solve a QUBO problem
   // QUBO function:
   // y = -5x1 - 3x2 - 8x3 - 6x4 + 4x1x2 + 8x1x3 + 2x2x3 + 10x3x4
   int main(int argc, char **argv) {
      xacc::Initialize(argc, argv);
      // Use the Qpp simulator as the accelerator
      auto acc = xacc::getAccelerator("qpp");
      
      auto buffer = xacc::qalloc(4);
      // The corresponding QUBO Hamiltonian is:
      auto observable = xacc::quantum::getObservable(
            "pauli",
            std::string("-5.0 - 0.5 Z0 - 1.0 Z2 + 0.5 Z3 + 1.0 Z0 Z1 + 2.0 Z0 Z2 + 0.5 Z1 Z2 + 2.5 Z2 Z3"));
      
      const int nbSteps = 12;
      const int nbParams = nbSteps*11;
      std::vector<double> initialParams;
      std::random_device rd;  
      std::mt19937 gen(rd()); 
      std::uniform_real_distribution<> dis(-2.0, 2.0);
      
      // Init random parameters
      for (int i = 0; i < nbParams; ++i)
      {
         initialParams.emplace_back(dis(gen));
      } 
      
      auto optimizer = xacc::getOptimizer("nlopt", 
         xacc::HeterogeneousMap { 
            std::make_pair("initial-parameters", initialParams),
            std::make_pair("nlopt-maxeval", nbParams*100) });
      
      auto qaoa = xacc::getService<xacc::Algorithm>("QAOA");
      
      const bool initOk = qaoa->initialize({
                              std::make_pair("accelerator", acc),
                              std::make_pair("optimizer", optimizer),
                              std::make_pair("observable", observable),
                              // number of time steps (p) param
                              std::make_pair("steps", nbSteps)
                           });
      qaoa->execute(buffer);
      std::cout << "Min QUBO: " << (*buffer)["opt-val"].as<double>() << "\n";
   }

In Python:

.. code:: python

   import xacc,sys, numpy as np

   # Get access to the desired QPU and
   # allocate some qubits to run on
   qpu = xacc.getAccelerator('qpp')

   # Construct the Hamiltonian as an XACC PauliOperator
   # This Hamiltonian corresponds to the QUBO problem:
   # y = -5x_1 -3x_2 -8x_3 -6x_4 + 4x_1x_2 + 8x_1x_3 + 2x_2x_3 + 10x_3x_4
   ham = xacc.getObservable('pauli', '-5.0 - 0.5 Z0 - 1.0 Z2 + 0.5 Z3 + 1.0 Z0 Z1 + 2.0 Z0 Z2 + 0.5 Z1 Z2 + 2.5 Z2 Z3')

   # We need 4 qubits
   buffer = xacc.qalloc(4)

   # There are 7 gamma terms (non-identity) in the cost Hamiltonian 
   # and 4 beta terms for mixer Hamiltonian
   nbParamsPerStep = 7 + 4

   # The number of steps (often referred to as 'p' parameter): 
   # alternating layers of mixer and cost Hamiltonian exponential.
   nbSteps = 4

   # Total number of params
   nbTotalParams = nbParamsPerStep * nbSteps

   # Init params randomly: 
   initParams = np.random.rand(nbTotalParams)

   # The optimizer: nlopt
   opt = xacc.getOptimizer('nlopt', { 'initial-parameters': initParams })

   # Create the QAOA algorithm
   qaoa = xacc.getAlgorithm('QAOA', {
                           'accelerator': qpu,
                           'observable': ham,
                           'optimizer': opt,
                           'steps': nbSteps
                           })

   result = qaoa.execute(buffer)
   print('Min QUBO value = ', buffer.getInformation('opt-val'))

Mccaskey, Alex's avatar
Mccaskey, Alex committed
1091

Nguyen, Thien's avatar
Nguyen, Thien committed
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
Quantum Phase Estimation
++++++++++++++++++++++++
The ``QPE`` algorithm (also known as quantum eigenvalue estimation algorithm) provides 
an implementation of Algorithm that estimates the phase (or eigenvalue) of an eigenvector of a unitary operator.

Here the unitary operator is called an `oracle` which is a quantum subroutine 
that acts upon a set of qubits and returns the answer as a phase. 
The bits precision is automatically inferred from the size of the input buffer.

+------------------------+------------------------------------------------------------------------+------------------------------------------+
|  Algorithm Parameter   |                  Parameter Description                                 |             type                         |
+========================+========================================================================+==========================================+
|    oracle              | The circuit represents the unitary operator.                           | pointer-like CompositeInstruction        |
+------------------------+------------------------------------------------------------------------+------------------------------------------+
|    accelerator         | The backend quantum computer to use.                                   | pointer-like Accelerator                 |
+------------------------+------------------------------------------------------------------------+------------------------------------------+
|   state-preparation    | The circuit to prepare the eigen state.                                | pointer-like CompositeInstruction        |
+------------------------+------------------------------------------------------------------------+------------------------------------------+


.. code:: cpp

   #include "xacc.hpp"
   #include "xacc_service.hpp"

   int main(int argc, char **argv) {
   xacc::Initialize(argc, argv);
   // Accelerator:
   auto acc = xacc::getAccelerator("qpp", {std::make_pair("shots", 4096)});
   
   // In this example: we want to estimate the *phase* of an arbitrary 'oracle'
   // i.e. Oracle(|State>) = exp(i*Phase)*|State>
   // and we need to estimate that Phase.

   // Oracle: CPhase(theta) or CU1(theta) which is defined as
   // 1 0 0 0
   // 0 1 0 0
   // 0 0 1 0
   // 0 0 0 e^(i*theta)
   // The eigenstate is |11>; i.e. CPhase(theta)|11> = e^(i*theta)|11>

   // Since this oracle operates on 2 qubits, we need to add more qubits to the buffer.
   // The more qubits we have, the more accurate the estimate.
   // Resolution := 2^(number qubits in the calculation register).
   // 5-bit precision => 7 qubits in total
   auto buffer = xacc::qalloc(7);
   auto qpe = xacc::getService<xacc::Algorithm>("QPE");
   auto compiler = xacc::getCompiler("xasm");
   
   // Create oracle: CPhase gate with theta = 2pi/3
   // i.e. the phase value to estimate is 1/3 ~ 0.33333.
   auto gateRegistry = xacc::getService<xacc::IRProvider>("quantum");
   auto oracle = gateRegistry->createComposite("oracle");
   oracle->addInstruction(gateRegistry->createInstruction("CPhase", { 0, 1 }, { 2.0 * M_PI/ 3.0 }));

   // Eigenstate preparation = |11> state
   auto statePrep = compiler->compile(R"(__qpu__ void prep1(qbit q) {
      X(q[0]); 
      X(q[1]); 
   })", nullptr)->getComposite("prep1");  
   
   // Initialize the Quantum Phase Estimation:
   qpe->initialize({
                     std::make_pair("accelerator", acc),
                     std::make_pair("oracle", oracle),
                     std::make_pair("state-preparation", statePrep)
                     });
   
   // Run the algorithm
   qpe->execute(buffer);
   // Expected result: 
   // The factor here is 2^5 (precision) = 32
   // we expect the two most-likely bitstring is 10 and 11
   // i.e. the true result is between 10/32 = 0.3125 and 11/32 = 0.34375  
   std::cout << "Probability of the two most-likely bitstrings 10 (theta = 0.3125) and 11 (theta = 0.34375 ): \n";
   std::cout << "Probability of |11010> (11) = " << buffer->computeMeasurementProbability("11010") << "\n";
   std::cout << "Probability of |01010> (10) = " << buffer->computeMeasurementProbability("01010") << "\n";

   xacc::Finalize();
   }

or in Python

.. code:: python

   import xacc,sys, numpy as np

   # Get access to the desired QPU and
   # allocate some qubits to run on
   qpu = xacc.getAccelerator('qpp',  { 'shots': 4096 })

   # In this example: we want to estimate the *phase* of an arbitrary 'oracle'
   # i.e. Oracle(|State>) = exp(i*Phase)*|State>
   # and we need to estimate that Phase.

   # The oracle is a simple T gate, and the eigenstate is |1>
   # T|1> = e^(i*pi/4)|1> 
   # The phase value of pi/4 = 2pi * (1/8)
   # i.e. if we use a 3-bit register for estimation, 
   # we will get the correct answer of 1 deterministically.

   xacc.qasm('''.compiler xasm
   .circuit oracle
   .qbit q
   T(q[0]);
   ''')
   oracle = xacc.getCompiled('oracle')

   # We need to prepare the eigenstate |1>
   xacc.qasm('''.compiler xasm
   .circuit prep
   .qbit q
   X(q[0]);
   ''')
   statePrep = xacc.getCompiled('prep')

   # We need 4 qubits (3-bit precision)
   buffer = xacc.qalloc(4)

   # Create the QPE algorithm
   qpe = xacc.getAlgorithm('QPE', {
                           'accelerator': qpu,
                           'oracle': oracle,
                           'state-preparation': statePrep
                           })

   qpe.execute(buffer)
   # We should only get the bit string of |100> = 1
   # i.e. phase value of 1/2^3 = 1/8.
   print(buffer)

Nguyen, Thien's avatar
Nguyen, Thien committed
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
QITE
++++
The Quantum Imaginary Time Evolution (QITE) Algorithm requires the following input information:
(`Motta et al. (2020) <https://arxiv.org/pdf/1901.07653.pdf>`_)

+------------------------+-----------------------------------------------------------------+--------------------------------------+
|  Algorithm Parameter   |                  Parameter Description                          |             type                     |
+========================+=================================================================+======================================+
|    observable          | The hermitian operator represents the cost Hamiltonian.         | std::shared_ptr<Observable>          |
+------------------------+-----------------------------------------------------------------+--------------------------------------+
|    accelerator         | The Accelerator backend to target                               | std::shared_ptr<Accelerator>         |
+------------------------+-----------------------------------------------------------------+--------------------------------------+
|    steps               | The number of Trotter steps.                                    | int                                  |
+------------------------+-----------------------------------------------------------------+--------------------------------------+
|    step-size           | The Trotter step size.                                          | double                               |
+------------------------+-----------------------------------------------------------------+--------------------------------------+

Optionally, users can provide these parameters:

+------------------------+-----------------------------------------------------------------+--------------------------------------+
|  Algorithm Parameter   |                  Parameter Description                          |             type                     |
+========================+=================================================================+======================================+
|    ansatz              | State preparation circuit.                                      | std::shared_ptr<CompositeInstruction>|
+------------------------+-----------------------------------------------------------------+--------------------------------------+
|    analytical          | If true, perform an analytical run rather than                  | boolean                              |
|                        | executing quantum circuits on the Accelerator backend.          |                                      |
+------------------------+-----------------------------------------------------------------+--------------------------------------+
|    initial-state       | For `analytical` mode only, select the initial state.           | int                                  |
+------------------------+-----------------------------------------------------------------+--------------------------------------+

This Algorithm will add ``opt-val`` (``double``) which is the energy value at the final Trotter step to the provided ``AcceleratorBuffer``.
The results of the algorithm are therefore retrieved via these keys (see snippet below). 
Also, energy values at each Trotter step are stored in the ``exp-vals`` field (``vector<double>``).

Nguyen, Thien's avatar
Nguyen, Thien committed
1257
1258
1259
1260
1261
1262
1263
1264
Note: during execution, the following line may be logged to the output console:

.. code:: cpp

   warning: solve(): system seems singular; attempting approx solution

This is completely normal and can be safely ignored.

Nguyen, Thien's avatar
Nguyen, Thien committed
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
.. code:: cpp

   #include "xacc.hpp"
   #include "xacc_observable.hpp"
   #include "xacc_service.hpp"

   int main(int argc, char **argv) {
      xacc::Initialize(argc, argv);
      // Use the Qpp simulator as the accelerator
      auto acc = xacc::getAccelerator("qpp");
      
      auto buffer = xacc::qalloc(1);
      auto observable = xacc::quantum::getObservable(
            "pauli",
            std::string("0.7071067811865475 X0 + 0.7071067811865475 Z0"));
      
      auto qite = xacc::getService<xacc::Algorithm>("qite");
      const int nbSteps = 25;
      const double stepSize = 0.1;

      const bool initOk =  qite->initialize({
         std::make_pair("accelerator", acc),
         std::make_pair("steps", nbSteps),
         std::make_pair("observable", observable),
         std::make_pair("step-size", stepSize)
      });

      qite->execute(buffer);
      std::cout << "Min Energy: " << (*buffer)["opt-val"].as<double>() << "\n";
   }

In Python:

.. code:: python

   import xacc,sys, numpy as np
   import matplotlib.pyplot as plt

   # Get access to the desired QPU and
   # allocate some qubits to run on
   qpu = xacc.getAccelerator('qpp')

   # Construct the Hamiltonian as an XACC PauliOperator
   ham = xacc.getObservable('pauli', '0.70710678118 X0 + 0.70710678118 Z0')

   # We just need 1 qubit
   buffer = xacc.qalloc(1)

   # Horizontal axis: 0 -> 2.5
   # The number of Trotter steps 
   nbSteps = 25

   # The Trotter step size
   stepSize = 0.1

   # Create the QITE algorithm
   qite = xacc.getAlgorithm('qite', {
                           'accelerator': qpu,
                           'observable': ham,
                           'step-size': stepSize,
                           'steps': nbSteps
                           })

   result = qite.execute(buffer)

   # Expected result: ~ -1
   print('Min energy value = ', buffer.getInformation('opt-val'))
   E = buffer.getInformation('exp-vals')
   # Plot energy vs. beta
   plt.plot(np.arange(0, nbSteps + 1) * stepSize, E, 'ro', label = 'XACC QITE')
   plt.grid()
   plt.show()


1339
1340
Accelerator Decorators
----------------------
1341
1342
ROErrorDecorator
++++++++++++++++
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
The ``ROErrorDecorator`` provides an ``AcceleratorDecorator`` implementation for affecting
readout error mitigation as in the `deuteron paper <https://journals.aps.org/prl/abstract/10.1103/PhysRevLett.120.210501>`_.
It takes as input readout error probabilities ``p(0|1)`` and ``p(1|0)`` for all qubits and shifts expecation values
accordingly (see paper).

By default it will request the backend properties from the decorated ``Accelerator`` (``Accelerator::getProperties()``). This method
returns a ``HeterogeneousMap``. If this map contains a vector of doubles at keys ``p01s`` and ``p10s``, then these
values will be used in the readout error correction. Alternatively, if the backend does not provide this data,
users can provide a custom JSON file containing the probabilities. This file should be structured as such

.. code:: bash

   {
       "shots": 1024,
       "backend": "qcs:Aspen-2Q-A",
       "0": {
           "0|1": 0.0565185546875,
           "1|0": 0.0089111328125,
           "+": 0.0654296875,
           "-": 0.047607421875
       },
       "1": {
           "0|1": 0.095458984375,
           "1|0": 0.0115966796875,
           "+": 0.1070556640625,
           "-": 0.0838623046875
       }
   }

Automating readout error mitigation with this decorator can be done in the following way:

.. code:: python

   qpu = xacc.getAccelerator('ibm:ibmq_johannesburg', {'shots':1024})

   # Turn on readout error correction by decorating qpu
   qpu = xacc.getAcceleratorDecorator('ro-error', qpu)

   # Now use qpu as your Accelerator...
   # execution will be automatically readout
   # error corrected

Similarly, with a provided configuration file

.. code:: cpp

   auto qpu = xacc::getAccelerator("qcs:Aspen-2Q-A");
   qpu = xacc::getAcceleratorDecorator("ro-error", qpu, {std::make_pair("file", "probs.json")});
1391

Mccaskey, Alex's avatar
Mccaskey, Alex committed
1392
1393
See `readout_error_correction_aer.py <https://github.com/eclipse/xacc/blob/master/python/examples/readout_error_correction_aer.py>`_
for a full example demonstrating the utility of the ``ROErrorDecorator``.
1394
1395
1396
1397
1398
1399
1400

RDMPurificationDecorator
++++++++++++++++++++++++

ImprovedSamplingDecorator
+++++++++++++++++++++++++

Mccaskey, Alex's avatar
Mccaskey, Alex committed
1401
1402
1403
1404
VQE Restart Decorator
+++++++++++++++++++++


1405
1406
IR Transformations
------------------
1407

1408
1409
CircuitOptimizer
+++++++++++++++++
Mccaskey, Alex's avatar
Mccaskey, Alex committed
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
This ``IRTransformation`` of type ``Optimization`` will search the DAG representation
of a quantum circuit and remove all zero-rotations, hadamard and cnot pairs, and merge
adjacent common rotations (e.g. ``Rx(.1)Rx(.1) -> Rx(.2)``).

.. code:: python

   # Create a bell state program with too many cnots
   xacc.qasm('''
   .compiler xasm
   .circuit foo
   .qbit q
   H(q[0]);
   CX(q[0], q[1]);
   CX(q[0], q[1]);
   CX(q[0], q[1]);
   Measure(q[0]);
   Measure(q[1]);
   ''')
   f = xacc.getCompiled('foo')
   assert(6 == f.nInstructions())

   # Run the circuit-optimizer IRTransformation, can pass
   # accelerator (here None) and options (here empty dict())
   optimizer = xacc.getIRTransformation('circuit-optimizer')
   optimizer.apply(f, None, {})

   # should have 4 instructions, not 6
   assert(4 == f.nInstructions())

1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454

Observables
-----------

Psi4 Frozen-Core
++++++++++++++++
The ``psi4-frozen-core`` observable generates an fermionic
observable using Psi4 and based on a user provided dictionary of options.
To use this Observable, ensure you have Psi4 installed under the same
``python3`` used for the XACC Python API.

.. code:: bash

   $ git clone https://github.com/psi4/psi4 && cd psi4 && mkdir build && cd build
   $ cmake .. -DPYTHON_EXECUTABLE=$(which python3) -DCMAKE_INSTALL_PREFIX=$(python3 -m site --user-site)/psi4
   $ make -j8 install
Mccaskey, Alex's avatar
Mccaskey, Alex committed
1455
   $ export PYTHONPATH=$(python3 -m site --user-site)/psi4/lib:$PYTHONPATH
1456

Mccaskey, Alex's avatar
Mccaskey, Alex committed
1457
This observable type takes a dictionary of options describing the
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
molecular geometry (key ``geometry``), the basis set (key ``basis``),
and the list of frozen (key ``frozen-spin-orbitals``) and active (key ``active-spin-orbitals``) spin
orbital lists.

With Psi4 and XACC installed, you can use the frozen-core
Observable in the following way in python.

.. code:: python

   import xacc

   geom = '''
   0 1
   Na  0.000000   0.0      0.0
   H   0.0        0.0  1.914388
   symmetry c1
   '''
   fo = [0, 1, 2, 3, 4, 10, 11, 12, 13, 14]
   ao = [5, 9, 15, 19]

   H = xacc.getObservable('psi4-frozen-core', {'basis': 'sto-3g',
                                       'geometry': geom,
                                       'frozen-spin-orbitals': fo,
                                       'active-spin-orbitals': ao})

1483
1484
1485
Circuit Generator
-----------------

Mccaskey, Alex's avatar
Mccaskey, Alex committed
1486
ASWAP Ansatz Circuit
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
++++++++++++++++++++
The ``ASWAP`` circuit generator generates a state preparation (ansatz) circuit for the VQE Algorithm.
(See `Gard, Bryan T., et al. <https://arxiv.org/abs/1904.10910>`_)

The ``ASWAP`` circuit generator requires the following input information:

+------------------------+------------------------------------------------------------------------+--------------------------------------+
|  Algorithm Parameter   |                  Parameter Description                                 |             type                     |
+========================+========================================================================+======================================+
|  nbQubits              | The number of qubits in the circuit.                                   | int                                  |
+------------------------+------------------------------------------------------------------------+--------------------------------------+
|  nbParticles           | The number of particles.                                               | int                                  |
+------------------------+------------------------------------------------------------------------+--------------------------------------+
|  timeReversalSymmetry  | Do we have time-reversal symmetry?                                     | boolean                              |
+------------------------+------------------------------------------------------------------------+--------------------------------------+

Example:

.. code:: cpp
Mccaskey, Alex's avatar
Mccaskey, Alex committed
1506

1507
1508
1509
1510
1511
1512
  #include "xacc.hpp"
  #include "xacc_observable.hpp"
  #include "xacc_service.hpp"

  int main(int argc, char **argv) {
    xacc::Initialize(argc, argv);
Mccaskey, Alex's avatar
Mccaskey, Alex committed
1513

1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
    auto accelerator = xacc::getAccelerator("qpp");
    auto H_N_2 = xacc::quantum::getObservable(
        "pauli", std::string("5.907 - 2.1433 X0X1 "
                            "- 2.1433 Y0Y1"
                            "+ .21829 Z0 - 6.125 Z1"));

    auto optimizer = xacc::getOptimizer("nlopt");
    // Use the ASWAP circuit as the ansatz
    xacc::qasm(R"(
        .compiler xasm
        .circuit deuteron_ansatz
        .parameters t0
        .qbit q
        ASWAP(q, t0, {{"nbQubits", 2}, {"nbParticles", 1}});
    )");
Mccaskey, Alex's avatar
Mccaskey, Alex committed
1529
1530
    auto ansatz = xacc::getCompiled("deuteron_ansatz");

1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
    // Get the VQE Algorithm and initialize it
    auto vqe = xacc::getAlgorithm("vqe");
    vqe->initialize({std::make_pair("ansatz", ansatz),
                    std::make_pair("observable", H_N_2),
                    std::make_pair("accelerator", accelerator),
                    std::make_pair("optimizer", optimizer)});

    // Allocate some qubits and execute
    auto buffer = xacc::qalloc(2);
    vqe->execute(buffer);
    // Expected result: -1.74886
    std::cout << "Energy: " << (*buffer)["opt-val"].as<double>() << "\n";
1543
   }