argmin_math/ndarray_m/
l2norm.rs

1// Copyright 2018-2024 argmin developers
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// http://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8use crate::ArgminL2Norm;
9use ndarray::Array1;
10use num_complex::Complex;
11use num_integer::Roots;
12
13macro_rules! make_norm_float {
14    ($t:ty) => {
15        impl ArgminL2Norm<$t> for Array1<$t> {
16            #[inline]
17            fn l2_norm(&self) -> $t {
18                self.iter().map(|a| a.powi(2)).sum::<$t>().sqrt()
19            }
20        }
21    };
22}
23
24macro_rules! make_norm_integer {
25    ($t:ty) => {
26        impl ArgminL2Norm<$t> for Array1<$t> {
27            #[inline]
28            fn l2_norm(&self) -> $t {
29                self.iter().map(|a| a.pow(2)).sum::<$t>().sqrt()
30            }
31        }
32    };
33}
34
35macro_rules! make_norm_complex {
36    ($i: ty, $t:ty) => {
37        impl ArgminL2Norm<$t> for Array1<$i> {
38            #[inline]
39            fn l2_norm(&self) -> $t {
40                self.iter().map(|a| a.norm_sqr()).sum::<$t>().sqrt()
41            }
42        }
43    };
44}
45
46macro_rules! make_norm_unsigned {
47    ($t:ty) => {
48        impl ArgminL2Norm<$t> for Array1<$t> {
49            #[inline]
50            fn l2_norm(&self) -> $t {
51                self.iter().map(|a| a.pow(2)).sum::<$t>().sqrt()
52            }
53        }
54    };
55}
56
57make_norm_unsigned!(u8);
58make_norm_unsigned!(u16);
59make_norm_unsigned!(u32);
60make_norm_unsigned!(u64);
61make_norm_integer!(i8);
62make_norm_integer!(i16);
63make_norm_integer!(i32);
64make_norm_integer!(i64);
65make_norm_float!(f32);
66make_norm_float!(f64);
67make_norm_complex!(Complex<i8>, i8);
68make_norm_complex!(Complex<i16>, i16);
69make_norm_complex!(Complex<i32>, i32);
70make_norm_complex!(Complex<i64>, i64);
71make_norm_complex!(Complex<u8>, u8);
72make_norm_complex!(Complex<u16>, u16);
73make_norm_complex!(Complex<u32>, u32);
74make_norm_complex!(Complex<u64>, u64);
75make_norm_complex!(Complex<f32>, f32);
76make_norm_complex!(Complex<f64>, f64);
77
78// All code that does not depend on a linked ndarray-linalg backend can still be tested as normal.
79// To avoid dublicating tests and to allow convenient testing of functionality that does not need ndarray-linalg the tests are still included here.
80// The tests expect the name for the crate containing the tested functions to be argmin_math
81#[cfg(test)]
82use crate as argmin_math;
83include!(concat!(
84    env!("CARGO_MANIFEST_DIR"),
85    "/ndarray-tests-src/l2norm.rs"
86));