About this notebook

Companion to Lecture 3: Surface codes and syndrome extraction. Every cell below was executed headless with the course’s pinned Deltakit (deltakit 0.10.2, deltakit-stim 0.2.7, pymatching 2.4.0, Python 3.12.12); each output is exactly what the code printed. Download the notebook (.ipynb)

Lecture 3 built the rotated surface code from the toric code and wrote the circuit that measures it. Here you run all of it. You will:

  1. draw the three code families Deltakit ships and check their parameters ;
  2. read one round of the syndrome-extraction circuit, gate by gate;
  3. count qubits, gates and detectors as the distance grows;
  4. try every schedule Deltakit offers and see that none of them loses distance;
  5. build a hook-aligned CNOT order by hand, and measure what it costs in distance and in logical error rate;
  6. meet the stability experiment, which needs Deltakit’s cloud service.
import deltakit
import deltakit_stim as stim
import matplotlib.pyplot as plt
import numpy as np
from IPython.display import SVG
from matplotlib_inline.backend_inline import set_matplotlib_formats
 
from deltakit.circuit.gates import PauliBasis
from deltakit.decode import PyMatchingDecoder
from deltakit.decode.analysis import StimDecoderManager
from deltakit.explorer.analysis import calculate_lep_and_lep_stddev
from deltakit.explorer.codes import (
    CSSCode,
    RotatedPlanarCode,
    ScheduleOrder,
    ScheduleType,
    UnrotatedPlanarCode,
    UnrotatedToricCode,
    css_code_memory_circuit,
    css_code_stability_circuit,
)
from deltakit.explorer.qpu import QPU, SD6Noise, SI1000Noise
 
set_matplotlib_formats("svg")
SEED = 2026
print("deltakit", deltakit.__version__, "| deltakit_stim", stim.__version__)
deltakit 0.10.2 | deltakit_stim 0.2.7

1. Three code families

Deltakit’s deltakit.explorer.codes has the toric code (UnrotatedToricCode), the planar code cut from it (UnrotatedPlanarCode) and the rotated surface code (RotatedPlanarCode). All three are CSS codes, so , with ranks over . The property parity_check_matrices returns as 0/1 arrays. A short Gaussian elimination gives the ranks, and you can compare them with the number of logical operators Deltakit lists.

def gf2_rank(m):
    """Rank of a 0/1 matrix over GF(2), by Gaussian elimination."""
    m = np.array(m, dtype=np.uint8) % 2
    rank = 0
    for col in range(m.shape[1]):
        rows = np.nonzero(m[rank:, col])[0]
        if len(rows) == 0:
            continue
        pivot = rank + rows[0]
        m[[rank, pivot]] = m[[pivot, rank]]
        for r in np.nonzero(m[:, col])[0]:
            if r != rank:
                m[r] ^= m[rank]
        rank += 1
        if rank == m.shape[0]:
            break
    return rank
 
 
families = [("toric", UnrotatedToricCode, L) for L in (3, 4, 5)]
families += [("planar", UnrotatedPlanarCode, L) for L in (3, 5)]
families += [("rotated", RotatedPlanarCode, d) for d in (3, 5, 7, 9)]
print("family   L/d    n  checks X/Z  rank X/Z  k  logicals  qubits")
for name, cls, L in families:
    code = cls(L, L)
    hx, hz = (np.asarray(m) for m in code.parity_check_matrices)
    n = len(code.data_qubits)
    rx, rz = gf2_rank(hx), gf2_rank(hz)
    print(f"{name:8s} {L:3d} {n:4d} {hx.shape[0]:6d}/{hz.shape[0]:<4d}"
          f" {rx:5d}/{rz:<4d} {n - rx - rz:2d} {len(code.x_logical_operators):6d}"
          f" {len(code.qubits):9d}")
family   L/d    n  checks X/Z  rank X/Z  k  logicals  qubits
toric      3   18      9/9        8/8     2      2        36
toric      4   32     16/16      15/15    2      2        64
toric      5   50     25/25      24/24    2      2       100
planar     3   13      6/6        6/6     1      1        25
planar     5   41     20/20      20/20    1      1        81
rotated    3    9      4/4        4/4     1      1        17
rotated    5   25     12/12      12/12    1      1        49
rotated    7   49     24/24      24/24    1      1        97
rotated    9   81     40/40      40/40    1      1       161

The table confirms the lecture’s counting. The toric code has checks of each type but rank , so at every size. The planar code has data qubits and . The rotated code has data qubits, checks of full rank, and qubits in all, with one ancilla per check.

draw_patch() draws any of them and returns a matplotlib (figure, axes) pair. The repetition code has no draw_patch.

fig, ax = UnrotatedToricCode(3, 3).draw_patch()
ax.grid(False)
plt.show()
The 3×3 toric code as Deltakit draws it: 18 data qubits and 18 checks. The patch is periodic: a plaquette that sticks out past an edge wraps around to the qubits on the opposite side, so every check has weight 4.

The 3×3 toric code as Deltakit draws it: 18 data qubits and 18 checks. The patch is periodic: a plaquette that sticks out past an edge wraps around to the qubits on the opposite side, so every check has weight 4.

fig, ax = UnrotatedPlanarCode(3, 3).draw_patch()
ax.grid(False)
plt.show()
The distance-3 unrotated planar code: 13 data qubits and 12 checks. The cut boundaries carry weight-3 checks.

The distance-3 unrotated planar code: 13 data qubits and 12 checks. The cut boundaries carry weight-3 checks.

Notebook 0 drew the distance-3 rotated code. It uses 9 data qubits where the planar code needs 13, and its boundary checks have weight 2.

2. One round of syndrome extraction

A one-round -basis memory circuit at shows the whole extraction circuit. Deltakit writes every check with an ancilla prepared in and measured in the basis. checks use CX from the ancilla, and checks use CZ:

 X check                      Z check
 anc  RX ──●──●──●──●── MX     anc  RX ──●──●──●──●── MX
 d1   ─────X──┼──┼──┼───       d1   ─────Z──┼──┼──┼───
 d2   ────────X──┼──┼───       d2   ────────Z──┼──┼───
 d3   ───────────X──┼───       d3   ───────────Z──┼───
 d4   ──────────────X───       d4   ──────────────Z───

(A CZ is symmetric, so “control” and “target” do not matter for it.) Here is the Stim text of the whole circuit. QUBIT_COORDS gives each qubit its Deltakit coordinates, with data qubits at odd and ancillas at even .

code3 = RotatedPlanarCode(3, 3)
one_round = css_code_memory_circuit(
    code3, num_rounds=1, logical_basis=PauliBasis.Z
).as_stim_circuit()
print(one_round)
QUBIT_COORDS(2, 4) 0
QUBIT_COORDS(4, 0) 1
QUBIT_COORDS(1, 5) 2
QUBIT_COORDS(3, 1) 3
QUBIT_COORDS(5, 1) 4
QUBIT_COORDS(6, 4) 5
QUBIT_COORDS(0, 2) 6
QUBIT_COORDS(2, 2) 7
QUBIT_COORDS(1, 3) 8
QUBIT_COORDS(3, 5) 9
QUBIT_COORDS(4, 4) 10
QUBIT_COORDS(5, 5) 11
QUBIT_COORDS(1, 1) 12
QUBIT_COORDS(4, 2) 13
QUBIT_COORDS(3, 3) 14
QUBIT_COORDS(2, 6) 15
QUBIT_COORDS(5, 3) 16
R 14 4 12 11 16 8 2 3 9
RX 5 1 0 13 6 10 15 7
TICK
I 12 8 2 3 14 9 4 16 11
TICK
CX 5 11 0 2 13 14
CZ 1 3 10 9 7 8
TICK
CX 5 16 0 8 13 3
CZ 1 4 10 11 7 14
TICK
CX 0 9 13 16 6 8
CZ 10 14 15 2 7 12
TICK
CX 0 14 13 4 6 12
CZ 10 16 15 9 7 3
TICK
MX 5 1 0 13 6 10 15 7
M 11 2 3 12 4 14 16 8 9
DETECTOR(4, 0, 0) rec[-16]
DETECTOR(4, 4, 0) rec[-12]
DETECTOR(2, 6, 0) rec[-11]
DETECTOR(2, 2, 0) rec[-10]
SHIFT_COORDS(0, 0, 1)
OBSERVABLE_INCLUDE(0) rec[-8] rec[-6] rec[-2]
DETECTOR(4, 0, 0) rec[-16] rec[-7] rec[-5]
DETECTOR(4, 4, 0) rec[-12] rec[-9] rec[-4] rec[-3] rec[-1]
DETECTOR(2, 6, 0) rec[-8] rec[-11] rec[-1]
DETECTOR(2, 2, 0) rec[-10] rec[-7] rec[-6] rec[-4] rec[-2]
SHIFT_COORDS(0, 0, 1)

