quantakit 1.0.0__tar.gz

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,17 @@
1
+ node_modules/
2
+ .next/
3
+ out/
4
+ coverage/
5
+ *.tsbuildinfo
6
+ next-env.d.ts
7
+ .env
8
+ .env.*
9
+ !.env.example
10
+ src/generated/
11
+ .DS_Store
12
+ Thumbs.db
13
+ # Contains plaintext credentials — never commit
14
+ Docs/Instructions.txt
15
+ ~$*
16
+ test-results/
17
+ playwright-report/
@@ -0,0 +1,12 @@
1
+ # QuantaKit SDK changelog
2
+
3
+ ## 1.0.0 — Book Edition (2026-12-04)
4
+ First public release; API frozen for the QuantaKit book. Pure Python + NumPy (Python 3.10–3.13).
5
+ - Circuits: 31 standard gates, measure, measure_all, reset, barrier, registers, parameters and parameter vectors, custom gates (`to_gate`/`append`), `compose`, `inverse`, `power`, `tensor`, `depth`, `count_ops`, text and matplotlib drawings.
6
+ - Local simulator: exact statevector up to 26 qubits, mid-circuit measurement and reset, seeded sampling, optional readout noise. No network access.
7
+ - Primitives: `Sampler` (BitArray counts per classical register) and `Estimator` (exact or shot-based expectation values).
8
+ - `quantum_info`: Statevector, DensityMatrix, Operator, SparsePauliOp, partial trace, fidelity, entropy.
9
+ - Transpiler: translation to any basis containing rz + sx (+ x, cx), gate cancellation, single-qubit merging, levels 0–3.
10
+ - Circuit library: Bell, GHZ, QFT, Grover, phase estimation, RealAmplitudes-style ansatz.
11
+ - OpenQASM 2.0/3.0 import and export.
12
+ - Optional QuantaKit Cloud client (`CloudService`).
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,74 @@
1
+ Metadata-Version: 2.5
2
+ Name: quantakit
3
+ Version: 1.0.0
4
+ Summary: QuantaKit SDK — build, simulate and run quantum circuits. Book Edition 1.0: stable API, offline local simulator.
5
+ Project-URL: Homepage, https://quantakit.my
6
+ Project-URL: Documentation, https://quantakit.my/docs
7
+ Author: Alaganu Enterprise
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Keywords: circuit,education,openqasm,quantum,quantum computing,qubit,simulator
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Intended Audience :: Education
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Scientific/Engineering :: Physics
21
+ Requires-Python: >=3.10
22
+ Requires-Dist: numpy>=1.23
23
+ Provides-Extra: test
24
+ Requires-Dist: pytest>=7; extra == 'test'
25
+ Provides-Extra: visualization
26
+ Requires-Dist: matplotlib>=3.6; extra == 'visualization'
27
+ Description-Content-Type: text/markdown
28
+
29
+ # QuantaKit SDK — Book Edition 1.0
30
+
31
+ Build, simulate and run quantum circuits in Python. **Everything runs offline** on the built-in simulator — no account,
32
+ no token, no quota. QuantaKit Cloud (https://quantakit.my) is optional.
33
+
34
+ ```bash
35
+ pip install quantakit==1.0.0 # the exact version the book uses
36
+ pip install "quantakit[visualization]==1.0.0" # + matplotlib plots
37
+ ```
38
+
39
+ ```python
40
+ from quantakit import QuantumCircuit, transpile, LocalSimulator
41
+ from quantakit.primitives import Sampler
42
+
43
+ qc = QuantumCircuit(2)
44
+ qc.h(0)
45
+ qc.cx(0, 1)
46
+ qc.measure_all()
47
+ print(qc.draw())
48
+
49
+ backend = LocalSimulator() # free, offline
50
+ job = Sampler(backend).run([transpile(qc, backend)], shots=4000, seed=7)
51
+ print(job.result()[0].data.meas.get_counts()) # {'00': ~2000, '11': ~2000}
52
+ ```
53
+
54
+ Switch to the cloud by changing one line: `backend = CloudService(token="qk_...").least_busy(min_qubits=2)`.
55
+
56
+ ## What's inside
57
+ | Module | Contents |
58
+ |---|---|
59
+ | `quantakit` | `QuantumCircuit`, registers, `Parameter`, `ParameterVector`, `transpile`, `LocalSimulator` |
60
+ | `quantakit.circuit.library` | Bell, GHZ, QFT, Grover, phase estimation, `real_amplitudes` ansatz |
61
+ | `quantakit.quantum_info` | `Statevector`, `DensityMatrix`, `Operator`, `SparsePauliOp`, `partial_trace`, `state_fidelity`, `entropy` |
62
+ | `quantakit.primitives` | `Sampler` (counts) and `Estimator` (expectation values) — local or cloud |
63
+ | `quantakit.qasm3` / `qasm2` | OpenQASM import/export |
64
+ | `quantakit.visualization` | `text_histogram` (no dependencies), `plot_histogram`, `plot_bloch_multivector` |
65
+ | `quantakit.cloud` | `CloudService` for QuantaKit Cloud (optional) |
66
+
67
+ Bit strings are written with the highest qubit on the left (`"01"` means q0 = 1, q1 = 0).
68
+
69
+ ## Stability promise (Book Edition)
70
+ - Version **1.0.0** is frozen for the book. Pin it: `pip install quantakit==1.0.0`.
71
+ - Every **1.x** release keeps every documented 1.0 API working. Anything deprecated keeps working for at least two minor releases.
72
+ - Breaking changes only happen in 2.0, which will be announced and will never replace 1.x on existing installs.
73
+
74
+ Documentation: https://quantakit.my/docs · Licence: Apache 2.0
@@ -0,0 +1,46 @@
1
+ # QuantaKit SDK — Book Edition 1.0
2
+
3
+ Build, simulate and run quantum circuits in Python. **Everything runs offline** on the built-in simulator — no account,
4
+ no token, no quota. QuantaKit Cloud (https://quantakit.my) is optional.
5
+
6
+ ```bash
7
+ pip install quantakit==1.0.0 # the exact version the book uses
8
+ pip install "quantakit[visualization]==1.0.0" # + matplotlib plots
9
+ ```
10
+
11
+ ```python
12
+ from quantakit import QuantumCircuit, transpile, LocalSimulator
13
+ from quantakit.primitives import Sampler
14
+
15
+ qc = QuantumCircuit(2)
16
+ qc.h(0)
17
+ qc.cx(0, 1)
18
+ qc.measure_all()
19
+ print(qc.draw())
20
+
21
+ backend = LocalSimulator() # free, offline
22
+ job = Sampler(backend).run([transpile(qc, backend)], shots=4000, seed=7)
23
+ print(job.result()[0].data.meas.get_counts()) # {'00': ~2000, '11': ~2000}
24
+ ```
25
+
26
+ Switch to the cloud by changing one line: `backend = CloudService(token="qk_...").least_busy(min_qubits=2)`.
27
+
28
+ ## What's inside
29
+ | Module | Contents |
30
+ |---|---|
31
+ | `quantakit` | `QuantumCircuit`, registers, `Parameter`, `ParameterVector`, `transpile`, `LocalSimulator` |
32
+ | `quantakit.circuit.library` | Bell, GHZ, QFT, Grover, phase estimation, `real_amplitudes` ansatz |
33
+ | `quantakit.quantum_info` | `Statevector`, `DensityMatrix`, `Operator`, `SparsePauliOp`, `partial_trace`, `state_fidelity`, `entropy` |
34
+ | `quantakit.primitives` | `Sampler` (counts) and `Estimator` (expectation values) — local or cloud |
35
+ | `quantakit.qasm3` / `qasm2` | OpenQASM import/export |
36
+ | `quantakit.visualization` | `text_histogram` (no dependencies), `plot_histogram`, `plot_bloch_multivector` |
37
+ | `quantakit.cloud` | `CloudService` for QuantaKit Cloud (optional) |
38
+
39
+ Bit strings are written with the highest qubit on the left (`"01"` means q0 = 1, q1 = 0).
40
+
41
+ ## Stability promise (Book Edition)
42
+ - Version **1.0.0** is frozen for the book. Pin it: `pip install quantakit==1.0.0`.
43
+ - Every **1.x** release keeps every documented 1.0 API working. Anything deprecated keeps working for at least two minor releases.
44
+ - Breaking changes only happen in 2.0, which will be announced and will never replace 1.x on existing installs.
45
+
46
+ Documentation: https://quantakit.my/docs · Licence: Apache 2.0
@@ -0,0 +1,50 @@
1
+ """Runs a tour of the SDK fully offline. Use it to check an installation: python run_all_offline.py"""
2
+
3
+ import math
4
+
5
+ import quantakit
6
+ from quantakit import QuantumCircuit, Parameter, transpile, LocalSimulator
7
+ from quantakit.circuit import library
8
+ from quantakit.primitives import Sampler, Estimator
9
+ from quantakit.quantum_info import Statevector, SparsePauliOp, partial_trace
10
+ from quantakit.visualization import text_histogram
11
+ from quantakit import qasm3
12
+
13
+ print(f"QuantaKit {quantakit.__version__} (Book Edition {quantakit.BOOK_EDITION})\n")
14
+
15
+ # 1. A Bell pair
16
+ qc = QuantumCircuit(2)
17
+ qc.h(0)
18
+ qc.cx(0, 1)
19
+ print(qc.draw(), "\n")
20
+ print("State:", Statevector(qc))
21
+
22
+ qc.measure_all()
23
+ counts = Sampler().run([qc], shots=1000, seed=7).result()[0].data.meas.get_counts()
24
+ print(text_histogram(counts), "\n")
25
+
26
+ # 2. Parameters and the Estimator
27
+ theta = Parameter("θ")
28
+ ry = QuantumCircuit(1)
29
+ ry.ry(theta, 0)
30
+ for value in (0, math.pi / 3, math.pi / 2, math.pi):
31
+ ev = Estimator().run([(ry, SparsePauliOp("Z"), [value])]).result()[0].data.evs
32
+ print(f"<Z> at theta = {value:.3f}: {ev:+.3f}")
33
+ print()
34
+
35
+ # 3. Entanglement seen through the reduced state
36
+ rho = partial_trace(Statevector(library.bell_state()), [1])
37
+ print("Purity of one qubit of a Bell pair:", round(rho.purity(), 3), "\n")
38
+
39
+ # 4. Grover search for 101
40
+ grover = library.grover(3, ["101"])
41
+ counts = Sampler().run([grover], shots=1000, seed=1).result()[0].data.meas.get_counts()
42
+ print(text_histogram(counts, sort="value", top=4), "\n")
43
+
44
+ # 5. Transpile to a hardware basis
45
+ hw = transpile(library.qft(3), basis_gates=["rz", "sx", "x", "cx"], optimization_level=2)
46
+ print("QFT(3) on rz/sx/x/cx:", hw.count_ops(), "depth", hw.depth(), "\n")
47
+
48
+ # 6. OpenQASM 3
49
+ print(qasm3.dumps(library.bell_state()))
50
+ print("All examples ran offline on", LocalSimulator())
@@ -0,0 +1,44 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.21"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "quantakit"
7
+ version = "1.0.0"
8
+ description = "QuantaKit SDK — build, simulate and run quantum circuits. Book Edition 1.0: stable API, offline local simulator."
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.10"
13
+ authors = [{ name = "Alaganu Enterprise" }]
14
+ keywords = ["quantum", "quantum computing", "qubit", "circuit", "simulator", "openqasm", "education"]
15
+ classifiers = [
16
+ "Development Status :: 5 - Production/Stable",
17
+ "Intended Audience :: Education",
18
+ "Intended Audience :: Science/Research",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3.10",
21
+ "Programming Language :: Python :: 3.11",
22
+ "Programming Language :: Python :: 3.12",
23
+ "Programming Language :: Python :: 3.13",
24
+ "Topic :: Scientific/Engineering :: Physics",
25
+ "Operating System :: OS Independent",
26
+ ]
27
+ dependencies = ["numpy>=1.23"]
28
+
29
+ [project.optional-dependencies]
30
+ visualization = ["matplotlib>=3.6"]
31
+ test = ["pytest>=7"]
32
+
33
+ [project.urls]
34
+ Homepage = "https://quantakit.my"
35
+ Documentation = "https://quantakit.my/docs"
36
+
37
+ [tool.hatch.build.targets.wheel]
38
+ packages = ["src/quantakit"]
39
+
40
+ [tool.hatch.build.targets.sdist]
41
+ include = ["src/quantakit", "tests", "examples", "README.md", "LICENSE", "CHANGELOG.md", "pyproject.toml"]
42
+
43
+ [tool.pytest.ini_options]
44
+ testpaths = ["tests"]
@@ -0,0 +1,25 @@
1
+ """QuantaKit SDK — build, simulate and run quantum circuits.
2
+
3
+ Book Edition 1.0: the public API documented at https://quantakit.my/docs is stable for every 1.x release.
4
+ Everything runs offline on the built-in local simulator; the cloud is optional.
5
+
6
+ >>> from quantakit import QuantumCircuit
7
+ >>> from quantakit.primitives import Sampler
8
+ >>> qc = QuantumCircuit(2); qc.h(0); qc.cx(0, 1); qc.measure_all()
9
+ >>> counts = Sampler().run([qc], shots=1000, seed=7).result()[0].data.meas.get_counts()
10
+ """
11
+
12
+ from .version import __version__, BOOK_EDITION
13
+ from .exceptions import (
14
+ QuantaKitError, CircuitError, TranspilerError, IsaError, BackendError, JobError, AuthError, QuotaError,
15
+ )
16
+ from .circuit import QuantumCircuit, QuantumRegister, ClassicalRegister, Parameter, ParameterVector, Gate
17
+ from .transpiler import transpile
18
+ from .sim import LocalSimulator
19
+
20
+ __all__ = [
21
+ "__version__", "BOOK_EDITION",
22
+ "QuantumCircuit", "QuantumRegister", "ClassicalRegister", "Parameter", "ParameterVector", "Gate",
23
+ "transpile", "LocalSimulator",
24
+ "QuantaKitError", "CircuitError", "TranspilerError", "IsaError", "BackendError", "JobError", "AuthError", "QuotaError",
25
+ ]
@@ -0,0 +1,7 @@
1
+ from .parameter import Parameter, ParameterVector, ParameterExpression
2
+ from .quantumcircuit import QuantumCircuit, QuantumRegister, ClassicalRegister, Instruction, Gate
3
+ from .gates import GATE_SPECS, gate_matrix
4
+ from . import library
5
+
6
+ __all__ = ["QuantumCircuit", "QuantumRegister", "ClassicalRegister", "Instruction", "Gate",
7
+ "Parameter", "ParameterVector", "ParameterExpression", "GATE_SPECS", "gate_matrix", "library"]
@@ -0,0 +1,167 @@
1
+ """Text (and optional matplotlib) circuit diagrams."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from typing import TYPE_CHECKING
7
+
8
+ from .parameter import ParameterExpression
9
+
10
+ if TYPE_CHECKING:
11
+ from .quantumcircuit import QuantumCircuit, Instruction
12
+
13
+ _LABEL = {"id": "I", "x": "X", "y": "Y", "z": "Z", "h": "H", "s": "S", "sdg": "S†", "sx": "√X", "sxdg": "√X†",
14
+ "t": "T", "tdg": "T†", "p": "P", "rx": "RX", "ry": "RY", "rz": "RZ", "u": "U", "reset": "|0>"}
15
+
16
+
17
+ def fmt_param(p) -> str:
18
+ if isinstance(p, ParameterExpression):
19
+ return str(p)
20
+ v = float(p)
21
+ for num, den, s in [(1, 1, "π"), (1, 2, "π/2"), (1, 4, "π/4"), (1, 8, "π/8"), (3, 4, "3π/4"), (1, 3, "π/3"), (2, 1, "2π")]:
22
+ for sign in (1, -1):
23
+ if abs(v - sign * num * math.pi / den) < 1e-9:
24
+ return ("-" if sign < 0 else "") + s
25
+ return f"{v:.3g}"
26
+
27
+
28
+ def _cells(ins: "Instruction") -> dict[int, str]:
29
+ """Text for each qubit wire the instruction touches."""
30
+ n, q, ps = ins.name, ins.qubits, ins.params
31
+ par = f"({','.join(fmt_param(p) for p in ps)})" if ps else ""
32
+ if ins.definition is not None:
33
+ lab = ins.label or n
34
+ return {qq: f"[{lab}]" if i == 0 else f"[{lab}:{i}]" for i, qq in enumerate(q)}
35
+ if n == "measure":
36
+ return {q[0]: f"M→{ins.clbits[0]}"}
37
+ if n == "barrier":
38
+ return {qq: "░" for qq in q}
39
+ if n in ("cx", "ccx"):
40
+ return {**{c: "■" for c in q[:-1]}, q[-1]: "⊕"}
41
+ if n in ("cz",):
42
+ return {q[0]: "■", q[1]: "■"}
43
+ if n in ("cy", "ch", "cp", "crx", "cry", "crz"):
44
+ base = {"cy": "Y", "ch": "H", "cp": "P", "crx": "RX", "cry": "RY", "crz": "RZ"}[n]
45
+ return {q[0]: "■", q[1]: f"{base}{par}"}
46
+ if n == "swap":
47
+ return {q[0]: "×", q[1]: "×"}
48
+ if n == "cswap":
49
+ return {q[0]: "■", q[1]: "×", q[2]: "×"}
50
+ if n in ("iswap", "rxx", "ryy", "rzz"):
51
+ lab = {"iswap": "iSWAP", "rxx": "RXX", "ryy": "RYY", "rzz": "RZZ"}[n]
52
+ return {q[0]: f"{lab}{par}", q[1]: f"{lab}{par}"}
53
+ return {q[0]: f"{_LABEL.get(n, n.upper())}{par}"}
54
+
55
+
56
+ def _layers(qc: "QuantumCircuit") -> list[list["Instruction"]]:
57
+ layers: list[list[Instruction]] = []
58
+ busy: list[int] = [0] * max(qc.num_qubits, 1)
59
+ for ins in qc.data:
60
+ lo, hi = min(ins.qubits), max(ins.qubits)
61
+ col = max(busy[lo:hi + 1])
62
+ while len(layers) <= col:
63
+ layers.append([])
64
+ layers[col].append(ins)
65
+ for k in range(lo, hi + 1):
66
+ busy[k] = col + 1
67
+ return layers
68
+
69
+
70
+ _ASCII = str.maketrans({"─": "-", "│": "|", "■": "*", "⊕": "+", "×": "x", "░": "|", "┼": "+", "→": ">", "†": "'", "√": "s", "π": "pi"})
71
+
72
+
73
+ def unicode_ok() -> bool:
74
+ """True if stdout can print box-drawing characters (False on some Windows consoles)."""
75
+ import os
76
+ import sys
77
+ if os.environ.get("QK_ASCII") == "1":
78
+ return False
79
+ enc = getattr(sys.stdout, "encoding", None) or "ascii"
80
+ try:
81
+ "─│■⊕█π".encode(enc)
82
+ return True
83
+ except (UnicodeEncodeError, LookupError):
84
+ return False
85
+
86
+
87
+ def draw_text(qc: "QuantumCircuit", ascii: bool | None = None) -> str:
88
+ text = _draw_text(qc)
89
+ if ascii is None:
90
+ ascii = not unicode_ok()
91
+ return text.translate(_ASCII) if ascii else text
92
+
93
+
94
+ def _draw_text(qc: "QuantumCircuit") -> str:
95
+ n = qc.num_qubits
96
+ if n == 0:
97
+ return "(empty circuit)"
98
+ names = []
99
+ for r in qc.qregs:
100
+ for i in range(r.size):
101
+ names.append(f"{r.name}{i}: " if len(qc.qregs) > 1 or r.name != "q" else f"q{i}: ")
102
+ width = max(len(s) for s in names)
103
+ rows = [s.rjust(width) + "─" for s in names]
104
+ gaps = [" " * width + " " for _ in range(n)] # spacer rows between wires for vertical links
105
+ for layer in _layers(qc):
106
+ cells: dict[int, str] = {}
107
+ links: set[int] = set()
108
+ for ins in layer:
109
+ cells.update(_cells(ins))
110
+ if len(ins.qubits) > 1 and ins.name != "barrier":
111
+ for k in range(min(ins.qubits), max(ins.qubits)):
112
+ links.add(k)
113
+ w = max((len(c) for c in cells.values()), default=1)
114
+ for k in range(n):
115
+ if k in cells:
116
+ text = cells[k].center(w, "─")
117
+ elif k in links:
118
+ text = "┼".center(w, "─")
119
+ else:
120
+ text = "─" * w
121
+ rows[k] += "─" + text + "─"
122
+ gaps[k] += " " + ("│".center(w) if k in links else " " * w) + " "
123
+ out = []
124
+ for k in range(n):
125
+ out.append(rows[k])
126
+ if k < n - 1:
127
+ out.append(gaps[k].rstrip())
128
+ if qc.num_clbits:
129
+ out.append(" " * width + f" classical bits: {', '.join(f'{r.name}[{r.size}]' for r in qc.cregs)}")
130
+ return "\n".join(out)
131
+
132
+
133
+ def draw_mpl(qc: "QuantumCircuit"):
134
+ try:
135
+ import matplotlib.pyplot as plt
136
+ except ImportError as e: # pragma: no cover
137
+ raise ImportError("Drawing with output='mpl' needs matplotlib: pip install \"quantakit[visualization]\"") from e
138
+ layers = _layers(qc)
139
+ fig, ax = plt.subplots(figsize=(1.2 + 0.8 * len(layers), 0.7 + 0.6 * qc.num_qubits))
140
+ n = qc.num_qubits
141
+ for k in range(n):
142
+ y = n - 1 - k
143
+ ax.plot([0, len(layers) + 0.5], [y, y], color="#5B6070", lw=1, zorder=0)
144
+ ax.text(-0.2, y, f"q{k}", ha="right", va="center", fontsize=10)
145
+ colors = {"h": "#D6455B", "s": "#D6455B", "sdg": "#D6455B", "sx": "#D6455B", "x": "#2F6FDE", "y": "#2F6FDE", "z": "#2F6FDE",
146
+ "t": "#138A84", "tdg": "#138A84", "p": "#138A84", "rx": "#7A4DD8", "ry": "#7A4DD8", "rz": "#7A4DD8", "u": "#7A4DD8"}
147
+ for col, layer in enumerate(layers, start=1):
148
+ for ins in layer:
149
+ ys = [n - 1 - q for q in ins.qubits]
150
+ if len(ys) > 1 and ins.name != "barrier":
151
+ ax.plot([col, col], [min(ys), max(ys)], color="#3D3DD8", lw=1.5, zorder=1)
152
+ for q, txt in _cells(ins).items():
153
+ y = n - 1 - q
154
+ if txt == "■":
155
+ ax.plot(col, y, "o", color="#3D3DD8", ms=7, zorder=2)
156
+ elif txt in ("⊕", "×"):
157
+ ax.text(col, y, txt, ha="center", va="center", fontsize=16, color="#3D3DD8", zorder=2)
158
+ elif txt == "░":
159
+ ax.plot([col, col], [y - 0.4, y + 0.4], color="#999", ls=":", zorder=1)
160
+ else:
161
+ c = "#5B6070" if ins.name in ("measure", "reset") else colors.get(ins.name, "#3D3DD8")
162
+ ax.text(col, y, txt, ha="center", va="center", fontsize=9, color="white", zorder=3,
163
+ bbox=dict(boxstyle="round,pad=0.35", fc=c, ec=c))
164
+ ax.set_xlim(-0.6, len(layers) + 0.8)
165
+ ax.set_ylim(-0.8, n - 0.2)
166
+ ax.axis("off")
167
+ return fig