Bemerkung

This page was generated from tutorials/algorithms/01_algorithms_introduction.ipynb.

# An Introduction to Algorithms in Qiskit¶

This is an introduction to algorithms in Qiskit and provides a high-level overview to help understand the various aspects of the functionality to get started. Other tutorials will provide more in-depth material, on given algorithms, and ways to use them etc.

## How is the algorithm library structured?¶

Qiskit provides a number of Algorithms and they are grouped by category according to the task they can perform. For instance `Minimum Eigensolvers`

to find the smallest eigen value of an operator, for example ground state energy of a chemistry Hamiltonian or a solution to an optimization problem when expressed as an Ising Hamiltonian. There are `Linear Solvers`

for linear systems of equations problems and `Amplitude Estimators`

for value estimation that can be used say in financial applications. The full set of categories can be seen in the Algorithms documentation link above.

Algorithms are configurable and often part of the configuration will be in the form of smaller building blocks, of which different instances of the building block type can be given. For instance with `VQE`

, the Variational Quantum Eigensolver, it takes a trial wavefunction, in the form of a `QuantumCircuit`

and a classical optimizer among other things.

Let’s take a look at an example to construct a VQE instance. Here `TwoLocal`

is the variational form (trial wavefunction), a parameterized circuit which can be varied, and `SLSQP`

a classical optimizer. These are created as separate instances and passed to VQE when it is constructed. Trying, for example, a different classical optimizer, or variational form is simply a case of creating an instance of the one you want and passing it into VQE.

```
[1]:
```

```
from qiskit.algorithms import VQE
from qiskit.algorithms.optimizers import SLSQP
from qiskit.circuit.library import TwoLocal
num_qubits = 2
ansatz = TwoLocal(num_qubits, 'ry', 'cz')
opt = SLSQP(maxiter=1000)
vqe = VQE(ansatz, optimizer=opt)
```

Let’s draw the ansatz so we can see it’s a QuantumCircuit where θ[0] through θ[7] will be the parameters that are varied as VQE optimizer finds the minimum eigenvalue. We’ll come back to the parameters later in a working example below.

```
[2]:
```

```
ansatz.draw()
```

```
[2]:
```

┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ q_0: ┤ RY(θ[0]) ├─■─┤ RY(θ[2]) ├─■─┤ RY(θ[4]) ├─■─┤ RY(θ[6]) ├ ├──────────┤ │ ├──────────┤ │ ├──────────┤ │ ├──────────┤ q_1: ┤ RY(θ[1]) ├─■─┤ RY(θ[3]) ├─■─┤ RY(θ[5]) ├─■─┤ RY(θ[7]) ├ └──────────┘ └──────────┘ └──────────┘ └──────────┘

But more is needed before we can run the algorithm so let’s get to that next.

## How to run an algorithm?¶

In order to run an algorithm we need to have backend, a simulator or real device, on which the circuits that comprise the algorithm can be run. So for example we can use the `aer_simulator_statevector`

from the Aer provider.

```
[3]:
```

```
from qiskit import Aer
backend = Aer.get_backend('aer_simulator_statevector')
```

Now a backend on its own does not have information on how you might want to run the circuits etc. For example how many shots, do you want a noise model, even options around transpiling the circuits. For this Qiskit Terra has a QuantumInstance which is provided both the backend as well as various settings around the circuit processing and execution so for instance:

```
[4]:
```

```
from qiskit.utils import QuantumInstance
backend = Aer.get_backend('aer_simulator')
quantum_instance = QuantumInstance(backend=backend, shots=800, seed_simulator=99)
```

Note: if you provide the backend directly then internally a QuantumInstance will be created from it, with default settings, so at all times the algorithms are working through a QuantumInstance.

So now we would be able to call the compute_mininum_eigenvalue() method. The latter is the interface of choice for the application modules, such as Nature and Optimization, in order that they can work interchangeably with any algorithm within the specific category.

## A complete working example¶

Let’s put what we have learned from above together and create a complete working example. VQE will find the minimum eigenvalue, i.e. minimum energy value of a Hamiltonian operator and hence we need such an operator for VQE to work with. Such an operator is given below. This was originally created by the Nature application module as the Hamiltonian for an H2 molecule at 0.735A interatomic distance. It’s a sum of Pauli terms as below, but for now I am not going to say anything further about it since the goal is to run the algorithm, but further information on operators can be found in other tutorials.

```
[5]:
```

```
from qiskit.opflow import X, Z, I
H2_op = (-1.052373245772859 * I ^ I) + \
(0.39793742484318045 * I ^ Z) + \
(-0.39793742484318045 * Z ^ I) + \
(-0.01128010425623538 * Z ^ Z) + \
(0.18093119978423156 * X ^ X)
```

So let’s build a VQE instance passing a backend using a QuantumInstance, to the constructor. Now VQE does have setters so the QuantumInstance can also be passed later.

Note: In order that you can run this notebook and see the exact same output the random number generator used throughout algorithms in algorithms_globals, as well as the transpiler and simulator, via the QuantumInstance, are seeded. You do not have to do this but if want to be able to reproduce the exact same outcome each time then this is how it’s done.

