Skip to content

Commit 6896a09

Browse files
committed
update Braket warnings handling
1 parent b4f9701 commit 6896a09

File tree

1 file changed

+23
-18
lines changed

1 file changed

+23
-18
lines changed

mpqp/qasm/qasm_to_braket.py

+23-18
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
"""File regrouping all features for translating QASM code to Amazon Braket objects."""
22

3+
import io
34
import warnings
4-
from logging import Logger, getLogger
5+
from logging import StreamHandler, getLogger
56

67
from braket.circuits import Circuit
78
from braket.ir.openqasm import Program
@@ -56,28 +57,32 @@ def qasm3_to_braket_Circuit(qasm3_str: str) -> Circuit:
5657
# we remove any include of stdgates.inc and replace it with custom include
5758
qasm3_str = qasm3_str.replace("stdgates.inc", "braket_custom_include.inc")
5859

59-
after_stdgates_included = open_qasm_hard_includes(qasm3_str, set())
60-
# NOTE : gphase is a already used in Braket and thus cannot be redefined as a native gate in OpenQASM.
60+
try:
61+
after_stdgates_included = open_qasm_hard_includes(qasm3_str, set())
62+
except Exception as e:
63+
warning_message = (
64+
f"An error occurred while processing the OpenQASM code with Braket: {e}"
65+
)
66+
warnings.warn(warning_message, UnsupportedBraketFeaturesWarning)
67+
return None
68+
69+
# NOTE: gphase is already used in Braket and thus cannot be redefined as a native gate in OpenQASM.
6170
# We used ggphase instead
62-
warning_message = (
63-
"This program uses OpenQASM language features that may not be "
64-
"supported on QPUs or on-demand simulators."
65-
)
71+
if "U(" in after_stdgates_included or "gphase(" in after_stdgates_included:
72+
# Issue a warning only if not already issued
73+
warning_message = "This program uses OpenQASM language features that may not be supported on QPUs or on-demand simulators."
74+
warnings.warn(warning_message, UnsupportedBraketFeaturesWarning)
6675

67-
# handle the logger output
68-
# capture their logger
76+
# capture the Braket logger
6977
braket_logger = getLogger()
70-
# add logger handler
7178

72-
logger_out = []
73-
circuit = Circuit.from_ir(after_stdgates_included)
79+
logger_output_stream = io.StringIO()
80+
stream_handler = StreamHandler(logger_output_stream)
81+
braket_logger.addHandler(stream_handler)
7482

75-
if warning_message in logger_out:
76-
warnings.warn("\n" + warning_message, UnsupportedBraketFeaturesWarning)
77-
del logger_out[logger_out.index(warning_message)]
78-
# remove logger handler
83+
circuit = Circuit.from_ir(after_stdgates_included)
7984

80-
for line in logger_out:
81-
braket_logger.warning(line)
85+
# remove the logger handler
86+
braket_logger.removeHandler(stream_handler)
8287

8388
return circuit

0 commit comments

Comments
 (0)