quantrs2-sim 0.1.3

Quantum circuit simulators for the QuantRS2 framework
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
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
//! Stim circuit executor with detector and observable support
//!
//! This module provides execution capabilities for Stim circuits, including:
//! - Running circuits with the stabilizer simulator
//! - Tracking measurement records for detector evaluation
//! - Computing detector values from measurement parities
//! - Computing observable values for logical qubit tracking
//!
//! ## Detector Model
//!
//! Detectors check parity conditions on measurement results. A detector triggers
//! when the XOR of its referenced measurement results differs from the expected value.
//!
//! ## Observable Model
//!
//! Observables track logical qubit values through a circuit. They are computed
//! as the XOR of specified measurement results.

use crate::error::{Result, SimulatorError};
use crate::stabilizer::{StabilizerSimulator, StabilizerTableau};
use crate::stim_parser::{
    MeasurementBasis, PauliTarget, PauliType, SingleQubitGateType, StimCircuit, StimInstruction,
    TwoQubitGateType,
};
use scirs2_core::random::prelude::*;

/// Record of a detector definition
#[derive(Debug, Clone)]
pub struct DetectorRecord {
    /// Detector index
    pub index: usize,
    /// Coordinates for visualization/debugging
    pub coordinates: Vec<f64>,
    /// Measurement record indices this detector depends on (negative = relative)
    pub record_targets: Vec<i32>,
    /// Expected parity (usually false for no error)
    pub expected_parity: bool,
}

/// Record of an observable definition
#[derive(Debug, Clone)]
pub struct ObservableRecord {
    /// Observable index
    pub index: usize,
    /// Measurement record indices this observable depends on
    pub record_targets: Vec<i32>,
}

/// Stim circuit executor with full error correction support
#[derive(Debug, Clone)]
pub struct StimExecutor {
    /// Stabilizer simulator for circuit execution
    simulator: StabilizerSimulator,
    /// Measurement record (chronological order)
    measurement_record: Vec<bool>,
    /// Detector definitions
    detectors: Vec<DetectorRecord>,
    /// Observable definitions
    observables: Vec<ObservableRecord>,
    /// Error tracking state for E/ELSE_CORRELATED_ERROR chains
    last_error_triggered: bool,
    /// Number of qubits
    num_qubits: usize,
}

impl StimExecutor {
    /// Create a new Stim executor
    #[must_use]
    pub fn new(num_qubits: usize) -> Self {
        Self {
            simulator: StabilizerSimulator::new(num_qubits),
            measurement_record: Vec::new(),
            detectors: Vec::new(),
            observables: Vec::new(),
            last_error_triggered: false,
            num_qubits,
        }
    }

    /// Create from a Stim circuit (auto-determines qubit count)
    #[must_use]
    pub fn from_circuit(circuit: &StimCircuit) -> Self {
        Self::new(circuit.num_qubits)
    }

    /// Execute a full Stim circuit
    pub fn execute(&mut self, circuit: &StimCircuit) -> Result<ExecutionResult> {
        // Reset state for new execution
        self.measurement_record.clear();
        self.detectors.clear();
        self.observables.clear();
        self.last_error_triggered = false;

        // Execute each instruction
        for instruction in &circuit.instructions {
            self.execute_instruction(instruction)?;
        }

        // Compute detector and observable values
        let detector_values = self.compute_detector_values();
        let observable_values = self.compute_observable_values();

        Ok(ExecutionResult {
            measurement_record: self.measurement_record.clone(),
            detector_values,
            observable_values,
            num_measurements: self.measurement_record.len(),
            num_detectors: self.detectors.len(),
            num_observables: self.observables.len(),
        })
    }

