Skip to main content
KetQat

Appearance

Lesson 31 h

The stabilizer formalism

Pauli groups, stabilizer codes, logical operators, distance and syndromes.

After this lesson you can

  • Represent n-qubit Pauli operators as binary symplectic vectors and decide commutation with the symplectic inner product
  • Define a stabilizer group and its code space, and compute k = n - rank of the check matrix over F_2
  • Identify logical operators as Paulis that commute with every stabilizer but are not stabilizers, and compute the code distance
  • Compute the syndrome of a Pauli error as its commutation pattern with the generators
  • Verify the parameters [[5,1,3]], [[7,1,3]] and [[9,1,3]] of the five-qubit, Steane and Shor codes with a self-written toolkit
  • Explain degeneracy and the CSS construction with the Steane code as an example

Read first: The repetition code

Why a new language

The repetition codes were described by listing code words. That stops working quickly: a code with kk logical qubits has 2k2^k basis code words, each a superposition of up to 2n2^n basis states. The stabilizer formalism, developed in Gottesman's thesis (Gottesman 1997), describes a code instead by a short list of Pauli operators that leave every code state unchanged. Everything we need (the code space dimension, the syndrome of an error, the logical operators, the distance) then reduces to linear algebra over the two-element field F2={0,1}\F_2 = \{0, 1\}. This lesson builds that algebra and uses it on three famous codes. The surface code, Floquet codes and most codes in current research are stabilizer codes.

The Pauli group

The Pauli group Pn\mathcal{P}_n on nn qubits consists of the tensor products P=λ P0⊗P1⊗⋯⊗Pn−1P = \lambda\, P_0 \otimes P_1 \otimes \dots \otimes P_{n-1} with Pj∈{I,X,Y,Z}P_j \in \{I, X, Y, Z\} and phase λ∈{±1,±i}\lambda \in \{\pm1, \pm i\}. We write these as strings, so XZZXI means X0Z1Z2X3I4X_0Z_1Z_2X_3I_4, character jj acting on qubit jj. Three facts are used constantly:

  1. Every Pauli squares to ±I\pm I, and Hermitian ones (phase ±1\pm1) have eigenvalues ±1\pm1.
  2. Any two Paulis either commute or anticommute. On one qubit, distinct non-identity Paulis anticommute. On nn qubits, PP and QQ anticommute exactly when the number of positions where they hold distinct non-identity letters is odd.
  3. The weight of a Pauli is the number of non-identity positions.

Worked example. XZ and ZX differ at both positions, two anticommutations, so they commute. XX and ZI differ only at position 0, so they anticommute.

The binary symplectic picture

Since phases do not affect commutation or weight, drop them and record a Pauli by two bit strings: xj=1x_j = 1 if position jj holds XX or YY, and zj=1z_j = 1 if it holds ZZ or YY. The Pauli becomes a vector (x ∣ z)∈F22n(x \,|\, z) \in \F_2^{2n}; for example XYZI is (1100 ∣ 0110)(1100\,|\,0110). Multiplying two Paulis adds their vectors modulo 2, up to a phase. Commutation becomes the symplectic inner product

⟨a,b⟩=xa⋅zb+za⋅xb(mod2),\langle a, b\rangle = x_a \cdot z_b + z_a \cdot x_b \pmod 2,

which is 0 when the Paulis commute and 1 when they anticommute: each qubit contributes 1 exactly when one operator has an XX-part and the other a ZZ-part there but not both. For XZ =(10∣01)= (10|01) and ZX =(01∣10)= (01|10) we get xa⋅zb=1x_a\cdot z_b = 1 and za⋅xb=1z_a \cdot x_b = 1, total 00: they commute, as found above.

Stabilizer groups and codes

A stabilizer group S\mathcal{S} is an abelian subgroup of Pn\mathcal{P}_n that does not contain −I-I. Its code space is the set of states fixed by every element:

