q1tsim 0.5.0

A simple, efficient, quantum computer simulator.
Documentation
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
// Copyright 2019 Q1t BV
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::stabilizer::{MeasurementInfo, StabilizerTableau};

pub struct StabilizerState
{
    /// The number of qubits in this state
    nr_bits: usize,
    /// The number of separate runs for evolving this state
    nr_shots: usize,
    /// Run counts for each quantum state
    counts: Vec<usize>,
    /// The quantum states themselves
    tableaus: Vec<StabilizerTableau>
}

impl StabilizerState
{
    /// Create a new quantum state of `nr_bits` qubits, all initialized to |0⟩,
    /// which will be measured `nr_shots` times.
    pub fn new(nr_bits: usize, nr_shots: usize) -> Self
    {
        StabilizerState
        {
            nr_bits: nr_bits,
            nr_shots: nr_shots,
            counts: vec![nr_shots],
            tableaus: vec![StabilizerTableau::new(nr_bits)]
        }
    }
}

impl crate::qustate::QuState for StabilizerState
{
    fn apply_gate<G>(&mut self, gate: &G, bits: &[usize]) -> crate::error::Result<()>
    where G: crate::gates::Gate + ?Sized
    {
        for t in self.tableaus.iter_mut()
        {
            t.apply_gate(gate, bits)?;
        }
        Ok(())
    }

    fn apply_unary_gate_all<G>(&mut self, gate: &G) -> crate::error::Result<()>
    where G: crate::gates::Gate + ?Sized
    {
        // XXX FIXME: this can possibly be done smarter
        for bit in 0..self.nr_bits
        {
            self.apply_gate(gate, &[bit])?;
        }
        Ok(())
    }

    fn apply_conditional_gate<G>(&mut self, control: &[bool], gate: &G,
        bits: &[usize]) -> crate::error::Result<()>
    where G: crate::gates::Gate + ?Sized
    {
        if control.len() != self.nr_shots
        {
            return Err(crate::error::Error::InvalidNrControlBits(control.len(),
                self.nr_shots, String::from(gate.description())));
        }

        let ranges = crate::qustate::collect_conditional_ranges(&self.counts,
            control);
        let mut new_tableaus = Vec::with_capacity(ranges.len());
        for &(icol, _, apply) in ranges.iter()
        {
            let mut tableau = self.tableaus[icol].clone();
            if apply
            {
                tableau.apply_gate(gate, bits)?;
            }
            new_tableaus.push(tableau);
        }

        self.tableaus = new_tableaus;
        self.counts = ranges.iter().map(|t| t.1).collect();

        Ok(())
    }

    fn measure<R: rand::Rng>(&mut self, qbit: usize, rng: &mut R)
        -> crate::error::Result<ndarray::Array1<u64>>
    {
        let mut res = ndarray::Array1::zeros(self.nr_shots);
        self.measure_into(qbit, 0, &mut res, rng)?;
        Ok(res)
    }

    fn measure_into<R: rand::Rng>(&mut self, qbit: usize, cbit: usize,
        res: &mut ndarray::Array1<u64>, rng: &mut R) -> crate::error::Result<()>
    {
        if qbit >= self.nr_bits
        {
            return Err(crate::error::Error::InvalidQBit(qbit));
        }
        if res.len() < self.nr_shots
        {
            return Err(crate::error::Error::NotEnoughSpace(res.len(), self.nr_shots));
        }

        let one_mask = 1 << cbit;
        let zero_mask = !one_mask;

        let mut new_tableaus = vec![];
        let mut new_counts = vec![];
        let mut res_start = 0;
        for (mut tableau, &count) in self.tableaus.drain(..).zip(self.counts.iter())
        {
            match tableau.measure(qbit)
            {
                MeasurementInfo::Deterministic(value) => {
                    new_tableaus.push(tableau);
                    new_counts.push(count);

                    // Store the result.
                    if value
                    {
                        res.slice_mut(s![res_start..res_start+count]).map_inplace(
                            |b| *b |= one_mask
                        );
                    }
                    else
                    {
                        res.slice_mut(s![res_start..res_start+count]).map_inplace(
                            |b| *b &= zero_mask
                        );
                    }
                },
                MeasurementInfo::Random(i) => {
                    let distribution = rand_distr::Binomial::new(count as u64, 0.5).unwrap();
                    let n0 = rng.sample(distribution) as usize;

                    if n0 == 0
                    {
                        tableau.collapse(i, qbit, true);
                        new_tableaus.push(tableau);
                        new_counts.push(count);
                    }
                    else if n0 == count
                    {
                        tableau.collapse(i, qbit, false);
                        new_tableaus.push(tableau);
                        new_counts.push(count);
                    }
                    else
                    {
                        let mut t0 = tableau.clone();
                        t0.collapse(i, qbit, false);
                        tableau.collapse(i, qbit, true);
                        new_tableaus.push(t0);
                        new_tableaus.push(tableau);
                        new_counts.push(n0);
                        new_counts.push(count - n0);
                    }

                    // Store the result.
                    res.slice_mut(s![res_start..res_start+n0]).map_inplace(
                        |b| *b &= zero_mask
                    );
                    res.slice_mut(s![res_start+n0..res_start+count]).map_inplace(
                        |b| *b |= one_mask
                    );
                }
            }

            res_start += count;
        }

        self.counts = new_counts;
        self.tableaus = new_tableaus;

        Ok(())
    }