    /// Execute a single instruction
    fn execute_instruction(&mut self, instruction: &StimInstruction) -> Result<()> {
        match instruction {
            // Gates
            StimInstruction::SingleQubitGate { gate_type, qubit } => {
                self.execute_single_qubit_gate(*gate_type, *qubit)?;
            }
            StimInstruction::TwoQubitGate {
                gate_type,
                control,
                target,
            } => {
                self.execute_two_qubit_gate(*gate_type, *control, *target)?;
            }

            // Measurements
            StimInstruction::Measure { basis, qubits } => {
                self.execute_measurement(*basis, qubits)?;
            }

            // Reset
            StimInstruction::Reset { qubits } => {
                self.execute_reset(qubits)?;
            }

            // Measure and reset
            StimInstruction::MeasureReset { basis, qubits } => {
                self.execute_measure_reset(*basis, qubits)?;
            }

            // Detectors and observables
            StimInstruction::Detector {
                coordinates,
                record_targets,
            } => {
                self.process_detector(coordinates, record_targets)?;
            }
            StimInstruction::ObservableInclude {
                observable_index,
                record_targets,
            } => {
                self.process_observable(*observable_index, record_targets)?;
            }

            // Noise instructions (stochastic)
            StimInstruction::XError {
                probability,
                qubits,
            } => {
                self.execute_x_error(*probability, qubits)?;
            }
            StimInstruction::YError {
                probability,
                qubits,
            } => {
                self.execute_y_error(*probability, qubits)?;
            }
            StimInstruction::ZError {
                probability,
                qubits,
            } => {
                self.execute_z_error(*probability, qubits)?;
            }
            StimInstruction::Depolarize1 {
                probability,
                qubits,
            } => {
                self.execute_depolarize1(*probability, qubits)?;
            }
            StimInstruction::Depolarize2 {
                probability,
                qubit_pairs,
            } => {
                self.execute_depolarize2(*probability, qubit_pairs)?;
            }
            StimInstruction::CorrelatedError {
                probability,
                targets,
            } => {
                self.execute_correlated_error(*probability, targets)?;
            }
            StimInstruction::ElseCorrelatedError {
                probability,
                targets,
            } => {
                self.execute_else_correlated_error(*probability, targets)?;
            }
            StimInstruction::PauliChannel1 { px, py, pz, qubits } => {
                self.execute_pauli_channel_1(*px, *py, *pz, qubits)?;
            }
            StimInstruction::PauliChannel2 {
                probabilities,
                qubit_pairs,
            } => {
                self.execute_pauli_channel_2(probabilities, qubit_pairs)?;
            }

            // Metadata instructions (no execution effect)
            StimInstruction::Comment(_)
            | StimInstruction::Tick
            | StimInstruction::ShiftCoords { .. }
            | StimInstruction::QubitCoords { .. } => {}

            // Repeat blocks
            StimInstruction::Repeat {
                count,
                instructions,
            } => {
                for _ in 0..*count {
                    for inst in instructions {
                        self.execute_instruction(inst)?;
                    }
                }
            }
        }

        Ok(())
    }

    /// Execute a single-qubit gate
    fn execute_single_qubit_gate(
        &mut self,
        gate_type: SingleQubitGateType,
        qubit: usize,
    ) -> Result<()> {
        let gate = gate_type.to_stabilizer_gate(qubit);
        self.simulator.apply_gate(gate).map_err(|e| {
            SimulatorError::InvalidOperation(format!("Gate execution failed: {:?}", e))
        })
    }

    /// Execute a two-qubit gate
    fn execute_two_qubit_gate(
        &mut self,
        gate_type: TwoQubitGateType,
        control: usize,
        target: usize,
    ) -> Result<()> {
        let gate = gate_type.to_stabilizer_gate(control, target);
        self.simulator.apply_gate(gate).map_err(|e| {
            SimulatorError::InvalidOperation(format!("Gate execution failed: {:?}", e))
        })
    }

