Skip to main content

lib_jsl_dsp/discrete/spectral/
linear_predictive_coding.rs

1//! Linear predictive coding (LPC).
2//!
3//! LPC models a signal as the output of an all-pole filter driven by a white excitation: each
4//! sample is predicted from the previous `order` samples, `x̂[n] = -Σ_{k=1}^{p} a[k] x[n-k]`, and the
5//! coefficients minimise the prediction error power. Writing `A(z) = 1 + a[1] z^-1 + … + a[p] z^-p`,
6//! the *analysis* filter `A(z)` whitens the signal into the residual, and the *synthesis* filter
7//! `1 / A(z)` rebuilds the signal from it. The all-pole spectrum `σ² / |A(e^{jω})|²` is a smooth
8//! estimate of the signal's spectral envelope, which is why LPC underlies speech coding.
9//!
10//! The coefficients here come from the *autocorrelation method*: the autocorrelation sequence is
11//! computed (implicitly windowing the signal with zeros outside the record) and the resulting
12//! Toeplitz normal equations are solved with the Levinson-Durbin recursion, which also yields the
13//! reflection (PARCOR) coefficients. The autocorrelation method always gives a stable synthesis
14//! filter (all reflection coefficients have magnitude below one).
15//!
16//! See the book entry [Parametric spectra: linear prediction, Burg and MUSIC](https://jwkunz.github.io/lib_jsl/book/spectral/parametric.html#linear-prediction-and-the-yule-walker-equations).
17
18use lib_jsl_core::ErrorsJSL;
19
20/// The result of an LPC analysis.
21#[derive(Clone, Debug, PartialEq)]
22#[non_exhaustive]
23pub struct LpcResult {
24    /// `A(z)` coefficients `[1, a1, …, ap]` (length `order + 1`).
25    pub coefficients: Vec<f64>,
26    /// Reflection (PARCOR) coefficients `k1 … kp`; `|k| < 1` means the synthesis filter is stable.
27    pub reflection: Vec<f64>,
28    /// Prediction error power after the final stage (`r[0] ∏(1 - k²)`).
29    pub error_power: f64,
30}
31
32/// Biased autocorrelation estimate `r[k] = Σ_n x[n] x[n+k]` for lags `0..=max_lag`.
33pub fn autocorrelation(x: &[f64], max_lag: usize) -> Vec<f64> {
34    (0..=max_lag).map(|k| x.iter().zip(x.iter().skip(k)).map(|(a, b)| a * b).sum()).collect()
35}
36
37/// Solves the Toeplitz normal equations for an autocorrelation sequence `r[0..=order]` with the
38/// Levinson-Durbin recursion.
39///
40/// Fails if `r[0]` is not positive or the sequence is not positive-definite to the requested order.
41pub fn levinson_durbin(r: &[f64], order: usize) -> Result<LpcResult, ErrorsJSL> {
42    if order == 0 || r.len() <= order {
43        return Err(ErrorsJSL::InvalidInputRange("Levinson-Durbin needs order >= 1 and order + 1 autocorrelation lags"));
44    }
45    if !(r[0] > 0.0) {
46        return Err(ErrorsJSL::InvalidInputRange("Zero-lag autocorrelation must be positive"));
47    }
48    // ANCHOR: levinson
49    let mut a = vec![0.0; order + 1];
50    a[0] = 1.0;
51    let mut err = r[0];
52    let mut reflection = Vec::with_capacity(order);
53    for m in 1..=order {
54        let acc: f64 = (0..m).map(|k| a[k] * r[m - k]).sum();
55        let k = -acc / err;
56        if !k.is_finite() || k.abs() >= 1.0 + 1e-12 {
57            return Err(ErrorsJSL::RuntimeError("Autocorrelation sequence is not positive-definite"));
58        }
59        let prev = a.clone();
60        for i in 1..m {
61            a[i] = prev[i] + k * prev[m - i];
62        }
63        a[m] = k;
64        reflection.push(k);
65        err *= 1.0 - k * k;
66    }
67    // ANCHOR_END: levinson
68    Ok(LpcResult { coefficients: a, reflection, error_power: err })
69}
70
71/// LPC analysis of `x` by the autocorrelation method.
72///
73/// `order` must be at least 1 and less than the signal length. An all-zero signal is rejected
74/// because it has no defined predictor.
75pub fn linear_predictive_coding(x: &[f64], order: usize) -> Result<LpcResult, ErrorsJSL> {
76    if order == 0 || order >= x.len() {
77        return Err(ErrorsJSL::InvalidInputRange("LPC order must satisfy 1 <= order < signal length"));
78    }
79    levinson_durbin(&autocorrelation(x, order), order)
80}
81
82/// The prediction residual `e = A(z) x` (the analysis filter), same length as `x`, assuming zero
83/// initial conditions.
84pub fn lpc_residual(x: &[f64], coefficients: &[f64]) -> Vec<f64> {
85    (0..x.len())
86        .map(|n| coefficients.iter().enumerate().filter(|(k, _)| *k <= n).map(|(k, a)| a * x[n - k]).sum())
87        .collect()
88}
89
90/// Runs an excitation through the synthesis filter `1 / A(z)`, the inverse of [`lpc_residual`].
91pub fn lpc_synthesize(excitation: &[f64], coefficients: &[f64]) -> Vec<f64> {
92    let mut y = Vec::with_capacity(excitation.len());
93    for (n, &e) in excitation.iter().enumerate() {
94        let feedback: f64 = (1..coefficients.len()).filter(|&k| k <= n).map(|k| coefficients[k] * y[n - k]).sum();
95        y.push(e - feedback);
96    }
97    y
98}
99
100/// Converts reflection coefficients to `A(z)` coefficients (the step-up recursion).
101pub fn reflection_to_lpc(reflection: &[f64]) -> Vec<f64> {
102    let mut a = vec![1.0];
103    for &k in reflection {
104        let mut next = a.clone();
105        next.push(0.0);
106        for i in 1..=a.len() {
107            next[i] += k * a[a.len() - i];
108        }
109        a = next;
110    }
111    a
112}
113
114/// Converts `A(z)` coefficients to reflection coefficients (the step-down recursion). Fails if a
115/// stage has `|k| >= 1` (an unstable or degenerate filter).
116pub fn lpc_to_reflection(coefficients: &[f64]) -> Result<Vec<f64>, ErrorsJSL> {
117    if coefficients.is_empty() || (coefficients[0] - 1.0).abs() > 1e-12 {
118        return Err(ErrorsJSL::InvalidInputRange("LPC coefficients must start with 1"));
119    }
120    let mut a = coefficients.to_vec();
121    let mut k = vec![0.0; a.len() - 1];
122    for m in (1..a.len()).rev() {
123        let km = a[m];
124        if km.abs() >= 1.0 {
125            return Err(ErrorsJSL::RuntimeError("Filter is not strictly stable: |reflection| >= 1"));
126        }
127        k[m - 1] = km;
128        let denom = 1.0 - km * km;
129        let prev = a.clone();
130        for i in 1..m {
131            a[i] = (prev[i] - km * prev[m - i]) / denom;
132        }
133        a.truncate(m);
134    }
135    Ok(k)
136}
137
138#[cfg(test)]
139mod tests {
140    use super::*;
141
142    fn lcg(seed: &mut u64) -> f64 {
143        *seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
144        ((*seed >> 33) as f64 / (1u64 << 31) as f64) - 0.5
145    }
146
147    /// Gaussian-ish unit-variance noise from a sum of uniforms.
148    fn noise(n: usize, seed: &mut u64) -> Vec<f64> {
149        (0..n).map(|_| (0..12).map(|_| lcg(seed)).sum::<f64>()).collect()
150    }
151
152    /// Synthesizes an AR process with `A(z) = 1 + a1 z^-1 + …`.
153    fn ar_process(a: &[f64], n: usize, seed: &mut u64) -> Vec<f64> {
154        lpc_synthesize(&noise(n + 500, seed), a)[500..].to_vec()
155    }
156
157    #[test]
158    fn levinson_solves_a_known_second_order_system() {
159        // r = [1, 0.5, 0.2]: closed form k1 = -r1/r0, a2 = (r1^2 - r0 r2) / (r0^2 - r1^2).
160        let res = levinson_durbin(&[1.0, 0.5, 0.2], 2).unwrap();
161        let a2 = (0.25 - 0.2) / (1.0 - 0.25);
162        let a1 = -0.5 * (1.0 + a2);
163        assert!((res.coefficients[1] - a1).abs() < 1e-12 && (res.coefficients[2] - a2).abs() < 1e-12);
164        assert!((res.reflection[0] + 0.5).abs() < 1e-12 && (res.reflection[1] - a2).abs() < 1e-12);
165        // Error power equals r0 + a1 r1 + a2 r2.
166        assert!((res.error_power - (1.0 + a1 * 0.5 + a2 * 0.2)).abs() < 1e-12);
167    }
168
169    #[test]
170    fn recovers_the_coefficients_of_an_ar_process() {
171        let mut seed = 42;
172        let truth = [1.0, -1.5, 0.9]; // poles at radius ~0.95
173        let x = ar_process(&truth, 50_000, &mut seed);
174        let est = linear_predictive_coding(&x, 2).unwrap();
175        assert!((est.coefficients[1] - truth[1]).abs() < 0.02, "{:?}", est.coefficients);
176        assert!((est.coefficients[2] - truth[2]).abs() < 0.02);
177        assert!((est.error_power / x.len() as f64 - 1.0).abs() < 0.1, "innovation power {}", est.error_power / x.len() as f64);
178        assert!(est.reflection.iter().all(|k| k.abs() < 1.0));
179    }
180
181    #[test]
182    fn a_pure_sinusoid_is_perfectly_predictable_with_two_coefficients() {
183        let w = 0.3;
184        let x: Vec<f64> = (0..400).map(|n| (w * n as f64).sin()).collect();
185        let res = linear_predictive_coding(&x, 2).unwrap();
186        // x[n] = 2 cos(w) x[n-1] - x[n-2]  =>  a = [1, -2cos w, 1]
187        assert!((res.coefficients[1] + 2.0 * w.cos()).abs() < 0.02);
188        assert!((res.coefficients[2] - 1.0).abs() < 0.02);
189        let e = lpc_residual(&x, &res.coefficients);
190        let tail: f64 = e[10..].iter().map(|v| v * v).sum::<f64>() / (e.len() - 10) as f64;
191        assert!(tail < 1e-3, "residual power {tail}");
192    }
193
194    #[test]
195    fn analysis_and_synthesis_are_inverses() {
196        let mut seed = 7;
197        let x = noise(300, &mut seed);
198        let a = [1.0, -0.6, 0.3, -0.1];
199        let e = lpc_residual(&x, &a);
200        let back = lpc_synthesize(&e, &a);
201        assert!(x.iter().zip(&back).all(|(p, q)| (p - q).abs() < 1e-10));
202        // The residual of the true model is white with the innovation variance.
203        let synth = lpc_synthesize(&x, &a);
204        let again = lpc_residual(&synth, &a);
205        assert!(x.iter().zip(&again).all(|(p, q)| (p - q).abs() < 1e-10));
206    }
207
208    #[test]
209    fn reflection_conversions_round_trip() {
210        let mut seed = 3;
211        let x = ar_process(&[1.0, -0.8, 0.5, -0.2], 5000, &mut seed);
212        let res = linear_predictive_coding(&x, 6).unwrap();
213        let rebuilt = reflection_to_lpc(&res.reflection);
214        assert!(rebuilt.iter().zip(&res.coefficients).all(|(p, q)| (p - q).abs() < 1e-12));
215        let k = lpc_to_reflection(&res.coefficients).unwrap();
216        assert!(k.iter().zip(&res.reflection).all(|(p, q)| (p - q).abs() < 1e-9));
217        assert!(lpc_to_reflection(&[1.0, -1.5, 0.6, 2.0]).is_err());
218        assert!(lpc_to_reflection(&[2.0, 1.0]).is_err());
219    }
220
221    #[test]
222    fn prediction_error_decreases_with_order() {
223        let mut seed = 11;
224        let x = ar_process(&[1.0, -1.2, 0.8, -0.3, 0.1], 20_000, &mut seed);
225        let errs: Vec<f64> = (1..=6).map(|p| linear_predictive_coding(&x, p).unwrap().error_power).collect();
226        assert!(errs.windows(2).all(|w| w[1] <= w[0] + 1e-9), "{errs:?}");
227    }
228
229    #[test]
230    fn invalid_arguments() {
231        assert!(linear_predictive_coding(&[1.0, 2.0, 3.0], 0).is_err());
232        assert!(linear_predictive_coding(&[1.0, 2.0, 3.0], 3).is_err());
233        assert!(linear_predictive_coding(&[0.0; 20], 2).is_err());
234        assert!(levinson_durbin(&[1.0, 0.5], 2).is_err());
235        assert!(levinson_durbin(&[1.0, 1.5, 0.0], 2).is_err());
236    }
237}