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
quantakit/__init__.py
ADDED
|
@@ -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
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""Standard gate library and unitary matrices.
|
|
2
|
+
|
|
3
|
+
Matrix convention: for a gate on qubits ``[a, b, ...]`` the matrix acts on the basis ``|a b ...>`` with
|
|
4
|
+
``a`` as the most significant bit (textbook order, e.g. CX = [[1,0,0,0],[0,1,0,0],[0,0,0,1],[0,0,1,0]] for cx(control=a, target=b)).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import math
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
|
|
12
|
+
import numpy as np
|
|
13
|
+
|
|
14
|
+
from ..exceptions import CircuitError
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class GateSpec:
|
|
19
|
+
name: str
|
|
20
|
+
num_qubits: int
|
|
21
|
+
num_params: int
|
|
22
|
+
family: str
|
|
23
|
+
description: str
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
GATE_SPECS: dict[str, GateSpec] = {s.name: s for s in [
|
|
27
|
+
GateSpec("id", 1, 0, "pauli", "Identity"),
|
|
28
|
+
GateSpec("x", 1, 0, "pauli", "Pauli-X (bit flip, NOT)"),
|
|
29
|
+
GateSpec("y", 1, 0, "pauli", "Pauli-Y"),
|
|
30
|
+
GateSpec("z", 1, 0, "pauli", "Pauli-Z (phase flip)"),
|
|
31
|
+
GateSpec("h", 1, 0, "clifford", "Hadamard: creates an equal superposition"),
|
|
32
|
+
GateSpec("s", 1, 0, "clifford", "S = sqrt(Z), phase of i on |1>"),
|
|
33
|
+
GateSpec("sdg", 1, 0, "clifford", "S-dagger, inverse of S"),
|
|
34
|
+
GateSpec("sx", 1, 0, "clifford", "Square root of X"),
|
|
35
|
+
GateSpec("sxdg", 1, 0, "clifford", "Inverse of SX"),
|
|
36
|
+
GateSpec("t", 1, 0, "phase", "T = sqrt(S), phase of e^{i pi/4} on |1>"),
|
|
37
|
+
GateSpec("tdg", 1, 0, "phase", "T-dagger, inverse of T"),
|
|
38
|
+
GateSpec("p", 1, 1, "phase", "Phase gate P(lambda): phase e^{i lambda} on |1>"),
|
|
39
|
+
GateSpec("rx", 1, 1, "rotation", "Rotation by theta about the X axis"),
|
|
40
|
+
GateSpec("ry", 1, 1, "rotation", "Rotation by theta about the Y axis"),
|
|
41
|
+
GateSpec("rz", 1, 1, "rotation", "Rotation by theta about the Z axis"),
|
|
42
|
+
GateSpec("u", 1, 3, "rotation", "General single-qubit gate U(theta, phi, lambda)"),
|
|
43
|
+
GateSpec("cx", 2, 0, "multi", "Controlled-X (CNOT): control, target"),
|
|
44
|
+
GateSpec("cy", 2, 0, "multi", "Controlled-Y"),
|
|
45
|
+
GateSpec("cz", 2, 0, "multi", "Controlled-Z"),
|
|
46
|
+
GateSpec("ch", 2, 0, "multi", "Controlled-Hadamard"),
|
|
47
|
+
GateSpec("cp", 2, 1, "multi", "Controlled phase CP(lambda)"),
|
|
48
|
+
GateSpec("crx", 2, 1, "multi", "Controlled RX(theta)"),
|
|
49
|
+
GateSpec("cry", 2, 1, "multi", "Controlled RY(theta)"),
|
|
50
|
+
GateSpec("crz", 2, 1, "multi", "Controlled RZ(theta)"),
|
|
51
|
+
GateSpec("swap", 2, 0, "multi", "Swap two qubits"),
|
|
52
|
+
GateSpec("iswap", 2, 0, "multi", "iSWAP: swap with a phase of i"),
|
|
53
|
+
GateSpec("rxx", 2, 1, "multi", "XX interaction exp(-i theta/2 X⊗X)"),
|
|
54
|
+
GateSpec("ryy", 2, 1, "multi", "YY interaction exp(-i theta/2 Y⊗Y)"),
|
|
55
|
+
GateSpec("rzz", 2, 1, "multi", "ZZ interaction exp(-i theta/2 Z⊗Z)"),
|
|
56
|
+
GateSpec("ccx", 3, 0, "multi", "Toffoli: two controls, one target"),
|
|
57
|
+
GateSpec("cswap", 3, 0, "multi", "Fredkin: control, then two targets"),
|
|
58
|
+
]}
|
|
59
|
+
|
|
60
|
+
NON_UNITARY = {"measure", "reset", "barrier"}
|
|
61
|
+
|
|
62
|
+
_I2 = np.eye(2, dtype=complex)
|
|
63
|
+
_X = np.array([[0, 1], [1, 0]], dtype=complex)
|
|
64
|
+
_Y = np.array([[0, -1j], [1j, 0]], dtype=complex)
|
|
65
|
+
_Z = np.array([[1, 0], [0, -1]], dtype=complex)
|
|
66
|
+
_H = np.array([[1, 1], [1, -1]], dtype=complex) / math.sqrt(2)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _u(theta: float, phi: float, lam: float) -> np.ndarray:
|
|
70
|
+
c, s = math.cos(theta / 2), math.sin(theta / 2)
|
|
71
|
+
return np.array([[c, -np.exp(1j * lam) * s], [np.exp(1j * phi) * s, np.exp(1j * (phi + lam)) * c]], dtype=complex)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _controlled(u: np.ndarray) -> np.ndarray:
|
|
75
|
+
out = np.eye(4, dtype=complex)
|
|
76
|
+
out[2:, 2:] = u
|
|
77
|
+
return out
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _single(name: str, p: list[float]) -> np.ndarray:
|
|
81
|
+
if name == "id": return _I2.copy()
|
|
82
|
+
if name == "x": return _X.copy()
|
|
83
|
+
if name == "y": return _Y.copy()
|
|
84
|
+
if name == "z": return _Z.copy()
|
|
85
|
+
if name == "h": return _H.copy()
|
|
86
|
+
if name == "s": return np.diag([1, 1j]).astype(complex)
|
|
87
|
+
if name == "sdg": return np.diag([1, -1j]).astype(complex)
|
|
88
|
+
if name == "t": return np.diag([1, np.exp(1j * math.pi / 4)])
|
|
89
|
+
if name == "tdg": return np.diag([1, np.exp(-1j * math.pi / 4)])
|
|
90
|
+
if name == "sx": return 0.5 * np.array([[1 + 1j, 1 - 1j], [1 - 1j, 1 + 1j]])
|
|
91
|
+
if name == "sxdg": return 0.5 * np.array([[1 - 1j, 1 + 1j], [1 + 1j, 1 - 1j]])
|
|
92
|
+
if name == "p": return np.diag([1, np.exp(1j * p[0])])
|
|
93
|
+
if name == "rx":
|
|
94
|
+
c, s = math.cos(p[0] / 2), math.sin(p[0] / 2)
|
|
95
|
+
return np.array([[c, -1j * s], [-1j * s, c]])
|
|
96
|
+
if name == "ry":
|
|
97
|
+
c, s = math.cos(p[0] / 2), math.sin(p[0] / 2)
|
|
98
|
+
return np.array([[c, -s], [s, c]], dtype=complex)
|
|
99
|
+
if name == "rz": return np.diag([np.exp(-1j * p[0] / 2), np.exp(1j * p[0] / 2)])
|
|
100
|
+
if name == "u": return _u(p[0], p[1], p[2])
|
|
101
|
+
raise CircuitError(f"Unknown single-qubit gate '{name}'.")
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def gate_matrix(name: str, params: list[float] | tuple = ()) -> np.ndarray:
|
|
105
|
+
"""Unitary matrix of a standard gate with numeric parameters."""
|
|
106
|
+
p = [float(v) for v in params]
|
|
107
|
+
spec = GATE_SPECS.get(name)
|
|
108
|
+
if spec is None:
|
|
109
|
+
raise CircuitError(f"Unknown gate '{name}'.", "See quantakit.circuit.GATE_SPECS for the gate list.")
|
|
110
|
+
if spec.num_qubits == 1:
|
|
111
|
+
return _single(name, p)
|
|
112
|
+
if name in ("cx", "cy", "cz", "ch", "cp", "crx", "cry", "crz"):
|
|
113
|
+
base = {"cx": "x", "cy": "y", "cz": "z", "ch": "h", "cp": "p", "crx": "rx", "cry": "ry", "crz": "rz"}[name]
|
|
114
|
+
return _controlled(_single(base, p))
|
|
115
|
+
if name == "swap":
|
|
116
|
+
return np.array([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]], dtype=complex)
|
|
117
|
+
if name == "iswap":
|
|
118
|
+
return np.array([[1, 0, 0, 0], [0, 0, 1j, 0], [0, 1j, 0, 0], [0, 0, 0, 1]], dtype=complex)
|
|
119
|
+
if name in ("rxx", "ryy", "rzz"):
|
|
120
|
+
pauli = {"rxx": _X, "ryy": _Y, "rzz": _Z}[name]
|
|
121
|
+
pp = np.kron(pauli, pauli)
|
|
122
|
+
return math.cos(p[0] / 2) * np.eye(4) - 1j * math.sin(p[0] / 2) * pp
|
|
123
|
+
if name == "ccx":
|
|
124
|
+
out = np.eye(8, dtype=complex)
|
|
125
|
+
out[6:, 6:] = _X
|
|
126
|
+
return out
|
|
127
|
+
if name == "cswap":
|
|
128
|
+
out = np.eye(8, dtype=complex)
|
|
129
|
+
out[[5, 6], :] = out[[6, 5], :]
|
|
130
|
+
return out
|
|
131
|
+
raise CircuitError(f"No matrix for gate '{name}'.")
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
#: Name of the inverse gate and how to transform parameters.
|
|
135
|
+
INVERSES: dict[str, tuple[str, str]] = {
|
|
136
|
+
"id": ("id", "same"), "x": ("x", "same"), "y": ("y", "same"), "z": ("z", "same"), "h": ("h", "same"),
|
|
137
|
+
"s": ("sdg", "same"), "sdg": ("s", "same"), "t": ("tdg", "same"), "tdg": ("t", "same"),
|
|
138
|
+
"sx": ("sxdg", "same"), "sxdg": ("sx", "same"),
|
|
139
|
+
"p": ("p", "neg"), "rx": ("rx", "neg"), "ry": ("ry", "neg"), "rz": ("rz", "neg"), "u": ("u", "u"),
|
|
140
|
+
"cx": ("cx", "same"), "cy": ("cy", "same"), "cz": ("cz", "same"), "ch": ("ch", "same"),
|
|
141
|
+
"cp": ("cp", "neg"), "crx": ("crx", "neg"), "cry": ("cry", "neg"), "crz": ("crz", "neg"),
|
|
142
|
+
"swap": ("swap", "same"), "rxx": ("rxx", "neg"), "ryy": ("ryy", "neg"), "rzz": ("rzz", "neg"),
|
|
143
|
+
"ccx": ("ccx", "same"), "cswap": ("cswap", "same"),
|
|
144
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""Ready-made circuits: Bell, GHZ, QFT, Grover operator, phase estimation and a layered ansatz."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
from typing import Iterable
|
|
7
|
+
|
|
8
|
+
from .quantumcircuit import QuantumCircuit
|
|
9
|
+
from .parameter import ParameterVector
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def bell_state() -> QuantumCircuit:
|
|
13
|
+
qc = QuantumCircuit(2, name="bell")
|
|
14
|
+
qc.h(0)
|
|
15
|
+
qc.cx(0, 1)
|
|
16
|
+
return qc
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def ghz_state(n: int) -> QuantumCircuit:
|
|
20
|
+
qc = QuantumCircuit(n, name=f"ghz{n}")
|
|
21
|
+
qc.h(0)
|
|
22
|
+
for k in range(n - 1):
|
|
23
|
+
qc.cx(k, k + 1)
|
|
24
|
+
return qc
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def qft(n: int, inverse: bool = False, do_swaps: bool = True) -> QuantumCircuit:
|
|
28
|
+
"""Quantum Fourier transform on n qubits (qubit 0 = least significant)."""
|
|
29
|
+
qc = QuantumCircuit(n, name="qft")
|
|
30
|
+
for j in reversed(range(n)):
|
|
31
|
+
qc.h(j)
|
|
32
|
+
for k in reversed(range(j)):
|
|
33
|
+
qc.cp(math.pi / 2 ** (j - k), k, j)
|
|
34
|
+
if do_swaps:
|
|
35
|
+
for k in range(n // 2):
|
|
36
|
+
qc.swap(k, n - 1 - k)
|
|
37
|
+
if inverse:
|
|
38
|
+
qc = qc.inverse()
|
|
39
|
+
qc.name = "iqft"
|
|
40
|
+
return qc
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def phase_oracle(n: int, marked: Iterable[str]) -> QuantumCircuit:
|
|
44
|
+
"""Flips the phase of each marked bit string (written q[n-1]…q0)."""
|
|
45
|
+
qc = QuantumCircuit(n, name="oracle")
|
|
46
|
+
for bits in marked:
|
|
47
|
+
if len(bits) != n:
|
|
48
|
+
raise ValueError(f"Marked state '{bits}' must have {n} bits.")
|
|
49
|
+
zeros = [n - 1 - i for i, b in enumerate(bits) if b == "0"]
|
|
50
|
+
if zeros:
|
|
51
|
+
qc.x(zeros)
|
|
52
|
+
if n == 1:
|
|
53
|
+
qc.z(0)
|
|
54
|
+
else:
|
|
55
|
+
qc.h(n - 1)
|
|
56
|
+
qc.mcx(list(range(n - 1)), n - 1)
|
|
57
|
+
qc.h(n - 1)
|
|
58
|
+
if zeros:
|
|
59
|
+
qc.x(zeros)
|
|
60
|
+
return qc
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def diffuser(n: int) -> QuantumCircuit:
|
|
64
|
+
qc = QuantumCircuit(n, name="diffuser")
|
|
65
|
+
qc.h(range(n))
|
|
66
|
+
qc.append(phase_oracle(n, ["0" * n]).to_gate("reflect0"), range(n))
|
|
67
|
+
qc.h(range(n))
|
|
68
|
+
return qc
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def grover_operator(oracle: QuantumCircuit) -> QuantumCircuit:
|
|
72
|
+
n = oracle.num_qubits
|
|
73
|
+
qc = QuantumCircuit(n, name="grover_op")
|
|
74
|
+
qc.compose(oracle, inplace=True)
|
|
75
|
+
qc.compose(diffuser(n), inplace=True)
|
|
76
|
+
return qc
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def grover(n: int, marked: Iterable[str], iterations: int | None = None, measure: bool = True) -> QuantumCircuit:
|
|
80
|
+
marked = list(marked)
|
|
81
|
+
if iterations is None:
|
|
82
|
+
iterations = max(1, int(math.floor(math.pi / 4 * math.sqrt(2 ** n / len(marked)))))
|
|
83
|
+
qc = QuantumCircuit(n, name="grover")
|
|
84
|
+
qc.h(range(n))
|
|
85
|
+
op = grover_operator(phase_oracle(n, marked))
|
|
86
|
+
for _ in range(iterations):
|
|
87
|
+
qc.compose(op, inplace=True)
|
|
88
|
+
if measure:
|
|
89
|
+
qc.measure_all()
|
|
90
|
+
return qc
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def real_amplitudes(n: int, reps: int = 2, prefix: str = "θ") -> QuantumCircuit:
|
|
94
|
+
"""Hardware-efficient ansatz: RY layers with a CX ladder."""
|
|
95
|
+
theta = ParameterVector(prefix, n * (reps + 1))
|
|
96
|
+
qc = QuantumCircuit(n, name="real_amplitudes")
|
|
97
|
+
k = 0
|
|
98
|
+
for r in range(reps + 1):
|
|
99
|
+
for q in range(n):
|
|
100
|
+
qc.ry(theta[k], q)
|
|
101
|
+
k += 1
|
|
102
|
+
if r < reps:
|
|
103
|
+
for q in range(n - 1):
|
|
104
|
+
qc.cx(q, q + 1)
|
|
105
|
+
return qc
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def phase_estimation(num_eval: int, unitary: QuantumCircuit) -> QuantumCircuit:
|
|
109
|
+
"""QPE: ``num_eval`` counting qubits (low qubits) then the unitary's qubits."""
|
|
110
|
+
m = unitary.num_qubits
|
|
111
|
+
qc = QuantumCircuit(num_eval + m, name="qpe")
|
|
112
|
+
qc.h(range(num_eval))
|
|
113
|
+
gate = unitary.to_gate("U")
|
|
114
|
+
for k in range(num_eval):
|
|
115
|
+
ctrl = _controlled(unitary).power(2 ** k)
|
|
116
|
+
qc.compose(ctrl, [k] + list(range(num_eval, num_eval + m)), inplace=True)
|
|
117
|
+
qc.compose(qft(num_eval, inverse=True), range(num_eval), inplace=True)
|
|
118
|
+
_ = gate
|
|
119
|
+
return qc
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _controlled(u: QuantumCircuit) -> QuantumCircuit:
|
|
123
|
+
"""Single-control version of a circuit built from gates that have controlled forms (phase-type gates)."""
|
|
124
|
+
m = u.num_qubits
|
|
125
|
+
out = QuantumCircuit(m + 1, name=f"c-{u.name}")
|
|
126
|
+
for ins in u.data:
|
|
127
|
+
q = [x + 1 for x in ins.qubits]
|
|
128
|
+
if ins.name in ("p", "rz") and len(q) == 1:
|
|
129
|
+
if ins.name == "p":
|
|
130
|
+
out.cp(ins.params[0], 0, q[0])
|
|
131
|
+
else:
|
|
132
|
+
out.crz(ins.params[0], 0, q[0])
|
|
133
|
+
elif ins.name in ("x", "y", "z", "h") and len(q) == 1:
|
|
134
|
+
getattr(out, "c" + ins.name)(0, q[0])
|
|
135
|
+
elif ins.name == "cx":
|
|
136
|
+
out.ccx(0, q[0], q[1])
|
|
137
|
+
elif ins.name == "s":
|
|
138
|
+
out.cp(math.pi / 2, 0, q[0])
|
|
139
|
+
elif ins.name == "t":
|
|
140
|
+
out.cp(math.pi / 4, 0, q[0])
|
|
141
|
+
else:
|
|
142
|
+
raise ValueError(f"phase_estimation: can't control gate '{ins.name}' in this edition.")
|
|
143
|
+
return out
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""Symbolic parameters: ``theta = Parameter("θ")`` then ``qc.rz(2 * theta + pi / 4, 0)`` and bind later."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
import uuid
|
|
7
|
+
from numbers import Number
|
|
8
|
+
from typing import Callable, Iterable, Mapping
|
|
9
|
+
|
|
10
|
+
from ..exceptions import CircuitError
|
|
11
|
+
|
|
12
|
+
_OPS: dict[str, Callable[[float, float], float]] = {
|
|
13
|
+
"+": lambda a, b: a + b,
|
|
14
|
+
"-": lambda a, b: a - b,
|
|
15
|
+
"*": lambda a, b: a * b,
|
|
16
|
+
"/": lambda a, b: a / b,
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _fmt(v: "ParameterExpression | float") -> str:
|
|
21
|
+
if isinstance(v, ParameterExpression):
|
|
22
|
+
return str(v)
|
|
23
|
+
if abs(v - math.pi) < 1e-12:
|
|
24
|
+
return "pi"
|
|
25
|
+
return repr(float(v)) if not float(v).is_integer() else str(int(v))
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class ParameterExpression:
|
|
29
|
+
"""An arithmetic expression of parameters and numbers."""
|
|
30
|
+
|
|
31
|
+
def __init__(self, op: str, left: "ParameterExpression | float", right: "ParameterExpression | float"):
|
|
32
|
+
self._op, self._left, self._right = op, left, right
|
|
33
|
+
|
|
34
|
+
# -- symbolic structure --
|
|
35
|
+
@property
|
|
36
|
+
def parameters(self) -> set["Parameter"]:
|
|
37
|
+
out: set[Parameter] = set()
|
|
38
|
+
for side in (self._left, self._right):
|
|
39
|
+
if isinstance(side, ParameterExpression):
|
|
40
|
+
out |= side.parameters
|
|
41
|
+
return out
|
|
42
|
+
|
|
43
|
+
def _eval(self, values: Mapping["Parameter", float]) -> "ParameterExpression | float":
|
|
44
|
+
l = self._left._eval(values) if isinstance(self._left, ParameterExpression) else self._left
|
|
45
|
+
r = self._right._eval(values) if isinstance(self._right, ParameterExpression) else self._right
|
|
46
|
+
if isinstance(l, ParameterExpression) or isinstance(r, ParameterExpression):
|
|
47
|
+
return ParameterExpression(self._op, l, r)
|
|
48
|
+
return _OPS[self._op](float(l), float(r))
|
|
49
|
+
|
|
50
|
+
def bind(self, values: Mapping["Parameter", float]) -> "ParameterExpression | float":
|
|
51
|
+
"""Substitute values; returns a float once every parameter is bound."""
|
|
52
|
+
return self._eval(values)
|
|
53
|
+
|
|
54
|
+
def __float__(self) -> float:
|
|
55
|
+
v = self._eval({})
|
|
56
|
+
if isinstance(v, ParameterExpression):
|
|
57
|
+
names = ", ".join(sorted(p.name for p in self.parameters))
|
|
58
|
+
raise CircuitError(f"Unbound parameter(s): {names}.", "Call circuit.assign_parameters(...) first.")
|
|
59
|
+
return float(v)
|
|
60
|
+
|
|
61
|
+
# -- arithmetic --
|
|
62
|
+
def _wrap(self, op: str, other, reverse=False):
|
|
63
|
+
if not isinstance(other, (ParameterExpression, Number)):
|
|
64
|
+
return NotImplemented
|
|
65
|
+
other = other if isinstance(other, ParameterExpression) else float(other)
|
|
66
|
+
return ParameterExpression(op, other, self) if reverse else ParameterExpression(op, self, other)
|
|
67
|
+
|
|
68
|
+
def __add__(self, o): return self._wrap("+", o)
|
|
69
|
+
def __radd__(self, o): return self._wrap("+", o, True)
|
|
70
|
+
def __sub__(self, o): return self._wrap("-", o)
|
|
71
|
+
def __rsub__(self, o): return self._wrap("-", o, True)
|
|
72
|
+
def __mul__(self, o): return self._wrap("*", o)
|
|
73
|
+
def __rmul__(self, o): return self._wrap("*", o, True)
|
|
74
|
+
def __truediv__(self, o): return self._wrap("/", o)
|
|
75
|
+
def __rtruediv__(self, o): return self._wrap("/", o, True)
|
|
76
|
+
def __neg__(self): return ParameterExpression("*", -1.0, self)
|
|
77
|
+
def __pos__(self): return self
|
|
78
|
+
|
|
79
|
+
def __str__(self) -> str:
|
|
80
|
+
return f"({_fmt(self._left)} {self._op} {_fmt(self._right)})"
|
|
81
|
+
|
|
82
|
+
__repr__ = __str__
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class Parameter(ParameterExpression):
|
|
86
|
+
"""A named symbolic value, e.g. ``Parameter("θ")``."""
|
|
87
|
+
|
|
88
|
+
def __init__(self, name: str):
|
|
89
|
+
self._name = str(name)
|
|
90
|
+
self._uuid = uuid.uuid4()
|
|
91
|
+
|
|
92
|
+
@property
|
|
93
|
+
def name(self) -> str:
|
|
94
|
+
return self._name
|
|
95
|
+
|
|
96
|
+
@property
|
|
97
|
+
def parameters(self) -> set["Parameter"]:
|
|
98
|
+
return {self}
|
|
99
|
+
|
|
100
|
+
def _eval(self, values):
|
|
101
|
+
return float(values[self]) if self in values else self
|
|
102
|
+
|
|
103
|
+
def __hash__(self):
|
|
104
|
+
return hash(self._uuid)
|
|
105
|
+
|
|
106
|
+
def __eq__(self, other):
|
|
107
|
+
return isinstance(other, Parameter) and other._uuid == self._uuid
|
|
108
|
+
|
|
109
|
+
def __str__(self):
|
|
110
|
+
return self._name
|
|
111
|
+
|
|
112
|
+
def __repr__(self):
|
|
113
|
+
return f"Parameter({self._name})"
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class ParameterVector:
|
|
117
|
+
"""A list of parameters named ``name[0]``, ``name[1]``, ..."""
|
|
118
|
+
|
|
119
|
+
def __init__(self, name: str, length: int):
|
|
120
|
+
self.name = name
|
|
121
|
+
self._params = [Parameter(f"{name}[{i}]") for i in range(length)]
|
|
122
|
+
|
|
123
|
+
def __getitem__(self, i):
|
|
124
|
+
return self._params[i]
|
|
125
|
+
|
|
126
|
+
def __len__(self):
|
|
127
|
+
return len(self._params)
|
|
128
|
+
|
|
129
|
+
def __iter__(self) -> Iterable[Parameter]:
|
|
130
|
+
return iter(self._params)
|
|
131
|
+
|
|
132
|
+
def __repr__(self):
|
|
133
|
+
return f"ParameterVector({self.name}, {len(self)})"
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def param_sort_key(p: Parameter):
|
|
137
|
+
"""Sort parameters by name, with vector elements in numeric order (θ[2] before θ[10])."""
|
|
138
|
+
name = p.name
|
|
139
|
+
if name.endswith("]") and "[" in name:
|
|
140
|
+
base, idx = name[:-1].split("[", 1)
|
|
141
|
+
if idx.isdigit():
|
|
142
|
+
return (base, int(idx))
|
|
143
|
+
return (name, -1)
|