1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
//! Abstractions for a quantum circuit
use std::{collections::HashSet, ops::Index};

use crate::gates::mc_apply;
use crate::unitaries::Unitary;
use crate::{
    core::State,
    gates::{apply, c_apply, c_transform_u, cc_apply, transform_u, Gate},
    math::{pow2f, Float, PI},
    measurement::measure_qubit,
};

/// See <https://en.wikipedia.org/wiki/Quantum_register>
#[derive(Clone)]
pub struct QuantumRegister(pub Vec<usize>);

impl Index<usize> for QuantumRegister {
    type Output = usize;

    #[inline]
    fn index(&self, i: usize) -> &Self::Output {
        &self.0[i]
    }
}

impl QuantumRegister {
    /// Create a new QuantumRegister
    pub fn new(size: usize) -> Self {
        assert!(size > 0);
        QuantumRegister((0..size).collect())
    }

    /// The length of the quantum register
    #[allow(clippy::len_without_is_empty)]
    #[inline]
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Update quantum register by shift
    #[inline]
    pub fn update_shift(&mut self, shift: usize) {
        self.0.iter_mut().for_each(|x| *x += shift);
    }

    /// Get the shift size for this register
    #[inline]
    pub fn get_shift(&self) -> usize {
        self[0]
    }
}

/// Control qubits
#[derive(Clone)]
pub enum Controls {
    /// No controls
    None,
    /// Single Control
    Single(usize),
    /// Multiple Controls
    Ones(Vec<usize>),

    /// Mixed Controls
    Mixed {
        /// Control qubits
        controls: Vec<usize>,
        /// Zeroes
        zeros: HashSet<usize>,
    },
}

impl Controls {
    fn from(&self, controls: &[usize], zeros: Option<HashSet<usize>>) -> Self {
        if let Some(zs) = zeros {
            Self::Mixed {
                controls: controls.to_vec(),
                zeros: zs,
            }
        } else if controls.is_empty() {
            Self::None
        } else if controls.len() == 1 {
            Self::Single(controls[0])
        } else {
            Self::Ones(controls.to_vec())
        }
    }

    fn unpack(&self) -> (Vec<usize>, HashSet<usize>) {
        match self {
            Self::None => (vec![], HashSet::new()),
            Self::Single(c0) => (vec![*c0], HashSet::new()),
            Self::Ones(controls) => (controls.clone(), HashSet::new()),
            Self::Mixed { controls, zeros } => (controls.clone(), zeros.clone()),
        }
    }

    fn new_with_control(&self, control: usize, shift: usize) -> Self {
        let (mut controls, mut zeros) = self.unpack();
        controls.iter_mut().for_each(|c| *c += shift);
        controls.push(control);

        if zeros.is_empty() {
            self.from(&controls, None)
        } else {
            zeros = zeros.iter().map(|z| z + shift).collect();
            self.from(&controls, Some(zeros))
        }
    }
}

/// QuantumTransformation to be applied to the State
#[derive(Clone)]
pub struct QuantumTransformation {
    /// The quantum logic gate
    pub gate: Gate,
    /// The target qubits
    pub target: usize,
    /// The control qubits
    pub controls: Controls,
}

struct QubitTracker {
    /// Used to keep track of the qubits that were already measured We can use a u64, since the
    /// number of qubits that one can simulate is very small. Hence, 64 bits suffices to keep
    /// track of all qubits.
    measured_qubits: u64,
    /// Used to keep track of the *values* of qubits that were already measured We can use a u64,
    /// since the number of qubits that one can simulate is very small, and the measured values are
    /// either 0 or 1. Hence, 64 bits suffices to keep track of all measurement values.
    measured_qubits_vals: u64,
}

impl QubitTracker {
    pub fn new() -> Self {
        Self {
            measured_qubits: 0,
            measured_qubits_vals: 0,
        }
    }

    fn is_qubit_measured(&self, target_qubit: usize) -> bool {
        ((self.measured_qubits >> target_qubit) & 1) == 1
    }

    fn get_qubit_measured_val(&mut self, target_qubit: usize) -> Option<u8> {
        if self.is_qubit_measured(target_qubit) {
            ((self.measured_qubits_vals & (1 << target_qubit)) >> target_qubit)
                .try_into()
                .ok()
        } else {
            None
        }
    }

    /// Set the given target qubit as measured
    fn set_measured_qubit(&mut self, target_qubit: usize) {
        self.measured_qubits |= 1 << target_qubit;
    }

    fn set_val_for_measured_qubit(&mut self, target_qubit: usize, value: u8) {
        self.measured_qubits_vals &= !(1 << target_qubit);
        self.measured_qubits_vals |= (value as u64) << target_qubit;
    }
}

