roqoqo 1.22.2

Rust Quantum Computing Toolkit by HQS
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
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
// 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.

//! Operations are the atomic instructions in any quantum program that can be represented by roqoqo.
//!
//! Operations can be of various kinds: Definitions, GateOperations, PRAGMAs or measurement Operations.
//! * Definition operations define the classical registers and variables in the Circuit.
//! * GateOperations are single-, two- or multi-qubit gate operations that act on a set of qubits
//!   and can be executed on a quantum computing device.
//! * PRAGMAs are operations that can be used when running a simulation of a quantum computing program.
//! * Measurement Operations are operations that perform a measurement either on a quantum computing device (MeasureQubit)
//!   or on a simulation of a quantum computing program (PRAGMA measurement operations).

use crate::RoqoqoError;
#[cfg(feature = "dynamic")]
use dyn_clone::DynClone;
use ndarray::Array2;
use num_complex::Complex64;
use qoqo_calculator::CalculatorFloat;
use roqoqo_derive::*;
use std::collections::{HashMap, HashSet};
/// Collection of roqoqo definition operations.
#[doc(hidden)]
mod define_operations;
pub use define_operations::*;
/// Collection of roqoqo measurement operations.
#[doc(hidden)]
mod measurement_operations;
pub use measurement_operations::*;
/// Collection of roqoqo multi qubit gate operations.
#[doc(hidden)]
mod multi_qubit_gate_operations;
pub use multi_qubit_gate_operations::*;
/// Collection of roqoqo PRAGMA operation structs.\
#[doc(hidden)]
mod pragma_operations;
pub use pragma_operations::*;
/// Collection of roqoqo single qubit gate operations.
#[doc(hidden)]
mod single_qubit_gate_operations;
pub use single_qubit_gate_operations::*;
/// Collection of roqoqo two qubit gate operations.
#[doc(hidden)]
mod two_qubit_gate_operations;
pub use two_qubit_gate_operations::*;
/// Collection of roqoqo three qubit gate operations.
#[doc(hidden)]
mod three_qubit_gate_operations;
pub use three_qubit_gate_operations::*;
/// Collection of roqoqo four qubit gate operations.
#[doc(hidden)]
mod four_qubit_gate_operations;
pub use four_qubit_gate_operations::*;
/// Collection of roqoqo bosonic operations.
#[doc(hidden)]
mod bosonic_operations;
pub use bosonic_operations::*;
/// Collection of roqoqo spin-boson operations.
mod spin_boson_operations;
pub use spin_boson_operations::*;

include!(concat!(env!("OUT_DIR"), "/_auto_generated_operations.rs"));

/// Represents qubits involved in a roqoqo Operation.
#[derive(Debug, PartialEq, Clone, Eq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
pub enum InvolvedQubits {
    /// Operation affects all qubits no matter how many there are.
    All,
    /// Operation affects no qubits (annotations etc.).
    None,
    /// Operation affects a specific set of qubits.
    Set(HashSet<usize>),
}

/// Represents classical register entries involved in a roqoqo Operation.
#[derive(Debug, PartialEq, Clone, Eq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
pub enum InvolvedClassical {
    /// Operation affects all entries of a classical register.
    All(String),
    /// Operation affects all entries of a classical register up to the number of qubits in device.
    AllQubits(String),
    /// Operation affects no classical entries (annotations etc.).
    None,
    /// Operation affects a specific set of classical entries.
    Set(HashSet<(String, usize)>),
}

/// Trait for returning minimum roqoqo version for which a operation is supported
pub trait SupportedVersion {
    /// Returns the minimum roqoqo version that supports the operation.
    ///
    /// Expects a semver version string. Returns the major and minor version
    /// already converted to unsigned integers and the optionla extension of the
    /// version string.
    fn minimum_supported_roqoqo_version(&self) -> (u32, u32, u32) {
        (1, 0, 0)
    }
}

#[cfg(feature = "dynamic")]
/// Universal basic trait for all operations of roqoqo.
#[cfg_attr(feature = "dynamic", typetag::serde(tag = "Operate"))]
pub trait Operate:
    InvolveQubits + SubstituteDyn + DynClone + std::fmt::Debug + Send + SupportedVersion
{
    /// Returns tags classifying the type of operation.
    ///
    /// Used for type based dispatch in ffi interfaces.
    fn tags(&self) -> &'static [&'static str];
    /// Returns hqslang name of operation.
    ///
    /// As a general rule that should correspond to the roqoqo name of the operation.
    fn hqslang(&self) -> &'static str;
    /// Returns true when operation has symbolic parameters.
    fn is_parametrized(&self) -> bool;
}

#[cfg(not(feature = "dynamic"))]
/// Universal basic trait for all operations of roqoqo.
///
/// # Example
/// ```
/// use roqoqo::operations::{Operate, PauliX, RotateZ};
/// use qoqo_calculator::CalculatorFloat;
///
/// let paulix = PauliX::new(0);
/// let gate_tags: &[&str; 4] = &[
///     "Operation",
///     "GateOperation",
///     "SingleQubitGateOperation",
///     "PauliX",
/// ];
///
/// // 1) The tags of the operation tell us what kind of operation it is, and what traits it implements
/// assert_eq!(paulix.tags(), gate_tags);
/// // 2) The name of the operation is given by hqslang
/// assert_eq!(paulix.hqslang(), "PauliX");
/// // 3) Whether a gate is parametrized is determined by whether any of its inputs are symbolic (CalculatorFloat with a string).
/// // As the PauliX gate only takes an integer input (qubit), it can never be parametrized.
/// assert!(!paulix.is_parametrized());
/// // However, a RotateZ gate can be parametrized:
/// let rotatez_param = RotateZ::new(0, CalculatorFloat::from("parametrized"));
/// assert!(rotatez_param.is_parametrized());
/// // But it can also not be parametrized:
/// let rotatez_not_param = RotateZ::new(0, CalculatorFloat::from(2.0));
/// assert!(!rotatez_not_param.is_parametrized());
/// ```
///
pub trait Operate:
    InvolveQubits + Substitute + Clone + std::fmt::Debug + Send + SupportedVersion
{
    /// Returns tags classifying the type of the operation.
    ///
    /// Used for type based dispatch in ffi interfaces.
    fn tags(&self) -> &'static [&'static str];
    /// Returns hqslang name of the operation.
    ///
    /// As a general rule that should correspond to the roqoqo name of the operation.
    fn hqslang(&self) -> &'static str;
    /// Returns `true` when operation has symbolic parameters.
    fn is_parametrized(&self) -> bool;
}

