Unable to compute expectation value

Hello!

I am trying to compute the expval of a certain observable given a predefined circuit. However, I get the following error:


Could someone help me figure out the problem with my code?
Thanks in advance!

Hi @grove0100!

Unfortunately this is a known bug that we are currently working to fix (see the relevant GitHub Issue here: WireError being thrown whenever running circuits where wire names are given explicitly · Issue #1459 · PennyLaneAI/pennylane · GitHub).

This bug occurs whenever the autograd interface is used with QNodes that take positional, non-trainable arguments (here, H falls into this category).

A workaround at the moment is to simply call your QNode with non-trainable arguments using keyword syntax, e.g.,

toy('exp', theta, H=qml.PauliX(1))

For example:

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

@qml.qnode(dev)
def circuit(op, params, H):
    qml.RX(params[0], wires=0)
    qml.broadcast(qml.CRX, wires=range(n), pattern="chain", parameters=params[1:n])

    if op == "state":
        return qml.state
    else:
        return qml.expval(H)

theta = np.ones((5,), requires_grad=True)
print(circuit("exp", theta, H=qml.PauliX(1)))

should work as expected.

A separate issue is that PennyLane does not currently support returning qml.state alongside expectation values; for example, the following will raise an error:

@qml.qnode(dev)
def circuit(x, H):
    qml.RX(x, wires=0)
    return qml.state(), qml.expval(H)

>>> circuit(0.5, H=qml.PauliX(0))
pennylane.QuantumFunctionError: The state or density matrix cannot be returned in combination with other return types

However this is something we can definitely look into supporting — if you have time, it would be super helpful if you could open a feature request over on our GitHub page detailing your requirements :slight_smile:

Thank you very much. Moving over to the TensorFlow environment has solved the problem.