Skip to main content
KetQat

Appearance

Lesson 91 h 10 min

Quantum resource estimation

Counting logical qubits, T gates and run time, and translating them into physical resources.

After this lesson you can

  • Separate logical-level costs (logical qubits, T or Toffoli count, depth) from physical-level costs (code distance, physical qubits, wall-clock time)
  • Choose a surface-code distance from a target failure probability using the scaling ansatz p_L ≈ A (p/p_th)^((d+1)/2) with explicitly labelled constants
  • Estimate magic-state factory footprint and run time with a coarse, stated model
  • Build a small resource estimator and reproduce its numbers for a stated toy workload, including a sensitivity analysis
  • Calibrate the suppression factor Λ of the ansatz against a seeded surface-code simulation, stating the noise model and decoder
  • Quote published estimates such as Gidney–Ekerå (2019) together with their assumptions

Read first: The quantum Fourier transform, Quantum phase estimation, Classical versus quantum complexity, Noise, limitations and modern hardware

Why estimate resources

Asymptotic statements such as "polynomial in log⁡N\log N" decide whether an algorithm is interesting. They do not decide whether it is useful: for that you need to know how many qubits, how many hours and what hardware quality a concrete instance requires. A resource estimate answers that question for a stated machine model. Its value lies as much in the stated assumptions as in the final numbers, because the numbers move by orders of magnitude when the assumptions move.

This lesson builds a deliberately coarse estimator in two layers. The logical layer describes the algorithm as a fault-tolerant circuit. The physical layer turns logical operations into surface-code patches, rounds of error correction and magic-state factories. Every constant in the physical layer is an assumption, and the lesson labels each one.

The logical layer

On a surface-code computer the natural gate set is Clifford + T. Clifford operations (Paulis, HH, SS, CNOT) can be implemented fault-tolerantly by lattice surgery at a cost that scales with the code distance, but they do not need special resources. The TT gate does: it is implemented by consuming a magic state that has been prepared and purified separately. That makes the T-count, or equivalently the Toffoli count with dedicated factories, the headline cost of most fault-tolerant algorithms.

The gadget below shows how one magic state ∣A⟩=T∣+⟩=(∣0⟩+eiπ/4∣1⟩)/2\ket{A} = T\ket{+} = (\ket0 + e^{i\pi/4}\ket1)/\sqrt2 becomes a TT gate on a data qubit qq. After a CNOT from qq to the magic qubit mm, the state is α∣0⟩(∣0⟩+eiπ/4∣1⟩)+β∣1⟩(∣1⟩+eiπ/4∣0⟩)\alpha\ket0(\ket0 + e^{i\pi/4}\ket1) + \beta\ket1(\ket1 + e^{i\pi/4}\ket0) (unnormalised) for ∣q⟩=α∣0⟩+β∣1⟩\ket q = \alpha\ket0 + \beta\ket1. Measuring mm and finding 0 leaves α∣0⟩+eiπ/4β∣1⟩=T∣q⟩\alpha\ket0 + e^{i\pi/4}\beta\ket1 = T\ket q; finding 1 leaves T†∣q⟩T^\dagger\ket q up to a global phase, which the Clifford correction SS turns into T∣q⟩T\ket q. Only Clifford operations and a measurement act on the data, so the whole cost of the non-Clifford gate sits in preparing a clean ∣A⟩\ket A.

Quantum circuit on 2 wires (q, m). step 1: H on m. step 2: T on m. step 3: CNOT, control q, target m. step 4: measure m. step 5: S if m = 1 on q.qmHTS if m = 1
T-gate teleportation: the magic qubit m is prepared in T|+⟩ (H then T, done fault-tolerantly by a factory), a CNOT from the data qubit q to m and a Z measurement of m apply T to q, with an S correction when the outcome is 1.

The numbers that characterise an algorithm at this level are:

  • logical qubits nLn_L, including ancillas and workspace;
  • T-count (or Toffoli count): one standard decomposition uses 7 TT gates per Toffoli (Nielsen and Chuang), and arbitrary-angle rotations, such as the controlled phases of the QFT, must each be approximated by a sequence of many TT and Clifford gates whose length grows as the required precision tightens;
  • T-depth or reaction depth, which bounds how far the computation can be parallelised.

These are properties of the circuit, independent of hardware, and they are where algorithmic improvements show up: the approximate QFT from earlier in this course is a resource optimisation at the logical layer.

