From bfbd0cd12c1943a1d236c060195a67490bd3b978 Mon Sep 17 00:00:00 2001 From: jonhas colina Date: Mon, 23 Nov 2026 00:27:17 -0500 Subject: [PATCH 1/5] adding support for coefficient-only Pauli and depolarizing channels --- Cargo.lock | 1 + crates/ppvm-pauli-sum-2/Cargo.toml | 1 + crates/ppvm-pauli-sum-2/src/lib.rs | 5 +- crates/ppvm-pauli-sum-2/src/noise.rs | 112 +++++++++++++++ crates/ppvm-pauli-sum-2/src/store.rs | 14 ++ crates/ppvm-pauli-sum-2/tests/noise.rs | 134 ++++++++++++++++++ .../tests/tableau_channels.rs | 122 ++++++++++++++++ 7 files changed, 388 insertions(+), 1 deletion(-) create mode 100644 crates/ppvm-pauli-sum-2/src/noise.rs create mode 100644 crates/ppvm-pauli-sum-2/tests/noise.rs create mode 100644 crates/ppvm-pauli-sum-2/tests/tableau_channels.rs 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/lib.rs b/crates/ppvm-pauli-sum-2/src/lib.rs index 6c1822838..7782f0918 100644 --- a/crates/ppvm-pauli-sum-2/src/lib.rs +++ b/crates/ppvm-pauli-sum-2/src/lib.rs @@ -4,6 +4,7 @@ mod clifford; mod compare; mod display; +mod noise; mod ops; mod policy; mod rotation; @@ -13,7 +14,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/noise.rs b/crates/ppvm-pauli-sum-2/src/noise.rs new file mode 100644 index 000000000..6afb910c4 --- /dev/null +++ b/crates/ppvm-pauli-sum-2/src/noise.rs @@ -0,0 +1,112 @@ +// 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. Lost sites +//! are skipped, matching the tableau, where gates and errors skip lost qubits. +//! 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}; + +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) + }; + let factors = [ + S::Coeff::one(), + factor(py.clone(), pz.clone()), + factor(px.clone(), py), + factor(px, pz), + ]; + self.storage.update_coefficients(|key, coeff| { + if !key.is_lost(qubit) && key.pauli_code(qubit) != 0 { + *coeff *= &factors[key.pauli_code(qubit) as usize]; + } + }); + } +} + +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 word codes use I,X,Z,Y. + let codes = [0u8, 1, 3, 2]; + 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; + let anti = |x: u8, y: u8| ((x & 1) & (y >> 1)) ^ ((x >> 1) & (y & 1)); + if anti((pair / 4) as u8, codes[error / 4]) + ^ anti((pair % 4) as u8, codes[error % 4]) + != 0 + { + factor = factor - (probability.clone() + probability.clone()); + } + } + factor + }); + self.storage.update_coefficients(|key, coeff| { + let x = if key.is_lost(a) { + 0 + } else { + key.pauli_code(a) as usize + }; + let y = if key.is_lost(b) { + 0 + } else { + key.pauli_code(b) as usize + }; + if x != 0 || y != 0 { + *coeff *= &factors[x * 4 + y]; + } + }); + } +} + +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 !key.is_lost(qubit) && key.pauli_code(qubit) != 0 { + *coeff *= &factor; + } + }); + } +} + +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..a08868b39 100644 --- a/crates/ppvm-pauli-sum-2/src/store.rs +++ b/crates/ppvm-pauli-sum-2/src/store.rs @@ -34,6 +34,12 @@ pub trait SignFlipByKey: Support { fn flip_sign_by_key(&mut self, negate: impl Fn(&Self::Key) -> bool); } +/// 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 optional generated terms. pub trait BranchInPlace: Support { /// Visit each original term once; merge branches only after all visits finish. @@ -175,6 +181,14 @@ 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)>) { let mut branches = std::mem::take(&mut self.buffer); 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..3045fb4c2 --- /dev/null +++ b/crates/ppvm-pauli-sum-2/tests/noise.rs @@ -0,0 +1,134 @@ +// 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 noise_batches_match_scalar_calls() { + let mut sum = PauliSum::::new(2); + sum += ("XY", 2.0); + sum += ("ZZ", 3.0); + let mut expected = sum.clone(); + sum.pauli_error_many(&[1, 0, 1], [0.1, 0.2, 0.3]); + for q in [1, 0, 1] { + expected.pauli_error(q, [0.1, 0.2, 0.3]); + } + sum.depolarize2_many(&[(0, 1), (1, 0)], 0.3); + expected.depolarize2(0, 1, 0.3); + expected.depolarize2(1, 0, 0.3); + assert_abs_diff_eq!(sum, expected, epsilon = 1e-12); +} + +#[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..ffbafd676 --- /dev/null +++ b/crates/ppvm-pauli-sum-2/tests/tableau_channels.rs @@ -0,0 +1,122 @@ +// 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, Depolarizing, Depolarizing2, LossChannel, Measure, PauliError, 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); +} From 8022be3e4f9166cf480572fcba04a05c252584a0 Mon Sep 17 00:00:00 2001 From: jonhas colina Date: Mon, 23 Nov 2026 00:27:35 -0500 Subject: [PATCH 2/5] adding amplitude damping and loss via branching --- crates/ppvm-pauli-sum-2/src/damping.rs | 41 ++++++++ crates/ppvm-pauli-sum-2/src/lib.rs | 2 + crates/ppvm-pauli-sum-2/src/loss.rs | 88 +++++++++++++++++ crates/ppvm-pauli-sum-2/src/store.rs | 15 +-- crates/ppvm-pauli-sum-2/tests/damping.rs | 57 +++++++++++ crates/ppvm-pauli-sum-2/tests/loss.rs | 97 +++++++++++++++++++ .../tests/tableau_channels.rs | 29 +++++- 7 files changed, 321 insertions(+), 8 deletions(-) create mode 100644 crates/ppvm-pauli-sum-2/src/damping.rs create mode 100644 crates/ppvm-pauli-sum-2/src/loss.rs create mode 100644 crates/ppvm-pauli-sum-2/tests/damping.rs create mode 100644 crates/ppvm-pauli-sum-2/tests/loss.rs 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..3b52f0483 --- /dev/null +++ b/crates/ppvm-pauli-sum-2/src/damping.rs @@ -0,0 +1,41 @@ +// 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; + } + // Packed codes: I = 0, X = 1, Z = 2, Y = 3. + match key.pauli_code(qubit) { + 1 | 3 => { + *coeff *= transverse; + None + } + 2 => { + let branch = *coeff * gamma; + *coeff *= survive; + Some((key.toggled_bits(qubit, false, true), branch)) + } + _ => None, + } + }); + } +} diff --git a/crates/ppvm-pauli-sum-2/src/lib.rs b/crates/ppvm-pauli-sum-2/src/lib.rs index 7782f0918..c0df8bc72 100644 --- a/crates/ppvm-pauli-sum-2/src/lib.rs +++ b/crates/ppvm-pauli-sum-2/src/lib.rs @@ -3,7 +3,9 @@ mod clifford; mod compare; +mod damping; mod display; +mod loss; mod noise; mod ops; mod policy; 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..e5d7f9a1b --- /dev/null +++ b/crates/ppvm-pauli-sum-2/src/loss.rs @@ -0,0 +1,88 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! Heisenberg loss maps matching the existing engine. Loss branches clear an +//! observable's loss flag; reset maps I/Z to an additional lost observable. +//! Zero coefficients stay stored, and truncation remains 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 one_lost = 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)) { + (true, true) => { + let weight = coeff.clone() * after_loss.clone(); + branches[0] = Some((key.loss_cleared(a), weight.clone())); + branches[1] = Some((key.loss_cleared(b), weight)); + let mut cleared = key.loss_cleared(a); + cleared.clear_lost(b); + branches[2] = Some((cleared, coeff.clone() * both.clone())); + } + (lost_a, lost_b) if lost_a || lost_b => { + let qubit = if lost_a { a } else { b }; + branches[0] = Some((key.loss_cleared(qubit), coeff.clone() * single.clone())); + *coeff *= &one_lost; + } + _ => *coeff *= &survive, + } + 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/store.rs b/crates/ppvm-pauli-sum-2/src/store.rs index a08868b39..a3e22a1f0 100644 --- a/crates/ppvm-pauli-sum-2/src/store.rs +++ b/crates/ppvm-pauli-sum-2/src/store.rs @@ -40,13 +40,13 @@ pub trait UpdateCoefficients: Support { fn update_coefficients(&mut self, update: impl FnMut(&Self::Key, &mut Self::Coeff)); } -/// Update original coefficients, then accumulate optional generated terms. +/// 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, ); } @@ -190,12 +190,13 @@ impl UpdateCoefficients for HashMapStore { } 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/tests/damping.rs b/crates/ppvm-pauli-sum-2/tests/damping.rs new file mode 100644 index 000000000..dcd5f574b --- /dev/null +++ b/crates/ppvm-pauli-sum-2/tests/damping.rs @@ -0,0 +1,57 @@ +// 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() { + let mut sum = PauliSum::::new(1); + for word in ["I", "X", "Y", "Z"] { + sum += (word, 1.0); + } + sum.amplitude_damping(0, 1.0); + assert_eq!(sum.len(), 4); + assert_eq!(sum.get(&PauliWord::from("I")), Some(2.0)); + for word in ["X", "Y", "Z"] { + assert_eq!(sum.get(&PauliWord::from(word)), Some(0.0)); + } +} + +#[test] +fn damping_does_not_reduce_or_truncate() { + let mut sum = PauliSum::::with_policy(1, CoefficientThreshold { threshold: 10.0 }); + sum += ("Z", 1.0); + sum.amplitude_damping(0, 0.0); + assert_eq!(sum.get(&PauliWord::from("I")), Some(0.0)); + assert_eq!(sum.len(), 2); + sum.reduce(); + assert_eq!(sum.len(), 1); + 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/tableau_channels.rs b/crates/ppvm-pauli-sum-2/tests/tableau_channels.rs index ffbafd676..ed439c133 100644 --- a/crates/ppvm-pauli-sum-2/tests/tableau_channels.rs +++ b/crates/ppvm-pauli-sum-2/tests/tableau_channels.rs @@ -10,7 +10,8 @@ use approx::assert_abs_diff_eq; use ppvm_pauli_sum_2::LossyPauliSum; use ppvm_tableau_2::{ActiveDormant, DenseState, GeneralizedTableau}; use ppvm_traits_2::{ - Clifford, Depolarizing, Depolarizing2, LossChannel, Measure, PauliError, TwoQubitPauliError, + Clifford, CorrelatedLossChannel, Depolarizing, Depolarizing2, LossChannel, Measure, PauliError, + ResetLossChannel, TwoQubitPauliError, }; type Sim = GeneralizedTableau>; @@ -120,3 +121,29 @@ fn pauli_and_depolarizing_averages_agree_with_tableau() { ]; 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); +} From b56007f558415f6f9d0f5a13568eb03007a49685 Mon Sep 17 00:00:00 2001 From: jonhas colina Date: Mon, 23 Nov 2026 00:34:26 -0500 Subject: [PATCH 3/5] refactor(ppvm-pauli-sum-2): simplify noise, damping, and loss channels --- crates/ppvm-pauli-sum-2/src/clifford.rs | 28 +++++++----- crates/ppvm-pauli-sum-2/src/damping.rs | 21 ++++----- crates/ppvm-pauli-sum-2/src/lib.rs | 4 +- crates/ppvm-pauli-sum-2/src/loss.rs | 33 ++++++++------ crates/ppvm-pauli-sum-2/src/noise.rs | 58 ++++++++++++------------ crates/ppvm-pauli-sum-2/src/store.rs | 16 ------- crates/ppvm-pauli-sum-2/tests/damping.rs | 26 +++-------- crates/ppvm-pauli-sum-2/tests/noise.rs | 16 ------- 8 files changed, 82 insertions(+), 120 deletions(-) diff --git a/crates/ppvm-pauli-sum-2/src/clifford.rs b/crates/ppvm-pauli-sum-2/src/clifford.rs index dc1ff4a07..78f4408f1 100644 --- a/crates/ppvm-pauli-sum-2/src/clifford.rs +++ b/crates/ppvm-pauli-sum-2/src/clifford.rs @@ -4,7 +4,7 @@ use ppvm_phased_pauli_word_2::Phased; use ppvm_traits_2::{Clifford, CliffordBatch, Coefficient, PauliBits, Phase, loss::LossInfo}; -use crate::{RekeyBijective, SignFlipByKey, Sum}; +use crate::{RekeyBijective, Sum, UpdateCoefficients}; /// Whether a gate on `qubit` can change `key`: every Clifford fixes `I` and lost sites. fn active(key: &K, qubit: usize) -> bool { @@ -93,7 +93,15 @@ where } } -impl Sum { +impl Sum { + fn flip_signs(&mut self, negate: impl Fn(&S::Key) -> bool) { + self.storage.update_coefficients(|key, coeff| { + if negate(key) { + coeff.mul_sign_assign(-1); + } + }); + } + fn flip_signs_many(&mut self, indices: &[usize], negate: impl Fn(&S::Key, usize) -> bool) { if indices.is_empty() { return; @@ -101,8 +109,7 @@ impl Sum { for &qubit in indices { self.check_qubit(qubit); } - self.storage - .flip_sign_by_key(|key| indices.iter().fold(false, |flip, &q| flip ^ negate(key, q))); + self.flip_signs(|key| indices.iter().fold(false, |flip, &q| flip ^ negate(key, q))); } } @@ -110,26 +117,23 @@ impl Sum { /// Two-qubit gates also require distinct indices, including on empty sums. impl Clifford for Sum where - S: RekeyBijective + SignFlipByKey, + S: RekeyBijective + UpdateCoefficients, S::Key: PauliBits + LossInfo, Phased: Clifford, { fn x(&mut self, qubit: usize) { self.check_qubit(qubit); - self.storage - .flip_sign_by_key(|key| !key.is_lost(qubit) && key.z_bit(qubit)); + self.flip_signs(|key| !key.is_lost(qubit) && key.z_bit(qubit)); } fn y(&mut self, qubit: usize) { self.check_qubit(qubit); - self.storage - .flip_sign_by_key(|key| !key.is_lost(qubit) && (key.x_bit(qubit) ^ key.z_bit(qubit))); + self.flip_signs(|key| !key.is_lost(qubit) && (key.x_bit(qubit) ^ key.z_bit(qubit))); } fn z(&mut self, qubit: usize) { self.check_qubit(qubit); - self.storage - .flip_sign_by_key(|key| !key.is_lost(qubit) && key.x_bit(qubit)); + self.flip_signs(|key| !key.is_lost(qubit) && key.x_bit(qubit)); } fn h(&mut self, qubit: usize) { @@ -177,7 +181,7 @@ where /// Pauli batches only update signs. Validate the whole batch before changing terms. impl CliffordBatch for Sum where - S: RekeyBijective + SignFlipByKey, + S: RekeyBijective + UpdateCoefficients, S::Key: PauliBits + LossInfo, Phased: Clifford, { diff --git a/crates/ppvm-pauli-sum-2/src/damping.rs b/crates/ppvm-pauli-sum-2/src/damping.rs index 3b52f0483..0f86e4201 100644 --- a/crates/ppvm-pauli-sum-2/src/damping.rs +++ b/crates/ppvm-pauli-sum-2/src/damping.rs @@ -23,19 +23,16 @@ where if key.is_lost(qubit) { return None; } - // Packed codes: I = 0, X = 1, Z = 2, Y = 3. - match key.pauli_code(qubit) { - 1 | 3 => { - *coeff *= transverse; - None - } - 2 => { - let branch = *coeff * gamma; - *coeff *= survive; - Some((key.toggled_bits(qubit, false, true), branch)) - } - _ => 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 c0df8bc72..d8c02459d 100644 --- a/crates/ppvm-pauli-sum-2/src/lib.rs +++ b/crates/ppvm-pauli-sum-2/src/lib.rs @@ -16,9 +16,7 @@ mod sum; pub use policy::{ CoefficientThreshold, CombinedPolicy, MaxLossWeight, MaxPauliWeight, NoPolicy, Policy, }; -pub use store::{ - BranchInPlace, HashMapStore, RekeyBijective, SignFlipByKey, StoreAlloc, UpdateCoefficients, -}; +pub use store::{BranchInPlace, HashMapStore, RekeyBijective, 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 index e5d7f9a1b..be153f61b 100644 --- a/crates/ppvm-pauli-sum-2/src/loss.rs +++ b/crates/ppvm-pauli-sum-2/src/loss.rs @@ -1,9 +1,10 @@ // SPDX-FileCopyrightText: 2026 The PPVM Authors // SPDX-License-Identifier: Apache-2.0 -//! Heisenberg loss maps matching the existing engine. Loss branches clear an -//! observable's loss flag; reset maps I/Z to an additional lost observable. -//! Zero coefficients stay stored, and truncation remains caller-controlled. +//! 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}; @@ -42,24 +43,28 @@ where ) { self.check_pair(a, b); let survive = S::Coeff::one() - (single.clone() + single.clone()) - both.clone(); - let one_lost = S::Coeff::one() - after_loss.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(); - branches[0] = Some((key.loss_cleared(a), weight.clone())); - branches[1] = Some((key.loss_cleared(b), weight)); - let mut cleared = key.loss_cleared(a); - cleared.clear_lost(b); - branches[2] = Some((cleared, coeff.clone() * both.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())), + ]; } - (lost_a, lost_b) if lost_a || lost_b => { - let qubit = if lost_a { a } else { b }; - branches[0] = Some((key.loss_cleared(qubit), coeff.clone() * single.clone())); - *coeff *= &one_lost; + // 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; } - _ => *coeff *= &survive, } branches.into_iter().flatten() }); diff --git a/crates/ppvm-pauli-sum-2/src/noise.rs b/crates/ppvm-pauli-sum-2/src/noise.rs index 6afb910c4..6de90374f 100644 --- a/crates/ppvm-pauli-sum-2/src/noise.rs +++ b/crates/ppvm-pauli-sum-2/src/noise.rs @@ -2,9 +2,10 @@ // 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. Lost sites -//! are skipped, matching the tableau, where gates and errors skip lost qubits. -//! Probabilities are assumed valid; coefficients may be complex. +//! 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::{ @@ -13,6 +14,16 @@ use ppvm_traits_2::{ 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, @@ -23,6 +34,7 @@ where 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()), @@ -30,8 +42,9 @@ where factor(px, pz), ]; self.storage.update_coefficients(|key, coeff| { - if !key.is_lost(qubit) && key.pauli_code(qubit) != 0 { - *coeff *= &factors[key.pauli_code(qubit) as usize]; + let code = live_code(key, qubit); + if code != 0 { + *coeff *= &factors[code]; } }); } @@ -43,40 +56,30 @@ where { 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 word codes use I,X,Z,Y. - let codes = [0u8, 1, 3, 2]; + // 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; - let anti = |x: u8, y: u8| ((x & 1) & (y >> 1)) ^ ((x >> 1) & (y & 1)); - if anti((pair / 4) as u8, codes[error / 4]) - ^ anti((pair % 4) as u8, codes[error % 4]) - != 0 - { + 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 x = if key.is_lost(a) { - 0 - } else { - key.pauli_code(a) as usize - }; - let y = if key.is_lost(b) { - 0 - } else { - key.pauli_code(b) as usize - }; - if x != 0 || y != 0 { - *coeff *= &factors[x * 4 + y]; + 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, @@ -86,13 +89,14 @@ where self.check_qubit(qubit); let factor = S::Coeff::one() - p * S::Coeff::from(4.0 / 3.0); self.storage.update_coefficients(|key, coeff| { - if !key.is_lost(qubit) && key.pauli_code(qubit) != 0 { + 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, @@ -102,9 +106,7 @@ where 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 { + if live_code(key, a) != 0 || live_code(key, b) != 0 { *coeff *= &factor; } }); diff --git a/crates/ppvm-pauli-sum-2/src/store.rs b/crates/ppvm-pauli-sum-2/src/store.rs index a3e22a1f0..397a19569 100644 --- a/crates/ppvm-pauli-sum-2/src/store.rs +++ b/crates/ppvm-pauli-sum-2/src/store.rs @@ -28,12 +28,6 @@ pub trait RekeyBijective: Support { ); } -/// Negate selected coefficients without moving keys or rebuilding storage. -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); -} - /// Change coefficients without copying keys or generating terms. pub trait UpdateCoefficients: Support { /// Visit each coefficient in place, preserving keys and explicit zeros. @@ -171,16 +165,6 @@ impl RekeyBijective for HashMapStore { } } -impl SignFlipByKey for HashMapStore { - fn flip_sign_by_key(&mut self, negate: impl Fn(&K) -> bool) { - for (key, coeff) in &mut self.terms { - if negate(key) { - coeff.mul_sign_assign(-1); - } - } - } -} - impl UpdateCoefficients for HashMapStore { fn update_coefficients(&mut self, mut update: impl FnMut(&K, &mut C)) { for (key, coeff) in &mut self.terms { diff --git a/crates/ppvm-pauli-sum-2/tests/damping.rs b/crates/ppvm-pauli-sum-2/tests/damping.rs index dcd5f574b..774897e0d 100644 --- a/crates/ppvm-pauli-sum-2/tests/damping.rs +++ b/crates/ppvm-pauli-sum-2/tests/damping.rs @@ -20,28 +20,16 @@ fn amplitude_damping_merges_into_identity_after_original_updates() { } #[test] -fn full_damping_keeps_zero_terms() { - let mut sum = PauliSum::::new(1); - for word in ["I", "X", "Y", "Z"] { - sum += (word, 1.0); - } +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(), 4); - assert_eq!(sum.get(&PauliWord::from("I")), Some(2.0)); - for word in ["X", "Y", "Z"] { + 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)); } -} - -#[test] -fn damping_does_not_reduce_or_truncate() { - let mut sum = PauliSum::::with_policy(1, CoefficientThreshold { threshold: 10.0 }); - sum += ("Z", 1.0); - sum.amplitude_damping(0, 0.0); - assert_eq!(sum.get(&PauliWord::from("I")), Some(0.0)); - assert_eq!(sum.len(), 2); - sum.reduce(); - assert_eq!(sum.len(), 1); sum.truncate(); assert!(sum.is_empty()); } diff --git a/crates/ppvm-pauli-sum-2/tests/noise.rs b/crates/ppvm-pauli-sum-2/tests/noise.rs index 3045fb4c2..fe30adb7e 100644 --- a/crates/ppvm-pauli-sum-2/tests/noise.rs +++ b/crates/ppvm-pauli-sum-2/tests/noise.rs @@ -97,22 +97,6 @@ fn noise_does_not_reduce_or_truncate() { assert!(sum.is_empty()); } -#[test] -fn noise_batches_match_scalar_calls() { - let mut sum = PauliSum::::new(2); - sum += ("XY", 2.0); - sum += ("ZZ", 3.0); - let mut expected = sum.clone(); - sum.pauli_error_many(&[1, 0, 1], [0.1, 0.2, 0.3]); - for q in [1, 0, 1] { - expected.pauli_error(q, [0.1, 0.2, 0.3]); - } - sum.depolarize2_many(&[(0, 1), (1, 0)], 0.3); - expected.depolarize2(0, 1, 0.3); - expected.depolarize2(1, 0, 0.3); - assert_abs_diff_eq!(sum, expected, epsilon = 1e-12); -} - #[test] fn invalid_noise_targets_panic_before_mutation() { use std::panic::{AssertUnwindSafe, catch_unwind}; From f3f3fe9ba1f24a28aeb2a9e96763874b71b7903d Mon Sep 17 00:00:00 2001 From: jonhas colina Date: Mon, 23 Nov 2026 01:22:47 -0500 Subject: [PATCH 4/5] perf(ppvm-pauli-sum-2): restore direct sign-flip path for Clifford X/Y/Z --- crates/ppvm-pauli-sum-2/src/clifford.rs | 28 +++++++++++-------------- crates/ppvm-pauli-sum-2/src/lib.rs | 4 +++- crates/ppvm-pauli-sum-2/src/noise.rs | 4 +++- crates/ppvm-pauli-sum-2/src/store.rs | 18 ++++++++++++++++ 4 files changed, 36 insertions(+), 18 deletions(-) diff --git a/crates/ppvm-pauli-sum-2/src/clifford.rs b/crates/ppvm-pauli-sum-2/src/clifford.rs index 78f4408f1..dc1ff4a07 100644 --- a/crates/ppvm-pauli-sum-2/src/clifford.rs +++ b/crates/ppvm-pauli-sum-2/src/clifford.rs @@ -4,7 +4,7 @@ use ppvm_phased_pauli_word_2::Phased; use ppvm_traits_2::{Clifford, CliffordBatch, Coefficient, PauliBits, Phase, loss::LossInfo}; -use crate::{RekeyBijective, Sum, UpdateCoefficients}; +use crate::{RekeyBijective, SignFlipByKey, Sum}; /// Whether a gate on `qubit` can change `key`: every Clifford fixes `I` and lost sites. fn active(key: &K, qubit: usize) -> bool { @@ -93,15 +93,7 @@ where } } -impl Sum { - fn flip_signs(&mut self, negate: impl Fn(&S::Key) -> bool) { - self.storage.update_coefficients(|key, coeff| { - if negate(key) { - coeff.mul_sign_assign(-1); - } - }); - } - +impl Sum { fn flip_signs_many(&mut self, indices: &[usize], negate: impl Fn(&S::Key, usize) -> bool) { if indices.is_empty() { return; @@ -109,7 +101,8 @@ impl Sum { for &qubit in indices { self.check_qubit(qubit); } - self.flip_signs(|key| indices.iter().fold(false, |flip, &q| flip ^ negate(key, q))); + self.storage + .flip_sign_by_key(|key| indices.iter().fold(false, |flip, &q| flip ^ negate(key, q))); } } @@ -117,23 +110,26 @@ impl Sum { /// Two-qubit gates also require distinct indices, including on empty sums. impl Clifford for Sum where - S: RekeyBijective + UpdateCoefficients, + S: RekeyBijective + SignFlipByKey, S::Key: PauliBits + LossInfo, Phased: Clifford, { fn x(&mut self, qubit: usize) { self.check_qubit(qubit); - self.flip_signs(|key| !key.is_lost(qubit) && key.z_bit(qubit)); + self.storage + .flip_sign_by_key(|key| !key.is_lost(qubit) && key.z_bit(qubit)); } fn y(&mut self, qubit: usize) { self.check_qubit(qubit); - self.flip_signs(|key| !key.is_lost(qubit) && (key.x_bit(qubit) ^ key.z_bit(qubit))); + self.storage + .flip_sign_by_key(|key| !key.is_lost(qubit) && (key.x_bit(qubit) ^ key.z_bit(qubit))); } fn z(&mut self, qubit: usize) { self.check_qubit(qubit); - self.flip_signs(|key| !key.is_lost(qubit) && key.x_bit(qubit)); + self.storage + .flip_sign_by_key(|key| !key.is_lost(qubit) && key.x_bit(qubit)); } fn h(&mut self, qubit: usize) { @@ -181,7 +177,7 @@ where /// Pauli batches only update signs. Validate the whole batch before changing terms. impl CliffordBatch for Sum where - S: RekeyBijective + UpdateCoefficients, + S: RekeyBijective + SignFlipByKey, S::Key: PauliBits + LossInfo, Phased: Clifford, { diff --git a/crates/ppvm-pauli-sum-2/src/lib.rs b/crates/ppvm-pauli-sum-2/src/lib.rs index d8c02459d..c0df8bc72 100644 --- a/crates/ppvm-pauli-sum-2/src/lib.rs +++ b/crates/ppvm-pauli-sum-2/src/lib.rs @@ -16,7 +16,9 @@ mod sum; pub use policy::{ CoefficientThreshold, CombinedPolicy, MaxLossWeight, MaxPauliWeight, NoPolicy, Policy, }; -pub use store::{BranchInPlace, HashMapStore, RekeyBijective, StoreAlloc, UpdateCoefficients}; +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/noise.rs b/crates/ppvm-pauli-sum-2/src/noise.rs index 6de90374f..0f099d7ba 100644 --- a/crates/ppvm-pauli-sum-2/src/noise.rs +++ b/crates/ppvm-pauli-sum-2/src/noise.rs @@ -106,7 +106,9 @@ where self.check_pair(a, b); let factor = S::Coeff::one() - p * S::Coeff::from(16.0 / 15.0); self.storage.update_coefficients(|key, coeff| { - if live_code(key, a) != 0 || live_code(key, b) != 0 { + 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 397a19569..05514bf89 100644 --- a/crates/ppvm-pauli-sum-2/src/store.rs +++ b/crates/ppvm-pauli-sum-2/src/store.rs @@ -28,6 +28,14 @@ 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); +} + /// Change coefficients without copying keys or generating terms. pub trait UpdateCoefficients: Support { /// Visit each coefficient in place, preserving keys and explicit zeros. @@ -165,6 +173,16 @@ impl RekeyBijective for HashMapStore { } } +impl SignFlipByKey for HashMapStore { + fn flip_sign_by_key(&mut self, negate: impl Fn(&K) -> bool) { + for (key, coeff) in &mut self.terms { + if negate(key) { + coeff.mul_sign_assign(-1); + } + } + } +} + impl UpdateCoefficients for HashMapStore { fn update_coefficients(&mut self, mut update: impl FnMut(&K, &mut C)) { for (key, coeff) in &mut self.terms { From 0998b164a3c3a9caccf91eb2c7ddb2af6b599496 Mon Sep 17 00:00:00 2001 From: jonhas colina Date: Mon, 23 Nov 2026 01:27:22 -0500 Subject: [PATCH 5/5] test(ppvm-pauli-sum-2): cover BranchInPlace multi-branch merge semantics --- crates/ppvm-pauli-sum-2/src/store/tests.rs | 31 ++++++++++++++++++++++ 1 file changed, 31 insertions(+) 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");