VS={∣ψ⟩:S∣ψ⟩=∣ψ⟩ for all S∈S}.V_{\mathcal{S}} = \{\ket{\psi} : S\ket{\psi} = \ket{\psi} \text{ for all } S \in \mathcal{S}\}.

(If −I-I were in S\mathcal{S}, it would require −∣ψ⟩=∣ψ⟩-\ket\psi = \ket\psi, so VSV_\mathcal{S} would be empty; commutation is needed for a common +1+1 eigenspace to exist.) We describe S\mathcal{S} by independent generators g1,…,grg_1, \dots, g_r, and stack their symplectic vectors as the rows of the r×2nr \times 2n check matrix HH.

Theorem (Gottesman 1997). If S\mathcal{S} has rr independent generators, VSV_\mathcal{S} has dimension 2n−r2^{n-r}, so it encodes k=n−rk = n - r logical qubits. With possibly redundant generators, k=n−rank⁡F2Hk = n - \operatorname{rank}_{\F_2} H.

The idea of the proof: each generator gig_i has ±1\pm1 eigenspaces of equal size, and because the generators are independent and commute, fixing the signs of all rr of them splits the 2n2^n-dimensional space into 2r2^r subspaces of equal dimension 2n−r2^{n-r}. The code space is the one with all signs +1+1; the others are the "error spaces" that errors move it into.

Example. The bit-flip code is generated by ZZI and IZZ: n=3n = 3, r=2r = 2, so k=1k = 1. Its check matrix is

H=(000110000011),H = \left(\begin{array}{ccc|ccc} 0&0&0&1&1&0\\ 0&0&0&0&1&1 \end{array}\right),

of rank 2. Adding the product ZIZ as a third row does not change the rank or kk.

Errors and syndromes

Measuring a generator gig_i on a code state always gives +1+1. After a Pauli error EE, the state E∣ψ⟩E\ket\psi satisfies giE∣ψ⟩=±Egi∣ψ⟩=±E∣ψ⟩g_iE\ket\psi = \pm E g_i\ket\psi = \pm E\ket\psi, with the minus sign exactly when EE anticommutes with gig_i. The syndrome of EE is therefore the bit string

σ(E)i=⟨gi,E⟩,i=1,…,r,\sigma(E)_i = \langle g_i, E\rangle, \qquad i = 1, \dots, r,

a pure commutation pattern that does not depend on the encoded state. In matrix form σ(E)=HΛe mod 2\sigma(E) = H\Lambda e \bmod 2, where ee is the vector of EE and Λ\Lambda swaps the xx and zz halves.

A generator is measured onto an ancilla with a Hadamard, controlled Paulis and a second Hadamard. For the five-qubit code's generator XZZXI:

Quantum circuit on 6 wires (q0, q1, q2, q3, q4, a). step 1: H on a. step 2: CNOT, control a, target q0. step 3: CZ on a and q1. step 4: CZ on a and q2. step 5: CNOT, control a, target q3. step 6: H on a. step 7: measure a.q0q1q2q3q4aHH
Measuring the generator X0 Z1 Z2 X3 onto an ancilla

The ancilla outcome is 0 for eigenvalue +1+1 and 1 for −1-1. In the lessons on syndrome extraction we will see why the order of these gates matters once they are noisy.

Logical operators and distance

Which errors cannot be detected? Exactly those with zero syndrome, the Paulis that commute with every element of S\mathcal{S}. This set is the centraliser C(S)C(\mathcal{S}); for Pauli stabilizer groups it coincides with the normaliser N(S)N(\mathcal{S}), which is the name used in many texts. It splits into two kinds:

  • Stabilizers (E∈SE \in \mathcal{S}, up to phase): they act trivially on every code state. Harmless.
  • Logical operators (E∈C(S)∖SE \in C(\mathcal{S}) \setminus \mathcal{S}): they map the code space to itself but act non-trivially on it. Undetectable and harmful.

There are 2k2k independent logical operators, which can be chosen as pairs Xˉj,Zˉj\bar X_j, \bar Z_j that obey the commutation relations of kk qubits. Two logical operators that differ by a stabilizer act identically on the code space, so each has many representatives of different weights.

