Skip to main content
KetQat

Appearance

Lesson 145 min

Why quantum error correction works

Errors, redundancy, no-cloning, and the discretisation of errors.

After this lesson you can

  • Derive the exact failure probability of an n-fold classical repetition code under independent bit flips
  • Explain why no-cloning, continuous errors and measurement disturbance do not rule out quantum error correction
  • Expand a single-qubit error in the Pauli basis and predict the outcome probabilities of a syndrome measurement
  • Encode a qubit into the three-qubit bit-flip code and measure its parity checks without learning the encoded amplitudes
  • State the Knill-Laflamme conditions and use them to decide whether a set of errors is correctable
  • Describe the threshold idea qualitatively and distinguish it from a statement about any particular device

Read first: Measurement and probability, Multiple qubits and entanglement, Noise, limitations and modern hardware

The problem error correction solves

Every operation on today's qubits fails with some probability. A useful algorithm may need millions or billions of operations, so even a per-operation failure probability of one in a thousand makes it essentially certain that something goes wrong long before the end. Better hardware lowers that probability, but no physical device is perfect, and for long computations the required improvement is many orders of magnitude. Quantum error correction is the strategy of building reliable logical qubits out of unreliable physical ones, so that the logical failure probability can be made smaller than the physical one, and smaller still by spending more qubits.

This lesson explains why that is possible at all. At first sight quantum mechanics seems to forbid it: you cannot copy an unknown state, errors form a continuum rather than a finite list, and looking at a qubit disturbs it. Each obstacle turns out to have a precise answer, and together the answers form the basis of every code in this course. We start with the classical idea the quantum codes generalise.

The classical repetition code

Suppose a channel flips each transmitted bit independently with probability pp. To protect one bit, send it nn times (nn odd) and decode by majority vote. The vote fails exactly when more than half of the copies were flipped. The number of flips KK is binomially distributed, so the logical failure probability is

pL(n,p)=Pr⁡ ⁣[K>n2]=∑k=(n+1)/2n(nk)pk(1−p)n−k.p_L(n, p) = \Pr\!\left[K > \tfrac{n}{2}\right] = \sum_{k=(n+1)/2}^{n} \binom{n}{k} p^k (1-p)^{n-k}.

For n=3n = 3 the vote fails when two or three copies flip:

pL(3,p)=3p2(1−p)+p3=3p2−2p3.p_L(3,p) = 3p^2(1-p) + p^3 = 3p^2 - 2p^3.

Worked example. With p=0.1p = 0.1, pL(3,0.1)=3(0.01)−2(0.001)=0.028p_L(3, 0.1) = 3(0.01) - 2(0.001) = 0.028. With five copies, pL(5,0.1)=10(0.1)3(0.9)2+5(0.1)4(0.9)+(0.1)5=0.0081+0.00045+0.00001=0.00856p_L(5, 0.1) = 10(0.1)^3(0.9)^2 + 5(0.1)^4(0.9) + (0.1)^5 = 0.0081 + 0.00045 + 0.00001 = 0.00856. At p=0.01p = 0.01 the three-copy code gives pL=3×10−4−2×10−6=2.98×10−4p_L = 3\times10^{-4} - 2\times10^{-6} = 2.98\times10^{-4}, about 34 times better than an unprotected bit.

Three features of this formula carry over to every code we study.

  1. Polynomial suppression. For small pp the leading term is (nt+1)pt+1\binom{n}{t+1}p^{t+1} with t=(n−1)/2t = (n-1)/2: a code that corrects tt errors turns a rate pp into a rate of order pt+1p^{t+1}.
  2. A break-even point. Encoding helps only when pL(n,p)<pp_L(n,p) < p. For the repetition code this holds for every p<1/2p < 1/2; at p=1/2p = 1/2 the output is random whatever nn is. The value of pp below which a larger code beats a smaller one is the classical ancestor of a threshold.
  3. The decoder is part of the code. Majority vote is the minimum-weight decision: it assumes the smallest number of flips consistent with what it sees, which is the most likely explanation when p<1/2p < 1/2.

Three apparent obstacles

Try to repeat this construction for a qubit ∣ψ⟩=α∣0⟩+β∣1⟩\ket{\psi} = \alpha\ket{0} + \beta\ket{1}.

No-cloning. There is no unitary that maps ∣ψ⟩∣0⟩∣0⟩\ket{\psi}\ket{0}\ket{0} to ∣ψ⟩∣ψ⟩∣ψ⟩\ket{\psi}\ket{\psi}\ket{\psi} for every ∣ψ⟩\ket{\psi} (see the foundations course). So we cannot make three copies to vote on.