/// A model of a Quantum circuit
/// See <https://en.wikipedia.org/wiki/Quantum_circuit>
pub struct QuantumCircuit {
    /// The list of operations to be applied to the State
    pub transformations: Vec<QuantumTransformation>,
    /// The Quantum State to which transformations are applied
    pub state: State,
    /// Tracks measured qubits for dynamic circuits
    qubit_tracker: QubitTracker,
    /// The sizes of the provided quantum registers
    pub quantum_registers_info: Vec<usize>,
}

impl QuantumCircuit {
    /// Create a new QuantumCircuit from multiple QuantumRegisters
    pub fn new(registers: &mut [&mut QuantumRegister]) -> Self {
        let mut bits = 0;

        let mut qr_sizes = Vec::with_capacity(registers.len());

        for r in registers.iter_mut() {
            r.update_shift(bits);
            qr_sizes.push(r.len());
            bits += r.len();
        }
        Self {
            transformations: Vec::new(),
            state: State::new(bits),
            qubit_tracker: QubitTracker::new(),
            quantum_registers_info: qr_sizes,
        }
    }

    /// Get a reference to the Quantum State
    pub fn get_statevector(&self) -> &State {
        &self.state
    }

    // TODO(saveliy): look into fusing the two loops
    /// Invert this circuit
    pub fn inverse(&mut self) {
        self.transformations.reverse();
        self.transformations.iter_mut().for_each(|qt| {
            qt.gate = qt.gate.clone().inverse();
        });
    }

    /// Measure a single qubit
    #[inline]
    pub fn measure(&mut self, target: usize) {
        self.add(QuantumTransformation {
            gate: Gate::M,
            target,
            controls: Controls::None,
        });
    }

    /// Add a SWAP gate that swaps two qubits
    #[inline]
    pub fn swap(&mut self, t0: usize, t1: usize) {
        self.add(QuantumTransformation {
            gate: Gate::SWAP(t0, t1),
            target: 0,
            controls: Controls::None,
        });
    }

    /// Add the X gate for a given target to the list of QuantumTransformations
    #[inline]
    pub fn x(&mut self, target: usize) {
        self.add(QuantumTransformation {
            gate: Gate::X,
            target,
            controls: Controls::None,
        });
    }

    /// Add the Y gate for a given target to the list of QuantumTransformations
    #[inline]
    pub fn y(&mut self, target: usize) {
        self.add(QuantumTransformation {
            gate: Gate::Y,
            target,
            controls: Controls::None,
        });
    }

    /// Add the Rx gate for a given target to the list of QuantumTransformations
    #[inline]
    pub fn rx(&mut self, angle: Float, target: usize) {
        self.add(QuantumTransformation {
            gate: Gate::RX(angle),
            target,
            controls: Controls::None,
        });
    }

    /// Add the CX gate for a given target qubit and control qubit to the list of
    /// QuantumTransformations
    #[inline]
    pub fn cx(&mut self, control: usize, target: usize) {
        self.add(QuantumTransformation {
            gate: Gate::X,
            target,
            controls: Controls::Single(control),
        });
    }

    /// Add the CCX gate for a given target qubit and two control qubits to the list of
    /// QuantumTransformations
    #[inline]
    pub fn ccx(&mut self, control1: usize, control2: usize, target: usize) {
        self.add(QuantumTransformation {
            gate: Gate::X,
            target,
            controls: Controls::Ones(vec![control1, control2]),
        });
    }

    /// Add the Hadamard (H) gate for a given target qubit to the list of QuantumTransformations
    #[inline]
    pub fn h(&mut self, target: usize) {
        self.add(QuantumTransformation {
            gate: Gate::H,
            target,
            controls: Controls::None,
        });
    }

    /// Add a controlled Hadamard gate for a given target qubit and a given control qubit to the list of
    /// QuantumTransformations
    #[inline]
    pub fn ch(&mut self, control: usize, target: usize) {
        self.add(QuantumTransformation {
            gate: Gate::H,
            target,
            controls: Controls::Single(control),
        });
    }

    /// Add Ry gate for a given target qubit to the list of QuantumTransformations
    #[inline]
    pub fn ry(&mut self, angle: Float, target: usize) {
        self.add(QuantumTransformation {
            gate: Gate::RY(angle),
            target,
            controls: Controls::None,
        });
    }

    /// Add CRy gate for a given target qubit and a given control qubit to the list of
    /// QuantumTransformations
    #[inline]
    pub fn cry(&mut self, angle: Float, control: usize, target: usize) {
        self.add(QuantumTransformation {
            gate: Gate::RY(angle),
            target,
            controls: Controls::Single(control),
        });
    }

