Skip to main content

lib_jsl_electromagnetics/algorithms/
direction_of_arrival.rs

1//! Direction-of-arrival estimation on sensor arrays.
2//!
3//! Given an array covariance `R` (estimated from snapshots, see
4//! [`crate::signal_models::covariance::sample_covariance`]), these scan steering vectors
5//! `a(Ω) = A(Ω) p` of any [`SensorArray`] (any geometry, embedded element patterns, a chosen
6//! polarization `p`) over candidate directions:
7//!
8//! * Bartlett (conventional beamforming) `aᴴRa / aᴴa`: robust, resolution limited to a beamwidth;
9//! * Capon (MVDR) `1 / (aᴴR⁻¹a)`: adaptive nulling sharpens the peaks;
10//! * MUSIC `aᴴa / (aᴴ E_n E_nᴴ a)` with the noise subspace `E_n`: super-resolution for a known
11//!   number of sources;
12//!
13//! and ESPRIT estimates the direction cosines of a uniform linear array in closed form from the
14//! rotational invariance between its two overlapping subarrays.
15//!
16//! See the book entry [Direction finding](https://jwkunz.github.io/lib_jsl/book/em-arrays/direction-finding.html).
17
18use crate::arrays::SensorArray;
19use crate::conventions::{C64, TimeConvention};
20use crate::linalg::{check_hermitian, hermitian_eigen, hermitian_transpose};
21use lib_jsl_core::ErrorsJSL;
22use ndarray::{Array1, Array2, s};
23use lib_jsl_linalg::{Eig, Inverse};
24
25fn steering(array: &SensorArray, direction: (f64, f64), polarization: [C64; 2]) -> Result<Array1<C64>, ErrorsJSL> {
26    array.steering_vector(direction.0, direction.1, polarization)
27}
28
29fn hermitian_product(a: &Array1<C64>, m: &Array2<C64>) -> f64 {
30    a.iter().zip(m.dot(a).iter()).map(|(x, y)| (x.conj() * y).re).sum()
31}
32
33fn norm_squared(a: &Array1<C64>) -> f64 {
34    a.iter().map(|v| v.norm_sqr()).sum()
35}
36
37/// The Bartlett spectrum `aᴴRa / aᴴa` at each `(θ, φ)`.
38pub fn bartlett_spectrum(array: &SensorArray, covariance: &Array2<C64>, directions: &[(f64, f64)], polarization: [C64; 2]) -> Result<Vec<f64>, ErrorsJSL> {
39    check_hermitian(covariance, array.len())?;
40    directions.iter().map(|&d| { let a = steering(array, d, polarization)?; Ok(hermitian_product(&a, covariance) / norm_squared(&a)) }).collect()
41}
42
43/// The Capon (minimum variance) spectrum `1 / (aᴴR⁻¹a)`, with `a` normalised to unit norm.
44pub fn capon_spectrum(array: &SensorArray, covariance: &Array2<C64>, directions: &[(f64, f64)], polarization: [C64; 2]) -> Result<Vec<f64>, ErrorsJSL> {
45    check_hermitian(covariance, array.len())?;
46    let inverse = covariance.inv().map_err(|_| ErrorsJSL::RuntimeError("The covariance is singular."))?;
47    directions.iter().map(|&d| { let a = steering(array, d, polarization)?; Ok(norm_squared(&a) / hermitian_product(&a, &inverse)) }).collect()
48}
49
50/// The MUSIC pseudospectrum `aᴴa / (aᴴ E_n E_nᴴ a)` for `sources` signals (fewer than the
51/// number of elements).
52pub fn music_spectrum(array: &SensorArray, covariance: &Array2<C64>, sources: usize, directions: &[(f64, f64)], polarization: [C64; 2]) -> Result<Vec<f64>, ErrorsJSL> {
53    let n = array.len();
54    check_hermitian(covariance, n)?;
55    if sources == 0 || sources >= n {
56        return Err(ErrorsJSL::InvalidInputRange("Need 0 < sources < elements."));
57    }
58    // ANCHOR: music
59    let (_, vectors) = hermitian_eigen(covariance)?;
60    let noise = vectors.slice(s![.., sources..]).to_owned();
61    let projector = noise.dot(&hermitian_transpose(&noise));
62    directions.iter().map(|&d| { let a = steering(array, d, polarization)?; Ok(norm_squared(&a) / hermitian_product(&a, &projector).max(1e-300)) }).collect()
63    // ANCHOR_END: music
64}
65
66/// The indices of the `count` largest local maxima of a spectrum sampled on a 1D grid (ends
67/// count when they exceed their single neighbour), strongest first.
68pub fn spectrum_peaks(spectrum: &[f64], count: usize) -> Vec<usize> {
69    let n = spectrum.len();
70    let mut peaks: Vec<usize> = (0..n)
71        .filter(|&i| (i == 0 || spectrum[i] > spectrum[i - 1]) && (i + 1 == n || spectrum[i] >= spectrum[i + 1]))
72        .collect();
73    peaks.sort_by(|&a, &b| spectrum[b].total_cmp(&spectrum[a]));
74    peaks.truncate(count);
75    peaks
76}
77
78/// ESPRIT for a uniform linear array of elements spaced `spacing` metres apart along its axis
79/// (elements ordered along the axis, identical patterns): returns the `sources` direction
80/// cosines `u = r̂ · axis` (for an array on the x axis in the xy plane, `u = cos φ`).
81pub fn esprit_ula(covariance: &Array2<C64>, sources: usize, spacing: f64, wavenumber: f64, convention: TimeConvention) -> Result<Vec<f64>, ErrorsJSL> {
82    let n = covariance.nrows();
83    check_hermitian(covariance, n)?;
84    if sources == 0 || sources >= n {
85        return Err(ErrorsJSL::InvalidInputRange("Need 0 < sources < elements."));
86    }
87    let (_, vectors) = hermitian_eigen(covariance)?;
88    // ANCHOR: esprit
89    let signal = vectors.slice(s![.., ..sources]).to_owned();
90    let (first, second) = (signal.slice(s![..n - 1, ..]).to_owned(), signal.slice(s![1.., ..]).to_owned());
91    // Least squares Ψ = (E₁ᴴE₁)⁻¹ E₁ᴴ E₂; its eigenvalues are e^{±jkd u}.
92    let e1h = hermitian_transpose(&first);
93    let psi = e1h.dot(&first).inv().map_err(|_| ErrorsJSL::RuntimeError("Degenerate signal subspace."))?.dot(&e1h.dot(&second));
94    let (eigenvalues, _) = psi.eig().map_err(|_| ErrorsJSL::RuntimeError("Eigendecomposition failed."))?;
95    let mut u: Vec<f64> = eigenvalues.iter().map(|l| (l.arg() / (convention.sign() * wavenumber * spacing)).clamp(-1.0, 1.0)).collect();
96    // ANCHOR_END: esprit
97    u.sort_by(f64::total_cmp);
98    Ok(u)
99}
100
101#[cfg(test)]
102mod tests {
103    use super::*;
104    use crate::antenna_models::HertzianDipole;
105    use crate::coordinates::transforms::RigidTransform;
106    use crate::signal_models::covariance::{sample_covariance, synthesize_snapshots};
107    use std::f64::consts::FRAC_PI_2;
108    use std::sync::Arc;
109
110    const F: f64 = 1e9;
111
112    /// An 8-element half-wave-spaced line of z dipoles on the x axis, the scene's true
113    /// covariance for two unit sources at the given azimuths with noise σ², and a sample estimate.
114    fn scene(azimuths_deg: [f64; 2], noise: f64) -> (SensorArray, Array2<C64>) {
115        let lambda = lib_jsl_core::constants::em::C0 / F;
116        let positions = SensorArray::linear_positions(8, lambda / 2.0, [1.0, 0.0, 0.0]);
117        let array = SensorArray::from_antenna(&positions, Arc::new(HertzianDipole::new(0.01)), &RigidTransform::identity(), F, TimeConvention::PlusJ, 1.0).unwrap();
118        let pol = [C64::new(1.0, 0.0), C64::new(0.0, 0.0)];
119        let mut r = Array2::<C64>::eye(8) * C64::new(noise, 0.0);
120        for az in azimuths_deg {
121            let a = array.steering_vector(FRAC_PI_2, az.to_radians(), pol).unwrap();
122            let a = &a / C64::new(norm_squared(&a).sqrt() / 8f64.sqrt(), 0.0);
123            for i in 0..8 {
124                for j in 0..8 {
125                    r[[i, j]] += a[i] * a[j].conj();
126                }
127            }
128        }
129        let snapshots = synthesize_snapshots(&r, 400, 3).unwrap();
130        (array, sample_covariance(&snapshots).unwrap())
131    }
132
133    fn grid() -> (Vec<f64>, Vec<(f64, f64)>) {
134        let az: Vec<f64> = (0..=1800).map(|i| i as f64 * 0.1).collect();
135        let dirs = az.iter().map(|a| (FRAC_PI_2, a.to_radians())).collect();
136        (az, dirs)
137    }
138
139    #[test]
140    fn music_resolves_sources_inside_a_beamwidth_where_bartlett_cannot() {
141        // 8 half-wave-spaced elements have a broadside beamwidth near 13°; the sources are 7° apart.
142        let (array, r) = scene([85.0, 92.0], 0.1);
143        let (az, dirs) = grid();
144        let pol = [C64::new(1.0, 0.0), C64::new(0.0, 0.0)];
145        let music = music_spectrum(&array, &r, 2, &dirs, pol).unwrap();
146        let mut found: Vec<f64> = spectrum_peaks(&music, 2).iter().map(|&i| az[i]).collect();
147        found.sort_by(f64::total_cmp);
148        assert!((found[0] - 85.0).abs() < 0.5 && (found[1] - 92.0).abs() < 0.5, "{found:?}");
149        let bartlett = bartlett_spectrum(&array, &r, &dirs, pol).unwrap();
150        let bartlett_peaks = spectrum_peaks(&bartlett[800..1000], 3);
151        assert_eq!(bartlett_peaks.len(), 1, "Bartlett merges the two sources");
152        let capon = capon_spectrum(&array, &r, &dirs, pol).unwrap();
153        let mut capon_found: Vec<f64> = spectrum_peaks(&capon, 2).iter().map(|&i| az[i]).collect();
154        capon_found.sort_by(f64::total_cmp);
155        assert!((capon_found[0] - 85.0).abs() < 1.5 && (capon_found[1] - 92.0).abs() < 1.5, "{capon_found:?}");
156        assert!(music_spectrum(&array, &r, 8, &dirs, pol).is_err());
157    }
158
159    #[test]
160    fn esprit_estimates_direction_cosines_in_closed_form() {
161        let (array, r) = scene([40.0, 120.0], 0.05);
162        let u = esprit_ula(&r, 2, array.wavelength() / 2.0, array.wavenumber(), TimeConvention::PlusJ).unwrap();
163        let mut angles: Vec<f64> = u.iter().map(|v| v.acos().to_degrees()).collect();
164        angles.sort_by(f64::total_cmp);
165        assert!((angles[0] - 40.0).abs() < 0.3 && (angles[1] - 120.0).abs() < 0.3, "{angles:?}");
166        assert!(spectrum_peaks(&[1.0, 3.0, 2.0, 5.0, 4.0], 5) == vec![3, 1]);
167    }
168}