quantum_planning/
state.rs1use 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
21pub const MAX_QUBITS: usize = 24;
23
24#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26pub struct TooManyQubits {
27 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#[derive(Clone, Debug)]
48pub struct StateVector {
49 qubits: usize,
51 amplitudes: Vec<Complex>,
53}
54
55impl StateVector {
56 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 #[must_use]
74 pub fn qubits(&self) -> usize {
75 self.qubits
76 }
77
78 #[must_use]
80 pub fn states(&self) -> usize {
81 self.amplitudes.len()
82 }
83
84 #[must_use]
86 pub fn amplitudes(&self) -> &[Complex] {
87 &self.amplitudes
88 }
89
90 pub fn reset(&mut self) {
92 self.amplitudes.fill(Complex::ZERO);
93 self.amplitudes[0] = Complex::ONE;
94 }
95
96 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 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 pub fn z(&mut self, qubit: usize) {
132 self.mcz([qubit]);
133 }
134
135 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 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 pub(crate) fn negate(&mut self, index: usize) {
174 self.amplitudes[index] = -self.amplitudes[index];
175 }
176
177 pub fn probabilities(&self) -> impl Iterator<Item = f64> + '_ {
179 self.amplitudes.iter().map(|amplitude| amplitude.norm_sqr())
180 }
181
182 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 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 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#[cfg(test)]
227mod tests {
228 use super::{MAX_QUBITS, StateVector, TooManyQubits};
229 use crate::SplitMix64;
230 use alloc::vec::Vec;
231
232 fn probabilities(state: &StateVector) -> Vec<f64> {
234 state.probabilities().collect()
235 }
236
237 #[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 #[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 #[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 #[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 #[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}