#[cfg(feature = "dynamic")]
dyn_clone::clone_trait_object!(Operate);

/// Trait for the qubits involved in each Operation.
///
/// # Example
/// ```
/// use roqoqo::operations::{CNOT, DefinitionFloat, InvolveQubits, InvolvedQubits, PragmaRepeatedMeasurement};
/// use std::collections::{HashMap, HashSet};
///
/// // The involved qubits of the operation tell us which qubits are affected by the Operation.
/// // There are three possibilities:
/// // 1) The involved qubits are a set of integers (usize): these are the qubits affected by the Operation
/// let cnot = CNOT::new(0, 1);
/// let mut qubits: HashSet<usize> = HashSet::new();
/// qubits.insert(0);
/// qubits.insert(1);
/// assert_eq!(cnot.involved_qubits(), InvolvedQubits::Set(qubits));
/// // 2) The involved qubits are None: there are no qubits affected by this Operation
/// let def_float = DefinitionFloat::new("ro".to_string(), 1, true);
/// assert_eq!(def_float.involved_qubits(), InvolvedQubits::None);
/// // 3) The involved qubits are All: all of the qubits in the Circuit are affected by the Operation
/// let mut qubit_mapping: HashMap<usize, usize> = HashMap::new();
/// qubit_mapping.insert(0, 1);
/// let pragma = PragmaRepeatedMeasurement::new("ro".to_string(), 2, Some(qubit_mapping.clone()));
/// assert_eq!(pragma.involved_qubits(), InvolvedQubits::All);
/// ```
pub trait InvolveQubits {
    /// Returns all qubits involved in operation.
    fn involved_qubits(&self) -> InvolvedQubits;

    /// Returns all classical registers involved in operation.
    fn involved_classical(&self) -> InvolvedClassical {
        InvolvedClassical::None
    }
}

/// Substitute trait allowing to replace symbolic parameters and to perform qubit mappings.
///
/// # Example
/// ```
/// use roqoqo::operations::{RotateZ, Substitute};
/// use qoqo_calculator::{Calculator, CalculatorFloat};
/// use std::collections::HashMap;
///
/// // 1) The substitute_parameters function substitutes all symbolic parameters in the Operation and its inputs
/// let rotatez = RotateZ::new(0, CalculatorFloat::from("sub"));
/// let mut substitution_dict: Calculator = Calculator::new();
/// substitution_dict.set_variable("sub", 0.0);
/// let result = rotatez
///     .substitute_parameters(&substitution_dict)
///     .unwrap();
/// assert_eq!(result, RotateZ::new(0, CalculatorFloat::from(0.0)));
/// // 2) The remap_qubits function remaps all qubits in the Operation and its inputs
/// let rotatez = RotateZ::new(0, CalculatorFloat::from(0.0));
/// let mut qubit_mapping_test: HashMap<usize, usize> = HashMap::new();
/// qubit_mapping_test.insert(0, 2);
/// qubit_mapping_test.insert(2, 0);
/// let result = rotatez.remap_qubits(&qubit_mapping_test).unwrap();
/// assert_eq!(result, RotateZ::new(2, CalculatorFloat::from(0.0)));
/// ```
///
pub trait Substitute
where
    Self: Sized,
{
    /// Substitutes symbolic parameters in clone of the operation.
    fn substitute_parameters(
        &self,
        calculator: &qoqo_calculator::Calculator,
    ) -> Result<Self, RoqoqoError>;
    /// Remaps the qubits in clone of the operation.
    fn remap_qubits(&self, mapping: &HashMap<usize, usize>) -> Result<Self, RoqoqoError>;
}

#[cfg(feature = "dynamic")]
/// Helper trait for implementing substitute for Box<dyn> operation.
pub trait SubstituteDyn {
    /// Substitute parameters in symbolic expression in clone of operation.
    fn substitute_parameters_dyn(
        &self,
        calculator: &qoqo_calculator::Calculator,
    ) -> Result<Box<dyn Operate>, RoqoqoError>;
    /// Remap qubits in operations in clone of operation.
    fn remap_qubits_dyn(
        &self,
        mapping: &HashMap<usize, usize>,
    ) -> Result<Box<dyn Operate>, RoqoqoError>;
}

#[cfg(feature = "dynamic")]
impl<T> SubstituteDyn for T
where
    T: 'static + Operate + Substitute,
{
    /// Substitute symbolic parameters in boxed clone of operation.
    fn substitute_parameters_dyn(
        &self,
        calculator: &qoqo_calculator::Calculator,
    ) -> Result<Box<dyn Operate>, RoqoqoError> {
        Ok(Box::new(Substitute::substitute_parameters(
            self, calculator,
        )?))
    }
    /// Remap qubits in operations in boxed clone of operation.
    fn remap_qubits_dyn(
        &self,
        mapping: &HashMap<usize, usize>,
    ) -> Result<Box<dyn Operate>, RoqoqoError> {
        Ok(Box::new(Substitute::remap_qubits(self, mapping)?))
    }
}

