argmin_math/ndarray_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::ArgminSignum;
9use ndarray::{Array1, Array2};
10use num_complex::Complex;
11
12macro_rules! make_signum {
13    ($t:ty) => {
14        impl ArgminSignum for Array1<$t> {
15            #[inline]
16            fn signum(mut self) -> Array1<$t> {
17                for a in &mut self {
18                    *a = a.signum();
19                }
20                self
21            }
22        }
23
24        impl ArgminSignum for Array2<$t> {
25            #[inline]
26            fn signum(mut self) -> Array2<$t> {
27                let m = self.shape()[0];
28                let n = self.shape()[1];
29                for i in 0..m {
30                    for j in 0..n {
31                        self[(i, j)] = self[(i, j)].signum();
32                    }
33                }
34                self
35            }
36        }
37    };
38}
39
40macro_rules! make_signum_complex {
41    ($t:ty) => {
42        impl ArgminSignum for Array1<$t> {
43            #[inline]
44            fn signum(mut self) -> Array1<$t> {
45                for a in &mut self {
46                    a.re = a.re.signum();
47                    a.im = a.im.signum();
48                }
49                self
50            }
51        }
52
53        impl ArgminSignum for Array2<$t> {
54            #[inline]
55            fn signum(mut self) -> Array2<$t> {
56                let m = self.shape()[0];
57                let n = self.shape()[1];
58                for i in 0..m {
59                    for j in 0..n {
60                        self[(i, j)].re = self[(i, j)].re.signum();
61                        self[(i, j)].im = self[(i, j)].im.signum();
62                    }
63                }
64                self
65            }
66        }
67    };
68}
69
70make_signum!(i8);
71make_signum!(i16);
72make_signum!(i32);
73make_signum!(i64);
74make_signum!(f32);
75make_signum!(f64);
76make_signum_complex!(Complex<i8>);
77make_signum_complex!(Complex<i16>);
78make_signum_complex!(Complex<i32>);
79make_signum_complex!(Complex<i64>);
80make_signum_complex!(Complex<f32>);
81make_signum_complex!(Complex<f64>);
82
83// All code that does not depend on a linked ndarray-linalg backend can still be tested as normal.
84// To avoid dublicating tests and to allow convenient testing of functionality that does not need ndarray-linalg the tests are still included here.
85// The tests expect the name for the crate containing the tested functions to be argmin_math
86#[cfg(test)]
87use crate as argmin_math;
88include!(concat!(
89    env!("CARGO_MANIFEST_DIR"),
90    "/ndarray-tests-src/signum.rs"
91));