Skip to main content

tpt_sci_quantum/
lib.rs

1//! # tpt-sci-quantum
2//!
3//! A from-scratch **qubit state-vector simulator** for the `tpt-science` pillar.
4//!
5//! The simulator represents an `n`-qubit pure state as a length-`2^n` vector of
6//! complex amplitudes (in the computational basis `|0...0>` … `|1...1>`). Gates
7//! are applied in place by iterating over the relevant pairs of basis states, and
8//! measurement samples a basis index from the Born rule distribution.
9//!
10//! No external quantum-simulation crates are used: the linear algebra is just
11//! complex scalars and explicit index arithmetic over the amplitude vector.
12//!
13//! ## Examples
14//!
15//! Build the Bell state `|Φ+⟩ = (|00⟩ + |11⟩)/√2` and check its marginals:
16//!
17//! ```
18//! use tpt_sci_quantum::State;
19//!
20//! let mut state = State::new(2).unwrap();
21//! state.h(0).unwrap();
22//! state.cnot(0, 1).unwrap();
23//!
24//! let p = state.probabilities();
25//! assert!((p[0] - 0.5).abs() < 1e-9);
26//! assert!((p[3] - 0.5).abs() < 1e-9);
27//! ```
28
29use num_complex::Complex;
30use std::f64::consts::SQRT_2;
31use tpt_math_prob_core::Rng;
32
33/// `1/√2`, used by several gate constants.
34const INV_SQRT2: f64 = 1.0 / SQRT_2;
35
36/// Tensor-product (Kronecker) circuit formulation built on `tpt-math-linalg`.
37pub mod tensor;
38pub use tensor::{Circuit, embed_gate_2x2, kron};
39
40/// Density-matrix representation and Kraus-channel noise application.
41pub mod density;
42pub use density::{DensityMatrix, Matrix};
43
44/// Errors produced by state construction and gate application.
45pub mod error;
46pub use error::StateError;
47
48/// A pure `n`-qubit state stored as a length-`2^n` amplitude vector.
49///
50/// Amplitudes are stored in computational-basis order: `amps[i]` is the
51/// amplitude of `|i⟩` where `i` is the integer whose binary little-endian
52/// representation encodes the per-qubit basis states.
53#[derive(Clone, Debug, PartialEq)]
54pub struct State {
55    amps: Vec<Complex<f64>>,
56}
57
58impl State {
59    /// Create the all-zero state `|0...0⟩` for `n` qubits.
60    ///
61    /// # Errors
62    ///
63    /// Returns [`StateError::TooManyQubits`] if `n == 0` (a zero-qubit state is
64    /// meaningless) or `n > 20` (the `2^20` amplitude vector is the supported
65    /// upper bound).
66    ///
67    /// # Examples
68    ///
69    /// ```
70    /// use tpt_sci_quantum::State;
71    /// let s = State::new(3).unwrap();
72    /// assert_eq!(s.n_qubits(), 3);
73    /// assert_eq!(s.amplitude(0), num_complex::Complex::new(1.0, 0.0));
74    /// ```
75    pub fn new(n: usize) -> Result<Self, StateError> {
76        if n == 0 || n > 20 {
77            return Err(StateError::TooManyQubits(n));
78        }
79        let dim = 1usize << n;
80        let mut amps = vec![Complex::new(0.0, 0.0); dim];
81        amps[0] = Complex::new(1.0, 0.0);
82        Ok(State { amps })
83    }
84
85    /// Alias for [`State::new`] retained for readability in examples.
86    ///
87    /// # Errors
88    ///
89    /// See [`State::new`].
90    pub fn zero(n: usize) -> Result<Self, StateError> {
91        Self::new(n)
92    }
93
94    /// The number of qubits represented by this state.
95    #[must_use]
96    pub fn n_qubits(&self) -> usize {
97        self.amps.len().trailing_zeros() as usize
98    }
99
100    /// The raw amplitude vector (computational-basis order).
101    #[must_use]
102    pub fn amplitudes(&self) -> &[Complex<f64>] {
103        &self.amps
104    }
105
106    /// The amplitude of the basis state `|index⟩`.
107    ///
108    /// # Panics
109    ///
110    /// Panics if `index >= 2^n`.
111    #[must_use]
112    pub fn amplitude(&self, index: usize) -> Complex<f64> {
113        self.amps[index]
114    }
115
116    /// The Born-rule probabilities `|amp|^2` for each basis state.
117    ///
118    /// The returned vector sums to `1` up to floating-point rounding.
119    #[must_use]
120    pub fn probabilities(&self) -> Vec<f64> {
121        self.amps.iter().map(Complex::norm_sqr).collect()
122    }
123
124    /// The Euclidean norm `sqrt(Σ |amp|^2)` of the state vector.
125    #[must_use]
126    pub fn norm(&self) -> f64 {
127        self.amps.iter().map(Complex::norm_sqr).sum::<f64>().sqrt()
128    }
129
130    /// Rescale the state so that its norm becomes `1`.
131    ///
132    /// # Panics
133    ///
134    /// Panics if the current norm is zero (a zero vector has no normalization).
135    pub fn normalize(&mut self) {
136        let n = self.norm();
137        let inv = 1.0 / n;
138        for a in &mut self.amps {
139            *a = a.scale(inv);
140        }
141    }
142
143    /// Sample a basis index from the Born-rule distribution.
144    ///
145    /// Uses `rng` to draw a uniform value in `[0, 1)` and returns the first
146    /// index whose cumulative probability exceeds it.
147    ///
148    /// This method is **non-destructive**: it only reads the state and reports
149    /// a sampled outcome. Repeated calls therefore keep returning outcomes from
150    /// the same (uncollapsed) distribution. Use [`State::measure_collapsing`]
151    /// when you need the standard post-measurement collapse semantics (as in
152    /// Qiskit/Cirq), where the state is projected onto the measured basis
153    /// state.
154    ///
155    /// # Examples
156    ///
157    /// ```
158    /// use tpt_sci_quantum::State;
159    /// use tpt_math_prob_core::SplitMix64;
160    ///
161    /// let mut state = State::new(1).unwrap();
162    /// state.h(0).unwrap();
163    /// let mut rng = SplitMix64::seed_from_u64(1);
164    /// let idx = state.measure(&mut rng);
165    /// assert!(idx == 0 || idx == 1);
166    /// ```
167    #[must_use]
168    pub fn measure(&self, rng: &mut impl Rng) -> usize {
169        let r = rng.next_f64();
170        let mut cumulative = 0.0;
171        for (i, a) in self.amps.iter().enumerate() {
172            cumulative += a.norm_sqr();
173            if r < cumulative {
174                return i;
175            }
176        }
177        self.amps.len() - 1
178    }
179
180    /// Sample a basis index and collapse the state onto that outcome.
181    ///
182    /// Unlike [`State::measure`], which only samples without disturbing the
183    /// state, this consumes the measurement: the state is projected onto the
184    /// measured computational-basis state (all other amplitudes zeroed) and the
185    /// surviving amplitude is renormalised. This matches the standard simulator
186    /// semantics (Qiskit/Cirq), where a subsequent measurement of the same
187    /// register is deterministic.
188    ///
189    /// # Examples
190    ///
191    /// ```
192    /// use tpt_sci_quantum::State;
193    /// use tpt_math_prob_core::SplitMix64;
194    ///
195    /// let mut state = State::new(1).unwrap();
196    /// state.x(0).unwrap(); // |1⟩
197    /// let mut rng = SplitMix64::seed_from_u64(7);
198    /// let idx = state.measure_collapsing(&mut rng);
199    /// assert_eq!(idx, 1);
200    /// assert!((state.amplitude(1).norm() - 1.0).abs() < 1e-9);
201    /// ```
202    pub fn measure_collapsing(&mut self, rng: &mut impl Rng) -> usize {
203        let idx = self.measure(rng);
204        let amp = self.amps[idx];
205        let norm = amp.norm();
206        for a in &mut self.amps {
207            *a = Complex::new(0.0, 0.0);
208        }
209        if norm > 0.0 {
210            // Preserve the (now unit-magnitude) phase of the surviving amplitude.
211            self.amps[idx] = amp.scale(1.0 / norm);
212        }
213        idx
214    }
215
216    /// Expectation value `⟨Z^{⊗n}⟩` of the all-qubit parity operator.
217    ///
218    /// Equal to `Σ_i (-1)^{popcount(i)} |amp_i|^2`. For the all-zero state this
219    /// is `1`; for a uniform superposition of even/odd parity states it is `0`.
220    #[must_use]
221    pub fn expectation_z(&self) -> f64 {
222        self.amps
223            .iter()
224            .enumerate()
225            .map(|(i, a)| {
226                let sign = if i.count_ones() & 1 == 0 { 1.0 } else { -1.0 };
227                sign * a.norm_sqr()
228            })
229            .sum()
230    }
231
232    /// Apply a single-qubit 2×2 gate to `qubit`.
233    ///
234    /// `gate` is row-major: `[g00, g01, g10, g11]` for
235    /// `[[g00, g01], [g10, g11]]`. For each pair of basis states that differ
236    /// only in `qubit`, the two amplitudes are transformed by the matrix.
237    ///
238    /// # Errors
239    ///
240    /// Returns [`StateError::InvalidQubit`] if `qubit >= n_qubits()`.
241    pub fn apply_single(
242        &mut self,
243        gate: &[Complex<f64>; 4],
244        qubit: usize,
245    ) -> Result<(), StateError> {
246        let n = self.n_qubits();
247        if qubit >= n {
248            return Err(StateError::InvalidQubit { qubit, n });
249        }
250        let (g00, g01, g10, g11) = (gate[0], gate[1], gate[2], gate[3]);
251        let flip = 1usize << qubit;
252        for i in 0..(1usize << n) {
253            if i & flip == 0 {
254                let j = i | flip;
255                let a0 = self.amps[i];
256                let a1 = self.amps[j];
257                self.amps[i] = g00 * a0 + g01 * a1;
258                self.amps[j] = g10 * a0 + g11 * a1;
259            }
260        }
261        Ok(())
262    }
263
264    /// Apply a controlled-NOT: flip `target` whenever `control` is set.
265    ///
266    /// # Errors
267    ///
268    /// Returns [`StateError::InvalidQubit`] if either qubit is out of range, or
269    /// [`StateError::SameQubits`] if `control == target`.
270    pub fn apply_cnot(&mut self, control: usize, target: usize) -> Result<(), StateError> {
271        let n = self.n_qubits();
272        if control >= n {
273            return Err(StateError::InvalidQubit { qubit: control, n });
274        }
275        if target >= n {
276            return Err(StateError::InvalidQubit { qubit: target, n });
277        }
278        if control == target {
279            return Err(StateError::SameQubits(control));
280        }
281        let c = 1usize << control;
282        let t = 1usize << target;
283        for i in 0..(1usize << n) {
284            if i & c != 0 && i & t == 0 {
285                self.amps.swap(i, i | t);
286            }
287        }
288        Ok(())
289    }
290
291    /// Apply a single-qubit `gate` to `target`, controlled on `control == 1`.
292    ///
293    /// # Errors
294    ///
295    /// Returns [`StateError::InvalidQubit`] if either qubit is out of range, or
296    /// [`StateError::SameQubits`] if `control == target`.
297    pub fn apply_controlled(
298        &mut self,
299        control: usize,
300        target: usize,
301        gate: &[Complex<f64>; 4],
302    ) -> Result<(), StateError> {
303        let n = self.n_qubits();
304        if control >= n {
305            return Err(StateError::InvalidQubit { qubit: control, n });
306        }
307        if target >= n {
308            return Err(StateError::InvalidQubit { qubit: target, n });
309        }
310        if control == target {
311            return Err(StateError::SameQubits(control));
312        }
313        let (g00, g01, g10, g11) = (gate[0], gate[1], gate[2], gate[3]);
314        let c = 1usize << control;
315        let t = 1usize << target;
316        for i in 0..(1usize << n) {
317            if i & c != 0 && i & t == 0 {
318                let j = i | t;
319                let a0 = self.amps[i];
320                let a1 = self.amps[j];
321                self.amps[i] = g00 * a0 + g01 * a1;
322                self.amps[j] = g10 * a0 + g11 * a1;
323            }
324        }
325        Ok(())
326    }
327
328    /// Apply the Hadamard gate `H` to `qubit`.
329    ///
330    /// # Errors
331    ///
332    /// Returns [`StateError::InvalidQubit`] if `qubit` is out of range.
333    pub fn h(&mut self, qubit: usize) -> Result<(), StateError> {
334        self.apply_single(&H, qubit)
335    }
336
337    /// Apply the Pauli-X (bit-flip) gate to `qubit`.
338    ///
339    /// # Errors
340    ///
341    /// Returns [`StateError::InvalidQubit`] if `qubit` is out of range.
342    pub fn x(&mut self, qubit: usize) -> Result<(), StateError> {
343        self.apply_single(&X, qubit)
344    }
345
346    /// Apply the Pauli-Y gate to `qubit`.
347    ///
348    /// # Errors
349    ///
350    /// Returns [`StateError::InvalidQubit`] if `qubit` is out of range.
351    pub fn y(&mut self, qubit: usize) -> Result<(), StateError> {
352        self.apply_single(&Y, qubit)
353    }
354
355    /// Apply the Pauli-Z (phase-flip) gate to `qubit`.
356    ///
357    /// # Errors
358    ///
359    /// Returns [`StateError::InvalidQubit`] if `qubit` is out of range.
360    pub fn z(&mut self, qubit: usize) -> Result<(), StateError> {
361        self.apply_single(&Z, qubit)
362    }
363
364    /// Apply the phase gate `S` to `qubit`.
365    ///
366    /// # Errors
367    ///
368    /// Returns [`StateError::InvalidQubit`] if `qubit` is out of range.
369    pub fn s(&mut self, qubit: usize) -> Result<(), StateError> {
370        self.apply_single(&S, qubit)
371    }
372
373    /// Apply the π/4 (T) gate to `qubit`.
374    ///
375    /// # Errors
376    ///
377    /// Returns [`StateError::InvalidQubit`] if `qubit` is out of range.
378    pub fn t(&mut self, qubit: usize) -> Result<(), StateError> {
379        self.apply_single(&T, qubit)
380    }
381
382    /// Apply a controlled-NOT gate.
383    ///
384    /// # Errors
385    ///
386    /// Returns [`StateError::InvalidQubit`] if either qubit is out of range, or
387    /// [`StateError::SameQubits`] if `control == target`.
388    pub fn cnot(&mut self, control: usize, target: usize) -> Result<(), StateError> {
389        self.apply_cnot(control, target)
390    }
391}
392
393/// Hadamard gate `H = (1/√2)·[[1,1],[1,-1]]`.
394pub const H: [Complex<f64>; 4] = [
395    Complex::new(INV_SQRT2, 0.0),
396    Complex::new(INV_SQRT2, 0.0),
397    Complex::new(INV_SQRT2, 0.0),
398    Complex::new(-INV_SQRT2, 0.0),
399];
400
401/// Pauli-X (bit-flip) gate `X = [[0,1],[1,0]]`.
402pub const X: [Complex<f64>; 4] = [
403    Complex::new(0.0, 0.0),
404    Complex::new(1.0, 0.0),
405    Complex::new(1.0, 0.0),
406    Complex::new(0.0, 0.0),
407];
408
409/// Pauli-Y gate `Y = [[0,-i],[i,0]]`.
410pub const Y: [Complex<f64>; 4] = [
411    Complex::new(0.0, 0.0),
412    Complex::new(0.0, -1.0),
413    Complex::new(0.0, 1.0),
414    Complex::new(0.0, 0.0),
415];
416
417/// Pauli-Z (phase-flip) gate `Z = [[1,0],[0,-1]]`.
418pub const Z: [Complex<f64>; 4] = [
419    Complex::new(1.0, 0.0),
420    Complex::new(0.0, 0.0),
421    Complex::new(0.0, 0.0),
422    Complex::new(-1.0, 0.0),
423];
424
425/// Phase gate `S = [[1,0],[0,i]]`.
426pub const S: [Complex<f64>; 4] = [
427    Complex::new(1.0, 0.0),
428    Complex::new(0.0, 0.0),
429    Complex::new(0.0, 0.0),
430    Complex::new(0.0, 1.0),
431];
432
433/// π/4 (T) gate `T = [[1,0],[0,e^{iπ/4}]]`.
434pub const T: [Complex<f64>; 4] = [
435    Complex::new(1.0, 0.0),
436    Complex::new(0.0, 0.0),
437    Complex::new(0.0, 0.0),
438    Complex::new(INV_SQRT2, INV_SQRT2),
439];
440
441#[cfg(test)]
442impl State {
443    /// Test-only accessor exposing the amplitude vector mutably.
444    fn amplitudes_mut_for_test(&mut self) -> &mut [Complex<f64>] {
445        &mut self.amps
446    }
447}
448
449#[cfg(test)]
450mod tests {
451    use super::*;
452    use approx::assert_abs_diff_eq;
453    use tpt_math_prob_core::SplitMix64;
454
455    const TOL: f64 = 1e-9;
456
457    #[test]
458    fn new_rejects_zero_and_too_many() {
459        assert_eq!(State::new(0), Err(StateError::TooManyQubits(0)));
460        assert_eq!(State::new(21), Err(StateError::TooManyQubits(21)));
461        assert!(State::new(1).is_ok());
462        assert!(State::new(20).is_ok());
463    }
464
465    #[test]
466    fn hadamard_on_zero_state() {
467        let mut s = State::new(1).unwrap();
468        s.h(0).unwrap();
469        let inv = INV_SQRT2;
470        assert_abs_diff_eq!(s.amplitude(0).re, inv, epsilon = TOL);
471        assert_abs_diff_eq!(s.amplitude(1).re, inv, epsilon = TOL);
472        assert_abs_diff_eq!(s.amplitude(0).im, 0.0, epsilon = TOL);
473        assert_abs_diff_eq!(s.amplitude(1).im, 0.0, epsilon = TOL);
474    }
475
476    #[test]
477    fn x_flips_zero_to_one() {
478        let mut s = State::new(1).unwrap();
479        s.x(0).unwrap();
480        assert_abs_diff_eq!(s.amplitude(1).re, 1.0, epsilon = TOL);
481        assert_abs_diff_eq!(s.amplitude(0).re, 0.0, epsilon = TOL);
482    }
483
484    #[test]
485    fn bell_state() {
486        let mut s = State::new(2).unwrap();
487        s.h(0).unwrap();
488        s.cnot(0, 1).unwrap();
489        let inv = INV_SQRT2;
490        assert_abs_diff_eq!(s.amplitude(0).re, inv, epsilon = TOL);
491        assert_abs_diff_eq!(s.amplitude(1).re, 0.0, epsilon = TOL);
492        assert_abs_diff_eq!(s.amplitude(2).re, 0.0, epsilon = TOL);
493        assert_abs_diff_eq!(s.amplitude(3).re, inv, epsilon = TOL);
494
495        let p = s.probabilities();
496        assert_abs_diff_eq!(p[0], 0.5, epsilon = TOL);
497        assert_abs_diff_eq!(p[3], 0.5, epsilon = TOL);
498        // All-qubit parity ⟨Z⊗Z⟩: both |00⟩ and |11⟩ have even popcount ⇒ +1.
499        assert_abs_diff_eq!(s.expectation_z(), 1.0, epsilon = TOL);
500    }
501
502    #[test]
503    fn ghz_state() {
504        let mut s = State::new(3).unwrap();
505        s.h(0).unwrap();
506        s.cnot(0, 1).unwrap();
507        s.cnot(1, 2).unwrap();
508        let inv = INV_SQRT2;
509        assert_abs_diff_eq!(s.amplitude(0).re, inv, epsilon = TOL);
510        assert_abs_diff_eq!(s.amplitude(7).re, inv, epsilon = TOL);
511        for i in [1usize, 2, 3, 4, 5, 6] {
512            assert_abs_diff_eq!(s.amplitude(i).norm(), 0.0, epsilon = TOL);
513        }
514        // GHZ parity: |000⟩ even (+1), |111⟩ odd (-1) ⇒ expectation 0.
515        assert_abs_diff_eq!(s.expectation_z(), 0.0, epsilon = TOL);
516    }
517
518    #[test]
519    fn measure_reproduces_distribution() {
520        let mut s = State::new(2).unwrap();
521        s.h(0).unwrap();
522        s.cnot(0, 1).unwrap();
523
524        let mut rng = SplitMix64::seed_from_u64(12345);
525        let trials = 2000;
526        let mut count0 = 0usize;
527        let mut count3 = 0usize;
528        for _ in 0..trials {
529            match s.measure(&mut rng) {
530                0 => count0 += 1,
531                3 => count3 += 1,
532                _ => {}
533            }
534        }
535        let f0 = count0 as f64 / trials as f64;
536        let f3 = count3 as f64 / trials as f64;
537        assert!((f0 - 0.5).abs() < 0.1, "f0 = {f0}");
538        assert!((f3 - 0.5).abs() < 0.1, "f3 = {f3}");
539    }
540
541    #[test]
542    fn measure_collapsing_projects_state() {
543        // |1> collapses deterministically to |1>.
544        let mut s = State::new(1).unwrap();
545        s.x(0).unwrap();
546        let mut rng = SplitMix64::seed_from_u64(7);
547        let idx = s.measure_collapsing(&mut rng);
548        assert_eq!(idx, 1);
549        assert!((s.amplitude(1).norm() - 1.0).abs() < TOL);
550        assert!((s.amplitude(0).norm()).abs() < TOL);
551
552        // A superposition collapses to one of its basis states and stays there.
553        let mut s2 = State::new(2).unwrap();
554        s2.h(0).unwrap();
555        s2.cnot(0, 1).unwrap();
556        let mut rng2 = SplitMix64::seed_from_u64(99);
557        let idx2 = s2.measure_collapsing(&mut rng2);
558        assert!(idx2 == 0 || idx2 == 3);
559        // After collapse, exactly one basis state carries unit probability.
560        let p = s2.probabilities();
561        let max_p: f64 = p.iter().cloned().fold(0.0, f64::max);
562        assert!((max_p - 1.0).abs() < TOL);
563        assert!((s2.norm() - 1.0).abs() < TOL);
564    }
565
566    #[test]
567    fn probabilities_sum_to_one() {
568        let mut s = State::new(3).unwrap();
569        s.h(0).unwrap();
570        s.h(1).unwrap();
571        s.h(2).unwrap();
572        let total: f64 = s.probabilities().iter().sum();
573        assert_abs_diff_eq!(total, 1.0, epsilon = TOL);
574        assert_abs_diff_eq!(s.norm(), 1.0, epsilon = TOL);
575    }
576
577    #[test]
578    fn error_paths() {
579        let mut s = State::new(2).unwrap();
580        assert_eq!(s.h(5), Err(StateError::InvalidQubit { qubit: 5, n: 2 }));
581        assert_eq!(s.cnot(1, 1), Err(StateError::SameQubits(1)));
582        assert_eq!(
583            s.cnot(5, 0),
584            Err(StateError::InvalidQubit { qubit: 5, n: 2 })
585        );
586    }
587
588    #[test]
589    fn controlled_gate_matches_analytic() {
590        // |0⟩ on target: controlled-X does nothing.
591        let mut s = State::new(2).unwrap();
592        s.x(0).unwrap(); // control = 1
593        s.apply_controlled(0, 1, &X).unwrap();
594        assert_abs_diff_eq!(s.amplitude(3).re, 1.0, epsilon = TOL);
595
596        // |0⟩ on control: target stays |0⟩.
597        let mut s2 = State::new(2).unwrap();
598        s2.apply_controlled(0, 1, &X).unwrap();
599        assert_abs_diff_eq!(s2.amplitude(0).re, 1.0, epsilon = TOL);
600    }
601
602    #[test]
603    fn normalize_restores_unit_norm() {
604        let mut s = State::new(2).unwrap();
605        s.h(0).unwrap();
606        s.cnot(0, 1).unwrap();
607        // Scale artificially then renormalize.
608        for a in s.amplitudes_mut_for_test() {
609            *a = a.scale(2.0);
610        }
611        assert_abs_diff_eq!(s.norm(), 2.0, epsilon = TOL);
612        s.normalize();
613        assert_abs_diff_eq!(s.norm(), 1.0, epsilon = TOL);
614    }
615}