Skip to content

Commit

Permalink
Merge pull request #174 from dlyongemallo/support_qasm3_output
Browse files Browse the repository at this point in the history
Support output to OpenQASM 3 format.
  • Loading branch information
jvdwetering authored Oct 22, 2023
2 parents f4f47c8 + 4d22062 commit 4e7eb4a
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 5 deletions.
11 changes: 8 additions & 3 deletions pyzx/circuit/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions pyzx/routing/parity_maps.py
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand Down
5 changes: 5 additions & 0 deletions tests/test_qasm.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 4e7eb4a

Please sign in to comment.