1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
use crate::{
    core::prelude::*,
    errors::prelude::*,
    extensions::prelude::*,
    math::prelude::*,
    numeric::prelude::*,
};

/// ArrayTrait - Array Math Misc functions
pub trait ArrayMathMisc<N: Numeric> where Self: Sized + Clone {

    /// Returns the discrete, linear convolution of two one-dimensional sequences
    /// arrays are flattened for computation
    ///
    /// # Arguments
    ///
    /// * `other` - array to perform the operation with
    /// * `mode` - {`full`, `valid`, `same`}, optional. defaults to `full`
    ///
    /// # Examples
    ///
    /// ```
    /// use arr_rs::prelude::*;
    ///
    /// let arr = Array::flat(vec![1., 2., 3.]);
    /// let other = Array::flat(vec![0., 1., 0.5]);
    /// assert_eq!(Array::flat(vec![0., 1., 2.5, 4., 1.5]), arr.convolve(&other.unwrap(), Some("full")));
    /// ```
    fn convolve(&self, other: &Array<N>, mode: Option<impl ConvolveModeType>) -> Result<Array<N>, ArrayError>;

    /// Clip (limit) the values in an array
    ///
    /// # Arguments
    ///
    /// * `a_min` - minimum array value
    /// * `a_max` - maximum array value
    ///
    /// # Examples
    ///
    /// ```
    /// use arr_rs::prelude::*;
    ///
    /// let arr = Array::flat(vec![1., 2., 3., 4.]);
    /// let a_min = Array::single(2.).unwrap();
    /// let a_max = Array::single(3.).unwrap();
    /// assert_eq!(Array::flat(vec![2., 2., 3., 3.]), arr.clip(Some(a_min), Some(a_max)));
    /// ```
    fn clip(&self, a_min: Option<Array<N>>, a_max: Option<Array<N>>) -> Result<Array<N>, ArrayError>;

    /// Computes square root of array elements
    ///
    /// # Examples
    ///
    /// ```
    /// use arr_rs::prelude::*;
    ///
    /// let arr = Array::flat(vec![1, 4, 9, 16]);
    /// assert_eq!(Array::flat(vec![1, 2, 3, 4]), arr.sqrt());
    /// ```
    fn sqrt(&self) -> Result<Array<N>, ArrayError>;

    /// Computes cube root of array elements
    ///
    /// # Examples
    ///
    /// ```
    /// use arr_rs::prelude::*;
    ///
    /// let arr = Array::flat(vec![1, 8, 27, 64]);
    /// assert_eq!(Array::flat(vec![1, 2, 3, 4]), arr.cbrt());
    /// ```
    fn cbrt(&self) -> Result<Array<N>, ArrayError>;

    /// Return the element-wise square of the input
    ///
    /// # Examples
    ///
    /// ```
    /// use arr_rs::prelude::*;
    ///
    /// let arr = Array::flat(vec![1, 2, 3, 4]);
    /// assert_eq!(Array::flat(vec![1, 4, 9, 16]), arr.square());
    /// ```
    fn square(&self) -> Result<Array<N>, ArrayError>;

    /// Computes absolute value of array elements
    ///
    /// # Examples
    ///
    /// ```
    /// use arr_rs::prelude::*;
    ///
    /// let arr = Array::flat(vec![1, -2, 3, -4]);
    /// assert_eq!(Array::flat(vec![1, 2, 3, 4]), arr.absolute());
    /// ```
    fn absolute(&self) -> Result<Array<N>, ArrayError>;

    /// Computes absolute value of array elements
    /// alias on `absolute`
    ///
    /// # Examples
    ///
    /// ```
    /// use arr_rs::prelude::*;
    ///
    /// let arr = Array::flat(vec![1, -2, 3, -4]);
    /// assert_eq!(Array::flat(vec![1, 2, 3, 4]), arr.abs());
    /// ```
    fn abs(&self) -> Result<Array<N>, ArrayError>;

    /// Computes absolute value of array elements
    /// alias on `absolute`
    ///
    /// # Examples
    ///
    /// ```
    /// use arr_rs::prelude::*;
    ///
    /// let arr = Array::flat(vec![1, -2, 3, -4]);
    /// assert_eq!(Array::flat(vec![1, 2, 3, 4]), arr.fabs());
    /// ```
    fn fabs(&self) -> Result<Array<N>, ArrayError>;

    /// Returns an element-wise indication of the sign of a number
    ///
    /// # Examples
    ///
    /// ```
    /// use arr_rs::prelude::*;
    ///
    /// let arr = Array::flat(vec![1, -2, -3, 4]);
    /// assert_eq!(Array::flat(vec![1, -1, -1, 1]), arr.sign());
    /// ```
    fn sign(&self) -> Result<Array<isize>, ArrayError>;

    /// Compute the Heaviside step function
    ///
    /// # Arguments
    ///
    /// * `other` - array to perform the operation with
    ///
    /// # Examples
    ///
    /// ```
    /// use arr_rs::prelude::*;
    ///
    /// let arr = Array::flat(vec![-1.5, 0., 2.]);
    /// assert_eq!(Array::flat(vec![0., 0.5, 1.]), arr.heaviside(&Array::single(0.5).unwrap()));
    /// ```
    fn heaviside(&self, other: &Array<N>) -> Result<Array<N>, ArrayError>;