    /// Execute measurements
    fn execute_measurement(&mut self, basis: MeasurementBasis, qubits: &[usize]) -> Result<()> {
        for &qubit in qubits {
            let outcome = match basis {
                MeasurementBasis::Z => self.simulator.measure(qubit),
                MeasurementBasis::X => self.simulator.tableau.measure_x(qubit),
                MeasurementBasis::Y => self.simulator.tableau.measure_y(qubit),
            }
            .map_err(|e| {
                SimulatorError::InvalidOperation(format!("Measurement failed: {:?}", e))
            })?;

            self.measurement_record.push(outcome);
        }
        Ok(())
    }

    /// Execute reset operations
    fn execute_reset(&mut self, qubits: &[usize]) -> Result<()> {
        for &qubit in qubits {
            self.simulator
                .tableau
                .reset(qubit)
                .map_err(|e| SimulatorError::InvalidOperation(format!("Reset failed: {:?}", e)))?;
        }
        Ok(())
    }

    /// Execute measure-and-reset operations
    fn execute_measure_reset(&mut self, basis: MeasurementBasis, qubits: &[usize]) -> Result<()> {
        self.execute_measurement(basis, qubits)?;
        self.execute_reset(qubits)
    }

    /// Process a DETECTOR instruction
    fn process_detector(&mut self, coordinates: &[f64], record_targets: &[i32]) -> Result<()> {
        let detector = DetectorRecord {
            index: self.detectors.len(),
            coordinates: coordinates.to_vec(),
            record_targets: record_targets.to_vec(),
            expected_parity: false, // Default expectation is no error (parity = 0)
        };
        self.detectors.push(detector);
        Ok(())
    }

    /// Process an OBSERVABLE_INCLUDE instruction
    fn process_observable(
        &mut self,
        observable_index: usize,
        record_targets: &[i32],
    ) -> Result<()> {
        // Find or create the observable record
        while self.observables.len() <= observable_index {
            self.observables.push(ObservableRecord {
                index: self.observables.len(),
                record_targets: Vec::new(),
            });
        }

        // Add the record targets to the observable
        self.observables[observable_index]
            .record_targets
            .extend_from_slice(record_targets);

        Ok(())
    }

    /// Compute detector values from measurement record
    pub fn compute_detector_values(&self) -> Vec<bool> {
        self.detectors
            .iter()
            .map(|detector| {
                let parity = self.compute_record_parity(&detector.record_targets);
                // Detector fires when parity differs from expected
                parity != detector.expected_parity
            })
            .collect()
    }

    /// Compute observable values from measurement record
    pub fn compute_observable_values(&self) -> Vec<bool> {
        self.observables
            .iter()
            .map(|observable| self.compute_record_parity(&observable.record_targets))
            .collect()
    }

    /// Compute XOR parity of measurement results at given record indices
    fn compute_record_parity(&self, record_targets: &[i32]) -> bool {
        let record_len = self.measurement_record.len() as i32;

        record_targets
            .iter()
            .filter_map(|&idx| {
                // Convert relative (negative) to absolute index
                let abs_idx = if idx < 0 {
                    (record_len + idx) as usize
                } else {
                    idx as usize
                };

                self.measurement_record.get(abs_idx).copied()
            })
            .fold(false, |acc, x| acc ^ x)
    }

    // ==================== Error/Noise Execution ====================

    /// Execute X errors with given probability
    fn execute_x_error(&mut self, probability: f64, qubits: &[usize]) -> Result<()> {
        let mut rng = thread_rng();
        for &qubit in qubits {
            if rng.random_bool(probability) {
                self.simulator
                    .apply_gate(crate::stabilizer::StabilizerGate::X(qubit))
                    .map_err(|e| {
                        SimulatorError::InvalidOperation(format!("X error failed: {:?}", e))
                    })?;
            }
        }
        Ok(())
    }

