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
// 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 super::{GetValueMixed, MixedIndex};
use crate::bosons::BosonProduct;
use crate::fermions::FermionProduct;
use crate::spins::DecoherenceProduct;
use crate::{StruqtureError, SymmetricIndex};
use num_complex::Complex64;
use serde::de::Error;
use serde::{
    de::{SeqAccess, Visitor},
    ser::SerializeTuple,
    Deserialize, Deserializer, Serialize, Serializer,
};
use std::{ops::Mul, str::FromStr};
use tinyvec::TinyVec;

/// A mixed product of decoherence products and boson products.
///
/// A [crate::spins::DecoherenceProduct] is a representation of products of decoherence matrices acting on qubits, in order to build the terms of a hamiltonian.
/// For instance, to represent the term $ \sigma_0^{+} \sigma_2^{-} $.
///
/// A [crate::bosons::BosonProduct] is a product of bosonic creation and annihilation operators.
/// It is used as an index for non-hermitian, normal ordered bosonic operators.
///
/// A [crate::fermions::FermionProduct] is a product of fermionic creation and annihilation operators.
/// It is used as an index for non-hermitian, normal ordered fermionic operators.
///
/// # Example
///
/// ```
/// use struqture::prelude::*;
/// use struqture::spins::DecoherenceProduct;
/// use struqture::bosons::BosonProduct;
/// use struqture::fermions::FermionProduct;
/// use struqture::mixed_systems::MixedDecoherenceProduct;
///
/// let m_product = MixedDecoherenceProduct::new([DecoherenceProduct::new().z(0)], [BosonProduct::new([0], [1]).unwrap()], [FermionProduct::new([0], [0]).unwrap()]).unwrap();
/// println!("{}", m_product);
///
/// ```
#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord, Default)]
pub struct MixedDecoherenceProduct {
    /// List of spin sub-indices
    spins: TinyVec<[DecoherenceProduct; 2]>,
    /// List of boson sub-indices
    bosons: TinyVec<[BosonProduct; 2]>,
    /// List of fermion sub-indices
    fermions: TinyVec<[FermionProduct; 2]>,
}

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

    fn json_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        schemars::json_schema!({
            "type": "string",
            "description": "Represents products of Spin operators and Bosonic and Fermionic creators and annhilators by a string. Spin Operators  X, iY and Z are preceeded and creators (c) and annihilators (a) are followed by the modes they are acting on. E.g. :S0X1iY:Bc0a0:Fc0a0:."
        })
    }
}

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

impl Serialize for MixedDecoherenceProduct {
    /// Serialization function for MixedDecoherenceProduct according to string type.
    ///
    /// # Arguments
    ///
    /// * `self` - MixedDecoherenceProduct to be serialized.
    /// * `serializer` - Serializer used for serialization.
    ///
    /// # Returns
    ///
    /// `S::Ok` - Serialized instance of MixedDecoherenceProduct.
    /// `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 tuple = serializer.serialize_tuple(3)?;
            tuple.serialize_element(&self.spins.as_slice())?;
            tuple.serialize_element(&self.bosons.as_slice())?;
            tuple.serialize_element(&self.fermions.as_slice())?;
            tuple.end()
        }
    }
}

/// Deserializing directly from string.
///
impl<'de> Deserialize<'de> for MixedDecoherenceProduct {
    /// Deserialization function for MixedDecoherenceProduct.
    ///
    /// # Arguments
    ///
    /// * `self` - Serialized instance of MixedDecoherenceProduct to be deserialized.
    /// * `deserializer` - Deserializer used for deserialization.
    ///
    /// # Returns
    ///
    /// `DecoherenceProduct` - Deserialized instance of MixedDecoherenceProduct.
    /// `D::Error` - Error in the deserialization process.
    fn deserialize<D>(deserializer: D) -> Result<MixedDecoherenceProduct, 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 = MixedDecoherenceProduct;

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

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

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

