Repository: Qiskit/qiskit

Issue:
Circuit incorrectly justifed
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->

### Information

- **Qiskit Terra version**: master
- **Python version**: 3.7
- **Operating system**: macOS

### What is the current behavior?
The following circuit is not correctly justified, the first `U2` after the measure appears in its own column, rather than underneath the other `U2`.

### Steps to reproduce the problem
```python
qasm = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[5];
creg c1[1];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
cx q[1],q[0];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
u2(0,3.14159265358979) q[1];
measure q[0] -> c1[0];
u2(0,3.14159265358979) q[0];
cx q[1],q[0];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
 """
from qiskit import QuantumCircuit
qc = QuantumCircuit.from_qasm_str(qasm)
print(qc)
```

```
        ┌──────────────┐┌───┐┌──────────────┐┌─┐                ┌──────────────┐┌───┐┌──────────────┐
q_0: |0>┤ U2(0,3.1416) ├┤ X ├┤ U2(0,3.1416) ├┤M├────────────────┤ U2(0,3.1416) ├┤ X ├┤ U2(0,3.1416) ├
        ├──────────────┤└─┬─┘├──────────────┤└╥┘┌──────────────┐└──────────────┘└─┬─┘├──────────────┤
q_1: |0>┤ U2(0,3.1416) ├──■──┤ U2(0,3.1416) ├─╫─┤ U2(0,3.1416) ├──────────────────■──┤ U2(0,3.1416) ├
        └──────────────┘     └──────────────┘ ║ └──────────────┘                     └──────────────┘
q_2: |0>──────────────────────────────────────╫──────────────────────────────────────────────────────
                                              ║                                                      
q_3: |0>──────────────────────────────────────╫──────────────────────────────────────────────────────
                                              ║                                                      
q_4: |0>──────────────────────────────────────╫──────────────────────────────────────────────────────
                                              ║                                                      
c1_0: 0 ══════════════════════════════════════╩══════════════════════════════════════════════════════

```
### What is the expected behavior?
```
        ┌──────────────┐┌───┐┌──────────────┐┌─┐┌──────────────┐┌───┐┌──────────────┐
q_0: |0>┤ U2(0,3.1416) ├┤ X ├┤ U2(0,3.1416) ├┤M├┤ U2(0,3.1416) ├┤ X ├┤ U2(0,3.1416) ├
        ├──────────────┤└─┬─┘├──────────────┤└╥┘├──────────────┤└─┬─┘├──────────────┤
q_1: |0>┤ U2(0,3.1416) ├──■──┤ U2(0,3.1416) ├─╫─┤ U2(0,3.1416) ├──■──┤ U2(0,3.1416) ├
        └──────────────┘     └──────────────┘ ║ └──────────────┘     └──────────────┘
q_2: |0>──────────────────────────────────────╫──────────────────────────────────────
                                              ║                                                      
q_3: |0>──────────────────────────────────────╫──────────────────────────────────────
                                              ║                                                      
q_4: |0>──────────────────────────────────────╫──────────────────────────────────────
                                              ║                                                      
c1_0: 0 ══════════════════════════════════════╩══════════════════════════════════════
```





Discussion:
It seems like this example has the same issue (last round of `H`):

<img width="551" alt="Screen Shot 2019-07-11 at 2 49 18 PM" src="https://user-images.githubusercontent.com/766693/61078440-9d69a080-a3ee-11e9-8f89-bc8362c6c3d3.png">

