Chapter 2: Fundamentals of Quantum Computation#
This chapter reviews the basic concepts of quantum computing needed for the rest of the notes. We define qubits and quantum states using Dirac notation and the Bloch sphere representation. Elementary quantum gates (Pauli rotations, Hadamard, phase gate, CNOT) and universal gate sets are introduced, along with quantum circuits and circuit diagrams. Key principles such as superposition and entanglement are explained. Finally, we cover measurement postulates, decoherence, and simple quantum protocols (like teleportation and superdense coding). These protocols exemplify how quantum information processing differs fundamentally from classical computing.
# Put every BookPrograms/chapter*/ and BookPrograms/common/ on sys.path
import sys, pathlib
root = pathlib.Path.cwd().resolve()
while not (root / 'BookPrograms').is_dir() and root.parent != root:
root = root.parent
sys.path[:0] = sorted(str(p) for p in (root / 'BookPrograms').iterdir() if p.is_dir())
import numpy as np
Quantum computing in a nutshell#
A gate-based quantum computer is a controllable quantum system used to prepare states, apply operations and sample measurement outcomes. For many-body physics the central question is how these operations can reveal an energy, a correlation function or a dynamical observable. This chapter develops the finite-dimensional mathematics needed to make that question precise. We begin with an overview of the ideal circuit model, then derive its ingredients: linear algebra, qubits, measurements, density matrices, entanglement and gates. The communication protocols put those ingredients together; the final two-level calculation connects them to the many-body algorithms of later chapters. Readers unfamiliar with the notation can return to this overview after Section Quantum gates.
The ideal gate model uses \(N\) two-level systems, called quantum bits or qubits, with orthonormal states \(\vert0\rangle\) and \(\vert1\rangle\). We label qubits \(a=0,\ldots,N-1\), with qubit \(0\) the leftmost tensor factor and the most significant bit in a basis-state index. A general pure register state is
Here a bit string denotes a tensor product, defined in Section Tensor products. Mixed states require density matrices (Section Density matrices). Storing the unrestricted pure-state vector classically requires \(2^N\) complex amplitudes: at 16 bytes per amplitude, \(N=50\) requires \(2^{54}\) bytes, or 16 PiB. This is a cost of that representation, not a proof that every 50-qubit calculation is difficult. Product states and other structured states can admit compact descriptions.
We usually initialize the register in \(\vert0\cdots0\rangle\). Between measurements an ideal closed system evolves unitarily: \(\vert\Psi^{(n+1)}\rangle=U^{(n)}\vert\Psi^{(n)}\rangle\), where
The symbol \(\mathcal{T}\) denotes time ordering, and \(\hbar=1\) throughout the book unless stated otherwise. A gate is a specified unitary operation. At the algorithmic level we choose gates; their physical implementation requires suitable control Hamiltonians. Single- and two-qubit gates provide a useful elementary set. A single-qubit gate on qubit \(a\) acts as
and a two-qubit gate on distinct qubits \(a,b\) acts as
The tensor factors of \(U\) are ordered as \((a,b)\). The second equation is written for \(a<b\); for another ordering the factors and indices must be reordered consistently. Universality, discussed in Section Universal gate sets, concerns which operations such gates can approximate, not whether every useful operation has a short circuit.
An ideal computational-basis measurement of qubit \(a\) returns \(\alpha\in\{0,1\}\) with probability
Conditional on an outcome with \(P_\alpha>0\), the register becomes
These equations specify pure-state preparation, ideal unitary gates and ideal projective readout. Noise, discarded outcomes and unobserved subsystems require the density-matrix description developed below. Measurement returns samples, not an accessible list of amplitudes: measuring the whole register once gives \(N\) classical bits. Preparing an arbitrary amplitude vector is also generally expensive. State preparation and readout therefore both belong in an algorithm’s resource accounting, often called its input/output bottleneck.
Circuit size imposes a separate restriction. For a fixed arrangement of one- and two-qubit gates with a bounded number of continuous parameters per gate, \(D\) layers contain \(\bigO(DN)\) parameters. Their image in state space has at most that many real dimensions; it need not be a linear subspace or a smooth manifold everywhere. In contrast, a normalized \(N\)-qubit pure state modulo global phase has
real parameters. A fixed family with polynomial depth cannot cover all pure states. This does not make the remaining states forever inaccessible: sufficiently long circuits can approximate them, and the physically relevant states may lie in a much smaller family. Finite discrete gate sets require an approximation argument rather than this continuous parameter count.
The useful question is whether a circuit family can prepare the states needed for a particular task, with an advantage over suitable classical methods. Its trainability is another issue. In variational algorithms, barren plateaus refer to gradients that typically become exponentially small with system size under specified assumptions about the circuit, cost function and initialization; noise can also produce such behavior. This is not a consequence of parameter counting alone. We return to these issues in Chapter 6; Ref. [Larocca2025] surveys them.
We now derive the mathematical ingredients. Standard references are Nielsen and Chuang [NielsenChuang], Scherer [Scherer2019] and, for readers who prefer to learn by programming, Hundt [Hundt2022]. The linear algebra needed here is included explicitly; Appendix B supplies the numerical background: norms and condition numbers, the classical algorithms for linear systems and eigenvalue problems, and the singular value decomposition.
Linear algebra in Dirac notation#
Vectors, inner and outer products#
When written in components, vectors and matrices are denoted in boldface, with lower-case letters for vectors and upper-case letters for matrices. Kets, gates and observables are also written in the usual Dirac notation. All spaces in this chapter are finite-dimensional. A vector with \(n\) complex components is written as
where the dagger denotes the Hermitian conjugate, the complex conjugate of the transpose. We start counting from zero, so that the first component \(x_0\) multiplies the basis state \(\vert 0\rangle\) below and the index of a component agrees with the integer encoded by a bit string of qubits.
Throughout the book we use Dirac’s bra-ket notation and replace the boldfaced vector by a ket and its Hermitian conjugate by a bra,
The inner product of two vectors of the same length is
so that \(\langle x\vert x\rangle=\sum_i|x_i|^2\) is real and non-negative, while in general
As an example, for \(\vert x\rangle = \begin{bmatrix} 1-i & 2+i\end{bmatrix}^T\)
we find \(\langle x\vert x\rangle = (1+i)(1-i)+(2-i)(2+i) = 7\), and the
normalized vector is \(\vert x\rangle/\sqrt{7}\). For
\(\vert x\rangle = \begin{bmatrix} -1 & 2i & 1\end{bmatrix}^T\) and
\(\vert y\rangle = \begin{bmatrix} 1 & 0 & i\end{bmatrix}^T\) we get
\(\langle x\vert y\rangle = -1+i\) but \(\langle y\vert x\rangle = -1-i\), as
Eq. (2.11) demands. The program dirac_algebra.py
reproduces these numbers.
The outer product of two vectors is the matrix
with elements \(x_iy_j^*\). Outer products are the building blocks of projection operators and of density matrices, and they play a central role in all of quantum mechanics.
Hermitian, unitary and normal matrices#
A general \(n\times n\) matrix \(\matr{A}\) has elements \(a_{ij}\) with the row index \(i\) and column index \(j\) both starting from zero; matrix-vector and matrix-matrix products are \(y_i = \sum_j a_{ij}x_j\) and \(c_{ij}=\sum_k a_{ik}b_{kj}\). Three classes of matrices dominate quantum mechanics:
Hermitian (self-adjoint) matrices, \(\matr{A}=\matr{A}^{\dagger}\), that is \(a_{ij}=a_{ji}^*\). Observables are represented by Hermitian operators; their eigenvalues are real and their eigenvectors can be chosen orthonormal.
Unitary matrices, \(\matr{U}\matr{U}^{\dagger}=\matr{U}^{\dagger}\matr{U}=\matr{I}\), so that \(\matr{U}^{-1}=\matr{U}^{\dagger}\). The time evolution of a closed quantum system, and hence every gate, is unitary.
Normal matrices, which commute with their adjoint, \([\matr{A},\matr{A}^{\dagger}]=0\). A matrix is normal if and only if it is diagonalizable by a unitary transformation. Hermitian and unitary matrices are both normal.
For real matrices, Hermitian reduces to symmetric, \(\matr{A}=\matr{A}^T\), and unitary reduces to orthogonal, \(\matr{A}^T\matr{A}=\matr{I}\). Normality is a separate property, \(\matr{A}\matr{A}^T=\matr{A}^T\matr{A}\) in the real case; being real does not imply being normal.
Unitary transformations are important because they preserve inner products. If \(\vert \phi_i\rangle=\matr{U}\vert \psi_i\rangle\) for two states \(\vert\psi_i\rangle\) and \(\vert\psi_j\rangle\), then
so norms and orthogonality are preserved: unitary transformations are rotations in state space. Since the inverse of a unitary matrix is its Hermitian conjugate, every unitary transformation is reversible. This is why the ideal closed-system evolution is reversible. Measurement and discarding an unobserved subsystem can give an effectively irreversible description of the system we retain; both require more than a unitary acting on that system alone.
Computational basis states, projectors and superposition#
Consider a two-level system whose two states are represented by the state vectors \(\vert\phi_0\rangle\) and \(\vert\phi_1\rangle\). These could be selected degrees of freedom of a single particle (fermion or boson), or effective many-body degrees of freedom. In actual realizations of quantum computers one searches for candidate systems where two suitable states can be isolated and coherently controlled; in many-body physics, where the number of degrees of freedom explodes, one is similarly always looking for effective ways to reduce the dimensionality to something a given many-body method can handle. We relabel the two states as the orthonormal computational basis
with \(\langle 0\vert 1\rangle=0\) and \(\langle 0\vert 0\rangle=\langle 1\vert 1\rangle=1\). With these two states we can write the identity operator as a sum of outer products, the completeness relation
and define the projection operators
They are idempotent, \(\matr{P}^2=\matr{P}\) and \(\matr{Q}^2=\matr{Q}\), they commute and satisfy \(\matr{P}\matr{Q}=0\), and their determinants vanish, so they cannot be used as unitary transformations. They do however play a central role in defining measurements, and in the many-body chapters in defining effective model spaces.
The quantum mechanical counterpart of a classical bit, which takes only the values \(0\) or \(1\), is a qubit in a general superposition of the two computational basis states,
where the complex coefficients \(\alpha = \langle 0 \vert \psi \rangle\) and \(\beta =\langle 1 \vert \psi\rangle\) are the overlaps of the state with the basis states. Normalization requires
Acting with the projection operators on \(\vert\psi\rangle\) we obtain
that is, \(\matr{P}\) projects out the \(\vert 0\rangle\) component of the state and \(\matr{Q}\) the \(\vert 1\rangle\) component. The outer product of the state with itself,
is the density matrix of the state, with unit trace \(\mathrm{Tr}\,\rho=|\alpha|^2+|\beta|^2=1\). We return to density matrices in Section Density matrices.
The Pauli matrices#
The Pauli matrices
play a role in quantum computing that is hard to overstate: they are the simplest gates, every single-qubit gate is generated by them, every operator on \(N\) qubits can be expanded in tensor products of them, and, after the mappings of Section From fermions to qubits, every many-body Hamiltonian becomes a weighted sum of such tensor products. In the physics literature they are often written \(\sigma_x,\sigma_y,\sigma_z\); we use both notations, with \(X,Y,Z\) preferred whenever we talk about gates. The Pauli matrices are Hermitian and unitary at the same time, they are involutory,
their determinants equal \(-1\), and they obey the commutation and anticommutation relations
Here \([A,B]=AB-BA\) and \(\{A,B\}=AB+BA\). These identities can be summarized as \(XY=iZ\) and cyclic permutations. Acting with \(X\) on the computational basis states gives
a spin flip, which is the quantum analogue of the classical NOT gate. On a superposition, \(X(\alpha\vert 0\rangle+\beta\vert 1\rangle) = \beta\vert 0\rangle+\alpha\vert 1\rangle\). The matrix \(Z\) leaves \(\vert 0\rangle\) unchanged and multiplies \(\vert 1\rangle\) by \(-1\), a relative phase shift, and \(Y=iXZ\) combines the two. The computational basis is the eigenbasis of \(Z\) with eigenvalues \(\pm 1\); the eigenbases of \(X\) and \(Y\) are the states \(\vert\pm\rangle\) and \(\vert\pm i\rangle\) introduced in Section Qubits and the Bloch sphere.
Two further \(2\times 2\) matrices appear again and again. The Hadamard matrix
creates superpositions from the basis states,
and the phase matrix
multiplies the \(\vert 1\rangle\) component by \(i\). Note that \(H=(X+Z)/\sqrt{2}\) is Hermitian and unitary, so \(H^2=\matr{I}\), while \(S^2=Z\). The identity \(HZH=X\), which follows from Eq. (2.23), is the reason why a measurement in the eigenbasis of \(X\) can be performed by first applying a Hadamard gate and then measuring in the computational basis, see Section Measuring one qubit of a register and in other bases. We do not use a special symbol to distinguish the Hadamard gate from a Hamiltonian; the context, and in the many-body chapters the hat on \(\op{H}\), makes the meaning clear.
Tensor products#
Consider two vectors of length two, \(\vert x \rangle = \begin{bmatrix} x_0 & x_1 \end{bmatrix}^T\) and \(\vert y \rangle = \begin{bmatrix} y_0 & y_1 \end{bmatrix}^T\). Their tensor product (also called Kronecker product) is the vector of length four
Applied to the computational basis states this gives the two-qubit basis
where, for instance, \(\vert 01\rangle = \vert 0\rangle\otimes\vert 1\rangle\). The bit string labelling a basis state, read as a binary number with the first qubit as the most significant bit, is the index of the single non-zero component: \(\vert 00\rangle=\vert 0\rangle\), \(\vert 01\rangle=\vert 1\rangle\), \(\vert 10\rangle=\vert 2\rangle\), \(\vert 11\rangle=\vert 3\rangle\) in the decimal labelling that is sometimes convenient. The construction extends to any number of qubits, \(\vert 000\rangle = \vert 0\rangle\otimes\vert 0\rangle\otimes\vert 0\rangle\) being a vector of length eight with a one in the first position, and in general \(N\) qubits span a space of dimension \(2^N\). This is the origin of Eq. (2.1), and we take care in the programs of this chapter to store the amplitudes \(\Psi_{i_0\cdots i_{N-1}}\) in exactly this order. Thus the integer index is \(j=\sum_{a=0}^{N-1}i_a2^{N-1-a}\).
The tensor product of two \(2\times 2\) matrices is the \(4\times 4\) matrix
and the essential rule for computing with tensor products is
A single-qubit gate \(U\) acting on qubit \(a\) of an \(N\)-qubit register is the operator \(\matr{I}\otimes\cdots\otimes U\otimes\cdots\otimes\matr{I}\) with \(U\) in position \(a\), and Eq. (2.3) is nothing but this operator written out in components.
Spectral decomposition of Hermitian operators#
Let \(\matr{A}\) be a Hermitian operator on a Hilbert space of dimension \(n\) and let \(\vert\psi\rangle\) be an eigenvector with eigenvalue \(\lambda\), \(\matr{A}\vert\psi\rangle = \lambda\vert\psi\rangle\). The equation \((\matr{A}-\lambda\matr{I})\vert\psi\rangle = 0\) has a non-trivial solution only if \(\operatorname{det}(\matr{A}-\lambda\matr{I})=0\), the characteristic equation. For a Hermitian matrix the \(n\) eigenvalues \(\lambda_i\) are real and the eigenvectors \(\vert i\rangle\), \(i=0,\dots,n-1\), can be chosen to form an orthonormal basis, including within degenerate eigenspaces. Expanding an arbitrary state in this eigenbasis, \(\vert \psi \rangle = \sum_{i}\alpha_i\vert i\rangle\) with \(\sum_i|\alpha_i|^2=1\), and acting with \(\matr{A}\) gives
Since the projector \(\matr{P}_j=\vert j\rangle\langle j\vert\) extracts the component \(\matr{P}_j\vert\psi\rangle = \alpha_j\vert j\rangle\), we can rewrite this as \(\matr{A}\vert\psi\rangle = \sum_i\lambda_i\matr{P}_i\vert\psi\rangle\), and because the state was arbitrary we conclude that
This is the spectral decomposition of a Hermitian (more generally, of a normal) operator. The projectors are orthogonal, \(\matr{P}_i\matr{P}_j=\delta_{ij}\matr{P}_i\), and complete, \(\sum_i\matr{P}_i=\matr{I}\). Two consequences will be used constantly. First, any function of the operator is defined by acting on the eigenvalues,
which is how we compute \(e^{-iHt}\) for a Hamiltonian \(H\) in Section From Hamiltonians to gates and \(\rho\log\rho\) for a density matrix in Section Entropy and entanglement entropy. Second, the spectral decomposition of an observable specifies the outcome probabilities for its ideal projective measurement. If eigenvalues are degenerate, we group their rank-one projectors into the projector onto the full eigenspace. The post-measurement state also depends on the measurement implementation; we use the Lüders update in Section Measurements.
As a two-dimensional example, let \(\vert\psi_a\rangle = \alpha_0\vert 0\rangle+\alpha_1\vert 1\rangle\) and \(\vert\psi_b\rangle = \beta_0\vert 0\rangle+\beta_1\vert 1\rangle\) be the eigenstates of a Hermitian \(2\times 2\) matrix with eigenvalues \(\lambda_a\) and \(\lambda_b\). Then
For the Pauli matrix \(Z\) the eigenstates are the computational basis states
themselves and \(Z = \matr{P}-\matr{Q}\) with the projectors of
Eq. (2.16); for \(X\) they are the Hadamard-rotated states of
Eq. (2.26) and
\(X = \vert +\rangle\langle +\vert - \vert -\rangle\langle -\vert\). The
program dirac_algebra.py performs the decomposition numerically
for a complex Hermitian matrix and verifies Eq. (2.34) for the
exponential. How the decomposition is computed for the matrices of
many-body physics, and at what cost, is the subject of
Sections Dense diagonalization and The power method and Krylov subspaces.
Qubits and the Bloch sphere#
A normalized qubit state \(\vert \psi \rangle = \alpha \vert 0 \rangle +\beta\vert 1\rangle\) is specified by two complex numbers subject to one real constraint, \(|\alpha|^2+|\beta|^2=1\), leaving three real parameters. One more is unobservable: multiplying the whole state by a global phase \(e^{i\gamma}\) leaves its density matrix, probabilities and expectation values unchanged. An overlap with a fixed vector acquires that phase, \(\langle\phi|e^{i\gamma}\psi\rangle=e^{i\gamma}\langle\phi|\psi\rangle\), but its absolute square is unchanged. Thus \(\vert\psi\rangle\) and \(e^{i\gamma}\vert\psi\rangle\) describe the same physical state. Relative phases between components, in contrast, affect interference. We can therefore choose \(\alpha\) real and non-negative and write
The two angles are the polar and azimuthal angles of a point on the unit sphere, the Bloch sphere shown in Fig. 2.1. The north pole \(\theta=0\) is \(\vert 0\rangle\), the south pole \(\theta=\pi\) is \(\vert 1\rangle\), and every superposition with equal weights lies on the equator, where \(\phi\) measures the relative phase between the two amplitudes. At either pole the azimuth is undefined; assigning \(\phi=0\) there is a convention, not a physical restriction. The half angle \(\theta/2\) in Eq. (2.36) is what makes orthogonal states, such as \(\vert 0\rangle\) and \(\vert 1\rangle\), antipodal on the sphere rather than perpendicular.

