pennylane
pennylane copied to clipboard
Use appropriate names in circuit drawings of `qml.cond`
Feature details
Drawing a circuit with qml.cond
shows this gate as ControlledOperation
in the circuit drawing,
Instead, use the name of the function in the condition.
Implementation
No response
How important would you say this feature is?
1: Not important. Would be nice to have.
Additional information
No response
It would definitely be nice to have @ankit27kh. I'm not sure how easy or hard this is to implement though. Do you have any thoughts on this @albi3ro?
@ankit27kh
Taking the example from the qml.cond
docs:
dev = qml.device("default.qubit", wires=2)
def qfunc1(x, wire):
qml.Hadamard(wire)
qml.RY(x, wire)
def qfunc2(x, y, z, wire):
qml.Hadamard(wire)
qml.Rot(x, y, z, wire)
@qml.qnode(dev)
def qnode(a, x, y, z):
qml.Hadamard(0)
m_0 = qml.measure(0)
qml.cond(m_0, lambda: qfunc1(a, wire=1), lambda: qfunc2(x, y, z, wire=1))()
return qml.expval(qml.PauliZ(1))
par = np.array(0.3, requires_grad=True)
x = np.array(1.2, requires_grad=True)
y = np.array(1.1, requires_grad=True)
z = np.array(0.3, requires_grad=True)
You can use expansion_strategy="device"
to turn the ControlledOperation
into a more familiar operations:
print(qml.draw(qnode, expansion_strategy='device')(par, x, y, z))
0: ──H─╭●────────╭●────────╭●────────╭●─────────X─╭●────────╭●────────╭●─────────X──X
1: ────╰Rϕ(1.57)─╰RX(1.57)─╰Rϕ(1.57)─╰RY(0.30)────╰Rϕ(1.57)─╰RX(1.57)─╰Rϕ(1.57)──────
──╭●────────────────────X─┤
──╰Rot(1.20,1.10,0.30)────┤ <Z>
QNode
's apply qml.defer_measurements
by default, so it turns Conditional
operations into standard controlled operations.
ControlledOperation
's don't display very well in circuit diagrams, but I'm trying to replace the class anyway, so eventually, generic controlled operations will display better.
Hi y'all 👋 I have PR #4228 up for review to add MPL support for the drawing of mid-circuit measurements connected to conditional operations. It comes with some limitations, but it should provide a fair bit of functionality here! Some notes
- it will only work with
qml.draw_mpl
for now, and notqml.draw
- As @albi3ro has described above, if you wrap your circuit in a QNode, it will probably apply the deferred measurement principle and won't matter anymore. However, you can draw an un-processed/un-decorated qfunc (see examples in the PR changes) if that's the case
The example you posted now returns:
0: ──H──┤↗├──────────────────────────────────────┤
1: ──────║───H──RY(0.30)──H──Rot(1.20,1.10,0.30)─┤ <Z>
╚═══╩══╩═════════╩══╝
This was added in PR #4930 and #4901