1use num_complex::Complex;
30use std::f64::consts::SQRT_2;
31use tpt_math_prob_core::Rng;
32
33const INV_SQRT2: f64 = 1.0 / SQRT_2;
35
36pub mod tensor;
38pub use tensor::{Circuit, embed_gate_2x2, kron};
39
40pub mod density;
42pub use density::{DensityMatrix, Matrix};
43
44pub mod error;
46pub use error::StateError;
47
48#[derive(Clone, Debug, PartialEq)]
54pub struct State {
55 amps: Vec<Complex<f64>>,
56}
57
58impl State {
59 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 pub fn zero(n: usize) -> Result<Self, StateError> {
91 Self::new(n)
92 }
93
94 #[must_use]
96 pub fn n_qubits(&self) -> usize {
97 self.amps.len().trailing_zeros() as usize
98 }
99
100 #[must_use]
102 pub fn amplitudes(&self) -> &[Complex<f64>] {
103 &self.amps
104 }
105
106 #[must_use]
112 pub fn amplitude(&self, index: usize) -> Complex<f64> {
113 self.amps[index]
114 }
115
116 #[must_use]
120 pub fn probabilities(&self) -> Vec<f64> {
121 self.amps.iter().map(Complex::norm_sqr).collect()
122 }
123
124 #[must_use]
126 pub fn norm(&self) -> f64 {
127 self.amps.iter().map(Complex::norm_sqr).sum::<f64>().sqrt()
128 }
129
130 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 #[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 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 self.amps[idx] = amp.scale(1.0 / norm);
212 }
213 idx
214 }
215
216 #[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 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 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 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 pub fn h(&mut self, qubit: usize) -> Result<(), StateError> {
334 self.apply_single(&H, qubit)
335 }
336
337 pub fn x(&mut self, qubit: usize) -> Result<(), StateError> {
343 self.apply_single(&X, qubit)
344 }
345
346 pub fn y(&mut self, qubit: usize) -> Result<(), StateError> {
352 self.apply_single(&Y, qubit)
353 }
354
355 pub fn z(&mut self, qubit: usize) -> Result<(), StateError> {
361 self.apply_single(&Z, qubit)
362 }
363
364 pub fn s(&mut self, qubit: usize) -> Result<(), StateError> {
370 self.apply_single(&S, qubit)
371 }
372
373 pub fn t(&mut self, qubit: usize) -> Result<(), StateError> {
379 self.apply_single(&T, qubit)
380 }
381
382 pub fn cnot(&mut self, control: usize, target: usize) -> Result<(), StateError> {
389 self.apply_cnot(control, target)
390 }
391}
392
393pub 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
401pub 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
409pub 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
417pub 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
425pub 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
433pub 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 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 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 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 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 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 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 let mut s = State::new(2).unwrap();
592 s.x(0).unwrap(); s.apply_controlled(0, 1, &X).unwrap();
594 assert_abs_diff_eq!(s.amplitude(3).re, 1.0, epsilon = TOL);
595
596 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 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}