microsoft/qdk
Publicmirrored fromhttps://github.com/microsoft/qdkAvailable
source/pip/qsharp/openqasm/_circuit.py
66lines · 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 get_interpreter, ipython_helper, Circuit |
| 10 | from .. import telemetry_events |
| 11 | |
| 12 | |
| 13 | def circuit( |
| 14 | source: Optional[Union[str, Callable]] = None, |
| 15 | *args, |
| 16 | **kwargs: Optional[Dict[str, Any]], |
| 17 | ) -> Circuit: |
| 18 | """ |
| 19 | Synthesizes a circuit for an OpenQASM program. Either a program string or |
| 20 | an operation must be provided. |
| 21 | |
| 22 | Args: |
| 23 | source (str): An OpenQASM program. Alternatively, a callable can be provided, |
| 24 | which must be an already imported global callable. |
| 25 | *args: The arguments to pass to the callable, if one is provided. |
| 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 | Returns: |
| 30 | Circuit: The synthesized circuit. |
| 31 | |
| 32 | Raises: |
| 33 | QasmError: If there is an error generating, parsing, or analyzing the OpenQASM source. |
| 34 | QSharpError: If there is an error evaluating the program. |
| 35 | QSharpError: If there is an error synthesizing the circuit. |
| 36 | """ |
| 37 | |
| 38 | ipython_helper() |
| 39 | start = monotonic() |
| 40 | telemetry_events.on_circuit_qasm() |
| 41 | if isinstance(source, Callable) and hasattr(source, "__global_callable"): |
| 42 | if len(args) == 1: |
| 43 | args = args[0] |
| 44 | elif len(args) == 0: |
| 45 | args = None |
| 46 | res = get_interpreter().circuit(callable=source.__global_callable, args=args) |
| 47 | else: |
| 48 | # remove any entries from kwargs with a None key or None value |
| 49 | kwargs = {k: v for k, v in kwargs.items() if k is not None and v is not None} |
| 50 | |
| 51 | if "search_path" not in kwargs: |
| 52 | kwargs["search_path"] = "." |
| 53 | |
| 54 | res = circuit_qasm_program( |
| 55 | source, |
| 56 | read_file, |
| 57 | list_directory, |
| 58 | resolve, |
| 59 | fetch_github, |
| 60 | **kwargs, |
| 61 | ) |
| 62 | |
| 63 | durationMs = (monotonic() - start) * 1000 |
| 64 | telemetry_events.on_circuit_qasm_end(durationMs) |
| 65 | |
| 66 | return res |
| 67 | |