Lecture 0 treated a surface code as a box labelled RotatedPlanarCode(3, 3). This lecture opens the box. The theory of stabilizer codes turns quantum error correction into linear algebra over the two-element field : a code becomes a pair of binary matrices, a syndrome a matrix–vector product, and the code’s parameters ranks and minimum weights that a computer can find.

It condenses four weeks of a first course into one sitting, and ends by reading the parity-check matrices out of Deltakit’s code classes to recompute the numbers in the label of the smallest rotated surface code (the -distance is left as an exercise).

Notebook and field map

This lecture has no notebook of its own: the code blocks below run as they are, in order, in one Python session. Notebook 2: Stim and detectors continues from here with circuits. Field map: The Pauli group, Stabilizer groups, Syndromes and logical operators, Code distance, CSS codes and the binary picture, The repetition code.

Why Pauli errors are enough

Start classically. Store a bit as three copies, and , let each copy flip independently with probability , and decode by majority vote. The vote fails only if two or three copies flip, so the logical error probability is

which is smaller than whenever . Redundancy plus a vote turns an error rate into one of order .

Three facts seem to block a quantum version. An unknown state cannot be copied. Looking at a qubit to vote on it collapses its superposition. And quantum errors form a continuum: a small rotation is an error for every angle . Each obstacle has an answer. We do not copy the state, we entangle it: . We do not measure the qubits, only parities such as and , which take the same value on both branches and so reveal nothing about and . And the continuum collapses under that same parity measurement.

To see the last point, apply to an encoded state . The result is a superposition of “no error” and ” happened”. Measuring gives on the first branch and on the second, so the measurement picks a branch: with probability the state is again, and with probability it is exactly , which we know how to undo. In general, every operator on one qubit is a linear combination of , and every operator on a set of qubits is a combination of Pauli strings on that set. A code that corrects every Pauli error on a set of qubits therefore corrects every error on that set, by linearity. This is why the rest of QEC is phrased in terms of the Pauli group (Definition 1.1).

Definition 1.1 (Pauli group).

The -qubit Pauli group is the set of operators with and each . The weight is the number of factors that are not .

Two Pauli strings either commute or anticommute. Two single-qubit factors anticommute exactly when both are non-identity and different, so and anticommute exactly when the number of positions where they clash in this way is odd. Stim’s PauliString does this bookkeeping, phases included. It prints the identity as _.

import deltakit_stim as stim
 
a = stim.PauliString("XYZ")
b = stim.PauliString("IXZ")
print("a*b =", a * b, "| commute:", a.commutes(b))
print("X*Z =", stim.PauliString("X") * stim.PauliString("Z"))
print("weight of a:", a.weight)
a*b = -iXZ_ | commute: False
X*Z = -iY
weight of a: 3

Here and clash only in the middle position ( against ), an odd number of times, so they anticommute.

Stabilizer groups, syndromes and logical operators

Definition 1.2 (Stabilizer code).

A stabilizer group is an abelian subgroup of that does not contain . Its code space is the set of states fixed by every element, . If has independent generators , the code space has dimension , so it stores logical qubits.

The dimension count in Definition 1.2 takes one line. The projector onto the code space is , and every element of other than is a Pauli string with trace zero, so . Excluding is what keeps the code space from being empty. The bit-flip code above is with , and ; its code space is spanned by and .

Now let a Pauli error hit a code state . For each generator, either or , so

where if commutes with and if it anticommutes. Measuring returns with certainty and leaves the state alone. The bit string is the syndrome. It depends only on the error, never on the encoded data, which is why measuring it is safe. In the bit-flip code, , and have syndromes , and : three single errors, three different syndromes, so one bit flip can always be located.

Errors with zero syndrome come in two kinds. The Pauli strings that commute with every element of form its normalizer . Elements of itself act as the identity on the code space. Elements of that are not in , even up to a phase, map the code space to itself but act on it nontrivially: they are logical operators. In the bit-flip code, and commute with both checks, are not in , and anticommute with each other, so they act as and on the encoded qubit. The figure sorts every Pauli error into three classes.

