diff --git a/crates/ppvm-pauli-sum-2/src/lib.rs b/crates/ppvm-pauli-sum-2/src/lib.rs index c0df8bc72..943ae053c 100644 --- a/crates/ppvm-pauli-sum-2/src/lib.rs +++ b/crates/ppvm-pauli-sum-2/src/lib.rs @@ -9,6 +9,9 @@ mod loss; mod noise; mod ops; mod policy; +mod product; +mod projection; +mod readout; mod rotation; mod store; mod sum; @@ -16,6 +19,7 @@ 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, }; diff --git a/crates/ppvm-pauli-sum-2/src/product.rs b/crates/ppvm-pauli-sum-2/src/product.rs new file mode 100644 index 000000000..d5d3acda9 --- /dev/null +++ b/crates/ppvm-pauli-sum-2/src/product.rs @@ -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 Mul<&Sum> for &Sum +where + S: Multiply + StoreAlloc, + S::Key: KeyProduct, + S::Coeff: ImaginaryUnit, + P: Clone, +{ + type Output = Sum; + + fn mul(self, rhs: &Sum) -> 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 + } +} diff --git a/crates/ppvm-pauli-sum-2/src/projection.rs b/crates/ppvm-pauli-sum-2/src/projection.rs new file mode 100644 index 000000000..b9f44113a --- /dev/null +++ b/crates/ppvm-pauli-sum-2/src/projection.rs @@ -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 Projection for Sum +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 Sum +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)) + }); + } +} diff --git a/crates/ppvm-pauli-sum-2/src/readout.rs b/crates/ppvm-pauli-sum-2/src/readout.rs new file mode 100644 index 000000000..d6ca120c5 --- /dev/null +++ b/crates/ppvm-pauli-sum-2/src/readout.rs @@ -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(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` in site order. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Pattern { + sites: Vec, +} + +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(&self, word: &W) -> bool { + self.sites + .iter() + .enumerate() + .all(|(site, set)| set.accepts(word, site)) + } +} + +/// One set per site, in site order. +impl From> for Pattern { + fn from(sites: Vec) -> Self { + Self { sites } + } +} + +impl Sum +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 + } +} diff --git a/crates/ppvm-pauli-sum-2/src/store.rs b/crates/ppvm-pauli-sum-2/src/store.rs index 05514bf89..e5afbab9c 100644 --- a/crates/ppvm-pauli-sum-2/src/store.rs +++ b/crates/ppvm-pauli-sum-2/src/store.rs @@ -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. @@ -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 Multiply for HashMapStore +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 Retain for HashMapStore { fn retain(&mut self, keep: impl Fn(&K, &C) -> bool) { Retain::retain(&mut self.terms, keep); diff --git a/crates/ppvm-pauli-sum-2/src/sum.rs b/crates/ppvm-pauli-sum-2/src/sum.rs index cc04df721..b461a14d6 100644 --- a/crates/ppvm-pauli-sum-2/src/sum.rs +++ b/crates/ppvm-pauli-sum-2/src/sum.rs @@ -135,6 +135,19 @@ impl Sum { 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 Sum diff --git a/crates/ppvm-pauli-sum-2/tests/common/mod.rs b/crates/ppvm-pauli-sum-2/tests/common/mod.rs new file mode 100644 index 000000000..22844ae5c --- /dev/null +++ b/crates/ppvm-pauli-sum-2/tests/common/mod.rs @@ -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; +pub type CSum = PauliSum; + +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 { + 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 { + 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(actual: &Sum, expected: &Sum) +where + S: Support, + S::Key: std::fmt::Debug, + S::Coeff: AbsDiffEq + 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)); +} diff --git a/crates/ppvm-pauli-sum-2/tests/product.rs b/crates/ppvm-pauli-sum-2/tests/product.rs new file mode 100644 index 000000000..f9900556f --- /dev/null +++ b/crates/ppvm-pauli-sum-2/tests/product.rs @@ -0,0 +1,84 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +mod common; + +use common::{C, CSum, assert_matrix_eq, assert_same_operator, c, dense, matmul, random_sum, word}; +use ppvm_pauli_sum_2::{CoefficientThreshold, PauliSum, PauliWord}; + +#[test] +fn single_qubit_products_follow_the_pauli_table() { + let (one, i) = (c(1.0, 0.0), c(0.0, 1.0)); + let table = [ + ("X", "Y", "Z", i), + ("Y", "Z", "X", i), + ("Z", "X", "Y", i), + ("Y", "X", "Z", -i), + ("Z", "Y", "X", -i), + ("X", "Z", "Y", -i), + ("X", "X", "I", one), + ("Y", "Y", "I", one), + ("Z", "Z", "I", one), + ("I", "Y", "Y", one), + ]; + for (a, b, product, phase) in table { + let result = &word(a) * &word(b); + assert_eq!(result.len(), 1, "{a}{b}"); + assert_eq!(result.get(&PauliWord::from(product)), Some(phase), "{a}{b}"); + } +} + +#[test] +fn products_match_dense_matrix_multiplication() { + for seed in 1..=8 { + let a = random_sum(3, 7, seed); + let b = random_sum(3, 7, seed + 100); + assert_matrix_eq(&dense(&(&a * &b)), &matmul(&dense(&a), &dense(&b))); + } +} + +#[test] +fn products_satisfy_ring_identities() { + let (a, b, d) = ( + random_sum(3, 6, 1), + random_sum(3, 6, 2), + random_sum(3, 6, 3), + ); + assert_same_operator(&(&(&a * &b) * &d), &(&a * &(&b * &d))); + assert_same_operator(&(&a * &(&b + &d)), &(&(&a * &b) + &(&a * &d))); + assert_same_operator(&(&(&a + &b) * &d), &(&(&a * &d) + &(&b * &d))); + let s = c(0.3, -1.2); + assert_same_operator(&(&(&a * s) * &b), &(&(&a * &b) * s)); + assert_same_operator(&(&a * &(&b * s)), &(&(&a * &b) * s)); + let identity = word("III"); + assert_eq!(&identity * &a, a); + assert_eq!(&a * &identity, a); + let zero = CSum::new(3); + assert!((&a * &zero).is_empty() && (&zero * &a).is_empty()); +} + +#[test] +fn products_keep_zeros_and_the_left_policy_without_truncating() { + let mut a = PauliSum::::with_policy(1, CoefficientThreshold { threshold: 10.0 }); + a += ("X", c(1.0, 0.0)); + a += ("Z", c(1.0, 0.0)); + a.preserve_key("X".into()); + let mut b = CSum::new(1); + b += ("X", c(1.0, 0.0)); + b += ("Z", c(-1.0, 0.0)); + // (X + Z)(X - Z) = (I - I) + (ZX - XZ) = 0·I + 2i·Y. + let mut product = &a * &b; + assert_eq!(product.len(), 2); + assert_eq!(product.get(&"I".into()), Some(c(0.0, 0.0))); + assert_eq!(product.get(&"Y".into()), Some(c(0.0, 2.0))); + assert_eq!(product.policy().threshold, 10.0); + assert!(product.preserved_keys().contains(&"X".into())); + product.truncate(); + assert!(product.is_empty()); +} + +#[test] +#[should_panic(expected = "product requires equal widths")] +fn products_reject_mismatched_widths() { + let _ = &word("XI") * &word("X"); +} diff --git a/crates/ppvm-pauli-sum-2/tests/projection.rs b/crates/ppvm-pauli-sum-2/tests/projection.rs new file mode 100644 index 000000000..0e6cbba92 --- /dev/null +++ b/crates/ppvm-pauli-sum-2/tests/projection.rs @@ -0,0 +1,119 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +mod common; + +use common::{CSum, assert_same_operator, c, random_sum}; +use ppvm_pauli_sum_2::{CoefficientThreshold, LossyPauliSum, LossyPauliWord, PauliSum}; +use ppvm_traits_2::{PauliBits, Projection}; + +type Terms = &'static [(&'static str, f64)]; + +#[test] +fn projectors_map_each_site_value() { + let cases: [(&str, Terms, Terms); 5] = [ + ("I", &[("I", 0.5), ("Z", 0.5)], &[("I", 0.5), ("Z", -0.5)]), + ("Z", &[("I", 0.5), ("Z", 0.5)], &[("I", -0.5), ("Z", 0.5)]), + ("X", &[("X", 0.0)], &[("X", 0.0)]), + ("Y", &[("Y", 0.0)], &[("Y", 0.0)]), + ("L", &[("L", 0.0)], &[("L", 0.0)]), + ]; + for (word, p0, p1) in cases { + for (project, expected) in [(0, p0), (1, p1)] { + let mut sum = LossyPauliSum::::new(1); + sum += (word, 1.0); + if project == 0 { + sum.p0(0) + } else { + sum.p1(0) + } + let expected: LossyPauliSum = LossyPauliSum::from_terms( + 1, + expected.iter().map(|&(w, v)| (LossyPauliWord::from(w), v)), + ); + assert_eq!(sum, expected, "p{project}({word})"); + } + } +} + +/// Every two-site lossy word, with distinct coefficients. +fn all_lossy_words() -> LossyPauliSum { + let mut sum = LossyPauliSum::::new(2); + for (i, a) in "IXYZL".chars().enumerate() { + for (j, b) in "IXYZL".chars().enumerate() { + sum += (format!("{a}{b}").as_str(), (5 * i + j + 1) as f64); + } + } + sum +} + +#[test] +fn projectors_are_idempotent_orthogonal_and_complete() { + let o = all_lossy_words(); + for q in 0..2 { + let project = |sum: &LossyPauliSum, one: bool| { + let mut out = sum.clone(); + if one { + out.p1(q) + } else { + out.p0(q) + } + out + }; + let (p0, p1) = (project(&o, false), project(&o, true)); + assert_same_operator(&project(&p0, false), &p0); + assert_same_operator(&project(&p1, true), &p1); + assert!(project(&p0, true).iter().all(|(_, v)| v == 0.0)); + assert!(project(&p1, false).iter().all(|(_, v)| v == 0.0)); + // P0 O P0 + P1 O P1 dephases the site: X, Y, and lost terms vanish. + let dephased: LossyPauliSum = + LossyPauliSum::from_terms(2, o.iter().filter(|(k, _)| !k.is_lost(q) && !k.x_bit(q))); + assert_same_operator(&(&p0 + &p1), &dephased); + } +} + +#[test] +fn projection_matches_conjugation_by_the_projector() { + let o = random_sum(3, 12, 9); + for q in 0..3 { + for one in [false, true] { + let z: String = (0..3).map(|i| if i == q { 'Z' } else { 'I' }).collect(); + let sign = if one { -0.5 } else { 0.5 }; + let mut projector = CSum::new(3); + projector += ("III", c(0.5, 0.0)); + projector += (z.as_str(), c(sign, 0.0)); + let mut actual = o.clone(); + if one { + actual.p1(q) + } else { + actual.p0(q) + } + assert_same_operator(&actual, &(&(&projector * &o) * &projector)); + } + } +} + +#[test] +fn projection_keeps_zero_terms_and_ignores_policy() { + let mut sum = PauliSum::::with_policy(2, CoefficientThreshold { threshold: 10.0 }); + sum += ("XI", 1.0); + sum += ("ZI", 1.0); + sum.p0(0); + assert_eq!(sum.len(), 3); + assert_eq!(sum.get(&"XI".into()), Some(0.0)); + sum.reduce(); + assert_eq!(sum.len(), 2); + sum.truncate(); + assert!(sum.is_empty()); +} + +#[test] +fn invalid_projection_target_panics_before_mutation() { + use std::panic::{AssertUnwindSafe, catch_unwind}; + let mut sum = PauliSum::::new(1); + sum += ("Z", 1.0); + let original = sum.clone(); + assert!(catch_unwind(AssertUnwindSafe(|| sum.p0(1))).is_err()); + assert!(catch_unwind(AssertUnwindSafe(|| sum.p1(1))).is_err()); + assert_eq!(sum, original); +} diff --git a/crates/ppvm-pauli-sum-2/tests/readout.rs b/crates/ppvm-pauli-sum-2/tests/readout.rs new file mode 100644 index 000000000..f4e3db241 --- /dev/null +++ b/crates/ppvm-pauli-sum-2/tests/readout.rs @@ -0,0 +1,103 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +mod common; + +use approx::assert_abs_diff_eq; +use common::{dense, random_sum}; +use ppvm_pauli_sum_2::{LossyPauliSum, Pattern, PauliSum, SiteSet}; +use ppvm_traits_2::{Clifford, LossChannel, Projection, RotationOne}; + +#[test] +fn trace_sums_coefficients_of_matching_words() { + // Powers of two, so each total shows exactly which words matched. + let mut sum = LossyPauliSum::::new(4); + for (word, coeff) in [ + ("ZYXL", 1.0), + ("ILXL", 2.0), + ("XYXL", 4.0), + ("IIXI", 8.0), + ("IIII", 16.0), + ] { + sum += (word, coeff); + } + let pattern = Pattern::from(vec![ + SiteSet::I | SiteSet::Z, + SiteSet::ANY, + SiteSet::X, + SiteSet::L, + ]); + assert_eq!(sum.trace(&pattern), 3.0); + // Lost sites are not live: L never matches `I` or `Z`. + assert_eq!(sum.trace(&Pattern::zero_state(4)), 16.0); + assert_eq!(sum.trace(&Pattern::from(vec![SiteSet::Y; 4])), 0.0); + assert_eq!( + LossyPauliSum::::new(4).trace(&Pattern::zero_state(4)), + 0.0 + ); +} + +#[test] +#[should_panic(expected = "pattern width must match sum width")] +fn trace_rejects_mismatched_widths() { + PauliSum::::new(2).trace(&Pattern::zero_state(3)); +} + +#[test] +fn basis_state_readout_matches_the_dense_diagonal() { + let o = random_sum(3, 16, 11); + let matrix = dense(&o); + for b in 0..8 { + // = <0|X^b O X^b|0>. + let mut flipped = o.clone(); + for q in (0..3).filter(|q| b >> (2 - q) & 1 == 1) { + flipped.x(q); + } + let readout = flipped.trace(&Pattern::zero_state(3)); + assert!((readout - matrix[b * 8 + b]).norm() < 1e-12, "b = {b:03b}"); + } +} + +/// Observables propagate backwards: apply the circuit's gates in reverse order. +#[test] +fn propagation_workloads_read_out_known_values() { + let zero = |n| Pattern::zero_state(n); + let observable = |w: &str| PauliSum::::from_terms(w.len(), [(w.into(), 1.0)]); + + let theta = 0.7; + let mut z = observable("Z"); + z.rx(0, theta); + assert_abs_diff_eq!(z.trace(&zero(1)), theta.cos(), epsilon = 1e-12); + + // GHZ: H(0), CNOT(0, 1), CNOT(1, 2). + for (w, expected) in [ + ("ZZI", 1.0), + ("IZZ", 1.0), + ("XXX", 1.0), + ("YYX", -1.0), + ("ZII", 0.0), + ] { + let mut o = observable(w); + o.cnot(1, 2); + o.cnot(0, 1); + o.h(0); + assert_eq!(o.trace(&zero(3)), expected, "{w}"); + } + + // Probability of outcome 0 after H on |0>: the observable is P0 itself. + let mut born = observable("I"); + born.p0(0); + born.h(0); + assert_abs_diff_eq!(born.trace(&zero(1)), 0.5, epsilon = 1e-12); + + // Loss from a live |0>: L reads out p, Z reads out 1 - p; a lost start reads L as 1. + let p = 0.3; + let lossy = |w: &str| { + let mut sum = LossyPauliSum::::from_terms(1, [(w.into(), 1.0)]); + sum.loss_channel(0, p); + sum + }; + assert_abs_diff_eq!(lossy("L").trace(&zero(1)), p, epsilon = 1e-12); + assert_abs_diff_eq!(lossy("Z").trace(&zero(1)), 1.0 - p, epsilon = 1e-12); + assert_eq!(lossy("L").trace(&Pattern::from(vec![SiteSet::L])), 1.0); +}