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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions crates/ppvm-pauli-sum-2/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,17 @@ mod loss;
mod noise;
mod ops;
mod policy;
mod product;
mod projection;
mod readout;
mod rotation;
mod store;
mod sum;

pub use policy::{
CoefficientThreshold, CombinedPolicy, MaxLossWeight, MaxPauliWeight, NoPolicy, Policy,
};
pub use readout::{Pattern, SiteSet};
pub use store::{
BranchInPlace, HashMapStore, RekeyBijective, SignFlipByKey, StoreAlloc, UpdateCoefficients,
};
Expand Down
38 changes: 38 additions & 0 deletions crates/ppvm-pauli-sum-2/src/product.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// SPDX-FileCopyrightText: 2026 The PPVM Authors
// SPDX-License-Identifier: Apache-2.0

//! Distributive products: `(Σ a_p P)(Σ b_q Q) = Σ a_p b_q i^k (PQ)`, where the word
//! product's residual phase `i^k` is absorbed into the coefficient. This needs a
//! coefficient ring with an imaginary unit, so real-coefficient sums and lossy
//! words have no product. Exact zeros stay stored; reduction and truncation are
//! explicit. Results keep the left operand's policy and preserved keys.

use std::ops::Mul;

use ppvm_traits_2::{ImaginaryUnit, KeyProduct, Multiply};

use crate::{StoreAlloc, Sum};

/// Multiplies every pair of terms, so this costs `|self| · |rhs|` word products.
/// Order matters, since Pauli words need not commute. Policies may differ; the
/// result keeps the left one. Panics if the widths differ.
impl<S, P, P2> Mul<&Sum<S, P2>> for &Sum<S, P>

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Can you add a wrapper that also implements the product for owned sums?

where
S: Multiply + StoreAlloc,
S::Key: KeyProduct,
S::Coeff: ImaginaryUnit,
P: Clone,
{
type Output = Sum<S, P>;

fn mul(self, rhs: &Sum<S, P2>) -> Self::Output {
assert_eq!(
self.n_sites(),
rhs.n_sites(),
"product requires equal widths"
);
let mut out = self.empty_like(self.len().max(rhs.len()));
self.storage.multiply_into(&rhs.storage, &mut out.storage);
out
}
}
47 changes: 47 additions & 0 deletions crates/ppvm-pauli-sum-2/src/projection.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// SPDX-FileCopyrightText: 2026 The PPVM Authors
// SPDX-License-Identifier: Apache-2.0

//! Z-basis projectors as `O ↦ P_m O P_m`, the same map in either picture.
//! On the projected site `I` and `Z` both become `(I ± Z)/2`; `X`, `Y`, and lost
//! sites become zero, which stays stored. Results are unnormalized, and
//! reduction and truncation stay caller-controlled.

use num::Zero;
use ppvm_traits_2::{Halvable, PauliBits, Projection, loss::LossInfo};

use crate::{BranchInPlace, Sum};

impl<S: BranchInPlace, P> Projection for Sum<S, P>
where
S::Key: PauliBits + LossInfo,
S::Coeff: Halvable,
{
fn p0(&mut self, qubit: usize) {
self.project(qubit, false);
}

fn p1(&mut self, qubit: usize) {
self.project(qubit, true);
}
}

impl<S: BranchInPlace, P> Sum<S, P>
where
S::Key: PauliBits + LossInfo,
S::Coeff: Halvable,
{
fn project(&mut self, qubit: usize, one: bool) {
self.check_qubit(qubit);
self.storage.branch_in_place(|key, coeff| {
if key.is_lost(qubit) || key.x_bit(qubit) {
*coeff = S::Coeff::zero();
return None;
}
// Keep half and send ±half to the I <-> Z partner: P0 maps I and Z to
// (I + Z)/2; P1 maps I to (I - Z)/2 and Z to (Z - I)/2.
*coeff = coeff.half();
let partner = if one { -coeff.clone() } else { coeff.clone() };
Some((key.toggled_bits(qubit, false, true), partner))
});
}
}
97 changes: 97 additions & 0 deletions crates/ppvm-pauli-sum-2/src/readout.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
// SPDX-FileCopyrightText: 2026 The PPVM Authors
// SPDX-License-Identifier: Apache-2.0

