quantum-matrix-viz 0.0.1__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.
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""Step-by-step matrix math for Qiskit circuits.
|
|
2
|
+
|
|
3
|
+
from quantum_matrix_viz import MatrixSteps
|
|
4
|
+
MatrixSteps(circuit).render_steps()
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
8
|
+
|
|
9
|
+
from .q_matrix_viz import MatrixSteps, show
|
|
10
|
+
|
|
11
|
+
__all__ = ["MatrixSteps", "show", "__version__"]
|
|
12
|
+
|
|
13
|
+
try:
|
|
14
|
+
__version__ = version("quantum_matrix_viz")
|
|
15
|
+
except PackageNotFoundError: # running from a source folder that was never pip-installed
|
|
16
|
+
__version__ = "0.0.0"
|
|
@@ -0,0 +1,531 @@
|
|
|
1
|
+
"""Step-by-step matrix math for Qiskit circuits.
|
|
2
|
+
|
|
3
|
+
quantum_matrix_viz shows how a circuit's unitary is built: every gate's
|
|
4
|
+
matrix laid out like the circuit diagram, each layer's tensor-product matrix,
|
|
5
|
+
the product of the layers, and the resulting state vector. It renders in a
|
|
6
|
+
Jupyter notebook and exports to LaTeX.
|
|
7
|
+
|
|
8
|
+
Example:
|
|
9
|
+
>>> from qiskit import QuantumCircuit
|
|
10
|
+
>>> from quantum_matrix_viz import MatrixSteps
|
|
11
|
+
>>> qc = QuantumCircuit(2)
|
|
12
|
+
>>> qc.h(0)
|
|
13
|
+
>>> qc.cx(0, 1)
|
|
14
|
+
>>> steps = MatrixSteps(qc)
|
|
15
|
+
>>> steps.render_steps() # show it in the notebook
|
|
16
|
+
>>> steps.export_tex("bell.tex") # or write a standalone .tex file
|
|
17
|
+
"""
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import Literal, get_args
|
|
21
|
+
from enum import Enum
|
|
22
|
+
from qiskit import QuantumCircuit
|
|
23
|
+
from qiskit.circuit import Gate, ControlledGate
|
|
24
|
+
from qiskit.quantum_info import Statevector
|
|
25
|
+
from qiskit.visualization import array_to_latex
|
|
26
|
+
from qiskit.quantum_info import Operator
|
|
27
|
+
from IPython.display import Math, display
|
|
28
|
+
import numpy as np
|
|
29
|
+
import sympy as sp
|
|
30
|
+
|
|
31
|
+
class Role(Enum):
|
|
32
|
+
"""What a grid cell does at its time step: idle (identity), a gate acting
|
|
33
|
+
on this qubit, or the control or target qubit of a controlled gate."""
|
|
34
|
+
IDENTITY = "identity"
|
|
35
|
+
GATE = "gate"
|
|
36
|
+
CONTROL = "control"
|
|
37
|
+
TARGET = "target"
|
|
38
|
+
|
|
39
|
+
@dataclass
|
|
40
|
+
class Cell:
|
|
41
|
+
"""One qubit at one layer of the circuit grid.
|
|
42
|
+
|
|
43
|
+
Attributes:
|
|
44
|
+
name: Display name for this qubit's part of the gate, e.g. "H", "●"
|
|
45
|
+
for a control, or "X" for the target of a CX.
|
|
46
|
+
role: What this qubit does in the layer (see Role).
|
|
47
|
+
op: The Qiskit gate for this cell. A target cell holds only the base
|
|
48
|
+
gate (X for CX); the full gate lives on the gate's first qubit.
|
|
49
|
+
None for idle qubits.
|
|
50
|
+
qargs: Indices of every qubit the gate acts on, in Qiskit's argument
|
|
51
|
+
order (controls first). None for idle qubits.
|
|
52
|
+
label: Name of the whole gate (e.g. "CX", "SWAP"), used to label
|
|
53
|
+
multi-qubit gates as a single factor.
|
|
54
|
+
"""
|
|
55
|
+
name: str
|
|
56
|
+
role: Role = Role.IDENTITY
|
|
57
|
+
op: Gate | None = None
|
|
58
|
+
qargs: tuple[int, ...] | None = None
|
|
59
|
+
label: str | None = None # whole-gate name for multi-qubit gates, e.g. "CX"
|
|
60
|
+
|
|
61
|
+
Convention = Literal["textbook", "qiskit"]
|
|
62
|
+
|
|
63
|
+
class MatrixSteps:
|
|
64
|
+
"""Step-by-step matrix breakdown of a Qiskit circuit.
|
|
65
|
+
|
|
66
|
+
The circuit is split into layers (gates that can run at the same time).
|
|
67
|
+
Each layer's matrix is the tensor product of its gates, and the circuit's
|
|
68
|
+
unitary is the product of the layer matrices, applied right to left.
|
|
69
|
+
|
|
70
|
+
The circuit is captured when the object is created, so later changes to
|
|
71
|
+
the circuit are not reflected; create a new MatrixSteps after editing it.
|
|
72
|
+
|
|
73
|
+
Attributes:
|
|
74
|
+
qc: A copy of the circuit being visualized, with barriers and final
|
|
75
|
+
measurements removed.
|
|
76
|
+
convention: Qubit ordering for matrices and states, "textbook"
|
|
77
|
+
(qubit 0 is the leftmost tensor factor and most significant bit)
|
|
78
|
+
or "qiskit" (qubit 0 is the rightmost factor and least
|
|
79
|
+
significant bit).
|
|
80
|
+
n_qubits: Number of qubits in the circuit.
|
|
81
|
+
layers: The circuit's DAG layers, in time order.
|
|
82
|
+
grid: The qubit-by-layer grid of Cells from layout_circuit.
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
I = np.eye(2, dtype=complex)
|
|
86
|
+
|
|
87
|
+
def __init__(self, qc: QuantumCircuit, convention: Convention="textbook"):
|
|
88
|
+
"""Set up the breakdown for a circuit.
|
|
89
|
+
|
|
90
|
+
Barriers are skipped, and measurements at the end of the circuit are
|
|
91
|
+
dropped, since neither changes the circuit's unitary.
|
|
92
|
+
|
|
93
|
+
Args:
|
|
94
|
+
qc: The circuit to visualize.
|
|
95
|
+
convention: "textbook" (default) or "qiskit" qubit ordering.
|
|
96
|
+
|
|
97
|
+
Raises:
|
|
98
|
+
ValueError: If convention is not "textbook" or "qiskit", or if the
|
|
99
|
+
circuit measures or resets a qubit before its last gate
|
|
100
|
+
(a mid-circuit measurement has no matrix).
|
|
101
|
+
"""
|
|
102
|
+
allowed = get_args(Convention)
|
|
103
|
+
if convention not in allowed:
|
|
104
|
+
raise ValueError(f"Matrix output convention {convention} is incorrect. Convention can only be one of {allowed}")
|
|
105
|
+
self.convention = convention
|
|
106
|
+
self.qc = _unitary_part(qc)
|
|
107
|
+
self.n_qubits = self.qc.num_qubits
|
|
108
|
+
self.layers = list(self.qc.to_dag().layers())
|
|
109
|
+
self.grid = self.layout_circuit()
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def __repr__(self):
|
|
113
|
+
"""Short summary showing the qubit and layer counts and convention."""
|
|
114
|
+
return (f"MatrixSteps(qc=<{self.n_qubits} qubits, {len(self.layers)} layers>, "
|
|
115
|
+
f"convention={self.convention!r})")
|
|
116
|
+
|
|
117
|
+
def layout_circuit(self):
|
|
118
|
+
"""Build the circuit grid: one row per qubit, one column per layer.
|
|
119
|
+
|
|
120
|
+
Each entry is a Cell describing what that qubit does at that layer,
|
|
121
|
+
so grid[q][k] is qubit q at layer k. Idle qubits get an identity Cell.
|
|
122
|
+
|
|
123
|
+
Returns:
|
|
124
|
+
A list of n_qubits rows, each a list of Cells, one per layer.
|
|
125
|
+
"""
|
|
126
|
+
n_layers = len(self.layers)
|
|
127
|
+
grid = [[Cell("I") for _ in range(n_layers)] for _ in range(self.n_qubits)]
|
|
128
|
+
|
|
129
|
+
for k, layer in enumerate(self.layers):
|
|
130
|
+
for node in layer["graph"].op_nodes():
|
|
131
|
+
qargs = [self.qc.find_bit(q).index for q in node.qargs]
|
|
132
|
+
if isinstance(node.op, ControlledGate):
|
|
133
|
+
n_ctrl = node.op.num_ctrl_qubits
|
|
134
|
+
controls, targets = qargs[:n_ctrl], qargs[n_ctrl:]
|
|
135
|
+
label = node.op.name.upper()
|
|
136
|
+
for q in controls:
|
|
137
|
+
grid[q][k] = Cell("●", Role.CONTROL, node.op,
|
|
138
|
+
tuple(qargs), label)
|
|
139
|
+
for q in targets:
|
|
140
|
+
base = node.op.base_gate
|
|
141
|
+
grid[q][k] = Cell(base.name.upper(), Role.TARGET, base,
|
|
142
|
+
tuple(qargs), label)
|
|
143
|
+
else:
|
|
144
|
+
for q in qargs:
|
|
145
|
+
grid[q][k] = Cell(node.op.name.upper(),
|
|
146
|
+
Role.GATE,
|
|
147
|
+
node.op,
|
|
148
|
+
tuple(qargs),
|
|
149
|
+
node.op.name.upper())
|
|
150
|
+
return grid
|
|
151
|
+
|
|
152
|
+
def layer_matrix(self, k):
|
|
153
|
+
"""Full 2^n x 2^n matrix of layer k, in the chosen convention.
|
|
154
|
+
|
|
155
|
+
Args:
|
|
156
|
+
k: Layer index, 0 for the first layer.
|
|
157
|
+
|
|
158
|
+
Returns:
|
|
159
|
+
The layer's Operator.
|
|
160
|
+
"""
|
|
161
|
+
op = Operator(np.eye(2**self.n_qubits))
|
|
162
|
+
for node in self.layers[k]["graph"].op_nodes():
|
|
163
|
+
qargs = [self.qc.find_bit(q).index for q in node.qargs]
|
|
164
|
+
op = op.compose(node.op, qargs=qargs)
|
|
165
|
+
return self._apply_convention(op)
|
|
166
|
+
|
|
167
|
+
def _apply_convention(self, obj):
|
|
168
|
+
"""Return an Operator (from a gate, circuit or Operator) or a
|
|
169
|
+
Statevector in the chosen qubit-ordering convention."""
|
|
170
|
+
if not isinstance(obj, Statevector):
|
|
171
|
+
obj = Operator(obj)
|
|
172
|
+
if self.convention == "textbook":
|
|
173
|
+
obj = obj.reverse_qargs()
|
|
174
|
+
return obj
|
|
175
|
+
|
|
176
|
+
def _layer_factors(self, k):
|
|
177
|
+
"""(LaTeX label, matrix) for each tensor factor of layer k, in display order."""
|
|
178
|
+
# vertical slice at layer k, keeping each cell's qubit index
|
|
179
|
+
column = [(q, row[k]) for q, row in enumerate(self.grid)]
|
|
180
|
+
if self.convention == "qiskit":
|
|
181
|
+
column = column[::-1]
|
|
182
|
+
|
|
183
|
+
factors = []
|
|
184
|
+
seen = set()
|
|
185
|
+
for q, cell in column:
|
|
186
|
+
if cell.qargs is not None and len(cell.qargs) > 1:
|
|
187
|
+
# multi-qubit gate (CX, SWAP, RZZ, ...): one factor, listed once
|
|
188
|
+
if cell.qargs in seen:
|
|
189
|
+
continue
|
|
190
|
+
seen.add(cell.qargs)
|
|
191
|
+
subscript = ",".join(str(i) for i in cell.qargs)
|
|
192
|
+
label = rf"{_name_latex(cell.label)}_{{{subscript}}}"
|
|
193
|
+
# the cell on the gate's first qubit holds the full gate
|
|
194
|
+
# (a target cell only holds the base gate, e.g. X for CX)
|
|
195
|
+
gate = self.grid[cell.qargs[0]][k].op
|
|
196
|
+
matrix = self._apply_convention(gate)
|
|
197
|
+
else:
|
|
198
|
+
label = _name_latex(cell.name)
|
|
199
|
+
matrix = self.I if cell.op is None else Operator(cell.op)
|
|
200
|
+
factors.append((label, matrix))
|
|
201
|
+
return factors
|
|
202
|
+
|
|
203
|
+
def _column_cells(self, k):
|
|
204
|
+
"""One grid entry per qubit for layer k, in display order, as
|
|
205
|
+
(LaTeX, starts_new_factor). A multi-qubit gate shows its matrix on the
|
|
206
|
+
first row it appears in; its other rows show only its name in
|
|
207
|
+
parentheses, so no tensor product is drawn through the gate."""
|
|
208
|
+
column = [(q, row[k]) for q, row in enumerate(self.grid)]
|
|
209
|
+
if self.convention == "qiskit":
|
|
210
|
+
column = column[::-1]
|
|
211
|
+
|
|
212
|
+
entries = []
|
|
213
|
+
seen = set()
|
|
214
|
+
for q, cell in column:
|
|
215
|
+
if cell.qargs is not None and len(cell.qargs) > 1:
|
|
216
|
+
subscript = ",".join(str(i) for i in cell.qargs)
|
|
217
|
+
name = rf"{_name_latex(cell.label)}_{{{subscript}}}"
|
|
218
|
+
if cell.qargs in seen:
|
|
219
|
+
entries.append((rf"\left(\,{name}\,\right)", False))
|
|
220
|
+
continue
|
|
221
|
+
seen.add(cell.qargs)
|
|
222
|
+
# the cell on the gate's first qubit holds the full gate
|
|
223
|
+
matrix = self._apply_convention(self.grid[cell.qargs[0]][k].op)
|
|
224
|
+
else:
|
|
225
|
+
name = _name_latex(cell.name)
|
|
226
|
+
matrix = self.I if cell.op is None else Operator(cell.op)
|
|
227
|
+
entries.append((rf"{name} = {_matrix_latex(matrix, factor_out=True)}", True))
|
|
228
|
+
return entries
|
|
229
|
+
|
|
230
|
+
def _gate_grid_latex(self):
|
|
231
|
+
"""Every gate matrix laid out like the circuit diagram: each row starts
|
|
232
|
+
with the qubit's index and its input state |0> with its vector, then
|
|
233
|
+
one column per layer (left to right in time), with tensor products
|
|
234
|
+
between rows."""
|
|
235
|
+
n_layers = len(self.layers)
|
|
236
|
+
cols = [self._column_cells(k) for k in range(n_layers)]
|
|
237
|
+
ket_vector = _matrix_latex(np.array([[1], [0]]))
|
|
238
|
+
# display order of the qubits, matching _column_cells
|
|
239
|
+
row_qubits = list(range(self.n_qubits))
|
|
240
|
+
if self.convention == "qiskit":
|
|
241
|
+
row_qubits.reverse()
|
|
242
|
+
|
|
243
|
+
lines = [" & ".join([""] + [rf"L_{{{k}}}" for k in range(n_layers)])]
|
|
244
|
+
for r in range(self.n_qubits):
|
|
245
|
+
if r > 0:
|
|
246
|
+
# the input state is always a full tensor product of kets
|
|
247
|
+
lines.append(" & ".join([r"\otimes"]
|
|
248
|
+
+ [r"\otimes" if cols[k][r][1] else ""
|
|
249
|
+
for k in range(n_layers)]))
|
|
250
|
+
ket = rf"(q_{{{row_qubits[r]}}})\; |0\rangle = " + ket_vector
|
|
251
|
+
lines.append(" & ".join([ket] + [cols[k][r][0] for k in range(n_layers)]))
|
|
252
|
+
|
|
253
|
+
spec = r"@{\qquad}".join("c" * (n_layers + 1))
|
|
254
|
+
return (r"\begin{array}{" + spec + "}"
|
|
255
|
+
+ r" \\[8pt] ".join(lines)
|
|
256
|
+
+ r"\end{array}")
|
|
257
|
+
|
|
258
|
+
def _factor_stack(self, k):
|
|
259
|
+
"""LaTeX for layer k's factors stacked vertically, top to bottom like
|
|
260
|
+
the circuit diagram, each with its matrix, joined by tensor products."""
|
|
261
|
+
rows = [rf"{label} &= {_matrix_latex(matrix, factor_out=True)}"
|
|
262
|
+
for label, matrix in self._layer_factors(k)]
|
|
263
|
+
return (r"\begin{aligned}"
|
|
264
|
+
+ r" \\[6pt] \otimes \\[6pt] ".join(rows)
|
|
265
|
+
+ r"\end{aligned}")
|
|
266
|
+
|
|
267
|
+
def _column_latex(self, k):
|
|
268
|
+
"""LaTeX for one column of the printout: the factor stack, with the
|
|
269
|
+
tensored layer matrix underneath (skipped at 5+ qubits)."""
|
|
270
|
+
stack = self._factor_stack(k)
|
|
271
|
+
if self.n_qubits >= 5:
|
|
272
|
+
return stack
|
|
273
|
+
return (r"\begin{gathered}" + stack + r" \\[14pt] "
|
|
274
|
+
+ _matrix_latex(self.layer_matrix(k)) + r"\end{gathered}")
|
|
275
|
+
|
|
276
|
+
def render_layer(self, k):
|
|
277
|
+
"""Show a single column (layer k) of the printout."""
|
|
278
|
+
show(self._column_latex(k))
|
|
279
|
+
|
|
280
|
+
def _steps_latex(self, time_order: bool = False) -> list[str]:
|
|
281
|
+
"""The printout as a list of LaTeX equations (no math delimiters):
|
|
282
|
+
1. every gate matrix in a grid shaped like the circuit diagram,
|
|
283
|
+
2. the tensored layer matrices in one line joined by matrix products,
|
|
284
|
+
3. the circuit unitary and the output state from |0...0>: U times the
|
|
285
|
+
input vector, which picks out U's first column, and the result
|
|
286
|
+
written as a sum of basis kets.
|
|
287
|
+
|
|
288
|
+
The product line runs L_last ... L_0 by default, because the matrix
|
|
289
|
+
nearest the state acts first. time_order=True lists it L_0 ... L_last,
|
|
290
|
+
matching the grid and the drawing, but that is not the order in which
|
|
291
|
+
the matrices multiply. Step 2 and the unitary are skipped at 5+ qubits."""
|
|
292
|
+
n_layers = len(self.layers)
|
|
293
|
+
math_order = list(reversed(range(n_layers)))
|
|
294
|
+
|
|
295
|
+
equations = [self._gate_grid_latex()]
|
|
296
|
+
|
|
297
|
+
product = " ".join(rf"L_{{{k}}}" for k in math_order)
|
|
298
|
+
unitary_part = self.qc # barriers and final measurements already removed
|
|
299
|
+
if self.n_qubits < 5:
|
|
300
|
+
line_order = list(range(n_layers)) if time_order else math_order
|
|
301
|
+
equations.append(r" \cdot ".join(
|
|
302
|
+
rf"\underbrace{{{_matrix_latex(self.layer_matrix(k))}}}_{{L_{{{k}}}}}"
|
|
303
|
+
for k in line_order))
|
|
304
|
+
equations.append(_join_latex(
|
|
305
|
+
r"U =", product, "=", self._apply_convention(unitary_part)))
|
|
306
|
+
|
|
307
|
+
zeros = "0" * self.n_qubits
|
|
308
|
+
dim = 2 ** self.n_qubits
|
|
309
|
+
psi = self._apply_convention(Statevector(unitary_part))
|
|
310
|
+
input_vector = np.zeros((dim, 1))
|
|
311
|
+
input_vector[0, 0] = 1
|
|
312
|
+
|
|
313
|
+
# U|0...0> is a weighted sum of U's columns with weights 1, 0, ..., 0,
|
|
314
|
+
# so the result is U's first column
|
|
315
|
+
shown = list(range(dim)) if dim <= 4 else [0, 1, dim - 1]
|
|
316
|
+
if self.n_qubits < 5:
|
|
317
|
+
u = self._apply_convention(unitary_part).data
|
|
318
|
+
def term(j):
|
|
319
|
+
weight = 1 if j == 0 else 0
|
|
320
|
+
return rf"{weight} \cdot " + _matrix_latex(u[:, [j]])
|
|
321
|
+
u_latex = _matrix_latex(u)
|
|
322
|
+
else:
|
|
323
|
+
# U is too big to print; name its columns instead
|
|
324
|
+
def term(j):
|
|
325
|
+
weight = 1 if j == 0 else 0
|
|
326
|
+
return rf"{weight} \cdot \text{{col}}_{{{j}}}(U)"
|
|
327
|
+
u_latex = "U"
|
|
328
|
+
terms = [term(j) for j in shown]
|
|
329
|
+
if dim > 4:
|
|
330
|
+
terms.insert(2, r"\cdots")
|
|
331
|
+
column_sum = " + ".join(terms)
|
|
332
|
+
|
|
333
|
+
equations.append(_join_latex(
|
|
334
|
+
r"|\psi\rangle = U", rf"|{zeros}\rangle", "=", u_latex, input_vector))
|
|
335
|
+
equations.append(_join_latex(
|
|
336
|
+
rf"U|{zeros}\rangle =", column_sum, "=", psi))
|
|
337
|
+
equations.append(r"|\psi\rangle = " + _ket_sum_latex(psi.data, self.n_qubits))
|
|
338
|
+
return equations
|
|
339
|
+
|
|
340
|
+
def render_steps(self, time_order: bool = False):
|
|
341
|
+
"""Show the full printout in the notebook. See _steps_latex for what
|
|
342
|
+
it contains and what time_order does."""
|
|
343
|
+
for equation in self._steps_latex(time_order):
|
|
344
|
+
show(equation)
|
|
345
|
+
|
|
346
|
+
def to_latex(self, time_order: bool = False, document: bool = False,
|
|
347
|
+
fit_width: bool = False, landscape: bool = False) -> str:
|
|
348
|
+
r"""The same printout as render_steps, as LaTeX source to paste into a
|
|
349
|
+
document. Use print(steps.to_latex()) to copy it from the notebook.
|
|
350
|
+
|
|
351
|
+
document=True returns a complete file that compiles on its own;
|
|
352
|
+
otherwise you get just the equations, and your document needs
|
|
353
|
+
\usepackage{amsmath}. fit_width=True shrinks each equation that is too
|
|
354
|
+
big for the page to fit its width and height (needs
|
|
355
|
+
\usepackage{adjustbox}), since the matrix lines are often wider than a
|
|
356
|
+
page. landscape=True turns the page sideways (only
|
|
357
|
+
with document=True, since otherwise your own document sets the page)."""
|
|
358
|
+
blocks = []
|
|
359
|
+
for equation in self._steps_latex(time_order):
|
|
360
|
+
if fit_width:
|
|
361
|
+
# shrink (never enlarge) to fit both the page width and height
|
|
362
|
+
blocks.append(r"\[" + "\n"
|
|
363
|
+
+ r"\begin{adjustbox}{max width=\linewidth, max totalheight=0.9\textheight}"
|
|
364
|
+
+ "\n" + r"$\displaystyle " + equation + "$" + "\n"
|
|
365
|
+
+ r"\end{adjustbox}" + "\n" + r"\]")
|
|
366
|
+
else:
|
|
367
|
+
blocks.append(r"\[" + "\n" + equation + "\n" + r"\]")
|
|
368
|
+
body = "\n\n".join(blocks)
|
|
369
|
+
|
|
370
|
+
if not document:
|
|
371
|
+
packages = r"\usepackage{amsmath}" + (r", \usepackage{adjustbox}" if fit_width else "")
|
|
372
|
+
return f"% requires {packages}\n" + body + "\n"
|
|
373
|
+
|
|
374
|
+
return ("\\documentclass{article}\n"
|
|
375
|
+
"\\usepackage{amsmath}\n"
|
|
376
|
+
"\\usepackage{adjustbox}\n"
|
|
377
|
+
"\\usepackage[" + ("landscape, " if landscape else "")
|
|
378
|
+
+ "margin=0.75in]{geometry}\n"
|
|
379
|
+
"\\begin{document}\n\n"
|
|
380
|
+
+ body
|
|
381
|
+
+ "\n\n\\end{document}\n")
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def export_tex(self, path: str = "matrix_steps.tex", time_order: bool = False,
|
|
385
|
+
fit_width: bool = True, landscape: bool = True) -> Path:
|
|
386
|
+
"""Write the printout to a standalone .tex file that compiles on its
|
|
387
|
+
own (open it in TeXShop or upload it to Overleaf). Returns the path.
|
|
388
|
+
|
|
389
|
+
The file is written relative to the notebook's folder unless path is
|
|
390
|
+
absolute. fit_width (on by default) shrinks equations that are too big
|
|
391
|
+
to fit the page; landscape (on by default) turns the page sideways to give
|
|
392
|
+
the wide matrix lines more room; time_order works as in render_steps."""
|
|
393
|
+
out = Path(path).expanduser()
|
|
394
|
+
if out.suffix != ".tex":
|
|
395
|
+
out = out.with_suffix(".tex")
|
|
396
|
+
out.write_text(self.to_latex(time_order=time_order, document=True,
|
|
397
|
+
fit_width=fit_width, landscape=landscape),
|
|
398
|
+
encoding="utf-8")
|
|
399
|
+
return out.resolve()
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def _unitary_part(qc: QuantumCircuit) -> QuantumCircuit:
|
|
403
|
+
"""Copy of qc with barriers and final measurements removed.
|
|
404
|
+
|
|
405
|
+
Raises:
|
|
406
|
+
ValueError: If a measurement or reset is followed by more gates on
|
|
407
|
+
any qubit, since the circuit then has no single unitary matrix.
|
|
408
|
+
"""
|
|
409
|
+
cleaned = qc.copy_empty_like()
|
|
410
|
+
for instruction in qc.data:
|
|
411
|
+
if instruction.operation.name != "barrier":
|
|
412
|
+
cleaned.append(instruction.operation, instruction.qubits,
|
|
413
|
+
instruction.clbits)
|
|
414
|
+
cleaned = cleaned.remove_final_measurements(inplace=False)
|
|
415
|
+
|
|
416
|
+
for instruction in cleaned.data:
|
|
417
|
+
if instruction.operation.name in ("measure", "reset"):
|
|
418
|
+
qubits = [cleaned.find_bit(q).index for q in instruction.qubits]
|
|
419
|
+
kind = ("measurement" if instruction.operation.name == "measure"
|
|
420
|
+
else "reset")
|
|
421
|
+
raise ValueError(
|
|
422
|
+
f"Mid-circuit {kind} on qubit {qubits[0]}: MatrixSteps can only "
|
|
423
|
+
"show circuits whose measurements all come at the end, because "
|
|
424
|
+
"a measurement or reset followed by more gates has no matrix. "
|
|
425
|
+
"Move measurements to the end, or visualize the part of the "
|
|
426
|
+
"circuit before the measurement.")
|
|
427
|
+
return cleaned
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
def _amplitude_latex(value: complex) -> str:
|
|
431
|
+
"""Exact-looking LaTeX for one amplitude, e.g. 1/2 or sqrt(2)/2."""
|
|
432
|
+
value = complex(value)
|
|
433
|
+
if abs(value.imag) < 1e-12:
|
|
434
|
+
value = value.real
|
|
435
|
+
return sp.latex(sp.nsimplify(value, tolerance=1e-10, rational=False))
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def _ket_sum_latex(amplitudes, n_qubits: int) -> str:
|
|
439
|
+
"""A state vector written as a sum of basis kets, skipping zero amplitudes,
|
|
440
|
+
e.g. 1/2|000> - 1/2|001> + 1/2|100>. Each ket is the binary form of its
|
|
441
|
+
position in the vector, so it follows whichever convention the vector is in."""
|
|
442
|
+
terms = []
|
|
443
|
+
for index, amp in enumerate(amplitudes):
|
|
444
|
+
if abs(amp) < 1e-10:
|
|
445
|
+
continue
|
|
446
|
+
ket = rf"|{index:0{n_qubits}b}\rangle"
|
|
447
|
+
amp = complex(amp)
|
|
448
|
+
negative = abs(amp.imag) < 1e-12 and amp.real < 0
|
|
449
|
+
magnitude = -amp.real if negative else amp
|
|
450
|
+
if abs(magnitude - 1) < 1e-10:
|
|
451
|
+
coeff = ""
|
|
452
|
+
else:
|
|
453
|
+
coeff = _amplitude_latex(magnitude)
|
|
454
|
+
if abs(complex(magnitude).imag) > 1e-12 and abs(complex(magnitude).real) > 1e-12:
|
|
455
|
+
coeff = rf"\left({coeff}\right)" # complex amplitudes like (1/2 + i/2)
|
|
456
|
+
sign = "-" if negative else "+"
|
|
457
|
+
if not terms:
|
|
458
|
+
terms.append(("-" if negative else "") + coeff + ket)
|
|
459
|
+
else:
|
|
460
|
+
terms.append(f" {sign} " + coeff + ket)
|
|
461
|
+
return "".join(terms) if terms else "0"
|
|
462
|
+
|
|
463
|
+
def _name_latex(name: str) -> str:
|
|
464
|
+
"""Gate name in math mode: single letters italic like H or X, longer
|
|
465
|
+
names upright so RZZ is not read as R*Z*Z."""
|
|
466
|
+
if name == "●":
|
|
467
|
+
return r"\bullet"
|
|
468
|
+
return name if len(name) == 1 else rf"\text{{{name}}}"
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
def _scalar_latex(c: float) -> str:
|
|
472
|
+
"""LaTeX for a positive scalar, preferring 1/sqrt(n) forms (e.g. 1/sqrt(2))."""
|
|
473
|
+
inv_sq = 1 / c**2
|
|
474
|
+
n = round(inv_sq)
|
|
475
|
+
if np.isclose(inv_sq, n) and n > 0:
|
|
476
|
+
root = round(np.sqrt(n))
|
|
477
|
+
if root * root == n:
|
|
478
|
+
return rf"\frac{{1}}{{{root}}}"
|
|
479
|
+
return rf"\frac{{1}}{{\sqrt{{{n}}}}}"
|
|
480
|
+
return sp.latex(sp.nsimplify(c))
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
def _matrix_latex(m, factor_out: bool = False) -> str:
|
|
484
|
+
"""LaTeX for a matrix. With factor_out, a scalar shared by every nonzero
|
|
485
|
+
entry's magnitude is pulled out front, e.g. H = 1/sqrt(2) [[1, 1], [1, -1]]."""
|
|
486
|
+
if isinstance(m, (Operator, Statevector)):
|
|
487
|
+
m = m.data
|
|
488
|
+
arr = np.asarray(m, dtype=complex)
|
|
489
|
+
if factor_out:
|
|
490
|
+
nonzero = np.abs(arr[np.abs(arr) > 1e-12])
|
|
491
|
+
if nonzero.size and np.allclose(nonzero, nonzero[0]) and not np.isclose(nonzero[0], 1):
|
|
492
|
+
c = nonzero[0]
|
|
493
|
+
return _scalar_latex(c) + " " + array_to_latex(arr / c, source=True).strip()
|
|
494
|
+
return array_to_latex(arr, source=True).strip()
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
def _to_latex(term) -> str:
|
|
498
|
+
"""LaTeX source for one term: a numpy array, sympy Matrix, Operator,
|
|
499
|
+
Statevector, or a plain string (e.g. "H", "=", r"\\otimes", r"|0\\rangle")."""
|
|
500
|
+
|
|
501
|
+
if isinstance(term, str):
|
|
502
|
+
return term
|
|
503
|
+
if isinstance(term, (sp.MatrixBase, sp.Expr)):
|
|
504
|
+
return sp.latex(term, mat_delim="", mat_str="bmatrix")
|
|
505
|
+
if isinstance(term, (Operator, Statevector)):
|
|
506
|
+
term = term.data
|
|
507
|
+
arr = np.asarray(term)
|
|
508
|
+
if arr.ndim == 1: # show state vectors as columns
|
|
509
|
+
arr = arr.reshape(-1, 1)
|
|
510
|
+
return array_to_latex(arr, source=True).strip()
|
|
511
|
+
|
|
512
|
+
|
|
513
|
+
def show(*terms):
|
|
514
|
+
"""Render terms side by side as one equation in Jupyter, e.g.
|
|
515
|
+
show("H", "=", H_matrix) or show(H, r"\\cdot", ket0, "=", result)."""
|
|
516
|
+
|
|
517
|
+
display(Math(_join_latex(*terms)))
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
def _join_latex(*terms) -> str:
|
|
521
|
+
"""LaTeX source for terms placed side by side, as show() renders them."""
|
|
522
|
+
return " ".join(_to_latex(t) for t in terms)
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
|
|
531
|
+
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: quantum_matrix_viz
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: This package is aimed at helping visualize the matrix math in a quantum circuit.
|
|
5
|
+
Author-email: Bailey Jung <baileykjung@gmail.com>
|
|
6
|
+
Project-URL: Homepage, https://github.com/jungbail/quantum_matrix_visualization_tool
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Classifier: Operating System :: OS Independent
|
|
9
|
+
Requires-Python: >=3.10
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
Requires-Dist: qiskit<3,>=2.6
|
|
12
|
+
Requires-Dist: numpy
|
|
13
|
+
Requires-Dist: sympy
|
|
14
|
+
Requires-Dist: ipython
|
|
15
|
+
|
|
16
|
+
# Quantum Matrix Visualization Tool
|
|
17
|
+
|
|
18
|
+
`quantum_matrix_viz` shows the matrix math behind simple quantum circuits, step by step, for educational purposes.
|
|
19
|
+
|
|
20
|
+
Qiskit's built-in `.draw()` method lays out a circuit nicely, but it doesn't show the matrix math going on behind the scenes. That's partly because Qiskit doesn't compute a state vector the way a person would by hand: writing out every gate as a full matrix takes $2^n \times 2^n$ entries for $n$ qubits, which quickly becomes too expensive and cumbersome on larger circuits.
|
|
21
|
+
|
|
22
|
+
This package takes a regular Qiskit circuit and expands the matrix math of each step the way you would on paper. You can view it in a Jupyter notebook or export it to LaTeX.
|
|
23
|
+
|
|
24
|
+
## What it shows
|
|
25
|
+
|
|
26
|
+
For a circuit, `quantum_matrix_viz` prints:
|
|
27
|
+
|
|
28
|
+
1. **Every gate matrix, laid out like the circuit diagram.** Each row is a qubit, starting with its input state $|0\rangle$, and each column is a layer of gates that run at the same time. Rows are joined by tensor products ($\otimes$).
|
|
29
|
+
2. **Each layer's full matrix**, the tensor product of that column, written out in one line and joined by matrix products.
|
|
30
|
+
3. **The circuit's unitary** $U$, the product of all the layer matrices.
|
|
31
|
+
4. **The output state**, computed as $U|0\cdots0\rangle$. The tool shows why that picks out the first column of $U$, then writes the result as a sum of basis kets, e.g. $\tfrac{1}{2}|000\rangle - \tfrac{1}{2}|001\rangle + \tfrac{1}{2}|100\rangle + \tfrac{1}{2}|101\rangle$.
|
|
32
|
+
|
|
33
|
+
Values are written exactly where possible: $\tfrac{1}{\sqrt{2}}$ instead of `0.7071067811865476`.
|
|
34
|
+
|
|
35
|
+
## Installation
|
|
36
|
+
|
|
37
|
+
Install from GitHub:
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
pip install git+https://github.com/jungbail/quantum_matrix_visualization_tool
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Requires Python 3.10 or newer. This installs Qiskit 2.x, NumPy, SymPy and IPython.
|
|
44
|
+
|
|
45
|
+
## Quick start
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
from qiskit import QuantumCircuit
|
|
49
|
+
from quantum_matrix_viz import MatrixSteps
|
|
50
|
+
|
|
51
|
+
qc = QuantumCircuit(3)
|
|
52
|
+
qc.h(0)
|
|
53
|
+
qc.cx(0, 2)
|
|
54
|
+
qc.x(2)
|
|
55
|
+
qc.cx(1, 2)
|
|
56
|
+
qc.h(2)
|
|
57
|
+
|
|
58
|
+
steps = MatrixSteps(qc)
|
|
59
|
+
steps.render_steps() # show the full breakdown in a Jupyter notebook
|
|
60
|
+
steps.export_tex("qc.tex") # or write it to a standalone LaTeX file
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Open the `.tex` file in TeXShop, Overleaf, or any LaTeX editor, and compile it.
|
|
64
|
+
|
|
65
|
+
## Usage
|
|
66
|
+
|
|
67
|
+
### Viewing in a notebook
|
|
68
|
+
|
|
69
|
+
| Method | What it shows |
|
|
70
|
+
|---|---|
|
|
71
|
+
| `steps.render_steps()` | The full breakdown described above |
|
|
72
|
+
| `steps.render_layer(k)` | Just layer `k`: its gates stacked with their matrices, and the layer's full matrix |
|
|
73
|
+
| `steps.layer_matrix(k)` | Returns layer `k`'s matrix as a Qiskit `Operator`, for your own calculations |
|
|
74
|
+
|
|
75
|
+
### Exporting to LaTeX
|
|
76
|
+
|
|
77
|
+
| Method | What it gives you |
|
|
78
|
+
|---|---|
|
|
79
|
+
| `steps.export_tex(path)` | Writes a complete `.tex` file that compiles on its own. Landscape page, and equations shrink to fit the page. |
|
|
80
|
+
| `steps.to_latex()` | The same equations as a string, to paste into your own document |
|
|
81
|
+
| `steps.to_latex(document=True)` | A complete document as a string |
|
|
82
|
+
|
|
83
|
+
`export_tex` options:
|
|
84
|
+
|
|
85
|
+
- `landscape=False` for a portrait page
|
|
86
|
+
- `fit_width=False` to keep equations at full size, even if they run off the page
|
|
87
|
+
|
|
88
|
+
If you paste `to_latex()` output into your own document, add `\usepackage{amsmath}` to your preamble, plus `\usepackage{adjustbox}` if you use `fit_width=True`. Use `print(steps.to_latex())` to copy it, so the backslashes come out correctly.
|
|
89
|
+
|
|
90
|
+
### Qubit ordering
|
|
91
|
+
|
|
92
|
+
There are two common conventions for ordering qubits, and they produce different-looking (but equivalent) matrices:
|
|
93
|
+
|
|
94
|
+
- **Textbook** (default): qubit 0 is the leftmost tensor factor and the leftmost bit in a ket, so $|q_0 q_1 q_2\rangle$. This matches most textbooks and lecture notes.
|
|
95
|
+
- **Qiskit**: qubit 0 is the rightmost factor and bit, so $|q_2 q_1 q_0\rangle$. This matches what Qiskit itself prints.
|
|
96
|
+
|
|
97
|
+
```python
|
|
98
|
+
MatrixSteps(qc, convention="qiskit").render_steps()
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
### Product order
|
|
102
|
+
|
|
103
|
+
Matrices act on a state from right to left, so a circuit with layers $L_0, L_1, L_2$ has the unitary $U = L_2 L_1 L_0$, and the product line is printed in that order. To list the layers in the same left-to-right order as the circuit drawing instead, pass `time_order=True`:
|
|
104
|
+
|
|
105
|
+
```python
|
|
106
|
+
steps.render_steps(time_order=True)
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
## Large circuits
|
|
110
|
+
|
|
111
|
+
The full matrices for $n$ qubits are $2^n \times 2^n$, so at **5 or more qubits** the full layer matrices and $U$ are left out. You still get the gate layout, the tensor-product structure of each layer, and the output state.
|
|
112
|
+
|
|
113
|
+
## Limitations
|
|
114
|
+
|
|
115
|
+
- **Barriers** are ignored.
|
|
116
|
+
- **Measurements at the end** of a circuit are dropped, since they don't change the unitary.
|
|
117
|
+
- **Mid-circuit measurements and resets** raise a `ValueError`, because a circuit that measures and then keeps going doesn't have a single matrix.
|
|
118
|
+
- **Parameterized gates** need their parameters assigned first (for example with `qc.assign_parameters(...)`).
|
|
119
|
+
- Every qubit starts in $|0\rangle$.
|
|
120
|
+
|
|
121
|
+
## Author
|
|
122
|
+
|
|
123
|
+
Bailey Jung
|
|
124
|
+
# quantum_matrix_visualization_tool
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
quantum_matrix_viz/__init__.py,sha256=xmha4mB4RCRPk0SL-3UJoV4Ts08fABc9s4ccSuK1RDQ,469
|
|
2
|
+
quantum_matrix_viz/q_matrix_viz.py,sha256=Z1F00Dstv8XPziydFupGRCNnUSJERRNmoEj6yuv0UGI,23152
|
|
3
|
+
quantum_matrix_viz-0.0.1.dist-info/METADATA,sha256=26lQ-bHroxK8T_56WVnjqyiJrxvqUMbCV31dQtCIMRo,5455
|
|
4
|
+
quantum_matrix_viz-0.0.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
5
|
+
quantum_matrix_viz-0.0.1.dist-info/top_level.txt,sha256=_k0IOHKtfLWWdzLL1X7kBcgvPMj3Lp2BXlDPmkgG8jM,19
|
|
6
|
+
quantum_matrix_viz-0.0.1.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
quantum_matrix_viz
|