0
$\begingroup$

I have a circuit with Rx gate, and I want to draw it with changed gate label. For example, instead of "RX" I want to have "custom_gate" written in the gate box. I have tried following code:

op = qml.RX(1.23456, wires=0, id='custom_gate')
op.name = 'custom_gate'
op.label(decimals=None, base_label="custom_gate", cache=None)

def circ():
    qml.apply(op)
    return 0

fig, ax = qml.draw_mpl(circ)()

And get this result:

enter image description here

Also, I've tried doing it with QNode instance, instead of quantum function -- got no difference.

As you can see, I've put "custom_gate" in several places, but none of them seems to work. Not sure, if I am doing it correctly, so please, show me a way how to do this. Probably, I have to acces the operations in constructed Qnode tape instead of initial gate, but both tape and qtape are NoneType objects

$\endgroup$

1 Answer 1

1
$\begingroup$

First, good news: Your approach to provide an id in order to impact the drawn circuit has been implemented very recently. So recent in fact, it is not in the newest release 0.33.1 of PennyLane yet, but will be included in 0.34. In the meantime, you can install from the master branch on Github to get the feature right now.

The id will yield something like this:

import pennylane as qml

@qml.qnode(qml.device('lightning.qubit', wires=1))
def circuit(a):
    qml.RX(a, wires=0, id="my Op")
    return qml.expval(qml.PauliZ(0))

print(qml.draw(circuit)(a=2.3))

>>> 0: ──RX(2.30,"my Op")─┤  <Z>

fig, ax = qml.draw_mpl(circuit)(a=2.3)

enter image description here

If you are not quite happy with this result (or want to stick to released versions), you can also create a custom operation with the desired name:

import pennylane as qml

class MyOp(qml.RX):
    pass

@qml.qnode(qml.device('lightning.qubit', wires=1))
def circuit(a):
    op = MyOp(a, wires=0)
    return qml.expval(qml.PauliZ(0))

print(qml.draw(circuit)(a=2.3))

>>> 0: ──MyOp(2.30)─┤  <Z>

fig, ax = qml.draw_mpl(circuit)(a=2.3)

enter image description here

Finally, if you want a label that is not a valid Python class name, you can get a bit hacky (not recommended, because it may interfere with functionality other than drawing!):

class MyOp(qml.RX):
    pass

MyOp.__name__ = "my OP"

@qml.qnode(qml.device('lightning.qubit', wires=1))
def circuit(a):
    op = MyOp(a, wires=0)
    return qml.expval(qml.PauliZ(0))

print(qml.draw(circuit)(a=2.3))

>>> 0: ──my Op(2.30)─┤  <Z>

fig, ax = qml.draw_mpl(circuit)(a=2.3)
plt.savefig("id_label.png")

enter image description here Hope this helps!

$\endgroup$
1
  • 1
    $\begingroup$ Thank you! This is exactly what I wanted! $\endgroup$ Dec 4, 2023 at 17:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.