<jupyter_start><jupyter_text>An Introduction to Algorithms in QiskitThis 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](https://qiskit.org/documentation/apidoc/algorithms.html) 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.<jupyter_code>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)<jupyter_output><empty_output><jupyter_text>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.<jupyter_code>ansatz.draw()<jupyter_output><empty_output><jupyter_text>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.<jupyter_code>from qiskit import Aer

backend = Aer.get_backend('aer_simulator_statevector')<jupyter_output><empty_output><jupyter_text>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`](https://qiskit.org/documentation/stubs/qiskit.utils.QuantumInstance.html) which is provided both the backend as well as various settings around the circuit processing and execution so for instance:<jupyter_code>from qiskit.utils import QuantumInstance

backend = Aer.get_backend('aer_simulator')
quantum_instance = QuantumInstance(backend=backend, shots=800, seed_simulator=99)<jupyter_output><empty_output><jupyter_text>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()](https://qiskit.org/documentation/stubs/qiskit.algorithms.VQE.htmlqiskit.algorithms.VQE.compute_minimum_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 exampleLet'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.<jupyter_code>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)<jupyter_output><empty_output><jupyter_text>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.<jupyter_code>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)<jupyter_output>{   '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.36020[...]<jupyter_text>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 ConstructionTo 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.<jupyter_code>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)<jupyter_output>{   '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.36020[...]<jupyter_text>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.<jupyter_code>import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.07289798501951683, 'fraction_numerical': 0.07142103597425889, 'mean_word_length': 4.217391304347826, 'pattern_counts': {'":': 0, '<': 31, '<?xml version=': 0, '>': 31, 'https://': 3, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '8', 'dir': 'jupyter-structured-clean-dedup', 'id': '121703', 'license': 'Apache-2.0', 'n_tokens_mistral': 3189, 'n_tokens_neox': 2714, 'n_words': 1032, 'path': 'tutorials/algorithms/01_algorithms_introduction.ipynb', 'repo_name': 'Qiskit/qiskit-iqx-tutorials', 'size': '9479'}