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
use std::iter::Sum;
use ndarray::*;
use num_traits::Float;
use super::vector::*;
use std::ops::Div;
pub fn from_diag<A>(d: &[A]) -> Array2<A>
where A: LinalgScalar
{
let n = d.len();
let mut e = Array::zeros((n, n));
for i in 0..n {
e[(i, i)] = d[i];
}
e
}
pub fn hstack<A, S>(xs: &[ArrayBase<S, Ix1>]) -> Result<Array<A, Ix2>, ShapeError>
where A: LinalgScalar,
S: Data<Elem = A>
{
let views: Vec<_> = xs.iter()
.map(|x| {
let n = x.len();
x.view().into_shape((n, 1)).unwrap()
})
.collect();
stack(Axis(1), &views)
}
pub fn vstack<A, S>(xs: &[ArrayBase<S, Ix1>]) -> Result<Array<A, Ix2>, ShapeError>
where A: LinalgScalar,
S: Data<Elem = A>
{
let views: Vec<_> = xs.iter()
.map(|x| {
let n = x.len();
x.view().into_shape((1, n)).unwrap()
})
.collect();
stack(Axis(0), &views)
}
pub enum NormalizeAxis {
Row = 0,
Column = 1,
}
pub fn normalize<A, S, T>(mut m: ArrayBase<S, Ix2>, axis: NormalizeAxis) -> (ArrayBase<S, Ix2>, Vec<T>)
where A: LinalgScalar + NormedField<Output = T> + Div<T, Output = A>,
S: DataMut<Elem = A>,
T: Float + Sum
{
let mut ms = Vec::new();
for mut v in m.axis_iter_mut(Axis(axis as usize)) {
let n = v.norm();
ms.push(n);
v.map_inplace(|x| *x = *x / n)
}
(m, ms)
}
pub fn all_close_max<A, Tol, S1, S2, D>(test: &ArrayBase<S1, D>,
truth: &ArrayBase<S2, D>,
atol: Tol)
-> Result<Tol, Tol>
where A: LinalgScalar + NormedField<Output = Tol>,
Tol: Float + Sum,
S1: Data<Elem = A>,
S2: Data<Elem = A>,
D: Dimension
{
let tol = (test - truth).norm_max();
if tol < atol { Ok(tol) } else { Err(tol) }
}
pub fn all_close_l1<A, Tol, S1, S2, D>(test: &ArrayBase<S1, D>, truth: &ArrayBase<S2, D>, rtol: Tol) -> Result<Tol, Tol>
where A: LinalgScalar + NormedField<Output = Tol>,
Tol: Float + Sum,
S1: Data<Elem = A>,
S2: Data<Elem = A>,
D: Dimension
{
let tol = (test - truth).norm_l1() / truth.norm_l1();
if tol < rtol { Ok(tol) } else { Err(tol) }
}
pub fn all_close_l2<A, Tol, S1, S2, D>(test: &ArrayBase<S1, D>, truth: &ArrayBase<S2, D>, rtol: Tol) -> Result<Tol, Tol>
where A: LinalgScalar + NormedField<Output = Tol>,
Tol: Float + Sum,
S1: Data<Elem = A>,
S2: Data<Elem = A>,
D: Dimension
{
let tol = (test - truth).norm_l2() / truth.norm_l2();
if tol < rtol { Ok(tol) } else { Err(tol) }
}