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
299
300
301
302
303
304
305
306
use super::super::{
    Buffer, DataDomain, DspVec, ErrorReason, FrequencyDomainOperations, InsertZerosOpsBuffered,
    MetaData, NumberSpace, RealNumberSpace, RededicateForceOps, ResizeOps, TimeDomain,
    TimeDomainOperations, ToFreqResult, ToSliceMut, TransRes, Vector,
};
use super::fft;
use numbers::*;
use window_functions::*;

/// Defines all operations which are valid on `DataVecs` containing time domain data.
/// # Failures
/// All operations in this trait set `self.len()` to `0` if the vector isn't in time domain.
pub trait TimeToFrequencyDomainOperations<S, T>: ToFreqResult
where
    S: ToSliceMut<T>,
    T: RealNumber,
{
    /// Performs a Fast Fourier Transformation transforming a time domain vector
    /// into a frequency domain vector.
    ///
    /// This version of the FFT neither applies a window nor does it scale the
    /// vector.
    /// # Example
    ///
    /// ```
    /// use std::f32;
    /// use basic_dsp_vector::*;
    /// let vector = vec!(1.0, 0.0, -0.5, 0.8660254, -0.5, -0.8660254).to_complex_time_vec();
    /// let mut buffer = SingleBuffer::new();
    /// let result = vector.plain_fft(&mut buffer);
    /// let actual = &result[..];
    /// let expected = &[0.0, 0.0, 3.0, 0.0, 0.0, 0.0];
    /// assert_eq!(actual.len(), expected.len());
    /// for i in 0..actual.len() {
    ///        assert!(f32::abs(actual[i] - expected[i]) < 1e-4);
    /// }
    /// ```
    fn plain_fft<B>(self, buffer: &mut B) -> Self::FreqResult
    where
        B: for<'a> Buffer<'a, S, T>;

    /// Performs a Fast Fourier Transformation transforming a time domain vector
    /// into a frequency domain vector.
    /// # Unstable
    /// FFTs of real vectors are unstable.
    /// # Example
    ///
    /// ```
    /// use std::f32;
    /// use basic_dsp_vector::*;
    /// let vector = vec!(1.0, 0.0, -0.5, 0.8660254, -0.5, -0.8660254).to_complex_time_vec();
    /// let mut buffer = SingleBuffer::new();
    /// let result = vector.fft(&mut buffer);
    /// let actual = &result[..];
    /// let expected = &[0.0, 0.0, 0.0, 0.0, 3.0, 0.0];
    /// assert_eq!(actual.len(), expected.len());
    /// for i in 0..actual.len() {
    ///        assert!(f32::abs(actual[i] - expected[i]) < 1e-4);
    /// }
    /// ```
    fn fft<B>(self, buffer: &mut B) -> Self::FreqResult
    where
        B: for<'a> Buffer<'a, S, T>;

    /// Applies a FFT window and performs a Fast Fourier Transformation transforming a time
    /// domain vector into a frequency domain vector.
    fn windowed_fft<B>(self, buffer: &mut B, window: &WindowFunction<T>) -> Self::FreqResult
    where
        B: for<'a> Buffer<'a, S, T>;
}

/// Defines all operations which are valid on `DataVecs` containing real time domain data.
/// # Failures
/// All operations in this trait set `self.len()` to `0` if the vector isn't in time domain or
/// with `VectorMustHaveAnOddLength` if `self.points()` isn't and odd number.
pub trait SymmetricTimeToFrequencyDomainOperations<S, T>: ToFreqResult
where
    S: ToSliceMut<T>,
    T: RealNumber,
{
    /// Performs a Symmetric Fast Fourier Transformation under the assumption that `self`
    /// is symmetric around the center. This assumption
    /// isn't verified and no error is raised if the vector isn't symmetric.
    ///
    /// This version of the IFFT neither applies a window nor does it scale the
    /// vector.
    /// # Failures
    /// TransRes may report the following `ErrorReason` members:
    ///
    /// 1. `VectorMustBeReal`: if `self` is in complex number space.
    /// 2. `VectorMustBeInTimeDomain`: if `self` is in frequency domain.
    ///
    /// # Unstable
    /// Symmetric IFFTs are unstable and may only work under certain conditions.
    fn plain_sfft<B>(self, buffer: &mut B) -> TransRes<Self::FreqResult>
    where
        B: for<'a> Buffer<'a, S, T>;

    /// Performs a Symmetric Fast Fourier Transformation under the assumption that `self`
    /// is symmetric around the center. This assumption
    /// isn't verified and no error is raised if the vector isn't symmetric.
    /// # Failures
    /// TransRes may report the following `ErrorReason` members:
    ///
    /// 1. `VectorMustBeReal`: if `self` is in complex number space.
    /// 2. `VectorMustBeInTimeDomain`: if `self` is in frequency domain.
    ///
    /// # Unstable
    /// Symmetric IFFTs are unstable and may only work under certain conditions.
    fn sfft<B>(self, buffer: &mut B) -> TransRes<Self::FreqResult>
    where
        B: for<'a> Buffer<'a, S, T>;

    /// Performs a Symmetric Fast Fourier Transformation under the assumption that `self`
    /// is symmetric around the center. This assumption
    /// isn't verified and no error is raised if the vector isn't symmetric.
    /// # Failures
    /// TransRes may report the following `ErrorReason` members:
    ///
    /// 1. `VectorMustBeReal`: if `self` is in complex number space.
    /// 2. `VectorMustBeInTimeDomain`: if `self` is in frequency domain.
    ///
    /// # Unstable
    /// Symmetric IFFTs are unstable and may only work under certain conditions.
    fn windowed_sfft<B>(
        self,
        buffer: &mut B,
        window: &WindowFunction<T>,
    ) -> TransRes<Self::FreqResult>
    where
        B: for<'a> Buffer<'a, S, T>;
}

