qoqo 1.22.2

Quantum computing circuit toolkit. Python interface of roqoqo
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
// Copyright © 2021-2024 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.

//! Qoqo measurement inputs

use num_complex::Complex64;
use pyo3::exceptions::{PyRuntimeError, PyTypeError, PyValueError};
use pyo3::prelude::*;
use pyo3::types::PyByteArray;
use roqoqo::measurements::{
    CheatedInput, CheatedPauliZProductInput, PauliProductMask, PauliZProductInput,
};
#[cfg(feature = "json_schema")]
use roqoqo::{operations::SupportedVersion, ROQOQO_VERSION};
use std::collections::HashMap;

#[pyclass(
    from_py_object,
    name = "PauliZProductInput",
    module = "qoqo.measurements"
)]
#[derive(Clone, Debug)]
/// Provides Necessary Information to run a [roqoqo::measurements::PauliZProduct] measurement.
///
/// The PauliZProductInput starts with just the number of qubtis and flipped measurements set.
/// The pauli_poduct_qubit_masks and measured_exp_vals start empty
/// and can be extended with [PauliZProductInput::add_pauliz_product]
/// [PauliZProductInput::add_linear_exp_val] and [PauliZProductInput::add_symbolic_exp_val]
///
/// Args:
///     number_qubits (int): The number of qubits in the PauliZProduct measurement.
///     use_flipped_measurement (bool): Whether or not to use flipped measurements.
///
/// Returns:
///     self: The new instance of PauliZProductInput with pauli_product_qubit_masks = an empty dictionary, the
///           specified number of qubits in input, number_pauli_products = 0, measured_exp_vals = an empty
///           dictionary, and whether to use flipped measurements as specified in input.
pub struct PauliZProductInputWrapper {
    /// Internal storage of [roqoqo::PauliZProductInput].
    pub internal: PauliZProductInput,
}

#[pymethods]
impl PauliZProductInputWrapper {
    /// Create new PauliZProductInput.
    ///
    /// The PauliZProductInput starts with just the number of qubtis and flipped measurements set.
    /// The pauli_poduct_qubit_masks and measured_exp_vals start empty
    /// and can be extended with [PauliZProductInput::add_pauliz_product]
    /// [PauliZProductInput::add_linear_exp_val] and [PauliZProductInput::add_symbolic_exp_val]
    ///
    /// Args:
    ///     number_qubits (int): The number of qubits in the PauliZProduct measurement.
    ///     use_flipped_measurement (bool): Whether or not to use flipped measurements.
    ///
    /// Returns:
    ///     self: The new instance of PauliZProductInput with pauli_product_qubit_masks = an empty dictionary, the
    ///           specified number of qubits in input, number_pauli_products = 0, measured_exp_vals = an empty
    ///           dictionary, and whether to use flipped measurements as specified in input.
    #[new]
    pub fn new(number_qubits: usize, use_flipped_measurement: bool) -> Self {
        Self {
            internal: PauliZProductInput::new(number_qubits, use_flipped_measurement),
        }
    }

    /// Add measured Pauli product to PauliZProductInput and returns index of Pauli product.
    ///
    /// When the pauli product is already in the measurement input the function only returns
    /// it index.
    ///
    /// Args:
    ///     readout (str): The name of the readout register the pauli_product is defined on.
    ///     pauli_product_mask (List[int]): List of the qubits involved in the Pauli produc measurement.
    ///
    /// Returns:
    ///     int: The index of the added Pauli product in the list of all Pauli products.
    ///
    /// Raises:
    ///     RuntimeError: Failed to add pauli product.
    pub fn add_pauliz_product(
        &mut self,
        readout: String,
        pauli_product_mask: PauliProductMask,
    ) -> PyResult<usize> {
        self.internal
            .add_pauliz_product(readout, pauli_product_mask)
            .map_err(|_| PyRuntimeError::new_err("Failed to add pauli product"))
    }

