use num_complex::Complex;
use tpt_math_linalg::tpt_math_linalg_dense::{DMatrix, DVector};
use crate::{State, StateError};
#[inline]
fn block(z: Complex<f64>) -> [f64; 4] {
[z.re, -z.im, z.im, z.re]
}
pub fn kron(a: &DMatrix<f64>, b: &DMatrix<f64>) -> DMatrix<f64> {
let (p, q) = (a.nrows(), a.ncols());
let (r, s) = (b.nrows(), b.ncols());
DMatrix::from_fn(p * r, q * s, |i, j| {
let ai = i / r;
let aj = j / s;
let bi = i % r;
let bj = j % s;
a[(ai, aj)] * b[(bi, bj)]
})
}
pub fn embed_gate_2x2(gate: &[Complex<f64>; 4]) -> DMatrix<f64> {
DMatrix::from_fn(4, 4, |i, j| {
let qr = i / 2;
let qc = j / 2;
let sr = i % 2;
let sc = j % 2;
let z = gate[qr * 2 + qc];
block(z)[sr * 2 + sc]
})
}
pub fn embed_gate_4x4(gate: &[Complex<f64>; 16]) -> DMatrix<f64> {
DMatrix::from_fn(8, 8, |i, j| {
let qr = i / 2;
let qc = j / 2;
let sr = i % 2;
let sc = j % 2;
let z = gate[qr * 4 + qc];
block(z)[sr * 2 + sc]
})
}
fn identity_2x2() -> DMatrix<f64> {
DMatrix::from_fn(2, 2, |i, j| if i == j { 1.0 } else { 0.0 })
}
pub(crate) fn embed_complex_square(entries: &[Complex<f64>], d: usize) -> DMatrix<f64> {
debug_assert_eq!(entries.len(), d * d);
DMatrix::from_fn(2 * d, 2 * d, |i, j| {
let qr = i / 2;
let qc = j / 2;
let sr = i % 2;
let sc = j % 2;
let z = entries[qr * d + qc];
block(z)[sr * 2 + sc]
})
}
pub(crate) fn unembed_entry(real: &DMatrix<f64>, i: usize, j: usize) -> Complex<f64> {
Complex::new(real[(2 * i, 2 * j)], real[(2 * i + 1, 2 * j)])
}
fn controlled_2q_matrix(
control: usize,
target: usize,
gate: &[Complex<f64>; 4],
) -> [Complex<f64>; 16] {
let lo = control.min(target);
let mut m = [Complex::new(0.0, 0.0); 16];
for idx_in in 0..4usize {
let b_lo = idx_in & 1;
let b_hi = (idx_in >> 1) & 1;
let control_bit = if control == lo { b_lo } else { b_hi };
if control_bit == 0 {
m[idx_in * 4 + idx_in] = Complex::new(1.0, 0.0);
} else {
let target_in = if target == lo { b_lo } else { b_hi };
for out_t in 0..2usize {
let amp = gate[target_in * 2 + out_t];
if amp.norm_sqr() < 1e-30 {
continue;
}
let mut idx_out = 0usize;
if control == lo {
idx_out |= control_bit;
} else {
idx_out |= control_bit << 1;
}
if target == lo {
idx_out |= out_t;
} else {
idx_out |= out_t << 1;
}
m[idx_out * 4 + idx_in] = amp;
}
}
}
m
}
fn swap_matrix() -> [Complex<f64>; 16] {
let mut m = [Complex::new(0.0, 0.0); 16];
m[0] = Complex::new(1.0, 0.0);
m[6] = Complex::new(1.0, 0.0);
m[9] = Complex::new(1.0, 0.0);
m[15] = Complex::new(1.0, 0.0);
m
}
#[derive(Clone)]
enum Elem {
Single {
qubit: usize,
gate: [Complex<f64>; 4],
},
Pair {
lo: usize,
hi: usize,
matrix: [Complex<f64>; 16],
},
}
#[derive(Clone, Default)]
pub struct Circuit {
n: usize,
elems: Vec<Elem>,
}
impl Circuit {
#[must_use]
pub fn new(n: usize) -> Self {
Circuit {
n,
elems: Vec::new(),
}
}
#[must_use]
pub fn n_qubits(&self) -> usize {
self.n
}
pub fn gate(&mut self, qubit: usize, gate: [Complex<f64>; 4]) -> &mut Self {
self.elems.push(Elem::Single { qubit, gate });
self
}
pub fn h(&mut self, qubit: usize) -> &mut Self {
self.gate(qubit, crate::H)
}
pub fn x(&mut self, qubit: usize) -> &mut Self {
self.gate(qubit, crate::X)
}
pub fn y(&mut self, qubit: usize) -> &mut Self {
self.gate(qubit, crate::Y)
}
pub fn z(&mut self, qubit: usize) -> &mut Self {
self.gate(qubit, crate::Z)
}
pub fn s(&mut self, qubit: usize) -> &mut Self {
self.gate(qubit, crate::S)
}
pub fn t(&mut self, qubit: usize) -> &mut Self {
self.gate(qubit, crate::T)
}
pub fn cnot(&mut self, control: usize, target: usize) -> &mut Self {
self.controlled(control, target, crate::X)
}
pub fn controlled(
&mut self,
control: usize,
target: usize,
gate: [Complex<f64>; 4],
) -> &mut Self {
if control == target {
return self;
}
let c = control;
let t = target;
let lo = c.min(t);
let hi = c.max(t);
let mut ops: Vec<Elem> = Vec::new();
for k in ((lo + 1)..hi).rev() {
ops.push(Elem::Pair {
lo: k,
hi: k + 1,
matrix: swap_matrix(),
});
}
ops.push(Elem::Pair {
lo,
hi: lo + 1,
matrix: controlled_2q_matrix(lo, lo + 1, &gate),
});
for k in (lo + 1)..hi {
ops.push(Elem::Pair {
lo: k,
hi: k + 1,
matrix: swap_matrix(),
});
}
self.elems.extend(ops);
self
}
#[must_use]
pub fn unitary(&self) -> DMatrix<f64> {
let n = self.n;
let expected = (1usize << n) * 2;
let mut acc = DMatrix::from_fn(expected, expected, |i, j| if i == j { 1.0 } else { 0.0 });
for e in &self.elems {
let m = match e {
Elem::Single { qubit, gate } => expand_single(n, *qubit, gate),
Elem::Pair { lo, hi, matrix } => expand_pair(n, *lo, *hi, matrix),
};
acc = m * acc;
}
acc
}
}
pub(crate) fn expand_single(n: usize, qubit: usize, gate: &[Complex<f64>; 4]) -> DMatrix<f64> {
let block = embed_gate_2x2(gate);
let mut u: Option<DMatrix<f64>> = None;
for q in 0..n {
let f = if q == qubit {
block.clone()
} else {
identity_2x2()
};
u = Some(match u {
None => f,
Some(prev) => kron(&f, &prev),
});
}
u.expect("n >= 1")
}
fn expand_pair(n: usize, lo: usize, hi: usize, matrix: &[Complex<f64>; 16]) -> DMatrix<f64> {
debug_assert_eq!(hi, lo + 1);
let block = embed_gate_4x4(matrix);
let mut u: Option<DMatrix<f64>> = None;
for q in 0..n {
if q == hi {
continue;
}
let f = if q == lo {
block.clone()
} else {
identity_2x2()
};
u = Some(match u {
None => f,
Some(prev) => kron(&f, &prev),
});
}
u.expect("n >= 2")
}
impl State {
pub fn apply_unitary(&self, u: &DMatrix<f64>) -> Result<State, StateError> {
let n = self.n_qubits();
let d = 1usize << n;
let expected = d * 2;
if u.nrows() != expected || u.ncols() != expected {
return Err(StateError::UnitarySizeMismatch {
expected,
got: u.nrows(),
});
}
let w = DVector::from_fn(expected, |k| {
let i = k / 2;
let part = k % 2;
let z = self.amps[i];
if part == 0 { z.re } else { z.im }
});
let out = u.clone() * w;
let mut amps = vec![Complex::new(0.0, 0.0); d];
for i in 0..d {
amps[i] = Complex::new(out[2 * i], out[2 * i + 1]);
}
Ok(State { amps })
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{H, X};
use approx::assert_abs_diff_eq;
const TOL: f64 = 1e-9;
#[test]
fn kron_identity_replicates_factor() {
let a = embed_gate_2x2(&H);
let i2 = DMatrix::from_fn(2, 2, |p, q| if p == q { 1.0 } else { 0.0 });
let k = kron(&a, &i2);
assert_eq!(k.nrows(), 8);
assert_eq!(k.ncols(), 8);
}
#[test]
fn single_h_matches_state_vector() {
let mut s = State::new(1).unwrap();
s.h(0).unwrap();
let expected = s.amplitudes().to_vec();
let mut c = Circuit::new(1);
c.h(0);
let u = c.unitary();
let s2 = State::new(1).unwrap().apply_unitary(&u).unwrap();
for (a, b) in expected.iter().zip(s2.amplitudes()) {
assert_abs_diff_eq!(a.re, b.re, epsilon = TOL);
assert_abs_diff_eq!(a.im, b.im, epsilon = TOL);
}
}
#[test]
fn bell_state_matches_unitary_path() {
let mut s = State::new(2).unwrap();
s.h(0).unwrap();
s.cnot(0, 1).unwrap();
let expected = s.amplitudes().to_vec();
let mut c = Circuit::new(2);
c.h(0).cnot(0, 1);
let u = c.unitary();
let s2 = State::new(2).unwrap().apply_unitary(&u).unwrap();
for (a, b) in expected.iter().zip(s2.amplitudes()) {
assert_abs_diff_eq!(a.re, b.re, epsilon = TOL);
assert_abs_diff_eq!(a.im, b.im, epsilon = TOL);
}
}
#[test]
fn ghz_with_nonadjacent_cnot() {
let mut s = State::new(3).unwrap();
s.h(0).unwrap();
s.cnot(0, 1).unwrap();
s.cnot(0, 2).unwrap();
let expected = s.amplitudes().to_vec();
let mut c = Circuit::new(3);
c.h(0).cnot(0, 1).cnot(0, 2);
let u = c.unitary();
let s2 = State::new(3).unwrap().apply_unitary(&u).unwrap();
for (a, b) in expected.iter().zip(s2.amplitudes()) {
assert_abs_diff_eq!(a.re, b.re, epsilon = TOL);
assert_abs_diff_eq!(a.im, b.im, epsilon = TOL);
}
let inv = std::f64::consts::FRAC_1_SQRT_2;
assert_abs_diff_eq!(s2.amplitude(0).re, inv, epsilon = TOL);
assert_abs_diff_eq!(s2.amplitude(7).re, inv, epsilon = TOL);
}
#[test]
fn controlled_gate_matches_analytic() {
let mut c = Circuit::new(2);
c.controlled(0, 1, X);
let u = c.unitary();
let s2 = State::new(2).unwrap().apply_unitary(&u).unwrap();
assert_abs_diff_eq!(s2.amplitude(0).re, 1.0, epsilon = TOL);
assert_abs_diff_eq!(s2.amplitude(3).norm(), 0.0, epsilon = TOL);
let mut c2 = Circuit::new(2);
c2.x(0).controlled(0, 1, X);
let s3 = State::new(2).unwrap().apply_unitary(&c2.unitary()).unwrap();
assert_abs_diff_eq!(s3.amplitude(3).re, 1.0, epsilon = TOL);
}
#[test]
fn unitary_size_mismatch_is_rejected() {
let wrong = DMatrix::from_fn(4, 4, |i, j| if i == j { 1.0 } else { 0.0 });
let s = State::new(2).unwrap();
assert_eq!(
s.apply_unitary(&wrong),
Err(StateError::UnitarySizeMismatch {
expected: 8,
got: 4
})
);
}
}