Skip to content

Commit 371adfa

Browse files
committed
Added get_qasm support for ControlledGates
1 parent 1ee59f1 commit 371adfa

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

bqskit/ir/gates/composed/controlled.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99

1010
from bqskit.ir.gate import Gate
1111
from bqskit.ir.gates.composedgate import ComposedGate
12+
from bqskit.ir.location import CircuitLocation
1213
from bqskit.qis.unitary.differentiable import DifferentiableUnitary
1314
from bqskit.qis.unitary.unitary import RealVector
1415
from bqskit.qis.unitary.unitarymatrix import UnitaryMatrix
@@ -286,6 +287,23 @@ def __init__(
286287
ctrl_U = np.kron(self.ctrl, U) + self.ihalf
287288
self._utry = UnitaryMatrix(ctrl_U, self.radixes)
288289

290+
def get_qasm(self, params: RealVector, location: CircuitLocation) -> str:
291+
"""
292+
Override default `Gate.get_qasm` method.
293+
294+
If the target gate is a standard gate, this function will output
295+
qasm in the form 'c+<gate_qasm>'. Otherwise an error will be raised.
296+
297+
Raises:
298+
AttributeError: If the target gate is non-standard.
299+
"""
300+
qasm_name = 'c' * self.num_controls + self.gate.qasm_name
301+
return '{}({}) q[{}];\n'.format(
302+
qasm_name,
303+
', '.join([str(p) for p in params]),
304+
'], q['.join([str(q) for q in location]),
305+
).replace('()', '')
306+
289307
def get_unitary(self, params: RealVector = []) -> UnitaryMatrix:
290308
"""Return the unitary for this gate, see :class:`Unitary` for more."""
291309
if hasattr(self, '_utry'):

tests/ir/lang/test_controlled_qasm.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
from __future__ import annotations
2+
3+
from bqskit.ir.lang.qasm2 import OPENQASM2Language
4+
5+
6+
class TestControlledQASM:
7+
def test_cu1(self) -> None:
8+
9+
input_qasm = (
10+
'OPENQASM 2.0;\n'
11+
'include "qelib1.inc";\n'
12+
'qreg q[2];\n'
13+
'cu1(3.1415) q[0], q[1];\n'
14+
)
15+
circuit = OPENQASM2Language().decode(input_qasm)
16+
17+
output_qasm = circuit.to('qasm')
18+
19+
assert input_qasm == output_qasm
20+
21+
def test_cu3(self) -> None:
22+
23+
input_qasm = (
24+
'OPENQASM 2.0;\n'
25+
'include "qelib1.inc";\n'
26+
'qreg q[2];\n'
27+
'cu3(3.1415, 0.0, -4.0) q[0], q[1];\n'
28+
)
29+
circuit = OPENQASM2Language().decode(input_qasm)
30+
31+
output_qasm = circuit.to('qasm')
32+
33+
assert input_qasm == output_qasm

0 commit comments

Comments
 (0)