The file to examine for the bug is `qiskit-terra/qiskit/visualization/text.py`
I think the error is likely to be in `qiskit-terra/qiskit/visualization/utils.py` in the method `_get_layered_instructions()` as I am seeing the bug in both the mpl and the latex outputs too. It is probably an error with the way the layers are being generated rather than drawn.
![image](https://user-images.githubusercontent.com/40489777/61373265-4271f680-a891-11e9-87cf-1d1baefb7089.png)
![image](https://user-images.githubusercontent.com/40489777/61373350-79480c80-a891-11e9-8290-28bbbc25d99e.png)

`print(qc.draw(justify='right'))` works as expected. `left` the default and `none` are broken.

Ditto `circuit_drawer`. Try:
```
circuit_drawer(qc, output='latex', interactive=True, justify='left')
circuit_drawer(qc, output='latex', interactive=True, justify='right')
circuit_drawer(qc, output='latex', interactive=True, justify='none')
```

I have examined the code and have enough of a handle on this that I can fix it **.IF.** I am sure I knew what is intended by `left`, `right`, and no justification.  _I do think I understand, but want to be sure._

Can someone please clearly enunciate the definitions?

Furthermore, I don't understand the "expected behavior" in the original report: There are 2 `u2` operations on `q1` after the `cx` and before the `measure`, so shouldn't there be a "hanging" one to right of the stacked `u2`s and before the `measure`? And likewise, the "hanging" `u2` seems to have moved over to the right of the `measure` ... is this really the "expected behavior" of diagramming the circuit generated by the qasm code given?
> `print(qc.draw(justify='right'))` works as expected. `left` the default and `none` are broken.
> 
> Ditto `circuit_drawer`. Try:
> 
> ```
> circuit_drawer(qc, output='latex', interactive=True, justify='left')
> circuit_drawer(qc, output='latex', interactive=True, justify='right')
> circuit_drawer(qc, output='latex', interactive=True, justify='none')
> ```

I was wrong, I believe now the only one that appears to be correct is `none` justification.
@jwoehr the justifications are to enable you too see the ASAP/ALAP layouts of the circuit. `left` means all the gates are drawn in the circuit as far to the left as possible, so the ASAP ordering. `right` means they are drawn as far to the right, ALAP ordering. `none` means each gate appears in its own column in the circuit.

The expected behaviour in the top example is that the two `u2` gates are stacked on top of eachother, as regardless of the order they were declared in they can happen at the same time.
Okay, thanks, @maddy-tod , I will work on it.

> The expected behaviour in the top example is that the two `u2` gates are stacked on top of eachother, as regardless of the order they were declared in they can happen at the same time.

@maddy-tod, me still confoozed :)

There are *3* `u2` circuits in the last stack before the `measure` in the example given, 1 for `q[0]` and 2 for `q[1]`.
```
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
u2(0,3.14159265358979) q[1];
```
Are you saying the 2 for `q[1]` get superimposed, drawn on top of one another, so I only see one of the `q[1]` ops?

See, if I add an `id` op:

```
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
id q[0];
u2(0,3.14159265358979) q[1];
measure q[0] -> c1[0];
```
etc., it comes out very nicely both left and right justification, as expected, with both `u2` operations showing:
```
left
        ┌────────────┐┌───┐┌────────────┐    ┌────┐    ┌─┐┌────────────┐┌───┐┌────────────┐
q_0: |0>┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├────┤ Id ├────┤M├┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├
        ├────────────┤└─┬─┘├────────────┤┌───┴────┴───┐└╥┘└────────────┘└─┬─┘├────────────┤
q_1: |0>┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├┤ U2(0,pi/1) ├─╫─────────────────■──┤ U2(0,pi/1) ├
        └────────────┘     └────────────┘└────────────┘ ║                    └────────────┘
q_2: |0>────────────────────────────────────────────────╫──────────────────────────────────
                                                        ║                                  
q_3: |0>────────────────────────────────────────────────╫──────────────────────────────────
                                                        ║                                  
q_4: |0>────────────────────────────────────────────────╫──────────────────────────────────
                                                        ║                                  
c1_0: 0 ════════════════════════════════════════════════╩══════════════════════════════════
                                                                                           
right
        ┌────────────┐┌───┐┌────────────┐    ┌────┐    ┌─┐┌────────────┐┌───┐┌────────────┐
q_0: |0>┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├────┤ Id ├────┤M├┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├
        ├────────────┤└─┬─┘├────────────┤┌───┴────┴───┐└╥┘└────────────┘└─┬─┘├────────────┤
q_1: |0>┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├┤ U2(0,pi/1) ├─╫─────────────────■──┤ U2(0,pi/1) ├
        └────────────┘     └────────────┘└────────────┘ ║                    └────────────┘
q_2: |0>────────────────────────────────────────────────╫──────────────────────────────────
                                                        ║                                  
q_3: |0>────────────────────────────────────────────────╫──────────────────────────────────
                                                        ║                                  
q_4: |0>────────────────────────────────────────────────╫──────────────────────────────────
                                                        ║                                  
c1_0: 0 ════════════════════════════════════════════════╩══════════════════════════════════
```
No, this is about the column they are drawn to, they should never be superimposed.

In the example you gave, the right justify is not correct, as the first `U2` gate is not in the column as far to the left as it can be. It should be directly underneath the other `U2`.

```

right
        ┌────────────┐┌───┐┌────────────┐    ┌────┐    ┌─┐┌────────────┐┌───┐┌────────────┐
q_0: |0>┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├────┤ Id ├────┤M├┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├
        ├────────────┤└─┬─┘├────────────┤    └────┘    └╥┘├────────────┤└─┬─┘├────────────┤
q_1: |0>┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├───────────────╫─┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├
        └────────────┘     └────────────                ║ └────────────┘     └────────────┘
q_2: |0>────────────────────────────────────────────────╫──────────────────────────────────
                                                        ║                                  
q_3: |0>────────────────────────────────────────────────╫──────────────────────────────────
                                                        ║                                  
q_4: |0>────────────────────────────────────────────────╫──────────────────────────────────
                                                        ║                                  
c1_0: 0 ════════════════════════════════════════════════╩══════════════════════════════════
```
Now I'm more confused!

In your diagram above, how can the "extra" `u2` on `q[1]` be to the right of the `measure`? It comes before the `measure` in the qasm code.
It is not directly following the qasm order, it is more looking at the topological order - aka which order the gates have to be executed in to stay consistent with the qasm.

Consider the circuit
```
qc = QuantumCircuit(2)

qc.iden(1)
qc.h(0)
qc.h(0)
```
When printed with left justify this follows the same ordering as the code.
```
        ┌───┐ ┌───┐
q_0: |0>┤ H ├─┤ H ├
        ├───┴┐└───┘
q_1: |0>┤ Id ├─────
        └────┘     
```
but with right justify the `Id` gate is shifted to be in the second column.
```
        ┌───┐┌───┐ 
q_0: |0>┤ H ├┤ H ├─
        └───┘├───┴┐
q_1: |0>─────┤ Id ├
             └────┘
```
even though the `Id` gate was declared before the `H` gates in the code. This is because with right justify we try to draw each gate as far to the right in the circuit, consistent with the code. As there is nothing else on this qubit it is ok to draw the gate in the final column.

Does this make more sense?
Okay, I think I was confused by the `measure` but since `q[1]` isn't being measured it doesn't matter where the second `u2[q1]` appears w/r/t the `messure`.
> It seems like this example has the same issue (last round of `H`):
> 
> <img alt="Screen Shot 2019-07-11 at 2 49 18 PM" width="551" src="https://user-images.githubusercontent.com/766693/61078440-9d69a080-a3ee-11e9-8f89-bc8362c6c3d3.png">

@1ucian0 , I recreate qasm for the circuit you illustrated above and test draw `left`, `right`, and `none` with this code: 
```
qasm = """
OPENQASM 2.0;
include "qelib1.inc";
qreg q[4];
h q[0];
h q[1];
h q[2];
h q[3];
cx q[0],q[3];
h q[1];
cx q[0],q[2];
cx q[0],q[1];
h q[2];
cx q[0],q[1];
h q[2];
cx q[0],q[2];
h q[1];
cx q[0],q[3];
h q[0];
h q[1];
h q[2];
h q[3];
 """
from qiskit import QuantumCircuit
qc = QuantumCircuit.from_qasm_str(qasm)
print("draw left")
print(qc.draw(justify='left'))
print("draw right")
print(qc.draw(justify='right'))
print("draw none")
print(qc.draw(justify='none'))
```
The resulting output is show below. Am I correct that _both_ `left` and `right` are incorrect (`left` for the reason you pointed out above, and `right` for the positioning of the last `h q[3]`) while `none` is correct?
```
draw left
        ┌───┐                                             ┌───┐
q_0: |0>┤ H ├──■─────────■────■────■────■─────────■───────┤ H ├
        ├───┤  │  ┌───┐  │  ┌─┴─┐┌─┴─┐  │  ┌───┐  │  ┌───┐└───┘
q_1: |0>┤ H ├──┼──┤ H ├──┼──┤ X ├┤ X ├──┼──┤ H ├──┼──┤ H ├─────
        ├───┤  │  └───┘┌─┴─┐├───┤├───┤┌─┴─┐└───┘  │  ├───┤     
q_2: |0>┤ H ├──┼───────┤ X ├┤ H ├┤ H ├┤ X ├───────┼──┤ H ├─────
        ├───┤┌─┴─┐     └───┘└───┘└───┘└───┘     ┌─┴─┐└───┘┌───┐
q_3: |0>┤ H ├┤ X ├──────────────────────────────┤ X ├─────┤ H ├
        └───┘└───┘                              └───┘     └───┘
draw right
        ┌───┐                                        ┌───┐
q_0: |0>┤ H ├──■─────────■────■────■────■─────────■──┤ H ├
        ├───┤  │  ┌───┐  │  ┌─┴─┐┌─┴─┐  │  ┌───┐  │  ├───┤
q_1: |0>┤ H ├──┼──┤ H ├──┼──┤ X ├┤ X ├──┼──┤ H ├──┼──┤ H ├
        ├───┤  │  └───┘┌─┴─┐├───┤├───┤┌─┴─┐├───┤  │  └───┘
q_2: |0>┤ H ├──┼───────┤ X ├┤ H ├┤ H ├┤ X ├┤ H ├──┼───────
        ├───┤┌─┴─┐     └───┘└───┘└───┘└───┘└───┘┌─┴─┐┌───┐
q_3: |0>┤ H ├┤ X ├──────────────────────────────┤ X ├┤ H ├
        └───┘└───┘                              └───┘└───┘
draw none
        ┌───┐                                                                      ┌───┐          
q_0: |0>┤ H ├──────────────────────■────■────■────■────────────────────────■────■──┤ H ├──────────
        └───┘┌───┐┌───┐            │    │  ┌─┴─┐┌─┴─┐┌───┐┌───┐            │    │  └───┘          
q_1: |0>─────┤ H ├┤ H ├────────────┼────┼──┤ X ├┤ X ├┤ H ├┤ H ├────────────┼────┼─────────────────
             └───┘└───┘┌───┐       │  ┌─┴─┐└───┘└───┘└───┘└───┘┌───┐┌───┐┌─┴─┐  │       ┌───┐     
q_2: |0>───────────────┤ H ├───────┼──┤ X ├────────────────────┤ H ├┤ H ├┤ X ├──┼───────┤ H ├─────
                       └───┘┌───┐┌─┴─┐└───┘                    └───┘└───┘└───┘┌─┴─┐     └───┘┌───┐
q_3: |0>────────────────────┤ H ├┤ X ├────────────────────────────────────────┤ X ├──────────┤ H ├
```

Thanks, @maddy-tod 
Given this source:
```
OPENQASM 2.0;
include "qelib1.inc";
qreg q[4];
h q[0];
h q[1];
h q[2];
h q[3];
cx q[0],q[3];
h q[1];
cx q[0],q[2];
cx q[0],q[1];
h q[2];
cx q[0],q[1];
h q[2];
cx q[0],q[2];
h q[1];
cx q[0],q[3];
h q[0];
h q[1];
h q[2];
h q[3];
```
is this now correct for left-justification?
```
        ┌───┐                                        ┌───┐
q_0: |0>┤ H ├──■─────────■────■────■────■─────────■──┤ H ├
        ├───┤  │  ┌───┐  │  ┌─┴─┐┌─┴─┐  │  ┌───┐  │  ├───┤
q_1: |0>┤ H ├──┼──┤ H ├──┼──┤ X ├┤ X ├──┼──┤ H ├──┼──┤ H ├
        ├───┤  │  └───┘┌─┴─┐├───┤├───┤┌─┴─┐├───┤  │  └───┘
q_2: |0>┤ H ├──┼───────┤ X ├┤ H ├┤ H ├┤ X ├┤ H ├──┼───────
        ├───┤┌─┴─┐     └───┘└───┘└───┘└───┘└───┘┌─┴─┐┌───┐
q_3: |0>┤ H ├┤ X ├──────────────────────────────┤ X ├┤ H ├
        └───┘└───┘                              └───┘└───┘
```
And ditto the question for this source and output, is this correct left-justification?
```
OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
creg c1[1];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
cx q[1],q[0];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
u2(0,3.14159265358979) q[1]; // or should this u2 appear to left of the measure?
measure q[0] -> c1[0];
u2(0,3.14159265358979) q[0];
cx q[1],q[0];
u2(0,3.14159265358979) q[0];
u2(0,3.14159265358979) q[1];
```

```
        ┌────────────┐┌───┐┌────────────┐┌─┐┌────────────┐┌───┐┌────────────┐
q_0: |0>┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├┤M├┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├
        ├────────────┤└─┬─┘├────────────┤└╥┘├────────────┤└─┬─┘├────────────┤
q_1: |0>┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├─╫─┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├
        └────────────┘     └────────────┘ ║ └────────────┘     └────────────┘
c1_0: 0 ══════════════════════════════════╩══════════════════════════════════
```
A little program to test this and 2 example qasm files representing the circuits we have been discussing.
```
usage: lay.py [-h] [filepath [filepath ...]]

Test qiskit-terra issue 2802. Usage: python lay.py file.qasm [file.qasm ...]

positional arguments:
  filepath    Filepath to 1 or more .qasm files

optional arguments:
  -h, --help  show this help message and exit
```
[lay.zip](https://github.com/Qiskit/qiskit-terra/files/3504435/lay.zip)

@jwoehr Yes, both those examples are now correct as all the gates are as far to the left in the circuit as they can be
> @jwoehr Yes, both those examples are now correct as all the gates are as far to the left in the circuit as they can be

Well, here is the punchline of the joke: That's what the code does when one calls for `right` justification!

Since `none` already works, I just have to

- switch `left` and `right` in `utils.py _get_layered_instructions()`, and
- make the _formerly-left-now-right_ work correctly.
I think the issue is that the layers don't taken into account where the actual gates will be plotted

```draw left
        ┌───┐                                             ┌───┐
q_0: |0>┤ H ├──■─────────■────■────■────■─────────■───────┤ H ├
        ├───┤  │  ┌───┐  │  ┌─┴─┐┌─┴─┐  │  ┌───┐  │  ┌───┐└───┘
q_1: |0>┤ H ├──┼──┤ H ├──┼──┤ X ├┤ X ├──┼──┤ H ├──┼──┤ H ├─────
        ├───┤  │  └───┘┌─┴─┐├───┤├───┤┌─┴─┐└───┘  │  ├───┤     
q_2: |0>┤ H ├──┼───────┤ X ├┤ H ├┤ H ├┤ X ├───────┼──┤ H ├─────
        ├───┤┌─┴─┐     └───┘└───┘└───┘└───┘     ┌─┴─┐└───┘┌───┐
q_3: |0>┤ H ├┤ X ├──────────────────────────────┤ X ├─────┤ H ├
        └───┘└───┘                              └───┘     └───┘
```
For example, of the last 3 columns, the first 2 are in the same layer, as all the gates could be executed in parallel. The last column is in a separate layer, as that contains gates that overlap with the previous two columns.

The required change would keep track of where in the column already contained gates, and use that to decide if a gate should stay in that column or not. I think the `right` justify works in a manner similar to this already.
So that change would still happen in `utils.py _get_layered_instructions()`?
Yes :) 
@maddy-tod , I offer apologies for being so dull-witted here, but I find the programming problem trivial and the behaviour specification nearly impenetrable :)

