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
//! Pauli string evolution and operations.
//!
//! This module provides efficient operations for Pauli strings, including:
//! - Pauli string construction and manipulation
//! - Time evolution of Pauli observables
//! - Commutation relations and algebra
//! - Measurement expectation values

use crate::prelude::SimulatorError;
use scirs2_core::ndarray::Array2;
use scirs2_core::parallel_ops::{IndexedParallelIterator, ParallelIterator};
use scirs2_core::Complex64;
use std::collections::HashMap;
use std::fmt;

use crate::error::Result;
use crate::trotter::{DynamicCircuit, Hamiltonian, TrotterDecomposer, TrotterMethod};
use quantrs2_core::gate::{
    multi::CNOT,
    single::{Hadamard, Phase, PhaseDagger, RotationX, RotationY, RotationZ},
    GateOp,
};
use quantrs2_core::qubit::QubitId;

/// Single Pauli operator type
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PauliOperator {
    /// Identity operator
    I,
    /// Pauli-X operator
    X,
    /// Pauli-Y operator
    Y,
    /// Pauli-Z operator
    Z,
}

impl fmt::Display for PauliOperator {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::I => write!(f, "I"),
            Self::X => write!(f, "X"),
            Self::Y => write!(f, "Y"),
            Self::Z => write!(f, "Z"),
        }
    }
}

impl PauliOperator {
    /// Parse from string
    pub fn from_str(s: &str) -> Result<Self> {
        match s.to_uppercase().as_str() {
            "I" => Ok(Self::I),
            "X" => Ok(Self::X),
            "Y" => Ok(Self::Y),
            "Z" => Ok(Self::Z),
            _ => Err(SimulatorError::InvalidInput(format!(
                "Invalid Pauli operator: {s}"
            ))),
        }
    }

    /// Get matrix representation
    #[must_use]
    pub fn matrix(&self) -> Array2<Complex64> {
        match self {
            Self::I => Array2::from_shape_vec(
                (2, 2),
                vec![
                    Complex64::new(1.0, 0.0),
                    Complex64::new(0.0, 0.0),
                    Complex64::new(0.0, 0.0),
                    Complex64::new(1.0, 0.0),
                ],
            )
            .expect("Pauli I matrix has valid shape"),
            Self::X => Array2::from_shape_vec(
                (2, 2),
                vec![
                    Complex64::new(0.0, 0.0),
                    Complex64::new(1.0, 0.0),
                    Complex64::new(1.0, 0.0),
                    Complex64::new(0.0, 0.0),
                ],
            )
            .expect("Pauli X matrix has valid shape"),
            Self::Y => Array2::from_shape_vec(
                (2, 2),
                vec![
                    Complex64::new(0.0, 0.0),
                    Complex64::new(0.0, -1.0),
                    Complex64::new(0.0, 1.0),
                    Complex64::new(0.0, 0.0),
                ],
            )
            .expect("Pauli Y matrix has valid shape"),
            Self::Z => Array2::from_shape_vec(
                (2, 2),
                vec![
                    Complex64::new(1.0, 0.0),
                    Complex64::new(0.0, 0.0),
                    Complex64::new(0.0, 0.0),
                    Complex64::new(-1.0, 0.0),
                ],
            )
            .expect("Pauli Z matrix has valid shape"),
        }
    }

    /// Check if commutes with another Pauli
    #[must_use]
    pub fn commutes_with(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::I, _) | (_, Self::I) => true,
            (a, b) if a == b => true,
            _ => false,
        }
    }

    /// Multiplication of Pauli operators (returns (result, phase))
    #[must_use]
    pub const fn multiply(&self, other: &Self) -> (Self, Complex64) {
        match (self, other) {
            (Self::I, p) | (p, Self::I) => (*p, Complex64::new(1.0, 0.0)),
            (Self::X, Self::X) | (Self::Y, Self::Y) | (Self::Z, Self::Z) => {
                (Self::I, Complex64::new(1.0, 0.0))
            }
            (Self::X, Self::Y) => (Self::Z, Complex64::new(0.0, 1.0)),
            (Self::Y, Self::X) => (Self::Z, Complex64::new(0.0, -1.0)),
            (Self::Y, Self::Z) => (Self::X, Complex64::new(0.0, 1.0)),
            (Self::Z, Self::Y) => (Self::X, Complex64::new(0.0, -1.0)),
            (Self::Z, Self::X) => (Self::Y, Complex64::new(0.0, 1.0)),
            (Self::X, Self::Z) => (Self::Y, Complex64::new(0.0, -1.0)),
        }
    }
}

