Skip to main content
KetQat

Appearance

Lesson 82 h

Floquet codes

Dynamically generated codes, the honeycomb code and measurement schedules.

After this lesson you can

  • Define the instantaneous stabilizer group of a measurement sequence and update it with the stabilizer measurement rule in binary symplectic form
  • Explain how products of non-commuting two-body checks can be inferred as weight-six stabilizers, and construct detectors from them
  • Build the honeycomb code on a torus, run its period-3 schedule and verify that it generates two logical qubits while the static subsystem code has none
  • Distinguish inner from outer logical operators and explain why a schedule that never pairs two colours fails
  • Argue from circuit structure why weight-two measurements matter for some hardware, citing published threshold comparisons with their stated noise models
  • Verify with Stim that every detector of a Floquet-code circuit is deterministic in the absence of noise

Read first: The stabilizer formalism, The surface code, Syndrome extraction with Stim

Why measure only two qubits at a time

The surface code asks the hardware for one thing over and over: measure a weight-four Pauli operator such as ZaZbZcZdZ_aZ_bZ_cZ_d. In a circuit model this means an ancilla, four two-qubit gates in a carefully chosen order, and a measurement. Every one of those operations can fail, and a single failure on the ancilla part-way through can spread to two data qubits (you will analyse this "hook" mechanism in detail in the next lesson). Some hardware does not even offer a convenient way to do it: in measurement-based architectures, for example those proposed with Majorana zero modes, the native operation is a direct measurement of a two-qubit Pauli product such as XaXbX_aX_b, with no ancilla and no entangling gate at all (Paetznick et al.).

So a natural question is whether a code can be run using only two-body Pauli measurements. Subsystem codes such as the Bacon–Shor code already measure small "gauge" operators and multiply their outcomes to learn larger stabilizers. Hastings and Haah found something stranger: a sequence of two-body measurements that, viewed as a static subsystem code, protects no logical qubit at all, yet whose time ordering continuously regenerates a toric-code-like state with two protected logical qubits on a torus (Hastings and Haah). Codes of this kind are called Floquet codes or dynamically generated codes, because the protection is a property of a periodic schedule rather than of a fixed stabilizer group.

This lesson builds the honeycomb code from its definition and verifies its key properties by exact Pauli algebra. The exercise makes you implement every step.

From subsystem codes to dynamically generated codes

Checks and the instantaneous stabilizer group

Fix nn qubits and a list of Pauli operators called checks. A schedule says which checks are measured in each round; checks measured in the same round must commute with each other, but checks in different rounds need not.

Suppose the system starts in some state, possibly the maximally mixed state, and we measure checks in the order the schedule prescribes. After any prefix of the schedule, the post-measurement state is a stabilizer state (or a mixture of stabilizer states with identical stabilizer group up to signs) whose stabilizer group is fixed by the measurements so far. Call it the instantaneous stabilizer group (ISG) Sr\mathcal S_r after round rr. The number of logical qubits the ISG leaves free is

kr=n−rank⁡(Sr),k_r = n - \operatorname{rank}(\mathcal S_r),

where the rank is the number of independent generators.

The ISG is updated by the standard stabilizer measurement rule. When a Pauli PP is measured:

  1. If PP anticommutes with some generators, pick one of them, gg; replace every other anticommuting generator hh by hghg (which now commutes with PP); finally replace gg by ±P\pm P. The outcome is uniformly random. The rank is unchanged.
  2. If PP commutes with every generator and is already in the group, the outcome is determined by the current signs. Nothing changes.
  3. If PP commutes with every generator and is not in the group, the outcome is random and ±P\pm P is appended. The rank grows by one, and kk drops by one.

Case 3 is the dangerous one once a code is running: if PP commutes with the whole ISG but is not in it, then PP acts on the encoded information, and measuring it destroys a logical qubit. A schedule preserves its logical qubits exactly when, in the steady state, no round ever falls into case 3 for any product of the checks it measures. A practical test follows: run the schedule and watch krk_r. If it stays constant over many periods, no logical information is being measured.

All of this is linear algebra over F2\F_2. Write a Pauli on nn qubits, ignoring its phase, as a vector (x∣z)∈F22n(x \mid z) \in \F_2^{2n}: XqX_q sets xqx_q, ZqZ_q sets zqz_q and YqY_q sets both. Two Paulis commute exactly when the symplectic product xa⋅zb+za⋅xbx_a\cdot z_b + z_a\cdot x_b is 0 mod 20 \bmod 2, products of Paulis are sums of vectors, and "is PP in the group" is a rank test after Gaussian elimination. Signs matter for the values of outcomes but never for which outcomes are random, so the whole structural analysis can drop them.

Inferring a product you never measured

Here is the mechanism that lets two-body checks build weight-six stabilizers. Take six qubits on a hexagon, numbered 0,…,50,\dots,5 around it, and six edge checks eke_k on the pairs (k,k+1 mod 6)(k, k+1 \bmod 6), with Pauli types X, Y, Z, X, Y, Z in turn:

