# 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 defining Qiskit OpenQASM conversions
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from qbraid_core._import import LazyLoader
from qbraid.passes.qasm.compat import add_stdgates_include, insert_gate_def, replace_gate_names
from qbraid.transpiler.annotations import weight
qiskit_qasm3 = LazyLoader("qiskit_qasm3", globals(), "qiskit.qasm3")
if TYPE_CHECKING:
import qiskit as qiskit_
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 Qiskit.
"""
replacements = {
"cnot": "cx",
"si": "sdg",
"ti": "tdg",
"v": "sx",
"vi": "sxdg",
"phaseshift": "p",
"cphaseshift": "cp",
}
qasm3 = replace_gate_names(qasm3, replacements)
qasm3 = add_stdgates_include(qasm3)
qasm3 = insert_gate_def(qasm3, "iswap")
qasm3 = insert_gate_def(qasm3, "sxdg")
return qasm3
[docs]
@weight(1)
def qasm3_to_qiskit(qasm: Qasm3StringType) -> qiskit_.QuantumCircuit:
"""Convert QASM 3.0 string to a Qiskit QuantumCircuit representation.
Args:
qasm (str): A string in QASM 3.0 format.
Returns:
qiskit.QuantumCircuit: A QuantumCircuit object representing the input QASM 3.0 string.
"""
try:
return qiskit_qasm3.loads(qasm)
except qiskit_qasm3.QASM3ImporterError:
pass
qasm = transform_notation(qasm)
return qiskit_qasm3.loads(qasm)