    fn measure_all<R: rand::Rng>(&mut self, rng: &mut R)
        -> crate::error::Result<ndarray::Array1<u64>>
    {
        let mut res = ndarray::Array1::zeros(self.nr_shots);
        let cbits: Vec<usize> = (0..self.nr_bits).collect();
        self.measure_all_into(&cbits, &mut res, rng)?;
        Ok(res)
    }

    fn measure_all_into<R: rand::Rng>(&mut self, cbits: &[usize],
        res: &mut ndarray::Array1<u64>, rng: &mut R) -> crate::error::Result<()>
    {
        // There does not seem to be a simpler way to measure all qubits from
        // a tableau, as there is for a vector state. So simply loop over all
        // bits
        for (qbit, &cbit) in cbits.iter().enumerate()
        {
            self.measure_into(qbit, cbit, res, rng)?;
        }
        Ok(())
    }

    fn peek_into<R: rand::Rng>(&self, qbit: usize, cbit: usize,
        res: &mut ndarray::Array1<u64>, rng: &mut R) -> crate::error::Result<()>
    {
        if qbit >= self.nr_bits
        {
            return Err(crate::error::Error::InvalidQBit(qbit));
        }
        if res.len() < self.nr_shots
        {
            return Err(crate::error::Error::NotEnoughSpace(res.len(), self.nr_shots));
        }

        let one_mask = 1 << cbit;
        let zero_mask = !one_mask;

        let mut res_start = 0;
        for (tableau, &count) in self.tableaus.iter().zip(self.counts.iter())
        {
            let n0 = match tableau.measure(qbit)
                {
                    MeasurementInfo::Deterministic(false) => count,
                    MeasurementInfo::Deterministic(true) => 0,
                    MeasurementInfo::Random(_) => {
                        let distribution = rand_distr::Binomial::new(count as u64, 0.5).unwrap();
                        rng.sample(distribution) as usize
                    }
                };

            if n0 > 0
            {
                res.slice_mut(s![res_start..res_start+n0]).map_inplace(
                    |b| *b &= zero_mask
                );
            }
            if n0 < count
            {
                res.slice_mut(s![res_start+n0..res_start+count]).map_inplace(
                    |b| *b |= one_mask
                );
            }

            res_start += count;
        }

        Ok(())
    }

    fn peek_all_into<R: rand::Rng>(&mut self, cbits: &[usize],
        res: &mut ndarray::Array1<u64>, rng: &mut R) -> crate::error::Result<()>
    {
        let mut offset = 0;
        let mut one_mask = 0;
        for cbit in cbits
        {
            one_mask |= 1u64 << cbit;
        }
        let zero_mask = !one_mask;

        for (tableau, &count) in self.tableaus.iter().zip(self.counts.iter())
        {
            let mut counts = vec![(0, count)];
            for (qbit, &cbit) in cbits.iter().enumerate()
            {
                let mut new_counts = vec![];
                let minfo = tableau.measure(qbit);

                for (idx, c) in counts
                {
                    let n0 = match minfo
                    {
                        MeasurementInfo::Deterministic(false) => c,
                        MeasurementInfo::Deterministic(true) => 0,
                        MeasurementInfo::Random(_) => {
                            let distribution = rand_distr::Binomial::new(c as u64, 0.5).unwrap();
                            rng.sample(distribution) as usize
                        }
                    };
                    if n0 > 0
                    {
                        new_counts.push((idx, n0));
                    }
                    if n0 < c
                    {
                        new_counts.push((idx | (1 << cbit), c-n0));
                    }
                }

                counts = new_counts;
            }

            for (idx, c) in counts
            {
                res.slice_mut(s![offset..offset+c]).map_inplace(
                    |b| *b = (*b & zero_mask) | idx
                );
                offset += c;
            }
        }

        Ok(())
    }

