Coverage Report

Created: 2025-11-28 06:44

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/linfa-linalg-0.2.1/src/norm.rs
Line
Count
Source
1
//! Norm of vectors
2
3
use ndarray::{prelude::*, Data};
4
5
/// Define norm as a metric linear space, treating the whole matrix as one big vector.
6
pub trait Norm {
7
    type Output;
8
9
    /// L-1 norm
10
    fn norm_l1(&self) -> Self::Output;
11
    /// L-2 norm
12
    fn norm_l2(&self) -> Self::Output;
13
    /// Maximum norm (L-infinite)
14
    fn norm_max(&self) -> Self::Output;
15
}
16
17
impl<A, S, D> Norm for ArrayBase<S, D>
18
where
19
    A: NdFloat + std::iter::Sum,
20
    S: Data<Elem = A>,
21
    D: Dimension,
22
{
23
    type Output = A;
24
25
0
    fn norm_l1(&self) -> Self::Output {
26
0
        self.iter().map(|x| x.abs()).sum()
27
0
    }
28
29
0
    fn norm_l2(&self) -> Self::Output {
30
0
        self.iter().map(|&x| x * x).sum::<A>().sqrt()
Unexecuted instantiation: <ndarray::ArrayBase<ndarray::data_repr::OwnedRepr<f64>, ndarray::dimension::dim::Dim<[usize; 1]>> as linfa_linalg::norm::Norm>::norm_l2::{closure#0}
Unexecuted instantiation: <ndarray::ArrayBase<ndarray::data_repr::OwnedRepr<f32>, ndarray::dimension::dim::Dim<[usize; 1]>> as linfa_linalg::norm::Norm>::norm_l2::{closure#0}
Unexecuted instantiation: <ndarray::ArrayBase<_, _> as linfa_linalg::norm::Norm>::norm_l2::{closure#0}
31
0
    }
Unexecuted instantiation: <ndarray::ArrayBase<ndarray::data_repr::OwnedRepr<f64>, ndarray::dimension::dim::Dim<[usize; 1]>> as linfa_linalg::norm::Norm>::norm_l2
Unexecuted instantiation: <ndarray::ArrayBase<ndarray::data_repr::OwnedRepr<f32>, ndarray::dimension::dim::Dim<[usize; 1]>> as linfa_linalg::norm::Norm>::norm_l2
Unexecuted instantiation: <ndarray::ArrayBase<_, _> as linfa_linalg::norm::Norm>::norm_l2
32
33
0
    fn norm_max(&self) -> Self::Output {
34
0
        self.iter().fold(A::zero(), |f, &val| val.abs().max(f))
35
0
    }
36
}
37
38
#[cfg(test)]
39
mod tests {
40
    use approx::assert_abs_diff_eq;
41
42
    use super::*;
43
44
    #[test]
45
    fn norms() {
46
        let a = array![[1.0f64, -3.], [2., -8.]];
47
        assert_abs_diff_eq!(a.norm_l1(), 14.);
48
        assert_abs_diff_eq!(a.norm_l2(), 78.0f64.sqrt());
49
        assert_abs_diff_eq!(a.norm_max(), 8.);
50
    }
51
}