    /// Add Phase (P) gate for a given target qubit to the list of QuantumTransformations
    #[inline]
    pub fn p(&mut self, angle: Float, target: usize) {
        self.add(QuantumTransformation {
            gate: Gate::P(angle),
            target,
            controls: Controls::None,
        });
    }

    /// Add the Controlled Phase (CP) gate for a given target qubit and a given control qubit to
    /// the list of QuantumTransformations
    #[inline]
    pub fn cp(&mut self, angle: Float, control: usize, target: usize) {
        self.add(QuantumTransformation {
            gate: Gate::P(angle),
            target,
            controls: Controls::Single(control),
        });
    }

    /// Add the Controlled U gate for a given target qubit and a given control qubit to the list of
    /// QuantumTransformations
    #[inline]
    pub fn cu(&mut self, theta: Float, phi: Float, lambda: Float, control: usize, target: usize) {
        self.add(QuantumTransformation {
            gate: Gate::U(theta, phi, lambda),
            target,
            controls: Controls::Single(control),
        });
    }

    /// Add the Controlled Y gate for a given target qubit and a given control qubit to the list of
    /// QuantumTransformations
    #[inline]
    pub fn cy(&mut self, control: usize, target: usize) {
        self.add(QuantumTransformation {
            gate: Gate::Y,
            target,
            controls: Controls::Single(control),
        });
    }

    /// Add the Controlled Rx gate for a given target qubit and a given control qubit to the list of
    /// QuantumTransformations
    #[inline]
    pub fn crx(&mut self, angle: Float, control: usize, target: usize) {
        self.add(QuantumTransformation {
            gate: Gate::RX(angle),
            target,
            controls: Controls::Single(control),
        });
    }

    /// Add Z gate for a given target qubit to the list of QuantumTransformations
    #[inline]
    pub fn z(&mut self, target: usize) {
        self.add(QuantumTransformation {
            gate: Gate::Z,
            target,
            controls: Controls::None,
        });
    }

    /// Add Rz gate for a given target qubit to the list of QuantumTransformations
    #[inline]
    pub fn rz(&mut self, angle: Float, target: usize) {
        self.add(QuantumTransformation {
            gate: Gate::RZ(angle),
            target,
            controls: Controls::None,
        });
    }

    /// Add the Controlled Rz gate for a given target qubit and a given control qubit to the list of
    /// QuantumTransformations
    #[inline]
    pub fn crz(&mut self, angle: Float, control: usize, target: usize) {
        self.add(QuantumTransformation {
            gate: Gate::RZ(angle),
            target,
            controls: Controls::Single(control),
        });
    }

    /// Add the U gate for a given target to the list of QuantumTransformations
    #[inline]
    pub fn u(&mut self, theta: Float, phi: Float, lambda: Float, target: usize) {
        self.add(QuantumTransformation {
            gate: Gate::U(theta, phi, lambda),
            target,
            controls: Controls::None,
        });
    }

    /// Add the bit flip noise gate for a given target qubit, given a probability
    // TODO(saveliy) this can potentially be optimized by checking the probability here,
    // and then add the X gate, if it evaluates the true. The advantage is for the case
    // where the overall number of `QuantumTransformation`s is large, and/or the
    // probability of bitflip bit is trivial.
    #[inline]
    pub fn bit_flip_noise(&mut self, prob: Float, target: usize) {
        self.add(QuantumTransformation {
            gate: Gate::BitFlipNoise(prob),
            target,
            controls: Controls::None,
        });
    }

    /// Add all transformations for an inverse Quantum Fourier Transform to the list of QuantumTransformations
    #[inline]
    pub fn iqft(&mut self, targets: &[usize]) {
        for j in (0..targets.len()).rev() {
            self.h(targets[j]);
            for k in (0..j).rev() {
                self.cp(-PI / pow2f(j - k), targets[j], targets[k]);
            }
        }
    }

    /// Append a QuantumCircuit to the given register of *this* QuantumCircuit
    pub fn append(&mut self, circuit: &QuantumCircuit, reg: &QuantumRegister) {
        assert_eq!(
            reg.len(),
            circuit.quantum_registers_info.iter().sum::<usize>()
        );
        for tr in circuit.transformations.iter() {
            self.add(QuantumTransformation {
                gate: tr.gate.clone(),
                target: reg.get_shift() + tr.target,
                controls: tr.controls.clone(),
            });
        }
    }

    /// Append a QuantumCircuit to the given register of *this* QuantumCircuit
    pub fn c_append(&mut self, circuit: &QuantumCircuit, c: usize, reg: &QuantumRegister) {
        assert!(!std::ops::Range {
            start: reg.get_shift(),
            end: reg.get_shift() + reg.len()
        }
        .contains(&c));
        for tr in circuit.transformations.iter() {
            self.add(QuantumTransformation {
                gate: tr.gate.clone(),
                target: reg.get_shift() + tr.target,
                controls: tr.controls.new_with_control(c, reg.get_shift()),
            });
        }
    }