/// A Pauli string is a tensor product of Pauli operators
#[derive(Debug, Clone)]
pub struct PauliString {
    /// Pauli operators at each qubit position
    pub operators: Vec<PauliOperator>,
    /// Overall coefficient
    pub coefficient: Complex64,
    /// Number of qubits
    pub num_qubits: usize,
}

impl PauliString {
    /// Create a new Pauli string
    #[must_use]
    pub fn new(num_qubits: usize) -> Self {
        Self {
            operators: vec![PauliOperator::I; num_qubits],
            coefficient: Complex64::new(1.0, 0.0),
            num_qubits,
        }
    }

    /// Create from string representation like "XYZI"
    pub fn from_string(pauli_str: &str, coefficient: Complex64) -> Result<Self> {
        let operators: Result<Vec<_>> = pauli_str
            .chars()
            .map(|c| PauliOperator::from_str(&c.to_string()))
            .collect();

        Ok(Self {
            operators: operators?,
            coefficient,
            num_qubits: pauli_str.len(),
        })
    }

    /// Create from qubit indices and Pauli operators
    pub fn from_ops(
        num_qubits: usize,
        ops: &[(usize, PauliOperator)],
        coefficient: Complex64,
    ) -> Result<Self> {
        let mut pauli_string = Self::new(num_qubits);
        pauli_string.coefficient = coefficient;

        for &(qubit, op) in ops {
            if qubit >= num_qubits {
                return Err(SimulatorError::IndexOutOfBounds(qubit));
            }
            pauli_string.operators[qubit] = op;
        }

        Ok(pauli_string)
    }

    /// Set operator at specific qubit
    pub fn set_operator(&mut self, qubit: usize, op: PauliOperator) -> Result<()> {
        if qubit >= self.num_qubits {
            return Err(SimulatorError::IndexOutOfBounds(qubit));
        }
        self.operators[qubit] = op;
        Ok(())
    }

    /// Get operator at specific qubit
    pub fn get_operator(&self, qubit: usize) -> Result<PauliOperator> {
        if qubit >= self.num_qubits {
            return Err(SimulatorError::IndexOutOfBounds(qubit));
        }
        Ok(self.operators[qubit])
    }

    /// Get non-identity operators
    #[must_use]
    pub fn non_identity_ops(&self) -> Vec<(usize, PauliOperator)> {
        self.operators
            .iter()
            .enumerate()
            .filter(|(_, &op)| op != PauliOperator::I)
            .map(|(i, &op)| (i, op))
            .collect()
    }

    /// Check if this Pauli string commutes with another
    #[must_use]
    pub fn commutes_with(&self, other: &Self) -> bool {
        if self.num_qubits != other.num_qubits {
            return false;
        }

        let mut anti_commute_count = 0;
        for i in 0..self.num_qubits {
            if !self.operators[i].commutes_with(&other.operators[i]) {
                anti_commute_count += 1;
            }
        }

        // Pauli strings commute if they anti-commute at an even number of positions
        anti_commute_count % 2 == 0
    }

    /// Multiply two Pauli strings
    pub fn multiply(&self, other: &Self) -> Result<Self> {
        if self.num_qubits != other.num_qubits {
            return Err(SimulatorError::DimensionMismatch(format!(
                "Pauli strings have different lengths: {} vs {}",
                self.num_qubits, other.num_qubits
            )));
        }

        let mut result = Self::new(self.num_qubits);
        let mut total_phase = self.coefficient * other.coefficient;

        for i in 0..self.num_qubits {
            let (op, phase) = self.operators[i].multiply(&other.operators[i]);
            result.operators[i] = op;
            total_phase *= phase;
        }

        result.coefficient = total_phase;
        Ok(result)
    }

