struqture 2.5.1

HQS tool for representing operators, Hamiltonians and open systems.
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
// Copyright © 2021-2023 HQS Quantum Simulations GmbH. All Rights Reserved.
//
// 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::fermions::FermionOperator;
use crate::mappings::JordanWignerSpinToFermion;
use crate::prelude::*;
use crate::spins::{PauliOperator, PlusMinusOperator};
use crate::{CorrespondsTo, GetValue, SpinIndex, StruqtureError, SymmetricIndex};
use num_complex::Complex64;
use qoqo_calculator::CalculatorComplex;
use serde::de::{Deserializer, Error, SeqAccess, Visitor};
use serde::ser::{SerializeSeq, Serializer};
use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
use std::collections::HashMap;
use std::fmt;
use std::hash::Hash;
use std::iter::{FromIterator, IntoIterator};
use std::ops::Mul;
use std::str::FromStr;
use tinyvec::{TinyVec, TinyVecIterator};
const INTERNAL_BUG_ADD_OPERATOR_PRODUCT: &str = "Internal bug in add_operator_product.";

/// Single Spin operators for PauliProducts:
///
/// I: identity matrix
/// $$
/// \begin{pmatrix}
/// 1 & 0\\\\
/// 0 & 1
/// \end{pmatrix}
/// $$
///
/// X: pauli x matrix
/// $$
/// \begin{pmatrix}
/// 0 & 1\\\\
/// 1 & 0
/// \end{pmatrix}
/// $$
///
/// Y: pauli y matrix
/// $$
/// \begin{pmatrix}
/// 0 & -i\\\\
/// i & 0
/// \end{pmatrix}
/// $$
///
/// Z: pauli z matrix
/// $$
/// \begin{pmatrix}
/// 1 & 0\\\\
/// 0 & -1
/// \end{pmatrix}
/// $$
///
#[derive(
    Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Default,
)]
#[cfg_attr(feature = "json_schema", derive(schemars::JsonSchema))]
pub enum SinglePauliOperator {
    #[default]
    Identity,
    X,
    Y,
    Z,
}

/// Creates a SinglePauliOperator from an &str representation.
///
/// # Arguments
///
/// * `s` - The string (&str) to be converted to a SinglePauliOperator.
///
/// # Returns
///
/// * `Ok(Self)` - The SinglePauliOperator of the input string.
/// * `Err(StruqtureError::IncorrectPauliEntry)` - The pauli matrix being set is not in [\"I\", \"X\", \"Y\", \"Z\"].
///
impl FromStr for SinglePauliOperator {
    type Err = StruqtureError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "I" => Ok(SinglePauliOperator::Identity),
            "X" => Ok(SinglePauliOperator::X),
            "Y" => Ok(SinglePauliOperator::Y),
            "Z" => Ok(SinglePauliOperator::Z),
            _ => Err(StruqtureError::IncorrectPauliEntry {
                pauli: s.to_string(),
            }),
        }
    }
}

/// Implements the fmt function (Display trait) of SinglePauliOperator.
///
impl fmt::Display for SinglePauliOperator {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SinglePauliOperator::Identity => write!(f, "I"),
            SinglePauliOperator::X => write!(f, "X"),
            SinglePauliOperator::Y => write!(f, "Y"),
            SinglePauliOperator::Z => write!(f, "Z"),
        }
    }
}

