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
use std::{
    fmt::Display,
    iter::Sum,
    ops::{Add, AddAssign, Index, IndexMut, Mul, MulAssign, Sub, SubAssign},
};

use num_complex::{Complex64, ComplexFloat};
use tabled::{
    builder::Builder,
    settings::{Margin, Style},
};

use crate::Vector;

#[derive(Debug, Clone)]
pub struct Matrix<const M: usize, const N: usize> {
    data: [[Complex64; N]; M],
}

impl<const M: usize, const N: usize> Index<[usize; 2]> for Matrix<M, N> {
    type Output = Complex64;

    fn index(&self, [i, j]: [usize; 2]) -> &Self::Output {
        &self.data[i][j]
    }
}

impl<const M: usize, const N: usize> IndexMut<[usize; 2]> for Matrix<M, N> {
    fn index_mut(&mut self, index: [usize; 2]) -> &mut Self::Output {
        &mut self.data[index[0]][index[1]]
    }
}

impl<const M: usize, const N: usize> AddAssign for Matrix<M, N> {
    fn add_assign(&mut self, rhs: Self) {
        self.iter_mut()
            .zip(rhs.iter())
            .for_each(|(left, right)| *left += right);
    }
}

impl<const M: usize, const N: usize> Add for Matrix<M, N> {
    type Output = Matrix<M, N>;

    fn add(self, rhs: Self) -> Self::Output {
        let mut result = self.clone();
        result += rhs;
        result
    }
}

impl<const M: usize, const N: usize> Sum for Matrix<M, N> {
    fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
        iter.reduce(|acc, x| acc + x).unwrap_or(Matrix::ZEROS)
    }
}

impl<const M: usize, const N: usize> SubAssign for Matrix<M, N> {
    fn sub_assign(&mut self, rhs: Self) {
        self.iter_mut()
            .zip(rhs.iter())
            .for_each(|(left, right)| *left -= right);
    }
}

impl<const M: usize, const N: usize> Sub for Matrix<M, N> {
    type Output = Matrix<M, N>;

    fn sub(self, rhs: Self) -> Self::Output {
        let mut result = self.clone();
        result -= rhs;
        result
    }
}

impl<const M: usize, const N: usize, const P: usize> Mul<Matrix<N, P>> for Matrix<M, N> {
    type Output = Matrix<M, P>;

    fn mul(self, rhs: Matrix<N, P>) -> Self::Output {
        let mut result = Matrix::ZEROS;

        for i in 0..M {
            for j in 0..P {
                for k in 0..N {
                    result[[i, j]] += self[[i, k]] * rhs[[k, j]];
                }
            }
        }

        result
    }
}

impl<const M: usize, const N: usize> MulAssign<Complex64> for Matrix<M, N> {
    fn mul_assign(&mut self, rhs: Complex64) {
        self.iter_mut().for_each(|x| *x *= rhs);
    }
}

impl<const M: usize, const N: usize> Mul<Complex64> for Matrix<M, N> {
    type Output = Matrix<M, N>;

    fn mul(self, rhs: Complex64) -> Self::Output {
        let mut result = self.clone();
        result *= rhs;
        result
    }
}

impl<const M: usize, const N: usize> Mul<Matrix<M, N>> for Complex64 {
    type Output = Matrix<M, N>;

    fn mul(self, rhs: Matrix<M, N>) -> Self::Output {
        rhs * self
    }
}

impl<const M: usize, const N: usize> PartialEq for Matrix<M, N> {
    fn eq(&self, other: &Self) -> bool {
        let epsilon = self.epsilon();
        self.iter()
            .zip(other.iter())
            .all(|(a, b)| (a - b).abs() < epsilon)
    }
}

impl<const M: usize, const N: usize> Matrix<M, N> {
    #[inline]
    pub const fn new(data: [[Complex64; N]; M]) -> Self {
        Self { data }
    }

    pub fn from_column_vectors(columns: [Vector<M>; N]) -> Self {
        Matrix::<N, M>::new(columns.map(|column| column.transpose().data[0])).transpose()
    }

    pub fn to_column_vectors(self) -> [Vector<M>; N] {
        self.transpose()
            .data
            .map(|row| Matrix::new([row]).transpose())
    }

    pub const ZEROS: Self = Matrix::new([[Complex64::ZERO; N]; M]);

    pub fn iter(&self) -> impl Iterator<Item = &Complex64> {
        self.data.iter().flatten()
    }

    pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut Complex64> {
        self.data.iter_mut().flatten()
    }

    pub fn epsilon(&self) -> f64 {
        self.iter()
            .map(|x| x.abs())
            .max_by(|a, b| a.total_cmp(b))
            .unwrap()
            * self.data.len().max(self.data[0].len()) as f64
            * f64::EPSILON
    }

    pub fn swap_row(&mut self, i: usize, j: usize) {
        self.data.swap(i, j);
    }

    pub fn multiply_row_by_scalar(&mut self, i: usize, scalar: Complex64) {
        self.data[i].iter_mut().for_each(|entry| *entry *= scalar);
    }

    pub fn add_row_with_scalar(&mut self, i: usize, j: usize, scalar: Complex64) {
        for k in 0..N {
            let value = scalar * self[[i, k]];
            self[[j, k]] += value;
        }
    }

    pub fn transpose(&self) -> Matrix<N, M> {
        let mut result = Matrix::ZEROS;

        for i in 0..M {
            for j in 0..N {
                result[[j, i]] = self[[i, j]];
            }
        }

        result
    }

