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
use super::super::{
    ComplexNumberSpace, Domain, DspVec, ErrorReason, MetaData, RealNumberSpace, ScalarResult,
    ToSlice, ToSliceMut,
};
use crate::inline_vector::InlineVector;
use crate::multicore_support::*;
use crate::numbers::*;
use crate::{array_to_complex, array_to_complex_mut};

/// Operations which allow to iterate over the vector and to derive results
/// or to change the vector.
pub trait MapInplaceOps<T>: Sized
where
    T: Sized,
{
    /// Transforms all vector elements using the function `map`.
    fn map_inplace<'a, A, F>(&mut self, argument: A, map: &F)
    where
        A: Sync + Copy + Send,
        F: Fn(T, usize, A) -> T + 'a + Sync;
}

/// Operations which allow to iterate over the vector and to derive results.
pub trait MapAggregateOps<T, R>: Sized
where
    T: Sized,
    R: Send,
{
    type Output;
    /// Transforms all vector elements using the function `map` and then aggregates
    /// all the results with `aggregate`. `aggregate` must be a commutativity and associativity;
    /// that's because there is no guarantee that the numbers will
    /// be aggregated in any deterministic order.
    fn map_aggregate<'a, A, FMap, FAggr>(
        &self,
        argument: A,
        map: &FMap,
        aggregate: &FAggr,
    ) -> Self::Output
    where
        A: Sync + Copy + Send,
        FMap: Fn(T, usize, A) -> R + 'a + Sync,
        FAggr: Fn(R, R) -> R + 'a + Sync + Send;
}

impl<S, T, N, D> MapInplaceOps<T> for DspVec<S, T, N, D>
where
    S: ToSliceMut<T>,
    T: RealNumber,
    N: RealNumberSpace,
    D: Domain,
{
    fn map_inplace<'a, A, F>(&mut self, argument: A, map: &F)
    where
        A: Sync + Copy + Send,
        F: Fn(T, usize, A) -> T + 'a + Sync,
    {
        if self.is_complex() {
            self.mark_vector_as_invalid();
            return;
        }

        let array = self.data.to_slice_mut();
        let length = array.len();
        Chunk::execute_with_range(
            Complexity::Small,
            &self.multicore_settings,
            &mut array[0..length],
            1,
            argument,
            move |array, range, argument| {
                let mut i = range.start;
                for num in array {
                    *num = map(*num, i, argument);
                    i += 1;
                }
            },
        );
    }
}

impl<S, T, N, D, R> MapAggregateOps<T, R> for DspVec<S, T, N, D>
where
    S: ToSlice<T>,
    T: RealNumber,
    N: RealNumberSpace,
    D: Domain,
    R: Send,
{
    type Output = ScalarResult<R>;

    fn map_aggregate<'a, A, FMap, FAggr>(
        &self,
        argument: A,
        map: &FMap,
        aggregate: &FAggr,
    ) -> ScalarResult<R>
    where
        A: Sync + Copy + Send,
        FMap: Fn(T, usize, A) -> R + 'a + Sync,
        FAggr: Fn(R, R) -> R + 'a + Sync + Send,
    {
        let mut result = {
            if self.is_complex() {
                return Err(ErrorReason::InputMustBeReal);
            }

            let array = self.data.to_slice();
            let length = array.len();
            if length == 0 {
                return Err(ErrorReason::InputMustNotBeEmpty);
            }
            Chunk::map_on_array_chunks(
                Complexity::Small,
                &self.multicore_settings,
                &array[0..length],
                1,
                argument,
                move |array, range, argument| {
                    let mut i = range.start;
                    let mut sum: Option<R> = None;
                    for num in array {
                        let res = map(*num, i, argument);
                        sum = match sum {
                            None => Some(res),
                            Some(s) => Some(aggregate(s, res)),
                        };
                        i += 1;
                    }
                    sum
                },
            )
        };
        // Would be nicer if we could use iter().fold(..) but we need
        // the value of R and not just a reference so we can't user an iter
        let mut only_valid_options = InlineVector::with_capacity(result.len());
        for _ in 0..result.len() {
            let elem = result.pop().unwrap();
            match elem {
                None => (),
                Some(e) => only_valid_options.push(e),
            };
        }

        if only_valid_options.is_empty() {
            return Err(ErrorReason::InputMustNotBeEmpty);
        }
        let mut aggregated = only_valid_options.pop().unwrap();
        for _ in 0..only_valid_options.len() {
            aggregated = aggregate(aggregated, only_valid_options.pop().unwrap());
        }
        Ok(aggregated)
    }
}