            deserializer.deserialize_str(TemporaryVisitor)
        } else {
            struct MixedDecoherenceProductVisitor;
            impl<'de> serde::de::Visitor<'de> for MixedDecoherenceProductVisitor {
                type Value = MixedDecoherenceProduct;
                fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                    std::fmt::Formatter::write_str(
                        formatter,
                        "Tuple of two sequences of unsigned integers",
                    )
                }
                // 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 spins: TinyVec<[DecoherenceProduct; 2]> = match access.next_element()? {
                        Some(x) => x,
                        None => {
                            return Err(M::Error::custom("Missing creator sequence".to_string()));
                        }
                    };
                    let bosons: TinyVec<[BosonProduct; 2]> = match access.next_element()? {
                        Some(x) => x,
                        None => {
                            return Err(M::Error::custom(
                                "Missing annihilator sequence".to_string(),
                            ));
                        }
                    };
                    let fermions: TinyVec<[FermionProduct; 2]> = match access.next_element()? {
                        Some(x) => x,
                        None => {
                            return Err(M::Error::custom("Missing fermion sequence".to_string()));
                        }
                    };
                    Ok(MixedDecoherenceProduct {
                        spins,
                        bosons,
                        fermions,
                    })
                }
            }
            let pp_visitor = MixedDecoherenceProductVisitor;

            deserializer.deserialize_tuple(3, pp_visitor)
        }
    }
}

impl MixedDecoherenceProduct {
    /// Export to struqture_1 format.
    #[cfg(feature = "struqture_1_export")]
    pub fn to_struqture_1(
        &self,
    ) -> Result<struqture_1::mixed_systems::MixedDecoherenceProduct, StruqtureError> {
        let self_string = self.to_string();
        let struqture_1_product = struqture_1::mixed_systems::MixedDecoherenceProduct::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::mixed_systems::MixedDecoherenceProduct,
    ) -> Result<Self, StruqtureError> {
        let value_string = value.to_string();
        let pauli_product = Self::from_str(&value_string)?;
        Ok(pauli_product)
    }
}

impl MixedIndex for MixedDecoherenceProduct {
    type BosonicIndexType = BosonProduct;
    type SpinIndexType = DecoherenceProduct;
    type FermionicIndexType = FermionProduct;

    /// Creates a new MixedDecoherenceProduct.
    ///
    /// # Arguments
    ///
    /// * `spins` - Products of decoherence matrices acting on qubits.
    /// * `bosons` - Products of bosonic creation and annihilation operators.
    /// * `fermions` - Products of fermionic creation and annihilation operators.
    ///
    /// # Returns
    ///
    /// * Ok(`Self`) - a new MixedDecoherenceProduct with the input of spins and bosons.
    fn new(
        spins: impl IntoIterator<Item = Self::SpinIndexType>,
        bosons: impl IntoIterator<Item = Self::BosonicIndexType>,
        fermions: impl IntoIterator<Item = Self::FermionicIndexType>,
    ) -> Result<Self, StruqtureError> {
        Ok(Self {
            spins: spins.into_iter().collect(),
            bosons: bosons.into_iter().collect(),
            fermions: fermions.into_iter().collect(),
        })
    }

