Skip to main content
KetQat

Appearance

Lesson 41 h 10 min

The surface code

The rotated surface code, its stabilizers, logical operators and distance.

After this lesson you can

  • Construct the X- and Z-check matrices of the rotated surface code for any odd distance and verify that they commute
  • Prove that every logical operator of the rotated surface code has weight at least d, and exhibit operators of weight d
  • Count data and measure qubits of rotated and unrotated layouts and of the toric code
  • Explain how boundary types determine which strings are logical, and detect a wrong boundary assignment by its distance
  • Describe errors as strings whose endpoints are syndrome defects, and relate the surface code to the repetition code
  • Compute k and the distance of small surface and toric codes by brute force and compare the layout with Stim's generator

Read first: The stabilizer formalism

Why the surface code

The codes of the introductory lessons have checks that act on qubits far apart (IIIXXXX in the Steane code touches qubits 3 to 6, Shor's XXXXXXIII six qubits). On hardware where qubits interact only with near neighbours on a chip, measuring such checks needs long-range gates or many SWAPs, and every extra gate adds noise. The surface code makes a different trade: every check acts on at most four qubits that are neighbours on a square grid, the code family scales simply by enlarging the grid, and under circuit-level noise it tolerates much higher physical error rates than earlier constructions. The price is a low encoding rate: one logical qubit per d2d^2 data qubits.

This lesson builds the code from the toric code, adds boundaries, and then works with the rotated layout used by Stim, by Google's experiments and in the rest of this course. Everything is checked by computation: the exercise constructs the check matrices for any distance and verifies k=1k = 1 and the distance by brute force.

Intuition first: the toric code

Kitaev's toric code (Kitaev 2003) places one qubit on each edge of an L×LL\times L square lattice with periodic boundaries, so n=2L2n = 2L^2. There are two kinds of checks:

  • for every vertex vv, the star Av=∏e∋vXeA_v = \prod_{e \ni v} X_e on the four edges meeting at vv;
  • for every face ff, the plaquette Bf=∏e∈∂fZeB_f = \prod_{e \in \partial f} Z_e on the four edges around ff.

A star and a plaquette share either zero or two edges, so all checks commute. The product of all stars is the identity (each edge belongs to exactly two stars), and likewise for plaquettes, so each family has L2−1L^2 - 1 independent generators and

k=2L2−2(L2−1)=2.k = 2L^2 - 2(L^2 - 1) = 2.

Errors are strings. A ZZ error on one edge anticommutes with the stars at its two endpoints. A chain of ZZ errors along a path flips only the stars at the two ends of the path: inside the path each vertex touches two error edges, and the two sign flips cancel. The syndrome therefore shows only the endpoints of error strings, called defects. XX errors behave the same way on the dual lattice (faces joined across edges), flipping the plaquettes at their ends.

Logical operators are non-contractible loops. A closed string of ZZ's has no endpoints, so it commutes with every star. If the loop is the boundary of a region, it equals the product of the plaquettes inside, a stabilizer. If it wraps around the torus, it is not a product of plaquettes: it is a logical operator. Two independent directions give Zˉ1,Zˉ2\bar Z_1, \bar Z_2, and dual loops of XX's give Xˉ1,Xˉ2\bar X_1, \bar X_2. The shortest non-contractible loop has length LL, so the distance is LL.

Decoding is pairing. Given the defects, the decoder must join them in pairs by correction strings. If error and correction together form a contractible loop, the result is a stabilizer and correction succeeded; if they form a non-contractible loop, a logical error occurred. Choosing the most likely pairing for independent errors means choosing the shortest total length, the problem solved by minimum-weight perfect matching. This geometric picture, and its connection with a statistical-mechanics phase transition, is developed in Dennis et al. (2002).

Boundaries: the planar code

A torus is not a chip. Bravyi and Kitaev showed how to cut the lattice open and keep one logical qubit (Bravyi and Kitaev 1998). The new ingredient is the boundary. Along one kind of boundary the checks are chosen so that a ZZ string can end there without flipping any star: the boundary absorbs ZZ-type defects. Along the other kind, XX strings end silently. A planar patch with two boundaries of each kind, alternating around the edge, encodes one logical qubit: Zˉ\bar Z is a ZZ string joining the two boundaries that absorb ZZ strings, Xˉ\bar X an XX string joining the other two. A defect near a boundary can now also be explained by a short string to that boundary, so the decoder may match a defect either to another defect or to the boundary.

The original unrotated planar code of distance dd has d2+(d−1)2d^2 + (d-1)^2 data qubits and 2d(d−1)2d(d-1) checks, so (2d−1)2(2d-1)^2 qubits in total with one measure qubit per check (25 for d=3d = 3; Stim's surface_code:unrotated_memory_z generator uses exactly 25, 81 and 169 qubits for d=3,5,7d = 3, 5, 7). Rotating the lattice by 45 degrees and trimming the corners gives the same distance with fewer qubits, as the next section shows; discussions of both layouts and of their small-distance performance can be found in Fowler et al. (2012) and Tomita and Svore (2014).

The rotated surface code

In the rotated code the data qubits sit on the vertices of a d×dd \times d grid and every check sits on a face. We fix one concrete convention, used in the exercise:

  • data qubit (r,c)(r, c), 0≤r,c<d0 \le r, c < d, has index q=rd+cq = rd + c;
  • the face with top-left corner (r,c)(r, c), −1≤r,c≤d−1-1 \le r, c \le d - 1, touches the data qubits (r,c),(r,c+1),(r+1,c),(r+1,c+1)(r,c), (r,c+1), (r+1,c), (r+1,c+1) that exist;
  • a face is XX-type when r+cr + c is even and ZZ-type when r+cr + c is odd;
  • every face with four qubits is a check; a two-qubit face on the top or bottom edge is a check only if it is XX-type, and on the left or right edge only if it is ZZ-type; corner faces with one qubit are never checks.

Distance-3 rotated surface code Nine data qubits on a 3 by 3 grid, numbered 0 to 8 row by row. Four weight-4 plaquettes fill the squares between them: X-type (shaded, labelled X) on the top-left and bottom-right squares, Z-type (unshaded, labelled Z) on the top-right and bottom-left squares. Four weight-2 boundary checks are drawn as half-discs: X-type on the top edge (qubits 1 and 2) and on the bottom edge (qubits 6 and 7), Z-type on the left edge (qubits 0 and 3) and on the right edge (qubits 5 and 8). A bold line marks the logical Z operator on the top row (qubits 0, 1, 2) and a bold dashed line marks the logical X operator on the left column (qubits 0, 3, 6). X X Z Z X X Z Z 0 1 2 3 4 5 6 7 8 solid bar: Z logical (row 0) · dashed bar: X logical (column 0)
The distance-3 rotated surface code in this lesson's convention

For d=3d = 3 this gives the XX checks {1,2}\{1,2\}, {0,1,3,4}\{0,1,3,4\}, {4,5,7,8}\{4,5,7,8\}, {6,7}\{6,7\} and the ZZ checks {0,3}\{0,3\}, {1,2,4,5}\{1,2,4,5\}, {3,4,6,7}\{3,4,6,7\}, {5,8}\{5,8\}.

Counting. There are (d−1)2(d-1)^2 four-qubit faces, half of each type because (d−1)2(d-1)^2 is even and the types alternate like a chessboard. Each type also gets d−1d - 1 two-qubit checks: (d−1)/2(d-1)/2 on each of its two edges. So each type has

(d−1)22+(d−1)=d2−12\frac{(d-1)^2}{2} + (d - 1) = \frac{d^2 - 1}{2}

checks, d2−1d^2 - 1 in total. With one measure qubit per check, a distance-dd patch uses d2d^2 data and d2−1d^2 - 1 measure qubits, 2d2−12d^2 - 1 in total: 17 for d=3d = 3, 49 for d=5d = 5, 97 for d=7d = 7. Compare 25, 81 and 169 for the unrotated layout.

Commutation. Two faces that share a side of a grid square overlap in two qubits, and they always have different types. Two faces that touch only at a corner overlap in one qubit, but they have the same type, and checks of the same type always commute. A boundary half-face overlaps in two qubits with the single adjacent four-qubit face of the other type. So every XX-ZZ overlap is even and HXHZT=0 mod 2H_XH_Z^{\mathsf T} = 0 \bmod 2.

One logical qubit. The d2−1d^2 - 1 checks are independent: the exercise confirms rank⁡HX+rank⁡HZ=d2−1\operatorname{rank}H_X + \operatorname{rank}H_Z = d^2 - 1 for d=3,5,7,9d = 3, 5, 7, 9, so

k=d2−(d2−1)=1.k = d^2 - (d^2 - 1) = 1.

Logical operators and the distance

Take Zˉ=Z(0,0)Z(0,1)⋯Z(0,d−1)\bar Z = Z_{(0,0)}Z_{(0,1)}\cdots Z_{(0,d-1)}, the top row, and Xˉ=X(0,0)X(1,0)⋯X(d−1,0)\bar X = X_{(0,0)}X_{(1,0)}\cdots X_{(d-1,0)}, the left column.

  • Zˉ\bar Z commutes with every XX check: a four-qubit XX face meets the top row in 0 or 2 qubits, and the top-edge XX checks lie entirely inside it.
  • Xˉ\bar X commutes with every ZZ check, by the same argument with columns and the left-edge ZZ checks.
  • They anticommute: they overlap in the single qubit (0,0)(0,0).

So the left and right edges, which carry only ZZ checks, are where ZZ strings can end undetected, and the top and bottom edges play that role for XX strings. This assignment of boundary types is what makes the code work.

Theorem (distance). Every logical operator of the rotated surface code has weight at least dd, so its distance is exactly dd.

Proof. The same argument that showed Xˉ\bar X commutes with all ZZ checks applies to the XX string on any column cc: every ZZ face meets a column in 0 or 2 qubits and the left and right ZZ checks are vertical pairs. So each column string Xˉ(c)\bar X^{(c)} commutes with all ZZ checks, and it anticommutes with Zˉ\bar Z (one shared qubit), so it is not a stabilizer: it is a representative of Xˉ\bar X. A non-trivial ZZ-type logical operator must anticommute with Xˉ\bar X, and hence with every Xˉ(c)\bar X^{(c)}, which requires an odd, hence non-zero, overlap with every one of the dd columns: weight at least dd. The same argument with rows bounds XX-type logical operators. A general logical operator P=X(a)Z(b)P = X(a)Z(b) of a CSS code commutes with all checks only if X(a)X(a) commutes with the ZZ checks and Z(b)Z(b) with the XX checks, and since PP is not a stabilizer at least one of the two parts is a non-trivial logical operator of weight at most that of PP. So the bound holds for every logical operator, and the row and column strings reach it. □\square

The exercise confirms this by brute force for d=3d = 3 and 55: no XX-type or ZZ-type logical of weight ≤d−1\le d - 1 exists. It also counts the minimum-weight logicals: for d=3d = 3 there are 8 of ZZ type, not just the 3 rows, because a minimum-weight string may step diagonally through a four-qubit face.

Why boundary types matter

What happens if the boundary checks are assigned wrongly? The following script builds variants of the d=5d = 5 patch: the correct one, one with XX-type two-qubit checks on all four edges, one with ZZ-type checks on all four edges, and one with no boundary checks at all.

import numpy as np

def checks(d, x_edges, z_edges):
    """Bulk faces plus two-qubit checks of each type on the named edges."""
    xs, zs = [], []
    for r in range(-1, d):
        for c in range(-1, d):
            s = [i * d + j for i in (r, r + 1) for j in (c, c + 1) if 0 <= i < d and 0 <= j < d]
            kind = "X" if (r + c) % 2 == 0 else "Z"
            edge = {r == -1: "top", r == d - 1: "bottom", c == -1: "left", c == d - 1: "right"}.get(True)
            keep = len(s) == 4 or (len(s) == 2 and edge in (x_edges if kind == "X" else z_edges))
            if keep:
                (xs if kind == "X" else zs).append(s)
    return xs, zs

def gf2_rank(m):
    m = m.copy() % 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 rows:
            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

def describe(d, x_edges, z_edges):
    xs, zs = checks(d, x_edges, z_edges)
    hx = np.zeros((len(xs), d * d), dtype=np.uint8)
    hz = np.zeros((len(zs), d * d), dtype=np.uint8)
    for i, s in enumerate(xs):
        hx[i, s] = 1
    for i, s in enumerate(zs):
        hz[i, s] = 1
    commute = not ((hx.astype(int) @ hz.T) % 2).any()
    return len(xs), len(zs), commute, d * d - gf2_rank(hx) - gf2_rank(hz)

d = 5
print("standard     ", describe(d, ("top", "bottom"), ("left", "right")))
print("X on 4 edges ", describe(d, ("top", "bottom", "left", "right"), ()))
print("Z on 4 edges ", describe(d, (), ("top", "bottom", "left", "right")))
print("no boundaries", describe(d, (), ()))

It prints (number of XX checks, number of ZZ checks, commute, kk):

Variant XX checks ZZ checks Commute kk Distance (ZZ-type / XX-type)
standard 12 12 yes 1 5 / 5
XX checks on all four edges 16 8 yes 1 5 / 1
ZZ checks on all four edges 8 16 yes 1 1 / 5
no boundary checks 8 8 yes 9 not computed

The distances in the last column come from the brute-force search you write in the exercise. The lesson is that k=1k = 1 and commuting checks are not enough. In the "all XX edges" variant a single XX on a corner qubit commutes with every ZZ check (no ZZ face touches the corner any more) and is not a stabilizer: an undetectable logical error of weight 1. Correct boundaries are what force logical strings to cross the whole patch.

Relation to the repetition code

The repetition code is a one-dimensional version of the same picture. On a line of qubits with checks ZiZi+1Z_iZ_{i+1}, a block of consecutive XX errors is detected only at its two ends, the two ends of the line act as boundaries, and a logical error is a string that spans the line. The surface code adds a second dimension so that both error types are strings with detected endpoints: XX strings must span the patch from top to bottom and ZZ strings from left to right. The bit-flip repetition code has distance dd against XX errors and 1 against ZZ errors; the surface code has distance dd against both, at the cost of d2d^2 instead of dd data qubits. Stim's repetition_code:memory and surface_code:rotated_memory_z circuits share the same structure, which is why the repetition code is the standard first test of any surface-code pipeline.

From checks to circuits

Each check is measured by a dedicated measure qubit at the centre of its face, coupled to its two or four data qubits by CNOTs, as in the circuits of the introductory lessons. A single XX or ZZ error on a data qubit flips at most two checks of the opposite type (one if it is next to the appropriate boundary). This is exactly the property that makes the decoding problem a graph problem: every elementary error is an edge between two checks or between a check and the boundary. In the next lesson these circuits are simulated in Stim, where the order of the CNOTs turns out to change the effective distance.

Stim lays out the same code on doubled integer coordinates (data qubits at odd positions, measure qubits at even positions) and may assign the boundary types differently from our convention; the exercise checks that its four-qubit and two-qubit checks match ours in number for each type.

Common mistakes

  • Counting checks as independent without checking the rank. In the toric code the product of all stars is the identity; k=2k = 2, not 0.
  • Assigning boundary types by symmetry. Commuting checks and k=1k = 1 can hide a weight-1 logical operator at a corner. Always compute the distance.
  • Treating "the" logical operator as unique. Zˉ\bar Z has many representatives (8 of minimum weight already for d=3d = 3); decoders care about equivalence classes, not strings.
  • Confusing rotated and unrotated qubit counts. For distance dd the rotated layout uses 2d2−12d^2 - 1 qubits and the unrotated (2d−1)2(2d-1)^2.
  • Mixing conventions between tools. Qubit indices, coordinates and which edges carry which checks differ between Stim, papers and this course. Map them explicitly before comparing.

Summary

  • The toric code on 2L22L^2 qubits has star and plaquette checks, k=2k = 2, distance LL; errors are strings detected at their endpoints.
  • Boundaries turn the torus into a planar patch with one logical qubit; each boundary type absorbs one type of string.
  • The rotated code has d2d^2 data qubits, (d2−1)/2(d^2-1)/2 checks of each type, 2d2−12d^2 - 1 qubits in total, k=1k = 1 and distance dd, proved by the column and row argument.
  • Wrong boundary assignments can keep k=1k = 1 yet reduce the distance to 1.

Exercise

In the exercise you implement the construction above, verify commutation, check counts and k=1k = 1 for dd up to 9, find the distance by brute force for d=3,5d = 3, 5, build the toric code and confirm k=2k = 2, and compare the check weight profile with Stim's generated circuit. Next, syndrome extraction with Stim turns these checks into noisy circuits.

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.

Constructing the rotated surface code and verifying its parameters

intermediate · about 1 h 30 min · needs numpy, stim, pytest

You will generate the check matrices of the rotated surface code for any odd distance dd, prove to yourself (numerically) that they define a [[d2,1,d]][[d^2, 1, d]] CSS code, and do the same for the toric code, which stores two logical qubits. A last check compares your layout with the checks that Stim's built-in circuit generator measures.

Layout (follow it exactly; the module docstring repeats it)

  • Data qubit (r,c)(r, c) with 0≤r,c<d0 \le r, c < d has index q=rd+cq = rd + c.
  • A plaquette is named by its top-left corner (r,c)(r, c), −1≤r,c≤d−1-1 \le r, c \le d-1, and touches whichever of (r,c),(r,c+1),(r+1,c),(r+1,c+1)(r,c), (r,c+1), (r+1,c), (r+1,c+1) exist.
  • It is XX-type when r+cr + c is even and ZZ-type when r+cr + c is odd.
  • Every weight-4 plaquette is a check. A weight-2 plaquette is a check only if it is XX-type on the top or bottom edge, or ZZ-type on the left or right edge. Weight-1 corners are never checks.

Functions to implement in starter.py

Function Contract
rotated_surface_code_checks(d) (x_checks, z_checks), each a list of sorted tuples of data-qubit indices, row-major by plaquette corner. ValueError unless dd is odd and ≥3\ge 3.
check_matrix(checks, n) The 0/1 incidence matrix.
css_commute(hx, hz) HXHZT=0 mod 2H_XH_Z^{\mathsf T} = 0 \bmod 2.
css_num_logical(hx, hz) k=n−rank⁡HX−rank⁡HZk = n - \operatorname{rank}H_X - \operatorname{rank}H_Z over F2\F_2.
logical_operators(d) (x_logical, z_logical): XX on column 0, ZZ on row 0.
css_min_logical_weight(h_detect, h_stab, max_weight) Smallest weight of vv with hdetectv=0h_{\text{detect}}v = 0 and v∉rowspace⁡(hstab)v \notin \operatorname{rowspace}(h_{\text{stab}}), or None up to max_weight.
count_min_weight_logicals(h_detect, h_stab, weight) How many such vectors have exactly that weight.
toric_code_check_matrices(L) Vertex (XX) and plaquette (ZZ) checks of the L×LL\times L toric code with 2L22L^2 edge qubits; edge indexing in the docstring.

_gf2_rank is provided.

What the checks verify

  • Counts: (d2−1)/2(d^2-1)/2 checks of each type, (d−1)2/2(d-1)^2/2 of weight 4 and d−1d-1 of weight 2, for d=3,5,7,9d = 3, 5, 7, 9.
  • Commutation, k=1k = 1, and logical operators of weight dd that commute with the opposite-type checks and anticommute with each other.
  • Distance by brute force for d=3,5d = 3, 5: no logical operator of weight ≤d−1\le d-1 in either sector, and one of weight dd.
  • Toric code: every check has weight 4, every qubit is in two checks of each type, k=2k = 2, and distance LL for L=2,3L = 2, 3.
  • Your weight profile per check type equals the one read from stim.Circuit.generated("surface_code:rotated_memory_z", ...).

Run the checks

python -m pytest test_exercise.py
Terminal
python -m pip install numpy stim pytest

starter.py

Python
"""Starter: the rotated surface code (and the toric code) as CSS check matrices.

Layout of the rotated code of odd distance d:

- data qubit (r, c), with 0 <= r, c < d, has index q = r * d + c;
- a plaquette is named by its top-left corner (r, c) with -1 <= r, c <= d - 1 and
  touches the data qubits (r, c), (r, c+1), (r+1, c), (r+1, c+1) that exist;
- a plaquette is X-type when r + c is even and Z-type when r + c is odd;
- every weight-4 (bulk) plaquette is a check; a weight-2 plaquette is a check
  only if it is X-type on the top or bottom edge, or Z-type on the left or right
  edge; corner plaquettes (weight 1) are never checks.

With this convention a row of Z operators and a column of X operators are
logical operators.
"""

from __future__ import annotations

import itertools

import numpy as np


def _gf2_rank(matrix: np.ndarray) -> int:
    m = np.array(matrix, dtype=np.uint8) % 2
    if m.ndim != 2 or m.size == 0:
        return 0
    rank = 0
    rows, cols = m.shape
    for col in range(cols):
        pivot = next((r for r in range(rank, rows) if m[r, col]), None)
        if pivot is None:
            continue
        m[[rank, pivot]] = m[[pivot, rank]]
        for r in range(rows):
            if r != rank and m[r, col]:
                m[r] ^= m[rank]
        rank += 1
        if rank == rows:
            break
    return rank


def rotated_surface_code_checks(d: int) -> tuple[list[tuple[int, ...]], list[tuple[int, ...]]]:
    """(x_checks, z_checks): each check is a sorted tuple of data-qubit indices.

    Follow the layout in the module docstring. Order checks by plaquette corner,
    row-major (r first, then c). Raise ValueError unless d is odd and >= 3.
    """
    raise NotImplementedError("rotated_surface_code_checks: implement this function")


def check_matrix(checks: list[tuple[int, ...]], n: int) -> np.ndarray:
    """0/1 matrix of shape (len(checks), n) with a 1 where check i touches qubit j."""
    raise NotImplementedError("check_matrix: implement this function")


def css_commute(hx: np.ndarray, hz: np.ndarray) -> bool:
    """Every X check overlaps every Z check on an even number of qubits: Hx Hz^T = 0 mod 2."""
    raise NotImplementedError("css_commute: implement this function")


def css_num_logical(hx: np.ndarray, hz: np.ndarray) -> int:
    """k = n - rank(Hx) - rank(Hz) over F_2."""
    raise NotImplementedError("css_num_logical: implement this function")


def logical_operators(d: int) -> tuple[np.ndarray, np.ndarray]:
    """(x_logical, z_logical) as 0/1 vectors of length d*d.

    X_L acts on the first column (c = 0), Z_L on the first row (r = 0).
    """
    raise NotImplementedError("logical_operators: implement this function")


def css_min_logical_weight(h_detect: np.ndarray, h_stab: np.ndarray, max_weight: int) -> int | None:
    """Smallest weight of v with h_detect v = 0 that is not in the row space of h_stab.

    For Z-type logical operators pass (Hx, Hz); for X-type pass (Hz, Hx). Search
    weights 1..max_weight by brute force; return None if none is found.
    """
    raise NotImplementedError("css_min_logical_weight: implement this function")


def count_min_weight_logicals(h_detect: np.ndarray, h_stab: np.ndarray, weight: int) -> int:
    """Number of weight-`weight` vectors v with h_detect v = 0 not in rowspace(h_stab)."""
    raise NotImplementedError("count_min_weight_logicals: implement this function")


def toric_code_check_matrices(L: int) -> tuple[np.ndarray, np.ndarray]:
    """(Hx, Hz) of the L x L toric code with 2 L^2 edge qubits.

    Horizontal edge (r, c) -> index r*L + c joins vertices (r, c) and (r, c+1);
    vertical edge (r, c) -> index L*L + r*L + c joins (r, c) and (r+1, c); all
    coordinates modulo L. X checks are vertex stars, Z checks are plaquettes
    (face with top-left vertex (r, c)). Keep all L^2 of each (they are redundant).
    """
    raise NotImplementedError("toric_code_check_matrices: 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()

from collections import Counter

import numpy as np
import pytest


def matrices(d):
    xs, zs = target.rotated_surface_code_checks(d)
    return target.check_matrix(xs, d * d), target.check_matrix(zs, d * d)


@pytest.mark.parametrize("d", [3, 5, 7, 9])
def test_counts_and_weights(d):
    xs, zs = target.rotated_surface_code_checks(d)
    # Independent counting argument: (d-1)^2 bulk plaquettes split evenly, plus d-1
    # boundary checks of each type, for (d^2-1)/2 of each type.
    assert len(xs) == len(zs) == (d * d - 1) // 2
    for checks in (xs, zs):
        weights = Counter(len(s) for s in checks)
        assert weights == Counter({4: (d - 1) ** 2 // 2, 2: d - 1})
        assert all(0 <= q < d * d for s in checks for q in s)


@pytest.mark.parametrize("d", [3, 5, 7, 9])
def test_commutation_and_one_logical_qubit(d):
    hx, hz = matrices(d)
    assert hx.shape == hz.shape == ((d * d - 1) // 2, d * d)
    assert target.css_commute(hx, hz)
    assert target.css_num_logical(hx, hz) == 1


def test_css_commute_detects_a_bad_check():
    hx, hz = matrices(3)
    bad = hz.copy()
    bad[0] = 0
    bad[0, 0] = 1  # a single-qubit Z check anticommutes with an X check
    assert not target.css_commute(hx, bad)


@pytest.mark.parametrize("d", [3, 5, 7])
def test_logical_operators(d):
    hx, hz = matrices(d)
    xl, zl = target.logical_operators(d)
    assert xl.sum() == zl.sum() == d
    assert not np.any((hz.astype(int) @ xl) % 2)  # X_L commutes with Z checks
    assert not np.any((hx.astype(int) @ zl) % 2)  # Z_L commutes with X checks
    assert int(xl.astype(int) @ zl) % 2 == 1  # X_L and Z_L anticommute


@pytest.mark.parametrize("d", [3, 5])
def test_distance_by_brute_force(d):
    hx, hz = matrices(d)
    assert target.css_min_logical_weight(hx, hz, d) == d  # Z-type logicals
    assert target.css_min_logical_weight(hz, hx, d) == d  # X-type logicals
    assert target.css_min_logical_weight(hx, hz, d - 1) is None


def test_count_min_weight_logicals_d3():
    hx, hz = matrices(3)
    # Every weight-3 Z-type logical meets each column once; at least the three rows qualify.
    count = target.count_min_weight_logicals(hx, hz, 3)
    assert count >= 3
    assert target.count_min_weight_logicals(hx, hz, 2) == 0


@pytest.mark.parametrize("L", [2, 3, 4])
def test_toric_code(L):
    hx, hz = target.toric_code_check_matrices(L)
    assert hx.shape == hz.shape == (L * L, 2 * L * L)
    assert np.all(hx.sum(axis=1) == 4) and np.all(hz.sum(axis=1) == 4)
    assert np.all(hx.sum(axis=0) == 2) and np.all(hz.sum(axis=0) == 2)
    assert target.css_commute(hx, hz)
    assert target.css_num_logical(hx, hz) == 2  # the torus stores two qubits
    if L <= 3:
        assert target.css_min_logical_weight(hx, hz, L) == L
        assert target.css_min_logical_weight(hz, hx, L) == L


def _stim_check_weights(d):
    stim = pytest.importorskip("stim")
    circuit = stim.Circuit.generated("surface_code:rotated_memory_z", distance=d, rounds=1)
    hadamard = set()
    partners = {}
    for inst in circuit.flattened():
        if inst.name == "H":
            hadamard |= {t.value for t in inst.targets_copy()}
        if inst.name == "CX":
            ts = [t.value for t in inst.targets_copy()]
            for control, tgt in zip(ts[::2], ts[1::2]):
                if control in hadamard:  # X-type measure qubit is the control
                    partners.setdefault(("X", control), set()).add(tgt)
                else:  # Z-type measure qubit is the target
                    partners.setdefault(("Z", tgt), set()).add(control)
        if inst.name in ("M", "MR") and partners:
            break
    weights = {"X": Counter(), "Z": Counter()}
    for (kind, _), support in partners.items():
        weights[kind][len(support)] += 1
    return weights


@pytest.mark.parametrize("d", [3, 5])
def test_weight_profile_matches_stim_generated_circuit(d):
    # Independent construction: the checks Stim's generator actually measures.
    stim_weights = _stim_check_weights(d)
    xs, zs = target.rotated_surface_code_checks(d)
    assert Counter(len(s) for s in xs) == stim_weights["X"]
    assert Counter(len(s) for s in zs) == stim_weights["Z"]

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. How many physical qubits (data plus one measure qubit per check) does a distance-11 rotated surface-code patch use?

    1 pt
  2. In the rotated surface code of distance d=7d = 7, how many XX-type checks have weight 4?

    1 pt
  3. In this lesson's distance-3 convention (data qubits 0 to 8 row by row; XX checks {1,2},{0,1,3,4},{4,5,7,8},{6,7}\{1,2\}, \{0,1,3,4\}, \{4,5,7,8\}, \{6,7\}; ZZ checks {0,3},{1,2,4,5},{3,4,6,7},{5,8}\{0,3\}, \{1,2,4,5\}, \{3,4,6,7\}, \{5,8\}), which operator is a logical operator?

    1 pt
  4. Use count_min_weight_logicals(hx, hz, 5) from your exercise on the distance-5 rotated code (pass HXH_X first, so you count ZZ-type logical operators). How many ZZ-type logical operators of weight exactly 5 are there?

    2 pts

    Computed by running exercise “rotated-surface-code-checks” on your computer.

  5. The lesson proves that every ZZ-type logical operator has weight at least dd. What is the key step?

    1 pt
  6. A colleague puts two-qubit XX-type checks on all four edges of a d=5d = 5 patch (and no two-qubit ZZ checks). All checks commute and k=1k = 1. What is wrong?

    1 pt
  7. Select every true statement about the L×LL \times L toric code.

    1 pt

    Select all that apply.

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

References

  1. A. Yu. Kitaev (2003). Fault-tolerant quantum computation by anyons. Annals of Physics 303, 2-30. doi:10.1016/S0003-4916(02)00018-0
  2. S. B. Bravyi, A. Yu. Kitaev (1998). Quantum codes on a lattice with boundary. arXiv:quant-ph/9811052
  3. Eric Dennis et al. (2002). Topological quantum memory. Journal of Mathematical Physics 43, 4452-4505. doi:10.1063/1.1499754
  4. Austin G. Fowler et al. (2012). Surface codes: Towards practical large-scale quantum computation. Physical Review A 86, 032324. doi:10.1103/PhysRevA.86.032324
  5. Yu Tomita, Krysta M. Svore (2014). Low-distance surface codes under realistic quantum noise. Physical Review A 90, 062320. doi:10.1103/PhysRevA.90.062320
  6. Daniel Gottesman (1997). Stabilizer Codes and Quantum Error Correction. PhD thesis, California Institute of Technology. arXiv:quant-ph/9705052