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
// 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.

//! Module containing the Circuit class that represents a quantum circuit in qoqo.
//!
//! In qoqo, single operations are collected in a circuit to build up a quantum program.
//! Qoqo circuits are strictly linear sequences of operations.
//! The circuit struct behaves similar to a list and provides several standard
//! functions of a Vec<Operation>, such as len(), is_empty(), get(), iter() and into_iter().
//!

use crate::{QoqoError, QOQO_VERSION};
use bincode::{deserialize, serialize};
use pyo3::exceptions::{PyIndexError, PyRuntimeError, PyTypeError, PyValueError};
use pyo3::prelude::*;
use pyo3::types::PyByteArray;
use roqoqo::prelude::*;
use roqoqo::{Circuit, OperationIterator, ROQOQO_VERSION};
use std::collections::HashSet;

use crate::operations::{convert_operation_to_pyobject, convert_pyany_to_operation};

/// Module containing the Circuit class that represents a quantum circuit in qoqo.
///
/// In qoqo, single operations are collected in a circuit to build up a quantum program.
/// Qoqo circuits are strictly linear sequences of operations.
/// The circuit struct behaves similar to a list and provides several standard
/// functions of a Vec<Operation>, such as len(), is_empty(), get(), iter() and into_iter().
///

#[pymodule]
fn circuit(_py: Python, module: &PyModule) -> PyResult<()> {
    module.add_class::<CircuitWrapper>()?;
    Ok(())
}
/// Circuit of Operations.
///
/// A quantum program is represented as a linear sequence of Operations.
#[pyclass(name = "Circuit", module = "qoqo")]
#[derive(Clone, Debug, PartialEq)]
pub struct CircuitWrapper {
    /// Internal storage of [roqoqo::Circuit]
    pub internal: Circuit,
}

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

impl CircuitWrapper {
    /// Extracts a Circuit from a CircuitWrapper python object.
    ///
    /// When working with qoqo and other rust based python packages compiled separately
    /// a downcast will not detect that two CircuitWrapper objects are compatible.
    /// Provides a custom function to convert qoqo Circuits between different Python packages.
    ///
    /// # Arguments:
    ///
    /// `input` - The Python object that should be casted to a [roqoqo::Circuit]
    pub fn from_pyany(input: Py<PyAny>) -> PyResult<Circuit> {
        Python::with_gil(|py| -> PyResult<Circuit> {
            let input = input.as_ref(py);
            if let Ok(try_downcast) = input.extract::<CircuitWrapper>() {
                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 Circuit: 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 Circuit: Cast to binary representation failed".to_string())
            })?;
                deserialize(&bytes[..]).map_err(|err| {
                    PyTypeError::new_err(format!(
                    "Python object cannot be converted to qoqo Circuit: Deserialization failed: {}",
                    err
                ))
                })
            }
        })
    }
}

#[pymethods]
impl CircuitWrapper {
    /// Create an empty quantum Circuit.
    ///
    /// Returns:
    ///     self: The new, empty Circuit.
    #[new]
    pub fn new() -> Self {
        Self {
            internal: Circuit::new(),
        }
    }

    /// Substitute the symbolic parameters in a clone of the Circuit according to the substitution_parameters input.
    ///
    /// Args:
    ///     substitution_parameters (dict[str, float]): The dictionary containing the substitutions to use in the Circuit.
    ///
    /// Returns:
    ///     self: The Circuit with the parameters substituted.
    ///
    /// Raises:
    ///     RuntimeError: The parameter substitution failed.
    pub fn substitute_parameters(
        &self,
        substitution_parameters: std::collections::HashMap<&str, f64>,
    ) -> PyResult<Self> {
        let mut calculator = qoqo_calculator::Calculator::new();
        for (key, val) in substitution_parameters.iter() {
            calculator.set_variable(key, *val);
        }
        Ok(Self {
            internal: self
                .internal
                .substitute_parameters(&calculator)
                .map_err(|x| {
                    pyo3::exceptions::PyRuntimeError::new_err(format!(
                        "Parameter Substitution failed: {:?}",
                        x
                    ))
                })?,
        })
    }

    /// Remap qubits in operations in clone of Circuit.
    ///
    /// Args:
    ///     mapping (dict[int, int]): The dictionary containing the {qubit: qubit} mapping to use in the Circuit.
    ///
    /// Returns:
    ///     self: The Circuit with the qubits remapped.
    ///
    /// Raises:
    ///     RuntimeError: The qubit remapping failed.
    pub fn remap_qubits(&self, mapping: std::collections::HashMap<usize, usize>) -> PyResult<Self> {
        let new_internal = self.internal.remap_qubits(&mapping).map_err(|err| {
            pyo3::exceptions::PyRuntimeError::new_err(format!("Qubit remapping failed: {:?}", err))
        })?;
        Ok(Self {
            internal: new_internal,
        })
    }