So let’s run VQE and print the result object it returns.

```
[6]:
```

```
from qiskit.utils import algorithm_globals
seed = 50
algorithm_globals.random_seed = seed
qi = QuantumInstance(Aer.get_backend('statevector_simulator'), seed_transpiler=seed, seed_simulator=seed)
ansatz = TwoLocal(rotation_blocks='ry', entanglement_blocks='cz')
slsqp = SLSQP(maxiter=1000)
vqe = VQE(ansatz, optimizer=slsqp, quantum_instance=qi)
result = vqe.compute_minimum_eigenvalue(H2_op)
print(result)
```

```
{ 'aux_operator_eigenvalues': None,
'cost_function_evals': 65,
'eigenstate': array([ 9.54859564e-05+0.j, -9.93766269e-01+0.j, 1.11483597e-01+0.j,
1.76972625e-05+0.j]),
'eigenvalue': -1.8572750175780233,
'optimal_parameters': { ParameterVectorElement(θ[1]): 4.426962028746158,
ParameterVectorElement(θ[5]): 1.5683259438037993,
ParameterVectorElement(θ[6]): -4.717618238771348,
ParameterVectorElement(θ[0]): 4.2965202693703635,
ParameterVectorElement(θ[4]): -2.5983257006415026,
ParameterVectorElement(θ[2]): 0.5470754201428533,
ParameterVectorElement(θ[7]): 0.3602072544539939,
ParameterVectorElement(θ[3]): 6.092947703759512},
'optimal_point': array([ 4.29652027, 4.42696203, 0.54707542, 6.0929477 , -2.5983257 ,
1.56832594, -4.71761824, 0.36020725]),
'optimal_value': -1.8572750175780233,
'optimizer_evals': 65,
'optimizer_time': 0.10349798202514648}
```

From the above result we can see it took the optimizer `65`

evaluations of parameter values until it found the minimum eigenvalue of `-1.85727`

which is the electronic ground state energy of the given H2 molecule. The optimal parameters of the ansatz can also be seen which are the values that were in the ansatz at the minimum value.

## Using VQE setting QuantumInstance after Construction¶

To close off let’s also create a VQE instance without supplying the QuantumInstance. We later set it as long as by the time VQE runs it has a QuantumInstance to use.

```
[7]:
```

```
algorithm_globals.random_seed = seed
qi = QuantumInstance(Aer.get_backend('aer_simulator_statevector'), seed_transpiler=seed, seed_simulator=seed)
ansatz = TwoLocal(rotation_blocks='ry', entanglement_blocks='cz')
slsqp = SLSQP(maxiter=1000)
vqe = VQE(ansatz, optimizer=slsqp)
vqe.quantum_instance = qi
result = vqe.compute_minimum_eigenvalue(operator=H2_op)
print(result)
```

```
{ 'aux_operator_eigenvalues': None,
'cost_function_evals': 65,
'eigenstate': array([ 9.54859564e-05+0.j, -9.93766269e-01+0.j, 1.11483597e-01+0.j,
1.76972625e-05+0.j]),
'eigenvalue': -1.8572750175780233,
'optimal_parameters': { ParameterVectorElement(θ[4]): -2.5983257006415026,
ParameterVectorElement(θ[0]): 4.2965202693703635,
ParameterVectorElement(θ[1]): 4.426962028746158,
ParameterVectorElement(θ[3]): 6.092947703759512,
ParameterVectorElement(θ[2]): 0.5470754201428533,
ParameterVectorElement(θ[6]): -4.717618238771348,
ParameterVectorElement(θ[7]): 0.3602072544539939,
ParameterVectorElement(θ[5]): 1.5683259438037993},
'optimal_point': array([ 4.29652027, 4.42696203, 0.54707542, 6.0929477 , -2.5983257 ,
1.56832594, -4.71761824, 0.36020725]),
'optimal_value': -1.8572750175780233,
'optimizer_evals': 65,
'optimizer_time': 0.11440682411193848}
```

As the identical seeding was used as the prior example the result can be seen to be the same.

This concludes this introduction to algorithms in Qiskit. Please check out the other algorithm tutorials in this series for both broader as well as more in depth coverage of the algorithms.

```
[8]:
```

```
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
```

### Version Information

Qiskit Software | Version |
---|---|

Qiskit | None |

Terra | 0.18.0.dev0+5920b66 |

Aer | 0.9.0 |

Ignis | 0.7.0.dev0+8195559 |

Aqua | None |

IBM Q Provider | None |

System information | |

Python | 3.8.8 (default, Apr 13 2021, 12:59:45) [Clang 10.0.0 ] |

OS | Darwin |

CPUs | 2 |

Memory (Gb) | 12.0 |

Thu May 27 10:59:11 2021 EDT |

### This code is a part of Qiskit

© Copyright IBM 2017, 2021.

This code is licensed under the Apache License, Version 2.0. You may

obtain a copy of this license in the LICENSE.txt file in the root directory

of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.

Any modifications or derivative works of this code must retain this

copyright notice, and modified files need to carry a notice indicating

that they have been altered from the originals.

```
[ ]:
```

```
```