I just started studying IBM Qiskit, and cannot find details about the barrier method on the QuantumCircuit class. It is shown in the circuit drawing, but I never heard about it after reading quantum computing text books. Is it a unitary gate? If so, how is it defined? Thanks.
1 Answer
You won't find the barrier in quantum computing textbooks because it isn't a standard primitive of quantum information theory like unitary gates and quantum circuits.
The barrier acts as a directive for circuit compilation to separate pieces of a circuit so that any optimizations or re-writes are constrained to only act between barriers (and if there are no barriers they act on the whole circuit).
This only comes into play when using the transpile
or execute
functions in Qiskit (execute
includes a transpile step).
Below is an example, and you can find more examples in these Qiskit tutorial notebooks:
Example
If a circuit has several 1-qubit gates in a row acting on the same qubit these can be combined into a single 1-qubit gate. If you explicitly want to prevent this sort of behaviour you can place a barrier between them.
Create a 1-qubit circuit with several gates
from qiskit import QuantumCircuit, QuantumRegister, transpile
qr = QuantumRegister(1)
circuit1 = QuantumCircuit(qr)
circuit1.u1(0.2, qr[0])
circuit1.u2(0.1,0.2, qr[0])
circuit1.u3(0.1, 0.2, 0.3, qr[0])
circuit1.draw()
This circuit is
┌─────────┐┌─────────────┐┌─────────────────┐
q0_0: |0>┤ U1(0.2) ├┤ U2(0.1,0.2) ├┤ U3(0.1,0.2,0.3) ├
└─────────┘└─────────────┘└─────────────────┘
If we transpile it, these gates are combined using the default settings
circuit1t = transpile(circuit1)
circuit1t.draw()
The returned circuit is
┌───────────────────────────┐
q0_0: |0>┤ U3(1.6629,0.6018,0.43905) ├
└───────────────────────────┘
Now if we want to avoid the gates being combined we could add barriers:
qr = QuantumRegister(1)
circuit2 = QuantumCircuit(qr)
circuit2.u1(0.2, qr[0])
circuit2.barrier(qr)
circuit2.u2(0.1,0.2, qr[0])
circuit2.barrier(qr)
circuit2.u3(0.1, 0.2, 0.3, qr[0])
circuit2.draw()
┌─────────┐ ░ ┌─────────────┐ ░ ┌─────────────────┐
q1_0: |0>┤ U1(0.2) ├─░─┤ U2(0.1,0.2) ├─░─┤ U3(0.1,0.2,0.3) ├
└─────────┘ ░ └─────────────┘ ░ └─────────────────┘
In this case transpiling wont change the circuit:
circuit2t = transpile(circuit2)
circuit2t.draw()
┌─────────┐ ░ ┌─────────────┐ ░ ┌─────────────────┐
q1_0: |0>┤ U1(0.2) ├─░─┤ U2(0.1,0.2) ├─░─┤ U3(0.1,0.2,0.3) ├
└─────────┘ ░ └─────────────┘ ░ └─────────────────┘