    /// Add linear definition of expectation value to measurement input.
    ///
    /// Adds an expectation value that is defined by a linear combination
    /// of expectation values of Pauli products.
    ///
    /// Args:
    ///     name (str): The name of the expectation value.
    ///     linear (Dict[int, float]): The linear combination of expectation values as a map between Pauli product index and coefficient.
    ///
    /// Raises:
    ///     RuntimeError: Failed to add linear expectation value.
    pub fn add_linear_exp_val(
        &mut self,
        name: String,
        linear: HashMap<usize, f64>,
    ) -> PyResult<()> {
        self.internal.add_linear_exp_val(name, linear).map_err(|x| {
            PyRuntimeError::new_err(format!("Failed to add linear expectation value {x:?}"))
        })
    }

    /// Add symbolic definition of expectation value to measurement input.
    ///
    /// Adds an expectation value that is defined by a symbolic combination
    /// of expectation values of Pauli products.
    ///
    /// Args:
    ///     name (str): The name of the expectation value.
    ///     symbolic (str): The symbolic expression for the expectation values given by [qoqo_calculator::CalculatorFloat].
    ///
    /// Raises:
    ///     RuntimeError: Failed to add symbolic expectation value.
    ///
    /// The i-th PauliProducts are hardcoded as variables pauli_product_i
    /// in the string expression of CalculatorFloat.
    pub fn add_symbolic_exp_val(&mut self, name: String, symbolic: String) -> PyResult<()> {
        self.internal
            .add_symbolic_exp_val(name, symbolic.into())
            .map_err(|x| {
                PyRuntimeError::new_err(format!("Failed to add symbolic expectation value {x:?}"))
            })
    }

    /// Serialize the PauliZProductInput to json form.
    ///
    /// Returns:
    ///     str: The serialized PauliZProductInput.
    ///
    /// Raises:
    ///     PyRuntimeError: Unexpected error serializing PauliZProductInput.
    pub fn to_json(&self) -> PyResult<String> {
        serde_json::to_string(&self.internal)
            .map_err(|_| PyRuntimeError::new_err("Unexpected error serializing PauliZProductInput"))
    }

    /// Deserialize the PauliZProductInput from json form.
    ///
    /// Returns:
    ///     PauliZProductInput: The deserialized PauliZProductInput.
    ///
    /// Raises:
    ///     PyRuntimeError: Cannot deserialize string to PauliZProductInput.
    #[staticmethod]
    pub fn from_json(json_string: &str) -> PyResult<Self> {
        Ok(Self {
            internal: serde_json::from_str(json_string).map_err(|_| {
                PyValueError::new_err("Cannot deserialize string to PauliZProductInput")
            })?,
        })
    }

    /// Return the bincode representation of the PauliZProductInput using the [bincode] crate.
    ///
    /// Returns:
    ///     ByteArray: The serialized PauliZProductInput (in [bincode] form).
    ///
    /// Raises:
    ///     ValueError: Cannot serialize PauliZProductInput to bytes.
    pub fn to_bincode(&self) -> PyResult<Py<PyByteArray>> {
        let serialized = bincode::serde::encode_to_vec(&self.internal, bincode::config::legacy())
            .map_err(|_| {
            PyValueError::new_err("Cannot serialize PauliZProductInput to bytes")
        })?;
        let b: Py<PyByteArray> = Python::attach(|py| -> Py<PyByteArray> {
            PyByteArray::new(py, &serialized[..]).into()
        });
        Ok(b)
    }

