forked from OpenSRDK/linear-algebra-rs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmul.rs
163 lines (136 loc) · 2.88 KB
/
mul.rs
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
use crate::matrix::Matrix;
use crate::number::{c64, Number};
use blas::{dgemm, zgemm};
use rayon::prelude::*;
use std::ops::Mul;
fn mul<T>(slf: T, rhs: Matrix<T>) -> Matrix<T>
where
T: Number,
{
let mut rhs = rhs;
rhs
.elems
.par_iter_mut()
.map(|r| {
*r *= slf;
})
.collect::<Vec<_>>();
rhs
}
fn mul_f64(lhs: &Matrix, rhs: &Matrix) -> Matrix {
if lhs.cols != rhs.rows {
panic!("Dimension mismatch.")
}
let m = lhs.rows as i32;
let k = lhs.cols as i32;
let n = rhs.cols as i32;
let mut new_matrix = Matrix::new(lhs.rows, rhs.cols);
unsafe {
dgemm(
'N' as u8,
'N' as u8,
m,
n,
k,
1.0,
lhs.elems.as_slice(),
m,
rhs.elems.as_slice(),
k,
0.0,
&mut new_matrix.elems,
m,
);
}
new_matrix
}
fn mul_c64(lhs: &Matrix<c64>, rhs: &Matrix<c64>) -> Matrix<c64> {
if lhs.cols != rhs.rows {
panic!("Dimension mismatch.")
}
let m = lhs.rows as i32;
let k = lhs.cols as i32;
let n = rhs.cols as i32;
let mut new_matrix = Matrix::<c64>::new(lhs.rows, rhs.cols);
unsafe {
zgemm(
'N' as u8,
'N' as u8,
m,
n,
k,
blas::c64::new(1.0, 0.0),
&lhs.elems,
m,
&rhs.elems,
k,
blas::c64::new(0.0, 0.0),
&mut new_matrix.elems,
m,
);
}
new_matrix
}
macro_rules! impl_mul_scalar {
{$t: ty} => {
impl Mul<Matrix<$t>> for $t {
type Output = Matrix<$t>;
fn mul(self, rhs: Matrix<$t>) -> Self::Output {
mul(self, rhs)
}
}
impl Mul<$t> for Matrix<$t> {
type Output = Matrix<$t>;
fn mul(self, rhs: $t) -> Self::Output {
mul(rhs, self)
}
}
};
}
impl_mul_scalar! {f64}
impl_mul_scalar! {c64}
macro_rules! impl_mul {
{$t: ty, $e: expr} => {
impl Mul<Matrix<$t>> for Matrix<$t> {
type Output = Matrix<$t>;
fn mul(self, rhs: Matrix<$t>) -> Self::Output {
$e(&self, &rhs)
}
}
impl Mul<&Matrix<$t>> for Matrix<$t> {
type Output = Matrix<$t>;
fn mul(self, rhs: &Matrix<$t>) -> Self::Output {
$e(&self, rhs)
}
}
impl Mul<Matrix<$t>> for &Matrix<$t> {
type Output = Matrix<$t>;
fn mul(self, rhs: Matrix<$t>) -> Self::Output {
$e(self, &rhs)
}
}
impl Mul<&Matrix<$t>> for &Matrix<$t> {
type Output = Matrix<$t>;
fn mul(self, rhs: &Matrix<$t>) -> Self::Output {
$e(self, rhs)
}
}
};
}
impl_mul! {f64, mul_f64}
impl_mul! {c64, mul_c64}
#[cfg(test)]
mod tests {
use crate::*;
#[test]
fn it_works() {
let a = mat!(
1.0, 2.0;
3.0, 4.0
) * mat!(
5.0, 6.0;
7.0, 8.0
);
assert_eq!(a[(0, 0)], 19.0);
}
}