Errors are continuous. A classical bit is either flipped or not. A qubit can be rotated by any small angle about any axis, or partly decohere. If every one of infinitely many errors needed its own correction, no finite procedure could cope.

Measurement disturbs the state. Majority vote reads every copy. Reading a qubit in the computational basis collapses α∣0⟩+β∣1⟩\alpha\ket{0}+\beta\ket{1} to ∣0⟩\ket{0} or ∣1⟩\ket{1}, destroying exactly the information we want to protect.

These were taken seriously as arguments against quantum computing until Shor constructed a nine-qubit code that corrects an arbitrary error on any one qubit (Shor 1995), and Steane independently found a seven-qubit code (Steane 1996). The rest of this lesson shows how each obstacle is avoided, using the simplest example.

Redundancy without copies

Instead of copying the state, entangle it. The encoding circuit below maps α∣0⟩+β∣1⟩\alpha\ket{0}+\beta\ket{1} on qubit q0q_0, with q1,q2q_1, q_2 starting in ∣0⟩\ket{0}, to

∣ψL⟩=α∣000⟩+β∣111⟩.\ket{\psi_L} = \alpha\ket{000} + \beta\ket{111}.
Quantum circuit on 3 wires (q0, q1, q2). step 1: CNOT, control q0, target q1. step 2: CNOT, control q0, target q2.q0q1q2
Encoding one qubit into the three-qubit bit-flip code

This is not three copies of ∣ψ⟩\ket{\psi}: the product state ∣ψ⟩⊗3\ket{\psi}^{\otimes 3} contains terms such as α2β∣001⟩\alpha^2\beta\ket{001}, while ∣ψL⟩\ket{\psi_L} contains only ∣000⟩\ket{000} and ∣111⟩\ket{111}. The circuit is linear, so it does not violate no-cloning. What is redundant is the basis information: in each branch the three qubits agree. The two-dimensional subspace spanned by the logical basis states ∣0L⟩=∣000⟩\ket{0_L} = \ket{000} and ∣1L⟩=∣111⟩\ket{1_L} = \ket{111} is the code space.

Measuring parities, not qubits

A bit flip XX on one qubit takes ∣ψL⟩\ket{\psi_L} out of the code space, for example X0∣ψL⟩=α∣100⟩+β∣011⟩X_0\ket{\psi_L} = \alpha\ket{100} + \beta\ket{011}. To find the flipped qubit we do not read the qubits. We measure two parity checks, the observables Z0Z1Z_0Z_1 and Z1Z2Z_1Z_2, each with eigenvalues ±1\pm1. Their outcomes form the syndrome:

Error Z0Z1Z_0Z_1 Z1Z2Z_1Z_2 Syndrome (s1,s2)(s_1, s_2) Correction
none +1+1 +1+1 (0,0)(0,0) none
X0X_0 −1-1 +1+1 (1,0)(1,0) X0X_0
X1X_1 −1-1 −1-1 (1,1)(1,1) X1X_1
X2X_2 +1+1 −1-1 (0,1)(0,1) X2X_2

Here s=1s = 1 records eigenvalue −1-1. The key point is that both basis states of each branch give the same syndrome: ∣100⟩\ket{100} and ∣011⟩\ket{011} both have Z0Z1=−1Z_0Z_1 = -1 and Z1Z2=+1Z_1Z_2 = +1. The syndrome therefore says which error happened while revealing nothing about α\alpha and β\beta, and the measurement leaves the superposition intact. This answers the third obstacle: we measure only operators that are constant on the code space and its displaced copies, never the encoded information itself.

In a circuit, each check is copied onto an ancilla qubit by two CNOTs and the ancilla is measured:

Quantum circuit on 5 wires (q0, q1, q2, a0, a1). step 1: CNOT, control q0, target a0. step 2: CNOT, control q1, target a0. step 3: CNOT, control q1, target a1. step 4: CNOT, control q2, target a1. step 5: measure a0; measure a1.q0q1q2a0a1
Measuring Z0Z1 and Z1Z2 onto two ancillas

Ancilla a0a_0 ends in ∣x0⊕x1⟩\ket{x_0 \oplus x_1} for every basis state ∣x0x1x2⟩\ket{x_0x_1x_2}, so its outcome is the parity, and because the parity is the same in both branches of the superposition the ancilla does not become entangled with the encoded amplitudes. The next lesson treats this code, and its phase-flip partner, in full.

Errors become discrete

Now the second obstacle. Any single-qubit operator EE can be written in the Pauli basis,

E=cII+cXX+cYY+cZZ,cP=12Tr⁡ ⁣(P†E),E = c_I I + c_X X + c_Y Y + c_Z Z, \qquad c_P = \tfrac12 \tr\!\left(P^\dagger E\right),