Figure 2.1: The Bloch sphere. (a) The six eigenstates of the Pauli matrices sit at the ends of the three axes, and a general state \(\vert\psi\rangle\) with \(\theta=2.0\) and \(\phi=0.7\) is drawn as a vector. (b) The trajectory traced by a spin precessing in a magnetic field along \(z\) (Larmor precession, Section From Hamiltonians to gates), a rotation \(R_x(\theta)\) about the \(x\) axis starting from \(\vert 0\rangle\), and a subsequent rotation \(R_y(\phi)\) about the \(y\) axis; the two-angle family \(R_y(\phi)R_x(\theta)\vert 0\rangle\) is the variational ansatz of Section A first Hamiltonian: the two-level system. Produced by bloch_sphere.py.
The Cartesian coordinates of the point are the expectation values of the three Pauli matrices, the Bloch vector
as one verifies by inserting Eq. (2.36). For a pure state \(|\vec{r}|=1\). We shall see in Section Density matrices that mixed states fill the interior of the ball, and that the density matrix of a qubit can be written in terms of its Bloch vector alone. Table 2.1 lists the six eigenstates of the Pauli matrices together with their Bloch angles. The states \(\vert\pm\rangle = (\vert 0\rangle\pm\vert 1\rangle)/\sqrt{2}\) are the \(X\) eigenstates on the \(\pm x\) axis, the states \(\vert\pm i\rangle = (\vert 0\rangle\pm i\vert 1\rangle)/\sqrt{2}\) are the \(Y\) eigenstates on the \(\pm y\) axis, and \(\vert 0\rangle,\vert 1\rangle\) are the \(Z\) eigenstates on the \(\pm z\) axis. Every unitary operation on one qubit is a rotation of the Bloch sphere, as we show in Section Single-qubit gates; the Hadamard gate, for example, is a rotation by \(\pi\) about the axis \((\uvec{x}+\uvec{z})/\sqrt{2}\), which maps the \(z\) axis onto the \(x\) axis and thereby \(\vert 0\rangle\) onto \(\vert +\rangle\).
state |
operator |
eigenvalue |
\(\theta\) |
\(\phi\) |
Bloch vector |
|---|---|---|---|---|---|
\(\vert 0\rangle\) |
\(Z\) |
\(+1\) |
\(0\) |
\(0\) |
\((0,0,1)\) |
\(\vert 1\rangle\) |
\(Z\) |
\(-1\) |
\(\pi\) |
\(0\) |
\((0,0,-1)\) |
\(\vert +\rangle = (\vert 0\rangle+\vert 1\rangle)/\sqrt{2}\) |
\(X\) |
\(+1\) |
\(\pi/2\) |
\(0\) |
\((1,0,0)\) |
\(\vert -\rangle = (\vert 0\rangle-\vert 1\rangle)/\sqrt{2}\) |
\(X\) |
\(-1\) |
\(\pi/2\) |
\(\pi\) |
\((-1,0,0)\) |
\(\vert +i\rangle = (\vert 0\rangle+i\vert 1\rangle)/\sqrt{2}\) |
\(Y\) |
\(+1\) |
\(\pi/2\) |
\(\pi/2\) |
\((0,1,0)\) |
\(\vert -i\rangle = (\vert 0\rangle-i\vert 1\rangle)/\sqrt{2}\) |
\(Y\) |
\(-1\) |
\(\pi/2\) |
\(3\pi/2\) |
\((0,-1,0)\) |
Table 2.1: Eigenstates of the Pauli matrices, their eigenvalues, Bloch angles
and Bloch vectors. Produced by bloch_sphere.py.
The conversion between amplitudes and Bloch angles is a few lines of
code. This version makes the convention at the poles explicit and
rejects a zero input vector. It uses the gate matrices of
gates.py in the folder LectureMaterial/BookPrograms/common/; put that
directory on the Python module search path before running the listings
in this chapter.
import numpy as np
from gates import X, Y, Z
def bloch_state(theta, phi):
return np.array([np.cos(theta / 2),
np.exp(1j * phi) * np.sin(theta / 2)])
def bloch_angles(psi):
psi = np.asarray(psi, dtype=complex)
if psi.shape != (2,) or not np.all(np.isfinite(psi)):
raise ValueError("Expected two finite amplitudes")
norm = np.linalg.norm(psi)
if norm == 0:
raise ValueError("A state vector must be nonzero")
a, b = psi / norm
theta = 2 * np.arctan2(abs(b), abs(a))
phi = 0.0 if min(abs(a), abs(b)) < 1e-12 else np.angle(b * a.conjugate())
return theta, phi % (2 * np.pi)
def bloch_vector(psi):
psi = np.asarray(psi, dtype=complex)
return np.array([np.vdot(psi, P @ psi).real for P in (X, Y, Z)])
psi = bloch_state(2.0, 0.7)
print(bloch_vector(psi), bloch_angles(np.exp(0.3j) * psi))
[ 0.69546903 0.58578549 -0.41614684] (np.float64(2.0), np.float64(0.6999999999999998))
The inverse conversion normalizes its input; bloch_vector
assumes a normalized state. Away from the poles a global phase changes
neither recovered angle. At a pole only the Bloch point, not its
azimuthal coordinate, is physically defined.
Measurements#
The projective measurement postulate#
We first consider an ideal projective measurement. Let \(\matr{A}=\sum_i\lambda_i\matr{P}_i\), where now \(i\) labels distinct eigenvalues and \(\matr{P}_i\) projects onto the entire eigenspace with eigenvalue \(\lambda_i\). Thus \(\matr{P}_i^\dagger=\matr{P}_i\), \(\matr{P}_i\matr{P}_j=\delta_{ij}\matr{P}_i\) and \(\sum_i\matr{P}_i=\matr{I}\). On a normalized state \(\vert\psi\rangle\), the outcome probability is
This is the Born rule; completeness gives \(\sum_i p_i=1\). For an outcome with \(p_i>0\), the ideal Lüders update is
It preserves coherences within a degenerate eigenspace. Resolving the individual basis states inside that eigenspace would be a finer measurement and can disturb the state further. With no intervening evolution or disturbance, repeating the same ideal projective measurement returns \(\lambda_i\) with certainty. The expectation value is
For a single qubit measured in the computational basis, the projectors are \(\matr{P}_0=\vert 0\rangle\langle 0\vert\) and \(\matr{P}_1=\vert 1\rangle\langle 1\vert\), and for the state \(\vert\psi\rangle=\alpha\vert 0\rangle+\beta\vert 1\rangle\) we obtain
with post-measurement states
for outcomes of nonzero probability; these are the basis states up to an irrelevant global phase. The measured observable is \(Z=\matr{P}_0-\matr{P}_1\), with \(\langle Z\rangle = |\alpha|^2-|\beta|^2\), the \(z\) component of the Bloch vector. Since a measurement can only yield one of the two basis states, the amplitudes \(\alpha\) and \(\beta\) are never observed directly: the only way to learn about them is to prepare the same state many times and to collect statistics, a point we return to in Section Statistics of repeated measurements.
It is useful to rewrite the Born rule as a trace. Using the cyclic property \(\mathrm{Tr}(\matr{A}\matr{B}\matr{C})=\mathrm{Tr}(\matr{C}\matr{A}\matr{B})\) and \(\mathrm{Tr}(\matr{A}\vert\psi\rangle\langle\psi\vert) = \langle\psi\vert\matr{A}\vert\psi\rangle\),
with \(\rho=\vert\psi\rangle\langle\psi\vert\) the density matrix of Eq. (2.20). For the qubit,
whose trace is \(|\alpha|^2\), in agreement with Eq. (2.41). The trace form is the one that generalizes to mixed states in Section Density matrices.
Measuring one qubit of a register and in other bases#
For an \(N\)-qubit state, a measurement of qubit \(a\) alone in the computational basis corresponds to the projectors \(\matr{P}^{(a)}_\alpha = \matr{I}\otimes\cdots\otimes\vert\alpha\rangle\langle\alpha\vert\otimes\cdots\otimes\matr{I}\), which act as the identity on all other qubits. Inserting them into the Born rule gives Eq. (2.5), the marginal probability obtained by summing \(|\Psi|^2\) over the values of the unmeasured qubits, and the collapse rule Eq. (2.6), which sets to zero every amplitude incompatible with the outcome and renormalizes the rest. The unmeasured qubits are in general left in a state that depends on the outcome, the mechanism behind the correlations of entangled states discussed in Section Two qubits and entanglement.
A measurement in a basis other than the computational one is performed by rotating the basis first. To measure \(X\), whose eigenstates are \(\vert\pm\rangle\), we note that \(H\vert\pm\rangle = \vert 0\rangle,\vert 1\rangle\) and therefore
that is, we apply a Hadamard gate and then measure in the computational basis. This is the operational content of the identity \(X=HZH\). In the same way \(Y\) is measured by applying \(S^{\dagger}\) followed by \(H\), since \((HS^\dagger)^\dagger Z(HS^\dagger)=Y\). Computational-basis readout is the convention of our circuit model, not a restriction on every physical measurement apparatus.
For a Pauli string \(P=\bigotimes_a P_a\), measure each non-identity factor in its eigenbasis. One shot returns eigenvalues \(s_a=\pm1\); the product \(s=\prod_{a:P_a\ne I}s_a\) is the measured value of \(P\). Thus \(\langle Z_0Z_1\rangle\) requires joint outcomes of both qubits, not just their individual averages. For example, \(\vert\Phi^+\rangle\) and \(\vert\Psi^+\rangle\) have identical one-qubit marginals, but their \(Z_0Z_1\) expectations are \(+1\) and \(-1\). Compatible strings may share measurement settings; Chapter 6 develops that accounting.
Statistics of repeated measurements#
A computational-basis measurement of one qubit returns one bit and generally changes its state. It need not destroy the physical system, and an eigenstate is unchanged by its ideal projective measurement. To estimate \(p=\mathrm{Prob}(0)=|\alpha|^2\), we independently prepare the same input and measure it \(N_s\) times, called \(N_s\) shots. The number of zero outcomes is binomially distributed under these assumptions. Its fraction \(\hat p\) has standard deviation
which decreases only as \(1/\sqrt{N_s}\): to gain one more decimal digit one needs a hundred times more shots. Figure 2.2 shows five independent experiments on a qubit with \(|\alpha|^2=0.3\). This shot noise is the sampling cost of this independent-measurement estimator. For a Pauli observable with \(\mu=\langle P\rangle\), a shot has value \(\pm1\) and variance \(1-\mu^2\), so the sample mean obeys
For \(P=Z\) this follows also from \(\widehat{\langle Z\rangle}=2\hat p-1\). These formulas describe sampling fluctuations, not systematic device errors. The shaded band is centered on the known true probability; it is not a confidence interval inferred from a particular sample. Other quantum estimation procedures can use different resources and precision scaling. Independent sampling is the procedure relevant to the variational measurements discussed here.