/// Functions for the SinglePauliOperator
///
impl SinglePauliOperator {
    /// Implements multiplication function for a SinglePauliOperator by a SinglePauliOperator.
    ///
    /// # Arguments
    ///
    /// * `left` - left-hand SinglePauliOperator to be multiplied.
    /// * `right` - right-hand SinglePauliOperator to be multiplied.
    pub fn multiply(left: SinglePauliOperator, right: SinglePauliOperator) -> (Self, Complex64) {
        let (result, coeff): (SinglePauliOperator, Complex64) = match (left, right) {
            (SinglePauliOperator::Identity, x) => (x, Complex64::new(1.0, 0.0)),
            (x, SinglePauliOperator::Identity) => (x, Complex64::new(1.0, 0.0)),
            (SinglePauliOperator::X, SinglePauliOperator::X) => {
                (SinglePauliOperator::Identity, Complex64::new(1.0, 0.0))
            }
            (SinglePauliOperator::X, SinglePauliOperator::Y) => {
                (SinglePauliOperator::Z, Complex64::new(0.0, 1.0))
            }
            (SinglePauliOperator::X, SinglePauliOperator::Z) => {
                (SinglePauliOperator::Y, Complex64::new(0.0, -1.0))
            }
            (SinglePauliOperator::Y, SinglePauliOperator::X) => {
                (SinglePauliOperator::Z, Complex64::new(0.0, -1.0))
            }
            (SinglePauliOperator::Y, SinglePauliOperator::Y) => {
                (SinglePauliOperator::Identity, Complex64::new(1.0, 0.0))
            }
            (SinglePauliOperator::Y, SinglePauliOperator::Z) => {
                (SinglePauliOperator::X, Complex64::new(0.0, 1.0))
            }
            (SinglePauliOperator::Z, SinglePauliOperator::X) => {
                (SinglePauliOperator::Y, Complex64::new(0.0, 1.0))
            }
            (SinglePauliOperator::Z, SinglePauliOperator::Y) => {
                (SinglePauliOperator::X, Complex64::new(0.0, -1.0))
            }
            (SinglePauliOperator::Z, SinglePauliOperator::Z) => {
                (SinglePauliOperator::Identity, Complex64::new(1.0, 0.0))
            }
        };
        (result, coeff)
    }
}

/// PauliProducts are combinations of SinglePauliOperators on specific qubits.
///
/// This is a representation of products of pauli matrices acting on qubits, in order to build the terms of a hamiltonian.
/// For instance, to represent the term $ \sigma_0^{x} \sigma_2^{x} $ :
/// ` PauliProduct::new().x(0).x(2) `
///
/// # Example
///
/// ```
/// use struqture::prelude::*;
/// use struqture::spins::{PauliProduct, SinglePauliOperator};
///
/// let mut pp = PauliProduct::new();
///
/// // Method 1 to add to PauliProduct:
/// pp = pp.set_pauli(0, SinglePauliOperator::X);
/// // Method 2 to add to PauliProduct:
/// pp = pp.z(1);
/// // These methods are equal:
/// assert_eq!(pp.clone().x(2), pp.clone().set_pauli(2, SinglePauliOperator::X));
///
/// // Access what you set:
/// assert_eq!(pp.get(&0).unwrap(), &SinglePauliOperator::X);
/// ```
///
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct PauliProduct {
    /// The internal dictionary of pauli matrices (I, X, Y, Z) and qubits
    items: TinyVec<[(usize, SinglePauliOperator); 5]>,
}
/// Implementing serde serialization writing directly to string.
///
impl Serialize for PauliProduct {
    /// Serialization function for PauliProduct according to string type.
    ///
    /// # Arguments
    ///
    /// * `self` - PauliProduct to be serialized.
    /// * `serializer` - Serializer used for serialization.
    ///
    /// # Returns
    ///
    /// `S::Ok` - Serialized instance of PauliProduct.
    /// `S::Error` - Error in the serialization process.
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let readable = serializer.is_human_readable();
        if readable {
            serializer.serialize_str(&self.to_string())
        } else {
            let mut sequence = serializer.serialize_seq(Some(self.items.len()))?;
            for item in self.items.iter() {
                sequence.serialize_element(item)?;
            }
            sequence.end()
        }
    }
}

#[cfg(feature = "json_schema")]
use schemars;

#[cfg(feature = "json_schema")]
impl schemars::JsonSchema for PauliProduct {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "struqture::spins::PauliProduct".into()
    }

    fn json_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        schemars::json_schema!({
            "type": "string",
            "description": "Represents products of Pauli Operators by a string of spin numbers followed by pauli operators. E.g. 0X10Y13Z14X."
        })
    }
}