because {I,X,Y,Z}\{I, X, Y, Z\} is an orthogonal basis of 2×22\times2 matrices under the trace inner product. Take a coherent over-rotation of qubit 0, RX(θ)=e−iθX/2=cos⁡(θ/2) I−isin⁡(θ/2) XR_X(\theta) = e^{-i\theta X/2} = \cos(\theta/2)\, I - i\sin(\theta/2)\, X. Applied to the encoded state it gives

RX(0)(θ)∣ψL⟩=cos⁡θ2 ∣ψL⟩−isin⁡θ2 X0∣ψL⟩.R_X^{(0)}(\theta)\ket{\psi_L} = \cos\tfrac{\theta}{2}\,\ket{\psi_L} - i\sin\tfrac{\theta}{2}\,X_0\ket{\psi_L}.

The two terms lie in orthogonal syndrome subspaces: the first has syndrome (0,0)(0,0), the second (1,0)(1,0). Measuring the syndrome therefore projects onto one term. With probability cos⁡2(θ/2)\cos^2(\theta/2) we see (0,0)(0,0) and the state is already ∣ψL⟩\ket{\psi_L}; with probability sin⁡2(θ/2)\sin^2(\theta/2) we see (1,0)(1,0), the state is X0∣ψL⟩X_0\ket{\psi_L} up to a global phase, and applying X0X_0 restores it. Either way the final state is exactly ∣ψL⟩\ket{\psi_L}.

Worked example. For θ=0.3\theta = 0.3 rad the syndrome is (1,0)(1,0) with probability sin⁡2(0.15)≈0.0223\sin^2(0.15) \approx 0.0223 and (0,0)(0,0) with probability ≈0.9777\approx 0.9777, and the corrected fidelity is 1 in both cases. The continuum of angles has collapsed onto two discrete events, "no error" and "X0X_0".

The argument is linear, so it extends to any error, including decoherence described by Kraus operators {Ek}\{E_k\}: expand each EkE_k in Paulis, and if the code corrects each Pauli term it corrects every linear combination of them. Correcting a finite set of Pauli errors is enough to correct every error in their linear span. This is the discretisation of errors, and it is why codes are designed and analysed against Pauli errors.

The bit-flip code is not a complete quantum code. A phase error ZjZ_j commutes with both checks, so the syndrome stays (0,0)(0,0), yet Z0∣ψL⟩=α∣000⟩−β∣111⟩Z_0\ket{\psi_L} = \alpha\ket{000} - \beta\ket{111} is a different logical state. Shor's code handles both types by nesting a phase-flip code around three bit-flip codes (Shor 1995).

You can check all of this numerically in a few lines:

import numpy as np

X = np.array([[0, 1], [1, 0]], dtype=complex)
Z = np.diag([1.0, -1.0]).astype(complex)
I = np.eye(2, dtype=complex)

def kron(*ops):
    out = np.array([[1.0 + 0j]])
    for op in ops:
        out = np.kron(out, op)
    return out

alpha, beta, theta = 0.6, 0.8j, 0.3
psi = np.zeros(8, dtype=complex)
psi[0], psi[7] = alpha, beta                      # alpha|000> + beta|111>
rx = np.cos(theta / 2) * I - 1j * np.sin(theta / 2) * X
damaged = kron(rx, I, I) @ psi                     # over-rotation of qubit 0

P = (np.eye(8) - kron(Z, Z, I)) / 2 @ (np.eye(8) + kron(I, Z, Z)) / 2  # syndrome (1, 0)
branch = P @ damaged
prob = np.vdot(branch, branch).real
corrected = kron(X, I, I) @ branch / np.sqrt(prob)
print(round(prob, 4), round(abs(np.vdot(psi, corrected)) ** 2, 12))  # 0.0223 1.0

The Knill-Laflamme conditions

When can a code correct a given set of errors? Let {∣iL⟩}\{\ket{i_L}\} be an orthonormal basis of the code space and {Ea}\{E_a\} a set of error operators. Knill and Laflamme proved (Knill and Laflamme 1997) the following.

Theorem (Knill-Laflamme conditions). There is a recovery operation that corrects every error in {Ea}\{E_a\}, and therefore every linear combination of them, if and only if

⟨iL∣Ea†Eb∣jL⟩=cab δijfor all i,j,a,b,\bra{i_L} E_a^\dagger E_b \ket{j_L} = c_{ab}\,\delta_{ij} \quad \text{for all } i, j, a, b,

where the numbers cabc_{ab} do not depend on ii and jj.

