1use num_complex::Complex;
63use tpt_math_linalg::tpt_math_linalg_dense::DMatrix;
64
65use crate::tensor::{self, Circuit};
66use crate::{State, StateError};
67
68const IDENTITY: [Complex<f64>; 4] = [
71 Complex::new(1.0, 0.0),
72 Complex::new(0.0, 0.0),
73 Complex::new(0.0, 0.0),
74 Complex::new(1.0, 0.0),
75];
76
77#[derive(Clone, Debug, PartialEq)]
84pub struct Matrix {
85 dim: usize,
86 data: Vec<Complex<f64>>,
87}
88
89impl Matrix {
90 pub fn from_row_major(dim: usize, data: Vec<Complex<f64>>) -> Result<Self, StateError> {
96 if data.len() != dim * dim {
97 return Err(StateError::MatrixSizeMismatch {
98 expected: dim * dim,
99 got: data.len(),
100 });
101 }
102 Ok(Matrix { dim, data })
103 }
104
105 #[must_use]
107 pub fn dim(&self) -> usize {
108 self.dim
109 }
110
111 #[must_use]
117 pub fn get(&self, row: usize, col: usize) -> Complex<f64> {
118 self.data[row * self.dim + col]
119 }
120
121 #[must_use]
123 pub fn data(&self) -> &[Complex<f64>] {
124 &self.data
125 }
126}
127
128fn embed_single_qubit_kraus(
134 n: usize,
135 qubit: usize,
136 gate: &[Complex<f64>; 4],
137 coeff: f64,
138) -> Matrix {
139 let scaled = [
140 gate[0].scale(coeff),
141 gate[1].scale(coeff),
142 gate[2].scale(coeff),
143 gate[3].scale(coeff),
144 ];
145 let real = tensor::expand_single(n, qubit, &scaled);
146 let d = 1usize << n;
147 let mut data = vec![Complex::new(0.0, 0.0); d * d];
148 for (i, row) in data.chunks_mut(d).enumerate() {
149 for (j, entry) in row.iter_mut().enumerate() {
150 *entry = tensor::unembed_entry(&real, i, j);
151 }
152 }
153 Matrix { dim: d, data }
154}
155
156#[derive(Clone, Debug, PartialEq)]
161pub struct DensityMatrix {
162 n: usize,
163 real: DMatrix<f64>,
166}
167
168impl DensityMatrix {
169 #[must_use]
171 pub fn n_qubits(&self) -> usize {
172 self.n
173 }
174
175 #[must_use]
177 pub fn dim(&self) -> usize {
178 1usize << self.n
179 }
180
181 #[must_use]
194 pub fn from_pure_state(state: &State) -> Self {
195 let n = state.n_qubits();
196 let d = 1usize << n;
197 let amps = state.amplitudes();
198 let mut entries = vec![Complex::new(0.0, 0.0); d * d];
199 for i in 0..d {
200 for j in 0..d {
201 entries[i * d + j] = amps[i] * amps[j].conj();
202 }
203 }
204 let real = tensor::embed_complex_square(&entries, d);
205 DensityMatrix { n, real }
206 }
207
208 pub fn from_mixture(states: &[State], probs: &[f64]) -> Result<Self, StateError> {
220 if states.is_empty() {
221 return Err(StateError::EmptyMixture);
222 }
223 if states.len() != probs.len() {
224 return Err(StateError::MixtureSizeMismatch {
225 states: states.len(),
226 probs: probs.len(),
227 });
228 }
229 if probs.iter().any(|&p| p < 0.0) {
230 return Err(StateError::NegativeProbability);
231 }
232 let sum: f64 = probs.iter().sum();
233 if (sum - 1.0).abs() > 1e-6 {
234 return Err(StateError::ProbabilitiesNotNormalized(sum));
235 }
236 let n = states[0].n_qubits();
237 for s in states {
238 if s.n_qubits() != n {
239 return Err(StateError::QubitCountMismatch {
240 expected: n,
241 got: s.n_qubits(),
242 });
243 }
244 }
245 let size = (1usize << n) * 2;
246 let mut real = DMatrix::from_fn(size, size, |_, _| 0.0);
247 for (s, &p) in states.iter().zip(probs) {
248 let component = Self::from_pure_state(s).real * p;
249 real = real + component;
250 }
251 Ok(DensityMatrix { n, real })
252 }
253
254 #[must_use]
260 pub fn entry(&self, i: usize, j: usize) -> Complex<f64> {
261 tensor::unembed_entry(&self.real, i, j)
262 }
263
264 #[must_use]
270 pub fn trace(&self) -> Complex<f64> {
271 let d = self.dim();
272 (0..d).map(|i| self.entry(i, i)).sum()
273 }
274
275 #[must_use]
279 pub fn probabilities(&self) -> Vec<f64> {
280 let d = self.dim();
281 (0..d).map(|i| self.entry(i, i).re).collect()
282 }
283
284 #[must_use]
287 pub fn expectation_z(&self) -> f64 {
288 let d = self.dim();
289 (0..d)
290 .map(|i| {
291 let sign = if i.count_ones() & 1 == 0 { 1.0 } else { -1.0 };
292 sign * self.entry(i, i).re
293 })
294 .sum()
295 }
296
297 fn conjugate_by(&mut self, u: &DMatrix<f64>) {
300 let ut = u.transpose();
301 self.real = u.clone() * self.real.clone() * ut;
302 }
303
304 pub fn apply_gate(&mut self, gate: &[Complex<f64>; 4], qubit: usize) -> Result<(), StateError> {
311 let n = self.n;
312 if qubit >= n {
313 return Err(StateError::InvalidQubit { qubit, n });
314 }
315 let mut c = Circuit::new(n);
316 c.gate(qubit, *gate);
317 self.conjugate_by(&c.unitary());
318 Ok(())
319 }
320
321 pub fn apply_cnot(&mut self, control: usize, target: usize) -> Result<(), StateError> {
328 let n = self.n;
329 if control >= n {
330 return Err(StateError::InvalidQubit { qubit: control, n });
331 }
332 if target >= n {
333 return Err(StateError::InvalidQubit { qubit: target, n });
334 }
335 if control == target {
336 return Err(StateError::SameQubits(control));
337 }
338 let mut c = Circuit::new(n);
339 c.cnot(control, target);
340 self.conjugate_by(&c.unitary());
341 Ok(())
342 }
343
344 pub fn h(&mut self, qubit: usize) -> Result<(), StateError> {
350 self.apply_gate(&crate::H, qubit)
351 }
352
353 pub fn x(&mut self, qubit: usize) -> Result<(), StateError> {
359 self.apply_gate(&crate::X, qubit)
360 }
361
362 pub fn y(&mut self, qubit: usize) -> Result<(), StateError> {
368 self.apply_gate(&crate::Y, qubit)
369 }
370
371 pub fn z(&mut self, qubit: usize) -> Result<(), StateError> {
377 self.apply_gate(&crate::Z, qubit)
378 }
379
380 pub fn apply_kraus(&mut self, kraus_ops: &[Matrix]) -> Result<(), StateError> {
395 let d = self.dim();
396 for k in kraus_ops {
397 if k.dim() != d {
398 return Err(StateError::MatrixSizeMismatch {
399 expected: d,
400 got: k.dim(),
401 });
402 }
403 }
404 let size = self.real.nrows();
405 let mut acc = DMatrix::from_fn(size, size, |_, _| 0.0);
406 for k in kraus_ops {
407 let k_real = tensor::embed_complex_square(k.data(), d);
408 let kt = k_real.transpose();
409 let term = k_real * self.real.clone() * kt;
410 acc = acc + term;
411 }
412 self.real = acc;
413 Ok(())
414 }
415
416 pub fn bit_flip_kraus(n: usize, qubit: usize, p: f64) -> Result<Vec<Matrix>, StateError> {
428 if qubit >= n {
429 return Err(StateError::InvalidQubit { qubit, n });
430 }
431 if !(0.0..=1.0).contains(&p) {
432 return Err(StateError::InvalidProbability(p));
433 }
434 let k0 = embed_single_qubit_kraus(n, qubit, &IDENTITY, (1.0 - p).sqrt());
435 let k1 = embed_single_qubit_kraus(n, qubit, &crate::X, p.sqrt());
436 Ok(vec![k0, k1])
437 }
438
439 pub fn depolarizing_kraus(n: usize, qubit: usize, p: f64) -> Result<Vec<Matrix>, StateError> {
454 if qubit >= n {
455 return Err(StateError::InvalidQubit { qubit, n });
456 }
457 if !(0.0..=1.0).contains(&p) {
458 return Err(StateError::InvalidProbability(p));
459 }
460 let c0 = (1.0 - 0.75 * p).sqrt();
461 let c = (p / 4.0).sqrt();
462 let k0 = embed_single_qubit_kraus(n, qubit, &IDENTITY, c0);
463 let k1 = embed_single_qubit_kraus(n, qubit, &crate::X, c);
464 let k2 = embed_single_qubit_kraus(n, qubit, &crate::Y, c);
465 let k3 = embed_single_qubit_kraus(n, qubit, &crate::Z, c);
466 Ok(vec![k0, k1, k2, k3])
467 }
468}
469
470#[cfg(test)]
471mod tests {
472 use super::*;
473 use approx::assert_abs_diff_eq;
474
475 const TOL: f64 = 1e-9;
476
477 #[test]
478 fn from_pure_state_matches_outer_product() {
479 let mut s = State::new(2).unwrap();
480 s.h(0).unwrap();
481 s.cnot(0, 1).unwrap();
482 let amps = s.amplitudes().to_vec();
483
484 let rho = DensityMatrix::from_pure_state(&s);
485 for i in 0..4 {
486 for j in 0..4 {
487 let expected = amps[i] * amps[j].conj();
488 let got = rho.entry(i, j);
489 assert_abs_diff_eq!(got.re, expected.re, epsilon = TOL);
490 assert_abs_diff_eq!(got.im, expected.im, epsilon = TOL);
491 }
492 }
493 assert_abs_diff_eq!(rho.trace().re, 1.0, epsilon = TOL);
494 assert_abs_diff_eq!(rho.trace().im, 0.0, epsilon = TOL);
495 }
496
497 #[test]
498 fn trace_stays_one_after_gate_application() {
499 let s = State::new(2).unwrap();
500 let mut rho = DensityMatrix::from_pure_state(&s);
501 rho.h(0).unwrap();
502 rho.apply_cnot(0, 1).unwrap();
503 assert_abs_diff_eq!(rho.trace().re, 1.0, epsilon = TOL);
504 assert_abs_diff_eq!(rho.trace().im, 0.0, epsilon = TOL);
505 }
506
507 #[test]
508 fn trace_stays_one_after_kraus_application() {
509 let mut s = State::new(2).unwrap();
510 s.h(0).unwrap();
511 s.cnot(0, 1).unwrap();
512 let mut rho = DensityMatrix::from_pure_state(&s);
513
514 let bit_flip = DensityMatrix::bit_flip_kraus(2, 0, 0.3).unwrap();
515 rho.apply_kraus(&bit_flip).unwrap();
516 assert_abs_diff_eq!(rho.trace().re, 1.0, epsilon = TOL);
517
518 let depolarizing = DensityMatrix::depolarizing_kraus(2, 1, 0.4).unwrap();
519 rho.apply_kraus(&depolarizing).unwrap();
520 assert_abs_diff_eq!(rho.trace().re, 1.0, epsilon = TOL);
521 }
522
523 #[test]
524 fn depolarizing_p0_is_identity() {
525 let mut s = State::new(1).unwrap();
526 s.h(0).unwrap();
527 let rho_before = DensityMatrix::from_pure_state(&s);
528 let mut rho = rho_before.clone();
529
530 let kraus = DensityMatrix::depolarizing_kraus(1, 0, 0.0).unwrap();
531 rho.apply_kraus(&kraus).unwrap();
532
533 for i in 0..2 {
534 for j in 0..2 {
535 let a = rho.entry(i, j);
536 let b = rho_before.entry(i, j);
537 assert_abs_diff_eq!(a.re, b.re, epsilon = TOL);
538 assert_abs_diff_eq!(a.im, b.im, epsilon = TOL);
539 }
540 }
541 }
542
543 #[test]
544 fn depolarizing_p1_is_maximally_mixed() {
545 let mut s = State::new(1).unwrap();
548 s.h(0).unwrap();
549 let mut rho = DensityMatrix::from_pure_state(&s);
550
551 let kraus = DensityMatrix::depolarizing_kraus(1, 0, 1.0).unwrap();
552 rho.apply_kraus(&kraus).unwrap();
553
554 assert_abs_diff_eq!(rho.entry(0, 0).re, 0.5, epsilon = TOL);
555 assert_abs_diff_eq!(rho.entry(1, 1).re, 0.5, epsilon = TOL);
556 assert_abs_diff_eq!(rho.entry(0, 1).norm(), 0.0, epsilon = TOL);
557 assert_abs_diff_eq!(rho.entry(1, 0).norm(), 0.0, epsilon = TOL);
558 assert_abs_diff_eq!(rho.trace().re, 1.0, epsilon = TOL);
559 }
560
561 #[test]
562 fn bit_flip_p1_matches_x_gate() {
563 let mut s = State::new(2).unwrap();
564 s.h(0).unwrap();
565 s.cnot(0, 1).unwrap();
566
567 let mut rho = DensityMatrix::from_pure_state(&s);
569 let kraus = DensityMatrix::bit_flip_kraus(2, 0, 1.0).unwrap();
570 rho.apply_kraus(&kraus).unwrap();
571
572 let mut s_flipped = s.clone();
574 s_flipped.x(0).unwrap();
575 let rho_expected = DensityMatrix::from_pure_state(&s_flipped);
576
577 for i in 0..4 {
578 for j in 0..4 {
579 let a = rho.entry(i, j);
580 let b = rho_expected.entry(i, j);
581 assert_abs_diff_eq!(a.re, b.re, epsilon = TOL);
582 assert_abs_diff_eq!(a.im, b.im, epsilon = TOL);
583 }
584 }
585 }
586
587 #[test]
588 fn gate_application_matches_pure_state_path() {
589 let mut s = State::new(3).unwrap();
593 s.h(0).unwrap();
594
595 let mut rho = DensityMatrix::from_pure_state(&State::new(3).unwrap());
596 rho.h(0).unwrap();
597
598 s.cnot(0, 1).unwrap();
599 rho.apply_cnot(0, 1).unwrap();
600 s.cnot(1, 2).unwrap();
601 rho.apply_cnot(1, 2).unwrap();
602
603 let p_state = s.probabilities();
604 let p_rho = rho.probabilities();
605 for (a, b) in p_state.iter().zip(p_rho.iter()) {
606 assert_abs_diff_eq!(a, b, epsilon = TOL);
607 }
608 assert_abs_diff_eq!(s.expectation_z(), rho.expectation_z(), epsilon = TOL);
609 }
610
611 #[test]
612 fn from_mixture_of_one_state_matches_pure() {
613 let mut s = State::new(1).unwrap();
614 s.h(0).unwrap();
615 let rho_pure = DensityMatrix::from_pure_state(&s);
616 let rho_mix = DensityMatrix::from_mixture(&[s], &[1.0]).unwrap();
617 for i in 0..2 {
618 for j in 0..2 {
619 let a = rho_pure.entry(i, j);
620 let b = rho_mix.entry(i, j);
621 assert_abs_diff_eq!(a.re, b.re, epsilon = TOL);
622 assert_abs_diff_eq!(a.im, b.im, epsilon = TOL);
623 }
624 }
625 }
626
627 #[test]
628 fn from_mixture_error_paths() {
629 let s0 = State::new(1).unwrap();
630 let mut s1 = State::new(1).unwrap();
631 s1.x(0).unwrap();
632
633 assert_eq!(
634 DensityMatrix::from_mixture(&[], &[]),
635 Err(StateError::EmptyMixture)
636 );
637 assert_eq!(
638 DensityMatrix::from_mixture(std::slice::from_ref(&s0), &[0.5, 0.5]),
639 Err(StateError::MixtureSizeMismatch {
640 states: 1,
641 probs: 2
642 })
643 );
644 assert_eq!(
645 DensityMatrix::from_mixture(&[s0.clone(), s1.clone()], &[0.5, 0.6]),
646 Err(StateError::ProbabilitiesNotNormalized(1.1))
647 );
648 assert_eq!(
649 DensityMatrix::from_mixture(&[s0, s1], &[-0.5, 1.5]),
650 Err(StateError::NegativeProbability)
651 );
652 }
653
654 #[test]
655 fn maximally_mixed_two_state_average() {
656 let s0 = State::new(1).unwrap(); let mut s1 = State::new(1).unwrap();
658 s1.x(0).unwrap(); let rho = DensityMatrix::from_mixture(&[s0, s1], &[0.5, 0.5]).unwrap();
660 assert_abs_diff_eq!(rho.entry(0, 0).re, 0.5, epsilon = TOL);
661 assert_abs_diff_eq!(rho.entry(1, 1).re, 0.5, epsilon = TOL);
662 assert_abs_diff_eq!(rho.entry(0, 1).norm(), 0.0, epsilon = TOL);
663 assert_abs_diff_eq!(rho.trace().re, 1.0, epsilon = TOL);
664 }
665
666 #[test]
667 fn invalid_qubit_and_probability_errors() {
668 let s = State::new(2).unwrap();
669 let mut rho = DensityMatrix::from_pure_state(&s);
670 assert_eq!(rho.h(5), Err(StateError::InvalidQubit { qubit: 5, n: 2 }));
671 assert_eq!(rho.apply_cnot(1, 1), Err(StateError::SameQubits(1)));
672 assert_eq!(
673 DensityMatrix::bit_flip_kraus(2, 0, 1.5),
674 Err(StateError::InvalidProbability(1.5))
675 );
676 assert_eq!(
677 DensityMatrix::depolarizing_kraus(2, 5, 0.1),
678 Err(StateError::InvalidQubit { qubit: 5, n: 2 })
679 );
680 }
681
682 #[test]
683 fn matrix_from_row_major_rejects_wrong_length() {
684 let data = vec![Complex::new(1.0, 0.0); 3];
685 assert!(Matrix::from_row_major(2, data).is_err());
686 }
687}