import pennylane as qp
wires = range(3)
device = qp.device('default.qubit', wires=wires)
@qp.qnode(device)
def my_circuit():
# Some circuit code
# ...
qp.measure(wires=2, postselect=0, reset=True)
# More circuit code which reuses wire 2 under
# the assumption that it is |0> here
# ....
return qp.state()
my_circuit()
This of course is not allowed as discussed in the following thread:
I was wondering if there are any suggested alternatives that would achieve something similar to what my code is trying to do? I need the full state at the end, so the suggestions given in the thread do not work. So far, my only idea has been to introduce an additional wire which takes the place of wire 2 in the second half of the code and to remove the mid-circuit measurement. This increases the memory requirements which I would prefer to avoid if possible.
One way to keep it at 3 wires is to do the postselection by hand between two QNodes. Since you postselect on 0 and then reset, wire 2 is already |0> afterwards, so the state after the measurement is still pure and you can just feed it back in with StatePrep:
import numpy as np
import pennylane as qp
dev = qp.device("default.qubit", wires=3)
@qp.qnode(dev)
def first_half():
# circuit code before the measurement
return qp.state()
@qp.qnode(dev)
def second_half(state):
qp.StatePrep(state, wires=range(3))
# circuit code after the measurement (wire 2 starts in |0>)
return qp.state()
psi = np.array(first_half()).reshape(2, 2, 2) # axes are wires 0, 1, 2
psi[:, :, 1] = 0 # keep only the branch where wire 2 gave 0
prob = np.linalg.norm(psi) ** 2 # postselection probability
psi = (psi / np.sqrt(prob)).reshape(-1)
final = second_half(psi)
PennyLane orders the state vector with wire 0 as the most significant bit, so the last axis after the reshape is wire 2. If you need gradients through the whole thing, swap the in-place assignment for something like qp.math.stack or multiplying by a mask, so the autodiff framework can follow it. It’s also worth checking prob, because if it’s tiny the renormalization will amplify numerical noise.