The distance dd is the minimum weight of a logical operator. A code with parameters nn, kk, dd is written [[n,k,d]][[n, k, d]] (double brackets distinguish quantum from classical codes). It detects every error of weight up to d−1d-1 and corrects every error of weight up to t=⌊(d−1)/2⌋t = \lfloor (d-1)/2\rfloor: two errors of weight ≤t\le t with the same syndrome differ by an element of C(S)C(\mathcal{S}) of weight ≤2t<d\le 2t < d, which must be a stabilizer, so correcting either one fixes both. This is the Knill-Laflamme condition (Knill and Laflamme 1997) in stabilizer form: {Ea}\{E_a\} is correctable if every product Ea†EbE_a^\dagger E_b is either in S\mathcal{S} (up to a phase) or anticommutes with some element of S\mathcal{S}.

Example. For the bit-flip code, ZII commutes with ZZI and IZZ and is not in the group they generate, so it is a logical operator (Zˉ\bar Z) of weight 1: the code is [[3,1,1]][[3,1,1]]. Its distance against XX errors alone is 3, but distance counts all Pauli errors.

Three codes in the stabilizer language

The Steane code [[7,1,3]][[7,1,3]]

Take the parity-check matrix of the classical [7,4,3][7,4,3] Hamming code, whose column jj is the binary representation of j+1j+1:

HHam=(000111101100111010101).H_{\text{Ham}} = \begin{pmatrix} 0&0&0&1&1&1&1\\ 0&1&1&0&0&1&1\\ 1&0&1&0&1&0&1 \end{pmatrix}.

Use each row once as an XX-type generator and once as a ZZ-type generator:

XX-type ZZ-type
IIIXXXX IIIZZZZ
IXXIIXX IZZIIZZ
XIXIXIX ZIZIZIZ

An XX-type and a ZZ-type generator commute when their supports overlap on an even number of qubits, which holds because any two rows of HHamH_{\text{Ham}} overlap in 2 positions and each row has weight 4. The six generators are independent, so k=7−6=1k = 7 - 6 = 1. This is Steane's code (Steane 1996), the smallest CSS code that corrects an arbitrary single-qubit error, built by the CSS construction of Calderbank, Shor and Steane (Calderbank and Shor 1996): XX-type checks from one classical code, ZZ-type checks from another, with the commutation condition HXHZT=0 mod 2H_XH_Z^{\mathsf T} = 0 \bmod 2. For CSS codes XX and ZZ errors are detected and corrected separately.

A single error XjX_j anticommutes with the ZZ-type generators whose row has a 1 in column jj, so its ZZ-part of the syndrome is the binary representation of j+1j+1: it names the qubit, exactly as in the classical Hamming code. The same holds for ZjZ_j with the XX-type generators, and YjY_j triggers both. All 21 single-qubit errors have distinct non-zero syndromes. Logical operators include $\bar X = $ XXXXXXX and $\bar Z = $ ZZZZZZZ, and lighter representatives such as XXXIIII (multiply XXXXXXX by the stabilizer IIIXXXX) have weight 3. No Pauli of weight 1 or 2 is a logical operator, so d=3d = 3.

The five-qubit code [[5,1,3]][[5,1,3]]

The smallest code that corrects an arbitrary single-qubit error uses five qubits (Laflamme et al. 1996); it was found independently by Bennett, DiVincenzo, Smolin and Wootters (1996). Its generators are cyclic shifts: XZZXI, IXZZX, XIXZZ, ZXIXZ. It is not a CSS code (generators mix XX and ZZ). Worked example: the syndrome of IIYII is (1,1,1,0)(1,1,1,0), because Y2Y_2 anticommutes with the ZZ in the first two generators and the XX in the third, and the fourth has II on qubit 2. With 4 generators there are 24=162^4 = 16 syndromes, and the identity plus 15 single-qubit errors use every one of them exactly once. Codes that use every syndrome this way are called perfect.