impl crate::SerializationSupport for PauliProduct {
    fn struqture_type() -> crate::StruqtureType {
        crate::StruqtureType::PauliProduct
    }
}

/// Deserializing directly from string.
///
impl<'de> Deserialize<'de> for PauliProduct {
    /// Deserialization function for PauliProduct.
    ///
    /// # Arguments
    ///
    /// * `self` - Serialized instance of PauliProduct to be deserialized.
    /// * `deserializer` - Deserializer used for deserialization.
    ///
    /// # Returns
    ///
    /// `PauliProduct` - Deserialized instance of PauliProduct.
    /// `D::Error` - Error in the deserialization process.
    fn deserialize<D>(deserializer: D) -> Result<PauliProduct, D::Error>
    where
        D: Deserializer<'de>,
    {
        let human_readable = deserializer.is_human_readable();
        if human_readable {
            struct TemporaryVisitor;
            impl<'de> Visitor<'de> for TemporaryVisitor {
                type Value = PauliProduct;

                fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                    formatter.write_str("String")
                }

                fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
                where
                    E: serde::de::Error,
                {
                    PauliProduct::from_str(v).map_err(|err| E::custom(format!("{err:?}")))
                }

                fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
                where
                    E: Error,
                {
                    PauliProduct::from_str(v).map_err(|err| E::custom(format!("{err:?}")))
                }
            }

            deserializer.deserialize_str(TemporaryVisitor)
        } else {
            struct PauliProductVisitor;
            impl<'de> serde::de::Visitor<'de> for PauliProductVisitor {
                type Value = PauliProduct;
                fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                    fmt::Formatter::write_str(formatter, "Identifier of PauliProduct variant")
                }
                // when variants are marked by String values
                fn visit_seq<M>(self, mut access: M) -> Result<Self::Value, M::Error>
                where
                    M: SeqAccess<'de>,
                {
                    let mut pp = PauliProduct::new();
                    while let Some(item) = access.next_element()? {
                        let entry: Entry = item;
                        pp = pp.set_pauli(entry.0 .0, entry.0 .1);
                    }
                    Ok(pp)
                }
            }
            #[derive(Deserialize)]
            #[serde(transparent)]
            struct Entry((usize, SinglePauliOperator));
            let pp_visitor = PauliProductVisitor;

            deserializer.deserialize_seq(pp_visitor)
        }
    }
}

impl SpinIndex for PauliProduct {
    type SingleSpinType = SinglePauliOperator;

    // From trait
    fn new() -> Self {
        PauliProduct {
            items: TinyVec::<[(usize, SinglePauliOperator); 5]>::with_capacity(5),
        }
    }

    // From trait
    fn set_pauli(self, index: usize, pauli: SinglePauliOperator) -> Self {
        let mut pp = self;
        if let Some((vecindex, insertindex, index_in_use)) =
            pp.items
                .iter()
                .enumerate()
                .find_map(|(vecindex, (innerindex, _))| {
                    if innerindex >= &index {
                        Some((vecindex, *innerindex, innerindex == &index))
                    } else {
                        None
                    }
                })
        {
            if index_in_use {
                match pauli {
                    SinglePauliOperator::Identity => {
                        let _x = pp.items.remove(vecindex);
                    }
                    _ => pp.items[vecindex] = (insertindex, pauli),
                }
            } else {
                match pauli {
                    SinglePauliOperator::Identity => (),
                    _ => {
                        pp.items.insert(vecindex, (index, pauli));
                    }
                }
            }
        } else {
            match pauli {
                SinglePauliOperator::Identity => (),
                _ => {
                    pp.items.push((index, pauli));
                }
            }
        }
        pp
    }

    // From trait
    fn get(&self, index: &usize) -> Option<&SinglePauliOperator> {
        self.items
            .iter()
            .find_map(|(key, value)| if key == index { Some(value) } else { None })
    }

