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
//! 2d matrices.

use std::ops::Add;
use std::ops::Mul;
use std::ops::Sub;

use crate::v2d;
use crate::Integer;
use crate::Matrix;
use crate::MatrixOps;
use crate::Vec2d;

const DIM: usize = 2;

/// A 2d discrete matrix.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
pub struct Matrix2d<S: Integer> {
    a: [[S; DIM]; DIM],
}

impl<S: Integer> Matrix2d<S> {
    /// Creates a new 2d matrix from its values by rows.
    pub fn new(a: S, b: S, c: S, d: S) -> Matrix2d<S> {
        let r0 = [a, b];
        let r1 = [c, d];
        Matrix2d { a: [r0, r1] }
    }
    /// Creates a new 2d matrix from a function.
    ///
    /// # Example
    ///
    /// ```
    /// # use core::convert::TryFrom;
    /// # use lowdim::Matrix2d;
    /// let m = Matrix2d::with(|i, j| i64::try_from(3 * i + j).unwrap());
    /// assert_eq!(Matrix2d::new(0, 1, 3, 4), m);
    /// ```
    pub fn with<F>(f: F) -> Matrix2d<S>
    where
        F: Fn(usize, usize) -> S,
    {
        let r0 = [f(0, 0), f(0, 1)];
        let r1 = [f(1, 0), f(1, 1)];
        Matrix2d { a: [r0, r1] }
    }
    /// Returns a row vector of a matrix.
    pub fn row_vec(&self, i: usize) -> Vec2d<S> {
        v2d(self.a[i][0], self.a[i][1])
    }
    /// Returns a column vector of a matrix.
    pub fn col_vec(&self, j: usize) -> Vec2d<S> {
        v2d(self.a[0][j], self.a[1][j])
    }
    /// Returns the diagonal vector of a matrix.
    pub fn diag_vec(&self) -> Vec2d<S> {
        v2d(self.a[0][0], self.a[1][1])
    }
    /// Returns the determinant of a matrix.
    pub fn det(&self) -> S
    where
        S: Copy + Sub<Output = S> + Mul<Output = S>,
    {
        self.a[0][0] * self.a[1][1] - self.a[0][1] * self.a[1][0]
    }
    /// Creates a matrix for a left rotation by a right angle.
    pub fn rotate_left_90() -> Matrix2d<S> {
        Matrix2d::new(S::zero(), -S::one(), S::one(), S::zero())
    }
    /// Creates a matrix for a rotation by 180 degrees.
    pub fn rotate_180() -> Matrix2d<S> {
        Matrix2d::new(-S::one(), S::zero(), S::zero(), -S::one())
    }
    /// Creates a matrix for a right rotation by a right angle.
    pub fn rotate_right_90() -> Matrix2d<S> {
        Matrix2d::new(S::zero(), S::one(), -S::one(), S::zero())
    }
    /// Creates a matrix for a reflection on the x-axis.
    pub fn reflect_x_axis() -> Matrix2d<S> {
        Matrix2d::new(S::one(), S::zero(), S::zero(), -S::one())
    }
    /// Creates a matrix for a reflection on the y-axis.
    pub fn reflect_y_axis() -> Matrix2d<S> {
        Matrix2d::new(-S::one(), S::zero(), S::zero(), S::one())
    }
    /// Creates a matrix for a reflection on the x=y diagonal.
    pub fn reflect_diagonal() -> Matrix2d<S> {
        Matrix2d::new(S::zero(), S::one(), S::one(), S::zero())
    }
    /// Creates a matrix for a reflection on the -x=y anti-diagonal.
    pub fn reflect_anti_diagonal() -> Matrix2d<S> {
        Matrix2d::new(S::zero(), -S::one(), -S::one(), S::zero())
    }
}