Pauli error E syndrome of E zero? no detected decoder sees it yes E in S, up to phase? yes harmless acts as identity no logical error E in N(S) but not in S lightest such E: weight d (distance)

Distance, degeneracy and when correction works

Definition 1.3 (Distance).

The distance of a stabilizer code is the smallest weight of a logical operator, . A code with physical qubits, logical qubits and distance is an code.

By Definition 1.3 the bit-flip code, with its weight-one , is only as a quantum code. It corrects any one bit flip but no phase flip at all. That asymmetry is the defining weakness of repetition codes, and the reason surface codes exist.

When can a set of errors be corrected? The general answer is the Knill–Laflamme condition.

Theorem 1.1 (Knill–Laflamme condition).

Let project onto the code space. A set of errors can be corrected if and only if for all , with numbers that do not depend on the encoded state.

For Pauli errors on a stabilizer code, is again a Pauli string, and there are three possibilities. If it anticommutes with some generator, . If it is in up to a phase, is a multiple of . If it is in , it is a nontrivial logical operator and the condition fails. So the Knill–Laflamme condition (Theorem 1.1) says that a set of Pauli errors is correctable exactly when no product is a logical operator. If every error has weight at most , every product has weight at most . A distance- code therefore corrects all errors of weight up to , and detects all errors of weight up to .

The same reasoning describes what a decoder does. Given a syndrome, it picks some Pauli with that syndrome and applies it. The net operator has zero syndrome, so it is either in or a logical operator. In the first case the correction worked, even if . In the second, a logical error happened and nothing signals it.

Remark 1.1 (Degeneracy).

Errors that differ by a stabilizer, with , have the same syndrome and the same effect on the code space. A code is degenerate when such pairs occur among the errors it is meant to correct. In Shor’s code is a stabilizer, so and are the same error as far as the code is concerned. A decoder should therefore ask not “which error happened?” but “which class happened?”, and the most likely class need not contain the most likely single error.

Degeneracy (Remark 1.1) has no classical analogue, and it is one reason quantum decoding differs from classical decoding; Lecture 5 returns to it.

The binary picture and CSS codes

Phases rarely matter for error correction, and without them a Pauli string is just two bit strings. Write for , so that on each qubit , and . Multiplying Pauli strings adds their vectors mod 2, and commutation becomes a bilinear form.

Definition 1.4 (Symplectic product and check matrix).

For and in , the symplectic product is , and the two Pauli strings commute exactly when it is . A stabilizer group with generators is described by its check matrix , whose rows are the generators’ vectors. The generators commute exactly when , with , and the syndrome of an error is .

Counting clashes was the symplectic product (Definition 1.4) in disguise: position contributes , which is exactly when the two factors are non-identity and different. Stim hands you the two bit strings:

x, z = stim.PauliString("XYZ").to_numpy()
print("x =", x.astype(int).tolist(), "  z =", z.astype(int).tolist())
x = [1, 1, 0]   z = [0, 1, 1]

Most codes in use have generators that are each made only of s or only of s. Then the check matrix is block diagonal, and everything splits in two.

Definition 1.5 (CSS code).

A CSS code (after Calderbank, Shor and Steane) has check matrix : the rows of are the supports of its -type generators, the rows of those of its -type generators. The generators commute if and only if over , and the code has logical qubits.

Everything about a CSS code (Definition 1.5) has a matrix form. The checks see only the part of an error and the checks only the part: and . So and errors can be decoded separately, and a error is one of each. An -type logical operator is a vector in (it passes every check) that is not in (it is not a product of checks), and the classes form a space of dimension . The -distance is the smallest weight of such a vector, is the same with the roles swapped, and . Ranks come from Gaussian elimination mod 2, so is cheap; the distance is a minimum-weight problem, hard in general but easy by brute force for small .

Familiar codes in this language: the repetition code has no checks and is the matrix of neighbouring pairs, so , and . The Steane code takes equal to the parity-check matrix of the classical Hamming code, which satisfies , and is . Kitaev’s toric code on an torus is , and the rotated surface code of Lecture 3 is . The five-qubit code, the smallest that corrects any single-qubit error, has generator and its cyclic shifts. It is not CSS: it mixes and inside one generator, and only the full check matrix describes it.

