Skip to main content

quantum_planning/
state.rs

1//! A state-vector simulator: `2^n` complex amplitudes and the gates the algorithms use.
2//!
3//! # Qubit order
4//!
5//! The order is little-endian. Qubit `q` is bit `q` of the basis-state index, so qubit 0 is
6//! the least significant bit. On three qubits, `X` on qubit 0 moves `|000⟩` (index 0) to
7//! index `0b001 = 1`, and `X` on qubit 2 moves it to index `0b100 = 4`. A
8//! [`PhaseOracle`](crate::PhaseOracle) gives basis index `i` to its index map, so candidate
9//! `i` is the basis state whose bits spell `i`.
10
11use alloc::vec;
12use alloc::vec::Vec;
13use core::f64::consts::FRAC_1_SQRT_2;
14use core::fmt;
15
16use rand_core::Rng;
17
18use crate::Complex;
19use crate::rng::unit_f64;
20
21/// The largest register the simulator accepts: `2^24` amplitudes, 256 MiB of state.
22pub const MAX_QUBITS: usize = 24;
23
24/// The error for a register with more than [`MAX_QUBITS`] qubits.
25#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26pub struct TooManyQubits {
27    /// The number of qubits that the caller asked for.
28    pub requested: usize,
29}
30
31impl fmt::Display for TooManyQubits {
32    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33        write!(
34            f,
35            "{} qubits requested, but the simulator holds at most {MAX_QUBITS}",
36            self.requested
37        )
38    }
39}
40
41impl core::error::Error for TooManyQubits {}
42
43/// The state of an `n`-qubit register as `2^n` complex amplitudes.
44///
45/// Gates change the state in place. Reuse one `StateVector` across runs: [`reset`](Self::reset)
46/// does not allocate. See the [module docs](self) for the qubit order.
47#[derive(Clone, Debug)]
48pub struct StateVector {
49    /// The number of qubits `n`. At most [`MAX_QUBITS`].
50    qubits: usize,
51    /// The amplitudes, indexed by basis state. Always `2^n` entries with norm 1 up to rounding.
52    amplitudes: Vec<Complex>,
53}
54
55impl StateVector {
56    /// Makes an `n`-qubit register in the state `|0…0⟩`.
57    ///
58    /// # Errors
59    ///
60    /// Returns [`TooManyQubits`] when `qubits` is more than [`MAX_QUBITS`].
61    pub fn new(qubits: usize) -> Result<Self, TooManyQubits> {
62        if qubits > MAX_QUBITS {
63            return Err(TooManyQubits { requested: qubits });
64        }
65
66        let mut amplitudes = vec![Complex::ZERO; 1 << qubits];
67        amplitudes[0] = Complex::ONE;
68
69        Ok(Self { qubits, amplitudes })
70    }
71
72    /// Returns the number of qubits.
73    #[must_use]
74    pub fn qubits(&self) -> usize {
75        self.qubits
76    }
77
78    /// Returns the number of basis states, `2^n`.
79    #[must_use]
80    pub fn states(&self) -> usize {
81        self.amplitudes.len()
82    }
83
84    /// Returns the amplitudes, indexed by basis state.
85    #[must_use]
86    pub fn amplitudes(&self) -> &[Complex] {
87        &self.amplitudes
88    }
89
90    /// Sets the register back to `|0…0⟩` without a new allocation.
91    pub fn reset(&mut self) {
92        self.amplitudes.fill(Complex::ZERO);
93        self.amplitudes[0] = Complex::ONE;
94    }
95
96    /// Applies the Hadamard gate to `qubit`.
97    ///
98    /// # Panics
99    ///
100    /// Panics when `qubit` is not less than [`qubits`](Self::qubits).
101    pub fn h(&mut self, qubit: usize) {
102        let bit = self.bit(qubit);
103
104        for zero in (0..self.states()).filter(|index| index & bit == 0) {
105            let a = self.amplitudes[zero];
106            let b = self.amplitudes[zero | bit];
107
108            self.amplitudes[zero] = (a + b).scale(FRAC_1_SQRT_2);
109            self.amplitudes[zero | bit] = (a - b).scale(FRAC_1_SQRT_2);
110        }
111    }
112
113    /// Applies the Pauli-X (NOT) gate to `qubit`.
114    ///
115    /// # Panics
116    ///
117    /// Panics when `qubit` is not less than [`qubits`](Self::qubits).
118    pub fn x(&mut self, qubit: usize) {
119        let bit = self.bit(qubit);
120
121        for zero in (0..self.states()).filter(|index| index & bit == 0) {
122            self.amplitudes.swap(zero, zero | bit);
123        }
124    }
125
126    /// Applies the Pauli-Z gate to `qubit`: the `|1⟩` component changes sign.
127    ///
128    /// # Panics
129    ///
130    /// Panics when `qubit` is not less than [`qubits`](Self::qubits).
131    pub fn z(&mut self, qubit: usize) {
132        self.mcz([qubit]);
133    }
134
135    /// Applies the phase gate `diag(1, e^(i·angle))` to `qubit`, with `angle` in radians.
136    ///
137    /// # Panics
138    ///
139    /// Panics when `qubit` is not less than [`qubits`](Self::qubits).
140    pub fn phase(&mut self, qubit: usize, angle: f64) {
141        let bit = self.bit(qubit);
142        let factor = Complex::from_angle(angle);
143
144        for (_, amplitude) in self.ones_mut(bit) {
145            *amplitude = *amplitude * factor;
146        }
147    }
148
149    /// Applies the multi-controlled Z gate on `qubits`: a basis state changes sign when all
150    /// of these qubits are `1`.
151    ///
152    /// The gate is symmetric, so no qubit is special as the target. One qubit gives `Z`. An
153    /// empty set changes the sign of every state, a global phase without physical effect.
154    ///
155    /// # Panics
156    ///
157    /// Panics when a qubit is not less than [`qubits`](Self::qubits).
158    pub fn mcz(&mut self, qubits: impl IntoIterator<Item = usize>) {
159        let mask = qubits
160            .into_iter()
161            .fold(0, |mask, qubit| mask | self.bit(qubit));
162
163        for (_, amplitude) in self.ones_mut(mask) {
164            *amplitude = -*amplitude;
165        }
166    }
167
168    /// Changes the sign of the amplitude of the basis state `index`.
169    ///
170    /// # Panics
171    ///
172    /// Panics when `index` is not less than [`states`](Self::states).
173    pub(crate) fn negate(&mut self, index: usize) {
174        self.amplitudes[index] = -self.amplitudes[index];
175    }
176
177    /// Returns the measurement probability of each basis state, in index order.
178    pub fn probabilities(&self) -> impl Iterator<Item = f64> + '_ {
179        self.amplitudes.iter().map(|amplitude| amplitude.norm_sqr())
180    }
181
182    /// Measures all qubits once and returns the basis-state index, without a state collapse.
183    ///
184    /// The draw comes from `rng`, so a fixed seed gives a reproducible result. When rounding
185    /// leaves the probabilities a little below 1 in total, the last index takes the rest.
186    pub fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> usize {
187        let draw = unit_f64(rng);
188        let mut cumulative = 0.0;
189
190        for (index, probability) in self.probabilities().enumerate() {
191            cumulative += probability;
192
193            if draw < cumulative {
194                return index;
195            }
196        }
197
198        self.states() - 1
199    }
200
201    /// Returns the index mask of `qubit`.
202    ///
203    /// # Panics
204    ///
205    /// Panics when `qubit` is not less than [`qubits`](Self::qubits).
206    fn bit(&self, qubit: usize) -> usize {
207        assert!(
208            qubit < self.qubits,
209            "qubit {qubit} is outside the {}-qubit register",
210            self.qubits
211        );
212
213        1 << qubit
214    }
215
216    /// Returns the amplitudes of the basis states that have all bits of `mask` set.
217    fn ones_mut(&mut self, mask: usize) -> impl Iterator<Item = (usize, &mut Complex)> {
218        self.amplitudes
219            .iter_mut()
220            .enumerate()
221            .filter(move |(index, _)| index & mask == mask)
222    }
223}
224
225/// Unit tests for the gates and the qubit order.
226#[cfg(test)]
227mod tests {
228    use super::{MAX_QUBITS, StateVector, TooManyQubits};
229    use crate::SplitMix64;
230    use alloc::vec::Vec;
231
232    /// Returns the probabilities of `state` as a vector.
233    fn probabilities(state: &StateVector) -> Vec<f64> {
234        state.probabilities().collect()
235    }
236
237    /// `X` on qubit `q` sets bit `q` of the basis index: the order is little-endian.
238    #[test]
239    fn orders_qubits_little_endian() {
240        let mut state = StateVector::new(3).unwrap();
241        state.x(0);
242        assert_eq!(probabilities(&state)[0b001], 1.0);
243
244        state.reset();
245        state.x(2);
246        assert_eq!(probabilities(&state)[0b100], 1.0);
247
248        state.x(0);
249        assert_eq!(probabilities(&state)[0b101], 1.0);
250    }
251
252    /// `H` gives an even superposition, and a second `H` undoes it.
253    #[test]
254    fn hadamard_is_its_own_inverse() {
255        let mut state = StateVector::new(2).unwrap();
256        state.h(1);
257
258        let even = probabilities(&state);
259        assert!((even[0b00] - 0.5).abs() < 1e-12 && (even[0b10] - 0.5).abs() < 1e-12);
260
261        state.h(1);
262        assert!((probabilities(&state)[0] - 1.0).abs() < 1e-12);
263    }
264
265    /// `Z`, the phase gate and `MCZ` change only the phases of the states they select.
266    #[test]
267    fn phase_gates_select_the_right_states() {
268        let mut state = StateVector::new(2).unwrap();
269        state.h(0);
270        state.h(1);
271        state.mcz([0, 1]);
272
273        let signs: Vec<f64> = state.amplitudes().iter().map(|a| a.re.signum()).collect();
274        assert_eq!(signs, [1.0, 1.0, 1.0, -1.0]);
275
276        state.z(0);
277        state.phase(1, core::f64::consts::PI);
278
279        let signs: Vec<f64> = state.amplitudes().iter().map(|a| a.re.signum()).collect();
280        assert_eq!(signs, [1.0, -1.0, -1.0, -1.0]);
281    }
282
283    /// Seeded samples follow the probabilities and repeat for the same seed.
284    #[test]
285    fn samples_follow_the_probabilities() {
286        let mut state = StateVector::new(1).unwrap();
287        state.phase(0, 1.0);
288        state.h(0);
289
290        let mut rng = SplitMix64::new(42);
291        let ones = (0..10_000).filter(|_| state.sample(&mut rng) == 1).count();
292        assert!((4_800..5_200).contains(&ones), "{ones} ones");
293
294        let first: Vec<usize> = {
295            let mut rng = SplitMix64::new(1);
296            (0..32).map(|_| state.sample(&mut rng)).collect()
297        };
298        let second: Vec<usize> = {
299            let mut rng = SplitMix64::new(1);
300            (0..32).map(|_| state.sample(&mut rng)).collect()
301        };
302        assert_eq!(first, second);
303    }
304
305    /// A register above the limit is an error, not an allocation.
306    #[test]
307    fn rejects_too_many_qubits() {
308        let requested = MAX_QUBITS + 1;
309
310        let error = StateVector::new(requested).unwrap_err();
311
312        assert_eq!(error, TooManyQubits { requested });
313        assert_eq!(
314            alloc::format!("{error}"),
315            "25 qubits requested, but the simulator holds at most 24"
316        );
317    }
318}