    /// Return clone of the circuit with all overrotation Pragmas applied.
    ///
    /// Returns:
    ///     Circuit: Circuit with the overrotation applied
    ///
    /// Raises:
    ///     RuntimeError: Error applying PragmaOverrotation in circuit.
    ////
    /// Example:
    ///
    /// >>> circuit = Circuit()
    /// >>> circuit += PragmaOverrotation("RotateY", [1,], 20.0, 30.0)
    /// >>> circuit += RotateX(0, 0.0)
    /// >>> circuit += RotateY(0, 1.0)
    /// >>> circuit += RotateY(1, 2.0)
    /// >>> circuit += RotateY(1, 3.0)
    /// >>> circuit_overrotated = circuit.overrotate()
    /// print(circuit)
    /// print(circuit_overrotated)
    ///
    pub fn overrotate(&self) -> PyResult<Self> {
        Ok(Self {
            internal: self.internal.overrotate().map_err(|_| {
                PyRuntimeError::new_err("Error applying PragmaOverrotation in circuit")
            })?,
        })
    }

    /// Count the number of occurences of a set of operation tags in the circuit.
    ///
    /// Args:
    ///     operations (list[str]): List of operation tags that should be counted.
    ///
    /// Returns:
    ///     int: The number of occurences of these operation tags.
    pub fn count_occurences(&self, operations: Vec<&str>) -> usize {
        let mut counter: usize = 0;
        for op in self.internal.iter() {
            if operations.iter().any(|x| op.tags().contains(x)) {
                counter += 1
            }
        }
        counter
    }

    /// Return a list of the hqslang names of all operations occuring in the circuit.
    ///
    /// Returns:
    ///     set[str]: The operation types in the Circuit.
    pub fn get_operation_types(&self) -> HashSet<&str> {
        let mut operations: HashSet<&str> = HashSet::new();
        for op in self.internal.iter() {
            let _ = operations.insert(op.hqslang());
        }
        operations
    }

    /// Return a copy of the Circuit (copy here produces a deepcopy).
    ///
    /// Returns:
    ///     Circuit: A deep copy of self.
    pub fn __copy__(&self) -> CircuitWrapper {
        self.clone()
    }

    /// Return a deep copy of the Circuit.
    ///
    /// Returns:
    ///     Circuit: A deep copy of self.
    pub fn __deepcopy__(&self, _memodict: Py<PyAny>) -> CircuitWrapper {
        self.clone()
    }

    /// Return the roqoqo and qoqo versions from when the code was compiled.
    ///
    /// Returns:
    ///     tuple[str, str]: The roqoqo and qoqo versions.
    fn _qoqo_versions(&self) -> (String, String) {
        let mut rsplit = ROQOQO_VERSION.split('.').take(2);
        let mut qsplit = QOQO_VERSION.split('.').take(2);
        let rver = format!(
            "{}.{}",
            rsplit.next().expect("ROQOQO_VERSION badly formatted"),
            rsplit.next().expect("ROQOQO_VERSION badly formatted")
        );
        let qver = format!(
            "{}.{}",
            qsplit.next().expect("QOQO_VERSION badly formatted"),
            qsplit.next().expect("QOQO_VERSION badly formatted")
        );
        (rver, qver)
    }

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

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