    /// Convert the bincode representation of the PauliZProductInput to a PauliZProductInput using the [bincode] crate.
    ///
    /// Args:
    ///     input (ByteArray): The serialized PauliZProductInput (in [bincode] form).
    ///
    /// Returns:
    ///     PauliZProductInput: The deserialized PauliZProductInput.
    ///
    /// Raises:
    ///     TypeError: Input cannot be converted to byte array.
    ///     ValueError: Input cannot be deserialized to PauliZProductInput.
    #[staticmethod]
    pub fn from_bincode(input: &Bound<PyAny>) -> PyResult<Self> {
        let bytes = input
            .extract::<Vec<u8>>()
            .map_err(|_| PyTypeError::new_err("Input cannot be converted to byte array"))?;

        Ok(Self {
            internal: bincode::serde::decode_from_slice(&bytes[..], bincode::config::legacy())
                .map_err(|_| {
                    PyValueError::new_err("Input cannot be deserialized to PauliZProductInput")
                })?
                .0,
        })
    }

    /// Implement __repr__ magic method
    pub fn __repr__(&self) -> String {
        format!("{:?}", self.internal)
    }

    /// Return a copy of the Object (copy here produces a deepcopy).
    pub fn __copy__(&self) -> Self {
        self.clone()
    }

    fn __richcmp__(
        &self,
        other: PauliZProductInputWrapper,
        op: pyo3::class::basic::CompareOp,
    ) -> PyResult<bool> {
        match op {
            pyo3::class::basic::CompareOp::Eq => Ok(self.internal == other.internal),
            pyo3::class::basic::CompareOp::Ne => Ok(self.internal != other.internal),
            _ => Err(pyo3::exceptions::PyNotImplementedError::new_err(
                "Other comparison not implemented",
            )),
        }
    }

    /// Return a deep copy of the Object.
    pub fn __deepcopy__(&self, _memodict: &Bound<PyAny>) -> Self {
        self.clone()
    }

    #[cfg(feature = "json_schema")]
    /// Return the JsonSchema for the json serialisation of the class.
    ///
    /// Returns:
    ///     str: The json schema serialized to json
    #[staticmethod]
    pub fn json_schema() -> String {
        let schema = schemars::schema_for!(PauliZProductInput);
        serde_json::to_string_pretty(&schema).expect("Unexpected failure to serialize schema")
    }

    #[cfg(feature = "json_schema")]
    /// Returns the current version of the qoqo library .
    ///
    /// Returns:
    ///     str: The current version of the library.
    #[staticmethod]
    pub fn current_version() -> String {
        ROQOQO_VERSION.to_string()
    }

    #[cfg(feature = "json_schema")]
    /// Return the minimum version of qoqo that supports this object.
    ///
    /// Returns:
    ///     str: The minimum version of the qoqo library to deserialize this object.
    pub fn min_supported_version(&self) -> String {
        let min_version: (u32, u32, u32) =
            PauliZProductInput::minimum_supported_roqoqo_version(&self.internal);
        format!("{}.{}.{}", min_version.0, min_version.1, min_version.2)
    }
}

#[pyclass(
    from_py_object,
    name = "CheatedPauliZProductInput",
    module = "qoqo.measurements"
)]
#[derive(Clone, Debug)]
/// Collected information for executing a cheated basis rotation measurement.
///
/// The CheatedPauliZProductInput starts with just the number of qubtis and flipped measurements set.
/// The pauli_poduct_qubit_masks and measured_exp_vals start empty
/// and can be extended with [CheatedPauliZProductInput::add_linear_exp_val] and
/// [CheatedPauliZProductInput::add_symbolic_exp_val].
///
/// Returns:
///     self: The new instance of CheatedPauliZProductInput with measured_exp_vals = an empty
///            HashMap and pauli_product_keys = an empty HashMap.
pub struct CheatedPauliZProductInputWrapper {
    /// Internal storage of [roqoqo::CheatedPauliZProductInput].
    pub internal: CheatedPauliZProductInput,
}

impl Default for CheatedPauliZProductInputWrapper {
    fn default() -> Self {
        Self::new()
    }
}

