Skip to main content

lib_jsl_dsp/discrete/spectral/
music.rs

1//! MUSIC (MUltiple SIgnal Classification) spectral estimation.
2//!
3//! MUSIC is a subspace method. The covariance matrix of the data has `p` large eigenvalues
4//! (signal plus noise) and `m - p` equal small ones (noise only). The eigenvectors of the small
5//! eigenvalues span the *noise subspace*, which is orthogonal to the steering vectors `a(θ)` of the
6//! true sources. The pseudospectrum
7//!
8//! `P(θ) = 1 / (a(θ)^H E_n E_n^H a(θ))`
9//!
10//! therefore has sharp peaks at the source parameters `θ`, with resolution well beyond the
11//! periodogram's. The core, [`music_pseudospectrum`], is generic over the steering vector, so the
12//! same machinery estimates the frequencies of sinusoids in a time series ([`music`],
13//! [`music_real`]) or the arrival angles of plane waves on a uniform linear array
14//! ([`music_doa`]).
15//!
16//! The number of sources must be known (or estimated separately), and for sinusoids in a *real*
17//! signal each sinusoid counts as two complex exponentials (at `±f`).
18//!
19//! See the book entry [Parametric spectra: linear prediction, Burg and MUSIC](https://jwkunz.github.io/lib_jsl/book/spectral/parametric.html#music).
20
21use lib_jsl_core::ErrorsJSL;
22use ndarray::{Array1, Array2};
23use lib_jsl_linalg::{Eigh, UPLO};
24use num_complex::Complex;
25use std::f64::consts::TAU;
26
27/// Estimates the `m × m` covariance matrix of a time series from its overlapping length-`m`
28/// snapshots `[x[i], …, x[i+m-1]]`. With `forward_backward` the estimate is averaged with its
29/// conjugate-reversed counterpart, which decorrelates coherent sources and halves the variance.
30pub fn sample_covariance(x: &[Complex<f64>], m: usize, forward_backward: bool) -> Result<Array2<Complex<f64>>, ErrorsJSL> {
31    if m < 2 || x.len() < m + 1 {
32        return Err(ErrorsJSL::InvalidInputRange("Need a window of at least 2 samples and more samples than the window"));
33    }
34    let k = x.len() - m + 1;
35    let mut r = Array2::<Complex<f64>>::zeros((m, m));
36    for s in 0..k {
37        for i in 0..m {
38            for j in 0..m {
39                r[(i, j)] += x[s + i] * x[s + j].conj();
40            }
41        }
42    }
43    r.mapv_inplace(|v| v / k as f64);
44    if forward_backward {
45        let jrj = Array2::from_shape_fn((m, m), |(i, j)| r[(m - 1 - i, m - 1 - j)].conj());
46        r = (r + jrj) * 0.5;
47    }
48    Ok(r)
49}
50
51/// Covariance matrix `E[x x^H]` of array data given as `sensors × snapshots`.
52pub fn covariance_from_snapshots(snapshots: &Array2<Complex<f64>>) -> Result<Array2<Complex<f64>>, ErrorsJSL> {
53    let (m, k) = snapshots.dim();
54    if m < 2 || k == 0 {
55        return Err(ErrorsJSL::InvalidInputRange("Need at least 2 sensors and 1 snapshot"));
56    }
57    let mut r = Array2::<Complex<f64>>::zeros((m, m));
58    for s in 0..k {
59        for i in 0..m {
60            for j in 0..m {
61                r[(i, j)] += snapshots[(i, s)] * snapshots[(j, s)].conj();
62            }
63        }
64    }
65    Ok(r.mapv(|v| v / k as f64))
66}
67
68/// Largest residual `|R v - λ v|` over the eigenpairs.
69fn eigen_residual(r: &Array2<Complex<f64>>, values: &[f64], vectors: &Array2<Complex<f64>>) -> f64 {
70    let m = values.len();
71    (0..m)
72        .map(|c| {
73            (0..m)
74                .map(|row| ((0..m).map(|k| r[(row, k)] * vectors[(k, c)]).sum::<Complex<f64>>() - vectors[(row, c)] * values[c]).norm_sqr())
75                .sum::<f64>()
76                .sqrt()
77        })
78        .fold(0.0, f64::max)
79}
80
81/// Eigenvalues (descending) and the matching eigenvectors (columns) of a Hermitian matrix,
82/// verified against `R v = λ v`.
83fn hermitian_eigen(r: &Array2<Complex<f64>>) -> Result<(Vec<f64>, Array2<Complex<f64>>), ErrorsJSL> {
84    let (vals, vecs) = r.eigh(UPLO::Lower).map_err(|_| ErrorsJSL::RuntimeError("Hermitian eigendecomposition failed"))?;
85    let m = vals.len();
86    let order: Vec<usize> = (0..m).rev().collect(); // eigh returns ascending order
87    let sorted: Vec<f64> = order.iter().map(|&i| vals[i]).collect();
88    let vectors = Array2::from_shape_fn((m, m), |(r_, c)| vecs[(r_, order[c])]);
89    let scale = sorted.iter().fold(0.0f64, |a, v| a.max(v.abs())).max(1e-300);
90    if eigen_residual(r, &sorted, &vectors) > 1e-8 * scale {
91        return Err(ErrorsJSL::RuntimeError("Eigendecomposition did not satisfy R v = lambda v"));
92    }
93    Ok((sorted, vectors))
94}
95
96/// The eigenvalues of a Hermitian covariance matrix, largest first.
97pub fn covariance_eigenvalues(covariance: &Array2<Complex<f64>>) -> Result<Vec<f64>, ErrorsJSL> {
98    Ok(hermitian_eigen(covariance)?.0)
99}
100
101/// MUSIC pseudospectrum of a covariance matrix.
102///
103/// `steering(θ)` returns the length-`m` steering vector for parameter `θ`; the pseudospectrum is
104/// evaluated at every value in `grid`. `num_sources` must be less than `m`.
105pub fn music_pseudospectrum<F>(covariance: &Array2<Complex<f64>>, num_sources: usize, steering: F, grid: &[f64]) -> Result<Vec<f64>, ErrorsJSL>
106where
107    F: Fn(f64) -> Vec<Complex<f64>>,
108{
109    let m = covariance.nrows();
110    if covariance.ncols() != m {
111        return Err(ErrorsJSL::IncompatibleArraySizes((m, covariance.ncols())));
112    }
113    if num_sources == 0 || num_sources >= m {
114        return Err(ErrorsJSL::InvalidInputRange("MUSIC needs 1 <= num_sources < covariance size"));
115    }
116    // ANCHOR: music
117    let (_, vectors) = hermitian_eigen(covariance)?;
118    let noise = vectors.slice(ndarray::s![.., num_sources..]).to_owned();
119    grid.iter()
120        .map(|&theta| {
121            let a = Array1::from(steering(theta));
122            if a.len() != m {
123                return Err(ErrorsJSL::IncompatibleArraySizes((a.len(), m)));
124            }
125            let proj: f64 = (0..noise.ncols()).map(|c| (0..m).map(|r| noise[(r, c)].conj() * a[r]).sum::<Complex<f64>>().norm_sqr()).sum();
126            Ok(1.0 / proj.max(f64::MIN_POSITIVE))
127        })
128        .collect()
129    // ANCHOR_END: music
130}
131
132/// A MUSIC frequency pseudospectrum.
133#[derive(Clone, Debug, PartialEq)]
134pub struct MusicSpectrum {
135    /// Frequency grid in Hz.
136    pub frequencies: Vec<f64>,
137    /// Pseudospectrum on that grid (a sharpness measure, not a power).
138    pub pseudospectrum: Vec<f64>,
139    /// Covariance eigenvalues, largest first; a clear gap after `num_sources` confirms the order.
140    pub eigenvalues: Vec<f64>,
141}
142
143impl MusicSpectrum {
144    /// The `count` highest local maxima of the pseudospectrum, as frequencies in Hz sorted
145    /// ascending, each refined by a parabolic fit of the log-pseudospectrum around its peak.
146    pub fn peak_frequencies(&self, count: usize) -> Vec<f64> {
147        let p = &self.pseudospectrum;
148        let mut peaks: Vec<usize> = (1..p.len().saturating_sub(1)).filter(|&i| p[i] > p[i - 1] && p[i] >= p[i + 1]).collect();
149        peaks.sort_by(|&a, &b| p[b].partial_cmp(&p[a]).unwrap());
150        peaks.truncate(count);
151        let mut freqs: Vec<f64> = peaks
152            .into_iter()
153            .map(|i| {
154                let (l, c, r) = (p[i - 1].ln(), p[i].ln(), p[i + 1].ln());
155                let denom = l - 2.0 * c + r;
156                let delta = if denom.abs() > 1e-300 { 0.5 * (l - r) / denom } else { 0.0 };
157                self.frequencies[i] + delta.clamp(-1.0, 1.0) * (self.frequencies[i + 1] - self.frequencies[i])
158            })
159            .collect();
160        freqs.sort_by(|a, b| a.partial_cmp(b).unwrap());
161        freqs
162    }
163}
164
165fn frequency_steering(m: usize, sample_rate: f64) -> impl Fn(f64) -> Vec<Complex<f64>> {
166    move |f| (0..m).map(|k| Complex::from_polar(1.0, TAU * f / sample_rate * k as f64)).collect()
167}
168
169/// MUSIC frequency estimation for a complex signal containing `num_sources` complex exponentials.
170///
171/// `window` is the covariance size `m` (`num_sources < window`, and larger windows give sharper
172/// peaks at higher cost). The pseudospectrum is evaluated at `num_points` frequencies spanning
173/// `[-sample_rate/2, sample_rate/2)`.
174pub fn music(x: &[Complex<f64>], num_sources: usize, window: usize, num_points: usize, sample_rate: f64) -> Result<MusicSpectrum, ErrorsJSL> {
175    if num_points < 3 || !(sample_rate > 0.0) {
176        return Err(ErrorsJSL::InvalidInputRange("Need at least 3 grid points and a positive sample rate"));
177    }
178    let r = sample_covariance(x, window, true)?;
179    let frequencies: Vec<f64> = (0..num_points).map(|i| (i as f64 / num_points as f64 - 0.5) * sample_rate).collect();
180    let pseudospectrum = music_pseudospectrum(&r, num_sources, frequency_steering(window, sample_rate), &frequencies)?;
181    Ok(MusicSpectrum { frequencies, pseudospectrum, eigenvalues: covariance_eigenvalues(&r)? })
182}
183
184/// MUSIC frequency estimation for a *real* signal containing `num_sinusoids` real sinusoids (each
185/// is two complex exponentials, so the signal subspace has dimension `2 * num_sinusoids`). The
186/// grid spans `[0, sample_rate/2]`.
187pub fn music_real(x: &[f64], num_sinusoids: usize, window: usize, num_points: usize, sample_rate: f64) -> Result<MusicSpectrum, ErrorsJSL> {
188    if num_points < 3 || !(sample_rate > 0.0) {
189        return Err(ErrorsJSL::InvalidInputRange("Need at least 3 grid points and a positive sample rate"));
190    }
191    let xc: Vec<Complex<f64>> = x.iter().map(|&v| Complex::new(v, 0.0)).collect();
192    let r = sample_covariance(&xc, window, true)?;
193    let frequencies: Vec<f64> = (0..num_points).map(|i| 0.5 * sample_rate * i as f64 / (num_points - 1) as f64).collect();
194    let pseudospectrum = music_pseudospectrum(&r, 2 * num_sinusoids, frequency_steering(window, sample_rate), &frequencies)?;
195    Ok(MusicSpectrum { frequencies, pseudospectrum, eigenvalues: covariance_eigenvalues(&r)? })
196}
197
198/// MUSIC direction-of-arrival pseudospectrum for a uniform linear array.
199///
200/// `covariance` is the sensor covariance; `spacing` is the element spacing in wavelengths (0.5 for
201/// the usual half-wavelength array); `angles_deg` are the candidate arrival angles measured from
202/// broadside. Returns the pseudospectrum at each angle.
203pub fn music_doa(covariance: &Array2<Complex<f64>>, num_sources: usize, spacing: f64, angles_deg: &[f64]) -> Result<Vec<f64>, ErrorsJSL> {
204    let m = covariance.nrows();
205    music_pseudospectrum(
206        covariance,
207        num_sources,
208        move |deg| (0..m).map(|k| Complex::from_polar(1.0, TAU * spacing * k as f64 * deg.to_radians().sin())).collect(),
209        angles_deg,
210    )
211}
212
213#[cfg(test)]
214mod tests {
215    use super::*;
216
217    fn lcg(seed: &mut u64) -> f64 {
218        *seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
219        ((*seed >> 33) as f64 / (1u64 << 31) as f64) - 0.5
220    }
221
222    fn gauss(seed: &mut u64) -> f64 {
223        (0..12).map(|_| lcg(seed)).sum::<f64>()
224    }
225
226    fn cgauss(seed: &mut u64, sigma: f64) -> Complex<f64> {
227        Complex::new(gauss(seed), gauss(seed)) * (sigma / 2f64.sqrt())
228    }
229
230    #[test]
231    fn estimates_complex_exponential_frequencies() {
232        let mut seed = 1;
233        let freqs = [0.12, -0.31]; // cycles per sample
234        let x: Vec<Complex<f64>> = (0..256)
235            .map(|n| freqs.iter().map(|f| Complex::from_polar(1.0, TAU * f * n as f64)).sum::<Complex<f64>>() + cgauss(&mut seed, 0.1))
236            .collect();
237        let spec = music(&x, 2, 24, 4096, 1.0).unwrap();
238        let est = spec.peak_frequencies(2);
239        assert!((est[0] + 0.31).abs() < 1e-3 && (est[1] - 0.12).abs() < 1e-3, "{est:?}");
240        // The eigenvalues show two strong components over a noise floor.
241        assert!(spec.eigenvalues[1] > 20.0 * spec.eigenvalues[2], "{:?}", &spec.eigenvalues[..4]);
242    }
243
244    #[test]
245    fn resolves_two_close_real_sinusoids() {
246        let mut seed = 2;
247        let fs = 8000.0;
248        let x: Vec<f64> = (0..400)
249            .map(|n| {
250                let t = n as f64 / fs;
251                (TAU * 440.0 * t).sin() + (TAU * 460.0 * t + 0.7).sin() + 0.1 * gauss(&mut seed)
252            })
253            .collect();
254        // 20 Hz apart is 1.0 DFT bin of this 400-sample record: the periodogram cannot resolve them.
255        let spec = music_real(&x, 2, 60, 4001, fs).unwrap();
256        let est = spec.peak_frequencies(2);
257        assert!((est[0] - 440.0).abs() < 1.0 && (est[1] - 460.0).abs() < 1.0, "{est:?}");
258    }
259
260    #[test]
261    fn finds_arrival_angles_on_a_uniform_linear_array() {
262        let mut seed = 3;
263        let (sensors, snapshots) = (8, 500);
264        let angles: [f64; 2] = [-20.0, 35.0];
265        let steer = |deg: f64| -> Vec<Complex<f64>> { (0..sensors).map(|k| Complex::from_polar(1.0, std::f64::consts::PI * k as f64 * deg.to_radians().sin())).collect() };
266        let data = Array2::from_shape_fn((sensors, snapshots), |_| Complex::new(0.0, 0.0));
267        let mut data = data;
268        for s in 0..snapshots {
269            let amps = [cgauss(&mut seed, 1.0), cgauss(&mut seed, 1.0)];
270            for (a, &deg) in amps.iter().zip(&angles) {
271                for (k, sv) in steer(deg).iter().enumerate() {
272                    data[(k, s)] += a * sv;
273                }
274            }
275            for k in 0..sensors {
276                data[(k, s)] += cgauss(&mut seed, 0.1);
277            }
278        }
279        let r = covariance_from_snapshots(&data).unwrap();
280        let grid: Vec<f64> = (0..3601).map(|i| -90.0 + 0.05 * i as f64).collect();
281        let p = music_doa(&r, 2, 0.5, &grid).unwrap();
282        let spec = MusicSpectrum { frequencies: grid, pseudospectrum: p, eigenvalues: covariance_eigenvalues(&r).unwrap() };
283        let est = spec.peak_frequencies(2);
284        assert!((est[0] + 20.0).abs() < 0.5 && (est[1] - 35.0).abs() < 0.5, "{est:?}");
285        assert!(spec.eigenvalues[1] > 10.0 * spec.eigenvalues[2]);
286    }
287
288    #[test]
289    fn forward_backward_covariance_is_hermitian_and_persymmetric() {
290        let mut seed = 4;
291        let x: Vec<Complex<f64>> = (0..60).map(|_| cgauss(&mut seed, 1.0)).collect();
292        let r = sample_covariance(&x, 6, true).unwrap();
293        for i in 0..6 {
294            for j in 0..6 {
295                assert!((r[(i, j)] - r[(j, i)].conj()).norm() < 1e-12, "Hermitian");
296                assert!((r[(i, j)] - r[(5 - j, 5 - i)]).norm() < 1e-12, "persymmetric");
297            }
298        }
299        let plain = sample_covariance(&x, 6, false).unwrap();
300        assert!(plain.diag().iter().all(|d| d.im.abs() < 1e-12 && d.re > 0.0));
301    }
302
303    #[test]
304    fn a_noise_free_exponential_has_rank_one() {
305        let x: Vec<Complex<f64>> = (0..100).map(|n| Complex::from_polar(2.0, TAU * 0.2 * n as f64)).collect();
306        let ev = covariance_eigenvalues(&sample_covariance(&x, 8, false).unwrap()).unwrap();
307        assert!((ev[0] - 8.0 * 4.0).abs() < 1e-8, "{ev:?}");
308        assert!(ev[1].abs() < 1e-8);
309    }
310
311    #[test]
312    fn invalid_arguments() {
313        let x = vec![Complex::new(1.0, 0.0); 20];
314        assert!(music(&x, 4, 4, 100, 1.0).is_err(), "sources must be fewer than the window");
315        assert!(music(&x, 0, 4, 100, 1.0).is_err());
316        assert!(music(&x, 1, 25, 100, 1.0).is_err(), "window longer than the data");
317        assert!(music(&x, 1, 4, 2, 1.0).is_err());
318        assert!(music_real(&[0.0; 20], 1, 6, 100, 0.0).is_err());
319        assert!(sample_covariance(&x, 1, false).is_err());
320        let r = Array2::<Complex<f64>>::eye(4);
321        assert!(music_pseudospectrum(&r, 1, |_| vec![Complex::new(1.0, 0.0); 3], &[0.0]).is_err(), "wrong steering length");
322    }
323}