    /// Append a QuantumCircuit to the given register of *this* QuantumCircuit
    pub fn mc_append(
        &mut self,
        circuit: &QuantumCircuit,
        controls: &[usize],
        reg: &QuantumRegister,
    ) {
        let hashed_controls: HashSet<_> = controls.iter().copied().collect();

        assert_eq!(controls.len(), hashed_controls.len());
        let range = std::ops::Range {
            start: reg.get_shift(),
            end: reg.get_shift() + reg.len(),
        };

        controls.iter().for_each(|c| {
            if range.contains(c) {
                panic!(
                    "control {} should not be in: Range(start: {} end: {})",
                    c, range.start, range.end
                );
            }
        });

        for control in controls.iter() {
            for tr in circuit.transformations.iter() {
                self.add(QuantumTransformation {
                    gate: tr.gate.clone(),
                    target: reg.get_shift() + tr.target,
                    controls: tr.controls.new_with_control(*control, reg.get_shift()),
                });
            }
        }
    }

    /// Add a Unitary for a given target qubit to the list of QuantumTransformations
    pub fn unitary(&mut self, u: Unitary, target: usize) {
        self.add(QuantumTransformation {
            gate: Gate::Unitary(u),
            target,
            controls: Controls::None,
        });
    }

    /// Append a `Unitary` to a `QuantumRegister`
    pub fn append_u(&mut self, u: Unitary, qr: &QuantumRegister) {
        assert_eq!(u.height, u.width);
        assert_eq!(u.height, 1 << qr.len());
        self.unitary(u, qr.get_shift());
    }

    /// Add a controlled Unitary for a given target qubit to the list of QuantumTransformations
    pub fn c_unitary(&mut self, u: Unitary, c: usize, t: usize) {
        self.add(QuantumTransformation {
            gate: Gate::Unitary(u),
            target: t,
            controls: Controls::Single(c),
        });
    }

    /// Append a controlled `Unitary` to a `QuantumRegister`
    pub fn c_append_u(&mut self, u: Unitary, c: usize, qr: &QuantumRegister) {
        assert_eq!(u.height, u.width);
        assert_eq!(u.height, 1 << qr.len());
        self.c_unitary(u, c, qr.get_shift());
    }

    /// Add a given `QuantumTransformation` to the list of transformations
    #[inline]
    pub fn add(&mut self, transformation: QuantumTransformation) {
        self.transformations.push(transformation);
    }

