PennyLaneAI / pennylane

PennyLane is a cross-platform Python library for quantum computing, quantum machine learning, and quantum chemistry. Train a quantum computer the same way as a neural network.
https://pennylane.ai
Apache License 2.0
2.19k stars 571 forks source link

draw quantum function #3666

Closed KetpuntoG closed 1 year ago

KetpuntoG commented 1 year ago

Feature details

based on user feedback:

"One thing I always found a little frustrating in Pennylane was drawing sections of circuits. Is there a way of doing this with having any measurements?"

I think that to solve this issue, It would be great to be able to pass a quantum function directly to the drawer without having to create the qnode

Implementation

No response

How important would you say this feature is?

1: Not important. Would be nice to have.

Additional information

No response

timmysilv commented 1 year ago

this can technically be done in a manner that isn't necessarily obvious, even with no measurements. The qml.drawer module expects tapes rather than quantum functions, so the user can do that transformation first if needed.

Example:

def qfunc(x):
  qml.RX(x, [0])
  qml.CNOT([0, 1])

print(qml.draw(qfunc)(1.1) will fail because qfunc is just a python callable, not a QNode.

A user can do something like this to get around that:

with qml.tape.QuantumTape() as t:
  qfunc(1.1)

print(qml.drawer.tape_text(t))

That said, I do NOT recommend this, because qml.drawer.tape_text is an internal detail. However, we could introduce a convenience function if this is desired from users. I'll make a PR to demonstrate an example.

timmysilv commented 1 year ago

I proposed something scrappy in #3760. Here's an example of it in action:

>>> import pennylane as qml
>>> def qfunc(x):
...     qml.RX(x, [0])
...     qml.CNOT([0, 1])
... 
>>> print(qml.draw_qfunc(qfunc)(1.1))
0: ──RX─╭●─┤  
1: ─────╰X─┤

Might this be what the user wants?

KetpuntoG commented 1 year ago

curious that it is not incorporated in the same qml.draw function, but this solution should work :)

timmysilv commented 1 year ago

updated the linked PR to incorporate into qml.draw. It came at a cost of messiness, which is why I was originally avoiding it, but I think it's an acceptable level of mess :)

KetpuntoG commented 1 year ago

Thanks!!

timmysilv commented 1 year ago

qml.draw and qml.draw_mpl should work with any quantum function on the latest master, and in PL >= 0.29 🕺