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
use core::ops::{AddAssign, MulAssign, SubAssign};

use num::{complex::ComplexFloat, traits::float::FloatConst, Complex, Float, NumCast, One, Zero};
use option_trait::Maybe;
use array_math::SliceMath;

use crate::{systems::Ar, quantities::{ContainerOrSingle, List, ListOrSingle, Lists, MaybeList}, System};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PsdMethod
{
    Fft,
    Polynomial
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PsdRange
{
    Whole,
    Shift,
    Half
}

pub trait Psd<'a, P, F, N, FF, R, M>: System
where
    P: Lists<<Self::Set as ComplexFloat>::Real>,
    F: List<<Self::Set as ComplexFloat>::Real>,
    N: Maybe<usize>,
    FF: Maybe<F>,
    M: Maybe<PsdMethod>,
    R: Maybe<PsdRange>
{
    fn psd<FS>(&'a self, numtaps: N, frequencies: FF, sampling_frequency: FS, range: R, method: M) -> (P, F)
    where
        FS: Maybe<<Self::Set as ComplexFloat>::Real>;
}

impl<'a, T, A, AV, N, M, R> Psd<'a, AV::Mapped<Vec<T::Real>>, Vec<T::Real>, N, (), R, M> for Ar<T, A, AV>
where
    T: ComplexFloat<Real: SubAssign + AddAssign> + Into<Complex<T::Real>>,
    A: MaybeList<T>,
    AV: ListOrSingle<(A, T::Real)>,
    AV::Mapped<Vec<T::Real>>: Lists<T::Real>,
    N: Maybe<usize>,
    M: Maybe<PsdMethod>,
    R: Maybe<PsdRange>,
    Complex<T::Real>: MulAssign + AddAssign
{
    fn psd<FS>(&'a self, numtaps: N, (): (), sampling_frequency: FS, range: R, method: M) -> (AV::Mapped<Vec<T::Real>>, Vec<T::Real>)
    where
        FS: Maybe<<Self::Set as ComplexFloat>::Real>
    {
        let one = T::Real::one();
        let two = one + one;

        let freq_len = numtaps.into_option()
            .unwrap_or(256);
        let freq_lenf = <T::Real as NumCast>::from(freq_len).unwrap();
        let fs = sampling_frequency.into_option()
            .unwrap_or(T::Real::TAU());
        let range = range.into_option()
            .unwrap_or(PsdRange::Whole);

        let w = fs/freq_lenf;
        let freq: Vec<_> = (0..if range == PsdRange::Half {freq_len/2 + 1} else {freq_len}).map(|i| {
            let mut i = <T::Real as NumCast>::from(i).unwrap();
            if range == PsdRange::Shift
            {
                i -= Float::floor(freq_lenf/two)
            }
            w*i
        }).collect();

        let method = method.into_option()
            .unwrap_or_else(|| if freq_len.is_power_of_two()
            {
                PsdMethod::Fft
            }
            else
            {
                PsdMethod::Polynomial
            });
        
        if method == PsdMethod::Polynomial
        {
            return self.psd((), freq, fs, (), ())
        }

        let psd = self.av.map_to_owned(|(a, v)| {
            let a = a.to_vec_option()
                .unwrap_or_else(|| vec![]);

            let mut fft_out: Vec<_> = a.into_iter()
                .map(|a| a.into())
                .collect();
            fft_out.resize(freq_len, Complex::zero());
            fft_out.fft();

            let vdfs = *v/fs;

            let mut psd: Vec<_> = fft_out.into_iter()
                .map(|o| vdfs/(o.conj()*o).re)
                .collect();
            match range
            {
                PsdRange::Shift => psd.rotate_right(freq_len/2),
                PsdRange::Half => {
                    let psd2 = psd.split_off(freq_len/2 + 1);
                    let psd0 = psd[0];
                    for (p, o) in psd.iter_mut()
                        .zip(core::iter::once(psd0)
                            .chain(psd2.into_iter()
                                .rev()
                            )
                        )
                    {
                        *p += o
                    }
                },
                PsdRange::Whole => ()
            }

            psd
        });

        (psd, freq)
    }
}

impl<'a, T, A, AV, M, R, const N: usize> Psd<'a, AV::Mapped<[T::Real; N]>, [T::Real; N], (), (), R, M> for Ar<T, A, AV>
where
    T: ComplexFloat,
    A: MaybeList<T>,
    AV: ListOrSingle<(A, T::Real)>,
    AV::Mapped<[T::Real; N]>: Lists<T::Real>,
    M: Maybe<PsdMethod>,
    R: Maybe<PsdRange>,
    Self: Psd<'a, AV::Mapped<Vec<T::Real>>, Vec<T::Real>, usize, (), PsdRange, M> + System<Set = T>,
    AV::Mapped<Vec<T::Real>>: Lists<T::Real> + ListOrSingle<Vec<T::Real>, Mapped<[T::Real; N]> = AV::Mapped<[T::Real; N]>>
{
    fn psd<FS>(&'a self, (): (), (): (), sampling_frequency: FS, range: R, method: M) -> (AV::Mapped<[T::Real; N]>, [T::Real; N])
    where
        FS: Maybe<<Self::Set as ComplexFloat>::Real>
    {
        if N == 0
        {
            return (self.av.map_to_owned(|_| [T::Real::zero(); N]), [T::Real::zero(); N])
        }
        
        let range = range.into_option()
            .unwrap_or(PsdRange::Whole);

        let numtaps = if range == PsdRange::Half
        {
            (N - 1)*2
        }
        else
        {
            N
        };

        let (psd, f) = self.psd(numtaps, (), sampling_frequency, range, method);

        (
            psd.map_into_owned(|psd: Vec<T::Real>| TryInto::<[T::Real; N]>::try_into(psd).ok().unwrap()),
            f.try_into().ok().unwrap()
        )
    }
}

impl<'a, T, A, AV, FF> Psd<'a, AV::Mapped<FF::Mapped<T::Real>>, FF, (), FF, (), ()> for Ar<T, A, AV>
where
    T: ComplexFloat + Into<Complex<T::Real>>,
    A: MaybeList<T>,
    AV: ListOrSingle<(A, T::Real)>,
    FF: List<T::Real>,
    AV::Mapped<FF::Mapped<T::Real>>: Lists<T::Real>,
    Complex<T::Real>: AddAssign + MulAssign
{
    fn psd<FS>(&'a self, (): (), frequencies: FF, sampling_frequency: FS, (): (), (): ()) -> (AV::Mapped<FF::Mapped<T::Real>>, FF)
    where
        FS: Maybe<<Self::Set as ComplexFloat>::Real>
    {
        let fs = sampling_frequency.into_option()
            .unwrap_or(T::Real::TAU());
        
        let w = T::Real::TAU()/fs;
        
        let psd = self.av.map_to_owned(|(a, v)| {
            let a: Vec<_> = a.to_vec_option()
                .unwrap_or_else(|| vec![])
                .into_iter()
                .map(|a| a.into())
                .collect();

            let vdfs = *v/fs;

            frequencies.map_to_owned(|&f| {
                let o = a.polynomial(Complex::cis(-w*f));
                vdfs/(o.conj()*o).re
            })
        });

        (psd, frequencies)
    }
}

#[cfg(test)]
mod test
{
    use array_math::ArrayOps;

    use crate::{plot, systems::Ar, analysis::Psd};

    #[test]
    fn test()
    {
        let ar = Ar::new(([1.0, 2.0, 3.0], 4.0));

        const N: usize = 1024;
        let (psd, f): ([_; N], _) = ar.psd((), (), (), (), ());

        plot::plot_curves("P(e^jw)", "plots/p_z_psd.png", [&f.zip(psd)])
            .unwrap();
    }
}