/// Trait for operations acting on exactly one qubit.
///
/// # Example
/// ```
/// use roqoqo::operations::{OperateSingleQubit, PauliX};
/// let paulix = PauliX::new(0);
/// assert_eq!(paulix.qubit(), &0_usize);
/// ```
///
pub trait OperateSingleQubit: Operate + InvolveQubits + Substitute + Clone + PartialEq {
    /// Returns `qubit` the Operation acts on.
    fn qubit(&self) -> &usize;
}

/// Trait for Operations acting on exactly two qubits.
///
/// # Example
/// ```
/// use roqoqo::operations::{CNOT, OperateTwoQubit};
/// let cnot = CNOT::new(0, 1);
/// assert_eq!(cnot.control(), &0_usize);
/// assert_eq!(cnot.target(), &1_usize);
/// ```
///
pub trait OperateTwoQubit: Operate + InvolveQubits + Substitute + Clone + PartialEq {
    /// Returns `target` qubit of two qubit Operation.
    fn target(&self) -> &usize;
    /// Returns `control` qubit of two qubit Operation.
    fn control(&self) -> &usize;
}

/// Trait for Operations acting on exactly three qubits.
///
/// # Example
/// ```
/// use roqoqo::operations::{ControlledControlledPauliZ, OperateThreeQubit};
/// let ccz = ControlledControlledPauliZ::new(0, 1, 2);
/// assert_eq!(ccz.control_0(), &0_usize);
/// assert_eq!(ccz.control_1(), &1_usize);
/// assert_eq!(ccz.target(), &2_usize);
/// ```
///
pub trait OperateThreeQubit: Operate + InvolveQubits + Substitute + Clone + PartialEq {
    /// Returns `target` qubit of three qubit Operation.
    fn target(&self) -> &usize;
    /// Returns `control_0` qubit of three qubit Operation.
    fn control_0(&self) -> &usize;
    /// Returns `control_1` qubit of three qubit Operation.
    fn control_1(&self) -> &usize;
}

/// Trait for Operations acting on exactly four qubits.
///
/// # Example
/// ```
/// use roqoqo::operations::{TripleControlledPauliX, OperateFourQubit};
/// let cccx = TripleControlledPauliX::new(0, 1, 2, 3);
/// assert_eq!(cccx.control_0(), &0_usize);
/// assert_eq!(cccx.control_1(), &1_usize);
/// assert_eq!(cccx.control_2(), &2_usize);
/// assert_eq!(cccx.target(), &3_usize);
/// ```
///
pub trait OperateFourQubit: Operate + InvolveQubits + Substitute + Clone + PartialEq {
    /// Returns `target` qubit of four qubit Operation.
    fn target(&self) -> &usize;
    /// Returns `control_0` qubit of four qubit Operation.
    fn control_0(&self) -> &usize;
    /// Returns `control_1` qubit of four qubit Operation.
    fn control_1(&self) -> &usize;
    /// Returns `control_2` qubit of four qubit Operation.
    fn control_2(&self) -> &usize;
}

/// Trait for operations acting on multiple (more than two) qubits.
///
/// # Example
/// ```
/// use roqoqo::operations::{MultiQubitMS, OperateMultiQubit};
/// use qoqo_calculator::CalculatorFloat;
/// let multi_ms = MultiQubitMS::new(vec![0, 1, 3], CalculatorFloat::from(0.0));
/// assert_eq!(multi_ms.qubits(), &vec![0, 1, 3]);
/// ```
///
pub trait OperateMultiQubit:
    Operate + InvolveQubits + Substitute + Clone + PartialEq + SupportedVersion
{
    /// Returns vector of qubits operation is acting on in descending order of significance
    fn qubits(&self) -> &Vec<usize>;
}

/// Trait for PRAGMA Operations that are not necessary available on all universal quantum hardware.
///
/// PRAGMA Operations are unphysical in terms of quantum mechanics and are meant to be used for simulation purposes only, i.e. to run on simulation backends.
///
pub trait OperatePragma:
    Operate + InvolveQubits + Substitute + Clone + PartialEq + SupportedVersion
{
}

/// Trait for PRAGMA Operations that are not necessary available on all universal quantum hardware, that indicate noise.
///
/// # Example
/// ```
/// use ndarray::{array, Array2};
/// use roqoqo::operations::{OperatePragmaNoise, OperatePragmaNoiseProba, PragmaDamping};
/// use qoqo_calculator::CalculatorFloat;
///
/// let pragma = PragmaDamping::new(0, CalculatorFloat::from(0.005), CalculatorFloat::from(0.02));
///
/// // 1) The superoperator representation of the noise Pragma
/// let superop_prob: f64 = *pragma.probability().float().unwrap();
/// let superop_sqrt: f64 = (1.0 - superop_prob.clone()).sqrt();
/// let superop: Array2<f64> = array![
///     [1.0, 0.0, 0.0, superop_prob.clone()],
///     [0.0, superop_sqrt, 0.0, 0.0],
///     [0.0, 0.0, superop_sqrt, 0.0],
///     [0.0, 0.0, 0.0, 1.0 - superop_prob.clone()],
/// ];
/// assert_eq!(superop, pragma.superoperator().unwrap());
/// // 2) The power function applied to the noise Pragma
/// let pragma_test = PragmaDamping::new(
///     0,
///     CalculatorFloat::from(0.005 * 1.5),
///     CalculatorFloat::from(0.02),
/// );
/// assert_eq!(pragma_test, pragma.powercf(CalculatorFloat::from(1.5)));
/// ```
///
pub trait OperatePragmaNoise:
    Operate + InvolveQubits + Substitute + Clone + PartialEq + OperatePragma + SupportedVersion
{
    /// Returns superoperator matrix of the Operation.
    fn superoperator(&self) -> Result<Array2<f64>, RoqoqoError>;
    /// Returns the gate to the power of `power`.
    fn powercf(&self, power: qoqo_calculator::CalculatorFloat) -> Self;
}

