microsoft/qdk

Public

mirrored fromhttps://github.com/microsoft/qdkAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v1.18.0

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

source/pip/qsharp/openqasm/_estimate.py

102lines · modecode

1# Copyright (c) Microsoft Corporation.
2# Licensed under the MIT License.
3
4import json
5from time import monotonic
6from typing import Any, Callable, Dict, List, Optional, Union
7from .._fs import read_file, list_directory, resolve
8from .._http import fetch_github
9from .._native import ( # type: ignore
10 resource_estimate_qasm_program,
11)
12from ..estimator import EstimatorParams, EstimatorResult
13
14from .._qsharp import (
15 get_interpreter,
16 ipython_helper,
17)
18from .. import telemetry_events
19
20
21def estimate(
22 source: Union[str, Callable],
23 params: Optional[Union[Dict[str, Any], List, EstimatorParams]] = None,
24 *args,
25 **kwargs: Optional[Dict[str, Any]],
26) -> EstimatorResult:
27 """
28 Estimates the resource requirements for executing OpenQASM source code.
29 Either a full program or a callable with arguments must be provided.
30
31 Args:
32 source (str): An OpenQASM program. Alternatively, a callable can be provided,
33 which must be an already imported global callable.
34 params: The parameters to configure estimation.
35 callable: The callable to estimate resources for, if no entry expression is provided.
36 *args: The arguments to pass to the callable, if one is provided.
37 **kwargs: Additional keyword arguments to pass to the execution.
38 - name (str): The name of the circuit. This is used as the entry point for the program. Defaults to 'program'.
39 - search_path (str): The optional search path for resolving imports.
40
41 Returns:
42 EstimatorResult: The estimated resources.
43
44 Raises:
45 QasmError: If there is an error generating, parsing, or analyzing the OpenQASM source.
46 QSharpError: If there is an error compiling the program.
47 """
48
49 ipython_helper()
50
51 def _coerce_estimator_params(
52 params: Optional[Union[Dict[str, Any], List, EstimatorParams]] = None,
53 ) -> List[Dict[str, Any]]:
54 if params is None:
55 params = [{}]
56 elif isinstance(params, EstimatorParams):
57 if params.has_items:
58 params = params.as_dict()["items"]
59 else:
60 params = [params.as_dict()]
61 elif isinstance(params, dict):
62 params = [params]
63 return params
64
65 params = _coerce_estimator_params(params)
66 param_str = json.dumps(params)
67 telemetry_events.on_estimate_qasm()
68 start = monotonic()
69 if isinstance(source, Callable) and hasattr(source, "__global_callable"):
70 if len(args) == 1:
71 args = args[0]
72 elif len(args) == 0:
73 args = None
74 res_str = get_interpreter().estimate(
75 param_str, callable=source.__global_callable, args=args
76 )
77 else:
78 # remove any entries from kwargs with a None key or None value
79 kwargs = {k: v for k, v in kwargs.items() if k is not None and v is not None}
80
81 if "search_path" not in kwargs:
82 kwargs["search_path"] = "."
83
84 res_str = resource_estimate_qasm_program(
85 source,
86 param_str,
87 read_file,
88 list_directory,
89 resolve,
90 fetch_github,
91 **kwargs,
92 )
93 res = json.loads(res_str)
94
95 try:
96 qubits = res[0]["logicalCounts"]["numQubits"]
97 except (KeyError, IndexError):
98 qubits = "unknown"
99
100 durationMs = (monotonic() - start) * 1000
101 telemetry_events.on_estimate_qasm_end(durationMs, qubits)
102 return EstimatorResult(res)