How to check qml.state in debug mode?

Hi,
I don’t think this question is directly related to the codebook but am asking as I do not know where to post my question(codebook is my first Pennylane experience).

I like to solve question using my local IDE(PyCharm), and hope to harness the debugging tool so that I can check the progress of quantum state. However, it seems the qml.state() from PyCharm debug mode does not yield what I was expecting. The code I tried was

import pennylane as qml

# CREATE A DEVICE
dev = qml.device("default.qubit", wires=1)

# CREATE A QNODE CALLED apply_hxh THAT APPLIES THE CIRCUIT ABOVE
@qml.qnode(dev)
def apply_hxh(state):
    if state == 1:
        qml.PauliX(wires=0)
    qml.Hadamard(wires=0)
    qml.PauliX(wires=0)       <------debugging point(aka the red dot)
    qml.Hadamard(wires=0)
    return qml.state()

# Print your results
print(apply_hxh(0))

At the debugging point, I typed

qml.state()

from PyCharm debugging console, and the output was

state(wires=[])

while I was expecting the output be something that representing |+>.
Would it be the issue with PyCharm, or is it something about the nature of quantum computation, that you cannot get state before measurement? Many thanks in advance :melting_face:

Hi @jheo2807 ,
Welcome to the forum!

I can’t speak to the debugger for PyCharm as I’ve never used it, but fundamentally, since qml.state() is a measurement process on all the qubits (under the hood, it’s mimicking something called quantum state tomography when simulating a quantum computation), it is not something you can typically do in a quantum computation, for the following reason:

Any measurement process collapses the state and would change the result of your computation. There are some subtle exceptions to this that I won’t get into (you can look up, for example, mid-circuit measurements if you are interested).

I think the easiest solution to what you are looking for is to use qml.Snapshot(). You can find an example of how to use it in the documentation.

Please let me know if that helps!