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
/*
* Copyright (c) 2023 Andrew Rowan Barlow. Licensed under the EUPL-1.2
* or later. You may obtain a copy of the licence at
* https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12. A copy
* of the EUPL-1.2 licence in English is given in LICENCE.txt which is
* found in the root directory of this repository.
*
* Author: Andrew Rowan Barlow <a.barlow.dev@gmail.com>
*/

//! Generic complex numbers.
//!
//! Simple implementation with operations that are needed for the quantum computer. Quantr will
//! mostly use `Complex<f64>`, so additional functionality is added for this type, such as square
//! roots and multiplication with `f64`.

use std::fmt;
use std::fmt::{Debug, Formatter};
use std::ops::{Add, Mul, Sub};

/// A square root trait, that is only implemented for `f32` and `f64` as Sqrt is not a closed
/// operation for int, uint, etc. This is needed for the absolute value of a complex number.
pub trait Sqr {
    fn square_root(self) -> Self;
}

impl Sqr for f32 {
    fn square_root(self) -> Self {
        self.sqrt()
    }
}

impl Sqr for f64 {
    fn square_root(self) -> Self {
        self.sqrt()
    }
}

/// Generic complex number for the quantum computer. Will mostly use `f64`.
#[derive(Debug, PartialEq, Copy, Clone)]
pub struct Complex<T> {
    pub real: T,
    pub imaginary: T,
}

/// Addition of two generic complex numbers.
impl<T: Add<Output = T>> Add for Complex<T> {
    type Output = Self;

    fn add(self, rhs: Self) -> Self::Output {
        Complex {
            real: self.real.add(rhs.real),
            imaginary: self.imaginary.add(rhs.imaginary),
        }
    }
}

/// Subtracts two generic complex numbers.
impl<T: Sub<Output = T>> Sub for Complex<T> {
    type Output = Self;

    fn sub(self, rhs: Self) -> Self::Output {
        Complex {
            real: self.real.sub(rhs.real),
            imaginary: self.imaginary.sub(rhs.imaginary),
        }
    }
}

/// Multiplying two generic complex numbers.
impl<T: Mul<Output = T> + Add<Output = T> + Sub<Output = T> + Copy> Mul for Complex<T> {
    type Output = Self;

    fn mul(self, rhs: Self) -> Self::Output {
        Complex {
            real: self
                .real
                .mul(rhs.real)
                .sub(self.imaginary.mul(rhs.imaginary)),
            imaginary: self
                .real
                .mul(rhs.imaginary)
                .add(self.imaginary.mul(rhs.real)),
        }
    }
}

/// Multiplication of `f64 * Complex<f64>`.
impl Mul<f64> for Complex<f64> {
    type Output = Self;

    fn mul(self, rhs: f64) -> Self::Output {
        Complex {
            real: self.real.mul(rhs),
            imaginary: self.imaginary.mul(rhs),
        }
    }
}

/// Multiplication `Complex<f64> * f64`.
impl Mul<Complex<f64>> for f64 {
    type Output = Complex<f64>;

    fn mul(self, rhs: Complex<f64>) -> Self::Output {
        Complex {
            real: rhs.real.mul(self),
            imaginary: rhs.imaginary.mul(self),
        }
    }
}

impl<T: Add<Output = T> + Mul<Output = T> + Copy> Complex<T> {
    /// Absolute square of a complex number, that is `|z|^2 = a^2+b^2`
    /// where `z = a + bi`.
    pub fn abs_square(self) -> T {
        self.real
            .mul(self.real)
            .add(self.imaginary.mul(self.imaginary))
    }
}

impl<T: Add<Output = T> + Mul<Output = T> + Sqr + Copy> Complex<T> {
    /// Absolute value of a complex number, that is
    /// `|z| = Sqrt(a^2+b^2)` where `z = a + bi`.
    pub fn abs(&self) -> T {
        self.abs_square().square_root()
    }
}

impl<T: fmt::Display> fmt::Display for Complex<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{} + {}i", self.real, self.imaginary)
    }
}

/// Shortcut for `complex!(0f64, 0f64)`.
#[macro_export]
macro_rules! complex_zero {
    () => {
        Complex::<f64> {
            real: 0f64,
            imaginary: 0f64,
        }
    };
}

/// Usage: `complex!(real: f64, imaginary: f64) -> Complex<f64>`
/// A quick way to define a f64 complex number.
#[macro_export]
macro_rules! complex {
    ($r:expr, $i:expr) => {
        Complex::<f64> {
            real: $r,
            imaginary: $i,
        }
    };
}

/// Usage: `complex_Re_array!(input: [f64; n]) -> [Complex<f64>; n]`
/// Returns an array of complex number with zero imaginary part, and reals set by `input`.
#[macro_export]
macro_rules! complex_Re_array {
    ( $( $x:expr ),*  ) => {
        [
        $(
            Complex::<f64> {
                real: $x,
                imaginary: 0f64
            }
        ),*
        ]
    };
}

