Skip to main content

lib_jsl_dsp/discrete/spectral/
maximum_entropy.rs

1//! Maximum entropy spectral estimation (Burg's method).
2//!
3//! Among all spectra consistent with a set of measured autocorrelation lags, the *maximum entropy*
4//! one is the all-pole (autoregressive) spectrum `σ² / |A(e^{jω})|²`. Burg's algorithm estimates
5//! the AR model directly from the data by minimising the forward and backward prediction error
6//! together, stage by stage, without first forming an autocorrelation estimate. Compared with the
7//! periodogram it resolves closely spaced sinusoids from short records and never windows the data,
8//! at the price of needing a model order (and, for high orders, spurious peaks).
9//!
10//! See the book entry [Parametric spectra: linear prediction, Burg and MUSIC](https://jwkunz.github.io/lib_jsl/book/spectral/parametric.html#burgs-method).
11
12use lib_jsl_core::ErrorsJSL;
13use std::f64::consts::TAU;
14
15/// The result of Burg's AR estimation.
16#[derive(Clone, Debug, PartialEq)]
17#[non_exhaustive]
18pub struct BurgResult {
19    /// `A(z)` coefficients `[1, a1, …, ap]`.
20    pub coefficients: Vec<f64>,
21    /// Reflection coefficients; always of magnitude below one, so the model is stable.
22    pub reflection: Vec<f64>,
23    /// Estimated variance of the driving white noise (the final prediction error power per sample).
24    pub variance: f64,
25}
26
27/// Burg's method for an AR model of the given `order` (`1 <= order < x.len()`).
28pub fn burg(x: &[f64], order: usize) -> Result<BurgResult, ErrorsJSL> {
29    let n = x.len();
30    if order == 0 || order >= n {
31        return Err(ErrorsJSL::InvalidInputRange("Burg order must satisfy 1 <= order < signal length"));
32    }
33    let mut variance = x.iter().map(|v| v * v).sum::<f64>() / n as f64;
34    if !(variance > 0.0) {
35        return Err(ErrorsJSL::InvalidInputRange("Signal must have nonzero power"));
36    }
37    // ANCHOR: burg
38    let mut f = x.to_vec(); // forward prediction errors
39    let mut b = x.to_vec(); // backward prediction errors
40    let mut a = vec![1.0];
41    let mut reflection = Vec::with_capacity(order);
42    for m in 1..=order {
43        let (mut num, mut den) = (0.0, 0.0);
44        for i in m..n {
45            num += f[i] * b[i - 1];
46            den += f[i] * f[i] + b[i - 1] * b[i - 1];
47        }
48        let k = if den > 0.0 { -2.0 * num / den } else { 0.0 };
49        // Update the error sequences (iterate downwards so b[i-1] is still the old value).
50        for i in (m..n).rev() {
51            let (fi, bi) = (f[i], b[i - 1]);
52            f[i] = fi + k * bi;
53            b[i] = bi + k * fi;
54        }
55        let mut next = a.clone();
56        next.push(0.0);
57        for i in 1..=a.len() {
58            next[i] += k * a[a.len() - i];
59        }
60        a = next;
61        reflection.push(k);
62        variance *= 1.0 - k * k;
63    }
64    // ANCHOR_END: burg
65    Ok(BurgResult { coefficients: a, reflection, variance })
66}
67
68/// Evaluates the all-pole power spectral density `σ² / (fs |A(e^{jω})|²)` at the given
69/// frequencies (Hz), as a two-sided density per Hz.
70pub fn ar_psd(coefficients: &[f64], variance: f64, frequencies: &[f64], sample_rate: f64) -> Vec<f64> {
71    frequencies
72        .iter()
73        .map(|&f| {
74            let w = TAU * f / sample_rate;
75            let (mut re, mut im) = (0.0, 0.0);
76            for (k, a) in coefficients.iter().enumerate() {
77                re += a * (w * k as f64).cos();
78                im -= a * (w * k as f64).sin();
79            }
80            variance / (sample_rate * (re * re + im * im))
81        })
82        .collect()
83}
84
85/// Maximum entropy power spectral density estimate of a real signal from an order-`order` Burg AR
86/// model, on `num_points` evenly spaced frequencies from 0 to Nyquist inclusive.
87///
88/// Returns `(frequencies in Hz, one-sided PSD in units²/Hz)`. The one-sided PSD integrates (over
89/// 0 to `sample_rate / 2`) to the signal power.
90pub fn maximum_entropy_spectrum(x: &[f64], order: usize, num_points: usize, sample_rate: f64) -> Result<(Vec<f64>, Vec<f64>), ErrorsJSL> {
91    if num_points < 2 || !(sample_rate > 0.0) {
92        return Err(ErrorsJSL::InvalidInputRange("Need at least 2 frequency points and a positive sample rate"));
93    }
94    let model = burg(x, order)?;
95    let freqs: Vec<f64> = (0..num_points).map(|i| 0.5 * sample_rate * i as f64 / (num_points - 1) as f64).collect();
96    let mut psd = ar_psd(&model.coefficients, model.variance, &freqs, sample_rate);
97    for (i, p) in psd.iter_mut().enumerate() {
98        if i != 0 && i != num_points - 1 {
99            *p *= 2.0; // fold the negative frequencies in
100        } else {
101            *p *= 1.0;
102        }
103    }
104    Ok((freqs, psd))
105}
106
107#[cfg(test)]
108mod tests {
109    use super::*;
110    use crate::discrete::spectral::linear_predictive_coding::lpc_synthesize;
111
112    fn lcg(seed: &mut u64) -> f64 {
113        *seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
114        ((*seed >> 33) as f64 / (1u64 << 31) as f64) - 0.5
115    }
116
117    fn noise(n: usize, seed: &mut u64) -> Vec<f64> {
118        (0..n).map(|_| (0..12).map(|_| lcg(seed)).sum::<f64>()).collect()
119    }
120
121    #[test]
122    fn recovers_ar_coefficients_and_innovation_variance() {
123        let mut seed = 5;
124        let truth = [1.0, -1.5, 0.9];
125        let x = lpc_synthesize(&noise(30_500, &mut seed), &truth)[500..].to_vec();
126        let m = burg(&x, 2).unwrap();
127        assert!((m.coefficients[1] - truth[1]).abs() < 0.02 && (m.coefficients[2] - truth[2]).abs() < 0.02, "{:?}", m.coefficients);
128        assert!((m.variance - 1.0).abs() < 0.1, "variance {}", m.variance);
129        assert!(m.reflection.iter().all(|k| k.abs() < 1.0));
130    }
131
132    #[test]
133    fn resolves_two_close_sinusoids_from_a_short_record() {
134        // 64 samples, tones 0.10 and 0.125 cycles/sample (spacing 0.025 is 1.6 DFT bins).
135        let mut seed = 9;
136        let n = 64;
137        let x: Vec<f64> = (0..n)
138            .map(|i| {
139                let t = i as f64;
140                (TAU * 0.10 * t).sin() + (TAU * 0.125 * t + 1.0).sin() + 0.05 * lcg(&mut seed)
141            })
142            .collect();
143        let (f, p) = maximum_entropy_spectrum(&x, 12, 2001, 1.0).unwrap();
144        let peaks: Vec<f64> = (1..p.len() - 1).filter(|&i| p[i] > p[i - 1] && p[i] > p[i + 1] && p[i] > 0.01 * p.iter().cloned().fold(0.0, f64::max)).map(|i| f[i]).collect();
145        assert!(peaks.iter().any(|&q| (q - 0.10).abs() < 0.004), "peaks {peaks:?}");
146        assert!(peaks.iter().any(|&q| (q - 0.125).abs() < 0.004), "peaks {peaks:?}");
147    }
148
149    #[test]
150    fn psd_integrates_to_the_signal_power() {
151        let mut seed = 13;
152        let x = lpc_synthesize(&noise(20_500, &mut seed), &[1.0, -0.9, 0.4])[500..].to_vec();
153        let power = x.iter().map(|v| v * v).sum::<f64>() / x.len() as f64;
154        let fs = 8000.0;
155        let (f, p) = maximum_entropy_spectrum(&x, 4, 4001, fs).unwrap();
156        let df = f[1] - f[0];
157        let integral: f64 = p.windows(2).map(|w| 0.5 * (w[0] + w[1]) * df).sum();
158        assert!((integral / power - 1.0).abs() < 0.05, "integral {integral} vs power {power}");
159    }
160
161    #[test]
162    fn matches_the_true_spectrum_of_an_ar_process() {
163        let mut seed = 17;
164        let truth = [1.0, -1.2, 0.72];
165        let x = lpc_synthesize(&noise(60_500, &mut seed), &truth)[500..].to_vec();
166        let m = burg(&x, 2).unwrap();
167        let freqs = [0.0, 0.05, 0.1, 0.2, 0.3, 0.45];
168        let est = ar_psd(&m.coefficients, m.variance, &freqs, 1.0);
169        let exact = ar_psd(&truth, 1.0, &freqs, 1.0);
170        for (e, t) in est.iter().zip(&exact) {
171            assert!((e / t - 1.0).abs() < 0.1, "{e} vs {t}");
172        }
173    }
174
175    #[test]
176    fn invalid_arguments() {
177        assert!(burg(&[1.0, 2.0, 3.0], 0).is_err());
178        assert!(burg(&[1.0, 2.0, 3.0], 3).is_err());
179        assert!(burg(&[0.0; 10], 2).is_err());
180        assert!(maximum_entropy_spectrum(&[1.0, 2.0, 3.0, 2.0, 1.0], 2, 1, 1.0).is_err());
181        assert!(maximum_entropy_spectrum(&[1.0, 2.0, 3.0, 2.0, 1.0], 2, 8, 0.0).is_err());
182    }
183}