Shor's code [[9,1,3]][[9,1,3]] and degeneracy

Shor's code (Shor 1995) has six ZZ-type generators ZZ on neighbouring qubits inside each block of three, and two XX-type generators XXXXXXIII and IIIXXXXXX. Here something new happens: Z0Z_0 and Z1Z_1 have the same syndrome (each anticommutes with XXXXXXIII only), yet the code corrects both, because Z0Z1Z_0Z_1 is a stabilizer. Correcting Z0Z_0 when Z1Z_1 occurred leaves Z0Z1Z_0Z_1, which acts trivially. Codes in which distinct low-weight errors act identically are degenerate. Degeneracy has no classical analogue, and decoders that ignore it can be suboptimal.

Computing it yourself

All of these statements can be checked by a few dozen lines of NumPy. The core is Gaussian elimination over F2\F_2:

import numpy as np

def to_vec(p):
    return np.array([c in "XY" for c in p] + [c in "ZY" for c in p], dtype=np.uint8)

def gf2_rank(m):
    m = np.array(m, dtype=np.uint8) % 2
    rank = 0
    for col in range(m.shape[1]):
        rows = [r for r in range(rank, m.shape[0]) if m[r, col]]
        if not rows:
            continue
        m[[rank, rows[0]]] = m[[rows[0], rank]]
        for r in range(m.shape[0]):
            if r != rank and m[r, col]:
                m[r] ^= m[rank]
        rank += 1
    return rank

five = ["XZZXI", "IXZZX", "XIXZZ", "ZXIXZ"]
H = np.array([to_vec(g) for g in five])
print("k =", 5 - gf2_rank(H))                       # k = 1
e = to_vec("IIYII")
n = 5
print([int((g[:n] @ e[n:] + g[n:] @ e[:n]) % 2) for g in H])  # [1, 1, 1, 0]

The exercise extends this to a full toolkit: commutation, syndromes, membership in the stabilizer group, logical operators of a given weight, and the distance by brute force over weights 1,2,…1, 2, \dots Brute force is fine for n≤9n \le 9, and it lets you confirm the parameters above from the generators alone. One check compares your Steane syndromes with the table produced by the KetQat SDK's steane-code product, which computes it independently and verifies it by state-vector projection.

Common mistakes

  • Forgetting to drop phases consistently. The symplectic vector ignores phases; that is fine for commutation, weight and rank, but not for the eigenvalue a measurement returns.
  • Counting generators instead of the rank. With redundant generators, k=n−rank⁡Hk = n - \operatorname{rank}H, not n−(number of rows)n - (\text{number of rows}).
  • Calling every zero-syndrome error a logical error. Stabilizers also have zero syndrome and act trivially; only C(S)∖SC(\mathcal{S})\setminus\mathcal{S} is harmful.
  • Taking the weight of one representative as the distance. XXXXXXX has weight 7, but the Steane code's distance is 3; minimise over all representatives.
  • Assuming one error, one syndrome, one correction. In degenerate codes several errors share a syndrome and one correction serves them all.
  • Mixing qubit orderings. Here character jj of a string acts on qubit jj. Libraries differ; check before comparing syndromes.

Summary

  • Paulis are vectors in F22n\F_2^{2n}; products add, and commutation is the symplectic inner product.
  • A stabilizer code is the joint +1+1 eigenspace of an abelian Pauli group without −I-I; k=n−rank⁡F2Hk = n - \operatorname{rank}_{\F_2} H.
  • The syndrome of an error is its commutation pattern with the generators.
  • Logical operators commute with all stabilizers without being stabilizers; the distance is their minimum weight, and the code corrects ⌊(d−1)/2⌋\lfloor (d-1)/2\rfloor errors.
  • The five-qubit, Steane and Shor codes are [[5,1,3]][[5,1,3]], [[7,1,3]][[7,1,3]] and [[9,1,3]][[9,1,3]]; Steane's is the simplest CSS code and Shor's is degenerate.