#[pymethods]
impl CheatedPauliZProductInputWrapper {
    /// Create new CheatedPauliZProductInput.
    ///
    /// The CheatedPauliZProductInput starts with just the number of qubtis and flipped measurements set.
    /// The pauli_poduct_qubit_masks and measured_exp_vals start empty
    /// and can be extended with [CheatedPauliZProductInput::add_linear_exp_val] and
    /// [CheatedPauliZProductInput::add_symbolic_exp_val].
    ///
    /// Returns:
    ///     self: The new instance of CheatedPauliZProductInput with measured_exp_vals = an empty
    ///            HashMap and pauli_product_keys = an empty HashMap.
    #[new]
    pub fn new() -> Self {
        Self {
            internal: CheatedPauliZProductInput::new(),
        }
    }

    /// Add measured Pauli product to CheatedPauliZProductInput and returns index of Pauli product.
    ///
    /// When the pauli product is already in the measurement input the function only returns
    /// its index.
    ///
    /// Args:
    ///     readout (str): The name of the readout register containing the pauli_product expectation value.
    ///
    /// Returns:
    ///     int: The index of the added Pauli product in the list of all Pauli products.
    pub fn add_pauliz_product(&mut self, readout: String) -> usize {
        self.internal.add_pauliz_product(readout)
    }

    /// Add linear definition of expectation value to measurement input.
    ///
    /// Adds an expectation value that is defined by a linear combination
    /// of expectation values of Pauli products.
    ///
    /// Args:
    ///     name (str): The name of the expectation value.
    ///     linear (Dict[int, float]): The linear combination of expectation values as a map between Pauli product index and coefficient.
    ///
    /// Raises:
    ///     RuntimeError: Failed to add linear expectation value.
    pub fn add_linear_exp_val(
        &mut self,
        name: String,
        linear: HashMap<usize, f64>,
    ) -> PyResult<()> {
        self.internal.add_linear_exp_val(name, linear).map_err(|x| {
            PyRuntimeError::new_err(format!("Failed to add linear expectation value {x:?}"))
        })
    }

    /// Add symbolic definition of expectation value to measurement input.
    ///
    /// Adds an expectation value that is defined by a symbolic combination
    /// of expectation values of Pauli products.
    ///
    /// Args:
    ///     name (str): The name of the expectation value.
    ///     symbolic (str): The symbolic expression for the expectation values given by [qoqo_calculator::CalculatorFloat].
    ///
    /// Raises:
    ///     RuntimeError: Failed to add symbolic expectation value.
    ///
    /// The i-th PauliProducts are hardcoded as variables pauli_product_i
    /// in the string expression of CalculatorFloat.
    ///
    pub fn add_symbolic_exp_val(&mut self, name: String, symbolic: String) -> PyResult<()> {
        self.internal
            .add_symbolic_exp_val(name, symbolic.into())
            .map_err(|x| {
                PyRuntimeError::new_err(format!("Failed to add symbolic expectation value {x:?}"))
            })
    }

    /// Serialize the CheatedPauliZProductInput to json form.
    ///
    /// Returns:
    ///     str: The serialized CheatedPauliZProductInput.
    ///
    /// Raises:
    ///     PyRuntimeError: Unexpected error serializing CheatedPauliZProductInput.
    pub fn to_json(&self) -> PyResult<String> {
        serde_json::to_string(&self.internal)
            .map_err(|_| PyRuntimeError::new_err("Unexpected error serializing PauliZProductInput"))
    }

    /// Deserialize the CheatedPauliZProductInput from json form.
    ///
    /// Returns:
    ///     CheatedPauliZProductInput: The deserialized CheatedPauliZProductInput.
    ///
    /// Raises:
    ///     PyRuntimeError: Cannot deserialize string to CheatedPauliZProductInput.
    #[staticmethod]
    pub fn from_json(json_string: &str) -> PyResult<Self> {
        Ok(Self {
            internal: serde_json::from_str(json_string).map_err(|_| {
                PyValueError::new_err("Cannot deserialize string to PauliZProductInput")
            })?,
        })
    }

