use crate::quantum_ops::{content_hash, DecodeReceipt, GrantRef};
use ed25519_dalek::SigningKey;
pub const QEC_FRAC: u32 = 12;
const SCALE: i64 = 1 << QEC_FRAC;
const L0: i64 = SCALE;
const MSG_MAX: i64 = 64 * SCALE;
const ALPHA_NUM: i64 = 7;
const GAMMA_MIN: i64 = -(6 * SCALE) / 10;
const GAMMA_MAX: i64 = (9 * SCALE) / 10;
fn splitmix64(state: &mut u64) -> u64 {
*state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = *state;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
}
#[derive(Clone, Debug)]
pub struct Gf2Basis {
words: usize,
rows: Vec<Vec<u64>>,
pivots: Vec<usize>,
}
fn bit_get(row: &[u64], i: usize) -> bool {
(row[i >> 6] >> (i & 63)) & 1 == 1
}
fn bit_set(row: &mut [u64], i: usize) {
row[i >> 6] |= 1u64 << (i & 63);
}
fn bit_xor(dst: &mut [u64], src: &[u64]) {
for (d, s) in dst.iter_mut().zip(src) {
*d ^= *s;
}
}
fn is_zero(row: &[u64]) -> bool {
row.iter().all(|&w| w == 0)
}
fn rref(rows_cols: &[Vec<usize>], n: usize) -> Vec<(usize, Vec<usize>)> {
let mut m: Vec<Vec<bool>> = rows_cols
.iter()
.map(|cols| {
let mut r = vec![false; n];
for &c in cols {
r[c] = true;
}
r
})
.collect();
let mut pivots: Vec<usize> = Vec::new();
let mut r = 0usize;
for c in 0..n {
let Some(sel) = (r..m.len()).find(|&i| m[i][c]) else { continue };
m.swap(r, sel);
for i in 0..m.len() {
if i != r && m[i][c] {
for j in 0..n {
let v = m[r][j];
m[i][j] ^= v;
}
}
}
pivots.push(c);
r += 1;
if r == m.len() {
break;
}
}
m.truncate(pivots.len());
pivots
.into_iter()
.zip(m)
.map(|(p, row)| (p, (0..n).filter(|&j| row[j]).collect()))
.collect()
}
impl Gf2Basis {
pub fn reduces_to_zero(&self, cols: &[usize], ncols: usize) -> bool {
let mut v = vec![0u64; ncols.div_ceil(64).max(1)];
for &c in cols {
bit_set(&mut v, c);
}
for (bi, br) in self.rows.iter().enumerate() {
if bit_get(&v, self.pivots[bi]) {
bit_xor(&mut v, br);
}
}
is_zero(&v)
}
pub fn from_rows(rows_cols: &[Vec<usize>], ncols: usize) -> Gf2Basis {
let words = ncols.div_ceil(64).max(1);
let mut basis: Vec<Vec<u64>> = Vec::new();
let mut pivots: Vec<usize> = Vec::new();
for cols in rows_cols {
let mut v = vec![0u64; words];
for &c in cols {
bit_set(&mut v, c);
}
for (bi, br) in basis.iter().enumerate() {
if bit_get(&v, pivots[bi]) {
bit_xor(&mut v, br);
}
}
if let Some(p) = Self::lowest_set(&v) {
for br in basis.iter_mut() {
if bit_get(br, p) {
bit_xor(br, &v);
}
}
basis.push(v);
pivots.push(p);
}
}
Gf2Basis { words, rows: basis, pivots }
}
fn lowest_set(v: &[u64]) -> Option<usize> {
for (w, &word) in v.iter().enumerate() {
if word != 0 {
return Some(w * 64 + word.trailing_zeros() as usize);
}
}
None
}
pub fn rank(&self) -> usize {
self.rows.len()
}
pub fn contains(&self, cols: &[usize]) -> bool {
let mut v = vec![0u64; self.words];
for &c in cols {
bit_set(&mut v, c);
}
for (bi, br) in self.rows.iter().enumerate() {
if bit_get(&v, self.pivots[bi]) {
bit_xor(&mut v, br);
}
}
is_zero(&v)
}
}
#[derive(Clone, Debug)]
pub struct CssCode {
pub id: String,
pub n: usize,
pub checks: Vec<Vec<usize>>,
pub stabs: Vec<Vec<usize>>,
stab_basis: Gf2Basis,
pub k: usize,
}
impl CssCode {
fn new(id: String, n: usize, checks: Vec<Vec<usize>>, stab: Vec<Vec<usize>>) -> CssCode {
let stab_basis = Gf2Basis::from_rows(&stab, n);
let check_basis = Gf2Basis::from_rows(&checks, n);
let k = n.saturating_sub(check_basis.rank() + stab_basis.rank());
CssCode { id, n, checks, stabs: stab, stab_basis, k }
}
pub fn check_matrix_bytes(&self) -> Vec<u8> {
let mut b = Vec::new();
b.extend_from_slice(b"wai:qec-checks\x01");
b.extend_from_slice(&(self.n as u64).to_le_bytes());
for row in &self.checks {
b.extend_from_slice(&(row.len() as u32).to_le_bytes());
for &c in row {
b.extend_from_slice(&(c as u32).to_le_bytes());
}
}
b
}
pub fn is_trivial(&self, residual_cols: &[usize]) -> bool {
self.stab_basis.contains(residual_cols)
}
pub fn toric(l: usize) -> CssCode {
let n = 2 * l * l;
let h = |i: usize, j: usize| (i % l) * l + (j % l); let v = |i: usize, j: usize| l * l + (i % l) * l + (j % l); let mut plaq = Vec::with_capacity(l * l); let mut star = Vec::with_capacity(l * l); for i in 0..l {
for j in 0..l {
let mut p = vec![h(i, j), h(i + 1, j), v(i, j), v(i, j + 1)];
p.sort_unstable();
p.dedup();
plaq.push(p);
let mut s = vec![h(i, j), h(i, j + l - 1), v(i, j), v(i + l - 1, j)];
s.sort_unstable();
s.dedup();
star.push(s);
}
}
CssCode::new(format!("toric:L{l}"), n, plaq, star)
}
pub fn surface(d: usize) -> CssCode {
assert!(d >= 3 && d % 2 == 1, "rotated surface code needs an odd distance >= 3");
let n = d * d;
let q = |r: usize, c: usize| r * d + c;
let mut z_checks: Vec<Vec<usize>> = Vec::new();
let mut x_stabs: Vec<Vec<usize>> = Vec::new();
for r in 0..d - 1 {
for c in 0..d - 1 {
let face = vec![q(r, c), q(r, c + 1), q(r + 1, c), q(r + 1, c + 1)];
if (r + c) % 2 == 0 {
z_checks.push(face);
} else {
x_stabs.push(face);
}
}
}
for c in (0..d - 1).step_by(2) {
x_stabs.push(vec![q(0, c), q(0, c + 1)]);
}
for c in (1..d - 1).step_by(2) {
x_stabs.push(vec![q(d - 1, c), q(d - 1, c + 1)]);
}
for r in (1..d - 1).step_by(2) {
z_checks.push(vec![q(r, 0), q(r + 1, 0)]);
}
for r in (0..d - 1).step_by(2) {
z_checks.push(vec![q(r, d - 1), q(r + 1, d - 1)]);
}
for v in z_checks.iter_mut().chain(x_stabs.iter_mut()) {
v.sort_unstable();
v.dedup();
}
CssCode::new(format!("surface:d{d}"), n, z_checks, x_stabs)
}
pub fn color_steane() -> CssCode {
let faces = vec![vec![3, 4, 5, 6], vec![1, 2, 5, 6], vec![0, 2, 4, 6]];
CssCode::new("color:steane".into(), 7, faces.clone(), faces)
}
pub fn is_self_dual(&self) -> bool {
let a = Gf2Basis::from_rows(&self.checks, self.n);
let b = Gf2Basis::from_rows(&self.stabs, self.n);
if a.rank() != b.rank() {
return false;
}
self.checks.iter().all(|r| b.reduces_to_zero(r, self.n))
&& self.stabs.iter().all(|r| a.reduces_to_zero(r, self.n))
}
pub fn has_transversal_hadamard(&self) -> bool {
self.is_self_dual()
}
#[cfg(feature = "quantum")]
pub fn encode_zero_circuit(&self) -> crate::quantum::Circuit {
let mut c = crate::quantum::Circuit::new(self.n as u8);
for (pivot, cols) in rref(&self.stabs, self.n) {
c.h(pivot as u8);
for col in cols {
if col != pivot {
c.cx(pivot as u8, col as u8);
}
}
}
c
}
pub fn bivariate_bicycle(l: usize, m: usize, a: &[(usize, usize)], b: &[(usize, usize)]) -> CssCode {
let lm = l * m;
let n = 2 * lm;
let cell = |i: usize, j: usize| (i % l) * m + (j % m);
let build = |monos: &[(usize, usize)]| -> Vec<Vec<usize>> {
let mut rows = vec![Vec::new(); lm];
for i in 0..l {
for j in 0..m {
let col = cell(i, j);
for &(px, py) in monos {
let row = cell(i + px, j + py);
rows[row].push(col);
}
}
}
for r in rows.iter_mut() {
r.sort_unstable();
r.dedup();
}
rows
};
let a_rows = build(a);
let b_rows = build(b);
let transpose = |rows: &[Vec<usize>]| -> Vec<Vec<usize>> {
let mut t = vec![Vec::new(); lm];
for (r, cols) in rows.iter().enumerate() {
for &c in cols {
t[c].push(r);
}
}
for x in t.iter_mut() {
x.sort_unstable();
}
t
};
let at = transpose(&a_rows);
let bt = transpose(&b_rows);
let hx: Vec<Vec<usize>> = (0..lm)
.map(|r| {
let mut row: Vec<usize> = a_rows[r].clone();
row.extend(b_rows[r].iter().map(|&c| c + lm));
row.sort_unstable();
row
})
.collect();
let hz: Vec<Vec<usize>> = (0..lm)
.map(|r| {
let mut row: Vec<usize> = bt[r].clone();
row.extend(at[r].iter().map(|&c| c + lm));
row.sort_unstable();
row
})
.collect();
let code = CssCode::new(String::new(), n, hz, hx);
CssCode { id: format!("bb:[[{},{}]]", code.n, code.k), ..code }
}
pub fn gross() -> CssCode {
CssCode::bivariate_bicycle(6, 6, &[(3, 0), (0, 1), (0, 2)], &[(0, 3), (1, 0), (2, 0)])
}
}
struct Tanner {
n: usize,
n_edges: usize,
e_var: Vec<u32>, chk_range: Vec<(u32, u32)>, var_edges: Vec<Vec<u32>>, }
impl Tanner {
fn build(checks: &[Vec<usize>], n: usize) -> Tanner {
let mut e_var = Vec::new();
let mut chk_range = Vec::with_capacity(checks.len());
let mut var_edges = vec![Vec::new(); n];
for cols in checks {
let start = e_var.len() as u32;
for &v in cols {
var_edges[v].push(e_var.len() as u32);
e_var.push(v as u32);
}
chk_range.push((start, e_var.len() as u32));
}
let n_edges = e_var.len();
Tanner { n, n_edges, e_var, chk_range, var_edges }
}
}
#[allow(clippy::too_many_arguments)]
fn bp_leg(
t: &Tanner,
syndrome: &[bool],
gamma: &[i64],
max_iter: u32,
mu_v2c: &mut [i64],
mu_c2v: &mut [i64],
) -> (Vec<bool>, bool, u32, u64) {
let mut hard = vec![false; t.n];
let mut messages = 0u64;
let mut iters = 0;
for _ in 0..max_iter {
iters += 1;
for (&(a, b), &s) in t.chk_range.iter().zip(syndrome) {
let (mut min1, mut min2) = (i64::MAX, i64::MAX);
let mut arg = a;
let mut neg_parity = false;
for e in a..b {
let x = mu_v2c[e as usize];
if x < 0 {
neg_parity = !neg_parity;
}
let mag = x.abs();
if mag < min1 {
min2 = min1;
min1 = mag;
arg = e;
} else if mag < min2 {
min2 = mag;
}
}
for e in a..b {
let x = mu_v2c[e as usize];
let base = if e == arg { min2 } else { min1 };
let mag = (base * ALPHA_NUM) >> 3;
let is_neg = neg_parity ^ (x < 0) ^ s;
mu_c2v[e as usize] = if is_neg { -mag } else { mag };
}
}
for v in 0..t.n {
let mut total = L0;
for &e in &t.var_edges[v] {
total += mu_c2v[e as usize];
}
hard[v] = total < 0;
let g = gamma[v];
for &e in &t.var_edges[v] {
let target = total - mu_c2v[e as usize];
let nv = if g == 0 {
target
} else {
(g * mu_v2c[e as usize] + (SCALE - g) * target) >> QEC_FRAC
};
mu_v2c[e as usize] = nv.clamp(-MSG_MAX, MSG_MAX);
}
}
messages += 2 * t.n_edges as u64;
let mut ok = true;
for (&(a, b), &s) in t.chk_range.iter().zip(syndrome) {
let mut par = false;
for e in a..b {
par ^= hard[t.e_var[e as usize] as usize];
}
if par != s {
ok = false;
break;
}
}
if ok {
return (hard, true, iters, messages);
}
}
(hard, false, iters, messages)
}
struct DecodeCore {
correction: Vec<bool>,
converged: bool,
legs: u32,
iters: u32,
messages: u64,
}
fn relay_bp(
t: &Tanner,
syndrome: &[bool],
seed: u64,
max_iter: u32,
max_legs: u32,
) -> DecodeCore {
let mut mu_v2c = vec![L0; t.n_edges];
let mut mu_c2v = vec![0i64; t.n_edges];
let gamma0 = vec![0i64; t.n];
let (mut hard, mut conv, mut it, mut msg) =
bp_leg(t, syndrome, &gamma0, max_iter, &mut mu_v2c, &mut mu_c2v);
let mut legs = 1u32;
let (mut tot_it, mut tot_msg) = (it, msg);
while !conv && legs < max_legs {
let mut gamma = vec![0i64; t.n];
let mut st = seed
.wrapping_mul(0x100_0001)
.wrapping_add(legs as u64)
.wrapping_add(0xD15EA5E);
let span = (GAMMA_MAX - GAMMA_MIN) as u64 + 1;
for gv in gamma.iter_mut() {
let r = splitmix64(&mut st);
*gv = GAMMA_MIN + (r % span) as i64;
}
let out = bp_leg(t, syndrome, &gamma, max_iter, &mut mu_v2c, &mut mu_c2v);
hard = out.0;
conv = out.1;
it = out.2;
msg = out.3;
tot_it += it;
tot_msg += msg;
legs += 1;
}
let _ = it;
let _ = msg;
DecodeCore { correction: hard, converged: conv, legs, iters: tot_it, messages: tot_msg }
}
#[derive(Clone, Copy, Debug)]
pub struct DecodeConfig {
pub p_fx: i64,
pub max_iter: u32,
pub max_legs: u32,
}
impl DecodeConfig {
pub fn from_p(p: f64) -> DecodeConfig {
DecodeConfig { p_fx: (p * SCALE as f64) as i64, max_iter: 32, max_legs: 12 }
}
}
#[derive(Clone, Debug)]
pub struct DecodeResult {
pub code_id: String,
pub n: usize,
pub error: Vec<u32>, pub correction: Vec<u32>, pub syndrome: Vec<u32>, pub converged: bool,
pub logical_success: bool,
pub legs: u32,
pub iters: u32,
pub messages: u64,
syndrome_bits: Vec<bool>,
correction_bits: Vec<bool>,
check_matrix_hash: [u8; 32],
}
fn sample_error(n: usize, p_fx: i64, seed: u64) -> Vec<bool> {
let mut e = vec![false; n];
let mut st = seed.wrapping_mul(0x2545_F491_4F6C_DD1D).wrapping_add(1);
for ei in e.iter_mut() {
let r = (splitmix64(&mut st) >> (64 - QEC_FRAC)) as i64; if r < p_fx {
*ei = true;
}
}
e
}
fn syndrome_of(checks: &[Vec<usize>], e: &[bool]) -> Vec<bool> {
checks
.iter()
.map(|row| row.iter().fold(false, |acc, &q| acc ^ e[q]))
.collect()
}
fn bits_to_ids(bits: &[bool]) -> Vec<u32> {
bits.iter()
.enumerate()
.filter(|&(_, &b)| b)
.map(|(i, _)| i as u32)
.collect()
}
fn canonical_bits(tag: &[u8], bits: &[bool]) -> Vec<u8> {
let mut out = tag.to_vec();
out.extend_from_slice(&(bits.len() as u64).to_le_bytes());
for chunk in bits.chunks(8) {
let mut byte = 0u8;
for (i, &b) in chunk.iter().enumerate() {
if b {
byte |= 1 << i;
}
}
out.push(byte);
}
out
}
pub fn decode_once(code: &CssCode, cfg: &DecodeConfig, seed: u64) -> DecodeResult {
let t = Tanner::build(&code.checks, code.n);
let error = sample_error(code.n, cfg.p_fx, seed);
let syndrome_bits = syndrome_of(&code.checks, &error);
let core = relay_bp(&t, &syndrome_bits, seed, cfg.max_iter, cfg.max_legs);
let residual: Vec<usize> = (0..code.n)
.filter(|&i| error[i] ^ core.correction[i])
.collect();
let logical_success = core.converged && code.is_trivial(&residual);
DecodeResult {
code_id: code.id.clone(),
n: code.n,
error: bits_to_ids(&error),
correction: bits_to_ids(&core.correction),
syndrome: bits_to_ids(&syndrome_bits),
converged: core.converged,
logical_success,
legs: core.legs,
iters: core.iters,
messages: core.messages,
syndrome_bits,
correction_bits: core.correction.clone(),
check_matrix_hash: content_hash(&code.check_matrix_bytes()),
}
}
impl DecodeResult {
pub fn seal(
&self,
signer: &SigningKey,
signer_id: impl Into<String>,
joules_micro: u64,
grant: GrantRef,
) -> DecodeReceipt {
DecodeReceipt::seal(
signer,
signer_id,
self.code_id.clone(),
"relay-bp.min-sum",
self.check_matrix_hash,
content_hash(&canonical_bits(b"wai:qec-syndrome\x01", &self.syndrome_bits)),
content_hash(&canonical_bits(b"wai:qec-correction\x01", &self.correction_bits)),
self.converged,
self.legs,
self.messages,
joules_micro,
grant,
None,
)
}
pub fn correction_bytes(&self) -> Vec<u8> {
canonical_bits(b"wai:qec-correction\x01", &self.correction_bits)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BenchResult {
pub trials: u32,
pub plain_logical_failures: u32,
pub relay_logical_failures: u32,
pub relay_total_messages: u64,
}
pub fn logical_z_support(code: &CssCode, max_weight: usize) -> Option<Vec<usize>> {
let n = code.n;
let check_basis = Gf2Basis::from_rows(&code.checks, n);
for w in 1..=max_weight.min(n) {
let mut combo: Vec<usize> = (0..w).collect();
loop {
let mut bits = vec![false; n];
for &q in &combo {
bits[q] = true;
}
if syndrome_of(&code.stabs, &bits).iter().all(|b| !b) && !check_basis.contains(&combo) {
return Some(combo);
}
if !next_combination(&mut combo, n) {
break;
}
}
}
None
}
fn next_combination(c: &mut [usize], n: usize) -> bool {
let w = c.len();
let mut i = w;
while i > 0 {
i -= 1;
if c[i] < n - (w - i) {
c[i] += 1;
for j in i + 1..w {
c[j] = c[j - 1] + 1;
}
return true;
}
}
false
}
pub fn x_distance(code: &CssCode, max_weight: usize) -> Option<usize> {
let n = code.n;
for w in 1..=max_weight.min(n) {
let mut combo: Vec<usize> = (0..w).collect();
loop {
let mut bits = vec![false; n];
for &q in &combo {
bits[q] = true;
}
if syndrome_of(&code.checks, &bits).iter().all(|b| !b) && !code.is_trivial(&combo) {
return Some(w);
}
if !next_combination(&mut combo, n) {
break;
}
}
}
None
}
fn uf_decode_graph(
nodes: usize,
boundary: usize,
edges: &[(usize, usize)],
weights: &[u32],
syndrome: &[bool],
) -> Vec<bool> {
let mut parent: Vec<usize> = (0..nodes).collect();
fn find(parent: &mut Vec<usize>, mut x: usize) -> usize {
while parent[x] != x {
parent[x] = parent[parent[x]];
x = parent[x];
}
x
}
let mut syn: Vec<bool> = (0..nodes).map(|i| syndrome.get(i).copied().unwrap_or(false)).collect();
syn[boundary] = false;
let mut grown: Vec<u32> = vec![0; edges.len()];
let maxw = weights.iter().copied().max().unwrap_or(1).max(1) as usize;
for _ in 0..(4 * nodes * maxw + 8) {
let mut parity = vec![false; nodes];
let mut touches = vec![false; nodes];
for v in 0..nodes {
let r = find(&mut parent, v);
if syn[v] {
parity[r] ^= true;
}
if v == boundary {
touches[r] = true;
}
}
if !(0..nodes).any(|v| find(&mut parent, v) == v && parity[v] && !touches[v]) {
break;
}
let mut to_union: Vec<usize> = Vec::new();
for (ei, &(a, b)) in edges.iter().enumerate() {
if grown[ei] >= 2 * weights.get(ei).copied().unwrap_or(1).max(1) {
continue;
}
let (ra, rb) = (find(&mut parent, a), find(&mut parent, b));
let odd_a = parity[ra] && !touches[ra];
let odd_b = parity[rb] && !touches[rb];
let inc = if ra == rb { u8::from(odd_a) } else { u8::from(odd_a) + u8::from(odd_b) };
if inc > 0 {
let cap = 2 * weights.get(ei).copied().unwrap_or(1).max(1);
grown[ei] = grown[ei].saturating_add(inc as u32);
if grown[ei] >= cap {
to_union.push(ei);
}
}
}
for ei in to_union {
let (a, b) = edges[ei];
let (ra, rb) = (find(&mut parent, a), find(&mut parent, b));
if ra != rb {
parent[ra] = rb;
}
}
}
let mut adj: Vec<Vec<(usize, usize)>> = vec![Vec::new(); nodes];
for (ei, &(a, b)) in edges.iter().enumerate() {
if grown[ei] >= 2 * weights.get(ei).copied().unwrap_or(1).max(1) {
adj[a].push((b, ei));
adj[b].push((a, ei));
}
}
let mut picked = vec![false; edges.len()];
let mut seen = vec![false; nodes];
for root in std::iter::once(boundary).chain(0..nodes) {
if seen[root] {
continue;
}
let mut order = vec![root];
let mut parent_edge: Vec<Option<(usize, usize)>> = vec![None; nodes];
seen[root] = true;
let mut i = 0;
while i < order.len() {
let v = order[i];
i += 1;
for &(w, ei) in &adj[v] {
if !seen[w] {
seen[w] = true;
parent_edge[w] = Some((v, ei));
order.push(w);
}
}
}
for &v in order.iter().rev() {
if v == root || !syn[v] {
continue;
}
if let Some((u, ei)) = parent_edge[v] {
picked[ei] ^= true;
syn[v] = false;
syn[u] ^= true;
}
}
}
picked
}
pub fn union_find_correct(code: &CssCode, syndrome: &[bool]) -> Option<Vec<bool>> {
let m = code.checks.len();
let boundary = m;
let mut owners: Vec<Vec<usize>> = vec![Vec::new(); code.n];
for (ci, chk) in code.checks.iter().enumerate() {
for &q in chk {
owners[q].push(ci);
}
}
let mut edges: Vec<(usize, usize)> = Vec::new();
let mut edge_qubit: Vec<usize> = Vec::new();
for (q, own) in owners.iter().enumerate() {
match own.len() {
0 => {}
1 => {
edges.push((own[0], boundary));
edge_qubit.push(q);
}
2 => {
edges.push((own[0], own[1]));
edge_qubit.push(q);
}
_ => return None,
}
}
let weights = vec![1u32; edges.len()];
let picked = uf_decode_graph(m + 1, boundary, &edges, &weights, syndrome);
let mut correction = vec![false; code.n];
for (ei, &on) in picked.iter().enumerate() {
if on {
correction[edge_qubit[ei]] ^= true;
}
}
Some(correction)
}
fn phenom_correction(code: &CssCode, cfg: &PhenomConfig, detector_bits: &[bool]) -> Option<Vec<bool>> {
let m = code.checks.len();
let t_rounds = cfg.rounds.max(1) as usize;
let layers = t_rounds + 1;
let mut owners: Vec<Vec<usize>> = vec![Vec::new(); code.n];
for (ci, chk) in code.checks.iter().enumerate() {
for &q in chk {
owners[q].push(ci);
}
}
if owners.iter().any(|o| o.len() > 2) {
return None;
}
let boundary = layers * m;
let node = |c: usize, t: usize| t * m + c;
let cost = |rate_fx: i64| -> u32 {
let r = rate_fx as f64 / 4096.0;
if r <= 0.0 { 0 } else { (-r.ln()).round().clamp(1.0, 12.0) as u32 }
};
let w_space = cost(cfg.p_data_fx);
let w_time = cost(cfg.q_meas_fx);
let mut edges: Vec<(usize, usize)> = Vec::new();
let mut weights: Vec<u32> = Vec::new();
let mut space_qubit: Vec<Option<usize>> = Vec::new();
if w_space > 0 {
for t in 0..layers {
for (q, own) in owners.iter().enumerate() {
match own.len() {
1 => {
edges.push((node(own[0], t), boundary));
weights.push(w_space);
space_qubit.push(Some(q));
}
2 => {
edges.push((node(own[0], t), node(own[1], t)));
weights.push(w_space);
space_qubit.push(Some(q));
}
_ => {}
}
}
}
}
if w_time > 0 {
for t in 0..layers - 1 {
for c in 0..m {
edges.push((node(c, t), node(c, t + 1)));
weights.push(w_time);
space_qubit.push(None);
}
}
}
let picked = uf_decode_graph(boundary + 1, boundary, &edges, &weights, detector_bits);
let mut correction = vec![false; code.n];
for (ei, &on) in picked.iter().enumerate() {
if on && let Some(q) = space_qubit[ei] {
correction[q] ^= true;
}
}
Some(correction)
}
#[derive(Clone, Copy, Debug)]
pub struct PhenomConfig {
pub rounds: u32,
pub p_data_fx: i64,
pub q_meas_fx: i64,
}
impl PhenomConfig {
pub fn from_p(rounds: u32, p_data: f64, q_meas: f64) -> PhenomConfig {
PhenomConfig {
rounds,
p_data_fx: (p_data * 4096.0) as i64,
q_meas_fx: (q_meas * 4096.0) as i64,
}
}
}
#[derive(Clone, Debug)]
pub struct PhenomResult {
pub rounds: u32,
pub detectors: Vec<u32>,
pub data_error: Vec<u32>,
pub correction: Vec<u32>,
pub logical_success: bool,
}
pub fn decode_phenomenological(
code: &CssCode,
cfg: &PhenomConfig,
seed: u64,
) -> Option<PhenomResult> {
let m = code.checks.len();
let t_rounds = cfg.rounds.max(1) as usize;
let layers = t_rounds + 1;
let mut owners: Vec<Vec<usize>> = vec![Vec::new(); code.n];
for (ci, chk) in code.checks.iter().enumerate() {
for &q in chk {
owners[q].push(ci);
}
}
if owners.iter().any(|o| o.len() > 2) {
return None;
}
let mut st = seed ^ 0x51ED_2701_A55A_1234;
let draw = |rate: i64, st: &mut u64| -> bool {
*st = st
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
(((*st >> 40) & 0xFFF) as i64) < rate
};
let mut cum_err = vec![false; code.n];
let mut s_prev = vec![false; m];
let mut detector_bits = vec![false; layers * m];
for t in 0..layers {
if t < t_rounds {
for q in 0..code.n {
if draw(cfg.p_data_fx, &mut st) {
cum_err[q] ^= true;
}
}
}
let s_true = syndrome_of(&code.checks, &cum_err);
let mut s_obs = s_true.clone();
if t < t_rounds {
for c in 0..m {
if draw(cfg.q_meas_fx, &mut st) {
s_obs[c] ^= true;
}
}
}
for c in 0..m {
detector_bits[t * m + c] = s_obs[c] ^ s_prev[c];
}
s_prev = s_obs;
}
let correction = phenom_correction(code, cfg, &detector_bits)?;
let residual: Vec<usize> = (0..code.n).filter(|&i| cum_err[i] ^ correction[i]).collect();
Some(PhenomResult {
rounds: cfg.rounds,
detectors: bits_to_ids(&detector_bits),
data_error: bits_to_ids(&cum_err),
correction: bits_to_ids(&correction),
logical_success: code.is_trivial(&residual),
})
}
#[derive(Clone, Copy, Debug)]
pub struct CircuitConfig {
pub rounds: u32,
pub p_data_fx: i64,
pub q_meas_fx: i64,
pub hook_fx: i64,
}
impl CircuitConfig {
pub fn from_p(rounds: u32, p_data: f64, q_meas: f64, hook: f64) -> CircuitConfig {
CircuitConfig {
rounds,
p_data_fx: (p_data * 4096.0) as i64,
q_meas_fx: (q_meas * 4096.0) as i64,
hook_fx: (hook * 4096.0) as i64,
}
}
fn phenom(&self) -> PhenomConfig {
PhenomConfig { rounds: self.rounds, p_data_fx: self.p_data_fx, q_meas_fx: self.q_meas_fx }
}
}
#[derive(Clone, Debug)]
pub struct CircuitResult {
pub rounds: u32,
pub data_error: Vec<u32>,
pub correction: Vec<u32>,
pub hook_events: Vec<u32>,
pub logical_success: bool,
}
pub fn decode_circuit_level(
code: &CssCode,
cfg: &CircuitConfig,
seed: u64,
) -> Option<CircuitResult> {
let m = code.checks.len();
let t_rounds = cfg.rounds.max(1) as usize;
let layers = t_rounds + 1;
let mut owners: Vec<Vec<usize>> = vec![Vec::new(); code.n];
for (ci, chk) in code.checks.iter().enumerate() {
for &q in chk {
owners[q].push(ci);
}
}
if owners.iter().any(|o| o.len() > 2) {
return None;
}
let mut st = seed ^ 0x51ED_2701_A55A_1234;
let draw = |rate: i64, st: &mut u64| -> bool {
*st = st.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
(((*st >> 40) & 0xFFF) as i64) < rate
};
let pick = |bound: usize, st: &mut u64| -> usize {
*st = st.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
if bound == 0 { 0 } else { ((*st >> 33) as usize) % bound }
};
let mut cum_err = vec![false; code.n];
let mut s_prev = vec![false; m];
let mut detector_bits = vec![false; layers * m];
let mut hook_events: Vec<u32> = Vec::new();
for t in 0..layers {
if t < t_rounds {
for q in 0..code.n {
if draw(cfg.p_data_fx, &mut st) {
cum_err[q] ^= true;
}
}
if cfg.hook_fx > 0 {
for stab in &code.stabs {
if !stab.is_empty() && draw(cfg.hook_fx, &mut st) {
let j = pick(stab.len(), &mut st);
for &q in &stab[j..] {
cum_err[q] ^= true;
}
hook_events.push((stab.len() - j) as u32);
}
}
}
}
let s_true = syndrome_of(&code.checks, &cum_err);
let mut s_obs = s_true.clone();
if t < t_rounds {
for c in 0..m {
if draw(cfg.q_meas_fx, &mut st) {
s_obs[c] ^= true;
}
}
}
for c in 0..m {
detector_bits[t * m + c] = s_obs[c] ^ s_prev[c];
}
s_prev = s_obs;
}
let correction = phenom_correction(code, &cfg.phenom(), &detector_bits)?;
let residual: Vec<usize> = (0..code.n).filter(|&i| cum_err[i] ^ correction[i]).collect();
Some(CircuitResult {
rounds: cfg.rounds,
data_error: bits_to_ids(&cum_err),
correction: bits_to_ids(&correction),
hook_events,
logical_success: code.is_trivial(&residual),
})
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DemMechanism {
pub detectors: Vec<u32>,
pub flips_observable: bool,
pub probability_ppm: u32,
}
pub fn to_dem(code: &CssCode, cfg: &CircuitConfig, max_logical_weight: usize) -> Option<String> {
let mechs = dem_mechanisms(code, cfg, max_logical_weight)?;
let m = code.checks.len();
let layers = cfg.rounds.max(1) as usize + 1;
let mut s = String::new();
s.push_str("# detector error model emitted by wai-quantum\n");
s.push_str(&format!("# code={} rounds={} detectors={}\n", code.id, cfg.rounds, layers * m));
for t in 0..layers {
for c in 0..m {
s.push_str(&format!("detector({c}, {t}) D{}\n", t * m + c));
}
}
for mech in &mechs {
let p = mech.probability_ppm as f64 / 1.0e6;
let mut line = format!("error({p:.9})");
for d in &mech.detectors {
line.push_str(&format!(" D{d}"));
}
if mech.flips_observable {
line.push_str(" L0");
}
s.push('\n');
s.truncate(s.len() - 1);
s.push_str(&line);
s.push('\n');
}
Some(s)
}
pub fn dem_mechanisms(
code: &CssCode,
cfg: &CircuitConfig,
max_logical_weight: usize,
) -> Option<Vec<DemMechanism>> {
let m = code.checks.len();
let t_rounds = cfg.rounds.max(1) as usize;
let mut owners: Vec<Vec<usize>> = vec![Vec::new(); code.n];
for (ci, chk) in code.checks.iter().enumerate() {
for &q in chk {
owners[q].push(ci);
}
}
if owners.iter().any(|o| o.len() > 2) {
return None;
}
let logical = logical_z_support(code, max_logical_weight)?;
let flips = |qs: &[usize]| qs.iter().filter(|q| logical.contains(q)).count() % 2 == 1;
let ppm = |fx: i64| ((fx as f64 / 4096.0) * 1.0e6).round().max(0.0) as u32;
let mut out: Vec<DemMechanism> = Vec::new();
if cfg.p_data_fx > 0 {
for t in 0..t_rounds {
for q in 0..code.n {
let mut ds: Vec<u32> = owners[q].iter().map(|&c| (t * m + c) as u32).collect();
ds.sort_unstable();
out.push(DemMechanism {
detectors: ds,
flips_observable: flips(&[q]),
probability_ppm: ppm(cfg.p_data_fx),
});
}
}
}
if cfg.q_meas_fx > 0 {
for t in 0..t_rounds {
for c in 0..m {
out.push(DemMechanism {
detectors: vec![(t * m + c) as u32, ((t + 1) * m + c) as u32],
flips_observable: false,
probability_ppm: ppm(cfg.q_meas_fx),
});
}
}
}
if cfg.hook_fx > 0 {
for t in 0..t_rounds {
for stab in &code.stabs {
if stab.is_empty() {
continue;
}
let each = ppm(cfg.hook_fx) / stab.len() as u32;
for j in 0..stab.len() {
let qs = &stab[j..];
let mut set: Vec<u32> = Vec::new();
for &q in qs {
for &c in &owners[q] {
let d = (t * m + c) as u32;
if let Some(pos) = set.iter().position(|&x| x == d) {
set.remove(pos); } else {
set.push(d);
}
}
}
set.sort_unstable();
let obs = flips(qs);
if set.is_empty() && !obs {
continue;
}
out.push(DemMechanism {
detectors: set,
flips_observable: obs,
probability_ppm: each,
});
}
}
}
}
Some(out)
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DemModel {
pub num_detectors: usize,
pub mechanisms: Vec<DemMechanism>,
}
pub fn from_dem(src: &str) -> Result<DemModel, String> {
let mut mechanisms = Vec::new();
let mut max_det: i64 = -1;
for (lineno, raw) in src.lines().enumerate() {
let line = raw.split('#').next().unwrap_or("").trim();
if line.is_empty() {
continue;
}
let head = line.split(['(', ' ']).next().unwrap_or("");
match head {
"detector" | "shift_detectors" | "logical_observable" | "observable_include" => {
for tok in line.split_whitespace() {
if let Some(d) = tok.strip_prefix('D')
&& let Ok(i) = d.trim_end_matches(',').parse::<i64>()
{
max_det = max_det.max(i);
}
}
}
"error" => {
let open = line.find('(').ok_or_else(|| format!("line {}: error without probability", lineno + 1))?;
let close = line[open..].find(')').ok_or_else(|| format!("line {}: unclosed probability", lineno + 1))? + open;
let p: f64 = line[open + 1..close]
.trim()
.parse()
.map_err(|_| format!("line {}: bad probability", lineno + 1))?;
if !(0.0..=1.0).contains(&p) {
return Err(format!("line {}: probability {p} outside [0,1]", lineno + 1));
}
let mut detectors = Vec::new();
let mut flips = false;
for tok in line[close + 1..].split_whitespace() {
if let Some(d) = tok.strip_prefix('D') {
let i: u32 = d.parse().map_err(|_| format!("line {}: bad detector {tok}", lineno + 1))?;
max_det = max_det.max(i as i64);
detectors.push(i);
} else if let Some(l) = tok.strip_prefix('L') {
let _: u32 = l.parse().map_err(|_| format!("line {}: bad observable {tok}", lineno + 1))?;
flips = !flips;
} else {
return Err(format!("line {}: unexpected target {tok}", lineno + 1));
}
}
detectors.sort_unstable();
if detectors.is_empty() && !flips {
continue; }
mechanisms.push(DemMechanism {
detectors,
flips_observable: flips,
probability_ppm: (p * 1.0e6).round().clamp(0.0, 1.0e6) as u32,
});
}
other => return Err(format!("line {}: unsupported DEM instruction `{other}`", lineno + 1)),
}
}
Ok(DemModel { num_detectors: (max_det + 1).max(0) as usize, mechanisms })
}
#[derive(Clone, Debug)]
pub struct DemDecode {
pub mechanisms: Vec<u32>,
pub observable_flipped: bool,
}
pub fn decode_dem(model: &DemModel, detectors: &[bool]) -> Result<DemDecode, String> {
let nd = model.num_detectors;
let boundary = nd;
let mut edges: Vec<(usize, usize)> = Vec::new();
let mut weights: Vec<u32> = Vec::new();
let mut index: Vec<usize> = Vec::new();
for (i, m) in model.mechanisms.iter().enumerate() {
let w = {
let p = m.probability_ppm as f64 / 1.0e6;
if p <= 0.0 { continue } else { (-p.ln()).round().clamp(1.0, 12.0) as u32 }
};
match m.detectors.len() {
0 => {}
1 => {
edges.push((m.detectors[0] as usize, boundary));
weights.push(w);
index.push(i);
}
2 => {
edges.push((m.detectors[0] as usize, m.detectors[1] as usize));
weights.push(w);
index.push(i);
}
k => {
return Err(format!(
"mechanism {i} touches {k} detectors; matching needs at most two — \
decompose the hyperedge or use a decoder that accepts one"
));
}
}
}
let picked = uf_decode_graph(nd + 1, boundary, &edges, &weights, detectors);
let mut used = Vec::new();
let mut flipped = false;
for (ei, &on) in picked.iter().enumerate() {
if on {
let mi = index[ei];
used.push(mi as u32);
flipped ^= model.mechanisms[mi].flips_observable;
}
}
Ok(DemDecode { mechanisms: used, observable_flipped: flipped })
}
pub fn benchmark_circuit_level(
code: &CssCode,
cfg: &CircuitConfig,
trials: u32,
seed: u64,
) -> (u32, u32) {
let mut fails = 0;
for tix in 0..trials {
let s = seed.wrapping_add(tix as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
match decode_circuit_level(code, cfg, s) {
Some(r) if r.logical_success => {}
_ => fails += 1,
}
}
(trials, fails)
}
pub fn benchmark_phenomenological(
code: &CssCode,
cfg: &PhenomConfig,
trials: u32,
seed: u64,
) -> (u32, u32) {
let mut fails = 0;
for tix in 0..trials {
let s = seed.wrapping_add(tix as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
match decode_phenomenological(code, cfg, s) {
Some(r) if r.logical_success => {}
_ => fails += 1,
}
}
(trials, fails)
}
pub fn decode_once_uf(code: &CssCode, cfg: &DecodeConfig, seed: u64) -> DecodeResult {
let error = sample_error(code.n, cfg.p_fx, seed);
let syndrome_bits = syndrome_of(&code.checks, &error);
let (correction, converged) = match union_find_correct(code, &syndrome_bits) {
Some(c) => (c, true),
None => (vec![false; code.n], false),
};
let residual: Vec<usize> = (0..code.n).filter(|&i| error[i] ^ correction[i]).collect();
let logical_success = converged && code.is_trivial(&residual);
DecodeResult {
code_id: code.id.clone(),
n: code.n,
error: bits_to_ids(&error),
correction: bits_to_ids(&correction),
syndrome: bits_to_ids(&syndrome_bits),
converged,
logical_success,
legs: 0,
iters: 0,
messages: 0,
syndrome_bits,
correction_bits: correction,
check_matrix_hash: content_hash(&code.check_matrix_bytes()),
}
}
pub fn benchmark_uf(code: &CssCode, p: f64, trials: u32, seed: u64) -> (u32, u32) {
let cfg = DecodeConfig::from_p(p);
let mut fails = 0;
for tix in 0..trials {
let s = seed.wrapping_add(tix as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
if !decode_once_uf(code, &cfg, s).logical_success {
fails += 1;
}
}
(trials, fails)
}
pub fn benchmark(code: &CssCode, p: f64, trials: u32, seed: u64, max_legs: u32) -> BenchResult {
let base = DecodeConfig::from_p(p);
let plain = DecodeConfig { max_legs: 1, ..base };
let relay = DecodeConfig { max_legs, ..base };
let mut pf = 0;
let mut rf = 0;
let mut msg = 0u64;
for tix in 0..trials {
let s = seed.wrapping_add(tix as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
if !decode_once(code, &plain, s).logical_success {
pf += 1;
}
let r = decode_once(code, &relay, s);
if !r.logical_success {
rf += 1;
}
msg += r.messages;
}
BenchResult { trials, plain_logical_failures: pf, relay_logical_failures: rf, relay_total_messages: msg }
}
#[cfg(test)]
mod tests {
use super::*;
fn key(s: u8) -> SigningKey {
SigningKey::from_bytes(&[s; 32])
}
#[test]
fn steane_is_a_distance_three_colour_code() {
let c = CssCode::color_steane();
assert_eq!(c.n, 7);
assert_eq!(c.k, 1, "one logical qubit");
assert_eq!(x_distance(&c, 5), Some(3), "distance must be found, not claimed");
assert!(c.is_self_dual(), "a colour code's two stabilizer families coincide");
assert!(c.has_transversal_hadamard());
}
#[test]
fn the_surface_code_has_no_transversal_hadamard() {
let s = CssCode::surface(3);
assert!(!s.is_self_dual(), "surface X and Z families sit on different supports");
assert!(!s.has_transversal_hadamard());
}
#[cfg(feature = "quantum")]
#[test]
fn the_encoder_prepares_a_codeword() {
for code in [CssCode::color_steane(), CssCode::surface(3)] {
let sv = code.encode_zero_circuit().simulate().unwrap();
for (i, a) in sv.amps.iter().enumerate() {
if a.norm2() == 0 {
continue;
}
for chk in &code.checks {
let par = chk.iter().filter(|&&q| (i >> q) & 1 == 1).count() % 2;
assert_eq!(par, 0, "{} left basis state {i:b} outside the code", code.id);
}
}
}
}
#[cfg(feature = "quantum_info")]
#[test]
fn transversal_hadamard_implements_a_logical_hadamard() {
use crate::quantum::ONE;
use crate::quantum_info::{expect_pauli, Pauli};
let code = CssCode::color_steane();
let zl: Vec<(u8, Pauli)> = (0..7).map(|q| (q, Pauli::Z)).collect();
let xl: Vec<(u8, Pauli)> = (0..7).map(|q| (q, Pauli::X)).collect();
let near = |got: i64, want: i64, what: &str| {
assert!((got - want).abs() < 1 << 13, "{what}: got {got}, want {want}");
};
let mut c = code.encode_zero_circuit();
let sv = c.simulate().unwrap();
near(expect_pauli(&sv, &zl), ONE, "<Z_L> on |0>_L");
near(expect_pauli(&sv, &xl), 0, "<X_L> on |0>_L");
for q in 0..7 {
c.h(q);
}
let out = c.simulate().unwrap();
near(expect_pauli(&out, &xl), ONE, "<X_L> after transversal H");
near(expect_pauli(&out, &zl), 0, "<Z_L> after transversal H");
for chk in &code.checks {
let zs: Vec<(u8, Pauli)> = chk.iter().map(|&q| (q as u8, Pauli::Z)).collect();
let xs: Vec<(u8, Pauli)> = chk.iter().map(|&q| (q as u8, Pauli::X)).collect();
near(expect_pauli(&out, &zs), ONE, "Z stabilizer after transversal H");
near(expect_pauli(&out, &xs), ONE, "X stabilizer after transversal H");
}
}
#[cfg(feature = "quantum_info")]
#[test]
fn transversal_hadamard_breaks_the_surface_code() {
use crate::quantum::ONE;
use crate::quantum_info::{expect_pauli, Pauli};
let code = CssCode::surface(3);
let mut c = code.encode_zero_circuit();
for q in 0..code.n as u8 {
c.h(q);
}
let out = c.simulate().unwrap();
let violated = code.checks.iter().any(|chk| {
let zs: Vec<(u8, Pauli)> = chk.iter().map(|&q| (q as u8, Pauli::Z)).collect();
(expect_pauli(&out, &zs) - ONE).abs() >= 1 << 13
});
assert!(violated, "transversal H must knock the surface code out of its code space");
}
#[test]
fn gf2_membership() {
let basis = Gf2Basis::from_rows(&[vec![0, 1], vec![1, 2]], 3);
assert_eq!(basis.rank(), 2);
assert!(basis.contains(&[0, 1]));
assert!(basis.contains(&[1, 2]));
assert!(basis.contains(&[0, 2]));
assert!(basis.contains(&[])); assert!(!basis.contains(&[0]));
assert!(!basis.contains(&[2]));
}
#[test]
fn surface_code_is_a_valid_css_code() {
for d in [3usize, 5, 7] {
let code = CssCode::surface(d);
assert_eq!(code.n, d * d, "d={d} qubit count");
assert_eq!(code.k, 1, "d={d} must encode exactly one logical qubit");
let x: Vec<&Vec<usize>> = code.stabs.iter().collect();
for zc in &code.checks {
for xs in &x {
let overlap = zc.iter().filter(|q| xs.contains(q)).count();
assert_eq!(overlap % 2, 0, "d={d}: X{xs:?} and Z{zc:?} anticommute");
}
}
assert_eq!(code.checks.len(), (d * d - 1) / 2, "d={d} Z-check count");
assert_eq!(x.len(), (d * d - 1) / 2, "d={d} X-stabilizer count");
for v in code.checks.iter().chain(x.iter().copied()) {
assert!(v.len() == 4 || v.len() == 2, "d={d}: weight {} stabilizer", v.len());
}
}
}
#[test]
fn surface_code_decodes() {
let d3 = CssCode::surface(3);
let r = benchmark(&d3, 0.01, 500, 7, 4);
let relay = r.relay_logical_failures as f64 / r.trials as f64;
assert!(relay <= 0.05, "d=3 at p=0.01 should rarely fail: {relay}");
assert!(
r.relay_logical_failures <= r.plain_logical_failures,
"relay {} must not do worse than plain BP {}",
r.relay_logical_failures,
r.plain_logical_failures
);
}
#[test]
fn relay_beats_plain_bp_on_qldpc() {
let bb = CssCode::gross();
let r = benchmark(&bb, 0.06, 400, 11, 16);
assert!(
r.relay_logical_failures < r.plain_logical_failures,
"relay {} should beat plain BP {} on a qLDPC code",
r.relay_logical_failures,
r.plain_logical_failures
);
}
#[test]
#[ignore]
fn probe_surface_threshold() {
println!("\n-- relay legs on the code Relay-BP was designed for: BB [[72,12]] --");
let bb = CssCode::gross();
println!(" p legs=1(plain) legs=4 legs=16");
for &pp in &[0.02f64, 0.04, 0.06] {
let f = |legs: u32| {
let r = benchmark(&bb, pp, 400, 11, legs);
r.relay_logical_failures as f64 / r.trials as f64
};
let plain = {
let r = benchmark(&bb, pp, 400, 11, 4);
r.plain_logical_failures as f64 / r.trials as f64
};
println!(" {pp:<8} {plain:<13.4} {:<9.4} {:<9.4}", f(4), f(16));
}
println!("\n-- the same sweep on topological codes --");
println!(" p surf d=3 surf d=5 toric L=3 toric L=5");
for &pp in &[0.001f64, 0.005, 0.01] {
let sf = |d: usize| {
let r = benchmark(&CssCode::surface(d), pp, 1500, 11, 16);
r.relay_logical_failures as f64 / r.trials as f64
};
let tf = |l: usize| {
let r = benchmark(&CssCode::toric(l), pp, 1500, 11, 16);
r.relay_logical_failures as f64 / r.trials as f64
};
println!(" {pp:<8} {:<9.4} {:<9.4} {:<9.4} {:<9.4}", sf(3), sf(5), tf(3), tf(5));
}
}
#[test]
fn union_find_makes_distance_count() {
let p = 0.01;
let rate = |d: usize| {
let (t, f) = benchmark_uf(&CssCode::surface(d), p, 1500, 11);
f as f64 / t as f64
};
let (r3, r5) = (rate(3), rate(5));
assert!(r5 < r3, "d=5 ({r5}) must beat d=3 ({r3}) below threshold");
assert!(r5 <= 0.005, "d=5 at p={p} should almost never fail: {r5}");
}
#[test]
fn union_find_beats_bp_on_topological_codes() {
let p = 0.02;
for d in [5usize, 7] {
let code = CssCode::surface(d);
let bp = {
let r = benchmark(&code, p, 1000, 11, 16);
r.relay_logical_failures as f64 / r.trials as f64
};
let (t, f) = benchmark_uf(&code, p, 1000, 11);
let uf = f as f64 / t as f64;
assert!(uf < bp, "d={d}: union-find {uf} should beat Relay-BP {bp}");
}
}
#[test]
fn union_find_refuses_non_matching_codes() {
assert!(
union_find_correct(&CssCode::gross(), &vec![false; CssCode::gross().checks.len()]).is_none(),
"a bivariate-bicycle qubit sits in three checks; UF must decline"
);
assert!(union_find_correct(&CssCode::surface(5), &vec![false; 12]).is_some());
}
#[test]
fn union_find_corrects_every_single_qubit_error() {
for d in [3usize, 5] {
let code = CssCode::surface(d);
for q in 0..code.n {
let mut err = vec![false; code.n];
err[q] = true;
let syn = syndrome_of(&code.checks, &err);
let corr = union_find_correct(&code, &syn).expect("matching graph");
let residual: Vec<usize> = (0..code.n).filter(|&i| err[i] ^ corr[i]).collect();
assert!(
code.is_trivial(&residual),
"d={d}: single error on qubit {q} left a logical residual {residual:?}"
);
}
}
}
#[test]
fn measurement_noise_alone_never_causes_a_logical_error() {
for d in [3usize, 5] {
let code = CssCode::surface(d);
let cfg = PhenomConfig::from_p(d as u32, 0.0, 0.05);
for t in 0..300u64 {
let r = decode_phenomenological(&code, &cfg, t.wrapping_mul(0x9E37_79B9))
.expect("matching graph");
assert!(
r.logical_success,
"d={d} seed={t}: pure measurement noise produced a logical failure \
(correction {:?} on an empty data error)",
r.correction
);
}
}
}
#[test]
fn phenomenological_distance_helps() {
let p = 0.005;
let rate = |d: usize| {
let cfg = PhenomConfig::from_p(d as u32, p, p);
let (t, f) = benchmark_phenomenological(&CssCode::surface(d), &cfg, 1200, 11);
f as f64 / t as f64
};
let (r3, r5) = (rate(3), rate(5));
assert!(r5 < r3, "d=5 ({r5}) must beat d=3 ({r3}) under noisy measurement");
}
#[test]
fn perfect_measurement_reduces_to_single_shot() {
for d in [3usize, 5] {
let code = CssCode::surface(d);
let cfg = PhenomConfig::from_p(1, 0.02, 0.0);
let (t1, f1) = benchmark_phenomenological(&code, &cfg, 1200, 11);
let (t2, f2) = benchmark_uf(&code, 0.02, 1200, 11);
let (a, b) = (f1 as f64 / t1 as f64, f2 as f64 / t2 as f64);
assert!((a - b).abs() < 0.02, "d={d}: spacetime {a} vs single-shot {b}");
}
}
#[test]
fn phenomenological_refuses_non_matching_codes() {
let cfg = PhenomConfig::from_p(3, 0.01, 0.01);
assert!(decode_phenomenological(&CssCode::gross(), &cfg, 1).is_none());
}
#[test]
fn surface_code_distance_is_d() {
for d in [3usize, 5] {
let code = CssCode::surface(d);
assert_eq!(
x_distance(&code, d + 1),
Some(d),
"surface d={d} should have X-distance exactly {d}"
);
}
}
#[test]
fn toric_code_distance_is_l() {
let code = CssCode::toric(3);
assert_eq!(code.k, 2, "toric encodes two logical qubits");
assert_eq!(x_distance(&code, 4), Some(3));
}
#[test]
fn union_find_corrects_every_error_below_the_distance() {
for d in [3usize, 5] {
let code = CssCode::surface(d);
let w = (d - 1) / 2; let mut combo: Vec<usize> = (0..w).collect();
let mut checked = 0u32;
loop {
let mut err = vec![false; code.n];
for &q in &combo {
err[q] = true;
}
let syn = syndrome_of(&code.checks, &err);
let corr = union_find_correct(&code, &syn).expect("matching graph");
let residual: Vec<usize> =
(0..code.n).filter(|&i| err[i] ^ corr[i]).collect();
assert!(
code.is_trivial(&residual),
"d={d}: weight-{w} error {combo:?} decoded to a logical residual {residual:?}"
);
checked += 1;
if !next_combination(&mut combo, code.n) {
break;
}
}
assert!(checked > 0, "d={d}: nothing checked");
}
}
#[test]
fn hooks_off_is_exactly_phenomenological() {
for &pp in &[0.005f64, 0.02] {
for d in [3usize, 5] {
let code = CssCode::surface(d);
let ph = PhenomConfig::from_p(d as u32, pp, pp);
let cl = CircuitConfig::from_p(d as u32, pp, pp, 0.0);
let (_, a) = benchmark_phenomenological(&code, &ph, 600, 11);
let (_, b) = benchmark_circuit_level(&code, &cl, 600, 11);
assert_eq!(a, b, "p={pp} d={d}: hook-free circuit level must equal phenomenological");
}
}
}
#[test]
fn hook_errors_cost_accuracy() {
let (p, d) = (0.005, 5usize);
let code = CssCode::surface(d);
let off = CircuitConfig::from_p(d as u32, p, p, 0.0);
let on = CircuitConfig::from_p(d as u32, p, p, p);
let (_, f_off) = benchmark_circuit_level(&code, &off, 1500, 11);
let (_, f_on) = benchmark_circuit_level(&code, &on, 1500, 11);
assert!(f_on > f_off, "hooks on ({f_on}) should fail more than hooks off ({f_off})");
}
#[test]
fn hook_weight_is_bounded_by_the_stabilizer() {
let code = CssCode::surface(5);
let maxw = code.stabs.iter().map(|s| s.len()).max().unwrap();
let cfg = CircuitConfig::from_p(5, 0.0, 0.0, 0.2);
let mut seen = 0;
for t in 0..200u64 {
let r = decode_circuit_level(&code, &cfg, t.wrapping_mul(0x9E37_79B9)).unwrap();
for &w in &r.hook_events {
assert!(w >= 1 && w as usize <= maxw, "hook weight {w} outside 1..={maxw}");
seen += 1;
}
}
assert!(seen > 0, "the probe never fired a hook");
}
#[test]
fn noiseless_circuit_never_fails() {
let code = CssCode::surface(5);
let cfg = CircuitConfig::from_p(5, 0.0, 0.0, 0.0);
for t in 0..200u64 {
let r = decode_circuit_level(&code, &cfg, t).unwrap();
assert!(r.logical_success && r.data_error.is_empty() && r.correction.is_empty());
}
}
#[test]
fn circuit_level_refuses_non_matching_codes() {
let cfg = CircuitConfig::from_p(3, 0.01, 0.01, 0.01);
assert!(decode_circuit_level(&CssCode::gross(), &cfg, 1).is_none());
}
#[test]
fn logical_z_is_a_valid_observable() {
for d in [3usize, 5] {
let code = CssCode::surface(d);
let lz = logical_z_support(&code, d + 1).expect("a logical Z exists");
assert_eq!(lz.len(), d, "d={d}: minimum-weight logical Z should have weight {d}");
let mut bits = vec![false; code.n];
for &q in &lz { bits[q] = true; }
assert!(syndrome_of(&code.stabs, &bits).iter().all(|b| !b));
let dx = x_distance(&code, d + 1).expect("a logical X exists");
assert_eq!(dx, d);
let mut combo: Vec<usize> = (0..d).collect();
let mut found = false;
loop {
let mut e = vec![false; code.n];
for &q in &combo { e[q] = true; }
if syndrome_of(&code.checks, &e).iter().all(|b| !b) && !code.is_trivial(&combo) {
let overlap = combo.iter().filter(|q| lz.contains(q)).count();
assert_eq!(overlap % 2, 1, "d={d}: logical Z {lz:?} misses logical X {combo:?}");
found = true;
break;
}
if !next_combination(&mut combo, code.n) { break; }
}
assert!(found, "d={d}: no minimum-weight logical X found");
}
}
#[test]
fn dem_encodes_the_codes_logical_structure() {
for d in [3usize, 5] {
let code = CssCode::surface(d);
let cfg = CircuitConfig::from_p(2, 0.001, 0.001, 0.0);
let mechs = dem_mechanisms(&code, &cfg, d + 1).expect("matching graph");
let mut combo: Vec<usize> = (0..d).collect();
let logical_x = loop {
let mut e = vec![false; code.n];
for &q in &combo { e[q] = true; }
if syndrome_of(&code.checks, &e).iter().all(|b| !b) && !code.is_trivial(&combo) {
break combo.clone();
}
assert!(next_combination(&mut combo, code.n), "d={d}: no logical X of weight {d}");
};
let mut detectors: Vec<u32> = Vec::new();
let mut obs = false;
for &q in &logical_x {
let mech = &mechs[q]; obs ^= mech.flips_observable;
for &dt in &mech.detectors {
if let Some(pos) = detectors.iter().position(|&x| x == dt) {
detectors.remove(pos);
} else {
detectors.push(dt);
}
}
}
assert!(detectors.is_empty(), "d={d}: logical X {logical_x:?} lit detectors {detectors:?}");
assert!(obs, "d={d}: logical X {logical_x:?} did not flip the observable");
}
}
#[test]
fn dem_says_stabilizers_are_harmless() {
let d = 5usize;
let code = CssCode::surface(d);
let cfg = CircuitConfig::from_p(2, 0.001, 0.001, 0.0);
let mechs = dem_mechanisms(&code, &cfg, d + 1).unwrap();
for stab in &code.stabs {
let mut detectors: Vec<u32> = Vec::new();
let mut obs = false;
for &q in stab {
let mech = &mechs[q];
obs ^= mech.flips_observable;
for &dt in &mech.detectors {
if let Some(pos) = detectors.iter().position(|&x| x == dt) {
detectors.remove(pos);
} else {
detectors.push(dt);
}
}
}
assert!(detectors.is_empty(), "stabilizer {stab:?} lit detectors {detectors:?}");
assert!(!obs, "stabilizer {stab:?} flipped the observable");
}
}
#[test]
fn no_dem_mechanism_is_an_invisible_logical() {
for d in [3usize, 5] {
let code = CssCode::surface(d);
for hook in [0.0, 0.002] {
let cfg = CircuitConfig::from_p(2, 0.001, 0.001, hook);
for m in dem_mechanisms(&code, &cfg, d + 1).unwrap() {
assert!(
!(m.detectors.is_empty() && m.flips_observable),
"d={d} hook={hook}: undetectable mechanism flips the observable"
);
assert!(
!m.detectors.is_empty(),
"d={d} hook={hook}: a mechanism with no detectors should have been dropped"
);
}
}
}
}
#[test]
fn dem_text_is_wellformed() {
let code = CssCode::surface(3);
let cfg = CircuitConfig::from_p(2, 0.002, 0.002, 0.001);
let dem = to_dem(&code, &cfg, 4).unwrap();
let n_det = 3 * code.checks.len(); assert_eq!(dem.lines().filter(|l| l.starts_with("detector(")).count(), n_det);
let errs: Vec<&str> = dem.lines().filter(|l| l.starts_with("error(")).collect();
assert!(!errs.is_empty());
for l in &errs {
let p: f64 = l[6..l.find(')').unwrap()].parse().expect("probability parses");
assert!(p > 0.0 && p < 1.0, "probability {p} out of range in {l}");
assert!(l.contains(" D"), "mechanism with no detectors: {l}");
for tok in l.split_whitespace().skip(1) {
let idx: u32 = tok.trim_start_matches(['D', 'L']).parse().expect("target index");
if tok.starts_with('D') {
assert!((idx as usize) < n_det, "detector {idx} out of range");
} else {
assert_eq!(idx, 0, "only one observable is defined");
}
}
}
assert!(dem.contains("logical") || dem.contains("L0"), "no observable referenced");
}
#[test]
fn dem_round_trips() {
for d in [3usize, 5] {
let code = CssCode::surface(d);
let cfg = CircuitConfig::from_p(2, 0.002, 0.003, 0.0);
let text = to_dem(&code, &cfg, d + 1).unwrap();
let parsed = from_dem(&text).expect("our own output must parse");
let native = dem_mechanisms(&code, &cfg, d + 1).unwrap();
assert_eq!(parsed.mechanisms.len(), native.len(), "d={d}: mechanism count");
assert_eq!(parsed.mechanisms, native, "d={d}: mechanisms changed through the text");
assert_eq!(parsed.num_detectors, (cfg.rounds as usize + 1) * code.checks.len());
}
}
#[test]
fn decoding_through_the_dem_matches_the_native_decoder() {
for d in [3usize, 5] {
let code = CssCode::surface(d);
let cfg = CircuitConfig::from_p(d as u32, 0.01, 0.01, 0.0);
let phen = PhenomConfig { rounds: cfg.rounds, p_data_fx: cfg.p_data_fx, q_meas_fx: cfg.q_meas_fx };
let model = from_dem(&to_dem(&code, &cfg, d + 1).unwrap()).unwrap();
let logical = logical_z_support(&code, d + 1).unwrap();
let m = code.checks.len();
let n_det = (cfg.rounds as usize + 1) * m;
let (mut native_fail, mut dem_fail) = (0u32, 0u32);
let trials = 600u32;
for tix in 0..trials {
let seed = (tix as u64).wrapping_add(7).wrapping_mul(0x9E37_79B9_7F4A_7C15);
let r = decode_phenomenological(&code, &phen, seed).unwrap();
if !r.logical_success {
native_fail += 1;
}
let mut bits = vec![false; n_det];
for &dd in &r.detectors {
bits[dd as usize] = true;
}
let truth = r.data_error.iter().filter(|q| logical.contains(&(**q as usize))).count() % 2 == 1;
let pred = decode_dem(&model, &bits).unwrap().observable_flipped;
if pred != truth {
dem_fail += 1;
}
}
let (a, b) = (native_fail as f64 / trials as f64, dem_fail as f64 / trials as f64);
assert!(
b <= a + 0.02,
"d={d}: decoding through the DEM ({b}) lost accuracy vs native ({a})"
);
}
}
#[test]
fn dem_ingest_refuses_what_it_cannot_honour() {
let hyper = "error(0.001) D0 D1 D2\n";
let model = from_dem(hyper).unwrap();
let e = decode_dem(&model, &[false; 3]).unwrap_err();
assert!(e.contains("three or more") || e.contains("at most two"), "{e}");
assert!(from_dem("repeat 5 {\n").unwrap_err().contains("unsupported"));
assert!(from_dem("error(2.0) D0\n").unwrap_err().contains("outside"));
assert!(from_dem("error(0.1) X3\n").unwrap_err().contains("unexpected target"));
}
#[test]
fn ingests_a_hand_written_dem() {
let src = "\
# hand written
detector(0, 0) D0
detector(1, 0) D1
error(0.01) D0 D1
error(0.02) D0 L0
error(0.02) D1 L0
";
let model = from_dem(src).expect("parses");
assert_eq!(model.num_detectors, 2);
assert_eq!(model.mechanisms.len(), 3);
let r = decode_dem(&model, &[true, true]).unwrap();
assert!(!r.observable_flipped, "the D0-D1 mechanism should explain it");
let r = decode_dem(&model, &[true, false]).unwrap();
assert!(r.observable_flipped);
}
#[test]
#[ignore]
fn probe_perf() {
use std::time::Instant;
println!("\n decoder throughput (surface code, p=0.01)");
for d in [3usize, 5, 7, 9, 11] {
let code = CssCode::surface(d);
let t0 = Instant::now();
let (trials, _) = benchmark_uf(&code, 0.01, 500, 11);
let el = t0.elapsed();
println!(" d={d:<3} n={:<4} checks={:<4} {:>8.1} shots/s ({:?}/shot)",
code.n, code.checks.len(),
trials as f64 / el.as_secs_f64(), el / trials);
}
println!("\n space-time decoder (d rounds, p=q=0.01)");
for d in [3usize, 5, 7] {
let code = CssCode::surface(d);
let cfg = PhenomConfig::from_p(d as u32, 0.01, 0.01);
let t0 = Instant::now();
let (trials, _) = benchmark_phenomenological(&code, &cfg, 200, 11);
let el = t0.elapsed();
println!(" d={d:<3} detectors={:<5} {:>8.1} shots/s", (d + 1) * code.checks.len(),
trials as f64 / el.as_secs_f64());
}
println!("\n code construction + distance verification");
for d in [3usize, 5] {
let t0 = Instant::now(); let c = CssCode::surface(d); let build = t0.elapsed();
let t1 = Instant::now(); let dd = x_distance(&c, d + 1); let dist = t1.elapsed();
println!(" d={d}: build {build:?}, distance {dd:?} in {dist:?}");
}
}
#[test]
#[ignore]
fn probe_dem_equivalence() {
println!("\n same shots, decoded natively vs through the exported DEM");
println!(" d p native via DEM");
for d in [3usize, 5] {
for &pp in &[0.005f64, 0.01, 0.02] {
let code = CssCode::surface(d);
let cfg = CircuitConfig::from_p(d as u32, pp, pp, 0.0);
let phen = PhenomConfig { rounds: cfg.rounds, p_data_fx: cfg.p_data_fx, q_meas_fx: cfg.q_meas_fx };
let model = from_dem(&to_dem(&code, &cfg, d + 1).unwrap()).unwrap();
let logical = logical_z_support(&code, d + 1).unwrap();
let n_det = (cfg.rounds as usize + 1) * code.checks.len();
let (mut a, mut b) = (0u32, 0u32);
let trials = 1500u32;
for tix in 0..trials {
let seed = (tix as u64).wrapping_add(7).wrapping_mul(0x9E37_79B9_7F4A_7C15);
let r = decode_phenomenological(&code, &phen, seed).unwrap();
if !r.logical_success { a += 1; }
let mut bits = vec![false; n_det];
for &dd in &r.detectors { bits[dd as usize] = true; }
let truth = r.data_error.iter().filter(|q| logical.contains(&(**q as usize))).count() % 2 == 1;
if decode_dem(&model, &bits).unwrap().observable_flipped != truth { b += 1; }
}
println!(" {d} {pp:<7} {:<8.4} {:<8.4}", a as f64/trials as f64, b as f64/trials as f64);
}
}
}
#[test]
#[ignore]
fn probe_print_dem() {
let code = CssCode::surface(3);
let cfg = CircuitConfig::from_p(1, 0.002, 0.002, 0.001);
let dem = to_dem(&code, &cfg, 4).unwrap();
for l in dem.lines().take(22) { println!("{l}"); }
println!("... ({} lines total)", dem.lines().count());
}
#[test]
#[ignore]
fn probe_dem_shapes() {
let code = CssCode::surface(5);
let cfg = CircuitConfig::from_p(2, 0.001, 0.001, 0.001);
let mechs = dem_mechanisms(&code, &cfg, 6).unwrap();
let mut hist = std::collections::BTreeMap::new();
for m in &mechs { *hist.entry(m.detectors.len()).or_insert(0u32) += 1; }
println!("\n detector-set size histogram: {hist:?}");
let empty = mechs.iter().filter(|m| m.detectors.is_empty()).count();
println!(" mechanisms with NO detectors: {empty} (of {})", mechs.len());
let empty_obs = mechs.iter().filter(|m| m.detectors.is_empty() && m.flips_observable).count();
println!(" empty AND flips observable (would be a silent logical): {empty_obs}");
println!(" X stabilizer weights: {:?}", {
let mut w: Vec<usize> = code.stabs.iter().map(|s| s.len()).collect(); w.sort_unstable(); w.dedup(); w });
for stab in code.stabs.iter().take(3) {
print!(" stab {stab:?}: ");
for j in 0..stab.len() {
let qs = &stab[j..];
let mut set: Vec<usize> = Vec::new();
for &q in qs {
for (ci, chk) in code.checks.iter().enumerate() {
if chk.contains(&q) {
if let Some(pos) = set.iter().position(|&x| x == ci) { set.remove(pos); } else { set.push(ci); }
}
}
}
print!("j={j}->{} ", set.len());
}
println!();
}
}
#[test]
#[ignore]
fn probe_circuit_level() {
println!("\n hook=0 must reproduce phenomenological exactly");
for &pp in &[0.005f64, 0.02] {
for d in [3usize, 5] {
let ph = PhenomConfig::from_p(d as u32, pp, pp);
let cl = CircuitConfig::from_p(d as u32, pp, pp, 0.0);
let (_, a) = benchmark_phenomenological(&CssCode::surface(d), &ph, 800, 11);
let (_, b) = benchmark_circuit_level(&CssCode::surface(d), &cl, 800, 11);
println!(" p={pp} d={d}: phenom {a} circuit(hook=0) {b} {}",
if a == b { "IDENTICAL" } else { "DIFFER" });
}
}
println!("\n hook errors lower the threshold (surface code, q=p, hook=p)");
println!(" p d=3 d=5 d=7");
for &pp in &[0.001f64, 0.002, 0.005, 0.01] {
let r = |d: usize| {
let cfg = CircuitConfig::from_p(d as u32, pp, pp, pp);
let (t, f) = benchmark_circuit_level(&CssCode::surface(d), &cfg, 1200, 11);
f as f64 / t as f64
};
println!(" {pp:<8} {:<9.4} {:<9.4} {:<9.4}", r(3), r(5), r(7));
}
println!("\n same p, hooks off vs on (d=5)");
for &pp in &[0.002f64, 0.005] {
let off = { let c=CircuitConfig::from_p(5,pp,pp,0.0); let (t,f)=benchmark_circuit_level(&CssCode::surface(5),&c,1200,11); f as f64/t as f64 };
let on = { let c=CircuitConfig::from_p(5,pp,pp,pp); let (t,f)=benchmark_circuit_level(&CssCode::surface(5),&c,1200,11); f as f64/t as f64 };
println!(" p={pp:<7} hooks off {:<8.4} hooks on {:<8.4}", off, on);
}
}
#[test]
#[ignore]
fn probe_phenomenological() {
println!("\n surface code, phenomenological noise (data p, measurement q=p), d rounds");
println!(" p d=3 d=5 d=7");
for &pp in &[0.001f64, 0.003, 0.005, 0.01, 0.02] {
let r = |d: usize| {
let cfg = PhenomConfig::from_p(d as u32, pp, pp);
let (t, f) = benchmark_phenomenological(&CssCode::surface(d), &cfg, 1200, 11);
f as f64 / t as f64
};
println!(" {pp:<8} {:<9.4} {:<9.4} {:<9.4}", r(3), r(5), r(7));
}
println!("\n sanity: q=0 (perfect measurement) should track the single-shot decoder");
for &pp in &[0.005f64, 0.02] {
let st = |d: usize| {
let cfg = PhenomConfig::from_p(1, pp, 0.0);
let (t, f) = benchmark_phenomenological(&CssCode::surface(d), &cfg, 1200, 11);
f as f64 / t as f64
};
let ss = |d: usize| { let (t,f)=benchmark_uf(&CssCode::surface(d), pp, 1200, 11); f as f64/t as f64 };
println!(" p={pp:<7} d=3 spacetime {:<8.4} single-shot {:<8.4} | d=5 spacetime {:<8.4} single-shot {:<8.4}",
st(3), ss(3), st(5), ss(5));
}
}
#[test]
#[ignore]
fn probe_union_find_vs_bp() {
println!("\n surface code — logical failure rate");
println!(" p d=3 BP d=3 UF d=5 BP d=5 UF d=7 BP d=7 UF");
for &pp in &[0.001f64, 0.005, 0.01, 0.02, 0.05] {
let bp = |d: usize| {
let r = benchmark(&CssCode::surface(d), pp, 2000, 11, 16);
r.relay_logical_failures as f64 / r.trials as f64
};
let uf = |d: usize| {
let (t, f) = benchmark_uf(&CssCode::surface(d), pp, 2000, 11);
f as f64 / t as f64
};
println!(" {pp:<8} {:<9.4} {:<9.4} {:<9.4} {:<9.4} {:<9.4} {:<9.4}",
bp(3), uf(3), bp(5), uf(5), bp(7), uf(7));
}
println!("\n toric code — UF");
for &pp in &[0.005f64, 0.02] {
let uf = |l: usize| { let (t,f)=benchmark_uf(&CssCode::toric(l), pp, 2000, 11); f as f64/t as f64 };
println!(" p={pp:<7} L=3 {:<8.4} L=5 {:<8.4}", uf(3), uf(5));
}
}
#[test]
fn toric_code_shape() {
let c = CssCode::toric(5);
assert_eq!(c.n, 50);
assert_eq!(c.checks.len(), 25);
assert_eq!(c.k, 2, "toric code encodes 2 logical qubits");
assert!(c.checks.iter().all(|r| r.len() == 4));
}
#[test]
fn gross_code_is_72_12() {
let c = CssCode::gross();
assert_eq!(c.n, 72);
assert_eq!(c.k, 12, "the gross-style BB code encodes 12 logical qubits");
assert!(c.checks.iter().all(|r| r.len() == 6));
}
#[test]
fn css_orthogonality_gross() {
let c = CssCode::gross();
let hx = CssCode::bivariate_bicycle(6, 6, &[(3, 0), (0, 1), (0, 2)], &[(0, 3), (1, 0), (2, 0)]);
for zc in &c.checks {
let zset: std::collections::HashSet<usize> = zc.iter().copied().collect();
for xs in raw_hx(&hx) {
let overlap = xs.iter().filter(|q| zset.contains(q)).count();
assert_eq!(overlap % 2, 0, "CSS orthogonality violated");
}
}
}
fn raw_hx(_c: &CssCode) -> Vec<Vec<usize>> {
let (l, m) = (6usize, 6usize);
let a = [(3usize, 0usize), (0, 1), (0, 2)];
let b = [(0usize, 3usize), (1, 0), (2, 0)];
let lm = l * m;
let cell = |i: usize, j: usize| (i % l) * m + (j % m);
let build = |monos: &[(usize, usize)]| -> Vec<Vec<usize>> {
let mut rows = vec![Vec::new(); lm];
for i in 0..l {
for j in 0..m {
let col = cell(i, j);
for &(px, py) in monos {
rows[cell(i + px, j + py)].push(col);
}
}
}
rows
};
let ar = build(&a);
let br = build(&b);
(0..lm)
.map(|r| {
let mut row = ar[r].clone();
row.extend(br[r].iter().map(|&c| c + lm));
row.sort_unstable();
row
})
.collect()
}
#[test]
fn decode_recovers_low_weight_errors() {
let c = CssCode::toric(5);
let cfg = DecodeConfig::from_p(0.02);
let mut fails = 0;
for s in 0..200u64 {
if !decode_once(&c, &cfg, s.wrapping_mul(0x9E37_79B9)).logical_success {
fails += 1;
}
}
assert!(fails < 20, "too many logical failures at p=0.02: {fails}/200");
}
#[test]
fn decode_is_deterministic() {
let c = CssCode::gross();
let cfg = DecodeConfig::from_p(0.03);
let a = decode_once(&c, &cfg, 12345);
let b = decode_once(&c, &cfg, 12345);
assert_eq!(a.correction, b.correction);
assert_eq!(a.messages, b.messages);
assert_eq!(a.legs, b.legs);
}
#[test]
fn relay_beats_plain_bp() {
let c = CssCode::gross();
let bench = benchmark(&c, 0.04, 150, 0xBEEF, 12);
assert!(
bench.relay_logical_failures <= bench.plain_logical_failures,
"relay {} must not exceed plain {}",
bench.relay_logical_failures, bench.plain_logical_failures
);
}
#[test]
fn decode_seals_verifying_receipt() {
let c = CssCode::gross();
let cfg = DecodeConfig::from_p(0.03);
let r = decode_once(&c, &cfg, 7);
let rec = r.seal(&key(1), "did:key:lab", 500_000, GrantRef::unbounded("quantum.decode"));
assert!(rec.verify());
assert!(rec.correction_matches(&r.correction_bytes()));
assert_eq!(rec.code_id, "bb:[[72,12]]");
assert_eq!(rec.work_messages, r.messages);
}
}