    // From trait
    fn iter(&self) -> std::slice::Iter<'_, (usize, SinglePauliOperator)> {
        match &self.items {
            TinyVec::Heap(x) => x.iter(),
            TinyVec::Inline(x) => x.iter(),
        }
    }

    // From trait
    fn remap_qubits(&self, mapping: &HashMap<usize, usize>) -> PauliProduct {
        let mut mutable_internal: TinyVec<[(usize, SinglePauliOperator); 5]> =
            TinyVec::<[(usize, SinglePauliOperator); 5]>::with_capacity(10);

        for (key, val) in self.iter() {
            mutable_internal.push(match mapping.get(key) {
                Some(x) => (*x, *val),
                None => (*key, *val),
            });
        }
        mutable_internal.sort_by(|(left_index, _), (right_index, _)| {
            left_index
                .partial_cmp(right_index)
                .expect("Cannot compare two unsigned integers internal error in struqture.spins")
        });
        PauliProduct {
            items: mutable_internal,
        }
    }

    // From trait
    fn multiply(left: PauliProduct, right: PauliProduct) -> (Self, Complex64) {
        left * right
    }

    // From trait
    fn concatenate(&self, other: PauliProduct) -> Result<PauliProduct, StruqtureError> {
        let mut return_list = self.items.clone();
        for (key, val) in other.iter() {
            if return_list.iter().any(|(index, _)| index == key) {
                return Err(StruqtureError::ProductIndexAlreadyOccupied { index: *key });
            } else {
                return_list.push((*key, *val));
            }
        }
        return_list.sort_by(|(left_index, _), (right_index, _)| {
            left_index
                .partial_cmp(right_index)
                .expect("Cannot compare two unsigned integers internal error in struqture.spins")
        });
        Ok(PauliProduct { items: return_list })
    }
}

/// Implements Ord for PauliProducts; length then index of the pauliproducts then operator of the products.
///
/// Using Rust's "Derived" ordering provides only lexicographical ordering.
/// Here we explicitly augment this to include the length of the PauliProduct
/// for comparison. For an example operator set: `[1X, 2Y, 1X2Y, 2X3Y, 1X2X3Z]`,
/// this would be ordered under this definition. Under the old behaviour this
/// set would order as: `[1X, 1X2X3Z, 1X2Y, 2X3Y, 2Y]` which is less readable.
///
/// # Arguments
///
/// * `self` - PauliProduct to be ordered.
///
/// # Returns
///
/// `Ordering` - The ordering result
impl Ord for PauliProduct {
    fn cmp(&self, other: &Self) -> Ordering {
        let me: &TinyVec<[(usize, SinglePauliOperator); 5]> = &(self.items);
        let them: &TinyVec<[(usize, SinglePauliOperator); 5]> = &(other.items);

        match me.len().cmp(&them.len()) {
            Ordering::Less => Ordering::Less,
            Ordering::Equal => me
                .into_iter()
                .cloned()
                .unzip::<usize, SinglePauliOperator, Vec<usize>, Vec<SinglePauliOperator>>()
                .cmp(
                    &them
                        .into_iter()
                        .cloned()
                        .unzip::<usize, SinglePauliOperator, Vec<usize>, Vec<SinglePauliOperator>>(
                        ),
                ), // If lengths are equal use the qubit index for comparison, then the pauli terms.
            Ordering::Greater => Ordering::Greater,
        }
    }
}

/// This method returns an ordering between `self` and `other` values if one exists.
impl PartialOrd for PauliProduct {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl CorrespondsTo<PauliProduct> for PauliProduct {
    /// Gets the PauliProduct corresponding to self (here, itself).
    ///
    /// # Returns
    ///
    /// * `PauliProduct` - The PauliProduct corresponding to Self.
    fn corresponds_to(&self) -> PauliProduct {
        self.clone()
    }
}

impl SymmetricIndex for PauliProduct {
    // From trait
    fn hermitian_conjugate(&self) -> (Self, f64) {
        (self.clone(), 1.0)
    }