    /// Return the bincode representation of the CheatedPauliZProductInput using the [bincode] crate.
    ///
    /// Returns:
    ///     ByteArray: The serialized CheatedPauliZProductInput (in [bincode] form).
    ///
    /// Raises:
    ///     ValueError: Cannot serialize CheatedPauliZProductInput to bytes.
    pub fn to_bincode(&self) -> PyResult<Py<PyByteArray>> {
        let serialized = bincode::serde::encode_to_vec(&self.internal, bincode::config::legacy())
            .map_err(|_| {
            PyValueError::new_err("Cannot serialize CheatedPauliZProductInput to bytes")
        })?;
        let b: Py<PyByteArray> = Python::attach(|py| -> Py<PyByteArray> {
            PyByteArray::new(py, &serialized[..]).into()
        });
        Ok(b)
    }

    /// Convert the bincode representation of the CheatedPauliZProductInput to a CheatedPauliZProductInput using the [bincode] crate.
    ///
    /// Args:
    ///     input (ByteArray): The serialized CheatedPauliZProductInput (in [bincode] form).
    ///
    /// Returns:
    ///     CheatedPauliZProductInput: The deserialized CheatedPauliZProductInput.
    ///
    /// Raises:
    ///     TypeError: Input cannot be converted to byte array.
    ///     ValueError: Input cannot be deserialized to CheatedPauliZProductInput.
    #[staticmethod]
    pub fn from_bincode(input: &Bound<PyAny>) -> PyResult<Self> {
        let bytes = input
            .extract::<Vec<u8>>()
            .map_err(|_| PyTypeError::new_err("Input cannot be converted to byte array"))?;

        Ok(Self {
            internal: bincode::serde::decode_from_slice(&bytes[..], bincode::config::legacy())
                .map_err(|_| {
                    PyValueError::new_err(
                        "Input cannot be deserialized to CheatedPauliZProductInput",
                    )
                })?
                .0,
        })
    }

    /// Implement __repr__ magic method
    pub fn __repr__(&self) -> String {
        format!("{:?}", self.internal)
    }

    /// Return a copy of the Object (copy here produces a deepcopy).
    pub fn __copy__(&self) -> Self {
        self.clone()
    }

    /// Return a deep copy of the Object.
    pub fn __deepcopy__(&self, _memodict: &Bound<PyAny>) -> Self {
        self.clone()
    }

    fn __richcmp__(
        &self,
        other: CheatedPauliZProductInputWrapper,
        op: pyo3::class::basic::CompareOp,
    ) -> PyResult<bool> {
        match op {
            pyo3::class::basic::CompareOp::Eq => Ok(self.internal == other.internal),
            pyo3::class::basic::CompareOp::Ne => Ok(self.internal != other.internal),
            _ => Err(pyo3::exceptions::PyNotImplementedError::new_err(
                "Other comparison not implemented",
            )),
        }
    }

    #[cfg(feature = "json_schema")]
    /// Return the JsonSchema for the json serialisation of the class.
    ///
    /// Returns:
    ///     str: The json schema serialized to json
    #[staticmethod]
    pub fn json_schema() -> String {
        let schema = schemars::schema_for!(CheatedPauliZProductInput);
        serde_json::to_string_pretty(&schema).expect("Unexpected failure to serialize schema")
    }

    #[cfg(feature = "json_schema")]
    /// Returns the current version of the qoqo library .
    ///
    /// Returns:
    ///     str: The current version of the library.
    #[staticmethod]
    pub fn current_version() -> String {
        ROQOQO_VERSION.to_string()
    }

    #[cfg(feature = "json_schema")]
    /// Return the minimum version of qoqo that supports this object.
    ///
    /// Returns:
    ///     str: The minimum version of the qoqo library to deserialize this object.
    pub fn min_supported_version(&self) -> String {
        let min_version: (u32, u32, u32) =
            CheatedPauliZProductInput::minimum_supported_roqoqo_version(&self.internal);
        format!("{}.{}.{}", min_version.0, min_version.1, min_version.2)
    }
}