/// Trait for PRAGMA Operations that are not necessary available on all universal quantum hardware, that indicate noise.
///
/// # Example
/// ```
/// use ndarray::{array, Array2};
/// use roqoqo::operations::{OperatePragmaNoiseProba, PragmaDamping};
/// use qoqo_calculator::CalculatorFloat;
///
/// let pragma = PragmaDamping::new(0, CalculatorFloat::from(0.005), CalculatorFloat::from(0.02));
///
/// // The probability of the noise Pragma
/// let proba_pre_exp: f64 = -1.0 * 0.005 * 0.02;
/// let proba = CalculatorFloat::from(1.0 - proba_pre_exp.exp());
/// assert_eq!(proba, pragma.probability());
/// ```
///
pub trait OperatePragmaNoiseProba:
    Operate
    + InvolveQubits
    + Substitute
    + Clone
    + PartialEq
    + OperatePragma
    + OperatePragmaNoise
    + SupportedVersion
{
    /// Returns the probability of the gate, based on its gate_time and rate.
    fn probability(&self) -> CalculatorFloat;
}

/// Trait for Operations acting with a unitary gate on a set of qubits.
///
/// # Example
/// ```
/// use ndarray::array;
/// use num_complex::Complex64;
/// use roqoqo::operations::{OperateGate, PauliX};
///
/// let paulix = PauliX::new(0);
/// let matrix = array![
///     [Complex64::new(0.0, 0.0), Complex64::new(1.0, 0.0)],
///     [Complex64::new(1.0, 0.0), Complex64::new(0.0, 0.0)]
/// ];
/// assert_eq!(paulix.unitary_matrix().unwrap(), matrix);
/// ```
///
pub trait OperateGate:
    Operate + InvolveQubits + Substitute + Clone + PartialEq + SupportedVersion
{
    /// Returns unitary matrix of the gate.
    fn unitary_matrix(&self) -> Result<Array2<Complex64>, RoqoqoError>;
}

/// Trait for unitary operations corresponding to rotations that can be characteriszed by a single rotation parameter theta.
///
/// # Example
/// ```
/// use qoqo_calculator::CalculatorFloat;
/// use roqoqo::operations::{Rotate, RotateX};
/// let rotatex = RotateX::new(0, 2.0.into());
///
/// // 1) The angle of rotation of the Rotate Operation
/// assert_eq!(rotatex.theta(), &CalculatorFloat::from(2.0));
/// // 2) The power function applied to the Rotate Operation
/// assert_eq!(rotatex.powercf(CalculatorFloat::from(1.5)), RotateX::new(0, 3.0.into()));
/// ```
///
pub trait Rotate:
    OperateGate + Operate + InvolveQubits + Substitute + Clone + PartialEq + SupportedVersion
{
    /// Returns rotation parameter theta.
    fn theta(&self) -> &CalculatorFloat;
    /// Returns the gate to the power of `power`.`
    fn powercf(&self, power: CalculatorFloat) -> Self;

    #[cfg(feature = "overrotate")]
    /// Returns clone of the gate with one parameter statistically overrotated.
    ///
    /// A random number drawn from a normal distribution N(0, variance^2)
    /// and multiplied by the amplitue  is added to the overrotated parameter.  
    /// gate_overrotated.parameter() = gate.parameter + amplitude * rand(N(0, variance^2))
    ///
    /// This functionc is specifically designed for statistical overrotations that change the angle
    /// of an applied rotation gate randomly during the execution of a quantum program.  
    /// For static overrotations that represent a drift in the callibration of gates and are constant
    /// during the execution of a quantum programm use symbolic parameters and the substitute_parameters
    /// function.
    ///
    /// # Arguments
    ///
    /// *`amplitude` - The amplitude the random number is multiplied with.
    /// *`variance` - The standard deviation of the normal distribution the random number is drawn from.
    ///
    /// # Example
    /// ```
    /// use roqoqo::prelude::*;
    /// use roqoqo::operations::RotateZ;
    ///
    /// let gate = RotateZ::new(0, 1.0.into());
    /// let overrotated_gate = gate.overrotate(&1.0, &0.5);
    /// println!("{gate:?}");
    /// println!("{overrotated_gate:?}");
    /// let gate_symbolic = RotateZ::new(0, "theta_var".into());
    /// let overrotated_symbolic = gate_symbolic.overrotate(&1.0, &0.5);
    /// println!("{gate_symbolic:?}");
    /// println!("{overrotated_symbolic:?}");
    /// ```
    fn overrotate(&self, amplitude: &f64, variance: &f64) -> Self;
}

/// Trait for definition operations.
///
/// # Example
/// ```
/// use roqoqo::operations::{Define, DefinitionFloat};
/// let definition = DefinitionFloat::new("ro".to_string(), 1, false);
/// assert_eq!(definition.name(), &"ro".to_string());
/// ```
///
pub trait Define:
    Operate + InvolveQubits + Substitute + Clone + PartialEq + SupportedVersion
{
    /// Returns name of definition operation.
    fn name(&self) -> &String;
}