    /// Execute Y errors with given probability
    fn execute_y_error(&mut self, probability: f64, qubits: &[usize]) -> Result<()> {
        let mut rng = thread_rng();
        for &qubit in qubits {
            if rng.random_bool(probability) {
                self.simulator
                    .apply_gate(crate::stabilizer::StabilizerGate::Y(qubit))
                    .map_err(|e| {
                        SimulatorError::InvalidOperation(format!("Y error failed: {:?}", e))
                    })?;
            }
        }
        Ok(())
    }

    /// Execute Z errors with given probability
    fn execute_z_error(&mut self, probability: f64, qubits: &[usize]) -> Result<()> {
        let mut rng = thread_rng();
        for &qubit in qubits {
            if rng.random_bool(probability) {
                self.simulator
                    .apply_gate(crate::stabilizer::StabilizerGate::Z(qubit))
                    .map_err(|e| {
                        SimulatorError::InvalidOperation(format!("Z error failed: {:?}", e))
                    })?;
            }
        }
        Ok(())
    }

    /// Execute single-qubit depolarizing noise
    fn execute_depolarize1(&mut self, probability: f64, qubits: &[usize]) -> Result<()> {
        let mut rng = thread_rng();
        // Depolarizing: with prob p, apply X, Y, or Z uniformly at random
        for &qubit in qubits {
            if rng.random_bool(probability) {
                let error_type: u8 = rng.random_range(0..3);
                let gate = match error_type {
                    0 => crate::stabilizer::StabilizerGate::X(qubit),
                    1 => crate::stabilizer::StabilizerGate::Y(qubit),
                    _ => crate::stabilizer::StabilizerGate::Z(qubit),
                };
                self.simulator.apply_gate(gate).map_err(|e| {
                    SimulatorError::InvalidOperation(format!("Depolarizing error failed: {:?}", e))
                })?;
            }
        }
        Ok(())
    }

    /// Execute two-qubit depolarizing noise
    fn execute_depolarize2(
        &mut self,
        probability: f64,
        qubit_pairs: &[(usize, usize)],
    ) -> Result<()> {
        let mut rng = thread_rng();
        // Two-qubit depolarizing: 15 non-identity Pauli pairs
        for &(q1, q2) in qubit_pairs {
            if rng.random_bool(probability) {
                // Select one of 15 non-identity two-qubit Paulis
                let error_idx: u8 = rng.random_range(0..15);
                let (pauli1, pauli2) = Self::two_qubit_pauli_from_index(error_idx);
                self.apply_pauli_to_qubit(pauli1, q1)?;
                self.apply_pauli_to_qubit(pauli2, q2)?;
            }
        }
        Ok(())
    }

    /// Execute a correlated error (E instruction)
    fn execute_correlated_error(
        &mut self,
        probability: f64,
        targets: &[PauliTarget],
    ) -> Result<()> {
        let mut rng = thread_rng();
        self.last_error_triggered = rng.random_bool(probability);

        if self.last_error_triggered {
            for target in targets {
                self.apply_pauli_to_qubit(target.pauli, target.qubit)?;
            }
        }
        Ok(())
    }

    /// Execute an else-correlated error (ELSE_CORRELATED_ERROR instruction)
    fn execute_else_correlated_error(
        &mut self,
        probability: f64,
        targets: &[PauliTarget],
    ) -> Result<()> {
        // Only consider triggering if the previous E did NOT trigger
        if !self.last_error_triggered {
            let mut rng = thread_rng();
            self.last_error_triggered = rng.random_bool(probability);

            if self.last_error_triggered {
                for target in targets {
                    self.apply_pauli_to_qubit(target.pauli, target.qubit)?;
                }
            }
        }
        // If previous error triggered, this one doesn't run (else branch not taken)
        Ok(())
    }