e0=X0X1,  e1=Y1Y2,  e2=Z2Z3,  e3=X3X4,  e4=Y4Y5,  e5=Z5Z0.e_0 = X_0X_1,\; e_1 = Y_1Y_2,\; e_2 = Z_2Z_3,\; e_3 = X_3X_4,\; e_4 = Y_4Y_5,\; e_5 = Z_5Z_0 .

Neighbouring checks share one qubit with different Pauli types, so they anticommute; checks two apart are disjoint and commute. Split them into A={e0,e2,e4}A = \{e_0, e_2, e_4\} and B={e1,e3,e5}B = \{e_1, e_3, e_5\}. Within each set everything commutes. The product of all six is, qubit by qubit (for example qubit 1 sees XX from e0e_0 and YY from e1e_1, and XY=iZXY = iZ),

W=e0e1e2e3e4e5∝Y0 Z1 X2 Y3 Z4 X5.W = e_0e_1e_2e_3e_4e_5 \propto Y_0\,Z_1\,X_2\,Y_3\,Z_4\,X_5 .

WW commutes with every eke_k: each check overlaps WW on two qubits, and on each of them the check's Pauli differs from WW's, giving two sign flips. Now measure AA, then BB. After the AA round the ISG contains e0,e2,e4e_0, e_2, e_4. Each BB check anticommutes with two of them, so its outcome is random, and by rule 1 the ISG after the BB round contains e1,e3,e5e_1, e_3, e_5 together with the products of AA checks that commute with all of BB. The product e0e2e4e_0e_2e_4 is such a product, so e0e2e4⋅e1e3e5∝We_0e_2e_4 \cdot e_1e_3e_5 \propto W is now in the ISG, and its value is the product of all six outcomes. Measure AA again and then BB again, and you obtain a second value of WW. Without errors the two agree, so their parity is a detector, even though every single check outcome in the second and later rounds is a fair coin.

Stim checks this for us. Its detector analysis refuses any detector that is not deterministic in the noiseless circuit (Gidney, Stim).

import stim

a_round = "MPP X0*X1 Z2*Z3 Y4*Y5"
b_round = "MPP Y1*Y2 X3*X4 Z5*Z0"
circuit = stim.Circuit("\n".join([
    "R 0 1 2 3 4 5",
    a_round, b_round, a_round, b_round,
    # W from rounds 3-4 times W from rounds 1-2: twelve measurement records
    "DETECTOR " + " ".join(f"rec[-{i}]" for i in range(1, 13)),
]))
circuit.detector_error_model()          # raises if the detector were random
shots = circuit.compile_sampler(seed=3).sample(4000)
print("mean of each B outcome in round 4:", shots[:, 9:12].mean(axis=0).round(2))
print("detection events:", circuit.compile_detector_sampler(seed=3).sample(4000).sum())

The detector-error-model call returns without complaint, the round-4 BB outcomes average close to 0.50.5 (they are random), and there are zero detection events. Replace Z5*Z0 by X5*X0 in the BB round and the call raises ValueError: The circuit contains non-deterministic detectors, because the new product no longer commutes with e4=Y4Y5e_4 = Y_4Y_5 and WW is no longer a stabilizer.

The honeycomb code

Lattice, colours and Pauli types

Place qubits on the vertices of a honeycomb lattice wrapped on a torus. Following Kitaev's honeycomb model (Kitaev), every edge has a Pauli type, X, Y or Z, according to its direction, so that each vertex has one edge of each type; the check on an edge (u,v)(u, v) of type α\alpha is αuαv\alpha_u\alpha_v. Hastings and Haah add a second label. The hexagonal plaquettes can be coloured with three colours, 0, 1 and 2, so that neighbouring plaquettes differ. Give each edge the colour of the two plaquettes it connects at its ends (the two plaquettes touching its endpoints that do not contain the edge; they always share a colour). Then each vertex also has one edge of each colour, the edges of one colour form a perfect matching of the qubits, and the six boundary edges of a plaquette of colour cc alternate between the two other colours.

The exercise builds this lattice from a triangular lattice of plaquettes: put plaquette (i,j)(i,j) at site (i,j)∈ZL2(i, j) \in \mathbb Z_L^2 with colour (i−j) mod 3(i-j) \bmod 3, and make every elementary triangle of three mutually adjacent plaquettes a qubit. For an L×LL\times L torus with LL a multiple of 3 this gives n=2L2n = 2L^2 qubits, 3L23L^2 edges and L2L^2 plaquettes. The plaquette operator is the product of its six boundary checks, a weight-six Pauli exactly like WW above; it commutes with every check on the lattice.

The period-3 schedule

The honeycomb code's schedule is: in round rr, measure every check of colour r mod 3r \bmod 3. Checks of one colour are disjoint, so each round is a single layer of commuting two-body measurements. A plaquette of colour cc is bounded by checks of colours c+1c+1 and c+2c+2, so it is inferred whenever those two colours are measured in consecutive rounds, exactly as in the hexagon example. In the sequence 0,1,2,0,1,2,…0,1,2,0,1,2,\dots every pair of distinct colours appears consecutively once per period, so every plaquette is re-inferred every three rounds and each inference can be compared with the previous one. That gives one detector per plaquette per period.

The ISG round by round: a computed example

Start from the maximally mixed state (empty ISG) on the L=6L = 6 torus, so n=72n = 72. Running the measurement rule in symplectic form, as the exercise asks you to, gives the number of free qubits after each round:

Round index rr 0 1 2 3 4 5 6 ...
Colour measured 0 1 2 0 1 2 0 ...
kr=n−rank⁡Srk_r = n - \operatorname{rank}\mathcal S_r 36 24 13 2 2 2 2 ...

These are exact values computed with the reference solution of the exercise (no sampling is involved), and the same steady value k=2k=2 appears for L=3L = 3 and L=9L = 9. The transient makes sense: round 0 fixes the 36 colour-0 checks; round 1 replaces them by the colour-1 checks but retains the colour-2 plaquettes they imply; round 2 adds the colour-0 plaquettes, round 3 the colour-1 plaquettes. From then on the ISG is generated by all plaquettes together with the checks just measured, and kk stays at 2: no round ever measures logical information.

Hastings and Haah identify this steady-state ISG as a toric code on a coarser hexagonal superlattice, in which each just-measured check pairs two physical qubits into one effective qubit; on a torus the toric code encodes two logical qubits, consistent with the computed k=2k = 2 (Hastings and Haah). The exercise also computes the static picture. The group generated by all checks, viewed as a subsystem code, has a centre (products of checks commuting with every check) large enough that the number of logical qubits n−rank⁡(centre)−gn - \operatorname{rank}(\text{centre}) - g, with gg the number of gauge qubits, is zero, matching the statement in their abstract that the subsystem code has no logical qubits.

Inner and outer logical operators

Because X and Y edges together give every vertex degree two, they form disjoint cycles, and on the torus these are non-contractible zigzag loops. The product of the checks around one such loop is ZZ on every vertex of the loop (each vertex contributes XY∝ZXY \propto Z). It commutes with every check: an X or Y check on the loop overlaps it on two qubits with differing Paulis, and a Z check touching the loop agrees with it wherever they overlap. It is a product of checks, and the exercise verifies it is never in the ISG. So it is a logical operator of every ISG, and since no check ever anticommutes with it, no measurement disturbs it. Hastings and Haah call such operators inner logical operators. Being products of checks is also why the static subsystem code puts them in its centre and loses them as logical operators.

The outer logical operators are the conjugate partners. An outer operator that commutes with the ISG after round rr generally anticommutes with some checks of round r+1r+1, so it must be multiplied by checks of the current colour to become a valid representative for the next ISG. Tracking a logical observable in a Floquet memory therefore means updating it with measurement outcomes every round. Hastings and Haah describe the net effect of one period as an automorphism of the embedded toric code that exchanges its electric and magnetic logical operators, so the logical operators repeat only every six rounds (Hastings and Haah). We quote that statement; the exercise verifies the inner operators but leaves the outer ones as an extension.

Schedules that fail

The order matters. With the period-2 schedule 0,1,0,1,…0,1,0,1,\dots only colour-2 plaquettes are ever inferred, and the exercise finds a steady-state kk of 24 on the L=6L=6 torus instead of 2. Those extra "logical qubits" are not protected: the plaquettes that would detect errors on them are never measured. A subtler failure is the period-4 schedule 0,1,2,10,1,2,1: colours 0 and 2 are never measured back to back, so colour-1 plaquettes are never inferred. The rule of thumb that falls out of the algebra is that each pair of colours must appear in consecutive rounds, and you should check any proposed schedule by running the ISG update rather than by intuition.

Why weight-two measurements matter for hardware

Compare what one stabilizer measurement costs in a CNOT-based circuit. A weight-two check ZaZbZ_aZ_b needs one ancilla and two CNOTs; a weight-four surface-code stabilizer needs four.

Quantum circuit on 3 wires (a, b, anc). step 1: CNOT, control a, target anc. step 2: CNOT, control b, target anc. step 3: measure anc.abanc
Measuring the two-body check Z_a Z_b with one ancilla: two CNOTs and one measurement

A fault on the ancilla between the two CNOTs can only reach one data qubit after it, so a two-body check has no hook errors of weight two. More importantly, some platforms can measure XaXbX_aX_b, YaYbY_aY_b or ZaZbZ_aZ_b directly, with no ancilla and no two-qubit gate, in which case the whole honeycomb code is a periodic sequence of native operations. The honeycomb lattice also has degree three, which suits hardware with sparse connectivity.

What does this buy in numbers? Published simulations answer it only within stated models, and those models matter:

  • Gidney, Newman, Fowler and Broughton simulated honeycomb and rotated surface code memories with a correlated minimum-weight perfect-matching decoder. In a controlled-NOT circuit model they report a threshold of 0.2–0.3% for the honeycomb code against 0.5–0.7% for the surface code; in a model with native two-body measurements, the honeycomb code's threshold lies between 1.5% and 2.0%, where pp is the collective error rate of the two-body measurement including correlated data depolarization (Gidney et al., 2021).
  • For a planar version, Gidney, Newman and McEwen estimate the qubit count needed for a one-in-a-trillion logical error rate at a 0.1% gate-level error rate as about 7000 physical qubits, or about 900 with native two-qubit parity measurements, again within their specific noise models (Gidney, Newman and McEwen).

