microsoft/qdk
Publicmirrored from https://github.com/microsoft/qdkAvailable
source/pip/qsharp/openqasm/_estimate.py
114lines · modecode
| 1 | # Copyright (c) Microsoft Corporation. |
| 2 | # Licensed under the MIT License. |
| 3 | |
| 4 | import json |
| 5 | import warnings |
| 6 | from time import monotonic |
| 7 | from typing import Any, Callable, Dict, List, Optional, Union, cast |
| 8 | from .._fs import read_file, list_directory, resolve |
| 9 | from .._http import fetch_github |
| 10 | from .._native import ( # type: ignore |
| 11 | resource_estimate_qasm_program, |
| 12 | ) |
| 13 | from ..estimator import EstimatorParams, EstimatorResult |
| 14 | |
| 15 | from .._qsharp import ( |
| 16 | get_interpreter, |
| 17 | ipython_helper, |
| 18 | python_args_to_interpreter_args, |
| 19 | ) |
| 20 | from .. import telemetry_events |
| 21 | |
| 22 | |
| 23 | def estimate( |
| 24 | source: Union[str, Callable], |
| 25 | params: Optional[Union[Dict[str, Any], List, EstimatorParams]] = None, |
| 26 | *args: Any, |
| 27 | **kwargs: Any, |
| 28 | ) -> EstimatorResult: |
| 29 | """ |
| 30 | Estimates the resource requirements for executing OpenQASM source code. |
| 31 | Either a full program or a callable with arguments must be provided. |
| 32 | |
| 33 | :param source: An OpenQASM program. Alternatively, a callable can be provided, |
| 34 | which must be an already imported global callable. |
| 35 | :type source: str or Callable |
| 36 | :param params: The parameters to configure estimation. |
| 37 | :type params: Dict, List, or EstimatorParams |
| 38 | :param *args: The arguments to pass to the callable, if one is provided. |
| 39 | :param **kwargs: Additional keyword arguments. Common options: |
| 40 | |
| 41 | - ``name`` (str): The name of the circuit. This is used as the entry point for the program. |
| 42 | Defaults to ``'program'``. |
| 43 | - ``search_path`` (str): The optional search path for resolving imports. |
| 44 | :return: The estimated resources. |
| 45 | :rtype: EstimatorResult |
| 46 | :raises ValueError: If ``source`` is neither a string nor a callable with a |
| 47 | ``__global_callable`` attribute. |
| 48 | :raises QasmError: If there is an error generating, parsing, or analyzing the OpenQASM source. |
| 49 | :raises QSharpError: If there is an error compiling the program. |
| 50 | """ |
| 51 | |
| 52 | warnings.warn( |
| 53 | "This version of QRE is deprecated and will be removed in a future release. Please use the new version of QRE in qdk.qre. Refer to aka.ms/qdk.QREv3 for more information.", |
| 54 | DeprecationWarning, |
| 55 | stacklevel=2, |
| 56 | ) |
| 57 | |
| 58 | ipython_helper() |
| 59 | |
| 60 | def _coerce_estimator_params( |
| 61 | params: Optional[ |
| 62 | Union[Dict[str, Any], List[Dict[str, Any]], EstimatorParams] |
| 63 | ] = None, |
| 64 | ) -> List[Dict[str, Any]]: |
| 65 | if params is None: |
| 66 | return [{}] |
| 67 | elif isinstance(params, EstimatorParams): |
| 68 | if params.has_items: |
| 69 | return cast(List[Dict[str, Any]], params.as_dict()["items"]) |
| 70 | else: |
| 71 | return [params.as_dict()] |
| 72 | elif isinstance(params, dict): |
| 73 | return [params] |
| 74 | return params |
| 75 | |
| 76 | params = _coerce_estimator_params(params) |
| 77 | param_str = json.dumps(params) |
| 78 | telemetry_events.on_estimate_qasm() |
| 79 | start = monotonic() |
| 80 | if isinstance(source, Callable) and hasattr(source, "__global_callable"): |
| 81 | args = python_args_to_interpreter_args(args) |
| 82 | res_str = get_interpreter().estimate( |
| 83 | param_str, entry_expr=None, callable=source.__global_callable, args=args |
| 84 | ) |
| 85 | elif isinstance(source, str): |
| 86 | # remove any entries from kwargs with a None key or None value |
| 87 | kwargs = {k: v for k, v in kwargs.items() if k is not None and v is not None} |
| 88 | |
| 89 | if "search_path" not in kwargs: |
| 90 | kwargs["search_path"] = "." |
| 91 | |
| 92 | res_str = resource_estimate_qasm_program( |
| 93 | source, |
| 94 | param_str, |
| 95 | read_file, |
| 96 | list_directory, |
| 97 | resolve, |
| 98 | fetch_github, |
| 99 | **kwargs, |
| 100 | ) |
| 101 | else: |
| 102 | raise ValueError( |
| 103 | "source must be a string or a callable with __global_callable attribute" |
| 104 | ) |
| 105 | res = json.loads(res_str) |
| 106 | |
| 107 | try: |
| 108 | qubits = res[0]["logicalCounts"]["numQubits"] |
| 109 | except (KeyError, IndexError): |
| 110 | qubits = "unknown" |
| 111 | |
| 112 | durationMs = (monotonic() - start) * 1000 |
| 113 | telemetry_events.on_estimate_qasm_end(durationMs, qubits) |
| 114 | return EstimatorResult(res) |
| 115 | |