In Deltakit

Deltakit’s code classes live in deltakit.explorer.codes (Deltakit spells it “stabiliser”), and every CSS code exposes its pair as parity_check_matrices. Rows are checks and columns are data qubits; ancilla qubits do not appear.

import numpy as np
from deltakit.explorer.codes import RotatedPlanarCode
 
code = RotatedPlanarCode(width=3, height=3)
hx, hz = code.parity_check_matrices
print("H_X", hx.shape, hx.dtype, "  H_Z", hz.shape, hz.dtype)
print("check weights: X", sorted(hx.sum(axis=1).tolist()),
      " Z", sorted(hz.sum(axis=1).tolist()))
H_X (4, 9) uint8   H_Z (4, 9) uint8
check weights: X [2, 2, 4, 4]  Z [2, 2, 4, 4]

Each kind has two weight-four checks on square plaquettes and two weight-two checks on the boundary. The row order follows set iteration inside Deltakit and changes from run to run, even with PYTHONHASHSEED fixed, so the block prints only order-free facts. The column order is fixed: data qubits sorted by coordinates. The figure shows both matrices on the lattice. (It draws downwards; Lecture 3 draws it upwards, where the bottom row here is the top row.)

stabilizer checks Z Z Z Z X X X X 0 1 2 3 4 5 6 7 8 logical operators 0 1 2 3 4 5 6 7 8 Z_L X_L (1,1) (5,5) solid: X checks, dashed: Z checks x to the right, y down

Now the CSS conditions of Definition 1.5, recomputed with a twelve-line Gaussian elimination over (subtracting is XOR):

def gf2_rank(m):
    """Rank over F_2, by Gaussian elimination with XOR."""
    m = np.array(m, dtype=np.uint8) % 2
    rank = 0
    for col in range(m.shape[1]):
        rows = rank + np.flatnonzero(m[rank:, col])
        if rows.size == 0:
            continue
        m[[rank, rows[0]]] = m[[rows[0], rank]]
        for i in np.flatnonzero(m[:, col]):
            if i != rank:
                m[i] ^= m[rank]
        rank += 1
    return rank
 
 
n = hx.shape[1]
print("H_X H_Z^T = 0 (mod 2):", not (hx.astype(int) @ hz.T % 2).any())
rx, rz = gf2_rank(hx), gf2_rank(hz)
print(f"n = {n}, rank H_X = {rx}, rank H_Z = {rz}, k = {n - rx - rz}")
print("Deltakit:", code.calculate_number_of_logical_qubits())
H_X H_Z^T = 0 (mod 2): True
n = 9, rank H_X = 4, rank H_Z = 4, k = 1
Deltakit: 1

The logical operators come as tuples of frozensets of single-qubit Paulis such as PauliX(Qubit(Coord2D(1, 5))). To turn one into a column vector, sort the data qubits by unique_identifier, which is the order the matrices use:

cols = sorted(code.data_qubits, key=lambda q: q.unique_identifier)
col = {q: j for j, q in enumerate(cols)}
print("columns:", " ".join(f"({x},{y})" for x, y in
                           (q.unique_identifier for q in cols)))
 
 
def to_vector(logical):
    """A logical operator (a set of single-qubit Paulis) as a 0/1 vector."""
    v = np.zeros(n, dtype=np.uint8)
    for pauli in logical:
        v[col[pauli.qubit]] = 1
    return v
 
 
xbar = to_vector(code.x_logical_operators[0])
zbar = to_vector(code.z_logical_operators[0])
print("X_L on columns", np.flatnonzero(xbar).tolist(),
      "  Z_L on columns", np.flatnonzero(zbar).tolist())
print("H_Z x_L =", (hz.astype(int) @ xbar % 2).tolist(),
      "  H_X z_L =", (hx.astype(int) @ zbar % 2).tolist())
print("x_L . z_L =", int(xbar.astype(int) @ zbar) % 2)
columns: (1,1) (1,3) (1,5) (3,1) (3,3) (3,5) (5,1) (5,3) (5,5)
X_L on columns [2, 5, 8]   Z_L on columns [0, 1, 2]
H_Z x_L = [0, 0, 0, 0]   H_X z_L = [0, 0, 0, 0]
x_L . z_L = 1