        Ok(Self {
            internal: deserialize(&bytes[..])
                .map_err(|_| PyValueError::new_err("Input cannot be deserialized to Circuit"))?,
        })
    }

    /// Return the json representation of the Circuit.
    ///
    /// Returns:
    ///     str: The serialized form of Circuit.
    ///
    /// Raises:
    ///     ValueError: Cannot serialize Circuit to json.
    fn to_json(&self) -> PyResult<String> {
        let serialized = serde_json::to_string(&self.internal)
            .map_err(|_| PyValueError::new_err("Cannot serialize Circuit to json"))?;
        Ok(serialized)
    }

    #[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!(Circuit);
        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) =
            Circuit::minimum_supported_roqoqo_version(&self.internal);
        format!("{}.{}.{}", min_version.0, min_version.1, min_version.2)
    }

    /// Convert the json representation of a Circuit to a Circuit.
    ///
    /// Args:
    ///     input (str): The serialized Circuit in json form.
    ///
    /// Returns:
    ///     Circuit: The deserialized Circuit.
    ///
    /// Raises:
    ///     ValueError: Input cannot be deserialized to Circuit.
    #[staticmethod]
    pub fn from_json(json_string: &str) -> PyResult<Self> {
        Ok(Self {
            internal: serde_json::from_str(json_string)
                .map_err(|_| PyValueError::new_err("Input cannot be deserialized to Circuit"))?,
        })
    }

    /// Return a copy of the Operation at a certain index of the Circuit.
    ///
    /// Args:
    ///     index (int): The index of the Operation to get in the Circuit.
    ///
    /// Returns:
    ///     Operation: The operation at the given index (if it exists).
    ///
    /// Raises:
    ///     IndexError: Index out of range.
    pub fn get(&self, index: usize) -> PyResult<PyObject> {
        let operation = self
            .internal
            .get(index)
            .ok_or_else(|| PyIndexError::new_err(format!("Index {} out of range", index)))?
            .clone();
        convert_operation_to_pyobject(operation)
    }

    /// Return the copy of a slice of the Circuit.
    ///
    /// Args:
    ///     start (Optional[int]): The starting index of the slice (inclusive).
    ///     stop (Optional[int]): The stopping index of the slice (exclusive).
    ///
    /// Returns:
    ///     Circuit: The slice of the operations in the Circuit with the specified indices.
    ///
    /// Raises:
    ///     IndexError: Stop index smaller than start index.
    ///     IndexError: Stop index out of range.
    ///     IndexError: Start index out of range.
    pub fn get_slice(&self, start: Option<usize>, stop: Option<usize>) -> PyResult<CircuitWrapper> {
        let start = match start {
            Some(x) => x,
            _ => 0,
        };
        let stop = match stop {
            Some(x) => x,
            _ => self.internal.len(),
        };
        if start >= stop {
            return Err(PyIndexError::new_err(format!(
                "Stop index {} smaller than start index {}",
                stop, start
            )));
        }
        if start >= self.internal.len() {
            return Err(PyIndexError::new_err(format!(
                "Start index {} out of range",
                start
            )));
        }
        if stop > self.internal.len() {
            return Err(PyIndexError::new_err(format!(
                "Stop index {} out of range",
                stop
            )));
        }

        // This is the preferred way once advance_by has been stabilized
        // let circuit_slice: Circuit =  self.internal.iter().advance_by(start).map_err(|| PyIndexError::new_err(format!("Start index {} out of range", start)))?.take(stop-start).collect();

        let mut tmp_iter = self.internal.iter();
        if start > 0 {
            tmp_iter.nth(start - 1);
        }
        let circuit_slice: Circuit = tmp_iter.take(stop - start + 1).cloned().collect();
        Ok(CircuitWrapper {
            internal: circuit_slice,
        })
    }

    /// Return a list of definitions in the Circuit.
    ///
    /// Definitions need to be unique.
    ///
    /// Returns:
    ///     list[Operation]: A vector of the definitions in the Circuit.
    pub fn definitions(&self) -> PyResult<Vec<PyObject>> {
        let mut defs: Vec<PyObject> = Vec::new();
        for op in self
            .internal
            .definitions()
            .iter()
            .cloned()
            .map(convert_operation_to_pyobject)
        {
            defs.push(op?)
        }
        Ok(defs)
    }

    /// Return a list of all operations in the Circuit.
    ///
    /// Returns:
    ///     list[Operation]: A vector of the operations in the Circuit.
    pub fn operations(&self) -> PyResult<Vec<PyObject>> {
        let mut ops: Vec<PyObject> = Vec::new();
        for op in self
            .internal
            .operations()
            .iter()
            .cloned()
            .map(convert_operation_to_pyobject)
        {
            ops.push(op?)
        }
        Ok(ops)
    }

    /// Return a list of operations with given tag.
    ///
    /// Args:
    ///     tag (str): tag by which to filter operations.
    ///
    /// Returns:
    ///     list[Operation]: A vector of the operations with the specified tag in the Circuit.
    pub fn filter_by_tag(&self, tag: &str) -> PyResult<Vec<PyObject>> {
        let mut tagged: Vec<PyObject> = Vec::new();
        for op in self
            .internal
            .iter()
            .filter(|x| x.tags().contains(&tag))
            .cloned()
            .map(convert_operation_to_pyobject)
        {
            tagged.push(op?)
        }
        Ok(tagged)
    }

    /// Add an Operation to Circuit.
    ///
    /// Args:
    ///     op (Operation): The Operation to add to the Circuit.
    pub fn add(&mut self, op: &PyAny) -> PyResult<()> {
        let operation = convert_pyany_to_operation(op).map_err(|x| {
            PyTypeError::new_err(format!("Cannot convert python object to Operation {:?}", x))
        })?;
        self.internal.add_operation(operation);
        Ok(())
    }

    /// Return a string containing a formatted (string) representation of the Circuit.
    ///
    /// Returns:
    ///     str: The string representation of the Circuit.
    fn __format__(&self, _format_spec: &str) -> PyResult<String> {
        Ok(format!("{}", self.internal))
    }

    /// Return a string containing a printable representation of the Circuit.
    ///
    /// Returns:
    ///     str: The printable string representation of the Circuit.
    fn __repr__(&self) -> PyResult<String> {
        Ok(format!("{}", self.internal))
    }

    /// Return the __richcmp__ magic method to perform rich comparison operations on Circuit.
    ///
    /// Args:
    ///     self: The PragmaGeneralNoiseWrapper object.
    ///     other: The object to compare self to.
    ///     op: Type of comparison.
    ///
    /// Returns:
    ///     Whether the two operations compared evaluated to True or False
    ///
    /// Raises:
    ///     NotImplementedError: Other comparison not implemented
    fn __richcmp__(&self, other: Py<PyAny>, op: pyo3::class::basic::CompareOp) -> PyResult<bool> {
        let other = Self::from_pyany(other);
        match op {
            pyo3::class::basic::CompareOp::Eq => match other {
                Ok(circ) => Ok(self.internal == circ),
                _ => Ok(false),
            },
            pyo3::class::basic::CompareOp::Ne => match other {
                Ok(circ) => Ok(self.internal != circ),
                _ => Ok(true),
            },
            _ => Err(pyo3::exceptions::PyNotImplementedError::new_err(
                "Other comparison not implemented",
            )),
        }
    }

    /// Create an iterator of the Circuit.
    ///
    /// Returns:
    ///     OperationIterator: The Circuit in iterator form.
    fn __iter__(slf: PyRef<Self>) -> PyResult<OperationIteratorWrapper> {
        Ok(OperationIteratorWrapper {
            internal: slf.internal.clone().into_iter(),
        })
    }

    /// Return the length of the Circuit.
    ///
    /// Returns:
    ///     int: The length of the Circuit.
    fn __len__(&self) -> usize {
        self.internal.len()
    }

    /// Return a copy of the Operation at a certain index of the Circuit.
    ///
    /// Args:
    ///     index (int): The index of the Operation to get in the Circuit.
    ///
    /// Returns:
    ///     Operation: The operation at the given index (if it exists).
    ///
    /// Raises:
    ///     IndexError: Index out of range.
    fn __getitem__(&self, index: usize) -> PyResult<PyObject> {
        let operation = self
            .internal
            .get(index)
            .ok_or_else(|| PyIndexError::new_err(format!("Index {} out of range", index)))?
            .clone();
        convert_operation_to_pyobject(operation)
    }

    /// Set an Operation at the specified index in the Circuit.
    ///
    /// Args:
    ///     index (int): The index of the Operation to set in the Circuit.
    ///     value (Operation): The Operation to set in the Circuit.
    ///
    /// Raises:
    ///     TypeError: Cannot convert python object to Operation.
    ///     IndexError: Index out of range.
    fn __setitem__(&mut self, index: usize, value: &PyAny) -> PyResult<()> {
        let operation = convert_pyany_to_operation(value)
            .map_err(|_| PyTypeError::new_err("Cannot convert python object to Operation"))?;
        let mut_reference = self
            .internal
            .get_mut(index)
            .ok_or_else(|| PyIndexError::new_err(format!("Index {} out of range", index)))?;
        *mut_reference = operation;
        Ok(())
    }

    /// Implement the `+=` (__iadd__) magic method to add a Operation to a Circuit.
    ///
    /// Args:
    ///     other (Operation): The Operation object to be added to self.
    ///
    /// Raises:
    ///     TypeError: Right hand side cannot be converted to Operation or Circuit.
    fn __iadd__(&mut self, other: Py<PyAny>) -> PyResult<()> {
        Python::with_gil(|py| -> PyResult<()> {
            let other_ref = other.as_ref(py);
            match convert_pyany_to_operation(other_ref) {
                Ok(x) => {
                    self.internal += x;
                    Ok(())
                }
                Err(_) => {
                    let other = convert_into_circuit(other_ref).map_err(|x| {
                        pyo3::exceptions::PyTypeError::new_err(format!(
                            "Right hand side cannot be converted to Operation or Circuit {:?}",
                            x
                        ))
                    });
                    match other {
                        Ok(x) => {
                            self.internal += x;
                            Ok(())
                        }
                        Err(y) => Err(y),
                    }
                }
            }
        })
    }

    /// Implement the `+` (__add__) magic method to add two Circuits.
    ///
    /// Args:
    ///     lhs (Circuit): The first Circuit object in this operation.
    ///     rhs (Circuit): The second Circuit object in this operation.
    ///
    /// Returns:
    ///     lhs + rhs (Circuit): the two Circuits added together.
    ///
    /// Raises:
    ///     TypeError: Left hand side can not be converted to Circuit.
    ///     TypeError: Right hand side cannot be converted to Operation or Circuit.
    fn __add__(lhs: Py<PyAny>, rhs: Py<PyAny>) -> PyResult<CircuitWrapper> {
        Python::with_gil(|py| -> PyResult<CircuitWrapper> {
            let (lhs_ref, rhs_ref) = (lhs.as_ref(py), rhs.as_ref(py));
            let self_circ = convert_into_circuit(lhs_ref).map_err(|_| {
                PyTypeError::new_err("Left hand side can not be converted to Circuit")
            })?;
            match convert_pyany_to_operation(rhs_ref) {
                Ok(x) => Ok(CircuitWrapper {
                    internal: self_circ + x,
                }),
                Err(_) => {
                    let other = convert_into_circuit(rhs_ref).map_err(|_| {
                        pyo3::exceptions::PyTypeError::new_err(
                            "Right hand side cannot be converted to Operation or Circuit",
                        )
                    })?;
                    Ok(CircuitWrapper {
                        internal: self_circ + other,
                    })
                }
            }
        })
    }
}

