# Why qiskit changed the order of gated applied to a circuit

Below I created a circuit and applied several gates to it:

n = 4

qubits = QuantumRegister(n, name='q')
ansilla = QuantumRegister(n - 1, name='ans')

circuit = QuantumCircuit(qubits, ansilla)

# I step
circuit.ccx(qubits[0], qubits[1], ansilla[0])

# II step
for i in range(2, n - 1):
circuit.ccx(qubits[i], ansilla[i-2], ansilla[i-1])

# III step
circuit.cx(ansilla[-1], qubits[-1])


When I draw a visualization with circuit.draw() I got the following diagram:

It draws III step before II step.

Is it a bug or how can I overcome this problem?

I use qiskit version=0.8.2

Why does it do it? I don't know.

What I do know is that it isn't a problem when the circuit is run. Step II and step III are applied to completely different sets of qubits. As such, it does not matter which is done first.

If you nevertheless want to stop it happening, circuit.draw(justify='none'). If that ever doesn't work for any reason, you can put a circuit.barrier() operation between the steps. This will stop the compiler doing whatever it is doing.

Since this behaviour is obvious not intended, please consider filing an issue so that it can be fixed.

• Is it possible to force qiskit to follow the order? – Kenenbek Arzymatov Aug 30 '19 at 11:46
• I updated my answer just as you were asking this! – James Wootton Aug 30 '19 at 11:47

The reason this happens is that the sort order is not guaranteed for the diagram.

It's a matter of network theory. networkx is the toolkit used for the DAG (Distributed Acyclic Graph) into which circuits are decomposed.

In your example, it doesn't matter to the computation which operation occurs first.

If it matters, the order displayed is guaranteed correct.