/// Trait for unitary operations without any free parameters.
///
/// # Example
/// ```
/// use roqoqo::operations::{OperateConstantGate, PauliX};
/// let paulix = PauliX::new(0);
/// ```
///
pub trait OperateConstantGate:
    OperateGate + Operate + InvolveQubits + Substitute + Clone + PartialEq + SupportedVersion
{
    /// Returns true when unitary operation U is self inverse U*U = I.
    fn inverse(&self) -> GateOperation;
}

/// Trait for unitary operations acting on exactly one qubit.
///
/// Implements the general single qubit unitary gates  that can be brought into the form:
///
/// U =exp(i * φ) * [[Re(α)+i * Im(α), -Re(β) + i * Im(β)], [Re(β) + i * Im(β) , Re(α) - i * Im(α) ]].
///
/// These gates can be parametrized by five real parameters:
///
/// * `alpha_r` - The real part Re(α) of the on-diagonal elements of the single-qubit unitary.
/// * `alpha_i` - The imaginary part Im(α) of the on-diagonal elements of the single-qubit unitary.
/// * `beta_r` - The real part Re(β) of the off-diagonal elements of the single-qubit unitary.
/// * `beta_i` - The imaginary part Im(β) of the off-diagonal elements of the single-qubit unitary.
/// * `global_phase` - The global phase φ of the single-qubit unitary.
///
/// These are the single qubit gates that are performed in the Circuit(), and are then translated
/// to quantum hardware through the relevant backend. Two-qubit gates are also available
/// (see roqoqo/src/operations/two_qubit_gate_operations.rs).
///
/// # Example
/// ```
/// use qoqo_calculator::CalculatorFloat;
/// use roqoqo::operations::{OperateSingleQubitGate, PauliX};
/// use std::f64::consts::PI;
///
/// let paulix = PauliX::new(0);
///
/// assert_eq!(paulix.alpha_r(), 0.0.into());
/// assert_eq!(paulix.alpha_i(), 0.0.into());
/// assert_eq!(paulix.beta_r(), 0.0.into());
/// assert_eq!(paulix.beta_i(), CalculatorFloat::from(-1.0));
/// assert_eq!(paulix.global_phase(), ((PI) / 2.0).into());
/// ```
///
pub trait OperateSingleQubitGate:
    Operate
    + OperateGate
    + InvolveQubits
    + Substitute
    + OperateSingleQubit
    + Clone
    + PartialEq
    + SupportedVersion
    + std::fmt::Debug
{
    /// Returns alpha_r parameter of operation.
    ///
    /// # Returns
    ///
    /// * `alpha_r` - The real part Re(α) of the on-diagonal elements of the single-qubit unitary matrix.
    fn alpha_r(&self) -> CalculatorFloat;

    /// Returns alpha_i parameter of operation.
    ///
    /// # Returns
    ///
    /// * `alpha_i` - The imaginary part Im(α) of the on-diagonal elements of the single-qubit unitary matrix.
    fn alpha_i(&self) -> CalculatorFloat;

    /// Returns beta_r parameter of operation.
    ///
    /// # Returns
    ///
    /// * `beta_r` - The real part Re(β) of the off-diagonal elements of the single-qubit unitary matrix.
    fn beta_r(&self) -> CalculatorFloat;

    /// Returns beta_i parameter of operation.
    ///
    /// # Returns
    ///
    /// * `beta_i` -  imaginary part Im(β) of the off-diagonal elements of the single-qubit unitary matrix.
    fn beta_i(&self) -> CalculatorFloat;

    /// Returns global_phase parameter of operation.
    ///
    /// # Returns
    ///
    /// * `global_phase` - The global phase phi φ of the single-qubit unitary.
    fn global_phase(&self) -> CalculatorFloat;

    /// Multiplies two compatible operations implementing OperateSingleQubitGate.
    ///
    /// Does not consume the two operations being multiplied.
    /// Only Operations
    ///
    /// # Arguments:
    ///
    /// * `other` - An Operation implementing [OperateSingleQubitGate].
    ///
    /// # Example
    /// ```
    /// use roqoqo::operations::{RotateZ, RotateX};
    /// use roqoqo::prelude::*;
    /// use qoqo_calculator::CalculatorFloat;
    ///
    /// let gate1 =  RotateZ::new(0, CalculatorFloat::from(1));
    /// let gate2 =  RotateX::new(0, CalculatorFloat::from(1));
    /// let multiplied = gate1.mul(&gate2).unwrap();
    /// ```
    fn mul<T>(&self, other: &T) -> Result<SingleQubitGate, RoqoqoError>
    where
        T: OperateSingleQubitGate,
    {
        if self.qubit() != other.qubit() {
            return Err(RoqoqoError::MultiplicationIncompatibleQubits {
                squbit: *self.qubit(),
                oqubit: *other.qubit(),
            });
        }
        let alpha = qoqo_calculator::CalculatorComplex::new(self.alpha_r(), self.alpha_i());
        let beta = qoqo_calculator::CalculatorComplex::new(self.beta_r(), self.beta_i());
        let oalpha = qoqo_calculator::CalculatorComplex::new(other.alpha_r(), other.alpha_i());
        let obeta = qoqo_calculator::CalculatorComplex::new(other.beta_r(), other.beta_i());
        let new_alpha = alpha.clone() * &oalpha - beta.conj() * &obeta;
        let new_beta = beta * oalpha + obeta * alpha.conj();

        if new_alpha.re.is_float()
            && new_alpha.im.is_float()
            && new_beta.re.is_float()
            && new_beta.im.is_float()
        {
            let norm = (new_alpha.re.float().unwrap().powf(2.0)
                + new_alpha.im.float().unwrap().powf(2.0)
                + new_beta.re.float().unwrap().powf(2.0)
                + new_beta.im.float().unwrap().powf(2.0))
            .sqrt();

            if (norm - 1.0).abs() > f64::EPSILON {
                Ok(SingleQubitGate::new(
                    *other.qubit(),
                    new_alpha.re / norm,
                    new_alpha.im / norm,
                    new_beta.re / norm,
                    new_beta.im / norm,
                    self.global_phase() + other.global_phase(),
                ))
            } else {
                Ok(SingleQubitGate::new(
                    *other.qubit(),
                    new_alpha.re,
                    new_alpha.im,
                    new_beta.re,
                    new_beta.im,
                    self.global_phase() + other.global_phase(),
                ))
            }
        } else {
            Ok(SingleQubitGate::new(
                *other.qubit(),
                new_alpha.re,
                new_alpha.im,
                new_beta.re,
                new_beta.im,
                self.global_phase() + other.global_phase(),
            ))
        }
    }
    /// Returns equivalent SingleQubitGate.
    ///
    /// Converts Operation implementing OperateSingleQubitGate Trait into SingleQubitGate.
    fn to_single_qubit_gate(&self) -> SingleQubitGate {
        SingleQubitGate::new(
            *self.qubit(),
            self.alpha_r(),
            self.alpha_i(),
            self.beta_r(),
            self.beta_i(),
            self.global_phase(),
        )
    }
}

