Algorithm Search⌘K

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.

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
Properties
deterministicexactnot linear in dataiterative
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 ww that make the output power wHRww^H R w as small as possible, for the covariance RR of the channel data, under the constraint wHa=1w^H a = 1, which keeps a signal from the look direction aa unchanged. The answer is w=R−1a/(aHR−1a)w = R^{-1} a / (a^H R^{-1} a). 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 RR 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 L×LL \times L matrix RR and a vector a≠0a \ne 0, find

w⋆=arg⁡min⁡w wHRwsubject towHa=1.w^\star = \arg\min_w\, w^H R w \quad \text{subject to} \quad w^H a = 1.

The value P(a)=1/(aHR−1a)P(a) = 1/(a^H R^{-1} a) of the minimum, as a function of the look direction, is the Capon spectrum.

The ultrasound problem: for one pixel, the input is 2Q+12Q + 1 delayed analytic channel vectors x(q)∈CMx^{(q)} \in \mathbb{C}^M 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 LL and a loading factor δ\delta. The output is one complex pixel value.

The algorithm

  1. CAPON-WEIGHTS(R, a, λ) ▷ the minimum variance weights
  2. 1R_λ ← R + λ I ▷ diagonal loading
  3. 2z ← solve R_λ z = a
  4. 3return w ← z / (a^H z)
  5. CAPON-PIXEL(x^(1) … x^(K), L, δ) ▷ K = 2Q + 1 delayed snapshots of length M
  6. 4S ← all subarrays x^(k)[l … l+L-1], l = 1 … M-L+1, k = 1 … K
  7. 5R ← (1/|S|) Σ_{y ∈ S} y y^H ▷ spatially smoothed covariance
  8. 6w ← CAPON-WEIGHTS(R, 1, δ tr(R)/L) ▷ steering vector of all ones
  9. 7g ← mean of the subarrays of the centre snapshot
  10. 8return 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 RλR_\lambda is positive definite. Line L3 scales the result so that wHa=1w^H a = 1. 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 LL, δ\delta and QQ are design choices that must be tuned; the tests use L=M/2L = M/2, δ=0.01\delta = 0.01 and Q=2Q = 2.

Example

Take R=(3112)R = \begin{pmatrix} 3 & 1 \\ 1 & 2 \end{pmatrix} and a=(1,1)a = (1, 1). Line L2 gives z=R−1a=(1/5,2/5)z = R^{-1} a = (1/5, 2/5), aHz=3/5a^H z = 3/5, and line L3 gives w=(1/3,2/3)w = (1/3, 2/3). The output power is wHRw=5/3w^H R w = 5/3. The DAS weights (1/2,1/2)(1/2, 1/2) also satisfy wHa=1w^H a = 1, but give 7/47/4. Capon puts more weight on the second channel, which has less power.

One interferer. For M=8M = 8 elements at half-wavelength spacing, a look direction u=0u = 0 and an interferer at u=0.4u = 0.4 with power 100 over unit noise, the gain toward the interferer is 0.0002630.000263 for Capon and 0.20230.2023 for DAS, and the output power is 0.13030.1303 against 4.2164.216. The closed form of the gain comes from the Woodbury identity.

Two close sources. For two sources at u=±0.1u = \pm 0.1 with noise power 0.010.01 and M=8M = 8, the Capon spectrum at u=0u = 0 is 0.01840.0184 times its value at u=0.1u = 0.1: two clear peaks. The DAS power at u=0u = 0 is 1.0931.093 times its value at u=0.1u = 0.1: one merged peak.

Ultrasound. The tests simulate M=16M = 16 elements with pitch 0.3 mm, a plane wave at normal incidence, f0=5f_0 = 5 MHz, fs=40f_s = 40 MHz and a Gaussian envelope with σt=0.1\sigma_t = 0.1 us. With one scatterer at (0,6)(0, 6) mm, both beamformers have a peak at the scatterer with values 0.9950.995 (unit gain), but at x=0.1x = 0.1 mm the normalized value is 0.0380.038 for Capon and 0.8930.893 for DAS. With two scatterers at x=±0.3x = \pm 0.3 mm, the value midway between them is 0.2290.229 of the peak for Capon and 0.680.68 for DAS. These are measurements on a simulation without noise; with speckle and noise the gain is smaller and depends on LL and δ\delta.

Correctness

By the Cauchy-Schwarz inequality, 1=∣wHa∣2≤(wHRw)(aHR−1a)1 = |w^H a|^2 \le (w^H R w)(a^H R^{-1} a) for every feasible ww, with equality only for ww parallel to R−1aR^{-1} a. So line L3 returns the unique minimizer, and the least power is 1/(aHR−1a)1/(a^H R^{-1} a). For white noise, R=σ2IR = \sigma^2 I, the weights are those of DAS. For one interferer of power ss, the gain toward it falls like 1/(Ls)1/(L s), 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, uHu^H is the conjugate transpose, and ⟨u,v⟩=uHv\langle u, v \rangle = u^H v is the dot product of the helper. RR is an L×LL \times L Hermitian matrix and a≠0a \ne 0 is the steering vector.