/// Usage: `complex_Im_array!(input: [f64; n]) -> [Complex<f64>; n]`
/// Returns an array of complex number with zero real part, and imaginary set by `input`.
#[macro_export]
macro_rules! complex_Im_array {
    ( $( $x:expr ),*  ) => {
        [
        $(
            Complex::<f64> {
                real: 0f64,
                imaginary: $x
            }
        ),*
        ]
    };
}

/// Usage: `complex_Re_vec!(input: [f64; n]) -> Vec<Complex<f64>>`
/// Returns a vector of complex number with zero imaginary part, and reals set by `input`.
#[macro_export]
macro_rules! complex_Re_vec {
    ( $( $x:expr ),*  ) => {
        {
            let mut temp_vec: Vec<Complex<f64>> = Vec::new();
            $(
                temp_vec.push(
                    Complex::<f64> {
                        real: $x,
                        imaginary: 0f64
                    }
                );
            )*
            temp_vec
        }
    };
}

/// Usage: `complex_Im_vec!(input: [f64; n]) -> Vec<Complex<f64>>`
/// Returns a vector of complex numbers with zero real part, and imaginaries set by `input`.
#[macro_export]
macro_rules! complex_Im_vec {
    ( $( $x:expr ),*  ) => {
        {
            let mut temp_vec: Vec<Complex<f64>> = Vec::new();
            $(
                temp_vec.push(
                    Complex::<f64> {
                        real: 0f64,
                        imaginary: $x,
                    }
                );
            )*
            temp_vec
        }
    };
}

/// Usage: `complex_Re!(real: f64) -> Complex<f64>`
/// A quick way to define a real f64; the imaginary part is set to zero.
#[macro_export]
macro_rules! complex_Re {
    ($r:expr) => {
        Complex::<f64> {
            real: $r,
            imaginary: 0f64,
        }
    };
}

/// Usage: `complex_Im!(imaginary: f64) -> Complex<f64>`
/// A quick way to define an imaginary f64; the real part is set to zero.
#[macro_export]
macro_rules! complex_Im {
    ($i:expr) => {
        Complex::<f64> {
            real: 0f64,
            imaginary: $i,
        }
    };
}

#[rustfmt::skip]
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn complex_imaginary_and_imaginary() {
        let num_one = Complex::<i8>{real: 0, imaginary: 9};
        let num_two = Complex::<i8>{real: 0, imaginary: 2};

        assert_eq!(num_one.mul(num_two), Complex::<i8>{real: -18, imaginary: 0})
    }

    #[test]
    fn complex_imaginary_and_real() {
        let num_one = Complex::<i8>{real: 0, imaginary: -9};
        let num_two = Complex::<i8>{real: 2, imaginary: 0};

        assert_eq!(num_one.mul(num_two), Complex::<i8>{real: 0, imaginary: -18})
    }

    #[test]
    fn complex_multiply() {
        let num_one = Complex::<i8>{real: 2, imaginary: 9};
        let num_two = Complex::<i8>{real: 7, imaginary: 3};

        assert_eq!(num_one.mul(num_two), Complex::<i8>{real: -13, imaginary: 69})
    }

    #[test]
    fn complex_add() {
        let num_one = Complex::<i8>{real: 2, imaginary: 9};
        let num_two = Complex::<i8>{real: 7, imaginary: -3};

        assert_eq!(num_one.add(num_two), Complex::<i8>{real: 9, imaginary: 6})
    }

    #[test]
    fn complex_sub() {
        let num_one = Complex::<i8>{real: 2, imaginary: 9};
        let num_two = Complex::<i8>{real: 7, imaginary: -3};

        assert_eq!(num_one.sub(num_two), Complex::<i8>{real: -5, imaginary: 12})
    }

    #[test]
    fn complex_abs() {
        let num_one = Complex::<f32>{real: 2f32, imaginary: 9f32};

        assert_eq!(num_one.abs_square(), 85f32)
    }

    #[test]
    fn complex_abs_square_root() {
        let num_one = Complex::<f32>{real: 2f32, imaginary: 9f32};

        assert_eq!(num_one.abs(), 85f32.sqrt())
    }

    #[test]
    fn scale_a_complex_number_with_f64_rhs() {
        let num_one = Complex::<f64>{real: 2f64, imaginary: 9f64};

        assert_eq!(5f64 * num_one, Complex::<f64>{real: 10f64, imaginary: 45f64})
    }

    #[test]
    fn scale_a_complex_number_with_f64_lhs() {
        let num_one = Complex::<f64>{real: 2f64, imaginary: 9f64};

        assert_eq!(num_one * 5f64, Complex::<f64>{real: 10f64, imaginary: 45f64})
    }
}