diff --git a/Cargo.lock b/Cargo.lock index 9b47df896..da14fb117 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2250,6 +2250,7 @@ dependencies = [ "ppvm-pauli-sum", "ppvm-pauli-word-2", "ppvm-phased-pauli-word-2", + "ppvm-tableau-2", "ppvm-traits-2", ] diff --git a/crates/ppvm-pauli-sum-2/Cargo.toml b/crates/ppvm-pauli-sum-2/Cargo.toml index ea6615a11..39b155a74 100644 --- a/crates/ppvm-pauli-sum-2/Cargo.toml +++ b/crates/ppvm-pauli-sum-2/Cargo.toml @@ -18,5 +18,6 @@ num = "0.4" approx = { version = "0.5.1", features = ["num-complex"] } [dev-dependencies] +ppvm-tableau-2 = { path = "../ppvm-tableau-2" } ppvm-pauli-sum = { path = "../ppvm-pauli-sum" } criterion = "0.8.2" diff --git a/crates/ppvm-pauli-sum-2/src/damping.rs b/crates/ppvm-pauli-sum-2/src/damping.rs new file mode 100644 index 000000000..0f86e4201 --- /dev/null +++ b/crates/ppvm-pauli-sum-2/src/damping.rs @@ -0,0 +1,38 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! Heisenberg amplitude damping: X, Y scale by sqrt(1 - gamma); Z maps to +//! (1 - gamma) Z + gamma I through the branching machinery. Lost sites are +//! skipped. Zero branches stay stored; reduction is caller-controlled. + +use num::One; +use ppvm_traits_2::{AmplitudeDamping, PauliBits, loss::LossInfo}; + +use crate::{BranchInPlace, Sum}; + +impl AmplitudeDamping for Sum +where + S::Key: PauliBits + LossInfo, + S::Coeff: num::Float, +{ + fn amplitude_damping(&mut self, qubit: usize, gamma: S::Coeff) { + self.check_qubit(qubit); + let survive = S::Coeff::one() - gamma; + let transverse = num::Float::sqrt(survive); + self.storage.branch_in_place(|key, coeff| { + if key.is_lost(qubit) { + return None; + } + if key.x_bit(qubit) { + *coeff *= transverse; + return None; + } + if !key.z_bit(qubit) { + return None; + } + let branch = *coeff * gamma; + *coeff *= survive; + Some((key.toggled_bits(qubit, false, true), branch)) + }); + } +} diff --git a/crates/ppvm-pauli-sum-2/src/lib.rs b/crates/ppvm-pauli-sum-2/src/lib.rs index 6c1822838..c0df8bc72 100644 --- a/crates/ppvm-pauli-sum-2/src/lib.rs +++ b/crates/ppvm-pauli-sum-2/src/lib.rs @@ -3,7 +3,10 @@ mod clifford; mod compare; +mod damping; mod display; +mod loss; +mod noise; mod ops; mod policy; mod rotation; @@ -13,7 +16,9 @@ mod sum; pub use policy::{ CoefficientThreshold, CombinedPolicy, MaxLossWeight, MaxPauliWeight, NoPolicy, Policy, }; -pub use store::{BranchInPlace, HashMapStore, RekeyBijective, SignFlipByKey, StoreAlloc}; +pub use store::{ + BranchInPlace, HashMapStore, RekeyBijective, SignFlipByKey, StoreAlloc, UpdateCoefficients, +}; pub use sum::{PreserveSet, Sum}; pub use ppvm_lossy_pauli_word_2::LossyPauliWord; diff --git a/crates/ppvm-pauli-sum-2/src/loss.rs b/crates/ppvm-pauli-sum-2/src/loss.rs new file mode 100644 index 000000000..be153f61b --- /dev/null +++ b/crates/ppvm-pauli-sum-2/src/loss.rs @@ -0,0 +1,93 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! Heisenberg loss maps matching `ppvm-tableau-2`. `I` projects onto a live +//! site and `L` onto a lost one. Loss branches clear an observable's loss flag; +//! reset adds an `L` copy of each `I`/`Z` term, since a lost qubit returns in +//! `|0>`. Zero coefficients stay stored; reduction is caller-controlled. + +use crate::{BranchInPlace, Sum}; +use num::{One, Zero}; +use ppvm_traits_2::{ + CorrelatedLossChannel, LossChannel, PauliBits, ResetLossChannel, + loss::{LossInfo, LossState}, +}; + +impl LossChannel for Sum +where + S::Key: LossState, +{ + fn loss_channel(&mut self, qubit: usize, p: S::Coeff) { + self.check_qubit(qubit); + let survive = S::Coeff::one() - p.clone(); + self.storage.branch_in_place(|key, coeff| { + if key.is_lost(qubit) { + Some((key.loss_cleared(qubit), coeff.clone() * p.clone())) + } else { + *coeff *= &survive; + None + } + }); + } +} + +impl CorrelatedLossChannel for Sum +where + S::Key: LossState, +{ + fn correlated_loss_channel( + &mut self, + a: usize, + b: usize, + [both, single, after_loss]: [S::Coeff; 3], + ) { + self.check_pair(a, b); + let survive = S::Coeff::one() - (single.clone() + single.clone()) - both.clone(); + let partner_survives = S::Coeff::one() - after_loss.clone(); + self.storage.branch_in_place(|key, coeff| { + let mut branches = [None, None, None]; + match (key.is_lost(a), key.is_lost(b)) { + (false, false) => *coeff *= &survive, + // Reached from one already lost (p_LN) or from both live (p_LL). + (true, true) => { + let weight = coeff.clone() * after_loss.clone(); + let mut neither = key.loss_cleared(a); + neither.clear_lost(b); + branches = [ + Some((key.loss_cleared(a), weight.clone())), + Some((key.loss_cleared(b), weight)), + Some((neither, coeff.clone() * both.clone())), + ]; + } + // Reached from both live (p_LQ), or the partner survived p_LN. + (lost_a, _) => { + let lost = if lost_a { a } else { b }; + branches[0] = Some((key.loss_cleared(lost), coeff.clone() * single.clone())); + *coeff *= &partner_survives; + } + } + branches.into_iter().flatten() + }); + } +} + +impl ResetLossChannel for Sum +where + S::Key: PauliBits + LossState, +{ + fn reset_loss_channel(&mut self, qubit: usize) { + self.check_qubit(qubit); + self.storage.branch_in_place(|key, coeff| { + if key.is_lost(qubit) { + *coeff = S::Coeff::zero(); + return None; + } + if key.x_bit(qubit) { + return None; + } + let mut lost = key.clone(); + lost.set_lost(qubit); + Some((lost, coeff.clone())) + }); + } +} diff --git a/crates/ppvm-pauli-sum-2/src/noise.rs b/crates/ppvm-pauli-sum-2/src/noise.rs new file mode 100644 index 000000000..0f099d7ba --- /dev/null +++ b/crates/ppvm-pauli-sum-2/src/noise.rs @@ -0,0 +1,116 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! Coefficient-only Heisenberg Pauli and depolarizing channels: each term is +//! rescaled in place, so no keys are created, removed, or merged. A Pauli keeps +//! its sign under errors it commutes with, so its factor is one minus twice +//! the anticommuting probability. Lost sites are skipped, matching the +//! tableau. Probabilities are assumed valid; coefficients may be complex. + +use num::One; +use ppvm_traits_2::{ + Depolarizing, Depolarizing2, PauliBits, PauliError, TwoQubitPauliError, loss::LossInfo, +}; + +use crate::{Sum, UpdateCoefficients}; + +/// Packed code at `qubit` (`0=I, 1=X, 2=Z, 3=Y`), treating a lost site as `I`. +#[inline] +fn live_code(key: &K, qubit: usize) -> usize { + if key.is_lost(qubit) { + 0 + } else { + key.pauli_code(qubit) as usize + } +} + +impl PauliError for Sum +where + S::Key: PauliBits + LossInfo, +{ + fn pauli_error(&mut self, qubit: usize, [px, py, pz]: [S::Coeff; 3]) { + self.check_qubit(qubit); + let factor = |a: S::Coeff, b: S::Coeff| { + let p = a + b; + S::Coeff::one() - (p.clone() + p) + }; + // Indexed by packed code: X anticommutes with Y, Z; Z with X, Y; Y with X, Z. + let factors = [ + S::Coeff::one(), + factor(py.clone(), pz.clone()), + factor(px.clone(), py), + factor(px, pz), + ]; + self.storage.update_coefficients(|key, coeff| { + let code = live_code(key, qubit); + if code != 0 { + *coeff *= &factors[code]; + } + }); + } +} + +impl TwoQubitPauliError for Sum +where + S::Key: PauliBits + LossInfo, +{ + fn two_qubit_pauli_error(&mut self, a: usize, b: usize, p: [S::Coeff; 15]) { + self.check_pair(a, b); + // Probabilities use I, X, Y, Z order; packed codes use I, X, Z, Y. + const CODE: [usize; 4] = [0, 1, 3, 2]; + let anti = |u: usize, v: usize| ((u & 1) & (v >> 1)) ^ ((u >> 1) & (v & 1)) != 0; + // Indexed by 4 * code_a + code_b. + let factors: [S::Coeff; 16] = std::array::from_fn(|pair| { + let mut factor = S::Coeff::one(); + for (i, probability) in p.iter().enumerate() { + let error = i + 1; + if anti(pair / 4, CODE[error / 4]) != anti(pair % 4, CODE[error % 4]) { + factor = factor - (probability.clone() + probability.clone()); + } + } + factor + }); + self.storage.update_coefficients(|key, coeff| { + let pair = 4 * live_code(key, a) + live_code(key, b); + if pair != 0 { + *coeff *= &factors[pair]; + } + }); + } +} + +/// Stim's `DEPOLARIZE1(p)`: each of `X`, `Y`, `Z` with probability `p/3`. +impl Depolarizing for Sum +where + S::Key: PauliBits + LossInfo, + S::Coeff: From, +{ + fn depolarize1(&mut self, qubit: usize, p: S::Coeff) { + self.check_qubit(qubit); + let factor = S::Coeff::one() - p * S::Coeff::from(4.0 / 3.0); + self.storage.update_coefficients(|key, coeff| { + if live_code(key, qubit) != 0 { + *coeff *= &factor; + } + }); + } +} + +/// Stim's `DEPOLARIZE2(p)`: each non-identity pair with probability `p/15`. +impl Depolarizing2 for Sum +where + S::Key: PauliBits + LossInfo, + S::Coeff: From, +{ + fn depolarize2(&mut self, a: usize, b: usize, p: S::Coeff) { + self.check_pair(a, b); + let factor = S::Coeff::one() - p * S::Coeff::from(16.0 / 15.0); + self.storage.update_coefficients(|key, coeff| { + let active_a = !key.is_lost(a) && key.pauli_code(a) != 0; + let active_b = !key.is_lost(b) && key.pauli_code(b) != 0; + if active_a || active_b { + *coeff *= &factor; + } + }); + } +} diff --git a/crates/ppvm-pauli-sum-2/src/store.rs b/crates/ppvm-pauli-sum-2/src/store.rs index 4e7f3b04d..05514bf89 100644 --- a/crates/ppvm-pauli-sum-2/src/store.rs +++ b/crates/ppvm-pauli-sum-2/src/store.rs @@ -29,18 +29,26 @@ pub trait RekeyBijective: Support { } /// Negate selected coefficients without moving keys or rebuilding storage. +/// Kept apart from [`UpdateCoefficients`]: Clifford `X`/`Y`/`Z` measured ~25% +/// slower when routed through the general update closure. pub trait SignFlipByKey: Support { /// Negate a coefficient exactly when `negate` returns true for its key. fn flip_sign_by_key(&mut self, negate: impl Fn(&Self::Key) -> bool); } -/// Update original coefficients, then accumulate optional generated terms. +/// Change coefficients without copying keys or generating terms. +pub trait UpdateCoefficients: Support { + /// Visit each coefficient in place, preserving keys and explicit zeros. + fn update_coefficients(&mut self, update: impl FnMut(&Self::Key, &mut Self::Coeff)); +} + +/// Update original coefficients, then accumulate generated terms. pub trait BranchInPlace: Support { /// Visit each original term once; merge branches only after all visits finish. /// Collisions add coefficients, exact zeros remain stored, and widths must match. - fn branch_in_place( + fn branch_in_place>( &mut self, - transform: impl FnMut(&Self::Key, &mut Self::Coeff) -> Option<(Self::Key, Self::Coeff)>, + transform: impl FnMut(&Self::Key, &mut Self::Coeff) -> I, ); } @@ -175,13 +183,22 @@ impl SignFlipByKey for HashMapStore { } } +impl UpdateCoefficients for HashMapStore { + fn update_coefficients(&mut self, mut update: impl FnMut(&K, &mut C)) { + for (key, coeff) in &mut self.terms { + update(key, coeff); + } + } +} + impl BranchInPlace for HashMapStore { - fn branch_in_place(&mut self, mut transform: impl FnMut(&K, &mut C) -> Option<(K, C)>) { + fn branch_in_place>( + &mut self, + mut transform: impl FnMut(&K, &mut C) -> I, + ) { let mut branches = std::mem::take(&mut self.buffer); for (key, coeff) in &mut self.terms { - if let Some(branch) = transform(key, coeff) { - branches.push(branch); - } + branches.extend(transform(key, coeff)); } for (key, coeff) in branches.drain(..) { self.terms.accumulate(key, coeff); diff --git a/crates/ppvm-pauli-sum-2/src/store/tests.rs b/crates/ppvm-pauli-sum-2/src/store/tests.rs index 5306111bf..9ab16fc25 100644 --- a/crates/ppvm-pauli-sum-2/src/store/tests.rs +++ b/crates/ppvm-pauli-sum-2/src/store/tests.rs @@ -52,6 +52,37 @@ fn scaling_and_retaining_do_not_implicitly_reduce() { assert!(store.is_empty()); } +#[test] +fn branching_merges_many_branches_per_term_after_all_visits() { + let mut store = Store::with_capacity(4); + for (word, coeff) in [("X", 1.0), ("Y", 2.0), ("Z", 3.0)] { + store.accumulate(word.into(), coeff); + } + let (x, y) = (PauliWord::from("X"), PauliWord::from("Y")); + let mut visits = 0; + store.branch_in_place(|key, coeff| { + visits += 1; + *coeff *= 10.0; + if *key == x { + // Two branches: one new key, one colliding with an original key. + vec![("I".into(), 0.5), ("Z".into(), 4.0)] + } else if *key == y { + // Cancels X's new branch; the exact zero stays stored. + vec![("I".into(), -0.5)] + } else { + vec![] + } + }); + // Only originals are visited, and Z is scaled before X's branch lands: + // merging early would give (3 + 4) * 10 = 70. + assert_eq!(visits, 3); + assert_eq!(store.len(), 4); + for (word, coeff) in [("I", 0.0), ("X", 10.0), ("Y", 20.0), ("Z", 34.0)] { + assert_eq!(store.get(&word.into()), Some(coeff), "{word}"); + } + assert!(store.buffer.is_empty()); +} + #[test] fn complex_pairings_preserve_operand_order() { let x = PauliWord::from("X"); diff --git a/crates/ppvm-pauli-sum-2/tests/damping.rs b/crates/ppvm-pauli-sum-2/tests/damping.rs new file mode 100644 index 000000000..774897e0d --- /dev/null +++ b/crates/ppvm-pauli-sum-2/tests/damping.rs @@ -0,0 +1,45 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +use approx::assert_abs_diff_eq; +use ppvm_pauli_sum_2::{CoefficientThreshold, LossyPauliSum, PauliSum, PauliWord}; +use ppvm_traits_2::AmplitudeDamping; + +#[test] +fn amplitude_damping_merges_into_identity_after_original_updates() { + let mut sum = LossyPauliSum::::new(1); + for (word, c) in [("I", 2.0), ("X", 3.0), ("Y", 4.0), ("Z", 5.0), ("L", 6.0)] { + sum += (word, c); + } + sum.amplitude_damping(0, 0.36); + let mut expected = LossyPauliSum::::new(1); + for (word, c) in [("I", 3.8), ("X", 2.4), ("Y", 3.2), ("Z", 3.2), ("L", 6.0)] { + expected += (word, c); + } + assert_abs_diff_eq!(sum, expected, epsilon = 1e-12); +} + +#[test] +fn full_damping_keeps_zero_terms_and_ignores_policy() { + let mut sum = PauliSum::::with_policy(1, CoefficientThreshold { threshold: 10.0 }); + sum += ("X", 1.0); + sum += ("Z", 1.0); + sum.amplitude_damping(0, 1.0); + assert_eq!(sum.len(), 3); + assert_eq!(sum.get(&PauliWord::from("I")), Some(1.0)); + for word in ["X", "Z"] { + assert_eq!(sum.get(&PauliWord::from(word)), Some(0.0)); + } + sum.truncate(); + assert!(sum.is_empty()); +} + +#[test] +fn invalid_damping_target_panics_before_mutation() { + use std::panic::{AssertUnwindSafe, catch_unwind}; + let mut sum = PauliSum::::new(1); + sum += ("Z", 1.0); + let original = sum.clone(); + assert!(catch_unwind(AssertUnwindSafe(|| sum.amplitude_damping(1, 0.1))).is_err()); + assert_eq!(sum, original); +} diff --git a/crates/ppvm-pauli-sum-2/tests/loss.rs b/crates/ppvm-pauli-sum-2/tests/loss.rs new file mode 100644 index 000000000..670f5dc68 --- /dev/null +++ b/crates/ppvm-pauli-sum-2/tests/loss.rs @@ -0,0 +1,97 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +use approx::assert_abs_diff_eq; +use num::Complex; +use ppvm_pauli_sum_2::{CoefficientThreshold, LossyPauliSum, LossyPauliWord}; +use ppvm_traits_2::{CorrelatedLossChannel, LossChannel, ResetLossChannel}; + +#[test] +fn single_loss_merges_branches_after_scaling_original_terms() { + let mut sum = LossyPauliSum::::new(1); + sum += ("L", 2.0); + sum += ("I", 3.0); + sum += ("X", 4.0); + sum.loss_channel(0, 0.2); + let mut expected = LossyPauliSum::::new(1); + expected += ("L", 2.0); + expected += ("I", 2.8); + expected += ("X", 3.2); + assert_abs_diff_eq!(sum, expected, epsilon = 1e-12); +} + +#[test] +fn correlated_loss_preserves_distinct_branch_weights_and_collisions() { + let mut sum = LossyPauliSum::>::new(2); + let c = Complex::new(1.0, 2.0); + for (word, v) in [("LL", 2.0), ("IL", 3.0), ("LI", 5.0), ("II", 7.0)] { + sum += (word, c * v); + } + sum.correlated_loss_channel(0, 1, [0.1.into(), 0.2.into(), 0.3.into()]); + let mut expected = LossyPauliSum::>::new(2); + for (word, v) in [("LL", 2.0), ("IL", 2.7), ("LI", 4.1), ("II", 5.3)] { + expected += (word, c * v); + } + assert_abs_diff_eq!(sum, expected, epsilon = 1e-12); +} + +#[test] +fn loss_maps_preserve_the_full_identity_including_lost_sectors() { + // I projects onto the live subspace; I+L is the full one-site identity. + let mut identity = LossyPauliSum::::new(2); + for word in ["II", "IL", "LI", "LL"] { + identity += (word, 1.0); + } + let mut sum = identity.clone(); + sum.loss_channel(0, 0.2); + sum.correlated_loss_channel(0, 1, [0.1, 0.2, 0.3]); + sum.reset_loss_channel(1); + assert_abs_diff_eq!(sum, identity, epsilon = 1e-12); +} + +#[test] +fn reset_loss_accumulates_i_and_z_into_l_without_reprocessing_them() { + let mut sum = LossyPauliSum::::new(1); + for (word, c) in [("I", 2.0), ("Z", 3.0), ("L", 11.0), ("X", 7.0)] { + sum += (word, c); + } + sum.reset_loss_channel(0); + let mut expected = LossyPauliSum::::new(1); + for (word, c) in [("I", 2.0), ("Z", 3.0), ("L", 5.0), ("X", 7.0)] { + expected += (word, c); + } + assert_eq!(sum, expected); +} + +#[test] +fn loss_keeps_zero_branches_and_does_not_apply_policy() { + let mut sum = LossyPauliSum::::with_policy(2, CoefficientThreshold { threshold: 10.0 }); + sum += ("LL", 1.0); + sum.correlated_loss_channel(0, 1, [0.0; 3]); + assert_eq!(sum.len(), 4); + assert_eq!(sum.get(&LossyPauliWord::from("II")), Some(0.0)); + sum.reduce(); + assert_eq!(sum.len(), 1); + sum.reset_loss_channel(0); + assert_eq!(sum.len(), 1); + assert_eq!(sum.get(&LossyPauliWord::from("LL")), Some(0.0)); + sum.truncate(); + assert!(sum.is_empty()); +} + +#[test] +fn invalid_loss_targets_panic_before_mutation() { + use std::panic::{AssertUnwindSafe, catch_unwind}; + let mut sum = LossyPauliSum::::new(1); + sum += ("L", 1.0); + let original = sum.clone(); + assert!(catch_unwind(AssertUnwindSafe(|| sum.loss_channel(1, 0.1))).is_err()); + assert!( + catch_unwind(AssertUnwindSafe( + || sum.correlated_loss_channel(0, 0, [0.1; 3]) + )) + .is_err() + ); + assert!(catch_unwind(AssertUnwindSafe(|| sum.reset_loss_channel(1))).is_err()); + assert_eq!(sum, original); +} diff --git a/crates/ppvm-pauli-sum-2/tests/noise.rs b/crates/ppvm-pauli-sum-2/tests/noise.rs new file mode 100644 index 000000000..fe30adb7e --- /dev/null +++ b/crates/ppvm-pauli-sum-2/tests/noise.rs @@ -0,0 +1,118 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +use approx::assert_abs_diff_eq; +use num::Complex; +use ppvm_pauli_sum_2::{CoefficientThreshold, LossyPauliSum, LossyPauliWord, PauliSum, PauliWord}; +use ppvm_traits_2::{Depolarizing, Depolarizing2, PauliError, TwoQubitPauliError}; + +#[test] +fn pauli_channel_scales_complex_coefficients_and_preserves_loss() { + let mut sum = LossyPauliSum::>::new(1); + let c = Complex::new(2.0, -3.0); + for word in ["I", "X", "Y", "Z", "L"] { + sum += (word, c); + } + sum.pauli_error(0, [0.1.into(), 0.2.into(), 0.3.into()]); + for (word, factor) in [("I", 1.0), ("X", 0.0), ("Y", 0.2), ("Z", 0.4), ("L", 1.0)] { + assert_abs_diff_eq!( + sum.get(&LossyPauliWord::from(word)).unwrap(), + c * factor, + epsilon = 1e-12 + ); + } + assert_eq!(sum.len(), 5); +} + +#[test] +fn all_two_qubit_pauli_errors_have_the_declared_order() { + let mut original = LossyPauliSum::::new(2); + for a in "IXYZL".chars() { + for b in "IXYZL".chars() { + original += (format!("{a}{b}").as_str(), 1.0); + } + } + let errors: Vec<_> = "IXYZ" + .chars() + .flat_map(|a| "IXYZ".chars().map(move |b| (a, b))) + .skip(1) + .collect(); + for (i, (a, b)) in errors.into_iter().enumerate() { + let mut sum = original.clone(); + let mut p = [0.0; 15]; + p[i] = 1.0; + sum.two_qubit_pauli_error(0, 1, p); + for x in "IXYZL".chars() { + for y in "IXYZL".chars() { + let anti = + |error, word| error != 'I' && word != 'I' && word != 'L' && error != word; + let sign = if anti(a, x) ^ anti(b, y) { -1.0 } else { 1.0 }; + assert_eq!( + sum.get(&LossyPauliWord::from(format!("{x}{y}").as_str())), + Some(sign) + ); + } + } + } +} + +#[test] +fn depolarization_matches_uniform_pauli_channels_including_loss() { + let mut original = LossyPauliSum::::new(2); + for a in "IXYZL".chars() { + for b in "IXYZL".chars() { + original += (format!("{a}{b}").as_str(), 1.0); + } + } + for p in [0.0, 0.3, 1.0] { + let mut sum = original.clone(); + let mut expected = original.clone(); + sum.depolarize1(0, p); + expected.pauli_error(0, [p / 3.0; 3]); + assert_abs_diff_eq!(sum, expected, epsilon = 1e-12); + let mut sum = original.clone(); + let mut expected = original.clone(); + sum.depolarize2(0, 1, p); + expected.two_qubit_pauli_error(0, 1, [p / 15.0; 15]); + assert_abs_diff_eq!(sum, expected, epsilon = 1e-12); + } +} + +#[test] +fn noise_does_not_reduce_or_truncate() { + let mut sum = PauliSum::::with_policy(1, CoefficientThreshold { threshold: 10.0 }); + sum += ("X", 1.0); + sum.x_error(0, 0.5); + assert_eq!(sum.get(&PauliWord::from("X")), Some(1.0)); + sum.z_error(0, 0.5); + assert_eq!(sum.get(&PauliWord::from("X")), Some(0.0)); + sum.depolarize1(0, 0.75); + assert_eq!(sum.len(), 1); + sum.reduce(); + assert!(sum.is_empty()); + sum += ("Z", 1.0); + sum.depolarize1(0, 0.3); + assert_eq!(sum.len(), 1); + sum.truncate(); + assert!(sum.is_empty()); +} + +#[test] +fn invalid_noise_targets_panic_before_mutation() { + use std::panic::{AssertUnwindSafe, catch_unwind}; + let mut sum = PauliSum::::new(1); + sum += ("Z", 1.0); + let original = sum.clone(); + assert!(catch_unwind(AssertUnwindSafe(|| sum.pauli_error(1, [0.1; 3]))).is_err()); + assert!( + catch_unwind(AssertUnwindSafe( + || sum.two_qubit_pauli_error(0, 0, [0.01; 15]) + )) + .is_err() + ); + assert!(catch_unwind(AssertUnwindSafe(|| sum.depolarize1(1, 0.1))).is_err()); + assert!(catch_unwind(AssertUnwindSafe(|| sum.depolarize2(0, 1, 0.1))).is_err()); + assert_eq!(sum, original); + let mut empty = PauliSum::::new(0); + assert!(catch_unwind(AssertUnwindSafe(|| empty.depolarize1(0, 0.1))).is_err()); +} diff --git a/crates/ppvm-pauli-sum-2/tests/tableau_channels.rs b/crates/ppvm-pauli-sum-2/tests/tableau_channels.rs new file mode 100644 index 000000000..ed439c133 --- /dev/null +++ b/crates/ppvm-pauli-sum-2/tests/tableau_channels.rs @@ -0,0 +1,149 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! Cross-check Heisenberg channels against `ppvm-tableau-2` trajectories. +//! Each tableau run prepares a Z-basis (or lost) state, applies the channel +//! forward, and measures; the sum applies the channel backward to an +//! observable and evaluates it on the prepared state. + +use approx::assert_abs_diff_eq; +use ppvm_pauli_sum_2::LossyPauliSum; +use ppvm_tableau_2::{ActiveDormant, DenseState, GeneralizedTableau}; +use ppvm_traits_2::{ + Clifford, CorrelatedLossChannel, Depolarizing, Depolarizing2, LossChannel, Measure, PauliError, + ResetLossChannel, TwoQubitPauliError, +}; + +type Sim = GeneralizedTableau>; +type ChannelPair = (fn(&mut Sim), fn(&mut LossyPauliSum)); + +const SHOTS: u64 = 8192; +const OBSERVABLES: [&str; 9] = ["II", "IZ", "IL", "ZI", "ZZ", "ZL", "LI", "LZ", "LL"]; + +/// Value of a word on a Z-basis state; `I` and `Z` vanish on lost sites. +fn basis_value(word: &str, state: &str) -> f64 { + word.chars() + .zip(state.chars()) + .map(|(p, s)| match (p, s) { + ('L', 'L') => 1.0, + (_, 'L') | ('L', _) | ('X' | 'Y', _) => 0.0, + ('Z', '1') => -1.0, + _ => 1.0, + }) + .product() +} + +/// Distinct two-qubit rates, so a misordered table changes the marginals. +fn distinct_rates() -> [f64; 15] { + std::array::from_fn(|k| 0.008 * (k + 1) as f64) +} + +fn assert_matches_tableau(initials: &[&str], channels: &[ChannelPair]) { + for initial in initials { + for &(forward, backward) in channels { + let mut averages = [0.0; OBSERVABLES.len()]; + for seed in 0..SHOTS { + let mut sim = Sim::new_with_seed(2, seed); + for (q, state) in initial.chars().enumerate() { + match state { + '1' => sim.x(q), + 'L' => sim.loss_channel(q, 1.0), + _ => {} + } + } + forward(&mut sim); + let output: String = (0..2) + .map(|q| match sim.measure(q) { + None => 'L', + Some(false) => '0', + Some(true) => '1', + }) + .collect(); + for (average, word) in averages.iter_mut().zip(OBSERVABLES) { + *average += basis_value(word, &output) / SHOTS as f64; + } + } + for (average, word) in averages.into_iter().zip(OBSERVABLES) { + let mut sum = LossyPauliSum::::new(2); + sum += (word, 1.0); + backward(&mut sum); + let expected: f64 = sum + .iter() + .map(|(key, c)| c * basis_value(&key.to_string(), initial)) + .sum(); + assert_abs_diff_eq!(average, expected, epsilon = 0.035); + } + } + } +} + +#[test] +fn pauli_probability_order_agrees_with_tableau_for_every_error() { + for error in 0..15 { + let mut p = [0.0; 15]; + p[error] = 1.0; + for (word, plus) in [("ZI", false), ("IZ", false), ("XI", true), ("IX", true)] { + let mut sim = Sim::new_with_seed(2, 0); + if plus { + sim.h(0); + sim.h(1); + } + sim.two_qubit_pauli_error(0, 1, p); + if plus { + sim.h(0); + sim.h(1); + } + let q = usize::from(word.starts_with('I')); + let measured = if sim.measure(q).unwrap() { -1.0 } else { 1.0 }; + let mut sum = LossyPauliSum::::new(2); + sum += (word, 1.0); + sum.two_qubit_pauli_error(0, 1, p); + assert_eq!(sum.iter().next().unwrap().1, measured); + } + } +} + +/// Includes lost targets and lost partners: the tableau skips errors on lost +/// qubits but still applies the partner's half of a two-qubit Pauli. +#[test] +fn pauli_and_depolarizing_averages_agree_with_tableau() { + let channels: [ChannelPair; 4] = [ + ( + |s| s.pauli_error(0, [0.1, 0.2, 0.3]), + |s| s.pauli_error(0, [0.1, 0.2, 0.3]), + ), + (|s| s.depolarize1(0, 0.4), |s| s.depolarize1(0, 0.4)), + (|s| s.depolarize2(0, 1, 0.4), |s| s.depolarize2(0, 1, 0.4)), + ( + |s| s.two_qubit_pauli_error(0, 1, distinct_rates()), + |s| s.two_qubit_pauli_error(0, 1, distinct_rates()), + ), + ]; + assert_matches_tableau(&["00", "11", "L1", "1L", "LL"], &channels); +} + +#[test] +fn loss_observables_agree_with_tableau_trajectories() { + let channels: [ChannelPair; 4] = [ + (|s| s.loss_channel(0, 0.23), |s| s.loss_channel(0, 0.23)), + ( + |s| s.correlated_loss_channel(0, 1, [0.11, 0.19, 0.37]), + |s| s.correlated_loss_channel(0, 1, [0.11, 0.19, 0.37]), + ), + (|s| s.reset_loss_channel(0), |s| s.reset_loss_channel(0)), + ( + |s| { + s.loss_channel(0, 0.23); + s.correlated_loss_channel(0, 1, [0.11, 0.19, 0.37]); + s.reset_loss_channel(1); + }, + // Heisenberg order: the last forward channel acts first. + |s| { + s.reset_loss_channel(1); + s.correlated_loss_channel(0, 1, [0.11, 0.19, 0.37]); + s.loss_channel(0, 0.23); + }, + ), + ]; + assert_matches_tableau(&["10", "L1", "1L", "LL"], &channels); +}