Theorem 1 (the optimum). Let RR be Hermitian positive definite. Among all ww with wHa=1w^H a = 1, the output power wHRww^H R w has the least value 1/(aHR−1a)1/(a^H R^{-1} a), and the only minimizer is

w⋆=R−1aaHR−1a.w^\star = \frac{R^{-1} a}{a^H R^{-1} a}.

Proof. RR has a Hermitian positive definite square root R1/2R^{1/2}. For a feasible ww, by the Cauchy-Schwarz inequality,

1=∣wHa∣2=∣(R1/2w)H(R−1/2a)∣2≤(wHRw) (aHR−1a).1 = |w^H a|^2 = |(R^{1/2} w)^H (R^{-1/2} a)|^2 \le (w^H R w)\,(a^H R^{-1} a).

The second factor is positive because R−1R^{-1} is positive definite and a≠0a \ne 0, so wHRw≥1/(aHR−1a)w^H R w \ge 1/(a^H R^{-1} a). Equality holds if and only if R1/2w=βR−1/2aR^{1/2} w = \beta R^{-1/2} a for a scalar β\beta, that is w=βR−1aw = \beta R^{-1} a. The constraint gives βˉ aHR−1a=1\bar\beta\, a^H R^{-1} a = 1, and since aHR−1aa^H R^{-1} a is real, β=1/(aHR−1a)\beta = 1/(a^H R^{-1} a). So w⋆w^\star is the only minimizer, and its power is 1/(aHR−1a)1/(a^H R^{-1} a). □\square

Lines L2 and L3 compute z=R−1az = R^{-1} a and w=z/(aHz)w = z / (a^H z), which is w⋆w^\star. 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 wHa=1w^H a = 1 and compare the power with 200 random feasible weights.

Theorem 2 (white noise gives delay-and-sum). If R=σ2IR = \sigma^2 I, then w⋆=a/(aHa)w^\star = a/(a^H a) and the least power is σ2/(aHa)\sigma^2/(a^H a). For a steering vector with ∣ai∣=1|a_i| = 1, such as the all-ones vector after focusing delays, w⋆=a/Lw^\star = a/L, the weights of delay-and-sum.

Proof. R−1a=a/σ2R^{-1} a = a/\sigma^2, so w⋆=a/(aHa)w^\star = a/(a^H a) and 1/(aHR−1a)=σ2/(aHa)1/(a^H R^{-1} a) = \sigma^2/(a^H a). □\square

Theorem 3 (one interferer). Let R=I+s a1a1HR = I + s\, a_1 a_1^H with s≥0s \ge 0 and ∣a1,i∣=1|a_{1,i}| = 1, so a1Ha1=La_1^H a_1 = L. Then, with c=a0Ha1c = a_0^H a_1 for the look direction a0a_0,

(w⋆)Ha1=c(1+Ls) a0HR−1a0,a0HR−1a0=L−s∣c∣21+Ls.(w^\star)^H a_1 = \frac{c}{(1 + L s)\, a_0^H R^{-1} a_0}, \qquad a_0^H R^{-1} a_0 = L - \frac{s |c|^2}{1 + L s}.

Proof. By the Sherman-Morrison formula, R−1=I−s a1a1H1+LsR^{-1} = I - \frac{s\, a_1 a_1^H}{1 + L s}, so R−1a1=a1/(1+Ls)R^{-1} a_1 = a_1 / (1 + L s) and a0HR−1a0=L−s∣c∣2/(1+Ls)a_0^H R^{-1} a_0 = L - s|c|^2/(1 + L s). Then (w⋆)Ha1=a0HR−1a1/(a0HR−1a0)(w^\star)^H a_1 = a_0^H R^{-1} a_1 / (a_0^H R^{-1} a_0), because R−1R^{-1} is Hermitian and the denominator is real. □\square

For ∣c∣<L|c| < L, the denominator stays at least L−∣c∣2/L>0L - |c|^2/L > 0, so the gain toward the interferer falls like 1/(Ls)1/(L s) as its power ss grows: the Capon beamformer places a null on it. Delay-and-sum has the fixed gain c/Lc/L. For L=8L = 8, s=100s = 100 and the directions u=0u = 0 and u=0.4u = 0.4 at half-wavelength spacing, the test finds 0.0002630.000263 against 0.20230.2023, and the output powers are 0.13030.1303 for Capon against 4.2164.216 for delay-and-sum.