#[pyclass(from_py_object, name = "CheatedInput", module = "qoqo.measurements")]
#[derive(Clone, Debug)]
/// Provides Necessary Information to run a cheated measurement.
///
/// The CheatedInput stores the number of qubits that are measured
/// and a dictionary mapping expectation value names to operators on the Hilbert space
/// of the qubits. The operators are represented by sparse lists of non-zero entry triples
/// of an operator matrix.
///
/// Args:
///     number_qubits (int): The number of qubits in the PauliZProduct measurement.
///
/// Returns:
///     CheatedInput: The new instance of CheatedInput with the specified number of qubits in input,
///                   and an empty dictionay of expectation values.
pub struct CheatedInputWrapper {
    /// Internal storage of [roqoqo::CheatedInput].
    pub internal: CheatedInput,
}

#[pymethods]
impl CheatedInputWrapper {
    /// Creates a new CheatedInput.
    ///
    /// The CheatedInput stores the number of qubits that are measured
    /// and a dictionary mapping expectation value names to operators on the Hilbert space
    /// of the qubits. The operators are represented by sparse lists of non-zero entry triples
    /// of an operator matrix.
    ///
    /// Args:
    ///     number_qubits (int): The number of qubits in the PauliZProduct measurement.
    ///
    /// Returns:
    ///     CheatedInput: The new instance of CheatedInput with the specified number of qubits in input,
    ///                   and an empty dictionay of expectation values.
    #[new]
    pub fn new(number_qubits: usize) -> Self {
        Self {
            internal: CheatedInput::new(number_qubits),
        }
    }

    /// Add operator based expectation value to measurement input.
    ///
    /// Adds an expectation value that is defined by an operator on the Hilbert space.
    ///
    /// Args:
    ///     name (str): The name of the expectation value.
    ///     operator (List[(int, int, complex)]): The measured operator on the Hilbert space,
    ///                                           given as a list of sparse matrix entries of the form (row, col, value).
    ///     readout (str): The mame of the readout register that contains the density matrix or satevector.
    ///
    /// Raises:
    ///     RuntimeError: Failed to add operator based expectation value.
    pub fn add_operator_exp_val(
        &mut self,
        name: String,
        operator: Vec<(usize, usize, Complex64)>,
        readout: String,
    ) -> PyResult<()> {
        self.internal
            .add_operator_exp_val(name, operator, readout)
            .map_err(|x| {
                PyRuntimeError::new_err(format!(
                    "Failed to add operator based expectation value {x:?}"
                ))
            })
    }

    /// Serialize the CheatedInput to json form.
    ///
    /// Returns:
    ///     str: The serialized CheatedInput.
    ///
    /// Raises:
    ///     PyRuntimeError: Unexpected error serializing CheatedInput.
    pub fn to_json(&self) -> PyResult<String> {
        serde_json::to_string(&self.internal)
            .map_err(|_| PyRuntimeError::new_err("Unexpected error serializing PauliZProductInput"))
    }

    /// Deserialize the CheatedInput from json form.
    ///
    /// Returns:
    ///     CheatedInput: The deserialized CheatedInput.
    ///
    /// Raises:
    ///     PyRuntimeError: Cannot deserialize string to CheatedInput.
    #[staticmethod]
    pub fn from_json(json_string: &str) -> PyResult<Self> {
        Ok(Self {
            internal: serde_json::from_str(json_string).map_err(|_| {
                PyValueError::new_err("Cannot deserialize string to PauliZProductInput")
            })?,
        })
    }

    /// Return the bincode representation of the CheatedInput using the [bincode] crate.
    ///
    /// Returns:
    ///     ByteArray: The serialized CheatedInput (in [bincode] form).
    ///
    /// Raises:
    ///     ValueError: Cannot serialize CheatedInput to bytes.
    pub fn to_bincode(&self) -> PyResult<Py<PyByteArray>> {
        let serialized =
            bincode::serde::encode_to_vec(&self.internal, bincode::config::legacy())
                .map_err(|_| PyValueError::new_err("Cannot serialize CheatedInput to bytes"))?;
        let b: Py<PyByteArray> = Python::attach(|py| -> Py<PyByteArray> {
            PyByteArray::new(py, &serialized[..]).into()
        });
        Ok(b)
    }