The conditions say two things. For i≠ji \ne j: an error must never map one logical state onto something overlapping a different logical state, or the errors would confuse logical information. For i=ji = j: the overlap ⟨iL∣Ea†Eb∣iL⟩\bra{i_L}E_a^\dagger E_b\ket{i_L} must be the same for every logical state, so no measurement that distinguishes errors can also learn anything about the encoded state. This is the precise form of "measure the error, not the data".

Example 1. For the bit-flip code with {I,X0,X1,X2}\{I, X_0, X_1, X_2\}: for a≠ba \ne b, Ea†EbE_a^\dagger E_b is a product of one or two XX's, which maps ∣000⟩\ket{000} and ∣111⟩\ket{111} to states of Hamming weight 1 or 2, orthogonal to both code words, so every entry is 0. For a=ba = b, Ea†Ea=IE_a^\dagger E_a = I gives δij\delta_{ij}. The conditions hold.

Example 2. With {I,Z0}\{I, Z_0\}: ⟨0L∣Z0∣0L⟩=+1\bra{0_L}Z_0\ket{0_L} = +1 but ⟨1L∣Z0∣1L⟩=−1\bra{1_L}Z_0\ket{1_L} = -1, so cIZ0c_{IZ_0} would have to equal both. The conditions fail, matching the earlier observation that the bit-flip code cannot see phase errors.

Example 3. With {X0,X1X2}\{X_0, X_1X_2\}: X0†X1X2=X0X1X2X_0^\dagger X_1X_2 = X_0X_1X_2 maps ∣000⟩\ket{000} to ∣111⟩\ket{111}, so ⟨1L∣X0X1X2∣0L⟩=1≠0\bra{1_L}X_0X_1X_2\ket{0_L} = 1 \ne 0. A single flip on qubit 0 and a double flip on qubits 1 and 2 have the same syndrome but differ by the logical operator X0X1X2X_0X_1X_2, so no decoder can handle both. This is why a code that corrects all single errors still fails on some double errors.

The threshold idea

So far a code reduces pp to roughly c pt+1c\,p^{t+1}, assuming perfect encoding, syndrome measurement and correction. Real syndrome circuits are built from the same noisy gates, and they can introduce errors faster than they remove them. Two results make the situation hopeful.

First, error correction can be made fault-tolerant: circuits can be designed so that a single fault causes at most a correctable pattern of errors. Second, codes can be scaled. In the concatenation argument, each level of encoding maps an error rate pp to about c p2c\,p^2, so after ℓ\ell levels the rate is about (cp)2ℓ/c(cp)^{2^\ell}/c, which falls doubly exponentially in ℓ\ell when cp<1cp < 1.

Theorem (threshold theorem, informal). For noise that is sufficiently weak and sufficiently local (independent or weakly correlated faults), there is a constant pth>0p_{\text{th}} > 0 such that any quantum circuit can be simulated to any desired accuracy with only polylogarithmic overhead, provided every physical operation fails with probability below pthp_{\text{th}}. Precise versions with explicit noise models were proved by Aharonov and Ben-Or (1999) and, with a rigorous lower bound of 2.73×10−52.73\times10^{-5} for adversarial independent stochastic noise and concatenated distance-3 codes, by Aliferis, Gottesman and Preskill (2006).

A threshold is a property of a noise model, a code family and a decoder together, not of a device or of a code alone. Rigorous proofs give conservative lower bounds; numerical studies of specific codes under specific noise models give much higher estimates, which we will compute ourselves for the surface code later in the course. A device is "below threshold" for a code only in the operational sense that its logical error rate decreases as the code grows, which has to be measured.

Common mistakes

  • "Encoding copies the state." α∣000⟩+β∣111⟩\alpha\ket{000}+\beta\ket{111} is an entangled state, not ∣ψ⟩⊗3\ket{\psi}^{\otimes 3}. The redundancy is in the correlations, not in copies.
  • Measuring the data to find the error. Measuring individual qubits collapses the encoded state. Only operators that act identically on all logical states, such as Z0Z1Z_0Z_1, may be measured.
  • Thinking small rotations need small corrections. The syndrome measurement discretises the error; the correction is always a full Pauli (or nothing), applied with the probability the measurement dictates.
  • Treating the bit-flip code as a full quantum code. It detects no phase errors at all, and its distance against arbitrary Pauli errors is 1.
  • Quoting a threshold without its assumptions. A threshold value means nothing without the noise model, the code family, the decoder and the unit of the error rate.

