The method you are looking for is circuit.data.insert
. Some simple examples are detailed in this paper. For your example, we have:
from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit
qr = QuantumRegister(1, 'q')
cr = ClassicalRegister(1, 'c')
base_circ = QuantumCircuit(qr, cr)
for i in range(3):
base_circ.measure(0,0)
base_circ.barrier()
base_circ.draw()
Output:
┌─┐ ░ ┌─┐ ░ ┌─┐ ░
q: ┤M├─░─┤M├─░─┤M├─░─
└╥┘ ░ └╥┘ ░ └╥┘ ░
c: 1/═╩═════╩═════╩════
0 0 0
Note that as mentioned in another answer, this circuit is just a list of CircuitInstruction
types
print(base_circ.data)
Output:
[CircuitInstruction(operation=Instruction(name='x', num_qubits=1, num_clbits=0, params=[]), qubits=(Qubit(QuantumRegister(1, 'q'), 0),), clbits=()), CircuitInstruction(operation=Instruction(name='measure', num_qubits=1, num_clbits=1, params=[]), qubits=(Qubit(QuantumRegister(1, 'q'), 0),), clbits=(Clbit(ClassicalRegister(1, 'c'), 0),)), CircuitInstruction(operation=Instruction(name='barrier', num_qubits=1, num_clbits=0, params=[]), qubits=(Qubit(QuantumRegister(1, 'q'), 0),), clbits=()), CircuitInstruction(operation=Instruction(name='x', num_qubits=1, num_clbits=0, params=[]), qubits=(Qubit(QuantumRegister(1, 'q'), 0),), clbits=()), CircuitInstruction(operation=Instruction(name='measure', num_qubits=1, num_clbits=1, params=[]), qubits=(Qubit(QuantumRegister(1, 'q'), 0),), clbits=(Clbit(ClassicalRegister(1, 'c'), 0),)), CircuitInstruction(operation=Instruction(name='barrier', num_qubits=1, num_clbits=0, params=[]), qubits=(Qubit(QuantumRegister(1, 'q'), 0),), clbits=()), CircuitInstruction(operation=Instruction(name='measure', num_qubits=1, num_clbits=1, params=[]), qubits=(Qubit(QuantumRegister(1, 'q'), 0),), clbits=(Clbit(ClassicalRegister(1, 'c'), 0),)), CircuitInstruction(operation=Instruction(name='barrier', num_qubits=1, num_clbits=0, params=[]), qubits=(Qubit(QuantumRegister(1, 'q'), 0),), clbits=())]
And so inserting operations is just a matter of inserting CircuitInstruction
objects to this list. Now there might be a better way to do this, but if I wanted to insert an X gate before the first two measures, I'd first declare a circuit that is just an X gate, and then insert that as a CircuitInstruction
with the built-in methods.
x_gate = QuantumCircuit(1)
x_gate.x(0)
base_circ.data.insert(0, x_gate.data[0])
base_circ.data.insert(3, x_gate.data[0])
base_circ.draw()
Output:
┌───┐┌─┐ ░ ┌───┐┌─┐ ░ ┌─┐ ░
q: ┤ X ├┤M├─░─┤ X ├┤M├─░─┤M├─░─
└───┘└╥┘ ░ └───┘└╥┘ ░ └╥┘ ░
c: 1/══════╩══════════╩═════╩════
0 0 0
Note that after the first insertion, your indices change. So as long as you keep tabs of where you are trying to insert operations you should be fine. Also note that the qubits
field in CircuitInstruction
need to match with the circuit you're trying to insert. Meaning that if you do it the way I showed here, the QuantumCircuit
for the single X gate needs to be of the same register size.
circuit.data.insert
$\endgroup$