10
$\begingroup$

Suppose I want to implement run several circuits one after another, but they are constructed in a similar fashion. I could reinstantiate a QuantumCircuit for each iteration, like this:

params = np.linspace(0, 2 * np.pi, num=20)
for p in params:
    circ = QuantumCircuit(q, c)
    do_stuff(circ, p)
    do_other_stuff()

but I'm afraid that creating a bunch of unnecessary circ objects takes too much memory or too many calls to the garbage collector.

Instead, I would like to remove the gates from the QuantumCircuit object and build the new circuit in the old object. Is it possible, and if so, is it reasonable?

$\endgroup$

1 Answer 1

10
$\begingroup$

Quantum circuits have a data attribute, which is a list of all gates. You can remove elements from this as with any Python list. For example, here's a circuit

q = QuantumRegister(1)
circ = QuantumCircuit(q)

circ.h(q[0])
circ.s(q[0])
circ.x(q[0])

Let's get rid of the S gate. First, we can look at the list of gates with circ.data. This gives

[<qiskit.extensions.standard.h.HGate at 0x11721b7b8>,
 <qiskit.extensions.standard.s.SGate at 0x11721b828>,
 <qiskit.extensions.standard.x.XGate at 0x11721b7f0>]

Element 1 of this list (i.e. the second element) is the gate we want rid of. We can do this with pop.

qiskit.data.pop(1)

The resulting circuit can then be seen by print(circ)

         ┌───┐┌───┐
q0_0: |0>┤ H ├┤ X ├
         └───┘└───┘

As you can see, we have succeeded in removing the S gate.

Note that you can get information about the elements of the data list using the methods name and qargs, etc, of gate objects. For example, to see that element 0 is a Hadamard, and to see which qubit it acts on, we can use

print( circ.data[0].name )
print( circ.data[0].qargs )

This returns

h
[(QuantumRegister(1, 'q0'), 0)]
$\endgroup$
1
  • $\begingroup$ Do you know if circ.data returns the gates in a topological order like in dag.topological_op_nodes()? $\endgroup$
    – FSeed
    Jun 5, 2022 at 18:43

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.