This completes the introduction. The next module builds the surface code, a CSS code whose checks are local on a square grid, and simulates it under realistic noise. For a textbook treatment of stabilizer codes see Nielsen and Chuang, section 10.5.

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.

A stabilizer-code toolkit: commutation, syndromes, k and distance

intermediate · about 1 h 15 min · needs numpy, pytest, ketqat[qec]

You will build, in plain NumPy, the handful of routines that every stabilizer code calculation rests on, and use them to recover the parameters [[n,k,d]][[n,k,d]] of five codes from their generators alone.

Conventions

A Pauli operator on nn qubits is a string over I X Y Z; character j acts on qubit j. Phases are ignored. Its binary symplectic vector is (x ∣ z)(x\,|\,z) of length 2n2n with xj=1x_j = 1 for X or Y on qubit j and zj=1z_j = 1 for Z or Y. So "XYZI" maps to [1,1,0,0, 0,1,1,0].

Functions to implement in starter.py

Function Contract
pauli_to_symplectic(p) / symplectic_to_pauli(v) The map above and its inverse; ValueError on letters other than IXYZ.
symplectic_product(a, b) xa⋅zb+za⋅xb mod 2x_a\cdot z_b + z_a\cdot x_b \bmod 2.
commutes(p, q) True when the two strings commute.
syndrome(stabilizers, error) Tuple of bits; bit i is 1 when the error anticommutes with generator i.
gf2_rank(matrix) Rank over F2\F_2 by Gaussian elimination modulo 2.
check_matrix(stabilizers) Rows are the generators' symplectic vectors.
is_valid_stabilizer_group(stabilizers) Generators commute pairwise.
num_logical_qubits(stabilizers) k=n−rank⁡F2k = n - \operatorname{rank}_{\F_2} of the check matrix.
in_stabilizer_group(stabilizers, p) p is a product of generators: adding its vector does not raise the rank.
is_logical_operator(stabilizers, p) Zero syndrome but not in the stabilizer group.
logical_operators_of_weight(stabilizers, w) Every weight-w string that is a non-trivial logical operator.
code_distance(stabilizers, max_weight=None) Smallest such weight, by brute force over w=1,2,…w = 1, 2, \dots; ValueError if k=0k = 0.

What the checks verify

  • Commutation agrees with multiplying the 4×44\times4 matrices of all 256 pairs of two-qubit Paulis (an independent method).
  • From the generators alone your toolkit reproduces the published parameters [[3,1,1]][[3,1,1]] (bit-flip code), [[4,2,2]][[4,2,2]], [[5,1,3]][[5,1,3]], [[7,1,3]][[7,1,3]] (Steane) and [[9,1,3]][[9,1,3]] (Shor).
  • 2k2^k equals the trace of the code-space projector ∏i(I+Si)/2\prod_i (I+S_i)/2 built from dense matrices.
  • Adding a redundant generator leaves kk unchanged.
  • The Steane code gives 21 distinct non-zero single-qubit syndromes and detects every weight-2 error; the five-qubit code's 15 single-qubit syndromes fill all 15 non-zero syndromes (it is a perfect code).
  • Your Steane syndromes match, bit for bit, the table produced by the KetQat SDK steane-code product, which builds its table independently and checks it by state-vector projection. The check is skipped if the SDK is not installed, and its run record goes to a temporary directory.

Run the checks

python -m pytest test_exercise.py

The brute-force distance search is fine for n≤9n \le 9. It grows like ∑w(nw)3w\sum_w \binom{n}{w}3^w, so it is not a method for large codes.

Terminal
python -m pip install numpy pytest "ketqat[qec]"

starter.py

Python
"""Starter: a small stabilizer-code toolkit in the binary symplectic picture.

A Pauli operator on n qubits is written as a string over I, X, Y, Z, character j
acting on qubit j (phases are ignored throughout). Its binary symplectic vector
is (x | z), length 2n, with x_j = 1 for X or Y on qubit j and z_j = 1 for Z or Y.
"""

from __future__ import annotations

import itertools

import numpy as np