    // From trait
    fn spins(&self) -> std::slice::Iter<'_, DecoherenceProduct> {
        self.spins.iter()
    }

    // From trait
    fn bosons(&self) -> std::slice::Iter<'_, BosonProduct> {
        self.bosons.iter()
    }

    // From trait
    fn fermions(&self) -> std::slice::Iter<'_, FermionProduct> {
        self.fermions.iter()
    }

    /// Creates a pair (MixedDecoherenceProduct, CalculatorComplex).
    ///
    /// The first item is the valid MixedDecoherenceProduct created from the input spins, bosons and fermions.
    /// The second term is the input CalculatorComplex transformed according to the valid order of inputs.
    ///
    /// # Arguments
    ///
    /// * `spins` - The DecoherenceProducts to have in the MixedDecoherenceProduct.
    /// * `bosons` - The BosonProducts to have in the MixedDecoherenceProduct.
    /// * `fermions` - The FermionProducts to have in the MixedDecoherenceProduct.
    /// * `value` - The CalculatorComplex to transform.
    ///
    /// # Returns
    ///
    /// * `Ok((MixedDecoherenceProduct, CalculatorComplex))` - The valid MixedDecoherenceProduct and the corresponding transformed CalculatorComplex.
    fn create_valid_pair(
        spins: impl IntoIterator<Item = Self::SpinIndexType>,
        bosons: impl IntoIterator<Item = Self::BosonicIndexType>,
        fermions: impl IntoIterator<Item = Self::FermionicIndexType>,
        value: qoqo_calculator::CalculatorComplex,
    ) -> Result<(Self, qoqo_calculator::CalculatorComplex), StruqtureError> {
        let spins: TinyVec<[DecoherenceProduct; 2]> = spins.into_iter().collect();
        let bosons: TinyVec<[BosonProduct; 2]> = bosons.into_iter().collect();
        let fermions: TinyVec<[FermionProduct; 2]> = fermions.into_iter().collect();
        Ok((Self::new(spins, bosons, fermions).unwrap(), value))
    }
}

impl FromStr for MixedDecoherenceProduct {
    type Err = StruqtureError;

    /// Constructs a MixedDecoherenceProduct from a string.
    ///
    /// # Arguments
    ///
    /// * `s` - The string to convert.
    ///
    /// # Returns
    ///
    /// * `Ok(Self)` - The successfully converted MixedDecoherenceProduct.
    /// * `Err(StruqtureError::ParsingError)` - Encountered subsystem that is neither spin, nor boson, nor fermion.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut spins: TinyVec<[DecoherenceProduct; 2]> =
            TinyVec::<[DecoherenceProduct; 2]>::with_capacity(2);
        let mut bosons: TinyVec<[BosonProduct; 2]> = TinyVec::<[BosonProduct; 2]>::with_capacity(2);
        let mut fermions: TinyVec<[FermionProduct; 2]> =
            TinyVec::<[FermionProduct; 2]>::with_capacity(2);
        let subsystems = s.split(':').filter(|s| !s.is_empty());
        for subsystem in subsystems {
            if let Some(rest) = subsystem.strip_prefix('S') {
                spins.push(DecoherenceProduct::from_str(rest)?);
            } else if let Some(rest) = subsystem.strip_prefix('B') {
                bosons.push(BosonProduct::from_str(rest)?);
            } else if let Some(rest) = subsystem.strip_prefix('F') {
                fermions.push(FermionProduct::from_str(rest)?);
            } else {
                return Err(StruqtureError::ParsingError {
                    target_type: "MixedIndex".to_string(),
                    msg: format!(
                        "Encountered subsystem that is neither spin, boson nor fermion: {subsystem}"
                    ),
                });
            }
        }

        Ok(Self {
            spins,
            bosons,
            fermions,
        })
    }
}

impl GetValueMixed<'_, MixedDecoherenceProduct> for MixedDecoherenceProduct {
    /// 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 MixedDecoherenceProduct.
    fn get_key(index: &MixedDecoherenceProduct) -> 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: &MixedDecoherenceProduct,
        value: qoqo_calculator::CalculatorComplex,
    ) -> qoqo_calculator::CalculatorComplex {
        value
    }
}

impl SymmetricIndex for MixedDecoherenceProduct {
    // From trait
    fn hermitian_conjugate(&self) -> (Self, f64) {
        let mut coefficient = 1.0;

        let mut new_spins = self.spins.clone();
        for spin in new_spins.iter_mut() {
            let (conj_spin, coeff) = spin.hermitian_conjugate();
            *spin = conj_spin;
            coefficient *= coeff;
        }
        let mut new_bosons = self.bosons.clone();
        for boson in new_bosons.iter_mut() {
            let (conj_boson, coeff) = boson.hermitian_conjugate();
            *boson = conj_boson;
            coefficient *= coeff;
        }
        let mut new_fermions = self.fermions.clone();
        for fermion in new_fermions.iter_mut() {
            let (conj_fermion, coeff) = fermion.hermitian_conjugate();
            *fermion = conj_fermion;
            coefficient *= coeff;
        }

        (
            Self {
                spins: new_spins,
                bosons: new_bosons,
                fermions: new_fermions,
            },
            coefficient,
        )
    }