/// Trait for all Operations operating on or affecting exactly two qubits.
///
/// # Example
/// ```
/// use roqoqo::operations::{ISwap, KakDecomposition, OperateTwoQubitGate};
/// use qoqo_calculator::CalculatorFloat;
/// let iswap = ISwap::new(0, 1);
///
/// assert_eq!(iswap.kak_decomposition().circuit_before, None);
/// assert_eq!(iswap.kak_decomposition().circuit_after, None);
/// assert_eq!(iswap.kak_decomposition().global_phase, CalculatorFloat::ZERO);
/// assert_eq!(iswap.kak_decomposition().k_vector, [CalculatorFloat::FRAC_PI_4, CalculatorFloat::FRAC_PI_4, CalculatorFloat::ZERO]);
/// ```
///
pub trait OperateTwoQubitGate:
    Operate
    + OperateGate
    + OperateTwoQubit
    + InvolveQubits
    + Substitute
    + Clone
    + PartialEq
    + SupportedVersion
{
    /// Returns [KakDecomposition] of two qubit gate.
    fn kak_decomposition(&self) -> KakDecomposition;
}

/// Trait for all Operations operating on or affecting exactly three qubits.
///
/// # Example
/// ```
/// use roqoqo::operations::{CNOT, ControlledPhaseShift, ControlledControlledPauliZ, OperateThreeQubitGate};
/// use roqoqo::Circuit;
/// use qoqo_calculator::CalculatorFloat;
///
/// let ccpz = ControlledControlledPauliZ::new(0, 1, 2);
/// let mut circuit = Circuit::new();
/// circuit += ControlledPhaseShift::new(1, 2, CalculatorFloat::FRAC_PI_2);
/// circuit += CNOT::new(0, 1);
/// circuit += ControlledPhaseShift::new(1, 2, -CalculatorFloat::FRAC_PI_2);
/// circuit += CNOT::new(0, 1);
/// circuit += ControlledPhaseShift::new(0, 2, CalculatorFloat::FRAC_PI_2);
///
/// assert_eq!(ccpz.circuit(), circuit);
/// ```
pub trait OperateThreeQubitGate:
    Operate
    + OperateGate
    + OperateThreeQubit
    + InvolveQubits
    + Substitute
    + Clone
    + PartialEq
    + SupportedVersion
{
    /// Returns a decomposition of the three-qubit operation using a circuit with two-qubit-operations.
    fn circuit(&self) -> crate::Circuit;
}

/// Trait for all Operations operating on or affecting exactly three qubits.
///
/// # Example
/// ```
/// use roqoqo::operations::{CNOT, TripleControlledPauliX, OperateFourQubitGate};
/// use roqoqo::Circuit;
///
/// let cccx = TripleControlledPauliX::new(0, 1, 2, 3);
/// let mut circuit = Circuit::new();
/// circuit += CNOT::new(0, 3);
/// circuit += CNOT::new(0, 1);
/// circuit += CNOT::new(1, 3);
/// circuit += CNOT::new(0, 1);
/// circuit += CNOT::new(1, 3);
/// circuit += CNOT::new(1, 2);
/// circuit += CNOT::new(2, 3);
/// circuit += CNOT::new(0, 2);
/// circuit += CNOT::new(2, 3);
/// circuit += CNOT::new(1, 2);
/// circuit += CNOT::new(2, 3);
/// circuit += CNOT::new(0, 2);
/// circuit += CNOT::new(2, 3);
///
/// assert_eq!(cccx.circuit(), circuit);
/// ```
pub trait OperateFourQubitGate:
    Operate
    + OperateGate
    + OperateFourQubit
    + InvolveQubits
    + Substitute
    + Clone
    + PartialEq
    + SupportedVersion
{
    /// Returns a decomposition of the three-qubit operation using a circuit with two-qubit-operations.
    fn circuit(&self) -> crate::Circuit;
}