Given the following qasm:
```
OPENQASM 2.0;
include "qelib1.inc";
qreg q[3];
creg c[1];
h q[0];
h q[1];
h q[2];
measure q[0] -> c[0];
h q[1];
```

Here is the current behaviour of the various justifications. Are they correct? Can a "rule" be enunciated about the priority of a multibit gate w/r/t a single bit gate, or the priority of a `measure` over other operators?

```
justification left:
        ┌───┐┌─┐     
q_0: |0>┤ H ├┤M├─────
        ├───┤└╥┘┌───┐
q_1: |0>┤ H ├─╫─┤ H ├
        ├───┤ ║ └───┘
q_2: |0>┤ H ├─╫──────
        └───┘ ║      
 c_0: 0 ══════╩══════

justification right:
        ┌───┐┌─┐     
q_0: |0>┤ H ├┤M├─────
        ├───┤└╥┘┌───┐
q_1: |0>┤ H ├─╫─┤ H ├
        ├───┤ ║ └───┘
q_2: |0>┤ H ├─╫──────
        └───┘ ║      
 c_0: 0 ══════╩══════

draw justification none:
        ┌───┐               ┌─┐
q_0: |0>┤ H ├───────────────┤M├
        └───┘┌───┐┌───┐     └╥┘
q_1: |0>─────┤ H ├┤ H ├──────╫─
             └───┘└───┘┌───┐ ║ 
q_2: |0>───────────────┤ H ├─╫─
                       └───┘ ║ 
 c_0: 0 ═════════════════════╩═

```

