3
$\begingroup$

In Qiskit, I am looking for a convenient way to "strip-off" a QuantumCircuit object from its multiple QuantumRegister and ClassicalRegister objects, such that in the final QuantumCircuit object there will be only 1 QuantumRegister and 1 ClassicalRegister, without any loss of the circuit's qubits, bits or content.

I haven't found any built-in option in Qiskit for this feature so far. However, when I look at a job page in IBM Quantum website I see a QASM code of the job's circuit exactly as I am looking for (with 1 qreg and 1 creg). So I infer there is a convenient way to implement this.

$\endgroup$

1 Answer 1

2
$\begingroup$

The easiest way from the top of my head is to simply compose your multiregistered circuit to a flat one:

Say you have this circuit:

from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister

qreg1 = QuantumRegister(1, 'qreg1')
qreg2 = QuantumRegister(1, 'qreg2')
creg1 = ClassicalRegister(1, 'creg1')
creg2 = ClassicalRegister(1, 'creg2')
circuit = QuantumCircuit(qreg1, qreg2, creg1, creg2)
circuit.h(qreg1)
circuit.cx(qreg1, qreg2)
circuit.measure(qreg1, creg1)
circuit.measure(qreg2, creg2)
circuit.draw()
         ┌───┐     ┌─┐   
  qreg1: ┤ H ├──■──┤M├───
         └───┘┌─┴─┐└╥┘┌─┐
  qreg2: ─────┤ X ├─╫─┤M├
              └───┘ ║ └╥┘
creg1: 1/═══════════╩══╬═
                    0  ║ 
creg2: 1/══════════════╩═
                       0 

You can compose it to a flat one like this, resulting in a circuit like the one you are searching for:

flat_circuit = QuantumCircuit(circuit.num_qubits, circuit.num_clbits)
flat_circuit.compose(circuit, inplace=True)
flat_circuit.draw()
     ┌───┐     ┌─┐   
q_0: ┤ H ├──■──┤M├───
     └───┘┌─┴─┐└╥┘┌─┐
q_1: ─────┤ X ├─╫─┤M├
          └───┘ ║ └╥┘
c: 2/═══════════╩══╩═
                0  1 
$\endgroup$
2
  • $\begingroup$ Works perfectly, thanks. However I wonder if this method can be computationally costly when dealing with large circuits. $\endgroup$
    – Ohad
    Mar 6, 2023 at 5:55
  • $\begingroup$ the code in QuantumCircuit.compose iterates on other.data and copy it. So yes. It is not O(1). $\endgroup$
    – luciano
    Apr 12, 2023 at 9:40

Your Answer

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

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