microsoft/qdk
Publicmirrored from https://github.com/microsoft/qdkAvailable
source/pip/qsharp/openqasm/_circuit.py
68lines · modecode
| 1 | # Copyright (c) Microsoft Corporation. |
| 2 | # Licensed under the MIT License. |
| 3 | |
| 4 | from time import monotonic |
| 5 | from typing import Any, Callable, Dict, Optional, Union |
| 6 | from .._fs import read_file, list_directory, resolve |
| 7 | from .._http import fetch_github |
| 8 | from .._native import circuit_qasm_program # type: ignore |
| 9 | from .._qsharp import ( |
| 10 | get_interpreter, |
| 11 | ipython_helper, |
| 12 | Circuit, |
| 13 | python_args_to_interpreter_args, |
| 14 | ) |
| 15 | from .. import telemetry_events |
| 16 | |
| 17 | |
| 18 | def circuit( |
| 19 | source: Optional[Union[str, Callable]] = None, |
| 20 | *args, |
| 21 | **kwargs: Optional[Dict[str, Any]], |
| 22 | ) -> Circuit: |
| 23 | """ |
| 24 | Synthesizes a circuit for an OpenQASM program. Either a program string or |
| 25 | an operation must be provided. |
| 26 | |
| 27 | Args: |
| 28 | source (str): An OpenQASM program. Alternatively, a callable can be provided, |
| 29 | which must be an already imported global callable. |
| 30 | *args: The arguments to pass to the callable, if one is provided. |
| 31 | **kwargs: Additional keyword arguments to pass to the execution. |
| 32 | - name (str): The name of the program. This is used as the entry point for the program. |
| 33 | - search_path (Optional[str]): The optional search path for resolving file references. |
| 34 | Returns: |
| 35 | Circuit: The synthesized circuit. |
| 36 | |
| 37 | Raises: |
| 38 | QasmError: If there is an error generating, parsing, or analyzing the OpenQASM source. |
| 39 | QSharpError: If there is an error evaluating the program. |
| 40 | QSharpError: If there is an error synthesizing the circuit. |
| 41 | """ |
| 42 | |
| 43 | ipython_helper() |
| 44 | start = monotonic() |
| 45 | telemetry_events.on_circuit_qasm() |
| 46 | if isinstance(source, Callable) and hasattr(source, "__global_callable"): |
| 47 | args = python_args_to_interpreter_args(args) |
| 48 | res = get_interpreter().circuit(callable=source.__global_callable, args=args) |
| 49 | else: |
| 50 | # remove any entries from kwargs with a None key or None value |
| 51 | kwargs = {k: v for k, v in kwargs.items() if k is not None and v is not None} |
| 52 | |
| 53 | if "search_path" not in kwargs: |
| 54 | kwargs["search_path"] = "." |
| 55 | |
| 56 | res = circuit_qasm_program( |
| 57 | source, |
| 58 | read_file, |
| 59 | list_directory, |
| 60 | resolve, |
| 61 | fetch_github, |
| 62 | **kwargs, |
| 63 | ) |
| 64 | |
| 65 | durationMs = (monotonic() - start) * 1000 |
| 66 | telemetry_events.on_circuit_qasm_end(durationMs) |
| 67 | |
| 68 | return res |
| 69 | |