Both logical operators pass every check of the other type, and they overlap on one qubit (column 2), so they anticommute, as and must. For the distance, nine qubits are few enough to try all bit strings: keep those in , drop those in , and take the lightest.

words = (np.arange(2**n)[:, None] >> np.arange(n)) & 1
passes = words[~(words @ hz.T % 2).any(axis=1)]
x_logicals = [w for w in passes if gf2_rank(np.vstack([hx, w])) > rx]
print(len(words), "strings,", len(passes), "pass every Z check,",
      len(x_logicals), "are X logicals")
print("lightest X logical: weight", min(int(w.sum()) for w in x_logicals),
      "| code.x_distance =", code.x_distance)
512 strings, 32 pass every Z check, 16 are X logicals
lightest X logical: weight 3 | code.x_distance = 3

The counts are the theory in numbers: has dimension (32 vectors), has dimension 4 (16 vectors), and the 32 split into two classes of 16, the stabilizers and the logicals, because . Finally, the same computation on other code classes, including a Steane code built from the Hamming matrix with CSSCode.from_matrix:

from deltakit.circuit.gates import PauliBasis
from deltakit.explorer.codes import (CSSCode, RepetitionCode,
                                     UnrotatedToricCode)
 
hamming = np.array([[1, 0, 1, 0, 1, 0, 1],
                    [0, 1, 1, 0, 0, 1, 1],
                    [0, 0, 0, 1, 1, 1, 1]], dtype=np.uint8)
examples = {
    "RepetitionCode(5)": RepetitionCode(distance=5),
    "RepetitionCode(5, X)": RepetitionCode(
        distance=5, stabiliser_type=PauliBasis.X),
    "UnrotatedToricCode(3, 3)": UnrotatedToricCode(
        horizontal_distance=3, vertical_distance=3),
    "Steane (from_matrix)": CSSCode.from_matrix(h_x=hamming, h_z=hamming),
}
for name, c in examples.items():
    h1, h2 = c.parity_check_matrices
    r1, r2 = gf2_rank(h1), gf2_rank(h2)
    print(f"{name:25s} H_X {h1.shape}  H_Z {h2.shape}"
          f"  ranks {r1}, {r2}  k = {h1.shape[1] - r1 - r2}")
 
try:
    CSSCode.from_matrix(h_x=np.array([[1, 1, 0]]), h_z=np.array([[0, 1, 1]]))
except ValueError as err:
    print("ValueError:", str(err).split(". ")[0])
RepetitionCode(5)         H_X (0, 5)  H_Z (4, 5)  ranks 0, 4  k = 1
RepetitionCode(5, X)      H_X (4, 5)  H_Z (0, 5)  ranks 4, 0  k = 1
UnrotatedToricCode(3, 3)  H_X (9, 18)  H_Z (9, 18)  ranks 8, 8  k = 2
Steane (from_matrix)      H_X (3, 7)  H_Z (3, 7)  ranks 3, 3  k = 1
ValueError: CSSCode object was initialised with anticommuting stabilisers

Three things to notice. The repetition code has an empty of shape : it is a CSS code with only one kind of check, and stabiliser_type=PauliBasis.X swaps the roles. The toric code’s nine checks of each type have rank 8, not 9, because on a torus the product of all checks of one type is the identity; that redundancy is how logical qubits appear. And Deltakit refuses checks that anticommute: and clash once, on the middle qubit, so the constructor raises a ValueError.

Try this

  • Build RotatedPlanarCode(width=3, height=5) and predict the shapes of and and the values of x_distance and z_distance before printing them.
  • Find by swapping hx and hz in the brute-force block. How many of the 16 logicals have weight 3? Draw one that is not a straight line.
  • Write the five-qubit code’s check matrix and verify with numpy. Why can CSSCode not represent it?
  • Build Shor’s code with CSSCode.from_matrix and check . Which pairs of single-qubit errors are degenerate?

Readings