From 917c4832f7d54e18045ed7eaad4566ba395867a5 Mon Sep 17 00:00:00 2001 From: jonhas colina Date: Mon, 16 Nov 2026 18:58:26 -0500 Subject: [PATCH 1/9] introducing ppvm-pauli-sum-2 that adds HashMapStore and Sum, along with truncation policies --- Cargo.lock | 17 ++ Cargo.toml | 1 + crates/ppvm-pauli-sum-2/Cargo.toml | 19 ++ crates/ppvm-pauli-sum-2/src/lib.rs | 21 ++ crates/ppvm-pauli-sum-2/src/policy.rs | 128 ++++++++++ crates/ppvm-pauli-sum-2/src/store.rs | 125 ++++++++++ crates/ppvm-pauli-sum-2/src/store/tests.rs | 157 ++++++++++++ crates/ppvm-pauli-sum-2/src/sum.rs | 254 ++++++++++++++++++++ crates/ppvm-pauli-sum-2/tests/sum.rs | 125 ++++++++++ crates/ppvm-pauli-sum-2/tests/truncation.rs | 161 +++++++++++++ 10 files changed, 1008 insertions(+) create mode 100644 crates/ppvm-pauli-sum-2/Cargo.toml create mode 100644 crates/ppvm-pauli-sum-2/src/lib.rs create mode 100644 crates/ppvm-pauli-sum-2/src/policy.rs create mode 100644 crates/ppvm-pauli-sum-2/src/store.rs create mode 100644 crates/ppvm-pauli-sum-2/src/store/tests.rs create mode 100644 crates/ppvm-pauli-sum-2/src/sum.rs create mode 100644 crates/ppvm-pauli-sum-2/tests/sum.rs create mode 100644 crates/ppvm-pauli-sum-2/tests/truncation.rs diff --git a/Cargo.lock b/Cargo.lock index fb4b5327a..50fdce8c8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1499,6 +1499,12 @@ version = "0.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5419bdc4f6a9207fbeba6d11b604d481addf78ecd10c11ad51e76c2f6482748d" +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + [[package]] name = "heck" version = "0.5.0" @@ -2234,6 +2240,17 @@ dependencies = [ "rayon", ] +[[package]] +name = "ppvm-pauli-sum-2" +version = "0.3.0" +dependencies = [ + "hashbrown 0.17.1", + "num", + "ppvm-lossy-pauli-word-2", + "ppvm-pauli-word-2", + "ppvm-traits-2", +] + [[package]] name = "ppvm-pauli-word" version = "0.3.0" diff --git a/Cargo.toml b/Cargo.toml index 783125d84..e6ddde52e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,6 +31,7 @@ members = [ # can't silently drift away from the public API. "crates/ppvm-tui", "skills/ppvm-usage/examples/rust", "crates/ppvm-lossy-pauli-word-2", "crates/ppvm-phased-pauli-word-2", + "crates/ppvm-pauli-sum-2", ] # Single version for every crate and the `bloqade-ppvm` Python package diff --git a/crates/ppvm-pauli-sum-2/Cargo.toml b/crates/ppvm-pauli-sum-2/Cargo.toml new file mode 100644 index 000000000..62cca2b31 --- /dev/null +++ b/crates/ppvm-pauli-sum-2/Cargo.toml @@ -0,0 +1,19 @@ +# SPDX-FileCopyrightText: 2026 The PPVM Authors +# SPDX-License-Identifier: Apache-2.0 + +[package] +name = "ppvm-pauli-sum-2" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +publish = false + +[dependencies] +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" } +hashbrown = { version = "0.17.1", default-features = false, features = ["inline-more"] } + +[dev-dependencies] +num = "0.4" diff --git a/crates/ppvm-pauli-sum-2/src/lib.rs b/crates/ppvm-pauli-sum-2/src/lib.rs new file mode 100644 index 000000000..ca7f1ab8a --- /dev/null +++ b/crates/ppvm-pauli-sum-2/src/lib.rs @@ -0,0 +1,21 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +mod policy; +mod store; +mod sum; + +pub use policy::{ + CoefficientThreshold, CombinedPolicy, MaxLossWeight, MaxPauliWeight, NoPolicy, Policy, +}; +pub use store::{HashMapStore, StoreAlloc}; +pub use sum::{PreserveSet, Sum}; + +pub use ppvm_lossy_pauli_word_2::LossyPauliWord; +pub use ppvm_pauli_word_2::PauliWord; + +/// A Pauli sum backed by a hash map, with real coefficients by default. +pub type PauliSum = Sum, P>; + +/// A Pauli sum whose words can represent lost qubits. +pub type LossyPauliSum = Sum, P>; diff --git a/crates/ppvm-pauli-sum-2/src/policy.rs b/crates/ppvm-pauli-sum-2/src/policy.rs new file mode 100644 index 000000000..14e8b0575 --- /dev/null +++ b/crates/ppvm-pauli-sum-2/src/policy.rs @@ -0,0 +1,128 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +use ppvm_traits_2::{Coefficient, Retain, Word, loss::LossInfo}; + +/// A truncation rule, applied only when the caller requests it. +pub trait Policy { + /// Initial capacity hint. Zero lets storage grow as terms are added. + fn capacity(&self, _n_sites: usize) -> usize { + 0 + } + + /// Remove terms according to this policy. + fn truncate>(&self, storage: &mut M); +} + +/// Keep all terms, including those with zero coefficients. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub struct NoPolicy; + +impl Policy for NoPolicy { + fn truncate>(&self, _storage: &mut M) {} +} + +/// Keep terms whose coefficient magnitude is at least `threshold`. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct CoefficientThreshold { + /// Inclusive lower bound on coefficient magnitude. + pub threshold: f64, +} + +impl Default for CoefficientThreshold { + fn default() -> Self { + Self { threshold: 1e-12 } + } +} + +impl Policy for CoefficientThreshold { + fn capacity(&self, n_sites: usize) -> usize { + n_sites.saturating_mul(10) + } + + fn truncate>(&self, storage: &mut M) { + storage.retain(|_, coeff| coeff.magnitude() >= self.threshold); + } +} + +/// Keep words with at most this many non-identity sites, including lost sites. +/// The default, `usize::MAX`, disables this limit. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct MaxPauliWeight(pub usize); + +impl Default for MaxPauliWeight { + fn default() -> Self { + Self(usize::MAX) + } +} + +impl Policy for MaxPauliWeight { + fn capacity(&self, n_sites: usize) -> usize { + n_sites.saturating_mul(10) + } + + fn truncate>(&self, storage: &mut M) { + if self.0 != usize::MAX { + storage.retain(|word, _| word.weight() <= self.0); + } + } +} + +/// Keep words with at most this many lost sites; defaults to `10`. +/// Ordinary Pauli words have loss weight zero. `usize::MAX` disables the limit. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct MaxLossWeight(pub usize); + +impl Default for MaxLossWeight { + fn default() -> Self { + Self(10) + } +} + +impl Policy for MaxLossWeight { + fn capacity(&self, n_sites: usize) -> usize { + n_sites.saturating_mul(10) + } + + fn truncate>(&self, storage: &mut M) { + if self.0 != usize::MAX { + storage.retain(|word, _| word.loss_weight() <= self.0); + } + } +} + +/// Apply two policies in order, retaining terms that survive both. +/// Uses the smaller initial capacity hint; policies can be nested. +/// +/// ``` +/// use ppvm_pauli_sum_2::{CoefficientThreshold, CombinedPolicy, MaxPauliWeight, PauliSum}; +/// +/// let policy = CombinedPolicy(CoefficientThreshold { threshold: 0.5 }, MaxPauliWeight(1)); +/// let mut sum = PauliSum::from_terms_with_policy( +/// 2, +/// policy, +/// [("II".into(), 0.0), ("XI".into(), 0.5), ("XY".into(), 2.0)], +/// ).preserving(["II".into()]); +/// +/// sum.truncate(); +/// assert_eq!(sum.get(&"II".into()), Some(0.0)); // Preserved despite the threshold. +/// assert_eq!(sum.get(&"XI".into()), Some(0.5)); // Meets both inclusive limits. +/// assert!(!sum.contains_key(&"XY".into())); // Exceeds the weight limit. +/// ``` +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub struct CombinedPolicy(pub P1, pub P2); + +impl Policy for CombinedPolicy +where + P1: Policy, + P2: Policy, +{ + fn capacity(&self, n_sites: usize) -> usize { + self.0.capacity(n_sites).min(self.1.capacity(n_sites)) + } + + fn truncate>(&self, storage: &mut M) { + self.0.truncate(storage); + self.1.truncate(storage); + } +} diff --git a/crates/ppvm-pauli-sum-2/src/store.rs b/crates/ppvm-pauli-sum-2/src/store.rs new file mode 100644 index 000000000..e2ed3e795 --- /dev/null +++ b/crates/ppvm-pauli-sum-2/src/store.rs @@ -0,0 +1,125 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +use hashbrown::{HashMap, hash_map::Entry}; +use ppvm_traits_2::{ + Accumulate, Coefficient, IdentityBuildHasher, Indexable, Pair, Retain, Scale, Support, + TermBatch, +}; + +/// Allocation and reuse of sparse-sum storage. +pub trait StoreAlloc { + /// Allocate storage for at least `capacity` terms. + fn with_capacity(capacity: usize) -> Self; + + /// Remove all terms while retaining allocated capacity. + fn clear(&mut self); +} + +/// Hash-map storage whose keys supply their own structural digests. +/// Exact-zero coefficients remain present until [`Accumulate::reduce`] is called. +#[derive(Debug, Clone)] +pub struct HashMapStore { + terms: HashMap, +} + +impl StoreAlloc for HashMapStore { + fn with_capacity(capacity: usize) -> Self { + Self { + terms: HashMap::with_capacity_and_hasher(capacity, IdentityBuildHasher), + } + } + + fn clear(&mut self) { + self.terms.clear(); + } +} + +impl Support for HashMapStore +where + K: Indexable, + C: Coefficient, +{ + type Key = K; + type Coeff = C; + + #[inline] + fn len(&self) -> usize { + self.terms.len() + } + + #[inline] + fn get(&self, key: &K) -> Option { + self.terms.get(key).cloned() + } + + fn iter(&self) -> impl Iterator { + self.terms + .iter() + .map(|(key, coeff)| (key.clone(), coeff.clone())) + } + + fn for_each_ref(&self, mut f: impl FnMut(&K, &C)) { + for (key, coeff) in &self.terms { + f(key, coeff); + } + } +} + +impl Accumulate for HashMapStore +where + K: Indexable, + C: Coefficient, +{ + fn accumulate_batch(&mut self, terms: &TermBatch) { + for (key, coeff) in terms.iter() { + if let Some(value) = self.terms.get_mut(key) { + *value += coeff; + } else { + self.terms.insert(key.clone(), coeff.clone()); + } + } + } + + #[inline] + fn accumulate(&mut self, key: K, coeff: C) { + match self.terms.entry(key) { + Entry::Occupied(mut entry) => *entry.get_mut() += coeff, + Entry::Vacant(entry) => { + entry.insert(coeff); + } + } + } + + fn reduce(&mut self) { + self.terms.retain(|_, coeff| !coeff.is_zero()); + } +} + +impl Scale for HashMapStore +where + K: Indexable, + C: Coefficient, +{ + fn scale(&mut self, scalar: &C) { + for coeff in self.terms.values_mut() { + *coeff *= scalar; + } + } +} + +impl Pair for HashMapStore +where + K: Indexable, + C: Coefficient, +{ +} + +impl Retain for HashMapStore { + fn retain(&mut self, keep: impl Fn(&K, &C) -> bool) { + self.terms.retain(|key, coeff| keep(key, coeff)); + } +} + +#[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 new file mode 100644 index 000000000..b1bf4b1bf --- /dev/null +++ b/crates/ppvm-pauli-sum-2/src/store/tests.rs @@ -0,0 +1,157 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +use num::Complex; +use ppvm_lossy_pauli_word_2::LossyPauliWord; +use ppvm_pauli_word_2::PauliWord; +use ppvm_traits_2::{KeyBatch, TermSink, Word}; + +use super::*; + +type Store = HashMapStore; + +#[test] +fn accumulation_preserves_zero_terms_until_reduce() { + let x = PauliWord::from("X"); + let z = PauliWord::from("Z"); + let mut store = Store::with_capacity(2); + let mut terms = TermBatch::new(); + terms.push(x, 2.0); + terms.push(x, -2.0); + terms.push(z, 0.0); + store.accumulate_batch(&terms); + + assert_eq!(store.len(), 2); + assert_eq!(store.get(&x), Some(0.0)); + assert_eq!(store.get(&z), Some(0.0)); + + terms.clear(); + terms.push(x, 3.0); + store.accumulate_batch(&terms); + store.accumulate(x, -1.0); + store.reduce(); + assert_eq!(store.len(), 1); + assert_eq!(store.get(&x), Some(2.0)); + assert_eq!(store.get(&z), None); +} + +#[test] +fn scaling_and_retaining_do_not_implicitly_reduce() { + let mut store = Store::with_capacity(3); + for (word, coeff) in [("II", 1.0), ("XI", 2.0), ("XY", 3.0)] { + store.accumulate(word.into(), coeff); + } + store.scale(&2.0); + store.retain(|key, coeff| key.weight() <= 1 && *coeff >= 4.0); + assert_eq!(store.len(), 1); + assert_eq!(store.get(&"XI".into()), Some(4.0)); + + store.scale(&0.0); + assert_eq!(store.get(&"XI".into()), Some(0.0)); + store.reduce(); + assert!(store.is_empty()); +} + +#[test] +fn complex_pairings_preserve_operand_order() { + let x = PauliWord::from("X"); + let mut left = HashMapStore::>::with_capacity(2); + left.accumulate(x, Complex::new(1.0, 2.0)); + left.accumulate(PauliWord::from("Z"), Complex::new(5.0, 0.0)); + let mut right = HashMapStore::with_capacity(1); + right.accumulate(x, Complex::new(3.0, 4.0)); + + assert_eq!(left.overlap(&right), Complex::new(-5.0, 10.0)); + assert_eq!(right.overlap(&left), Complex::new(-5.0, 10.0)); + assert_eq!(left.hermitian_overlap(&right), Complex::new(11.0, -2.0)); + assert_eq!(right.hermitian_overlap(&left), Complex::new(11.0, 2.0)); + + let empty = HashMapStore::with_capacity(0); + assert_eq!(left.overlap(&empty), Complex::new(0.0, 0.0)); + assert_eq!(empty.hermitian_overlap(&left), Complex::new(0.0, 0.0)); +} + +#[test] +fn support_iteration_and_batch_probes_agree() { + let x = PauliWord::from("X"); + let z = PauliWord::from("Z"); + let mut store = Store::with_capacity(2); + store.accumulate(x, 2.0); + store.accumulate(z, 0.0); + + let mut visited = Vec::new(); + store.for_each_ref(|key, coeff| visited.push((*key, *coeff))); + assert_eq!(visited, store.iter().collect::>()); + + let mut keys = KeyBatch::new(); + keys.push(z); + keys.push(PauliWord::from("I")); + keys.push(x); + keys.fill_hashes(); + let mut values = [None; 3]; + store.probe_batch(&keys, &mut values); + assert_eq!(values, [Some(0.0), None, Some(2.0)]); +} + +#[test] +fn lossy_words_keep_distinct_support() { + let mut store = HashMapStore::::with_capacity(2); + store.accumulate("LI".into(), 2.0); + store.accumulate("II".into(), 3.0); + store.accumulate("LI".into(), -1.0); + assert_eq!(store.len(), 2); + assert_eq!(store.get(&"LI".into()), Some(1.0)); + store.retain(|key, _| key.loss_weight() == 0); + assert_eq!(store.len(), 1); + assert_eq!(store.get(&"II".into()), Some(3.0)); +} + +#[test] +fn clone_and_clear_keep_storage_independent() { + let x = PauliWord::from("X"); + let mut store = Store::with_capacity(8); + store.accumulate(x, 2.0); + let capacity = store.terms.capacity(); + + let mut cloned = store.clone(); + assert_eq!(cloned.get(&x), Some(2.0)); + cloned.accumulate(x, 1.0); + assert_eq!(store.get(&x), Some(2.0)); + + store.clear(); + assert!(store.is_empty()); + assert_eq!(store.terms.capacity(), capacity); + assert_eq!(cloned.get(&x), Some(3.0)); + store.accumulate(x, 4.0); + assert_eq!(store.get(&x), Some(4.0)); +} + +#[test] +fn hash_collisions_do_not_merge_distinct_keys() { + #[derive(Clone, PartialEq, Eq)] + struct Key(u8); + + impl std::hash::Hash for Key { + fn hash(&self, state: &mut H) { + state.write_u64(self.key_hash()); + } + } + + impl Indexable for Key { + fn key_hash(&self) -> u64 { + 0 + } + } + + let mut store = HashMapStore::with_capacity(2); + store.accumulate(Key(0), 1.0); + store.accumulate(Key(1), 2.0); + let mut batch = TermBatch::new(); + batch.push(Key(0), 3.0); + batch.push(Key(2), 5.0); + store.accumulate_batch(&batch); + assert_eq!(store.len(), 3); + assert_eq!(store.get(&Key(0)), Some(4.0)); + assert_eq!(store.get(&Key(1)), Some(2.0)); + assert_eq!(store.get(&Key(2)), Some(5.0)); +} diff --git a/crates/ppvm-pauli-sum-2/src/sum.rs b/crates/ppvm-pauli-sum-2/src/sum.rs new file mode 100644 index 000000000..3427368f6 --- /dev/null +++ b/crates/ppvm-pauli-sum-2/src/sum.rs @@ -0,0 +1,254 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +use std::collections::HashSet; + +use ppvm_traits_2::{ + Accumulate, Conjugate, IdentityBuildHasher, Indexable, Pair, Retain, Scale, Support, Word, +}; + +use crate::{NoPolicy, Policy, StoreAlloc}; + +/// Keys protected from truncation, using their structural digests for lookup. +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)] +pub struct Sum { + storage: S, + policy: P, + n_sites: usize, + preserved_keys: PreserveSet, +} + +impl Sum { + /// Number of sites, including when the sum is empty. + pub fn n_sites(&self) -> usize { + self.n_sites + } + + /// The sum's truncation policy. + pub fn policy(&self) -> &P { + &self.policy + } + + /// Keys protected from [`Self::truncate`]. Absent keys are not inserted. + pub fn preserved_keys(&self) -> &PreserveSet { + &self.preserved_keys + } + + /// Remove all truncation exemptions without changing stored terms. + pub fn clear_preserved_keys(&mut self) { + self.preserved_keys.clear(); + } + + /// Number of stored terms, including zero coefficients. + pub fn len(&self) -> usize { + self.storage.len() + } + + /// Whether there are no stored terms. + pub fn is_empty(&self) -> bool { + self.storage.is_empty() + } + + /// Coefficient at `key`, or `None` if it is absent. + pub fn get(&self, key: &S::Key) -> Option { + self.storage.get(key) + } + + /// Whether this exact key and coefficient are present. + pub fn contains(&self, key: &S::Key, coeff: &S::Coeff) -> bool { + self.get(key).is_some_and(|value| value == *coeff) + } + + /// Whether a key is present, even with a zero coefficient. + pub fn contains_key(&self, key: &S::Key) -> bool { + self.get(key).is_some() + } + + /// Iterate over owned key/coefficient pairs in storage order. + pub fn iter(&self) -> impl Iterator + '_ { + self.storage.iter() + } + + /// Visit terms by reference, avoiding copies when storage supports it. + pub fn for_each_ref(&self, f: impl FnMut(&S::Key, &S::Coeff)) { + self.storage.for_each_ref(f); + } +} + +impl Sum +where + S::Key: Word + Indexable, +{ + /// Protect a key from truncation. Panics if its width does not match. + pub fn preserve_key(&mut self, key: S::Key) { + assert_eq!( + key.n_sites(), + self.n_sites, + "preserved key width must match sum width" + ); + self.preserved_keys.insert(key); + } + + /// Protect these keys from truncation; all must match the sum's width. + #[must_use] + pub fn preserving(mut self, keys: impl IntoIterator) -> Self { + for key in keys { + self.preserve_key(key); + } + self + } +} + +impl Sum { + /// Construct an empty sum with an explicit policy and capacity hint. + pub fn with_capacity(n_sites: usize, policy: P, capacity: usize) -> Self { + Self { + storage: S::with_capacity(capacity), + policy, + n_sites, + preserved_keys: PreserveSet::default(), + } + } + + /// Remove all terms, retaining width, policy, preserved keys, and capacity. + pub fn clear(&mut self) { + self.storage.clear(); + } +} + +impl Sum +where + S: Support + StoreAlloc, + P: Policy, +{ + /// Construct an empty sum with the default policy. + pub fn new(n_sites: usize) -> Self + where + P: Default, + { + Self::with_policy(n_sites, P::default()) + } + + /// Construct an empty sum using the policy's initial capacity hint. + pub fn with_policy(n_sites: usize, policy: P) -> Self { + let capacity = policy.capacity(n_sites); + Self::with_capacity(n_sites, policy, capacity) + } +} + +impl Sum +where + S: Accumulate + StoreAlloc, + S::Key: Word, + P: Policy, +{ + /// Accumulate terms with the default policy. Panics on a width mismatch. + pub fn from_terms(n_sites: usize, terms: impl IntoIterator) -> Self + where + P: Default, + { + Self::from_terms_with_policy(n_sites, P::default(), terms) + } + + /// Accumulate terms with an explicit policy. Panics on a width mismatch. + pub fn from_terms_with_policy( + n_sites: usize, + policy: P, + terms: impl IntoIterator, + ) -> Self { + let mut sum = Self::with_policy(n_sites, policy); + for (key, coeff) in terms { + sum.add_term(key, coeff); + } + sum + } +} + +impl Sum { + /// Add to the coefficient at `key`, inserting it if absent. + /// Panics before changing the sum if the word's width does not match. + pub fn add_term(&mut self, key: S::Key, coeff: S::Coeff) + where + S::Key: Word, + { + assert_eq!( + key.n_sites(), + self.n_sites, + "term width must match sum width" + ); + self.storage.accumulate(key, coeff); + } + + /// Remove coefficients that are exactly zero, including preserved keys. + pub fn reduce(&mut self) { + self.storage.reduce(); + } +} + +impl Sum { + /// Multiply every coefficient by `scalar` without removing any terms. + pub fn scale(&mut self, scalar: &S::Coeff) { + self.storage.scale(scalar); + } +} + +impl Sum { + /// Sum products of matching coefficients, without conjugation. + /// Panics if the sums have different widths. + pub fn overlap(&self, other: &Self) -> S::Coeff { + assert_eq!(self.n_sites, other.n_sites, "overlap requires equal widths"); + self.storage.overlap(&other.storage) + } + + /// Sum products of matching coefficients, conjugating this sum's coefficients. + /// Panics if the sums have different widths. + pub fn hermitian_overlap(&self, other: &Self) -> S::Coeff + where + S::Coeff: Conjugate, + { + assert_eq!(self.n_sites, other.n_sites, "overlap requires equal widths"); + self.storage.hermitian_overlap(&other.storage) + } +} + +impl Sum +where + S: Support + Retain, + S::Key: Indexable, + P: Policy, +{ + /// Apply the policy, leaving preserved terms and their coefficients intact. + /// [`NoPolicy`] leaves every term in place; absent preserved keys stay absent. + pub fn truncate(&mut self) { + self.policy.truncate(&mut ProtectedStorage { + storage: &mut self.storage, + preserved_keys: &self.preserved_keys, + }); + } +} + +/// Let policies filter storage without removing preserved keys. +struct ProtectedStorage<'a, S, K> { + storage: &'a mut S, + preserved_keys: &'a PreserveSet, +} + +impl Retain for ProtectedStorage<'_, S, K> +where + S: Retain, + K: Indexable, +{ + fn retain(&mut self, keep: impl Fn(&K, &C) -> bool) { + if self.preserved_keys.is_empty() { + self.storage.retain(keep); + } else { + self.storage + .retain(|key, coeff| self.preserved_keys.contains(key) || keep(key, coeff)); + } + } +} diff --git a/crates/ppvm-pauli-sum-2/tests/sum.rs b/crates/ppvm-pauli-sum-2/tests/sum.rs new file mode 100644 index 000000000..ee28c93a9 --- /dev/null +++ b/crates/ppvm-pauli-sum-2/tests/sum.rs @@ -0,0 +1,125 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +use num::Complex; +use ppvm_pauli_sum_2::{LossyPauliSum, NoPolicy, PauliSum, PauliWord, Policy}; +use ppvm_traits_2::Retain; +use std::panic::{AssertUnwindSafe, catch_unwind}; + +#[test] +fn empty_sums_retain_their_width() { + let mut sum = PauliSum::::with_capacity(3, NoPolicy, 8); + assert_eq!(sum.n_sites(), 3); + assert!(sum.is_empty()); + sum.add_term("XYZ".into(), 2.0); + let mut cloned = sum.clone(); + sum.clear(); + assert_eq!(sum.n_sites(), 3); + assert!(sum.is_empty()); + assert_eq!(cloned.get(&"XYZ".into()), Some(2.0)); + cloned.add_term("XYZ".into(), -2.0); + cloned.reduce(); + assert!(cloned.is_empty()); + assert_eq!(cloned.n_sites(), 3); + + let mut zero_width = PauliSum::::new(0); + zero_width.add_term("".into(), 1.0); + assert_eq!(zero_width.get(&"".into()), Some(1.0)); +} + +#[test] +fn construction_and_insertion_accumulate_without_reducing() { + let x = PauliWord::from("X"); + let z = PauliWord::from("Z"); + let mut sum = PauliSum::::from_terms(1, [(x, 2.0), (x, -2.0), (z, 3.0)]); + assert_eq!(sum.len(), 2); + assert!(sum.contains(&x, &0.0)); + assert!(!sum.contains(&x, &2.0)); + assert!(sum.contains_key(&x)); + assert!(!sum.contains_key(&"Y".into())); + assert_eq!(sum.policy(), &NoPolicy); + sum.truncate(); + assert_eq!(sum.len(), 2); + sum.add_term(z, 1.0); + sum.scale(&2.0); + assert_eq!(sum.get(&z), Some(8.0)); + sum.reduce(); + assert_eq!(sum.iter().collect::>(), vec![(z, 8.0)]); + let mut visited = Vec::new(); + sum.for_each_ref(|key, coeff| visited.push((*key, *coeff))); + assert_eq!(visited, vec![(z, 8.0)]); +} + +#[test] +fn lossy_alias_uses_the_same_core_operations() { + let mut sum = LossyPauliSum::::from_terms_with_policy( + 2, + NoPolicy, + [("XL".into(), 2.0), ("XI".into(), 3.0), ("XL".into(), -1.0)], + ); + sum.scale(&2.0); + assert_eq!(sum.len(), 2); + assert_eq!(sum.get(&"XL".into()), Some(2.0)); + assert_eq!(sum.get(&"XI".into()), Some(6.0)); + let other = LossyPauliSum::::from_terms(2, [("XL".into(), 3.0)]); + assert_eq!(sum.overlap(&other), 6.0); +} + +#[test] +fn complex_scaling_and_pairing_use_the_storage_algebra() { + let x = PauliWord::from("X"); + let mut left = PauliSum::>::from_terms(1, [(x, Complex::new(1.0, 2.0))]); + left.scale(&Complex::new(0.0, 1.0)); + assert_eq!(left.get(&x), Some(Complex::new(-2.0, 1.0))); + let right = PauliSum::>::from_terms(1, [(x, Complex::new(3.0, 4.0))]); + assert_eq!(left.overlap(&right), Complex::new(-10.0, -5.0)); + assert_eq!(left.hermitian_overlap(&right), Complex::new(-2.0, -11.0)); +} + +#[test] +fn invalid_insertions_leave_the_sum_unchanged() { + let mut sum = PauliSum::::from_terms(2, [("XI".into(), 3.0)]); + let result = catch_unwind(AssertUnwindSafe(|| sum.add_term("X".into(), 2.0))); + assert!(result.is_err()); + assert_eq!(sum.len(), 1); + assert_eq!(sum.get(&"XI".into()), Some(3.0)); + + assert!(catch_unwind(|| PauliSum::::from_terms(2, [("X".into(), 1.0)])).is_err()); + assert!(catch_unwind(|| LossyPauliSum::::from_terms(2, [("L".into(), 1.0)])).is_err()); +} + +#[test] +fn overlap_rejects_different_widths_even_for_empty_sums() { + let left = PauliSum::::new(1); + let right = PauliSum::::new(2); + assert!(catch_unwind(|| left.overlap(&right)).is_err()); + assert!(catch_unwind(|| left.hermitian_overlap(&right)).is_err()); +} + +#[test] +fn explicit_policies_need_neither_default_nor_clone() { + struct KeepAbove(f64); + + impl Policy for KeepAbove { + fn truncate>(&self, storage: &mut M) { + storage.retain(|_, coeff| coeff.abs() >= self.0); + } + } + + let mut sums = [ + PauliSum::with_policy(1, KeepAbove(2.0)), + PauliSum::with_capacity(1, KeepAbove(2.0), 4), + PauliSum::from_terms_with_policy(1, KeepAbove(2.0), []), + ]; + for sum in &mut sums { + sum.add_term("X".into(), 1.0); + sum.add_term("Z".into(), 3.0); + assert_eq!(sum.len(), 2); + sum.truncate(); + assert_eq!(sum.len(), 1); + assert_eq!(sum.get(&"Z".into()), Some(3.0)); + sum.clear(); + assert!(sum.is_empty()); + assert_eq!(sum.policy().0, 2.0); + } +} diff --git a/crates/ppvm-pauli-sum-2/tests/truncation.rs b/crates/ppvm-pauli-sum-2/tests/truncation.rs new file mode 100644 index 000000000..04710e4de --- /dev/null +++ b/crates/ppvm-pauli-sum-2/tests/truncation.rs @@ -0,0 +1,161 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +use num::Complex; +use ppvm_pauli_sum_2::{ + CoefficientThreshold, CombinedPolicy, LossyPauliSum, MaxLossWeight, MaxPauliWeight, PauliSum, +}; +use std::panic::{AssertUnwindSafe, catch_unwind}; + +#[test] +fn threshold_is_inclusive_and_truncation_is_explicit() { + let mut sum = PauliSum::from_terms_with_policy( + 1, + CoefficientThreshold { threshold: 0.5 }, + [ + ("I".into(), 0.25), + ("I".into(), 0.25), + ("X".into(), -0.5), + ("Y".into(), 0.25), + ("Z".into(), 1.0), + ("Z".into(), -1.0), + ], + ); + assert_eq!(sum.len(), 4); + sum.truncate(); + assert_eq!(sum.len(), 2); + assert_eq!(sum.get(&"I".into()), Some(0.5)); + assert_eq!(sum.get(&"X".into()), Some(-0.5)); + sum.scale(&0.5); + assert_eq!(sum.len(), 2); + sum.truncate(); + assert!(sum.is_empty()); +} + +#[test] +fn threshold_uses_complex_magnitude() { + let mut sum = PauliSum::from_terms_with_policy( + 1, + CoefficientThreshold { threshold: 5.0 }, + [ + ("X".into(), Complex::new(3.0, 4.0)), + ("Y".into(), Complex::new(0.0, -4.0)), + ("Z".into(), Complex::new(-6.0, 0.0)), + ], + ); + sum.truncate(); + assert_eq!(sum.len(), 2); + assert!(sum.contains_key(&"X".into())); + assert!(sum.contains_key(&"Z".into())); +} + +#[test] +fn pauli_weight_counts_nonidentity_and_lost_sites() { + let terms = [("II".into(), 1.0), ("XI".into(), 2.0), ("XY".into(), 3.0)]; + for (limit, expected) in [(0, 1), (1, 2), (usize::MAX, 3)] { + let mut sum = PauliSum::from_terms_with_policy(2, MaxPauliWeight(limit), terms); + sum.truncate(); + assert_eq!(sum.len(), expected); + assert_eq!(sum.get(&"II".into()), Some(1.0)); + } + + let mut sum = LossyPauliSum::from_terms_with_policy( + 2, + MaxPauliWeight(1), + [("LI".into(), 1.0), ("LX".into(), 2.0)], + ); + sum.truncate(); + assert_eq!(sum.len(), 1); + assert_eq!(sum.get(&"LI".into()), Some(1.0)); +} + +#[test] +fn loss_weight_only_counts_lost_sites() { + let terms = [("XY".into(), 1.0), ("XL".into(), 2.0), ("LL".into(), 3.0)]; + for (limit, expected) in [(0, 1), (1, 2), (usize::MAX, 3)] { + let mut sum = LossyPauliSum::from_terms_with_policy(2, MaxLossWeight(limit), terms.clone()); + sum.truncate(); + assert_eq!(sum.len(), expected); + assert_eq!(sum.get(&"XY".into()), Some(1.0)); + } + + let mut ordinary = PauliSum::from_terms_with_policy(2, MaxLossWeight(0), [("XY".into(), 1.0)]); + ordinary.truncate(); + assert_eq!(ordinary.len(), 1); +} + +#[test] +fn default_limits_match_the_source_policies() { + assert_eq!(CoefficientThreshold::default().threshold, 1e-12); + assert_eq!(MaxPauliWeight::default().0, usize::MAX); + assert_eq!(MaxLossWeight::default().0, 10); + let mut sum = LossyPauliSum::::from_terms( + 11, + [("LLLLLLLLLLX".into(), 1.0), ("LLLLLLLLLLL".into(), 2.0)], + ); + sum.truncate(); + assert_eq!(sum.len(), 1); + assert_eq!(sum.get(&"LLLLLLLLLLX".into()), Some(1.0)); +} + +#[test] +fn nested_policies_filter_independently_and_preserve_exact_coefficients() { + let mut sum = LossyPauliSum::from_terms_with_policy( + 3, + CombinedPolicy( + CoefficientThreshold { threshold: 0.5 }, + CombinedPolicy(MaxPauliWeight(2), MaxLossWeight(1)), + ), + [ + ("XLI".into(), 0.5), + ("XII".into(), 0.25), + ("XYZ".into(), 2.0), + ("LLI".into(), 3.0), + ("LLL".into(), 0.0), + ], + ) + .preserving(["LLL".into(), "LLL".into(), "YII".into()]); + assert_eq!(sum.preserved_keys().len(), 2); + for _ in 0..2 { + sum.truncate(); + assert_eq!(sum.len(), 2); + assert_eq!(sum.get(&"XLI".into()), Some(0.5)); + assert_eq!(sum.get(&"LLL".into()), Some(0.0)); + assert!(!sum.contains_key(&"YII".into())); + } + sum.add_term("YII".into(), 0.125); + sum.truncate(); + assert_eq!(sum.get(&"YII".into()), Some(0.125)); + sum.reduce(); + assert!(!sum.contains_key(&"LLL".into())); + sum.clear_preserved_keys(); + sum.truncate(); + assert_eq!(sum.len(), 1); + assert_eq!(sum.get(&"XLI".into()), Some(0.5)); +} + +#[test] +fn clearing_terms_keeps_exemptions_and_cloning_is_independent() { + let mut sum = PauliSum::from_terms_with_policy(1, MaxPauliWeight(0), [("X".into(), 2.0)]) + .preserving(["X".into()]); + let mut cloned = sum.clone(); + cloned.clear_preserved_keys(); + cloned.truncate(); + assert!(cloned.is_empty()); + sum.clear(); + assert!(sum.is_empty()); + assert_eq!(sum.preserved_keys().len(), 1); + sum.add_term("X".into(), 3.0); + sum.truncate(); + assert_eq!(sum.get(&"X".into()), Some(3.0)); +} + +#[test] +fn invalid_preserved_width_leaves_sum_unchanged() { + let mut sum = PauliSum::from_terms_with_policy(2, MaxPauliWeight(0), [("XI".into(), 1.0)]) + .preserving(["XI".into()]); + assert!(catch_unwind(AssertUnwindSafe(|| sum.preserve_key("X".into()))).is_err()); + assert_eq!(sum.preserved_keys().len(), 1); + sum.truncate(); + assert_eq!(sum.get(&"XI".into()), Some(1.0)); +} From de5fc4bddec92c6b7a2a2d4d409f5bd1bf41a89c Mon Sep 17 00:00:00 2001 From: jonhas colina Date: Tue, 17 Nov 2026 00:35:49 -0500 Subject: [PATCH 2/9] added clifford to pauli-sum-2 --- Cargo.lock | 1 + crates/ppvm-pauli-sum-2/Cargo.toml | 1 + crates/ppvm-pauli-sum-2/src/clifford.rs | 113 ++++++++++++++ crates/ppvm-pauli-sum-2/src/lib.rs | 3 +- crates/ppvm-pauli-sum-2/src/store.rs | 56 ++++++- crates/ppvm-pauli-sum-2/src/store/tests.rs | 53 +++++++ crates/ppvm-pauli-sum-2/src/sum.rs | 3 +- crates/ppvm-pauli-sum-2/tests/clifford.rs | 169 +++++++++++++++++++++ 8 files changed, 396 insertions(+), 3 deletions(-) create mode 100644 crates/ppvm-pauli-sum-2/src/clifford.rs create mode 100644 crates/ppvm-pauli-sum-2/tests/clifford.rs diff --git a/Cargo.lock b/Cargo.lock index 50fdce8c8..ca99e0977 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2248,6 +2248,7 @@ dependencies = [ "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 62cca2b31..68d51d38c 100644 --- a/crates/ppvm-pauli-sum-2/Cargo.toml +++ b/crates/ppvm-pauli-sum-2/Cargo.toml @@ -13,6 +13,7 @@ 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" } +ppvm-phased-pauli-word-2 = { path = "../ppvm-phased-pauli-word-2" } hashbrown = { version = "0.17.1", default-features = false, features = ["inline-more"] } [dev-dependencies] 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..42bb56a7b --- /dev/null +++ b/crates/ppvm-pauli-sum-2/src/clifford.rs @@ -0,0 +1,113 @@ +// 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, 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"); + } +} + +impl Sum { + fn conjugate_terms(&mut self, gate: impl Fn(&mut Phased)) { + self.storage.rekey_bijective(|key, coeff| { + let mut phased_word = Phased::new(key); + gate(&mut phased_word); + let (key, phase) = phased_word.into_parts(); + // Keys carry no phase; absorb the conjugation sign into the coefficient. + match phase { + Phase::Pos1 => (key, coeff), + Phase::Neg1 => (key, -coeff), + _ => unreachable!("Clifford conjugation produces only real signs"), + } + }); + } +} + +/// 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.check_qubit(qubit); + self.conjugate_terms(|word| word.h(qubit)); + } + + fn s(&mut self, qubit: usize) { + self.check_qubit(qubit); + self.conjugate_terms(|word| word.s(qubit)); + } + + fn s_dag(&mut self, qubit: usize) { + self.check_qubit(qubit); + self.conjugate_terms(|word| word.s_dag(qubit)); + } + + fn sqrt_x(&mut self, qubit: usize) { + self.check_qubit(qubit); + self.conjugate_terms(|word| word.sqrt_x(qubit)); + } + + fn sqrt_x_dag(&mut self, qubit: usize) { + self.check_qubit(qubit); + self.conjugate_terms(|word| word.sqrt_x_dag(qubit)); + } + + fn sqrt_y(&mut self, qubit: usize) { + self.check_qubit(qubit); + self.conjugate_terms(|word| word.sqrt_y(qubit)); + } + + fn sqrt_y_dag(&mut self, qubit: usize) { + self.check_qubit(qubit); + self.conjugate_terms(|word| word.sqrt_y_dag(qubit)); + } + + fn cnot(&mut self, control: usize, target: usize) { + self.check_pair(control, target); + self.conjugate_terms(|word| word.cnot(control, target)); + } + + fn cz(&mut self, qubit0: usize, qubit1: usize) { + self.check_pair(qubit0, qubit1); + self.conjugate_terms(|word| word.cz(qubit0, qubit1)); + } + + fn cy(&mut self, control: usize, target: usize) { + self.check_pair(control, target); + self.conjugate_terms(|word| word.cy(control, target)); + } +} + +impl CliffordBatch for Sum where Self: Clifford {} diff --git a/crates/ppvm-pauli-sum-2/src/lib.rs b/crates/ppvm-pauli-sum-2/src/lib.rs index ca7f1ab8a..abcb0d4ec 100644 --- a/crates/ppvm-pauli-sum-2/src/lib.rs +++ b/crates/ppvm-pauli-sum-2/src/lib.rs @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: 2026 The PPVM Authors // SPDX-License-Identifier: Apache-2.0 +mod clifford; mod policy; mod store; mod sum; @@ -8,7 +9,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/store.rs b/crates/ppvm-pauli-sum-2/src/store.rs index e2ed3e795..c0b307f19 100644 --- a/crates/ppvm-pauli-sum-2/src/store.rs +++ b/crates/ppvm-pauli-sum-2/src/store.rs @@ -16,22 +16,51 @@ 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 must map distinct input keys to distinct output keys. + /// Zero coefficients remain stored; callers must preserve word widths. + fn rekey_bijective( + &mut self, + transform: impl FnMut(Self::Key, Self::Coeff) -> (Self::Key, Self::Coeff), + ); +} + +/// 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; reused when a gate changes keys. + scratch: HashMap, +} + +impl Clone for HashMapStore { + fn clone(&self) -> Self { + Self { + terms: self.terms.clone(), + scratch: HashMap::with_hasher(IdentityBuildHasher), + } + } } impl StoreAlloc for HashMapStore { fn with_capacity(capacity: usize) -> Self { Self { terms: HashMap::with_capacity_and_hasher(capacity, IdentityBuildHasher), + scratch: HashMap::with_hasher(IdentityBuildHasher), } } fn clear(&mut self) { self.terms.clear(); + self.scratch.clear(); } } @@ -115,6 +144,31 @@ where { } +impl RekeyBijective for HashMapStore { + fn rekey_bijective(&mut self, mut transform: impl FnMut(K, C) -> (K, C)) { + self.scratch.clear(); + self.scratch.reserve(self.terms.len()); + // Changed keys must be reinserted into their new hash buckets. + for (key, coeff) in self.terms.drain() { + let (new_key, new_coeff) = transform(key, coeff); + let replaced = self.scratch.insert(new_key, new_coeff); + debug_assert!(replaced.is_none(), "rekey must preserve distinct keys"); + } + // Keep the emptied source map for the next gate to reuse. + std::mem::swap(&mut self.terms, &mut self.scratch); + } +} + +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 Retain for HashMapStore { fn retain(&mut self, keep: impl Fn(&K, &C) -> bool) { self.terms.retain(|key, coeff| keep(key, coeff)); diff --git a/crates/ppvm-pauli-sum-2/src/store/tests.rs b/crates/ppvm-pauli-sum-2/src/store/tests.rs index b1bf4b1bf..cb6d05574 100644 --- a/crates/ppvm-pauli-sum-2/src/store/tests.rs +++ b/crates/ppvm-pauli-sum-2/src/store/tests.rs @@ -155,3 +155,56 @@ 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 rekey_reuses_both_maps_and_clone_omits_scratch() { + use ppvm_phased_pauli_word_2::Phased; + use ppvm_traits_2::{Clifford, Phase}; + + let mut store = Store::with_capacity(16); + store.accumulate("X".into(), 2.0); + store.accumulate("Y".into(), 0.0); + let original_capacity = store.terms.capacity(); + let conjugate_h = |key, coeff: f64| { + let mut word = Phased::new(key); + word.h(0); + let (key, phase) = word.into_parts(); + (key, if phase == Phase::Neg1 { -coeff } else { coeff }) + }; + store.rekey_bijective(conjugate_h); + let rebuilt_capacity = store.terms.capacity(); + assert_eq!(store.scratch.capacity(), original_capacity); + assert!(store.scratch.is_empty()); + assert_eq!(store.get(&"Z".into()), Some(2.0)); + assert_eq!(store.get(&"Y".into()), Some(0.0)); + + let cloned = store.clone(); + assert_eq!(cloned.scratch.capacity(), 0); + for _ in 0..3 { + store.rekey_bijective(conjugate_h); + assert_eq!(store.terms.capacity(), original_capacity); + assert_eq!(store.scratch.capacity(), rebuilt_capacity); + assert_eq!(store.get(&"X".into()), Some(2.0)); + store.rekey_bijective(conjugate_h); + assert_eq!(store.terms.capacity(), rebuilt_capacity); + assert_eq!(store.scratch.capacity(), original_capacity); + } + store.clear(); + assert_eq!(store.terms.capacity(), rebuilt_capacity); + assert_eq!(store.scratch.capacity(), original_capacity); + assert!(store.is_empty()); + assert_eq!(cloned.get(&"Z".into()), Some(2.0)); +} + +#[test] +fn sign_flips_do_not_allocate_a_second_map() { + let mut store = Store::with_capacity(16); + store.accumulate("X".into(), 2.0); + store.accumulate("Z".into(), 3.0); + let capacity = store.terms.capacity(); + store.flip_sign_by_key(|key| *key == PauliWord::from("X")); + assert_eq!(store.get(&"X".into()), Some(-2.0)); + assert_eq!(store.get(&"Z".into()), Some(3.0)); + assert_eq!(store.terms.capacity(), capacity); + assert_eq!(store.scratch.capacity(), 0); +} diff --git a/crates/ppvm-pauli-sum-2/src/sum.rs b/crates/ppvm-pauli-sum-2/src/sum.rs index 3427368f6..8ee5e1080 100644 --- a/crates/ppvm-pauli-sum-2/src/sum.rs +++ b/crates/ppvm-pauli-sum-2/src/sum.rs @@ -17,7 +17,7 @@ pub type PreserveSet = HashSet; /// are explicit; adding or scaling terms never removes zero coefficients. #[derive(Debug, Clone)] pub struct Sum { - storage: S, + pub(crate) storage: S, policy: P, n_sites: usize, preserved_keys: PreserveSet, @@ -35,6 +35,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/clifford.rs b/crates/ppvm-pauli-sum-2/tests/clifford.rs new file mode 100644 index 000000000..db9e7d26e --- /dev/null +++ b/crates/ppvm-pauli-sum-2/tests/clifford.rs @@ -0,0 +1,169 @@ +// 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); + +// 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, + ] +} + +fn assert_same(actual: &PauliSum, expected: &PauliSum) { + assert_eq!(actual.n_sites(), expected.n_sites()); + assert_eq!(actual.len(), expected.len()); + for (key, coeff) in expected.iter() { + assert_eq!(actual.get(&key), Some(coeff)); + } +} + +#[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(2, [("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); + for sum in [&mut left, &mut right] { + sum.h(1); + sum.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_same(&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_same(&sum, &original); + } + } + } +} + +#[test] +fn batches_and_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(); + actual.s_many(&[0, 2, 0]); + actual.cnot_many(&[(0, 1), (1, 2), (0, 1)]); + for q in [0, 2, 0] { + expected.s(q); + } + for (a, b) in [(0, 1), (1, 2), (0, 1)] { + expected.cnot(a, b); + } + assert_same(&actual, &expected); + + 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_same(&actual, &expected); + } +} From 8a5ffbb3d8c73578c4da4fb5a0d81c5ed4a833fa Mon Sep 17 00:00:00 2001 From: jonhas colina Date: Tue, 17 Nov 2026 00:52:40 -0500 Subject: [PATCH 3/9] added sum arithmetic and formatting --- Cargo.lock | 2 + crates/ppvm-pauli-sum-2/Cargo.toml | 3 +- crates/ppvm-pauli-sum-2/src/compare.rs | 68 +++++++ crates/ppvm-pauli-sum-2/src/display.rs | 51 +++++ crates/ppvm-pauli-sum-2/src/lib.rs | 3 + crates/ppvm-pauli-sum-2/src/ops.rs | 157 ++++++++++++++++ crates/ppvm-pauli-sum-2/src/store.rs | 2 +- crates/ppvm-pauli-sum-2/src/sum.rs | 7 +- crates/ppvm-pauli-sum-2/tests/arithmetic.rs | 198 ++++++++++++++++++++ 9 files changed, 487 insertions(+), 4 deletions(-) create mode 100644 crates/ppvm-pauli-sum-2/src/compare.rs create mode 100644 crates/ppvm-pauli-sum-2/src/display.rs create mode 100644 crates/ppvm-pauli-sum-2/src/ops.rs create mode 100644 crates/ppvm-pauli-sum-2/tests/arithmetic.rs diff --git a/Cargo.lock b/Cargo.lock index ca99e0977..26525545b 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", ] @@ -2244,6 +2245,7 @@ dependencies = [ name = "ppvm-pauli-sum-2" version = "0.3.0" dependencies = [ + "approx", "hashbrown 0.17.1", "num", "ppvm-lossy-pauli-word-2", diff --git a/crates/ppvm-pauli-sum-2/Cargo.toml b/crates/ppvm-pauli-sum-2/Cargo.toml index 68d51d38c..8afaf75f6 100644 --- a/crates/ppvm-pauli-sum-2/Cargo.toml +++ b/crates/ppvm-pauli-sum-2/Cargo.toml @@ -15,6 +15,5 @@ ppvm-pauli-word-2 = { path = "../ppvm-pauli-word-2" } ppvm-lossy-pauli-word-2 = { path = "../ppvm-lossy-pauli-word-2" } ppvm-phased-pauli-word-2 = { path = "../ppvm-phased-pauli-word-2" } hashbrown = { version = "0.17.1", default-features = false, features = ["inline-more"] } - -[dev-dependencies] num = "0.4" +approx = { version = "0.5.1", features = ["num-complex"] } 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 abcb0d4ec..d4ce69e63 100644 --- a/crates/ppvm-pauli-sum-2/src/lib.rs +++ b/crates/ppvm-pauli-sum-2/src/lib.rs @@ -2,6 +2,9 @@ // SPDX-License-Identifier: Apache-2.0 mod clifford; +mod compare; +mod display; +mod ops; mod policy; mod store; mod sum; 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 c0b307f19..cd65dc42b 100644 --- a/crates/ppvm-pauli-sum-2/src/store.rs +++ b/crates/ppvm-pauli-sum-2/src/store.rs @@ -113,7 +113,7 @@ where #[inline] fn accumulate(&mut self, key: K, coeff: C) { match self.terms.entry(key) { - Entry::Occupied(mut entry) => *entry.get_mut() += coeff, + Entry::Occupied(mut entry) => *entry.get_mut() += &coeff, Entry::Vacant(entry) => { entry.insert(coeff); } diff --git a/crates/ppvm-pauli-sum-2/src/sum.rs b/crates/ppvm-pauli-sum-2/src/sum.rs index 8ee5e1080..22897bce0 100644 --- a/crates/ppvm-pauli-sum-2/src/sum.rs +++ b/crates/ppvm-pauli-sum-2/src/sum.rs @@ -15,7 +15,12 @@ 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 { pub(crate) storage: S, policy: P, 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"); +} From ef084435043bd9f5d7bb691c8a455105601c7476 Mon Sep 17 00:00:00 2001 From: jonhas colina Date: Tue, 17 Nov 2026 11:29:23 -0500 Subject: [PATCH 4/9] removed hashbrown dependency and switched to using std::HashMap. Also, focused on reusing shared ppvm-traits-2 implementations and moved single term accumulation into shared usages --- Cargo.lock | 7 ---- crates/ppvm-pauli-sum-2/Cargo.toml | 1 - crates/ppvm-pauli-sum-2/src/store.rs | 40 ++++++------------- .../ppvm-traits-2/src/containers/hash_join.rs | 11 +++++ 4 files changed, 23 insertions(+), 36 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 50fdce8c8..df9386f70 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1499,12 +1499,6 @@ version = "0.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5419bdc4f6a9207fbeba6d11b604d481addf78ecd10c11ad51e76c2f6482748d" -[[package]] -name = "hashbrown" -version = "0.17.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" - [[package]] name = "heck" version = "0.5.0" @@ -2244,7 +2238,6 @@ dependencies = [ name = "ppvm-pauli-sum-2" version = "0.3.0" dependencies = [ - "hashbrown 0.17.1", "num", "ppvm-lossy-pauli-word-2", "ppvm-pauli-word-2", diff --git a/crates/ppvm-pauli-sum-2/Cargo.toml b/crates/ppvm-pauli-sum-2/Cargo.toml index 62cca2b31..1d9f73d87 100644 --- a/crates/ppvm-pauli-sum-2/Cargo.toml +++ b/crates/ppvm-pauli-sum-2/Cargo.toml @@ -13,7 +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" } -hashbrown = { version = "0.17.1", default-features = false, features = ["inline-more"] } [dev-dependencies] num = "0.4" diff --git a/crates/ppvm-pauli-sum-2/src/store.rs b/crates/ppvm-pauli-sum-2/src/store.rs index e2ed3e795..6b4bfbef5 100644 --- a/crates/ppvm-pauli-sum-2/src/store.rs +++ b/crates/ppvm-pauli-sum-2/src/store.rs @@ -1,7 +1,8 @@ // SPDX-FileCopyrightText: 2026 The PPVM Authors // SPDX-License-Identifier: Apache-2.0 -use hashbrown::{HashMap, hash_map::Entry}; +use std::collections::HashMap; + use ppvm_traits_2::{ Accumulate, Coefficient, IdentityBuildHasher, Indexable, Pair, Retain, Scale, Support, TermBatch, @@ -50,19 +51,15 @@ where #[inline] fn get(&self, key: &K) -> Option { - self.terms.get(key).cloned() + Support::get(&self.terms, key) } fn iter(&self) -> impl Iterator { - self.terms - .iter() - .map(|(key, coeff)| (key.clone(), coeff.clone())) + Support::iter(&self.terms) } - fn for_each_ref(&self, mut f: impl FnMut(&K, &C)) { - for (key, coeff) in &self.terms { - f(key, coeff); - } + fn for_each_ref(&self, f: impl FnMut(&K, &C)) { + self.terms.for_each_ref(f); } } @@ -72,27 +69,16 @@ where C: Coefficient, { fn accumulate_batch(&mut self, terms: &TermBatch) { - for (key, coeff) in terms.iter() { - if let Some(value) = self.terms.get_mut(key) { - *value += coeff; - } else { - self.terms.insert(key.clone(), coeff.clone()); - } - } + self.terms.accumulate_batch(terms); } #[inline] fn accumulate(&mut self, key: K, coeff: C) { - match self.terms.entry(key) { - Entry::Occupied(mut entry) => *entry.get_mut() += coeff, - Entry::Vacant(entry) => { - entry.insert(coeff); - } - } + self.terms.accumulate(key, coeff); } fn reduce(&mut self) { - self.terms.retain(|_, coeff| !coeff.is_zero()); + self.terms.reduce(); } } @@ -102,9 +88,7 @@ where C: Coefficient, { fn scale(&mut self, scalar: &C) { - for coeff in self.terms.values_mut() { - *coeff *= scalar; - } + self.terms.scale(scalar); } } @@ -115,9 +99,9 @@ where { } -impl Retain for HashMapStore { +impl Retain for HashMapStore { fn retain(&mut self, keep: impl Fn(&K, &C) -> bool) { - self.terms.retain(|key, coeff| keep(key, coeff)); + Retain::retain(&mut self.terms, keep); } } diff --git a/crates/ppvm-traits-2/src/containers/hash_join.rs b/crates/ppvm-traits-2/src/containers/hash_join.rs index dd6a10e25..df34db140 100644 --- a/crates/ppvm-traits-2/src/containers/hash_join.rs +++ b/crates/ppvm-traits-2/src/containers/hash_join.rs @@ -52,6 +52,17 @@ where K: Indexable, C: Coefficient, { + /// Accumulate an owned term without allocating a singleton batch. + #[inline] + fn accumulate(&mut self, key: K, coeff: C) { + match self.entry(key) { + Entry::Occupied(mut entry) => *entry.get_mut() += &coeff, + Entry::Vacant(entry) => { + entry.insert(coeff); + } + } + } + /// Build side of the hash join: probe each produced term, accumulate its /// coefficient onto a matching key, insert on a miss. #[inline] From 41bcade88c8cd4fddaa6971f9ad97c6e45701277 Mon Sep 17 00:00:00 2001 From: jonhas colina Date: Tue, 17 Nov 2026 11:35:16 -0500 Subject: [PATCH 5/9] removed the need for truncation policy to overlap. --- crates/ppvm-pauli-sum-2/src/sum.rs | 8 ++++---- crates/ppvm-pauli-sum-2/tests/sum.rs | 16 ++++++++++++---- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/crates/ppvm-pauli-sum-2/src/sum.rs b/crates/ppvm-pauli-sum-2/src/sum.rs index 3427368f6..a2b682369 100644 --- a/crates/ppvm-pauli-sum-2/src/sum.rs +++ b/crates/ppvm-pauli-sum-2/src/sum.rs @@ -199,15 +199,15 @@ impl Sum { impl Sum { /// Sum products of matching coefficients, without conjugation. - /// Panics if the sums have different widths. - pub fn overlap(&self, other: &Self) -> S::Coeff { + /// Policies may differ. Panics if the sums have different widths. + pub fn overlap(&self, other: &Sum) -> S::Coeff { assert_eq!(self.n_sites, other.n_sites, "overlap requires equal widths"); self.storage.overlap(&other.storage) } /// Sum products of matching coefficients, conjugating this sum's coefficients. - /// Panics if the sums have different widths. - pub fn hermitian_overlap(&self, other: &Self) -> S::Coeff + /// Policies may differ. Panics if the sums have different widths. + pub fn hermitian_overlap(&self, other: &Sum) -> S::Coeff where S::Coeff: Conjugate, { diff --git a/crates/ppvm-pauli-sum-2/tests/sum.rs b/crates/ppvm-pauli-sum-2/tests/sum.rs index ee28c93a9..3f9f72eeb 100644 --- a/crates/ppvm-pauli-sum-2/tests/sum.rs +++ b/crates/ppvm-pauli-sum-2/tests/sum.rs @@ -2,7 +2,9 @@ // SPDX-License-Identifier: Apache-2.0 use num::Complex; -use ppvm_pauli_sum_2::{LossyPauliSum, NoPolicy, PauliSum, PauliWord, Policy}; +use ppvm_pauli_sum_2::{ + CoefficientThreshold, LossyPauliSum, NoPolicy, PauliSum, PauliWord, Policy, +}; use ppvm_traits_2::Retain; use std::panic::{AssertUnwindSafe, catch_unwind}; @@ -66,14 +68,20 @@ fn lossy_alias_uses_the_same_core_operations() { } #[test] -fn complex_scaling_and_pairing_use_the_storage_algebra() { +fn complex_pairing_accepts_different_policies_without_truncating() { let x = PauliWord::from("X"); let mut left = PauliSum::>::from_terms(1, [(x, Complex::new(1.0, 2.0))]); left.scale(&Complex::new(0.0, 1.0)); assert_eq!(left.get(&x), Some(Complex::new(-2.0, 1.0))); - let right = PauliSum::>::from_terms(1, [(x, Complex::new(3.0, 4.0))]); + let right = PauliSum::from_terms_with_policy( + 1, + CoefficientThreshold { threshold: 10.0 }, + [(x, Complex::new(3.0, 4.0))], + ); assert_eq!(left.overlap(&right), Complex::new(-10.0, -5.0)); + assert_eq!(right.overlap(&left), Complex::new(-10.0, -5.0)); assert_eq!(left.hermitian_overlap(&right), Complex::new(-2.0, -11.0)); + assert_eq!(right.hermitian_overlap(&left), Complex::new(-2.0, 11.0)); } #[test] @@ -91,7 +99,7 @@ fn invalid_insertions_leave_the_sum_unchanged() { #[test] fn overlap_rejects_different_widths_even_for_empty_sums() { let left = PauliSum::::new(1); - let right = PauliSum::::new(2); + let right = PauliSum::::with_policy(2, CoefficientThreshold::default()); assert!(catch_unwind(|| left.overlap(&right)).is_err()); assert!(catch_unwind(|| left.hermitian_overlap(&right)).is_err()); } From 6e177448b742e98cd62f33cc25d8cfc12a9c99ae Mon Sep 17 00:00:00 2001 From: jonhas colina Date: Tue, 17 Nov 2026 11:42:05 -0500 Subject: [PATCH 6/9] inverted the order for lookups --- crates/ppvm-pauli-sum-2/src/sum.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ppvm-pauli-sum-2/src/sum.rs b/crates/ppvm-pauli-sum-2/src/sum.rs index a2b682369..d43a37c65 100644 --- a/crates/ppvm-pauli-sum-2/src/sum.rs +++ b/crates/ppvm-pauli-sum-2/src/sum.rs @@ -248,7 +248,7 @@ where self.storage.retain(keep); } else { self.storage - .retain(|key, coeff| self.preserved_keys.contains(key) || keep(key, coeff)); + .retain(|key, coeff| keep(key, coeff) || self.preserved_keys.contains(key)); } } } From 983f93948b5667d9d5b32b1c09ad67c64a72f748 Mon Sep 17 00:00:00 2001 From: jonhas colina Date: Tue, 17 Nov 2026 12:21:04 -0500 Subject: [PATCH 7/9] cleaned up given mishaps from recent merge --- Cargo.lock | 4 --- crates/ppvm-pauli-sum-2/Cargo.toml | 3 +-- crates/ppvm-pauli-sum-2/src/store.rs | 25 +++++++++++++++++++ crates/ppvm-pauli-sum-2/tests/clifford.rs | 30 ++++++++++------------- 4 files changed, 39 insertions(+), 23 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 74c62a1cb..4f01e3265 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2239,11 +2239,7 @@ dependencies = [ name = "ppvm-pauli-sum-2" version = "0.3.0" dependencies = [ -<<<<<<< HEAD "approx", - "hashbrown 0.17.1", -======= ->>>>>>> trait-2/pauli-sum-core "num", "ppvm-lossy-pauli-word-2", "ppvm-pauli-word-2", diff --git a/crates/ppvm-pauli-sum-2/Cargo.toml b/crates/ppvm-pauli-sum-2/Cargo.toml index d2953ae96..b68144306 100644 --- a/crates/ppvm-pauli-sum-2/Cargo.toml +++ b/crates/ppvm-pauli-sum-2/Cargo.toml @@ -13,7 +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/store.rs b/crates/ppvm-pauli-sum-2/src/store.rs index cd26c72d6..117c4326b 100644 --- a/crates/ppvm-pauli-sum-2/src/store.rs +++ b/crates/ppvm-pauli-sum-2/src/store.rs @@ -134,5 +134,30 @@ impl Retain for HashMapStore { } } +impl RekeyBijective for HashMapStore { + fn rekey_bijective(&mut self, mut transform: impl FnMut(K, C) -> (K, C)) { + self.scratch.clear(); + self.scratch.reserve(self.terms.len()); + // Changed keys must be reinserted into their new hash buckets. + for (key, coeff) in self.terms.drain() { + let (new_key, new_coeff) = transform(key, coeff); + let replaced = self.scratch.insert(new_key, new_coeff); + debug_assert!(replaced.is_none(), "rekey must preserve distinct keys"); + } + // Keep the emptied source map for the next gate to reuse. + std::mem::swap(&mut self.terms, &mut self.scratch); + } +} + +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/tests/clifford.rs b/crates/ppvm-pauli-sum-2/tests/clifford.rs index db9e7d26e..c3863c922 100644 --- a/crates/ppvm-pauli-sum-2/tests/clifford.rs +++ b/crates/ppvm-pauli-sum-2/tests/clifford.rs @@ -28,14 +28,6 @@ fn gates() -> [Gate; 13] { ] } -fn assert_same(actual: &PauliSum, expected: &PauliSum) { - assert_eq!(actual.n_sites(), expected.n_sites()); - assert_eq!(actual.len(), expected.len()); - for (key, coeff) in expected.iter() { - assert_eq!(actual.get(&key), Some(coeff)); - } -} - #[test] fn propagation_matches_phased_words_including_loss() { let alphabet = ['I', 'X', 'Y', 'Z', 'L']; @@ -82,15 +74,19 @@ fn complex_coefficients_absorb_signs_and_preserve_overlap() { ("IZ".into(), Complex::new(-1.0, 4.0)), ], ); - let mut right = PauliSum::from_terms(2, [("XY".into(), Complex::new(1.0, -2.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); - for sum in [&mut left, &mut right] { - sum.h(1); - sum.cnot(0, 1); - } + 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); } @@ -122,13 +118,13 @@ fn invalid_gate_arguments_do_not_change_terms() { for gate in gates::() { let mut sum = original.clone(); assert!(catch_unwind(AssertUnwindSafe(|| gate(&mut sum, 2, 0))).is_err()); - assert_same(&sum, &original); + 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_same(&sum, &original); + assert_eq!(sum, original); } } } @@ -153,7 +149,7 @@ fn batches_and_aliases_follow_gate_order() { for (a, b) in [(0, 1), (1, 2), (0, 1)] { expected.cnot(a, b); } - assert_same(&actual, &expected); + assert_eq!(actual, expected); let aliases: [(Gate, Gate); 4] = [ (PauliSum::cx, PauliSum::cnot), @@ -164,6 +160,6 @@ fn batches_and_aliases_follow_gate_order() { for (alias, gate) in aliases { alias(&mut actual, 0, 1); gate(&mut expected, 0, 1); - assert_same(&actual, &expected); + assert_eq!(actual, expected); } } From 2387b84dad0d40b6bb4c70a8a1e12df01860ab9e Mon Sep 17 00:00:00 2001 From: jonhas colina Date: Tue, 17 Nov 2026 16:05:20 -0500 Subject: [PATCH 8/9] added dedicated clifford overrides for cliffordbatch methods and calling s directory on s_many --- crates/ppvm-pauli-sum-2/src/clifford.rs | 125 ++++++++++++++++++++- crates/ppvm-pauli-sum-2/src/store/tests.rs | 32 ++++++ crates/ppvm-pauli-sum-2/tests/clifford.rs | 118 +++++++++++++++++-- crates/ppvm-traits-2/src/gates/clifford.rs | 4 +- 4 files changed, 265 insertions(+), 14 deletions(-) diff --git a/crates/ppvm-pauli-sum-2/src/clifford.rs b/crates/ppvm-pauli-sum-2/src/clifford.rs index 42bb56a7b..cd24f1afe 100644 --- a/crates/ppvm-pauli-sum-2/src/clifford.rs +++ b/crates/ppvm-pauli-sum-2/src/clifford.rs @@ -32,6 +32,57 @@ impl Sum { } }); } + + 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_terms(|word| gate(word, qubit)), + _ => self.conjugate_terms(|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_terms(|word| gate(word, a, b)), + _ => self.conjugate_terms(|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. @@ -110,4 +161,76 @@ where } } -impl CliffordBatch for Sum where Self: Clifford {} +/// 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/store/tests.rs b/crates/ppvm-pauli-sum-2/src/store/tests.rs index cb6d05574..a40d418a8 100644 --- a/crates/ppvm-pauli-sum-2/src/store/tests.rs +++ b/crates/ppvm-pauli-sum-2/src/store/tests.rs @@ -208,3 +208,35 @@ fn sign_flips_do_not_allocate_a_second_map() { assert_eq!(store.terms.capacity(), capacity); assert_eq!(store.scratch.capacity(), 0); } + +#[test] +fn clifford_batches_rebuild_once_and_skip_rebuilding_for_signs() { + use crate::{NoPolicy, PauliSum}; + use ppvm_traits_2::CliffordBatch; + + let batches: [fn(&mut PauliSum); 2] = [ + |sum| sum.h_many(&[0, 1]), + |sum| sum.cnot_many(&[(0, 1), (1, 0)]), + ]; + for batch in batches { + let mut sum = PauliSum::with_capacity(2, NoPolicy, 64); + sum.add_term("XY".into(), 2.0); + sum.add_term("YZ".into(), 0.0); + let original_capacity = sum.storage.terms.capacity(); + + sum.h_many(&[]); + sum.cnot_many(&[]); + sum.x_many(&[0, 1]); + sum.y_many(&[1, 0]); + sum.z_many(&[0, 0]); + assert_eq!(sum.storage.terms.capacity(), original_capacity); + assert_eq!(sum.storage.scratch.capacity(), 0); + + batch(&mut sum); + // Two scalar calls would swap back to the original, larger map. + assert_eq!(sum.storage.scratch.capacity(), original_capacity); + assert!(sum.storage.terms.capacity() < original_capacity); + assert!(sum.storage.scratch.is_empty()); + assert_eq!(sum.len(), 2); + } +} diff --git a/crates/ppvm-pauli-sum-2/tests/clifford.rs b/crates/ppvm-pauli-sum-2/tests/clifford.rs index c3863c922..c8b54f2be 100644 --- a/crates/ppvm-pauli-sum-2/tests/clifford.rs +++ b/crates/ppvm-pauli-sum-2/tests/clifford.rs @@ -8,6 +8,26 @@ 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] { @@ -131,7 +151,93 @@ fn invalid_gate_arguments_do_not_change_terms() { } #[test] -fn batches_and_aliases_follow_gate_order() { +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, [ @@ -141,16 +247,6 @@ fn batches_and_aliases_follow_gate_order() { ], ); let mut expected = actual.clone(); - actual.s_many(&[0, 2, 0]); - actual.cnot_many(&[(0, 1), (1, 2), (0, 1)]); - for q in [0, 2, 0] { - expected.s(q); - } - for (a, b) in [(0, 1), (1, 2), (0, 1)] { - expected.cnot(a, b); - } - assert_eq!(actual, expected); - let aliases: [(Gate, Gate); 4] = [ (PauliSum::cx, PauliSum::cnot), (PauliSum::zcx, PauliSum::cnot), 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]) { From 334d7a64b9fbe2f8982de1d8dd3c2fa59b6a5af8 Mon Sep 17 00:00:00 2001 From: David Plankensteiner Date: Wed, 18 Nov 2026 16:11:05 +0100 Subject: [PATCH 9/9] Trait 2/pauli sum inplace rekey (#307) I ran some benchmarks comparing ppvm-paulisum-2 to ppvm-paulisum on the original branch, with mixed results. There were some regressions when applying single gates specifically. The root cause is that conjugating terms moved every key around, even if the gate wouldn't touch the key. Now, this is checked beforehand and performance is better in every benchmark than on current main. Co-authored-by: Claude Opus 5.5 --- crates/ppvm-pauli-sum-2/src/clifford.rs | 103 +++++++++++------- crates/ppvm-pauli-sum-2/src/store.rs | 38 ++++--- crates/ppvm-pauli-sum-2/src/store/tests.rs | 121 +++++++-------------- 3 files changed, 128 insertions(+), 134 deletions(-) diff --git a/crates/ppvm-pauli-sum-2/src/clifford.rs b/crates/ppvm-pauli-sum-2/src/clifford.rs index cd24f1afe..5aebcf84e 100644 --- a/crates/ppvm-pauli-sum-2/src/clifford.rs +++ b/crates/ppvm-pauli-sum-2/src/clifford.rs @@ -2,7 +2,9 @@ // SPDX-License-Identifier: Apache-2.0 use ppvm_phased_pauli_word_2::Phased; -use ppvm_traits_2::{Clifford, CliffordBatch, PauliBits, Phase, Support, loss::LossInfo}; +use ppvm_traits_2::{ + Clifford, CliffordBatch, Coefficient, PauliBits, Phase, Support, loss::LossInfo, +}; use crate::{RekeyBijective, SignFlipByKey, Sum}; @@ -18,21 +20,48 @@ impl Sum { } } -impl Sum { - fn conjugate_terms(&mut self, gate: impl Fn(&mut Phased)) { +/// 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| { - let mut phased_word = Phased::new(key); + if !touched(key) { + return None; + } + let mut phased_word = Phased::new(key.clone()); gate(&mut phased_word); - let (key, phase) = phased_word.into_parts(); + let (new_key, phase) = phased_word.into_parts(); // Keys carry no phase; absorb the conjugation sign into the coefficient. match phase { - Phase::Pos1 => (key, coeff), - Phase::Neg1 => (key, -coeff), + 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], @@ -43,12 +72,15 @@ impl Sum { } match indices { [] => {} - &[qubit] => self.conjugate_terms(|word| gate(word, qubit)), - _ => self.conjugate_terms(|word| { - for &qubit in indices { - gate(word, qubit); - } - }), + &[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); + } + }, + ), } } @@ -62,12 +94,15 @@ impl Sum { } match pairs { [] => {} - &[(a, b)] => self.conjugate_terms(|word| gate(word, a, b)), - _ => self.conjugate_terms(|word| { - for &(a, b) in pairs { - gate(word, a, b); - } - }), + &[(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); + } + }, + ), } } } @@ -111,53 +146,43 @@ where } fn h(&mut self, qubit: usize) { - self.check_qubit(qubit); - self.conjugate_terms(|word| word.h(qubit)); + self.conjugate_single(qubit, |word| word.h(qubit)); } fn s(&mut self, qubit: usize) { - self.check_qubit(qubit); - self.conjugate_terms(|word| word.s(qubit)); + self.conjugate_single(qubit, |word| word.s(qubit)); } fn s_dag(&mut self, qubit: usize) { - self.check_qubit(qubit); - self.conjugate_terms(|word| word.s_dag(qubit)); + self.conjugate_single(qubit, |word| word.s_dag(qubit)); } fn sqrt_x(&mut self, qubit: usize) { - self.check_qubit(qubit); - self.conjugate_terms(|word| word.sqrt_x(qubit)); + self.conjugate_single(qubit, |word| word.sqrt_x(qubit)); } fn sqrt_x_dag(&mut self, qubit: usize) { - self.check_qubit(qubit); - self.conjugate_terms(|word| word.sqrt_x_dag(qubit)); + self.conjugate_single(qubit, |word| word.sqrt_x_dag(qubit)); } fn sqrt_y(&mut self, qubit: usize) { - self.check_qubit(qubit); - self.conjugate_terms(|word| word.sqrt_y(qubit)); + self.conjugate_single(qubit, |word| word.sqrt_y(qubit)); } fn sqrt_y_dag(&mut self, qubit: usize) { - self.check_qubit(qubit); - self.conjugate_terms(|word| word.sqrt_y_dag(qubit)); + self.conjugate_single(qubit, |word| word.sqrt_y_dag(qubit)); } fn cnot(&mut self, control: usize, target: usize) { - self.check_pair(control, target); - self.conjugate_terms(|word| word.cnot(control, target)); + self.conjugate_pair(control, target, |word| word.cnot(control, target)); } fn cz(&mut self, qubit0: usize, qubit1: usize) { - self.check_pair(qubit0, qubit1); - self.conjugate_terms(|word| word.cz(qubit0, qubit1)); + self.conjugate_pair(qubit0, qubit1, |word| word.cz(qubit0, qubit1)); } fn cy(&mut self, control: usize, target: usize) { - self.check_pair(control, target); - self.conjugate_terms(|word| word.cy(control, target)); + self.conjugate_pair(control, target, |word| word.cy(control, target)); } } diff --git a/crates/ppvm-pauli-sum-2/src/store.rs b/crates/ppvm-pauli-sum-2/src/store.rs index 117c4326b..58f183557 100644 --- a/crates/ppvm-pauli-sum-2/src/store.rs +++ b/crates/ppvm-pauli-sum-2/src/store.rs @@ -19,11 +19,12 @@ pub trait StoreAlloc { /// Replace each key with a unique new key, optionally changing its coefficient. pub trait RekeyBijective: Support { - /// The callback must map distinct input keys to distinct output keys. + /// 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, Self::Coeff) -> (Self::Key, Self::Coeff), + transform: impl FnMut(&Self::Key, &mut Self::Coeff) -> Option, ); } @@ -38,15 +39,15 @@ pub trait SignFlipByKey: Support { #[derive(Debug)] pub struct HashMapStore { terms: HashMap, - // Empty between operations; reused when a gate changes keys. - scratch: 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(), - scratch: HashMap::with_hasher(IdentityBuildHasher), + moved: Vec::new(), } } } @@ -55,13 +56,13 @@ impl StoreAlloc for HashMapStore { fn with_capacity(capacity: usize) -> Self { Self { terms: HashMap::with_capacity_and_hasher(capacity, IdentityBuildHasher), - scratch: HashMap::with_hasher(IdentityBuildHasher), + moved: Vec::new(), } } fn clear(&mut self) { self.terms.clear(); - self.scratch.clear(); + self.moved.clear(); } } @@ -135,17 +136,22 @@ impl Retain for HashMapStore { } impl RekeyBijective for HashMapStore { - fn rekey_bijective(&mut self, mut transform: impl FnMut(K, C) -> (K, C)) { - self.scratch.clear(); - self.scratch.reserve(self.terms.len()); - // Changed keys must be reinserted into their new hash buckets. - for (key, coeff) in self.terms.drain() { - let (new_key, new_coeff) = transform(key, coeff); - let replaced = self.scratch.insert(new_key, new_coeff); + 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"); } - // Keep the emptied source map for the next gate to reuse. - std::mem::swap(&mut self.terms, &mut self.scratch); + self.moved = moved; } } diff --git a/crates/ppvm-pauli-sum-2/src/store/tests.rs b/crates/ppvm-pauli-sum-2/src/store/tests.rs index a40d418a8..5306111bf 100644 --- a/crates/ppvm-pauli-sum-2/src/store/tests.rs +++ b/crates/ppvm-pauli-sum-2/src/store/tests.rs @@ -157,86 +157,49 @@ fn hash_collisions_do_not_merge_distinct_keys() { } #[test] -fn rekey_reuses_both_maps_and_clone_omits_scratch() { +fn partial_rekey_matches_word_conjugation() { + use crate::PauliSum; use ppvm_phased_pauli_word_2::Phased; - use ppvm_traits_2::{Clifford, Phase}; - - let mut store = Store::with_capacity(16); - store.accumulate("X".into(), 2.0); - store.accumulate("Y".into(), 0.0); - let original_capacity = store.terms.capacity(); - let conjugate_h = |key, coeff: f64| { - let mut word = Phased::new(key); - word.h(0); - let (key, phase) = word.into_parts(); - (key, if phase == Phase::Neg1 { -coeff } else { coeff }) - }; - store.rekey_bijective(conjugate_h); - let rebuilt_capacity = store.terms.capacity(); - assert_eq!(store.scratch.capacity(), original_capacity); - assert!(store.scratch.is_empty()); - assert_eq!(store.get(&"Z".into()), Some(2.0)); - assert_eq!(store.get(&"Y".into()), Some(0.0)); - - let cloned = store.clone(); - assert_eq!(cloned.scratch.capacity(), 0); - for _ in 0..3 { - store.rekey_bijective(conjugate_h); - assert_eq!(store.terms.capacity(), original_capacity); - assert_eq!(store.scratch.capacity(), rebuilt_capacity); - assert_eq!(store.get(&"X".into()), Some(2.0)); - store.rekey_bijective(conjugate_h); - assert_eq!(store.terms.capacity(), rebuilt_capacity); - assert_eq!(store.scratch.capacity(), original_capacity); - } - store.clear(); - assert_eq!(store.terms.capacity(), rebuilt_capacity); - assert_eq!(store.scratch.capacity(), original_capacity); - assert!(store.is_empty()); - assert_eq!(cloned.get(&"Z".into()), Some(2.0)); -} - -#[test] -fn sign_flips_do_not_allocate_a_second_map() { - let mut store = Store::with_capacity(16); - store.accumulate("X".into(), 2.0); - store.accumulate("Z".into(), 3.0); - let capacity = store.terms.capacity(); - store.flip_sign_by_key(|key| *key == PauliWord::from("X")); - assert_eq!(store.get(&"X".into()), Some(-2.0)); - assert_eq!(store.get(&"Z".into()), Some(3.0)); - assert_eq!(store.terms.capacity(), capacity); - assert_eq!(store.scratch.capacity(), 0); -} - -#[test] -fn clifford_batches_rebuild_once_and_skip_rebuilding_for_signs() { - use crate::{NoPolicy, PauliSum}; - use ppvm_traits_2::CliffordBatch; - - let batches: [fn(&mut PauliSum); 2] = [ - |sum| sum.h_many(&[0, 1]), - |sum| sum.cnot_many(&[(0, 1), (1, 0)]), + 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 batch in batches { - let mut sum = PauliSum::with_capacity(2, NoPolicy, 64); - sum.add_term("XY".into(), 2.0); - sum.add_term("YZ".into(), 0.0); - let original_capacity = sum.storage.terms.capacity(); - - sum.h_many(&[]); - sum.cnot_many(&[]); - sum.x_many(&[0, 1]); - sum.y_many(&[1, 0]); - sum.z_many(&[0, 0]); - assert_eq!(sum.storage.terms.capacity(), original_capacity); - assert_eq!(sum.storage.scratch.capacity(), 0); - - batch(&mut sum); - // Two scalar calls would swap back to the original, larger map. - assert_eq!(sum.storage.scratch.capacity(), original_capacity); - assert!(sum.storage.terms.capacity() < original_capacity); - assert!(sum.storage.scratch.is_empty()); - assert_eq!(sum.len(), 2); + 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); }