diff --git a/Cargo.lock b/Cargo.lock index df9386f70..4f01e3265 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -126,6 +126,7 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6" dependencies = [ + "num-complex", "num-traits", ] @@ -2238,9 +2239,11 @@ dependencies = [ name = "ppvm-pauli-sum-2" version = "0.3.0" dependencies = [ + "approx", "num", "ppvm-lossy-pauli-word-2", "ppvm-pauli-word-2", + "ppvm-phased-pauli-word-2", "ppvm-traits-2", ] diff --git a/crates/ppvm-pauli-sum-2/Cargo.toml b/crates/ppvm-pauli-sum-2/Cargo.toml index 1d9f73d87..b68144306 100644 --- a/crates/ppvm-pauli-sum-2/Cargo.toml +++ b/crates/ppvm-pauli-sum-2/Cargo.toml @@ -13,6 +13,6 @@ publish = false ppvm-traits-2 = { path = "../ppvm-traits-2" } ppvm-pauli-word-2 = { path = "../ppvm-pauli-word-2" } ppvm-lossy-pauli-word-2 = { path = "../ppvm-lossy-pauli-word-2" } - -[dev-dependencies] +ppvm-phased-pauli-word-2 = { path = "../ppvm-phased-pauli-word-2" } num = "0.4" +approx = { version = "0.5.1", features = ["num-complex"] } diff --git a/crates/ppvm-pauli-sum-2/src/clifford.rs b/crates/ppvm-pauli-sum-2/src/clifford.rs new file mode 100644 index 000000000..5aebcf84e --- /dev/null +++ b/crates/ppvm-pauli-sum-2/src/clifford.rs @@ -0,0 +1,261 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +use ppvm_phased_pauli_word_2::Phased; +use ppvm_traits_2::{ + Clifford, CliffordBatch, Coefficient, PauliBits, Phase, Support, loss::LossInfo, +}; + +use crate::{RekeyBijective, SignFlipByKey, Sum}; + +impl Sum { + fn check_qubit(&self, qubit: usize) { + assert!(qubit < self.n_sites(), "qubit out of bounds"); + } + + fn check_pair(&self, qubit0: usize, qubit1: usize) { + self.check_qubit(qubit0); + self.check_qubit(qubit1); + assert_ne!(qubit0, qubit1, "two-qubit gates require distinct qubits"); + } +} + +/// Whether a gate on `qubit` can change `key`: every Clifford fixes `I` and lost sites. +fn active(key: &K, qubit: usize) -> bool { + !key.is_lost(qubit) && (key.x_bit(qubit) || key.z_bit(qubit)) +} + +impl Sum +where + S::Key: PauliBits + LossInfo, +{ + /// Conjugate the terms for which `touched` is true; all others are left in place. + fn conjugate_terms( + &mut self, + touched: impl Fn(&S::Key) -> bool, + gate: impl Fn(&mut Phased), + ) { + self.storage.rekey_bijective(|key, coeff| { + if !touched(key) { + return None; + } + let mut phased_word = Phased::new(key.clone()); + gate(&mut phased_word); + let (new_key, phase) = phased_word.into_parts(); + // Keys carry no phase; absorb the conjugation sign into the coefficient. + match phase { + Phase::Pos1 => {} + Phase::Neg1 => coeff.mul_sign_assign(-1), + _ => unreachable!("Clifford conjugation produces only real signs"), + } + (new_key != *key).then_some(new_key) + }); + } + + fn conjugate_single(&mut self, qubit: usize, gate: impl Fn(&mut Phased)) { + self.check_qubit(qubit); + self.conjugate_terms(|key| active(key, qubit), gate); + } + + fn conjugate_pair(&mut self, a: usize, b: usize, gate: impl Fn(&mut Phased)) { + self.check_pair(a, b); + self.conjugate_terms(|key| active(key, a) || active(key, b), gate); + } + + fn conjugate_single_batch( + &mut self, + indices: &[usize], + gate: impl Fn(&mut Phased, usize), + ) { + for &qubit in indices { + self.check_qubit(qubit); + } + match indices { + [] => {} + &[qubit] => self.conjugate_single(qubit, |word| gate(word, qubit)), + _ => self.conjugate_terms( + |key| indices.iter().any(|&q| active(key, q)), + |word| { + for &qubit in indices { + gate(word, qubit); + } + }, + ), + } + } + + fn conjugate_pair_batch( + &mut self, + pairs: &[(usize, usize)], + gate: impl Fn(&mut Phased, usize, usize), + ) { + for &(a, b) in pairs { + self.check_pair(a, b); + } + match pairs { + [] => {} + &[(a, b)] => self.conjugate_pair(a, b, |word| gate(word, a, b)), + _ => self.conjugate_terms( + |key| pairs.iter().any(|&(a, b)| active(key, a) || active(key, b)), + |word| { + for &(a, b) in pairs { + gate(word, a, b); + } + }, + ), + } + } +} + +impl Sum { + fn flip_signs_many(&mut self, indices: &[usize], negate: impl Fn(&S::Key, usize) -> bool) { + if indices.is_empty() { + return; + } + 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))); + } +} + +/// Conjugate each term, validating qubit indices before changing storage. +/// Two-qubit gates also require distinct indices, including on empty sums. +impl Clifford for Sum +where + S: RekeyBijective + SignFlipByKey, + S::Key: PauliBits + LossInfo, +{ + 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)); + } + + 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))); + } + + 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)); + } + + fn h(&mut self, qubit: usize) { + self.conjugate_single(qubit, |word| word.h(qubit)); + } + + fn s(&mut self, qubit: usize) { + self.conjugate_single(qubit, |word| word.s(qubit)); + } + + fn s_dag(&mut self, qubit: usize) { + self.conjugate_single(qubit, |word| word.s_dag(qubit)); + } + + fn sqrt_x(&mut self, qubit: usize) { + self.conjugate_single(qubit, |word| word.sqrt_x(qubit)); + } + + fn sqrt_x_dag(&mut self, qubit: usize) { + self.conjugate_single(qubit, |word| word.sqrt_x_dag(qubit)); + } + + fn sqrt_y(&mut self, qubit: usize) { + self.conjugate_single(qubit, |word| word.sqrt_y(qubit)); + } + + fn sqrt_y_dag(&mut self, qubit: usize) { + self.conjugate_single(qubit, |word| word.sqrt_y_dag(qubit)); + } + + fn cnot(&mut self, control: usize, target: usize) { + self.conjugate_pair(control, target, |word| word.cnot(control, target)); + } + + fn cz(&mut self, qubit0: usize, qubit1: usize) { + self.conjugate_pair(qubit0, qubit1, |word| word.cz(qubit0, qubit1)); + } + + fn cy(&mut self, control: usize, target: usize) { + self.conjugate_pair(control, target, |word| word.cy(control, target)); + } +} + +/// Apply gates in input order, rebuilding storage once per batch of changed keys. +/// Pauli batches only update signs. Validate the whole batch before changing terms. +impl CliffordBatch for Sum +where + S: RekeyBijective + SignFlipByKey, + S::Key: PauliBits + LossInfo, +{ + fn x_many(&mut self, indices: &[usize]) { + if let &[qubit] = indices { + self.x(qubit); + return; + } + self.flip_signs_many(indices, |key, q| !key.is_lost(q) && key.z_bit(q)); + } + + fn y_many(&mut self, indices: &[usize]) { + if let &[qubit] = indices { + self.y(qubit); + return; + } + self.flip_signs_many(indices, |key, q| { + !key.is_lost(q) && (key.x_bit(q) ^ key.z_bit(q)) + }); + } + + fn z_many(&mut self, indices: &[usize]) { + if let &[qubit] = indices { + self.z(qubit); + return; + } + self.flip_signs_many(indices, |key, q| !key.is_lost(q) && key.x_bit(q)); + } + + fn h_many(&mut self, indices: &[usize]) { + self.conjugate_single_batch(indices, Phased::h); + } + + fn s_many(&mut self, indices: &[usize]) { + self.conjugate_single_batch(indices, Phased::s); + } + + fn s_dag_many(&mut self, indices: &[usize]) { + self.conjugate_single_batch(indices, Phased::s_dag); + } + + fn sqrt_x_many(&mut self, indices: &[usize]) { + self.conjugate_single_batch(indices, Phased::sqrt_x); + } + + fn sqrt_x_dag_many(&mut self, indices: &[usize]) { + self.conjugate_single_batch(indices, Phased::sqrt_x_dag); + } + + fn sqrt_y_many(&mut self, indices: &[usize]) { + self.conjugate_single_batch(indices, Phased::sqrt_y); + } + + fn sqrt_y_dag_many(&mut self, indices: &[usize]) { + self.conjugate_single_batch(indices, Phased::sqrt_y_dag); + } + + fn cnot_many(&mut self, pairs: &[(usize, usize)]) { + self.conjugate_pair_batch(pairs, Phased::cnot); + } + + fn cz_many(&mut self, pairs: &[(usize, usize)]) { + self.conjugate_pair_batch(pairs, Phased::cz); + } + + fn cy_many(&mut self, pairs: &[(usize, usize)]) { + self.conjugate_pair_batch(pairs, Phased::cy); + } +} diff --git a/crates/ppvm-pauli-sum-2/src/compare.rs b/crates/ppvm-pauli-sum-2/src/compare.rs new file mode 100644 index 000000000..cff7dbfed --- /dev/null +++ b/crates/ppvm-pauli-sum-2/src/compare.rs @@ -0,0 +1,68 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! Comparisons include width and explicit zero terms, but ignore configuration. + +use approx::{AbsDiffEq, RelativeEq}; +use ppvm_traits_2::Support; + +use crate::Sum; + +impl Sum { + fn compare_coefficients( + &self, + other: &Self, + equal: impl Fn(&S::Coeff, &S::Coeff) -> bool, + ) -> bool { + self.n_sites() == other.n_sites() + && self.len() == other.len() + && self.iter().all(|(key, coeff)| { + other + .get(&key) + .is_some_and(|other_coeff| equal(&coeff, &other_coeff)) + }) + } +} + +impl PartialEq for Sum { + fn eq(&self, other: &Self) -> bool { + self.compare_coefficients(other, |a, b| a == b) + } +} + +impl Eq for Sum where S::Coeff: Eq {} + +impl AbsDiffEq for Sum +where + S::Coeff: AbsDiffEq, + ::Epsilon: Copy, +{ + type Epsilon = ::Epsilon; + + fn default_epsilon() -> Self::Epsilon { + S::Coeff::default_epsilon() + } + + fn abs_diff_eq(&self, other: &Self, epsilon: Self::Epsilon) -> bool { + self.compare_coefficients(other, |a, b| a.abs_diff_eq(b, epsilon)) + } +} + +impl RelativeEq for Sum +where + S::Coeff: RelativeEq, + ::Epsilon: Copy, +{ + fn default_max_relative() -> Self::Epsilon { + S::Coeff::default_max_relative() + } + + fn relative_eq( + &self, + other: &Self, + epsilon: Self::Epsilon, + max_relative: Self::Epsilon, + ) -> bool { + self.compare_coefficients(other, |a, b| a.relative_eq(b, epsilon, max_relative)) + } +} diff --git a/crates/ppvm-pauli-sum-2/src/display.rs b/crates/ppvm-pauli-sum-2/src/display.rs new file mode 100644 index 000000000..0ee9b5c62 --- /dev/null +++ b/crates/ppvm-pauli-sum-2/src/display.rs @@ -0,0 +1,51 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! Terms are sorted by weight; ties retain storage iteration order. +//! Display uses three coefficient decimals, Debug uses eight; empty sums print nothing. + +use std::fmt::{self, Debug, Display}; + +use ppvm_traits_2::{Support, Word}; + +use crate::Sum; + +fn format_terms( + sum: &Sum, + f: &mut fmt::Formatter<'_>, + precision: usize, +) -> fmt::Result +where + S::Key: Word + Display, + S::Coeff: Display, +{ + let mut terms: Vec<_> = sum.iter().collect(); + terms.sort_by_key(|(key, _)| key.weight()); + for (index, (key, coeff)) in terms.iter().enumerate() { + if index != 0 { + write!(f, " + ")?; + } + write!(f, "{coeff:.precision$} * {key}")?; + } + Ok(()) +} + +impl Display for Sum +where + S::Key: Word + Display, + S::Coeff: Display, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + format_terms(self, f, 3) + } +} + +impl Debug for Sum +where + S::Key: Word + Display, + S::Coeff: Display, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + format_terms(self, f, 8) + } +} diff --git a/crates/ppvm-pauli-sum-2/src/lib.rs b/crates/ppvm-pauli-sum-2/src/lib.rs index ca7f1ab8a..d4ce69e63 100644 --- a/crates/ppvm-pauli-sum-2/src/lib.rs +++ b/crates/ppvm-pauli-sum-2/src/lib.rs @@ -1,6 +1,10 @@ // SPDX-FileCopyrightText: 2026 The PPVM Authors // SPDX-License-Identifier: Apache-2.0 +mod clifford; +mod compare; +mod display; +mod ops; mod policy; mod store; mod sum; @@ -8,7 +12,7 @@ mod sum; pub use policy::{ CoefficientThreshold, CombinedPolicy, MaxLossWeight, MaxPauliWeight, NoPolicy, Policy, }; -pub use store::{HashMapStore, StoreAlloc}; +pub use store::{HashMapStore, RekeyBijective, SignFlipByKey, StoreAlloc}; pub use sum::{PreserveSet, Sum}; pub use ppvm_lossy_pauli_word_2::LossyPauliWord; diff --git a/crates/ppvm-pauli-sum-2/src/ops.rs b/crates/ppvm-pauli-sum-2/src/ops.rs new file mode 100644 index 000000000..46a2c3d64 --- /dev/null +++ b/crates/ppvm-pauli-sum-2/src/ops.rs @@ -0,0 +1,157 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +//! Arithmetic accumulates coefficients without reducing or truncating terms. +//! Results retain the left operand's policy and preserved keys. + +use std::ops::{Add, AddAssign, Mul, MulAssign, Sub, SubAssign}; + +use ppvm_traits_2::{Accumulate, Scale, Word}; + +use crate::Sum; + +impl> AddAssign<(K, S::Coeff)> for Sum +where + S::Key: Word, +{ + fn add_assign(&mut self, (key, coeff): (K, S::Coeff)) { + self.add_term(key.into(), coeff); + } +} + +impl AddAssign<&Self> for Sum { + fn add_assign(&mut self, rhs: &Self) { + assert_eq!( + self.n_sites(), + rhs.n_sites(), + "addition requires equal widths" + ); + for (key, coeff) in rhs.iter() { + self.storage.accumulate(key, coeff); + } + } +} + +impl AddAssign for Sum { + fn add_assign(&mut self, rhs: Self) { + *self += &rhs; + } +} + +impl Add<&Self> for Sum { + type Output = Self; + + fn add(mut self, rhs: &Self) -> Self { + self += rhs; + self + } +} + +impl Add for Sum { + type Output = Self; + + fn add(self, rhs: Self) -> Self { + self + &rhs + } +} + +impl Add<&Sum> for &Sum { + type Output = Sum; + + fn add(self, rhs: &Sum) -> Self::Output { + self.clone() + rhs + } +} + +impl Add> for &Sum { + type Output = Sum; + + fn add(self, rhs: Sum) -> Self::Output { + self.clone() + rhs + } +} + +impl SubAssign<&Self> for Sum { + fn sub_assign(&mut self, rhs: &Self) { + assert_eq!( + self.n_sites(), + rhs.n_sites(), + "subtraction requires equal widths" + ); + for (key, coeff) in rhs.iter() { + self.storage.accumulate(key, -coeff); + } + } +} + +impl SubAssign for Sum { + fn sub_assign(&mut self, rhs: Self) { + *self -= &rhs; + } +} + +impl Sub<&Self> for Sum { + type Output = Self; + + fn sub(mut self, rhs: &Self) -> Self { + self -= rhs; + self + } +} + +impl Sub for Sum { + type Output = Self; + + fn sub(self, rhs: Self) -> Self { + self - &rhs + } +} + +impl Sub<&Sum> for &Sum { + type Output = Sum; + + fn sub(self, rhs: &Sum) -> Self::Output { + self.clone() - rhs + } +} + +impl Sub> for &Sum { + type Output = Sum; + + fn sub(self, rhs: Sum) -> Self::Output { + self.clone() - rhs + } +} + +// Each scalar type supports assignment, an owned sum, and a borrowed sum. +macro_rules! scalar_ops { + ($coeff:ty, $scalar:ty) => { + impl, P> MulAssign<$scalar> for Sum { + fn mul_assign(&mut self, rhs: $scalar) { + self.scale(&rhs); + } + } + + impl, P> Mul<$scalar> for Sum { + type Output = Self; + + fn mul(mut self, rhs: $scalar) -> Self { + self *= rhs; + self + } + } + + impl + Clone, P: Clone> Mul<$scalar> for &Sum { + type Output = Sum; + + fn mul(self, rhs: $scalar) -> Self::Output { + self.clone() * rhs + } + } + }; +} + +scalar_ops!(f64, f64); +scalar_ops!(f64, &f64); +scalar_ops!(num::Complex, num::Complex); +scalar_ops!(num::Complex, &num::Complex); diff --git a/crates/ppvm-pauli-sum-2/src/store.rs b/crates/ppvm-pauli-sum-2/src/store.rs index 6b4bfbef5..58f183557 100644 --- a/crates/ppvm-pauli-sum-2/src/store.rs +++ b/crates/ppvm-pauli-sum-2/src/store.rs @@ -17,22 +17,52 @@ pub trait StoreAlloc { fn clear(&mut self); } +/// Replace each key with a unique new key, optionally changing its coefficient. +pub trait RekeyBijective: Support { + /// The callback may update the coefficient in place and returns the new key, + /// or `None` if the key is unchanged. Distinct keys must map to distinct keys. + /// Zero coefficients remain stored; callers must preserve word widths. + fn rekey_bijective( + &mut self, + transform: impl FnMut(&Self::Key, &mut Self::Coeff) -> Option, + ); +} + +/// 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); +} + /// Hash-map storage whose keys supply their own structural digests. /// Exact-zero coefficients remain present until [`Accumulate::reduce`] is called. -#[derive(Debug, Clone)] +#[derive(Debug)] pub struct HashMapStore { terms: HashMap, + // Empty between operations; holds the terms whose keys a gate changes. + moved: Vec<(K, C)>, +} + +impl Clone for HashMapStore { + fn clone(&self) -> Self { + Self { + terms: self.terms.clone(), + moved: Vec::new(), + } + } } impl StoreAlloc for HashMapStore { fn with_capacity(capacity: usize) -> Self { Self { terms: HashMap::with_capacity_and_hasher(capacity, IdentityBuildHasher), + moved: Vec::new(), } } fn clear(&mut self) { self.terms.clear(); + self.moved.clear(); } } @@ -105,5 +135,35 @@ impl Retain for HashMapStore { } } +impl RekeyBijective for HashMapStore { + fn rekey_bijective(&mut self, mut transform: impl FnMut(&K, &mut C) -> Option) { + let mut moved = std::mem::take(&mut self.moved); + // Unchanged keys stay in place; only changed keys move to new buckets. + self.terms.retain(|key, coeff| match transform(key, coeff) { + None => true, + Some(new_key) => { + moved.push((new_key, coeff.clone())); + false + } + }); + // Bijectivity: a changed key cannot land on a key that stayed in place. + for (key, coeff) in moved.drain(..) { + let replaced = self.terms.insert(key, coeff); + debug_assert!(replaced.is_none(), "rekey must preserve distinct keys"); + } + self.moved = moved; + } +} + +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); + } + } + } +} + #[cfg(test)] mod tests; diff --git a/crates/ppvm-pauli-sum-2/src/store/tests.rs b/crates/ppvm-pauli-sum-2/src/store/tests.rs index b1bf4b1bf..5306111bf 100644 --- a/crates/ppvm-pauli-sum-2/src/store/tests.rs +++ b/crates/ppvm-pauli-sum-2/src/store/tests.rs @@ -155,3 +155,51 @@ fn hash_collisions_do_not_merge_distinct_keys() { assert_eq!(store.get(&Key(1)), Some(2.0)); assert_eq!(store.get(&Key(2)), Some(5.0)); } + +#[test] +fn partial_rekey_matches_word_conjugation() { + use crate::PauliSum; + use ppvm_phased_pauli_word_2::Phased; + use ppvm_traits_2::{Clifford, CliffordBatch, Phase}; + + // All 4-qubit words, so most gates leave some terms in place and move others. + let words: Vec<(PauliWord, f64)> = (0..256) + .map(|i| { + let s: String = (0..4) + .map(|q| ['I', 'X', 'Y', 'Z'][(i >> (2 * q)) & 3]) + .collect(); + (PauliWord::from(s.as_str()), i as f64 + 1.0) + }) + .collect(); + type SumGate = fn(&mut PauliSum); + type WordGate = fn(&mut Phased); + let gates: [(SumGate, WordGate); 3] = [ + (|s| s.h(1), |w| w.h(1)), + (|s| s.cnot(2, 0), |w| w.cnot(2, 0)), + ( + |s| s.s_many(&[0, 3]), + |w| { + w.s(0); + w.s(3); + }, + ), + ]; + for (apply_sum, apply_word) in gates { + let mut sum = PauliSum::from_terms(4, words.clone()); + apply_sum(&mut sum); + assert_eq!(sum.len(), words.len()); + for (word, coeff) in words.as_slice() { + let mut phased = Phased::new(*word); + apply_word(&mut phased); + let (key, phase) = phased.into_parts(); + let expected = if phase == Phase::Neg1 { -coeff } else { *coeff }; + assert_eq!(sum.get(&key), Some(expected)); + } + } + + let original: PauliSum = PauliSum::from_terms(4, words.clone()); + let mut twice = original.clone(); + twice.h(2); + twice.h(2); + assert_eq!(twice, original); +} diff --git a/crates/ppvm-pauli-sum-2/src/sum.rs b/crates/ppvm-pauli-sum-2/src/sum.rs index d43a37c65..3c36c00fc 100644 --- a/crates/ppvm-pauli-sum-2/src/sum.rs +++ b/crates/ppvm-pauli-sum-2/src/sum.rs @@ -15,9 +15,14 @@ pub type PreserveSet = HashSet; /// A sparse sum of words and coefficients, all with the same site count. /// Storage determines the key and coefficient types. Reduction and truncation /// are explicit; adding or scaling terms never removes zero coefficients. -#[derive(Debug, Clone)] +/// Arithmetic retains the left operand's policy and preserved keys. +/// Addition and subtraction panic on unequal widths. +/// Exact and approximate comparisons require matching widths and stored keys, +/// including explicit zeros, and compare coefficients independently of policy. +/// Display sorts terms by weight with three coefficient decimals; Debug uses eight. +#[derive(Clone)] pub struct Sum { - storage: S, + pub(crate) storage: S, policy: P, n_sites: usize, preserved_keys: PreserveSet, @@ -35,6 +40,7 @@ impl Sum { } /// Keys protected from [`Self::truncate`]. Absent keys are not inserted. + /// Gates transform stored terms, leaving these key exemptions fixed. pub fn preserved_keys(&self) -> &PreserveSet { &self.preserved_keys } diff --git a/crates/ppvm-pauli-sum-2/tests/arithmetic.rs b/crates/ppvm-pauli-sum-2/tests/arithmetic.rs new file mode 100644 index 000000000..30c83dc11 --- /dev/null +++ b/crates/ppvm-pauli-sum-2/tests/arithmetic.rs @@ -0,0 +1,198 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +// Borrowed and owned operator forms are both part of the API under test. +#![allow(clippy::op_ref)] + +use approx::{AbsDiffEq, RelativeEq}; +use num::Complex; +use ppvm_pauli_sum_2::{CoefficientThreshold, LossyPauliSum, NoPolicy, PauliSum}; +use ppvm_traits_2::Clifford; +use std::panic::{AssertUnwindSafe, catch_unwind}; + +#[test] +fn addition_and_subtraction_accumulate_all_ownership_forms() { + let left = PauliSum::::from_terms(1, [("X".into(), 2.0), ("Z".into(), 3.0)]); + let right = PauliSum::::from_terms(1, [("X".into(), -2.0), ("Y".into(), 4.0)]); + let added = + PauliSum::::from_terms(1, [("X".into(), 0.0), ("Y".into(), 4.0), ("Z".into(), 3.0)]); + let subtracted = PauliSum::::from_terms( + 1, + [("X".into(), 4.0), ("Y".into(), -4.0), ("Z".into(), 3.0)], + ); + assert_eq!(&left + &right, added); + assert_eq!(left.clone() + &right, added); + assert_eq!(&left + right.clone(), added); + assert_eq!(left.clone() + right.clone(), added); + assert_eq!(&left - &right, subtracted); + assert_eq!(left.clone() - &right, subtracted); + assert_eq!(&left - right.clone(), subtracted); + assert_eq!(left.clone() - right.clone(), subtracted); + let mut actual = left.clone(); + actual += &right; + assert_eq!(actual, added); + actual = left.clone(); + actual += right.clone(); + assert_eq!(actual, added); + actual = left.clone(); + actual -= &right; + assert_eq!(actual, subtracted); + actual = left.clone(); + actual -= right; + assert_eq!(actual, subtracted); + actual += ("X", -4.0); + assert_eq!(actual.get(&"X".into()), Some(0.0)); + assert_eq!(left.get(&"X".into()), Some(2.0)); +} + +#[test] +fn arithmetic_keeps_left_configuration_and_explicit_zeros() { + let left = PauliSum::from_terms_with_policy( + 1, + CoefficientThreshold { threshold: 10.0 }, + [("X".into(), 0.25)], + ) + .preserving(["X".into()]); + let right = PauliSum::from_terms_with_policy( + 1, + CoefficientThreshold { threshold: 20.0 }, + [("Z".into(), 0.5)], + ) + .preserving(["Z".into()]); + for sum in [&left + &right, &left - &right] { + assert_eq!(sum.len(), 2); + assert_eq!(sum.policy(), left.policy()); + assert_eq!(sum.preserved_keys(), left.preserved_keys()); + } + let mut cancelled = &left - &left; + assert_eq!(cancelled.get(&"X".into()), Some(0.0)); + cancelled.reduce(); + assert!(cancelled.is_empty()); +} + +#[test] +fn width_errors_happen_before_mutation_including_empty_sums() { + let original = PauliSum::::from_terms(1, [("X".into(), 2.0)]); + let mut left = original.clone(); + for right in [ + PauliSum::::new(2), + PauliSum::from_terms(2, [("XI".into(), 1.0)]), + ] { + assert!(catch_unwind(AssertUnwindSafe(|| left += &right)).is_err()); + assert_eq!(left, original); + assert!(catch_unwind(AssertUnwindSafe(|| left -= &right)).is_err()); + assert_eq!(left, original); + } + assert!(catch_unwind(AssertUnwindSafe(|| left += ("XX", 1.0))).is_err()); + assert_eq!(left, original); + assert!(catch_unwind(|| PauliSum::::new(1) + PauliSum::::new(2)).is_err()); +} + +#[test] +fn scalars_support_owned_and_borrowed_operands_without_reducing() { + let sum = PauliSum::::from_terms(1, [("X".into(), 2.0), ("Z".into(), -3.0)]); + let expected = PauliSum::::from_terms(1, [("X".into(), 4.0), ("Z".into(), -6.0)]); + let scalar = 2.0; + assert_eq!(&sum * scalar, expected); + assert_eq!(&sum * &scalar, expected); + assert_eq!(sum.clone() * scalar, expected); + assert_eq!(sum.clone() * &scalar, expected); + let mut actual = sum.clone(); + actual *= &scalar; + assert_eq!(actual, expected); + actual = sum.clone(); + actual *= scalar; + assert_eq!(actual, expected); + actual *= 0.0; + assert_eq!(actual.len(), 2); + assert_eq!(actual.get(&"X".into()), Some(0.0)); + assert_eq!(sum.get(&"X".into()), Some(2.0)); +} + +#[test] +fn complex_and_lossy_sums_use_the_same_arithmetic() { + let a = LossyPauliSum::>::from_terms(1, [("L".into(), Complex::new(1.0, 2.0))]); + let b = LossyPauliSum::>::from_terms(1, [("L".into(), Complex::new(2.0, -1.0))]); + assert_eq!((&a + &b).get(&"L".into()), Some(Complex::new(3.0, 1.0))); + assert_eq!((&a - &b).get(&"L".into()), Some(Complex::new(-1.0, 3.0))); + let scalar = Complex::new(2.0, -1.0); + let expected = + LossyPauliSum::>::from_terms(1, [("L".into(), Complex::new(4.0, 3.0))]); + assert_eq!(&a * scalar, expected); + assert_eq!(&a * &scalar, expected); + assert_eq!(a.clone() * scalar, expected); + assert_eq!(a.clone() * &scalar, expected); + let mut actual = a.clone(); + actual *= &scalar; + assert_eq!(actual, expected); + actual = a.clone(); + actual *= scalar; + assert_eq!(actual, expected); + assert!(actual.abs_diff_eq(&expected, 1e-12)); + assert!(actual.relative_eq(&expected, 1e-12, 1e-12)); +} + +#[test] +fn equality_compares_values_not_policy_or_scratch() { + let a = PauliSum::from_terms_with_policy( + 1, + CoefficientThreshold { threshold: 1.0 }, + [("X".into(), 2.0), ("Z".into(), 3.0)], + ); + let mut b = PauliSum::with_capacity(1, CoefficientThreshold { threshold: 2.0 }, 64) + .preserving(["X".into()]); + b += ("Z", 3.0); + b += ("X", 2.0); + b.h(0); + b.h(0); + assert_eq!(a, b); + assert!(a.relative_eq(&b, 0.0, 0.0)); + b += ("I", 0.0); + assert_ne!(a, b); + assert!(!a.abs_diff_eq(&b, 100.0)); + b.reduce(); + assert_eq!(a, b); + assert_ne!(PauliSum::::new(1), PauliSum::::new(2)); +} + +#[test] +fn approximate_comparisons_require_matching_keys_and_width() { + let a = PauliSum::::from_terms(1, [("X".into(), 1000.0)]); + let b = PauliSum::::from_terms(1, [("X".into(), 1000.01)]); + assert_ne!(a, b); + assert!(a.abs_diff_eq(&b, 0.02)); + assert!(!a.abs_diff_eq(&b, 0.001)); + assert!(a.relative_eq(&b, 0.0, 1e-4)); + assert!(!a.relative_eq(&b, 0.0, 1e-6)); + let different_key = PauliSum::::from_terms(1, [("Z".into(), 1000.0)]); + assert!(!a.abs_diff_eq(&different_key, 1e9)); + assert!(!a.relative_eq(&different_key, 1e9, 1e9)); + assert!(!PauliSum::::new(1).abs_diff_eq(&PauliSum::new(2), 1e9)); + let nan = PauliSum::::from_terms(1, [("X".into(), f64::NAN)]); + assert_ne!(nan, nan); + assert!(!nan.abs_diff_eq(&nan, 1e-6)); +} + +#[test] +fn formatting_sorts_by_weight_and_includes_zero_terms() { + let sum = PauliSum::::from_terms( + 2, + [ + ("XX".into(), -2.0), + ("II".into(), 1.23456789), + ("IX".into(), 0.0), + ], + ); + assert_eq!(format!("{sum}"), "1.235 * II + 0.000 * IX + -2.000 * XX"); + assert_eq!( + format!("{sum:?}"), + "1.23456789 * II + 0.00000000 * IX + -2.00000000 * XX" + ); + let empty = PauliSum::::with_capacity(2, NoPolicy, 10); + assert_eq!(format!("{empty}"), ""); + assert_eq!(format!("{empty:?}"), ""); + let lossy = LossyPauliSum::::from_terms(2, [("LX".into(), -0.5)]); + assert_eq!(format!("{lossy}"), "-0.500 * LX"); + let complex = PauliSum::>::from_terms(1, [("X".into(), Complex::new(1.0, -2.0))]); + assert_eq!(format!("{complex}"), "1.000-2.000i * X"); +} diff --git a/crates/ppvm-pauli-sum-2/tests/clifford.rs b/crates/ppvm-pauli-sum-2/tests/clifford.rs new file mode 100644 index 000000000..c8b54f2be --- /dev/null +++ b/crates/ppvm-pauli-sum-2/tests/clifford.rs @@ -0,0 +1,261 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +use num::Complex; +use ppvm_pauli_sum_2::{CoefficientThreshold, LossyPauliSum, LossyPauliWord, PauliSum}; +use ppvm_phased_pauli_word_2::Phased; +use ppvm_traits_2::{Clifford, CliffordBatch}; +use std::panic::{AssertUnwindSafe, catch_unwind}; + +type Gate = fn(&mut T, usize, usize); +type Batch = fn(&mut T, &[Q]); + +fn single_batches() -> [Batch; 10] { + [ + T::x_many, + T::y_many, + T::z_many, + T::h_many, + T::s_many, + T::s_dag_many, + T::sqrt_x_many, + T::sqrt_x_dag_many, + T::sqrt_y_many, + T::sqrt_y_dag_many, + ] +} + +fn pair_batches() -> [Batch; 3] { + [T::cnot_many, T::cz_many, T::cy_many] +} + +// Single-qubit gates ignore the second index. +fn gates() -> [Gate; 13] { + [ + |s, q, _| s.x(q), + |s, q, _| s.y(q), + |s, q, _| s.z(q), + |s, q, _| s.h(q), + |s, q, _| s.s(q), + |s, q, _| s.s_dag(q), + |s, q, _| s.sqrt_x(q), + |s, q, _| s.sqrt_x_dag(q), + |s, q, _| s.sqrt_y(q), + |s, q, _| s.sqrt_y_dag(q), + T::cnot, + T::cz, + T::cy, + ] +} + +#[test] +fn propagation_matches_phased_words_including_loss() { + let alphabet = ['I', 'X', 'Y', 'Z', 'L']; + let mut original = LossyPauliSum::::new(2); + for first in alphabet { + for second in alphabet { + let word = LossyPauliWord::from(format!("{first}{second}").as_str()); + original.add_term(word, original.len() as f64); + } + } + for (gate_index, (apply_sum, apply_word)) in gates::() + .into_iter() + .zip(gates::>()) + .enumerate() + { + for (a, b) in [(0, 1), (1, 0)] { + let mut sum = original.clone(); + apply_sum(&mut sum, a, b); + assert_eq!(sum.len(), original.len()); + for (key, coeff) in original.iter() { + let mut expected = Phased::new(key); + apply_word(&mut expected, a, b); + let coeff = if expected.is_positive() { + coeff + } else { + -coeff + }; + assert_eq!( + sum.get(expected.word()), + Some(coeff), + "gate {gate_index}, ({a}, {b})" + ); + } + } + } +} + +#[test] +fn complex_coefficients_absorb_signs_and_preserve_overlap() { + let mut left = PauliSum::>::from_terms( + 2, + [ + ("XY".into(), Complex::new(2.0, 3.0)), + ("IZ".into(), Complex::new(-1.0, 4.0)), + ], + ); + let mut right = PauliSum::from_terms_with_policy( + 2, + CoefficientThreshold { threshold: 10.0 }, + [("XY".into(), Complex::new(1.0, -2.0))], + ); + let overlap = left.hermitian_overlap(&right); + left.z(0); + assert_eq!(left.get(&"XY".into()), Some(Complex::new(-2.0, -3.0))); + right.z(0); + left.h(1); + right.h(1); + left.cnot(0, 1); + right.cnot(0, 1); + assert_eq!(left.get(&"YZ".into()), Some(Complex::new(2.0, 3.0))); + assert_eq!(left.hermitian_overlap(&right), overlap); +} + +#[test] +fn gates_keep_zero_terms_and_leave_truncation_explicit() { + let mut sum = PauliSum::from_terms_with_policy( + 1, + CoefficientThreshold { threshold: 1.0 }, + [("X".into(), 0.0), ("Z".into(), 0.25)], + ) + .preserving(["X".into()]); + sum.h(0); + assert_eq!(sum.len(), 2); + assert_eq!(sum.get(&"Z".into()), Some(0.0)); + assert_eq!(sum.get(&"X".into()), Some(0.25)); + assert!(sum.preserved_keys().contains(&"X".into())); + sum.truncate(); + assert_eq!(sum.len(), 1); + assert_eq!(sum.get(&"X".into()), Some(0.25)); +} + +#[test] +fn invalid_gate_arguments_do_not_change_terms() { + for original in [ + PauliSum::new(2), + PauliSum::from_terms(2, [("XY".into(), 2.0)]), + ] { + for gate in gates::() { + let mut sum = original.clone(); + assert!(catch_unwind(AssertUnwindSafe(|| gate(&mut sum, 2, 0))).is_err()); + assert_eq!(sum, original); + } + for gate in [PauliSum::cnot, PauliSum::cz, PauliSum::cy] { + for (a, b) in [(0, 0), (0, 2)] { + let mut sum = original.clone(); + assert!(catch_unwind(AssertUnwindSafe(|| gate(&mut sum, a, b))).is_err()); + assert_eq!(sum, original); + } + } + } +} + +#[test] +fn batches_match_scalar_gates_with_repeated_targets_and_loss() { + type TestSum = LossyPauliSum, CoefficientThreshold>; + let original = TestSum::from_terms_with_policy( + 3, + CoefficientThreshold { threshold: 10.0 }, + [ + ("XYZ".into(), Complex::new(2.0, 3.0)), + ("ZIX".into(), Complex::new(0.0, 0.0)), + ("LXY".into(), Complex::new(-1.0, 4.0)), + ("YLL".into(), Complex::new(3.0, -2.0)), + ], + ) + .preserving(["XYZ".into()]); + + for (batch, scalar) in single_batches::() + .into_iter() + .zip(gates::()) + { + for indices in [&[][..], &[0], &[2, 0, 2, 1]] { + let mut actual = original.clone(); + let mut expected = original.clone(); + batch(&mut actual, indices); + for &q in indices { + scalar(&mut expected, q, 0); + } + assert_eq!(actual, expected); + assert_eq!(actual.policy(), original.policy()); + assert_eq!(actual.preserved_keys(), original.preserved_keys()); + } + } + for (batch, scalar) in pair_batches::() + .into_iter() + .zip(&gates::()[10..]) + { + for pairs in [ + &[][..], + &[(0, 1)], + &[(0, 1), (1, 2)], + &[(0, 1), (1, 2), (0, 2), (0, 1)], + ] { + for reverse in [false, true] { + let mut pairs = pairs.to_vec(); + if reverse { + pairs.reverse(); + } + let mut actual = original.clone(); + let mut expected = original.clone(); + batch(&mut actual, &pairs); + for &(a, b) in &pairs { + scalar(&mut expected, a, b); + } + assert_eq!(actual, expected, "pairs={pairs:?}, reverse={reverse}"); + assert_eq!(actual.policy(), original.policy()); + assert_eq!(actual.preserved_keys(), original.preserved_keys()); + } + } + } +} + +#[test] +fn invalid_batches_are_rejected_before_any_gate_runs() { + for original in [ + PauliSum::new(2), + PauliSum::from_terms(2, [("XY".into(), 2.0)]), + ] { + for batch in single_batches::() { + let mut sum = original.clone(); + assert!(catch_unwind(AssertUnwindSafe(|| batch(&mut sum, &[0, 2]))).is_err()); + assert_eq!(sum, original); + } + for batch in pair_batches::() { + for invalid in [(0, 2), (2, 0), (1, 1)] { + let mut sum = original.clone(); + assert!( + catch_unwind(AssertUnwindSafe(|| { + batch(&mut sum, &[(0, 1), invalid]); + })) + .is_err() + ); + assert_eq!(sum, original); + } + } + } +} + +#[test] +fn aliases_follow_gate_order() { + let mut actual = PauliSum::from_terms( + 3, + [ + ("XYZ".into(), 2.0), + ("IXZ".into(), -3.0), + ("ZIX".into(), 0.0), + ], + ); + let mut expected = actual.clone(); + let aliases: [(Gate, Gate); 4] = [ + (PauliSum::cx, PauliSum::cnot), + (PauliSum::zcx, PauliSum::cnot), + (PauliSum::zcz, PauliSum::cz), + (PauliSum::zcy, PauliSum::cy), + ]; + for (alias, gate) in aliases { + alias(&mut actual, 0, 1); + gate(&mut expected, 0, 1); + assert_eq!(actual, expected); + } +} diff --git a/crates/ppvm-traits-2/src/gates/clifford.rs b/crates/ppvm-traits-2/src/gates/clifford.rs index 431f21f4d..9606b36e5 100644 --- a/crates/ppvm-traits-2/src/gates/clifford.rs +++ b/crates/ppvm-traits-2/src/gates/clifford.rs @@ -50,8 +50,8 @@ pub trait Clifford { } /// Batched Clifford gates: apply the same gate to many qubits in one call. -/// The defaults loop over [`Clifford`] and are load-bearing — fused backends -/// (bit-plane tableaus) override them, term-wise ones take the empty impl. +/// Defaults apply scalar gates in input order. Backends can override them to +/// process each term once or use fused bit-plane operations. pub trait CliffordBatch: Clifford { /// Apply Pauli `X` to every qubit in `indices`. fn x_many(&mut self, indices: &[usize]) {