Read it from the top:

  • R resets the 9 data qubits to , and RX the 8 ancillas to .
  • I marks the data qubits as idle for one time step. This is where a phenomenological noise model puts its data errors (Lecture 4).
  • Four layers of CX and CZ follow, six gates per layer. In each CX or CZ line the targets come in pairs, ancilla first. Ancilla 13 at is an check. It meets data qubits 14, 3, 16 and 4, at , , and : top-left, bottom-left, top-right, bottom-right, the “N” order.
  • MX measures the ancillas and M the data qubits.
  • The first four DETECTORs are the first-round checks, which are deterministic because the data started in . The last four compare each check with the product of its data-qubit readouts. OBSERVABLE_INCLUDE(0) is : the readouts of qubits 12, 8 and 2, the left column.

Stim can draw what each detector “looks at”. A detslice diagram shows, at each time step, the Pauli product that the detector is sensitive to: a fault there that anticommutes with it flips the detector. Here are all eight detectors of the noiseless one-round circuit, one panel per time step:

SVG(str(one_round.diagram("detslice-svg", tick=range(1, 7))))
Stim's detslice diagram of the one-round d = 3 Z-basis memory, one panel per time step, from just after the resets (top left) to just after the last CZ layer (bottom right). Each coloured patch is one detector's slice: red marks X sensitivity, on the Z-check ancillas that are prepared and read in the X basis, and blue marks Z sensitivity, on data qubits. The middle panels show the CZ layers moving the sensitivity between ancilla and data.

Stim's detslice diagram of the one-round d = 3 Z-basis memory, one panel per time step, from just after the resets (top left) to just after the last CZ layer (bottom right). Each coloured patch is one detector's slice: red marks X sensitivity, on the Z-check ancillas that are prepared and read in the X basis, and blue marks Z sensitivity, on data qubits. The middle panels show the CZ layers moving the sensitivity between ancilla and data.

3. Counting operations and detectors

Every resource of a -round memory experiment grows with . The lecture derived three formulas: qubits, two-qubit gates per round, and detectors for rounds. Check them for with :

