From 83fc4d27aab0ae657363d724636652c7034f53fd Mon Sep 17 00:00:00 2001 From: Jason Han Date: Tue, 24 Nov 2026 19:56:36 -0600 Subject: [PATCH] feat: added code definition in Rust --- Cargo.lock | 8 + Cargo.toml | 1 + crates/ppvm-code/Cargo.toml | 12 + crates/ppvm-code/src/lib.rs | 337 ++++++++++++++++++++++++++ crates/ppvm-code/src/readout.rs | 106 ++++++++ crates/ppvm-python-native/Cargo.toml | 1 + crates/ppvm-python-native/src/code.rs | 139 +++++++++++ crates/ppvm-python-native/src/lib.rs | 4 + ppvm-python/README.md | 31 +++ ppvm-python/pyproject.toml | 1 + ppvm-python/src/ppvm/__init__.py | 1 + ppvm-python/src/ppvm/_core.pyi | 33 +++ ppvm-python/src/ppvm/code.py | 281 +++++++++++++++++++++ ppvm-python/test/test_code.py | 151 ++++++++++++ ppvm-python/uv.lock | 2 + 15 files changed, 1108 insertions(+) create mode 100644 crates/ppvm-code/Cargo.toml create mode 100644 crates/ppvm-code/src/lib.rs create mode 100644 crates/ppvm-code/src/readout.rs create mode 100644 crates/ppvm-python-native/src/code.rs create mode 100644 ppvm-python/src/ppvm/code.py create mode 100644 ppvm-python/test/test_code.py diff --git a/Cargo.lock b/Cargo.lock index d907095d9..f6b1dc05a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2185,6 +2185,13 @@ dependencies = [ "ratatui", ] +[[package]] +name = "ppvm-code" +version = "0.4.1" +dependencies = [ + "ppvm-pauli-kernels", +] + [[package]] name = "ppvm-lindblad" version = "0.4.1" @@ -2285,6 +2292,7 @@ dependencies = [ "num", "numpy", "paste", + "ppvm-code", "ppvm-lindblad", "ppvm-pauli-sum", "ppvm-stim", diff --git a/Cargo.toml b/Cargo.toml index ad216df51..8448fce52 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,6 +12,7 @@ ppvm-sym = { version = "0.4.1", path = "crates/ppvm-sym" } [workspace] members = [ + "crates/ppvm-code", "crates/ppvm-traits", "crates/ppvm-pauli-word", "crates/ppvm-pauli-sum", diff --git a/crates/ppvm-code/Cargo.toml b/crates/ppvm-code/Cargo.toml new file mode 100644 index 000000000..fc1e463f6 --- /dev/null +++ b/crates/ppvm-code/Cargo.toml @@ -0,0 +1,12 @@ +# SPDX-FileCopyrightText: 2026 The PPVM Authors +# SPDX-License-Identifier: Apache-2.0 +[package] +name = "ppvm-code" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +publish = false + +[dependencies] +ppvm-pauli-kernels = { path = "../ppvm-pauli-kernels" } diff --git a/crates/ppvm-code/src/lib.rs b/crates/ppvm-code/src/lib.rs new file mode 100644 index 000000000..c499c6407 --- /dev/null +++ b/crates/ppvm-code/src/lib.rs @@ -0,0 +1,337 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! Qubit stabilizer codes defined by signed Hermitian Pauli generators. +mod readout; +pub use readout::Parity; + +use ppvm_pauli_kernels::row_product; +use std::{fmt, sync::OnceLock}; + +/// A signed Hermitian Pauli row. Site zero is the leftmost letter. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Row { + n: usize, + x: Vec, + z: Vec, + negative: bool, +} + +impl Row { + fn identity(n: usize) -> Self { + let words = n.div_ceil(64); + Self { + n, + x: vec![0; words], + z: vec![0; words], + negative: false, + } + } + + /// Build a row from equal-length binary X/Z planes; (1,1) is Hermitian Y. + pub fn from_bits(xs: &[bool], zs: &[bool], negative: bool) -> Result { + if xs.len() != zs.len() { + return Err("X and Z rows must have equal width".into()); + } + let mut row = Self::identity(xs.len()); + row.negative = negative; + for (i, (&x, &z)) in xs.iter().zip(zs).enumerate() { + row.x[i / 64] |= u64::from(x) << (i % 64); + row.z[i / 64] |= u64::from(z) << (i % 64); + } + Ok(row) + } + + fn bit(&self, column: usize) -> bool { + let (plane, i) = if column < self.n { + (&self.x, column) + } else { + (&self.z, column - self.n) + }; + plane[i / 64] >> (i % 64) & 1 != 0 + } + + fn set(&mut self, column: usize) { + let (plane, i) = if column < self.n { + (&mut self.x, column) + } else { + (&mut self.z, column - self.n) + }; + plane[i / 64] |= 1 << (i % 64); + } + + // Call only on equal-width rows. + fn anticommutes(&self, other: &Self) -> bool { + let mut parity = 0; + for i in 0..self.x.len() { + parity ^= (self.x[i] & other.z[i]) ^ (self.z[i] & other.x[i]); + } + parity.count_ones() % 2 == 1 + } + + fn multiply_check(&mut self, other: &Self) { + let phase = row_product(&mut self.x, &mut self.z, &other.x, &other.z); + debug_assert!(phase == 0 || phase == 2); + self.negative ^= other.negative ^ (phase == 2); + } + + // Only binary representatives matter when choosing a new logical basis. + fn add_support(&mut self, other: &Self) { + for i in 0..self.x.len() { + self.x[i] ^= other.x[i]; + self.z[i] ^= other.z[i]; + } + } +} + +impl std::str::FromStr for Row { + type Err = String; + fn from_str(text: &str) -> Result { + let letters = text.strip_prefix(['+', '-']).unwrap_or(text); + let mut row = Row::identity(letters.len()); + row.negative = text.starts_with('-'); + for (i, letter) in letters.bytes().enumerate() { + match letter { + b'I' | b'_' => (), + b'X' => row.set(i), + b'Z' => row.set(row.n + i), + b'Y' => { + row.set(i); + row.set(row.n + i); + } + _ => return Err(format!("invalid signed Pauli {text:?} at site {i}")), + } + } + Ok(row) + } +} + +impl fmt::Display for Row { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(if self.negative { "-" } else { "+" })?; + for i in 0..self.n { + f.write_str(match (self.bit(i), self.bit(self.n + i)) { + (false, false) => "I", + (true, false) => "X", + (false, true) => "Z", + (true, true) => "Y", + })?; + } + Ok(()) + } +} + +/// The joint +1 eigenspace of the supplied signed generators. +#[derive(Clone, Debug)] +pub struct Code { + n: usize, + checks: Vec, + independent: Vec, + // A reduced basis keyed by leading column. Also used to find the centralizer. + pivots: Vec<(usize, Row)>, + logicals: OnceLock>, +} + +impl Code { + /// Preserve all input checks in order, including consistent redundant checks. + pub fn new(n: usize, checks: Vec) -> Result { + if n > usize::MAX / 2 { + return Err("tableau width is too large".into()); + } + let mut pivots: Vec<(usize, Row)> = Vec::new(); + let mut independent = Vec::new(); + for (i, check) in checks.iter().enumerate() { + if check.n != n { + return Err(format!("row {i} has width {}, expected {n}", check.n)); + } + for &j in &independent { + if check.anticommutes(&checks[j]) { + return Err(format!("rows {j} and {i} anticommute")); + } + } + let mut reduced = check.clone(); + for (column, basis) in &pivots { + if reduced.bit(*column) { + reduced.multiply_check(basis); + } + } + if let Some(column) = (0..2 * n).find(|&c| reduced.bit(c)) { + for (_, basis) in &mut pivots { + if basis.bit(column) { + basis.multiply_check(&reduced); + } + } + let pos = pivots.partition_point(|(c, _)| *c < column); + pivots.insert(pos, (column, reduced)); + independent.push(i); + } else if reduced.negative { + return Err(format!( + "row {i} is inconsistent: the generators produce -I" + )); + } + } + Ok(Self { + n, + checks, + independent, + pivots, + logicals: OnceLock::new(), + }) + } + + pub fn n(&self) -> usize { + self.n + } + pub fn k(&self) -> usize { + self.n - self.pivots.len() + } + /// Test signed membership; e.g. a code stabilized by -ZZ excludes +ZZ. + pub fn contains_stabilizer(&self, op: &Row) -> Result { + if op.n != self.n { + return Err("Pauli width must equal code width".into()); + } + if self.pivots.iter().any(|(_, s)| op.anticommutes(s)) { + return Ok(false); + } + let mut row = op.clone(); + for (pivot, basis) in &self.pivots { + if row.bit(*pivot) { + row.multiply_check(basis); + } + } + Ok(!row.negative && row.x.iter().chain(&row.z).all(|&w| w == 0)) + } + + pub fn stabilizers(&self) -> &[Row] { + &self.checks + } + pub fn independent_stabilizers(&self) -> impl Iterator { + self.independent.iter().map(|&i| &self.checks[i]) + } + + /// Deterministic logical X/Z pairs in the centralizer modulo the stabilizers. + pub fn logical_pairs(&self) -> &[(Row, Row)] { + self.logicals.get_or_init(|| self.derive_logicals()) + } + + /// Select a logical convention; commutation modulo the checks guarantees + /// that all 2k representatives are independent modulo the stabilizer group. + pub fn with_logicals(mut self, xs: Vec, zs: Vec) -> Result { + if xs.len() != self.k() || zs.len() != self.k() { + return Err(format!("expected {} logical X/Z pairs", self.k())); + } + for (i, row) in xs.iter().chain(&zs).enumerate() { + if row.n != self.n { + return Err(format!("logical row {i} has incorrect width")); + } + if self.pivots.iter().any(|(_, s)| s.anticommutes(row)) { + return Err(format!("logical row {i} anticommutes with a stabilizer")); + } + } + for i in 0..xs.len() { + for j in 0..xs.len() { + if xs[i].anticommutes(&xs[j]) + || zs[i].anticommutes(&zs[j]) + || xs[i].anticommutes(&zs[j]) != (i == j) + { + return Err(format!( + "invalid commutation between logical operators at indices {i} and {j}" + )); + } + } + } + self.logicals = OnceLock::from(xs.into_iter().zip(zs).collect::>()); + Ok(self) + } + + fn derive_logicals(&self) -> Vec<(Row, Row)> { + if self.k() == 0 { + return Vec::new(); + } + let n = self.n; + // Null vectors of [X|Z] are centralizing Paulis after swapping X and Z. + let swap = |c: usize| if c < n { c + n } else { c - n }; + let mut space = Vec::new(); + for free in 0..2 * n { + if self.pivots.binary_search_by_key(&free, |(p, _)| *p).is_ok() { + continue; + } + let mut row = Row::identity(n); + row.set(swap(free)); + for (pivot, equation) in &self.pivots { + if equation.bit(free) { + row.set(swap(*pivot)); + } + } + space.push(row); + } + // Symplectic Gram-Schmidt. Unpaired rows are in the stabilizer span. + let mut pairs = Vec::with_capacity(self.k()); + while let Some(x) = space.pop() { + let Some(i) = space.iter().position(|r| x.anticommutes(r)) else { + continue; + }; + let z = space.remove(i); + for r in &mut space { + let toggle_z = r.anticommutes(&x); + let toggle_x = r.anticommutes(&z); + if toggle_z { + r.add_support(&z); + } + if toggle_x { + r.add_support(&x); + } + } + pairs.push((x, z)); + } + debug_assert_eq!(pairs.len(), self.k()); + pairs + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn code(checks: &[&str]) -> Result { + Code::new( + checks[0].len() - 1, + checks.iter().map(|s| s.parse()).collect::>()?, + ) + } + + #[test] + fn signed_dependencies() { + let good = code(&["+XX", "+ZZ", "-YY", "+II"]).unwrap(); + assert_eq!((good.n(), good.k(), good.stabilizers().len()), (2, 0, 4)); + assert!(code(&["+XX", "+ZZ", "+YY"]).unwrap_err().contains("-I")); + assert!(code(&["+II", "-II"]).is_err()); + assert!(code(&["+XZ", "+ZZ"]).is_err()); + } + + #[test] + fn perfect_five_logicals() { + let c = code(&["+XZZXI", "+IXZZX", "+XIXZZ", "+ZXIXZ"]).unwrap(); + let pairs = c.logical_pairs(); + assert_eq!(pairs.len(), 1); + let (x, z) = &pairs[0]; + assert!(x.anticommutes(z)); + assert!( + c.checks + .iter() + .all(|s| !s.anticommutes(x) && !s.anticommutes(z)) + ); + } + + #[test] + fn logical_pairs_across_storage_words() { + let n = 65; + let mut g = Row::identity(n); + g.set(0); + g.set(n - 1); + let c = Code::new(n, vec![g]).unwrap(); + let (xs, zs) = c.logical_pairs().iter().cloned().unzip(); + assert_eq!(c.k(), 64); + c.with_logicals(xs, zs).unwrap(); + } +} diff --git a/crates/ppvm-code/src/readout.rs b/crates/ppvm-code/src/readout.rs new file mode 100644 index 000000000..b2246ac40 --- /dev/null +++ b/crates/ppvm-code/src/readout.rs @@ -0,0 +1,106 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +use crate::{Code, Row}; + +/// A parity of single-qubit measurement bits, XORed with a fixed offset. +#[derive(Debug, PartialEq, Eq)] +pub struct Parity { + pub qubits: Vec, + pub offset: bool, +} + +impl Row { + fn incompatible(&self, i: usize, axis: u8) -> bool { + let x = self.bit(i); + let z = self.bit(self.n + i); + match axis { + b'X' => z, + b'Z' => x, + b'Y' => x ^ z, + _ => unreachable!("validated measurement axis"), + } + } + + fn parity(&self) -> Parity { + Parity { + qubits: (0..self.n) + .filter(|&i| self.bit(i) || self.bit(self.n + i)) + .collect(), + offset: self.negative, + } + } +} + +impl Code { + /// Derive deterministic terminal checks and logical parities. Axes are in + /// physical-qubit order. Logical axes are in logical order; I skips a slot. + /// Each resulting detector is zero on an ideal shot from the codespace. + pub fn terminal_readout( + &self, + axes: &[u8], + logical_axes: &[u8], + ) -> Result<(Vec, Vec), String> { + if axes.len() != self.n || !axes.iter().all(|b| b"XYZ".contains(b)) { + return Err("supply one X, Y or Z measurement axis for every physical qubit".into()); + } + if logical_axes.len() != self.k() || !logical_axes.iter().all(|b| b"IXYZ".contains(b)) { + return Err("supply one X, Y, Z or I (skip) for every logical qubit".into()); + } + // Eliminate components that anticommute with a local readout axis, + // carrying the signed physical row alongside the projected pivot. + let mut pivots: Vec<(usize, Row)> = Vec::new(); + let mut detectors = Vec::new(); + for check in self.independent_stabilizers() { + let mut row = check.clone(); + reduce(&mut row, axes, &pivots); + if let Some(i) = axes + .iter() + .enumerate() + .position(|(i, &a)| row.incompatible(i, a)) + { + let pos = pivots.partition_point(|(c, _)| *c < i); + pivots.insert(pos, (i, row)); + } else { + detectors.push(row.parity()); + } + } + + let mut observables = Vec::new(); + for (i, (&axis, (x, z))) in logical_axes.iter().zip(self.logical_pairs()).enumerate() { + let mut row = match axis { + b'X' => x.clone(), + b'Z' => z.clone(), + b'Y' => { + // Logical Y = i X Z in the signed logical convention. + let mut y = x.clone(); + let phase = ppvm_pauli_kernels::row_product(&mut y.x, &mut y.z, &z.x, &z.z); + y.negative ^= z.negative ^ ((phase + 1) % 4 == 2); + y + } + _ => continue, + }; + reduce(&mut row, axes, &pivots); + if axes + .iter() + .enumerate() + .any(|(i, &a)| row.incompatible(i, a)) + { + return Err(format!( + "logical {} at index {i} is inaccessible in this readout", + char::from(axis) + )); + } + observables.push(row.parity()); + } + Ok((detectors, observables)) + } +} + +fn reduce(row: &mut Row, axes: &[u8], pivots: &[(usize, Row)]) { + for (i, p) in pivots { + if row.incompatible(*i, axes[*i]) { + row.multiply_check(p); + } + } +} diff --git a/crates/ppvm-python-native/Cargo.toml b/crates/ppvm-python-native/Cargo.toml index 2c6b986cc..1267a6d8d 100644 --- a/crates/ppvm-python-native/Cargo.toml +++ b/crates/ppvm-python-native/Cargo.toml @@ -15,6 +15,7 @@ crate-type = ["cdylib"] test = false [dependencies] +ppvm-code = { path = "../ppvm-code" } bnum = "0.13.0" # mimalloc reduces peak RSS for the allocation-heavy adaptive-Pauli (lindblad) # paths; installed as the global allocator in lib.rs. diff --git a/crates/ppvm-python-native/src/code.rs b/crates/ppvm-python-native/src/code.rs new file mode 100644 index 000000000..b7eabe6d7 --- /dev/null +++ b/crates/ppvm-python-native/src/code.rs @@ -0,0 +1,139 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +use numpy::{PyReadonlyArray1, PyReadonlyArray2}; +use ppvm_code::{Code, Row}; +use pyo3::{exceptions::PyValueError, prelude::*}; + +type IndexedParities = Vec<(Vec, bool)>; + +#[pyclass(frozen, module = "ppvm._core")] +pub struct CodeSpec(Code); + +fn parse(rows: Vec) -> PyResult> { + rows.iter() + .map(|row| row.parse().map_err(PyValueError::new_err)) + .collect() +} + +#[pymethods] +impl CodeSpec { + #[new] + #[pyo3(signature = (n, stabilizers, logical_xs=None, logical_zs=None))] + fn new( + n: usize, + stabilizers: Vec, + logical_xs: Option>, + logical_zs: Option>, + ) -> PyResult { + let code = Code::new(n, parse(stabilizers)?).map_err(PyValueError::new_err)?; + Self::finish(code, logical_xs, logical_zs) + } + + #[staticmethod] + #[pyo3(signature = (xs, zs, signs, logical_xs=None, logical_zs=None))] + fn from_tableau( + xs: PyReadonlyArray2<'_, bool>, + zs: PyReadonlyArray2<'_, bool>, + signs: PyReadonlyArray1<'_, bool>, + logical_xs: Option>, + logical_zs: Option>, + ) -> PyResult { + let x = xs.as_array(); + let z = zs.as_array(); + let signs = signs.as_array(); + if x.dim() != z.dim() || signs.len() != x.nrows() { + return Err(PyValueError::new_err( + "expected matching X/Z matrices and one sign per row", + )); + } + let mut rows = Vec::with_capacity(x.nrows()); + for ((xr, zr), &sign) in x.rows().into_iter().zip(z.rows()).zip(signs) { + rows.push( + Row::from_bits(&xr.to_vec(), &zr.to_vec(), sign).map_err(PyValueError::new_err)?, + ); + } + let code = Code::new(x.ncols(), rows).map_err(PyValueError::new_err)?; + Self::finish(code, logical_xs, logical_zs) + } + + fn contains_stabilizer(&self, op: &str) -> PyResult { + let row = op.parse().map_err(PyValueError::new_err)?; + self.0 + .contains_stabilizer(&row) + .map_err(PyValueError::new_err) + } + + fn terminal_readout( + &self, + axes: &str, + logical_axes: &str, + ) -> PyResult<(IndexedParities, IndexedParities)> { + let (checks, obs) = self + .0 + .terminal_readout(axes.as_bytes(), logical_axes.as_bytes()) + .map_err(PyValueError::new_err)?; + let pack = + |rows: Vec| rows.into_iter().map(|p| (p.qubits, p.offset)).collect(); + Ok((pack(checks), pack(obs))) + } + + #[getter] + fn n(&self) -> usize { + self.0.n() + } + #[getter] + fn k(&self) -> usize { + self.0.k() + } + #[getter] + fn stabilizers(&self) -> Vec { + self.0 + .stabilizers() + .iter() + .map(ToString::to_string) + .collect() + } + #[getter] + fn independent_stabilizers(&self) -> Vec { + self.0 + .independent_stabilizers() + .map(ToString::to_string) + .collect() + } + #[getter] + fn logical_xs(&self) -> Vec { + self.0 + .logical_pairs() + .iter() + .map(|(x, _)| x.to_string()) + .collect() + } + #[getter] + fn logical_zs(&self) -> Vec { + self.0 + .logical_pairs() + .iter() + .map(|(_, z)| z.to_string()) + .collect() + } +} + +impl CodeSpec { + fn finish( + code: Code, + logical_xs: Option>, + logical_zs: Option>, + ) -> PyResult { + match (logical_xs, logical_zs) { + (None, None) => Ok(Self(code)), + (Some(xs), Some(zs)) => code + .with_logicals(parse(xs)?, parse(zs)?) + .map(Self) + .map_err(PyValueError::new_err), + _ => Err(PyValueError::new_err( + "supply both logical_xs and logical_zs", + )), + } + } +} diff --git a/crates/ppvm-python-native/src/lib.rs b/crates/ppvm-python-native/src/lib.rs index e4f9228c8..c8b5a3064 100644 --- a/crates/ppvm-python-native/src/lib.rs +++ b/crates/ppvm-python-native/src/lib.rs @@ -11,6 +11,7 @@ static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc; use pyo3::exceptions::PyValueError; use pyo3::prelude::*; +pub mod code; pub mod interface; pub mod interface_tableau; pub mod interface_tableau_sum; @@ -39,6 +40,9 @@ pub(crate) fn flat_pairs(targets: &[usize]) -> PyResult> { pub mod _core { // NOTE: it's not possible to use #[pymodule_export] inside a macro_rules! + #[pymodule_export] + pub use crate::code::CodeSpec; + // PauliSum #[pymodule_export] pub use crate::interface::PauliSumIndexMapFxHash0; diff --git a/ppvm-python/README.md b/ppvm-python/README.md index d82402362..32c29a0e4 100644 --- a/ppvm-python/README.md +++ b/ppvm-python/README.md @@ -52,6 +52,37 @@ r1 = tab.measure(1) print(f"Qubit 0: {r0}, Qubit 1: {r1}") # always correlated ``` +### Stabilizer codes + +Define a code by its signed commuting Pauli checks, including checks that mix +X, Y, and Z. The order of letters is physical-qubit order, starting with qubit +zero. Supply logical representatives to select a specific encoding convention. + +```python +from ppvm import Code + +five = Code.from_stabilizers( + ["XZZXI", "IXZZX", "XIXZZ", "ZXIXZ"], + logical_xs=["XXXXX"], logical_zs=["ZZZZZ"], +) +assert (five.n, five.k) == (5, 1) +assert five.state_stabilizers([1])[-1] == "-ZZZZZ" + +# One row of X bits, one row of Z bits, and a minus sign: the -ZZ code. +odd = Code.from_tableau([[0, 0]], [[1, 1]], signs=[1], + logical_xs=["XX"], logical_zs=["ZI"]) +check, = odd.terminal_readout("ZZ").detectors +assert (check.indices, check.offset) == ((0, 1), True) +``` + +`Code.from_css(hx, hz)` accepts separate positive X and Z checks. All constructors +preserve redundant checks and reject inconsistent signs. `encoder_tableau()` +exports a forward Stim tableau with logical inputs last. `synthesize_state_prep()`, +`synthesize_encoder()`, and `synthesize_logical_clifford(logical_tableau)` +return verified Stim circuits for ideal Clifford operations. Terminal readout +covers one Pauli measurement per physical qubit; repeated syndrome rounds need +a separate measurement schedule. + ## Documentation Full documentation is available at the [ppvm docs site](https://queracomputing.github.io/ppvm/). diff --git a/ppvm-python/pyproject.toml b/ppvm-python/pyproject.toml index 3a5bad020..21d699f37 100644 --- a/ppvm-python/pyproject.toml +++ b/ppvm-python/pyproject.toml @@ -26,6 +26,7 @@ dependencies = [ "bloqade-circuit>=0.15.5", "kirin-toolchain~=0.22.2", "numpy>=2.2.6", + "stim>=1.15", "typing-extensions>=4.0", ] diff --git a/ppvm-python/src/ppvm/__init__.py b/ppvm-python/src/ppvm/__init__.py index 7c1b0fa8b..bc7179640 100644 --- a/ppvm-python/src/ppvm/__init__.py +++ b/ppvm-python/src/ppvm/__init__.py @@ -2,6 +2,7 @@ # SPDX-License-Identifier: Apache-2.0 from ._core import StimProgram as StimProgram +from .code import Code as Code from .generalized_tableau import GeneralizedTableau as GeneralizedTableau from .generalized_tableau import MeasurementResult as MeasurementResult from .generalized_tableau import sample_stim as sample_stim diff --git a/ppvm-python/src/ppvm/_core.pyi b/ppvm-python/src/ppvm/_core.pyi index 0edf04d64..86654bd52 100644 --- a/ppvm-python/src/ppvm/_core.pyi +++ b/ppvm-python/src/ppvm/_core.pyi @@ -2,6 +2,39 @@ from collections.abc import Sequence import numpy as np +class CodeSpec: + def contains_stabilizer(self, op: str) -> bool: ... + def terminal_readout( + self, axes: str, logical_axes: str + ) -> tuple[list[tuple[list[int], bool]], list[tuple[list[int], bool]]]: ... + def __init__( + self, + n: int, + stabilizers: list[str], + logical_xs: list[str] | None = ..., + logical_zs: list[str] | None = ..., + ) -> None: ... + @staticmethod + def from_tableau( + xs: np.ndarray, + zs: np.ndarray, + signs: np.ndarray, + logical_xs: list[str] | None = ..., + logical_zs: list[str] | None = ..., + ) -> CodeSpec: ... + @property + def n(self) -> int: ... + @property + def k(self) -> int: ... + @property + def stabilizers(self) -> list[str]: ... + @property + def independent_stabilizers(self) -> list[str]: ... + @property + def logical_xs(self) -> list[str]: ... + @property + def logical_zs(self) -> list[str]: ... + class _PauliSumBase: def __init__( self, diff --git a/ppvm-python/src/ppvm/code.py b/ppvm-python/src/ppvm/code.py new file mode 100644 index 000000000..a9c8e07ae --- /dev/null +++ b/ppvm-python/src/ppvm/code.py @@ -0,0 +1,281 @@ +# SPDX-FileCopyrightText: 2026 The PPVM Authors +# SPDX-License-Identifier: Apache-2.0 + +"""Qubit codes specified by signed stabilizer generators.""" + +from __future__ import annotations + +from collections.abc import Iterable, Sequence +from dataclasses import dataclass +from operator import index +from typing import NamedTuple + +import numpy as np +import stim +from numpy.typing import ArrayLike + +from ._core import CodeSpec + + +def _bits(data: ArrayLike, name: str, ndim: int) -> np.ndarray: + a = np.asarray(data) + if a.ndim != ndim: + raise ValueError(f"{name} must be {ndim}-dimensional") + if a.size and (a.dtype.kind not in "biu" or not np.all((a == 0) | (a == 1))): + raise ValueError(f"{name} must contain binary integers or booleans") + return a.astype(np.bool_, copy=False) + + +def _strings(rows: Iterable[str | stim.PauliString]) -> list[str]: + if isinstance(rows, str): + raise TypeError("supply a sequence of signed Pauli strings, e.g. ['+ZZ']") + strings = [] + for row in rows: + if not isinstance(row, str): + if not isinstance(row, stim.PauliString): + raise TypeError("expected a signed Pauli string or stim.PauliString") + row = str(row) + strings.append(row) + return strings + + +def _synthesize_clifford(target: stim.Tableau) -> stim.Circuit: + circuit = target.to_circuit() + if circuit.to_tableau() != target: + raise RuntimeError("synthesized circuit does not implement the requested Clifford") + return circuit + + +class Parity(NamedTuple): + """XOR the indicated record bits and the offset to evaluate the parity.""" + + indices: tuple[int, ...] + offset: bool + + +class TerminalReadout(NamedTuple): + detectors: tuple[Parity, ...] + observables: tuple[Parity, ...] + + +@dataclass(frozen=True, slots=True, eq=False) +class Code: + """Joint +1 eigenspace of signed, commuting qubit Pauli generators. + + Column zero is qubit zero. Redundant, consistent checks retain their input + order. The default logical basis is deterministic; supply both ordered + logical X and Z lists to use a particular convention. + """ + + _spec: CodeSpec + + @classmethod + def from_stabilizers( + cls, + stabilizers: Iterable[str | stim.PauliString], + *, + n_qubits: int | None = None, + logical_xs: Iterable[str | stim.PauliString] | None = None, + logical_zs: Iterable[str | stim.PauliString] | None = None, + ) -> Code: + """Construct from rows such as '+XZZXI' or '-YY'; I and _ mean identity.""" + rows = _strings(stabilizers) + if n_qubits is None: + if not rows: + raise ValueError("specify n_qubits for an empty generator set") + n_qubits = len(rows[0].removeprefix("+").removeprefix("-")) + n = index(n_qubits) + if n < 0: + raise ValueError("n_qubits must be nonnegative") + return cls( + CodeSpec( + n, + rows, + None if logical_xs is None else _strings(logical_xs), + None if logical_zs is None else _strings(logical_zs), + ) + ) + + @classmethod + def from_tableau( + cls, + xs: ArrayLike, + zs: ArrayLike, + signs: ArrayLike | None = None, + *, + logical_xs: Iterable[str | stim.PauliString] | None = None, + logical_zs: Iterable[str | stim.PauliString] | None = None, + ) -> Code: + """Each row is one check. (x,z)=(1,1) is Y; sign 1 denotes minus.""" + x = _bits(xs, "xs", 2) + z = _bits(zs, "zs", 2) + if x.shape != z.shape: + raise ValueError("xs and zs must have identical shapes") + m = x.shape[0] + negative = np.zeros(m, dtype=bool) if signs is None else _bits(signs, "signs", 1) + if len(negative) != m: + raise ValueError("expected one sign bit per generator") + return cls( + CodeSpec.from_tableau( + x, + z, + negative, + None if logical_xs is None else _strings(logical_xs), + None if logical_zs is None else _strings(logical_zs), + ) + ) + + @classmethod + def from_css( + cls, + hx: ArrayLike, + hz: ArrayLike, + *, + logical_xs: Iterable[str | stim.PauliString] | None = None, + logical_zs: Iterable[str | stim.PauliString] | None = None, + ) -> Code: + """Construct from positive X and Z checks with the same physical-qubit order.""" + x = _bits(hx, "hx", 2) + z = _bits(hz, "hz", 2) + if x.shape[1] != z.shape[1]: + raise ValueError("hx and hz must have the same number of columns") + return cls.from_tableau( + np.vstack((x, np.zeros_like(z))), + np.vstack((np.zeros_like(x), z)), + logical_xs=logical_xs, + logical_zs=logical_zs, + ) + + @property + def n(self) -> int: + """Number of physical qubits.""" + return self._spec.n + + @property + def k(self) -> int: + """Number of encoded qubits (n minus stabilizer rank).""" + return self._spec.k + + @property + def stabilizers(self) -> tuple[str, ...]: + """Original signed checks, including redundant rows.""" + return tuple(self._spec.stabilizers) + + @property + def logical_xs(self) -> tuple[str, ...]: + """Ordered logical X representatives in physical-qubit order.""" + return tuple(self._spec.logical_xs) + + @property + def logical_zs(self) -> tuple[str, ...]: + """Ordered logical Z representatives paired with logical_xs.""" + return tuple(self._spec.logical_zs) + + def state_stabilizers(self, bits: Sequence[int] | None = None) -> tuple[str, ...]: + """Independent signed generators of a logical computational-basis state. + + Defaults to all logical zeros. bits[i] sets the eigenvalue of logical_zs[i]. + """ + signs = np.zeros(self.k, dtype=bool) if bits is None else _bits(bits, "bits", 1) + if len(signs) != self.k: + raise ValueError(f"expected {self.k} logical state bits") + checks = self._spec.independent_stabilizers + for z, toggle in zip(self.logical_zs, signs, strict=True): + checks.append(("-" if z.startswith("+") else "+") + z[1:] if toggle else z) + return tuple(checks) + + def synthesize_state_prep(self, bits: Sequence[int] | None = None) -> stim.Circuit: + """Prepare and verify the signed logical basis state. Returns a Stim circuit.""" + rows = [stim.PauliString(p) for p in self.state_stabilizers(bits)] + return _synthesize_clifford(stim.Tableau.from_stabilizers(rows)) + + def terminal_readout( + self, + bases: str, + *, + order: Sequence[int] | None = None, + logical_bases: str | None = None, + ) -> TerminalReadout: + """Derive parities for destructive single-qubit Pauli measurements. + + bases[q] is the physical X/Y/Z axis on qubit q. order[j] is the qubit + measured into record j (default: identity). logical_bases chooses X, Y or + Z for each logical qubit, or I to skip it; defaults to all Z. Detectors + form an independent basis of measurable stabilizers. Observables are + returned in logical order, using equivalent representatives when needed. + """ + measured = range(self.n) if order is None else [index(q) for q in order] + if sorted(measured) != list(range(self.n)): + raise ValueError("order must be a permutation of the physical qubits") + records = {q: j for j, q in enumerate(measured)} + dets, obs = self._spec.terminal_readout( + bases, "Z" * self.k if logical_bases is None else logical_bases + ) + + def remap(rows): + return tuple( + Parity(tuple(sorted(records[q] for q in support)), sign) for support, sign in rows + ) + + return TerminalReadout(remap(dets), remap(obs)) + + def contains_stabilizer(self, pauli: str | stim.PauliString) -> bool: + """Test membership in the signed stabilizer group, including the phase.""" + return self._spec.contains_stabilizer(_strings([pauli])[0]) + + def encoder_tableau(self) -> stim.Tableau: + """Forward Stim Clifford tableau. The last k inputs carry logical data. + + The first n-k inputs are zero ancillas. Their Z images are the independent + checks, and both Pauli images of every data input use our logical basis. + """ + checks = [stim.PauliString(s) for s in self._spec.independent_stabilizers] + logical_zs = [stim.PauliString(s) for s in self.logical_zs] + logical_xs = [stim.PauliString(s) for s in self.logical_xs] + zs = checks + logical_zs + completion = stim.Tableau.from_stabilizers(zs) + xs = [] + for i in range(len(checks)): + dual = completion.x_output(i) + # Remove overlap with our chosen logical X representatives while + # preserving the dual's commutation with every ancilla check. + for x, z in zip(logical_xs, logical_zs, strict=True): + if not dual.commutes(x): + dual *= z + xs.append(dual) + return stim.Tableau.from_conjugated_generators(xs=xs + logical_xs, zs=zs) + + def synthesize_encoder(self) -> stim.Circuit: + """Return a verified ideal encoding circuit using Stim.""" + return _synthesize_clifford(self.encoder_tableau()) + + def synthesize_logical_clifford(self, logical: stim.Tableau) -> stim.Circuit: + """Return a verified ideal circuit acting as logical on the encoded data. + + Its target is logical decoding, the requested Clifford, then re-encoding. + Fault tolerance requires a separate circuit-level analysis. + """ + return _synthesize_clifford(self._logical_target(logical)) + + def _logical_target(self, logical: stim.Tableau) -> stim.Tableau: + if not isinstance(logical, stim.Tableau) or len(logical) != self.k: + raise ValueError(f"expected a {self.k}-qubit logical stim.Tableau") + encoder = self.encoder_tableau() + lifted = stim.Tableau(self.n) + lifted.append(logical, list(range(self.n - self.k, self.n))) + return encoder.inverse().then(lifted).then(encoder) + + def implements_logical_clifford(self, physical: stim.Tableau, logical: stim.Tableau) -> bool: + """Check a physical Clifford's action on the codespace up to global phase.""" + if not isinstance(physical, stim.Tableau) or len(physical) != self.n: + raise ValueError(f"expected a {self.n}-qubit physical stim.Tableau") + target = self._logical_target(logical) + for check in self._spec.independent_stabilizers: + if not self.contains_stabilizer(physical(stim.PauliString(check))): + return False + for rep in (*self.logical_xs, *self.logical_zs): + p = stim.PauliString(rep) + residual = physical(p) * target(p) + if residual.sign.imag or not self.contains_stabilizer(residual): + return False + return True diff --git a/ppvm-python/test/test_code.py b/ppvm-python/test/test_code.py new file mode 100644 index 000000000..748724c3d --- /dev/null +++ b/ppvm-python/test/test_code.py @@ -0,0 +1,151 @@ +# SPDX-FileCopyrightText: 2026 The PPVM Authors +# SPDX-License-Identifier: Apache-2.0 + +import numpy as np +import pytest + +from ppvm import Code + +FIVE = ("+XZZXI", "+IXZZX", "+XIXZZ", "+ZXIXZ") +STEANE_H = [[1, 1, 1, 1, 0, 0, 0], [0, 1, 1, 0, 1, 1, 0], [0, 0, 1, 1, 1, 0, 1]] + + +def test_non_css_tableau_and_target(): + xs = [[p in "XY" for p in row[1:]] for row in FIVE] + zs = [[p in "ZY" for p in row[1:]] for row in FIVE] + code = Code.from_tableau(xs, zs, logical_xs=["XXXXX"], logical_zs=["ZZZZZ"]) + assert (code.n, code.k, code.stabilizers) == (5, 1, FIVE) + assert code.state_stabilizers() == (*FIVE, "+ZZZZZ") + assert code.state_stabilizers([1]) == (*FIVE, "-ZZZZZ") + + +def test_steane_and_empty_checks(): + code = Code.from_css(STEANE_H, STEANE_H) + assert (code.n, code.k) == (7, 1) + assert len(code.state_stabilizers()) == 7 + empty = np.zeros((0, 3), dtype=bool) + code = Code.from_tableau(empty, empty) + assert (code.n, code.k) == (3, 3) + + +def test_y_sign_and_redundant_rows(): + code = Code.from_tableau([[1, 1], [0, 0], [1, 1]], [[0, 0], [1, 1], [1, 1]], [0, 0, 1]) + assert code.stabilizers == ("+XX", "+ZZ", "-YY") + assert code.state_stabilizers() == ("+XX", "+ZZ") + with pytest.raises(ValueError, match="-I"): + Code.from_stabilizers(["XX", "ZZ", "YY"]) + + +@pytest.mark.parametrize( + ("args", "error"), + [ + (([[2]], [[0]]), "binary"), + (([[1]], [[1, 1]]), "shape"), + (([[1]], [[1]], []), "sign"), + (([[1], [0]], [[0], [1]]), "anticommute"), + ], +) +def test_bad_tableau(args, error): + with pytest.raises(ValueError, match=error): + Code.from_tableau(*args) + + +def test_signed_logical_and_bad_inputs(): + code = Code.from_stabilizers(["-ZZ"], logical_xs=["XX"], logical_zs=["-ZI"]) + assert code.state_stabilizers([1]) == ("-ZZ", "+ZI") + for xs, zs in [(["XI"], ["ZI"]), (["ZZ"], ["IZ"]), ([], [])]: + with pytest.raises(ValueError): + Code.from_stabilizers(["ZZ"], logical_xs=xs, logical_zs=zs) + with pytest.raises(ValueError, match="invalid signed Pauli"): + Code.from_stabilizers(["+iX"]) + + +def test_non_css_logical_one_preparation(): + import stim + + code = Code.from_stabilizers(FIVE, logical_xs=["XXXXX"], logical_zs=["ZZZZZ"]) + circuit = code.synthesize_state_prep([1]) + sim = stim.TableauSimulator() + sim.do_circuit(circuit) + for row in code.state_stabilizers([1]): + assert sim.peek_observable_expectation(stim.PauliString(row)) == 1 + + +def test_terminal_readout_combinations_and_offsets(): + # Neither original check is directly measurable in Y, but their signed + # product -YY is deterministic. + bell = Code.from_stabilizers(["XX", "ZZ"]) + assert bell.terminal_readout("YY").detectors == (((0, 1), True),) + odd = Code.from_stabilizers(["-ZZ"], logical_xs=["XX"], logical_zs=["ZI"]) + readout = odd.terminal_readout("XZ", order=[1, 0]) + # ZI is equivalent to -IZ modulo the signed stabilizer. + assert readout.detectors == () + assert readout.observables == (((0,), True),) + with pytest.raises(ValueError, match="inaccessible"): + odd.terminal_readout("XX") + with pytest.raises(ValueError, match="permutation"): + odd.terminal_readout("ZZ", order=[0, 0]) + one = Code.from_stabilizers([], n_qubits=1, logical_xs=["-X"], logical_zs=["Z"]) + assert one.terminal_readout("Y", logical_bases="Y").observables == (((0,), True),) + + +def test_encoder_tableau_exact_logical_basis(): + import stim + + code = Code.from_stabilizers(["-ZZI"], logical_xs=["-XXI", "IIY"], logical_zs=["ZII", "-IIZ"]) + tab = code.encoder_tableau() + assert [tab.z_output(i) for i in range(3)] == [ + stim.PauliString(s) for s in ("-ZZI", "ZII", "-IIZ") + ] + assert [tab.x_output(i) for i in (1, 2)] == [stim.PauliString(s) for s in code.logical_xs] + + +def test_encoder_and_logical_gadget(): + import stim + + code = Code.from_stabilizers(["-ZZ"], logical_xs=["XX"], logical_zs=["ZI"]) + encoder = stim.Tableau.from_circuit(code.synthesize_encoder()) + assert encoder == code.encoder_tableau() + gadget = code.synthesize_logical_clifford(stim.Tableau.from_named_gate("S")) + physical = stim.Tableau.from_circuit(gadget) + assert physical(stim.PauliString("-ZZ")) == stim.PauliString("-ZZ") + z = stim.PauliString("ZI") + x = stim.PauliString("XX") + assert physical(z) == z + assert physical(x) == 1j * x * z + + +def test_gadget_preserves_group_and_logical_action(): + import stim + + code = Code.from_stabilizers([stim.PauliString("-ZZ")], logical_xs=["XX"], logical_zs=["ZI"]) + assert code.contains_stabilizer("-ZZ") + assert not code.contains_stabilizer("ZZ") + identity = stim.Tableau(1) + assert code.implements_logical_clifford(stim.Tableau(2), identity) + # SWAP preserves the odd-parity code but interchanges its two words. + swap = stim.Tableau.from_named_gate("SWAP") + assert not code.implements_logical_clifford(swap, identity) + assert code.implements_logical_clifford(swap, stim.Tableau.from_named_gate("X")) + + +def test_two_steane_blocks_terminal_readout(): + h = np.array(STEANE_H) + two = np.kron(np.eye(2, dtype=int), h) + support = "XXIIIXI" + xs = [support + "I" * 7, "I" * 7 + support] + code = Code.from_css(two, two, logical_xs=xs, logical_zs=[x.replace("X", "Z") for x in xs]) + layout = list(range(7)) + list(range(13, 6, -1)) + readout = code.terminal_readout("Z" * 14, order=layout) + assert [p.indices for p in readout.detectors] == [ + tuple(sorted(layout.index(q) for q in row.nonzero()[0])) for row in two + ] + assert readout.observables == (((0, 1, 5), False), ((8, 12, 13), False)) + + +def test_idle_wires_survive_synthesis(): + import stim + + code = Code.from_stabilizers([], n_qubits=2, logical_xs=["XI", "IX"], logical_zs=["ZI", "IZ"]) + assert code.synthesize_state_prep().num_qubits == 2 + assert code.synthesize_encoder().to_tableau() == stim.Tableau(2) diff --git a/ppvm-python/uv.lock b/ppvm-python/uv.lock index 1f3585f5f..3ece9f4eb 100644 --- a/ppvm-python/uv.lock +++ b/ppvm-python/uv.lock @@ -82,6 +82,7 @@ dependencies = [ { name = "bloqade-circuit" }, { name = "kirin-toolchain" }, { name = "numpy" }, + { name = "stim" }, { name = "typing-extensions" }, ] @@ -100,6 +101,7 @@ requires-dist = [ { name = "bloqade-circuit", specifier = ">=0.15.5" }, { name = "kirin-toolchain", specifier = "~=0.22.2" }, { name = "numpy", specifier = ">=2.2.6" }, + { name = "stim", specifier = ">=1.15" }, { name = "typing-extensions", specifier = ">=4.0" }, ]