The physical layer

Surface-code patches

A logical qubit is a patch of rotated surface code of distance dd: d2d^2 data qubits and d2−1d^2 - 1 measurement qubits, so 2d2−12d^2 - 1 physical qubits (Fowler et al. 2012). Each round (or cycle) measures all stabilisers once and takes time τ\tau; a logical operation such as a lattice-surgery merge takes about dd rounds. Algorithms also need routing space between data patches. Lattice-surgery layouts trade space for speed, and published layouts use between roughly one and a half and a little over two patch-sized tiles per logical qubit (Litinski 2019, A Game of Surface Codes). The estimator uses a routing factor of 2 (an assumption).

How logical errors scale with distance

Below threshold, logical errors are suppressed exponentially in the distance. A common empirical ansatz, of the form used by Fowler and coauthors, is

pL(d)≈A(ppth)(d+1)/2p_L(d) \approx A\left(\frac{p}{p_{\text{th}}}\right)^{(d+1)/2}

per patch per round, where pp is the physical error rate, pthp_{\text{th}} a threshold and AA a prefactor. Increasing dd by 2 multiplies pLp_L by p/pthp/p_{\text{th}}, so the suppression factor is Λ=pth/p\Lambda = p_{\text{th}}/p. The ansatz is a fit, not a theorem: AA and pthp_{\text{th}} depend on the noise model, the decoder and the syndrome-extraction circuit, and it is accurate only well below threshold. This lesson's estimator uses p=10−3p = 10^{-3}, pth=10−2p_{\text{th}} = 10^{-2} and A=0.1A = 0.1, so Λ=10\Lambda = 10: all three are illustrative assumptions, and the calibration section below shows how a simulation pins down Λ\Lambda for one concrete noise model.

Choosing the distance

If NpatchN_{\text{patch}} patches must survive RR rounds and failures are rare and roughly independent, the union bound gives a failure probability of at most Npatch R pL(d)N_{\text{patch}}\,R\,p_L(d). Choose the smallest odd dd for which this is below the error budget δ\delta:

Npatch  R(d)  A(ppth)(d+1)/2≤δ.N_{\text{patch}}\;R(d)\;A\left(\frac{p}{p_{\text{th}}}\right)^{(d+1)/2} \le \delta .

RR itself depends on dd, because each logical step takes dd rounds, so the condition is solved by trying d=3,5,7,…d = 3, 5, 7, \dots in turn. Because pLp_L falls exponentially while RR grows only linearly in dd, the required distance grows only logarithmically with the size of the computation.

Magic-state factories

A distillation factory consumes many noisy magic states and outputs fewer, much cleaner ones; it occupies a block of tiles for the duration of each distillation round. Litinski showed that careful factory design makes this overhead considerably smaller than earlier estimates suggested (Litinski 2019, Magic State Distillation). At a coarse level a factory is described by two numbers: its footprint, in tiles, and the time it needs per output state. The estimator assumes a factory of 25 tiles that outputs one T state every 6d6d rounds (both assumptions for illustration), and that the computation consumes one T state per logical step of dd rounds. Keeping up then requires ⌈6d/d⌉=6\lceil 6d/d\rceil = 6 factories running in parallel. The factories' own output error is assumed to meet its target, so only data patches count against the error budget.

Run time

With T gates consumed one per step, the run takes R=Tcount⋅dR = T_{\text{count}}\cdot d rounds and RτR\tau seconds. The cycle time τ=1 μs\tau = 1\,\mu\mathrm{s} is another assumption. Real schedules may be faster (several T gates per step, with more factories) or slower (waiting for the classical decoder to react before a measurement-dependent correction).

Worked example: a toy workload

Take an algorithm with nL=100n_L = 100 logical qubits and 10810^8 T gates, and the assumptions collected in the table.

assumption value
physical error rate pp 10−310^{-3}
ansatz threshold pthp_{\text{th}} and prefactor AA 10−210^{-2} and 0.10.1
round (cycle) time τ\tau 1 μs1\,\mu\mathrm{s}
routing factor (tiles per logical qubit) 2
factory footprint and period 25 tiles, one T state per 6d6d rounds
error budget for the data patches 10−210^{-2}

