linear_predictive_coding/
lib.rs

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
use ndarray::prelude::*;
// use ndarray_inverse::Inverse;

/// 自己相関関数を求める関数
/// # Arguments
/// [;N]
///
/// # Returns
/// [;N]
pub fn correlate(a: ArrayView1<f64>) -> Array1<f64> {
    a.iter()
        .enumerate()
        .map(|(n, _)| {
            a.slice(s![n..])
                .iter()
                .zip(a.iter())
                .map(|(x, y)| x * y)
                .sum::<f64>()
        })
        .collect()
}

// pub fn calc_lpc_by_low_speed(a: ArrayView1<f64>, depth: usize) -> Array1<f64> {
//     let r = correlate(a);

//     let mut large_r: Array2<f64> = Array2::zeros((depth, depth));
//     for i in 0..depth {
//         for j in 0..depth {
//             large_r[[i, j]] = r[(i as isize - j as isize).abs() as usize];
//         }
//     }

//     println!("{:?}", large_r);

//     let r = r.slice(s![1..=depth]);

//     println!("{:?}", r);

//     let inverse_large_r = large_r.inv().unwrap();

//     let a = inverse_large_r.dot(&r);

//     let minus_a = a.mapv(|x| -x);

//     minus_a
// }

/// https://qiita.com/hirokisince1998/items/fd50c0515c7788458fce
/// Levinson-Durbin法
pub fn calc_lpc_by_levinson_durbin(a: ArrayView1<f64>, depth: usize) -> Array1<f64> {
    let r = correlate(a);
    println!("{:?}", r);
    let r = r.slice(s![..=depth]);
    println!("{:?}", r);

    fn calc_lpc_by_high_speed_inner(
        a: ArrayView1<f64>,
        depth: usize,
        r: ArrayView1<f64>,
    ) -> (Array1<f64>, f64) {
        if depth == 1 {
            let a = Array1::from_iter(vec![1.0, -r[1] as f64 / r[0]]);
            let e = a.dot(&r.slice(s![..2]));

            // println!("{:?}", a);

            (a, e)
        } else {
            let (aa, ee) = calc_lpc_by_high_speed_inner(a, depth - 1, r);

            let kk = -aa.dot(&r.slice(s![1..=depth; -1])) / ee;

            let large_u = ndarray::concatenate![Axis(0), aa.view(), Array1::from_elem(1, 0.0)];

            let large_v = large_u.slice(s![..; -1]);

            let a = large_u.clone() + large_v.mapv(|x| x * kk);

            let e = ee * (1.0 - kk * kk);

            (a, e)
        }
    }

    let (a, _) = calc_lpc_by_high_speed_inner(a, depth, r.view());

    a.slice_move(s![1..])
}

/// Burg法
pub fn calc_lpc_by_burg(x: ArrayView1<f64>, depth: usize) -> Array1<f64> {
    let mut a = Array1::<f64>::zeros(depth + 1);

    let mut k = Array1::<f64>::zeros(depth);

    a[0] = 1.0;

    let mut f = x.to_owned();

    let mut b = x.to_owned();

    let n = x.len();

    for p in 0..depth {
        let kf = f.slice(s![p + 1..]);
        let kb = b.slice(s![..n - p - 1]);
        // 要素ごとの積
        let d = kf.iter().map(|x| x * x).sum::<f64>() + kb.iter().map(|x| x * x).sum::<f64>();
        k[p] = -2.0 * kf.iter().zip(kb.iter()).map(|(x, y)| x * y).sum::<f64>() / d;
        let u = a.slice(s![..=p + 1]);
        let v = u.slice(s![..; -1]);

        println!("u: {:?}", u);
        println!("v: {:?}", v);

        let added = &u + &v.mapv(|x| x * k[p]);
        a.slice_mut(s![..=p + 1]).assign(&added.view());
        let fu = b.slice(s![..n - p - 1]).mapv(|x| x * k[p]);
        let bu = f.slice(s![p + 1..]).mapv(|x| x * k[p]);
        f.slice_mut(s![p + 1..])
            .iter_mut()
            .zip(fu.iter())
            .for_each(|(x, fu)| *x += *fu);
        b.slice_mut(s![..n - p - 1])
            .iter_mut()
            .zip(bu.iter())
            .for_each(|(x, bu)| *x += bu);
    }

    a.slice_move(s![1..])
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_correlate() {
        let a = Array1::from(vec![2., 3., -1., -2., 1., 4., 1.]);
        let expected = Array1::from(vec![36.0, 11.0, -16.0, -7.0, 13.0, 11.0, 2.0]);
        assert_eq!(correlate(a.view()), expected);
    }

    // #[test]
    // fn test_calc_lpc_by_low_speed() {
    //     let a = Array1::from(vec![2., 3., -1., -2., 1., 4., 1.]);
    //     let depth = 3;
    //     let expected = Array1::from(vec![
    //         -0.6919053749597682,
    //         0.7615062761506275,
    //         -0.34575152880592214,
    //     ]);
    //     assert_eq!(calc_lpc_by_low_speed(a.view(), depth), expected);
    // }

    #[test]
    fn test_calc_lpc_by_high_speed() {
        let a = Array1::from(vec![2., 3., -1., -2., 1., 4., 1.]);
        let depth = 3;
        let expected = Array1::from(vec![
            -0.6919053749597684,
            0.7615062761506278,
            -0.3457515288059223,
        ]);
        assert_eq!(calc_lpc_by_levinson_durbin(a.view(), depth), expected);
    }

    #[test]
    fn test_calc_lpc_by_burg() {
        let a = Array1::from(vec![2., 3., -1., -2., 1., 4., 1.]);
        let depth = 3;
        let expected = Array1::from(vec![
            -1.0650404360323664,
            1.157238171254371,
            -0.5771692748969812,
        ]);
        assert_eq!(calc_lpc_by_burg(a.view(), depth), expected);
    }
}