Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
b8f921a
Added initial_state option to mpl drawer
enavarro51 May 1, 2020
c00fec6
Lint fix
enavarro51 May 1, 2020
fe49919
Merge branch 'master' into fixissue4293branch
enavarro51 May 2, 2020
d53be1a
Set default to False & doc changes
enavarro51 May 2, 2020
a9fdba6
Lint fix
enavarro51 May 2, 2020
1f22fef
Merge branch 'fixissue4293branch' of https://github.com/enavarro51/qi…
enavarro51 May 2, 2020
46daba4
Merge branch 'master' into fixissue4293branch
enavarro51 May 2, 2020
0a1bc0b
Added reno for initial_state
enavarro51 May 3, 2020
1026737
Merge branch 'fixissue4293branch' of https://github.com/enavarro51/qi…
enavarro51 May 3, 2020
2d4e906
Merge branch 'master' into fixissue4293branch
enavarro51 May 18, 2020
9312b69
Merge branch 'master' into fixissue4293branch
enavarro51 May 21, 2020
9efd998
Merge branch 'master' into fixissue4293branch
enavarro51 Jun 1, 2020
fdc072e
Merge branch 'fixissue4293branch' of github.com:enavarro51/qiskit-ter…
1ucian0 Jun 3, 2020
fbed099
link to file
1ucian0 Jun 3, 2020
f6f9461
Merge branch 'binder' into binder-mpl
1ucian0 Jun 3, 2020
7443be8
the first test
1ucian0 Jun 3, 2020
b410327
Merge branch 'binder' into binder-mpl
1ucian0 Jun 3, 2020
bd3e6af
clean notebook
1ucian0 Jun 3, 2020
f16475e
Merge branch 'binder' into binder-mpl
1ucian0 Jun 3, 2020
ced0c81
filter MPL
1ucian0 Jun 3, 2020
eb59486
Merge branch 'binder' into binder-mpl
1ucian0 Jun 3, 2020
996fa6a
filter
1ucian0 Jun 3, 2020
0874d01
Merge branch 'binder' into binder-mpl
1ucian0 Jun 3, 2020
ba6d6e7
filter
1ucian0 Jun 3, 2020
f089c1a
Merge branch 'binder' into binder-mpl
1ucian0 Jun 3, 2020
ba84ce9
filter
1ucian0 Jun 3, 2020
4bf10bf
filter 1
1ucian0 Jun 3, 2020
ff619b8
Merge branch 'binder' into binder-mpl
1ucian0 Jun 3, 2020
5064586
filter 2
1ucian0 Jun 3, 2020
ad9b6ed
Merge branch 'binder' into binder-mpl
1ucian0 Jun 3, 2020
935d12c
comment
1ucian0 Jun 3, 2020
7a19dec
Merge branch 'binder' into binder-mpl
1ucian0 Jun 3, 2020
42574a5
merge
1ucian0 Jun 4, 2020
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions qiskit/visualization/circuit_visualization.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,6 @@ def circuit_drawer(circuit,
when the ``output`` kwarg is set to use the ``mpl`` backend. It
will be silently ignored with all other outputs.
initial_state (bool): Optional. Adds ``|0>`` in the beginning of the wire.
Only used by the ``text``, ``latex`` and ``latex_source`` outputs.
Default: ``False``.
cregbundle (bool): Optional. If set True bundle classical registers. Not used by
the ``matplotlib`` output. Default: ``False``.
Expand Down Expand Up @@ -321,6 +320,7 @@ def circuit_drawer(circuit,
justify=justify,
idle_wires=idle_wires,
with_layout=with_layout,
initial_state=initial_state,
fold=fold,
ax=ax)
else:
Expand Down Expand Up @@ -624,6 +624,7 @@ def _matplotlib_circuit_drawer(circuit,
justify=None,
idle_wires=True,
with_layout=True,
initial_state=False,
fold=None,
ax=None):
"""Draw a quantum circuit based on matplotlib.
Expand All @@ -644,6 +645,8 @@ def _matplotlib_circuit_drawer(circuit,
idle_wires (bool): Include idle wires. Default is True.
with_layout (bool): Include layout information, with labels on the physical
layout. Default: True.
initial_state (bool): Optional. Adds ``|0>`` in the beginning of the line.
Default: ``False``.
fold (int): amount ops allowed before folding. Default is 25.
ax (matplotlib.axes.Axes): An optional Axes object to be used for
the visualization output. If none is specified a new matplotlib
Expand All @@ -670,5 +673,5 @@ def _matplotlib_circuit_drawer(circuit,
qcd = _matplotlib.MatplotlibDrawer(qregs, cregs, ops, scale=scale, style=style,
plot_barriers=plot_barriers,
reverse_bits=reverse_bits, layout=layout,
fold=fold, ax=ax)
initial_state=initial_state, fold=fold, ax=ax)
return qcd.draw(filename)
25 changes: 17 additions & 8 deletions qiskit/visualization/matplotlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,8 @@ def get_index(self):
class MatplotlibDrawer:
def __init__(self, qregs, cregs, ops,
scale=1.0, style=None, plot_barriers=True,
reverse_bits=False, layout=None, fold=25, ax=None):
reverse_bits=False, layout=None, initial_state=False,
fold=25, ax=None):

if not HAS_MATPLOTLIB:
raise ImportError('The class MatplotlibDrawer needs matplotlib. '
Expand Down Expand Up @@ -139,6 +140,7 @@ def __init__(self, qregs, cregs, ops,
self.plot_barriers = plot_barriers
self.reverse_bits = reverse_bits
self.layout = layout
self.initial_state = initial_state
if style:
if isinstance(style, dict):
self._style.set_style(style)
Expand Down Expand Up @@ -542,19 +544,26 @@ def _fix_double_script(label):
return ' '.join(words)

len_longest_label = 0
if self.initial_state:
initial_qbit = ' |0>'
initial_cbit = ' 0 '
else:
initial_qbit = ''
initial_cbit = ''

# quantum register
for ii, reg in enumerate(self._qreg):
if len(self._qreg) > 1:
if self.layout is None:
label = '${{{name}}}_{{{index}}}$'.format(name=reg.register.name,
index=reg.index)
label = '${{{name}}}_{{{index}}}$'.format(
name=reg.register.name, index=reg.index) + initial_qbit
else:
label = '${{{name}}}_{{{index}}} \\mapsto {{{physical}}}$'.format(
name=self.layout[reg.index].register.name,
index=self.layout[reg.index].index,
physical=reg.index)
physical=reg.index) + initial_qbit
else:
label = '${name}$'.format(name=reg.register.name)
label = '${name}$'.format(name=reg.register.name) + initial_qbit

label = _fix_double_script(label)
if len(label) > len_longest_label:
Expand All @@ -578,7 +587,7 @@ def _fix_double_script(label):
self._creg, n_creg)):
pos = y_off - idx
if self._style.bundle:
label = '${}$'.format(reg.register.name)
label = '${}$'.format(reg.register.name) + initial_cbit
label = _fix_double_script(label)
self._creg_dict[ii] = {
'y': pos,
Expand All @@ -589,7 +598,7 @@ def _fix_double_script(label):
if not (not nreg or reg.register != nreg.register):
continue
else:
label = '${}_{{{}}}$'.format(reg.register.name, reg.index)
label = '${}_{{{}}}$'.format(reg.register.name, reg.index) + initial_cbit
label = _fix_double_script(label)
self._creg_dict[ii] = {
'y': pos,
Expand Down Expand Up @@ -646,7 +655,7 @@ def _draw_regs_sub(self, n_fold, feedline_l=False, feedline_r=False):
clip_on=True,
zorder=PORDER_TEXT)
self.ax.text(self.x_offset - 0.2, y, this_creg['label'], ha='right', va='center',
fontsize=1.5 * self._style.fs,
fontsize=1.25 * self._style.fs,
color=self._style.tc,
clip_on=True,
zorder=PORDER_TEXT)
Expand Down
17 changes: 17 additions & 0 deletions releasenotes/notes/initial-state-all-drawers-7c9de960ac4bdd7a.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
features:
- |
A new kwarg, ``initial_state`` has been added to the
:func:`qiskit.visualization.circuit_drawer` function and the
:class:`~qiskit.circuit.QuantumCircuit` method
:meth:`~qiskit.circuit.QuantumCircuit.draw`. When set to ``True`` the
initial state will now be included in circuit visualizations for all drawers.
For example:

.. jupyter-execute::

from qiskit import QuantumCircuit

circuit = QuantumCircuit(2)
circuit.measure_all()
circuit.draw(output='mpl', initial_state=True)
Binary file added test/binder/mpl/references/long_name.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
43 changes: 43 additions & 0 deletions test/binder/mpl/test_circuit_matplotlib_drawer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# -*- coding: utf-8 -*-

# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.

import unittest

from qiskit import QuantumCircuit, QuantumRegister
from qiskit import visualization


class TestMatplotlibDrawer(unittest.TestCase):

def test_long_name(self):
"""Test to see that long register names can be seen completely
As reported in #2605
"""

# add a register with a very long name
qr = QuantumRegister(4, 'veryLongQuantumRegisterName')
# add another to make sure adjustments are made based on longest
qrr = QuantumRegister(1, 'q0')
circuit = QuantumCircuit(qr, qrr)

# check gates are shifted over accordingly
circuit.h(qr)
circuit.h(qr)
circuit.h(qr)

visualization.circuit_drawer(circuit, output='mpl', filename='long_name.png')


if __name__ == '__main__':
unittest.main(verbosity=1)
44 changes: 44 additions & 0 deletions test/binder/mpl_tester.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%run 'mpl/test_circuit_matplotlib_drawer.py'"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%run -i 'results.py'\n",
"results"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.7"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
47 changes: 47 additions & 0 deletions test/binder/results.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# -*- coding: utf-8 -*-

# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.

import os

CWD = os.path.dirname(os.path.abspath(__file__))


class Results:
def __init__(self, namelist):
self.namelist = namelist

def _repr_html_(self):
ret = "<table>"
ret += '<tr><td>Filename</td><td>Result</td><td>Reference</td></tr>'
for name in self.namelist:
ret += '<tr>'
ret += '<td>' + name + '</td>'
ret += '<td><img src="' + name + '"</td>'
reference = os.path.join('mpl', 'references', name)
if os.path.exists(os.path.join(CWD, reference)):
ret += '<td><img src="' + reference + '"</td>'
else:
ret += '<td style="text-align:center">' \
'Add <a download="%s" href="%s">this image</a> ' \
'to %s and push</td>' % (name, reference, reference)
ret += '</tr>'
ret += "</table>"
return ret


namelist = []
for file in os.listdir(CWD):
if file.endswith(".png"):
namelist.append(file)
results = Results(namelist)