ds = [3, 5, 7, 9, 11]
counts = {}
print(" d  qubits  2d^2-1  2q gates  4d(d-1)r  detectors  r(d^2-1)  ticks")
for d in ds:
    c = css_code_memory_circuit(
        RotatedPlanarCode(d, d), num_rounds=d, logical_basis=PauliBasis.Z
    ).as_stim_circuit()
    flat = list(c.flattened())
    n2q = sum(len(i.targets_copy()) // 2 for i in flat if i.name in ("CX", "CZ"))
    ticks = sum(1 for i in flat if i.name == "TICK")
    counts[d] = (c.num_qubits, n2q, c.num_detectors)
    print(f"{d:2d} {c.num_qubits:7d} {2 * d * d - 1:7d} {n2q:9d} {4 * d * (d - 1) * d:9d}"
          f" {c.num_detectors:10d} {d * (d * d - 1):9d} {ticks:6d}")
 d  qubits  2d^2-1  2q gates  4d(d-1)r  detectors  r(d^2-1)  ticks
 3      17      17        72        72         24        24     18
 5      49      49       400       400        120       120     30
 7      97      97      1176      1176        336       336     42
 9     161     161      2592      2592        720       720     54
11     241     241      4840      4840       1320      1320     66
fig, ax = plt.subplots()
labels = ["qubits", "two-qubit gates", "detectors"]
for k, label in enumerate(labels):
    ax.plot(ds, [counts[d][k] for d in ds], marker="o", label=label)
guide = [counts[3][1] * (d / 3) ** 3 for d in ds]
ax.plot(ds, guide, linestyle="--", color="0.5", label="slope 3")
ax.set_xscale("log")
ax.set_yscale("log")
ax.set_xticks(ds, [str(d) for d in ds])
ax.minorticks_off()
ax.set_xlabel("code distance d (rounds = d)")
ax.set_ylabel("count")
ax.legend()
plt.show()
Size of a d-round rotated surface-code memory circuit against distance, on log–log axes. Two-qubit gates and detectors both grow like d³ (the dashed guide has slope 3); qubits grow like d².

Size of a d-round rotated surface-code memory circuit against distance, on log–log axes. Two-qubit gates and detectors both grow like d³ (the dashed guide has slope 3); qubits grow like d².

4. Schedules Deltakit offers

RotatedPlanarCode takes schedule_type and schedule_order. The type decides whether and checks are measured at the same time (SIMULTANEOUS, the default) or one type after the other (Z_FIRST, X_FIRST). The order reflects the CNOT pattern (HORIZONTALLY_REFLECTED is the default). For each combination, the cell below counts the time steps of a 5-round, memory and asks Stim for its circuit distance under SD6 noise: the fewest graphlike faults (shortest_graphlike_error) that flip the observable without lighting a detector. It tries both memory bases.

def circuit_distance(code, basis, rounds, p=1e-3):
    circ = css_code_memory_circuit(code, num_rounds=rounds, logical_basis=basis)
    qpu = QPU(circ.qubits, noise_model=SD6Noise(p=p))
    noisy = qpu.compile_and_add_noise_to_circuit(circ).as_stim_circuit()
    return len(noisy.shortest_graphlike_error())
 
 
def tick_count(code, rounds):
    c = css_code_memory_circuit(code, num_rounds=rounds, logical_basis=PauliBasis.Z)
    return sum(1 for i in c.as_stim_circuit().flattened() if i.name == "TICK")
 
 
types = [ScheduleType.SIMULTANEOUS, ScheduleType.Z_FIRST, ScheduleType.X_FIRST]
print(f"{'type':13s} {'order':23s} ticks  dist Z/X")
for st in types:
    for so in ScheduleOrder:
        code = RotatedPlanarCode(5, 5, schedule_type=st, schedule_order=so)
        dz = circuit_distance(code, PauliBasis.Z, 5)
        dx = circuit_distance(code, PauliBasis.X, 5)
        print(f"{st.name:13s} {so.name:23s} {tick_count(code, 5):5d}  {dz}/{dx}")
type          order                   ticks  dist Z/X
SIMULTANEOUS  STANDARD                   30  5/5
SIMULTANEOUS  HORIZONTALLY_REFLECTED     30  5/5
SIMULTANEOUS  VERTICALLY_REFLECTED       30  5/5
SIMULTANEOUS  DOUBLY_REFLECTED           30  5/5
Z_FIRST       STANDARD                   55  5/5
Z_FIRST       HORIZONTALLY_REFLECTED     55  5/5
Z_FIRST       VERTICALLY_REFLECTED       55  5/5
Z_FIRST       DOUBLY_REFLECTED           55  5/5
X_FIRST       STANDARD                   55  5/5
X_FIRST       HORIZONTALLY_REFLECTED     55  5/5
X_FIRST       VERTICALLY_REFLECTED       55  5/5
X_FIRST       DOUBLY_REFLECTED           55  5/5

Every schedule keeps the full distance 5. The sequential types cost depth: 55 time steps for five rounds instead of 30, which means more idle noise per round on real hardware. To see a hook error you have to build a bad order yourself.

5. A hook-aligned order, built by hand

A check’s paulis list is its CNOT schedule, with None where a weight-2 boundary check sits out a step. So the code below rebuilds each check with its terms in a new order and wraps the result in a CSSCode. Offsets are measured from the ancilla, with pointing up. Stabiliser, the check class, is not exported in Deltakit 0.10.2, so we take it from an existing check.

TL, TR, BL, BR = (-1, 1), (1, 1), (-1, -1), (1, -1)
N_ORDER, Z_ORDER = (TL, BL, TR, BR), (TL, TR, BL, BR)
 
 
def offset(stab, pauli):
    a = stab.ancilla_qubit.unique_identifier
    q = pauli.qubit.unique_identifier
    return (int(q[0] - a[0]), int(q[1] - a[1]))
 
 
def reorder(code, x_order, z_order):
    """Same checks and logicals, new CNOT order for each check type."""
    Stabiliser = type(code.stabilisers[0][0])
    checks = []
    for s in code.stabilisers[0]:
        terms = [p for p in s.paulis if p is not None]
        is_x = type(terms[0]).__name__.endswith("X")
        by_offset = {offset(s, p): p for p in terms}
        order = x_order if is_x else z_order
        checks.append(Stabiliser(paulis=[by_offset.get(o) for o in order],
                                 ancilla_qubit=s.ancilla_qubit))
    return CSSCode(stabilisers=[checks],
                   x_logical_operators=code.x_logical_operators,
                   z_logical_operators=code.z_logical_operators)
 
 
same = reorder(code3, N_ORDER, Z_ORDER)
for basis in (PauliBasis.Z, PauliBasis.X):
    a = css_code_memory_circuit(code3, num_rounds=3, logical_basis=basis)
    b = css_code_memory_circuit(same, num_rounds=3, logical_basis=basis)
    print(f"{basis.name}-memory: reorder(N, Z) gives the default circuit:",
          str(a.as_stim_circuit()) == str(b.as_stim_circuit()))
Z-memory: reorder(N, Z) gives the default circuit: True
X-memory: reorder(N, Z) gives the default circuit: True

With the default orders, reorder reproduces Deltakit’s own circuit exactly, so the helper changes nothing else. Now try all four combinations of N and Z orders for the two check types, at in both memory bases:

orders = {"N": N_ORDER, "Z": Z_ORDER}
print("X checks  Z checks   d   Z-memory  X-memory")
for d in (3, 5, 7):
    base = RotatedPlanarCode(d, d)
    for xo, zo in (("N", "Z"), ("Z", "Z"), ("N", "N"), ("Z", "N")):
        code = reorder(base, orders[xo], orders[zo])
        dz = circuit_distance(code, PauliBasis.Z, d)
        dx = circuit_distance(code, PauliBasis.X, d)
        print(f"   {xo}         {zo}     {d}   {dz:6d}   {dx:6d}")
X checks  Z checks   d   Z-memory  X-memory
   N         Z     3        3        3
   Z         Z     3        2        3
   N         N     3        3        2
   Z         N     3        2        2
   N         Z     5        5        5
   Z         Z     5        3        5
   N         N     5        5        3
   Z         N     5        3        3
   N         Z     7        7        7
   Z         Z     7        4        7
   N         N     7        7        4
   Z         N     7        4        4

The pattern is exactly the lecture’s argument. checks in Z order end on a horizontal pair, along . That hurts the -basis memory, whose observable is flipped by strings, and its distance falls to = 2, 3, 4. checks in N order end on a vertical pair, along , and hurt the -basis memory in the same way.

Stim can name the faults. For the bad circuit, shortest_graphlike_error() returns two ExplainedError objects. Each one has the detectors it flips and one or more circuit locations that produce it:

bad3 = reorder(code3, Z_ORDER, Z_ORDER)
circ = css_code_memory_circuit(bad3, num_rounds=3, logical_basis=PauliBasis.Z)
qpu = QPU(circ.qubits, noise_model=SD6Noise(p=1e-3))
noisy = qpu.compile_and_add_noise_to_circuit(circ)
for err in noisy.as_stim_circuit().shortest_graphlike_error():
    terms = " ".join(str(t) for t in err.dem_error_terms)
    loc = err.circuit_error_locations[0]
    pauli = "*".join(str(t) for t in loc.flipped_pauli_product)
    print(f"{terms:36s} <- {pauli} after {loc.tick_offset} ticks")
D3[coords 2,2,0] D7[coords 4,2,1]    <- X13[coords 4,2]*Y3[coords 3,1] after 5 ticks
D3[coords 2,2,0] D7[coords 4,2,1] L0 <- X12[coords 1,1]*Y7[coords 2,2] after 5 ticks

The first fault acts on qubit 13, the -check ancilla at , partway through the round: the hook. It lights two detectors and leaves an pair on the bottom row. The second is an ordinary fault next to qubit 12 at . Together they make a full row of that flips (the L0 term), while every detector they light is lit twice and so stays dark.

Distance is a worst case. What does the hook cost on average? Run 200,000 shots of a 5-round, memory with SI1000 noise at , for the N order and the bad -check order, in both bases. Both codes go through the same reorder helper, so the only difference is the order. (At the N-order copy reads the data out in a different order than Deltakit’s own circuit, so the same seed assigns its random draws differently. Its DEM is identical, and the built-in default’s counts differ from these only by shot noise.)

results = {}
for label, xo in (("N order", N_ORDER), ("hook-aligned (Z)", Z_ORDER)):
    code = reorder(RotatedPlanarCode(5, 5), xo, Z_ORDER)
    for basis in (PauliBasis.Z, PauliBasis.X):
        c = css_code_memory_circuit(code, num_rounds=5, logical_basis=basis)
        qpu = QPU(c.qubits, noise_model=SI1000Noise(p=1e-3))
        noisy = qpu.compile_and_add_noise_to_circuit(c)
        dec, dcirc = PyMatchingDecoder.construct_decoder_and_stim_circuit(noisy)
        manager = StimDecoderManager(dcirc, dec, seed=SEED, batch_size=100_000)
        n, f = manager.run_batch_shots(200_000)
        results[label, basis.name] = (int(f), int(n))
        print(f"{label:17s} {basis.name}-memory: {int(f):4d} fails in {int(n)} shots")
N order           Z-memory:  185 fails in 200000 shots
N order           X-memory:  192 fails in 200000 shots
hook-aligned (Z)  Z-memory:  547 fails in 200000 shots
hook-aligned (Z)  X-memory:  214 fails in 200000 shots
fig, ax = plt.subplots()
labels = ["N order", "hook-aligned (Z)"]
xs = np.arange(2)
for k, basis in enumerate(("Z", "X")):
    fails = [results[label, basis][0] for label in labels]
    shots = [results[label, basis][1] for label in labels]
    lep, err = calculate_lep_and_lep_stddev(fails=fails, shots=shots)
    ax.bar(xs + (k - 0.5) * 0.36, lep, width=0.36, yerr=err, capsize=3,
           label=f"{basis}-basis memory")
ax.set_xticks(xs, ["X checks in N order\n(hook-safe)",
                   "X checks in Z order\n(hook-aligned)"])
ax.set_ylabel("logical error probability (5 rounds)")
ax.set_axisbelow(True)
ax.grid(axis="x", visible=False)
ax.legend()
plt.show()
Logical error probability of a 5-round, distance-5 memory with SI1000 noise at p = 10⁻³, 200,000 shots per bar, PyMatching. A hook-aligned X-check order roughly triples the Z-memory failures and barely changes the X memory.

Logical error probability of a 5-round, distance-5 memory with SI1000 noise at p = 10⁻³, 200,000 shots per bar, PyMatching. A hook-aligned X-check order roughly triples the Z-memory failures and barely changes the X memory.

The hook-aligned order roughly triples the failures of the -basis memory. The -basis memory, whose logical operator lies across the hook pairs, barely changes. A circuit-level distance of 3 instead of 5 means that the leading failure needs two faults instead of three, and at that shows up directly in the count.

6. Stability experiments need the cloud

A stability experiment (Lecture 3) tests the time direction: a patch with no logical qubit, whose checks of one type multiply to a fixed value. Deltakit has css_code_stability_circuit, but it builds the circuit through Riverlane’s cloud service:

try:
    css_code_stability_circuit(code3, num_rounds=3, logical_basis=PauliBasis.Z)
except NotImplementedError as err:
    print("NotImplementedError:", err)
NotImplementedError: A `client` is required to obtain a stability circuit.

Try this

  1. Build RotatedPlanarCode(5, 3) and find its circuit distance in each memory basis. Which of width and height sets which?
  2. Use reorder with both check types in the hook-aligned order and rerun the LEP comparison. Do both bases now suffer?
  3. Measure the LEP of ScheduleType.Z_FIRST against SIMULTANEOUS at with SI1000 noise. The distance is the same; do the extra idle steps cost anything?
  4. Find the circuit distance of a bad order with only 1 round of a memory. Does the number of rounds matter for a hook?