# Copyright 2025 qBraid
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Module for converting Braket circuits to/from OpenQASM 3
"""
from __future__ import annotations
from typing import TYPE_CHECKING
import pyqasm
from qbraid_core._import import LazyLoader
from qbraid.passes.qasm.compat import (
convert_qasm_pi_to_decimal,
remove_stdgates_include,
replace_gate_names,
)
from qbraid.programs.exceptions import QasmError
from qbraid.transpiler.annotations import weight
braket_circuits = LazyLoader("braket_circuits", globals(), "braket.circuits")
braket_openqasm = LazyLoader("braket_openqasm", globals(), "braket.ir.openqasm")
if TYPE_CHECKING:
import braket.circuits
from qbraid.programs.typer import Qasm3StringType
def transform_notation(qasm3: str) -> str:
"""
Process an OpenQASM 3 program that was generated by
an external tool to make it compatible with Amazon Braket.
"""
replacements = {
"cx": "cnot",
"sdg": "si",
"tdg": "ti",
"sx": "v",
"id": "i",
"sxdg": "vi",
"p": "phaseshift",
"cp": "cphaseshift",
}
qasm3 = remove_stdgates_include(qasm3)
qasm3 = replace_gate_names(qasm3, replacements)
qasm3 = convert_qasm_pi_to_decimal(qasm3)
return qasm3
[docs]
@weight(1)
def qasm3_to_braket(qasm: Qasm3StringType) -> braket.circuits.Circuit:
"""Converts an OpenQASM 3.0 string to a ``braket.circuits.Circuit``.
Args:
qasm: OpenQASM 3 string
Returns:
The Amazon Braket circuit equivalent to the input OpenQASM 3.0 string
Raises:
ProgramConversionError: If qasm to braket conversion fails
"""
module = pyqasm.loads(qasm)
module.unroll()
qasm = pyqasm.dumps(module)
qasm = transform_notation(qasm)
try:
program = braket_openqasm.Program(source=qasm)
return braket_circuits.Circuit.from_ir(source=program.source, inputs=program.inputs)
except Exception as err:
raise QasmError("Error converting qasm3 string to braket circuit") from err