argmin_math/ndarray_m/
l1norm.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::ArgminL1Norm;
9use ndarray::Array1;
10use num_complex::Complex;
11
12macro_rules! make_l1norm {
13    ($t:ty) => {
14        impl ArgminL1Norm<$t> for Array1<$t> {
15            #[inline]
16            fn l1_norm(&self) -> $t {
17                self.iter().map(|a| a.abs()).sum()
18            }
19        }
20    };
21}
22
23macro_rules! make_l1norm_complex {
24    ($i: ty, $t:ty) => {
25        impl ArgminL1Norm<$t> for Array1<$i> {
26            #[inline]
27            fn l1_norm(&self) -> $t {
28                self.iter().map(|a| a.l1_norm()).sum::<$t>().into()
29            }
30        }
31    };
32}
33
34macro_rules! make_l1norm_unsigned {
35    ($t:ty) => {
36        impl ArgminL1Norm<$t> for Array1<$t> {
37            #[inline]
38            fn l1_norm(&self) -> $t {
39                self.iter().sum()
40            }
41        }
42    };
43}
44
45make_l1norm_unsigned!(u8);
46make_l1norm_unsigned!(u16);
47make_l1norm_unsigned!(u32);
48make_l1norm_unsigned!(u64);
49make_l1norm!(i8);
50make_l1norm!(i16);
51make_l1norm!(i32);
52make_l1norm!(i64);
53make_l1norm!(f32);
54make_l1norm!(f64);
55make_l1norm_complex!(Complex<i8>, i8);
56make_l1norm_complex!(Complex<i16>, i16);
57make_l1norm_complex!(Complex<i32>, i32);
58make_l1norm_complex!(Complex<i64>, i64);
59make_l1norm_complex!(Complex<u8>, u8);
60make_l1norm_complex!(Complex<u16>, u16);
61make_l1norm_complex!(Complex<u32>, u32);
62make_l1norm_complex!(Complex<u64>, u64);
63make_l1norm_complex!(Complex<f32>, f32);
64make_l1norm_complex!(Complex<f64>, f64);
65
66// All code that does not depend on a linked ndarray-linalg backend can still be tested as normal.
67// To avoid dublicating tests and to allow convenient testing of functionality that does not need ndarray-linalg the tests are still included here.
68// The tests expect the name for the crate containing the tested functions to be argmin_math
69#[cfg(test)]
70use crate as argmin_math;
71include!(concat!(
72    env!("CARGO_MANIFEST_DIR"),
73    "/ndarray-tests-src/l1norm.rs"
74));