impl<S, T, N, D> TimeToFrequencyDomainOperations<S, T> for DspVec<S, T, N, D>
where
    DspVec<S, T, N, D>: ToFreqResult,
    <DspVec<S, T, N, D> as ToFreqResult>::FreqResult:
        RededicateForceOps<DspVec<S, T, N, D>> + FrequencyDomainOperations<S, T>,
    S: ToSliceMut<T>,
    T: RealNumber,
    N: NumberSpace,
    D: TimeDomain,
{
    fn plain_fft<B>(mut self, buffer: &mut B) -> Self::FreqResult
    where
        B: for<'a> Buffer<'a, S, T>,
    {
        if self.domain() != DataDomain::Time {
            self.valid_len = 0;
            self.number_space.to_complex();
            self.domain.to_freq();
            return Self::FreqResult::rededicate_from_force(self);
        }

        if !self.is_complex() {
            self.zero_interleave_b(buffer, 2);
            self.number_space.to_complex();
        }

        fft(&mut self, buffer, false);

        self.domain.to_freq();
        Self::FreqResult::rededicate_from_force(self)
    }

    fn fft<B>(self, buffer: &mut B) -> Self::FreqResult
    where
        B: for<'a> Buffer<'a, S, T>,
    {
        let mut result = self.plain_fft(buffer);
        result.fft_shift();
        result
    }

    fn windowed_fft<B>(mut self, buffer: &mut B, window: &WindowFunction<T>) -> Self::FreqResult
    where
        B: for<'a> Buffer<'a, S, T>,
    {
        self.apply_window(window);
        let mut result = self.plain_fft(buffer);
        result.fft_shift();
        result
    }
}

macro_rules! unmirror {
    ($self_: ident, $points: ident) => {
        let len = $points;
        let len = len / 2 + 1;
        $self_
            .resize(len)
            .expect("Shrinking a vector should always succeed");
    };
}

impl<S, T, N, D> SymmetricTimeToFrequencyDomainOperations<S, T> for DspVec<S, T, N, D>
where
    DspVec<S, T, N, D>: ToFreqResult,
    <DspVec<S, T, N, D> as ToFreqResult>::FreqResult:
        RededicateForceOps<DspVec<S, T, N, D>> + FrequencyDomainOperations<S, T> + ResizeOps,
    S: ToSliceMut<T>,
    T: RealNumber,
    N: RealNumberSpace,
    D: TimeDomain,
{
    fn plain_sfft<B>(mut self, buffer: &mut B) -> TransRes<Self::FreqResult>
    where
        B: for<'a> Buffer<'a, S, T>,
    {
        if self.domain() != DataDomain::Time || self.is_complex() {
            self.valid_len = 0;
            self.number_space.to_complex();
            self.domain.to_freq();
            return Err((
                ErrorReason::InputMustBeInTimeDomain,
                Self::FreqResult::rededicate_from_force(self),
            ));
        }

        if self.points() % 2 == 0 {
            self.valid_len = 0;
            self.number_space.to_complex();
            self.domain.to_freq();
            return Err((
                ErrorReason::InputMustHaveAnOddLength,
                Self::FreqResult::rededicate_from_force(self),
            ));
        }

        self.zero_interleave_b(buffer, 2);
        self.number_space.to_complex();
        let points = self.points();
        let mut result = self.plain_fft(buffer);
        unmirror!(result, points);
        Ok(result)
    }

    fn sfft<B>(mut self, buffer: &mut B) -> TransRes<Self::FreqResult>
    where
        B: for<'a> Buffer<'a, S, T>,
    {
        if self.domain() != DataDomain::Time || self.is_complex() {
            self.valid_len = 0;
            self.number_space.to_complex();
            self.domain.to_freq();
            return Err((
                ErrorReason::InputMustBeInTimeDomain,
                Self::FreqResult::rededicate_from_force(self),
            ));
        }

        if self.points() % 2 == 0 {
            self.valid_len = 0;
            self.number_space.to_complex();
            self.domain.to_freq();
            return Err((
                ErrorReason::InputMustHaveAnOddLength,
                Self::FreqResult::rededicate_from_force(self),
            ));
        }

        self.zero_interleave_b(buffer, 2);
        self.number_space.to_complex();
        let points = self.points();
        let mut result = self.fft(buffer);
        unmirror!(result, points);
        Ok(result)
    }

    fn windowed_sfft<B>(
        mut self,
        buffer: &mut B,
        window: &WindowFunction<T>,
    ) -> TransRes<Self::FreqResult>
    where
        B: for<'a> Buffer<'a, S, T>,
    {
        if self.domain() != DataDomain::Time || self.is_complex() {
            self.valid_len = 0;
            self.number_space.to_complex();
            self.domain.to_freq();
            return Err((
                ErrorReason::InputMustBeInTimeDomain,
                Self::FreqResult::rededicate_from_force(self),
            ));
        }

        if self.points() % 2 == 0 {
            self.valid_len = 0;
            self.number_space.to_complex();
            self.domain.to_freq();
            return Err((
                ErrorReason::InputMustHaveAnOddLength,
                Self::FreqResult::rededicate_from_force(self),
            ));
        }

        self.zero_interleave_b(buffer, 2);
        self.number_space.to_complex();
        self.apply_window(window);
        let points = self.points();
        let mut result = self.fft(buffer);
        unmirror!(result, points);
        Ok(result)
    }
}