Skip to content

Instantly share code, notes, and snippets.

@leigh-johnson
Last active October 24, 2025 19:40
Show Gist options
  • Select an option

  • Save leigh-johnson/4f2e0915041608d8e46b0acde9c92740 to your computer and use it in GitHub Desktop.

Select an option

Save leigh-johnson/4f2e0915041608d8e46b0acde9c92740 to your computer and use it in GitHub Desktop.
Quantum error correction example: erasure conversion for X repetition code in Stim
import stim
c = stim.Circuit(open("x_rep3.stim").read())
print(c.detector_error_model()) # inspect the detector error model
sampler = c.compile_detector_sampler()
print(sampler.sample(shots=5)) # inspect detection events
c = stim.Circuit(open("x_rep3_erasure.stim").read())
print(c.detector_error_model()) # inspect the detector error model
sampler = c.compile_detector_sampler()
print(sampler.sample(shots=5)) # inspect detection events
# 3-qubit X-repetition; data qubits 0,1,2
# Prepare |000>
R 0 1 2
# Optional X noise on data (unknown-location faults)
X_ERROR(0.02) 0 1 2
TICK
# Round 1: measure Z-parity checks
MPP Z0*Z1
MPP Z1*Z2
# Expected parity is +1 from |000>, so -1 => detection event
DETECTOR rec[-1] # D1: checks Z1Z2
DETECTOR rec[-2] # D0: checks Z0Z1
TICK
# Round 2: repeat checks; detect *changes* to cancel measurement noise
MPP Z0*Z1
MPP Z1*Z2
DETECTOR rec[-1] ^ rec[-3] # D3: Z1Z2 changed between rounds
DETECTOR rec[-2] ^ rec[-4] # D2: Z0Z1 changed between rounds
# 3-qubit X-repetition with erasure conversion
R 0 1 2
TICK
# --- round 1 erasure checks (heralds) ---
# With probability p_e, qubit is erased (maximally mixed) and a 1-bit herald is produced.
# We feed that herald to a DETECTOR so the decoder *knows the location*.
HERALDED_ERASE(0.03) 0
DETECTOR rec[-1] # E0 (round 1)
HERALDED_ERASE(0.03) 1
DETECTOR rec[-1] # E1 (round 1)
HERALDED_ERASE(0.03) 2
DETECTOR rec[-1] # E2 (round 1)
# Round 1 stabilizer measurements
MPP Z0*Z1
MPP Z1*Z2
DETECTOR rec[-1] # D1 (round 1)
DETECTOR rec[-2] # D0 (round 1)
TICK
# --- round 2 erasure checks (heralds) ---
HERALDED_ERASE(0.03) 0
DETECTOR rec[-1] # E0 (round 2)
HERALDED_ERASE(0.03) 1
DETECTOR rec[-1] # E1 (round 2)
HERALDED_ERASE(0.03) 2
DETECTOR rec[-1] # E2 (round 2)
# Round 2 stabilizer measurements
MPP Z0*Z1
MPP Z1*Z2
DETECTOR rec[-1] ^ rec[-3] # D3: Z1Z2 changed
DETECTOR rec[-2] ^ rec[-4] # D2: Z0Z1 changed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment