microsoft/qdk
Publicmirrored fromhttps://github.com/microsoft/qdkAvailable
source/pip/qsharp/openqasm/_import.py
64lines · modecode
| 1 | # Copyright (c) Microsoft Corporation. |
| 2 | # Licensed under the MIT License. |
| 3 | |
| 4 | from time import monotonic |
| 5 | from typing import Any, Dict, Optional |
| 6 | |
| 7 | from ._ipython import display_or_print |
| 8 | from .._fs import read_file, list_directory, resolve |
| 9 | from .._http import fetch_github |
| 10 | from .._qsharp import ( |
| 11 | get_interpreter, |
| 12 | ipython_helper, |
| 13 | ) |
| 14 | from .. import telemetry_events |
| 15 | |
| 16 | |
| 17 | def import_openqasm( |
| 18 | source: str, |
| 19 | **kwargs: Optional[Dict[str, Any]], |
| 20 | ) -> Any: |
| 21 | """ |
| 22 | Imports OpenQASM source code into the active Q# interpreter. |
| 23 | |
| 24 | Args: |
| 25 | source (str): An OpenQASM program or fragment. |
| 26 | **kwargs: Additional keyword arguments to pass to the execution. |
| 27 | - name (str): The name of the program. This is used as the entry point for the program. |
| 28 | - search_path (Optional[str]): The optional search path for resolving file references. |
| 29 | - output_semantics (OutputSemantics, optional): The output semantics for the compilation. |
| 30 | - program_type (ProgramType, optional): The type of program compilation to perform. Defaults to `ProgramType.Operation`. |
| 31 | |
| 32 | Returns: |
| 33 | value: The value returned by the last statement in the source code. |
| 34 | |
| 35 | Raises: |
| 36 | QasmError: If there is an error generating, parsing, or analyzing the OpenQASM source. |
| 37 | QSharpError: If there is an error compiling the program. |
| 38 | """ |
| 39 | |
| 40 | ipython_helper() |
| 41 | |
| 42 | telemetry_events.on_import_qasm() |
| 43 | start_time = monotonic() |
| 44 | |
| 45 | # remove any entries from kwargs with a None key or None value |
| 46 | kwargs = {k: v for k, v in kwargs.items() if k is not None and v is not None} |
| 47 | |
| 48 | if "search_path" not in kwargs: |
| 49 | kwargs["search_path"] = "." |
| 50 | |
| 51 | res = get_interpreter().import_qasm( |
| 52 | source, |
| 53 | display_or_print, |
| 54 | read_file, |
| 55 | list_directory, |
| 56 | resolve, |
| 57 | fetch_github, |
| 58 | **kwargs, |
| 59 | ) |
| 60 | |
| 61 | durationMs = (monotonic() - start_time) * 1000 |
| 62 | telemetry_events.on_import_qasm_end(durationMs) |
| 63 | |
| 64 | return res |
| 65 | |