Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/ppvm-pauli-sum-2/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
38 changes: 38 additions & 0 deletions crates/ppvm-pauli-sum-2/src/damping.rs
Original file line number Diff line number Diff line change
@@ -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<S: BranchInPlace, P> AmplitudeDamping<S::Coeff> for Sum<S, P>
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))
});
}
}
7 changes: 6 additions & 1 deletion crates/ppvm-pauli-sum-2/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@

mod clifford;
mod compare;
mod damping;
mod display;
mod loss;
mod noise;
mod ops;
mod policy;
mod rotation;
Expand All @@ -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;
Expand Down
93 changes: 93 additions & 0 deletions crates/ppvm-pauli-sum-2/src/loss.rs
Original file line number Diff line number Diff line change
@@ -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<S: BranchInPlace, P> LossChannel<S::Coeff> for Sum<S, P>
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<S: BranchInPlace, P> CorrelatedLossChannel<S::Coeff> for Sum<S, P>
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<S: BranchInPlace, P> ResetLossChannel for Sum<S, P>
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()))
});
}
}
116 changes: 116 additions & 0 deletions crates/ppvm-pauli-sum-2/src/noise.rs
Original file line number Diff line number Diff line change
@@ -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<K: PauliBits + LossInfo>(key: &K, qubit: usize) -> usize {
if key.is_lost(qubit) {
0
} else {
key.pauli_code(qubit) as usize
}
}

impl<S: UpdateCoefficients, P> PauliError<S::Coeff> for Sum<S, P>
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<S: UpdateCoefficients, P> TwoQubitPauliError<S::Coeff> for Sum<S, P>
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<S: UpdateCoefficients, P> Depolarizing<S::Coeff> for Sum<S, P>
where
S::Key: PauliBits + LossInfo,
S::Coeff: From<f64>,
{
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<S: UpdateCoefficients, P> Depolarizing2<S::Coeff> for Sum<S, P>
where
S::Key: PauliBits + LossInfo,
S::Coeff: From<f64>,
{
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;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you re-use the live_code helper here?

let active_b = !key.is_lost(b) && key.pauli_code(b) != 0;
if active_a || active_b {
*coeff *= &factor;
}
});
}
}
31 changes: 24 additions & 7 deletions crates/ppvm-pauli-sum-2/src/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<I: IntoIterator<Item = (Self::Key, Self::Coeff)>>(
&mut self,
transform: impl FnMut(&Self::Key, &mut Self::Coeff) -> Option<(Self::Key, Self::Coeff)>,
transform: impl FnMut(&Self::Key, &mut Self::Coeff) -> I,
);
}

Expand Down Expand Up @@ -175,13 +183,22 @@ impl<K: Indexable, C: Coefficient> SignFlipByKey for HashMapStore<K, C> {
}
}

impl<K: Indexable, C: Coefficient> UpdateCoefficients for HashMapStore<K, C> {
fn update_coefficients(&mut self, mut update: impl FnMut(&K, &mut C)) {
for (key, coeff) in &mut self.terms {
update(key, coeff);
}
}
}

impl<K: Indexable, C: Coefficient> BranchInPlace for HashMapStore<K, C> {
fn branch_in_place(&mut self, mut transform: impl FnMut(&K, &mut C) -> Option<(K, C)>) {
fn branch_in_place<I: IntoIterator<Item = (K, C)>>(
&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);
Expand Down
31 changes: 31 additions & 0 deletions crates/ppvm-pauli-sum-2/src/store/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
Loading
Loading