Summary

  • The classical repetition code turns a flip rate pp into pL=∑k>n/2(nk)pk(1−p)n−kp_L = \sum_{k>n/2}\binom{n}{k}p^k(1-p)^{n-k}, which is 3p2−2p33p^2-2p^3 for three copies.
  • Quantum codes replace copies by entanglement, majority vote by measurement of parity checks, and continuous errors by their Pauli components.
  • Syndrome measurement reveals the error without revealing the logical state, and it projects any error onto a discrete Pauli error.
  • The Knill-Laflamme conditions decide exactly which error sets a code can correct.
  • The threshold theorem says that below a model-dependent error rate, arbitrarily reliable computation is possible with modest overhead.

The exercise asks you to verify these statements numerically: the exact repetition formula against Monte Carlo, the projection of coherent rotations onto discrete errors, and the Knill-Laflamme conditions for correctable and uncorrectable error sets. Next, the repetition code works through bit-flip and phase-flip codes, their syndromes and logical error rates, and their use as a memory over many rounds. For a textbook treatment of this material see Nielsen and Chuang, chapter 10.

Exercises

Run these on your own computer. Each comes with automated checks: python -m pytest test_exercise.py. Nothing you write is sent to KetQat.

Majority vote, discretised errors and the Knill-Laflamme conditions

introductory · about 45 min · needs numpy, pytest

In this exercise you check, with small state-vector calculations, the three ideas the lesson builds on: the exact failure probability of a classical repetition code, the fact that measuring a syndrome turns a continuous error into a discrete one, and the Knill-Laflamme conditions that decide whether a set of errors is correctable.

Conventions: qubit 0 is the leftmost tensor factor and the most significant bit of a basis index, so ∣q0q1q2⟩\ket{q_0q_1q_2} has index 4q0+2q1+q24q_0 + 2q_1 + q_2. RX(θ)=e−iθX/2R_X(\theta) = e^{-i\theta X/2}.

Functions to implement in starter.py

Function Contract
majority_failure_probability(n, p) Exact probability that a majority vote over n (odd) independently flipped copies fails. ValueError for even n or p outside [0,1][0,1].
pauli_coefficients(u) Coefficients cPc_P of a 2×22\times 2 matrix in the basis {I,X,Y,Z}\{I, X, Y, Z\}, as a dict.
encode_bit_flip(alpha, beta) The normalised vector α∣000⟩+β∣111⟩\alpha\ket{000}+\beta\ket{111}.
apply_single_qubit(state, u, qubit) Apply u to one qubit of a 3-qubit state.
syndrome_projectors() The four projectors onto the joint eigenspaces of Z0Z1Z_0Z_1 and Z1Z2Z_1Z_2, keyed by (s1, s2) with 1 meaning eigenvalue −1-1.
correct_after_error(alpha, beta, u, qubit) Encode, apply u, measure the syndrome by projection, apply the correction table, and report each syndrome's probability and the fidelity with the encoded state afterwards.
knill_laflamme_holds(codewords, errors) Decide whether ⟨i∣Ea†Eb∣j⟩=cabδij\bra{i}E_a^\dagger E_b\ket{j} = c_{ab}\delta_{ij} holds.

The private helpers _kron_all and _pauli_string are provided.

What the checks verify

  • The three-copy failure probability equals the closed form 3p2−2p33p^2-2p^3; the nn-copy formula satisfies P(p)+P(1−p)=1P(p) + P(1-p) = 1 and agrees with a seeded Monte Carlo run within five standard errors.
  • The Pauli coefficients rebuild a random matrix and give cos⁡(θ/2)\cos(\theta/2) and −isin⁡(θ/2)-i\sin(\theta/2) for RX(θ)R_X(\theta).
  • The projectors are orthogonal, sum to the identity and each has rank 2.
  • After a coherent RX(θ)R_X(\theta) on any qubit, the syndrome is (0,0)(0,0) with probability cos⁡2(θ/2)\cos^2(\theta/2) and the matching single-flip syndrome with probability sin⁡2(θ/2)\sin^2(\theta/2), and every branch is corrected with fidelity 1. A phase rotation is invisible to this code and damages the state.
  • The Knill-Laflamme conditions hold for {I,X0,X1,X2}\{I, X_0, X_1, X_2\} and for linear combinations of those errors, and fail for {I,Z0}\{I, Z_0\} and for {X0,X1X2}\{X_0, X_1X_2\}.

Run the checks

python -m pytest test_exercise.py

Every check fails with NotImplementedError until you implement the functions.

Terminal
python -m pip install numpy pytest

starter.py

Python
"""Starter: discretisation of errors and the Knill-Laflamme conditions.

Conventions: qubit 0 is the leftmost tensor factor and the most significant bit
of a basis index, so |q0 q1 q2> has index 4*q0 + 2*q1 + q2.
"""

from __future__ import annotations

import math

import numpy as np

