This page was generated from docs/tutorials/03_vqe_simulation_with_noise.ipynb.

VQE with Qiskit Aer Primitives#

This notebook demonstrates how to leverage the Qiskit Aer Primitives to run both noiseless and noisy simulations locally. Qiskit Aer not only allows you to define your own custom noise model, but also to easily create a noise model based on the properties of a real quantum device. This notebook will show an example of the latter, to illustrate the general workflow of running algorithms with local noisy simulators.

For further information on the Qiskit Aer noise model, you can consult the Qiskit Aer documentation, as well the tutorial for building noise models.

The algorithm of choice is once again VQE, where the task consists on finding the minimum (ground state) energy of a Hamiltonian. As shown in previous tutorials, VQE takes in a qubit operator as input. Here, you will take a set of Pauli operators that were originally computed by Qiskit Nature for the H2 molecule, using the SparsePauliOp class.

from qiskit.quantum_info import SparsePauliOp

H2_op = SparsePauliOp.from_list(
        ("II", -1.052373245772859),
        ("IZ", 0.39793742484318045),
        ("ZI", -0.39793742484318045),
        ("ZZ", -0.01128010425623538),
        ("XX", 0.18093119978423156),

print(f"Number of qubits: {H2_op.num_qubits}")
Number of qubits: 2

As the above problem is still easily tractable classically, you can use NumPyMinimumEigensolver to compute a reference value to compare the results later.

from qiskit_algorithms import NumPyMinimumEigensolver

numpy_solver = NumPyMinimumEigensolver()
result = numpy_solver.compute_minimum_eigenvalue(operator=H2_op)
ref_value = result.eigenvalue.real
print(f"Reference value: {ref_value:.5f}")
Reference value: -1.85728

The following examples will all use the same ansatz and optimizer, defined as follows:

# define ansatz and optimizer
from qiskit.circuit.library import TwoLocal
from qiskit_algorithms.optimizers import SPSA

iterations = 125
ansatz = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz")
spsa = SPSA(maxiter=iterations)

Performance without noise#

Let’s first run the VQE on the default Aer simulator without adding noise, with a fixed seed for the run and transpilation to obtain reproducible results. This result should be relatively close to the reference value from the exact computation.

# define callback
# note: Re-run this cell to restart lists before training
counts = []
values = []

def store_intermediate_result(eval_count, parameters, mean, std):
# define Aer Estimator for noiseless statevector simulation
from qiskit_algorithms.utils import algorithm_globals
from qiskit_aer.primitives import Estimator as AerEstimator

seed = 170
algorithm_globals.random_seed = seed

noiseless_estimator = AerEstimator(
    run_options={"seed": seed, "shots": 1024},
    transpile_options={"seed_transpiler": seed},
# instantiate and run VQE
from qiskit_algorithms import VQE

vqe = VQE(noiseless_estimator, ansatz, optimizer=spsa, callback=store_intermediate_result)
result = vqe.compute_minimum_eigenvalue(operator=H2_op)

print(f"VQE on Aer qasm simulator (no noise): {result.eigenvalue.real:.5f}")
print(f"Delta from reference energy value is {(result.eigenvalue.real - ref_value):.5f}")
VQE on Aer qasm simulator (no noise): -1.85160
Delta from reference energy value is 0.00567

You captured the energy values above during the convergence, so you can track the process in the graph below.

import pylab

pylab.rcParams["figure.figsize"] = (12, 4)
pylab.plot(counts, values)
pylab.xlabel("Eval count")
pylab.title("Convergence with no noise")
Text(0.5, 1.0, 'Convergence with no noise')

Performance with noise#

Now, let’s add noise to our simulation. Here we create a fake device, using GenericBackendV2, which has a default noise model. As stated in the introduction, it is also possible to create custom noise models from scratch, but this task is beyond the scope of this notebook.

By default the fake device will have all to all coupling, so to make it more realistic, we will give it a coupling map (this map matches what the 5-qubit Vigo device had) Note: You can also use this coupling map as the entanglement map for the variational form if you choose to.

from qiskit_aer.noise import NoiseModel
from qiskit.providers.fake_provider import GenericBackendV2

coupling_map = [(0, 1), (1, 2), (2, 3), (3, 4)]
device = GenericBackendV2(num_qubits=5, coupling_map=coupling_map, seed=54)

noise_model = NoiseModel.from_backend(device)

  Basis gates: ['cx', 'delay', 'id', 'measure', 'reset', 'rz', 'sx', 'x']
  Instructions with noise: ['x', 'cx', 'sx', 'id', 'measure']
  Qubits with noise: [0, 1, 2, 3, 4]
  Specific qubit errors: [('cx', (0, 1)), ('cx', (1, 2)), ('cx', (2, 3)), ('cx', (3, 4)), ('id', (0,)), ('id', (1,)), ('id', (2,)), ('id', (3,)), ('id', (4,)), ('sx', (0,)), ('sx', (1,)), ('sx', (2,)), ('sx', (3,)), ('sx', (4,)), ('x', (0,)), ('x', (1,)), ('x', (2,)), ('x', (3,)), ('x', (4,)), ('measure', (0,)), ('measure', (1,)), ('measure', (2,)), ('measure', (3,)), ('measure', (4,))]

Once the noise model is defined, you can run VQE using an Aer Estimator, where you can pass the noise model to the underlying simulator using the backend_options dictionary. Please note that this simulation will take longer than the noiseless one.

noisy_estimator = AerEstimator(
        "method": "density_matrix",
        "coupling_map": coupling_map,
        "noise_model": noise_model,
    run_options={"seed": seed, "shots": 1024},
    transpile_options={"seed_transpiler": seed},

Instead of defining a new instance of the VQE class, you can now simply assign a new estimator to our previous VQE instance. As the callback method will be re-used, you will also need to re-start the counts and values variables to be able to plot the convergence graph later on.

# re-start callback variables
counts = []
values = []
vqe.estimator = noisy_estimator

result1 = vqe.compute_minimum_eigenvalue(operator=H2_op)

print(f"VQE on Aer qasm simulator (with noise): {result1.eigenvalue.real:.5f}")
print(f"Delta from reference energy value is {(result1.eigenvalue.real - ref_value):.5f}")
VQE on Aer qasm simulator (with noise): -1.84320
Delta from reference energy value is 0.01407
if counts or values:
    pylab.rcParams["figure.figsize"] = (12, 4)
    pylab.plot(counts, values)
    pylab.xlabel("Eval count")
    pylab.title("Convergence with noise")


In this tutorial, you compared three calculations for the H2 molecule ground state. First, you produced a reference value using a classical minimum eigensolver. Then, you proceeded to run VQE using the Qiskit Aer Estimator with 1024 shots. Finally, you extracted a noise model from a backend and used it to define a new Estimator for noisy simulations. The results are:

print(f"Reference value: {ref_value:.5f}")
print(f"VQE on Aer qasm simulator (no noise): {result.eigenvalue.real:.5f}")
print(f"VQE on Aer qasm simulator (with noise): {result1.eigenvalue.real:.5f}")
Reference value: -1.85728
VQE on Aer qasm simulator (no noise): -1.85160
VQE on Aer qasm simulator (with noise): -1.84320

You can notice that, while the noiseless simulation’s result is closer to the exact reference value, there is still some difference. This is due to the sampling noise, introduced by limiting the number of shots to 1024. A larger number of shots would decrease this sampling error and close the gap between these two values.

As for the noise introduced by real devices (or simulated noise models), it could be tackled through a wide variety of error mitigation techniques. The Qiskit Runtime Primitives have enabled error mitigation through the resilience_level option. This option is currently available for remote simulators and real backends accessed via the Runtime Primitives, you can consult this documentation for further information.

import tutorial_magics


Version Information

System information
Python version3.8.18
Wed Apr 10 17:18:37 2024 UTC

This code is a part of a Qiskit project

© Copyright IBM 2017, 2024.

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

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.