The data region has Npatch=200N_{\text{patch}} = 200 tiles. For d=23d = 23, R=2.3×109R = 2.3\times10^9 rounds and pL=0.1×(0.1)12=10−13p_L = 0.1\times(0.1)^{12} = 10^{-13}, so the failure bound is 200×2.3×109×10−13=0.046200\times2.3\times10^9\times10^{-13} = 0.046, above budget. For d=25d = 25, R=2.5×109R = 2.5\times10^9 and pL=10−14p_L = 10^{-14}, giving 0.0050.005, within budget. So d=25d = 25. Each tile holds 2⋅252−1=1,2492\cdot25^2 - 1 = 1{,}249 physical qubits, there are 200+6×25=350200 + 6\times25 = 350 tiles, and

Nphys=350×1249=437,150,Trun=108×25×1 μs=2,500 s≈42 min.N_{\text{phys}} = 350 \times 1249 = 437{,}150, \qquad T_{\text{run}} = 10^8 \times 25 \times 1\,\mu\mathrm{s} = 2{,}500\,\mathrm s \approx 42\text{ min}.

The same search in a few lines of Python:

p, p_th, A, budget = 1e-3, 1e-2, 0.1, 1e-2     # assumptions, see the table
data_tiles, factory_tiles, t_count, tau = 200, 6 * 25, 1e8, 1e-6
d = 3
while data_tiles * t_count * d * A * (p / p_th) ** ((d + 1) / 2) > budget:
    d += 2
print(d, (data_tiles + factory_tiles) * (2 * d * d - 1), t_count * d * tau)

It prints 25 437150 2500.0, and the estimator in the exercise reproduces the same numbers. Its sensitivity to the assumptions is the real lesson:

change distance physical qubits run time
baseline 25 437,150 2,500 s
p=2×10−3p = 2\times10^{-3} (Λ=5\Lambda = 5) 37 957,950 3,700 s
p=5×10−4p = 5\times10^{-4} (Λ=20\Lambda = 20) 19 252,350 1,900 s
nL=1000n_L = 1000, 101010^{10} T gates 31 4,130,150 310,000 s (3.6 days)

Doubling the physical error rate roughly doubles the qubit count, because the distance needed at Λ=5\Lambda = 5 is much larger than at Λ=10\Lambda = 10. Physical error rates, not logical qubit counts, dominate the footprint at this scale; and 150 of the baseline machine's 350 tiles, about 43%, are magic-state factories.

Calibrating the ansatz with a simulation

Where do AA and pthp_{\text{th}} come from? From simulations or experiments of the actual code, noise model and decoder. The KetQat SDK's surface-code-memory product runs a rotated surface-code memory experiment with Stim and decodes it with PyMatching (KetQat SDK). Its noise model is circuit-level depolarizing noise of strength pp after every Clifford gate, with no measurement, reset or idle errors; the decoder is minimum-weight perfect matching with the matching noise model; the reported rate is per experiment of the stated number of rounds.

A memory experiment of rr rounds fails with probability PP. If each round independently flips the logical qubit with probability ε\varepsilon, then P=12[1−(1−2ε)r]P = \tfrac12[1 - (1-2\varepsilon)^r], which inverts to the per-round rate ε=12[1−(1−2P)1/r]\varepsilon = \tfrac12[1 - (1-2P)^{1/r}]. With p=0.005p = 0.005, d=3,5,7d = 3, 5, 7, r=dr = d rounds, memory in the Z basis, 50,000 shots per distance and seed 11 (Stim 1.16.0, PyMatching 2.4.0), the exercise's reference solution measures:

distance dd per-round logical error rate
3 1.81×10−31.81\times10^{-3}
5 7.90×10−47.90\times10^{-4}
7 2.92×10−42.92\times10^{-4}

A least-squares fit of ln⁡pL\ln p_L against (d+1)/2(d+1)/2 gives Λ≈2.49\Lambda \approx 2.49 and A≈0.0115A \approx 0.0115. With the illustrative pth=10−2p_{\text{th}} = 10^{-2}, the ansatz would predict Λ=0.01/0.005=2\Lambda = 0.01/0.005 = 2. So for this noise model the effective pthp_{\text{th}} near p=0.005p = 0.005 is about Λp≈1.2×10−2\Lambda p \approx 1.2\times10^{-2}. These are numerical results for one noise model at one physical error rate, with statistical uncertainty from the finite number of failures (the d=7d = 7 point rests on about 100 failures). They are not a threshold estimate, which requires sweeping pp and locating where curves for different distances cross, and they are not a hardware prediction: real devices add measurement errors, leakage and correlated noise, all of which lower the effective threshold.

Published estimates, with their assumptions

The most cited estimate in this area is for factoring a 2048-bit RSA modulus. Gidney and Ekerå estimated that it could be done in about 8 hours using 20 million noisy qubits, assuming a planar grid of qubits with nearest-neighbour connectivity, a physical gate error rate of 10−310^{-3}, a surface-code cycle time of 1 μ\mus and a classical reaction time of 10 μ\mus (Gidney and Ekerå 2021, arXiv preprint 2019). In a 2025 preprint, Gidney estimated that under the same assumptions the same task could be done in less than a week with fewer than one million noisy qubits, trading a longer run time for far fewer qubits through approximate residue arithmetic, more compact storage of idle logical qubits, and cheaper magic-state preparation (Gidney 2025).

Read these the way this lesson reads its own toy estimate. They are estimates for a hypothetical machine whose stated properties no existing device has at that scale, not demonstrations; they assume a specific error rate, cycle time and connectivity; and the more than twentyfold change in qubit count between them came from algorithmic and architectural ideas, not from new hardware. Babbush and coauthors used the same kind of reasoning to argue that the slow logical clock of surface-code machines makes quadratic speed-ups hard to exploit (Babbush et al. 2021), the argument behind the crossover exercise in the complexity lesson.

What the toy model leaves out

The estimator ignores, among other things: the detailed layout and routing schedule; Clifford costs; the error budget of the factories; the synthesis cost of arbitrary rotations; decoder reaction time and its effect on the schedule; storage tricks for idle qubits; and noise beyond the simulated model (leakage, correlated errors, drift). Each of these can change the answer by a large factor. Use the toy model to understand which assumptions matter, and a dedicated estimation tool or a published analysis for any number that will inform a decision.

Exercise: a small resource estimator

In surface-code-resource-estimator you implement the scaling ansatz, the patch size, the distance search, the full estimate, the per-round conversion of memory-experiment failure rates, the fit of Λ\Lambda, and a calibration run against the SDK's [email protected] product. The checks verify the factor Λ=pth/p\Lambda = p_{\text{th}}/p per distance step, the patch size, the toy workload (with the chosen distance checked independently: it meets the budget and d−2d-2 does not), the direction of every sensitivity, the round-trip of the per-round formula, recovery of known constants from synthetic data, and that the simulated logical error rates decrease with distance with a plausible Λ\Lambda.

Common mistakes

  • Quoting a number without its assumptions. "20 million qubits" means nothing without the error rate, cycle time, connectivity and reaction time.
  • Using the ansatz near or above threshold. It is a below-threshold fit; at p≥pthp \ge p_{\text{th}} larger codes do not help.
  • Mixing per-round and per-experiment rates. A memory experiment of dd rounds fails about dd times more often than a single round.
  • Forgetting the factories. In the toy example they are about 43% of the machine.
  • Treating a local fit as a threshold. Λ\Lambda at one pp is not pthp_{\text{th}}.
  • Ignoring that the distance depends on the run length. Longer computations need larger codes.

Summary

A resource estimate has a logical layer (logical qubits, T count, depth) and a physical layer (code distance, patches, factories, rounds). With the ansatz pL≈A(p/pth)(d+1)/2p_L \approx A(p/p_{\text{th}})^{(d+1)/2} and a union bound, the distance is the smallest odd dd for which NpatchR pL(d)N_{\text{patch}}R\,p_L(d) fits the error budget; physical qubits follow from 2d2−12d^2 - 1 per tile, and run time from rounds times cycle time. For a toy workload of 100 logical qubits and 10810^8 T gates under stated assumptions, this gives d=25d = 25, about 437,000 physical qubits and 42 minutes, and the sensitivity table shows the physical error rate dominating. Simulation calibrates the ansatz for a specific noise model: for circuit-level depolarizing noise at p=0.005p = 0.005 with matching decoding, Λ≈2.5\Lambda \approx 2.5. Published estimates such as Gidney–Ekerå's must always be quoted with their assumptions. This completes the course: from Grover's rotation to the cost of running algorithms like it at scale, the recurring lesson is to state what is proven, what is assumed and what was measured.

Exercises

Run these on your own computer. Each comes with automated checks: python -m pytest test_exercise.py. Nothing you write is sent to KetQat.

A surface-code resource estimator, calibrated against simulation

advanced · about 1 h 15 min · needs numpy, pytest, stim, PyMatching, ketqat[qec]

Build a coarse fault-tolerant resource estimator, reproduce the toy workload from the lesson, explore its sensitivity, and then calibrate its central assumption, the suppression factor Λ\Lambda, against a seeded surface-code simulation from the KetQat SDK.

Every constant in DEFAULT_ASSUMPTIONS is an assumption for illustration, not a property of a real device. Keep that label on any number you report from this exercise.

Functions to implement in starter.py

Function Contract
logical_error_per_round(p, d, A, p_th) A(p/pth)(d+1)/2A(p/p_{\text{th}})^{(d+1)/2}
physical_qubits_per_patch(d) 2d2−12d^2 - 1 (rotated surface code)
estimate(n_logical, t_count, assumptions=None, d_max=101) the model in the docstring: data tiles ⌈routing⋅nL⌉\lceil\text{routing}\cdot n_L\rceil, ⌈factory_period_d⌉\lceil\text{factory\_period\_d}\rceil factories, rounds =T⋅d= T\cdot d, smallest odd d≥3d \ge 3 with tiles × rounds × pL(d)≤p_L(d) \le budget; return the dict of results. Raise ValueError if p≥pthp \ge p_{\text{th}}.
per_round_error(p_experiment, rounds) invert P=12[1−(1−2ε)r]P = \tfrac12[1 - (1-2\varepsilon)^r]
fit_suppression(distances, per_round_rates) least-squares fit of ln⁡pL=ln⁡C−d+12ln⁡Λ\ln p_L = \ln C - \tfrac{d+1}{2}\ln\Lambda; return (Λ,C)(\Lambda, C)
measure_suppression(p, distances, shots, seed) run [email protected] (rounds =d= d, Z basis) at each distance, convert to per-round rates, fit; return (rates, Lambda, C)

What the checks verify

  • The ansatz drops by exactly pth/pp_{\text{th}}/p per distance step of 2.
  • Patch sizes for d=3d = 3 (17) and d=25d = 25 (1,249).
  • The toy workload (100 logical qubits, 10810^8 T gates, default assumptions) gives d=25d = 25, 6 factories, 350 tiles, 350×1249350 \times 1249 physical qubits and 2,500 s; the distance is checked independently (it meets the budget and d−2d - 2 does not).
  • Lower pp lowers dd, higher pp raises it, longer and larger workloads cost more, and p≥pthp \ge p_{\text{th}} is refused.
  • per_round_error inverts the repetition formula, and fit_suppression recovers known constants from synthetic data.
  • At p=0.005p = 0.005 the SDK simulation (circuit-level depolarizing noise after every Clifford, MWPM decoding) gives per-round rates that fall with distance and a fitted Λ\Lambda between 1.5 and 4. Skipped if the SDK, Stim or PyMatching is not installed.

Run the checks

python -m pytest test_exercise.py

The calibration test takes about a second; its run records go to a temporary directory.

Going further

Repeat the calibration at p=0.003p = 0.003 and p=0.007p = 0.007. Plot Λ\Lambda against 1/p1/p: if the ansatz held exactly, what would the plot look like? Then feed your fitted AA and Λ\Lambda back into estimate (set p_th = Lambda * p) and compare the toy workload's footprint with the illustrative defaults.

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

starter.py

Python
"""Starter: a coarse surface-code resource estimator and its calibration.

EVERY constant in DEFAULT_ASSUMPTIONS is an assumption chosen for illustration, not a
property of any real device. The estimator is a teaching model: it is meant to show
how the answer moves when an assumption moves, not to predict a specific machine.
"""

import math

import numpy as np

DEFAULT_ASSUMPTIONS = {
    "p": 1e-3,                 # physical error rate per operation (assumed)
    "p_th": 1e-2,              # threshold in the scaling ansatz (assumed)
    "A": 0.1,                  # prefactor in the scaling ansatz (assumed)
    "cycle_time_s": 1e-6,      # one syndrome-extraction round (assumed)
    "routing_factor": 2.0,     # patches per logical qubit, including routing space (assumed)
    "factory_tiles": 25,       # patch-sized tiles occupied by one magic-state factory (assumed)
    "factory_period_d": 6.0,   # one factory emits one T state every factory_period_d * d rounds (assumed)
    "error_budget": 1e-2,      # allowed probability that any data patch fails during the run
}


def logical_error_per_round(p, d, A, p_th):
    """Scaling ansatz p_L(d) = A (p / p_th)^((d + 1) / 2), per patch per round."""
    raise NotImplementedError


def physical_qubits_per_patch(d):
    """Rotated surface code: d^2 data qubits plus d^2 - 1 measurement qubits."""
    raise NotImplementedError


def estimate(n_logical, t_count, assumptions=None, d_max=101):
    """Resource estimate for a workload of `n_logical` logical qubits and `t_count` T gates.

    Model: T gates are consumed one at a time, one per logical time step of d rounds, so the
    run takes t_count * d rounds. Enough factories run in parallel to supply one T state per
    step: ceil(factory_period_d). Only the data/routing patches are counted against the error
    budget (factories are assumed to meet their own output-error target). The code distance is
    the smallest odd d >= 3 with  data_tiles * rounds * p_L(d) <= error_budget.

    Returns a dict with keys distance, data_tiles, factories, total_tiles, physical_qubits,
    rounds, runtime_s, failure_probability.
    """
    raise NotImplementedError


def per_round_error(p_experiment, rounds):
    """Per-round logical flip probability e from a memory experiment's failure probability P over
    `rounds` rounds, assuming independent flips each round: P = (1 - (1 - 2e)^rounds) / 2."""
    raise NotImplementedError


def fit_suppression(distances, per_round_rates):
    """Least-squares fit of ln p_L = ln C - ((d + 1) / 2) ln Lambda.

    Returns (Lambda, C). Lambda is the factor by which p_L falls when d grows by 2.
    """
    raise NotImplementedError


def measure_suppression(p, distances, shots, seed):
    """Run the KetQat SDK's surface-code-memory product (rotated code, d rounds, Z basis,
    circuit-level depolarizing noise after every Clifford, MWPM) at each distance and return
    (per-round rates, fitted Lambda, fitted C)."""
    raise NotImplementedError

test_exercise.py

Python
import importlib.util
import os
from pathlib import Path

def _load_target():
    name = os.environ.get("KETQAT_COMMONS_TARGET", "starter")
    path = Path(__file__).with_name(f"{name}.py")
    spec = importlib.util.spec_from_file_location(f"{Path(__file__).parent.name}_{name}", path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

target = _load_target()

import math

import pytest

A = target.DEFAULT_ASSUMPTIONS


def test_ansatz_suppression_factor_per_distance_step():
    for d in (3, 7, 15):
        ratio = target.logical_error_per_round(1e-3, d, 0.1, 1e-2) / target.logical_error_per_round(1e-3, d + 2, 0.1, 1e-2)
        assert ratio == pytest.approx(10.0)
    assert target.logical_error_per_round(1e-3, 3, 0.1, 1e-2) == pytest.approx(1e-3)


def test_patch_size():
    assert target.physical_qubits_per_patch(3) == 17
    assert target.physical_qubits_per_patch(25) == 1249


def test_toy_workload_by_hand():
    # 100 logical qubits, 10^8 T gates, default assumptions.
    est = target.estimate(100, 1e8)
    data_tiles = 200
    # Independent check of the distance: d meets the budget, d - 2 does not.
    def failure(d):
        return data_tiles * 1e8 * d * 0.1 * 0.1 ** ((d + 1) / 2)
    d = est["distance"]
    assert d % 2 == 1
    assert failure(d) <= 1e-2 < failure(d - 2)
    assert d == 25
    assert est["factories"] == 6
    assert est["total_tiles"] == 200 + 6 * 25
    assert est["physical_qubits"] == 350 * (2 * 25**2 - 1)
    assert est["runtime_s"] == pytest.approx(1e8 * 25 * 1e-6)


def test_estimates_move_the_right_way():
    base = target.estimate(100, 1e8)
    assert target.estimate(100, 1e8, {"p": 5e-4})["distance"] < base["distance"]
    assert target.estimate(100, 1e8, {"p": 2e-3})["distance"] > base["distance"]
    assert target.estimate(100, 1e10)["distance"] >= base["distance"]
    assert target.estimate(1000, 1e8)["physical_qubits"] > base["physical_qubits"]
    with pytest.raises(ValueError):
        target.estimate(100, 1e8, {"p": 2e-2})


def test_per_round_error_inverts_the_repetition_formula():
    for e, r in [(1e-3, 5), (2e-4, 25), (0.01, 3)]:
        P = (1 - (1 - 2 * e) ** r) / 2
        assert target.per_round_error(P, r) == pytest.approx(e, rel=1e-10)


def test_fit_recovers_known_constants():
    lam, c = 3.0, 0.05
    ds = [3, 5, 7, 9]
    rates = [c * lam ** (-(d + 1) / 2) for d in ds]
    fit_lam, fit_c = target.fit_suppression(ds, rates)
    assert fit_lam == pytest.approx(lam)
    assert fit_c == pytest.approx(c)


@pytest.fixture
def ketqat_home(tmp_path, monkeypatch):
    monkeypatch.setenv("KETQAT_HOME", str(tmp_path / "ketqat-home"))


def test_calibration_against_the_sdk_surface_code(ketqat_home):
    pytest.importorskip("ketqat_runner.catalog")
    pytest.importorskip("stim")
    pytest.importorskip("pymatching")
    rates, lam, c = target.measure_suppression(0.005, [3, 5, 7], 50000, 11)
    assert rates[0] > rates[1] > rates[2] > 0, "below threshold, larger codes must fail less often"
    # Below threshold Lambda > 1; the ansatz with p_th = 0.01 would predict exactly 0.01 / 0.005 = 2.
    assert 1.5 < lam < 4.0

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. Run estimate(100, 1e8) from your surface-code-resource-estimator solution with the default (illustrative) assumptions. How many physical qubits does it report?

    1 pt

    Computed by running exercise “surface-code-resource-estimator” on your computer.

  2. Same workload, but with {"p": 2e-3} instead of 10−310^{-3} (so Λ=5\Lambda = 5). What code distance does the estimator choose?

    1 pt

    Computed by running exercise “surface-code-resource-estimator” on your computer.

  3. Run measure_suppression(0.005, [3, 5, 7], 50000, 11) (SDK [email protected], Stim 1.16.0, PyMatching 2.4.0) and enter the fitted Λ\Lambda.

    2 pts

    Computed by running exercise “surface-code-resource-estimator” on your computer.

  4. A d=9d = 9 memory experiment over 9 rounds fails with probability P=9×10−4P = 9\times10^{-4}. What is the approximate per-round logical error rate?

    1 pt
  5. Which is a correct way to quote Gidney and Ekerå's RSA-2048 estimate?

    1 pt
  6. How many physical qubits does one rotated surface-code patch of distance d=17d = 17 use (data plus measurement qubits)?

    1 pt
  7. Which statements about the scaling ansatz pL≈A(p/pth)(d+1)/2p_L \approx A(p/p_{\text{th}})^{(d+1)/2} are correct? Select all that apply.

    1 pt

    Select all that apply.

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

References

  1. 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
  2. Daniel Litinski (2019). A Game of Surface Codes: Large-Scale Quantum Computing with Lattice Surgery. Quantum 3, 128. doi:10.22331/q-2019-03-05-128
  3. Daniel Litinski (2019). Magic State Distillation: Not as Costly as You Think. Quantum 3, 205. doi:10.22331/q-2019-12-02-205
  4. Craig Gidney, Martin Ekerå (2021). How to factor 2048 bit RSA integers in 8 hours using 20 million noisy qubits. Quantum 5, 433 (arXiv preprint 2019). doi:10.22331/q-2021-04-15-433
  5. Craig Gidney (2025). How to factor 2048 bit RSA integers with less than a million noisy qubits. arXiv:2505.15917
  6. Ryan Babbush et al. (2021). Focus beyond quadratic speedups for error-corrected quantum advantage. PRX Quantum 2, 010103. doi:10.1103/PRXQuantum.2.010103
  7. Michael A. Nielsen, Isaac L. Chuang (2010). Quantum Computation and Quantum Information (10th Anniversary Edition). Cambridge University Press. doi:10.1017/CBO9780511976667
  8. KetQat contributors (2026). KetQat SDK (open source, Apache-2.0), catalog products used at main 2cedabb.