//! Readout by pattern: [`Sum::trace`] adds the coefficients of keys that a
//! per-site [`Pattern`] accepts. With `{I, Z}` on every site this is
//! `⟨0…0|O|0…0⟩`; conjugate by `X` first to read other basis states. `I`
//! denotes a live site, so lost sites only match patterns that accept `L`.

use std::ops::BitOr;

use num::Zero;

use ppvm_traits_2::{PauliBits, Support, loss::LossInfo};

use crate::Sum;

/// Accepted values for one site, from `I`, `X`, `Y`, `Z`, and lost (`L`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SiteSet(u8);

impl SiteSet {
// Bit `1 << code` for packed codes `0=I, 1=X, 2=Z, 3=Y`; bit 4 is lost.
pub const I: Self = Self(1);
pub const X: Self = Self(1 << 1);
pub const Z: Self = Self(1 << 2);
pub const Y: Self = Self(1 << 3);
pub const L: Self = Self(1 << 4);
pub const ANY: Self = Self(0b1_1111);

#[inline]
fn accepts<W: PauliBits + LossInfo>(self, word: &W, site: usize) -> bool {
let value = if word.is_lost(site) {
Self::L.0
} else {
1 << word.pauli_code(site)
};
self.0 & value != 0
}
}

impl BitOr for SiteSet {
type Output = Self;

fn bitor(self, rhs: Self) -> Self {
Self(self.0 | rhs.0)
}
}

/// One accepted [`SiteSet`] per site; a word matches when every site does.
/// Build one from a `Vec<SiteSet>` in site order.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Pattern {
sites: Vec<SiteSet>,
}

impl Pattern {
/// `{I, Z}` on every site: readout in the all-zero state.
pub fn zero_state(n_sites: usize) -> Self {
vec![SiteSet::I | SiteSet::Z; n_sites].into()
}

fn matches<W: PauliBits + LossInfo>(&self, word: &W) -> bool {
self.sites
.iter()
.enumerate()
.all(|(site, set)| set.accepts(word, site))
}
}

/// One set per site, in site order.
impl From<Vec<SiteSet>> for Pattern {
fn from(sites: Vec<SiteSet>) -> Self {
Self { sites }
}
}

impl<S: Support, P> Sum<S, P>
where
S::Key: PauliBits + LossInfo,
{
/// Sum of the coefficients whose keys `pattern` accepts, or zero if none do.
/// Panics if the pattern's width differs from the sum's.
pub fn trace(&self, pattern: &Pattern) -> S::Coeff {
assert_eq!(
pattern.sites.len(),
self.n_sites(),
"pattern width must match sum width"
);
let mut total = S::Coeff::zero();
self.for_each_ref(|key, coeff| {
if pattern.matches(key) {
total += coeff;
}
});
total
}
}
16 changes: 14 additions & 2 deletions crates/ppvm-pauli-sum-2/src/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
use std::collections::HashMap;

use ppvm_traits_2::{
Accumulate, Coefficient, IdentityBuildHasher, Indexable, Pair, Retain, Scale, Support,
TermBatch,
Accumulate, Coefficient, IdentityBuildHasher, ImaginaryUnit, Indexable, KeyProduct, Multiply,
Pair, Retain, Scale, Support, TermBatch,
};

/// Allocation and reuse of sparse-sum storage.
Expand Down Expand Up @@ -147,6 +147,18 @@ where
{
}

/// Delegates to the map's product, which absorbs each key product's phase
/// into its coefficient and leaves exact zeros stored.
impl<K, C> Multiply for HashMapStore<K, C>
where
K: Indexable + KeyProduct,
C: ImaginaryUnit,
{
fn multiply_into(&self, other: &Self, acc: &mut Self) {
self.terms.multiply_into(&other.terms, &mut acc.terms);
}
}