/// Trait for all Operations operating on or affecting more than two qubits.
///
/// # Example
/// ```
/// use roqoqo::operations::{CNOT, Hadamard, MultiQubitMS, OperateMultiQubitGate, RotateZ};
/// use roqoqo::Circuit;
/// use qoqo_calculator::CalculatorFloat;
///
/// let multi_ms = MultiQubitMS::new(vec![0, 1, 2], CalculatorFloat::from(1.0));
/// let mut circuit = Circuit::new();
/// circuit += Hadamard::new(0);
/// circuit += Hadamard::new(1);
/// circuit += Hadamard::new(2);
/// circuit += CNOT::new(0, 1);
/// circuit += CNOT::new(1, 2);
/// circuit += RotateZ::new(2, CalculatorFloat::from(1.0));
/// circuit += CNOT::new(1, 2);
/// circuit += CNOT::new(0, 1);
/// circuit += Hadamard::new(0);
/// circuit += Hadamard::new(1);
/// circuit += Hadamard::new(2);
///
/// assert_eq!(multi_ms.circuit(), circuit);
/// ```
///
pub trait OperateMultiQubitGate:
    Operate
    + OperateGate
    + OperateMultiQubit
    + InvolveQubits
    + Substitute
    + Clone
    + PartialEq
    + SupportedVersion
{
    /// Returns a decomposition of the multi-qubit operation using a circuit with two-qubit-operations.
    fn circuit(&self) -> crate::Circuit;
}

/// Marker trait to show that some operation has been implemented in roqoqo 1.1.0
pub trait ImplementedIn1point1: Operate {}

/// Marker trait to show that some operation has been implemented in roqoqo 1.2.0
pub trait ImplementedIn1point2: Operate {}

/// Marker trait to show that some operation has been implemented in roqoqo 1.3.0
pub trait ImplementedIn1point3: Operate {}

/// Marker trait to show that some operation has been implemented in roqoqo 1.4.0
pub trait ImplementedIn1point4: Operate {}

/// Marker trait to show that some operation has been implemented in roqoqo 1.5.0
pub trait ImplementedIn1point5: Operate {}

/// Marker trait to show that some operation has been implemented in roqoqo 1.6.0
pub trait ImplementedIn1point6: Operate {}

/// Marker trait to show that some operation has been implemented in roqoqo 1.7.0
pub trait ImplementedIn1point7: Operate {}

/// Marker trait to show that some operation has been implemented in roqoqo 1.8.0
pub trait ImplementedIn1point8: Operate {}

/// Marker trait to show that some operation has been implemented in roqoqo 1.9.0
pub trait ImplementedIn1point9: Operate {}

/// Marker trait to show that some operation has been implemented in roqoqo 1.10.0
pub trait ImplementedIn1point10: Operate {}

/// Marker trait to show that some operation has been implemented in roqoqo 1.11.0
pub trait ImplementedIn1point11: Operate {}

/// Marker trait to show that some operation has been implemented in roqoqo 1.13.0
pub trait ImplementedIn1point13: Operate {}

/// Marker trait to show that some operation has been implemented in roqoqo 1.14.0
pub trait ImplementedIn1point14: Operate {}

/// Marker trait to show that some operation has been implemented in roqoqo 1.15.0
pub trait ImplementedIn1point15: Operate {}

/// Marker trait to show that some operation has been implemented in roqoqo 1.16.0
pub trait ImplementedIn1point16: Operate {}

/// Marker trait to show that some operation has been implemented in roqoqo 1.17.0
pub trait ImplementedIn1point17: Operate {}

/// Marker trait to show that some operation has been implemented in roqoqo 1.18.0
pub trait ImplementedIn1point18: Operate {}

/// Marker trait to show that some operation has been implemented in roqoqo 1.19.0
pub trait ImplementedIn1point19: Operate {}

/// Marker trait to show that some operation has been implemented in roqoqo 1.20.0
pub trait ImplementedIn1point20: Operate {}

/// Marker trait to show that some operation has been implemented in roqoqo 1.21.0
pub trait ImplementedIn1point21: Operate {}

#[cfg(feature = "dynamic")]
/// A wrapper for Operate trait objects.
///
/// This wrapper struct can be used to insert Operate trait objects in a circuit.
/// The intended use case is to store structs from an external crate that implement Operate,
/// in a circuit.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
pub struct DynOperation(Box<dyn Operate>);

#[cfg(feature = "dynamic")]
#[cfg_attr(feature = "dynamic", typetag::serde)]
impl Operate for DynOperation {
    fn tags(&self) -> &'static [&'static str] {
        self.0.tags()
    }
    fn hqslang(&self) -> &'static str {
        self.0.hqslang()
    }
    fn is_parametrized(&self) -> bool {
        self.0.is_parametrized()
    }
}

#[cfg(feature = "dynamic")]
impl SupportedVersion for DynOperation {
    fn minimum_supported_roqoqo_version(&self) -> (u32, u32, u32) {
        self.0.minimum_supported_roqoqo_version()
    }
}

#[cfg(feature = "dynamic")]
impl InvolveQubits for DynOperation {
    fn involved_qubits(&self) -> InvolvedQubits {
        self.0.involved_qubits()
    }
}
#[cfg(feature = "dynamic")]
/// Implements [Substitute] trait allowing to replace symbolic parameters and to perform qubit mappings.
impl Substitute for DynOperation {
    fn substitute_parameters(
        &self,
        calculator: &qoqo_calculator::Calculator,
    ) -> Result<Self, RoqoqoError> {
        Ok(DynOperation(self.0.substitute_parameters_dyn(calculator)?))
    }
    fn remap_qubits(&self, mapping: &HashMap<usize, usize>) -> Result<Self, RoqoqoError> {
        Ok(DynOperation(self.0.remap_qubits_dyn(mapping)?))
    }
}
#[cfg(feature = "dynamic")]
impl PartialEq for DynOperation {
    fn eq(&self, other: &Self) -> bool {
        self.0.hqslang() == other.0.hqslang()
    }
}

