0
$\begingroup$

I'm trying to print the quantum gates in a circuit using the QuantumCircuit.data. However, the printed quantum gate order is not the same as the drawing. For example, in the QFT5 circuit generated from qiskit.circuit.library, the gate order should be CP(4,1), H(2), CP(3,1), CP(4,0), CP(2,1). However, the printed gate order is H(2), CP(4,1), CP(3,1), CP(2,1), CP(4,0). Is there any way I can print the original gate order? enter image description here

enter image description here

The code I used to print the gate order is:

for gate in circuit.data:
    print(gate[0].name)
    print(gate[1])
$\endgroup$

1 Answer 1

1
$\begingroup$

First of all, the two orders are equivalent in the sense that both of them implements the same unitary.

If you want to print the circuit gates in the same order as its plot, you can use the following code snippet:

qft5 = QFT(5, do_swaps=False).decompose()

from qiskit.converters import circuit_to_dag, dag_to_circuit
dag = circuit_to_dag(qft5)
for layer in dag.layers():
    layer_as_circuit = dag_to_circuit(layer['graph'])
    for _inst in layer_as_circuit.data:
        print(_inst.operation.name, [qubit.index for qubit in  _inst.qubits])

And if you want the gates in the circuit plot to match their order in QuantumCircuit.data, you can achieve this by inserting a Barrier after each H-gate:

from qiskit.circuit.library import QFT
from qiskit.circuit import CircuitInstruction
from qiskit.circuit.library import Barrier

qft5 = QFT(5, do_swaps=False).decompose()

# Insert barrier after each H-gate
_len = len(qft5.data)
for index, _instr in enumerate(reversed(qft5.data)):
    if _instr.operation.name == 'h':
        qft5.data.insert(_len - index, CircuitInstruction(Barrier(5), range(5)))

qft5.draw('mpl', fold=-1)

enter image description here

If you prefer to draw the circuit without barriers, you can set plot_barriers to False:

qft5.draw('mpl', plot_barriers=False)

enter image description here

$\endgroup$
2
  • $\begingroup$ Thanks. But I think you misunderstood my question. What I want is to print out the gate order of the original qft5.draw('mpl'), which is shown in my question. I have updated the question with the code I used to print the gate order. $\endgroup$
    – Amanli
    Commented Jun 29, 2023 at 17:27
  • $\begingroup$ I updated my answer $\endgroup$ Commented Jun 30, 2023 at 9:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.