_TO_BITS = {"I": (0, 0), "X": (1, 0), "Z": (0, 1), "Y": (1, 1)}
_FROM_BITS = {bits: ch for ch, bits in _TO_BITS.items()}


def pauli_to_symplectic(pauli: str) -> np.ndarray:
    """'XZIY' -> array([x_0..x_{n-1}, z_0..z_{n-1}]) of dtype uint8. ValueError on other letters."""
    raise NotImplementedError("pauli_to_symplectic: implement this function")


def symplectic_to_pauli(vector: np.ndarray) -> str:
    """Inverse of pauli_to_symplectic."""
    raise NotImplementedError("symplectic_to_pauli: implement this function")


def symplectic_product(a: np.ndarray, b: np.ndarray) -> int:
    """x_a . z_b + z_a . x_b mod 2: 0 when the Paulis commute, 1 when they anticommute."""
    raise NotImplementedError("symplectic_product: implement this function")


def commutes(p: str, q: str) -> bool:
    """True when the Pauli strings p and q commute."""
    raise NotImplementedError("commutes: implement this function")


def syndrome(stabilizers: list[str], error: str) -> tuple[int, ...]:
    """Bit i is 1 when `error` anticommutes with stabilizers[i]."""
    raise NotImplementedError("syndrome: implement this function")


def gf2_rank(matrix: np.ndarray) -> int:
    """Rank of a 0/1 matrix over the binary field F_2 (Gaussian elimination mod 2)."""
    raise NotImplementedError("gf2_rank: implement this function")


def check_matrix(stabilizers: list[str]) -> np.ndarray:
    """Stack the symplectic vectors of the generators: shape (len(stabilizers), 2n)."""
    raise NotImplementedError("check_matrix: implement this function")


def is_valid_stabilizer_group(stabilizers: list[str]) -> bool:
    """Generators pairwise commute (phases ignored, so -I cannot be detected here)."""
    raise NotImplementedError("is_valid_stabilizer_group: implement this function")


def num_logical_qubits(stabilizers: list[str]) -> int:
    """k = n - rank of the check matrix over F_2 (redundant generators allowed)."""
    raise NotImplementedError("num_logical_qubits: implement this function")


def in_stabilizer_group(stabilizers: list[str], pauli: str) -> bool:
    """True when `pauli` is a product of generators (up to phase)."""
    raise NotImplementedError("in_stabilizer_group: implement this function")


def is_logical_operator(stabilizers: list[str], pauli: str) -> bool:
    """Commutes with every generator but is not itself in the stabilizer group."""
    raise NotImplementedError("is_logical_operator: implement this function")


def logical_operators_of_weight(stabilizers: list[str], weight: int) -> list[str]:
    """All Pauli strings of exactly this weight that are non-trivial logical operators."""
    raise NotImplementedError("logical_operators_of_weight: implement this function")