    /// Get weight (number of non-identity operators)
    #[must_use]
    pub fn weight(&self) -> usize {
        self.operators
            .iter()
            .filter(|&&op| op != PauliOperator::I)
            .count()
    }

    /// Convert to Pauli string representation
    #[must_use]
    pub fn pauli_string(&self) -> String {
        self.operators
            .iter()
            .map(std::string::ToString::to_string)
            .collect()
    }

    /// Create time evolution circuit for this Pauli string
    pub fn evolution_circuit(&self, time: f64) -> Result<DynamicCircuit> {
        let mut circuit = DynamicCircuit::new(self.num_qubits);

        if self.weight() == 0 {
            // Identity operator - no gates needed
            return Ok(circuit);
        }

        let non_identity = self.non_identity_ops();
        let angle = -2.0 * self.coefficient.re * time;

        if non_identity.len() == 1 {
            // Single-qubit Pauli evolution
            let (qubit, op) = non_identity[0];
            match op {
                PauliOperator::X => circuit.add_gate(Box::new(RotationX {
                    target: QubitId::new(qubit as u32),
                    theta: angle,
                }))?,
                PauliOperator::Y => circuit.add_gate(Box::new(RotationY {
                    target: QubitId::new(qubit as u32),
                    theta: angle,
                }))?,
                PauliOperator::Z => circuit.add_gate(Box::new(RotationZ {
                    target: QubitId::new(qubit as u32),
                    theta: angle,
                }))?,
                PauliOperator::I => {} // Should not happen
            }
        } else {
            // Multi-qubit Pauli string evolution

            // Apply basis rotations to convert all non-identity operators to Z
            for &(qubit, op) in &non_identity {
                match op {
                    PauliOperator::X => circuit.add_gate(Box::new(Hadamard {
                        target: QubitId::new(qubit as u32),
                    }))?,
                    PauliOperator::Y => {
                        circuit.add_gate(Box::new(Hadamard {
                            target: QubitId::new(qubit as u32),
                        }))?;
                        circuit.add_gate(Box::new(Phase {
                            target: QubitId::new(qubit as u32),
                        }))?;
                    }
                    PauliOperator::Z => {} // No basis change needed
                    PauliOperator::I => {} // Should not happen
                }
            }

            // Apply CNOT ladder to disentangle all Z operators to the last qubit
            for i in 0..non_identity.len() - 1 {
                circuit.add_gate(Box::new(CNOT {
                    control: QubitId::new(non_identity[i].0 as u32),
                    target: QubitId::new(non_identity[i + 1].0 as u32),
                }))?;
            }

            // Apply Z rotation on the last qubit
            circuit.add_gate(Box::new(RotationZ {
                target: QubitId::new(non_identity[non_identity.len() - 1].0 as u32),
                theta: angle,
            }))?;

            // Reverse CNOT ladder
            for i in (0..non_identity.len() - 1).rev() {
                circuit.add_gate(Box::new(CNOT {
                    control: QubitId::new(non_identity[i].0 as u32),
                    target: QubitId::new(non_identity[i + 1].0 as u32),
                }))?;
            }

            // Reverse basis rotations
            for &(qubit, op) in non_identity.iter().rev() {
                match op {
                    PauliOperator::X => circuit.add_gate(Box::new(Hadamard {
                        target: QubitId::new(qubit as u32),
                    }))?,
                    PauliOperator::Y => {
                        circuit.add_gate(Box::new(PhaseDagger {
                            target: QubitId::new(qubit as u32),
                        }))?;
                        circuit.add_gate(Box::new(Hadamard {
                            target: QubitId::new(qubit as u32),
                        }))?;
                    }
                    PauliOperator::Z => {} // No basis change needed
                    PauliOperator::I => {} // Should not happen
                }
            }
        }

        Ok(circuit)
    }
}

impl fmt::Display for PauliString {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "({}) {}", self.coefficient, self.pauli_string())
    }
}

/// Sum of Pauli strings (Pauli operator)
#[derive(Debug, Clone)]
pub struct PauliOperatorSum {
    /// Individual Pauli string terms
    pub terms: Vec<PauliString>,
    /// Number of qubits
    pub num_qubits: usize,
}