/// Check if a HashMap is a valid mapping for remapping_qubits
#[inline]
pub(crate) fn check_valid_mapping(mapping: &HashMap<usize, usize>) -> Result<(), RoqoqoError> {
    for q in mapping.values() {
        if !mapping.contains_key(q) {
            return Err(RoqoqoError::QubitMappingError { qubit: *q });
        }
    }
    Ok(())
}

/// Represents bosonic modes involved in a roqoqo bosonic Operation.
#[derive(Debug, PartialEq, Clone, Eq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
pub enum InvolvedModes {
    /// Operation affects all bosonic modes no matter how many there are.
    All,
    /// Operation affects no bosonic modes (annotations etc.).
    None,
    /// Operation affects a specific set of bosonic modes.
    Set(HashSet<usize>),
}

// #[cfg(feature = "dynamic")]
// dyn_clone::clone_trait_object!(Operate);

/// Trait for the bosonic modes involved in each bosonic Operation.
///
/// # Example
/// ```
/// use roqoqo::operations::{InvolveModes, InvolvedModes, PhotonDetection, BeamSplitter};
/// use std::collections::HashSet;
///
/// let measurement = PhotonDetection::new(1, "ro".into(), 0);
/// let operation = BeamSplitter::new(0, 1, 0.1.into(), 0.2.into());
///
/// let mut modes: HashSet<usize> = HashSet::new();
/// modes.insert(1);
/// assert_eq!(measurement.involved_modes(), InvolvedModes::Set(modes.clone()));
/// modes.insert(0);
/// assert_eq!(operation.involved_modes(), InvolvedModes::Set(modes));
/// ```
pub trait InvolveModes {
    /// Returns all bosonic modes involved in operation.
    fn involved_modes(&self) -> InvolvedModes {
        InvolvedModes::None
    }
}

/// SubstituteModes trait allowing to perform bosonic mode mappings.
///
/// # Example
/// ```
/// use roqoqo::operations::{SubstituteModes, BeamSplitter};
/// use qoqo_calculator::{Calculator, CalculatorFloat};
/// use std::collections::HashMap;
///
/// let mut mode_mapping_test: HashMap<usize, usize> = HashMap::new();
/// mode_mapping_test.insert(0, 2);
/// mode_mapping_test.insert(1, 0);
/// mode_mapping_test.insert(2, 1);
///
/// let operation = BeamSplitter::new(0, 1, 0.1.into(), 0.2.into());
/// let operation_after_remapping = BeamSplitter::new(2, 0, 0.1.into(), 0.2.into());
/// assert_eq!(operation.remap_modes(&mode_mapping_test).unwrap(), operation_after_remapping);
/// ```
///
pub trait SubstituteModes
where
    Self: Sized,
{
    /// Remaps the bosonic modes in clone of the operation.
    fn remap_modes(&self, mapping: &HashMap<usize, usize>) -> Result<Self, RoqoqoError>;
}

/// Trait for Operations acting with a unitary gate on a set of bosonic modes.
///
/// # Example
/// ```
/// use roqoqo::operations::{OperateModeGate, Squeezing};
///
/// let _op = Squeezing::new(0, 0.1.into(), 0.0.into());
/// ```
///
pub trait OperateModeGate:
    Operate + InvolveModes + SubstituteModes + Clone + PartialEq + SupportedVersion
{
}

/// Trait for bosonic operations acting on exactly one bosonic modes.
///
/// # Example
/// ```
/// use roqoqo::operations::{OperateSingleMode, PhotonDetection};
///
/// let op = PhotonDetection::new(0, "ro".into(), 0);
/// assert_eq!(op.mode(), &0_usize);
/// ```
///
pub trait OperateSingleMode: Operate + InvolveModes + SubstituteModes + Clone + PartialEq {
    /// Returns `mode` the bosonic Operation acts on.
    fn mode(&self) -> &usize;
}

/// Trait for Operations acting on exactly two bosonic modes.
///
/// # Example
/// ```
/// use roqoqo::operations::{OperateTwoMode, BeamSplitter};
///
/// let op = BeamSplitter::new(2, 3, 1.0.into(), 0.1.into());
/// assert_eq!(op.mode_0(), &2_usize);
/// assert_eq!(op.mode_1(), &3_usize);
/// ```
///
pub trait OperateTwoMode: Operate + InvolveModes + SubstituteModes + Clone + PartialEq {
    /// Returns `mode_0` bosonic mode of two bosonic mode Operation.
    fn mode_0(&self) -> &usize;
    /// Returns `mode_1` bosonic mode of two bosonic mode Operation.
    fn mode_1(&self) -> &usize;
}

/// Trait for unitary operations acting on exactly one bosonic mode.
///
/// # Example
/// ```
/// use roqoqo::operations::{OperateSingleModeGate, PhaseShift};
///
/// let _op = PhaseShift::new(0, 0.1.into());
/// ```
///
pub trait OperateSingleModeGate:
    Operate
    + OperateModeGate
    + InvolveModes
    + SubstituteModes
    + OperateSingleMode
    + Clone
    + PartialEq
    + SupportedVersion
    + std::fmt::Debug
{
}

/// Trait for all Operations operating on or affecting exactly two bosonic modes.
///
/// # Example
/// ```
/// use roqoqo::operations::{OperateTwoModeGate, BeamSplitter};
///
/// let _op = BeamSplitter::new(0, 1, 0.2.into(), 0.5.into());
/// ```
///
pub trait OperateTwoModeGate:
    Operate
    + OperateModeGate
    + OperateTwoMode
    + InvolveModes
    + SubstituteModes
    + Clone
    + PartialEq
    + SupportedVersion
{
}