impl<S: Integer> MatrixOps<S, Matrix2d<S>> for Matrix2d<S> {}
impl<'a, S: Integer> MatrixOps<S, &'a Matrix2d<S>> for Matrix2d<S> {}
impl<'a, S: Integer> MatrixOps<S, Matrix2d<S>, Matrix2d<S>> for &'a Matrix2d<S> {}
impl<'a, S: Integer> MatrixOps<S, &'a Matrix2d<S>, Matrix2d<S>> for &'a Matrix2d<S> {}

impl<S: Integer> MatrixOps<S, Vec2d<S>, Vec2d<S>> for Matrix2d<S> {}
impl<'a, S: Integer> MatrixOps<S, &'a Vec2d<S>, Vec2d<S>> for Matrix2d<S> {}
impl<'a, S: Integer> MatrixOps<S, Vec2d<S>, Vec2d<S>> for &'a Matrix2d<S> {}
impl<'a, S: Integer> MatrixOps<S, &'a Vec2d<S>, Vec2d<S>> for &'a Matrix2d<S> {}

impl<S: Integer> Matrix<S> for Matrix2d<S> {
    type V = Vec2d<S>;

    fn with<F>(f: F) -> Self
    where
        F: Fn(usize, usize) -> S,
    {
        Self::new(f(0, 0), f(0, 1), f(1, 0), f(1, 1))
    }
}

impl<S: Integer> Mul<Vec2d<S>> for Matrix2d<S>
where
    S: Copy + Add<Output = S> + Mul<Output = S>,
{
    type Output = Vec2d<S>;

    fn mul(self, other: Vec2d<S>) -> Vec2d<S> {
        let x = self.row_vec(0) * other;
        let y = self.row_vec(1) * other;
        v2d(x, y)
    }
}

impl<'a, S: Integer> Mul<&'a Vec2d<S>> for Matrix2d<S>
where
    S: Copy + Add<Output = S> + Mul<Output = S>,
{
    type Output = Vec2d<S>;

    fn mul(self, other: &'a Vec2d<S>) -> Vec2d<S> {
        let x = self.row_vec(0) * other;
        let y = self.row_vec(1) * other;
        v2d(x, y)
    }
}

impl<'a, S: Integer> Mul<Vec2d<S>> for &'a Matrix2d<S>
where
    S: Copy + Add<Output = S> + Mul<Output = S>,
{
    type Output = Vec2d<S>;

    fn mul(self, other: Vec2d<S>) -> Vec2d<S> {
        let x = self.row_vec(0) * other;
        let y = self.row_vec(1) * other;
        v2d(x, y)
    }
}

impl<'a, S: Integer> Mul<&'a Vec2d<S>> for &'a Matrix2d<S>
where
    S: Copy + Add<Output = S> + Mul<Output = S>,
{
    type Output = Vec2d<S>;

    fn mul(self, other: &'a Vec2d<S>) -> Vec2d<S> {
        let x = self.row_vec(0) * other;
        let y = self.row_vec(1) * other;
        v2d(x, y)
    }
}

impl<S: Integer> Mul<Matrix2d<S>> for Matrix2d<S>
where
    S: Copy + Add<Output = S> + Mul<Output = S>,
{
    type Output = Matrix2d<S>;

    fn mul(self, other: Matrix2d<S>) -> Matrix2d<S> {
        Matrix2d::with(|i, j| self.row_vec(i) * other.col_vec(j))
    }
}

impl<'a, S: Integer> Mul<&'a Matrix2d<S>> for Matrix2d<S>
where
    S: Copy + Add<Output = S> + Mul<Output = S>,
{
    type Output = Matrix2d<S>;

    fn mul(self, other: &'a Matrix2d<S>) -> Matrix2d<S> {
        Matrix2d::with(|i, j| self.row_vec(i) * other.col_vec(j))
    }
}

impl<'a, S: Integer> Mul<Matrix2d<S>> for &'a Matrix2d<S>
where
    S: Copy + Add<Output = S> + Mul<Output = S>,
{
    type Output = Matrix2d<S>;

    fn mul(self, other: Matrix2d<S>) -> Matrix2d<S> {
        Matrix2d::with(|i, j| self.row_vec(i) * other.col_vec(j))
    }
}

impl<'a, S: Integer> Mul<&'a Matrix2d<S>> for &'a Matrix2d<S>
where
    S: Copy + Add<Output = S> + Mul<Output = S>,
{
    type Output = Matrix2d<S>;

    fn mul(self, other: &'a Matrix2d<S>) -> Matrix2d<S> {
        Matrix2d::with(|i, j| self.row_vec(i) * other.col_vec(j))
    }
}

#[cfg(test)]
mod tests {
    use core::convert::TryFrom;

    use crate::v2d;
    use crate::Matrix;
    use crate::Matrix2d;

    #[test]
    fn test_with() {
        let m = Matrix2d::with(|i, j| i64::try_from(3 * i + j).unwrap());
        assert_eq!(Matrix2d::new(0, 1, 3, 4), m);
    }

    #[test]
    fn test_zero() {
        let m = Matrix2d::zero();
        assert_eq!(Matrix2d::new(0, 0, 0, 0), m);
    }

    #[test]
    fn test_unit() {
        let m = Matrix2d::unit();
        assert_eq!(Matrix2d::new(1, 0, 0, 1), m);
    }

    #[test]
    fn test_row_vec() {
        let m = Matrix2d::new(1, 2, 3, 4);
        assert_eq!(v2d(1, 2), m.row_vec(0));
    }

    #[test]
    fn test_col_vec() {
        let m = Matrix2d::new(1, 2, 3, 4);
        assert_eq!(v2d(2, 4), m.col_vec(1));
    }

    #[test]
    fn test_diag_vec() {
        let m = Matrix2d::with(|i, j| i64::try_from(3 * i + j).unwrap());
        assert_eq!(v2d(0, 4), m.diag_vec());
    }

    #[test]
    fn test_det() {
        // Test a diagonal matrix and all its row permutations,
        // in order to cover all terms of the determinant formula.

        // The determinant of a diagonal matrix is the product of its diagonal elements
        // (all other elements are zero in a diagonal matrix).
        let m = Matrix2d::new(2, 0, 0, 3);
        assert_eq!(6, m.det());

        // Transpositions of the rows change the sign.
        let m = Matrix2d::new(0, 3, 2, 0);
        assert_eq!(-6, m.det());
    }

    #[test]
    fn test_rotate_left_90() {
        let vx = v2d(1, 0);
        let vy = v2d(0, 1);
        let m = Matrix2d::rotate_left_90();
        assert_eq!(vy, m * vx);
        assert_eq!(-vx, m * vy);
    }

    #[test]
    fn test_rotate_right_90() {
        let vx = v2d(1, 0);
        let vy = v2d(0, 1);
        let m = Matrix2d::rotate_right_90();
        assert_eq!(-vy, m * vx);
        assert_eq!(vx, m * vy);
    }

    #[test]
    fn test_mul_mv() {
        let m = Matrix2d::new(1, 3, 7, 15);
        let v = v2d(2, 3);
        assert_eq!(v2d(11, 59), m * v);
        assert_eq!(v2d(11, 59), m * &v);
        assert_eq!(v2d(11, 59), &m * v);
        assert_eq!(v2d(11, 59), &m * &v);
    }

    #[test]
    fn test_mul_mm() {
        let m0 = Matrix2d::new(1, 3, 7, 15);
        let m1 = Matrix2d::new(1, 2, 3, 4);
        assert_eq!(Matrix2d::new(10, 14, 52, 74), m0 * m1);
        assert_eq!(Matrix2d::new(10, 14, 52, 74), m0 * &m1);
        assert_eq!(Matrix2d::new(10, 14, 52, 74), &m0 * m1);
        assert_eq!(Matrix2d::new(10, 14, 52, 74), &m0 * &m1);
    }
}