    // From trait
    fn is_natural_hermitian(&self) -> bool {
        true
    }
}

/// Implements the multiplication function of PauliProduct by PauliProduct.
///
impl Mul<PauliProduct> for PauliProduct {
    type Output = (Self, Complex64);
    /// Implement `*` for PauliProduct and PauliProduct.
    ///
    /// # Arguments
    ///
    /// * `other` - The PauliProduct to multiply by.
    ///
    /// # Returns
    ///
    /// * `(Self, Complex64)` - The two PauliProducts multiplied and the resulting prefactor.
    ///
    /// # Panics
    ///
    /// * Unexpectedly failed construction of PauliProduct creation internal struqture bug.
    fn mul(self, rhs: PauliProduct) -> Self::Output {
        let mut factor = Complex64::new(1.0, 0.0);
        let mut return_product = PauliProduct::new();
        for (key, left_operator) in self.iter() {
            match rhs.get(key) {
                Some(right_operator) => {
                    let (tmp_product, tmp_factor) =
                        SinglePauliOperator::multiply(*left_operator, *right_operator);
                    factor *= tmp_factor;
                    return_product = return_product.set_pauli(*key, tmp_product);
                }
                None => {
                    return_product = return_product.set_pauli(*key, *left_operator);
                }
            }
        }
        for (key, right_operator) in rhs.iter().filter(|(key, _)| self.get(key).is_none()) {
            return_product = return_product.set_pauli(*key, *right_operator);
        }

        (return_product, factor)
    }
}

impl GetValue<PauliProduct> for PauliProduct {
    type ValueIn = CalculatorComplex;
    type ValueOut = CalculatorComplex;

    /// Gets the key corresponding to the input index (here, itself).
    ///
    /// # Arguments
    ///
    /// * `index` - The index for which to get the corresponding Product.
    ///
    /// # Returns
    ///
    /// * `Self` - The corresponding PauliProduct.
    fn get_key(index: &PauliProduct) -> Self {
        index.clone()
    }

    /// Gets the transformed value corresponding to the input index and value (here, itself).
    ///
    /// # Arguments
    ///
    /// * `index` - The index to transform the value by.
    /// * `value` - The value to be transformed.
    ///
    /// # Returns
    ///
    /// * `CalculatorComplex` - The transformed value.
    fn get_transform(
        _index: &PauliProduct,
        value: qoqo_calculator::CalculatorComplex,
    ) -> qoqo_calculator::CalculatorComplex {
        value
    }
}

/// Functions for the PauliProduct
///
impl PauliProduct {
    /// Export to struqture_1 format.
    #[cfg(feature = "struqture_1_export")]
    pub fn to_struqture_1(&self) -> Result<struqture_1::spins::PauliProduct, StruqtureError> {
        let self_string = self.to_string();
        let struqture_1_product = struqture_1::spins::PauliProduct::from_str(&self_string)
            .map_err(|err| StruqtureError::GenericError {
                msg: format!("{err}"),
            })?;
        Ok(struqture_1_product)
    }

    /// Export to struqture_1 format.
    #[cfg(feature = "struqture_1_import")]
    pub fn from_struqture_1(
        value: &struqture_1::spins::PauliProduct,
    ) -> Result<Self, StruqtureError> {
        let value_string = value.to_string();
        let pauli_product = Self::from_str(&value_string)?;
        Ok(pauli_product)
    }

    /// Sets a new entry for SinglePauliOperator X in the internal dictionary. This function consumes Self.
    ///
    /// # Arguments
    ///
    /// * `index` - Index of set object.
    ///
    /// # Returns
    ///
    /// * `Self` - The entry was correctly set and the PauliProduct is returned.
    pub fn x(self, index: usize) -> Self {
        self.set_pauli(index, SinglePauliOperator::X)
    }