Figure 2.2: Estimate of \(\mathrm{Prob}(0)\) for the qubit \(\vert\psi\rangle = \sqrt{0.3}\vert 0\rangle+\sqrt{0.7}\,e^{0.4i}\vert 1\rangle\) as a function of the number of shots, for five independent sequences of measurements. The shaded band is the one-standard-deviation interval of Eq. (2.46). Produced by measurement.py.
The state-vector simulator implements these rules directly. The shared
StateVector class stores \(2^N\) amplitudes and applies small gates
by tensor contraction. The following standalone measurement routine makes
the normalization and nonzero-probability conditions explicit; qubit
\(0\) is the leftmost tensor factor. It returns a new vector.
import numpy as np
def measure_qubit(psi, qubit, rng=None, outcome=None):
"""Measure a qubit (0 is leftmost); return a new collapsed vector."""
psi = np.asarray(psi, dtype=complex).reshape(-1)
dim = psi.size
if dim < 2 or dim & (dim - 1):
raise ValueError("The dimension must be a power of two")
n = dim.bit_length() - 1
if (not isinstance(qubit, (int, np.integer))
or not 0 <= qubit < n):
raise ValueError("Invalid qubit index")
if not np.all(np.isfinite(psi)) or not np.isclose(np.vdot(psi, psi), 1):
raise ValueError("Expected a normalized finite state")
tensor = psi.reshape((2,) * n).copy()
axes = tuple(a for a in range(n) if a != qubit)
p = (abs(tensor) ** 2).sum(axis=axes)
if outcome is None:
rng = np.random.default_rng() if rng is None else rng
outcome = int(rng.choice(2, p=p / p.sum()))
if (not isinstance(outcome, (int, np.integer))
or outcome not in (0, 1) or p[outcome] <= 0):
raise ValueError("Invalid or impossible outcome")
discard = [slice(None)] * n
discard[qubit] = 1 - outcome
tensor[tuple(discard)] = 0
return outcome, float(p[outcome]), tensor.reshape(dim) / np.sqrt(p[outcome])
bell = np.array([1, 0, 0, 1], dtype=complex) / np.sqrt(2)
print(measure_qubit(bell, 0, outcome=1))
(1, 0.4999999999999999, array([0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j]))
The classical simulator can inspect the full vector because it stores it explicitly, at exponential memory cost. A processor instead stores the quantum state physically; extracting information requires a specified measurement, possibly after changing basis. Repeatedly measuring an already collapsed register is not the same experiment as independently preparing the original state for each shot.
Density matrices#
Pure and mixed states#
A normalized state vector specifies a pure state. This is a mathematical property of the state, not a statement that an observer knows its amplitudes: an unknown state may still be pure, as in teleportation. A density matrix describes both pure and mixed states. A mixture can arise from classical randomization of preparations or from retaining only part of an entangled system. In the second case the mixedness is not merely ignorance about a pre-existing pure state of the subsystem.
Consider the ensemble \(\{p_i,\vert\psi_i\rangle\}\) and a measurement with projectors \(\matr{P}_x\). The probability of outcome \(x\) is the average of the Born rule (2.43) over the ensemble,
where we have defined the density matrix or density operator
Every measurable quantity depends on the ensemble only through \(\rho\), so two ensembles with the same density matrix are indistinguishable by measurements on the system alone when no preparation record is available. An external record or correlated system can distinguish the preparations. From the definition, \(\rho\) is Hermitian, positive semidefinite (all its eigenvalues are non-negative) and has unit trace,
and conversely every matrix with these three properties is a valid density matrix. By the spectral decomposition there is always an orthonormal basis \(\{\vert b_i\rangle\}\) in which
so that any density matrix can be viewed as an ensemble of orthogonal pure states with the eigenvalues as probabilities. A state is pure if and only if one eigenvalue equals one and the others vanish, which can be tested without diagonalizing:
The quantity \(\mathrm{Tr}(\rho^2)\) is called the purity; it is at most one, and its smallest value \(1/d\) is attained by the maximally mixed state \(\rho=\matr{I}/d\) of a \(d\)-dimensional system. It gives uniform probabilities in every orthonormal measurement basis, but does not identify a unique preparation ensemble. The expectation value of an observable and the post-measurement state after outcome \(x\) are
where the conditional state is defined only for \(\mathrm{Tr}(\matr{P}_x\rho)>0\). If the outcome is not retained, the state is instead \(\rho'=\sum_x\matr{P}_x\rho\matr{P}_x\). Under a unitary transformation, in particular for a time-independent closed-system Hamiltonian \(H\),
The trace and the eigenvalues, and therefore the purity, are invariant under unitary transformations: \(\mathrm{Tr}(U\rho U^{\dagger})=\mathrm{Tr}(U^{\dagger}U\rho)=1\). Unitary evolution can never turn a mixed state into a pure one, nor the reverse.
For a single qubit, the four matrices \(\matr{I},X,Y,Z\) form a basis of the \(2\times 2\) Hermitian matrices, and the conditions (2.50) imply that every density matrix can be written as
where \(\vec{r}=(\mathrm{Tr}(\rho X),\mathrm{Tr}(\rho Y),\mathrm{Tr}(\rho Z))\) is the Bloch vector of Eq. (2.37). The eigenvalues of Eq. (2.55) are \((1\pm|\vec{r}|)/2\) and the purity is \((1+|\vec{r}|^2)/2\), so pure states lie on the surface of the Bloch sphere, mixed states fill its interior, and the maximally mixed state \(\rho=\matr{I}/2\) sits at the center. An equal mixture of \(\vert 0\rangle\) and \(\vert 1\rangle\) and an equal mixture of \(\vert +\rangle\) and \(\vert -\rangle\) both give \(\rho=\matr{I}/2\), a first illustration that different ensembles can be the same state. The superposition \((\vert 0\rangle+\vert 1\rangle)/\sqrt{2}\), on the other hand, has \(\rho=\frac{1}{2}\begin{bmatrix} 1 & 1\\ 1 & 1\end{bmatrix}\): the difference between the superposition and the mixture is entirely in the off-diagonal elements, the coherences, and it becomes visible when we measure \(X\) rather than \(Z\), since \(\langle X\rangle = 1\) for the superposition and \(0\) for the mixture.
Reduced density matrices and the partial trace#
The second, and for many-body physics the most important, source of mixed states is the description of a subsystem. Let a system be composed of two parts \(A\) and \(B\) with Hilbert space \(\mathcal{H}_A\otimes\mathcal{H}_B\) and density matrix \(\rho_{AB}\), and let \(\matr{O}_A\) be an observable acting on \(A\) alone, that is \(\matr{O}_A\otimes\matr{I}_B\) on the full space. Its expectation value can be written as \(\mathrm{Tr}_A(\rho_A\matr{O}_A)\) in terms of the reduced density matrix
where the sum runs over an orthonormal basis of \(B\). The operation \(\mathrm{Tr}_B\) is the partial trace over \(B\); on outer products it acts as
which together with linearity determines it completely. In components, for two qubits with \(\rho_{AB}\) indexed by the pairs \((a,b)\) and \((c,d)\), \((\rho_A)_{ac}=\sum_b \rho_{(ab),(cb)}\). The reduced density matrix is the complete description of \(A\) for an observer who has no access to \(B\), and it is in general mixed even when \(\rho_{AB}\) is pure. For a pure joint state, this local mixedness diagnoses entanglement. For a mixed joint state, it does not suffice, as we explain in Section Two qubits and entanglement.
The partial trace is a reshape followed by traces over paired row and column axes. Here is a standalone version for a qubit register; retained qubits remain in increasing order, consistent with our tensor convention.
import numpy as np
def partial_trace(rho, keep):
"""Trace out other qubits; retain the original factor order."""
rho = np.asarray(rho, dtype=complex)
if rho.ndim != 2:
raise ValueError("Expected a matrix")
dim = rho.shape[0]
if rho.shape != (dim, dim) or dim < 1 or dim & (dim - 1):
raise ValueError("Expected a square matrix of dimension 2**n")
n = dim.bit_length() - 1
keep = [int(keep)] if isinstance(keep, (int, np.integer)) else list(keep)
if (len(set(keep)) != len(keep)
or any(not isinstance(q, (int, np.integer))
or q not in range(n) for q in keep)):
raise ValueError("Invalid retained qubits")
keep = sorted(keep)
t = rho.reshape((2,) * (2 * n))
for k, q in enumerate(q for q in range(n) if q not in keep):
row = q - k
t = np.trace(t, axis1=row, axis2=row + n - k)
return t.reshape(2 ** len(keep), 2 ** len(keep))
bell = np.array([1, 0, 0, 1]) / np.sqrt(2)
rho = np.outer(bell, bell.conj())
print(partial_trace(rho, keep=0)) # identity / 2
[[0.5+0.j 0. +0.j]
[0. +0.j 0.5+0.j]]
The shared DensityMatrix class wraps the same contraction and
also implements purity, expectation values and entropy.
Decoherence#
When a qubit interacts with an environment, information can become stored in correlations with degrees of freedom that we do not observe. The reduced qubit dynamics can then be non-unitary. Decoherence is the loss of coherence in the relevant basis and is an important source of error in quantum hardware. It motivates quantum error correction [QCbook], which is outside the scope of these notes.
If the initial joint state is \(\rho\otimes\rho_E\), with a fixed environment state independent of \(\rho\), unitary evolution of the joint system followed by a partial trace defines a completely positive, trace-preserving quantum channel. Its Kraus representation is
For an initially pure environment \(\vert e_0\rangle\), insert a complete environment basis in the partial trace: \(E_k=(\matr{I}\otimes\langle k|)U(\matr{I}\otimes|e_0\rangle)\). Then unitarity of \(U\) gives the completeness relation in Eq. (2.58). A mixed environment gives an additional sum over its initial eigenstates. The map preserves positivity, including when applied to one part of an entangled state; this is the meaning of complete positivity. It need not preserve purity.
The phase-flip channel is a simple model of dephasing. A \(Z\) operation occurs with probability \(0\le p\le1\):
After \(n\) identical applications the coherence is multiplied by \((1-2p)^n\). It tends to zero for \(0<p<1\); \(p=0\) is the identity channel, while \(p=1\) is the unitary \(Z\) operation and causes no loss of purity. At \(p=1/2\) one application removes the off-diagonal elements. The limiting diagonal state is maximally mixed only for equal initial populations. For \(p>1/2\) the coherence also alternates in sign.
In the zero-temperature amplitude-damping model, \(\vert1\rangle\) decays to \(\vert0\rangle\) with probability \(0\le\gamma\le1\), with Kraus operators
Direct multiplication gives
For \(0<\gamma\le1\), repeated applications approach \(\vert0\rangle\). The purity need not initially fall: \(\vert0\rangle\) is already fixed, and a maximally mixed input becomes progressively purer. For the specific initial state \(\vert+\rangle\) used in Fig. 2.3, the purity does fall and then recover.
To connect discrete steps to relaxation times, a simple Markovian model uses \(\gamma(t)=1-e^{-t/T_1}\) and, for pure dephasing, \(p(t)=(1-e^{-t/T_\phi})/2\). If these independent processes act together, the off-diagonal elements decay as \(e^{-t/T_2}\), with
This relation assumes exponential relaxation in this model, not every possible noise process. Circuit duration relative to these times is one part of an error budget; gate errors, readout errors and error correction must also be considered.

Figure 2.3: Bloch-vector components, purity and von Neumann entropy of a qubit initially in \(\vert +\rangle\) under repeated application of the dephasing channel (left) and the amplitude-damping channel (right). For this initial state, dephasing drives it towards the maximally mixed state, while amplitude damping drives it towards \(\vert0\rangle\) through a mixed intermediate state. The probabilities per step are \(p=0.05\) and \(\gamma=0.08\), respectively. Produced by decoherence.py.
Two qubits and entanglement#
Bell states#
We now consider a system composed of two subsystems \(A\) and \(B\), each with computational basis states \(\vert 0\rangle\) and \(\vert 1\rangle\). The subsystems may be single particles, single qubits, or composite many-particle systems of a given symmetry; the results of this section are independent of what they represent. The computational basis of the composite system consists of the four product states of Eq. (2.29), \(\vert ab\rangle = \vert a\rangle_A\otimes\vert b\rangle_B\). From them we can build another orthonormal basis, the Bell states
They are normalized, for instance \(\langle\Phi^{+}\vert\Phi^{+}\rangle = \frac{1}{2}(\langle 00\vert 00\rangle+\langle 00\vert 11\rangle+\langle 11\vert 00\rangle+\langle 11\vert 11\rangle)=1\), and mutually orthogonal, for instance \(\langle \Phi^{+}\vert\Phi^{-}\rangle = \frac{1}{2}(1-0+0-1)=0\); four orthonormal vectors in a four-dimensional space form a basis. The corresponding density matrices, in the ordering \(\{\vert 00\rangle,\vert 01\rangle,\vert 10\rangle,\vert 11\rangle\}\), are
Measuring one of the qubits of a Bell state determines the state of the other. To see this, let us measure qubit \(A\) of \(\vert\Phi^+\rangle\) in the computational basis. The projectors on the two-qubit space are
and the Born rule gives
with the post-measurement states
The outcome on \(A\) is completely random, but once it is known the state of \(B\) is fixed, even though the measurement took place locally on \(A\). In the language of density matrices, \(p(k)=\mathrm{Tr}(\matr{P}_k\rho_{\Phi^+})=1/2\) and \(\rho^{(0)}=\vert 00\rangle\langle 00\vert\), \(\rho^{(1)}=\vert 11\rangle\langle 11\vert\): the two qubits are perfectly correlated. If the measurement result is not communicated, Bob must average over both outcomes and still assigns \(\rho_B=\matr{I}/2\). These correlations do not allow Alice to send a signal by choosing whether to measure.
Separable and entangled states#
A state like \(\vert 00\rangle = \vert 0\rangle_A\otimes\vert 0\rangle_B\) is a product state: each subsystem is in a definite pure state of its own, and a measurement on \(A\) tells us nothing we did not already know about \(B\). The Bell state \(\vert\Phi^+\rangle\) cannot be written in this form for any choice of single-qubit states, as one verifies by trying: \((\alpha\vert 0\rangle+\beta\vert 1\rangle)\otimes(\gamma\vert 0\rangle+\delta\vert 1\rangle)\) has the \(\vert 01\rangle\) component \(\alpha\delta\) and the \(\vert 10\rangle\) component \(\beta\gamma\), and both vanish only if \(\alpha\delta=\beta\gamma=0\), which is incompatible with non-zero \(\vert 00\rangle\) and \(\vert 11\rangle\) components \(\alpha\gamma\) and \(\beta\delta\). This leads to the definition: a pure bipartite state \(\vert\psi\rangle_{AB}\) is entangled if it cannot be written as a product state \(\vert\psi\rangle_A\otimes\vert\phi\rangle_B\), and separable otherwise. For mixed states the definition is that \(\rho_{AB}\) is separable if it is a convex combination of product density matrices,
and entangled otherwise.
For many-body physics we must distinguish a bipartition into controllable subsystems from the formal particle labels used to antisymmetrize identical fermions. Two spins localized at distinguishable sites \(A\) and \(B\) can realize the singlet \((\vert\uparrow\rangle_A\vert\downarrow\rangle_B- \vert\downarrow\rangle_A\vert\uparrow\rangle_B)/\sqrt2\) as a Bell pair. For identical electrons, the subsystem and the allowed operations must be specified before assigning such an interpretation.
For example, the independent-particle \(1s^2\) approximation to helium is
Its spin factor is a singlet, but the electron labels \(1,2\) are not independently addressable qubits. This wave function is a single Slater determinant. In the occupation basis of its two occupied spin orbitals it is simply \(\vert11\rangle\); other orbital or spatial partitions can have different entanglement. The exact helium ground state also contains spatial correlation beyond this independent-particle form. Thus antisymmetry alone is neither a certificate of computational hardness nor the same resource as an addressable Bell pair. Chapter 3 distinguishes these fermionic descriptions.
Reduced density matrices of entangled states#
The partial trace makes the distinction between product and entangled states quantitative. Take \(\mathrm{Tr}_B\) of \(\rho_{\Phi^+}\) term by term with Eq. (2.57):
so that
The same holds for all four Bell states: although the two-qubit state is pure, each qubit on its own is in the maximally mixed state, with purity \(1/2\) and a vanishing Bloch vector. All the information in a Bell state resides in the correlations between the qubits and none in the qubits themselves. For a product state, on the other hand, the reduced density matrices are pure (Exercise 2.6). Purity of the reduced density matrix is therefore a test for entanglement of a pure bipartite state, and its entropy, introduced next, a measure of it.
The Schmidt decomposition#
A systematic way to analyze a pure bipartite state is the Schmidt decomposition, which is an application of the singular value decomposition of Section The singular value decomposition. Any pure state can be expanded in product states of orthonormal bases \(\vert i\rangle_A\) and \(\vert j\rangle_B\),
where the coefficients form a \(d_A\times d_B\) matrix \(\matr{C}\). Its singular value decomposition \(\matr{C}=\matr{U}\matr{\Sigma}\matr{V}^{\dagger}\), with unitary \(\matr{U}\) and \(\matr{V}\) and a rectangular diagonal \(\matr{\Sigma}\) with non-negative singular values, gives \(c_{ij}=\sum_k u_{ik}\sigma_k v_{jk}^*\) and therefore
where the new bases \(\vert k\rangle_A\) and \(\vert k\rangle_B\) are orthonormal because \(\matr{U}\) and \(\matr{V}\) are unitary. The positive numbers retained in the last sum are the Schmidt coefficients; they satisfy \(\sum_k\sigma_k^2=1\). Their number \(r=\mathrm{rank}(\matr C)\) is the Schmidt rank, at most \(d_{\min}=\min(d_A,d_B)\). Zero singular values do not count towards the rank. Notice the complex conjugation in the \(B\) vectors: they are columns of \(\matr V^*\), or equivalently rows of \(\matr V^\dagger\) read as ket components. A state is a product state if and only if its Schmidt rank is one, and it is entangled if the rank is larger than one. Moreover, the reduced density matrices follow at once from Eq. (2.73),
so both have the same non-zero eigenvalues \(\sigma_k^2\). For the Bell
states \(\sigma_0=\sigma_1=1/\sqrt2\). In a fixed
\(d_A\times d_B\) space, a maximally entangled
pure state has rank \(d_{\min}\) and all \(d_{\min}\) coefficients equal
to \(1/\sqrt{d_{\min}}\). Equal coefficients on a smaller support only
maximize entanglement within that support. The program entanglement.py computes the Schmidt
decomposition of arbitrary two-qubit states with numpy.linalg.svd
and checks Eqs. (2.73) and (2.74).
Entropy and entanglement entropy#
Entropy quantifies uncertainty. For a classical random variable with outcomes \(x\) of probability \(p(x)\), the information content of a single outcome is \(-\log_2 p(x)\): a rare event carries much information, a certain one none. The average information, the Shannon entropy, is
measured in bits, with the convention \(0\log 0=0\). For a binary variable with probabilities \(p\) and \(1-p\) we get the binary entropy
shown in the left panel of Fig. 2.4: \(H_2(0)=H_2(1)=0\) when the outcome is certain, and \(H_2(1/2)=1\) bit when our knowledge is no better than a coin toss. The function is continuous, non-negative, additive for independent variables, and maximal for the uniform distribution, which is what one asks of a measure of ignorance.
The quantum counterpart replaces the probability distribution by the density matrix. The von Neumann entropy is
where \(\lambda_i\) are the eigenvalues of \(\rho\) and the second form follows from the spectral decomposition (2.51) and Eq. (2.34): in the eigenbasis, \(\rho\) is the diagonal matrix \(\matr{D}=\mathrm{diag}(\lambda_0,\dots,\lambda_{n-1})\), the unitary that diagonalizes it drops out of the trace, and \(-\mathrm{Tr}(\matr{D}\log_2\matr{D}) = -\sum_i\lambda_i\log_2\lambda_i\) is the Shannon entropy of the eigenvalue distribution. A pure state has eigenvalues \(\{1,0,\dots\}\) and \(S=0\); the maximally mixed state in \(d\) dimensions has \(S=\log_2 d\), its largest possible value; and \(S\) is invariant under unitary transformations, so it does not change during the evolution of a closed system. One cannot simply use the classical definition with the diagonal elements of \(\rho\) in some basis, because the result is the Shannon entropy of that particular measurement, not in general the entropy of the state. A pure state can have random measurement outcomes: \(\vert+\rangle\) has \(S=0\) but yields one bit of Shannon entropy when measured in the computational basis. The spectral definition avoids this basis dependence. At zero eigenvalues, \(\lambda\log\lambda\) is defined by its continuous limit, zero.
For a pure bipartite state the von Neumann entropy of the reduced density matrix,
is the entanglement entropy. It vanishes for product states, it equals one bit for the Bell states, and it is symmetric between the two subsystems because both reduced density matrices have the same nonzero eigenvalues \(\sigma_k^2\). The right panel of Fig. 2.4 shows \(S_A\) for the family \(\cos\theta\vert 00\rangle+\sin\theta\vert 11\rangle\), which interpolates between the product state \(\vert 00\rangle\) at \(\theta=0\), the Bell state at \(\theta=\pi/4\) and the product state \(\vert 11\rangle\) at \(\theta=\pi/2\); Table 2.2 gives the numbers. For a mixed joint state, \(S(\rho_A)\) is not an entanglement measure by itself: the separable mixture \((\vert00\rangle\langle00|+\vert11\rangle\langle11|)/2\) also has \(S(\rho_A)=S(\rho_B)=1\). Its correlations are classical, unlike those of a pure Bell state.
Entanglement helps diagnose the cost of tensor-network methods, but the statement requires care. An exact matrix product state of bond dimension \(\chi\) has Schmidt rank at most \(\chi\) across each bond cut, and hence
For approximation, order the Schmidt coefficients from largest to smallest. Discarding all but \(\chi\) terms loses weight \(\epsilon_\chi=\sum_{k=\chi}^{r-1}\sigma_k^2\); the normalized truncated state has squared overlap \(1-\epsilon_\chi\) with the original state across that cut, and by the Eckart–Young theorem, Eq. (B.36), no other state of Schmidt rank \(\chi\) has a larger one. The tails of these spectra, the cuts selected by the network geometry, and the cost of contracting and finding the tensors matter. Small von Neumann entropy alone is not a general guarantee of efficient simulation.

Figure 2.4: Left: the binary Shannon entropy \(H_2(p)\) of Eq. (2.76). Right: the entanglement entropy \(S(\rho_A)\) of the two-qubit state \(\cos\theta\vert 00\rangle+\sin\theta\vert 11\rangle\), which reaches one bit for the Bell state at \(\theta=\pi/4\). Produced by entanglement.py.
\(\theta/\pi\) |
\(0\) |
\(0.05\) |
\(0.10\) |
\(0.15\) |
\(0.20\) |
\(0.25\) |
|---|---|---|---|---|---|---|
\(S(\rho_A)\) [bit] |
\(0\) |
\(0.1659\) |
\(0.4545\) |
\(0.7340\) |
\(0.9300\) |
\(1.0000\) |
Table 2.2: Entanglement entropy of \(\cos\theta\vert 00\rangle+\sin\theta\vert 11\rangle\),
whose Schmidt coefficients are \(\cos\theta\) and \(\sin\theta\). Produced by
entanglement.py.
The following excerpt from entanglement.py computes the reduced
density matrix and entropy of the Bell states with the classes introduced
above; the printed table reproduces Eq. (2.71).
import numpy as np
from density_matrix import DensityMatrix
bell = {"Phi+": [1, 0, 0, 1], "Phi-": [1, 0, 0, -1],
"Psi+": [0, 1, 1, 0], "Psi-": [0, 1, -1, 0]}
for name, v in bell.items():
rho_AB = DensityMatrix.from_state(np.array(v) / np.sqrt(2))
rho_A = rho_AB.partial_trace(keep=0)
print(name, rho_A.rho.real.round(3).tolist(),
"purity", rho_A.purity(), "S =", rho_A.von_neumann_entropy())
def entanglement_entropy(psi):
return DensityMatrix.from_state(psi).partial_trace(0).von_neumann_entropy()
for theta in np.linspace(0, np.pi / 2, 11):
print(f"{theta/np.pi:5.2f} {entanglement_entropy([np.cos(theta), 0, 0, np.sin(theta)]):.4f}")
Phi+ [[0.5, 0.0], [0.0, 0.5]] purity 0.4999999999999998 S = 1.0000000000000002
Phi- [[0.5, 0.0], [0.0, 0.5]] purity 0.4999999999999998 S = 1.0000000000000002
Psi+ [[0.5, 0.0], [0.0, 0.5]] purity 0.4999999999999998 S = 1.0000000000000002
Psi- [[0.5, 0.0], [0.0, 0.5]] purity 0.4999999999999998 S = 1.0000000000000002
0.00 0.0000
0.05 0.1659
0.10 0.4545
0.15 0.7340
0.20 0.9300
0.25 1.0000
0.30 0.9300
0.35 0.7340
0.40 0.4545
0.45 0.1659
0.50 0.0000
Quantum gates#
From Hamiltonians to gates#
Quantum gates are physical actions applied to the system that carries the qubits. Mathematically they are unitary matrices acting on the normalized vectors that represent the qubits; physically they are the time evolution generated by a Hamiltonian that the experimenter switches on for a controlled time. The time-dependent Schrödinger equation
has, for a time-independent Hamiltonian, the formal solution
and because \(H\) is Hermitian the time-evolution operator \(U(t,t_0)\) is unitary, \(U^{\dagger}=U^{-1}\). It satisfies \(U(t_0,t_0)=\matr{I}\), \(U(t,t')U(t',t'')=U(t,t'')\) and \(U(t,t')^{\dagger}=U(t',t)\), so a sequence of evolutions under different Hamiltonians is a product of unitaries, which is what a sequence of gates is. When the Hamiltonian depends on time, Eq. (2.81) is replaced by the time-ordered exponential of Eq. (2.2), which Section The time-ordered exponential turns into a product of short evolutions. Chapter 4 discusses how to implement \(e^{-iHt}\) for a many-body Hamiltonian as a circuit.
The simplest example is a spin-\(1/2\) in a magnetic field, the working principle of nuclear magnetic resonance and a useful effective model for several qubit platforms. The magnetic moment \(\vec{\mu}=\gamma\vec{S}\) couples to the field through \(H=-\vec{\mu}\cdot\vec{B}\), and for a constant field along \(z\) this becomes
where \(\omega_L=\gamma B_z\) is a signed Larmor frequency ; the positive precession rate is \(|\omega_L|\). The computational basis states \(\vert 0\rangle\) and \(\vert 1\rangle\) are the eigenstates of \(H_z\) with energies \(\mp\omega_L/2\), and using Eq. (2.34), which for an operator \(\matr{A}\) with eigenvector \(\vert a\rangle\) reads \(e^{\matr{A}}\vert a\rangle = \sum_n \frac{1}{n!}\matr{A}^n\vert a\rangle = e^{a}\vert a\rangle\), the time evolution of the state (2.36) is
where the prefactor is a global phase and can be omitted when computing this state’s observables. The polar angle is constant and the azimuthal angle decreases linearly in time: the Bloch vector precesses about the \(z\) axis at the Larmor frequency, as drawn in Fig. 2.1(b). Letting the field act for a time \(t\) therefore implements a rotation about \(z\) by the signed angle \(-\omega_L t\), the gate \(R_z(-\omega_L t)\) defined below. A field along \(x\) or \(y\), or an oscillating field resonant with \(\omega_L\), produces rotations about the other axes, and this is how single-qubit gates are realized in NMR and, with microwave or laser pulses, in superconducting and trapped-ion processors.
Single-qubit gates#
A single-qubit gate is a \(2\times2\) unitary matrix, an element of \(\mathrm U(2)\). Removing an overall phase gives a determinant-one representative in \(\mathrm{SU}(2)\). A useful three-parameter representative, up to such a phase, is
Its determinant is \(e^{i(\phi+\lambda)}\), so the displayed matrix is not generally in \(\mathrm{SU}(2)\). Multiplication by \(e^{-i(\phi+\lambda)/2}\) gives the special-unitary representative in Eq. (2.87). Acting on \(\vert0\rangle\), it produces the Bloch state (2.36); \(\lambda\) does not affect that input. The Pauli matrices are traceless Hermitian generators. With the mathematical convention that \(\mathfrak{su}(2)\) consists of anti-Hermitian matrices, its basis is \(-iX/2,-iY/2,-iZ/2\). Exponentiating gives the rotation gates. For any matrix with \(\matr{A}^2=\matr{I}\) the power series of the exponential splits into even and odd terms,
which applied to the Pauli matrices with \(\alpha=\theta/2\) gives
The gate \(R_{\sigma}(\theta)\) rotates the Bloch vector by the angle \(\theta\) about the axis \(\sigma=x,y,z\), and more generally \(R_{\uvec{n}}(\theta)=e^{-i\theta\,\uvec{n}\cdot\vec{\sigma}/2}\) rotates it about the unit vector \(\uvec{n}\); the factor \(1/2\) in the exponent is the same half angle that appears in the Bloch parametrization. Rotations by \(2\pi\) give \(-\matr{I}\) rather than \(\matr{I}\), which is harmless for a uncontrolled application, where \(-\matr I\) multiplies the whole register state by a global phase, but matters when that operation is controlled. Any single-qubit gate can be decomposed into three rotations,
as one verifies by multiplying the three matrices of
Eq. (2.86). This is the Euler-angle decomposition of a
rotation, and it is what a compiler uses to express an arbitrary
single-qubit operation in terms of the rotations that the hardware
provides. Table 2.3 collects the gates we use most, with
their matrices and their interpretation as rotations. The Pauli gates are
rotations by \(\pi\) about the coordinate axes (up to a global phase,
\(X = iR_x(\pi)\) and so on); the phase gate \(S\) and the \(\pi/8\) gate \(T\)
are rotations about \(z\) by \(\pi/2\) and \(\pi/4\), with \(T^2=S\) and \(S^2=Z\);
the Hadamard gate is the rotation by \(\pi\) about the axis
\((\uvec{x}+\uvec{z})/\sqrt{2}\), which exchanges the \(x\) and \(z\) axes and
therefore satisfies \(HXH=Z\) and \(HZH=X\). All the identities in the
table are verified numerically by gates.py.
gate |
symbol |
matrix |
Bloch-sphere action |
|---|---|---|---|
Pauli \(X\) (NOT) |
\(X\) |
\(\begin{bmatrix} 0 & 1 \\ 1 & 0\end{bmatrix}\) |
rotation by \(\pi\) about \(x\) |
Pauli \(Y\) |
\(Y\) |
\(\begin{bmatrix} 0 & -i \\ i & 0\end{bmatrix}\) |
rotation by \(\pi\) about \(y\) |
Pauli \(Z\) |
\(Z\) |
\(\begin{bmatrix} 1 & 0 \\ 0 & -1\end{bmatrix}\) |
rotation by \(\pi\) about \(z\) |
Hadamard |
\(H\) |
\(\frac{1}{\sqrt{2}}\begin{bmatrix} 1 & 1 \\ 1 & -1\end{bmatrix}\) |
rotation by \(\pi\) about \((\uvec{x}+\uvec{z})/\sqrt{2}\) |
phase |
\(S\) |
\(\begin{bmatrix} 1 & 0 \\ 0 & i\end{bmatrix}\) |
rotation by \(\pi/2\) about \(z\) |
\(\pi/8\) |
\(T\) |
\(\begin{bmatrix} 1 & 0 \\ 0 & e^{i\pi/4}\end{bmatrix}\) |
rotation by \(\pi/4\) about \(z\) |
phase shift |
\(P(\lambda)\) |
\(\begin{bmatrix} 1 & 0 \\ 0 & e^{i\lambda}\end{bmatrix}\) |
rotation by \(\lambda\) about \(z\) |
rotations |
\(R_x,R_y,R_z(\theta)\) |
Eq. (2.86) |
rotation by \(\theta\) about \(x,y,z\) |
general |
\(U(\theta,\phi,\lambda)\) |
Eq. (2.84) |
\(R_z(\phi)R_y(\theta)R_z(\lambda)\) |
controlled-NOT |
\(\mathrm{CNOT}\), \(\mathrm{CX}\) |
\(\begin{bmatrix} 1&0&0&0\\0&1&0&0\\0&0&0&1\\0&0&1&0\end{bmatrix}\) |
flips target if control is \(\vert 1\rangle\) |
controlled-\(Z\) |
\(\mathrm{CZ}\) |
\(\mathrm{diag}(1,1,1,-1)\) |
phase \(-1\) on \(\vert 11\rangle\) |
controlled-\(U\) |
\(\mathrm{C}U\) |
\(\vert 0\rangle\langle 0\vert\otimes\matr{I}+\vert 1\rangle\langle 1\vert\otimes U\) |
\(U\) on target if control is \(\vert 1\rangle\) |
swap |
\(\mathrm{SWAP}\) |
\(\begin{bmatrix} 1&0&0&0\\0&0&1&0\\0&1&0&0\\0&0&0&1\end{bmatrix}\) |
\(\vert xy\rangle\to\vert yx\rangle\) |
Table 2.3: Elementary quantum gates. Single-qubit gates act on the basis
\(\{\vert 0\rangle,\vert 1\rangle\}\), two-qubit gates on
\(\{\vert 00\rangle,\vert 01\rangle,\vert 10\rangle,\vert 11\rangle\}\) with the
first qubit as control. The \(P(\lambda)\) family contains \(Z=P(\pi)\),
\(S=P(\pi/2)\) and \(T=P(\pi/4)\). Verified by gates.py.
Two-qubit gates#
A two-qubit gate is a \(4\times 4\) unitary matrix, an element of \(\mathrm{SU}(4)\) up to a phase. Tensor products \(U_1\otimes U_2\) of single-qubit gates are two-qubit gates, but they cannot create entanglement: they map product states onto product states, by Eq. (2.31). Controlled gates are one important family of potentially entangling operations, not the only family. Moreover, a controlled-\(U\) is not entangling if \(U\) is proportional to the identity, and even CNOT does not entangle every input. For a computational-basis control, the controlled gate applies \(U\) to the target if the control bit is \(1\), and applies the identity if it is \(0\). Its action on a superposition follows by linearity; the control’s populations stay fixed, but its coherences and reduced state can change. Written as a sum over the two cases,
For example, if \(U\vert u\rangle=e^{i\varphi}\vert u\rangle\), then
The target stays in its eigenstate while its eigenphase becomes a relative phase of the control. This phase kickback is central to Chapter 5. In particular, a phase on \(U\) cannot be discarded before adding a control:
The most important controlled gate is the controlled-NOT or CNOT gate, \(\mathrm{CX}\), obtained with \(U=X\),
that is, \(\mathrm{CNOT}\vert x y\rangle = \vert x, y\oplus x\rangle\) with
\(\oplus\) the addition modulo two. On a superposition of the control it
does something no classical gate can do: applied to
\((\vert 0\rangle+\vert 1\rangle)/\sqrt{2}\otimes\vert 0\rangle\) it produces
the Bell state \(\vert\Phi^+\rangle\), because the sum over the two values of
the control is carried through to the target. The controlled-\(Z\) gate
\(\mathrm{CZ}=\mathrm{diag}(1,1,1,-1)\) is symmetric in control and target and
related to the CNOT by conjugation with Hadamard gates on the target,
\(\mathrm{CNOT} = (\matr{I}\otimes H)\,\mathrm{CZ}\,(\matr{I}\otimes H)\), a
direct consequence of \(HZH=X\). Finally the SWAP
gate exchanges the two qubits, \(\mathrm{SWAP}\vert xy\rangle=\vert yx\rangle\);
it is not a controlled gate, but it can be built from three CNOT gates with
alternating control and target, a circuit identity shown in
Fig. 2.5 and verified in circuit.py. The
three-qubit Toffoli gate, a CNOT with two controls, completes the standard
repertoire; together with suitably initialized ancillary bits it
supports universal classical reversible computation.
Universal gate sets#
A set of gates is universal if every unitary operation on \(N\) qubits can be approximated to arbitrary precision by a circuit built from that set. Two facts make universality tractable. First, any unitary on \(N\) qubits can be decomposed exactly into single-qubit gates and CNOT gates, so the pair {arbitrary single-qubit rotations, CNOT} is universal; this is the standard choice when compiling for hardware whose native operations are parametrized rotations and one entangling gate. This existence statement does not imply efficient synthesis of a generic \(N\)-qubit unitary: the number of elementary gates can grow exponentially with \(N\). Second, single-qubit rotations can be approximated by a finite set: \(H\) and \(T\) are dense in the single-qubit unitaries modulo global phase. Thus {\(H\), \(T\), CNOT} is universal in that sense. The Solovay–Kitaev theorem gives \(\bigO(\log^c(1/\epsilon))\) gates for approximating a fixed-dimensional target unitary using an appropriate finite, inverse-closed universal set. Here the inverse generators are available since \(H^{-1}=H\) and \(T^{-1}=T^7\). This is a bound on precision overhead, not a polylogarithmic cost for an arbitrary many-qubit computation. Phases needed for controlled operations must be retained explicitly. The discrete set matters because the fault-tolerant constructions of quantum error correction [QCbook] can implement a finite set of gates on encoded qubits, and \(T\) is typically by far the most expensive of them. The gates \(H\), \(S\) and CNOT alone generate the Clifford group, which is not universal: stabilizer-state inputs, Clifford gates and Pauli measurements with classical feed-forward can be simulated efficiently classically (the Gottesman–Knill theorem). Supplying arbitrary non-stabilizer input states changes the premise. This is a reminder that entanglement by itself is not the source of quantum computational power.
Quantum circuits#
Quantum circuits are diagrammatic representations of quantum algorithms; they are read a little like music, with one line per qubit. The horizontal direction is time, running from left to right. Each qubit is a horizontal line, a quantum wire, labeled on the left with its initial state, usually \(\vert 0\rangle\). Gates are boxes placed on the wires, and are applied in chronological order from left to right, so that the circuit \(A\) followed by \(B\) corresponds to the operator product \(BA\), in the opposite order from the diagram. A controlled gate is drawn as a dot on the control wire connected by a vertical line to the gate on the target wire, and the CNOT target is drawn as \(\oplus\). Measurements are drawn as a meter symbol; the recorded outcome is a classical wire, drawn doubled. A surviving post-measurement quantum system may also continue along a quantum wire. Figure 2.5 shows the circuit that prepares \(\vert\Phi^+\rangle\) from \(\vert 00\rangle\), the other three Bell states being obtained by an additional \(X\) on the second qubit and/or \(Z\) on the first, and the decomposition of the SWAP gate into three CNOT gates.

Figure 2.5: (a) The circuit that prepares the Bell state \(\vert\Phi^+\rangle\): a Hadamard gate on the first qubit followed by a CNOT with the first qubit as control. (b) The SWAP gate as three CNOT gates with alternating control and target. Both identities are verified in circuit.py.
Let us follow the Bell circuit step by step, since the same pattern returns in every algorithm of this book. The Hadamard gate on the first qubit produces \(\frac{1}{\sqrt{2}}(\vert 0\rangle+\vert 1\rangle)\otimes\vert 0\rangle =\frac{1}{\sqrt{2}}(\vert 00\rangle+\vert 10\rangle)\), and the CNOT then flips the second qubit in the second term only, \(\frac{1}{\sqrt{2}}(\vert 00\rangle+\vert 11\rangle)=\vert\Phi^+\rangle\). Two gates and no interaction with anything else have produced a maximally entangled state; the inverse circuit, a CNOT followed by a Hadamard, maps the four Bell states back onto the four computational basis states and is therefore a Bell measurement when followed by a measurement in the computational basis. This is the tool we need for the protocols of Section Two protocols: superdense coding and teleportation.
Describing circuits in code is as natural as drawing them. The class
Circuit in circuit.py is a list of Gate objects,
each holding a matrix, its target qubits and optional control qubits; a
circuit is executed by applying the gates in order to a
StateVector, and its full \(2^N\times 2^N\) unitary is obtained by
running it on every basis state. Chapters 4
and 6 build their Trotter and variational circuits with the
same class.
import numpy as np
from circuit import Circuit
import gates as G
bell = Circuit(2).h(0).cnot(0, 1)
print(bell.draw()) # the ASCII version of the Bell circuit
print(bell.run()) # (0.7071)|00> + (0.7071)|11>
swap = Circuit(2).cnot(0, 1).cnot(1, 0).cnot(0, 1)
assert np.allclose(swap.unitary(), G.SWAP)
print(bell, "depth", bell.depth)
q0: |0>--[H]--*---
q1: |0>------(+)--
(+0.7071+0.0000j)|00> + (+0.7071+0.0000j)|11>
Circuit(2 qubits, 2 gates, depth 2) depth 2
The first two print statements display a text drawing and the normalized Bell state. The assertion checks the SWAP decomposition. The depth of a circuit, the number of layers of gates that act on disjoint qubits and can be executed in parallel, is a useful measure of sequential work and enters the counting argument of Section Quantum computing in a nutshell. Actual duration also depends on gate times, connectivity, scheduling and measurement latency.
Two protocols: superdense coding and teleportation#
Entanglement is a resource. Two protocols, both using a single Bell pair shared between two parties conventionally called Alice and Bob, show what the resource buys and how the rules of Sections Measurements and Quantum gates combine into something a classical channel cannot do.
Superdense coding#
Alice wants to send Bob two classical bits \(b_1b_2\) but may transmit only one qubit. If they share the Bell state \(\vert\Phi^+\rangle\), with Alice holding the first qubit, she can do it [BennettWiesner1992]. She applies to her qubit one of the four Pauli operations
for the messages \(00\), \(01\), \(10\) and \(11\) respectively, and sends her
qubit to Bob. Since the four Bell states are orthogonal, Bob can
distinguish them perfectly: he applies the inverse of the Bell circuit, a
CNOT followed by a Hadamard on the first qubit, which maps
\(\vert\Phi^+\rangle,\vert\Psi^+\rangle,\vert\Phi^-\rangle,\vert\Psi^-\rangle\)
onto \(\vert 00\rangle,\vert 01\rangle,\vert 10\rangle,\vert 11\rangle\), and
measures both qubits in the computational basis to read \(b_1b_2\). A single
qubit thus carries two bits of classical information, twice what a qubit
could carry without shared entanglement; the entanglement was consumed in
the process. The circuit is shown in Fig. 2.6, and
protocols.py runs it for all four messages.

Figure 2.6: Superdense coding. A Bell pair is shared, Alice encodes two bits by one of four Pauli operations on her qubit and sends it, and Bob decodes with the inverse Bell circuit and two measurements.
Quantum teleportation#
Teleportation is the converse task: Alice holds a qubit in an unknown state \(\vert\psi\rangle=\alpha\vert 0\rangle+\beta\vert 1\rangle\) and wants Bob to end up with it, but she may only send classical bits [Bennett1993]. Since she cannot measure \(\alpha\) and \(\beta\), and cannot copy the state either (the no-cloning theorem, Exercise 2.10), she again uses a shared Bell pair. Number the qubits so that Alice holds qubit \(0\) in the state \(\vert\psi\rangle\) and qubit \(1\), while Bob holds qubit \(2\); qubits \(1\) and \(2\) are in \(\vert\Phi^+\rangle\). The initial three-qubit state is
Alice applies a CNOT from qubit \(0\) to qubit \(1\) and then a Hadamard to qubit \(0\), the inverse Bell circuit. The CNOT gives \(\frac{1}{\sqrt{2}}[\alpha\vert 0\rangle(\vert 00\rangle+\vert 11\rangle)+\beta\vert 1\rangle(\vert 10\rangle+\vert 01\rangle)]\), and the Hadamard turns \(\vert 0\rangle\) into \((\vert 0\rangle+\vert 1\rangle)/\sqrt{2}\) and \(\vert 1\rangle\) into \((\vert 0\rangle-\vert 1\rangle)/\sqrt{2}\). Collecting the terms according to the values \(m_0m_1\) of Alice’s two qubits,
Alice now measures her two qubits and obtains each of the four outcomes with probability \(1/4\); by Eq. (2.6) Bob’s qubit collapses onto the corresponding state in Eq. (2.94), which is \(\vert\psi\rangle\) up to a known Pauli operation. Alice sends the two bits \(m_0m_1\) to Bob over a classical channel, and Bob applies the correction
The conditional state before correction is
\(X^{m_1}Z^{m_0}\vert\psi\rangle\), so its inverse is
\(Z^{m_0}X^{m_1}\). Thus \(X\) acts first and \(Z\) afterwards, consistently
with the circuit and code. For \(m_0m_1=11\) the state
\(\alpha\vert 1\rangle-\beta\vert 0\rangle\) first becomes
\(\alpha\vert 0\rangle-\beta\vert 1\rangle\) and then \(\alpha\vert 0\rangle+\beta\vert 1\rangle\).
After the Bell pair has been distributed, the unknown state is
transferred using only classical communication, and without Alice learning anything about \(\alpha\) and
\(\beta\); her outcomes are uniformly random. Nothing travels faster than
light, since Bob’s qubit is in the maximally mixed state \(\matr{I}/2\)
until the two classical bits arrive, and the original state is destroyed
on Alice’s side, in agreement with no-cloning. Figure 2.7
shows the circuit, and protocols.py verifies
Eq. (2.95) for two hundred random input states by comparing
Bob’s reduced density matrix with \(\vert\psi\rangle\langle\psi\vert\). The
same algebra also permits a coherent circuit with controlled
corrections, a useful construction in quantum error correction. Such
coherent controls require quantum interactions and are not themselves
a classical communication channel.

Figure 2.7: Quantum teleportation. Alice (upper two wires) performs a Bell measurement on her unknown qubit and her half of a Bell pair, sends the two outcomes to Bob over a classical channel (double lines), and Bob (lower wire) applies the Pauli correction of Eq. (2.95).
The implementation follows the circuit line by line; the measurement outcomes are drawn by the simulator and the corrections are ordinary Python conditionals, exactly as a control program on real hardware would do it.
from statevector import StateVector
from density_matrix import DensityMatrix
def teleport(psi, rng=None):
sv = StateVector.product(psi, [1, 0], [1, 0]) # qubit 0: |psi>, qubits 1,2: |00>
sv.h(1).cnot(1, 2) # Bell pair between Alice (1) and Bob (2)
sv.cnot(0, 1).h(0) # Alice's Bell measurement, basis change
m0, _ = sv.measure(0, rng=rng)
m1, _ = sv.measure(1, rng=rng)
if m1: sv.x(2) # classical corrections
if m0: sv.z(2)
return DensityMatrix.from_state(sv).partial_trace(2), (m0, m1)
A first Hamiltonian: the two-level system#
We close with a two-dimensional Hamiltonian. It can describe one physical qubit or an effective two-state subspace of a many-body problem; two dimensions alone do not make it a many-body system. It already contains the ingredients of the variational algorithms of Chapter 6: a Hamiltonian written in terms of Pauli operators, a parametrized circuit that prepares trial states, and an energy that is minimized over the parameters. Consider the real symmetric Hamiltonian
where \(H_0\) plays the role of a non-interacting one-body part whose eigenstates \(\vert 0\rangle\) and \(\vert 1\rangle\), with energies \(E_1\) and \(E_2\), define the computational basis, \(H_I\) an interaction with \(V_{12}=V_{21}\) by hermiticity, and \(\lambda\in[0,1]\) a coupling strength interpolating between the non-interacting and the fully interacting system. Since \(\matr{I}\) and \(Z\) span the diagonal \(2\times 2\) matrices and \(X\) the symmetric off-diagonal ones, we can rewrite both parts in the Pauli basis,
with \(E_\pm = (E_1\pm E_2)/2\), \(V_\pm=(V_{11}\pm V_{22})/2\) and \(V_o = V_{12}\). Define \(a=E_++\lambda V_+\), \(b=E_-+\lambda V_-\), \(c=\lambda V_o\), so \(H=a\matr I+bZ+cX\). Since \(ZX+XZ=0\), \((bZ+cX)^2=(b^2+c^2)\matr I\). The ordered interacting energies are therefore
Here \(E_0(\lambda),E_1(\lambda)\) label the interacting spectrum, whereas the constants \(E_1,E_2\) in \(H_0\) are the bare input energies. For \(R>0\), the ground-state projector and the weight of \(\vert0\rangle\) follow without constructing an eigenvector:
At \(R=0\), \(H=a\matr I\) is degenerate and there is no unique ground-state projector. This rewriting is the one-qubit version of the mappings of Section From fermions to qubits: every Hamiltonian on \(N\) qubits is a linear combination of the \(4^N\) tensor products of Pauli matrices, and its expectation value is the corresponding combination of expectation values of Pauli strings, each of which can be measured as in Section Measuring one qubit of a register and in other bases.
We choose \(E_1=0\), \(E_2=4\), \(V_{11}=-V_{22}=3\) and \(V_{12}=V_{21}=0.2\). The left panel of Fig. 2.8 shows the two eigenvalues as functions of \(\lambda\). The diagonal elements \(E_1+\lambda V_{11}\) and \(E_2+\lambda V_{22}\) cross at \(\lambda=2/3\), but the small coupling \(V_o\) turns the crossing into an avoided crossing and interchanges the character of the eigenvectors: for \(\lambda<2/3\) the \(\vert0\rangle\) weight exceeds \(1/2\), equals \(1/2\) at \(\lambda=2/3\), and is below \(1/2\) for larger \(\lambda\). The sampled value at \(\lambda=0.6\) is \(0.9287\), but that does not justify a \(90\%\) bound all the way to the crossing. At \(\lambda=1\) the weight is \(0.0097\) and \(E_0(1)=2-\sqrt{1.04}\simeq0.9802\). The diagonal crossing is at \(\lambda=2/3\); the minimum spectral gap is slightly displaced because the off-diagonal element also depends on \(\lambda\). Here \(\Delta(\lambda)=2\sqrt{(-2+3\lambda)^2+(0.2\lambda)^2}\), whose minimum is at \(\lambda=75/113\simeq0.6637\).
\(\lambda\) |
\(E_0\) |
\(E_1\) |
\(\vert \langle 0\vert E_0\rangle\vert ^2\) |
|---|---|---|---|
\(0\) |
\(0.0000\) |
\(4.0000\) |
\(1.0000\) |
\(0.3\) |
\(0.8984\) |
\(3.1016\) |
\(0.9993\) |
\(0.6\) |
\(1.7668\) |
\(2.2332\) |
\(0.9287\) |
\(2/3\) |
\(1.8667\) |
\(2.1333\) |
\(0.5000\) |
\(0.7\) |
\(1.8280\) |
\(2.1720\) |
\(0.2094\) |
\(1\) |
\(0.9802\) |
\(3.0198\) |
\(0.0097\) |
Table 2.4: Eigenvalues of the two-level Hamiltonian
(2.96) and the weight of \(\vert 0\rangle\) in the ground
state, as functions of the coupling \(\lambda\). Produced by
two_level_system.py.
Diagonalizing a \(2\times 2\) matrix is of course trivial, but let us pretend we could only prepare states with gates and measure Pauli operators, which is the situation on a quantum computer. From Section Single-qubit gates we know that every point on the Bloch sphere can be reached from \(\vert 0\rangle\) by two rotations, and we take as trial state
a circuit with two parametrized gates. These angles are rotation parameters, not the polar and azimuthal angles of Eq. (2.36). Direct multiplication, or rotating the initial Bloch vector \((0,0,1)\), gives
Allowing both rotation angles to range over \([0,2\pi)\) covers the whole sphere, with redundant parameterizations. Its energy,
requires only the expectation values of \(Z\) and \(X\) in the trial state, which we obtain from independently prepared copies with and without a preceding Hadamard gate. Equation (2.101) makes the landscape and its derivatives explicit:
Writing a normalized trial state in the energy eigenbasis gives \(E=\sum_j|d_j|^2E_j\ge E_0\), the variational principle. Our ansatz can attain the ground-state Bloch vector \(-(c,0,b)/R\) when \(R>0\), so its unrestricted minimum is exactly \(a-R\). At \(\lambda=1\) one minimum is \(\theta=\pi\), \(\phi=\arctan(0.2)\) modulo the angular redundancies.
The variational bound applies to the exact expectation of the stated Hamiltonian, including that of a normalized mixed state. A finite-shot estimate can fluctuate below \(E_0\); such a value is not a violation of the variational principle. With independent sets of \(N_Z,N_X\) shots, the elementary estimator has
The identity term has no sampling cost.
The right panel of Fig. 2.8 shows \(E(\theta,\phi)\) at \(\lambda=1\) on a grid of angles in steps of ten degrees. The single guess \(\theta=\pi/2\), \(\phi=0.2\pi\) gives \(E=2.0000\), not impressive; the best point of the coarse grid, \(\theta=170^\circ\), \(\phi=10^\circ\), gives \(E=0.9960\), within \(0.016\) of the exact value. That plotted grid uses \(0^\circ,10^\circ,\ldots,170^\circ\) and excludes the important endpoint \(\theta=180^\circ\). Including \(180^\circ\) already gives \(E\simeq0.9805\) on a ten-degree grid. The reported one-degree grid includes both endpoints and reduces the error to about \(1.5\times10^{-5}\). Its improvement combines a finer mesh with changed endpoint coverage. The restriction to \([0,\pi]\) is sufficient to include a ground state of this real Hamiltonian, but does not cover arbitrary complex qubit states. For many parameters, optimization replaces a full grid; gradients are one option, with no general guarantee of finding the global optimum. This is the setting of the variational quantum eigensolver in Chapter 6.

Figure 2.8: Left: eigenvalues of the two-level Hamiltonian (2.96) as functions of \(\lambda\) (solid), the diagonal matrix elements (dotted) and the weight of \(\vert 0\rangle\) in the ground state (dashed, right axis). Right: the energy of the trial state \(R_y(\phi)R_x(\theta)\vert 0\rangle\) at \(\lambda=1\); the star marks the lowest point of the original ten-degree grid \(0^\circ,10^\circ,\ldots,170^\circ\), which excludes \(180^\circ\). Produced by two_level_system.py.
The class TwoLevelSystem in two_level_system.py holds
the Hamiltonian in both forms and the trial state:
import numpy as np
import gates as G
class TwoLevelSystem:
def __init__(self, E1=0.0, E2=4.0, V11=3.0, V22=-3.0, V12=0.2):
self.E_plus, self.E_minus = (E1 + E2) / 2, (E1 - E2) / 2
self.V_plus, self.V_minus, self.V_o = (V11 + V22) / 2, (V11 - V22) / 2, V12
def hamiltonian(self, lam):
return ((self.E_plus + lam * self.V_plus) * G.I
+ (self.E_minus + lam * self.V_minus) * G.Z
+ lam * self.V_o * G.X)
def ansatz(self, theta, phi):
return G.Ry(phi) @ G.Rx(theta) @ np.array([1, 0], dtype=complex)
def energy(self, theta, phi, lam):
psi = self.ansatz(theta, phi)
return float(np.real(np.vdot(psi, self.hamiltonian(lam) @ psi)))
tls = TwoLevelSystem()
E0 = np.linalg.eigvalsh(tls.hamiltonian(1.0))[0]
angles = np.deg2rad(np.arange(0, 180, 10))
grid = np.array([[tls.energy(th, ph, 1.0) for ph in angles] for th in angles])
print(f"exact E0 = {E0:.4f}, plotted grid E = {grid.min():.4f}")
inclusive = np.deg2rad(np.arange(0, 181, 10))
best = min(tls.energy(th, ph, 1.0) for th in inclusive for ph in inclusive)
print(f"ten-degree grid including endpoints: E = {best:.4f}")
exact E0 = 0.9802, plotted grid E = 0.9960
ten-degree grid including endpoints: E = 0.9805
Exercises#
Commutator identities. Prove that for operators \(\op{A}\), \(\op{B}\) and \(\op{C}\)
\([\op{A}+\op{B},\op{C}]= [\op{A},\op{C}]+[\op{B},\op{C}]\);
\([\op{A},\op{B}\op{C}]= [\op{A},\op{B}]\op{C}+\op{B}[\op{A},\op{C}]\);
\([\op{A},[\op{B},\op{C}]]+[\op{B},[\op{C},\op{A}]]+[\op{C},[\op{A},\op{B}]]=0\) (the Jacobi identity).
Pauli matrices. Derive the commutation rules \([\sigma_i,\sigma_j]\) for \(i,j=x,y,z\) and show that \(XX=YY=ZZ=\matr{I}\). Which of the Pauli matrices has the computational basis as its eigenbasis, and what are the eigenvalues? Show that \(\sigma_i\sigma_j = \delta_{ij}\matr{I} +i\sum_{k=x,y,z}\epsilon_{ijk}\sigma_k\) and use it to prove that \(HZH=X\) with the Hadamard matrix \(H=(X+Z)/\sqrt{2}\).
Shared eigenvectors. Prove that two Hermitian operators \(\op{A}\) and \(\op{B}\) that commute share a basis of eigenstates. Why does this matter for the simultaneous measurement of two observables?
One-qubit gates in code. Write a function that sets up the one-qubit computational basis and applies the Pauli matrices, the Hadamard gate and the phase gate to the basis states. Verify Eqs. (2.24) and (2.26) and check that all five matrices are unitary. Then determine the Bloch angles of the resulting states with the functions of Section Qubits and the Bloch sphere.
Traces and exponentials. Prove that the trace is cyclic, \(\mathrm{Tr}(\matr{A}\matr{B}\matr{C})=\mathrm{Tr}(\matr{C}\matr{A}\matr{B})=\mathrm{Tr}(\matr{B}\matr{C}\matr{A})\). Let \(\matr{A}\) satisfy \(\matr{A}^2=\matr{I}\) and let \(\alpha\) be real; show from the power series that \(e^{i\alpha\matr{A}} = \matr{I}\cos\alpha+i\matr{A}\sin\alpha\). Does this apply to the Pauli matrices? Use it to verify the rotation matrices of Eq. (2.86) and the decomposition (2.87).
Reduced density matrices. For each of the four Bell states find the reduced density matrix of each qubit by computing the partial trace by hand, and compare with
entanglement.py. Then suppose the composite system is in the product state \(\vert a\rangle\otimes\vert b\rangle\) of pure states of \(A\) and \(B\); show that the reduced density matrix of \(A\) is the pure state \(\vert a\rangle\langle a\vert\), and similarly for \(B\).Bloch angles of Pauli eigenstates. Determine the Bloch angles \(\theta\) and \(\phi\) of the eigenstates of each Pauli matrix and compare with Table 2.1. Show that two states are orthogonal if and only if their Bloch vectors are antipodal, and that \(|\langle\phi\vert\psi\rangle|^2 = (1+\vec{r}_\phi\cdot\vec{r}_\psi)/2\).
Mixed states of a qubit. Show that Eq. (2.55) has eigenvalues \((1\pm|\vec{r}|)/2\), so that positivity requires \(|\vec{r}|\le 1\), and that the purity is \((1+|\vec{r}|^2)/2\). Compute the von Neumann entropy as a function of \(|\vec{r}|\) and plot it. Which ensembles of pure states produce the state with \(\vec{r}=(0,0,1/2)\)?
Entanglement entropy. Write the state \(\cos\theta\vert 00\rangle+\sin\theta\vert 11\rangle\) in Schmidt form and derive the analytic expression for its entanglement entropy. Extend the computation to the state \(\frac{1}{2}(\vert 00\rangle+\vert 01\rangle+\vert 10\rangle-\vert 11\rangle)\); is it entangled? Answer both by hand and with the Schmidt decomposition of
entanglement.py.No cloning. Suppose a unitary \(U\) on two qubits copies an arbitrary state, \(U\vert\psi\rangle\vert 0\rangle = \vert\psi\rangle\vert\psi\rangle\). Apply it to \(\vert 0\rangle\), \(\vert 1\rangle\) and \(\vert +\rangle\) and derive a contradiction with linearity. Explain why the teleportation protocol does not violate this theorem.
Circuits. Using the
Circuitclass, verify that (a) \(\mathrm{CNOT}=(\matr{I}\otimes H)\,\mathrm{CZ}\,(\matr{I}\otimes H)\), (b) a CNOT with control and target exchanged equals \((H\otimes H)\,\mathrm{CNOT}\,(H\otimes H)\), and (c) the circuit of Fig. 2.5(a) followed by \(X\) on the second qubit and \(Z\) on the first produces \(\vert\Psi^-\rangle\). Draw each circuit.Superdense coding and teleportation. Run
protocols.pyand modify the superdense-coding function so that the shared state is \(\vert\Psi^-\rangle\) instead of \(\vert\Phi^+\rangle\); which encoding operations must Alice now use? Then modify the teleportation function so that Bob’s correction is omitted, and compute Bob’s reduced density matrix averaged over Alice’s outcomes. Interpret the result.The two-level system. Show that with \(E_\pm=(E_1\pm E_2)/2\) the non-interacting part can be written as \(H_0=E_+\matr{I}+E_-Z\), and that with \(V_\pm=(V_{11}\pm V_{22})/2\) and \(V_o=V_{12}=V_{21}\) the interaction becomes \(H_I=V_+\matr{I}+V_-Z+V_oX\). Explain how \(\langle X\rangle\) is measured on a device that only measures in the computational basis, using \(X=HZH\). Finally compute the gradient of \(E(\theta,\phi)\) in Eq. (2.102) analytically and verify Eq. (2.104). Test gradient descent from several initial points, including stationary points, and compare with the exact minimum and both grid conventions in Section A first Hamiltonian: the two-level system. Estimate the uncertainty of an energy measured with \(N_X=N_Z=1000\) using Eq. (2.105).
Measurement and degeneracy. For \(\matr A=\mathrm{diag}(0,0,1)\) and \(\vert\psi\rangle=(\vert0\rangle+\vert1\rangle+\vert2\rangle)/\sqrt3\), find the outcome probabilities and the Lüders state after observing zero. Compare it with the state obtained by resolving \(\vert0\rangle,\vert1\rangle\) individually and then forgetting which of those two results occurred. Which coherence distinguishes them?
Controlled phases. Derive Eqs. (2.89) and (2.90). Apply controlled-\(Z\) to \(\vert+\rangle\vert1\rangle\) and explain how the control changes without changing its computational-basis probabilities. Why can a phase of an uncontrolled gate become observable after controlling it?
Noise and correlations. Derive Eq. (2.61) from the Kraus operators. Compare the purity trajectories starting from \(\vert0\rangle\), \(\vert+\rangle\) and \(\matr I/2\). Next compare \(\rho_{\Phi^+}\) with the separable mixture \((\vert00\rangle\langle00|+\vert11\rangle\langle11|)/2\). They have identical reduced states and identical \(ZZ\) correlations; which \(XX\) measurement distinguishes them?
Programs for this chapter#
The numerical tables and plots are generated by the programs in
LectureMaterial/BookPrograms/chapter2/ and from the shared modules in
LectureMaterial/BookPrograms/common/ that this chapter introduces and
the later chapters reuse. All of them are imported by the notebook
LectureMaterial/Notebooks/chapter2/chapter2.ipynb, and all
run on numpy and matplotlib alone.
The standalone listings printed in the text make the conventions and
selected input checks explicit; they do not replace the shared modules.
Run each listing with LectureMaterial/BookPrograms/common/ on
PYTHONPATH. The circuit diagrams are drawn directly in
LaTeX. The programs also verify the measurement conventions,
noise-channel limits, Schmidt truncation, teleportation branches and
analytic two-level results stated in the text.
common/gates.pyThe gate matrices of Table 2.3, the rotation gates and \(U(\theta,\phi,\lambda)\), the controlled-\(U\) construction, and helpers for commutators, tensor products and unitarity checks; run as a script it verifies every gate identity quoted in the text. Instantaneous.common/statevector.pyThe classStateVector: the \(2^N\) amplitudes of Eq. (2.1), gates on arbitrary subsets of qubits by tensor contraction, marginal probabilities, projective measurement with collapse, sampling of shots, expectation values. Instantaneous.common/circuit.pyThe classesGateandCircuit: gate lists with controls, execution on aStateVector, the full unitary, depth, inverse and an ASCII drawing; run as a script it checks the Bell circuits and the SWAP identity of Fig. 2.5. Instantaneous.common/density_matrix.pyThe classDensityMatrix: ensembles, Bloch vector, purity, Born rule and post-measurement state, unitary evolution, partial trace and von Neumann entropy, and the Shannon entropy. Instantaneous.common/bookplot.pyFigure directory and matplotlib conventions shared by all chapters.dirac_algebra.pyThe worked examples of Section Linear algebra in Dirac notation: inner and outer products, projectors, Pauli algebra, tensor products, spectral decomposition of a Hermitian matrix. Instantaneous.bloch_sphere.pyBloch angles and Bloch vectors, Table 2.1 and Fig. 2.1 with the Larmor precession of Eq. (2.83). A few seconds.measurement.pyThe Born rule, post-measurement states, the \(X\)-basis measurement, marginals in a three-qubit register and the shot-noise study of Fig. 2.2, degenerate measurements and joint Pauli correlations. A few seconds.decoherence.pyThe dephasing and amplitude-damping channels in Kraus form, their limiting cases and relaxation model, and Fig. 2.3. A second.entanglement.pyBell states, measurement correlations, reduced density matrices, the Schmidt decomposition through the singular value decomposition, Table 2.2 and Fig. 2.4, separable correlations and Schmidt truncation errors. A second.protocols.pySuperdense coding for all four messages and teleportation of 200 random states in every measurement branch, both on the state-vector simulator, with the circuit of Fig. 2.7. A second.two_level_system.pyThe two-level Hamiltonian in matrix and Pauli form, Table 2.4, the grid search over the trial state (2.100), including endpoint comparisons, analytic energies, gradients and shot variances, and Fig. 2.8. A few seconds.
Running the programs of this chapter#
Each cell below runs one of the programs listed above as a script and shows the figures it writes to BookFigures/.
import runpy, time
from IPython.display import Image, display
t0 = time.time()
runpy.run_path(str(root / 'BookPrograms' / 'common/gates.py'), run_name='__main__')
for png in sorted((root / 'BookFigures' / 'chapter2').glob('*.png')):
if png.stat().st_mtime >= t0:
display(Image(str(png)))
all gate identities verified
determinants of X, Y, Z: [-1.0, -1.0, -1.0]
import runpy, time
from IPython.display import Image, display
t0 = time.time()
runpy.run_path(str(root / 'BookPrograms' / 'common/statevector.py'), run_name='__main__')
for png in sorted((root / 'BookFigures' / 'chapter2').glob('*.png')):
if png.stat().st_mtime >= t0:
display(Image(str(png)))
Bell state |Phi+> = (+0.7071+0.0000j)|00> + (+0.7071+0.0000j)|11>
marginals of qubit 0: [0.5 0.5]
1000 shots: {'00': 507, '11': 493}
outcome 1 with probability 0.5000000000000001; post-measurement state: (+1.0000+0.0000j)|11>
state-vector simulator checks passed
import runpy, time
from IPython.display import Image, display
t0 = time.time()
runpy.run_path(str(root / 'BookPrograms' / 'common/circuit.py'), run_name='__main__')
for png in sorted((root / 'BookFigures' / 'chapter2').glob('*.png')):
if png.stat().st_mtime >= t0:
display(Image(str(png)))
Circuit(2 qubits, 2 gates, depth 2)
q0: |0>--[H]--*---
q1: |0>------(+)--
state: (+0.7071+0.0000j)|00> + (+0.7071+0.0000j)|11>
q0: |0>---*--(+)--*---
q1: |0>--(+)--*--(+)--
circuit checks passed
import runpy, time
from IPython.display import Image, display
t0 = time.time()
runpy.run_path(str(root / 'BookPrograms' / 'common/density_matrix.py'), run_name='__main__')
for png in sorted((root / 'BookFigures' / 'chapter2').glob('*.png')):
if png.stat().st_mtime >= t0:
display(Image(str(png)))
rho_A for |Phi+>:
[[0.5 0. ]
[0. 0.5]]
S(rho_A) = 1.0000000000000002 bit
density-matrix checks passed
import runpy, time
from IPython.display import Image, display
t0 = time.time()
runpy.run_path(str(root / 'BookPrograms' / 'common/bookplot.py'), run_name='__main__')
for png in sorted((root / 'BookFigures' / 'chapter2').glob('*.png')):
if png.stat().st_mtime >= t0:
display(Image(str(png)))
import runpy, time
from IPython.display import Image, display
t0 = time.time()
runpy.run_path(str(root / 'BookPrograms' / 'chapter2/dirac_algebra.py'), run_name='__main__')
for png in sorted((root / 'BookFigures' / 'chapter2').glob('*.png')):
if png.stat().st_mtime >= t0:
display(Image(str(png)))
<x|x> = 7.0 normalised x = [0.378 -0.378j 0.7559+0.378j]
<x|y> = (-1+1j) <y|x> = (-1-1j)
P = |0><0| =
[[1. 0.]
[0. 0.]]
Q = |1><1| =
[[0. 0.]
[0. 1.]]
P|psi> = [0.6+0.j 0. +0.j] Q|psi> = [0.+0.j 0.+0.8j]
rho = |psi><psi| =
[[0.36+0.j 0. -0.48j]
[0. +0.48j 0.64+0.j ]]
trace = 1.0
[X,Y] = 2iZ, XY = iZ, and cyclic permutations: verified
H|0> = [0.7071+0.j 0.7071+0.j] H|1> = [ 0.7071+0.j -0.7071+0.j]
|00> = [1. 0. 0. 0.]
|01> = [0. 1. 0. 0.]
|10> = [0. 0. 1. 0.]
|11> = [0. 0. 0. 1.]
|000> = [1. 0. 0. 0. 0. 0. 0. 0.]
A (x) B =
[[0 1 0 2]
[1 0 2 0]
[0 3 0 4]
[3 0 4 0]]
eigenvalues of A: [1. 4.]
lambda = 1.0000, projector
[[ 0.6667+0.j -0.3333+0.3333j]
[-0.3333-0.3333j 0.3333+0.j ]]
lambda = 4.0000, projector
[[0.3333+0.j 0.3333-0.3333j]
[0.3333+0.3333j 0.6667+0.j ]]
exp(A) from the spectral decomposition agrees with the power series
import runpy, time
from IPython.display import Image, display
t0 = time.time()
runpy.run_path(str(root / 'BookPrograms' / 'chapter2/bloch_sphere.py'), run_name='__main__')
for png in sorted((root / 'BookFigures' / 'chapter2').glob('*.png')):
if png.stat().st_mtime >= t0:
display(Image(str(png)))
state operator eigenvalue theta phi Bloch vector
|0> Z 1 0.00π 0.00π [0. 0. 1.]
|1> Z -1 1.00π 0.00π [ 0. 0. -1.]
|+> X 1 0.50π 0.00π [1. 0. 0.]
|-> X -1 0.50π 1.00π [-1. 0. 0.]
|+i> Y 1 0.50π 0.50π [0. 1. 0.]
|-i> Y -1 0.50π 1.50π [ 0. -1. 0.]
Global-phase invariance, both poles, and signed Larmor precession: verified
Bloch angles of psi = [0.5403+0.j 0.6436+0.5421j] -> theta=2.0, phi=0.7
figure written to BookFigures/chapter2/bloch_sphere.pdf
import runpy, time
from IPython.display import Image, display
t0 = time.time()
runpy.run_path(str(root / 'BookPrograms' / 'chapter2/measurement.py'), run_name='__main__')
for png in sorted((root / 'BookFigures' / 'chapter2').glob('*.png')):
if png.stat().st_mtime >= t0:
display(Image(str(png)))
outcome 0: probability 0.3000, post-measurement state [1.+0.j 0.+0.j]
outcome 1: probability 0.7000, post-measurement state [0. +0.j 0.9211+0.3894j]
Tr(P_0 rho) = 0.29999999999999993
<Z> = p0 - p1 = -0.4 <X> = 0.8441663449378976
P(+) = |<+|psi>|^2 = 0.9221 = P(0) after H = 0.9221
P(qubit 1 = 0), P(qubit 1 = 1) in |Psi> = [0.5 0.5]
after finding qubit 1 = 1 the register is (+0.8525+0.0000j)|110> + (+0.5227+0.0000j)|111>
Impossible postselection correctly rejected
Degenerate measurement: p(0) = 2/3; coherence after Luders = 1/2, after refinement = 0
Bell pair: <XX> = 1, while <X_A><X_B> = 0
figure written to BookFigures/chapter2/measurement_shots.pdf
import runpy, time
from IPython.display import Image, display
t0 = time.time()
runpy.run_path(str(root / 'BookPrograms' / 'chapter2/decoherence.py'), run_name='__main__')
for png in sorted((root / 'BookFigures' / 'chapter2').glob('*.png')):
if png.stat().st_mtime >= t0:
display(Image(str(png)))
rho(|+>) after one dephasing step with p = 0.1:
[[0.5 0.4]
[0.4 0.5]]
Phase-flip endpoints: p=0 identity, p=1/2 full dephasing, p=1 unitary Z
Amplitude damping: purity depends on the initial state and can increase
Independent Markovian relaxation model: 1/T2 = 1/(2*T1) + 1/Tphi verified
step purity (dephasing) purity (damping) <Z> (damping)
0 1.0000 1.0000 0.0000
5 0.6743 0.8877 0.3409
10 0.5608 0.8772 0.5656
20 0.5074 0.9235 0.8113
30 0.5009 0.9624 0.9180
figure written to BookFigures/chapter2/decoherence.pdf
import runpy, time
from IPython.display import Image, display
t0 = time.time()
runpy.run_path(str(root / 'BookPrograms' / 'chapter2/entanglement.py'), run_name='__main__')
for png in sorted((root / 'BookFigures' / 'chapter2').glob('*.png')):
if png.stat().st_mtime >= t0:
display(Image(str(png)))
Bell states form an orthonormal basis: Gram matrix =
[[ 1. -0. 0. 0.]
[-0. 1. 0. 0.]
[ 0. 0. 1. -0.]
[ 0. 0. -0. 1.]]
qubit A = 0 with probability 0.50; state afterwards (+1.0000+0.0000j)|00>
qubit A = 1 with probability 0.50; state afterwards (+1.0000+0.0000j)|11>
state rho_A purity S(rho_A) Schmidt coeffs
Phi+ [[0.5, 0.0], [0.0, 0.5]] 0.500 1.000 [0.7071, 0.7071]
Phi- [[0.5, 0.0], [0.0, 0.5]] 0.500 1.000 [0.7071, 0.7071]
Psi+ [[0.5, 0.0], [0.0, 0.5]] 0.500 1.000 [0.7071, 0.7071]
Psi- [[0.5, 0.0], [0.0, 0.5]] 0.500 1.000 [0.7071, 0.7071]
product state: Schmidt rank 1 , S(rho_A) = 0.0
random state: Schmidt coefficients [0.9863 0.1647] -> S(rho_A) = 0.1798 bit
Bell state and separable mixture: same marginals and ZZ, different XX (1 versus 0)
Schmidt truncation: discarded weight 0.060447, squared overlap 0.939553
theta/pi S(rho_A)
0.00 0.0000
0.05 0.1659
0.10 0.4545
0.15 0.7340
0.20 0.9300
0.25 1.0000
0.30 0.9300
0.35 0.7340
0.40 0.4545
0.45 0.1659
0.50 0.0000
figure written to BookFigures/chapter2/entropy.pdf
import runpy, time
from IPython.display import Image, display
t0 = time.time()
runpy.run_path(str(root / 'BookPrograms' / 'chapter2/protocols.py'), run_name='__main__')
for png in sorted((root / 'BookFigures' / 'chapter2').glob('*.png')):
if png.stat().st_mtime >= t0:
display(Image(str(png)))
superdense coding:
Alice sends 00 -> Bob reads 00
Alice sends 01 -> Bob reads 01
Alice sends 10 -> Bob reads 10
Alice sends 11 -> Bob reads 11
teleportation:
All 800 forced branches passed, including exact correction phases and Bob's unconditioned I/2 state
200 random states teleported exactly; outcomes of Alice's measurement: {(0, 0): 44, (0, 1): 46, (1, 0): 53, (1, 1): 57}
input state [0.8253+0.j 0.351 +0.4423j] -> Alice's bits (0, 0) -> Bob's Bloch vector [0.5794 0.7301 0.3624]
teleportation circuit before the measurements:
q0: |0>-----------*--[H]--
q1: |0>--[H]--*--(+)------
q2: |0>------(+)----------
import runpy, time
from IPython.display import Image, display
t0 = time.time()
runpy.run_path(str(root / 'BookPrograms' / 'chapter2/two_level_system.py'), run_name='__main__')
for png in sorted((root / 'BookFigures' / 'chapter2').glob('*.png')):
if png.stat().st_mtime >= t0:
display(Image(str(png)))
lambda = 1.0: eigenvalues [0.9802 3.0198]
ground state [ 0.0985+0.j -0.9951+0.j], |0>-component squared 0.0097
lambda E_0 E_1 |<0|E_0>|^2
0.000 0.0000 4.0000 1.0000
0.300 0.8984 3.1016 0.9993
0.600 1.7668 2.2332 0.9287
0.667 1.8667 2.1333 0.5000
0.700 1.8280 2.1720 0.2094
1.000 0.9802 3.0198 0.0097
Equal basis weights at lambda=0.66666667; smallest gap at lambda=0.66371681
Analytic minimum: theta=180 deg, phi=11.30993247 deg, E=0.9801960973
Independent-shot energy standard error (1000 shots each): 0.00877058
single ansatz theta=pi/2, phi=0.2pi: E = 2.0000
best grid point: theta = 170 deg, phi = 10 deg, E = 0.9960, E - E_0 = 0.0158
inclusive ten-degree grid: theta=180 deg, phi=10 deg, E=0.9804626115, E - E_0=0.0002665142
one-degree grid: theta = 180 deg, phi = 11 deg, E - E_0 = 1.49e-05
figure written to BookFigures/chapter2/two_level_system.pdf