    /// Run the list of transformations against the State
    pub fn execute(&mut self) {
        for tr in self.transformations.drain(..) {
            match (&tr.controls, tr.gate) {
                (Controls::None, Gate::Unitary(u)) => transform_u(&mut self.state, &u, tr.target),
                (Controls::Single(c), Gate::Unitary(u)) => {
                    c_transform_u(&mut self.state, &u, *c, tr.target)
                }
                (Controls::None, Gate::M) => {
                    if !self.qubit_tracker.is_qubit_measured(tr.target) {
                        let value = measure_qubit(&mut self.state, tr.target, true, None);
                        self.qubit_tracker.set_measured_qubit(tr.target);
                        self.qubit_tracker
                            .set_val_for_measured_qubit(tr.target, value);
                    }
                }
                (Controls::None, gate) => {
                    apply(gate, &mut self.state, tr.target);
                }
                (Controls::Single(control), gate) => {
                    if let Some(c_bit) = self.qubit_tracker.get_qubit_measured_val(*control) {
                        if c_bit == 1 {
                            apply(gate, &mut self.state, tr.target);
                        }
                    } else {
                        c_apply(gate, &mut self.state, *control, tr.target);
                    }
                }
                (Controls::Ones(controls), Gate::X) => {
                    cc_apply(
                        Gate::X,
                        &mut self.state,
                        controls[0],
                        controls[1],
                        tr.target,
                    );
                }
                (Controls::Mixed { controls, zeros }, gate) => {
                    mc_apply(
                        gate,
                        &mut self.state,
                        controls,
                        Some(zeros.to_owned()),
                        tr.target,
                    );
                }
                _ => todo!(),
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::utils::to_table;
    use crate::{
        math::modulus,
        utils::{assert_float_closeness, gen_random_state, swap},
    };

    #[test]
    fn register_shift() {
        const N: usize = 4;
        let mut qr = QuantumRegister::new(N);
        assert_eq!(qr.get_shift(), 0);

        qr.update_shift(4);
        assert_eq!(qr.get_shift(), 4);
    }

    #[test]
    fn value_encoding() {
        let v = 2.4;
        let n = 3;

        let mut q = QuantumRegister::new(n);
        let mut qc = QuantumCircuit::new(&mut [&mut q]);

        for i in 0..n {
            qc.h(i)
        }

        for i in 0..n {
            qc.p((2 as Float) * PI / pow2f(i + 1) * v, i)
        }

        let targets: Vec<usize> = (0..n).rev().collect();
        qc.iqft(&targets);
        qc.execute();
    }

    #[test]
    fn z_gate() {
        let n = 2;
        let mut q = QuantumRegister::new(n);
        let mut qc = QuantumCircuit::new(&mut [&mut q]);

        for i in 0..n {
            qc.h(i)
        }

        qc.z(0);

        qc.execute();
    }

    #[test]
    fn crx() {
        let n = 3;
        let mut q = QuantumRegister::new(n);
        let mut qc = QuantumCircuit::new(&mut [&mut q]);

        for i in 0..n {
            qc.h(i)
        }

        let mut t = 0;
        while t < n - 1 {
            qc.crx(3.043, t, t + 1);
            t += 2;
        }

        qc.execute();
    }

    #[test]
    fn ch() {
        let n = 3;
        let mut state = State::new(n);

        for target in 0..n {
            apply(Gate::H, &mut state, target);
        }
        c_apply(Gate::H, &mut state, 0, 1);

        let mut q = QuantumRegister::new(n);
        let mut qc = QuantumCircuit::new(&mut [&mut q]);
        for target in 0..n {
            qc.h(target);
        }
        qc.ch(0, 1);
        qc.execute();

        assert_eq!(qc.state.reals, state.reals);
        assert_eq!(qc.state.imags, state.imags);
    }

    #[test]
    fn crz() {
        let n = 3;
        let mut state = State::new(n);

        for target in 0..n {
            apply(Gate::H, &mut state, target);
        }
        c_apply(Gate::RZ(PI / 2.0), &mut state, 0, 1);

        let mut q = QuantumRegister::new(n);
        let mut qc = QuantumCircuit::new(&mut [&mut q]);
        for target in 0..n {
            qc.h(target);
        }
        qc.crz(PI / 2.0, 0, 1);
        qc.execute();

        assert_eq!(qc.state.reals, state.reals);
        assert_eq!(qc.state.imags, state.imags);
    }

    #[test]
    fn cy() {
        let n = 3;
        let mut q = QuantumRegister::new(n);
        let mut qc = QuantumCircuit::new(&mut [&mut q]);

        for i in 0..n {
            qc.h(i)
        }

        let mut t = 0;
        while t < n - 1 {
            qc.cy(t, t + 1);
            t += 2;
        }

        qc.execute();
    }

    #[test]
    fn ccx() {
        let n = 3;
        let mut q = QuantumRegister::new(n);
        let mut qc = QuantumCircuit::new(&mut [&mut q]);

        for i in 0..n - 1 {
            qc.h(i)
        }

        qc.ccx(0, 1, 2);

        qc.execute();
        let _state = qc.get_statevector();
    }

    #[test]
    fn x_gate() {
        let n = 2;
        let mut q = QuantumRegister::new(n);
        let mut qc = QuantumCircuit::new(&mut [&mut q]);

        for i in 0..n {
            qc.h(i)
        }

        qc.rx(PI / 2.0, 0);
        qc.execute();
    }

    #[test]
    fn all_gates_as_transformations() {
        const N: usize = 17;
        let mut q = QuantumRegister::new(N);
        let mut qc = QuantumCircuit::new(&mut [&mut q]);

        for t in 0..N {
            qc.h(t)
        }

        qc.x(0);
        qc.y(1);
        qc.z(2);
        qc.p(PI, 3);
        qc.cp(PI, 3, 4);
        qc.rx(PI, 5);
        qc.ry(PI, 6);
        qc.rz(PI, 7);
        qc.u(PI, PI, PI, 8);
        qc.cy(9, 10);
        qc.crx(PI, 11, 12);
        qc.cry(PI, 13, 14);
        qc.execute();

        let mut state = State::new(N);
        for t in 0..N {
            apply(Gate::H, &mut state, t);
        }

        apply(Gate::X, &mut state, 0);
        apply(Gate::Y, &mut state, 1);
        apply(Gate::Z, &mut state, 2);
        apply(Gate::P(PI), &mut state, 3);
        c_apply(Gate::P(PI), &mut state, 3, 4);
        apply(Gate::RX(PI), &mut state, 5);
        apply(Gate::RY(PI), &mut state, 6);
        apply(Gate::RZ(PI), &mut state, 7);
        apply(Gate::U(PI, PI, PI), &mut state, 8);
        c_apply(Gate::Y, &mut state, 9, 10);
        c_apply(Gate::RX(PI), &mut state, 11, 12);
        c_apply(Gate::RY(PI), &mut state, 13, 14);

        state
            .reals
            .iter()
            .zip(state.imags.iter())
            .zip(qc.state.reals.iter())
            .zip(qc.state.imags.iter())
            .for_each(|(((s_re, s_im), qc_re), qc_im)| {
                assert_float_closeness(*qc_re, *s_re, 0.001);
                assert_float_closeness(*qc_im, *s_im, 0.001);
            });
    }

    #[test]
    fn measure() {
        const N: usize = 21;
        let state = gen_random_state(N);

        let sum = state
            .reals
            .iter()
            .zip(state.imags.iter())
            .map(|(re, im)| modulus(*re, *im).powi(2))
            .sum();

        // Make sure the generated random state is sound
        assert_float_closeness(sum, 1.0, 0.001);

        let mut qc = QuantumCircuit {
            state,
            transformations: Vec::new(),
            qubit_tracker: QubitTracker::new(),
            quantum_registers_info: Vec::new(),
        };

        // Add Measure gates for all the qubits
        for target in 0..N {
            qc.measure(target);
        }

        // Execute the circuit
        qc.execute();

        // Allocate stack storage of measured qubit values
        let mut measured_vals = [0; N];

        // Now collect the measured values
        for (target, measured_val) in measured_vals.iter_mut().enumerate() {
            let val = qc
                .qubit_tracker
                .get_qubit_measured_val(target)
                .expect("qubit: {target} should be measured");
            *measured_val = val;
        }

        // Now we need to measure again...

        // Add Measure gates for all the qubits
        for target in 0..N {
            qc.measure(target);
        }

        // Execute the circuit
        qc.execute();

        // Now check that the new measured values are the same as what we got before
        for (target, measured_val) in measured_vals.iter().enumerate() {
            assert!(
                qc.qubit_tracker.is_qubit_measured(target),
                "qubit {target} was already measured, but it wasn't marked as measured"
            );
            assert_eq!(
                *measured_val,
                qc.qubit_tracker
                    .get_qubit_measured_val(target)
                    .expect("qubit: {target} should be measured")
            );
        }
    }

    #[test]
    fn swap_all_qubits() {
        const N: usize = 9;
        let mut qc = QuantumCircuit {
            state: gen_random_state(N),
            transformations: Vec::new(),
            qubit_tracker: QubitTracker::new(),
            quantum_registers_info: Vec::new(),
        };

        let sum = qc
            .state
            .reals
            .iter()
            .zip(qc.state.imags.iter())
            .map(|(re, im)| modulus(*re, *im).powi(2))
            .sum();

        // Make sure the generated random state is sound
        assert_float_closeness(sum, 1.0, 0.001);

        let mut state = qc.state.clone();

        // Add swap gates, for pairs of qubits, to the circuit. Simultaneously, directly apply swap
        // to the lone state (using the 3 CX gate implementation)
        for i in 0..(N >> 1) {
            qc.swap(i, N - 1 - i);
            swap(&mut state, i, N - 1 - i);
        }

        qc.execute();

        assert_eq!(qc.state.n, state.n);
        assert_eq!(qc.state.reals, state.reals);
        assert_eq!(qc.state.imags, state.imags);
    }

    #[test]
    fn inverse_iqft() {
        const N: usize = 2;
        let original_state = gen_random_state(N);
        let mut qc1 = QuantumCircuit {
            state: original_state.clone(),
            transformations: Vec::new(),
            qubit_tracker: QubitTracker::new(),
            quantum_registers_info: Vec::new(),
        };

        // First we apply iqft to all qubits
        let targets: Vec<_> = (0..N).rev().collect();
        qc1.iqft(&targets);
        qc1.execute();

        // Next, we apply inverse of iqft to all qubits
        qc1.iqft(&targets);
        qc1.inverse();
        qc1.execute();

        // Check that after applying iqft and iqft inverse, we get the original state back
        original_state
            .reals
            .iter()
            .zip(original_state.imags.iter())
            .zip(qc1.state.reals.iter())
            .zip(qc1.state.imags.iter())
            .for_each(|(((os_re, os_im), qc1_re), qc1_im)| {
                assert_float_closeness(*qc1_re, *os_re, 0.001);
                assert_float_closeness(*qc1_im, *os_im, 0.001);
            });
    }

    #[test]
    fn inverse() {
        const N: usize = 2;
        let mut qc1 = QuantumCircuit {
            state: State::new(N),
            transformations: Vec::new(),
            qubit_tracker: QubitTracker::new(),
            quantum_registers_info: Vec::new(),
        };

        qc1.h(0);
        qc1.p(PI / 4.0, 1);
        qc1.inverse();
        qc1.execute();

        let mut qc2 = QuantumCircuit {
            state: State::new(N),
            transformations: Vec::new(),
            qubit_tracker: QubitTracker::new(),
            quantum_registers_info: Vec::new(),
        };
        qc2.p(-(PI / 4.0), 1);
        qc2.h(0);
        qc2.execute();

        assert_eq!(qc1.state.reals, qc2.state.reals);
        assert_eq!(qc1.state.imags, qc2.state.imags);
    }

    // Helper function for testing QuantumCircuit *append methods
    fn gate_to_single_qubit_circuit(gate: Gate) -> QuantumCircuit {
        let mut qr = QuantumRegister::new(1);
        let mut qc = QuantumCircuit::new(&mut [&mut qr]);
        qc.add(QuantumTransformation {
            gate,
            target: 0,
            controls: Controls::None,
        });
        qc
    }

    // Helper function for testing `QuantumCircuit`'s `append` method
    fn gate_to_circuit(gate: Gate, n: usize, target: usize) -> QuantumCircuit {
        let mut qr = QuantumRegister::new(n);
        let mut qc = QuantumCircuit::new(&mut [&mut qr]);
        qc.add(QuantumTransformation {
            gate,
            target,
            controls: Controls::None,
        });
        qc
    }

    // Helper function for creating an IQFT circuit for testing `QuantumCicuit`'s
    // `append` method
    fn iqft_circuit(n: usize) -> QuantumCircuit {
        let mut iqft_qr = QuantumRegister::new(n);
        let mut iqft_qc = QuantumCircuit::new(&mut [&mut iqft_qr]);
        let targets: Vec<usize> = (0..n).rev().collect();
        iqft_qc.iqft(&targets);
        iqft_qc
    }

    // Helper function for creating an IQFT circuit for testing `QuantumCircuit`'s
    // `c_append` or `mc_append` method
    fn iqft_circuit_from_controlled_append(n: usize, multi_control: bool) -> QuantumCircuit {
        let mut iqft_qr = QuantumRegister::new(n);
        let mut iqft_qc = QuantumCircuit::new(&mut [&mut iqft_qr]);
        let targets: Vec<usize> = (0..n).rev().collect();

        for j in (0..targets.len()).rev() {
            iqft_qc.append(&gate_to_circuit(Gate::H, n, targets[j]), &iqft_qr);
            for k in (0..j).rev() {
                let mut qr = QuantumRegister::new(1);
                qr.update_shift(targets[k]);
                if multi_control {
                    iqft_qc.mc_append(
                        &gate_to_single_qubit_circuit(Gate::P(-PI / pow2f(j - k))),
                        &[targets[j]],
                        &qr,
                    );
                } else {
                    iqft_qc.c_append(
                        &gate_to_single_qubit_circuit(Gate::P(-PI / pow2f(j - k))),
                        targets[j],
                        &qr,
                    );
                }
            }
        }
        iqft_qc
    }

    #[test]
    fn append() {
        let mut qr0 = QuantumRegister::new(1);
        let mut qr1 = QuantumRegister::new(1);
        let mut qc = QuantumCircuit::new(&mut [&mut qr0, &mut qr1]);
        qc.append(&gate_to_single_qubit_circuit(Gate::H), &qr0);
        qc.append(&gate_to_single_qubit_circuit(Gate::H), &qr1);
        qc.execute();

        qc.state
            .reals
            .iter()
            .zip(qc.state.imags.iter())
            .for_each(|(z_re, z_im)| {
                assert_float_closeness(*z_re, 0.5, 0.0001);
                assert_float_closeness(*z_im, 0.0, 0.0001);
            });
        println!("{}", to_table(&qc.state));
    }

    #[test]
    fn append_value_encoding() {
        let n = 3;
        let v = 4.0;
        let mut qr = QuantumRegister::new(n);
        let mut qc = QuantumCircuit::new(&mut [&mut qr]);

        for t in 0..n {
            qc.append(&gate_to_circuit(Gate::H, n, t), &qr);
        }
        for t in 0..n {
            qc.append(
                &gate_to_circuit(Gate::P(2.0 * PI / (pow2f(t + 1)) * v), n, t),
                &qr,
            );
        }

        let iqft_qc = iqft_circuit(n);
        qc.append(&iqft_qc, &qr);
        qc.execute();

        let encoded_integer = v as usize;

        qc.state
            .reals
            .iter()
            .zip(qc.state.imags.iter())
            .enumerate()
            .for_each(|(i, (z_re, z_im))| {
                if i == encoded_integer {
                    assert_float_closeness(*z_re, 1.0, 0.0001);
                    assert_float_closeness(*z_im, 0.0, 0.0001);
                } else {
                    assert_float_closeness(*z_re, 0.0, 0.0001);
                    assert_float_closeness(*z_im, 0.0, 0.0001);
                }
            });
        println!("{}", to_table(&qc.state));
    }

    #[test]
    fn c_append_value_encoding() {
        let n = 3;
        let v = 4.0;
        let mut qr = QuantumRegister::new(n);
        let mut qc = QuantumCircuit::new(&mut [&mut qr]);

        for t in 0..n {
            qc.append(&gate_to_circuit(Gate::H, n, t), &qr);
        }
        for t in 0..n {
            qc.append(
                &gate_to_circuit(Gate::P(2.0 * PI / (pow2f(t + 1)) * v), n, t),
                &qr,
            );
        }

        let iqft_qc = iqft_circuit_from_controlled_append(n, false);
        qc.append(&iqft_qc, &qr);
        qc.execute();
        let encoded_integer = v as usize;

        qc.state
            .reals
            .iter()
            .zip(qc.state.imags.iter())
            .enumerate()
            .for_each(|(i, (z_re, z_im))| {
                if i == encoded_integer {
                    assert_float_closeness(*z_re, 1.0, 0.0001);
                    assert_float_closeness(*z_im, 0.0, 0.0001);
                } else {
                    assert_float_closeness(*z_re, 0.0, 0.0001);
                    assert_float_closeness(*z_im, 0.0, 0.0001);
                }
            });
        println!("{}", to_table(&qc.state));
    }

    #[test]
    fn mc_append_value_encoding() {
        let n = 3;
        let v = 4.0;
        let mut qr = QuantumRegister::new(n);
        let mut qc = QuantumCircuit::new(&mut [&mut qr]);

        for t in 0..n {
            qc.append(&gate_to_circuit(Gate::H, n, t), &qr);
        }
        for t in 0..n {
            qc.append(
                &gate_to_circuit(Gate::P(2.0 * PI / (pow2f(t + 1)) * v), n, t),
                &qr,
            );
        }

        let iqft_qc = iqft_circuit_from_controlled_append(n, true);
        qc.append(&iqft_qc, &qr);
        qc.execute();

        let encoded_integer = v as usize;

        qc.state
            .reals
            .iter()
            .zip(qc.state.imags.iter())
            .enumerate()
            .for_each(|(i, (z_re, z_im))| {
                if i == encoded_integer {
                    assert_float_closeness(*z_re, 1.0, 0.0001);
                    assert_float_closeness(*z_im, 0.0, 0.0001);
                } else {
                    assert_float_closeness(*z_re, 0.0, 0.0001);
                    assert_float_closeness(*z_im, 0.0, 0.0001);
                }
            });
        println!("{}", to_table(&qc.state));
    }

    #[test]
    fn bit_flip_noise() {
        const N: usize = 1;
        let state = gen_random_state(N);

        let mut qc1 = QuantumCircuit {
            state: state.clone(),
            transformations: Vec::new(),
            qubit_tracker: QubitTracker::new(),
            quantum_registers_info: Vec::new(),
        };

        let mut qc2 = QuantumCircuit {
            state,
            transformations: Vec::new(),
            qubit_tracker: QubitTracker::new(),
            quantum_registers_info: Vec::new(),
        };

        // Sanity checks
        assert_eq!(qc1.state.reals, qc2.state.reals);
        assert_eq!(qc1.state.imags, qc2.state.imags);

        for target in 0..N {
            qc2.bit_flip_noise(0.0, target);
        }

        // BitFlipNoise with prob==0.0 should not change anything
        assert_eq!(qc1.state.reals, qc2.state.reals);
        assert_eq!(qc1.state.imags, qc2.state.imags);

        // BitFlipNoise with prob==1.0 should be equivalent to applying the X gate
        for target in 0..N {
            qc1.x(target);
            qc2.bit_flip_noise(1.0, target);
        }
        assert_eq!(qc1.state.reals, qc2.state.reals);
        assert_eq!(qc1.state.imags, qc2.state.imags);
    }

    #[test]
    fn controlled_u() {
        const N: usize = 3;
        let mut qr = QuantumRegister::new(N);
        let mut qc = QuantumCircuit::new(&mut [&mut qr]);

        let (control, target) = (0, 1);
        qc.cu(1.0, 2.0, 3.0, control, target);
        qc.execute();

        let mut state = State::new(N);
        c_apply(Gate::U(1.0, 2.0, 3.0), &mut state, control, target);

        assert_eq!(qc.state.n, state.n);
        assert_eq!(qc.state.reals, state.reals);
        assert_eq!(qc.state.imags, state.imags);
    }
}