Qiskit / qiskit

Qiskit is an open-source SDK for working with quantum computers at the level of extended quantum circuits, operators, and primitives.
https://www.ibm.com/quantum/qiskit
Apache License 2.0
5.23k stars 2.36k forks source link

Text-based circuit drawer output is scrambled in notebook unless print is called. #1167

Closed nonhermitian closed 5 years ago

nonhermitian commented 6 years ago

Informations

What is the current behavior?

from qiskit import *
from qiskit.tools.visualization import circuit_drawer

q = QuantumRegister(5)
qc = QuantumCircuit(q)
qc.ccx(q[1], q[2], q[3])
qc.ccx(q[0], q[2], q[4])
qc.x(q[4])
qc.x(q[3])

circuit_drawer(qc, output='text')

' \nq1_0: |0>────────────■───────\n │ \nq1_1: |0>──■─────────┼───────\n │ │ \nq1_2: |0>──■─────────■───────\n ┌─┴─┐┌───┐ │ \nq1_3: |0>┤ X ├┤ X ├──┼───────\n └───┘└───┘┌─┴─┐┌───┐\nq1_4: |0>──────────┤ X ├┤ X ├\n └───┘└───┘'

Steps to reproduce the problem

The output is messed up unless calling print(circuit_drawer(qc, output='text')). Therefore it is not a drop in replacement for the other methods which work fine in a notebook.

What is the expected behavior?

Suggested solutions

ajavadia commented 6 years ago

Yeah I saw this too and thought it's a problem with my environment. I didn't know print() fixes it. Can we fix it to work without print?

mtreinish commented 6 years ago

I'm not sure there is a way short of having the text backend realize it's in jupyter and call print() for you, and then not return anything. (or returning a string subclass that redefines __repr__) The problem is that jupyter is displaying the value of the return from the circuit_drawer() (basically calling repr() on it) function but not rendering it. This is the same thing as if you had a line with just a string variable without calling print. For example:

Python 3.7.0 (default, Sep 15 2018, 19:13:07) 
[GCC 8.2.1 20180831] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> test = 'a\nb\n'
>>> test
'a\nb\n'
>>> print(test)
a
b

>>> 
1ucian0 commented 6 years ago

Would you prefer the text drawer to return a list of lines? Maybe with some particular option? Does any other plugin have to deal with something similar (latex_src)?

mtreinish commented 6 years ago

The other backends return a pillow Image object which jupyter understands and renders the image.

nonhermitian commented 6 years ago

Why not just return an object with repr or maybe even html_repr that does what we want when it is called

1ucian0 commented 6 years ago

Well... the return type is a string. You should print it, like any other string.

1ucian0 commented 6 years ago

After discussing with @mtreinish, I will wrap the output in an object to implement _repr_html_.