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
/*
 * Copyright (c) 2018-2020 Thomas Kramer.
 *
 * This file is part of LibrEDA 
 * (see https://codeberg.org/libreda/iron-shapes).
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

//! Data structures and functions for 2x2 matrices.

use crate::CoordinateType;

use crate::vector::Vector;

/// A 2x2 matrix of the form:
/// ```txt
/// [[ m11, m12 ],
///  [ m21, m22 ]]
/// ```
#[derive(Clone, Hash, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Matrix2d<T: CoordinateType> {
    /// m11
    pub(crate) m11: T,
    /// m12
    pub(crate) m12: T,
    /// m21
    pub(crate) m21: T,
    /// m22
    pub(crate) m22: T,
}

impl<T> Matrix2d<T>
    where T: CoordinateType
{
    /// Create a new 2x2 matrix with entries of the form:
    /// ```txt
    /// [[ m11, m12 ],
    ///  [ m21, m22 ]]
    /// ```
    pub fn new(m11: T, m12: T, m21: T, m22: T) -> Self {
        Matrix2d {
            m11,
            m12,
            m21,
            m22,
        }
    }

    /// Return the identity matrix.
    pub fn identity() -> Self {
        Self::new(T::one(), T::zero(), T::zero(), T::one())
    }

    /// Compute product of the matrix with a scalar.
    pub fn mul_scalar(&self, rhs: T) -> Self {
        Matrix2d::new(
            self.m11 * rhs, self.m12 * rhs,
            self.m21 * rhs, self.m22 * rhs,
        )
    }

    /// Compute matrix-column-vector multiplication.
    /// The vector is interpreted as column vector.
    pub fn mul_column_vector(&self, rhs: Vector<T>) -> Vector<T> {
        Vector::new(
            rhs.x * self.m11 + rhs.y * self.m12,
            rhs.x * self.m21 + rhs.y * self.m22,
        )
    }

    /// Matrix-matrix multiplication.
    pub fn mul_matrix(&self, rhs: &Self) -> Self {
        let a = self;
        let b = rhs;
        let c11 = a.m11 * b.m11 + a.m12 * b.m21;
        let c12 = a.m11 * b.m12 + a.m12 * b.m22;
        let c21 = a.m21 * b.m11 + a.m22 * b.m21;
        let c22 = a.m21 * b.m12 + a.m22 * b.m22;
        Self::new(
            c11, c12,
            c21, c22,
        )
    }

    /// Compute the transpose of the matrix.
    pub fn transpose(&self) -> Self {
        Self::new(self.m11, self.m21,
                  self.m12, self.m22)
    }

    /// Compute the determinant of this matrix.
    pub fn determinant(&self) -> T {
        self.m11 * self.m22 - self.m12 * self.m21
    }

    /// Test if this matrix is the identity matrix.
    pub fn is_identity(&self) -> bool {
        self == &Self::identity()
    }

    /// Test if this matrix is unitary.
    pub fn is_unitary(&self) -> bool {
        self.mul_matrix(&self.transpose()).is_identity()
    }

    /// Compute the inverse matrix.
    /// `None` will be returned if the determinant is zero and the matrix
    /// is not invertible.
    pub fn try_inverse(&self) -> Option<Self> {
        // Compute determinant.
        let det = self.determinant();
        if !det.is_zero() {
            let z = T::zero();
            Some(Self::new(self.m22 / det, z - self.m12 / det,
                           z - self.m21 / det, self.m11 / det))
        } else {
            None
        }
    }
}

impl<T: CoordinateType> Default for Matrix2d<T> {
    fn default() -> Self {
        Self::identity()
    }
}

#[test]
fn test_matrix_multiplication() {
    let a = Matrix2d::new(1.0, 2.0, 3.0, 4.0);
    let b = Matrix2d::new(5.0, 6.0, 7.0, 8.0);
    let id = Matrix2d::identity();
    assert_eq!(id.mul_matrix(&id), id);
    assert_eq!(b.mul_matrix(&id), b);
    assert_eq!(id.mul_matrix(&b), b);
    assert_eq!(a.mul_matrix(&b), Matrix2d::new(19.0, 22.0, 15.0 + 28.0, 18.0 + 32.0));
}

#[test]
fn test_inverse() {
    let m = Matrix2d::new(2.0, 1.0, 4.0, 8.0);
    let i = m.try_inverse().unwrap();
    assert_eq!(m.mul_matrix(&i), Matrix2d::identity());
    assert_eq!(i.mul_matrix(&m), Matrix2d::identity());
}