Repository navigation
Add sum products, z-basis projection, and pattern readout to PPVM-pauli-sum-2 #316
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
JonhasA
wants to merge
2
commits into
trait-2/pauli-sum-2-loss-noise
Choose a base branch
from
trait-2/pauli-sum-2-product-readout
base: trait-2/pauli-sum-2-loss-noise
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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> | ||
| 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 | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)) | ||
| }); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)); | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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?