How to run VQE on a noisy system?

Hello Pennylane team,

I would like to ask about implementing the Variational Quantum Eigensolver (VQE) algorithm using Quantum Natural Gradient (QNG) on a noisy system. Are there any examples or guidelines I can follow to set up a noisy simulation system,

Thank you for your assistance!

This is the code I want to run on a noisy system

import pennylane as qml
from pennylane import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import minimize

dataset = qml.data.load("qchem", molname="HeH+", bondlength=0.775, basis="STO-3G")[0]
hamiltonian, qubits = dataset.hamiltonian, len(dataset.hamiltonian.wires)
hamiltonian_coeffs, hamiltonian_ops = hamiltonian.terms()

print("Number of qubits = ", qubits)

dev = qml.device("default.qubit", wires=qubits)

def ansatz(params, wires=[0, 1, 2, 3]):
    for i in range(4):
        qml.RY(params[i], wires=i)
    for i in range(4): # HEA ansatz
        qml.CNOT(wires=[0, 1])
        qml.CNOT(wires=[0, 2])
        qml.CNOT(wires=[0, 3])
        qml.CNOT(wires=[1, 2])
        qml.CNOT(wires=[1, 3])
        qml.CNOT(wires=[2, 3])
        for i in range(4):
            qml.RY(params[i], wires=i)

@qml.qnode(dev)
def cost(params):
    ansatz(params)
    return qml.expval(hamiltonian)

np.random.seed(2)
init_params = np.random.uniform(low=0, high=2 * np.pi, size=24, requires_grad=True)
max_iterations = 100
step_size = 0.5 

hamiltonian = qml.Hamiltonian(np.array(hamiltonian_coeffs, requires_grad=False), hamiltonian_ops)

opt = qml.QNGOptimizer(step_size, approx="block-diag", lam=1)

params = init_params

qngd_cost = []
trajectory_qng = [init_params]


print("QNG Iteration:")
for n in range(max_iterations):
    params, prev_energy = opt.step_and_cost(cost, params)
    qngd_cost.append(prev_energy)

    energy_ngd = cost(params)
    trajectory_qng.append(params)
    print(
            "Iteration = {:},  Energy = {:.8f} Ha".format(n, energy_ngd)
        )

# store in numpy
trajectory_qng = np.array(trajectory_qng)
qngd_cost = np.array(qngd_cost)

Hi @Dwi_Cahyo_Mariyanto ,

If you want to use a noisy device I would recommend using the default.mixed device and adding the noise channels of your choice. Here you can find several demos on using noise models with PennyLane. Our demo on noisy circuits can be a good one to start with.

Once you set your device with the noise that you want you can run your usual programs, such as VQE. Note that simulating noisy circuits requires more memory since you’re using density matrices, so you’ll only be able to simulate systems up to about 16 qubits on a laptop.

One important thing to note is that not all optimizers will be able to work with noisy circuits so you might need to change a few things in your code to make it work. Let me know if you have any specific issues with this.

If you’re interested in learning more about noisy quantum circuits, then definitely check out our codebook module on this topic.

I hope this helps!

1 Like