    /// Convert the bincode representation of the CheatedInput to a CheatedInput using the [bincode] crate.
    ///
    /// Args:
    ///     input (ByteArray): The serialized CheatedInput (in [bincode] form).
    ///
    /// Returns:
    ///     CheatedInput: The deserialized CheatedInput.
    ///
    /// Raises:
    ///     TypeError: Input cannot be converted to byte array.
    ///     ValueError: Input cannot be deserialized to CheatedInput.
    #[staticmethod]
    pub fn from_bincode(input: &Bound<PyAny>) -> PyResult<Self> {
        let bytes = input
            .extract::<Vec<u8>>()
            .map_err(|_| PyTypeError::new_err("Input cannot be converted to byte array"))?;

        Ok(Self {
            internal: bincode::serde::decode_from_slice(&bytes[..], bincode::config::legacy())
                .map_err(|_| PyValueError::new_err("Input cannot be deserialized to CheatedInput"))?
                .0,
        })
    }

    /// Implement __repr__ magic method
    pub fn __repr__(&self) -> String {
        format!("{:?}", self.internal)
    }

    /// Return a copy of the Object (copy here produces a deepcopy).
    pub fn __copy__(&self) -> Self {
        self.clone()
    }

    /// Return a deep copy of the Object.
    pub fn __deepcopy__(&self, _memodict: &Bound<PyAny>) -> Self {
        self.clone()
    }
    fn __richcmp__(
        &self,
        other: CheatedInputWrapper,
        op: pyo3::class::basic::CompareOp,
    ) -> PyResult<bool> {
        match op {
            pyo3::class::basic::CompareOp::Eq => Ok(self.internal == other.internal),
            pyo3::class::basic::CompareOp::Ne => Ok(self.internal != other.internal),
            _ => Err(pyo3::exceptions::PyNotImplementedError::new_err(
                "Other comparison not implemented",
            )),
        }
    }

    #[cfg(feature = "json_schema")]
    /// Return the JsonSchema for the json serialisation of the class.
    ///
    /// Returns:
    ///     str: The json schema serialized to json
    #[staticmethod]
    pub fn json_schema() -> String {
        let schema = schemars::schema_for!(CheatedInput);
        serde_json::to_string_pretty(&schema).expect("Unexpected failure to serialize schema")
    }

    #[cfg(feature = "json_schema")]
    /// Returns the current version of the qoqo library .
    ///
    /// Returns:
    ///     str: The current version of the library.
    #[staticmethod]
    pub fn current_version() -> String {
        ROQOQO_VERSION.to_string()
    }

    #[cfg(feature = "json_schema")]
    /// Return the minimum version of qoqo that supports this object.
    ///
    /// Returns:
    ///     str: The minimum version of the qoqo library to deserialize this object.
    pub fn min_supported_version(&self) -> String {
        let min_version: (u32, u32, u32) =
            CheatedInput::minimum_supported_roqoqo_version(&self.internal);
        format!("{}.{}.{}", min_version.0, min_version.1, min_version.2)
    }
}