I2 = np.eye(2, dtype=complex)
X = np.array([[0, 1], [1, 0]], dtype=complex)
Y = np.array([[0, -1j], [1j, 0]], dtype=complex)
Z = np.array([[1, 0], [0, -1]], dtype=complex)
PAULIS = {"I": I2, "X": X, "Y": Y, "Z": Z}


def _kron_all(factors):
    out = np.array([[1.0 + 0j]])
    for f in factors:
        out = np.kron(out, f)
    return out


def _pauli_string(label: str) -> np.ndarray:
    return _kron_all([PAULIS[ch] for ch in label])


def majority_failure_probability(n: int, p: float) -> float:
    """Exact probability that majority vote over n independent copies fails.

    Each copy is flipped independently with probability p; the vote fails when more
    than n/2 copies are flipped. Raise ValueError unless n is a positive odd integer
    and 0 <= p <= 1.
    """
    raise NotImplementedError("majority_failure_probability: implement this function")


def pauli_coefficients(u: np.ndarray) -> dict[str, complex]:
    """Coefficients c_P with u = sum_P c_P P over P in {I, X, Y, Z}.

    Returns a dict with keys "I", "X", "Y", "Z" and complex values. Hint: the Paulis
    are orthogonal under the trace inner product, Tr(P^dag Q) = 2 delta_PQ.
    """
    raise NotImplementedError("pauli_coefficients: implement this function")


def encode_bit_flip(alpha: complex, beta: complex) -> np.ndarray:
    """alpha|000> + beta|111> as a complex length-8 vector, normalised.

    Raise ValueError if alpha and beta are both zero.
    """
    raise NotImplementedError("encode_bit_flip: implement this function")


def apply_single_qubit(state: np.ndarray, u: np.ndarray, qubit: int) -> np.ndarray:
    """Apply the 2x2 matrix u to qubit 0, 1 or 2 of a 3-qubit state vector.

    Qubit 0 is the leftmost tensor factor (most significant bit of the index).
    """
    raise NotImplementedError("apply_single_qubit: implement this function")


def syndrome_projectors() -> dict[tuple[int, int], np.ndarray]:
    """Projectors onto the joint eigenspaces of Z0Z1 and Z1Z2.

    Key (s1, s2): s1 = 0 for eigenvalue +1 of Z0Z1 and 1 for -1; s2 likewise for Z1Z2.
    """
    raise NotImplementedError("syndrome_projectors: implement this function")


def correct_after_error(alpha: complex, beta: complex, u: np.ndarray, qubit: int) -> list[dict]:
    """Encode, apply u to one qubit, measure the syndrome, correct.

    Measure the syndrome by projecting with syndrome_projectors(), then apply the
    correction table (0, 0) -> nothing, (1, 0) -> X on qubit 0, (1, 1) -> X on
    qubit 1, (0, 1) -> X on qubit 2.

    Returns one dict per syndrome with non-negligible probability (> 1e-12):
    {"syndrome": (s1, s2), "probability": float, "fidelity": float}, where fidelity
    is |<encoded|corrected>|^2 for the normalised post-correction state.
    """
    raise NotImplementedError("correct_after_error: implement this function")


def knill_laflamme_holds(codewords: list[np.ndarray], errors: list[np.ndarray], atol: float = 1e-9) -> bool:
    """Check the Knill-Laflamme conditions numerically.

    codewords: orthonormal basis vectors of the code space. errors: matrices E_a.
    Return True when <i|E_a^dag E_b|j> = c_ab delta_ij (within atol) for all
    codewords i, j and all pairs of errors a, b, with c_ab independent of i.
    """
    raise NotImplementedError("knill_laflamme_holds: implement this function")

test_exercise.py

Python
import importlib.util
import os
from pathlib import Path