The honest reading is conditional: when two-body measurements are native and good, Floquet codes are strong candidates; when every check must be compiled into CNOTs, the surface code's higher circuit-level threshold usually wins. Neither result is a statement about a particular device.

Planar, CSS and other variants

The torus is convenient for analysis but not for chips. Haah and Hastings constructed boundaries for the honeycomb code, giving a planar version with one logical qubit per patch (Haah and Hastings), and Gidney, Newman and McEwen designed boundaries that need no extra connectivity (Gidney, Newman and McEwen). Paetznick and co-authors studied planar Floquet codes on Majorana-based architectures, measuring the checks directly without auxiliary qubits (Paetznick et al.).

The honeycomb code mixes X, Y and Z checks, so it is not a CSS code. Davydova, Tantivasadakarn and Balasubramanian introduced a CSS honeycomb code whose checks are each purely X-type or purely Z-type; its checks do not form a subsystem code with a useful parent, yet the schedule still embeds an instantaneous toric code and conserves logical information (Davydova et al.). Kesselring and co-authors view Floquet codes as sequences of anyon-condensation steps on the colour code and use this to construct a CSS Floquet colour code (Kesselring et al.). We mention these only qualitatively; their thresholds and overheads depend on noise models we have not reproduced here.

What this lesson verified and what it quoted

Verified by computation you can rerun (exercise and snippet): the measurement rule; the inference of weight-six plaquettes from two-body checks; krk_r round by round, including the steady state k=2k=2 on tori with L=3,6,9L = 3, 6, 9; that the static subsystem code has k=0k=0; that inner logical operators commute with every check and never enter the ISG; that schedules missing a colour pair fail; and that the Stim circuit's detectors are deterministic without noise.

Quoted from the literature, with the papers cited: the identification of the ISG with a toric code on a superlattice, the electric–magnetic exchange of outer logical operators each period, all thresholds and qubit counts, and the properties of planar and CSS variants.

Common mistakes

  • Treating Floquet checks like stabilizers. Individual check outcomes after the first period are random; only products that commute with the preceding round, such as plaquettes, are detectors. Building a detector from a single check comparison across rounds gives a non-deterministic detector, which Stim reports.
  • Comparing the wrong rounds. A plaquette of colour cc is completed by the two rounds measuring c+1c+1 and c+2c+2. Off-by-one record arithmetic is the most common bug in Floquet circuits; let detector_error_model() catch it.
  • Counting kk from the static code. The subsystem code generated by all checks has no logical qubits. The protection lives in the ISG of the schedule.
  • Forgetting to update the logical observable. The outer logical operator must be multiplied by check outcomes as the schedule proceeds; a fixed Pauli string read out at the end is not a valid observable.
  • Quoting thresholds without their model. "The honeycomb threshold is about 1.5%" is meaningful only for native two-body measurements and the decoder and error model of the cited study.

Summary

  • A Floquet code is defined by a schedule of checks. Its protection lives in the instantaneous stabilizer group, which the stabilizer measurement rule updates round by round in binary symplectic form.
  • Products of anticommuting two-body checks measured in consecutive rounds can be inferred as weight-six stabilizers. Comparing successive inferences gives deterministic detectors.
  • The honeycomb code measures one colour of edges per round with period 3. On a torus its ISG encodes two logical qubits in the steady state, while the static subsystem code encodes none.
  • Inner logical operators are products of checks and are never disturbed. Outer logical operators must be updated every round.
  • Weight-two checks remove weight-two hook errors and suit native pair measurements. Published thresholds favour Floquet codes only in such models.

What next

The next lesson, Fault-tolerant quantum computing, asks how errors spread through syndrome-extraction and logic circuits, and how a universal gate set is built from fault-tolerant pieces.

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.

The honeycomb code's measurement schedule, verified in symplectic form and in Stim

advanced · about 2 h · needs numpy, stim, pytest

In this exercise you build the honeycomb code from scratch and check, by exact Pauli algebra, the claims the lesson makes about it. Nothing here is sampled from a random process except the final noisy Stim run, whose only job is to show that the detectors respond to noise.

What you implement (starter.py)

Pauli operators on n qubits are uint8 vectors of length 2n in the layout [x | z]; signs and phases are ignored.

Function Contract
honeycomb_lattice(L) The honeycomb lattice on an L x L torus (L a multiple of 3), built from the triangle construction in the docstring. Returns n, the edge list (u, v, pauli, colour) and the plaquettes (colour, [edge indices]).
pauli_vector(n, ops) Symplectic vector of a product such as [(0, "X"), (3, "Z")].
commutes(a, b) The symplectic inner product test.
gf2_rank(rows) Rank over F2\F_2 by Gaussian elimination.
in_span(generators, v) Whether v is a product of the generators.
measure(generators, P) The stabilizer update rule for measuring P; returns the new generators and "deterministic" or "random".
check_vectors(lattice) The two-body check PuPvP_uP_v of every edge.
plaquette_vectors(lattice) Each plaquette as the product of its six boundary checks.
run_schedule(lattice, schedule, rounds) Start from the empty group (the maximally mixed state); in round r measure all checks of colour schedule[r % len(schedule)]; return the instantaneous stabilizer group (ISG) after every round.
logical_qubit_count(n, generators) k=n−rank⁡k = n - \operatorname{rank}.
honeycomb_circuit(L, rounds, p=0.0) A Stim circuit: reset all qubits, then one MPP per round for the checks of colour r mod 3; from round 4 on, one DETECTOR per plaquette completed by rounds (r-1, r), comparing it with the same plaquette completed by rounds (r-4, r-3). With p > 0, add DEPOLARIZE1(p) before each round and a flip probability p on each MPP result.

What the checks verify

python -m pytest test_exercise.py (about 3 s) checks:

  1. Pauli algebra against Stim's PauliString.commutes on random operators, and small rank and span cases.
  2. The measurement rule against Stim's tableau simulator: for random two-body measurement sequences on four qubits, your classification of each outcome as deterministic or random must agree with peek_observable_expectation.
  3. The lattice satisfies the invariants of a properly 3-coloured honeycomb: every qubit has one edge of each Pauli type and one edge of each colour, and every plaquette's six boundary edges carry the two other colours, three each.
  4. Plaquettes have weight 6 and commute with every check.
  5. The static subsystem code generated by all checks has no logical qubits (computed from the rank of the gauge group and of its centre). This is the statement in the abstract of Hastings and Haah, recomputed.
  6. The period-3 schedule produces an ISG that encodes exactly two logical qubits on the torus from round index 3 onwards, for L = 3 and L = 6, and from then on contains every plaquette and the checks just measured.
  7. An inner logical operator (the product of checks around an X/Y cycle, found by walking the graph) commutes with every check and is never in the ISG, so no check measurement ever learns its value.
  8. A period-2 schedule (0, 1) never infers the colour-0 and colour-1 plaquettes and leaves more than two (unprotected) logical qubits.
  9. Your Stim circuit's detectors are deterministic without noise: Stim's detector_error_model() raises on any non-deterministic detector, and a noiseless sample has no detection events. With p = 0.01 detection events appear.

Debugging task (not graded, but do it)

Change your detector definition so that it compares the plaquette completed by rounds (r-1, r) with the value from rounds (r-3, r-2) instead of (r-4, r-3). Run circuit.detector_error_model() and read the error. Then explain, in two or three sentences in your notes, which plaquette colour rounds (r-3, r-2) actually complete and why the product you built is therefore not a stabilizer. Finally run run_schedule with (0, 1, 2, 1) for L = 6 and explain from the colour pairs that appear consecutively why the steady-state kk is larger than 2. The quiz asks for that number.

Conventions

Stim numbers qubits from 0 and MPP X0*X1 measures X0X1X_0X_1. Qubit ordering in the symplectic vectors follows the qubit indices; there is no big- or little-endian issue because nothing here builds a state vector.

Terminal
python -m pip install numpy stim pytest

starter.py

Python
"""Starter: the honeycomb code's measurement schedule in binary symplectic form.

Pauli operators on n qubits are uint8 vectors of length 2n, laid out as [x | z]:
X_q sets x[q], Z_q sets z[q], Y_q sets both. Phases and signs are ignored
throughout, because every question asked here (commutation, group membership,
rank) is independent of them.

Implement every function. Run the checks with `python -m pytest test_exercise.py`.
"""

from __future__ import annotations

import numpy as np
import stim

PAULIS = ("X", "Y", "Z")


def honeycomb_lattice(L: int) -> dict:
    """Honeycomb lattice on an L x L torus with 3-coloured plaquettes (L a multiple of 3).

    Plaquettes sit at the sites (i, j) of a triangular lattice, i, j in Z_L, and
    plaquette (i, j) has colour (i - j) mod 3. Every qubit (vertex) is a triangle of
    three mutually adjacent plaquettes:

    * up triangle   u(i, j) = {(i, j), (i+1, j), (i, j+1)}      -> qubit 2*(i*L + j)
    * down triangle d(i, j) = {(i+1, j), (i, j+1), (i+1, j+1)}  -> qubit 2*(i*L + j) + 1

    Two qubits share an edge when their triangles share a side. Each up triangle
    u(i, j) has three edges, appended in this order:

    * to d(i, j),     Pauli "X", colour (i - j) mod 3
    * to d(i, j-1),   Pauli "Y", colour (i - j - 1) mod 3
    * to d(i-1, j),   Pauli "Z", colour (i - j + 1) mod 3

    The colour of an edge is the colour of the two plaquettes at its ends that do
    not contain it. Returns {"L", "n", "edges": [(u, v, pauli, colour)],
    "plaquettes": [(colour, [edge indices])]} with plaquettes in (i, j) row-major order.
    """
    raise NotImplementedError


def pauli_vector(n: int, ops) -> np.ndarray:
    """Binary symplectic vector [x | z] of the Pauli product given as [(qubit, "X"|"Y"|"Z"), ...]."""
    raise NotImplementedError


def commutes(a: np.ndarray, b: np.ndarray) -> bool:
    """True when the Paulis a and b commute: the symplectic product x_a.z_b + z_a.x_b is 0 mod 2."""
    raise NotImplementedError


def gf2_rank(rows) -> int:
    """Rank over F_2 of a list (or 2-D array) of 0/1 vectors."""
    raise NotImplementedError


def in_span(generators, v: np.ndarray) -> bool:
    """True when v is a product of the generators (ignoring phase)."""
    raise NotImplementedError


def measure(generators, P: np.ndarray):
    """Update a stabilizer group when the Pauli P is measured.

    Returns (new_generators, kind). kind is "deterministic" when P (up to sign) is
    already in the group, otherwise "random". Rules:
    * P anticommutes with some generators: keep one of them, g, multiply every other
      anticommuting generator by g, then replace g by P.
    * P commutes with all generators and is not in the group: append P.
    * P is in the group: the group is unchanged.
    """
    raise NotImplementedError


def check_vectors(lattice: dict) -> list:
    """The two-body check P_u P_v of every edge, in edge order."""
    raise NotImplementedError


def plaquette_vectors(lattice: dict) -> list:
    """Each plaquette operator as the product of the six checks on its boundary."""
    raise NotImplementedError


def run_schedule(lattice: dict, schedule, rounds: int) -> list:
    """Start from the empty stabilizer group (maximally mixed state); in round r measure
    every check whose colour is schedule[r % len(schedule)]. Returns the list of
    instantaneous stabilizer groups (each a list of generator vectors) after each round."""
    raise NotImplementedError


def logical_qubit_count(n: int, generators) -> int:
    """k = n - rank of the stabilizer group."""
    raise NotImplementedError


def honeycomb_circuit(L: int, rounds: int, p: float = 0.0) -> stim.Circuit:
    """Stim circuit of the honeycomb code with the period-3 colour schedule 0, 1, 2.

    All qubits start in |0>. Round r measures every check of colour r mod 3 with one
    MPP instruction. When p > 0, DEPOLARIZE1(p) acts on every qubit before each round
    and each MPP result is flipped with probability p. From round 4 on, every
    plaquette completed by rounds (r-1, r) gets a DETECTOR comparing that value with
    the value completed by rounds (r-4, r-3). Each detector has coordinates
    (plaquette index, r).
    """
    raise NotImplementedError

test_exercise.py

Python
"""Checks for the honeycomb measurement-schedule exercise.

Independent references used here: Stim's own Pauli algebra (PauliString.commutes),
Stim's tableau simulator (which measurements are deterministic), Stim's detector
analysis (which detectors are deterministic), lattice invariants that any correct
honeycomb lattice satisfies, and the published facts that the honeycomb code's
instantaneous stabilizer group encodes two logical qubits on a torus while the
static subsystem code encodes none (Hastings and Haah, Quantum 5, 564 (2021)).
"""

import importlib.util
import os
from pathlib import Path

import numpy as np
import pytest
import stim


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()


def _to_stim(v):
    n = len(v) // 2
    return stim.PauliString.from_numpy(xs=v[:n].astype(bool), zs=v[n:].astype(bool))


def _xy_cycle_operator(lattice):
    """Product of the checks around the X/Y cycle through qubit 0.

    Every qubit has exactly one X edge and one Y edge, so X and Y edges form disjoint
    cycles; on the torus they are non-contractible zigzag loops. Found by walking the
    graph, independently of the lattice's numbering.
    """
    n = lattice["n"]
    edges = [(k, u, v) for k, (u, v, p, _) in enumerate(lattice["edges"]) if p in "XY"]
    checks = target.check_vectors(lattice)
    used, node, op = set(), 0, np.zeros(2 * n, dtype=np.uint8)
    while True:
        step = next(((k, u, v) for k, u, v in edges if k not in used and node in (u, v)), None)
        if step is None:
            return op
        k, u, v = step
        used.add(k)
        op ^= checks[k]
        node = v if node == u else u


def test_pauli_algebra_matches_stim():
    rng = np.random.default_rng(11)
    n = 5
    for _ in range(300):
        ops_a = [(q, "XYZ"[rng.integers(3)]) for q in rng.choice(n, size=rng.integers(1, n + 1), replace=False)]
        ops_b = [(q, "XYZ"[rng.integers(3)]) for q in rng.choice(n, size=rng.integers(1, n + 1), replace=False)]
        a, b = target.pauli_vector(n, ops_a), target.pauli_vector(n, ops_b)
        assert a.shape == (2 * n,)
        assert target.commutes(a, b) == _to_stim(a).commutes(_to_stim(b))
    assert target.gf2_rank([[1, 1, 0], [0, 1, 1], [1, 0, 1]]) == 2
    assert target.gf2_rank(np.eye(6, dtype=np.uint8)) == 6
    assert target.in_span([np.array([1, 1, 0, 0], np.uint8)], np.array([1, 1, 0, 0], np.uint8))
    assert not target.in_span([np.array([1, 1, 0, 0], np.uint8)], np.array([1, 0, 0, 0], np.uint8))


