The following public-API Qiskit program verifies the three transformations, arranges the Bloch spheres in the teaching order X, H, Z, labels the x-axis endpoints, and writes the two superposition formulas below the figure. Install the visualisation dependencies with python -m pip install "qiskit[visualization]".
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
from qiskit.circuit.library import HGate, XGate, ZGate
from qiskit.quantum_info import Statevector
from qiskit.visualization.bloch import Bloch
def bloch_vector(state):
alpha, beta = state.data
overlap = np.conj(alpha) * beta
return [
float(2 * np.real(overlap)),
float(2 * np.imag(overlap)),
float(abs(alpha) ** 2 - abs(beta) ** 2),
]
zero = Statevector.from_label("0")
one = zero.evolve(XGate())
plus = zero.evolve(HGate())
minus = plus.evolve(ZGate())
assert one.equiv(Statevector.from_label("1"))
assert plus.equiv(Statevector.from_label("+"))
assert minus.equiv(Statevector.from_label("-"))
rows = [
("X gate", zero, one, r"Input: $|0\rangle$", r"Output: $|1\rangle$"),
("H gate", zero, plus, r"Input: $|0\rangle$", r"Output: $|+\rangle$"),
("Z gate", plus, minus, r"Input: $|+\rangle$", r"Output: $|-\rangle$"),
]
fig = plt.figure(figsize=(9.6, 12.6), facecolor="white")
for row_index, (gate, before, after, before_title, after_title) in enumerate(rows):
for column_index, (state, title, color) in enumerate((
(before, before_title, "#1565C0"),
(after, after_title, "#D32F2F"),
)):
axis = fig.add_subplot(
3, 2, row_index * 2 + column_index + 1, projection="3d"
)
sphere = Bloch(fig=fig, axes=axis, font_size=13)
sphere.xlabel = [r"$|+\rangle$", r"$|-\rangle$"]
sphere.vector_color = [color]
sphere.add_vectors(bloch_vector(state))
sphere.render(title=title)
fig.text(
0.03, 0.805 - row_index * 0.31, gate,
rotation=90, va="center", ha="center", fontweight="bold",
)
fig.suptitle(
"Bloch-sphere gate order: X, then H, then Z",
fontsize=19, fontweight="bold", y=0.995,
)
fig.text(
0.5, 0.018,
r"$|+\rangle=(|0\rangle+|1\rangle)/\sqrt{2}$"
r" and $|-\rangle=(|0\rangle-|1\rangle)/\sqrt{2}$",
ha="center", fontsize=13,
)
fig.tight_layout(rect=(0.055, 0.05, 1, 0.975), h_pad=1.4)
output = Path("bloch-sphere-x-h-z-gates.png")
fig.savefig(output, dpi=220, bbox_inches="tight", facecolor="white")
print(output)
Verification built in: the assertions stop the program unless X maps |0⟩ to |1⟩, H maps |0⟩ to |+⟩, and Z maps |+⟩ to |−⟩.
Leave a Reply