def _load_target():
    name = os.environ.get("KETQAT_COMMONS_TARGET", "starter")
    path = Path(__file__).with_name(f"{name}.py")
    spec = importlib.util.spec_from_file_location(f"{Path(__file__).parent.name}_{name}", path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

target = _load_target()

import math

import numpy as np
import pytest

X = np.array([[0, 1], [1, 0]], dtype=complex)
Z = np.array([[1, 0], [0, -1]], dtype=complex)
I2 = np.eye(2, dtype=complex)


def rx(theta):
    return np.array([[math.cos(theta / 2), -1j * math.sin(theta / 2)], [-1j * math.sin(theta / 2), math.cos(theta / 2)]])


def kron(*fs):
    out = np.array([[1.0 + 0j]])
    for f in fs:
        out = np.kron(out, f)
    return out


# --- classical repetition -------------------------------------------------

@pytest.mark.parametrize("p", [0.0, 0.01, 0.1, 0.3, 0.5, 0.9])
def test_majority_three_matches_closed_form(p):
    # Independent value: 3p^2(1-p) + p^3 = 3p^2 - 2p^3.
    assert target.majority_failure_probability(3, p) == pytest.approx(3 * p**2 - 2 * p**3, abs=1e-12)


def test_majority_symmetry_and_half():
    # Swapping the roles of right and wrong copies: P_fail(p) + P_fail(1-p) = 1 for odd n.
    for n in (1, 5, 9):
        for p in (0.07, 0.2, 0.45):
            assert target.majority_failure_probability(n, p) + target.majority_failure_probability(n, 1 - p) == pytest.approx(1.0)
        assert target.majority_failure_probability(n, 0.5) == pytest.approx(0.5)


def test_majority_monte_carlo_agreement():
    rng = np.random.default_rng(12345)
    n, p, shots = 5, 0.2, 200_000
    flips = rng.random((shots, n)) < p
    observed = np.mean(flips.sum(axis=1) > n // 2)
    exact = target.majority_failure_probability(n, p)
    sigma = math.sqrt(exact * (1 - exact) / shots)
    assert abs(observed - exact) < 5 * sigma


def test_majority_rejects_even_n():
    with pytest.raises(ValueError):
        target.majority_failure_probability(4, 0.1)


# --- Pauli expansion ------------------------------------------------------

def test_pauli_coefficients_reconstruct_random_matrix():
    rng = np.random.default_rng(7)
    u = rng.normal(size=(2, 2)) + 1j * rng.normal(size=(2, 2))
    c = target.pauli_coefficients(u)
    Y = np.array([[0, -1j], [1j, 0]])
    rebuilt = c["I"] * I2 + c["X"] * X + c["Y"] * Y + c["Z"] * Z
    assert np.allclose(rebuilt, u)


def test_pauli_coefficients_of_rotation():
    theta = 0.37
    c = target.pauli_coefficients(rx(theta))
    assert c["I"] == pytest.approx(math.cos(theta / 2))
    assert c["X"] == pytest.approx(-1j * math.sin(theta / 2))
    assert abs(c["Y"]) < 1e-12 and abs(c["Z"]) < 1e-12


# --- the three-qubit code -------------------------------------------------

def test_encoding_and_projectors():
    state = target.encode_bit_flip(0.6, 0.8j)
    assert state.shape == (8,)
    assert state[0] == pytest.approx(0.6) and state[7] == pytest.approx(0.8j)
    projs = target.syndrome_projectors()
    assert set(projs) == {(0, 0), (0, 1), (1, 0), (1, 1)}
    total = sum(projs.values())
    assert np.allclose(total, np.eye(8))
    for key, proj in projs.items():
        assert np.allclose(proj @ proj, proj)
        assert round(np.trace(proj).real) == 2
    # An X error on qubit 0 lands in the (1, 0) eigenspace: Z0Z1 = -1, Z1Z2 = +1.
    damaged = kron(X, I2, I2) @ state
    assert np.allclose(projs[(1, 0)] @ damaged, damaged)


@pytest.mark.parametrize("qubit", [0, 1, 2])
@pytest.mark.parametrize("theta", [0.0, 0.3, 1.1, math.pi / 2, 2.9])
def test_coherent_rotation_is_discretised_and_corrected(qubit, theta):
    alpha, beta = 0.6, 0.8 * np.exp(0.4j)
    results = target.correct_after_error(alpha, beta, rx(theta), qubit)
    probs = {r["syndrome"]: r["probability"] for r in results}
    flipped = {0: (1, 0), 1: (1, 1), 2: (0, 1)}[qubit]
    # Independent value: the syndrome measurement selects "no error" with
    # probability cos^2(theta/2) and "X on this qubit" with sin^2(theta/2).
    assert probs.get((0, 0), 0.0) == pytest.approx(math.cos(theta / 2) ** 2, abs=1e-9)
    assert probs.get(flipped, 0.0) == pytest.approx(math.sin(theta / 2) ** 2, abs=1e-9)
    assert sum(probs.values()) == pytest.approx(1.0)
    for r in results:
        assert r["fidelity"] == pytest.approx(1.0, abs=1e-9)


def test_phase_error_is_not_corrected_by_bit_flip_code():
    # Z on one qubit commutes with both checks: syndrome (0, 0), and it flips the relative sign.
    rz = np.diag([np.exp(-0.5j), np.exp(0.5j)])  # R_Z(1.0)
    results = target.correct_after_error(1 / math.sqrt(2), 1 / math.sqrt(2), rz, 1)
    assert [r["syndrome"] for r in results] == [(0, 0)]
    assert results[0]["fidelity"] == pytest.approx(math.cos(0.5) ** 2, abs=1e-9)


# --- Knill-Laflamme -------------------------------------------------------

def _codewords():
    zero = np.zeros(8, dtype=complex)
    zero[0] = 1
    one = np.zeros(8, dtype=complex)
    one[7] = 1
    return [zero, one]


def test_knill_laflamme_bit_flips_satisfied():
    errors = [kron(I2, I2, I2), kron(X, I2, I2), kron(I2, X, I2), kron(I2, I2, X)]
    assert target.knill_laflamme_holds(_codewords(), errors) is True


def test_knill_laflamme_phase_flip_violated():
    errors = [kron(I2, I2, I2), kron(Z, I2, I2)]
    assert target.knill_laflamme_holds(_codewords(), errors) is False


def test_knill_laflamme_weight_one_and_two_violated():
    # X0 and X1X2 differ by the logical operator X0X1X2: indistinguishable syndromes.
    errors = [kron(X, I2, I2), kron(I2, X, X)]
    assert target.knill_laflamme_holds(_codewords(), errors) is False


def test_knill_laflamme_closed_under_linear_combinations():
    # Correctable set {I, X_j} implies every linear combination is correctable too.
    errors = [kron(I2, I2, I2), kron(rx(0.8), I2, I2), kron(I2, rx(-1.3), I2)]
    assert target.knill_laflamme_holds(_codewords(), errors) is True

Check your understanding

8 questions. Pass with 70% of the points. Answers are checked on the server; retakes are allowed. Explanations appear once you pass or after three complete attempts.

  1. A bit is sent three times through a channel that flips each copy independently with probability p=0.05p = 0.05, and decoded by majority vote. What is the probability that the decoded bit is wrong?

    1 pt
  2. Implement majority_failure_probability in the exercise and evaluate it for n=7n = 7 copies and p=0.05p = 0.05. Enter the result.

    2 pts

    Computed by running exercise “error-discretisation” on your computer.

  3. Why does the encoding α∣0⟩+β∣1⟩↦α∣000⟩+β∣111⟩\alpha\ket{0} + \beta\ket{1} \mapsto \alpha\ket{000} + \beta\ket{111} not contradict the no-cloning theorem?

    1 pt
  4. The state 0.6∣000⟩+0.8∣111⟩0.6\ket{000} + 0.8\ket{111} suffers a coherent rotation RX(θ)=e−iθX/2R_X(\theta) = e^{-i\theta X/2} with θ=0.5\theta = 0.5 rad on qubit 1 (the middle qubit). The checks Z0Z1Z_0Z_1 and Z1Z2Z_1Z_2 are then measured. What is the probability of the syndrome (1,1)(1,1)? (You can confirm it with correct_after_error from the exercise.)

    1 pt
  5. Which syndrome (s1,s2)(s_1, s_2) of the checks (Z0Z1,Z1Z2)(Z_0Z_1, Z_1Z_2) does a bit flip on qubit 1 produce, with s=1s = 1 meaning eigenvalue −1-1?

    1 pt
  6. A phase error Z0Z_0 hits the bit-flip code state α∣000⟩+β∣111⟩\alpha\ket{000}+\beta\ket{111}. What happens?

    1 pt
  7. Select every true statement about the Knill-Laflamme conditions ⟨iL∣Ea†Eb∣jL⟩=cabδij\bra{i_L}E_a^\dagger E_b\ket{j_L} = c_{ab}\delta_{ij}.

    1 pt

    Select all that apply.

  8. Which statement about an error-correction threshold is accurate?

    1 pt

Sign in with GitHub to check answers and save progress. Reading stays free without an account.

References

  1. Peter W. Shor (1995). Scheme for reducing decoherence in quantum computer memory. Physical Review A 52, R2493-R2496. doi:10.1103/PhysRevA.52.R2493
  2. Andrew M. Steane (1996). Error Correcting Codes in Quantum Theory. Physical Review Letters 77, 793-797. doi:10.1103/PhysRevLett.77.793
  3. Emanuel Knill, Raymond Laflamme (1997). Theory of quantum error-correcting codes. Physical Review A 55, 900-911. doi:10.1103/PhysRevA.55.900
  4. Dorit Aharonov, Michael Ben-Or (1999). Fault-Tolerant Quantum Computation With Constant Error Rate. arXiv:quant-ph/9906129
  5. Panos Aliferis, Daniel Gottesman, John Preskill (2006). Quantum accuracy threshold for concatenated distance-3 codes. Quantum Information and Computation 6, 97-165. arXiv:quant-ph/0504218
  6. Michael A. Nielsen, Isaac L. Chuang (2010). Quantum Computation and Quantum Information (10th Anniversary Edition). Cambridge University Press. doi:10.1017/CBO9780511976667