argmin_math/nalgebra_m/
signum.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::{Allocator, ArgminSignum};
9
10use nalgebra::{base::dimension::Dim, DefaultAllocator, OMatrix, SimdComplexField};
11
12impl<N, R, C> ArgminSignum for OMatrix<N, R, C>
13where
14    N: SimdComplexField,
15    R: Dim,
16    C: Dim,
17    DefaultAllocator: Allocator<N, R, C>,
18{
19    #[inline]
20    fn signum(self) -> OMatrix<N, R, C> {
21        self.map(|v| v.simd_signum())
22    }
23}
24
25#[cfg(test)]
26mod tests {
27    use super::*;
28    use approx::assert_relative_eq;
29    use nalgebra::{Matrix2x3, Vector3};
30    use paste::item;
31
32    macro_rules! make_test {
33        ($t:ty) => {
34            item! {
35                #[test]
36                fn [<test_signum_ $t>]() {
37                    let a = Vector3::new(3 as $t, -4 as $t, -8 as $t);
38                    let b = Vector3::new(1 as $t, -1 as $t, -1 as $t);
39                    let res = <Vector3<$t> as ArgminSignum>::signum(a);
40                    for i in 0..3 {
41                        assert_relative_eq!(b[i], res[i], epsilon = $t::EPSILON);
42                    }
43                }
44            }
45
46            item! {
47                #[test]
48                fn [<test_signum_scalar_mat_2_ $t>]() {
49                    let b = Matrix2x3::new(
50                        3 as $t, -4 as $t, 8 as $t,
51                        -2 as $t, -5 as $t, 9 as $t
52                    );
53                    let target = Matrix2x3::new(
54                        1 as $t, -1 as $t, 1 as $t,
55                        -1 as $t, -1 as $t, 1 as $t
56                    );
57                    let res = b.signum();
58                    for i in 0..3 {
59                        for j in 0..2 {
60                            assert_relative_eq!(target[(j, i)], res[(j, i)], epsilon = $t::EPSILON);
61                        }
62                    }
63                }
64            }
65        };
66    }
67
68    make_test!(f32);
69    make_test!(f64);
70}