    /// Execute Pauli channel (single qubit)
    fn execute_pauli_channel_1(
        &mut self,
        px: f64,
        py: f64,
        pz: f64,
        qubits: &[usize],
    ) -> Result<()> {
        let mut rng = thread_rng();
        for &qubit in qubits {
            let r: f64 = rng.random();
            if r < px {
                self.simulator
                    .apply_gate(crate::stabilizer::StabilizerGate::X(qubit))
                    .map_err(|e| {
                        SimulatorError::InvalidOperation(format!("Pauli channel failed: {:?}", e))
                    })?;
            } else if r < px + py {
                self.simulator
                    .apply_gate(crate::stabilizer::StabilizerGate::Y(qubit))
                    .map_err(|e| {
                        SimulatorError::InvalidOperation(format!("Pauli channel failed: {:?}", e))
                    })?;
            } else if r < px + py + pz {
                self.simulator
                    .apply_gate(crate::stabilizer::StabilizerGate::Z(qubit))
                    .map_err(|e| {
                        SimulatorError::InvalidOperation(format!("Pauli channel failed: {:?}", e))
                    })?;
            }
            // Otherwise, identity (no error)
        }
        Ok(())
    }

    /// Execute Pauli channel (two qubits)
    fn execute_pauli_channel_2(
        &mut self,
        probabilities: &[f64],
        qubit_pairs: &[(usize, usize)],
    ) -> Result<()> {
        if probabilities.len() != 15 {
            return Err(SimulatorError::InvalidOperation(
                "PAULI_CHANNEL_2 requires 15 probabilities".to_string(),
            ));
        }

        let mut rng = thread_rng();
        for &(q1, q2) in qubit_pairs {
            let r: f64 = rng.random();
            let mut cumulative = 0.0;

            for (i, &p) in probabilities.iter().enumerate() {
                cumulative += p;
                if r < cumulative {
                    let (pauli1, pauli2) = Self::two_qubit_pauli_from_index(i as u8);
                    self.apply_pauli_to_qubit(pauli1, q1)?;
                    self.apply_pauli_to_qubit(pauli2, q2)?;
                    break;
                }
            }
        }
        Ok(())
    }

    /// Apply a Pauli operator to a qubit
    fn apply_pauli_to_qubit(&mut self, pauli: PauliType, qubit: usize) -> Result<()> {
        let gate = match pauli {
            PauliType::I => return Ok(()), // Identity, do nothing
            PauliType::X => crate::stabilizer::StabilizerGate::X(qubit),
            PauliType::Y => crate::stabilizer::StabilizerGate::Y(qubit),
            PauliType::Z => crate::stabilizer::StabilizerGate::Z(qubit),
        };
        self.simulator.apply_gate(gate).map_err(|e| {
            SimulatorError::InvalidOperation(format!("Pauli application failed: {:?}", e))
        })
    }

    /// Convert index (0-14) to two-qubit Pauli pair (excluding II)
    /// Order: IX, IY, IZ, XI, XX, XY, XZ, YI, YX, YY, YZ, ZI, ZX, ZY, ZZ
    fn two_qubit_pauli_from_index(idx: u8) -> (PauliType, PauliType) {
        // Mapping: 0=I, 1=X, 2=Y, 3=Z
        // Index maps to (p1, p2) excluding (0,0)
        let idx = idx + 1; // Skip II
        let p1 = idx / 4;
        let p2 = idx % 4;

        let to_pauli = |i| match i {
            0 => PauliType::I,
            1 => PauliType::X,
            2 => PauliType::Y,
            _ => PauliType::Z,
        };

        (to_pauli(p1), to_pauli(p2))
    }

    // ==================== Accessors ====================

    /// Get the measurement record
    #[must_use]
    pub fn measurement_record(&self) -> &[bool] {
        &self.measurement_record
    }

    /// Get detector definitions
    #[must_use]
    pub fn detectors(&self) -> &[DetectorRecord] {
        &self.detectors
    }

    /// Get observable definitions
    #[must_use]
    pub fn observables(&self) -> &[ObservableRecord] {
        &self.observables
    }

