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
/*
   Appellation: arr <mod>
   Contrib: FL03 <jo3mccain@icloud.com>
*/
use nd::linalg::Dot;
use nd::*;
use num::traits::{Num, NumAssign};

pub trait Affine<T> {
    type Output;

    fn affine(&self, mul: T, add: T) -> Self::Output;
}

pub trait Inverse {
    type Output;

    fn inverse(&self) -> Self::Output;
}

pub trait Matmul<Rhs = Self> {
    type Output;

    fn matmul(&self, rhs: Rhs) -> Self::Output;
}

pub trait Matpow<Rhs = Self> {
    type Output;

    fn pow(&self, rhs: Rhs) -> Self::Output;
}

/*
 ********* Implementations *********
*/
impl<A, D> Affine<A> for Array<A, D>
where
    A: LinalgScalar + ScalarOperand,
    D: Dimension,
{
    type Output = Array<A, D>;
    fn affine(&self, mul: A, add: A) -> Self {
        self * mul + add
    }
}

// #[cfg(feature = "blas")]
impl<T> Inverse for Array<T, Ix2>
where
    T: Copy + NumAssign + ScalarOperand,
{
    type Output = Option<Self>;
    fn inverse(&self) -> Self::Output {
        crate::inverse(self)
    }
}

impl<A, B, C> Matmul<B> for A
where
    A: Dot<B, Output = C>,
{
    type Output = C;
    fn matmul(&self, rhs: B) -> Self::Output {
        self.dot(&rhs)
    }
}

impl<A> Matpow<i32> for Array2<A>
where
    A: Clone + Num,
    Array2<A>: Dot<Self, Output = Self>,
{
    type Output = Array2<A>;

    fn pow(&self, rhs: i32) -> Self::Output {
        if !self.is_square() {
            panic!("Matrix must be square to be raised to a power");
        }
        let mut res = Array::eye(self.shape()[0]);
        for _ in 0..rhs {
            res = res.dot(&self);
        }
        res
    }
}