impl CheatedPauliZProductInputWrapper {
    /// Extracts a CheatedPauliZProductInput from a CheatedPauliZProductInputWrapper python object.
    ///
    /// When working with qoqo and other rust based python packages compiled separately
    /// a downcast will not detect that two CheatedPauliZProductInputWrapper objects are compatible.
    /// Provides a custom function to convert qoqo CheatedPauliZProductInputs between different Python packages.
    ///
    /// # Arguments:
    ///
    /// `input` - The Python object that should be casted to a [roqoqo::CheatedPauliZProductInput]
    pub fn from_pyany(input: &Bound<PyAny>) -> PyResult<CheatedPauliZProductInput> {
        if let Ok(try_downcast) = input.extract::<CheatedPauliZProductInputWrapper>() {
            Ok(try_downcast.internal)
        } else {
            let get_bytes = input.call_method0("to_bincode").map_err(|_| {
                PyTypeError::new_err("Python object cannot be converted to qoqo CheatedPauliZInput: Cast to binary representation failed".to_string())
            })?;
            let bytes = get_bytes.extract::<Vec<u8>>().map_err(|_| {
                PyTypeError::new_err("Python object cannot be converted to qoqo CheatedPauliZInput: Cast to binary representation failed".to_string())
            })?;
            bincode::serde::decode_from_slice(&bytes[..], bincode::config::legacy()).map_err(|err| {
                    PyTypeError::new_err(format!(
                    "Python object cannot be converted to qoqo CheatedPauliZInput: Deserialization failed: {err}"
                ))
                }).map(|(deserialized, _)| deserialized)
        }
    }
}

impl PauliZProductInputWrapper {
    /// Extracts a PauliZProductInput from a PauliZProductInputWrapper python object.
    ///
    /// When working with qoqo and other rust based python packages compiled separately
    /// a downcast will not detect that two PauliZProductInputWrapper objects are compatible.
    /// Provides a custom function to convert qoqo PauliZProductInputs between different Python packages.
    ///
    /// # Arguments:
    ///
    /// `input` - The Python object that should be casted to a [roqoqo::PauliZProductInput]
    pub fn from_pyany(input: &Bound<PyAny>) -> PyResult<PauliZProductInput> {
        if let Ok(try_downcast) = input.extract::<PauliZProductInputWrapper>() {
            Ok(try_downcast.internal)
        } else {
            let get_bytes = input.call_method0("to_bincode").map_err(|_| {
                PyTypeError::new_err("Python object cannot be converted to qoqo PauliZInput: Cast to binary representation failed".to_string())
            })?;
            let bytes = get_bytes.extract::<Vec<u8>>().map_err(|_| {
                PyTypeError::new_err("Python object cannot be converted to qoqo PauliZInput: Cast to binary representation failed".to_string())
            })?;
            bincode::serde::decode_from_slice(&bytes[..], bincode::config::legacy()).map_err(|err| {
                    PyTypeError::new_err(format!(
                    "Python object cannot be converted to qoqo PauliZInput: Deserialization failed: {err}"
                ))
                }).map(|(deserialized, _)| deserialized)
        }
    }
}

impl CheatedInputWrapper {
    /// Extracts a CheatedInput from a CheatedInputWrapper python object.
    ///
    /// When working with qoqo and other rust based python packages compiled separately
    /// a downcast will not detect that two CheatedInputWrapper objects are compatible.
    /// Provides a custom function to convert qoqo CheatedPInputs between different Python packages.
    ///
    /// # Arguments:
    ///
    /// `input` - The Python object that should be casted to a [roqoqo::CheatedInput]
    pub fn from_pyany(input: &Bound<PyAny>) -> PyResult<CheatedInput> {
        if let Ok(try_downcast) = input.extract::<CheatedInputWrapper>() {
            Ok(try_downcast.internal)
        } else {
            let get_bytes = input.call_method0("to_bincode").map_err(|_| {
                PyTypeError::new_err("Python object cannot be converted to qoqo CheatedInput: Cast to binary representation failed".to_string())
            })?;
            let bytes = get_bytes.extract::<Vec<u8>>().map_err(|_| {
                PyTypeError::new_err("Python object cannot be converted to qoqo CheatedInput: Cast to binary representation failed".to_string())
            })?;
            bincode::serde::decode_from_slice(&bytes[..], bincode::config::legacy()).map_err(|err| {
                    PyTypeError::new_err(format!(
                    "Python object cannot be converted to qoqo CheatedInput: Deserialization failed: {err}"
                ))
                }).map(|(deserialized, _)| deserialized)
        }
    }
}