    /// Get the stabilizer simulator
    #[must_use]
    pub fn simulator(&self) -> &StabilizerSimulator {
        &self.simulator
    }

    /// Get the current stabilizers
    #[must_use]
    pub fn get_stabilizers(&self) -> Vec<String> {
        self.simulator.get_stabilizers()
    }

    /// Get the number of qubits
    #[must_use]
    pub fn num_qubits(&self) -> usize {
        self.num_qubits
    }
}

/// Result of executing a Stim circuit
#[derive(Debug, Clone)]
pub struct ExecutionResult {
    /// Full measurement record
    pub measurement_record: Vec<bool>,
    /// Detector values (true = detector fired)
    pub detector_values: Vec<bool>,
    /// Observable values
    pub observable_values: Vec<bool>,
    /// Total number of measurements
    pub num_measurements: usize,
    /// Total number of detectors
    pub num_detectors: usize,
    /// Total number of observables
    pub num_observables: usize,
}

impl ExecutionResult {
    /// Check if any detector fired (indicating an error was detected)
    #[must_use]
    pub fn any_detector_fired(&self) -> bool {
        self.detector_values.iter().any(|&x| x)
    }

    /// Count how many detectors fired
    #[must_use]
    pub fn detector_fire_count(&self) -> usize {
        self.detector_values.iter().filter(|&&x| x).count()
    }

    /// Get a bit-packed representation of measurements
    #[must_use]
    pub fn packed_measurements(&self) -> Vec<u8> {
        self.measurement_record
            .chunks(8)
            .map(|chunk| {
                let mut byte = 0u8;
                for (i, &bit) in chunk.iter().enumerate() {
                    if bit {
                        byte |= 1 << i;
                    }
                }
                byte
            })
            .collect()
    }

