Note
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)
/home/computertreker/git/qiskit/qiskit/.tox/docs/lib/python3.7/site-packages/sympy/core/expr.py:3951: SymPyDeprecationWarning:
expr_free_symbols method has been deprecated since SymPy 1.9. See
https://github.com/sympy/sympy/issues/21494 for more info.
deprecated_since_version="1.9").warn()
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: ┤0 ├ │ TwoLocal(θ[0],θ[1],θ[2],θ[3],θ[4],θ[5],θ[6],θ[7]) │ q_1: ┤1 ├ └────────────────────────────────────────────────────┘
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.55146158e-05+0.j, -9.93766272e-01+0.j, 1.11483575e-01+0.j,
1.77493990e-05+0.j]),
'eigenvalue': (-1.8572750175664259+0j),
'optimal_parameters': { ParameterVectorElement(θ[3]): 6.092947779034692,
ParameterVectorElement(θ[5]): 1.5683260003556614,
ParameterVectorElement(θ[7]): 0.3602072577510429,
ParameterVectorElement(θ[6]): -4.717618171283927,
ParameterVectorElement(θ[4]): -2.5983258978150006,
ParameterVectorElement(θ[1]): 4.426962083985579,
ParameterVectorElement(θ[2]): 0.5470754664946292,
ParameterVectorElement(θ[0]): 4.296520455019831},
'optimal_point': array([ 4.29652046, 4.42696208, 0.54707547, 6.09294778, -2.5983259 ,
1.568326 , -4.71761817, 0.36020726]),
'optimal_value': -1.8572750175664259,
'optimizer_evals': None,
'optimizer_time': 0.0652775764465332}
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.55146158e-05+0.j, -9.93766272e-01+0.j, 1.11483575e-01+0.j,
1.77493990e-05+0.j]),
'eigenvalue': (-1.8572750175664259+0j),
'optimal_parameters': { ParameterVectorElement(θ[7]): 0.3602072577510429,
ParameterVectorElement(θ[5]): 1.5683260003556614,
ParameterVectorElement(θ[6]): -4.717618171283927,
ParameterVectorElement(θ[4]): -2.5983258978150006,
ParameterVectorElement(θ[3]): 6.092947779034692,
ParameterVectorElement(θ[0]): 4.296520455019831,
ParameterVectorElement(θ[2]): 0.5470754664946292,
ParameterVectorElement(θ[1]): 4.426962083985579},
'optimal_point': array([ 4.29652046, 4.42696208, 0.54707547, 6.09294778, -2.5983259 ,
1.568326 , -4.71761817, 0.36020726]),
'optimal_value': -1.8572750175664259,
'optimizer_evals': None,
'optimizer_time': 0.0690913200378418}
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
/home/computertreker/git/qiskit/qiskit/.tox/docs/lib/python3.7/site-packages/qiskit/aqua/__init__.py:86: DeprecationWarning: The package qiskit.aqua is deprecated. It was moved/refactored to qiskit-terra For more information see <https://github.com/Qiskit/qiskit-aqua/blob/main/README.md#migration-guide>
warn_package('aqua', 'qiskit-terra')
Version Information
Qiskit Software | Version |
---|---|
qiskit-terra | 0.18.2 |
qiskit-aer | 0.8.2 |
qiskit-ignis | 0.6.0 |
qiskit-ibmq-provider | 0.16.0 |
qiskit-aqua | 0.9.5 |
qiskit | 0.29.1 |
qiskit-nature | 0.2.2 |
qiskit-finance | 0.3.0 |
qiskit-optimization | 0.2.3 |
qiskit-machine-learning | 0.2.1 |
System information | |
Python | 3.7.12 (default, Nov 22 2021, 14:57:10) [GCC 11.1.0] |
OS | Linux |
CPUs | 32 |
Memory (Gb) | 125.71650314331055 |
Tue Jan 04 10:58:52 2022 EST |
This code is a part of Qiskit
© Copyright IBM 2017, 2022.
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.
[ ]: