About this notebook
Companion to Lecture 6: Measuring performance: LEP, Λ, thresholds and error budgets. 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 6 turned failure counts into performance numbers. Here you produce those numbers yourself, from seeded simulations of the rotated surface code under SI1000 noise, decoded by PyMatching. You will:
- put error bars on a failure count, including the case of zero failures;
- sweep the noise strength for
and locate where the curves cross; - fit the logical error per round from four round counts;
- extract
, and see why the one-round-count shortcut overestimates it; - turn
into QuOps and a qubit count.
The pipeline is the one from Notebook 0, wrapped in one helper:
RotatedPlanarCode(d) ─► css_code_memory_circuit(rounds) ─► QPU(SI1000Noise(p)) ─► noisy
noisy ─► PyMatchingDecoder.construct_decoder_and_stim_circuit ─► (decoder, circuit to sample)
StimDecoderManager(circuit, decoder, seed=SEED).run_batch_shots(n) ─► (shots, fails)import warnings
import deltakit
import matplotlib.pyplot as plt
import numpy as np
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 import analysis as an
from deltakit.explorer.codes import RotatedPlanarCode, css_code_memory_circuit
from deltakit.explorer.qpu import QPU, SI1000Noise
set_matplotlib_formats("svg")
SEED = 2026
print("deltakit", deltakit.__version__)deltakit 0.10.2
def fails_at(d, p, rounds, shots):
"""Seeded Z-memory: number of logical failures in `shots` shots."""
code = RotatedPlanarCode(width=d, height=d)
circ = css_code_memory_circuit(code, num_rounds=rounds, logical_basis=PauliBasis.Z)
qpu = QPU(qubits=code.qubits, noise_model=SI1000Noise(p=p))
noisy = qpu.compile_and_add_noise_to_circuit(circ)
dec, dcirc = PyMatchingDecoder.construct_decoder_and_stim_circuit(noisy)
manager = StimDecoderManager(dcirc, dec, seed=SEED, batch_size=100_000)
return int(manager.run_batch_shots(shots)[1])1. Error bars from a count
With
n = 100_000
print(f"{'fails':>5} {'LEP ± sigma':<20}{'R = e^2 interval':<24}{'R = 1000 interval'}")
for f in (344, 3, 0):
try:
lep, std = an.calculate_lep_and_lep_stddev(fails=f, shots=n)
sym = f"{lep:.2e} ± {std:.1e}"
except ValueError:
sym = "ValueError"
lo2, _, hi2 = an.calculate_lep_asymmetric([f], [n], max_likelihood_factor=np.exp(2))
lo3, _, hi3 = an.calculate_lep_asymmetric([f], [n])
e2 = f"[{lo2[0]:.1e}, {hi2[0]:.1e}]"
e3 = f"[{lo3[0]:.1e}, {hi3[0]:.1e}]"
print(f"{f:>5} {sym:<20}{e2:<24}{e3}")
print(f"zero fails: ln(R)/n = {2 / n:.1e} for R = e^2, "
f"{np.log(1000) / n:.1e} for R = 1000")fails LEP ± sigma R = e^2 interval R = 1000 interval
344 3.44e-03 ± 1.9e-04 [3.1e-03, 3.8e-03] [2.8e-03, 4.2e-03]
3 3.00e-05 ± 1.7e-05 [7.2e-06, 7.9e-05] [1.1e-06, 1.5e-04]
0 ValueError [0.0e+00, 2.0e-05] [0.0e+00, 6.9e-05]
zero fails: ln(R)/n = 2.0e-05 for R = e^2, 6.9e-05 for R = 1000
The symmetric bar refuses zero failures. The likelihood interval still bounds
Pass plain integers
In Deltakit 0.10.2,
calculate_lep_asymmetricaccepts Python integers and lists, but a NumPy integer scalar such asnp.int64(3)raisesTypeError: len() of unsized object.
pp = np.geomspace(1e-7, 3e-4, 400)
fig, ax = plt.subplots()
for f in (3, 0):
loglik = (n - f) * np.log1p(-pp) + (f * np.log(pp) if f else 0)
best = (n - f) * np.log1p(-f / n) + (f * np.log(f / n) if f else 0)
ax.plot(pp, np.exp(loglik - best), label=f"{f} fails in {n:,} shots")
ax.axhline(np.exp(-2), color="0.35", ls="--", lw=1)
ax.axhline(1e-3, color="0.35", ls=":", lw=1)
ax.text(2.8e-4, np.exp(-2) * 1.25, "1/e² cut", ha="right", fontsize=9)
ax.text(1.2e-7, 1.25e-3, "1/1000 cut (default)", ha="left", fontsize=9)
ax.set_xscale("log")
ax.set_yscale("log")
ax.set_xlim(1e-7, 3e-4)
ax.set_ylim(1e-4, 2)
ax.set_xlabel("logical error probability p")
ax.set_ylabel("likelihood / maximum likelihood")
ax.legend(loc="center left", bbox_to_anchor=(0.0, 0.45))
plt.show()Relative likelihood (p/p̂)^f ((1 − p)/(1 − p̂))^(n − f) of the logical error probability for 3 and 0 failures in 100,000 shots, on log axes. A likelihood interval keeps the p above the cut: 1/e² (dashed) is the two-sigma analogue, 1/1000 (dotted) Deltakit's default. For zero failures the curve is (1 − p)^n and the interval runs from 0 to ln(R)/n.
2. A threshold sweep
Nine noise strengths, three distances, rounds
PS = [1.5e-3, 2e-3, 2.5e-3, 3e-3, 3.5e-3, 4e-3, 4.5e-3, 5e-3, 6e-3]
DS = [3, 5, 7]
SHOTS = 200_000
sweep = {(d, p): fails_at(d, p, d, SHOTS) for p in PS for d in DS}
print("Threshold sweep: SI1000 noise, Z memory, rounds = d, PyMatching, seed 2026")
print(f"logical failures out of {SHOTS:,} shots per point")
print(f"{'p':>8} | {'d = 3':>7} | {'d = 5':>7} | {'d = 7':>7} | {'shots':>7}")
for p in PS:
print(f"{p:>8.1e} | " + " | ".join(f"{sweep[d, p]:>7}" for d in DS) + f" | {SHOTS:>7}")Threshold sweep: SI1000 noise, Z memory, rounds = d, PyMatching, seed 2026
logical failures out of 200,000 shots per point
p | d = 3 | d = 5 | d = 7 | shots
1.5e-03 | 1494 | 602 | 259 | 200000
2.0e-03 | 2617 | 1511 | 759 | 200000
2.5e-03 | 4173 | 2834 | 1746 | 200000
3.0e-03 | 5614 | 4586 | 3541 | 200000
3.5e-03 | 7440 | 7066 | 6021 | 200000
4.0e-03 | 9495 | 9932 | 9690 | 200000
4.5e-03 | 11488 | 13250 | 14284 | 200000
5.0e-03 | 13740 | 16938 | 19622 | 200000
6.0e-03 | 18872 | 25421 | 32590 | 200000
Now the crossings. For each pair of distances, find the two grid points between which the
order of the LEPs flips and interpolate linearly in
lep = {k: f / SHOTS for k, f in sweep.items()}
def crossing(da, db):
g = [np.log(lep[da, p] / lep[db, p]) for p in PS]
for i in range(len(PS) - 1):
if g[i] > 0 >= g[i + 1]:
t = g[i] / (g[i] - g[i + 1])
return float(np.exp(np.log(PS[i]) + t * np.log(PS[i + 1] / PS[i])))
return None
for da, db in ((3, 5), (5, 7), (3, 7)):
print(f"d = {da} and d = {db} cross at p = {crossing(da, db):.2e}")d = 3 and d = 5 cross at p = 3.76e-03 d = 5 and d = 7 cross at p = 4.12e-03 d = 3 and d = 7 cross at p = 3.95e-03
fig, ax = plt.subplots()
for d, marker in zip(DS, ("s", "o", "^")):
y = np.array([lep[d, p] for p in PS])
ax.errorbar(PS, y, yerr=np.sqrt(y * (1 - y) / SHOTS), marker=marker, capsize=2,
label=f"d = {d} (rounds = {d})")
ax.axvspan(3.5e-3, 4.5e-3, color="0.85", zorder=0, label="curves cross")
ax.set_xscale("log")
ax.set_yscale("log")
ax.set_xticks([2e-3, 3e-3, 4e-3, 6e-3], ["0.002", "0.003", "0.004", "0.006"])
ax.set_xlabel("SI1000 noise strength p")
ax.set_ylabel("logical error probability (rounds = d)")
ax.legend()
plt.show()Logical error probability of a d-round memory against SI1000 noise strength p, 200,000 shots per point with binomial error bars (smaller than the markers), on log–log axes. Below about p = 0.0035 larger codes fail less often; the curves cross between 0.0035 and 0.0045, and the crossing drifts upward with d.
These curves compare runs of different length:
eps_sweep = {k: 0.5 * (1 - (1 - 2 * lep[k]) ** (1 / k[0])) for k in lep}
print("logical error per round, rounds = d (single-point formula)")
print(f"{'p':>8} | {'d = 3':>9} | {'d = 5':>9} | {'d = 7':>9}")
for p in PS:
print(f"{p:>8.1e} | " + " | ".join(f"{eps_sweep[d, p]:>9.3e}" for d in DS))logical error per round, rounds = d (single-point formula)
p | d = 3 | d = 5 | d = 7
1.5e-03 | 2.503e-03 | 6.035e-04 | 1.852e-04
2.0e-03 | 4.400e-03 | 1.520e-03 | 5.439e-04
2.5e-03 | 7.054e-03 | 2.867e-03 | 1.257e-03
3.0e-03 | 9.537e-03 | 4.673e-03 | 2.569e-03
3.5e-03 | 1.272e-02 | 7.275e-03 | 4.416e-03
4.0e-03 | 1.635e-02 | 1.035e-02 | 7.227e-03
4.5e-03 | 1.993e-02 | 1.401e-02 | 1.089e-02
5.0e-03 | 2.404e-02 | 1.822e-02 | 1.536e-02
6.0e-03 | 3.367e-02 | 2.849e-02 | 2.739e-02
fig, ax = plt.subplots()
for d, marker in zip(DS, ("s", "o", "^")):
ax.plot(PS, [eps_sweep[d, p] for p in PS], marker=marker, label=f"d = {d}")
ax.set_xscale("log")
ax.set_yscale("log")
ax.set_xticks([2e-3, 3e-3, 4e-3, 6e-3], ["0.002", "0.003", "0.004", "0.006"])
ax.set_xlabel("SI1000 noise strength p")
ax.set_ylabel("logical error per round")
ax.legend()
plt.show()The same sweep as logical error per round, each point converted on its own (SPAM included). Per round, the larger codes are still better at p = 0.006, though d = 5 and d = 7 have nearly met: the per-round threshold of this circuit lies above the total-LEP crossing.
Which threshold?
The total-LEP crossing near
is the conventional threshold plot, but it penalises the larger code for running longer. Per round, the order has not flipped at (converted point by point; slope fits over several round counts cross per round near to ). Quote the quantity whenever you quote a threshold.
3. Logical error per round from several round counts
If each round flips the logical independently with probability compute_logical_error_per_round.
ROUNDS = [5, 10, 20, 40]
P0 = 1e-3
runs, fits = {}, {}
for d in DS:
runs[d] = [fails_at(d, P0, r, SHOTS) for r in ROUNDS]
lep_r, std_r = an.calculate_lep_and_lep_stddev(runs[d], [SHOTS] * len(ROUNDS))
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
fits[d] = an.compute_logical_error_per_round(ROUNDS, lep_r, std_r)
fit = fits[d]
print(f"d = {d}: fails at r = {ROUNDS}: {runs[d]}")
print(f" eps = {fit.leppr:.4e} ± {fit.leppr_stddev:.1e}, "
f"SPAM = {fit.spam_error:+.2e} ± {fit.spam_error_stddev:.1e}")
for w in caught:
print(" warning:", str(w.message).split(". ")[0] + ".")d = 3: fails at r = [5, 10, 20, 40]: [1199, 2273, 4489, 8626] eps = 1.1181e-03 ± 1.4e-05, SPAM = +4.10e-04 ± 1.9e-04 warning: The maximum estimated logical error probability (0.04313) is below 0.2. d = 5: fails at r = [5, 10, 20, 40]: [177, 394, 832, 1630] eps = 2.1159e-04 ± 5.6e-06, SPAM = -1.55e-04 ± 7.6e-05 warning: The maximum estimated logical error probability (0.00815) is below 0.2. d = 7: fails at r = [5, 10, 20, 40]: [30, 63, 129, 273] eps = 3.4375e-05 ± 2.3e-06, SPAM = -2.54e-05 ± 3.1e-05 warning: The maximum estimated logical error probability (0.001365) is below 0.2.
Deltakit warns because every LEP is far below 0.2; at these small values
One caveat: fails_at reuses one seed for every round count, so the four runs at a distance
draw the same noise for their shared first rounds and the points are not quite independent.
Seeding each round count separately (seed=SEED + r) lowers
fig, axes = plt.subplots(1, 3, figsize=(6.4, 2.9))
rr = np.linspace(0, 42, 50)
for ax, d in zip(axes, DS):
pl = np.array(runs[d]) / SHOTS
y = -0.5 * np.log(1 - 2 * pl)
yerr = np.sqrt(pl * (1 - pl) / SHOTS) / (1 - 2 * pl)
ax.errorbar(ROUNDS, y, yerr=yerr, fmt="o", capsize=2)
fit = fits[d]
line = -0.5 * (np.log(1 - 2 * fit.spam_error) + rr * np.log(1 - 2 * fit.leppr))
ax.plot(rr, line, "-", lw=1.2)
ax.set_title(f"d = {d}")
ax.set_xlabel("rounds r")
ax.ticklabel_format(axis="y", style="sci", scilimits=(0, 0))
axes[0].set_ylabel("−½ ln(1 − 2 p_L)")
plt.show()−½ ln(1 − 2p_L), which is close to p_L, against the number of rounds at p = 10⁻³, with the weighted straight-line fit for each distance. The slope gives the error per round ε; the intercept at r = 0 is the SPAM term, positive at d = 3, slightly negative at d = 5 and indistinguishable from zero at d = 7.
fit_logical_error_per_round_asymmetric fits the same model with asymmetric errors, but it
clamps the SPAM term at zero. Where the free fit finds a negative intercept, the clamp moves
for d in DS:
with warnings.catch_warnings():
warnings.simplefilter("ignore") # the same "below 0.2" warning as above
afit = an.fit_logical_error_per_round_asymmetric(
ROUNDS, runs[d], [SHOTS] * len(ROUNDS))
print(f"d = {d}: free fit eps = {fits[d].leppr:.3e}, "
f"clamped fit eps = {afit.leppr:.3e} (SPAM {afit.spam_error:.0e})")d = 3: free fit eps = 1.118e-03, clamped fit eps = 1.118e-03 (SPAM 4e-04) d = 5: free fit eps = 2.116e-04, clamped fit eps = 2.033e-04 (SPAM 1e-12) d = 7: free fit eps = 3.438e-05, clamped fit eps = 3.303e-05 (SPAM 1e-12)
4. Λ, and the one-round-count shortcut
Fit
eps = [fits[d].leppr for d in DS]
eps_std = [fits[d].leppr_stddev for d in DS]
ld = an.calculate_lambda_and_lambda_stddev(DS, eps, eps_std)
print(f"slope fit: Lambda = {ld.lambda_:.2f} ± {ld.lambda_std:.2f}, "
f"Lambda0 = {ld.lambda0:.1f} ± {ld.lambda0_std:.1f}")
print(f"consecutive ratios: eps3/eps5 = {eps[0] / eps[1]:.2f}, "
f"eps5/eps7 = {eps[1] / eps[2]:.2f}")slope fit: Lambda = 5.46 ± 0.12, Lambda0 = 29.9 ± 1.6 consecutive ratios: eps3/eps5 = 5.28, eps5/eps7 = 6.16
The field map’s
SHORT_SHOTS = 400_000
short = {d: fails_at(d, P0, d, SHORT_SHOTS) for d in DS}
eps_short, std_short = [], []
for d in DS:
lep1, std1 = an.calculate_lep_and_lep_stddev(fails=short[d], shots=SHORT_SHOTS)
k = (1 - 2 * lep1) ** (1 / d)
eps_short.append((1 - k) / 2)
std_short.append(std1 * k / (1 - 2 * lep1) / d)
ld_short = an.calculate_lambda_and_lambda_stddev(DS, eps_short, std_short)
print("rounds = d fails:", short)
print(f"shortcut: Lambda = {ld_short.lambda_:.2f} ± {ld_short.lambda_std:.2f}, "
f"Lambda0 = {ld_short.lambda0:.1f} ± {ld_short.lambda0_std:.1f}")
for d, a, b in zip(DS, eps_short, eps):
print(f" d = {d}: shortcut eps / slope eps = {a / b:.3f}")rounds = d fails: {3: 1409, 5: 368, 7: 87}
shortcut: Lambda = 6.26 ± 0.27, Lambda0 = 21.7 ± 2.2
d = 3: shortcut eps / slope eps = 1.053
d = 5: shortcut eps / slope eps = 0.870
d = 7: shortcut eps / slope eps = 0.904
The shortcut folds the SPAM term into
fig, ax = plt.subplots()
dd = np.linspace(3, 7, 20)
ax.errorbar(DS, eps, yerr=eps_std, fmt="o", color="C0", capsize=2,
label="slope over 5–40 rounds")
ax.plot(dd, 1 / (ld.lambda0 * ld.lambda_ ** ((dd + 1) / 2)), "-", color="C0", lw=1.2,
label=f"its fit: Λ = {ld.lambda_:.2f}")
ax.errorbar(DS, eps_short, yerr=std_short, fmt="s", color="C1", mfc="white", capsize=2,
label="rounds = d shortcut")
ax.plot(dd, 1 / (ld_short.lambda0 * ld_short.lambda_ ** ((dd + 1) / 2)), "--", color="C1",
lw=1.2, label=f"its fit: Λ = {ld_short.lambda_:.2f}")
ax.set_yscale("log")
ax.set_xticks(DS)
ax.set_xlabel("code distance d")
ax.set_ylabel("logical error per round")
ax.legend()
plt.show()Logical error per round against distance at p = 10⁻³, log scale. Filled markers: slopes over 5 to 40 rounds (200,000 shots each) and their Λ fit. Open markers: the rounds = d shortcut (400,000 shots). The shortcut's line is steeper, so it promises more suppression per step than the slope fit supports.
5. From Λ to QuOps and qubits
Deltakit counts QuOps as LambdaData.lambda0 means
Two conventions for
predict_quops_at_distance(1 / ld.lambda0, ld.lambda_, d)is right. Passingld.lambda0unchanged understates QuOps by a factor, several hundred here.
L, L0 = ld.lambda_, ld.lambda0
for d in (11, 15, 21):
good = an.predict_quops_at_distance(1 / L0, L, d)
bad = an.predict_quops_at_distance(L0, L, d)
print(f"d = {d}: {good:,.0f} QuOps (with lambda0 passed unchanged: {bad:,.0f})")
for target in (1e6, 1e9, 1e12):
d_need = an.predict_distance_for_quops(1 / L0, L, target)
qubits = 2 * d_need ** 2 - 1
print(f"{target:.0e} QuOps need d = {d_need}: {qubits:,} physical qubits per patch")d = 11: 71,970 QuOps (with lambda0 passed unchanged: 81) d = 15: 1,572,737 QuOps (with lambda0 passed unchanged: 1,758) d = 21: 182,741,904 QuOps (with lambda0 passed unchanged: 204,174) 1e+06 QuOps need d = 15: 449 physical qubits per patch 1e+09 QuOps need d = 25: 1,249 physical qubits per patch 1e+12 QuOps need d = 33: 2,177 physical qubits per patch
The same targets from the shortcut’s
Ls, L0s = ld_short.lambda_, ld_short.lambda0
for target in (1e6, 1e9, 1e12):
d_slope = an.predict_distance_for_quops(1 / L0, L, target)
d_short = an.predict_distance_for_quops(1 / L0s, Ls, target)
print(f"{target:.0e} QuOps: d = {d_slope} from the slope fit, "
f"d = {d_short} from the shortcut")1e+06 QuOps: d = 15 from the slope fit, d = 15 from the shortcut 1e+09 QuOps: d = 25 from the slope fit, d = 23 from the shortcut 1e+12 QuOps: d = 33 from the slope fit, d = 31 from the shortcut
Error budgets are not run here
deltakit.explorer.analysis.error_budget.get_error_budgetsplitsinto one share per noise parameter (Lecture 6). It has no seed and draws progress bars, so its numbers change from run to run and cannot appear in a reproducible notebook. Lecture 6 shows the call and the shares two runs gave.
Try this
- Refit section 3 with rounds
[5, 10]only, then[20, 40]only. Which pair’sis closer to the four-point fit, and why? - Add
to the sweep at the four largest (about 4 s per point). Does the crossing with move further up? - Replace
SI1000Noise(p=p)bySD6Noise(p=p)(import it fromdeltakit.explorer.qpu) and rerun section 2. Where do the curves cross now?- Halve
SHORT_SHOTSand rerun section 4 with two other seeds. How much does the shortcut’sscatter, and does it ever fall to the slope fit’s value?