    /// Sets a new entry for SinglePauliOperator Y in the internal dictionary. This function consumes Self.
    ///
    /// # Arguments
    ///
    /// * `index` - Index of set object.
    ///
    /// # Returns
    ///
    /// * `Self` - The entry was correctly set and the PauliProduct is returned.
    pub fn y(self, index: usize) -> Self {
        self.set_pauli(index, SinglePauliOperator::Y)
    }

    /// Sets a new entry for SinglePauliOperator Z in the internal dictionary. This function consumes Self.
    ///
    /// # Arguments
    ///
    /// * `index` - Index of set object.
    ///
    /// # Returns
    ///
    /// * `Self` - The entry was correctly set and the PauliProduct is returned.
    pub fn z(self, index: usize) -> Self {
        self.set_pauli(index, SinglePauliOperator::Z)
    }

    /// Creates a new PauliProduct with pre-allocated capacity.
    ///
    /// # Arguments
    ///
    /// * `capacity` - The capacity of the PauliProduct to create.
    ///
    /// # Returns
    ///
    /// * `Self` - The new (empty) PauliProduct.
    pub fn with_capacity(cap: usize) -> Self {
        PauliProduct {
            items: TinyVec::<[(usize, SinglePauliOperator); 5]>::with_capacity(cap),
        }
    }
}

/// Implements the default function (Default trait) of PauliProduct (an empty PauliProduct).
///
impl Default for PauliProduct {
    fn default() -> Self {
        Self::new()
    }
}

impl FromStr for PauliProduct {
    type Err = StruqtureError;
    /// Constructs a PauliProduct from a string.
    ///
    /// # Arguments
    ///
    /// * `s` - The string to convert.
    ///
    /// # Returns
    ///
    /// * `Ok(Self)` - The successfully converted PauliProduct.
    /// * `Err(StruqtureError::IncorrectPauliEntry)` - The pauli matrix being set is not in [\"I\", \"X\", \"Y\", \"Z\"].
    /// * `Err(StruqtureError::FromStringFailed)` - Using {} instead of unsigned integer as spin index.
    /// * `Err(StruqtureError::FromStringFailed)` - At least one spin index is used more than once.
    ///
    /// # Panics
    ///
    /// * Cannot compare two unsigned integers internal error in struqture.spins.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s == "I" || s.is_empty() {
            Ok(Self::new()) // If the string is identity then it's an empty PauliProduct
        } else {
            if !s.starts_with(char::is_numeric) {
                return Err(StruqtureError::FromStringFailed {
                    msg: format!("Missing spin index in the following PauliProduct: {s}"),
                });
            }
            let mut internal: TinyVec<[(usize, SinglePauliOperator); 5]> =
                TinyVec::<[(usize, SinglePauliOperator); 5]>::with_capacity(10);

            let value = s.to_string();
            let vec_paulis = value.split(char::is_numeric).filter(|s| !s.is_empty());
            let vec_indices = value.split(char::is_alphabetic).filter(|s| !s.is_empty());

            for (index, pauli) in vec_indices.zip(vec_paulis) {
                match index.parse() {
                    Ok(num) => {
                        let spin: SinglePauliOperator = SinglePauliOperator::from_str(pauli)?;
                        match spin {
                            SinglePauliOperator::Identity => (),
                            _ => {
                                internal.push((num, spin));
                            }
                        }
                    }
                    Err(_) => {
                        return Err(StruqtureError::FromStringFailed {
                            msg: format!("Using {index} instead of unsigned integer as spin index"),
                        })
                    }
                }
            }
            internal.sort_by(|(left_index, _), (right_index, _)| {
                left_index.partial_cmp(right_index).expect(
                    "Cannot compare two unsigned integers internal error in struqture.spins",
                )
            });

            // We now check that all the internal elements are strictly increasing after sorting.
            // We could test this criteria while sorting, but this would require augmenting an
            // existing sorting routine, which is fraught with peril, instead we just do a linear
            // iteration using the "overlapping windows" iterator. Non-trivial example:"1X2Z3X2Y"
            // Note that .all() short-circuits if a single element is false (this is a good thing).
            match internal.windows(2).all(|w| w[0].0 < w[1].0) {
                true => Ok(PauliProduct { items: internal }),
                false => Err(StruqtureError::FromStringFailed {
                    msg: "At least one spin index is used more than once.".to_string(),
                }),
            }
        }
    }
}

