Documentation of expval

You need a feedback topic for documentation.

qml.expval needs to be better explained in the documentation

This function returns an expectationMP which I found it impossible to recover the expval as a double from.

However when returned inside a qnode the return type becomes pennylane.numpy.tensor.tensor.

So there is black magic going on here that is not at all obvious. In particular the documentation needs to explain the obvious which is how one can obtain a double from eZ when one writes:

eZ = expval(PauliZ(0))

or warn that

eZ = expval(PauliZ(0))
eX = expval(PauliX(0))
eY = expval(PauliY(0))

isn’t going to return what one might naively expect it to and you can’t write the code this way.

Thanks… this was rough to debug without the suggested documentation

Hey @IanDavis! Welcome to the forum :smile:

Thank you for your feedback :slight_smile:. I think the main source of confusion here is the distinction between qml.expval on its own versus when it’s returned from a QNode. Let me explain what’s going on under the hood at a high level.

If I just print out qml.expval(qml.PauliZ(0)), here’s what I get:

>>> import pennylane as qml
>>> qml.expval(qml.PauliZ(0))
expval(PauliZ(wires=[0]))
>>> type(qml.expval(qml.PauliZ(0)))
<class 'pennylane.measurements.expval.ExpectationMP'>

In that sense, the documentation for expval is correct: it’s returning a measurement process instance — expval(PauliZ(wires=[0])) — whose type is ExpectationMP.

However, a measurement process instance has no meaning / value on its own — it’s simply a process. A value is associated to the process when there’s something to inject into the process: a quantum state generated by a quantum circuit! So, in the context of being returned from a QNode — pennylane’s lingo for a quantum circuit — the measurement is assigned a value whose type is a pennylane.numpy.tensor.tensor, as you said.

Side note: pennylane.numpy.tensor.tensor really just means a NumPy array :slight_smile:.

Let me know if this helps!

1 Like

That was a really good question, by the way!

Thanks Isaac, my main point was that this needs to be explained more clearly in the documentation. Otherwise I am unlikely to be alone in putting a lot of effort into trying to find some way of recovering the expectation value from an ExpectationMP. There is nothing to suggest that one can’t do this. Your comments in the documetation would be helpful here.

Also I think that the top level topics should include a topic focused on documentation, and how the documentation might be improved, corrected, etc.

1 Like

Thanks! I sent your feedback to the right people here and it’s in their hands :slight_smile:. In the meantime, please feel free to ask as many questions as you need to here on the forum :rocket: