Algorithmadvanced
Capon beamformer
Also called MVDR beamformer, minimum variance beamformer.
Choose the array weights that minimize the output power with unit gain in the look direction: w = R^-1 a / (a^H R^-1 a). In ultrasound, R comes from subarray averages at each pixel.
- Solves
- Beamforming
- Time
- O(n^2 (K M L^2 + L^3)) worst
- Space
- O(L^2) extra
- Where
- K = the number of snapshots per pixel; L = the subarray length; M = the number of array elements; n = the number of pixels along one side of the image
- Model
- Real RAM
- Properties
- deterministicexactnot linear in dataiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Jack Capon, 1969
The Capon beamformer, also called the minimum variance distortionless response (MVDR) beamformer, chooses the array weights from the data. Fixed weights, as in delay-and-sum (DAS), give every direction the same treatment. Capon instead asks for the weights that make the output power as small as possible, for the covariance of the channel data, under the constraint , which keeps a signal from the look direction unchanged. The answer is . The constraint protects the wanted signal, and the minimum removes as much as possible of everything else, so the beamformer places nulls on strong interferers and narrows the main lobe. In medical ultrasound, the look direction after the focusing delays is the all-ones vector, and is estimated at each pixel from the delayed channel data, with averaging over subarrays and diagonal loading. The method is one instance of adaptive beamforming; MUSIC uses the same covariance, but the eigenvectors of its noise subspace.
In plain words
Delay-and-sum adds all channels with equal weight. That is fine when only the wanted echo is present, but strong echoes from the side leak into the sum. The Capon beamformer looks at the data first and chooses a weight for each channel. There is one rule: an echo from exactly the point you want must come through unchanged. Among all weights that keep this rule, it picks the ones that make the total output as quiet as possible. Since the wanted echo is protected, the only way to be quiet is to cancel the unwanted echoes. The result is a sharper image, at the cost of a small matrix problem for every pixel.
The problem
The narrowband problem: given a Hermitian positive definite matrix and a vector , find
The value of the minimum, as a function of the look direction, is the Capon spectrum.
The ultrasound problem: for one pixel, the input is delayed analytic channel vectors at the sample times around the pixel, as in dynamic receive focusing; the middle one is the pixel sample. The parameters are a subarray length and a loading factor . The output is one complex pixel value.
The algorithm
CAPON-WEIGHTS(R, a, λ) ▷ the minimum variance weights- 1
R_λ ← R + λ I ▷ diagonal loading - 2
z ← solve R_λ z = a - 3
return w ← z / (a^H z) CAPON-PIXEL(x^(1) … x^(K), L, δ) ▷ K = 2Q + 1 delayed snapshots of length M- 4
S ← all subarrays x^(k)[l … l+L-1], l = 1 … M-L+1, k = 1 … K - 5
R ← (1/|S|) Σ_{y ∈ S} y y^H ▷ spatially smoothed covariance - 6
w ← CAPON-WEIGHTS(R, 1, δ tr(R)/L) ▷ steering vector of all ones - 7
g ← mean of the subarrays of the centre snapshot - 8
return w^H g
Line L2 is a linear solve, done in the code by Gaussian elimination from a shared helper; a Cholesky factorization fits because is positive definite. Line L3 scales the result so that . Lines L4 and L5 average the covariance over the subarrays and over the snapshots near the pixel: without this, one snapshot gives a matrix of rank one. The loading of L6 is relative to the mean power on the diagonal. The parameters , and are design choices that must be tuned; the tests use , and .
Example
Take and . Line L2 gives , , and line L3 gives . The output power is . The DAS weights also satisfy , but give . Capon puts more weight on the second channel, which has less power.
One interferer. For elements at half-wavelength spacing, a look direction and an interferer at with power 100 over unit noise, the gain toward the interferer is for Capon and for DAS, and the output power is against . The closed form of the gain comes from the Woodbury identity.
Two close sources. For two sources at with noise power and , the Capon spectrum at is times its value at : two clear peaks. The DAS power at is times its value at : one merged peak.
Ultrasound. The tests simulate elements with pitch 0.3 mm, a plane wave at normal incidence, MHz, MHz and a Gaussian envelope with us. With one scatterer at mm, both beamformers have a peak at the scatterer with values (unit gain), but at mm the normalized value is for Capon and for DAS. With two scatterers at mm, the value midway between them is of the peak for Capon and for DAS. These are measurements on a simulation without noise; with speckle and noise the gain is smaller and depends on and .
Correctness
By the Cauchy-Schwarz inequality, for every feasible , with equality only for parallel to . So line L3 returns the unique minimizer, and the least power is . For white noise, , the weights are those of DAS. For one interferer of power , the gain toward it falls like , while DAS keeps a fixed gain. At an ultrasound pixel, an aligned echo passes with unit gain for any loading, and a very large loading gives a DAS with a trapezoidal taper. The proofs are in proofs/correctness.md.
These are theorems for the true covariance. With a covariance estimated from few samples, the weights are random, and a signal that is correlated with the clutter, or a small error in the steering vector, can be partly cancelled. This is why the loading and the smoothing exist.
Proof: The Capon weights are the unique minimum-power distortionless weights, reduce to delay-and-sum for white noise, and null a strong interfererfull
We prove the facts behind the main page: lines L1 to L3 (the weights) and lines L4 to L8 (one ultrasound pixel). Vectors are complex column vectors, is the conjugate transpose, and is the dot product of the helper. is an Hermitian matrix and is the steering vector.
Theorem 1 (the optimum). Let be Hermitian positive definite. Among all with , the output power has the least value , and the only minimizer is
Proof. has a Hermitian positive definite square root . For a feasible , by the Cauchy-Schwarz inequality,
The second factor is positive because is positive definite and , so . Equality holds if and only if for a scalar , that is . The constraint gives , and since is real, . So is the only minimizer, and its power is .
Lines L2 and L3 compute and , which is . A Lagrange multiplier argument gives the same formula; the inequality above also shows that it is the global minimum and that it is unique. The tests check and compare the power with 200 random feasible weights.
Theorem 2 (white noise gives delay-and-sum). If , then and the least power is . For a steering vector with , such as the all-ones vector after focusing delays, , the weights of delay-and-sum.
Proof. , so and .
Theorem 3 (one interferer). Let with and , so . Then, with for the look direction ,
Proof. By the Sherman-Morrison formula, , so and . Then , because is Hermitian and the denominator is real.
For , the denominator stays at least , so the gain toward the interferer falls like as its power grows: the Capon beamformer places a null on it. Delay-and-sum has the fixed gain . For , and the directions and at half-wavelength spacing, the test finds against , and the output powers are for Capon against for delay-and-sum.
Theorem 4 (the ultrasound pixel). In lines L4 to L8 the steering vector is the all-ones vector of length , is the average of over the subarrays of all snapshots, the loading is , and is the average of the subarrays of the centre snapshot. Then:
- If and the data are not all zero, is Hermitian positive definite, so line L2 is well defined.
- If the centre snapshot is aligned, that is, every channel holds the same value , then the output is for every and every for which the weights exist.
- As the output tends to , a delay-and-sum with a trapezoidal taper over the channels. For or this is the plain mean of the channels.
Proof. (1) Each is Hermitian positive semidefinite, so is too, and when some sample is nonzero. Adding with makes every eigenvalue at least .
(2) Every subarray of the centre snapshot equals , so , and the output is by the constraint.
(3) in direction, so and the output tends to . Channel appears in for the subarrays that contain it, so its total weight is the number of such subarrays divided by , which is a trapezoid in . For there is one subarray, so the output is . For the weight is and is the mean of the channels.
Part 2 is the distortionless property at the pixel level: an echo that the focusing delays have aligned passes with unit gain, whatever the clutter in . The tests check parts 2 and 3.
Remark (rank). Without loading, is a sum of outer products for snapshots, so its rank is at most . If this is less than , is singular and line L2 fails. Spatial smoothing over subarrays raises the rank, and it also decorrelates coherent sources in the covariance (Shan, Wax and Kailath 1985); diagonal loading makes the solve well posed in every case.
Theorem 5 (cost). With snapshots, one pixel costs for line L5, for line L2 by Gaussian elimination, and for line L7; that is . An image costs times this, and the extra space is .
Proof. Each outer product costs , the solve is cubic, and the other lines are linear in their inputs.
Complexity
In the real-RAM model, line L5 costs for snapshots, line L2 costs and line L7 costs . One pixel costs , and an image costs , against for DAS. The extra space is for the covariance. For this is cubic in per pixel, which is the main cost of the method; faster variants use fewer subarrays, a recursive update of along depth, or a beamspace with fewer dimensions.
Properties
- Distortionless: , so a signal from the look direction passes with unit gain.
- Data-adaptive and nonlinear in the data, because depends on . For fixed , the output is linear in .
- The least power is , never more than the DAS power with the same constraint.
- Equal to DAS for white noise; nulls a strong interferer with a gain of order .
- Sensitive to errors in the steering vector and in ; diagonal loading trades resolution for robustness, and the right amount is a design choice, not derived.
Variants and improvements
- Diagonal loading (Cox, Zeskind and Owen 1987). Adding to limits the size of and makes the beamformer robust; for large it tends to DAS.
- Spatial smoothing (Shan, Wax and Kailath 1985). Averaging the covariance over subarrays decorrelates coherent sources, such as the echoes of one transmit, and raises the rank of .
- Forward-backward averaging. Adding the flipped and conjugated covariance doubles the number of samples.
- Eigenspace and beamspace methods. Projecting onto the strongest eigenvectors of , or onto a few fixed beams, lowers the cost and the variance.
- MUSIC and ESPRIT. For direction finding, MUSIC and ESPRIT use the eigenstructure of the same covariance and resolve sources more sharply, but they do not give a power estimate.
- Other adaptive combiners. The coherence factor scales DAS by a measure of agreement, and delay-multiply-and-sum uses pairwise products; both are cheaper.
When to use it
Use the Capon beamformer when lateral resolution or interference rejection matters and there is enough computing power for a small linear solve per pixel: passive arrays in sonar and radio, direction finding, and research ultrasound with channel data. Use DAS when speed, a well-understood speckle pattern or quantitative linear processing matters, or when the data are too few to estimate .
Pitfalls
- Self-cancellation. If the steering vector is slightly wrong, for example from a wrong speed of sound, or if the wanted signal is in the covariance and coherent with clutter, the minimization cancels part of the wanted signal. Use loading and smoothing.
- Singular covariance. One snapshot gives a rank-one ; without smoothing or loading the solve fails or is unstable.
- Explicit inverse. Computing and multiplying is slower and less accurate than a solve with a factorization.
- Speckle. Capon on speckle can change the speckle statistics and the brightness of regions; compare the contrast with care.
- Loading scale. A fixed absolute behaves differently at different depths; scale it by as in L6.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/capon-beamformer/. The authors are listed in prov/EAKMFX.jsonl.
"""The Capon (minimum variance distortionless response, MVDR) beamformer.
Narrowband form: for a Hermitian positive definite covariance R and a steering
vector a, the weights w = R^-1 a / (a^H R^-1 a) minimize the output power
w^H R w subject to w^H a = 1, and the minimum is 1 / (a^H R^-1 a).
Ultrasound form (Synnevag, Austeng and Holm 2007): after the focusing delays of
one pixel, the steering vector is the all-ones vector. The covariance comes
from one or more delayed snapshots by spatial smoothing over subarrays of
length L, with diagonal loading delta * trace(R) / L; both are design choices.
Linear algebra comes from the shared helper imgla (solve, dot).
"""
import cmath
import math
from imgla import dot, solve
def steering_vector(m_count, spacing, u):
"""a_m(u) = exp(-i 2 pi spacing m u) of a uniform linear array, spacing = d / lambda."""
return [cmath.exp(-2j * math.pi * spacing * m * u) for m in range(m_count)]
def capon_weights(r, a, loading=0.0):
"""w = (R + loading I)^-1 a / (a^H (R + loading I)^-1 a)."""
n = len(a)
rl = [[r[i][j] + (loading if i == j else 0.0) for j in range(n)] for i in range(n)] # @line L1
z = solve(rl, a) # @line L2
return [v / dot(a, z) for v in z] # @line L3
def capon_power(r, a):
"""The Capon spectrum value 1 / (a^H R^-1 a), the least output power under w^H a = 1."""
return 1.0 / dot(a, solve(r, a)).real
def output_power(r, w):
"""w^H R w, a real number for Hermitian R."""
rw = [sum(r[i][j] * w[j] for j in range(len(w))) for i in range(len(w))]
return dot(w, rw).real
def outer_sum(vectors):
"""The sample covariance (1/K) sum_k x_k x_k^H of K snapshots."""
n = len(vectors[0])
r = [[0j] * n for _ in range(n)]
for x in vectors:
for i in range(n):
xi = x[i]
for j in range(n):
r[i][j] += xi * x[j].conjugate()
k = len(vectors)
return [[v / k for v in row] for row in r]
def capon_pixel(snapshots, sub_len, delta):
"""The Capon value of one pixel from delayed channel snapshots.
snapshots: a list of 2K + 1 delayed channel vectors (length M) at the
sample times around the pixel; the middle one is the pixel sample.
sub_len: the subarray length L, 1 <= L <= M. delta: the loading factor.
"""
m = len(snapshots[0])
n_sub = m - sub_len + 1
subs = [x[l:l + sub_len] for x in snapshots for l in range(n_sub)] # @line L4
r = outer_sum(subs) # @line L5
trace = sum(r[i][i].real for i in range(sub_len))
ones = [1.0] * sub_len
w = capon_weights(r, ones, delta * trace / sub_len) # @line L6
centre = snapshots[len(snapshots) // 2]
g = [sum(centre[l + i] for l in range(n_sub)) / n_sub for i in range(sub_len)] # @line L7
return dot(w, g) # @line L8
# ---------------------------------------------------------------- a small imaging test bench
SOUND_SPEED = 1.54 # mm per microsecond (1540 m/s)
def element_positions(m_count, pitch):
"""x positions of a linear array, centered at x = 0."""
return [(j - (m_count - 1) / 2) * pitch for j in range(m_count)]
def simulate_iq(elements, scatterers, f0, sigma_t, fs, t0, ns, c=SOUND_SPEED):
"""Complex baseband traces for a plane wave at normal incidence and point scatterers (x, z, amp)."""
data = []
for xj in elements:
tr = [0j] * ns
for (sx, sz, amp) in scatterers:
tau = sz / c + math.hypot(sx - xj, sz) / c
rot = amp * cmath.exp(-2j * math.pi * f0 * tau)
lo = max(0, math.ceil((tau - 5 * sigma_t - t0) * fs))
hi = min(ns - 1, math.floor((tau + 5 * sigma_t - t0) * fs))
for q in range(lo, hi + 1):
dt = t0 + q / fs - tau
tr[q] += rot * math.exp(-dt * dt / (2 * sigma_t * sigma_t))
data.append(tr)
return data
def delayed_snapshots(data, elements, px, pz, t0, fs, f0, half_window, c=SOUND_SPEED):
"""Delayed analytic channel vectors at the pixel time plus or minus q / fs, q <= half_window."""
out = []
for q in range(-half_window, half_window + 1):
x = []
for xj, tr in zip(elements, data):
t = pz / c + math.hypot(px - xj, pz) / c + q / fs
u = (t - t0) * fs
k = math.floor(u)
if k < 0 or k + 1 >= len(tr):
x.append(0j)
continue
phi = u - k
x.append(((1 - phi) * tr[k] + phi * tr[k + 1]) * cmath.exp(2j * math.pi * f0 * t))
out.append(x)
return out
imgla.py 259 lines
# SPDX-License-Identifier: MIT
# Shared helper of the imaging and inverse problems pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Dense linear algebra on lists of rows (float, complex or Fraction entries).
A matrix is a list of rows. A vector is a list of numbers. The inner product
is <u, v> = sum_i conj(u_i) v_i, linear in the second argument, so that the
adjoint A^H satisfies <A x, y> = <x, A^H y>.
"""
import math
def _flat(x):
"""Flatten a list of rows (an image) into one list; a vector is returned as is."""
if x and isinstance(x[0], (list, tuple)):
return [v for row in x for v in row]
return x
def zeros(m, n):
"""The m x n zero matrix."""
return [[0.0] * n for _ in range(m)]
def eye(n):
"""The n x n identity matrix."""
out = zeros(n, n)
for i in range(n):
out[i][i] = 1.0
return out
def transpose(a):
"""A^T."""
return [list(col) for col in zip(*a)]
def conj_transpose(a):
"""A^H, the conjugate transpose."""
return [[v.conjugate() for v in col] for col in zip(*a)]
def matmul(a, b):
"""The product A B."""
bt = list(zip(*b))
return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]
def matvec(a, x):
"""The product A x."""
return [sum(v * w for v, w in zip(row, x)) for row in a]
def rmatvec(a, y):
"""The product A^H y."""
n = len(a[0]) if a else 0
out = [0.0] * n
for row, yi in zip(a, y):
if yi == 0:
continue
for j, v in enumerate(row):
out[j] += v.conjugate() * yi
return out
def dot(u, v):
"""<u, v> = sum_i conj(u_i) v_i. Images (lists of rows) are flattened."""
return sum(a.conjugate() * b for a, b in zip(_flat(u), _flat(v)))
def norm2(x):
"""The Euclidean norm. Images (lists of rows) are flattened."""
return math.sqrt(sum(abs(v) ** 2 for v in _flat(x)))
def solve(a, b):
"""Solve A x = b by Gaussian elimination with partial pivoting.
b is a vector or a matrix (a list of rows). A must be square and
nonsingular; a zero pivot raises ValueError. Fractions stay exact.
"""
n = len(a)
vec = not (b and isinstance(b[0], (list, tuple)))
rhs = [[bi] for bi in b] if vec else [list(r) for r in b]
m = [list(row) + rhs[i] for i, row in enumerate(a)]
w = len(m[0])
for c in range(n):
p = max(range(c, n), key=lambda r: abs(m[r][c]))
if m[p][c] == 0:
raise ValueError("singular matrix")
m[c], m[p] = m[p], m[c]
piv = m[c][c]
for r in range(c + 1, n):
f = m[r][c] / piv
if f != 0:
mr, mc = m[r], m[c]
for j in range(c, w):
mr[j] -= f * mc[j]
x = [[0.0] * (w - n) for _ in range(n)]
for r in range(n - 1, -1, -1):
for j in range(w - n):
s = m[r][n + j] - sum(m[r][k] * x[k][j] for k in range(r + 1, n))
x[r][j] = s / m[r][r]
return [row[0] for row in x] if vec else x
def cholesky(a):
"""Lower triangular L with A = L L^H for a Hermitian positive definite A."""
n = len(a)
low = zeros(n, n)
for j in range(n):
d = a[j][j] - sum(abs(low[j][k]) ** 2 for k in range(j))
d = d.real if isinstance(d, complex) else d
if not d > 0:
raise ValueError("matrix is not positive definite")
ljj = math.sqrt(d)
low[j][j] = ljj
for i in range(j + 1, n):
s = a[i][j] - sum(low[i][k] * low[j][k].conjugate() for k in range(j))
low[i][j] = s / ljj
return low
def cho_solve(low, b):
"""Solve (L L^H) x = b, with L from cholesky."""
n = len(low)
z = [0.0] * n
for i in range(n):
z[i] = (b[i] - sum(low[i][k] * z[k] for k in range(i))) / low[i][i]
x = [0.0] * n
for i in range(n - 1, -1, -1):
s = z[i] - sum(low[k][i].conjugate() * x[k] for k in range(i + 1, n))
x[i] = s / low[i][i].conjugate()
return x
def _rot_params(app, aqq, apq):
"""c, s of the Jacobi rotation that zeroes the (p, q) entry of [[app, apq], [apq, aqq]]."""
theta = (aqq - app) / (2.0 * apq)
t = (1.0 if theta >= 0 else -1.0) / (abs(theta) + math.sqrt(theta * theta + 1.0))
c = 1.0 / math.sqrt(1.0 + t * t)
return c, c * t
def sym_eig(a, tol=1e-15, max_sweeps=100):
"""Eigenvalues (ascending) and eigenvectors (as columns) of a real symmetric matrix.
Cyclic Jacobi method. Returns (w, Q) with A = Q diag(w) Q^T.
"""
n = len(a)
m = [[float(v) for v in row] for row in a]
q = eye(n)
for _ in range(max_sweeps):
off = sum(m[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
scale = sum(m[i][i] ** 2 for i in range(n)) + off
if off <= (tol * tol) * scale or off == 0.0:
break
for p in range(n - 1):
for r in range(p + 1, n):
apq = m[p][r]
if apq == 0.0:
continue
c, s = _rot_params(m[p][p], m[r][r], apq)
for k in range(n):
mkp, mkr = m[k][p], m[k][r]
m[k][p] = c * mkp - s * mkr
m[k][r] = s * mkp + c * mkr
mp, mr = m[p], m[r]
for k in range(n):
mpk, mrk = mp[k], mr[k]
mp[k] = c * mpk - s * mrk
mr[k] = s * mpk + c * mrk
m[p][r] = m[r][p] = 0.0
for k in range(n):
qkp, qkr = q[k][p], q[k][r]
q[k][p] = c * qkp - s * qkr
q[k][r] = s * qkp + c * qkr
order = sorted(range(n), key=lambda i: m[i][i])
w = [m[i][i] for i in order]
qs = [[q[k][i] for i in order] for k in range(n)]
return w, qs
def _complete(cols, m):
"""Replace zero columns of an m-row column list by unit vectors orthogonal to the others."""
for idx, col in enumerate(cols):
if any(v != 0.0 for v in col):
continue
for e in range(m):
cand = [0.0] * m
cand[e] = 1.0
for _ in range(2):
for jdx, other in enumerate(cols):
if jdx == idx or not any(v != 0.0 for v in other):
continue
h = sum(a * b for a, b in zip(other, cand))
cand = [a - h * b for a, b in zip(cand, other)]
nrm = math.sqrt(sum(v * v for v in cand))
if nrm > 0.5:
cols[idx] = [v / nrm for v in cand]
break
return cols
def svd(a, tol=1e-15, max_sweeps=100):
"""Thin SVD of a real m x n matrix by one-sided Jacobi (Hestenes).
Returns (U, S, V) with p = min(m, n): U is m x p, S a list of p values in
descending order, V is n x p, U^T U = I, V^T V = I and A = U diag(S) V^T.
"""
m, n = len(a), len(a[0])
if m < n:
v, s, u = svd(transpose(a), tol, max_sweeps)
return u, s, v
cols = [[float(a[i][j]) for i in range(m)] for j in range(n)]
vcols = [[1.0 if i == j else 0.0 for i in range(n)] for j in range(n)]
for _ in range(max_sweeps):
rotated = False
for p in range(n - 1):
for r in range(p + 1, n):
cp, cr = cols[p], cols[r]
alpha = sum(x * x for x in cp)
beta = sum(x * x for x in cr)
gamma = sum(x * y for x, y in zip(cp, cr))
if gamma == 0.0 or abs(gamma) <= tol * math.sqrt(alpha * beta):
continue
rotated = True
c, s = _rot_params(alpha, beta, gamma)
cols[p] = [c * x - s * y for x, y in zip(cp, cr)]
cols[r] = [s * x + c * y for x, y in zip(cp, cr)]
vp, vr = vcols[p], vcols[r]
vcols[p] = [c * x - s * y for x, y in zip(vp, vr)]
vcols[r] = [s * x + c * y for x, y in zip(vp, vr)]
if not rotated:
break
sig = [math.sqrt(sum(x * x for x in col)) for col in cols]
# A column below 1e-150 times the largest one is zero to working precision;
# its squares underflow, so its direction carries no information.
floor = max(sig) * 1e-150 if sig else 0.0
sig = [t if t > floor and t > 1e-150 else 0.0 for t in sig]
order = sorted(range(n), key=lambda j: -sig[j])
s_out = [sig[j] for j in order]
ucols = [[x / sig[j] for x in cols[j]] if sig[j] > 0.0 else [0.0] * m for j in order]
ucols = _complete(ucols, m)
u = [[ucols[j][i] for j in range(n)] for i in range(m)]
v = [[vcols[j][i] for j in order] for i in range(n)]
return u, s_out, v
def adjoint_gap(apply_a, apply_ah, x, y):
"""|<A x, y> - <x, A^H y>| / (||A x|| ||y||) for given functions A and A^H.
x and y may be vectors or images (lists of rows). If the denominator is
zero, the absolute gap is returned.
"""
ax = apply_a(x)
gap = abs(dot(ax, y) - dot(x, apply_ah(y)))
den = norm2(ax) * norm2(y)
return gap / den if den > 0.0 else gap
test_capon_beamformer.py 131 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/capon-beamformer/. The authors are listed in prov/EAKMFX.jsonl.
import random
from capon_beamformer import (capon_pixel, capon_power, capon_weights, delayed_snapshots, element_positions,
outer_sum, output_power, simulate_iq, steering_vector)
from imgla import dot
F0, SIGMA, FS, T0, NS = 5.0, 0.1, 40.0, 7.0, 120
ELEMENTS = element_positions(16, 0.3)
XS = [round(-1.5 + 0.1 * k, 10) for k in range(31)]
def _random_covariance(rng, n, k):
snaps = [[complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(n)] for _ in range(k)]
return outer_sum(snaps)
def _interference(m, u_signal, u_int, power_int):
a1 = steering_vector(m, 0.5, u_int)
r = [[power_int * a1[i] * a1[j].conjugate() + (1.0 if i == j else 0.0) for j in range(m)] for i in range(m)]
return r, steering_vector(m, 0.5, u_signal), a1
def test_distortionless_constraint() -> None:
rng = random.Random(4401)
for n in (2, 5, 8):
r = _random_covariance(rng, n, 3 * n)
a = steering_vector(n, 0.5, rng.uniform(-1, 1))
w = capon_weights(r, a)
assert abs(dot(w, a) - 1) < 1e-10
def test_least_power_among_feasible_weights() -> None:
rng = random.Random(4402)
n = 6
r = _random_covariance(rng, n, 20)
a = steering_vector(n, 0.5, 0.3)
w = capon_weights(r, a)
p_min = output_power(r, w)
assert abs(p_min - capon_power(r, a)) < 1e-10 * p_min
for _ in range(200):
v = [complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(n)]
# move v onto the feasible set w^H a = 1 along a
c = (1 - dot(v, a)) / dot(a, a)
u = [vi + c.conjugate() * ai for vi, ai in zip(v, a)]
assert abs(dot(u, a) - 1) < 1e-10
assert output_power(r, u) >= p_min * (1 - 1e-12)
def test_white_noise_gives_the_das_weights() -> None:
m = 7
r = [[2.5 if i == j else 0.0 for j in range(m)] for i in range(m)]
a = steering_vector(m, 0.5, 0.2)
w = capon_weights(r, a)
assert all(abs(wi - ai / m) < 1e-12 for wi, ai in zip(w, a))
assert abs(capon_power(r, a) - 2.5 / m) < 1e-12
def test_interferer_response_matches_the_closed_form() -> None:
# R = I + s a1 a1^H; by the Woodbury identity w^H a1 = (a0^H a1) / ((1 + M s) a0^H R^-1 a0)
m, s = 8, 100.0
r, a0, a1 = _interference(m, 0.0, 0.4, s)
w = capon_weights(r, a0)
c01 = dot(a0, a1)
denom = m - s * abs(c01) ** 2 / (1 + m * s)
assert abs(abs(dot(w, a1)) - abs(c01) / ((1 + m * s) * denom)) < 1e-12
das_gain = abs(c01) / m
assert abs(dot(w, a1)) < 0.02 * das_gain
def test_resolves_two_close_sources_that_das_merges() -> None:
m = 8
a1 = steering_vector(m, 0.5, 0.1)
a2 = steering_vector(m, 0.5, -0.1)
r = [[a1[i] * a1[j].conjugate() + a2[i] * a2[j].conjugate() + (0.01 if i == j else 0.0) for j in range(m)]
for i in range(m)]
cap = {u: capon_power(r, steering_vector(m, 0.5, u)) for u in (-0.1, 0.0, 0.1)}
das = {u: output_power(r, [v / m for v in steering_vector(m, 0.5, u)]) for u in (-0.1, 0.0, 0.1)}
assert cap[0.0] < 0.05 * cap[0.1] and cap[0.0] < 0.05 * cap[-0.1]
assert das[0.0] > das[0.1]
def test_aligned_channels_return_the_value() -> None:
v = 0.7 - 1.1j
snaps = [[v] * 12 for _ in range(5)]
for sub_len in (1, 4, 12):
assert abs(capon_pixel(snaps, sub_len, 0.01) - v) < 1e-10
def test_large_loading_gives_das() -> None:
rng = random.Random(4403)
snaps = [[complex(rng.gauss(0, 1), rng.gauss(0, 1)) for _ in range(10)] for _ in range(3)]
centre = snaps[1]
assert abs(capon_pixel(snaps, 10, 1e9) - sum(centre) / 10) < 1e-6
# with L = 1 there is nothing to adapt: the result is the plain average
assert abs(capon_pixel(snaps, 1, 0.01) - sum(centre) / 10) < 1e-10
def _profile(data, combiner):
prof = [abs(combiner(delayed_snapshots(data, ELEMENTS, px, 6.0, T0, FS, F0, 2))) for px in XS]
peak = max(prof)
return [v / peak for v in prof], peak
def _das(snaps):
return sum(snaps[len(snaps) // 2]) / len(snaps[0])
def _capon(snaps):
return capon_pixel(snaps, 8, 0.01)
def test_point_target_is_narrower_than_das() -> None:
data = simulate_iq(ELEMENTS, [(0.0, 6.0, 1.0)], F0, SIGMA, FS, T0, NS)
p_das, peak_das = _profile(data, _das)
p_cap, peak_cap = _profile(data, _capon)
i0 = XS.index(0.0)
assert p_das.index(1.0) == i0 and p_cap.index(1.0) == i0
# both outputs keep the unit gain at the target
assert abs(peak_das - 1) < 0.01 and abs(peak_cap - 1) < 0.01
assert p_cap[i0 + 1] < 0.1 < 0.8 < p_das[i0 + 1]
def test_two_targets_are_better_separated_than_with_das() -> None:
data = simulate_iq(ELEMENTS, [(-0.3, 6.0, 1.0), (0.3, 6.0, 1.0)], F0, SIGMA, FS, T0, NS)
p_das, _ = _profile(data, _das)
p_cap, _ = _profile(data, _capon)
i0 = XS.index(0.0)
assert p_cap[i0] < 0.4 and p_das[i0] > 0.6
History
Capon (1969) introduced the method for high-resolution frequency-wavenumber analysis of the signals of seismometer arrays: the power estimate at each wavenumber is the output power of the filter that passes that plane wave without distortion and has the least output power. The method was also called the maximum likelihood method. It became a standard of adaptive array processing in radar, sonar and communications, where its sensitivity led to diagonal loading (Cox, Zeskind and Owen 1987) and spatial smoothing (Shan, Wax and Kailath 1985). Synnevag, Austeng and Holm (2007) applied the minimum variance beamformer to medical ultrasound imaging with a covariance estimated per pixel, and reported a much narrower main lobe than DAS.
References
- Jack Capon, High-resolution frequency-wavenumber spectrum analysis, Proceedings of the IEEE 57(8), 1969, 1408 to 1418, the minimum variance estimate of the frequency-wavenumber spectrum and its weights (general locator)
- Johan-Fredrik Synnevag, Andreas Austeng and Sverre Holm, Adaptive beamforming applied to medical ultrasound imaging, IEEE Transactions on Ultrasonics, Ferroelectrics, and Frequency Control 54(8), 2007, 1606 to 1613, the minimum variance beamformer per pixel, with subarray averaging, diagonal loading and the comparison with delay-and-sum (general locator)
- Tie-Jun Shan, Mati Wax and Thomas Kailath, On spatial smoothing for direction-of-arrival estimation of coherent signals, IEEE Transactions on Acoustics, Speech, and Signal Processing 33(4), 1985, 806 to 811, spatial smoothing over subarrays to decorrelate coherent sources (general locator)
- Henry Cox, Robert M. Zeskind and Mark M. Owen, Robust adaptive beamforming, IEEE Transactions on Acoustics, Speech, and Signal Processing 35(10), 1987, 1365 to 1376, diagonal loading and the robustness of the minimum variance beamformer (general locator)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag EAKMFX Edit this page History Report an error Markdown