microsoft/qdk

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v1.23.0

Branches

Tags

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

Clone

HTTPS

Download ZIP

source/pip/qsharp/openqasm/_estimate.py

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