impl<K: Indexable, C: Coefficient> Retain<K, C> for HashMapStore<K, C> {
fn retain(&mut self, keep: impl Fn(&K, &C) -> bool) {
Retain::retain(&mut self.terms, keep);
Expand Down
13 changes: 13 additions & 0 deletions crates/ppvm-pauli-sum-2/src/sum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,19 @@ impl<S: Support + StoreAlloc, P> Sum<S, P> {
pub fn clear(&mut self) {
self.storage.clear();
}

/// An empty sum with this sum's width, policy, and preserved keys.
pub(crate) fn empty_like(&self, capacity: usize) -> Self
where
P: Clone,
{
Self {
storage: S::with_capacity(capacity),
policy: self.policy.clone(),
n_sites: self.n_sites,
preserved_keys: self.preserved_keys.clone(),
}
}
}

impl<S, P> Sum<S, P>
Expand Down
109 changes: 109 additions & 0 deletions crates/ppvm-pauli-sum-2/tests/common/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
// SPDX-FileCopyrightText: 2026 The PPVM Authors
// SPDX-License-Identifier: Apache-2.0

//! Shared helpers: deterministic random sums, a dense-matrix oracle, and
//! operator comparison that treats missing keys as zero.
#![allow(dead_code)]

use approx::AbsDiffEq;
use num::{Complex, Zero};
use ppvm_pauli_sum_2::{PauliSum, PauliWord, Sum};
use ppvm_traits_2::{PauliBits, Support};

pub type C = Complex<f64>;
pub type CSum = PauliSum<C>;

pub fn c(re: f64, im: f64) -> C {
Complex::new(re, im)
}

/// A one-term sum with coefficient one.
pub fn word(w: &str) -> CSum {
CSum::from_terms(w.len(), [(PauliWord::from(w), c(1.0, 0.0))])
}

/// A deterministic random complex sum; repeated words accumulate.
pub fn random_sum(n_sites: usize, n_terms: usize, seed: u64) -> CSum {
let mut state = seed.wrapping_mul(0x9e37_79b9_7f4a_7c15) | 1;
let mut below = move |bound: u64| {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
state % bound
};
let mut sum = CSum::new(n_sites);
for _ in 0..n_terms {
let w: String = (0..n_sites)
.map(|_| ['I', 'X', 'Y', 'Z'][below(4) as usize])
.collect();
let mut unit = || below(2001) as f64 / 1000.0 - 1.0;
sum += (w.as_str(), c(unit(), unit()));
}
sum
}

/// Dense `2^n × 2^n` matrix, row-major; site 0 is the most significant factor.
pub fn dense(sum: &CSum) -> Vec<C> {
let n = sum.n_sites();
let dim = 1 << n;
let one = c(1.0, 0.0);
let i = c(0.0, 1.0);
let o = C::zero();
// Indexed by packed code: I, X, Z, Y.
let paulis = [
[[one, o], [o, one]],
[[o, one], [one, o]],
[[one, o], [o, -one]],
[[o, -i], [i, o]],
];
let mut out = vec![C::zero(); dim * dim];
for (key, coeff) in sum.iter() {
for row in 0..dim {
for col in 0..dim {
let entry = (0..n).fold(coeff, |acc, site| {
let bit = |x: usize| (x >> (n - 1 - site)) & 1;
acc * paulis[key.pauli_code(site) as usize][bit(row)][bit(col)]
});
out[row * dim + col] += entry;
}
}
}
out
}

pub fn matmul(a: &[C], b: &[C]) -> Vec<C> {
let dim = (a.len() as f64).sqrt() as usize;
let mut out = vec![C::zero(); dim * dim];
for row in 0..dim {
for k in 0..dim {
for col in 0..dim {
out[row * dim + col] += a[row * dim + k] * b[k * dim + col];
}
}
}
out
}

pub fn assert_matrix_eq(actual: &[C], expected: &[C]) {
assert_eq!(actual.len(), expected.len());
for (i, (a, e)) in actual.iter().zip(expected).enumerate() {
assert!((a - e).norm() < 1e-12, "entry {i}: {a} != {e}");
}
}

/// Equal as operators: every key's coefficient agrees, absent keys counting as zero.
pub fn assert_same_operator<S, P1, P2>(actual: &Sum<S, P1>, expected: &Sum<S, P2>)
where
S: Support,
S::Key: std::fmt::Debug,
S::Coeff: AbsDiffEq<Epsilon = f64> + std::fmt::Debug,
{
assert_eq!(actual.n_sites(), expected.n_sites());
let check = |key: &S::Key| {
let a = actual.get(key).unwrap_or_else(S::Coeff::zero);
let e = expected.get(key).unwrap_or_else(S::Coeff::zero);
assert!(a.abs_diff_eq(&e, 1e-12), "{key:?}: {a:?} != {e:?}");
};
actual.for_each_ref(|key, _| check(key));
expected.for_each_ref(|key, _| check(key));
}
Loading
Loading