Assume my function Qiskit receives a certain circuit as an input. How do I check if this circuit already has some measurements appended to it? If so, how can I modify them? For example, if there are measurements on certain qubits, I would like to remove those in order to add some more gates, and then add the measurement of all qubits.


The easiest way to do this is probably by converting the circuit to a DAGCircuit, which can be done using the method from qiskit.converters import circuit_to_dag. From the DAG you can get properties, such as any measurement operations, by using the function my_dag.named_nodes('measurement'). DAGNode objects are returned which will tell you the properties of the measurement. You can then remove nodes using my_dag.remove_op_node(a_measurement_node), it is preferable to remove and add nodes than to modify inplace. Following this you could convert the DAGCircuit back to a QuantumCircuit using from qiskit.converters import dag_to_circuit and then append any measurement operations as desired.

  • $\begingroup$ Wow, that's quite involved but will hopefully work :) Why can't I just copy the gates one by one to another circuit, until I reach the measurement? $\endgroup$ – mavzolej May 25 '20 at 20:24
  • $\begingroup$ That would also work, but it would mean creating a new circuit, but if you are fine with doing that it should work $\endgroup$ – met927 May 26 '20 at 10:34
  • $\begingroup$ Could you explain how exactly I should do it this way? $\endgroup$ – mavzolej May 26 '20 at 12:09
  • 1
    $\begingroup$ You could iterate over QuantumCircuit.data() which returns a list like object of (instruction, qargs, cargs). You should then be able to do new_circuit.append(instruction, qargs,cargs) $\endgroup$ – met927 May 26 '20 at 14:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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