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

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 1


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']]):
        elif line.startswith('barrier'):
    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)):
                             ┌───┐ ┌───┐
   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
  • $\begingroup$ 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'" $\endgroup$
    – MShakeG
    Sep 7, 2020 at 21:47
  • $\begingroup$ Additionally I thought it might be the version so I upgraded from 0.19 to 0.20 and still the same issue. $\endgroup$
    – MShakeG
    Sep 7, 2020 at 22:30
  • 1
    $\begingroup$ 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]) $\endgroup$
    – MShakeG
    Sep 7, 2020 at 22:38
  • $\begingroup$ 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. $\endgroup$
    – luciano
    Sep 8, 2020 at 15:21
  • $\begingroup$ will try, thanks:) $\endgroup$
    – MShakeG
    Sep 8, 2020 at 15:30

Your Answer

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

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