    pub fn gaussian_elimination(self) -> (Matrix<M, N>, Matrix<M, M>, usize) {
        let mut row_echelon_matrix = self;
        let mut operation_matrix = Matrix::<M, M>::identity();
        let mut row_swap_count = 0;
        let size = M.min(N);

        for i in 0..size {
            let max_entry_index = (i..size)
                .max_by(|&j, &k| {
                    row_echelon_matrix[[j, i]]
                        .abs()
                        .total_cmp(&row_echelon_matrix[[k, i]].abs())
                })
                .unwrap();
            if row_echelon_matrix[[max_entry_index, i]] == Complex64::ZERO {
                continue;
            }
            if max_entry_index != i {
                row_echelon_matrix.swap_row(i, max_entry_index);
                operation_matrix.swap_row(i, max_entry_index);
                row_swap_count += 1;
            }

            for j in i + 1..size {
                let scalar = -row_echelon_matrix[[j, i]] / row_echelon_matrix[[i, i]];
                row_echelon_matrix.add_row_with_scalar(i, j, scalar);
                operation_matrix.add_row_with_scalar(i, j, scalar);
            }
        }

        (row_echelon_matrix, operation_matrix, row_swap_count)
    }

    pub fn rank(&self) -> usize {
        let epsilon = self.epsilon();
        let (row_echelon_matrix, _, _) = self.clone().gaussian_elimination();
        row_echelon_matrix
            .data
            .iter()
            .map(|row| row.iter().any(|&entry| entry.abs() >= epsilon))
            .filter(|&x| x)
            .count()
    }
}

impl<const M: usize> Matrix<M, M> {
    pub fn diagonal(data: [Complex64; M]) -> Self {
        let mut result = Matrix::ZEROS;
        for i in 0..M {
            result[[i, i]] = data[i];
        }

        result
    }

    pub fn identity() -> Self {
        Self::diagonal([Complex64::ONE; M])
    }

    pub fn determinant(&self) -> Complex64 {
        let (row_echelon_matrix, _, row_swap_count) = self.clone().gaussian_elimination();
        let sign = if row_swap_count % 2 == 0 { 1. } else { -1. };
        sign * (0..M)
            .map(|i| row_echelon_matrix[[i, i]])
            .product::<Complex64>()
    }

    pub fn gauss_jordan_elimination(self) -> (Matrix<M, M>, Matrix<M, M>) {
        let epsilon = self.epsilon();
        let (mut reduced_row_echelon_matrix, mut operation_matrix, _) = self.gaussian_elimination();

        for i in 1..M {
            if reduced_row_echelon_matrix[[i, i]].abs() <= epsilon {
                continue;
            }
            for j in 0..=i - 1 {
                let scalar =
                    -reduced_row_echelon_matrix[[j, i]] / reduced_row_echelon_matrix[[i, i]];

                reduced_row_echelon_matrix.add_row_with_scalar(i, j, scalar);
                operation_matrix.add_row_with_scalar(i, j, scalar);
            }
        }

        for i in 0..M {
            if reduced_row_echelon_matrix[[i, i]].abs() <= epsilon {
                continue;
            }

            let scalar = 1. / reduced_row_echelon_matrix[[i, i]];
            reduced_row_echelon_matrix.multiply_row_by_scalar(i, scalar);
            operation_matrix.multiply_row_by_scalar(i, scalar);
        }

        (reduced_row_echelon_matrix, operation_matrix)
    }

    pub fn inverse(self) -> Option<Matrix<M, M>> {
        let (reduced_row_echelon_matrix, operation_matrix) = self.gauss_jordan_elimination();
        if reduced_row_echelon_matrix == Matrix::<M, M>::identity() {
            Some(operation_matrix)
        } else {
            None
        }
    }

    pub fn qr_decomposition(self) -> (Matrix<M, M>, Matrix<M, M>) {
        let q = Matrix::from_column_vectors(Vector::<M>::gram_schimidt_process(
            self.clone().to_column_vectors(),
        ));
        let r = q.transpose() * self;

        (q, r)
    }

    pub fn schur_form(self, iterations: usize) -> Matrix<M, M> {
        let mut result = self;

        for _ in 0..iterations {
            let (q, r) = result.qr_decomposition();
            result = r * q;
        }

        result
    }

    pub fn eigenvalues(&self, iterations: usize) -> [Complex64; M] {
        let schur_form = self.clone().schur_form(iterations);
        let mut eigenvalues: [Complex64; M] = (0..M)
            .map(|i| schur_form[[i, i]])
            .collect::<Vec<_>>()
            .try_into()
            .unwrap();

        eigenvalues.sort_by(|a, b| b.re().total_cmp(&a.abs()));

        eigenvalues
    }

    pub fn eigenvectors(&self, iterations: usize) -> [Vector<M>; M] {
        (0..iterations)
            .fold(self.clone().qr_decomposition().0, |q, _| {
                (self.clone() * q).qr_decomposition().0
            })
            .to_column_vectors()
    }
}

impl<const M: usize, const N: usize> Display for Matrix<M, N> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut table_builder = Builder::default();
        for i in 0..M {
            table_builder.push_record(self.data[i].iter().map(|x| x.to_string()));
        }
        let mut table = table_builder.build();
        table.with(Style::blank());
        table.with(Margin::new(4, 0, 0, 0));

        write!(f, "[\n{}\n]", table)
    }
}