def test_measurement_update_matches_tableau_simulator():
    rng = np.random.default_rng(5)
    n = 4
    for trial in range(40):
        sim = stim.TableauSimulator()
        sim.set_num_qubits(n)
        gens = [target.pauli_vector(n, [(q, "Z")]) for q in range(n)]  # |0000>
        for _ in range(12):
            support = rng.choice(n, size=rng.integers(1, 3), replace=False)
            P = target.pauli_vector(n, [(q, "XYZ"[rng.integers(3)]) for q in support])
            expected = "random" if sim.peek_observable_expectation(_to_stim(P)) == 0 else "deterministic"
            gens, kind = target.measure(gens, P)
            assert kind == expected, f"trial {trial}: wrong classification"
            sim.measure_observable(_to_stim(P))
            assert target.gf2_rank(gens) == n  # a pure state stays pure
            assert all(target.commutes(g, h) for g in gens for h in gens)


@pytest.mark.parametrize("L", [3, 6])
def test_lattice_invariants(L):
    lat = target.honeycomb_lattice(L)
    n, edges = lat["n"], lat["edges"]
    assert n == 2 * L * L and len(edges) == 3 * L * L and len(lat["plaquettes"]) == L * L
    for q in range(n):
        mine = [e for e in edges if q in e[:2]]
        assert sorted(e[2] for e in mine) == ["X", "Y", "Z"], "one edge of each Pauli type per qubit"
        assert sorted(e[3] for e in mine) == [0, 1, 2], "one edge of each colour per qubit"
    for colour, boundary in lat["plaquettes"]:
        assert len(boundary) == 6
        assert sorted(edges[k][3] for k in boundary) == sorted([(colour + 1) % 3] * 3 + [(colour + 2) % 3] * 3)
    # Edge colour = colour of the plaquettes at its ends that do not contain it, so an
    # edge never lies on the boundary of a plaquette of its own colour.
    for colour, boundary in lat["plaquettes"]:
        assert all(edges[k][3] != colour for k in boundary)


@pytest.mark.parametrize("L", [3, 6])
def test_plaquettes_commute_with_every_check(L):
    lat = target.honeycomb_lattice(L)
    checks = target.check_vectors(lat)
    plaqs = target.plaquette_vectors(lat)
    for P in plaqs:
        assert int(P.sum()) > 0
        weight = int(np.count_nonzero(P[: lat["n"]] | P[lat["n"]:]))
        assert weight == 6
        assert all(target.commutes(P, c) for c in checks)


def test_static_subsystem_code_has_no_logical_qubits():
    """Hastings-Haah: viewed as a subsystem code, the honeycomb code has no logical qubits."""
    lat = target.honeycomb_lattice(3)
    n = lat["n"]
    checks = target.check_vectors(lat)
    rank_gauge = target.gf2_rank(checks)
    # Centre of the gauge group: products of checks commuting with every check.
    omega = np.array([[0 if target.commutes(a, b) else 1 for b in checks] for a in checks], dtype=np.uint8)
    # nullspace of omega over F2 via the rank of the augmented system
    sym = np.concatenate([omega, np.eye(len(checks), dtype=np.uint8)], axis=1)
    rows = sym.copy()
    r = 0
    for col in range(len(checks)):
        piv = np.flatnonzero(rows[r:, col])
        if piv.size == 0:
            continue
        p = r + piv[0]
        rows[[r, p]] = rows[[p, r]]
        for i in np.flatnonzero(rows[:, col]):
            if i != r:
                rows[i] ^= rows[r]
        r += 1
    centre = [(row[len(checks):].astype(np.int64) @ np.array(checks, dtype=np.int64)) % 2 for row in rows[r:]]
    rank_centre = target.gf2_rank(centre)
    gauge_qubits = (rank_gauge - rank_centre) // 2
    assert n - rank_centre - gauge_qubits == 0


@pytest.mark.parametrize("L", [3, 6])
def test_period_three_schedule_generates_two_logical_qubits(L):
    lat = target.honeycomb_lattice(L)
    n = lat["n"]
    history = target.run_schedule(lat, (0, 1, 2), 9)
    ks = [target.logical_qubit_count(n, g) for g in history]
    ranks = [n - k for k in ks]
    assert ranks == sorted(ranks), "the group can only grow from the maximally mixed start"
    assert ks[3:] == [2] * 6, f"steady state should encode 2 logical qubits on the torus, got {ks}"
    plaqs = target.plaquette_vectors(lat)
    checks = target.check_vectors(lat)
    for r in range(3, 9):
        gens = history[r]
        assert all(target.in_span(gens, P) for P in plaqs), f"round {r}: every plaquette is in the ISG"
        colour = r % 3
        assert all(target.in_span(gens, c) for (_, _, _, cc), c in zip(lat["edges"], checks) if cc == colour)


