Skip to main content

lib_jsl_electromagnetics/algorithms/
beamforming.rs

1//! Shared beamformer conventions and figures of merit.
2//!
3//! A beamformer combines array snapshots `x` (length `N`) as `y = wᴴ x`, so a weight vector `w`
4//! passes a signal with steering vector `a` with gain `wᴴ a` and outputs the power `wᴴ R w` for a
5//! covariance `R`.
6//!
7//! See the book entry [Arrays, scenes and beamformers](https://jwkunz.github.io/lib_jsl/book/em-arrays/beamforming.html).
8
9use crate::conventions::C64;
10use crate::linalg::quadratic_form;
11use lib_jsl_core::ErrorsJSL;
12use ndarray::{Array1, Array2};
13
14/// The output power `wᴴ R w` (W when `R` is in W).
15pub fn output_power(weights: &Array1<C64>, covariance: &Array2<C64>) -> Result<f64, ErrorsJSL> {
16    if covariance.dim() != (weights.len(), weights.len()) {
17        return Err(ErrorsJSL::IncompatibleArraySizes((covariance.nrows(), weights.len())));
18    }
19    Ok(quadratic_form(weights, covariance))
20}
21
22/// The signal-to-interference-plus-noise ratio `wᴴ R_s w / wᴴ R_n w`.
23pub fn sinr(weights: &Array1<C64>, signal: &Array2<C64>, interference_plus_noise: &Array2<C64>) -> Result<f64, ErrorsJSL> {
24    let n = output_power(weights, interference_plus_noise)?;
25    if n <= 0.0 {
26        return Err(ErrorsJSL::InvalidInputRange("The interference-plus-noise output power is not positive."));
27    }
28    Ok(output_power(weights, signal)? / n)
29}
30
31/// The complex gain `wᴴ a` of the beamformer for a steering vector.
32pub fn response(weights: &Array1<C64>, steering: &Array1<C64>) -> Result<C64, ErrorsJSL> {
33    if weights.len() != steering.len() {
34        return Err(ErrorsJSL::IncompatibleArraySizes((weights.len(), steering.len())));
35    }
36    Ok(weights.iter().zip(steering.iter()).map(|(w, a)| w.conj() * a).sum())
37}
38
39/// `w / ‖w‖`, with the phase fixed so the largest-magnitude weight is real and positive (making
40/// eigenvector solutions reproducible).
41pub fn normalize(weights: &Array1<C64>) -> Result<Array1<C64>, ErrorsJSL> {
42    let norm = weights.iter().map(|v| v.norm_sqr()).sum::<f64>().sqrt();
43    if norm.is_nan() || norm <= 0.0 {
44        return Err(ErrorsJSL::InvalidInputRange("Cannot normalise a zero weight vector."));
45    }
46    // The reference element is the first whose magnitude is within a relative 1e-9 of the
47    // largest, so equal-magnitude weights (steering vectors) get a phase reference that does not
48    // depend on rounding noise.
49    let largest = weights.iter().fold(0.0f64, |m, v| m.max(v.norm()));
50    let big = weights.iter().copied().find(|v| v.norm() >= largest * (1.0 - 1e-9)).expect("non-zero weights");
51    let phase = big.conj() / big.norm();
52    Ok(weights.mapv(|v| v * phase / norm))
53}