use num_complex::Complex64;
use crate::gates;
pub const MAX_DENSITY_QUBITS: usize = 12;
#[derive(Debug, Clone, PartialEq)]
pub struct DensityMatrix {
n_qubits: usize,
dim: usize,
entries: Vec<Complex64>,
}
impl DensityMatrix {
pub fn new(n_qubits: usize) -> Self {
assert!(
n_qubits <= MAX_DENSITY_QUBITS,
"a density matrix is 4^n entries; {n_qubits} qubits exceeds the \
maximum of {MAX_DENSITY_QUBITS}"
);
let dim = 1usize << n_qubits;
let mut entries = vec![Complex64::new(0.0, 0.0); dim * dim];
entries[0] = Complex64::new(1.0, 0.0);
DensityMatrix {
n_qubits,
dim,
entries,
}
}
pub(crate) fn zeros(n_qubits: usize) -> Self {
let mut rho = DensityMatrix::new(n_qubits);
rho.entries[0] = Complex64::new(0.0, 0.0);
rho
}
pub fn from_state(state: &crate::State) -> Self {
let n_qubits = state.n_qubits();
let mut rho = DensityMatrix::new(n_qubits);
let amps = state.amplitudes();
for (i, a) in amps.iter().enumerate() {
for (j, b) in amps.iter().enumerate() {
rho.entries[i * rho.dim + j] = a * b.conj();
}
}
rho
}
pub fn n_qubits(&self) -> usize {
self.n_qubits
}
pub fn entries(&self) -> &[Complex64] {
&self.entries
}
pub fn entry(&self, row: usize, col: usize) -> Complex64 {
self.entries[row * self.dim + col]
}
pub fn probability(&self, index: usize) -> f64 {
self.entry(index, index).re
}
pub fn trace(&self) -> f64 {
(0..self.dim).map(|i| self.probability(i)).sum()
}
pub fn purity(&self) -> f64 {
self.entries.iter().map(|e| e.norm_sqr()).sum()
}
pub fn prob_qubit_one(&self, q: usize) -> f64 {
assert!(q < self.n_qubits, "qubit out of range");
let mask = 1usize << q;
(0..self.dim)
.filter(|i| i & mask != 0)
.map(|i| self.probability(i))
.sum()
}
pub fn apply_1q(&mut self, gate: &[[Complex64; 2]; 2], target: usize) {
assert!(target < self.n_qubits, "target qubit out of range");
self.apply_masked(gate, 0, target);
}
pub fn apply_controlled_1q(
&mut self,
gate: &[[Complex64; 2]; 2],
control: usize,
target: usize,
) {
assert_ne!(control, target, "control and target must differ");
self.apply_multi_controlled_1q(gate, &[control], target);
}
pub fn apply_multi_controlled_1q(
&mut self,
gate: &[[Complex64; 2]; 2],
controls: &[usize],
target: usize,
) {
assert!(target < self.n_qubits, "target qubit out of range");
let mut cmask = 0usize;
for &c in controls {
assert!(c < self.n_qubits, "control qubit out of range");
assert_ne!(c, target, "control and target must differ");
cmask |= 1usize << c;
}
self.apply_masked(gate, cmask, target);
}
fn apply_masked(&mut self, gate: &[[Complex64; 2]; 2], cmask: usize, target: usize) {
let mask = 1usize << target;
let dim = self.dim;
for row in 0..dim {
if row & mask != 0 || (row & cmask) != cmask {
continue;
}
for col in 0..dim {
let (a, b) = (
self.entries[row * dim + col],
self.entries[(row | mask) * dim + col],
);
self.entries[row * dim + col] = gate[0][0] * a + gate[0][1] * b;
self.entries[(row | mask) * dim + col] = gate[1][0] * a + gate[1][1] * b;
}
}
for row in 0..dim {
for col in 0..dim {
if col & mask != 0 || (col & cmask) != cmask {
continue;
}
let (a, b) = (
self.entries[row * dim + col],
self.entries[row * dim + (col | mask)],
);
self.entries[row * dim + col] = gate[0][0].conj() * a + gate[0][1].conj() * b;
self.entries[row * dim + (col | mask)] =
gate[1][0].conj() * a + gate[1][1].conj() * b;
}
}
}
pub fn swap_qubits(&mut self, a: usize, b: usize) {
if a == b {
return;
}
self.apply_controlled_1q(&gates::x(), a, b);
self.apply_controlled_1q(&gates::x(), b, a);
self.apply_controlled_1q(&gates::x(), a, b);
}
pub fn apply_kraus(&mut self, ops: &[[[Complex64; 2]; 2]], target: usize) {
assert!(target < self.n_qubits, "target qubit out of range");
assert!(
!ops.is_empty(),
"a channel needs at least one Kraus operator"
);
let mut total = vec![Complex64::new(0.0, 0.0); self.entries.len()];
let mut scratch = self.clone();
for k in ops {
scratch.entries.copy_from_slice(&self.entries);
scratch.apply_masked(k, 0, target);
for (acc, term) in total.iter_mut().zip(scratch.entries.iter()) {
*acc += term;
}
}
self.entries = total;
}
pub fn project(&mut self, q: usize, outcome: bool) {
assert!(q < self.n_qubits, "qubit out of range");
let mask = 1usize << q;
let want = if outcome { mask } else { 0 };
let dim = self.dim;
for row in 0..dim {
for col in 0..dim {
if (row & mask) != want || (col & mask) != want {
self.entries[row * dim + col] = Complex64::new(0.0, 0.0);
}
}
}
}
pub fn add_assign(&mut self, other: &DensityMatrix) {
assert_eq!(self.n_qubits, other.n_qubits, "registers must match");
for (a, b) in self.entries.iter_mut().zip(other.entries.iter()) {
*a += b;
}
}
pub fn measure_dephase(&mut self, q: usize) {
assert!(q < self.n_qubits, "qubit out of range");
let mask = 1usize << q;
let dim = self.dim;
for row in 0..dim {
for col in 0..dim {
if (row & mask) != (col & mask) {
self.entries[row * dim + col] = Complex64::new(0.0, 0.0);
}
}
}
}
pub fn reset(&mut self, q: usize) {
assert!(q < self.n_qubits, "qubit out of range");
let c = |re: f64| Complex64::new(re, 0.0);
let k0 = [[c(1.0), c(0.0)], [c(0.0), c(0.0)]];
let k1 = [[c(0.0), c(1.0)], [c(0.0), c(0.0)]];
self.apply_kraus(&[k0, k1], q);
}
}