@pytest.mark.parametrize("L", [3, 6])
def test_inner_logical_operator_survives_every_round(L):
    lat = target.honeycomb_lattice(L)
    loop = _xy_cycle_operator(lat)
    checks = target.check_vectors(lat)
    assert all(target.commutes(loop, c) for c in checks), "a product of checks around a cycle commutes with every check"
    for r, gens in enumerate(target.run_schedule(lat, (0, 1, 2), 9)):
        if r < 3:
            continue
        assert all(target.commutes(loop, g) for g in gens)
        assert not target.in_span(gens, loop), "the inner logical operator is never fixed by the ISG"


def test_period_two_schedule_loses_the_toric_code():
    lat = target.honeycomb_lattice(6)
    n = lat["n"]
    history = target.run_schedule(lat, (0, 1), 8)
    k = target.logical_qubit_count(n, history[-1])
    assert k > 2
    plaqs = target.plaquette_vectors(lat)
    colours = [c for c, _ in lat["plaquettes"]]
    inferred = [sum(target.in_span(history[-1], P) for P, c in zip(plaqs, colours) if c == colour) for colour in range(3)]
    assert inferred[0] == 0 and inferred[1] == 0 and inferred[2] == colours.count(2)


@pytest.mark.parametrize("L", [3, 6])
def test_stim_detectors_are_deterministic(L):
    circuit = target.honeycomb_circuit(L, rounds=12)
    assert circuit.num_detectors == (12 - 4) * (L * L // 3)
    # Raises ValueError("non-deterministic detectors") if any detector is wrong.
    circuit.detector_error_model()
    samples = circuit.compile_detector_sampler(seed=1).sample(200)
    assert not samples.any()
    noisy = target.honeycomb_circuit(L, rounds=12, p=0.01)
    assert noisy.num_detectors == circuit.num_detectors
    rate = noisy.compile_detector_sampler(seed=2).sample(2000).mean()
    assert 0.01 < rate < 0.5

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. In the steady state of the honeycomb code, a colour-1 check is measured right after the colour-0 round. Why is its individual outcome uniformly random?

    1 pt
  2. Which operators are in the steady-state instantaneous stabilizer group right after a colour-1 round of the period-3 honeycomb schedule on a torus? Select all that apply.

    1 pt

    Select all that apply.

  3. In the honeycomb schedule, which pair of consecutive rounds completes (lets you infer) the value of a colour-2 plaquette?

    1 pt
  4. Viewed as a static subsystem code (gauge group generated by all checks), how many logical qubits does the honeycomb code on a torus have?

    1 pt
  5. Run run_schedule(honeycomb_lattice(6), (0, 1, 2, 1), 12) from the exercise and compute logical_qubit_count of the final instantaneous stabilizer group. Enter the steady-state number of logical qubits k.

    1 pt

    Computed by running exercise “honeycomb-measurement-schedule” on your computer.

  6. How many detectors does honeycomb_circuit(L=6, rounds=12) from the exercise contain? (Each round from index 4 to 11 adds one detector per plaquette of the colour it completes; the L = 6 torus has 36 plaquettes, 12 of each colour.)

    1 pt

    Computed by running exercise “honeycomb-measurement-schedule” on your computer.

  7. Gidney, Newman, Fowler and Broughton (2021) report a honeycomb-code threshold between 1.5% and 2.0% and a threshold of 0.2-0.3% in another setting. Which reading is correct?

    1 pt

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

References

  1. Matthew B. Hastings, Jeongwan Haah (2021). Dynamically Generated Logical Qubits. Quantum 5, 564. doi:10.22331/q-2021-10-19-564
  2. Alexei Kitaev (2006). Anyons in an exactly solved model and beyond. Annals of Physics 321, 2-111. doi:10.1016/j.aop.2005.10.005
  3. Craig Gidney et al. (2021). A Fault-Tolerant Honeycomb Memory. Quantum 5, 605. doi:10.22331/q-2021-12-20-605
  4. Craig Gidney, Michael Newman, Matt McEwen (2022). Benchmarking the Planar Honeycomb Code. Quantum 6, 813. doi:10.22331/q-2022-09-21-813
  5. Jeongwan Haah, Matthew B. Hastings (2022). Boundaries for the Honeycomb Code. Quantum 6, 693. doi:10.22331/q-2022-04-21-693
  6. Adam Paetznick et al. (2023). Performance of planar Floquet codes with Majorana-based qubits. PRX Quantum 4, 010310. doi:10.1103/PRXQuantum.4.010310
  7. Margarita Davydova, Nathanan Tantivasadakarn, Shankar Balasubramanian (2023). Floquet codes without parent subsystem codes. PRX Quantum 4, 020341. doi:10.1103/PRXQuantum.4.020341
  8. Markus S. Kesselring et al. (2024). Anyon condensation and the color code. PRX Quantum 5, 010342. doi:10.1103/PRXQuantum.5.010342
  9. Craig Gidney (2021). Stim: a fast stabilizer circuit simulator. Quantum 5, 497. doi:10.22331/q-2021-07-06-497