How to Implement the COBYLA Optimizer in PennyLane for Quantum Optimization

Hi PennyLane Help Team,

I am currently working on a quantum optimization problem and I would like to implement the COBYLA optimizer in my PennyLane code. I have some experience with other optimizers in PennyLane but am unsure about the specific setup and parameters for COBYLA.

Could you please guide me on how to set up and use the COBYLA optimizer in my code?

import pennylane as qml
from pennylane import numpy as np
import matplotlib.pyplot as plt

# Define constants for the Hamiltonian
alpha = 0.4
beta = 0.2

# Define the Hamiltonian for H2
H = alpha * (qml.PauliZ(0) @ qml.Identity(1) + qml.Identity(0) @ qml.PauliZ(1)) + beta * qml.PauliX(0) @ qml.PauliX(1)

# Set up the device (1 qubit in this case)
dev = qml.device('lightning.qubit', wires=2)

# Define the quantum circuit ansatz directly as a QNode
@qml.qnode(dev, interface="autograd", diff_method="best")
# Define the ansatz for the H2 molecule
def ansatz(params):
    # Apply initial rotations
    qml.RY(2 * params[0], wires=0)
    qml.RY(2 * params[1], wires=1)
    # Apply entangling gate (CNOT)
    qml.CNOT(wires=[0, 1])
    # Apply final rotations
    qml.RY(2 * params[2], wires=0)
    qml.RY(2 * params[3], wires=1)
    return qml.expval(H)# Measure the expectation value of the Hamiltonian

#define ansatz as cost
cost = ansatz

# Initial parameters
np.random.seed(42)
theta_initial = np.array([-0.1, 0.2, 1.1, 2.0], requires_grad=True)
eta = 0.05  # Learning rate
steps = 50  # Number of iterations

Hi @Dwi_Cahyo_Mariyanto ,

COBYLA is not a native PennyLane optimizer. You can find PennyLane’s built-in optimizers here. If none of these optimizers work for what you want, you could try using a different interface such as JAX. If you choose to use JAX then you should import numpy from jax and use it instead of PennyLane’s Numpy for creating your initial paramenters:

from jax import numpy as jnp

This demo shows how to use JAX and JAXopt with PennyLane. You could try modifying it to use jaxopt.ScipyMinimize, which allows you to use COBYLA as a method.

If you haven’t worked with JAX before I’d first recommend that you familiarize yourself with the demo and then try modifying it to use jaxopt.ScipyMinimize.

Let me know if you manage to make it work!

1 Like