impl<S, T, N, D> MapInplaceOps<Complex<T>> for DspVec<S, T, N, D>
where
    S: ToSliceMut<T>,
    T: RealNumber,
    N: ComplexNumberSpace,
    D: Domain,
{
    fn map_inplace<'a, A, F>(&mut self, argument: A, map: &F)
    where
        A: Sync + Copy + Send,
        F: Fn(Complex<T>, usize, A) -> Complex<T> + 'a + Sync,
    {
        if !self.is_complex() {
            self.mark_vector_as_invalid();
            return;
        }

        let array = self.data.to_slice_mut();
        let length = array.len();
        Chunk::execute_with_range(
            Complexity::Small,
            &self.multicore_settings,
            &mut array[0..length],
            2,
            argument,
            move |array, range, argument| {
                let mut i = range.start / 2;
                let array = array_to_complex_mut(array);
                for num in array {
                    *num = map(*num, i, argument);
                    i += 1;
                }
            },
        );
    }
}

impl<S, T, N, D, R> MapAggregateOps<Complex<T>, R> for DspVec<S, T, N, D>
where
    S: ToSlice<T>,
    T: RealNumber,
    N: ComplexNumberSpace,
    D: Domain,
    R: Send,
{
    type Output = ScalarResult<R>;

    fn map_aggregate<'a, A, FMap, FAggr>(
        &self,
        argument: A,
        map: &FMap,
        aggregate: &FAggr,
    ) -> ScalarResult<R>
    where
        A: Sync + Copy + Send,
        FMap: Fn(Complex<T>, usize, A) -> R + 'a + Sync,
        FAggr: Fn(R, R) -> R + 'a + Sync + Send,
    {
        let mut result = {
            if !self.is_complex() {
                return Err(ErrorReason::InputMustBeComplex);
            }

            let array = self.data.to_slice();
            let length = array.len();
            if length == 0 {
                return Err(ErrorReason::InputMustNotBeEmpty);
            }
            Chunk::map_on_array_chunks(
                Complexity::Small,
                &self.multicore_settings,
                &array[0..length],
                2,
                argument,
                move |array, range, argument| {
                    let array = array_to_complex(array);
                    let mut i = range.start / 2;
                    let mut sum: Option<R> = None;
                    for num in array {
                        let res = map(*num, i, argument);
                        sum = match sum {
                            None => Some(res),
                            Some(s) => Some(aggregate(s, res)),
                        };
                        i += 1;
                    }
                    sum
                },
            )
        };
        // Would be nicer if we could use iter().fold(..) but we need
        // the value of R and not just a reference so we can't user an iter
        let mut only_valid_options = InlineVector::with_capacity(result.len());
        for _ in 0..result.len() {
            let elem = result.pop().unwrap();
            match elem {
                None => (),
                Some(e) => only_valid_options.push(e),
            };
        }

        if only_valid_options.is_empty() {
            return Err(ErrorReason::InputMustNotBeEmpty);
        }
        let mut aggregated = only_valid_options.pop().unwrap();
        for _ in 0..only_valid_options.len() {
            aggregated = aggregate(aggregated, only_valid_options.pop().unwrap());
        }
        Ok(aggregated)
    }
}