diff --git a/pyzx/circuit/__init__.py b/pyzx/circuit/__init__.py index 87f67376..f2bd2bf3 100644 --- a/pyzx/circuit/__init__.py +++ b/pyzx/circuit/__init__.py @@ -389,10 +389,15 @@ def to_quipper(self) -> str: s += "Outputs: " + ", ".join("{!s}:Qbit".format(i) for i in range(self.qubits)) return s - def to_qasm(self) -> str: + def to_qasm(self, version: int = 2) -> str: """Produces a QASM description of the circuit.""" - s = """OPENQASM 2.0;\ninclude "qelib1.inc";\n""" - s += "qreg q[{!s}];\n".format(self.qubits) + assert version in [2, 3] + if version == 3: + s = """OPENQASM 3;\ninclude "stdgates.inc";\n""" + s += "qubit[{!s}] q;\n".format(self.qubits) + else: + s = """OPENQASM 2.0;\ninclude "qelib1.inc";\n""" + s += "qreg q[{!s}];\n".format(self.qubits) for g in self.gates: s += g.to_qasm() + "\n" return s diff --git a/pyzx/routing/parity_maps.py b/pyzx/routing/parity_maps.py index 8eec42f6..f14c8856 100644 --- a/pyzx/routing/parity_maps.py +++ b/pyzx/routing/parity_maps.py @@ -106,8 +106,8 @@ def prepend_gate(self, gate: Union[Gate, str], *args, **kwargs): gate = gate_class(*args, **kwargs) self.gates.insert(0, gate) - def to_qasm(self) -> str: - qasm = super().to_qasm() + def to_qasm(self, version: int = 2) -> str: + qasm = super().to_qasm(version) initial_perm = "// Initial wiring: " + str(self.row_perm) end_perm = "// Resulting wiring: " + str(self.col_perm) return "\n".join([initial_perm, end_perm, qasm]) diff --git a/tests/test_qasm.py b/tests/test_qasm.py index 885786db..4754b909 100644 --- a/tests/test_qasm.py +++ b/tests/test_qasm.py @@ -174,6 +174,11 @@ def compare_gate_matrix_with_qiskit(gates, num_qubits: int, num_angles: int, qas self.assertTrue(compare_tensors(pyzx_matrix, qiskit_matrix, False), f"Gate: {gate}\nqasm:\n{qasm}\npyzx_matrix:\n{pyzx_matrix}\nqiskit_matrix:\n{qiskit_matrix}") + s = c.to_qasm(qasm_version) + round_trip = Circuit.from_qasm(s) + self.assertEqual(c.qubits, round_trip.qubits) + self.assertListEqual(c.gates, round_trip.gates) + # Test standard gates common to both OpenQASM 2 and 3. compare_gate_matrix_with_qiskit( ['x', 'y', 'z', 'h', 's', 'sdg', 't', 'tdg', 'sx'], 1, 0)