From 1650b7473914ae10203623342fdf6a64126dd055 Mon Sep 17 00:00:00 2001 From: jonhas colina Date: Sun, 22 Nov 2026 23:41:22 -0500 Subject: [PATCH 1/3] added single qubit rotation support with storage support. --- Cargo.lock | 4 +- crates/ppvm-pauli-sum-2/Cargo.toml | 4 + crates/ppvm-pauli-sum-2/src/clifford.rs | 2 + crates/ppvm-pauli-sum-2/src/lib.rs | 3 +- crates/ppvm-pauli-sum-2/src/rotation.rs | 38 ++++++ crates/ppvm-pauli-sum-2/src/store.rs | 39 +++++- crates/ppvm-pauli-sum-2/tests/rotation.rs | 149 ++++++++++++++++++++++ 7 files changed, 230 insertions(+), 9 deletions(-) create mode 100644 crates/ppvm-pauli-sum-2/src/rotation.rs create mode 100644 crates/ppvm-pauli-sum-2/tests/rotation.rs diff --git a/Cargo.lock b/Cargo.lock index e0e378b19..9b47df896 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2241,11 +2241,13 @@ dependencies = [ [[package]] name = "ppvm-pauli-sum-2" -version = "0.3.0" +version = "0.4.1" dependencies = [ "approx", + "criterion 0.8.2", "num", "ppvm-lossy-pauli-word-2", + "ppvm-pauli-sum", "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 b68144306..ea6615a11 100644 --- a/crates/ppvm-pauli-sum-2/Cargo.toml +++ b/crates/ppvm-pauli-sum-2/Cargo.toml @@ -16,3 +16,7 @@ ppvm-lossy-pauli-word-2 = { path = "../ppvm-lossy-pauli-word-2" } ppvm-phased-pauli-word-2 = { path = "../ppvm-phased-pauli-word-2" } num = "0.4" approx = { version = "0.5.1", features = ["num-complex"] } + +[dev-dependencies] +ppvm-pauli-sum = { path = "../ppvm-pauli-sum" } +criterion = "0.8.2" diff --git a/crates/ppvm-pauli-sum-2/src/clifford.rs b/crates/ppvm-pauli-sum-2/src/clifford.rs index 5aebcf84e..8f05001a1 100644 --- a/crates/ppvm-pauli-sum-2/src/clifford.rs +++ b/crates/ppvm-pauli-sum-2/src/clifford.rs @@ -126,6 +126,7 @@ impl Clifford for Sum where S: RekeyBijective + SignFlipByKey, S::Key: PauliBits + LossInfo, + Phased: Clifford, { fn x(&mut self, qubit: usize) { self.check_qubit(qubit); @@ -192,6 +193,7 @@ impl CliffordBatch for Sum where S: RekeyBijective + SignFlipByKey, S::Key: PauliBits + LossInfo, + Phased: Clifford, { fn x_many(&mut self, indices: &[usize]) { if let &[qubit] = indices { diff --git a/crates/ppvm-pauli-sum-2/src/lib.rs b/crates/ppvm-pauli-sum-2/src/lib.rs index d4ce69e63..6c1822838 100644 --- a/crates/ppvm-pauli-sum-2/src/lib.rs +++ b/crates/ppvm-pauli-sum-2/src/lib.rs @@ -6,13 +6,14 @@ mod compare; mod display; mod ops; mod policy; +mod rotation; mod store; mod sum; pub use policy::{ CoefficientThreshold, CombinedPolicy, MaxLossWeight, MaxPauliWeight, NoPolicy, Policy, }; -pub use store::{HashMapStore, RekeyBijective, SignFlipByKey, StoreAlloc}; +pub use store::{BranchInPlace, 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/rotation.rs b/crates/ppvm-pauli-sum-2/src/rotation.rs new file mode 100644 index 000000000..5f3941a6f --- /dev/null +++ b/crates/ppvm-pauli-sum-2/src/rotation.rs @@ -0,0 +1,38 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +use ppvm_traits_2::{Angle, Coefficient, Pauli, PauliBits, RotationOne, loss::LossInfo}; + +use crate::{BranchInPlace, Sum}; + +impl RotationOne for Sum +where + S: BranchInPlace, + S::Key: PauliBits + LossInfo, + A: Angle, +{ + fn rotate_1(&mut self, axis: Pauli, qubit: usize, theta: A) { + assert!(qubit < self.n_sites(), "qubit out of bounds"); + if axis == Pauli::I { + return; + } + let (sin, cos) = theta.sin_cos(); + self.storage.branch_in_place(|key, coeff| { + if key.is_lost(qubit) { + return None; + } + let x = key.x_bit(qubit); + let z = key.z_bit(qubit); + // Heisenberg conjugation: Rx sends Z to cos(theta) Z + sin(theta) Y. + let (toggle_x, toggle_z, negative) = match axis { + Pauli::X if z => (true, false, x), + Pauli::Y if x != z => (true, true, z), + Pauli::Z if x => (false, true, !z), + _ => return None, + }; + let branch = coeff.clone() * sin.mul_sign(if negative { -1 } else { 1 }); + *coeff *= &cos; + Some((key.toggled_bits(qubit, toggle_x, toggle_z), branch)) + }); + } +} diff --git a/crates/ppvm-pauli-sum-2/src/store.rs b/crates/ppvm-pauli-sum-2/src/store.rs index 58f183557..4e7f3b04d 100644 --- a/crates/ppvm-pauli-sum-2/src/store.rs +++ b/crates/ppvm-pauli-sum-2/src/store.rs @@ -34,20 +34,30 @@ pub trait SignFlipByKey: Support { fn flip_sign_by_key(&mut self, negate: impl Fn(&Self::Key) -> bool); } +/// Update original coefficients, then accumulate optional generated terms. +pub trait BranchInPlace: Support { + /// Visit each original term once; merge branches only after all visits finish. + /// Collisions add coefficients, exact zeros remain stored, and widths must match. + fn branch_in_place( + &mut self, + transform: impl FnMut(&Self::Key, &mut Self::Coeff) -> Option<(Self::Key, Self::Coeff)>, + ); +} + /// Hash-map storage whose keys supply their own structural digests. /// Exact-zero coefficients remain present until [`Accumulate::reduce`] is called. #[derive(Debug)] pub struct HashMapStore { terms: HashMap, - // Empty between operations; holds the terms whose keys a gate changes. - moved: Vec<(K, C)>, + // Empty between operations; buffers rekeyed or generated terms. + buffer: Vec<(K, C)>, } impl Clone for HashMapStore { fn clone(&self) -> Self { Self { terms: self.terms.clone(), - moved: Vec::new(), + buffer: Vec::new(), } } } @@ -56,13 +66,13 @@ impl StoreAlloc for HashMapStore { fn with_capacity(capacity: usize) -> Self { Self { terms: HashMap::with_capacity_and_hasher(capacity, IdentityBuildHasher), - moved: Vec::new(), + buffer: Vec::new(), } } fn clear(&mut self) { self.terms.clear(); - self.moved.clear(); + self.buffer.clear(); } } @@ -137,7 +147,7 @@ impl Retain for HashMapStore { impl RekeyBijective for HashMapStore { fn rekey_bijective(&mut self, mut transform: impl FnMut(&K, &mut C) -> Option) { - let mut moved = std::mem::take(&mut self.moved); + let mut moved = std::mem::take(&mut self.buffer); // Unchanged keys stay in place; only changed keys move to new buckets. self.terms.retain(|key, coeff| match transform(key, coeff) { None => true, @@ -151,7 +161,7 @@ impl RekeyBijective for HashMapStore { let replaced = self.terms.insert(key, coeff); debug_assert!(replaced.is_none(), "rekey must preserve distinct keys"); } - self.moved = moved; + self.buffer = moved; } } @@ -165,5 +175,20 @@ impl SignFlipByKey for HashMapStore { } } +impl BranchInPlace for HashMapStore { + fn branch_in_place(&mut self, mut transform: impl FnMut(&K, &mut C) -> Option<(K, C)>) { + let mut branches = std::mem::take(&mut self.buffer); + for (key, coeff) in &mut self.terms { + if let Some(branch) = transform(key, coeff) { + branches.push(branch); + } + } + for (key, coeff) in branches.drain(..) { + self.terms.accumulate(key, coeff); + } + self.buffer = branches; + } +} + #[cfg(test)] mod tests; diff --git a/crates/ppvm-pauli-sum-2/tests/rotation.rs b/crates/ppvm-pauli-sum-2/tests/rotation.rs new file mode 100644 index 000000000..32eab9fcc --- /dev/null +++ b/crates/ppvm-pauli-sum-2/tests/rotation.rs @@ -0,0 +1,149 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +use approx::assert_abs_diff_eq; +use num::Complex; +use ppvm_pauli_sum_2::{CoefficientThreshold, LossyPauliSum, LossyPauliWord, PauliSum, PauliWord}; +use ppvm_traits_2::{Pauli, RotationOne}; + +#[test] +fn colliding_branches_use_original_coefficients() { + for (axis, positive, negative) in [ + (Pauli::X, "Z", "Y"), + (Pauli::Y, "X", "Z"), + (Pauli::Z, "Y", "X"), + ] { + let mut sum = PauliSum::::new(1); + sum += (positive, 2.0); + sum += (negative, 3.0); + sum += ("I", 4.0); + sum.rotate_1(axis, 0, 0.37); + let (sin, cos) = 0.37_f64.sin_cos(); + assert_abs_diff_eq!( + sum.get(&PauliWord::from(positive)).unwrap(), + 2.0 * cos - 3.0 * sin, + epsilon = 1e-12 + ); + assert_abs_diff_eq!( + sum.get(&PauliWord::from(negative)).unwrap(), + 3.0 * cos + 2.0 * sin, + epsilon = 1e-12 + ); + assert_eq!(sum.get(&PauliWord::from("I")), Some(4.0)); + assert_eq!(sum.len(), 3); + } +} + +#[test] +fn complex_coefficients_with_real_angles() { + let mut sum = PauliSum::>::new(1); + let coeff = Complex::new(2.0, -3.0); + sum += ("Z", coeff); + sum.rx(0, 0.37_f64); + assert_abs_diff_eq!( + sum.get(&PauliWord::from("Z")).unwrap(), + coeff * 0.37_f64.cos(), + epsilon = 1e-12 + ); + assert_abs_diff_eq!( + sum.get(&PauliWord::from("Y")).unwrap(), + coeff * 0.37_f64.sin(), + epsilon = 1e-12 + ); +} + +#[test] +fn zeros_and_truncation_remain_explicit() { + let mut sum = PauliSum::::with_policy(1, CoefficientThreshold { threshold: 10.0 }); + sum += ("Z", 1.0); + sum.rx(0, 0.0); + assert_eq!(sum.get(&PauliWord::from("Z")), Some(1.0)); + assert_eq!(sum.get(&PauliWord::from("Y")), Some(0.0)); + sum.reduce(); + assert_eq!(sum.len(), 1); + sum.truncate(); + assert!(sum.is_empty()); + + // Z cancels exactly: sin(theta) * cos(theta) - cos(theta) * sin(theta). + let (sin, cos) = 0.37_f64.sin_cos(); + let mut sum = PauliSum::::new(1); + sum += ("Y", cos); + sum += ("Z", sin); + sum.rx(0, 0.37); + assert_eq!(sum.get(&PauliWord::from("Z")), Some(0.0)); + assert_eq!(sum.len(), 2); +} + +#[test] +fn lost_and_commuting_sites_are_unchanged() { + for (axis, commuting) in [(Pauli::X, "X"), (Pauli::Y, "Y"), (Pauli::Z, "Z")] { + let mut sum = LossyPauliSum::::new(1); + sum += ("L", 2.0); + sum += ("I", 3.0); + sum += (commuting, 4.0); + let original = sum.clone(); + sum.rotate_1(axis, 0, 0.37); + assert_eq!(sum, original); + } + let mut sum = LossyPauliSum::::new(2); + sum += ("LZ", 2.0); + sum.rx(1, 0.37); + assert_abs_diff_eq!( + sum.get(&LossyPauliWord::from("LY")).unwrap(), + 2.0 * 0.37_f64.sin(), + epsilon = 1e-12 + ); +} + +#[test] +fn identity_and_invalid_indices() { + use std::panic::{AssertUnwindSafe, catch_unwind}; + let mut sum = PauliSum::::new(1); + sum += ("Z", 1.0); + let original = sum.clone(); + sum.rotate_1(Pauli::I, 0, 0.37); + assert_eq!(sum, original); + for axis in [Pauli::I, Pauli::X, Pauli::Y, Pauli::Z] { + assert!(catch_unwind(AssertUnwindSafe(|| sum.rotate_1(axis, 1, 0.37))).is_err()); + assert_eq!(sum, original); + } + let mut empty = PauliSum::::new(0); + assert!(catch_unwind(AssertUnwindSafe(|| empty.rx(0, 0.37))).is_err()); +} + +#[test] +fn sequence_matches_existing_engine() { + use old::RotationOne as _; + use ppvm_pauli_sum::prelude as old; + let mut legacy: old::PauliSum> = + old::PauliSum::builder().n_qubits(2).build(); + let mut sum = PauliSum::::new(2); + for (i, word) in ["II", "XY", "YZ", "ZX", "IZ", "IY"].iter().enumerate() { + let coeff = (i as f64 - 2.0) / 3.0; + legacy += (old::PauliWord::<[u8; 1]>::from(*word), coeff); + sum += (*word, coeff); + } + for step in 0..24 { + let theta = (step as f64 - 8.0) * 0.17; + let q = step % 2; + match step % 3 { + 0 => { + legacy.rx(q, theta); + sum.rx(q, theta); + } + 1 => { + legacy.ry(q, theta); + sum.ry(q, theta); + } + _ => { + legacy.rz(q, theta); + sum.rz(q, theta); + } + } + for (key, coeff) in legacy.iter() { + let key = PauliWord::from(key.to_string().as_str()); + assert_abs_diff_eq!(sum.get(&key).unwrap(), *coeff, epsilon = 1e-12); + } + assert_eq!(sum.len(), legacy.len()); + } +} From 4f768d3cf25465f5ea7d7556388f022835b71c2c Mon Sep 17 00:00:00 2001 From: jonhas colina Date: Sun, 22 Nov 2026 23:58:28 -0500 Subject: [PATCH 2/3] added two qubit support alongisde remianing interfaces --- crates/ppvm-pauli-sum-2/src/rotation.rs | 246 +++++++++++++- .../tests/rotation_interfaces.rs | 301 ++++++++++++++++++ 2 files changed, 546 insertions(+), 1 deletion(-) create mode 100644 crates/ppvm-pauli-sum-2/tests/rotation_interfaces.rs diff --git a/crates/ppvm-pauli-sum-2/src/rotation.rs b/crates/ppvm-pauli-sum-2/src/rotation.rs index 5f3941a6f..1b3544158 100644 --- a/crates/ppvm-pauli-sum-2/src/rotation.rs +++ b/crates/ppvm-pauli-sum-2/src/rotation.rs @@ -1,7 +1,15 @@ // SPDX-FileCopyrightText: 2026 The PPVM Authors // SPDX-License-Identifier: Apache-2.0 -use ppvm_traits_2::{Angle, Coefficient, Pauli, PauliBits, RotationOne, loss::LossInfo}; +//! Heisenberg rotations, with reduction and truncation left to the caller. +//! Two-site generators drop lost sites, leaving a rotation on the survivor. +//! CRx inherits this convention through Rx(theta/2) and RZX(-theta/2): a lost +//! control cancels the rotations; a lost target leaves Rz(-theta/2) on control. + +use ppvm_traits_2::{ + Angle, CRx, Coefficient, Pauli, PauliBits, RotXY, RotationOne, RotationOneBatch, RotationTwo, + RotationTwoBatch, Support, TGate, U3Gate, loss::LossInfo, +}; use crate::{BranchInPlace, Sum}; @@ -36,3 +44,239 @@ where }); } } + +impl RotationOneBatch for Sum +where + S: BranchInPlace, + S::Key: PauliBits + LossInfo, + A: Angle, +{ +} + +impl RotationTwo for Sum +where + S: BranchInPlace, + S::Key: PauliBits + LossInfo, + A: Angle, +{ + fn rotate_2(&mut self, axis_a: Pauli, axis_b: Pauli, a: usize, b: usize, theta: A) { + assert!( + a < self.n_sites() && b < self.n_sites(), + "qubit out of bounds" + ); + assert_ne!(a, b, "rotation requires distinct qubits"); + let (sin, cos) = theta.sin_cos(); + self.storage.branch_in_place(|key, coeff| { + // A lost site drops out of the generator, preserving the reference's + // single-qubit fallback on the surviving site. + let axis_a = if key.is_lost(a) { Pauli::I } else { axis_a }; + let axis_b = if key.is_lost(b) { Pauli::I } else { axis_b }; + let (mask_a, anti_a, negative_a) = local_product(axis_a, key.x_bit(a), key.z_bit(a)); + let (mask_b, anti_b, negative_b) = local_product(axis_b, key.x_bit(b), key.z_bit(b)); + if anti_a == anti_b { + return None; + } + // Exactly one local product anticommutes; the other has phase +1. + let negative = if anti_a { negative_a } else { negative_b }; + let branch = coeff.clone() * sin.mul_sign(if negative { -1 } else { 1 }); + *coeff *= &cos; + Some((key.toggled_bits2(a, mask_a, b, mask_b), branch)) + }); + } + + #[inline] + fn rxx(&mut self, a: usize, b: usize, theta: A) { + assert!( + a < self.n_sites() && b < self.n_sites(), + "qubit out of bounds" + ); + assert_ne!(a, b, "rotation requires distinct qubits"); + let (sin, cos) = theta.sin_cos(); + self.storage.branch_in_place(|key, coeff| { + if key.is_lost(a) { + return single_branch(key, coeff, Pauli::X, b, &sin, &cos); + } + if key.is_lost(b) { + return single_branch(key, coeff, Pauli::X, a, &sin, &cos); + } + let za = key.z_bit(a); + let zb = key.z_bit(b); + if za == zb { + return None; + } + let xa = key.x_bit(a); + let xb = key.x_bit(b); + let x_anti = if za { xa } else { xb }; + let sign = if x_anti { -1 } else { 1 }; + let branch = coeff.clone() * sin.mul_sign(sign); + *coeff *= &cos; + Some(( + key.toggled_bits2(a, [true, false], b, [true, false]), + branch, + )) + }); + } + + #[inline] + fn ryy(&mut self, a: usize, b: usize, theta: A) { + assert!( + a < self.n_sites() && b < self.n_sites(), + "qubit out of bounds" + ); + assert_ne!(a, b, "rotation requires distinct qubits"); + let (sin, cos) = theta.sin_cos(); + self.storage.branch_in_place(|key, coeff| { + if key.is_lost(a) { + return single_branch(key, coeff, Pauli::Y, b, &sin, &cos); + } + if key.is_lost(b) { + return single_branch(key, coeff, Pauli::Y, a, &sin, &cos); + } + let xa = key.x_bit(a); + let za = key.z_bit(a); + let xb = key.x_bit(b); + let zb = key.z_bit(b); + let anti_a = xa != za; + if anti_a == (xb != zb) { + return None; + } + let x_anti = if anti_a { xa } else { xb }; + let sign = if x_anti { 1 } else { -1 }; + let branch = coeff.clone() * sin.mul_sign(sign); + *coeff *= &cos; + Some((key.toggled_bits2(a, [true, true], b, [true, true]), branch)) + }); + } + + #[inline] + fn rzz(&mut self, a: usize, b: usize, theta: A) { + assert!( + a < self.n_sites() && b < self.n_sites(), + "qubit out of bounds" + ); + assert_ne!(a, b, "rotation requires distinct qubits"); + let (sin, cos) = theta.sin_cos(); + self.storage.branch_in_place(|key, coeff| { + if key.is_lost(a) { + return single_branch(key, coeff, Pauli::Z, b, &sin, &cos); + } + if key.is_lost(b) { + return single_branch(key, coeff, Pauli::Z, a, &sin, &cos); + } + let xa = key.x_bit(a); + let xb = key.x_bit(b); + if xa == xb { + return None; + } + let za = key.z_bit(a); + let zb = key.z_bit(b); + let z_anti = if xa { za } else { zb }; + let sign = if z_anti { 1 } else { -1 }; + let branch = coeff.clone() * sin.mul_sign(sign); + *coeff *= &cos; + Some(( + key.toggled_bits2(a, [false, true], b, [false, true]), + branch, + )) + }); + } +} + +/// Generator mask, anticommutation, and sign of i * axis * word (when anticommuting). +#[inline] +fn local_product(axis: Pauli, x: bool, z: bool) -> ([bool; 2], bool, bool) { + match axis { + Pauli::I => ([false, false], false, false), + Pauli::X => ([true, false], z, x), + Pauli::Y => ([true, true], x != z, z), + Pauli::Z => ([false, true], x, !z), + } +} + +impl RotationTwoBatch for Sum +where + S: BranchInPlace, + S::Key: PauliBits + LossInfo, + A: Angle, +{ +} + +impl TGate for Sum +where + Self: RotationOne, + f64: Angle, +{ + fn t(&mut self, qubit: usize) { + self.rz(qubit, std::f64::consts::FRAC_PI_4); + } + + fn t_dag(&mut self, qubit: usize) { + self.rz(qubit, -std::f64::consts::FRAC_PI_4); + } +} + +impl U3Gate for Sum +where + Self: RotationOne, + A: Angle, +{ + fn u3(&mut self, qubit: usize, theta: A, phi: A, lambda: A) { + // U3 = Rz(phi) Ry(theta) Rz(lambda); propagate in Heisenberg order. + self.rz(qubit, phi); + self.ry(qubit, theta); + self.rz(qubit, lambda); + } +} + +impl RotXY for Sum +where + Self: RotationOne, + A: Angle + Clone + std::ops::Neg, +{ + fn r(&mut self, qubit: usize, axis_angle: A, theta: A) { + self.rz(qubit, axis_angle.clone()); + self.rx(qubit, theta); + self.rz(qubit, -axis_angle); + } +} + +impl CRx for Sum +where + Self: RotationOne + RotationTwo, + A: Angle + Clone + std::ops::Mul + std::ops::Neg, +{ + fn crx(&mut self, control: usize, target: usize, theta: A) { + assert!( + control < self.n_sites() && target < self.n_sites(), + "qubit out of bounds" + ); + assert_ne!(control, target, "rotation requires distinct qubits"); + // |1><1| ⊗ X = (IX - ZX)/2. The two generators commute. + // Loss follows the constituent rotations' surviving-site convention. + let half = theta * 0.5; + self.rx(target, half.clone()); + self.rzx(control, target, -half); + } +} + +// Single-site fallback for a two-site rotation whose other site is lost. +#[inline] +fn single_branch( + key: &W, + coeff: &mut C, + axis: Pauli, + qubit: usize, + sin: &C, + cos: &C, +) -> Option<(W, C)> { + if key.is_lost(qubit) { + return None; + } + let (mask, anti, negative) = local_product(axis, key.x_bit(qubit), key.z_bit(qubit)); + if !anti { + return None; + } + let branch = coeff.clone() * sin.mul_sign(if negative { -1 } else { 1 }); + *coeff *= cos; + Some((key.toggled_bits(qubit, mask[0], mask[1]), branch)) +} diff --git a/crates/ppvm-pauli-sum-2/tests/rotation_interfaces.rs b/crates/ppvm-pauli-sum-2/tests/rotation_interfaces.rs new file mode 100644 index 000000000..f3b140e0a --- /dev/null +++ b/crates/ppvm-pauli-sum-2/tests/rotation_interfaces.rs @@ -0,0 +1,301 @@ +// SPDX-FileCopyrightText: 2026 The PPVM Authors +// SPDX-License-Identifier: Apache-2.0 + +use approx::assert_abs_diff_eq; +use num::Complex; +use ppvm_pauli_sum_2::{LossyPauliSum, LossyPauliWord, PauliSum}; +use ppvm_traits_2::{ + CRx, Pauli, RotXY, RotationOne, RotationOneBatch, RotationTwo, RotationTwoBatch, TGate, U3Gate, +}; + +const AXES: [(Pauli, char); 4] = [ + (Pauli::I, 'I'), + (Pauli::X, 'X'), + (Pauli::Y, 'Y'), + (Pauli::Z, 'Z'), +]; +type C = Complex; +type Matrix = [[C; 4]; 4]; + +fn multiply(a: Matrix, b: Matrix) -> Matrix { + std::array::from_fn(|i| std::array::from_fn(|j| (0..4).map(|k| a[i][k] * b[k][j]).sum())) +} + +fn pauli(a: Pauli, b: Pauli) -> Matrix { + fn entry(p: Pauli, i: usize, j: usize) -> C { + match p { + Pauli::I => C::new((i == j) as u8 as f64, 0.0), + Pauli::X => C::new((i != j) as u8 as f64, 0.0), + Pauli::Y if i != j => C::new(0.0, if i == 0 { -1.0 } else { 1.0 }), + Pauli::Z if i == j => C::new(if i == 0 { 1.0 } else { -1.0 }, 0.0), + _ => C::new(0.0, 0.0), + } + } + std::array::from_fn(|i| { + std::array::from_fn(|j| entry(a, i / 2, j / 2) * entry(b, i % 2, j % 2)) + }) +} + +fn rotation(a: Pauli, b: Pauli, theta: f64) -> Matrix { + let generator = pauli(a, b); + let identity = pauli(Pauli::I, Pauli::I); + std::array::from_fn(|i| { + std::array::from_fn(|j| { + identity[i][j] * (theta / 2.0).cos() - C::i() * generator[i][j] * (theta / 2.0).sin() + }) + }) +} + +fn observable() -> PauliSum { + let mut sum = PauliSum::new(2); + for (i, (_, a)) in AXES.iter().enumerate() { + for (j, (_, b)) in AXES.iter().enumerate() { + sum += ( + format!("{a}{b}").as_str(), + C::new((i * 4 + j + 1) as f64 / 17.0, (i as f64 - j as f64) / 9.0), + ); + } + } + sum +} + +fn matrix(sum: &PauliSum) -> Matrix { + let mut out = [[C::new(0.0, 0.0); 4]; 4]; + for (a, ca) in AXES { + for (b, cb) in AXES { + let key = ppvm_pauli_sum_2::PauliWord::from(format!("{ca}{cb}").as_str()); + let coeff = sum.get(&key).unwrap_or_default(); + let term = pauli(a, b); + for i in 0..4 { + for j in 0..4 { + out[i][j] += coeff * term[i][j]; + } + } + } + } + out +} + +fn check_conjugation(sum: &PauliSum, unitary: Matrix) { + let adjoint = std::array::from_fn(|i| std::array::from_fn(|j| unitary[j][i].conj())); + let expected = multiply(multiply(adjoint, matrix(&observable())), unitary); + let actual = matrix(sum); + for i in 0..4 { + for j in 0..4 { + assert_abs_diff_eq!(actual[i][j], expected[i][j], epsilon = 1e-12); + } + } +} + +#[test] +fn all_two_qubit_axes_match_dense_conjugation() { + for (a, _) in AXES { + for (b, _) in AXES { + for theta in [0.0, 0.37, -0.81] { + let mut sum = observable(); + sum.rotate_2(a, b, 0, 1, theta); + check_conjugation(&sum, rotation(a, b, theta)); + } + } + } +} + +#[test] +fn lost_sites_reduce_to_surviving_rotation() { + for (a, _) in AXES { + for (b, _) in AXES { + for word in ["LX", "LY", "LZ", "XL", "YL", "ZL", "LL"] { + let mut sum = LossyPauliSum::::new(2); + sum += (word, 2.0); + let mut expected = sum.clone(); + if word.starts_with('L') { + expected.rotate_1(b, 1, 0.37); + } else { + expected.rotate_1(a, 0, 0.37); + } + sum.rotate_2(a, b, 0, 1, 0.37); + assert_abs_diff_eq!(sum, expected, epsilon = 1e-12); + } + } + } +} + +#[test] +fn composite_interfaces_match_dense_unitaries() { + let mut sum = observable(); + sum.u3(1, 0.37, -0.51, 0.82); + check_conjugation( + &sum, + multiply( + multiply( + rotation(Pauli::I, Pauli::Z, -0.51), + rotation(Pauli::I, Pauli::Y, 0.37), + ), + rotation(Pauli::I, Pauli::Z, 0.82), + ), + ); + + let mut sum = observable(); + sum.r(1, 0.51, 0.37); + check_conjugation( + &sum, + multiply( + multiply( + rotation(Pauli::I, Pauli::Z, 0.51), + rotation(Pauli::I, Pauli::X, 0.37), + ), + rotation(Pauli::I, Pauli::Z, -0.51), + ), + ); + + let mut sum = observable(); + sum.t(1); + check_conjugation( + &sum, + rotation(Pauli::I, Pauli::Z, std::f64::consts::FRAC_PI_4), + ); + sum.t_dag(1); + assert_abs_diff_eq!(sum, observable(), epsilon = 1e-12); + + for theta in [0.0, 0.37, -0.81] { + let mut sum = observable(); + sum.crx(0, 1, theta); + // Build a controlled Rx directly: identity in the control=0 block. + let rx = rotation(Pauli::I, Pauli::X, theta); + let mut unitary = pauli(Pauli::I, Pauli::I); + for i in 2..4 { + for j in 2..4 { + unitary[i][j] = rx[i][j]; + } + } + check_conjugation(&sum, unitary); + } +} + +#[test] +fn batches_match_ordered_scalar_calls() { + type Single = fn(&mut PauliSum, usize, f64); + type Singles = fn(&mut PauliSum, &[usize], f64); + let singles: [(Single, Singles); 3] = [ + (PauliSum::rx, PauliSum::rx_many), + (PauliSum::ry, PauliSum::ry_many), + (PauliSum::rz, PauliSum::rz_many), + ]; + for (scalar, batch) in singles { + let mut sum = observable(); + let mut expected = sum.clone(); + batch(&mut sum, &[1, 0, 1], 0.37); + for q in [1, 0, 1] { + scalar(&mut expected, q, 0.37); + } + assert_abs_diff_eq!(sum, expected, epsilon = 1e-12); + } + type Pair = fn(&mut PauliSum, usize, usize, f64); + type Pairs = fn(&mut PauliSum, &[(usize, usize)], f64); + let pairs: [(Pair, Pairs); 9] = [ + (PauliSum::rxx, PauliSum::rxx_many), + (PauliSum::rxy, PauliSum::rxy_many), + (PauliSum::rxz, PauliSum::rxz_many), + (PauliSum::ryx, PauliSum::ryx_many), + (PauliSum::ryy, PauliSum::ryy_many), + (PauliSum::ryz, PauliSum::ryz_many), + (PauliSum::rzx, PauliSum::rzx_many), + (PauliSum::rzy, PauliSum::rzy_many), + (PauliSum::rzz, PauliSum::rzz_many), + ]; + for (scalar, batch) in pairs { + let mut sum = observable(); + let mut expected = sum.clone(); + batch(&mut sum, &[(0, 1), (1, 0)], 0.37); + scalar(&mut expected, 0, 1, 0.37); + scalar(&mut expected, 1, 0, 0.37); + assert_abs_diff_eq!(sum, expected, epsilon = 1e-12); + } + let mut sum = observable(); + sum.t_many(&[0, 1]); + sum.t_dag_many(&[0, 1]); + assert_abs_diff_eq!(sum, observable(), epsilon = 1e-12); +} + +#[test] +fn invalid_pairs_panic_before_mutation() { + use std::panic::{AssertUnwindSafe, catch_unwind}; + for (a, b) in [(0, 0), (0, 2), (2, 0)] { + let mut sum = observable(); + assert!(catch_unwind(AssertUnwindSafe(|| sum.rxx(a, b, 0.37))).is_err()); + assert_eq!(sum, observable()); + assert!(catch_unwind(AssertUnwindSafe(|| sum.crx(a, b, 0.37))).is_err()); + assert_eq!(sum, observable()); + } + let mut empty = PauliSum::::new(0); + assert!(catch_unwind(AssertUnwindSafe(|| empty.rzz(0, 1, 0.37))).is_err()); +} + +#[test] +fn two_qubit_zero_branches_remain_until_reduced() { + let mut sum = PauliSum::::new(2); + sum += ("ZI", 2.0); + sum.rxx(0, 1, 0.0); + assert_eq!(sum.len(), 2); + assert_eq!(sum.get(&ppvm_pauli_sum_2::PauliWord::from("YX")), Some(0.0)); + sum.reduce(); + assert_eq!(sum.len(), 1); + + let mut sum = observable(); + sum.crx(0, 1, C::new(0.37, 0.0)); + let mut expected = observable(); + expected.crx(0, 1, 0.37); + assert_abs_diff_eq!(sum, expected, epsilon = 1e-12); +} + +#[test] +fn controlled_rotation_loss_follows_generator_decomposition() { + let mut sum = LossyPauliSum::::new(2); + sum += ("LZ", 1.0); + sum.crx(0, 1, 0.37); + assert_abs_diff_eq!( + sum.get(&LossyPauliWord::from("LZ")).unwrap(), + 1.0, + epsilon = 1e-12 + ); + assert_abs_diff_eq!( + sum.get(&LossyPauliWord::from("LY")).unwrap(), + 0.0, + epsilon = 1e-12 + ); + let mut sum = LossyPauliSum::::new(2); + sum += ("XL", 1.0); + let mut expected = sum.clone(); + expected.rz(0, -0.37 / 2.0); + sum.crx(0, 1, 0.37); + assert_abs_diff_eq!(sum, expected, epsilon = 1e-12); +} + +#[test] +fn specialized_pairs_match_generic_with_loss_and_complex_coefficients() { + type Gate = fn(&mut LossyPauliSum, usize, usize, f64); + let gates: [(Pauli, Gate); 3] = [ + (Pauli::X, LossyPauliSum::rxx), + (Pauli::Y, LossyPauliSum::ryy), + (Pauli::Z, LossyPauliSum::rzz), + ]; + for (axis, gate) in gates { + for theta in [0.0, 0.37, -0.81] { + for (a, b) in [(0, 1), (1, 0)] { + let mut sum = LossyPauliSum::::new(2); + for (i, x) in "IXYZL".chars().enumerate() { + for (j, y) in "IXYZL".chars().enumerate() { + sum += ( + format!("{x}{y}").as_str(), + C::new(i as f64 - 2.0, j as f64 - 1.0), + ); + } + } + let mut expected = sum.clone(); + expected.rotate_2(axis, axis, a, b, theta); + gate(&mut sum, a, b, theta); + assert_abs_diff_eq!(sum, expected, epsilon = 1e-12); + } + } + } +} From 6150eeb9bee4428700b89dd82e7a827f5752304c Mon Sep 17 00:00:00 2001 From: jonhas colina Date: Mon, 23 Nov 2026 00:07:05 -0500 Subject: [PATCH 3/3] asked claude to simplify comments and to simplify test cases --- crates/ppvm-pauli-sum-2/src/clifford.rs | 16 +--- crates/ppvm-pauli-sum-2/src/rotation.rs | 82 ++++++------------ crates/ppvm-pauli-sum-2/src/sum.rs | 10 +++ crates/ppvm-pauli-sum-2/tests/rotation.rs | 36 +++----- .../tests/rotation_interfaces.rs | 85 ++++++++++--------- 5 files changed, 96 insertions(+), 133 deletions(-) diff --git a/crates/ppvm-pauli-sum-2/src/clifford.rs b/crates/ppvm-pauli-sum-2/src/clifford.rs index 8f05001a1..dc1ff4a07 100644 --- a/crates/ppvm-pauli-sum-2/src/clifford.rs +++ b/crates/ppvm-pauli-sum-2/src/clifford.rs @@ -2,24 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 use ppvm_phased_pauli_word_2::Phased; -use ppvm_traits_2::{ - Clifford, CliffordBatch, Coefficient, PauliBits, Phase, Support, loss::LossInfo, -}; +use ppvm_traits_2::{Clifford, CliffordBatch, Coefficient, PauliBits, Phase, loss::LossInfo}; use crate::{RekeyBijective, SignFlipByKey, Sum}; -impl Sum { - fn check_qubit(&self, qubit: usize) { - assert!(qubit < self.n_sites(), "qubit out of bounds"); - } - - fn check_pair(&self, qubit0: usize, qubit1: usize) { - self.check_qubit(qubit0); - self.check_qubit(qubit1); - assert_ne!(qubit0, qubit1, "two-qubit gates require distinct qubits"); - } -} - /// Whether a gate on `qubit` can change `key`: every Clifford fixes `I` and lost sites. fn active(key: &K, qubit: usize) -> bool { !key.is_lost(qubit) && (key.x_bit(qubit) || key.z_bit(qubit)) diff --git a/crates/ppvm-pauli-sum-2/src/rotation.rs b/crates/ppvm-pauli-sum-2/src/rotation.rs index 1b3544158..6130ab7af 100644 --- a/crates/ppvm-pauli-sum-2/src/rotation.rs +++ b/crates/ppvm-pauli-sum-2/src/rotation.rs @@ -3,8 +3,8 @@ //! Heisenberg rotations, with reduction and truncation left to the caller. //! Two-site generators drop lost sites, leaving a rotation on the survivor. -//! CRx inherits this convention through Rx(theta/2) and RZX(-theta/2): a lost -//! control cancels the rotations; a lost target leaves Rz(-theta/2) on control. +//! For CRx, a lost control cancels the rotations; a lost target leaves +//! Rz(-theta/2) on the control. use ppvm_traits_2::{ Angle, CRx, Coefficient, Pauli, PauliBits, RotXY, RotationOne, RotationOneBatch, RotationTwo, @@ -20,35 +20,19 @@ where A: Angle, { fn rotate_1(&mut self, axis: Pauli, qubit: usize, theta: A) { - assert!(qubit < self.n_sites(), "qubit out of bounds"); + self.check_qubit(qubit); if axis == Pauli::I { return; } let (sin, cos) = theta.sin_cos(); - self.storage.branch_in_place(|key, coeff| { - if key.is_lost(qubit) { - return None; - } - let x = key.x_bit(qubit); - let z = key.z_bit(qubit); - // Heisenberg conjugation: Rx sends Z to cos(theta) Z + sin(theta) Y. - let (toggle_x, toggle_z, negative) = match axis { - Pauli::X if z => (true, false, x), - Pauli::Y if x != z => (true, true, z), - Pauli::Z if x => (false, true, !z), - _ => return None, - }; - let branch = coeff.clone() * sin.mul_sign(if negative { -1 } else { 1 }); - *coeff *= &cos; - Some((key.toggled_bits(qubit, toggle_x, toggle_z), branch)) - }); + self.storage + .branch_in_place(|key, coeff| single_branch(key, coeff, axis, qubit, &sin, &cos)); } } -impl RotationOneBatch for Sum +impl RotationOneBatch for Sum where - S: BranchInPlace, - S::Key: PauliBits + LossInfo, + Self: RotationOne, A: Angle, { } @@ -60,11 +44,7 @@ where A: Angle, { fn rotate_2(&mut self, axis_a: Pauli, axis_b: Pauli, a: usize, b: usize, theta: A) { - assert!( - a < self.n_sites() && b < self.n_sites(), - "qubit out of bounds" - ); - assert_ne!(a, b, "rotation requires distinct qubits"); + self.check_pair(a, b); let (sin, cos) = theta.sin_cos(); self.storage.branch_in_place(|key, coeff| { // A lost site drops out of the generator, preserving the reference's @@ -86,11 +66,7 @@ where #[inline] fn rxx(&mut self, a: usize, b: usize, theta: A) { - assert!( - a < self.n_sites() && b < self.n_sites(), - "qubit out of bounds" - ); - assert_ne!(a, b, "rotation requires distinct qubits"); + self.check_pair(a, b); let (sin, cos) = theta.sin_cos(); self.storage.branch_in_place(|key, coeff| { if key.is_lost(a) { @@ -119,11 +95,7 @@ where #[inline] fn ryy(&mut self, a: usize, b: usize, theta: A) { - assert!( - a < self.n_sites() && b < self.n_sites(), - "qubit out of bounds" - ); - assert_ne!(a, b, "rotation requires distinct qubits"); + self.check_pair(a, b); let (sin, cos) = theta.sin_cos(); self.storage.branch_in_place(|key, coeff| { if key.is_lost(a) { @@ -150,11 +122,7 @@ where #[inline] fn rzz(&mut self, a: usize, b: usize, theta: A) { - assert!( - a < self.n_sites() && b < self.n_sites(), - "qubit out of bounds" - ); - assert_ne!(a, b, "rotation requires distinct qubits"); + self.check_pair(a, b); let (sin, cos) = theta.sin_cos(); self.storage.branch_in_place(|key, coeff| { if key.is_lost(a) { @@ -193,10 +161,9 @@ fn local_product(axis: Pauli, x: bool, z: bool) -> ([bool; 2], bool, bool) { } } -impl RotationTwoBatch for Sum +impl RotationTwoBatch for Sum where - S: BranchInPlace, - S::Key: PauliBits + LossInfo, + Self: RotationTwo, A: Angle, { } @@ -246,11 +213,7 @@ where A: Angle + Clone + std::ops::Mul + std::ops::Neg, { fn crx(&mut self, control: usize, target: usize, theta: A) { - assert!( - control < self.n_sites() && target < self.n_sites(), - "qubit out of bounds" - ); - assert_ne!(control, target, "rotation requires distinct qubits"); + self.check_pair(control, target); // |1><1| ⊗ X = (IX - ZX)/2. The two generators commute. // Loss follows the constituent rotations' surviving-site convention. let half = theta * 0.5; @@ -259,7 +222,7 @@ where } } -// Single-site fallback for a two-site rotation whose other site is lost. +// Shared by single-qubit rotations and the surviving-site loss fallback. #[inline] fn single_branch( key: &W, @@ -272,11 +235,16 @@ fn single_branch( if key.is_lost(qubit) { return None; } - let (mask, anti, negative) = local_product(axis, key.x_bit(qubit), key.z_bit(qubit)); - if !anti { - return None; - } + let x = key.x_bit(qubit); + let z = key.z_bit(qubit); + // Heisenberg conjugation: Rx sends Z to cos(theta) Z + sin(theta) Y. + let (toggle_x, toggle_z, negative) = match axis { + Pauli::X if z => (true, false, x), + Pauli::Y if x != z => (true, true, z), + Pauli::Z if x => (false, true, !z), + _ => return None, + }; let branch = coeff.clone() * sin.mul_sign(if negative { -1 } else { 1 }); *coeff *= cos; - Some((key.toggled_bits(qubit, mask[0], mask[1]), branch)) + Some((key.toggled_bits(qubit, toggle_x, toggle_z), branch)) } diff --git a/crates/ppvm-pauli-sum-2/src/sum.rs b/crates/ppvm-pauli-sum-2/src/sum.rs index 3c36c00fc..cc04df721 100644 --- a/crates/ppvm-pauli-sum-2/src/sum.rs +++ b/crates/ppvm-pauli-sum-2/src/sum.rs @@ -29,6 +29,16 @@ pub struct Sum { } impl Sum { + pub(crate) fn check_qubit(&self, qubit: usize) { + assert!(qubit < self.n_sites(), "qubit out of bounds"); + } + + pub(crate) 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"); + } + /// Number of sites, including when the sum is empty. pub fn n_sites(&self) -> usize { self.n_sites diff --git a/crates/ppvm-pauli-sum-2/tests/rotation.rs b/crates/ppvm-pauli-sum-2/tests/rotation.rs index 32eab9fcc..2d7b6ad40 100644 --- a/crates/ppvm-pauli-sum-2/tests/rotation.rs +++ b/crates/ppvm-pauli-sum-2/tests/rotation.rs @@ -19,18 +19,11 @@ fn colliding_branches_use_original_coefficients() { sum += ("I", 4.0); sum.rotate_1(axis, 0, 0.37); let (sin, cos) = 0.37_f64.sin_cos(); - assert_abs_diff_eq!( - sum.get(&PauliWord::from(positive)).unwrap(), - 2.0 * cos - 3.0 * sin, - epsilon = 1e-12 - ); - assert_abs_diff_eq!( - sum.get(&PauliWord::from(negative)).unwrap(), - 3.0 * cos + 2.0 * sin, - epsilon = 1e-12 - ); - assert_eq!(sum.get(&PauliWord::from("I")), Some(4.0)); - assert_eq!(sum.len(), 3); + let mut expected = PauliSum::::new(1); + expected += (positive, 2.0 * cos - 3.0 * sin); + expected += (negative, 3.0 * cos + 2.0 * sin); + expected += ("I", 4.0); + assert_abs_diff_eq!(sum, expected, epsilon = 1e-12); } } @@ -40,16 +33,10 @@ fn complex_coefficients_with_real_angles() { let coeff = Complex::new(2.0, -3.0); sum += ("Z", coeff); sum.rx(0, 0.37_f64); - assert_abs_diff_eq!( - sum.get(&PauliWord::from("Z")).unwrap(), - coeff * 0.37_f64.cos(), - epsilon = 1e-12 - ); - assert_abs_diff_eq!( - sum.get(&PauliWord::from("Y")).unwrap(), - coeff * 0.37_f64.sin(), - epsilon = 1e-12 - ); + let mut expected = PauliSum::>::new(1); + expected += ("Z", coeff * 0.37_f64.cos()); + expected += ("Y", coeff * 0.37_f64.sin()); + assert_abs_diff_eq!(sum, expected, epsilon = 1e-12); } #[test] @@ -63,7 +50,10 @@ fn zeros_and_truncation_remain_explicit() { assert_eq!(sum.len(), 1); sum.truncate(); assert!(sum.is_empty()); +} +#[test] +fn exact_cancellation_keeps_zero_until_reduced() { // Z cancels exactly: sin(theta) * cos(theta) - cos(theta) * sin(theta). let (sin, cos) = 0.37_f64.sin_cos(); let mut sum = PauliSum::::new(1); @@ -72,6 +62,8 @@ fn zeros_and_truncation_remain_explicit() { sum.rx(0, 0.37); assert_eq!(sum.get(&PauliWord::from("Z")), Some(0.0)); assert_eq!(sum.len(), 2); + sum.reduce(); + assert_eq!(sum.len(), 1); } #[test] diff --git a/crates/ppvm-pauli-sum-2/tests/rotation_interfaces.rs b/crates/ppvm-pauli-sum-2/tests/rotation_interfaces.rs index f3b140e0a..56dff6fc0 100644 --- a/crates/ppvm-pauli-sum-2/tests/rotation_interfaces.rs +++ b/crates/ppvm-pauli-sum-2/tests/rotation_interfaces.rs @@ -3,7 +3,7 @@ use approx::assert_abs_diff_eq; use num::Complex; -use ppvm_pauli_sum_2::{LossyPauliSum, LossyPauliWord, PauliSum}; +use ppvm_pauli_sum_2::{LossyPauliSum, LossyPauliWord, PauliSum, PauliWord}; use ppvm_traits_2::{ CRx, Pauli, RotXY, RotationOne, RotationOneBatch, RotationTwo, RotationTwoBatch, TGate, U3Gate, }; @@ -52,7 +52,7 @@ fn observable() -> PauliSum { for (j, (_, b)) in AXES.iter().enumerate() { sum += ( format!("{a}{b}").as_str(), - C::new((i * 4 + j + 1) as f64 / 17.0, (i as f64 - j as f64) / 9.0), + C::new((i * 4 + j + 1) as f64, i as f64 - j as f64), ); } } @@ -63,7 +63,7 @@ fn matrix(sum: &PauliSum) -> Matrix { let mut out = [[C::new(0.0, 0.0); 4]; 4]; for (a, ca) in AXES { for (b, cb) in AXES { - let key = ppvm_pauli_sum_2::PauliWord::from(format!("{ca}{cb}").as_str()); + let key = PauliWord::from(format!("{ca}{cb}").as_str()); let coeff = sum.get(&key).unwrap_or_default(); let term = pauli(a, b); for i in 0..4 { @@ -121,33 +121,27 @@ fn lost_sites_reduce_to_surviving_rotation() { } #[test] -fn composite_interfaces_match_dense_unitaries() { +fn u3_matches_dense_unitary() { let mut sum = observable(); sum.u3(1, 0.37, -0.51, 0.82); - check_conjugation( - &sum, - multiply( - multiply( - rotation(Pauli::I, Pauli::Z, -0.51), - rotation(Pauli::I, Pauli::Y, 0.37), - ), - rotation(Pauli::I, Pauli::Z, 0.82), - ), - ); + let phi = rotation(Pauli::I, Pauli::Z, -0.51); + let theta = rotation(Pauli::I, Pauli::Y, 0.37); + let lambda = rotation(Pauli::I, Pauli::Z, 0.82); + check_conjugation(&sum, multiply(multiply(phi, theta), lambda)); +} +#[test] +fn xy_rotation_matches_dense_unitary() { let mut sum = observable(); sum.r(1, 0.51, 0.37); - check_conjugation( - &sum, - multiply( - multiply( - rotation(Pauli::I, Pauli::Z, 0.51), - rotation(Pauli::I, Pauli::X, 0.37), - ), - rotation(Pauli::I, Pauli::Z, -0.51), - ), - ); + let forward = rotation(Pauli::I, Pauli::Z, 0.51); + let x = rotation(Pauli::I, Pauli::X, 0.37); + let backward = rotation(Pauli::I, Pauli::Z, -0.51); + check_conjugation(&sum, multiply(multiply(forward, x), backward)); +} +#[test] +fn t_matches_dense_unitary_and_t_dag_inverts_it() { let mut sum = observable(); sum.t(1); check_conjugation( @@ -156,24 +150,25 @@ fn composite_interfaces_match_dense_unitaries() { ); sum.t_dag(1); assert_abs_diff_eq!(sum, observable(), epsilon = 1e-12); +} +#[test] +fn crx_matches_dense_unitary() { for theta in [0.0, 0.37, -0.81] { let mut sum = observable(); sum.crx(0, 1, theta); - // Build a controlled Rx directly: identity in the control=0 block. + // Identity for control=0, Rx for control=1. let rx = rotation(Pauli::I, Pauli::X, theta); let mut unitary = pauli(Pauli::I, Pauli::I); for i in 2..4 { - for j in 2..4 { - unitary[i][j] = rx[i][j]; - } + unitary[i][2..4].copy_from_slice(&rx[i][2..4]); } check_conjugation(&sum, unitary); } } #[test] -fn batches_match_ordered_scalar_calls() { +fn single_batches_match_ordered_scalar_calls() { type Single = fn(&mut PauliSum, usize, f64); type Singles = fn(&mut PauliSum, &[usize], f64); let singles: [(Single, Singles); 3] = [ @@ -190,6 +185,10 @@ fn batches_match_ordered_scalar_calls() { } assert_abs_diff_eq!(sum, expected, epsilon = 1e-12); } +} + +#[test] +fn pair_batches_match_ordered_scalar_calls() { type Pair = fn(&mut PauliSum, usize, usize, f64); type Pairs = fn(&mut PauliSum, &[(usize, usize)], f64); let pairs: [(Pair, Pairs); 9] = [ @@ -211,6 +210,10 @@ fn batches_match_ordered_scalar_calls() { scalar(&mut expected, 1, 0, 0.37); assert_abs_diff_eq!(sum, expected, epsilon = 1e-12); } +} + +#[test] +fn t_batches_invert_each_other() { let mut sum = observable(); sum.t_many(&[0, 1]); sum.t_dag_many(&[0, 1]); @@ -237,10 +240,13 @@ fn two_qubit_zero_branches_remain_until_reduced() { sum += ("ZI", 2.0); sum.rxx(0, 1, 0.0); assert_eq!(sum.len(), 2); - assert_eq!(sum.get(&ppvm_pauli_sum_2::PauliWord::from("YX")), Some(0.0)); + assert_eq!(sum.get(&PauliWord::from("YX")), Some(0.0)); sum.reduce(); assert_eq!(sum.len(), 1); +} +#[test] +fn crx_accepts_complex_angles() { let mut sum = observable(); sum.crx(0, 1, C::new(0.37, 0.0)); let mut expected = observable(); @@ -279,18 +285,19 @@ fn specialized_pairs_match_generic_with_loss_and_complex_coefficients() { (Pauli::Y, LossyPauliSum::ryy), (Pauli::Z, LossyPauliSum::rzz), ]; + let mut original = LossyPauliSum::::new(2); + for (i, x) in "IXYZL".chars().enumerate() { + for (j, y) in "IXYZL".chars().enumerate() { + original += ( + format!("{x}{y}").as_str(), + C::new(i as f64 - 2.0, j as f64 - 1.0), + ); + } + } for (axis, gate) in gates { for theta in [0.0, 0.37, -0.81] { for (a, b) in [(0, 1), (1, 0)] { - let mut sum = LossyPauliSum::::new(2); - for (i, x) in "IXYZL".chars().enumerate() { - for (j, y) in "IXYZL".chars().enumerate() { - sum += ( - format!("{x}{y}").as_str(), - C::new(i as f64 - 2.0, j as f64 - 1.0), - ); - } - } + let mut sum = original.clone(); let mut expected = sum.clone(); expected.rotate_2(axis, axis, a, b, theta); gate(&mut sum, a, b, theta);