    /// Get a bit-packed representation of detector values
    #[must_use]
    pub fn packed_detectors(&self) -> Vec<u8> {
        self.detector_values
            .chunks(8)
            .map(|chunk| {
                let mut byte = 0u8;
                for (i, &bit) in chunk.iter().enumerate() {
                    if bit {
                        byte |= 1 << i;
                    }
                }
                byte
            })
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_basic_execution() {
        let circuit_str = r#"
            H 0
            CNOT 0 1
            M 0 1
        "#;

        let circuit = StimCircuit::from_str(circuit_str).unwrap();
        let mut executor = StimExecutor::from_circuit(&circuit);
        let result = executor.execute(&circuit).unwrap();

        assert_eq!(result.num_measurements, 2);
        // Bell state: measurements should be correlated
        assert_eq!(result.measurement_record[0], result.measurement_record[1]);
    }

    #[test]
    fn test_detector_execution() {
        // Deterministic test: prepare |00⟩ state, measure both
        // M0=0, M1=0, XOR=0, detector should not fire
        let circuit_str = r#"
            M 0 1
            DETECTOR rec[-1] rec[-2]
        "#;

        let circuit = StimCircuit::from_str(circuit_str).unwrap();
        let mut executor = StimExecutor::from_circuit(&circuit);
        let result = executor.execute(&circuit).unwrap();

        assert_eq!(result.num_detectors, 1);
        // |00⟩ state: M0=0, M1=0, XOR=0, detector should NOT fire
        assert!(!result.measurement_record[0]);
        assert!(!result.measurement_record[1]);
        assert!(!result.detector_values[0]);
    }

    #[test]
    fn test_detector_with_error() {
        // Test detector firing when error is introduced
        // Apply X to qubit 0, measure both: M0=1, M1=0, XOR=1
        let circuit_str = r#"
            X 0
            M 0 1
            DETECTOR rec[-1] rec[-2]
        "#;

        let circuit = StimCircuit::from_str(circuit_str).unwrap();
        let mut executor = StimExecutor::from_circuit(&circuit);
        let result = executor.execute(&circuit).unwrap();

        assert_eq!(result.num_detectors, 1);
        // |10⟩ state: M0=1, M1=0, XOR=1, detector SHOULD fire
        assert!(result.measurement_record[0]);
        assert!(!result.measurement_record[1]);
        assert!(result.detector_values[0]);
    }

    #[test]
    fn test_observable_execution() {
        let circuit_str = r#"
            H 0
            CNOT 0 1
            M 0 1
            OBSERVABLE_INCLUDE(0) rec[-1]
            OBSERVABLE_INCLUDE(1) rec[-2]
        "#;

        let circuit = StimCircuit::from_str(circuit_str).unwrap();
        let mut executor = StimExecutor::from_circuit(&circuit);
        let result = executor.execute(&circuit).unwrap();

        assert_eq!(result.num_observables, 2);
    }

    #[test]
    fn test_measure_reset() {
        let circuit_str = r#"
            H 0
            MR 0
            M 0
        "#;

        let circuit = StimCircuit::from_str(circuit_str).unwrap();
        let mut executor = StimExecutor::from_circuit(&circuit);
        let result = executor.execute(&circuit).unwrap();

        assert_eq!(result.num_measurements, 2);
        // After reset, second measurement should be 0
        assert!(!result.measurement_record[1]);
    }

    #[test]
    fn test_noise_execution() {
        // Note: This test is probabilistic, but with p=1.0 it's deterministic
        let circuit_str = r#"
            X_ERROR(1.0) 0
            M 0
        "#;

        let circuit = StimCircuit::from_str(circuit_str).unwrap();
        let mut executor = StimExecutor::from_circuit(&circuit);
        let result = executor.execute(&circuit).unwrap();

        // X error on |0⟩ gives |1⟩, so measurement should be 1
        assert!(result.measurement_record[0]);
    }

    #[test]
    fn test_correlated_error() {
        // E with probability 1.0 should always trigger
        let circuit_str = r#"
            E(1.0) X0 X1
            M 0 1
        "#;

        let circuit = StimCircuit::from_str(circuit_str).unwrap();
        let mut executor = StimExecutor::from_circuit(&circuit);
        let result = executor.execute(&circuit).unwrap();

        // Both qubits should be flipped
        assert!(result.measurement_record[0]);
        assert!(result.measurement_record[1]);
    }

    #[test]
    fn test_else_correlated_error() {
        // E(1.0) always triggers, so ELSE should not
        let circuit_str = r#"
            E(1.0) X0
            ELSE_CORRELATED_ERROR(1.0) X1
            M 0 1
        "#;

        let circuit = StimCircuit::from_str(circuit_str).unwrap();
        let mut executor = StimExecutor::from_circuit(&circuit);
        let result = executor.execute(&circuit).unwrap();

        // E triggers, ELSE doesn't
        assert!(result.measurement_record[0]); // X0 applied
        assert!(!result.measurement_record[1]); // X1 NOT applied
    }

    #[test]
    fn test_packed_measurements() {
        let mut result = ExecutionResult {
            measurement_record: vec![true, false, true, true, false, false, true, false, true],
            detector_values: vec![],
            observable_values: vec![],
            num_measurements: 9,
            num_detectors: 0,
            num_observables: 0,
        };

        let packed = result.packed_measurements();
        // First 8 bits: 1,0,1,1,0,0,1,0 = 0b01001101 = 77
        // 9th bit: 1 = 0b00000001 = 1
        assert_eq!(packed[0], 0b01001101);
        assert_eq!(packed[1], 0b00000001);
    }

    #[test]
    fn test_detector_fire_count() {
        let result = ExecutionResult {
            measurement_record: vec![],
            detector_values: vec![true, false, true, true, false],
            observable_values: vec![],
            num_measurements: 0,
            num_detectors: 5,
            num_observables: 0,
        };

        assert!(result.any_detector_fired());
        assert_eq!(result.detector_fire_count(), 3);
    }
}