Skip to main content

tpt_sci_quantum/
density.rs

1//! Density-matrix representation and Kraus-channel noise application.
2//!
3//! [`DensityMatrix`] models an `n`-qubit *mixed* state as a `2^n × 2^n`
4//! complex Hermitian, trace-1, positive-semidefinite matrix `ρ`, alongside
5//! (not replacing) the pure-state [`crate::State`] vector representation.
6//! Mixed states arise from classical uncertainty about the prepared pure
7//! state, or from tracing out an environment — most commonly from applying
8//! **noise channels**, which is the main reason to reach for this module.
9//!
10//! ## Representation
11//!
12//! Internally `ρ` is stored as the real `2·2^n × 2·2^n` block embedding used
13//! throughout this crate (see [`crate::tensor`]): each complex entry
14//! `a + bi` becomes the real `2×2` block `[[a, -b], [b, a]]`. This lets gate
15//! application and Kraus-channel application reuse ordinary real matrix
16//! multiplication (`tpt-math-linalg`'s `DMatrix<f64>`) instead of re-deriving
17//! complex arithmetic, and it reuses [`crate::tensor::Circuit`]'s
18//! Kronecker-product unitary assembly directly for gates. A convenient
19//! identity of the embedding — `embed(A†) == embed(A).transpose()` — is what
20//! lets both unitary conjugation `ρ ↦ U ρ U†` and the general Kraus map
21//! `ρ ↦ Σ_k K_k ρ K_k†` be implemented as plain real matrix products.
22//!
23//! Because storage is `O(4^n)` (`2^n × 2^n` complex, or equivalently
24//! `2^(n+1) × 2^(n+1)` real), density-matrix simulation is practical only for
25//! a much smaller qubit count than the pure-state [`crate::State`] path
26//! (which stores just `O(2^n)` amplitudes and supports up to 20 qubits) — a
27//! dozen or so qubits is already multiple gigabytes of `f64` storage for the
28//! dense matrix.
29//!
30//! ## Examples
31//!
32//! Build a Bell state as a density matrix and confirm it is the outer
33//! product of the pure state with itself:
34//!
35//! ```
36//! use tpt_sci_quantum::{State, DensityMatrix};
37//!
38//! let mut state = State::new(2).unwrap();
39//! state.h(0).unwrap();
40//! state.cnot(0, 1).unwrap();
41//!
42//! let rho = DensityMatrix::from_pure_state(&state);
43//! assert!((rho.trace().re - 1.0).abs() < 1e-9);
44//! let p = rho.probabilities();
45//! assert!((p[0] - 0.5).abs() < 1e-9);
46//! assert!((p[3] - 0.5).abs() < 1e-9);
47//! ```
48//!
49//! Apply single-qubit bit-flip noise to one qubit of a two-qubit register:
50//!
51//! ```
52//! use tpt_sci_quantum::{State, DensityMatrix};
53//!
54//! let state = State::new(2).unwrap(); // |00>
55//! let mut rho = DensityMatrix::from_pure_state(&state);
56//! let kraus = DensityMatrix::bit_flip_kraus(2, 0, 1.0).unwrap(); // deterministic flip
57//! rho.apply_kraus(&kraus).unwrap();
58//! let p = rho.probabilities();
59//! assert!((p[1] - 1.0).abs() < 1e-9); // |01> (qubit 0 flipped)
60//! ```
61
62use num_complex::Complex;
63use tpt_math_linalg::tpt_math_linalg_dense::DMatrix;
64
65use crate::tensor::{self, Circuit};
66use crate::{State, StateError};
67
68/// Identity gate, `I = [[1, 0], [0, 1]]`, used internally by the noise-channel
69/// constructors.
70const 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/// A dense complex square matrix, stored row-major.
78///
79/// Used to pass Kraus operators to [`DensityMatrix::apply_kraus`]. Most
80/// callers will not build one by hand: [`DensityMatrix::bit_flip_kraus`] and
81/// [`DensityMatrix::depolarizing_kraus`] construct ready-made single-qubit
82/// noise channels, already embedded into the full `n`-qubit space.
83#[derive(Clone, Debug, PartialEq)]
84pub struct Matrix {
85    dim: usize,
86    data: Vec<Complex<f64>>,
87}
88
89impl Matrix {
90    /// Build a `dim × dim` matrix from `data` in row-major order.
91    ///
92    /// # Errors
93    ///
94    /// Returns [`StateError::MatrixSizeMismatch`] if `data.len() != dim * dim`.
95    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    /// The row/column count of this (square) matrix.
106    #[must_use]
107    pub fn dim(&self) -> usize {
108        self.dim
109    }
110
111    /// The entry at `(row, col)`.
112    ///
113    /// # Panics
114    ///
115    /// Panics if `row >= dim()` or `col >= dim()`.
116    #[must_use]
117    pub fn get(&self, row: usize, col: usize) -> Complex<f64> {
118        self.data[row * self.dim + col]
119    }
120
121    /// The raw row-major entries.
122    #[must_use]
123    pub fn data(&self) -> &[Complex<f64>] {
124        &self.data
125    }
126}
127
128/// Embed a single-qubit `gate`, scaled by the real `coeff`, into the full
129/// `n`-qubit space acting on `qubit` (identity elsewhere), returning it as a
130/// [`Matrix`]. Reuses [`tensor::expand_single`] (the same Kronecker-product
131/// assembly `Circuit::unitary` uses for single-qubit gates) and then
132/// un-embeds the result back into an ordinary complex [`Matrix`].
133fn 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/// An `n`-qubit mixed state stored as a `2^n × 2^n` density matrix `ρ`.
157///
158/// See the [module docs](self) for the storage representation and its
159/// `O(4^n)` memory cost.
160#[derive(Clone, Debug, PartialEq)]
161pub struct DensityMatrix {
162    n: usize,
163    /// Real `2d × 2d` block embedding of the complex `d × d` density matrix
164    /// (`d = 2^n`); see [`tensor::embed_complex_square`].
165    real: DMatrix<f64>,
166}
167
168impl DensityMatrix {
169    /// The number of qubits represented by this density matrix.
170    #[must_use]
171    pub fn n_qubits(&self) -> usize {
172        self.n
173    }
174
175    /// The Hilbert-space dimension `2^n`.
176    #[must_use]
177    pub fn dim(&self) -> usize {
178        1usize << self.n
179    }
180
181    /// Build the density matrix `ρ = |ψ⟩⟨ψ|` of a pure [`State`].
182    ///
183    /// # Examples
184    ///
185    /// ```
186    /// use tpt_sci_quantum::{State, DensityMatrix};
187    /// let mut s = State::new(1).unwrap();
188    /// s.h(0).unwrap();
189    /// let rho = DensityMatrix::from_pure_state(&s);
190    /// assert!((rho.entry(0, 0).re - 0.5).abs() < 1e-9);
191    /// assert!((rho.entry(0, 1).re - 0.5).abs() < 1e-9);
192    /// ```
193    #[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    /// Build a classical mixture `ρ = Σ_k p_k |ψ_k⟩⟨ψ_k|` of pure states with
209    /// probabilities `probs`.
210    ///
211    /// # Errors
212    ///
213    /// Returns [`StateError::EmptyMixture`] if `states` is empty,
214    /// [`StateError::MixtureSizeMismatch`] if `states.len() != probs.len()`,
215    /// [`StateError::QubitCountMismatch`] if the states have differing qubit
216    /// counts, [`StateError::NegativeProbability`] if any probability is
217    /// negative, or [`StateError::ProbabilitiesNotNormalized`] if the
218    /// probabilities do not sum to `1` (within `1e-6`).
219    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    /// The complex entry `ρ[(i, j)]`.
255    ///
256    /// # Panics
257    ///
258    /// Panics if `i >= dim()` or `j >= dim()`.
259    #[must_use]
260    pub fn entry(&self, i: usize, j: usize) -> Complex<f64> {
261        tensor::unembed_entry(&self.real, i, j)
262    }
263
264    /// The trace `Tr(ρ) = Σ_i ρ[(i, i)]`.
265    ///
266    /// Equal to `1` (up to floating-point rounding) for any physically valid
267    /// density matrix; useful as a validity check after gate/channel
268    /// application.
269    #[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    /// The measurement probabilities `ρ[(i, i)]` for each computational basis
276    /// state (the diagonal of `ρ`, which is real and non-negative for a
277    /// physical density matrix).
278    #[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    /// Expectation value `⟨Z^{⊗n}⟩ = Σ_i (-1)^{popcount(i)} ρ[(i, i)]` of the
285    /// all-qubit parity operator, analogous to [`State::expectation_z`].
286    #[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    /// Apply a real-embedded unitary `u ρ u^T` (`u^T` stands in for `u†`
298    /// under the real embedding) built by [`Circuit::unitary`].
299    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    /// Apply a single-qubit `gate` to `qubit` via unitary conjugation
305    /// `ρ ↦ U ρ U†`.
306    ///
307    /// # Errors
308    ///
309    /// Returns [`StateError::InvalidQubit`] if `qubit >= n_qubits()`.
310    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    /// Apply a controlled-NOT: flip `target` whenever `control` is set.
322    ///
323    /// # Errors
324    ///
325    /// Returns [`StateError::InvalidQubit`] if either qubit is out of range,
326    /// or [`StateError::SameQubits`] if `control == target`.
327    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    /// Apply the Hadamard gate `H` to `qubit`.
345    ///
346    /// # Errors
347    ///
348    /// Returns [`StateError::InvalidQubit`] if `qubit` is out of range.
349    pub fn h(&mut self, qubit: usize) -> Result<(), StateError> {
350        self.apply_gate(&crate::H, qubit)
351    }
352
353    /// Apply the Pauli-X gate to `qubit`.
354    ///
355    /// # Errors
356    ///
357    /// Returns [`StateError::InvalidQubit`] if `qubit` is out of range.
358    pub fn x(&mut self, qubit: usize) -> Result<(), StateError> {
359        self.apply_gate(&crate::X, qubit)
360    }
361
362    /// Apply the Pauli-Y gate to `qubit`.
363    ///
364    /// # Errors
365    ///
366    /// Returns [`StateError::InvalidQubit`] if `qubit` is out of range.
367    pub fn y(&mut self, qubit: usize) -> Result<(), StateError> {
368        self.apply_gate(&crate::Y, qubit)
369    }
370
371    /// Apply the Pauli-Z gate to `qubit`.
372    ///
373    /// # Errors
374    ///
375    /// Returns [`StateError::InvalidQubit`] if `qubit` is out of range.
376    pub fn z(&mut self, qubit: usize) -> Result<(), StateError> {
377        self.apply_gate(&crate::Z, qubit)
378    }
379
380    /// Apply a set of Kraus operators, `ρ ↦ Σ_k K_k ρ K_k†`.
381    ///
382    /// `kraus_ops` must satisfy `Σ_k K_k† K_k = I` for the result to remain a
383    /// physically valid (trace-1) density matrix; this is not checked here
384    /// (validate with [`DensityMatrix::trace`] after the call if needed). Each
385    /// operator must be `dim() × dim()`, i.e. already embedded into the full
386    /// `n`-qubit space — see [`DensityMatrix::bit_flip_kraus`] and
387    /// [`DensityMatrix::depolarizing_kraus`] for ready-made single-qubit
388    /// channels.
389    ///
390    /// # Errors
391    ///
392    /// Returns [`StateError::MatrixSizeMismatch`] if any operator is not
393    /// `dim() × dim()`.
394    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    /// Kraus operators for the single-qubit **bit-flip channel** on `qubit`
417    /// within an `n`-qubit register: with probability `p` the qubit is
418    /// flipped by `X`, and with probability `1 - p` it is left alone.
419    ///
420    /// `K_0 = √(1-p)·I`, `K_1 = √p·X`, each embedded into the full `n`-qubit
421    /// space (identity on all other qubits).
422    ///
423    /// # Errors
424    ///
425    /// Returns [`StateError::InvalidQubit`] if `qubit >= n`, or
426    /// [`StateError::InvalidProbability`] if `p` is outside `[0, 1]`.
427    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    /// Kraus operators for the single-qubit **depolarizing channel** on
440    /// `qubit` within an `n`-qubit register: `ρ ↦ (1-p)·ρ + p·I/2` (the qubit
441    /// is replaced by the maximally mixed state with probability `p`).
442    ///
443    /// `K_0 = √(1 - 3p/4)·I`, `K_1 = √(p/4)·X`, `K_2 = √(p/4)·Y`,
444    /// `K_3 = √(p/4)·Z`, each embedded into the full `n`-qubit space
445    /// (identity on all other qubits). At `p = 0` this is the identity
446    /// channel; at `p = 1` it fully depolarizes `qubit` to the maximally
447    /// mixed state regardless of the input.
448    ///
449    /// # Errors
450    ///
451    /// Returns [`StateError::InvalidQubit`] if `qubit >= n`, or
452    /// [`StateError::InvalidProbability`] if `p` is outside `[0, 1]`.
453    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        // Start from a pure (non-mixed) state so full depolarization is a
546        // real change, not a no-op.
547        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        // Density-matrix path: bit-flip channel with p=1 on qubit 0.
568        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        // Reference: apply an X gate directly to the same pure state.
573        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        // Cross-check: applying gates to a DensityMatrix built from a pure
590        // state (no noise) gives the same measurement statistics as applying
591        // the same gates directly to the State.
592        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(); // |0>
657        let mut s1 = State::new(1).unwrap();
658        s1.x(0).unwrap(); // |1>
659        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}