def code_distance(stabilizers: list[str], max_weight: int | None = None) -> int:
    """Smallest weight of a non-trivial logical operator, by brute force over weights 1, 2, ...

    Search up to max_weight (default n). Raise ValueError if k = 0 or nothing is
    found up to max_weight.
    """
    raise NotImplementedError("code_distance: 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 itertools

import numpy as np
import pytest

STEANE = ["IIIXXXX", "IXXIIXX", "XIXIXIX", "IIIZZZZ", "IZZIIZZ", "ZIZIZIZ"]
FIVE_QUBIT = ["XZZXI", "IXZZX", "XIXZZ", "ZXIXZ"]
SHOR = ["ZZIIIIIII", "IZZIIIIII", "IIIZZIIII", "IIIIZZIII", "IIIIIIZZI", "IIIIIIIZZ",
        "XXXXXXIII", "IIIXXXXXX"]
BIT_FLIP = ["ZZI", "IZZ"]
FOUR_TWO_TWO = ["XXXX", "ZZZZ"]

KNOWN = [  # (generators, n, k, d): textbook parameters, the independent reference
    (BIT_FLIP, 3, 1, 1),
    (FOUR_TWO_TWO, 4, 2, 2),
    (FIVE_QUBIT, 5, 1, 3),
    (STEANE, 7, 1, 3),
    (SHOR, 9, 1, 3),
]

_M = {"I": np.eye(2), "X": np.array([[0, 1], [1, 0]]), "Y": np.array([[0, -1j], [1j, 0]]), "Z": np.diag([1, -1])}


def dense(p):
    out = np.array([[1.0 + 0j]])
    for ch in p:
        out = np.kron(out, _M[ch])
    return out


def test_symplectic_round_trip_and_layout():
    v = target.pauli_to_symplectic("XYZI")
    assert v.tolist() == [1, 1, 0, 0, 0, 1, 1, 0]
    for p in ("I", "XZ", "YYIZ", "ZXIYX"):
        assert target.symplectic_to_pauli(target.pauli_to_symplectic(p)) == p
    with pytest.raises(ValueError):
        target.pauli_to_symplectic("XQ")


def test_commutation_matches_matrix_multiplication():
    # Independent method: compare PQ with QP as dense matrices for every pair on 2 qubits.
    labels = ["".join(t) for t in itertools.product("IXYZ", repeat=2)]
    for p in labels:
        for q in labels:
            dp, dq = dense(p), dense(q)
            assert target.commutes(p, q) == np.allclose(dp @ dq, dq @ dp)
    assert target.symplectic_product(target.pauli_to_symplectic("XX"), target.pauli_to_symplectic("ZI")) == 1


def test_gf2_rank():
    assert target.gf2_rank(np.array([[1, 1, 0], [0, 1, 1], [1, 0, 1]])) == 2  # third row is the sum
    assert target.gf2_rank(np.eye(4, dtype=np.uint8)) == 4
    assert target.gf2_rank(np.zeros((3, 3), dtype=np.uint8)) == 0


@pytest.mark.parametrize("gens,n,k,d", KNOWN)
def test_known_code_parameters(gens, n, k, d):
    assert target.is_valid_stabilizer_group(gens)
    assert target.check_matrix(gens).shape == (len(gens), 2 * n)
    assert target.num_logical_qubits(gens) == k
    assert target.code_distance(gens) == d


@pytest.mark.parametrize("gens,n,k,d", KNOWN[:4])
def test_k_agrees_with_code_space_dimension(gens, n, k, d):
    # Independent method: the code-space projector prod (I + S)/2 has trace 2^k.
    proj = np.eye(2**n, dtype=complex)
    for s in gens:
        proj = proj @ (np.eye(2**n) + dense(s)) / 2
    assert round(np.trace(proj).real) == 2 ** target.num_logical_qubits(gens)


def test_redundant_generator_does_not_change_k():
    product = "".join({("Z", "Z"): "I", ("Z", "I"): "Z", ("I", "Z"): "Z", ("I", "I"): "I"}[(a, b)] for a, b in zip(SHOR[0], SHOR[1]))
    assert target.num_logical_qubits(SHOR + [product]) == 1
    assert target.in_stabilizer_group(SHOR, product)


def test_logical_operators():
    assert target.is_logical_operator(STEANE, "XXXXXXX")
    assert target.is_logical_operator(STEANE, "ZZZZZZZ")
    assert not target.is_logical_operator(STEANE, "IIIXXXX")  # a stabilizer
    assert not target.is_logical_operator(STEANE, "XIIIIII")  # detectable error
    assert target.is_logical_operator(FIVE_QUBIT, "XXXXX")
    assert target.is_logical_operator(FIVE_QUBIT, "ZZZZZ")
    assert not target.commutes("XXXXX", "ZZZZZ")
    assert target.is_logical_operator(BIT_FLIP, "ZII")  # why the bit-flip code has d = 1
    assert target.logical_operators_of_weight(FIVE_QUBIT, 2) == []


def test_steane_syndromes_are_distinct_and_detect_weight_two():
    singles = ["".join(ch if j == q else "I" for j in range(7)) for q in range(7) for ch in "XYZ"]
    table = {target.syndrome(STEANE, e) for e in singles}
    assert len(table) == 21 and (0,) * 6 not in table
    for a, b in itertools.combinations(range(7), 2):
        e = ["I"] * 7
        e[a], e[b] = "X", "Z"
        assert any(target.syndrome(STEANE, "".join(e)))


def test_five_qubit_code_is_perfect():
    # 15 single-qubit errors fill all 2^4 - 1 non-zero syndromes exactly once.
    singles = ["".join(ch if j == q else "I" for j in range(5)) for q in range(5) for ch in "XYZ"]
    syns = {target.syndrome(FIVE_QUBIT, e) for e in singles}
    assert len(syns) == 15 and (0, 0, 0, 0) not in syns


def test_steane_syndrome_table_matches_ketqat_product(tmp_path, monkeypatch):
    catalog = pytest.importorskip("ketqat_runner.catalog")
    monkeypatch.setenv("KETQAT_HOME", str(tmp_path))
    result = catalog.run("[email protected]", seed=0, exhaustive=True).result
    gens = result["stabilizers"]
    assert target.num_logical_qubits(gens) == 1
    # The product builds its table from its own symplectic code and verifies it by
    # state-vector projection; bit i of its syndrome string belongs to generator i.
    for bits, error in result["syndrome_table"].items():
        assert "".join(map(str, target.syndrome(gens, error))) == bits

Check your understanding

7 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. Do XYZ and ZZX commute?

    1 pt
  2. A code on n=4n = 4 qubits is defined by the generators ZZII, IZZI, ZIZI and XXXX. How many logical qubits kk does it encode?

    1 pt
  3. For the five-qubit code with generators XZZXI, IXZZX, XIXZZ, ZXIXZ (in this order), what is the syndrome of the error ZIIII?

    1 pt
  4. Use logical_operators_of_weight from your toolkit: how many Pauli strings of weight exactly 3 are non-trivial logical operators of the five-qubit code?

    2 pts

    Computed by running exercise “stabilizer-toolkit” on your computer.

  5. Select every true statement about a stabilizer code with stabilizer group S\mathcal{S}.

    1 pt

    Select all that apply.

  6. In Shor's nine-qubit code, Z0Z_0 and Z1Z_1 have the same syndrome. Why is this not a problem?

    1 pt
  7. In a CSS code built from XX-check matrix HXH_X and ZZ-check matrix HZH_Z, what condition guarantees that all generators commute?

    1 pt

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

References

  1. Daniel Gottesman (1997). Stabilizer Codes and Quantum Error Correction. PhD thesis, California Institute of Technology. arXiv:quant-ph/9705052
  2. A. R. Calderbank, Peter W. Shor (1996). Good quantum error-correcting codes exist. Physical Review A 54, 1098-1105. doi:10.1103/PhysRevA.54.1098
  3. Andrew M. Steane (1996). Error Correcting Codes in Quantum Theory. Physical Review Letters 77, 793-797. doi:10.1103/PhysRevLett.77.793
  4. Raymond Laflamme et al. (1996). Perfect Quantum Error Correcting Code. Physical Review Letters 77, 198-201. doi:10.1103/PhysRevLett.77.198
  5. Charles H. Bennett et al. (1996). Mixed-state entanglement and quantum error correction. Physical Review A 54, 3824-3851. doi:10.1103/PhysRevA.54.3824
  6. Peter W. Shor (1995). Scheme for reducing decoherence in quantum computer memory. Physical Review A 52, R2493-R2496. doi:10.1103/PhysRevA.52.R2493
  7. Emanuel Knill, Raymond Laflamme (1997). Theory of quantum error-correcting codes. Physical Review A 55, 900-911. doi:10.1103/PhysRevA.55.900
  8. Michael A. Nielsen, Isaac L. Chuang (2010). Quantum Computation and Quantum Information (10th Anniversary Edition). Cambridge University Press. doi:10.1017/CBO9780511976667