# How to split a Quantum Circuit on a barrier in Qiskit?

Let's say I have a QuantumCircuit with multiple barriers as shown in the visual below:

How would I split up the QuantumCircuit on the barriers into a list of 3 QuantumCircuits in Qiskit?

NB: Not directly relevant to the question, but the circuit is a random Unitary circuit, as I'm doing randomised-benchmarking. The circuit is generated as shown in the Qiskit Textbook: 5.3 Randomized Benchmarking.

## 1 Answer

For such a simple circuit, probably the easier way is to dump it as QASM and read it back.

def split_circuit_by_barrier(circuit):
qasm = circuit.qasm()
prelude = []
circuits = [[]]
for line in qasm.splitlines():
if any([line.startswith(t) for t in ['OPENQASM', 'include', 'qreg', 'creg']]):
prelude.append(line)
elif line.startswith('barrier'):
circuits.append([])
else:
circuits[-1].append(line)
circuits_with_prelude = [prelude+circuit for circuit in circuits]
for circuit_with_prelude in circuits_with_prelude:
yield QuantumCircuit.from_qasm_str('\n'.join(circuit_with_prelude))


Taking your example:

for subcircuit in (split_circuit_by_barrier(circuit)):
print(subcircuit)

                             ┌───┐ ┌───┐
q_0: ─────────────────■───┤ H ├─┤ S ├─────
┌───┐┌───┐┌───┐┌─┴─┐┌┴───┴┐├───┤┌───┐
q_1: ┤ H ├┤ H ├┤ S ├┤ X ├┤ SDG ├┤ H ├┤ X ├
└───┘└───┘└───┘└───┘└─────┘└───┘└───┘
meas: 2/═════════════════════════════════════

┌─────┐┌───┐
q_0: ┤ SDG ├┤ H ├───────■───────────────────
└┬───┬┘├───┤┌───┐┌─┴─┐┌─────┐┌───┐┌───┐
q_1: ─┤ X ├─┤ H ├┤ S ├┤ X ├┤ SDG ├┤ H ├┤ H ├
└───┘ └───┘└───┘└───┘└─────┘└───┘└───┘
meas: 2/═══════════════════════════════════════

┌─┐
q_0: ┤M├───
└╥┘┌─┐
q_1: ─╫─┤M├
║ └╥┘
meas: 2/═╩══╩═
0  1

• Thank you for the answer. However when I run your function on my QuantumCircuit I get the following error: QasmError: "Expected an ID, received 'creg'" Sep 7 '20 at 21:47
• Additionally I thought it might be the version so I upgraded from 0.19 to 0.20 and still the same issue. Sep 7 '20 at 22:30
• additionally I think the reason I might be getting the above error is because I manually added the classical registers and measurements like so: qc.add_register(ClassicalRegister(2,'creg')); qc.barrier(); qc.measure([0,1], [0,1]) Sep 7 '20 at 22:38
• I see. This is a bug github.com/Qiskit/qiskit-terra/issues/5043 . The problem is the creg name. Change the name and I think it will work. Sep 8 '20 at 15:21
• will try, thanks:) Sep 8 '20 at 15:30