Is even justifcation `none` correct in the above?

Incidentally, the bizarre output of `utils.py _get_layered_instructions()` as currently defined illustrates how tangled the code really is :)

```
ops by layer:
:::
	<qiskit.extensions.standard.h.HGate object at 0x7fb44f23f780> [Qubit(QuantumRegister(3, 'q'), 0)]
	<qiskit.extensions.standard.h.HGate object at 0x7fb44f23f4a8> [Qubit(QuantumRegister(3, 'q'), 1)]
	<qiskit.extensions.standard.h.HGate object at 0x7fb44f23f6d8> [Qubit(QuantumRegister(3, 'q'), 2)]
:::
	<qiskit.circuit.measure.Measure object at 0x7fb44f23f3c8> [Qubit(QuantumRegister(3, 'q'), 0)]
	<qiskit.circuit.measure.Measure object at 0x7fb44f23f3c8> [Qubit(QuantumRegister(3, 'q'), 0)]
	<qiskit.circuit.measure.Measure object at 0x7fb44f23f3c8> [Qubit(QuantumRegister(3, 'q'), 0)]
:::
	<qiskit.extensions.standard.h.HGate object at 0x7fb44f23f240> [Qubit(QuantumRegister(3, 'q'), 1)]
```
I attach again the current version of my little program `lay.py` to test layer generation and draw output.
[lay.py.zip](https://github.com/Qiskit/qiskit-terra/files/3522123/lay.py.zip)

For justification right, the H on q_2 should be on the last time slice, not the first.
Question about `DagCircuit`:

Given the following Qasm source as `qasm_src`:
```
OPENQASM 2.0;
include "qelib1.inc";
qreg q[3];
creg c[1];
h q[0];
h q[1];
h q[2];
measure q[0] -> c[0];
cx q[2],q[1];
h q[1];
```
and then
```
q_circ = QuantumCircuit.from_qasm_str(qasm_src)
noney =_get_layered_instructions(q_circ, justify='none')
```
`_get_layered_instructions(q_circ, justify='none')` simply does a 
```
ops = []
for node in dag.topological_op_nodes():
    ops.append([node]
```
which comes out like this:

```
<qiskit.extensions.standard.h.HGate object at 0x7f214a874668> [Qubit(QuantumRegister(3, 'q'), 0)]
<qiskit.extensions.standard.h.HGate object at 0x7f214a874ba8> [Qubit(QuantumRegister(3, 'q'), 1)]
<qiskit.extensions.standard.h.HGate object at 0x7f214a874e80> [Qubit(QuantumRegister(3, 'q'), 2)]
<qiskit.extensions.standard.cx.CnotGate object at 0x7f214a862c50> [Qubit(QuantumRegister(3, 'q'), 2), Qubit(QuantumRegister(3, 'q'), 1)]
<qiskit.extensions.standard.h.HGate object at 0x7f214a862ac8> [Qubit(QuantumRegister(3, 'q'), 1)]
<qiskit.circuit.measure.Measure object at 0x7f214a862dd8> [Qubit(QuantumRegister(3, 'q'), 0)]
```
- Why does `topological_op_nodes()` move the `measure` to the end?
- Is this behavior predictable and following a rule for all circuits?
If you have a look at the DAG generated by the qasm you have given, it can be seen that the measure is independent of the `cx` and final `h` so it does not matter where in the list comes in relation to them.
![image](https://user-images.githubusercontent.com/40489777/63764568-046be780-c8bf-11e9-8e2f-7d851128a4b9.png)
According to the [networkx documentation](https://networkx.github.io/documentation/latest/reference/algorithms/generated/networkx.algorithms.dag.topological_sort.html) topological sorts are non unique, which means that both the qasm order and the order returned by the DAG are valid (along with many other potential orderings!). We have found that the order the nodes are returned can vary with python versions, but ultimately they are all valid orderings.

Resolving patch:
diff --git a/qiskit/visualization/utils.py b/qiskit/visualization/utils.py
--- a/qiskit/visualization/utils.py
+++ b/qiskit/visualization/utils.py
@@ -64,7 +64,8 @@ def _trim(image):
     return image
 
 
-def _get_layered_instructions(circuit, reverse_bits=False, justify=None, idle_wires=True):
+def _get_layered_instructions(circuit, reverse_bits=False,
+                              justify=None, idle_wires=True):
     """
     Given a circuit, return a tuple (qregs, cregs, ops) where
     qregs and cregs are the quantum and classical registers
@@ -95,89 +96,8 @@ def _get_layered_instructions(circuit, reverse_bits=False, justify=None, idle_wi
         for node in dag.topological_op_nodes():
             ops.append([node])
 
-    if justify == 'left':
-        for dag_layer in dag.layers():
-            layers = []
-            current_layer = []
-
-            dag_nodes = dag_layer['graph'].op_nodes()
-            dag_nodes.sort(key=lambda nd: nd._node_id)
-
-            for node in dag_nodes:
-                multibit_gate = len(node.qargs) + len(node.cargs) > 1
-
-                if multibit_gate:
-                    # need to see if it crosses over any other nodes
-                    gate_span = _get_gate_span(qregs, node)
-
-                    all_indices = []
-                    for check_node in dag_nodes:
-                        if check_node != node:
-                            all_indices += _get_gate_span(qregs, check_node)
-
-                    if any(i in gate_span for i in all_indices):
-                        # needs to be a new layer
-                        layers.append([node])
-                    else:
-                        # can be added
-                        current_layer.append(node)
-                else:
-                    current_layer.append(node)
-
-            if current_layer:
-                layers.append(current_layer)
-            ops += layers
-
-    if justify == 'right':
-        dag_layers = []
-
-        for dag_layer in dag.layers():
-            dag_layers.append(dag_layer)
-
-        # Have to work from the end of the circuit
-        dag_layers.reverse()
-
-        # Dict per layer, keys are qubits and values are the gate
-        layer_dicts = [{}]
-
-        for dag_layer in dag_layers:
-
-            dag_instructions = dag_layer['graph'].op_nodes()
-
-            # sort into the order they were input
-            dag_instructions.sort(key=lambda nd: nd._node_id)
-            for instruction_node in dag_instructions:
-
-                gate_span = _get_gate_span(qregs, instruction_node)
-
-                added = False
-                for i in range(len(layer_dicts)):
-                    # iterate from the end
-                    curr_dict = layer_dicts[-1 - i]
-
-                    if any(index in curr_dict for index in gate_span):
-                        added = True
-
-                        if i == 0:
-                            new_dict = {}
-
-                            for index in gate_span:
-                                new_dict[index] = instruction_node
-                            layer_dicts.append(new_dict)
-                        else:
-                            curr_dict = layer_dicts[-i]
-                            for index in gate_span:
-                                curr_dict[index] = instruction_node
-
-                        break
-
-                if not added:
-                    for index in gate_span:
-                        layer_dicts[0][index] = instruction_node
-
-        # need to convert from dict format to layers
-        layer_dicts.reverse()
-        ops = [list(layer.values()) for layer in layer_dicts]
+    else:
+        ops = _LayerSpooler(dag, justify)
 
     if reverse_bits:
         qregs.reverse()
@@ -193,9 +113,20 @@ def _get_layered_instructions(circuit, reverse_bits=False, justify=None, idle_wi
     return qregs, cregs, ops
 
 
-def _get_gate_span(qregs, instruction):
-    """Get the list of qubits drawing this gate would cover"""
+def _sorted_nodes(dag_layer):
+    """Convert DAG layer into list of nodes sorted by node_id
+    qiskit-terra #2802
+    """
+    dag_instructions = dag_layer['graph'].op_nodes()
+    # sort into the order they were input
+    dag_instructions.sort(key=lambda nd: nd._node_id)
+    return dag_instructions
 
+
+def _get_gate_span(qregs, instruction):
+    """Get the list of qubits drawing this gate would cover
+    qiskit-terra #2802
+    """
     min_index = len(qregs)
     max_index = 0
     for qreg in instruction.qargs:
@@ -208,5 +139,139 @@ def _get_gate_span(qregs, instruction):
 
     if instruction.cargs:
         return qregs[min_index:]
+    if instruction.condition:
+        return qregs[min_index:]
 
     return qregs[min_index:max_index + 1]
+
+
+def _any_crossover(qregs, node, nodes):
+    """Return True .IFF. 'node' crosses over any in 'nodes',"""
+    gate_span = _get_gate_span(qregs, node)
+    all_indices = []
+    for check_node in nodes:
+        if check_node != node:
+            all_indices += _get_gate_span(qregs, check_node)
+    return any(i in gate_span for i in all_indices)
+
+
+class _LayerSpooler(list):
+    """Manipulate list of layer dicts for _get_layered_instructions."""
+
+    def __init__(self, dag, justification):
+        """Create spool"""
+        super(_LayerSpooler, self).__init__()
+        self.dag = dag
+        self.qregs = dag.qubits()
+        self.justification = justification
+
+        if self.justification == 'left':
+
+            for dag_layer in dag.layers():
+                current_index = len(self) - 1
+                dag_nodes = _sorted_nodes(dag_layer)
+                for node in dag_nodes:
+                    self.add(node, current_index)
+
+        else:
+            dag_layers = []
+
+            for dag_layer in dag.layers():
+                dag_layers.append(dag_layer)
+
+            # going right to left!
+            dag_layers.reverse()
+
+            for dag_layer in dag_layers:
+                current_index = 0
+                dag_nodes = _sorted_nodes(dag_layer)
+                for node in dag_nodes:
+                    self.add(node, current_index)
+
+    def is_found_in(self, node, nodes):
+        """Is any qreq in node found in any of nodes?"""
+        all_qargs = []
+        for a_node in nodes:
+            for qarg in a_node.qargs:
+                all_qargs.append(qarg)
+        return any(i in node.qargs for i in all_qargs)
+
+    def insertable(self, node, nodes):
+        """True .IFF. we can add 'node' to layer 'nodes'"""
+        return not _any_crossover(self.qregs, node, nodes)
+
+    def slide_from_left(self, node, index):
+        """Insert node into first layer where there is no conflict going l > r"""
+        if not self:
+            self.append([node])
+            inserted = True
+
+        else:
+            inserted = False
+            curr_index = index
+            last_insertable_index = None
+
+            while curr_index > -1:
+                if self.is_found_in(node, self[curr_index]):
+                    break
+                if self.insertable(node, self[curr_index]):
+                    last_insertable_index = curr_index
+                curr_index = curr_index - 1
+
+            if last_insertable_index:
+                self[last_insertable_index].append(node)
+                inserted = True
+
+            else:
+                inserted = False
+                curr_index = index
+                while curr_index < len(self):
+                    if self.insertable(node, self[curr_index]):
+                        self[curr_index].append(node)
+                        inserted = True
+                        break
+                    curr_index = curr_index + 1
+
+        if not inserted:
+            self.append([node])
+
+    def slide_from_right(self, node, index):
+        """Insert node into rightmost layer as long there is no conflict."""
+        if not self:
+            self.insert(0, [node])
+            inserted = True
+
+        else:
+            inserted = False
+            curr_index = index
+            last_insertable_index = None
+
+            while curr_index < len(self):
+                if self.is_found_in(node, self[curr_index]):
+                    break
+                if self.insertable(node, self[curr_index]):
+                    last_insertable_index = curr_index
+                curr_index = curr_index + 1
+
+            if last_insertable_index:
+                self[last_insertable_index].append(node)
+                inserted = True
+
+            else:
+                curr_index = index
+                while curr_index > -1:
+                    if self.insertable(node, self[curr_index]):
+                        self[curr_index].append(node)
+                        inserted = True
+                        break
+                    curr_index = curr_index - 1
+
+        if not inserted:
+            self.insert(0, [node])
+
+    def add(self, node, index):
+        """Add 'node' where it belongs, starting the try at 'index'."""
+        if self.justification == "left":
+            self.slide_from_left(node, index)
+        else:
+            self.slide_from_right(node, index)


Test patch:
diff --git a/test/python/visualization/test_visualization.py b/test/python/visualization/test_visualization.py
--- a/test/python/visualization/test_visualization.py
+++ b/test/python/visualization/test_visualization.py
@@ -19,6 +19,7 @@
 import unittest
 
 from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
+from qiskit.circuit import Qubit, Clbit
 from qiskit.circuit.random import random_circuit
 from qiskit.visualization import utils
 from qiskit.visualization import circuit_drawer
@@ -209,6 +210,178 @@ def test_get_layered_instructions_remove_idle_wires(self):
         self.assertEqual(exp,
                          [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops])
 
+    def test_get_layered_instructions_left_justification_simple(self):
+        """ Test _get_layered_instructions left justification simple since #2802
+q_0: |0>───────■──
+        ┌───┐  │
+q_1: |0>┤ H ├──┼──
+        ├───┤  │
+q_2: |0>┤ H ├──┼──
+        └───┘┌─┴─┐
+q_3: |0>─────┤ X ├
+             └───┘
+"""
+        qc = QuantumCircuit(4)
+        qc.h(1)
+        qc.h(2)
+        qc.cx(0, 3)
+
+        (_, _, layered_ops) = utils._get_layered_instructions(qc, justify='left')
+
+        l_exp = [[('h', [Qubit(QuantumRegister(4, 'q'), 1)], []),
+                  ('h', [Qubit(QuantumRegister(4, 'q'), 2)], [])],
+                 [('cx', [Qubit(QuantumRegister(4, 'q'), 0),
+                          Qubit(QuantumRegister(4, 'q'), 3)], [])
+                  ]
+                 ]
+
+        self.assertEqual(l_exp,
+                         [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops])
+
+    def test_get_layered_instructions_right_justification_simple(self):
+        """ Test _get_layered_instructions right justification simple since #2802
+q_0: |0>──■───────
+          │  ┌───┐
+q_1: |0>──┼──┤ H ├
+          │  ├───┤
+q_2: |0>──┼──┤ H ├
+        ┌─┴─┐└───┘
+q_3: |0>┤ X ├─────
+        └───┘
+"""
+        qc = QuantumCircuit(4)
+        qc.h(1)
+        qc.h(2)
+        qc.cx(0, 3)
+
+        (_, _, layered_ops) = utils._get_layered_instructions(qc, justify='right')
+
+        r_exp = [[('cx', [Qubit(QuantumRegister(4, 'q'), 0),
+                          Qubit(QuantumRegister(4, 'q'), 3)], [])],
+                 [('h', [Qubit(QuantumRegister(4, 'q'), 1)], []),
+                  ('h', [Qubit(QuantumRegister(4, 'q'), 2)], [])
+                  ]
+                 ]
+
+        self.assertEqual(r_exp,
+                         [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops])
+
+    def test_get_layered_instructions_left_justification_less_simple(self):
+        """ Test _get_layered_instructions left justification
+        less simple example since #2802
+        ┌────────────┐┌───┐┌────────────┐              ┌─┐┌────────────┐┌───┐┌────────────┐
+q_0: |0>┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├──────────────┤M├┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├
+        ├────────────┤└─┬─┘├────────────┤┌────────────┐└╥┘└────────────┘└─┬─┘├────────────┤
+q_1: |0>┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├┤ U2(0,pi/1) ├─╫─────────────────■──┤ U2(0,pi/1) ├
+        └────────────┘     └────────────┘└────────────┘ ║                    └────────────┘
+q_2: |0>────────────────────────────────────────────────╫──────────────────────────────────
+                                                        ║
+q_3: |0>────────────────────────────────────────────────╫──────────────────────────────────
+                                                        ║
+q_4: |0>────────────────────────────────────────────────╫──────────────────────────────────
+                                                        ║
+c1_0: 0 ════════════════════════════════════════════════╩══════════════════════════════════
+        """
+        qasm = """
+        OPENQASM 2.0;
+        include "qelib1.inc";
+        qreg q[5];
+        creg c1[1];
+        u2(0,3.14159265358979) q[0];
+        u2(0,3.14159265358979) q[1];
+        cx q[1],q[0];
+        u2(0,3.14159265358979) q[0];
+        u2(0,3.14159265358979) q[1];
+        u2(0,3.14159265358979) q[1];
+        measure q[0] -> c1[0];
+        u2(0,3.14159265358979) q[0];
+        cx q[1],q[0];
+        u2(0,3.14159265358979) q[0];
+        u2(0,3.14159265358979) q[1];
+        """
+        qc = QuantumCircuit.from_qasm_str(qasm)
+
+        (_, _, layered_ops) = utils._get_layered_instructions(qc, justify='left')
+
+        l_exp = [[('u2', [Qubit(QuantumRegister(5, 'q'), 0)], []),
+                  ('u2', [Qubit(QuantumRegister(5, 'q'), 1)], [])],
+                 [('cx',
+                   [Qubit(QuantumRegister(5, 'q'), 1), Qubit(QuantumRegister(5, 'q'), 0)],
+                   [])],
+                 [('u2', [Qubit(QuantumRegister(5, 'q'), 0)], []),
+                  ('u2', [Qubit(QuantumRegister(5, 'q'), 1)], [])],
+                 [('u2', [Qubit(QuantumRegister(5, 'q'), 1)], [])],
+                 [('measure',
+                   [Qubit(QuantumRegister(5, 'q'), 0)],
+                   [Clbit(ClassicalRegister(1, 'c1'), 0)])],
+                 [('u2', [Qubit(QuantumRegister(5, 'q'), 0)], [])],
+                 [('cx',
+                   [Qubit(QuantumRegister(5, 'q'), 1), Qubit(QuantumRegister(5, 'q'), 0)],
+                   [])],
+                 [('u2', [Qubit(QuantumRegister(5, 'q'), 0)], []),
+                  ('u2', [Qubit(QuantumRegister(5, 'q'), 1)], [])]]
+
+        self.assertEqual(l_exp,
+                         [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops])
+
+    def test_get_layered_instructions_right_justification_less_simple(self):
+        """ Test _get_layered_instructions right justification
+        less simple example since #2802
+        ┌────────────┐┌───┐┌────────────┐┌─┐┌────────────┐┌───┐┌────────────┐
+q_0: |0>┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├┤M├┤ U2(0,pi/1) ├┤ X ├┤ U2(0,pi/1) ├
+        ├────────────┤└─┬─┘├────────────┤└╥┘├────────────┤└─┬─┘├────────────┤
+q_1: |0>┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├─╫─┤ U2(0,pi/1) ├──■──┤ U2(0,pi/1) ├
+        └────────────┘     └────────────┘ ║ └────────────┘     └────────────┘
+q_2: |0>──────────────────────────────────╫──────────────────────────────────
+                                          ║
+q_3: |0>──────────────────────────────────╫──────────────────────────────────
+                                          ║
+q_4: |0>──────────────────────────────────╫──────────────────────────────────
+                                          ║
+c1_0: 0 ══════════════════════════════════╩══════════════════════════════════
+        """
+        qasm = """
+        OPENQASM 2.0;
+        include "qelib1.inc";
+        qreg q[5];
+        creg c1[1];
+        u2(0,3.14159265358979) q[0];
+        u2(0,3.14159265358979) q[1];
+        cx q[1],q[0];
+        u2(0,3.14159265358979) q[0];
+        u2(0,3.14159265358979) q[1];
+        u2(0,3.14159265358979) q[1];
+        measure q[0] -> c1[0];
+        u2(0,3.14159265358979) q[0];
+        cx q[1],q[0];
+        u2(0,3.14159265358979) q[0];
+        u2(0,3.14159265358979) q[1];
+        """
+        qc = QuantumCircuit.from_qasm_str(qasm)
+
+        (_, _, layered_ops) = utils._get_layered_instructions(qc, justify='right')
+
+        r_exp = [[('u2', [Qubit(QuantumRegister(5, 'q'), 0)], []),
+                  ('u2', [Qubit(QuantumRegister(5, 'q'), 1)], [])],
+                 [('cx',
+                   [Qubit(QuantumRegister(5, 'q'), 1), Qubit(QuantumRegister(5, 'q'), 0)],
+                   [])],
+                 [('u2', [Qubit(QuantumRegister(5, 'q'), 0)], []),
+                  ('u2', [Qubit(QuantumRegister(5, 'q'), 1)], [])],
+                 [('measure',
+                   [Qubit(QuantumRegister(5, 'q'), 0)],
+                   [Clbit(ClassicalRegister(1, 'c1'), 0)])],
+                 [('u2', [Qubit(QuantumRegister(5, 'q'), 0)], []),
+                  ('u2', [Qubit(QuantumRegister(5, 'q'), 1)], [])],
+                 [('cx',
+                   [Qubit(QuantumRegister(5, 'q'), 1), Qubit(QuantumRegister(5, 'q'), 0)],
+                   [])],
+                 [('u2', [Qubit(QuantumRegister(5, 'q'), 0)], []),
+                  ('u2', [Qubit(QuantumRegister(5, 'q'), 1)], [])]]
+
+        self.assertEqual(r_exp,
+                         [[(op.name, op.qargs, op.cargs) for op in ops] for ops in layered_ops])
+
 
 if __name__ == '__main__':
     unittest.main(verbosity=2)