Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Relax wire_order restrictions in circuit visualization #9893

Merged
merged 22 commits into from
Jul 13, 2023
Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
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
2 changes: 1 addition & 1 deletion qiskit/opflow/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@

Operators and State functions are the building blocks of Quantum Algorithms.

A library for Quantum Algorithms & Applications is more than a collection of
A library for Quantum Algorithms & Applications (QA&A) is more than a collection of
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is unrelated. I just saw it around and noticed that QA&A is not a very common acronym.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It'd probably be better to revert this, especially with opflow deprecated. It's a problem that's existed forever (and capitalising unexpected words in a sentence like this is a not-altogether-unheard-of way of implicitly defining an acronym anyway).

Copy link
Member Author

@1ucian0 1ucian0 Jul 13, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done in b94ac8d

algorithms wrapped in Python functions. It needs to provide tools to make writing
algorithms simple and easy. This is the layer of modules between the circuits and algorithms,
providing the language and computational primitives for QA&A research.
Expand Down
51 changes: 31 additions & 20 deletions qiskit/visualization/circuit/circuit_visualization.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ def circuit_drawer(
information on the contents.
output (str): select the output method to use for drawing the circuit.
Valid choices are ``text``, ``mpl``, ``latex``, ``latex_source``.
By default the `text` drawer is used unless the user config file
By default, the `text` drawer is used unless the user config file
(usually ``~/.qiskit/settings.conf``) has an alternative backend set
as the default. For example, ``circuit_drawer = latex``. If the output
kwarg is set, that backend will always be used over the default in
Expand Down Expand Up @@ -205,27 +205,38 @@ def circuit_drawer(
raise VisualizationError(
"The wire_order option cannot be set when the reverse_bits option is True."
)
if wire_order is not None and len(wire_order) != circuit.num_qubits + circuit.num_clbits:
raise VisualizationError(
"The wire_order list must be the same "
"length as the sum of the number of qubits and clbits in the circuit."
)
if wire_order is not None and set(wire_order) != set(
range(circuit.num_qubits + circuit.num_clbits)
):
raise VisualizationError(
"There must be one and only one entry in the "
"wire_order list for the index of each qubit and each clbit in the circuit."
)

if circuit.clbits and (reverse_bits or wire_order is not None):
complete_wire_order = wire_order
if wire_order is not None:
wire_order_len = len(wire_order)
total_wire_len = circuit.num_qubits + circuit.num_clbits
if wire_order_len not in [circuit.num_qubits, total_wire_len]:
raise VisualizationError(
f"The wire_order list (length {wire_order_len}) should as long as "
f"the number of qubits ({circuit.num_qubits}) or the "
f"total numbers of qubits and classical bits {total_wire_len}."
)

if len(set(wire_order)) != len(wire_order):
raise VisualizationError("The wire_order list should not have repeated elements.")

if wire_order_len == circuit.num_qubits:
complete_wire_order = wire_order + list(range(circuit.num_qubits, total_wire_len))

if (
circuit.clbits
and (reverse_bits or wire_order is not None)
and not set(wire_order or []).issubset(set(range(circuit.num_qubits)))
):
if cregbundle:
warn(
"cregbundle set to False since either reverse_bits or wire_order has been set.",
"cregbundle set to False since either reverse_bits or wire_order "
"(over classical bit) has been set.",
RuntimeWarning,
2,
)
cregbundle = False

if output == "text":
return _text_circuit_drawer(
circuit,
Expand All @@ -239,7 +250,7 @@ def circuit_drawer(
fold=fold,
initial_state=initial_state,
cregbundle=cregbundle,
wire_order=wire_order,
wire_order=complete_wire_order,
)
elif output == "latex":
image = _latex_circuit_drawer(
Expand All @@ -254,7 +265,7 @@ def circuit_drawer(
with_layout=with_layout,
initial_state=initial_state,
cregbundle=cregbundle,
wire_order=wire_order,
wire_order=complete_wire_order,
)
elif output == "latex_source":
return _generate_latex_source(
Expand All @@ -269,7 +280,7 @@ def circuit_drawer(
with_layout=with_layout,
initial_state=initial_state,
cregbundle=cregbundle,
wire_order=wire_order,
wire_order=complete_wire_order,
)
elif output == "mpl":
image = _matplotlib_circuit_drawer(
Expand All @@ -286,7 +297,7 @@ def circuit_drawer(
ax=ax,
initial_state=initial_state,
cregbundle=cregbundle,
wire_order=wire_order,
wire_order=complete_wire_order,
)
else:
raise VisualizationError(
Expand Down Expand Up @@ -351,7 +362,7 @@ def _text_circuit_drawer(
TextDrawing: An instance that, when printed, draws the circuit in ascii art.

Raises:
VisualizationError: When the filename extenstion is not .txt.
VisualizationError: When the filename extension is not .txt.
"""
qubits, clbits, nodes = _utils._get_layered_instructions(
circuit,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
---
features:
- |
Some restrictions when using ``wire_order`` in the circuit drawers had been relaxed.
Now, ``wire_order`` can list just qubits and, in that case, it can be used
with ``cregbundle=True``, since it will not affect the classical bits.

.. code-block::

from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister

qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
cr2 = ClassicalRegister(2, "ca")
circuit = QuantumCircuit(qr, cr, cr2)
circuit.h(0)
circuit.h(3)
circuit.x(1)
circuit.x(3).c_if(cr, 10)
circuit.draw('text', wire_order=[2, 3], cregbundle=True)

.. parsed-literal::

q_2: ────────────
┌───┐ ┌───┐
q_3: ┤ H ├─┤ X ├─
├───┤ └─╥─┘
q_0: ┤ H ├───╫───
├───┤ ║
q_1: ┤ X ├───╫───
└───┘┌──╨──┐
c: 4/═════╡ 0xa ╞
└─────┘
ca: 2/════════════
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this example will work after the new changes any more because of the partial wire order. We should replace it with one that assigns all qubits.

Copy link
Member Author

@1ucian0 1ucian0 Jul 13, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oops... fixed in d2224cd

Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
\documentclass[border=2px]{standalone}

\usepackage[braket, qm]{qcircuit}
\usepackage{graphicx}

\begin{document}
\scalebox{1.0}{
\Qcircuit @C=1.0em @R=0.2em @!R { \\
\nghost{{q}_{2} : } & \lstick{{q}_{2} : } & \qw & \qw & \qw & \qw\\
\nghost{{q}_{1} : } & \lstick{{q}_{1} : } & \gate{\mathrm{X}} & \qw & \qw & \qw\\
\nghost{{q}_{3} : } & \lstick{{q}_{3} : } & \gate{\mathrm{H}} & \gate{\mathrm{X}} & \qw & \qw\\
\nghost{{q}_{0} : } & \lstick{{q}_{0} : } & \gate{\mathrm{H}} & \qw & \qw & \qw\\
\nghost{{c}_{0} : } & \lstick{{c}_{0} : } & \cw & \controlo \cw \cwx[-2] & \cw & \cw\\
\nghost{{c}_{1} : } & \lstick{{c}_{1} : } & \cw & \controlo \cw \cwx[-1] & \cw & \cw\\
\nghost{{c}_{2} : } & \lstick{{c}_{2} : } & \cw & \control \cw \cwx[-1] & \cw & \cw\\
\nghost{{c}_{3} : } & \lstick{{c}_{3} : } & \cw & \control \cw^(0.0){^{\mathtt{0xc}}} \cwx[-1] & \cw & \cw\\
\nghost{{ca}_{0} : } & \lstick{{ca}_{0} : } & \cw & \cw & \cw & \cw\\
\nghost{{ca}_{1} : } & \lstick{{ca}_{1} : } & \cw & \cw & \cw & \cw\\
\\ }}
\end{document}
4 changes: 1 addition & 3 deletions test/python/visualization/test_circuit_drawer.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,10 +108,8 @@ def test_wire_order_raises(self):

circuit = QuantumCircuit(3, 3)
circuit.x(1)
with self.assertRaisesRegex(VisualizationError, "the same length as"):
visualization.circuit_drawer(circuit, wire_order=[0, 1, 2])

with self.assertRaisesRegex(VisualizationError, "one and only one entry"):
with self.assertRaisesRegex(VisualizationError, "should not have repeated elements"):
visualization.circuit_drawer(circuit, wire_order=[2, 1, 0, 3, 1, 5])

with self.assertRaisesRegex(VisualizationError, "cannot be set when the reverse_bits"):
Expand Down
22 changes: 21 additions & 1 deletion test/python/visualization/test_circuit_latex.py
Original file line number Diff line number Diff line change
Expand Up @@ -681,7 +681,7 @@ def test_idle_wires_barrier(self):

def test_wire_order(self):
"""Test the wire_order option to latex drawer"""
filename = self._get_resource_path("test_latex_wire_order.tex")
filename = self._get_resource_path("test_latex_wire_order_only.tex")
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
cr2 = ClassicalRegister(2, "ca")
Expand All @@ -699,6 +699,26 @@ def test_wire_order(self):
)
self.assertEqualToReference(filename)

def test_wire_order_only_qubits(self):
"""Test the wire_order list with qubits only to latex drawer"""
filename = self._get_resource_path("test_wire_order_only_qubits.tex")
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
cr2 = ClassicalRegister(2, "ca")
circuit = QuantumCircuit(qr, cr, cr2)
circuit.h(0)
circuit.h(3)
circuit.x(1)
circuit.x(3).c_if(cr, 12)
circuit_drawer(
circuit,
cregbundle=False,
wire_order=[2, 1, 3, 0, 4, 5, 6, 7, 8, 9],
filename=filename,
output="latex_source",
)
self.assertEqualToReference(filename)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test says its wire_order is only qubits, but it's actually got all of them. It should probably be a test of what it says, and shouldn't include the clbits.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

actually, these tests make little sense now. Removing them in 445489c and add those that cover the involved code in this PR.



if __name__ == "__main__":
unittest.main(verbosity=2)
31 changes: 31 additions & 0 deletions test/python/visualization/test_circuit_text_drawer.py
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,37 @@ def test_wire_order(self):
str(_text_circuit_drawer(circuit, wire_order=[2, 1, 3, 0, 6, 8, 9, 5, 4, 7])), expected
)

def test_wire_order_only_qubits(self):
"""Test the wire_order option with only qubits"""
expected = "\n".join(
[
" ",
"q_2: |0>────────────",
" ┌───┐ ",
"q_1: |0>┤ X ├───────",
" ├───┤ ┌───┐ ",
"q_3: |0>┤ H ├─┤ X ├─",
" ├───┤ └─╥─┘ ",
"q_0: |0>┤ H ├───╫───",
" └───┘┌──╨──┐",
" c: 0 4/═════╡ 0xa ╞",
" └─────┘",
"ca: 0 2/════════════",
" ",
]
)
qr = QuantumRegister(4, "q")
cr = ClassicalRegister(4, "c")
cr2 = ClassicalRegister(2, "ca")
circuit = QuantumCircuit(qr, cr, cr2)
circuit.h(0)
circuit.h(3)
circuit.x(1)
circuit.x(3).c_if(cr, 10)
self.assertEqual(
str(_text_circuit_drawer(circuit, wire_order=[2, 1, 3, 0, 4, 5, 6, 7, 8, 9])), expected
)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test says its wire_order is only qubits, but it actually has all bits.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

test removed. See #9893 (comment)


def test_text_swap(self):
"""Swap drawing."""
expected = "\n".join(
Expand Down