/// Implements the format function (Display trait) of PauliProduct.
///
impl fmt::Display for PauliProduct {
    /// Formats the PauliProduct using the given formatter.
    ///
    /// # Arguments
    ///
    /// * `f` - The formatter to use.
    ///
    /// # Returns
    ///
    /// * `std::fmt::Result` - The formatted PauliProduct.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut string: String = String::new();
        if self.items.is_empty() {
            string.push('I');
        } else {
            for (index, pauli) in self.items.iter() {
                string.push_str(format!("{index}").as_str());
                string.push_str(format!("{pauli}").as_str());
            }
        }
        write!(f, "{string}")
    }
}

/// Implements the into_iter function (IntoIterator trait) of PauliProduct.
///
impl IntoIterator for PauliProduct {
    type Item = (usize, SinglePauliOperator);

    type IntoIter = TinyVecIterator<[(usize, SinglePauliOperator); 5]>;
    /// Returns the PauliProduct in Iterator form.
    ///
    /// # Returns
    ///
    /// * `Self::IntoIter` - The PauliProduct in Iterator form.
    fn into_iter(self) -> Self::IntoIter {
        self.items.into_iter()
    }
}

/// Implements the from_iter function (FromIterator trait) of PauliProduct.
///
impl FromIterator<(usize, SinglePauliOperator)> for PauliProduct {
    /// Returns the object in PauliProduct form, from an Iterator form of the object.
    ///
    /// # Arguments
    ///
    /// * `iter` - The iterator containing the information from which to create the PauliProduct.
    ///
    /// # Returns
    ///
    /// * `Self::IntoIter` - The iterator in PauliProduct form.
    fn from_iter<I: IntoIterator<Item = (usize, SinglePauliOperator)>>(iter: I) -> Self {
        let mut pp = PauliProduct::new();
        for (index, pauli) in iter {
            pp = pp.set_pauli(index, pauli);
        }
        pp
    }
}

/// Implements the extend function (Extend trait) of PauliProduct.
///
impl Extend<(usize, SinglePauliOperator)> for PauliProduct {
    /// Extends the PauliProduct by the specified operations (in Iterator form).
    ///
    /// # Arguments
    ///
    /// * `iter` - The iterator containing the operations by which to extend the PauliProduct.
    fn extend<I: IntoIterator<Item = (usize, SinglePauliOperator)>>(&mut self, iter: I) {
        let mut pp = self.clone();
        for (index, pauli) in iter {
            pp = pp.set_pauli(index, pauli);
        }
        *self = pp;
    }
}

impl JordanWignerSpinToFermion for PauliProduct {
    type Output = FermionOperator;

    /// Implements JordanWignerSpinToFermion for a PauliProduct.
    ///
    /// The convention used is that |0> represents an empty fermionic state (spin-orbital),
    /// and |1> represents an occupied fermionic state.
    ///
    /// # Returns
    ///
    /// `FermionOperator` - The fermion operator that results from the transformation.
    ///
    /// # Panics
    ///
    /// * Internal bug in `add_operator_product`
    fn jordan_wigner(&self) -> Self::Output {
        let mut qubit_operator = PauliOperator::new();
        qubit_operator
            .add_operator_product(self.clone(), 1.0.into())
            .expect(INTERNAL_BUG_ADD_OPERATOR_PRODUCT);

        let plus_minus_operator = PlusMinusOperator::from(qubit_operator);
        plus_minus_operator.jordan_wigner()
    }
}