Skip to content

Commit a9d2236

Browse files
Add exporter implementation
1 parent 5922ec4 commit a9d2236

File tree

2 files changed

+131
-0
lines changed

2 files changed

+131
-0
lines changed

graphix/qasm3_exporter.py

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
"""Exporter to OpenQASM3."""
2+
3+
from __future__ import annotations
4+
5+
from fractions import Fraction
6+
from math import pi
7+
from typing import TYPE_CHECKING
8+
9+
# assert_never added in Python 3.11
10+
from typing_extensions import assert_never
11+
12+
from graphix.instruction import Instruction, InstructionKind
13+
14+
if TYPE_CHECKING:
15+
from collections.abc import Iterator
16+
17+
from graphix import Circuit
18+
19+
20+
def circuit_to_qasm3(circuit: Circuit) -> str:
21+
"""Export circuit instructions to OpenQASM 3.0 representation.
22+
23+
Returns
24+
-------
25+
str
26+
The OpenQASM 3.0 string representation of the circuit.
27+
"""
28+
return "\n".join(circuit_to_qasm3_lines(circuit))
29+
30+
31+
def circuit_to_qasm3_lines(circuit: Circuit) -> Iterator[str]:
32+
"""Export circuit instructions to line-by-line OpenQASM 3.0 representation.
33+
34+
Returns
35+
-------
36+
Iterator[str]
37+
The OpenQASM 3.0 lines that represent the circuit.
38+
"""
39+
yield "OPENQASM 3;"
40+
yield 'include "stdgates.inc";'
41+
yield f"qubit[{circuit.width}] q;"
42+
if any(instr.kind == InstructionKind.M for instr in circuit.instruction):
43+
yield f"bit[{circuit.width}] b;"
44+
for instr in circuit.instruction:
45+
yield f"{instruction_to_qasm3(instr)};"
46+
47+
48+
def instruction_to_qasm3(instruction: Instruction) -> str:
49+
"""Get the qasm3 representation of a single circuit instruction."""
50+
if instruction.kind == InstructionKind.M:
51+
return f"b[{instruction.target}] = measure q[{instruction.target}]"
52+
# Use of `==` here for mypy
53+
if (
54+
instruction.kind == InstructionKind.RX # noqa: PLR1714
55+
or instruction.kind == InstructionKind.RY
56+
or instruction.kind == InstructionKind.RZ
57+
):
58+
if not isinstance(instruction.angle, float):
59+
raise ValueError("QASM export of symbolic pattern is not supported")
60+
rad_over_pi = instruction.angle / pi
61+
tol = 1e-9
62+
frac = Fraction(rad_over_pi).limit_denominator(1000)
63+
if abs(rad_over_pi - float(frac)) > tol:
64+
angle = f"{rad_over_pi}*pi"
65+
num, den = frac.numerator, frac.denominator
66+
sign = "-" if num < 0 else ""
67+
num = abs(num)
68+
if den == 1:
69+
angle = f"{sign}pi" if num == 1 else f"{sign}{num}*pi"
70+
else:
71+
angle = f"{sign}pi/{den}" if num == 1 else f"{sign}{num}*pi/{den}"
72+
return f"{instruction.kind.name.lower()}({angle}) q[{instruction.target}]"
73+
74+
# Use of `==` here for mypy
75+
if (
76+
instruction.kind == InstructionKind.H # noqa: PLR1714
77+
or instruction.kind == InstructionKind.I
78+
or instruction.kind == InstructionKind.S
79+
or instruction.kind == InstructionKind.X
80+
or instruction.kind == InstructionKind.Y
81+
or instruction.kind == InstructionKind.Z
82+
):
83+
return f"{instruction.kind.name.lower()} q[{instruction.target}]"
84+
if instruction.kind == InstructionKind.CNOT:
85+
return f"cx q[{instruction.control}], q[{instruction.target}]"
86+
if instruction.kind == InstructionKind.SWAP:
87+
return f"swap q[{instruction.targets[0]}], q[{instruction.targets[1]}]"
88+
if instruction.kind == InstructionKind.RZZ:
89+
return f"rzz q[{instruction.control}], q[{instruction.target}]"
90+
if instruction.kind == InstructionKind.CCX:
91+
return f"ccx q[{instruction.controls[0]}], q[{instruction.controls[1]}], q[{instruction.target}]"
92+
# Use of `==` here for mypy
93+
if instruction.kind == InstructionKind._XC or instruction.kind == InstructionKind._ZC: # noqa: PLR1714
94+
raise ValueError("Internal instruction should not appear")
95+
assert_never(instruction.kind)

tests/test_qasm3_exporter.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
"""Test exporter to OpenQASM3."""
2+
3+
from __future__ import annotations
4+
5+
from typing import TYPE_CHECKING
6+
7+
import pytest
8+
from numpy.random import PCG64, Generator
9+
10+
from graphix.qasm3_exporter import circuit_to_qasm3
11+
from graphix.random_objects import rand_circuit
12+
13+
try:
14+
from graphix_qasm_parser import OpenQASMParser
15+
except ImportError:
16+
pytestmark = pytest.mark.skip(reason="graphix-qasm-parser not installed")
17+
18+
if TYPE_CHECKING:
19+
import sys
20+
21+
# We skip type-checking the case where there is no
22+
# graphix-qasm-parser, since pyright cannot figure out that
23+
# tests are skipped in this case.
24+
sys.exit(1)
25+
26+
27+
@pytest.mark.parametrize("jumps", range(1, 11))
28+
def test_circuit_to_qasm3(fx_bg: PCG64, jumps: int) -> None:
29+
rng = Generator(fx_bg.jumped(jumps))
30+
nqubits = 5
31+
depth = 4
32+
circuit = rand_circuit(nqubits, depth, rng)
33+
qasm = circuit_to_qasm3(circuit)
34+
parser = OpenQASMParser()
35+
parsed_circuit = parser.parse_str(qasm)
36+
assert parsed_circuit.instruction == circuit.instruction

0 commit comments

Comments
 (0)