/// Convert generic python object to [roqoqo::Circuit].
///
/// Fallible conversion of generic python object to [roqoqo::Circuit].
pub fn convert_into_circuit(input: &PyAny) -> Result<Circuit, QoqoError> {
    if let Ok(try_downcast) = input.extract::<CircuitWrapper>() {
        return Ok(try_downcast.internal);
    }
    // Everything that follows tries to extract the circuit when two separately
    // compiled python packages are involved
    // let get_version = input
    //     .call_method0("_qoqo_versions")
    //     .map_err(|_| QoqoError::CannotExtractObject)?;
    // let version = get_version
    //     .extract::<(&str, &str)>()
    //     .map_err(|_| QoqoError::CannotExtractObject)?;
    // let mut rsplit = ROQOQO_VERSION.split('.').take(2);
    // let mut qsplit = QOQO_VERSION.split('.').take(2);
    // let rver = format!(
    //     "{}.{}",
    //     rsplit.next().expect("ROQOQO_VERSION badly formatted"),
    //     rsplit.next().expect("ROQOQO_VERSION badly formatted")
    // );
    // let qver = format!(
    //     "{}.{}",
    //     qsplit.next().expect("QOQO_VERSION badly formatted"),
    //     qsplit.next().expect("QOQO_VERSION badly formatted")
    // );
    // let test_version: (&str, &str) = (rver.as_str(), qver.as_str());
    // if version == test_version {
    let get_bytes = input
        .call_method0("to_bincode")
        .map_err(|_| QoqoError::CannotExtractObject)?;
    let bytes = get_bytes
        .extract::<Vec<u8>>()
        .map_err(|_| QoqoError::CannotExtractObject)?;
    deserialize(&bytes[..]).map_err(|_| QoqoError::CannotExtractObject)
    // } else {
    //     Err(QoqoError::VersionMismatch)
    // }
}

/// Iterator for iterating over Operations in a Circuit.
#[pyclass(name = "OperationIterator", module = "qoqo")]
#[derive(Debug)]
pub struct OperationIteratorWrapper {
    internal: OperationIterator,
}

#[pymethods]
impl OperationIteratorWrapper {
    /// Create an iterator of the Circuit.
    ///
    /// Returns:
    ///     OperationIterator: The Circuit in iterator form.
    fn __iter__(slf: PyRef<Self>) -> PyRef<Self> {
        slf
    }

    /// Advance the iterator and return the next value.
    ///
    /// Returns None when iteration is finished. Individual iterator implementations may choose to resume iteration,
    /// and so calling next() again may or may not eventually start returning Some(Operation) again at some point.
    ///
    /// Returns:
    ///     Optional[Operation]: Operation that is next in the Iterator.
    fn __next__(mut slf: PyRefMut<Self>) -> Option<PyObject> {
        slf.internal
            .next()
            .map(|op| convert_operation_to_pyobject(op).unwrap())
    }
}