    // From trait
    fn is_natural_hermitian(&self) -> bool {
        self.bosons.iter().all(|b| b.is_natural_hermitian())
            && self.fermions.iter().all(|f| f.is_natural_hermitian())
    }
}

/// Implements the multiplication function of MixedDecoherenceProduct by MixedDecoherenceProduct.
///
impl Mul<MixedDecoherenceProduct> for MixedDecoherenceProduct {
    type Output = Result<Vec<(MixedDecoherenceProduct, Complex64)>, StruqtureError>;

    /// Implement `*` for MixedDecoherenceProduct and MixedDecoherenceProduct.
    ///
    /// # Arguments
    ///
    /// * `other` - The MixedDecoherenceProduct to multiply by.
    ///
    /// # Returns
    ///
    /// * `Ok(Vec<(MixedDecoherenceProduct, Complex64)>)` - The two MixedDecoherenceProducts multiplied.
    /// * `Err(StruqtureError::MismatchedNumberSubsystems)` - Number of subsystems in left and right do not match.
    fn mul(self, rhs: MixedDecoherenceProduct) -> Self::Output {
        if self.spins().len() != rhs.spins().len()
            || self.bosons().len() != rhs.bosons().len()
            || self.fermions().len() != rhs.fermions().len()
        {
            return Err(StruqtureError::MismatchedNumberSubsystems {
                target_number_spin_subsystems: self.spins().len(),
                target_number_boson_subsystems: self.bosons().len(),
                target_number_fermion_subsystems: self.fermions().len(),
                actual_number_spin_subsystems: rhs.spins().len(),
                actual_number_boson_subsystems: rhs.bosons().len(),
                actual_number_fermion_subsystems: rhs.fermions().len(),
            });
        }
        let mut coefficient = Complex64::new(1.0, 0.0);
        let mut result_vec: Vec<(MixedDecoherenceProduct, Complex64)> = Vec::new();
        let mut tmp_spins: Vec<DecoherenceProduct> = Vec::with_capacity(self.spins().len());
        let mut tmp_bosons: Vec<Vec<BosonProduct>> = Vec::with_capacity(self.bosons().len());
        let mut tmp_fermions: Vec<Vec<(FermionProduct, f64)>> =
            Vec::with_capacity(self.fermions().len());
        for (left, right) in self.spins.into_iter().zip(rhs.spins) {
            let (val, coeff) = left * right;
            tmp_spins.push(val);
            coefficient *= coeff;
        }
        // iterate through boson subsystems and multiply subsystem
        for (left, right) in self.bosons.into_iter().zip(rhs.bosons) {
            let boson_multiplication = left.clone() * right.clone();
            if !tmp_bosons.is_empty() {
                let mut internal_tmp_bosons: Vec<Vec<BosonProduct>> = Vec::new();
                for bp in boson_multiplication.clone() {
                    for tmp_bp in tmp_bosons.iter() {
                        let mut tmp_entry = tmp_bp.clone();
                        tmp_entry.push(bp.clone());
                        internal_tmp_bosons.push(tmp_entry);
                    }
                }
                tmp_bosons.clone_from(&internal_tmp_bosons);
            } else {
                for bp in boson_multiplication.clone() {
                    tmp_bosons.push(vec![bp]);
                }
            }
        }
        for (left, right) in self.fermions.into_iter().zip(rhs.fermions) {
            let fermion_multiplication = left * right;
            if !tmp_fermions.is_empty() {
                let mut internal_tmp_fermions: Vec<Vec<(FermionProduct, f64)>> = Vec::new();
                for fp in fermion_multiplication {
                    for tmp_fp in tmp_fermions.iter() {
                        let mut tmp_entry = tmp_fp.clone();
                        tmp_entry.push(fp.clone());
                        internal_tmp_fermions.push(tmp_entry);
                    }
                }
                tmp_fermions = internal_tmp_fermions;
            } else {
                for fp in fermion_multiplication.clone() {
                    tmp_fermions.push(vec![fp]);
                }
            }
        }

        // Combining results
        for boson in tmp_bosons.clone() {
            if !tmp_fermions.is_empty() {
                for fermion in tmp_fermions.iter() {
                    let mut fermion_vec: Vec<FermionProduct> = Vec::new();
                    let mut sign = Complex64::new(1.0, 0.0);
                    for (f, val) in fermion {
                        fermion_vec.push(f.clone());
                        sign *= val;
                    }
                    result_vec.push((
                        MixedDecoherenceProduct::new(
                            tmp_spins.clone(),
                            boson.clone(),
                            fermion_vec,
                        )?,
                        coefficient * sign,
                    ));
                }
            } else {
                result_vec.push((
                    MixedDecoherenceProduct::new(tmp_spins.clone(), boson.clone(), vec![])?,
                    coefficient,
                ));
            }
        }
        if tmp_bosons.is_empty() && !tmp_fermions.is_empty() {
            for fermion in tmp_fermions.iter() {
                let mut fermion_vec: Vec<FermionProduct> = Vec::new();
                let mut sign = Complex64::new(1.0, 0.0);
                for (f, val) in fermion {
                    fermion_vec.push(f.clone());
                    sign *= val;
                }
                result_vec.push((
                    MixedDecoherenceProduct::new(tmp_spins.clone(), [], fermion_vec)?,
                    coefficient * sign,
                ));
            }
        } else if tmp_bosons.is_empty() && tmp_fermions.is_empty() {
            result_vec.push((
                MixedDecoherenceProduct::new(tmp_spins.clone(), [], [])?,
                coefficient,
            ))
        }

        Ok(result_vec)
    }
}

