Repository: Qiskit/qiskit

Issue:
Consistent gates order in visualizations (and DAG?)
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues to confirm this idea does not exist. -->

### What is the expected enhancement?

As a spin-off from #1617 (thanks @Exferro!) , during that PR it was detected that the same `QuantumCircuit` produces different visualizations between Python [3.5](https://github.com/Qiskit/qiskit-terra/blob/73d47fd924edd948aee51b648b15d06211a17a20/test/python/tools/visualization/references/3.5/deep/mpl.png) and [3.6/3.7](https://github.com/Qiskit/qiskit-terra/blob/73d47fd924edd948aee51b648b15d06211a17a20/test/python/tools/visualization/references/3.6/deep/mpl.png) - the order in which `measure`s are drawn is different.

Digging a bit deeper, it seems it might be a mixture of two issues:
* the order of the instructions in the circuit (`circuit.data`) is not preserved in the final visualization
* potentially, there might be some `dict` vs `OrderedDict` issue involved (based on the example at #1617 producing the _same_ result in 3.6/3.7, and a different one in 3.5) - this is not confirmed.

### Desired behaviour

Ideally, we should be able to at least guarantee a "consistent" order (same visualization is produced regardless of Python version), and hopefully one that respects the original instruction order.

### Proposed solution

The main flow when producing a visualization is through [`_get_instructions()`](
https://github.com/Qiskit/qiskit-terra/blob/179290f082a9c4b905402db8a60fe7bb899f79e8/qiskit/tools/visualization/_utils.py#L68), which in turn ends up invoking [`node_nums_in_topological_order()`](https://github.com/Qiskit/qiskit-terra/blob/179290f082a9c4b905402db8a60fe7bb899f79e8/qiskit/dagcircuit/_dagcircuit.py#L984). A possible solution might involve ensuring that the topological sorting always return the same solution, for example "tagging" or adding extra information to the DAG for allowing it to restore the order in which gates were added to the circuit (@ajavadia can ellaborate into the idea).

## Good first contribution!

I am actually tagging this as `good first contribution`, as I believe is an interesting change to explore both the circuits/dags and the visualization sides of Terra - and with a cool end result!  If somebody is interested, please ping us by replying to this issue :tada: 






Discussion:
As an example, the following circuit:
```
  qr = QuantumRegister(2, name='qr')
  cr = ClassicalRegister(2, name='cr')
  circuit = QuantumCircuit(qr, cr)

  circuit.x(qr[0])
  circuit.measure(qr, cr)
  ```
  has the following instructions in `circuit,data`:
  ```
  [<qiskit.extensions.standard.x.XGate object at 0x7f7333d1fef0>,
   <qiskit.circuit.measure.Measure object at 0x7f73305ebfd0>,
   <qiskit.circuit.measure.Measure object at 0x7f732a7c5630>]
  ```
  and produces the following output (ie. the order of the boxes):
  ```
              ┌───┐┌─┐
  qr_0: |0>───┤ X ├┤M├
           ┌─┐└───┘└╥┘
  qr_1: |0>┤M├──────╫─
           └╥┘      ║
   cr_0: 0 ═╬═══════╩═
            ║
   cr_1: 0 ═╩═════════
  ```


For reference, the original circuit showing the symptons in #1617 is:
```
    qr = QuantumRegister(20, name='qr')
    cr = ClassicalRegister(20, name='cr')
    circuit = QuantumCircuit(qr, cr)

    for i in range(10):
        circuit.x(qr[i])
        circuit.h(qr[i])
        circuit.x(qr[i])

    circuit.barrier(qr)
    circuit.measure(qr, cr)
```
Hi @diego-plan9 I would like to work on this issue. I will try and familiarise myself with the visualisation code and get back to you if I have any questions!
That would be awesome, @maddy-tod , thanks! Don't hesitate indeed on pinging us as much as needed (specially as in this particular issue, part of the work is finding out the extent of problem and exploring a bit, and being able to reproduce it in your environment), and looking forward to your contribution!
So there are two issues:
1. For a given DAG, topological sort can give different orders (on python 3.5, 3.6, 3.7). I haven't checked this, so I think we need to confirm first. You can do something like:
```python
# ... build a circuit....

from qiskit.converters import circuit_to_dag
dag = circuit_to_dag(circuit)
dag.node_nums_in_topological_order()
```

2. The order is not the same as the user specified when building a circuit. This is verifiable by a simple circuit:
```
from qiskit import *
q = QuantumRegister(4)
circuit = QuantumCircuit(q)
circuit.cx(q[0], q[1])
circuit.cx(q[2], q[3])

print(circuit)
q0_0: |0>───────■──
              ┌─┴─┐
q0_1: |0>─────┤ X ├
              └───┘
q0_2: |0>──■───────
         ┌─┴─┐
q0_3: |0>┤ X ├─────
         └───┘
```

We can solve both issues by forcing an order on the DAG topological sort.
In the DAGCircuit class, we can assign more fields to the nodes, as a sort of metadata. So we can tag each node by the place of that gate in the original `circuit.data` list. Then have to force `networkx.topological_sort()` to take this into account when two nodes have equal priority. I don't know how to do this last part, but I think it should be doable.
[networkx.lexicographical_topological_sort](https://networkx.github.io/documentation/stable/reference/algorithms/generated/networkx.algorithms.dag.lexicographical_topological_sort.html) supports a key function to resolve ambiguities in topological sort order.
> 1. For a given DAG, topological sort can give different orders (on python 3.5, 3.6, 3.7). I haven't checked this, so I think we need to confirm first. You can do something like:

I have looked at this, and you are correct different Python versions give different orderings.

Resolving patch:
diff --git a/qiskit/converters/circuit_to_dag.py b/qiskit/converters/circuit_to_dag.py
--- a/qiskit/converters/circuit_to_dag.py
+++ b/qiskit/converters/circuit_to_dag.py
@@ -46,6 +46,7 @@ def circuit_to_dag(circuit):
         "load": ["load", -1, 0, 1],
         "noise": ["noise", -1, 0, 1]
     }
+
     for main_instruction in circuit.data:
         # TODO: generate definitions and nodes for CompositeGates,
         # for now simply drop their instructions into the DAG
diff --git a/qiskit/dagcircuit/_dagcircuit.py b/qiskit/dagcircuit/_dagcircuit.py
--- a/qiskit/dagcircuit/_dagcircuit.py
+++ b/qiskit/dagcircuit/_dagcircuit.py
@@ -997,7 +997,7 @@ def node_nums_in_topological_order(self):
         Returns:
             list: The list of node numbers in topological order
         """
-        return nx.topological_sort(self.multi_graph)
+        return nx.lexicographical_topological_sort(self.multi_graph)
 
     def substitute_circuit_all(self, op, input_circuit, wires=None):
         """Replace every occurrence of operation op with input_circuit.


Test patch:
diff --git a/test/python/test_dagcircuit.py b/test/python/test_dagcircuit.py
--- a/test/python/test_dagcircuit.py
+++ b/test/python/test_dagcircuit.py
@@ -212,7 +212,7 @@ def test_nodes_in_topological_order(self):
         self.dag.apply_operation_back(HGate(self.qubit2))
 
         named_nodes = self.dag.node_nums_in_topological_order()
-        self.assertEqual([9, 10, 7, 8, 5, 3, 1, 11, 13, 4, 12, 14, 15, 6, 2],
+        self.assertEqual([1, 3, 5, 7, 8, 9, 10, 11, 12, 13, 4, 14, 2, 15, 6],
                          [i for i in named_nodes])
 
 
diff --git a/test/python/tools/visualization/__init__.py b/test/python/tools/visualization/__init__.py
--- a/test/python/tools/visualization/__init__.py
+++ b/test/python/tools/visualization/__init__.py
@@ -0,0 +1,8 @@
+# -*- coding: utf-8 -*-
+
+# Copyright 2018, IBM.
+#
+# This source code is licensed under the Apache License, Version 2.0 found in
+# the LICENSE.txt file in the root directory of this source tree.
+
+"""Tests for visualization tools."""
diff --git a/test/python/tools/visualization/references/matplotlib_ref.png b/test/python/tools/visualization/references/matplotlib_ref.png
Binary files a/test/python/tools/visualization/references/matplotlib_ref.png and b/test/python/tools/visualization/references/matplotlib_ref.png differ
diff --git a/test/python/tools/visualization/references/text_ref.txt b/test/python/tools/visualization/references/text_ref.txt
--- a/test/python/tools/visualization/references/text_ref.txt
+++ b/test/python/tools/visualization/references/text_ref.txt
@@ -1,13 +1,13 @@
-              ┌───┐┌───┐┌───┐ ░ ┌───┐┌───┐┌─────┐┌───┐┌─────┐┌────┐     ┌────────────┐┌────────────┐┌────────────┐┌────────────┐┌────────────┐┌───────────────────┐┌──────────────────────────┐                                                                                      ┌─┐
-q_0: |0>──────┤ X ├┤ Y ├┤ Z ├─░─┤ H ├┤ S ├┤ Sdg ├┤ T ├┤ Tdg ├┤ Id ├─|0>─┤ Rx(3.1416) ├┤ Ry(3.1416) ├┤ Rz(3.1416) ├┤ U0(3.1416) ├┤ U1(3.1416) ├┤ U2(3.1416,3.1416) ├┤ U3(3.1416,3.1416,3.1416) ├─X───■────■───■───■───■────────────────────■────────────────────■─────────■───■───────┤M├
-            ░ └───┘└───┘└───┘ ░ └───┘└───┘└─────┘└───┘└─────┘└────┘     └────────────┘└────────────┘└────────────┘└────────────┘└────────────┘└───────────────────┘└──────────────────────────┘ │ ┌─┴─┐┌─┴─┐ │ ┌─┴─┐ │3.1416 ┌────────────┴─────────────┐┌─────┴──────┐  │   │    ┌─┐└╥┘
-q_1: |0>────░───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────X─┤ X ├┤ Y ├─■─┤ H ├─■───────┤ U3(3.1416,3.1416,3.1416) ├┤ Rz(3.1416) ├──■───X────┤M├─╫─
-         ░  ░                                                                                                                                                                                     └───┘└───┘   └───┘         └──────────────────────────┘└────────────┘┌─┴─┐ │ ┌─┐└╥┘ ║ 
-q_2: |0>─░─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤ X ├─X─┤M├─╫──╫─
-         ░                                                                                                                                                                                                                                                             └───┘   └╥┘ ║  ║ 
- c_0: 0 ════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╬══╬══╩═
-                                                                                                                                                                                                                                                                                ║  ║    
- c_1: 0 ════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╬══╩════
-                                                                                                                                                                                                                                                                                ║       
- c_2: 0 ════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╩═══════
+        ┌───┐┌───┐┌───┐ ░       ┌───┐┌───┐┌─────┐┌───┐┌─────┐┌────┐     ┌────────────┐┌────────────┐┌────────────┐┌────────────┐┌────────────┐┌───────────────────┐┌──────────────────────────┐                                                                                ┌─┐      
+q_0: |0>┤ X ├┤ Y ├┤ Z ├─░───────┤ H ├┤ S ├┤ Sdg ├┤ T ├┤ Tdg ├┤ Id ├─|0>─┤ Rx(3.1416) ├┤ Ry(3.1416) ├┤ Rz(3.1416) ├┤ U0(3.1416) ├┤ U1(3.1416) ├┤ U2(3.1416,3.1416) ├┤ U3(3.1416,3.1416,3.1416) ├─X───■────■───■───■───■────────────────────■────────────────────■─────────■───■─┤M├──────
+        └───┘└───┘└───┘ ░  ░    └───┘└───┘└─────┘└───┘└─────┘└────┘     └────────────┘└────────────┘└────────────┘└────────────┘└────────────┘└───────────────────┘└──────────────────────────┘ │ ┌─┴─┐┌─┴─┐ │ ┌─┴─┐ │3.1416 ┌────────────┴─────────────┐┌─────┴──────┐  │   │ └╥┘┌─┐   
+q_1: |0>───────────────────░────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────X─┤ X ├┤ Y ├─■─┤ H ├─■───────┤ U3(3.1416,3.1416,3.1416) ├┤ Rz(3.1416) ├──■───X──╫─┤M├───
+                           ░  ░                                                                                                                                                                   └───┘└───┘   └───┘         └──────────────────────────┘└────────────┘┌─┴─┐ │  ║ └╥┘┌─┐
+q_2: |0>──────────────────────░────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┤ X ├─X──╫──╫─┤M├
+                              ░                                                                                                                                                                                                                                        └───┘    ║  ║ └╥┘
+ c_0: 0 ════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╩══╬══╬═
+                                                                                                                                                                                                                                                                                   ║  ║ 
+ c_1: 0 ═══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╩══╬═
+                                                                                                                                                                                                                                                                                      ║ 
+ c_2: 0 ══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════╩═
                                                                                                                                                                                                                                                                                         
\ No newline at end of file
diff --git a/test/python/tools/visualization/test_circuit_text_drawer.py b/test/python/tools/visualization/test_circuit_text_drawer.py
--- a/test/python/tools/visualization/test_circuit_text_drawer.py
+++ b/test/python/tools/visualization/test_circuit_text_drawer.py
@@ -106,19 +106,19 @@ class TestTextDrawerGatesInCircuit(QiskitTestCase):
 
     def test_text_measure_1(self):
         """ The measure operator, using 3-bit-length registers. """
-        expected = '\n'.join(["              ┌─┐",
-                              "q_0: |0>──────┤M├",
-                              "           ┌─┐└╥┘",
-                              "q_1: |0>───┤M├─╫─",
-                              "        ┌─┐└╥┘ ║ ",
-                              "q_2: |0>┤M├─╫──╫─",
-                              "        └╥┘ ║  ║ ",
-                              " c_0: 0 ═╬══╬══╩═",
-                              "         ║  ║    ",
-                              " c_1: 0 ═╬══╩════",
-                              "         ║       ",
-                              " c_2: 0 ═╩═══════",
-                              "                 "])
+        expected = '\n'.join(['        ┌─┐      ',
+                              'q_0: |0>┤M├──────',
+                              '        └╥┘┌─┐   ',
+                              'q_1: |0>─╫─┤M├───',
+                              '         ║ └╥┘┌─┐',
+                              'q_2: |0>─╫──╫─┤M├',
+                              '         ║  ║ └╥┘',
+                              ' c_0: 0 ═╩══╬══╬═',
+                              '            ║  ║ ',
+                              ' c_1: 0 ════╩══╬═',
+                              '               ║ ',
+                              ' c_2: 0 ═══════╩═',
+                              '                 '])
         qr = QuantumRegister(3, 'q')
         cr = ClassicalRegister(3, 'c')
         circuit = QuantumCircuit(qr, cr)
@@ -127,19 +127,19 @@ def test_text_measure_1(self):
 
     def test_text_measure_1_reversebits(self):
         """ The measure operator, using 3-bit-length registers, with reversebits """
-        expected = '\n'.join(["        ┌─┐      ",
-                              "q_2: |0>┤M├──────",
-                              "        └╥┘┌─┐   ",
-                              "q_1: |0>─╫─┤M├───",
-                              "         ║ └╥┘┌─┐",
-                              "q_0: |0>─╫──╫─┤M├",
-                              "         ║  ║ └╥┘",
-                              " c_2: 0 ═╩══╬══╬═",
-                              "            ║  ║ ",
-                              " c_1: 0 ════╩══╬═",
-                              "               ║ ",
-                              " c_0: 0 ═══════╩═",
-                              "                 "])
+        expected = '\n'.join(['              ┌─┐',
+                              'q_2: |0>──────┤M├',
+                              '           ┌─┐└╥┘',
+                              'q_1: |0>───┤M├─╫─',
+                              '        ┌─┐└╥┘ ║ ',
+                              'q_0: |0>┤M├─╫──╫─',
+                              '        └╥┘ ║  ║ ',
+                              ' c_2: 0 ═╬══╬══╩═',
+                              '         ║  ║    ',
+                              ' c_1: 0 ═╬══╩════',
+                              '         ║       ',
+                              ' c_0: 0 ═╩═══════',
+                              '                 '])
         qr = QuantumRegister(3, 'q')
         cr = ClassicalRegister(3, 'c')
         circuit = QuantumCircuit(qr, cr)
@@ -148,23 +148,23 @@ def test_text_measure_1_reversebits(self):
 
     def test_text_measure_2(self):
         """ The measure operator, using some registers. """
-        expected = '\n'.join(["               ",
-                              "q1_0: |0>──────",
-                              "               ",
-                              "q1_1: |0>──────",
-                              "            ┌─┐",
-                              "q2_0: |0>───┤M├",
-                              "         ┌─┐└╥┘",
-                              "q2_1: |0>┤M├─╫─",
-                              "         └╥┘ ║ ",
-                              " c1_0: 0 ═╬══╬═",
-                              "          ║  ║ ",
-                              " c1_1: 0 ═╬══╬═",
-                              "          ║  ║ ",
-                              " c2_0: 0 ═╬══╩═",
-                              "          ║    ",
-                              " c2_1: 0 ═╩════",
-                              "               "])
+        expected = '\n'.join(['               ',
+                              'q1_0: |0>──────',
+                              '               ',
+                              'q1_1: |0>──────',
+                              '         ┌─┐   ',
+                              'q2_0: |0>┤M├───',
+                              '         └╥┘┌─┐',
+                              'q2_1: |0>─╫─┤M├',
+                              '          ║ └╥┘',
+                              ' c1_0: 0 ═╬══╬═',
+                              '          ║  ║ ',
+                              ' c1_1: 0 ═╬══╬═',
+                              '          ║  ║ ',
+                              ' c2_0: 0 ═╩══╬═',
+                              '             ║ ',
+                              ' c2_1: 0 ════╩═',
+                              '               '])
 
         qr1 = QuantumRegister(2, 'q1')
         cr1 = ClassicalRegister(2, 'c1')
@@ -176,23 +176,23 @@ def test_text_measure_2(self):
 
     def test_text_measure_2_reversebits(self):
         """ The measure operator, using some registers, with reversebits """
-        expected = '\n'.join(["         ┌─┐   ",
-                              "q2_1: |0>┤M├───",
-                              "         └╥┘┌─┐",
-                              "q2_0: |0>─╫─┤M├",
-                              "          ║ └╥┘",
-                              "q1_1: |0>─╫──╫─",
-                              "          ║  ║ ",
-                              "q1_0: |0>─╫──╫─",
-                              "          ║  ║ ",
-                              " c2_1: 0 ═╩══╬═",
-                              "             ║ ",
-                              " c2_0: 0 ════╩═",
-                              "               ",
-                              " c1_1: 0 ══════",
-                              "               ",
-                              " c1_0: 0 ══════",
-                              "               "])
+        expected = '\n'.join(['            ┌─┐',
+                              'q2_1: |0>───┤M├',
+                              '         ┌─┐└╥┘',
+                              'q2_0: |0>┤M├─╫─',
+                              '         └╥┘ ║ ',
+                              'q1_1: |0>─╫──╫─',
+                              '          ║  ║ ',
+                              'q1_0: |0>─╫──╫─',
+                              '          ║  ║ ',
+                              ' c2_1: 0 ═╬══╩═',
+                              '          ║    ',
+                              ' c2_0: 0 ═╩════',
+                              '               ',
+                              ' c1_1: 0 ══════',
+                              '               ',
+                              ' c1_0: 0 ══════',
+                              '               '])
 
         qr1 = QuantumRegister(2, 'q1')
         cr1 = ClassicalRegister(2, 'c1')
@@ -204,15 +204,15 @@ def test_text_measure_2_reversebits(self):
 
     def test_text_swap(self):
         """ Swap drawing. """
-        expected = '\n'.join(["               ",
-                              "q1_0: |0>────X─",
-                              "             │ ",
-                              "q1_1: |0>─X──┼─",
-                              "          │  │ ",
-                              "q2_0: |0>─┼──X─",
-                              "          │    ",
-                              "q2_1: |0>─X────",
-                              "               "])
+        expected = '\n'.join(['               ',
+                              'q1_0: |0>─X────',
+                              '          │    ',
+                              'q1_1: |0>─┼──X─',
+                              '          │  │ ',
+                              'q2_0: |0>─X──┼─',
+                              '             │ ',
+                              'q2_1: |0>────X─',
+                              '               '])
 
         qr1 = QuantumRegister(2, 'q1')
         qr2 = QuantumRegister(2, 'q2')
@@ -222,15 +222,15 @@ def test_text_swap(self):
 
     def test_text_swap_reversebits(self):
         """ Swap drawing with reversebits. """
-        expected = '\n'.join(["               ",
-                              "q2_1: |0>─X────",
-                              "          │    ",
-                              "q2_0: |0>─┼──X─",
-                              "          │  │ ",
-                              "q1_1: |0>─X──┼─",
-                              "             │ ",
-                              "q1_0: |0>────X─",
-                              "               "])
+        expected = '\n'.join(['               ',
+                              'q2_1: |0>────X─',
+                              '             │ ',
+                              'q2_0: |0>─X──┼─',
+                              '          │  │ ',
+                              'q1_1: |0>─┼──X─',
+                              '          │    ',
+                              'q1_0: |0>─X────',
+                              '               '])
 
         qr1 = QuantumRegister(2, 'q1')
         qr2 = QuantumRegister(2, 'q2')
@@ -427,15 +427,15 @@ def test_text_ccx(self):
 
     def test_text_reset(self):
         """ Reset drawing. """
-        expected = '\n'.join(["                        ",
-                              "q1_0: |0>───────────|0>─",
-                              "                        ",
-                              "q1_1: |0>──────|0>──────",
-                              "                        ",
-                              "q2_0: |0>───────────────",
-                              "                        ",
-                              "q2_1: |0>─|0>───────────",
-                              "                        "])
+        expected = '\n'.join(['                        ',
+                              'q1_0: |0>─|0>───────────',
+                              '                        ',
+                              'q1_1: |0>──────|0>──────',
+                              '                        ',
+                              'q2_0: |0>───────────────',
+                              '                        ',
+                              'q2_1: |0>───────────|0>─',
+                              '                        '])
         qr1 = QuantumRegister(2, 'q1')
         qr2 = QuantumRegister(2, 'q2')
         circuit = QuantumCircuit(qr1, qr2)
@@ -445,15 +445,15 @@ def test_text_reset(self):
 
     def test_text_single_gate(self):
         """ Single Qbit gate drawing. """
-        expected = '\n'.join(["                   ┌───┐",
-                              "q1_0: |0>──────────┤ H ├",
-                              "              ┌───┐└───┘",
-                              "q1_1: |0>─────┤ H ├─────",
-                              "              └───┘     ",
-                              "q2_0: |0>───────────────",
-                              "         ┌───┐          ",
-                              "q2_1: |0>┤ H ├──────────",
-                              "         └───┘          "])
+        expected = '\n'.join(['         ┌───┐          ',
+                              'q1_0: |0>┤ H ├──────────',
+                              '         └───┘┌───┐     ',
+                              'q1_1: |0>─────┤ H ├─────',
+                              '              └───┘     ',
+                              'q2_0: |0>───────────────',
+                              '                   ┌───┐',
+                              'q2_1: |0>──────────┤ H ├',
+                              '                   └───┘'])
         qr1 = QuantumRegister(2, 'q1')
         qr2 = QuantumRegister(2, 'q2')
         circuit = QuantumCircuit(qr1, qr2)
@@ -463,15 +463,15 @@ def test_text_single_gate(self):
 
     def test_text_barrier(self):
         """ Barrier drawing. """
-        expected = '\n'.join(["             ░ ",
-                              "q1_0: |0>────░─",
-                              "             ░ ",
-                              "q1_1: |0>────░─",
-                              "             ░ ",
-                              "q2_0: |0>──────",
-                              "          ░    ",
-                              "q2_1: |0>─░────",
-                              "          ░    "])
+        expected = '\n'.join(['          ░    ',
+                              'q1_0: |0>─░────',
+                              '          ░    ',
+                              'q1_1: |0>─░────',
+                              '          ░    ',
+                              'q2_0: |0>──────',
+                              '             ░ ',
+                              'q2_1: |0>────░─',
+                              '             ░ '])
         qr1 = QuantumRegister(2, 'q1')
         qr2 = QuantumRegister(2, 'q2')
         circuit = QuantumCircuit(qr1, qr2)
@@ -481,15 +481,15 @@ def test_text_barrier(self):
 
     def test_text_no_barriers(self):
         """ Drawing without plotbarriers. """
-        expected = '\n'.join(["                        ┌───┐",
-                              "q1_0: |0>───────────────┤ H ├",
-                              "                   ┌───┐└───┘",
-                              "q1_1: |0>──────────┤ H ├─────",
-                              "              ┌───┐└───┘     ",
-                              "q2_0: |0>─────┤ H ├──────────",
-                              "         ┌───┐└───┘          ",
-                              "q2_1: |0>┤ H ├───────────────",
-                              "         └───┘               "])
+        expected = '\n'.join(['         ┌───┐               ',
+                              'q1_0: |0>┤ H ├───────────────',
+                              '         └───┘┌───┐          ',
+                              'q1_1: |0>─────┤ H ├──────────',
+                              '              └───┘┌───┐     ',
+                              'q2_0: |0>──────────┤ H ├─────',
+                              '                   └───┘┌───┐',
+                              'q2_1: |0>───────────────┤ H ├',
+                              '                        └───┘'])
         qr1 = QuantumRegister(2, 'q1')
         qr2 = QuantumRegister(2, 'q2')
         circuit = QuantumCircuit(qr1, qr2)
diff --git a/test/python/tools/visualization/test_visualization.py b/test/python/tools/visualization/test_visualization.py
--- a/test/python/tools/visualization/test_visualization.py
+++ b/test/python/tools/visualization/test_visualization.py
@@ -175,7 +175,6 @@ def setUp(self):
     def test_get_instructions(self):
         """ _get_instructions without reversebits """
         (qregs, cregs, ops) = _utils._get_instructions(self.circuit)
-
         self.assertEqual([(self.qr1, 0), (self.qr1, 1), (self.qr2, 0), (self.qr2, 1)], qregs)
         self.assertEqual([(self.cr1, 0), (self.cr1, 1), (self.cr2, 0), (self.cr2, 1)], cregs)
         self.assertEqual([op['name'] for op in ops],
diff --git a/test/python/transpiler/test_stochastic_swap.py b/test/python/transpiler/test_stochastic_swap.py
--- a/test/python/transpiler/test_stochastic_swap.py
+++ b/test/python/transpiler/test_stochastic_swap.py
@@ -349,63 +349,67 @@ def test_overoptimization_case(self):
         circuit.measure(qr[2], cr[2])
         circuit.measure(qr[3], cr[3])
         dag = circuit_to_dag(circuit)
-        #                                     ┌───┐     ┌─┐
-        # q_0: |0>────────────────────────────┤ X ├──■──┤M├────────────────
-        #                                ┌───┐└───┘┌─┴─┐└╥┘┌───┐        ┌─┐
-        # q_1: |0>───────────────────────┤ Y ├─────┤ X ├─╫─┤ S ├──■─────┤M├
-        #         ┌───┐             ┌───┐└───┘     └───┘ ║ └───┘┌─┴─┐┌─┐└╥┘
-        # q_2: |0>┤ Z ├──■──────────┤ T ├────────────────╫──────┤ X ├┤M├─╫─
-        #         └───┘┌─┴─┐┌───┐┌─┐└───┘                ║      └───┘└╥┘ ║
-        # q_3: |0>─────┤ X ├┤ H ├┤M├─────────────────────╫────────────╫──╫─
-        #              └───┘└───┘└╥┘                     ║            ║  ║
-        # c_0: 0  ════════════════╬══════════════════════╩════════════╬══╬═
-        #                         ║                                   ║  ║
-        # c_1: 0  ════════════════╬═══════════════════════════════════╬══╩═
-        #                         ║                                   ║
-        # c_2: 0  ════════════════╬═══════════════════════════════════╩════
-        #                         ║
-        # c_3: 0  ════════════════╩════════════════════════════════════════
+        #           ┌───┐                                        ┌─┐
+        # q_0: | 0 >┤ X ├────────────■───────────────────────────┤M├─────────
+        #           └───┘┌───┐     ┌─┴─┐     ┌───┐               └╥┘┌─┐
+        # q_1: | 0 >─────┤ Y ├─────┤ X ├─────┤ S ├────────────■───╫─┤M├──────
+        #                └───┘┌───┐└───┘     └───┘┌───┐     ┌─┴─┐ ║ └╥┘┌─┐
+        # q_2: | 0 >──────────┤ Z ├───────■───────┤ T ├─────┤ X ├─╫──╫─┤M├───
+        #                     └───┘     ┌─┴─┐     └───┘┌───┐└───┘ ║  ║ └╥┘┌─┐
+        # q_3: | 0 >────────────────────┤ X ├──────────┤ H ├──────╫──╫──╫─┤M├
+        #                               └───┘          └───┘      ║  ║  ║ └╥┘
+        # c_0: 0    ══════════════════════════════════════════════╩══╬══╬══╬═
+        #                                                            ║  ║  ║
+        #  c_1: 0   ═════════════════════════════════════════════════╩══╬══╬═
+        #                                                               ║  ║
+        #  c_2: 0   ════════════════════════════════════════════════════╩══╬═
+        #                                                                  ║
+        #  c_3: 0   ═══════════════════════════════════════════════════════╩═
         #
         expected = QuantumCircuit(qr, cr)
         expected.x(qr[0])
         expected.y(qr[1])
         expected.z(qr[2])
-        expected.cx(qr[2], qr[3])
-        expected.h(qr[3])
-        expected.measure(qr[3], cr[3])
         expected.swap(qr[1], qr[2])
         expected.cx(qr[0], qr[2])
         expected.measure(qr[0], cr[0])
-        expected.s(qr[2])
+        expected.swap(qr[2], qr[3])
+        expected.s(qr[3])
+        expected.cx(qr[1], qr[2])
         expected.t(qr[1])
+        expected.h(qr[2])
+        expected.swap(qr[2], qr[3])
         expected.cx(qr[2], qr[1])
-        expected.measure(qr[2], cr[1])
         expected.measure(qr[1], cr[2])
+        expected.measure(qr[2], cr[1])
+        expected.measure(qr[3], cr[3])
         expected_dag = circuit_to_dag(expected)
-        #                                        ┌───┐                     ┌─┐
-        # q_0: |0>───────────────────────────────┤ X ├──■──────────────────┤M├
-        #                           ┌───┐   ┌───┐└───┘  │       ┌───┐┌─┐   └╥┘
-        # q_1: |0>──────────────────┤ Y ├─X─┤ T ├───────┼───────┤ X ├┤M├────╫─
-        #         ┌───┐             └───┘ │ └───┘     ┌─┴─┐┌───┐└─┬─┘└╥┘┌─┐ ║
-        # q_2: |0>┤ Z ├──■────────────────X───────────┤ X ├┤ S ├──■───╫─┤M├─╫─
-        #         └───┘┌─┴─┐┌───┐┌─┐                  └───┘└───┘      ║ └╥┘ ║
-        # q_3: |0>─────┤ X ├┤ H ├┤M├──────────────────────────────────╫──╫──╫─
-        #              └───┘└───┘└╥┘                                  ║  ║  ║
-        # c_0: 0  ════════════════╬═══════════════════════════════════╬══╬══╩═
-        #                         ║                                   ║  ║
-        # c_1: 0  ════════════════╬═══════════════════════════════════╬══╩════
-        #                         ║                                   ║
-        # c_2: 0  ════════════════╬═══════════════════════════════════╩═══════
-        #                         ║
-        # c_3: 0  ════════════════╩═══════════════════════════════════════════
+        #                      ┌───┐     ┌─┐
+        # q_0: |0>─────────────┤ X ├──■──┤M├────────────────────────────────────────
+        #              ┌───┐   └───┘  │  └╥┘             ┌───┐        ┌───┐┌─┐
+        # q_1: |0>─────┤ Y ├─X────────┼───╫───────────■──┤ T ├────────┤ X ├┤M├──────
+        #         ┌───┐└───┘ │      ┌─┴─┐ ║         ┌─┴─┐└───┘┌───┐   └─┬─┘└╥┘┌─┐
+        # q_2: |0>┤ Z ├──────X──────┤ X ├─╫──X──────┤ X ├─────┤ H ├─X───■───╫─┤M├───
+        #         └───┘             └───┘ ║  │ ┌───┐└───┘     └───┘ │       ║ └╥┘┌─┐
+        # q_3: |0>────────────────────────╫──X─┤ S ├────────────────X───────╫──╫─┤M├
+        #                                 ║    └───┘                        ║  ║ └╥┘
+        #  c_0: 0 ════════════════════════╩═════════════════════════════════╬══╬══╬═
+        #                                                                   ║  ║  ║
+        #  c_1: 0 ══════════════════════════════════════════════════════════╬══╩══╬═
+        #                                                                   ║     ║
+        #  c_2: 0 ══════════════════════════════════════════════════════════╩═════╬═
+        #                                                                         ║
+        #  c_3: 0 ════════════════════════════════════════════════════════════════╩═
+
         #
         # Layout --
         #  (QuantumRegister(4, 'q'), 0): 0,
-        #  (QuantumRegister(4, 'q'), 1): 2,
-        #  (QuantumRegister(4, 'q'), 2): 1,
+        #  (QuantumRegister(4, 'q'), 1): 1,
+        #  (QuantumRegister(4, 'q'), 2): 2,
         #  (QuantumRegister(4, 'q'), 3): 3}
         pass_ = StochasticSwap(coupling, None, 20, 13)
         after = pass_.run(dag)
+
         self.assertEqual(expected_dag, after)
 
     def test_already_mapped(self):