|
1 | 1 | //! Define trait for vectors
|
2 | 2 |
|
3 |
| -use ndarray::{LinalgScalar, Array, Ix1}; |
| 3 | +use std::iter::Sum; |
| 4 | +use ndarray::{LinalgScalar, ArrayBase, Data, Dimension}; |
4 | 5 | use num_traits::float::Float;
|
5 | 6 |
|
6 | 7 | /// Methods for vectors
|
7 | 8 | pub trait Vector {
|
8 | 9 | type Scalar;
|
| 10 | + /// rename of norm_l2 |
| 11 | + fn norm(&self) -> Self::Scalar { |
| 12 | + self.norm_l2() |
| 13 | + } |
| 14 | + /// L-1 norm |
| 15 | + fn norm_l1(&self) -> Self::Scalar; |
9 | 16 | /// L-2 norm
|
10 |
| - fn norm(&self) -> Self::Scalar; |
| 17 | + fn norm_l2(&self) -> Self::Scalar; |
| 18 | + /// maximum norm |
| 19 | + fn norm_max(&self) -> Self::Scalar; |
11 | 20 | }
|
12 | 21 |
|
13 |
| -impl<A: Float + LinalgScalar> Vector for Array<A, Ix1> { |
14 |
| - type Scalar = A; |
15 |
| - fn norm(&self) -> Self::Scalar { |
16 |
| - self.dot(&self).sqrt() |
| 22 | +impl<A, S, D, T> Vector for ArrayBase<S, D> |
| 23 | + where A: LinalgScalar + Squared<Output = T>, |
| 24 | + T: Float + Sum, |
| 25 | + S: Data<Elem = A>, |
| 26 | + D: Dimension |
| 27 | +{ |
| 28 | + type Scalar = T; |
| 29 | + fn norm_l1(&self) -> Self::Scalar { |
| 30 | + self.iter().map(|x| x.sq_abs()).sum() |
| 31 | + } |
| 32 | + fn norm_l2(&self) -> Self::Scalar { |
| 33 | + self.iter().map(|x| x.squared()).sum::<T>().sqrt() |
| 34 | + } |
| 35 | + fn norm_max(&self) -> Self::Scalar { |
| 36 | + self.iter().fold(T::zero(), |f, &val| { |
| 37 | + let v = val.sq_abs(); |
| 38 | + if f > v { f } else { v } |
| 39 | + }) |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +pub trait Squared { |
| 44 | + type Output; |
| 45 | + fn squared(&self) -> Self::Output; |
| 46 | + fn sq_abs(&self) -> Self::Output; |
| 47 | +} |
| 48 | + |
| 49 | +impl<A: Float> Squared for A { |
| 50 | + type Output = A; |
| 51 | + fn squared(&self) -> A { |
| 52 | + *self * *self |
| 53 | + } |
| 54 | + fn sq_abs(&self) -> A { |
| 55 | + self.abs() |
17 | 56 | }
|
18 | 57 | }
|
0 commit comments