/// Implements the format function (Display trait) of MixedDecoherenceProduct.
///
impl std::fmt::Display for MixedDecoherenceProduct {
    /// Formats the MixedDecoherenceProduct using the given formatter.
    ///
    /// # Arguments
    ///
    /// * `f` - The formatter to use.
    ///
    /// # Returns
    ///
    /// * `std::fmt::Result` - The formatted MixedDecoherenceProduct.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut string: String = String::new();
        for spin in self.spins() {
            string.push_str(format!("S{spin}:").as_str());
        }
        for boson in self.bosons() {
            string.push_str(format!("B{boson}:").as_str());
        }
        for fermion in self.fermions() {
            string.push_str(format!("F{fermion}:").as_str());
        }
        write!(f, "{string}")
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use itertools::Itertools;
    use test_case::test_case;

    #[test_case("", &[], &[]; "empty")]
    #[test_case(":S0X1X:", &[], &[DecoherenceProduct::from_str("0X1X").unwrap()]; "single spin systems")]
    #[test_case(":S0X1X:S0Z:", &[], &[DecoherenceProduct::from_str("0X1X").unwrap(), DecoherenceProduct::from_str("0Z").unwrap()]; "two spin systems")]
    #[test_case(":S0X1X:Bc0a1:", &[BosonProduct::from_str("c0a1").unwrap()], &[DecoherenceProduct::from_str("0X1X").unwrap()]; "spin-boson systems")]
    fn from_string(stringformat: &str, bosons: &[BosonProduct], spins: &[DecoherenceProduct]) {
        let test_new = <MixedDecoherenceProduct as std::str::FromStr>::from_str(stringformat);
        assert!(test_new.is_ok());
        let res = test_new.unwrap();
        let empty_bosons: Vec<BosonProduct> = bosons.to_vec();
        let res_bosons: Vec<BosonProduct> = res.bosons.iter().cloned().collect_vec();
        assert_eq!(res_bosons, empty_bosons);
        let empty_spins: Vec<DecoherenceProduct> = spins.to_vec();
        let res_spins: Vec<DecoherenceProduct> = res.spins.iter().cloned().collect_vec();
        assert_eq!(res_spins, empty_spins);
    }
}