    /// Replace NaN with zero and infinity with large finite numbers
    ///
    /// # Examples
    ///
    /// ```
    /// use arr_rs::prelude::*;
    ///
    /// let arr = Array::flat(vec![1., 2., f64::NAN, f64::INFINITY]);
    /// assert_eq!(Array::flat(vec![1., 2., 0., f64::MAX]), arr.nan_to_num());
    /// ```
    fn nan_to_num(&self) -> Result<Array<N>, ArrayError>;
}

impl <N: Numeric> ArrayMathMisc<N> for Array<N> {

    fn convolve(&self, other: &Array<N>, mode: Option<impl ConvolveModeType>) -> Result<Array<N>, ArrayError> {
        if self.len()? == 0 || other.len()? == 0 {
            return Err(ArrayError::ParameterError { param: "`array|other`", message: "cannot be empty", })
        }

        let mode = match mode {
            Some(cm) => cm.to_mode()?,
            None => ConvolveMode::Full,
        };

        let mut arrays = (self.to_array_f64()?, other.to_array_f64()?);
        if arrays.1.len()? > arrays.0.len()? { arrays = arrays.swap() };
        let mut out = vec![0.; arrays.0.len()? + arrays.1.len()? - 1];
        for i in 0 .. arrays.0.len()? { for j in 0 .. arrays.1.len()? {
            out[i + j] += arrays.0[i] * arrays.1[j]
        } }
        let (n, m) = (arrays.0.len()?, arrays.1.len()?);

        match mode {
            ConvolveMode::Full => out.to_vec(),
            ConvolveMode::Valid => out.iter().skip(m - 1).take(n - m + 1).copied().collect(),
            ConvolveMode::Same => out.iter().skip((m - 1) / 2).take(n).copied().collect(),
        }.to_array()?.to_array_num()
    }

    fn clip(&self, a_min: Option<Array<N>>, a_max: Option<Array<N>>) -> Result<Array<N>, ArrayError> {
        let a_min = if let Some(min) = a_min { min } else { self.min(None)? }
            .broadcast_to(self.get_shape()?)?;
        let a_max = if let Some(max) = a_max { max } else { self.max(None)? }
            .broadcast_to(self.get_shape()?)?;
        let borders = a_min.zip(&a_max)?;

        self.zip(&borders)?
            .map(|tuple| {
                if tuple.0 < tuple.1.0 { tuple.1.0 }
                else if tuple.0 > tuple.1.1 { tuple.1.1 }
                else { tuple.0 }
            })
    }

    fn sqrt(&self) -> Result<Array<N>, ArrayError> {
        self.map(|i| N::from(i.to_f64().sqrt()))
    }

    fn cbrt(&self) -> Result<Array<N>, ArrayError> {
        self.map(|i| N::from(i.to_f64().cbrt()))
    }

    fn square(&self) -> Result<Array<N>, ArrayError> {
        self.map(|i| N::from(i.to_f64().powf(2.)))
    }

    fn absolute(&self) -> Result<Array<N>, ArrayError> {
        self.map(|i| N::from(i.to_f64().abs()))
    }

    fn abs(&self) -> Result<Array<N>, ArrayError> {
        self.absolute()
    }

    fn fabs(&self) -> Result<Array<N>, ArrayError> {
        self.absolute()
    }

    fn sign(&self) -> Result<Array<isize>, ArrayError> {
        self.map(|&i| if i < N::zero() { -1 } else { 1 })
    }

    fn heaviside(&self, other: &Array<N>) -> Result<Array<N>, ArrayError> {
        self.zip(other)?
            .map(|tuple|
                if tuple.0 < N::zero() { N::zero() }
                else if tuple.0 == N::zero() { tuple.1 }
                else { N::one() }
            )
    }

    fn nan_to_num(&self) -> Result<Array<N>, ArrayError> {
        self.map(|&item|
            if item.is_nan() { N::zero() }
            else if item.is_inf() { item.max() }
            else { item }
        )
    }
}

impl <N: Numeric> ArrayMathMisc<N> for Result<Array<N>, ArrayError> {

    fn convolve(&self, other: &Array<N>, mode: Option<impl ConvolveModeType>) -> Result<Array<N>, ArrayError> {
        self.clone()?.convolve(other, mode)
    }

    fn clip(&self, a_min: Option<Array<N>>, a_max: Option<Array<N>>) -> Result<Array<N>, ArrayError> {
        self.clone()?.clip(a_min, a_max)
    }

    fn sqrt(&self) -> Result<Array<N>, ArrayError> {
        self.clone()?.sqrt()
    }

    fn cbrt(&self) -> Result<Array<N>, ArrayError> {
        self.clone()?.cbrt()
    }

    fn square(&self) -> Result<Array<N>, ArrayError> {
        self.clone()?.square()
    }

    fn absolute(&self) -> Result<Array<N>, ArrayError> {
        self.clone()?.absolute()
    }

    fn abs(&self) -> Result<Array<N>, ArrayError> {
        self.clone()?.abs()
    }

    fn fabs(&self) -> Result<Array<N>, ArrayError> {
        self.clone()?.fabs()
    }

    fn sign(&self) -> Result<Array<isize>, ArrayError> {
        self.clone()?.sign()
    }

    fn heaviside(&self, other: &Array<N>) -> Result<Array<N>, ArrayError> {
        self.clone()?.heaviside(other)
    }

    fn nan_to_num(&self) -> Result<Array<N>, ArrayError> {
        self.clone()?.nan_to_num()
    }
}