Error: iteration over a 0-d array on Pennylane codebook UI only

Hi, I need some help to understand this error : “Error: iteration over a 0-d array.”

This error only happens when I run on the Pennylane UI on the web site.
Here is my code:

# Debug error sur Pennylane
# Import the H2 molecule dataset
dataset = qml.data.load('qchem', folder_path="/tmp", molname="H2")[0]
# Define Hamiltonian and qubits
H, qubits = dataset.hamiltonian, len(dataset.hamiltonian.wires)
# The Hartree-Fock State
hf = dataset.hf_state
# Define the single and double excitations
singles, doubles = qml.qchem.excitations(electrons=2, orbitals=qubits)
num_params = len(singles) + len(doubles)

# Définir la fonction d'optimisation personnalisée
def optimizer_hf(params):
    opt = qml.AdamOptimizer(stepsize=0.1)
    max_iterations = 100
    tolerance = 1e-6
    prev_energy = float("inf")

    for i in range(max_iterations):
        try:
            params = opt.step(cost_hf, params)  # **Vérification de l'itération sur params**
            energy = cost_hf(params)
            print(f"Iteration {i + 1}: Energy = {energy:.6f}")

            if abs(prev_energy - energy) < tolerance:
                print("Converged!")
                break

            prev_energy = energy
        except ValueError as e:
            print(f"Optimization error: {e}")
            break

    return params


def run_VQE_hf():
    """Executes the VQE optimizing the parameters of the Hartree-Fock ansatz.

    Returns:
        (np.array): an array with the optimized trainable parameters.
        (float): the ground state energy
    """
    ##################
    # YOUR CODE HERE #
    ##################
    initial_params = np.random.rand(num_params)  # **Assurez-vous que num_params est > 1**
    print("Initial Parameters:\n", initial_params)

    optimized_params = optimizer_hf(initial_params)
    print(f"Optimized Parameters:\n{optimized_params}")

    final_cost = cost_hf(optimized_params)
    print(f"Final Cost = {final_cost}")
    
    return final_cost

E = run_VQE_hf()
print("Energy:", E)

You can notice the result on Pennylane and on local execution in the encloser. I did not have this error locally while Pennylane raise this error exception: “Error: iteration over a 0-d array.” .


Notices that I used loccaly:
import pennylane as qml
from pennylane import numpy as np

I try to catch error but unable to find the 0-d array no where.

Hi @quantumel ,

I think the issue here is that run_VQE_hf() isn’t returning what it should.

Take a look at what it should return.

    """
    ...
    
    Returns:
        (np.array): an array with the optimized trainable parameters.
        (float): the ground state energy
    """

I hope this helps!

Thank you for your hint.

The new feature “compare with our solution” is great.

1 Like

I’m happy to hear that you like this new feature @quantumel !
Thanks for your feedback.