impl PauliOperatorSum {
    /// Create new empty sum
    #[must_use]
    pub const fn new(num_qubits: usize) -> Self {
        Self {
            terms: Vec::new(),
            num_qubits,
        }
    }

    /// Add a Pauli string term
    pub fn add_term(&mut self, pauli_string: PauliString) -> Result<()> {
        if pauli_string.num_qubits != self.num_qubits {
            return Err(SimulatorError::DimensionMismatch(format!(
                "Pauli string has {} qubits, expected {}",
                pauli_string.num_qubits, self.num_qubits
            )));
        }
        self.terms.push(pauli_string);
        Ok(())
    }

    /// Combine like terms
    pub fn simplify(&mut self) {
        let mut simplified_terms: HashMap<String, Complex64> = HashMap::new();

        for term in &self.terms {
            let key = format!("{term}");
            *simplified_terms
                .entry(key)
                .or_insert(Complex64::new(0.0, 0.0)) += term.coefficient;
        }

        self.terms.clear();
        for (pauli_str, coeff) in simplified_terms {
            if coeff.norm() > 1e-15 {
                if let Ok(term) = PauliString::from_string(&pauli_str, coeff) {
                    self.terms.push(term);
                }
            }
        }
    }

    /// Convert to Hamiltonian for Trotter evolution
    #[must_use]
    pub fn to_hamiltonian(&self) -> Hamiltonian {
        let mut ham = Hamiltonian::new(self.num_qubits);

        for term in &self.terms {
            let non_identity = term.non_identity_ops();

            match non_identity.len() {
                0 => {} // Identity term - ignore for Hamiltonian
                1 => {
                    let (qubit, op) = non_identity[0];
                    let pauli_str = match op {
                        PauliOperator::X => "X",
                        PauliOperator::Y => "Y",
                        PauliOperator::Z => "Z",
                        PauliOperator::I => continue,
                    };
                    let _ = ham.add_single_pauli(qubit, pauli_str, term.coefficient.re);
                }
                2 => {
                    let (q1, op1) = non_identity[0];
                    let (q2, op2) = non_identity[1];
                    let pauli1 = match op1 {
                        PauliOperator::X => "X",
                        PauliOperator::Y => "Y",
                        PauliOperator::Z => "Z",
                        PauliOperator::I => continue,
                    };
                    let pauli2 = match op2 {
                        PauliOperator::X => "X",
                        PauliOperator::Y => "Y",
                        PauliOperator::Z => "Z",
                        PauliOperator::I => continue,
                    };
                    let _ = ham.add_two_pauli(q1, q2, pauli1, pauli2, term.coefficient.re);
                }
                _ => {
                    // Multi-qubit case
                    let qubits: Vec<usize> = non_identity.iter().map(|&(q, _)| q).collect();
                    let paulis: Vec<String> = non_identity
                        .iter()
                        .map(|&(_, op)| match op {
                            PauliOperator::X => "X".to_string(),
                            PauliOperator::Y => "Y".to_string(),
                            PauliOperator::Z => "Z".to_string(),
                            PauliOperator::I => "I".to_string(),
                        })
                        .collect();
                    let _ = ham.add_pauli_string(qubits, paulis, term.coefficient.re);
                }
            }
        }

        ham
    }

    /// Time evolution using Trotter decomposition
    pub fn time_evolution_circuit(
        &self,
        time: f64,
        trotter_steps: usize,
        method: TrotterMethod,
    ) -> Result<DynamicCircuit> {
        let hamiltonian = self.to_hamiltonian();
        let decomposer = TrotterDecomposer::new(method, trotter_steps);
        decomposer.decompose(&hamiltonian, time)
    }

    /// Direct time evolution without Trotter approximation (for single terms)
    pub fn exact_evolution_circuit(&self, time: f64) -> Result<DynamicCircuit> {
        let mut circuit = DynamicCircuit::new(self.num_qubits);

        for term in &self.terms {
            let term_circuit = term.evolution_circuit(time)?;
            for gate in term_circuit.gates() {
                circuit.add_gate(gate.clone())?;
            }
        }

        Ok(circuit)
    }
}