Theorem 4 (the ultrasound pixel). In lines L4 to L8 the steering vector is the all-ones vector 1\mathbf 1 of length LL, RR is the average of xxHx x^H over the subarrays of all snapshots, the loading is λ=δ tr⁡(R)/L\lambda = \delta\, \operatorname{tr}(R)/L, and gg is the average of the subarrays of the centre snapshot. Then:

  1. If δ>0\delta > 0 and the data are not all zero, R+λIR + \lambda I is Hermitian positive definite, so line L2 is well defined.
  2. If the centre snapshot is aligned, that is, every channel holds the same value vv, then the output is vv for every LL and every δ\delta for which the weights exist.
  3. As δ→∞\delta \to \infty the output tends to 1L∑igi\frac{1}{L} \sum_i g_i, a delay-and-sum with a trapezoidal taper over the MM channels. For L=ML = M or L=1L = 1 this is the plain mean of the MM channels.

Proof. (1) Each xxHx x^H is Hermitian positive semidefinite, so RR is too, and tr⁡(R)>0\operatorname{tr}(R) > 0 when some sample is nonzero. Adding λI\lambda I with λ>0\lambda > 0 makes every eigenvalue at least λ\lambda.

(2) Every subarray of the centre snapshot equals v1v \mathbf 1, so g=v1g = v \mathbf 1, and the output is wHg=v wH1=vw^H g = v\, w^H \mathbf 1 = v by the constraint.

(3) (R+λI)−11=λ−1(I+R/λ)−11→λ−11(R + \lambda I)^{-1} \mathbf 1 = \lambda^{-1} (I + R/\lambda)^{-1} \mathbf 1 \to \lambda^{-1} \mathbf 1 in direction, so w→1/Lw \to \mathbf 1/L and the output tends to 1L∑igi\frac{1}{L} \sum_i g_i. Channel kk appears in gig_i for the subarrays that contain it, so its total weight is the number of such subarrays divided by L(M−L+1)L(M - L + 1), which is a trapezoid in kk. For L=ML = M there is one subarray, so the output is 1M∑kxk\frac{1}{M} \sum_k x_k. For L=1L = 1 the weight is w=1w = 1 and gg is the mean of the MM channels. □\square

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 RR. The tests check parts 2 and 3.

Remark (rank). Without loading, RR is a sum of K(M−L+1)K (M - L + 1) outer products for KK snapshots, so its rank is at most K(M−L+1)K (M - L + 1). If this is less than LL, RR 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 KK snapshots, one pixel costs O(K(M−L+1)L2)O(K (M - L + 1) L^2) for line L5, O(L3)O(L^3) for line L2 by Gaussian elimination, and O(ML)O(M L) for line L7; that is O(KML2+L3)O(K M L^2 + L^3). An n×nn \times n image costs n2n^2 times this, and the extra space is O(L2)O(L^2).

Proof. Each outer product costs L2L^2, the solve is cubic, and the other lines are linear in their inputs. □\square

Complexity

In the real-RAM model, line L5 costs O(K(M−L+1)L2)O(K (M - L + 1) L^2) for KK snapshots, line L2 costs O(L3)O(L^3) and line L7 costs O(ML)O(M L). One pixel costs O(KML2+L3)O(K M L^2 + L^3), and an n×nn \times n image costs O(n2(KML2+L3))O(n^2 (K M L^2 + L^3)), against O(n2M)O(n^2 M) for DAS. The extra space is O(L2)O(L^2) for the covariance. For L=M/2L = M/2 this is cubic in MM per pixel, which is the main cost of the method; faster variants use fewer subarrays, a recursive update of RR along depth, or a beamspace with fewer dimensions.

Properties

  • Distortionless: wHa=1w^H a = 1, so a signal from the look direction passes with unit gain.
  • Data-adaptive and nonlinear in the data, because ww depends on RR. For fixed RR, the output wHxw^H x is linear in xx.
  • The least power is 1/(aHR−1a)1/(a^H R^{-1} a), 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 1/(Ls)1/(L s).
  • Sensitive to errors in the steering vector and in RR; 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 λI\lambda I to RR limits the size of ww and makes the beamformer robust; for large λ\lambda 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 RR.
  • Forward-backward averaging. Adding the flipped and conjugated covariance doubles the number of samples.
  • Eigenspace and beamspace methods. Projecting onto the strongest eigenvectors of RR, 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 RR.

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 RR; without smoothing or loading the solve fails or is unstable.
  • Explicit inverse. Computing R−1R^{-1} 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 λ\lambda behaves differently at different depths; scale it by tr⁡(R)/L\operatorname{tr}(R)/L 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.

capon_beamformer.pyI0RawGitHub
# 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

  1. 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)
  2. 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)
  3. 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)
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example