|
1 | 1 | """File regrouping all features for translating QASM code to Amazon Braket objects."""
|
2 | 2 |
|
| 3 | +import io |
3 | 4 | import warnings
|
4 |
| -from logging import Logger, getLogger |
| 5 | +from logging import StreamHandler, getLogger |
5 | 6 |
|
6 | 7 | from braket.circuits import Circuit
|
7 | 8 | from braket.ir.openqasm import Program
|
@@ -56,28 +57,32 @@ def qasm3_to_braket_Circuit(qasm3_str: str) -> Circuit:
|
56 | 57 | # we remove any include of stdgates.inc and replace it with custom include
|
57 | 58 | qasm3_str = qasm3_str.replace("stdgates.inc", "braket_custom_include.inc")
|
58 | 59 |
|
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. |
61 | 70 | # 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) |
66 | 75 |
|
67 |
| - # handle the logger output |
68 |
| - # capture their logger |
| 76 | + # capture the Braket logger |
69 | 77 | braket_logger = getLogger()
|
70 |
| - # add logger handler |
71 | 78 |
|
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) |
74 | 82 |
|
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) |
79 | 84 |
|
80 |
| - for line in logger_out: |
81 |
| - braket_logger.warning(line) |
| 85 | + # remove the logger handler |
| 86 | + braket_logger.removeHandler(stream_handler) |
82 | 87 |
|
83 | 88 | return circuit
|
0 commit comments