impl fmt::Display for PauliOperatorSum {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.terms.is_empty() {
            write!(f, "0")
        } else {
            let term_strs: Vec<String> = self.terms.iter().map(|t| format!("{t}")).collect();
            write!(f, "{}", term_strs.join(" + "))
        }
    }
}

/// Utilities for common Pauli string operations
pub struct PauliUtils;

impl PauliUtils {
    /// Create a single-qubit Pauli string
    pub fn single_qubit(
        num_qubits: usize,
        qubit: usize,
        op: PauliOperator,
        coeff: Complex64,
    ) -> Result<PauliString> {
        PauliString::from_ops(num_qubits, &[(qubit, op)], coeff)
    }

    /// Create an all-X Pauli string
    #[must_use]
    pub fn all_x(num_qubits: usize, coeff: Complex64) -> PauliString {
        let mut pauli = PauliString::new(num_qubits);
        pauli.coefficient = coeff;
        for i in 0..num_qubits {
            pauli.operators[i] = PauliOperator::X;
        }
        pauli
    }

    /// Create an all-Z Pauli string
    #[must_use]
    pub fn all_z(num_qubits: usize, coeff: Complex64) -> PauliString {
        let mut pauli = PauliString::new(num_qubits);
        pauli.coefficient = coeff;
        for i in 0..num_qubits {
            pauli.operators[i] = PauliOperator::Z;
        }
        pauli
    }

    /// Create random Pauli string
    pub fn random(num_qubits: usize, weight: usize, coeff: Complex64) -> Result<PauliString> {
        if weight > num_qubits {
            return Err(SimulatorError::InvalidInput(
                "Weight cannot exceed number of qubits".to_string(),
            ));
        }

        let mut pauli = PauliString::new(num_qubits);
        pauli.coefficient = coeff;

        // Randomly select positions for non-identity operators
        let mut positions: Vec<usize> = (0..num_qubits).collect();
        fastrand::shuffle(&mut positions);

        let ops = [PauliOperator::X, PauliOperator::Y, PauliOperator::Z];

        for &pos in &positions[..weight] {
            pauli.operators[pos] = ops[fastrand::usize(0..3)];
        }

        Ok(pauli)
    }

    /// Check if a set of Pauli strings are mutually commuting
    #[must_use]
    pub fn are_mutually_commuting(pauli_strings: &[PauliString]) -> bool {
        for i in 0..pauli_strings.len() {
            for j in i + 1..pauli_strings.len() {
                if !pauli_strings[i].commutes_with(&pauli_strings[j]) {
                    return false;
                }
            }
        }
        true
    }

