-
Notifications
You must be signed in to change notification settings - Fork 0
/
rmatrix.rs
345 lines (291 loc) · 10.8 KB
/
rmatrix.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
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
use Vec;
#[derive(Debug)]
#[derive(PartialEq)]
#[derive(Clone)]
pub struct RMatrix {
pub elem: Vec<f32>,
pub rows: usize,
pub cols: usize
}
impl RMatrix {
/**
* Add two matrices.
* The first matrix is mutated and contains the summation.
*/
pub fn mut_add(&mut self, v: &RMatrix) {
if (self.rows, self.cols) != (v.rows, v.cols) {
println!("he matrix layouts differ !")
}
for i in 0..self.rows * self.cols {
self.elem[i] += v.elem[i];
}
}
pub fn add(self: &RMatrix, v: &RMatrix) -> Result<RMatrix, String> {
if (self.rows, self.cols) != (v.rows, v.cols) {
return Err(String::from("The matrix layouts differ !"))
}
return Ok(RMatrix {
elem: self.elem.iter().zip(v.elem.iter()).map(|(u, v)| u+v).collect(),
rows: self.rows,
cols: self.cols,
});
}
/**
* Sub operation A-B.
* The first matrix is mutated and contains the summation.
*/
pub fn mut_sub(&mut self, v: &RMatrix) {
if (self.rows, self.cols) != (v.rows, v.cols) {
println!("he matrix layouts differ !")
}
for i in 0..self.rows * self.cols {
self.elem[i] -= v.elem[i];
}
}
pub fn sub(self: &RMatrix, v: &RMatrix) -> Result<RMatrix, String> {
if (self.rows, self.cols) != (v.rows, v.cols) {
return Err(String::from("The matrix layouts differ !"))
}
return Ok(RMatrix {
elem: self.elem.iter().zip(v.elem.iter()).map(|(u, v)| u-v).collect(),
rows: self.rows,
cols: self.cols,
});
}
pub fn mult_by_scalar(self: &RMatrix, r: f32) -> RMatrix {
return RMatrix {
elem: self.elem.iter().map(|x| x*r).collect(),
rows: self.rows,
cols: self.cols,
};
}
/**
* Dot product of two matrices
*/
pub fn dot(&self, v: &RMatrix) -> Result<RMatrix, String> {
if self.cols != v.rows {
return Err(String::from("The col size of matrix 1 must equal the row size of matrix 2 !"))
}
let mut w: RMatrix = RMatrix{elem: vec![0.; self.rows * v.cols], rows: self.rows, cols: v.cols};
for i in 0..self.rows {
for j in 0..v.cols {
let mut sum = 0.0;
for k in 0..self.cols {
sum += self.elem[i * self.cols + k] * v.elem[k * v.cols + j]
}
w.elem[i * w.cols + j] = sum;
}
}
return Ok(w);
}
/**
* Swap two rows j and k of the matrix (mutates the matrix)
* (inefficient, allocates a buffer)
*/
pub fn swap_rows(&mut self, j: usize, k: usize) {
let mut temp_row = vec![0.;self.cols];
temp_row.copy_from_slice(&self.elem[j*self.cols..(j+1)*self.cols]);
self.elem.copy_within(k*self.cols..(k+1)*self.cols, j*self.cols);
self.elem[k*self.cols..(k+1)*self.cols].copy_from_slice(&temp_row);
}
pub fn transpose(&self) -> RMatrix {
let nelems = self.rows * self.cols;
let mut t: RMatrix = RMatrix{elem: vec![0.;nelems], rows: self.cols, cols: self.rows};
for n in 0..nelems {
let i = n / self.rows;
let j = n % self.rows;
t.elem[n] = self.elem[j*self.cols + i]
}
return t;
}
/*
* LU factorization with partial pivoting
*
* Code adapted from C (https://en.wikipedia.org/wiki/LU_decomposition)
* INPUT : a - square matrix having dimension n
* tol - small tolerance number to detect failure when the matrix is near degenerate
* OUTPUT: a LU matrix contains a copy of both matrices L-E and U as a=(L-E)+U such that PA=LU.
* The permutation matrix p is not stored as a RMatrix, but as an integer vector of size n+1
* containing column indexes where the permutation matrix has "1". The last element p[n]=S+n,
* where S is the number of row exchanges needed for determinant computation, det(p)=(-1)^S
*/
pub fn decompose_lup(&mut self, tol: f32) -> Result<(RMatrix, Vec<usize>), String> {
if self.rows != self.cols {
return Err(String::from("The matrix must be square !"))
}
let mut a: RMatrix = self.clone();
let n = a.rows;
// Permutation vector
let mut p: Vec::<usize> = vec![0;n+1];
for i in 0..n {p[i] = i};
for i in 0..n { // for each row
let mut max_a: f32 = 0.0f32;
let mut imax = i;
for k in i..n {
let abs_a = a.elem[k*n + i].abs();
if abs_a > max_a { // find the pivot
max_a = abs_a;
imax = k;
}
}
if max_a < tol {
return Err(String::from("matrix is degenerate !"))
}
if imax != i {
//pivot p and rows of A
p.swap(i, imax);
a.swap_rows(i, imax);
//count pivots starting from n (for determinant)
p[n] += 1;
}
// Gaussian elimination
for j in i + 1..n {
a.elem[j * n + i] /= a.elem[i * n + i];
for k in i + 1..n {
a.elem[j * n + k] -= a.elem[j * n + i] * a.elem[i * n + k]
}
}
}
return Ok((a,p)); //decomposition done
}
/* Solve A*x = B
*
* INPUT: a,p filled by decompose_lup, such that PA = LU in LU*x=Pb
* b - rhs vector, given as a column RMatrix
* OUTPUT: x - solution vector of a*x=b, returned as a column RMatrix
*/
pub fn solve_lup(&self, p: &Vec<usize>, b: &RMatrix) -> Result<RMatrix, String> {
let n = self.rows;
if n != self.cols {
return Err(String::from("The matrix a must be square !"))
}
if p.len() != n + 1 {
return Err(String::from("The p vector must have the number of rows of a + 1 !"))
}
if b.rows != n {
return Err(String::from("The b column matrix must have the number of rows of a !"))
}
// Solution vector
let mut x= vec![0.;n];
for i in 0..n {
x[i] = b.elem[p[i]];
for k in 0..i {
x[i] -= self.elem[i * n + k] * x[k];
}
}
for i in (0..n).rev() {
for k in i + 1..n {
x[i] -= self.elem[i * n + k] * x[k];
}
x[i] /= self.elem[i * n + i];
}
return Ok(RMatrix {elem: x, rows: n, cols: 1});
}
/*
* Invert the matrix
* INPUT: a,p filled in decompose_lup
* OUTPUT: the inverse of the initial matrix
*/
pub fn inverse(self: &RMatrix, p: &Vec<usize>) -> Result<RMatrix, String> {
let n = self.rows;
if n != self.cols {
return Err(String::from("The matrix must be square !"))
}
if p.len() != n + 1 {
return Err(String::from("The P vector must have N+1 rows !"))
}
// Inverse matrix
let mut i_a: Vec<f32> = vec![0.; n*n];
for j in 0..n {
for i in 0..n {
i_a[i * n + j] = if p[i] == j { 1.0 } else { 0.0 }; // P matrix
for k in 0..i {
i_a[i * n + j] -= self.elem[i * n + k] * i_a[k * n + j];
}
}
for i in (0..n).rev() {
for k in i + 1..n {
i_a[i * n + j] -= self.elem[i * n + k] * i_a[k * n + j];
}
i_a[i * n + j] /= self.elem [i * n + i];
}
}
return Ok(RMatrix {elem: i_a, rows: n, cols: n});
}
/* INPUT: p vector filled in decompose_lup
* OUTPUT: return the determinant of the initial matrix
*/
pub fn determinant(&self, p: &Vec<usize>) -> f32 {
let n = self.rows;
let mut det = self.elem[0] as f32;
for i in 1..n {
det *= self.elem[i * n + i];
}
if (p[n-1] as i32 - (n-1) as i32) % 2 == 0 {
return det;
}
else {
return -det;
}
}
/**
* Compute the norm of a vector
*/
pub fn norm_vector(v: &Vec<f32>) -> f32 {
return f32::sqrt(v.iter().map(|x| x*x).sum());
}
pub fn norm(v: &RMatrix) -> f32 {
return RMatrix::norm_vector(&v.elem);
}
/**
* Identity matrix
* n : size of the matrix
* scale: multiplicative factor (put 1. for the unit identity matrix)
*/
pub fn eye(n: usize, scale: f32) -> RMatrix {
let mut v = vec![0.; n*n];
for i in 0..n {
v[i*n + i] = scale;
}
return RMatrix{elem: v, rows: n, cols: n};
}
/**
* Inverse iteration method for finding an eigenvalue/eigenvector pair,
* given an initial guess.
*
* INPUT: y, alpha initial guess for the eigenvector and eigenvalue
* INPUT: epsilon precision of the result
* OUTPUT: an eigenvalue/eigenvector pair that is the closest to y
*/
pub fn inverse_iter(self: &RMatrix,
y: &RMatrix, alpha: f32,
epsilon: f32)
-> Result<(u32, f32, RMatrix), String> {
let n = self.rows;
if n != self.cols {
return Err(String::from("The matrix must be square !"))
}
if y.rows != n || y.cols != 1 {
return Err(String::from("The initial guess vector must have the dimensions (rows: n, cols: 1), where n is the size of the matrix !"))
}
let mut yy = y.clone();
let alphax_i = RMatrix::eye(n, alpha);
let mut b = self.sub(&alphax_i)?; // A - alpha*I aka "shifted of origin"
let (lu, permut) = b.decompose_lup(epsilon).unwrap();
let mut iter = 0;
let mut distance = f32::MAX;
let mut theta = 0.0_f32;
while distance > epsilon * f32::abs(theta) {
iter += 1;
let norm_y = RMatrix::norm_vector(&yy.elem);
let v = RMatrix{elem: yy.mult_by_scalar(1.0 / norm_y).elem,
rows: n,
cols: 1};
// solve (A - sigma*I) y = v, where v = y/||y||
yy = lu.solve_lup(&permut, &v)?;
theta = v.transpose().dot(&yy)?.elem[0];
distance = RMatrix::norm(&yy.sub(&v.mult_by_scalar(theta))?);
}
return Ok((iter, alpha + 1.0/theta, yy.mult_by_scalar(1.0/theta)));
}
}