qsharp 1.6.3.dev0__cp38-abi3-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,95 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT License.
3
+
4
+ // This file provides CodeMirror syntax highlighting for Q# magic cells
5
+ // in classic Jupyter Notebooks. It does nothing in other (Jupyter Notebook 7,
6
+ // VS Code, Azure Notebooks, etc.) environments.
7
+
8
+ // Detect the prerequisites and do nothing if they don't exist.
9
+ if (window.require && window.CodeMirror && window.Jupyter) {
10
+ // The simple mode plugin for CodeMirror is not loaded by default, so require it.
11
+ window.require(["codemirror/addon/mode/simple"], function defineMode() {
12
+ let rules = [
13
+ {
14
+ token: "comment",
15
+ regex: /(\/\/).*/,
16
+ beginWord: false,
17
+ },
18
+ {
19
+ token: "string",
20
+ regex: String.raw`^\"(?:[^\"\\]|\\[\s\S])*(?:\"|$)`,
21
+ beginWord: false,
22
+ },
23
+ {
24
+ token: "keyword",
25
+ regex: String.raw`(namespace|open|as|operation|function|body|adjoint|newtype|controlled|internal)\b`,
26
+ beginWord: true,
27
+ },
28
+ {
29
+ token: "keyword",
30
+ regex: String.raw`(if|elif|else|repeat|until|fixup|for|in|return|fail|within|apply)\b`,
31
+ beginWord: true,
32
+ },
33
+ {
34
+ token: "keyword",
35
+ regex: String.raw`(Adjoint|Controlled|Adj|Ctl|is|self|auto|distribute|invert|intrinsic)\b`,
36
+ beginWord: true,
37
+ },
38
+ {
39
+ token: "keyword",
40
+ regex: String.raw`(let|set|use|borrow|mutable)\b`,
41
+ beginWord: true,
42
+ },
43
+ {
44
+ token: "operatorKeyword",
45
+ regex: String.raw`(not|and|or)\b|(w/)`,
46
+ beginWord: true,
47
+ },
48
+ {
49
+ token: "operatorKeyword",
50
+ regex: String.raw`(=)|(!)|(<)|(>)|(\+)|(-)|(\*)|(/)|(\^)|(%)|(\|)|(&&&)|(~~~)|(\.\.\.)|(\.\.)|(\?)`,
51
+ beginWord: false,
52
+ },
53
+ {
54
+ token: "meta",
55
+ regex: String.raw`(Int|BigInt|Double|Bool|Qubit|Pauli|Result|Range|String|Unit)\b`,
56
+ beginWord: true,
57
+ },
58
+ {
59
+ token: "atom",
60
+ regex: String.raw`(true|false|Pauli(I|X|Y|Z)|One|Zero)\b`,
61
+ beginWord: true,
62
+ },
63
+ ];
64
+ let simpleRules = [];
65
+ for (let rule of rules) {
66
+ simpleRules.push({
67
+ token: rule.token,
68
+ regex: new RegExp(rule.regex, "g"),
69
+ sol: rule.beginWord,
70
+ });
71
+ if (rule.beginWord) {
72
+ // Need an additional rule due to the fact that CodeMirror simple mode doesn't work with ^ token
73
+ simpleRules.push({
74
+ token: rule.token,
75
+ regex: new RegExp(String.raw`\W` + rule.regex, "g"),
76
+ sol: false,
77
+ });
78
+ }
79
+ }
80
+
81
+ // Register the mode defined above with CodeMirror
82
+ window.CodeMirror.defineSimpleMode("qsharp", { start: simpleRules });
83
+ window.CodeMirror.defineMIME("text/x-qsharp", "qsharp");
84
+
85
+ // Tell Jupyter to associate %%qsharp magic cells with the qsharp mode
86
+ window.Jupyter.CodeCell.options_default.highlight_modes["qsharp"] = {
87
+ reg: [/^%%qsharp/],
88
+ };
89
+
90
+ // Force re-highlighting of all cells the first time this code runs
91
+ for (const cell of window.Jupyter.notebook.get_cells()) {
92
+ cell.auto_highlight();
93
+ }
94
+ });
95
+ }
qsharp/__init__.py ADDED
@@ -0,0 +1,49 @@
1
+ # Copyright (c) Microsoft Corporation.
2
+ # Licensed under the MIT License.
3
+
4
+ from ._qsharp import (
5
+ init,
6
+ eval,
7
+ run,
8
+ compile,
9
+ circuit,
10
+ estimate,
11
+ set_quantum_seed,
12
+ set_classical_seed,
13
+ dump_machine,
14
+ dump_circuit,
15
+ StateDump,
16
+ ShotResult,
17
+ )
18
+
19
+ from ._native import Result, Pauli, QSharpError, TargetProfile
20
+
21
+ # IPython notebook specific features
22
+ try:
23
+ if __IPYTHON__: # type: ignore
24
+ from ._ipython import register_magic, enable_classic_notebook_codemirror_mode
25
+
26
+ register_magic()
27
+ enable_classic_notebook_codemirror_mode()
28
+ except NameError:
29
+ pass
30
+
31
+
32
+ __all__ = [
33
+ "init",
34
+ "eval",
35
+ "run",
36
+ "set_quantum_seed",
37
+ "set_classical_seed",
38
+ "dump_machine",
39
+ "dump_circuit",
40
+ "compile",
41
+ "circuit",
42
+ "estimate",
43
+ "Result",
44
+ "Pauli",
45
+ "QSharpError",
46
+ "TargetProfile",
47
+ "StateDump",
48
+ "ShotResult",
49
+ ]
qsharp/_fs.py ADDED
@@ -0,0 +1,37 @@
1
+ # Copyright (c) Microsoft Corporation.
2
+ # Licensed under the MIT License.
3
+
4
+ import os
5
+ from typing import Dict, List, Tuple
6
+
7
+
8
+ def read_file(path: str) -> Tuple[str, str]:
9
+ with open(path, mode="r", encoding="utf-8-sig") as f:
10
+ return (path, f.read())
11
+
12
+
13
+ def list_directory(dir_path: str) -> List[Dict[str, str]]:
14
+ def map_dir(e: str) -> Dict[str, str]:
15
+ return {
16
+ "path": os.path.join(dir_path, e),
17
+ "entry_name": e,
18
+ "type": (
19
+ "file"
20
+ if os.path.isfile(os.path.join(dir_path, e))
21
+ else "folder" if os.path.isdir(os.path.join(dir_path, e)) else "unknown"
22
+ ),
23
+ }
24
+
25
+ return list(map(map_dir, os.listdir(dir_path)))
26
+
27
+
28
+ def resolve(base: str, path: str) -> str:
29
+ return os.path.normpath(join(base, path))
30
+
31
+
32
+ def exists(path) -> bool:
33
+ return os.path.exists(path)
34
+
35
+
36
+ def join(path: str, *paths) -> str:
37
+ return os.path.join(path, *paths)
qsharp/_http.py ADDED
@@ -0,0 +1,10 @@
1
+ # Copyright (c) Microsoft Corporation.
2
+ # Licensed under the MIT License.
3
+
4
+
5
+ def fetch_github(owner: str, repo: str, ref: str, path: str) -> str:
6
+ import urllib
7
+
8
+ path_no_leading_slash = path[1:] if path.startswith("/") else path
9
+ url = f"https://raw.githubusercontent.com/{owner}/{repo}/{ref}/{path_no_leading_slash}"
10
+ return urllib.request.urlopen(url).read().decode("utf-8")
qsharp/_ipython.py ADDED
@@ -0,0 +1,61 @@
1
+ # Copyright (c) Microsoft Corporation.
2
+ # Licensed under the MIT License.
3
+
4
+ from IPython.display import display, Javascript, Pretty
5
+ from IPython.core.magic import register_cell_magic
6
+ from ._native import QSharpError
7
+ from ._qsharp import get_interpreter
8
+ import pathlib
9
+
10
+
11
+ def register_magic():
12
+ @register_cell_magic
13
+ def qsharp(line, cell):
14
+ """Cell magic to interpret Q# code in Jupyter notebooks."""
15
+
16
+ def callback(output):
17
+ display(output)
18
+
19
+ try:
20
+ return get_interpreter().interpret(cell, callback)
21
+ except QSharpError as e:
22
+ raise QSharpCellError(str(e))
23
+
24
+
25
+ def enable_classic_notebook_codemirror_mode():
26
+ """
27
+ Registers %%qsharp cells with MIME type text/x-qsharp
28
+ and defines a CodeMirror mode to enable syntax highlighting.
29
+ This only works in "classic" Jupyter notebooks, not Notebook v7.
30
+ """
31
+ js_to_inject = open(
32
+ pathlib.Path(__file__)
33
+ .parent.resolve()
34
+ .joinpath(".data", "qsharp_codemirror.js"),
35
+ mode="r",
36
+ encoding="utf-8",
37
+ ).read()
38
+
39
+ # Extend the JavaScript display helper to print nothing when used
40
+ # in a non-browser context (i.e. IPython console)
41
+ class JavaScriptWithPlainTextFallback(Javascript):
42
+ def __repr__(self):
43
+ return ""
44
+
45
+ # This will run the JavaScript in the context of the frontend.
46
+ display(JavaScriptWithPlainTextFallback(js_to_inject))
47
+
48
+
49
+ class QSharpCellError(BaseException):
50
+ """
51
+ Error raised when a %%qsharp cell fails.
52
+ """
53
+
54
+ def __init__(self, traceback: str):
55
+ self.traceback = traceback.splitlines()
56
+
57
+ def _render_traceback_(self):
58
+ # We want to specifically override the traceback so that
59
+ # the Q# error directly from the interpreter is shown
60
+ # instead of the Python error.
61
+ return self.traceback
qsharp/_native.pyd ADDED
Binary file
qsharp/_native.pyi ADDED
@@ -0,0 +1,233 @@
1
+ # Copyright (c) Microsoft Corporation.
2
+ # Licensed under the MIT License.
3
+
4
+ from enum import Enum
5
+ from typing import Any, Callable, ClassVar, Optional, Dict, List
6
+
7
+ class TargetProfile:
8
+ """
9
+ A Q# target profile.
10
+
11
+ A target profile describes the capabilities of the hardware or simulator
12
+ which will be used to run the Q# program.
13
+ """
14
+
15
+ Base: ClassVar[Any]
16
+ """
17
+ Target supports the minimal set of capabilities required to run a quantum
18
+ program.
19
+
20
+ This option maps to the Base Profile as defined by the QIR specification.
21
+ """
22
+
23
+ Adaptive_RI: ClassVar[Any]
24
+ """
25
+ Target supports the Adaptive profile with integer computation and qubit
26
+ reset capabilities.
27
+
28
+ This profile includes all of the required Adaptive Profile
29
+ capabilities, as well as the optional integer computation and qubit
30
+ reset capabilities, as defined by the QIR specification.
31
+ """
32
+
33
+ Unrestricted: ClassVar[Any]
34
+ """
35
+ Describes the unrestricted set of capabilities required to run any Q# program.
36
+ """
37
+
38
+ class Interpreter:
39
+ """A Q# interpreter."""
40
+
41
+ def __init__(
42
+ self,
43
+ target_profile: TargetProfile,
44
+ language_features: Optional[List[str]],
45
+ project_root: Optional[str],
46
+ read_file: Callable[[str], str],
47
+ list_directory: Callable[[str], str],
48
+ resolve_path: Callable[[str, str], str],
49
+ ) -> None:
50
+ """
51
+ Initializes the Q# interpreter.
52
+
53
+ :param target_profile: The target profile to use for the interpreter.
54
+ :param project_root: A directory that contains a `qsharp.json` manifest.
55
+ :param read_file: A function that reads a file from the file system.
56
+ :param list_directory: A function that lists the contents of a directory.
57
+ :param resolve_path: A function that joins path segments and normalizes the resulting path.
58
+ """
59
+ ...
60
+
61
+ def interpret(self, input: str, output_fn: Callable[[Output], None]) -> Any:
62
+ """
63
+ Interprets Q# source code.
64
+
65
+ :param input: The Q# source code to interpret.
66
+ :param output_fn: A callback function that will be called with each output.
67
+
68
+ :returns value: The value returned by the last statement in the input.
69
+
70
+ :raises QSharpError: If there is an error interpreting the input.
71
+ """
72
+ ...
73
+
74
+ def run(self, entry_expr: str, output_fn: Callable[[Output], None]) -> Any:
75
+ """
76
+ Runs the given Q# expression with an independent instance of the simulator.
77
+
78
+ :param entry_expr: The entry expression.
79
+ :param output_fn: A callback function that will be called with each output.
80
+
81
+ :returns values: A result or runtime errors.
82
+
83
+ :raises QSharpError: If there is an error interpreting the input.
84
+ """
85
+ ...
86
+
87
+ def qir(self, entry_expr: str) -> str:
88
+ """
89
+ Generates QIR from Q# source code.
90
+
91
+ :param entry_expr: The entry expression.
92
+
93
+ :returns qir: The QIR string.
94
+ """
95
+ ...
96
+
97
+ def circuit(
98
+ self,
99
+ entry_expr: Optional[str],
100
+ operation: Optional[str],
101
+ ) -> Circuit:
102
+ """
103
+ Synthesizes a circuit for a Q# program. Either an entry
104
+ expression or an operation must be provided.
105
+
106
+ :param entry_expr: An entry expression.
107
+
108
+ :param operation: The operation to synthesize. This can be a name of
109
+ an operation of a lambda expression. The operation must take only
110
+ qubits or arrays of qubits as parameters.
111
+
112
+ :raises QSharpError: If there is an error synthesizing the circuit.
113
+ """
114
+ ...
115
+
116
+ def estimate(self, entry_expr: str, params: str) -> str:
117
+ """
118
+ Estimates resources for Q# source code.
119
+
120
+ :param entry_expr: The entry expression.
121
+ :param params: The parameters to configure estimation.
122
+
123
+ :returns resources: The estimated resources.
124
+ """
125
+ ...
126
+
127
+ def set_quantum_seed(self, seed: Optional[int]) -> None:
128
+ """
129
+ Sets the seed for the quantum random number generator.
130
+
131
+ :param seed: The seed to use for the quantum random number generator. If None,
132
+ the seed will be generated from entropy.
133
+ """
134
+ ...
135
+
136
+ def set_classical_seed(self, seed: Optional[int]) -> None:
137
+ """
138
+ Sets the seed for the classical random number generator.
139
+
140
+ :param seed: The seed to use for the classical random number generator. If None,
141
+ the seed will be generated from entropy.
142
+ """
143
+ ...
144
+
145
+ def dump_machine(self) -> StateDumpData:
146
+ """
147
+ Returns the sparse state vector of the simulator as a StateDump object.
148
+
149
+ :returns: The state of the simulator.
150
+ """
151
+ ...
152
+
153
+ def dump_circuit(self) -> Circuit:
154
+ """
155
+ Dumps the current circuit state of the interpreter.
156
+
157
+ This circuit will contain the gates that have been applied
158
+ in the simulator up to the current point.
159
+ """
160
+ ...
161
+
162
+ class Result(Enum):
163
+ """
164
+ A Q# measurement result.
165
+ """
166
+
167
+ Zero: int
168
+ One: int
169
+
170
+ class Pauli(Enum):
171
+ """
172
+ A Q# Pauli operator.
173
+ """
174
+
175
+ I: int
176
+ X: int
177
+ Y: int
178
+ Z: int
179
+
180
+ class Output:
181
+ """
182
+ An output returned from the Q# interpreter.
183
+ Outputs can be a state dumps or messages. These are normally printed to the console.
184
+ """
185
+
186
+ def __repr__(self) -> str: ...
187
+ def __str__(self) -> str: ...
188
+ def _repr_html_(self) -> str: ...
189
+ def _repr_latex_(self) -> Optional[str]: ...
190
+ def state_dump(self) -> Optional[StateDumpData]: ...
191
+
192
+ class StateDumpData:
193
+ """
194
+ A state dump returned from the Q# interpreter.
195
+ """
196
+
197
+ """
198
+ The number of allocated qubits at the time of the dump.
199
+ """
200
+ qubit_count: int
201
+
202
+ """
203
+ Get the amplitudes of the state vector as a dictionary from state integer to
204
+ complex amplitudes.
205
+ """
206
+ def get_dict(self) -> dict: ...
207
+ def __repr__(self) -> str: ...
208
+ def __str__(self) -> str: ...
209
+ def _repr_html_(self) -> str: ...
210
+ def _repr_latex_(self) -> Optional[str]: ...
211
+
212
+ class Circuit:
213
+ def json(self) -> str: ...
214
+ def __repr__(self) -> str: ...
215
+ def __str__(self) -> str: ...
216
+
217
+ class QSharpError(BaseException):
218
+ """
219
+ An error returned from the Q# interpreter.
220
+ """
221
+
222
+ ...
223
+
224
+ def physical_estimates(logical_resources: str, params: str) -> str:
225
+ """
226
+ Estimates physical resources from pre-calculated logical resources.
227
+
228
+ :param logical_resources: The logical resources to estimate from.
229
+ :param params: The parameters to configure physical estimation.
230
+
231
+ :returns resources: The estimated resources.
232
+ """
233
+ ...