quantakit 1.0.0__py3-none-any.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.
- quantakit/__init__.py +25 -0
- quantakit/circuit/__init__.py +7 -0
- quantakit/circuit/drawer.py +167 -0
- quantakit/circuit/gates.py +144 -0
- quantakit/circuit/library.py +143 -0
- quantakit/circuit/parameter.py +143 -0
- quantakit/circuit/quantumcircuit.py +467 -0
- quantakit/cloud/__init__.py +210 -0
- quantakit/exceptions.py +40 -0
- quantakit/primitives/__init__.py +238 -0
- quantakit/qasm.py +189 -0
- quantakit/qasm2.py +11 -0
- quantakit/qasm3.py +11 -0
- quantakit/quantum_info/__init__.py +319 -0
- quantakit/sim/__init__.py +52 -0
- quantakit/sim/engine.py +149 -0
- quantakit/transpiler/__init__.py +257 -0
- quantakit/version.py +4 -0
- quantakit/visualization/__init__.py +112 -0
- quantakit-1.0.0.dist-info/METADATA +74 -0
- quantakit-1.0.0.dist-info/RECORD +23 -0
- quantakit-1.0.0.dist-info/WHEEL +4 -0
- quantakit-1.0.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
"""Transpiler: rewrite circuits into a backend's native gates, with light optimisation.
|
|
2
|
+
|
|
3
|
+
Levels: 0 = translate only; 1 = also cancel adjacent inverse gates; 2 (default for cloud) and 3 = also merge runs of
|
|
4
|
+
single-qubit gates into the fewest native gates. All-to-all connectivity is assumed in this edition (no SWAP routing).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import cmath
|
|
10
|
+
import math
|
|
11
|
+
from typing import Sequence
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
|
|
15
|
+
from ..circuit.gates import gate_matrix
|
|
16
|
+
from ..circuit.quantumcircuit import QuantumCircuit, Instruction
|
|
17
|
+
from ..circuit.parameter import ParameterExpression
|
|
18
|
+
from ..exceptions import TranspilerError, IsaError
|
|
19
|
+
from ..sim.engine import flatten
|
|
20
|
+
|
|
21
|
+
PI = math.pi
|
|
22
|
+
|
|
23
|
+
# Rules that rewrite a gate into simpler gates. Each returns a list of (name, qubits, params).
|
|
24
|
+
def _rules(name: str, q: tuple[int, ...], p: list):
|
|
25
|
+
a = q[0]
|
|
26
|
+
if name == "cz": c, t = q; return [("h", (t,), []), ("cx", (c, t), []), ("h", (t,), [])]
|
|
27
|
+
if name == "cy": c, t = q; return [("sdg", (t,), []), ("cx", (c, t), []), ("s", (t,), [])]
|
|
28
|
+
if name == "ch":
|
|
29
|
+
c, t = q
|
|
30
|
+
return [("s", (t,), []), ("h", (t,), []), ("t", (t,), []), ("cx", (c, t), []), ("tdg", (t,), []), ("h", (t,), []), ("sdg", (t,), [])]
|
|
31
|
+
if name == "cp":
|
|
32
|
+
c, t = q; l = p[0]
|
|
33
|
+
return [("p", (c,), [l / 2]), ("cx", (c, t), []), ("p", (t,), [-l / 2]), ("cx", (c, t), []), ("p", (t,), [l / 2])]
|
|
34
|
+
if name == "crz":
|
|
35
|
+
c, t = q; th = p[0]
|
|
36
|
+
return [("rz", (t,), [th / 2]), ("cx", (c, t), []), ("rz", (t,), [-th / 2]), ("cx", (c, t), [])]
|
|
37
|
+
if name == "cry":
|
|
38
|
+
c, t = q; th = p[0]
|
|
39
|
+
return [("ry", (t,), [th / 2]), ("cx", (c, t), []), ("ry", (t,), [-th / 2]), ("cx", (c, t), [])]
|
|
40
|
+
if name == "crx":
|
|
41
|
+
c, t = q; th = p[0]
|
|
42
|
+
return [("h", (t,), []), ("rz", (t,), [th / 2]), ("cx", (c, t), []), ("rz", (t,), [-th / 2]), ("cx", (c, t), []), ("h", (t,), [])]
|
|
43
|
+
if name == "swap":
|
|
44
|
+
x, y = q
|
|
45
|
+
return [("cx", (x, y), []), ("cx", (y, x), []), ("cx", (x, y), [])]
|
|
46
|
+
if name == "iswap":
|
|
47
|
+
x, y = q
|
|
48
|
+
return [("s", (x,), []), ("s", (y,), []), ("h", (x,), []), ("cx", (x, y), []), ("cx", (y, x), []), ("h", (y,), [])]
|
|
49
|
+
if name == "rzz":
|
|
50
|
+
x, y = q
|
|
51
|
+
return [("cx", (x, y), []), ("rz", (y,), [p[0]]), ("cx", (x, y), [])]
|
|
52
|
+
if name == "rxx":
|
|
53
|
+
x, y = q
|
|
54
|
+
return [("h", (x,), []), ("h", (y,), []), ("cx", (x, y), []), ("rz", (y,), [p[0]]), ("cx", (x, y), []), ("h", (x,), []), ("h", (y,), [])]
|
|
55
|
+
if name == "ryy":
|
|
56
|
+
x, y = q
|
|
57
|
+
return [("rx", (x,), [PI / 2]), ("rx", (y,), [PI / 2]), ("cx", (x, y), []), ("rz", (y,), [p[0]]), ("cx", (x, y), []), ("rx", (x,), [-PI / 2]), ("rx", (y,), [-PI / 2])]
|
|
58
|
+
if name == "ccx":
|
|
59
|
+
c1, c2, t = q
|
|
60
|
+
return [("h", (t,), []), ("cx", (c2, t), []), ("tdg", (t,), []), ("cx", (c1, t), []), ("t", (t,), []), ("cx", (c2, t), []),
|
|
61
|
+
("tdg", (t,), []), ("cx", (c1, t), []), ("t", (c2,), []), ("t", (t,), []), ("h", (t,), []), ("cx", (c1, c2), []),
|
|
62
|
+
("t", (c1,), []), ("tdg", (c2,), []), ("cx", (c1, c2), [])]
|
|
63
|
+
if name == "cswap":
|
|
64
|
+
c, x, y = q
|
|
65
|
+
return [("cx", (y, x), []), ("ccx", (c, x, y), []), ("cx", (y, x), [])]
|
|
66
|
+
return None
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _zsx(u: np.ndarray, q: int, basis: set[str]) -> tuple[list[tuple[str, tuple, list]], float]:
|
|
70
|
+
"""Decompose a 2x2 unitary into rz·sx·rz·sx·rz (or rz only / x) — returns ops and global phase."""
|
|
71
|
+
det = np.linalg.det(u)
|
|
72
|
+
phase = cmath.phase(det) / 2
|
|
73
|
+
v = u * cmath.exp(-1j * phase) # now in SU(2)
|
|
74
|
+
theta = 2 * math.atan2(abs(v[1, 0]), abs(v[0, 0]))
|
|
75
|
+
a = cmath.phase(v[1, 1]) if abs(v[1, 1]) > 1e-12 else 0.0
|
|
76
|
+
b = cmath.phase(v[1, 0]) if abs(v[1, 0]) > 1e-12 else 0.0
|
|
77
|
+
phi_plus_lam = 2 * a
|
|
78
|
+
phi_minus_lam = 2 * b if abs(v[1, 0]) > 1e-12 else 0.0
|
|
79
|
+
phi = (phi_plus_lam + phi_minus_lam) / 2
|
|
80
|
+
lam = (phi_plus_lam - phi_minus_lam) / 2
|
|
81
|
+
ops: list[tuple[str, tuple, list]] = []
|
|
82
|
+
if abs(theta) < 1e-10:
|
|
83
|
+
total = phi + lam
|
|
84
|
+
if abs(math.remainder(total, 2 * PI)) > 1e-10:
|
|
85
|
+
ops.append(("rz", (q,), [math.remainder(total, 2 * PI)]))
|
|
86
|
+
elif abs(theta - PI) < 1e-10 and "x" in basis and abs(math.remainder(phi - lam - PI, 2 * PI)) < 1e-10:
|
|
87
|
+
# pure X up to a phase
|
|
88
|
+
ops.append(("x", (q,), []))
|
|
89
|
+
else:
|
|
90
|
+
# U(θ,φ,λ) = RZ(φ+π) · SX · RZ(θ+π) · SX · RZ(λ) (up to global phase)
|
|
91
|
+
for name, ang in (("rz", lam), ("sx", None), ("rz", theta + PI), ("sx", None), ("rz", phi + PI)):
|
|
92
|
+
if name == "sx":
|
|
93
|
+
ops.append(("sx", (q,), []))
|
|
94
|
+
elif abs(math.remainder(ang, 2 * PI)) > 1e-10:
|
|
95
|
+
ops.append(("rz", (q,), [math.remainder(ang, 2 * PI)]))
|
|
96
|
+
# fix global phase to match u exactly
|
|
97
|
+
m = np.eye(2, dtype=complex)
|
|
98
|
+
for name, _, ps in ops:
|
|
99
|
+
m = gate_matrix(name, ps) @ m
|
|
100
|
+
idx = np.unravel_index(np.argmax(np.abs(u)), u.shape)
|
|
101
|
+
gph = cmath.phase(u[idx] / m[idx]) if abs(m[idx]) > 1e-12 else 0.0
|
|
102
|
+
return ops, gph
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _translate(qc: QuantumCircuit, basis: set[str] | None) -> QuantumCircuit:
|
|
106
|
+
out = QuantumCircuit(*[type(r)(r.size, r.name) for r in qc.qregs], *[type(r)(r.size, r.name) for r in qc.cregs], name=qc.name)
|
|
107
|
+
out.global_phase = float(sum(_phases(qc)))
|
|
108
|
+
out.metadata = dict(qc.metadata)
|
|
109
|
+
|
|
110
|
+
def emit(name: str, q: tuple, p: list, depth=0):
|
|
111
|
+
if depth > 20:
|
|
112
|
+
raise TranspilerError(f"Could not translate gate '{name}'.")
|
|
113
|
+
if name in ("measure", "barrier", "reset"):
|
|
114
|
+
return
|
|
115
|
+
if basis is None or name in basis:
|
|
116
|
+
out.data.append(Instruction(name, q, (), list(p)))
|
|
117
|
+
return
|
|
118
|
+
rule = _rules(name, q, p)
|
|
119
|
+
if rule is not None:
|
|
120
|
+
for n2, q2, p2 in rule:
|
|
121
|
+
emit(n2, q2, p2, depth + 1)
|
|
122
|
+
return
|
|
123
|
+
if len(q) == 1:
|
|
124
|
+
if any(isinstance(x, ParameterExpression) and x.parameters for x in p):
|
|
125
|
+
if name == "rz" and "rz" in basis:
|
|
126
|
+
out.data.append(Instruction(name, q, (), list(p)))
|
|
127
|
+
return
|
|
128
|
+
raise TranspilerError(f"Can't translate '{name}' with an unbound parameter.", "Bind parameters before transpiling to a hardware basis.")
|
|
129
|
+
if not {"rz", "sx"} <= basis:
|
|
130
|
+
raise TranspilerError(f"Basis {sorted(basis)} can't express '{name}'. Include 'rz' and 'sx'.")
|
|
131
|
+
ops, gph = _zsx(gate_matrix(name, [float(x) for x in p]), q[0], basis)
|
|
132
|
+
out.global_phase += gph
|
|
133
|
+
for n2, q2, p2 in ops:
|
|
134
|
+
out.data.append(Instruction(n2, q2, (), p2))
|
|
135
|
+
return
|
|
136
|
+
raise TranspilerError(f"No rule to translate '{name}' into {sorted(basis)}.")
|
|
137
|
+
|
|
138
|
+
for ins in flatten(qc):
|
|
139
|
+
if ins.name in ("measure", "barrier", "reset"):
|
|
140
|
+
out.data.append(Instruction(ins.name, ins.qubits, ins.clbits, []))
|
|
141
|
+
else:
|
|
142
|
+
emit(ins.name, ins.qubits, ins.params)
|
|
143
|
+
return out
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _phases(qc: QuantumCircuit):
|
|
147
|
+
yield qc.global_phase
|
|
148
|
+
for ins in qc.data:
|
|
149
|
+
if ins.definition is not None:
|
|
150
|
+
yield from _phases(ins.definition)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
_SELF_INVERSE = {"x", "y", "z", "h", "cx", "cy", "cz", "swap", "ccx", "id"}
|
|
154
|
+
_PAIRS = {("s", "sdg"), ("sdg", "s"), ("t", "tdg"), ("tdg", "t"), ("sx", "sxdg"), ("sxdg", "sx")}
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _cancel(qc: QuantumCircuit) -> QuantumCircuit:
|
|
158
|
+
changed = True
|
|
159
|
+
data = list(qc.data)
|
|
160
|
+
while changed:
|
|
161
|
+
changed = False
|
|
162
|
+
last: dict[int, int] = {}
|
|
163
|
+
keep = [True] * len(data)
|
|
164
|
+
for i, ins in enumerate(data):
|
|
165
|
+
if ins.name == "id":
|
|
166
|
+
keep[i] = False
|
|
167
|
+
changed = True
|
|
168
|
+
continue
|
|
169
|
+
prev = {last.get(q) for q in ins.qubits} | ({last.get(c + 10**6) for c in ins.clbits})
|
|
170
|
+
if len(prev) == 1 and None not in prev:
|
|
171
|
+
j = prev.pop()
|
|
172
|
+
pj = data[j]
|
|
173
|
+
if keep[j] and pj.qubits == ins.qubits and not ins.clbits and not pj.clbits and (
|
|
174
|
+
(pj.name == ins.name and ins.name in _SELF_INVERSE) or (pj.name, ins.name) in _PAIRS):
|
|
175
|
+
keep[i] = keep[j] = False
|
|
176
|
+
for q in ins.qubits:
|
|
177
|
+
last.pop(q, None)
|
|
178
|
+
changed = True
|
|
179
|
+
continue
|
|
180
|
+
for q in ins.qubits:
|
|
181
|
+
last[q] = i
|
|
182
|
+
for c in ins.clbits:
|
|
183
|
+
last[c + 10**6] = i
|
|
184
|
+
data = [d for d, k in zip(data, keep) if k]
|
|
185
|
+
out = qc.copy()
|
|
186
|
+
out.data = data
|
|
187
|
+
return out
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _merge_1q(qc: QuantumCircuit, basis: set[str] | None) -> QuantumCircuit:
|
|
191
|
+
"""Merge consecutive single-qubit gates on each wire into one matrix, then re-synthesise."""
|
|
192
|
+
out = qc.copy()
|
|
193
|
+
out.data = []
|
|
194
|
+
pending: dict[int, list[Instruction]] = {}
|
|
195
|
+
|
|
196
|
+
def flush(q: int):
|
|
197
|
+
run = pending.pop(q, [])
|
|
198
|
+
if not run:
|
|
199
|
+
return
|
|
200
|
+
if len(run) == 1 or any(i.is_parameterized for i in run):
|
|
201
|
+
out.data.extend(run)
|
|
202
|
+
return
|
|
203
|
+
m = np.eye(2, dtype=complex)
|
|
204
|
+
for i in run:
|
|
205
|
+
m = gate_matrix(i.name, [float(x) for x in i.params]) @ m
|
|
206
|
+
if basis is None or {"rz", "sx"} <= basis:
|
|
207
|
+
ops, gph = _zsx(m, q, basis or {"rz", "sx", "x"})
|
|
208
|
+
if basis is None and len(ops) >= len(run):
|
|
209
|
+
out.data.extend(run)
|
|
210
|
+
return
|
|
211
|
+
out.global_phase += gph
|
|
212
|
+
out.data.extend(Instruction(n, qq, (), p) for n, qq, p in ops)
|
|
213
|
+
else:
|
|
214
|
+
out.data.extend(run)
|
|
215
|
+
|
|
216
|
+
for ins in qc.data:
|
|
217
|
+
if len(ins.qubits) == 1 and ins.name not in ("measure", "reset", "barrier"):
|
|
218
|
+
pending.setdefault(ins.qubits[0], []).append(ins)
|
|
219
|
+
continue
|
|
220
|
+
for q in ins.qubits:
|
|
221
|
+
flush(q)
|
|
222
|
+
out.data.append(ins)
|
|
223
|
+
for q in list(pending):
|
|
224
|
+
flush(q)
|
|
225
|
+
return out
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def transpile(circuits: "QuantumCircuit | Sequence[QuantumCircuit]", backend=None, optimization_level: int = 1,
|
|
229
|
+
seed: int | None = None, basis_gates: Sequence[str] | None = None, seed_transpiler: int | None = None):
|
|
230
|
+
"""Rewrite circuit(s) for a backend. Returns a new circuit (or list, if a list was given).
|
|
231
|
+
|
|
232
|
+
``basis_gates`` overrides the backend's native gates; ``None`` keeps every gate (local simulator).
|
|
233
|
+
``seed`` is recorded in ``circuit.metadata`` for reproducibility (this edition's passes are deterministic).
|
|
234
|
+
"""
|
|
235
|
+
single = isinstance(circuits, QuantumCircuit)
|
|
236
|
+
circs = [circuits] if single else list(circuits)
|
|
237
|
+
if not 0 <= int(optimization_level) <= 3:
|
|
238
|
+
raise TranspilerError("optimization_level must be 0, 1, 2 or 3.")
|
|
239
|
+
basis = set(basis_gates) if basis_gates is not None else (set(backend.basis_gates) if backend is not None and getattr(backend, "basis_gates", None) else None)
|
|
240
|
+
out = []
|
|
241
|
+
for qc in circs:
|
|
242
|
+
nq = getattr(backend, "num_qubits", None)
|
|
243
|
+
if nq is not None and qc.num_qubits > nq:
|
|
244
|
+
raise IsaError(f"Circuit uses {qc.num_qubits} qubits; backend '{backend.name}' has {nq}.", code="QK-1003")
|
|
245
|
+
t = _translate(qc, basis)
|
|
246
|
+
if optimization_level >= 1:
|
|
247
|
+
t = _cancel(t)
|
|
248
|
+
if optimization_level >= 2:
|
|
249
|
+
t = _cancel(_merge_1q(t, basis))
|
|
250
|
+
t.metadata = {**qc.metadata, "transpile": {"optimization_level": optimization_level, "seed": seed if seed is not None else seed_transpiler,
|
|
251
|
+
"basis": sorted(basis) if basis else "any", "depth_before": qc.depth(), "depth_after": t.depth()}}
|
|
252
|
+
t.name = qc.name
|
|
253
|
+
out.append(t)
|
|
254
|
+
return out[0] if single else out
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
__all__ = ["transpile"]
|
quantakit/version.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""Histograms and Bloch vectors. Text versions work everywhere; plots need ``pip install "quantakit[visualization]"``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
from typing import Mapping, Sequence
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _normalise(counts: Mapping[str, float]) -> dict[str, float]:
|
|
12
|
+
total = sum(counts.values()) or 1
|
|
13
|
+
return {k: v / total for k, v in counts.items()}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def text_histogram(counts: Mapping[str, float], width: int = 40, sort: str = "key", top: int | None = None) -> str:
|
|
17
|
+
"""A histogram as text — handy in terminals and printed exercises.
|
|
18
|
+
|
|
19
|
+
>>> print(text_histogram({"00": 503, "11": 521}))
|
|
20
|
+
00 │████████████████████████████████████▋ 503 (49.1%)
|
|
21
|
+
11 │████████████████████████████████████████ 521 (50.9%)
|
|
22
|
+
"""
|
|
23
|
+
if not counts:
|
|
24
|
+
return "(no counts)"
|
|
25
|
+
items = sorted(counts.items(), key=(lambda kv: kv[0]) if sort == "key" else (lambda kv: -kv[1]))
|
|
26
|
+
if top:
|
|
27
|
+
items = sorted(items, key=lambda kv: -kv[1])[:top]
|
|
28
|
+
total = sum(counts.values()) or 1
|
|
29
|
+
peak = max(v for _, v in items)
|
|
30
|
+
blocks = " ▏▎▍▌▋▊▉█"
|
|
31
|
+
lines = []
|
|
32
|
+
keyw = max(len(k) for k, _ in items)
|
|
33
|
+
for k, v in items:
|
|
34
|
+
full = v / peak * width
|
|
35
|
+
bar = "█" * int(full) + (blocks[int((full - int(full)) * 8)] if full < width else "")
|
|
36
|
+
val = f"{v:g}" if isinstance(v, int) or float(v).is_integer() else f"{v:.3f}"
|
|
37
|
+
lines.append(f"{k.rjust(keyw)} │{bar.ljust(width)} {val} ({v / total:.1%})")
|
|
38
|
+
out = "\n".join(lines)
|
|
39
|
+
from ..circuit.drawer import unicode_ok
|
|
40
|
+
if not unicode_ok(): # e.g. Windows consoles that aren't UTF-8
|
|
41
|
+
out = out.translate(str.maketrans({"█": "#", "│": "|", **{c: "" for c in blocks[1:-1]}}))
|
|
42
|
+
return out
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def plot_histogram(data: "Mapping[str, float] | Sequence[Mapping[str, float]]", legend: Sequence[str] | None = None,
|
|
46
|
+
title: str | None = None, sort: str = "key", figsize=(7, 4)):
|
|
47
|
+
"""Bar chart of one or more count/probability dicts (matplotlib)."""
|
|
48
|
+
try:
|
|
49
|
+
import matplotlib.pyplot as plt
|
|
50
|
+
except ImportError as e: # pragma: no cover
|
|
51
|
+
raise ImportError('plot_histogram needs matplotlib: pip install "quantakit[visualization]" (or use text_histogram)') from e
|
|
52
|
+
series = [data] if isinstance(data, Mapping) else list(data)
|
|
53
|
+
probs = [_normalise(s) for s in series]
|
|
54
|
+
keys = sorted({k for p in probs for k in p})
|
|
55
|
+
if sort == "value":
|
|
56
|
+
keys.sort(key=lambda k: -probs[0].get(k, 0))
|
|
57
|
+
fig, ax = plt.subplots(figsize=figsize)
|
|
58
|
+
w = 0.8 / len(probs)
|
|
59
|
+
palette = ["#3D3DD8", "#E8913A", "#1A7F4B", "#D6455B"]
|
|
60
|
+
for i, p in enumerate(probs):
|
|
61
|
+
xs = [j + i * w - 0.4 + w / 2 for j in range(len(keys))]
|
|
62
|
+
bars = ax.bar(xs, [p.get(k, 0) for k in keys], width=w, color=palette[i % 4], label=(legend[i] if legend else None))
|
|
63
|
+
for b, k in zip(bars, keys):
|
|
64
|
+
v = p.get(k, 0)
|
|
65
|
+
if v > 0:
|
|
66
|
+
ax.text(b.get_x() + b.get_width() / 2, v, f"{v:.3f}", ha="center", va="bottom", fontsize=8)
|
|
67
|
+
ax.set_xticks(range(len(keys)))
|
|
68
|
+
ax.set_xticklabels(keys, rotation=60 if len(keys) > 8 else 0, fontfamily="monospace")
|
|
69
|
+
ax.set_ylabel("Probability")
|
|
70
|
+
ax.set_xlabel("Outcome")
|
|
71
|
+
if title:
|
|
72
|
+
ax.set_title(title)
|
|
73
|
+
if legend:
|
|
74
|
+
ax.legend()
|
|
75
|
+
ax.spines[["top", "right"]].set_visible(False)
|
|
76
|
+
fig.tight_layout()
|
|
77
|
+
return fig
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def bloch_vectors(state) -> list[tuple[float, float, float]]:
|
|
81
|
+
"""(x, y, z) Bloch vector of every qubit of a Statevector (length < 1 means the qubit is entangled)."""
|
|
82
|
+
from ..quantum_info import Statevector, partial_trace
|
|
83
|
+
sv = state if isinstance(state, Statevector) else Statevector(state)
|
|
84
|
+
n = sv.num_qubits
|
|
85
|
+
out = []
|
|
86
|
+
X = np.array([[0, 1], [1, 0]]); Y = np.array([[0, -1j], [1j, 0]]); Z = np.array([[1, 0], [0, -1]])
|
|
87
|
+
for q in range(n):
|
|
88
|
+
rho = partial_trace(sv, [k for k in range(n) if k != q]).data
|
|
89
|
+
out.append(tuple(float(np.real(np.trace(rho @ P))) for P in (X, Y, Z)))
|
|
90
|
+
return out
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def plot_bloch_multivector(state, figsize=None):
|
|
94
|
+
"""One Bloch sphere per qubit (matplotlib)."""
|
|
95
|
+
try:
|
|
96
|
+
import matplotlib.pyplot as plt
|
|
97
|
+
except ImportError as e: # pragma: no cover
|
|
98
|
+
raise ImportError('plot_bloch_multivector needs matplotlib: pip install "quantakit[visualization]"') from e
|
|
99
|
+
vecs = bloch_vectors(state)
|
|
100
|
+
fig = plt.figure(figsize=figsize or (3 * len(vecs), 3.2))
|
|
101
|
+
u, v = np.mgrid[0:2 * math.pi:30j, 0:math.pi:15j]
|
|
102
|
+
for i, (x, y, z) in enumerate(vecs):
|
|
103
|
+
ax = fig.add_subplot(1, len(vecs), i + 1, projection="3d")
|
|
104
|
+
ax.plot_wireframe(np.cos(u) * np.sin(v), np.sin(u) * np.sin(v), np.cos(v), color="#ccc", lw=0.4)
|
|
105
|
+
ax.quiver(0, 0, 0, x, y, z, color="#7A4DD8", lw=2.5, arrow_length_ratio=0.12)
|
|
106
|
+
ax.set_title(f"q{i}")
|
|
107
|
+
ax.set_box_aspect((1, 1, 1))
|
|
108
|
+
ax.set_axis_off()
|
|
109
|
+
return fig
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
__all__ = ["text_histogram", "plot_histogram", "bloch_vectors", "plot_bloch_multivector"]
|
|
@@ -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,23 @@
|
|
|
1
|
+
quantakit/__init__.py,sha256=wbAynrSSg9Apti8IqtMBAYEQxxnOlvpdQc6n8rrc83Q,1163
|
|
2
|
+
quantakit/exceptions.py,sha256=5gsiWE1qa9eSalX4ZYs4Khlwh87L-D5L9ZX8HrxD1hg,830
|
|
3
|
+
quantakit/qasm.py,sha256=2t3jxuvqSKCGevPU41QRdFDdONi8jAisDdiQ_vOFC3k,7548
|
|
4
|
+
quantakit/qasm2.py,sha256=wNyLtekxMyzaF6SCpbY5QPlpFrsVsbFUesnyoECGRdk,229
|
|
5
|
+
quantakit/qasm3.py,sha256=-k6V9ourOPfphhqbkZAmsvXkq75iJc-Vqq7N29ekyT8,230
|
|
6
|
+
quantakit/version.py,sha256=S473VR_nXFZhTtSub5FiGHxHvH4lyd9N-J_U2RP3IQk,144
|
|
7
|
+
quantakit/circuit/__init__.py,sha256=XddZUqLxks0B1qKArx5RAlsGNdqIvLw4px5Is3op3yc,433
|
|
8
|
+
quantakit/circuit/drawer.py,sha256=z7upfOhW39-VOVQfeMyzJ-2LJdlDKKHS3fYiBfPsrPA,6989
|
|
9
|
+
quantakit/circuit/gates.py,sha256=z5gtM9bZN2ze5_DwXYpE2fI_g231vze41vmXpI7CLh4,6679
|
|
10
|
+
quantakit/circuit/library.py,sha256=0XEVvuSjzsjxAtGkvUCOGfXOtwtIB3Y4gLdxYvNl9YY,4586
|
|
11
|
+
quantakit/circuit/parameter.py,sha256=lP98OiINurZC6wnv0Wg_V8KKie3VgQl1Yg7fKWQxgD4,4863
|
|
12
|
+
quantakit/circuit/quantumcircuit.py,sha256=2eZy3IajVFlz0L_ySHo77mMp_kWGpaGIhLjneiJOTZk,21770
|
|
13
|
+
quantakit/cloud/__init__.py,sha256=peW6w8kIbn5gF16x9iTuwiMoOgGjhdb7-ZZu-Wn0qEY,10534
|
|
14
|
+
quantakit/primitives/__init__.py,sha256=3dt91u63TWgrTT-kiKALM_S41JBXb2oEntOvwgKOAa8,9984
|
|
15
|
+
quantakit/quantum_info/__init__.py,sha256=AA85NujcHqmG4sgVQ-U0EHY93uuDg8uxRX2pDe5j5Yk,13216
|
|
16
|
+
quantakit/sim/__init__.py,sha256=0H0pa-YuS4D295AkioLcXLhqPWNPkK05qFN1tWSSXJM,1794
|
|
17
|
+
quantakit/sim/engine.py,sha256=fDo_hmob3F9rRUm5hcUp8T-2BnqwqIn1NVWIniHo_D4,5869
|
|
18
|
+
quantakit/transpiler/__init__.py,sha256=LCSnRQyInoBrxOeFl8YJ_X8gwbZ4kEcZYxr9JzEgWCw,11577
|
|
19
|
+
quantakit/visualization/__init__.py,sha256=JTMPcfpael6egyTaGnzdlKmKhT9gbsivRIEtwY1vRms,5234
|
|
20
|
+
quantakit-1.0.0.dist-info/METADATA,sha256=CjDRnmU10oFhI5prB1M3x0iPvfFw4HkFU1emHP1zr20,3350
|
|
21
|
+
quantakit-1.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
22
|
+
quantakit-1.0.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
23
|
+
quantakit-1.0.0.dist-info/RECORD,,
|