    /// Find maximal set of mutually commuting Pauli strings
    #[must_use]
    pub fn maximal_commuting_set(pauli_strings: &[PauliString]) -> Vec<usize> {
        let mut commuting_set = Vec::new();

        for (i, pauli) in pauli_strings.iter().enumerate() {
            let mut can_add = true;
            for &j in &commuting_set {
                if !pauli.commutes_with(&pauli_strings[j]) {
                    can_add = false;
                    break;
                }
            }

            if can_add {
                commuting_set.push(i);
            }
        }

        commuting_set
    }
}

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

    #[test]
    fn test_pauli_operator_multiply() {
        let (result, phase) = PauliOperator::X.multiply(&PauliOperator::Y);
        assert_eq!(result, PauliOperator::Z);
        assert_eq!(phase, Complex64::new(0.0, 1.0));

        let (result, phase) = PauliOperator::Y.multiply(&PauliOperator::X);
        assert_eq!(result, PauliOperator::Z);
        assert_eq!(phase, Complex64::new(0.0, -1.0));
    }

    #[test]
    fn test_pauli_string_creation() {
        let pauli = PauliString::from_string("XYZ", Complex64::new(1.0, 0.0))
            .expect("Pauli string 'XYZ' should be parsed successfully");
        assert_eq!(pauli.num_qubits, 3);
        assert_eq!(pauli.operators[0], PauliOperator::X);
        assert_eq!(pauli.operators[1], PauliOperator::Y);
        assert_eq!(pauli.operators[2], PauliOperator::Z);
    }

    #[test]
    fn test_pauli_string_multiply() {
        let p1 = PauliString::from_string("XY", Complex64::new(1.0, 0.0))
            .expect("Pauli string 'XY' should be parsed successfully");
        let p2 = PauliString::from_string("YZ", Complex64::new(1.0, 0.0))
            .expect("Pauli string 'YZ' should be parsed successfully");

        let result = p1
            .multiply(&p2)
            .expect("Pauli string multiplication should succeed");
        assert_eq!(result.operators[0], PauliOperator::Z);
        assert_eq!(result.operators[1], PauliOperator::X);
        assert_eq!(result.coefficient, Complex64::new(-1.0, 0.0));
    }

    #[test]
    fn test_pauli_string_commutation() {
        let p1 = PauliString::from_string("XY", Complex64::new(1.0, 0.0))
            .expect("Pauli string 'XY' should be parsed successfully");
        let p2 = PauliString::from_string("ZI", Complex64::new(1.0, 0.0))
            .expect("Pauli string 'ZI' should be parsed successfully");
        let p3 = PauliString::from_string("XI", Complex64::new(1.0, 0.0))
            .expect("Pauli string 'XI' should be parsed successfully");

        assert!(!p1.commutes_with(&p2)); // XY and ZI anti-commute at first qubit
        assert!(p1.commutes_with(&p3)); // XY and XI commute
    }

    #[test]
    fn test_pauli_string_weight() {
        let p1 = PauliString::from_string("XIYZ", Complex64::new(1.0, 0.0))
            .expect("Pauli string 'XIYZ' should be parsed successfully");
        assert_eq!(p1.weight(), 3);

        let p2 = PauliString::from_string("IIII", Complex64::new(1.0, 0.0))
            .expect("Pauli string 'IIII' should be parsed successfully");
        assert_eq!(p2.weight(), 0);
    }

    #[test]
    fn test_pauli_operator_sum() {
        let mut sum = PauliOperatorSum::new(2);

        let p1 = PauliString::from_string("XX", Complex64::new(1.0, 0.0))
            .expect("Pauli string 'XX' should be parsed successfully");
        let p2 = PauliString::from_string("YY", Complex64::new(0.5, 0.0))
            .expect("Pauli string 'YY' should be parsed successfully");

        sum.add_term(p1)
            .expect("Adding term 'XX' to sum should succeed");
        sum.add_term(p2)
            .expect("Adding term 'YY' to sum should succeed");

        assert_eq!(sum.terms.len(), 2);
    }

    #[test]
    fn test_evolution_circuit_single_qubit() {
        let pauli = PauliString::from_string("X", Complex64::new(1.0, 0.0))
            .expect("Pauli string 'X' should be parsed successfully");
        let circuit = pauli
            .evolution_circuit(1.0)
            .expect("Evolution circuit creation should succeed");
        assert!(circuit.gate_count() > 0);
    }

    #[test]
    fn test_evolution_circuit_multi_qubit() {
        let pauli = PauliString::from_string("XYZ", Complex64::new(1.0, 0.0))
            .expect("Pauli string 'XYZ' should be parsed successfully");
        let circuit = pauli
            .evolution_circuit(1.0)
            .expect("Evolution circuit creation should succeed");
        assert!(circuit.gate_count() > 0);
    }

    #[test]
    fn test_utils_single_qubit() {
        let pauli = PauliUtils::single_qubit(3, 1, PauliOperator::X, Complex64::new(1.0, 0.0))
            .expect("Single qubit Pauli creation should succeed");
        assert_eq!(pauli.operators[0], PauliOperator::I);
        assert_eq!(pauli.operators[1], PauliOperator::X);
        assert_eq!(pauli.operators[2], PauliOperator::I);
    }

    #[test]
    fn test_mutually_commuting() {
        let p1 = PauliString::from_string("XX", Complex64::new(1.0, 0.0))
            .expect("Pauli string 'XX' should be parsed successfully");
        let p2 = PauliString::from_string("ZZ", Complex64::new(1.0, 0.0))
            .expect("Pauli string 'ZZ' should be parsed successfully");
        let p3 = PauliString::from_string("YY", Complex64::new(1.0, 0.0))
            .expect("Pauli string 'YY' should be parsed successfully");

        let paulis = vec![p1, p2, p3];
        assert!(PauliUtils::are_mutually_commuting(&paulis));
    }
}