    fn reset<R: rand::Rng>(&mut self, bit: usize, _rng: &mut R) -> crate::error::Result<()>
    {
        for tableau in self.tableaus.iter_mut()
        {
            tableau.reset(bit);
        }
        Ok(())
    }

    fn reset_all(&mut self)
    {
        self.tableaus = vec![StabilizerTableau::new(self.nr_bits)];
        self.counts = vec![self.nr_shots];
    }
}

#[cfg(test)]
mod tests
{
    use super::StabilizerState;
    use crate::gates::{CX, H, X};
    use crate::qustate::QuState;

    #[test]
    fn test_new()
    {
        let state = StabilizerState::new(4, 1024);
        assert_eq!(state.nr_bits, 4);
        assert_eq!(state.nr_shots, 1024);
        assert_eq!(state.counts, vec![1024]);
        assert_eq!(state.tableaus.len(), 1);
        assert_eq!(format!("{}", state.tableaus[0]), String::from(
r#"+ZIII
+IZII
+IIZI
+IIIZ"#));
    }

    #[test]
    fn test_apply_conditional_gate()
    {
        let mut s = StabilizerState::new(2, 5);
        assert_eq!(s.apply_conditional_gate(&[false, false, true, true, false], &X::new(), &[1]), Ok(()));
        assert_eq!(s.counts, vec![2, 2, 1]);
        let ss = s.tableaus.iter().map(|t| format!("{}", t)).collect::<Vec<String>>().join("\n\n");
        assert_eq!(ss, String::from(
r#"+ZI
+IZ

+ZI
-IZ

+ZI
+IZ"#));

        let mut s = StabilizerState::new(2, 5);
        assert_eq!(s.apply_conditional_gate(&[false, false, true, true, true], &X::new(), &[0]), Ok(()));
        assert_eq!(s.counts, vec![2, 3]);
        let ss = s.tableaus.iter().map(|t| format!("{}", t)).collect::<Vec<String>>().join("\n\n");
        assert_eq!(ss, String::from(
r#"+ZI
+IZ

-ZI
+IZ"#));

        let mut s = StabilizerState::new(2, 5);
        assert_eq!(s.apply_conditional_gate(&[true, false, true, true, false], &H::new(), &[1]), Ok(()));
        assert_eq!(s.counts, vec![1, 1, 2, 1]);
        let ss = s.tableaus.iter().map(|t| format!("{}", t)).collect::<Vec<String>>().join("\n\n");
        assert_eq!(ss, String::from(
r#"+IX
+ZI

+ZI
+IZ

+IX
+ZI

+ZI
+IZ"#));

        let mut s = StabilizerState::new(2, 5);
        assert_eq!(s.apply_gate(&H::new(), &[1]), Ok(()));
        assert_eq!(s.apply_conditional_gate(&[true, false, true, true, false], &CX::new(), &[1, 0]), Ok(()));
        assert_eq!(s.counts, vec![1, 1, 2, 1]);
        let ss = s.tableaus.iter().map(|t| format!("{}", t)).collect::<Vec<String>>().join("\n\n");
        assert_eq!(ss, String::from(
r#"+XX
+ZZ

+IX
+ZI

+XX
+ZZ

+IX
+ZI"#));


        let mut s = StabilizerState::new(2, 5);
        assert_eq!(s.apply_conditional_gate(&[true, true, true, false, false], &H::new(), &[0]), Ok(()));
        assert_eq!(s.counts, vec![3, 2]);
        let ss = s.tableaus.iter().map(|t| format!("{}", t)).collect::<Vec<String>>().join("\n\n");
        assert_eq!(ss, String::from(
r#"+XI
+IZ

+ZI
+IZ"#));
        assert_eq!(s.apply_conditional_gate(&[false, false, true, true, true], &H::new(), &[0]), Ok(()));
        assert_eq!(s.counts, vec![2, 1, 2]);
        let ss = s.tableaus.iter().map(|t| format!("{}", t)).collect::<Vec<String>>().join("\n\n");
        assert_eq!(ss, String::from(
r#"+XI
+IZ

+ZI
+IZ

+XI
+IZ"#));
    }

    #[test]
    fn test_measure()
    {
        let mut rng = rand::thread_rng();

        // |0⟩
        let mut s = StabilizerState::new(1, 3);
        let m = s.measure(0, &mut rng).unwrap();
        assert_eq!(m, array![0, 0, 0]);
        assert_eq!(s.counts, vec![3]);
        let ss = s.tableaus.iter().map(|t| format!("{}", t)).collect::<Vec<String>>().join("\n\n");
        assert_eq!(ss, String::from("+Z"));

        // |0⟩⊗|0⟩
        let mut s = StabilizerState::new(2, 3);
        let m = s.measure(1, &mut rng).unwrap();
        assert_eq!(m, array![0, 0, 0]);
        assert_eq!(s.counts, vec![3]);
        let ss = s.tableaus.iter().map(|t| format!("{}", t)).collect::<Vec<String>>().join("\n\n");
        assert_eq!(ss, String::from("+ZI\n+IZ"));
        let m = s.measure(0, &mut rng).unwrap();
        assert_eq!(m, array![0, 0, 0]);
        assert_eq!(s.counts, vec![3]);
        let ss = s.tableaus.iter().map(|t| format!("{}", t)).collect::<Vec<String>>().join("\n\n");
        assert_eq!(ss, String::from("+ZI\n+IZ"));

        // (H|0⟩)⊗(H|0⟩), unnormalized
        let mut s = StabilizerState::new(2, 1024);
        assert_eq!(s.apply_unary_gate_all(&H::new()), Ok(()));
        let m0 = s.measure(0, &mut rng).unwrap();
        let mut prev_b = m0[0];
        let mut sc_idx = 0;
        for &b in m0.iter()
        {
            if b != prev_b
            {
                sc_idx += 1;
                prev_b = b;
            }
            match b
            {
                0 => assert_eq!(format!("{}", s.tableaus[sc_idx]), String::from("+IX\n+ZI")),
                1 => assert_eq!(format!("{}", s.tableaus[sc_idx]), String::from("+IX\n-ZI")),
                // LCOV_EXCL_START
                _ => panic!("Invalid value {} for bit", b)
                // LCOV_EXCL_STOP
            }
        }

        // After collapse, a new measurement should yield the same result
        let m0b = s.measure(0, &mut rng).unwrap();
        assert_eq!(m0b, m0);

        // Measure second bit
        let m1 = s.measure(1, &mut rng).unwrap();
        let mut prev_b0 = m0[0];
        let mut prev_b1 = m1[0];
        let mut sc_idx = 0;
        for j in 0..s.nr_shots
        {
            let b0 = m0[j];
            let b1 = m1[j];
            if b0 != prev_b0 || b1 != prev_b1
            {
                sc_idx += 1;
                prev_b0 = b0;
                prev_b1 = b1;
            }
            match (b0, b1)
            {
                (0, 0) => assert_eq!(format!("{}", s.tableaus[sc_idx]), String::from("+ZI\n+IZ")),
                (0, 1) => assert_eq!(format!("{}", s.tableaus[sc_idx]), String::from("+ZI\n-IZ")),
                (1, 0) => assert_eq!(format!("{}", s.tableaus[sc_idx]), String::from("-ZI\n+IZ")),
                (1, 1) => assert_eq!(format!("{}", s.tableaus[sc_idx]), String::from("-ZI\n-IZ")),
                // LCOV_EXCL_START
                _      => panic!("Invalid value {:?} for bits", (b0, b1))
                // LCOV_EXCL_STOP
            }
        }
    }

    #[test]
    fn test_peek_into()
    {
        let nr_shots = 1024;
        let mut measurements = ndarray::Array1::zeros(nr_shots);

        let mut rng = rand::thread_rng();

        // |0⟩
        let s = StabilizerState::new(1, nr_shots);
        assert_eq!(s.peek_into(0, 0, &mut measurements, &mut rng), Ok(()));
        assert!(measurements.iter().all(|&bits| bits == 0));
        let ss = s.tableaus.iter().map(|t| format!("{}", t)).collect::<Vec<String>>().join("\n\n");
        assert_eq!(ss, String::from("+Z"));

        // H|0⟩
        let mut s = StabilizerState::new(1, nr_shots);
        assert_eq!(s.apply_gate(&H::new(), &[0]), Ok(()));
        assert_eq!(s.peek_into(0, 0, &mut measurements, &mut rng), Ok(()));
        assert!(crate::stats::measurement_ok(measurements.sum() as usize, nr_shots,
            0.5, 1.0e-5));
        let ss = s.tableaus.iter().map(|t| format!("{}", t)).collect::<Vec<String>>().join("\n\n");
        assert_eq!(ss, String::from("+X"));

        // H|0⟩⊗ H|0⟩
        let mut s = StabilizerState::new(2, nr_shots);
        assert_eq!(s.apply_unary_gate_all(&H::new()), Ok(()));
        assert_eq!(s.peek_into(0, 0, &mut measurements, &mut rng), Ok(()));
        assert!(crate::stats::measurement_ok(measurements.sum() as usize, nr_shots,
            0.5, 1.0e-5));
        measurements.fill(0);
        assert_eq!(s.peek_into(1, 0, &mut measurements, &mut rng), Ok(()));
        assert!(crate::stats::measurement_ok(measurements.sum() as usize, nr_shots,
            0.5, 1.0e-5));
        let ss = s.tableaus.iter().map(|t| format!("{}", t)).collect::<Vec<String>>().join("\n\n");
        assert_eq!(ss, String::from("+XI\n+IX"));

        // H|0⟩⊗ |1⟩
        let mut s = StabilizerState::new(2, nr_shots);
        assert_eq!(s.apply_gate(&H::new(), &[0]), Ok(()));
        assert_eq!(s.apply_gate(&X::new(), &[1]), Ok(()));
        assert_eq!(s.peek_into(0, 0, &mut measurements, &mut rng), Ok(()));
        assert!(crate::stats::measurement_ok(measurements.sum() as usize, nr_shots,
            0.5, 1.0e-5));
        measurements.fill(0);
        assert_eq!(s.peek_into(1, 0, &mut measurements, &mut rng), Ok(()));
        assert_eq!(measurements.sum() as usize, nr_shots);
        let ss = s.tableaus.iter().map(|t| format!("{}", t)).collect::<Vec<String>>().join("\n\n");
        assert_eq!(ss, String::from("+XI\n-IZ"));
    }

    #[test]
    fn test_measure_all()
    {
        let nr_bits = 3;
        let nr_shots = 5;

        let mut rng = rand::thread_rng();

        let mut s = StabilizerState::new(nr_bits, nr_shots);
        assert_eq!(s.apply_unary_gate_all(&X::new()), Ok(()));
        let result = s.measure_all(&mut rng).unwrap();
        assert_eq!(result.shape(), [nr_shots]);
        assert!(result.iter().all(|&b| b == 0b111));

        let mut s = StabilizerState::new(nr_bits, nr_shots);
        assert_eq!(s.apply_gate(&X::new(), &[0]), Ok(()));
        assert_eq!(s.apply_gate(&X::new(), &[1]), Ok(()));
        let result = s.measure_all(&mut rng).unwrap();
        assert_eq!(result.shape(), [nr_shots]);
        assert!(result.iter().all(|&b| b == 0b011));

        let mut s = StabilizerState::new(nr_bits, nr_shots);
        assert_eq!(s.apply_gate(&H::new(), &[2]), Ok(()));
        let result = s.measure_all(&mut rng).unwrap();
        assert_eq!(result.shape(), [nr_shots]);
        assert!(result.iter().all(|&b| (b & 0b011) == 0));
    }

    #[test]
    fn test_peek_all()
    {
        let tol = 1.0e-5;
        let nr_bits = 3;
        let nr_shots = 1024;

        let mut rng = rand::thread_rng();

        let mut s = StabilizerState::new(nr_bits, nr_shots);
        assert_eq!(s.apply_unary_gate_all(&X::new()), Ok(()));
        assert_eq!(s.apply_gate(&H::new(), &[0]), Ok(()));
        assert_eq!(s.apply_gate(&H::new(), &[2]), Ok(()));
        let mut result = ndarray::Array1::zeros(nr_shots);
        assert_eq!(s.peek_all_into(&[0, 1, 2], &mut result, &mut rng), Ok(()));
        // Ensure quantum state is preserved
        assert_eq!(s.counts, vec![nr_shots]);
        let ss = s.tableaus.iter().map(|t| format!("{}", t)).collect::<Vec<String>>().join("\n\n");
        assert_eq!(ss, String::from("-XII\n-IIX\n-IZI"));
        // Ensure measurement is correct
        assert_eq!(result.shape(), [nr_shots]);
        let mut n = vec![0; nr_bits];
        for &bits in result.iter()
        {
            for i in 0..nr_bits
            {
                n[i] += (bits as usize >> i) & 1;
            }
        }
        assert!(crate::stats::measurement_ok(n[0], nr_shots, 0.5, tol));
        assert_eq!(n[1], nr_shots);
        assert!(crate::stats::measurement_ok(n[2], nr_shots, 0.5, tol));
    }

    #[test]
    fn test_reset()
    {
        let nr_runs = 10;

        let mut rng = rand::thread_rng();

        let mut s = StabilizerState::new(1, nr_runs);
        assert_eq!(s.reset(0, &mut rng), Ok(()));
        let ss = s.tableaus.iter().map(|t| format!("{}", t)).collect::<Vec<String>>().join("\n\n");
        assert_eq!(ss, String::from("+Z"));

        let mut s = StabilizerState::new(1, nr_runs);
        assert_eq!(s.apply_gate(&X::new(), &[0]), Ok(()));
        assert_eq!(s.reset(0, &mut rng), Ok(()));
        let ss = s.tableaus.iter().map(|t| format!("{}", t)).collect::<Vec<String>>().join("\n\n");
        assert_eq!(ss, String::from("+Z"));

        let mut s = StabilizerState::new(2, nr_runs);
        assert_eq!(s.apply_unary_gate_all(&X::new()), Ok(()));
        assert_eq!(s.reset(0, &mut rng), Ok(()));
        let ss = s.tableaus.iter().map(|t| format!("{}", t)).collect::<Vec<String>>().join("\n\n");
        assert_eq!(ss, String::from("+ZI\n-IZ"));

        let mut s = StabilizerState::new(2, nr_runs);
        assert_eq!(s.apply_unary_gate_all(&X::new()), Ok(()));
        assert_eq!(s.reset(1, &mut rng), Ok(()));
        let ss = s.tableaus.iter().map(|t| format!("{}", t)).collect::<Vec<String>>().join("\n\n");
        assert_eq!(ss, String::from("-ZI\n+IZ"));

        let mut s = StabilizerState::new(2, nr_runs);
        assert_eq!(s.apply_gate(&X::new(), &[0]), Ok(()));
        assert_eq!(s.apply_gate(&H::new(), &[0]), Ok(()));
        assert_eq!(s.reset(0, &mut rng), Ok(()));
        let ss = s.tableaus.iter().map(|t| format!("{}", t)).collect::<Vec<String>>().join("\n\n");
        assert_eq!(ss, String::from("+ZI\n+IZ"));

        let mut s = StabilizerState::new(2, nr_runs);
        assert_eq!(s.apply_gate(&X::new(), &[0]), Ok(()));
        assert_eq!(s.apply_gate(&H::new(), &[0]), Ok(()));
        assert_eq!(s.reset(1, &mut rng), Ok(()));
        let ss = s.tableaus.iter().map(|t| format!("{}", t)).collect::<Vec<String>>().join("\n\n");
        assert_eq!(ss, String::from("-XI\n+IZ"));
    }

    #[test]
    fn test_reset_all()
    {
        let nr_bits = 5;
        let nr_runs = 100;

        let mut s = StabilizerState::new(nr_bits, nr_runs);
        assert_eq!(s.apply_gate(&H::new(), &[2]), Ok(()));
        assert_eq!(s.apply_gate(&X::new(), &[0]), Ok(()));
        assert_eq!(s.apply_gate(&H::new(), &[4]), Ok(()));

        s.reset_all();
        assert_eq!(s.counts, vec![nr_runs]);
        let ss = s.tableaus.iter().map(|t| format!("{}", t)).collect::<Vec<String>>().join("\n\n");
        assert_eq!(ss, String::from(
r#"+ZIIII
+IZIII
+IIZII
+IIIZI
+IIIIZ"#));
    }

}