Skip to content

Commit

Permalink
Added get_qasm support for ControlledGates
Browse files Browse the repository at this point in the history
  • Loading branch information
mtweiden committed Jan 17, 2024
1 parent 1ee59f1 commit 371adfa
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
18 changes: 18 additions & 0 deletions bqskit/ir/gates/composed/controlled.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

from bqskit.ir.gate import Gate
from bqskit.ir.gates.composedgate import ComposedGate
from bqskit.ir.location import CircuitLocation
from bqskit.qis.unitary.differentiable import DifferentiableUnitary
from bqskit.qis.unitary.unitary import RealVector
from bqskit.qis.unitary.unitarymatrix import UnitaryMatrix
Expand Down Expand Up @@ -286,6 +287,23 @@ def __init__(
ctrl_U = np.kron(self.ctrl, U) + self.ihalf
self._utry = UnitaryMatrix(ctrl_U, self.radixes)

def get_qasm(self, params: RealVector, location: CircuitLocation) -> str:
"""
Override default `Gate.get_qasm` method.
If the target gate is a standard gate, this function will output
qasm in the form 'c+<gate_qasm>'. Otherwise an error will be raised.
Raises:
AttributeError: If the target gate is non-standard.
"""
qasm_name = 'c' * self.num_controls + self.gate.qasm_name
return '{}({}) q[{}];\n'.format(
qasm_name,
', '.join([str(p) for p in params]),
'], q['.join([str(q) for q in location]),
).replace('()', '')

def get_unitary(self, params: RealVector = []) -> UnitaryMatrix:
"""Return the unitary for this gate, see :class:`Unitary` for more."""
if hasattr(self, '_utry'):
Expand Down
33 changes: 33 additions & 0 deletions tests/ir/lang/test_controlled_qasm.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
from __future__ import annotations

from bqskit.ir.lang.qasm2 import OPENQASM2Language


class TestControlledQASM:
def test_cu1(self) -> None:

input_qasm = (
'OPENQASM 2.0;\n'
'include "qelib1.inc";\n'
'qreg q[2];\n'
'cu1(3.1415) q[0], q[1];\n'
)
circuit = OPENQASM2Language().decode(input_qasm)

output_qasm = circuit.to('qasm')

assert input_qasm == output_qasm

def test_cu3(self) -> None:

input_qasm = (
'OPENQASM 2.0;\n'
'include "qelib1.inc";\n'
'qreg q[2];\n'
'cu3(3.1415, 0.0, -4.0) q[0], q[1];\n'
)
circuit = OPENQASM2Language().decode(input_qasm)

output_qasm = circuit.to('qasm')

assert input_qasm == output_qasm

0 comments on commit 371adfa

Please sign in to comment.