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
use crate::polynomials::Pol;
use crate::{F2D, F3D};
use std::fmt::Display;

#[derive(Debug, PartialEq)]
/// 2D Vector
pub struct Vec2<T> {
    /// x component
    pub x: T,
    /// y component
    pub y: T,
}

#[derive(Debug, PartialEq)]
/// 3D Vector
pub struct Vec3<T> {
    /// x component
    pub x: T,
    /// y component
    pub y: T,
    /// z component
    pub z: T,
}

#[derive(Debug, PartialEq)]
/// Matrix
pub struct Matrix<T> {
    mat: Vec<T>,
    n_col: usize,
    n_row: usize,
}

impl<T> Matrix<T> {
    /// Creates new matrix from vector
    pub fn new(mat: Vec<T>, n_row: usize, n_col: usize) -> Self {
        Self { mat, n_row, n_col }
    }

    /// Get the element from the i-th row and j-th column (starts from 1)
    pub fn get(&self, row: usize, col: usize) -> &T {
        &self.mat[(row - 1) * self.n_row + col - 1]
    }
}

impl<T: std::ops::AddAssign<T> + Clone> Matrix<T> {
    /// Calculate the trace of the matrix
    pub fn trace(&self) -> T {
        let mut result = self.get(1, 1).clone();

        for i in 2..=self.n_row {
            result += (*self.get(i, i)).clone();
        }

        result
    }
}

impl<T: PartialEq> Matrix<T> {
    /// Check if the matrix is symmetric
    pub fn is_symmetric(&self) -> bool {
        for i in 1..=self.n_row {
            for j in (i + 1)..=self.n_col {
                if self.get(i, j) != self.get(j, i) {
                    return false;
                }
            }
        }

        true
    }
}

impl Matrix<f64> {
    /// Calculate the characteristic polynomial
    pub fn pol(&self) -> Pol {
        if self.n_col != self.n_row {
            panic!("No pol in non-square matrix");
        }

        let mut mat = Vec::with_capacity(self.mat.len());
        let mut next_diagonal = 0;

        for (i, el) in self.mat.iter().enumerate() {
            if i == next_diagonal {
                mat.push(Pol::new(vec![*el, -1.]));
                next_diagonal += 1 + self.n_col;
            } else {
                mat.push(Pol::new(vec![*el]));
            }
        }

        let mat_minus_identity = Matrix {
            mat,
            n_row: self.n_row,
            n_col: self.n_col,
        };

        mat_minus_identity.determinant()
    }
}

impl Matrix<Pol> {
    /// Computes determinant (2x2 and 3x3)
    pub fn determinant(&self) -> Pol {
        if self.n_row != self.n_col {
            panic!("Cant' calculate determinant of non-square matrix")
        }

        if self.n_row == 2 {
            (self.mat[0].clone() * self.mat[3].clone())
                - (self.mat[1].clone() * self.mat[2].clone())
        } else if self.n_row == 3 {
            self.get(1, 1) * self.get(2, 2) * self.get(3, 3)
                + self.get(1, 2) * self.get(2, 3) * self.get(3, 1)
                + self.get(1, 3) * self.get(2, 1) * self.get(3, 2)
                - self.get(3, 1) * self.get(2, 2) * self.get(1, 3)
                - self.get(3, 2) * self.get(2, 3) * self.get(1, 1)
                - self.get(3, 3) * self.get(2, 1) * self.get(1, 2)
        } else {
            panic!("Matrix size not supported")
        }
    }
}

impl Matrix<F2D> {
    /// Eval
    pub fn eval(&self, x: f64, y: f64) -> Matrix<f64> {
        Matrix {
            mat: self.mat.iter().map(|func| func.eval(x, y)).collect(),
            n_col: self.n_col,
            n_row: self.n_row,
        }
    }
}
impl Matrix<F3D> {
    /// Eval
    pub fn eval(&self, x: f64, y: f64, z: f64) -> Matrix<f64> {
        Matrix {
            mat: self.mat.iter().map(|func| func.eval(x, y, z)).collect(),
            n_col: self.n_col,
            n_row: self.n_row,
        }
    }
}

impl<T: Display> Display for Matrix<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut result = String::new();

        for (i, el) in self.mat.iter().enumerate() {
            if i % self.n_col == 0 && i != 0 {
                result += "|\n";
            }

            result += &format!("|{:^width$}", el.to_string(), width = 20);
        }

        write!(f, "{}|", result)
    }
}

impl<T: Display> Display for Vec2<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "({}, {})", self.x, self.y)
    }
}

impl<T: Display> Display for Vec3<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "({}, {}, {})", self.x, self.y, self.z)
    }
}