23. Beamforming and Direction of Arrival¶
PySDR’s Beamforming & DOA chapter is one of its longest, and it is mostly linear algebra. A uniform linear array of \(N_r\) antennas receives a signal from angle \(\theta\). Each element sees it with a phase shift described by the steering vector \(s(\theta)\). Beamformers combine the elements with weights \(w\), and DOA estimation scans \(\theta\) for the angles where some measure of power peaks. The chapter builds a scenario with 8 elements and three signals, at 20, 25 and \(-40\) degrees (the last at a tenth of the amplitude), and compares three scans: the conventional (delay-and-sum) beamformer, MVDR/Capon, and MUSIC.
In NumPy all of this is matrix products, np.linalg.pinv and np.linalg.eig. In C++ the interesting questions are different. What should a matrix be when its size is the number of antennas and known when the program is compiled? How do we avoid inverting a matrix, which is rarely the right operation numerically? And which eigensolver should we use when the matrix is Hermitian? This chapter answers them for PySDR’s scenario and compares every spectrum with PySDR’s code.
The code is in code/include/cppsdr/doa.hpp and code/tests/test_doa.cpp; figure-generating-scripts/doa_reference.py runs PySDR’s scenario and its three scans (fixed seed).
The Array Size Is a Type¶
An SDR array has a handful of elements, 2 to 16, and the number is fixed by the hardware. That makes it a natural template parameter. Vectors and matrices become std::arrays of known size:
using cd = std::complex<double>;
template <std::size_t M> using cvec = std::array<cd, M>;
template <std::size_t M> using cmat = std::array<std::array<cd, M>, M>; // m[row][col]
template <std::size_t M>
cvec<M> steering(double theta, double d = 0.5)
{
const cd step = std::polar(1.0, 2 * std::numbers::pi * d * std::sin(theta));
cvec<M> s{};
s[0] = 1;
for (std::size_t k = 1; k < M; ++k) s[k] = s[k - 1] * step; // e^{2j pi d k sin(theta)}
return s;
}
There is no heap allocation, which is what Kormanyos recommends for real-time code in general (Real-Time C++: std::array as the default container, no new at run time). Loops have compile-time trip counts, so the compiler can unroll them, and a cmat<8> cannot be multiplied by a cvec<4> by accident. The steering vector illustrates a small idea from Oscillators and Frequency Shifting: PySDR computes np.exp once per element, while the C++ version computes one sine and cosine per angle and then a running product. For 8 elements the rounding error of 7 multiplications is negligible.
The Covariance as a Stream¶
All adaptive methods start from the spatial covariance matrix, \(\hat R = \frac{1}{N} \sum_n x_n x_n^H\), where \(x_n\) is one snapshot (one sample from each element). PySDR computes it as X @ X.conj().T / N on the whole recording. A receiver accumulates it snapshot by snapshot. \(R\) is Hermitian (\(R_{ji} = R_{ij}^*\)), so only the upper triangle needs to be accumulated, 36 of the 64 entries for 8 elements:
void push(cvec<M> const& x)
{
for (std::size_t i = 0; i < M; ++i)
for (std::size_t j = i; j < M; ++j) acc_[i][j] += x[i] * std::conj(x[j]);
++n_;
}
As everywhere in this book, the test checks that accumulating PySDR’s 10 000 snapshots in random blocks gives a bit-identical matrix.
MVDR Without an Inverse¶
The MVDR (Capon) spectrum is \(P(\theta) = 1 / (s^H R^{-1} s)\). PySDR derives this shortcut in its chapter and implements it as a function that is called once per angle:
def power_mvdr(theta, X):
s = np.exp(2j * np.pi * d * np.arange(X.shape[0]) * np.sin(theta))
s = s.reshape(-1,1)
R = (X @ X.conj().T)/X.shape[1] # Calc covariance matrix
Rinv = np.linalg.pinv(R) # pseudo-inverse tends to work better than a true inverse
return 1/(s.conj().T @ Rinv @ s).squeeze()
Called for 1000 angles, this recomputes the covariance (8 × 8 × 10 000 complex multiply-adds) and its pseudo-inverse 1000 times, although neither depends on the angle. Moving them out of the loop is the first step, and the obvious one.
The second step removes the inverse altogether. Numerical linear algebra has a rule of thumb: you almost never need \(R^{-1}\), only \(R^{-1}\) applied to something, and that is a linear system to solve. \(R\) is Hermitian and positive definite (with noise on every element, it always is), so it has a Cholesky factorization \(R = L L^H\), with \(L\) lower triangular, at half the cost of a general factorization. Then
which reads: solve one triangular system \(L y = s\) by forward substitution and take the squared length of \(y\). No inverse, no back substitution, about \(M^2/2\) complex multiply-adds per angle:
template <std::size_t M>
class mvdr {
public:
explicit mvdr(cmat<M> r, double diagonal_loading = 0); // Cholesky once, here
double power(double theta, double d = 0.5) const
{
return 1 / norm2(forward_solve(l_, steering<M>(theta, d)));
}
cvec<M> weights(double theta, double d = 0.5) const; // R^-1 s / (s^H R^-1 s), if a beam is needed
private:
cmat<M> l_{};
};
If \(R\) is not positive definite (too few snapshots, or a dead element), the factorization detects it, and the constructor reports it rather than producing a meaningless inverse. The standard remedy, diagonal loading (adding a small constant to the diagonal), is a constructor argument. On PySDR’s scenario the Cholesky spectrum agrees with PySDR’s pseudo-inverse version to better than 0.0001 dB at all 1000 angles. The covariance here is well conditioned (condition number about 3000), so the pseudo-inverse buys nothing over a solve. The test also checks the two properties that define MVDR, using weights(): the weights pass the look direction with gain exactly 1 (\(w^H s = 1\) to \(10^{-16}\)), and the output power \(w^H R w\) equals the shortcut \(1/(s^H R^{-1} s)\) to \(10^{-10}\).
MUSIC and a Hermitian Eigensolver¶
MUSIC splits the eigenvectors of \(R\) into a signal subspace (the largest eigenvalues) and a noise subspace (the rest), and scans for the angles whose steering vector is orthogonal to the noise subspace: \(P(\theta) = 1/\|V_n^H s\|^2\). PySDR computes the eigenvectors with np.linalg.eig, the solver for general matrices. For a Hermitian matrix, np.linalg.eigh is the right tool: its eigenvalues are real and sorted, and its eigenvectors are orthonormal by construction. MUSIC relies on the latter, because \(V_n V_n^H\) is a projection only if the columns of \(V_n\) are orthonormal. The general solver’s eigenvectors are only orthonormal up to rounding: on PySDR’s scenario they deviate by \(10^{-10}\), which changes nothing in practice. It is still worth knowing which tool the problem calls for.
C++ has no linear algebra in its standard library yet (C++26 adds <linalg>, but without eigensolvers), and pulling in Eigen or LAPACK for an 8 × 8 matrix is a heavy dependency. The classic algorithm for small Hermitian matrices fits in 50 lines: Jacobi’s method. It repeatedly applies a plane rotation that zeroes one off-diagonal element, sweeping over all pairs until the matrix is diagonal. The product of the rotations is the eigenvector matrix, unitary by construction because each rotation is. For a complex Hermitian matrix, each step first removes the phase of the element to be zeroed, then applies an ordinary real rotation (eigh in doa.hpp). On PySDR’s covariance it converges in a few sweeps. The test checks the eigenvectors’ orthonormality (\(10^{-15}\)) and the residual \(\|Rv - \lambda v\|\) (\(4 \cdot 10^{-15}\)), and gets the same eigenvalues as NumPy:
0.004838 0.004902 0.005062 0.005127 0.005156 | 0.08143 1.29 14.72
These are PySDR’s eigenvalue plot in numbers: five eigenvalues form a noise floor at the noise power, and three stand above it, one per signal. The weakest signal, a tenth of the amplitude, sits 12 dB above the floor. The test checks this ratio, PySDR’s “trick” for estimating the number of signals. The MUSIC spectrum then matches PySDR’s to 0.007 dB at all 1000 angles.
The Three Spectra¶
The figure reproduces PySDR’s comparison from the C++ code. The conventional beamformer (orange) merges the two signals 5 degrees apart into one lobe peaking at 22.5 degrees, and the weak signal at \(-40\) degrees is lost among the sidelobes. MVDR (blue) resolves all three. MUSIC (green) resolves them with very sharp peaks. Its height is not a power, only a measure of orthogonality to the noise subspace. The test asserts each of these statements, with peak positions to 0.5 degrees.
One detail of PySDR’s MUSIC code, for readers who adapt it: after converting the metric to dB, it normalizes with results /= np.max(results). Dividing dB values rescales them rather than shifting them to a 0 dB peak; the conventional scan in the same chapter uses results -= np.max(results), which is what the figure above does for all three. The peak positions are unaffected either way.
Key Takeaways¶
The number of antenna elements is a template parameter:
std::arrayvectors and matrices, no heap, dimension errors caught by the compiler.Accumulate the covariance snapshot by snapshot, upper triangle only; it is Hermitian.
Never invert \(R\) for MVDR: factor it once (Cholesky), then each angle is one triangular solve, \(P = 1/\|L^{-1}s\|^2\). PySDR’s version recomputes the covariance and its pseudo-inverse for every angle.
Hermitian problems deserve Hermitian solvers: a 50-line Jacobi method gives orthonormal eigenvectors by construction and matches NumPy’s eigenvalues.
On PySDR’s scenario all three C++ spectra match PySDR’s: conventional and MVDR to 0.0001 dB, MUSIC to 0.007 dB.