OpenQASM 2 Export and Import
Convert a circuit to OpenQASM 2.0 with qasm2.dumps, rebuild it with qasm2.loads, and verify the operator matches.
OpenQASM is a text language for describing quantum circuits. Version 2.0 uses the qelib1.inc library and qreg/creg registers, and measurement is written measure q[0] -> c[0];. In Qiskit the qiskit.qasm2 module is used: dumps returns text and loads builds a circuit from text.
To verify, we remove the final measurements (because a unitary operator is not defined with measurement) and compare the two operators with Operator.equiv.
Requirements: pip install qiskit qiskit-aer. The code runs on your machine or in Colab, not inside WordPress.
Code
from qiskit import QuantumCircuit, qasm2
from qiskit.quantum_info import Operator
qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.rz(0.5, 1)
qc.measure([0, 1], [0, 1])
text = qasm2.dumps(qc)
print(text)
back = qasm2.loads(text)
print("ops:", dict(back.count_ops()))
a = qc.remove_final_measurements(inplace=False)
b = back.remove_final_measurements(inplace=False)
print("same unitary:", Operator(a).equiv(Operator(b)))
Line-by-line code explanation
| Line | Explanation |
|---|---|
| 1-2 | Import the circuit, the qasm2 module and Operator. |
| 4 | A two-qubit circuit. |
| 5-7 | H, CNOT and an RZ rotation. |
| 8 | Measurement. |
| 10 | Convert the circuit to OpenQASM 2 text. |
| 11 | Print it. |
| 13 | Rebuild the circuit from the text. |
| 14 | Count its operations. |
| 15-16 | Remove the final measurements from both copies. |
| 17 | Compare the two unitary operators. |
Expected output (from an actual run)
OPENQASM 2.0;
include "qelib1.inc";
qreg q[2];
creg c[2];
h q[0];
cx q[0],q[1];
rz(0.5) q[1];
measure q[0] -> c[0];
measure q[1] -> c[1];
ops: {'measure': 2, 'h': 1, 'cx': 1, 'rz': 1}
same unitary: True
The output is deterministic.
Related topics
References
- Andrew W. Cross; Lev S. Bishop; John A. Smolin; Jay M. Gambetta (2017). Open Quantum Assembly Language. arXiv:1707.03429 doi:10.48550/arXiv.1707.03429
- OpenQASM contributors (2025). OpenQASM Live Specification. openqasm.com openqasm.com
- IBM Quantum (2025). Qiskit SDK API documentation. IBM Quantum Documentation quantum.cloud.ibm.com
