use num_complex::Complex64;
use crate::gates;
pub type Kraus = [[Complex64; 2]; 2];
fn scaled(g: Kraus, s: f64) -> Kraus {
let f = Complex64::new(s, 0.0);
[[f * g[0][0], f * g[0][1]], [f * g[1][0], f * g[1][1]]]
}
pub fn is_trace_preserving(ops: &[Kraus]) -> bool {
let mut sum = [[Complex64::new(0.0, 0.0); 2]; 2];
for k in ops {
for i in 0..2 {
for j in 0..2 {
sum[i][j] += k[0][i].conj() * k[0][j] + k[1][i].conj() * k[1][j];
}
}
}
let identity = [
[Complex64::new(1.0, 0.0), Complex64::new(0.0, 0.0)],
[Complex64::new(0.0, 0.0), Complex64::new(1.0, 0.0)],
];
(0..2).all(|i| (0..2).all(|j| (sum[i][j] - identity[i][j]).norm() < 1e-12))
}
pub fn bit_flip(p: f64) -> Vec<Kraus> {
flip_channel(p, gates::x())
}
pub fn phase_flip(p: f64) -> Vec<Kraus> {
flip_channel(p, gates::z())
}
fn flip_channel(p: f64, g: Kraus) -> Vec<Kraus> {
let p = p.clamp(0.0, 1.0);
vec![scaled(gates::id(), (1.0 - p).sqrt()), scaled(g, p.sqrt())]
}
pub fn depolarizing(p: f64) -> Vec<Kraus> {
let p = p.clamp(0.0, 1.0);
let each = (p / 3.0).sqrt();
vec![
scaled(gates::id(), (1.0 - p).sqrt()),
scaled(gates::x(), each),
scaled(gates::y(), each),
scaled(gates::z(), each),
]
}
pub fn amplitude_damping(gamma: f64) -> Vec<Kraus> {
let gamma = gamma.clamp(0.0, 1.0);
let c = |re: f64| Complex64::new(re, 0.0);
vec![
[[c(1.0), c(0.0)], [c(0.0), c((1.0 - gamma).sqrt())]],
[[c(0.0), c(gamma.sqrt())], [c(0.0), c(0.0)]],
]
}
pub fn phase_damping(gamma: f64) -> Vec<Kraus> {
let gamma = gamma.clamp(0.0, 1.0);
let c = |re: f64| Complex64::new(re, 0.0);
vec![
[[c(1.0), c(0.0)], [c(0.0), c((1.0 - gamma).sqrt())]],
[[c(0.0), c(0.0)], [c(0.0), c(gamma.sqrt())]],
]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn channels_are_trace_preserving() {
for p in [0.0, 0.05, 0.3, 0.5, 0.87, 1.0] {
for ops in [
bit_flip(p),
phase_flip(p),
depolarizing(p),
amplitude_damping(p),
phase_damping(p),
] {
assert!(is_trace_preserving(&ops), "not trace preserving at p={p}");
}
}
}
#[test]
fn zero_strength_is_the_identity_branch() {
for ops in [
bit_flip(0.0),
phase_flip(0.0),
depolarizing(0.0),
amplitude_damping(0.0),
phase_damping(0.0),
] {
let id = gates::id();
for i in 0..2 {
for j in 0..2 {
assert!((ops[0][i][j] - id[i][j]).norm() < 1e-12);
}
}
}
}
#[test]
fn strength_is_clamped() {
for ops in [depolarizing(-0.5), amplitude_damping(2.0), bit_flip(1.5)] {
assert!(is_trace_preserving(&ops));
assert!(ops.iter().all(|k| k
.iter()
.flatten()
.all(|e| e.re.is_finite() && e.im.is_finite())));
}
}
#[test]
fn detects_a_non_physical_channel() {
let mut ops = depolarizing(0.3);
ops[1] = scaled(ops[1], 2.0);
assert!(!is_trace_preserving(&ops));
}
}