Algorithm Search⌘K

Algorithmadvanced

Phase gradient autofocus

Also called PGA.

Estimate and remove a phase error common to all range bins of a SAR image from the phase derivatives of circularly shifted bright scatterers.

Time
O(I M N log N) worst
Space
O(M N) extra · data
Where
I = the number of iterations; M = the number of range bins; N = the number of azimuth samples
Properties
deterministicnot exactnot linear in dataiterative
Origin
Paul H. Eichel, Dennis C. Ghiglia, Charles V. Jakowatz Jr., 1989

Phase gradient autofocus (PGA) removes the blur that an unknown phase error causes in a synthetic aperture radar image. If the path of the antenna is not known to a small part of the wavelength, or the atmosphere adds a delay, the azimuth phase history of every range bin is multiplied by the same unknown factor eiϕ(k)e^{i\phi(k)}, and every target is smeared in azimuth by the same point spread function. PGA estimates ϕ\phi from the image itself. In each range bin it shifts the brightest pixel to the center, cuts a window around it to keep the blurred response of that scatterer and drop most others, and takes the azimuth DFT. The phase differences of neighboring samples, summed over all range bins, estimate the derivative of ϕ\phi; integrating gives ϕ\phi, which is removed. The steps are repeated, with a smaller window as the image gets sharper. A constant and a linear part of ϕ\phi only shift the image, so PGA estimates ϕ\phi up to a+bka + b k. PGA is a heuristic with strong measured results; one exact statement holds for isolated scatterers.

In plain words

A blurred radar picture is often blurred in the same way everywhere, because the same error in the flight path affects every echo. Bright single reflectors show this blur clearly. Move the brightest point of each row to the middle, so that all the blurred copies line up. Cut away the rest of each row. Now every row shows the same blur, plus a little noise. Turning each row back into the frequency form shows the error as a twist in its phase, and averaging over many rows gives a good estimate of the twist. Untwist the picture and repeat a few times.

The problem

The input is a complex image gm[j]g_m[j] with MM range bins mm and NN azimuth pixels jj. Its azimuth phase histories are Gm=DFT(gm)G_m = \text{DFT}(g_m). The model is Gm(k)=Fm(k) eiϕ(k)G_m(k) = F_m(k)\, e^{i\phi(k)}, where FmF_m is the phase history of the focused image and ϕ\phi is an unknown phase error, the same for every range bin. The output is an estimate ϕ^\hat\phi and the corrected image IDFT(Gme−iϕ^)\text{IDFT}(G_m e^{-i\hat\phi}). Because ei(a+bk)e^{i(a + b k)} with b=2πs/Nb = 2\pi s/N only multiplies the image by a constant and shifts it by ss pixels, ϕ\phi can only be found up to a+bka + b k. The Fourier sign is e−i2πfte^{-i 2\pi f t}, as for the DFT. Autofocus does not solve SAR image formation by itself; it corrects the output of an image formation algorithm.

The algorithm

  1. PGA(g, iterations, tol) ▷ g[m][j]: complex image, range bin m, azimuth pixel j; c = N/2
  2. 1for every row m: s_m[j] ← g_m[(j + j_m - c) mod N] with j_m the index of the largest |g_m[j]| ▷ center shift
  3. 2w_m[j] ← s_m[j] for |j - c| within the window, 0 elsewhere ▷ window from the -10 dB width
  4. 3h_m ← DFT(w_m) for every row m
  5. 4Δ(k) ← arg Σ_m h_m[k] conj(h_m[k - 1]) for k = 1, ..., N - 1 ▷ phase gradient, summed over rows
  6. 5ψ ← arg Σ_k e^{iΔ(k)}; φ̂(k) ← Σ_{l ≤ k} wrap(Δ(l) - ψ); remove the line a + b k from φ̂
  7. 6g_m ← IDFT(DFT(g_m) · e^{-iφ̂}) for every row m; add φ̂ to the total estimate
  8. 7if rms(φ̂) < tol or the iterations are done: return g and the total estimate; else go to L1

Line L1 moves the brightest pixel of each row to the center cc, which removes the different positions of the scatterers: each row then holds a copy of the blur that peaks at cc. Line L2 keeps a window around the center. Its width is 1.5 times the width of the region where the summed intensity ∑m∣sm[j]∣2\sum_m |s_m[j]|^2 stays above 10% of its center value, but at least 16 pixels; this follows the blur and drops clutter outside it. Line L3 returns to the phase history. Line L4 is the estimate of the gradient: in each row, hm[k] hm[k−1]‾h_m[k]\, \overline{h_m[k - 1]} has the phase ϕ(k)−ϕ(k−1)\phi(k) - \phi(k - 1) plus noise, and the sum over rows weights each row by its energy. Line L5 integrates; removing the circular mean ψ\psi first keeps the integration away from jumps of 2π2\pi, and the linear part is removed at the end. Line L6 applies the correction, and L7 stops when the correction is small. The default is at most 8 iterations and a tolerance of 0.01 rad.

Example

The tests use M=24M = 24 range bins of N=64N = 64 azimuth pixels. Each row has one bright scatterer, of amplitude 3, 4 or 5 at a random place, in complex Gaussian clutter of standard deviation 0.3 per part. The phase error is ϕ(k)=8t2+3t3\phi(k) = 8 t^2 + 3 t^3 with t=(k−32)/32t = (k - 32)/32, whose rms after removing its best line is 2.385 rad. The rms of the remaining error, also after removing the best line, is:

seed 1 iteration 2 4 8
1 0.53 0.188 0.153 0.178
2 0.385 0.222 0.197 0.194
3 0.488 0.174 0.158 0.161
4 0.40 0.172 0.131 0.113

Most of the gain comes in the first two iterations; the rest of the error is set by the clutter. For a quadratic error 6t26 t^2, a brute-force search over 41 quadratic coefficients that maximizes ∑∣g∣4\sum |g|^4 finds 6.0, and PGA gives 6.38. With one scatterer per row, no clutter and the full window, one iteration finds ϕ\phi up to a+bka + b k within 10−1510^{-15}. All values are measurements on these simulations, except the last, which the theorem of the next section predicts.

Correctness

PGA is a heuristic: there is no general guarantee that its iterations converge to the true phase error. One exact statement holds. If every row holds a single scatterer, the blur ∣IDFT(eiϕ)∣|\text{IDFT}(e^{i\phi})| has a unique largest value, the window keeps whole rows, and the differences ϕ(k)−ϕ(k−1)\phi(k) - \phi(k - 1) all lie in an open interval of length π\pi, then one iteration returns ϕ\phi exactly up to a+bka + b k. With clutter, the estimate of L4 is a sum over rows of the true gradient with independent noise, and the sum lowers the noise as the number of rows with a strong scatterer grows; this is the reason PGA works well on real scenes, and the window improves the ratio of the scatterer energy to the clutter energy in each row. The proof of the exact case is in proofs/correctness.md.

Proof: For one isolated scatterer per range bin, one PGA iteration recovers the phase error exactly up to a constant and a linear termfull

PGA as a whole is a heuristic: for images with clutter there is no theorem that its iterations converge to the true phase error, and its accuracy there is a measurement, given on the main page. We prove three exact facts about one iteration as written on the main page (lines L1 to L5): the part of the error that cannot be found, the effect of the center shift, and exact recovery for isolated scatterers.

Setting. Indices are taken mod NN and c=N/2c = N/2. The DFT is X(k)=∑jx[j]e−i2πkj/NX(k) = \sum_j x[j] e^{-i 2\pi k j/N} and IDFT\text{IDFT} is its inverse. The image rows are gm=IDFT(Fmeiϕ)g_m = \text{IDFT}(F_m e^{i\phi}) with the focused histories FmF_m and a phase error ϕ\phi common to all rows. Let b=IDFT(eiϕ)b = \text{IDFT}(e^{i\phi}), the blur of a point. wrap(t)\text{wrap}(t) is the representative of tt mod 2π2\pi in (−π,π](-\pi, \pi].

Theorem 1 (the part that cannot be found). For real aa and an integer ss, replacing ϕ(k)\phi(k) by ϕ(k)+a+2πsk/N\phi(k) + a + 2\pi s k/N multiplies every row by eiae^{ia} and shifts it circularly by ss pixels.

Proof. IDFT(Xei2πsk/N)[j]=x[j+s]\text{IDFT}(X e^{i 2\pi s k/N})[j] = x[j + s] by the shift theorem of the DFT, and the constant eiae^{ia} factors out. □\square

So no method that uses only the image can tell ϕ\phi from ϕ+a+2πsk/N\phi + a + 2\pi s k/N when the scene is unknown, and PGA reports ϕ^\hat\phi with its best line removed.

Theorem 2 (the center shift lines up isolated scatterers). Let row mm hold one scatterer, Fm(k)=αme−i2πkpm/NF_m(k) = \alpha_m e^{-i 2\pi k p_m/N} with αm≠0\alpha_m \ne 0, and let ∣b∣|b| have a unique largest value at the index j∗j^*. Then after L1, sm[j]=αm b[j+j∗−c]s_m[j] = \alpha_m\, b[j + j^* - c] for every mm, so every row is the same blur times its own amplitude, peaking at cc.

Proof. gm=IDFT(αme−i2πkpm/Neiϕ)g_m = \text{IDFT}(\alpha_m e^{-i 2\pi k p_m/N} e^{i\phi}), so by the shift theorem gm[j]=αmb[j−pm]g_m[j] = \alpha_m b[j - p_m]. Its largest modulus is at jm=pm+j∗j_m = p_m + j^*, a unique index because ∣b∣|b| has a unique maximum. L1 gives sm[j]=gm[j+jm−c]=αmb[j+j∗−c]s_m[j] = g_m[j + j_m - c] = \alpha_m b[j + j^* - c]. □\square

Theorem 3 (exact recovery). Under the hypotheses of Theorem 2, let the window of L2 keep whole rows, and let the differences δ(k)=ϕ(k)−ϕ(k−1)\delta(k) = \phi(k) - \phi(k - 1), k=1,…,N−1k = 1, \ldots, N - 1, all lie in an open interval of length π\pi. Then the estimate of L5 satisfies ϕ^(k)=ϕ(k)−aˉ−bˉk\hat\phi(k) = \phi(k) - \bar a - \bar b k for real numbers aˉ\bar a, bˉ\bar b, that is, one iteration finds ϕ\phi up to a constant and a linear term.

Proof. With d=c−j∗d = c - j^*, Theorem 2 and the shift theorem give hm(k)=DFT(sm)(k)=αmeiϕ(k)e−i2πkd/Nh_m(k) = \text{DFT}(s_m)(k) = \alpha_m e^{i\phi(k)} e^{-i 2\pi k d/N}. Hence hm[k] hm[k−1]‾=∣αm∣2ei(δ(k)−2πd/N)h_m[k]\, \overline{h_m[k - 1]} = |\alpha_m|^2 e^{i(\delta(k) - 2\pi d/N)}, and the sum over mm is (∑m∣αm∣2)ei(δ(k)−2πd/N)\big(\sum_m |\alpha_m|^2\big) e^{i(\delta(k) - 2\pi d/N)} with a positive factor, so L4 gives Δ(k)≡δ(k)−2πd/N(mod2π)\Delta(k) \equiv \delta(k) - 2\pi d/N \pmod{2\pi}. Let θ\theta be the circular mean of the δ(k)\delta(k), the argument of ∑keiδ(k)\sum_k e^{i\delta(k)}. All eiδ(k)e^{i\delta(k)} lie on an open half circle, so the sum is not zero and θ\theta can be taken in the same open interval of length π\pi; therefore ∣δ(k)−θ∣<π|\delta(k) - \theta| < \pi for every kk. The circular mean of the Δ(k)\Delta(k) is ψ≡θ−2πd/N\psi \equiv \theta - 2\pi d/N, so Δ(k)−ψ≡δ(k)−θ\Delta(k) - \psi \equiv \delta(k) - \theta, and since ∣δ(k)−θ∣<π|\delta(k) - \theta| < \pi, wrap(Δ(k)−ψ)=δ(k)−θ\text{wrap}(\Delta(k) - \psi) = \delta(k) - \theta exactly. Summing from 1 to kk gives ϕ(k)−ϕ(0)−kθ\phi(k) - \phi(0) - k\theta, which is ϕ\phi minus a constant and a linear term. Removing the best line changes it by another constant and linear term. □\square

By Theorem 1 this is all that can be recovered. With clutter, each row of L4 adds noise to ∣αm∣2ei(δ(k)−2πdm/N)|\alpha_m|^2 e^{i(\delta(k) - 2\pi d_m/N)} and the shift dmd_m may differ between rows when the brightest pixel is not the scatterer; the sum over rows averages the noise, which is why the method works well in measurements, but this is not a theorem.

Cost. One iteration does MM shifts and windows in O(MN)O(M N), MM DFTs and MM inverse DFTs in O(MNlog⁡N)O(M N \log N) with an FFT, and the sums of L4 and L5 in O(MN)O(M N). With II iterations the total is O(IMNlog⁡N)O(I M N \log N) in the real-RAM model, with O(MN)O(M N) extra space.

Complexity

Each iteration does MM shifts and windows in O(MN)O(M N), MM DFTs and MM inverse DFTs in O(MNlog⁡N)O(M N \log N) with an FFT, and the gradient sum and integration in O(MN)O(M N). With II iterations the total is O(IMNlog⁡N)O(I M N \log N) in the real-RAM model, with O(MN)O(M N) extra space.

Properties

  • Not linear in the data: the shift, the window and the phase are all chosen from the data.
  • Estimates a phase error of any shape, not only a polynomial of low order.
  • Blind to a constant and to a linear phase, which only shift the image.
  • Needs a phase error that is the same for every range bin, and scatterers that stand out from the clutter in many rows.
  • Works on the complex image, so it can be applied after any image formation algorithm.

Variants and improvements

  • Other gradient estimators. The derivative can be estimated as ∑mIm(hm‾hm′)/∑m∣hm∣2\sum_m \text{Im}(\overline{h_m} h_m') / \sum_m |h_m|^2 from a derivative of each history, or, as here, from the phase of summed products of neighbors, which needs no derivative of the data.
  • Row selection. Using only the range bins whose brightest pixel stands out most from the rest of the row improves the estimate in scenes with weak scatterers.
  • Range-dependent errors. For errors that change with range, as in wide scenes or in stripmap mode, PGA is applied to blocks of range bins or extended with a model of how ϕ\phi varies.
  • Model-based autofocus. Map drift fits a quadratic phase from the shift between images of two subapertures, and contrast or sharpness methods search over the coefficients of a polynomial phase, as in the brute-force test.

When to use it

Use PGA after forming a SAR image, for spotlight images formed by the polar format algorithm or backprojection when the motion measurement is not accurate enough, and when the phase error may have a complex shape. For a smooth error with a few known terms, a model-based method is cheaper and more robust. Scenes without bright scatterers, such as calm water or uniform fields, give PGA little to work with.

Pitfalls

  • A window that is too narrow at the start. The first window must hold the whole blur, or the estimate keeps only part of the error. Start wide and let it shrink.
  • Wrapping. Integrating gradients that are wrapped to (−π,π](-\pi, \pi] can add jumps of 2π2\pi when the gradient has a large linear part; remove the circular mean first, as in L5.
  • Errors that depend on range. PGA assumes one ϕ\phi for all range bins. If the error changes over the scene, the estimate is an average and focuses only part of it.
  • Too few iterations or too strict a stop. Most of the gain comes in the first iterations, and the rest is limited by the clutter; a very small tolerance only runs more iterations.
  • Wrong axis. PGA works on the azimuth phase history; the image must be in range bins by azimuth pixels.

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.

imgkit.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the imaging and inverse problems pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small images and signals for the imaging and inverse problems pages.

Conventions:
- A signal is a list of numbers. An image is a list of rows, img[i][j], with
  row i from the top and column j from the left.
- An n x n image covers the square [-1, 1]^2. The center of pixel (i, j) is
  x_j = -1 + (2 j + 1) / n and y_i = 1 - (2 i + 1) / n, so y goes up.
- DFT: X_k = sum_j x_j exp(-2 pi i j k / n), unnormalized; the inverse has
  the factor 1 / n. Index k stands for frequency k for k < n / 2 and k - n
  otherwise. fftshift moves the zero frequency to position n // 2.
- Periodic convolution kernels are stored with their center at index 0
  (wrapped around), so a delta kernel gives the identity and no shift.
"""

import cmath
import math

# ------------------------------------------------------------------ images


def new_image(n1, n2, value=0.0):
    """An n1 x n2 image (n1 rows, n2 columns) filled with value."""
    return [[value] * n2 for _ in range(n1)]


def img_add(a, b):
    """The pixelwise sum a + b."""
    return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]


def img_scale(a, c):
    """The image c a."""
    return [[c * x for x in row] for row in a]


def img_dot(a, b):
    """<a, b> = sum conj(a_ij) b_ij."""
    return sum(x.conjugate() * y for ra, rb in zip(a, b) for x, y in zip(ra, rb))


def img_norm(a):
    """The Euclidean (Frobenius) norm of an image."""
    return math.sqrt(sum(abs(x) ** 2 for row in a for x in row))


def flatten(img):
    """Row-major vector of an image."""
    return [x for row in img for x in row]


def unflatten(v, n1, n2):
    """The n1 x n2 image of a row-major vector."""
    return [list(v[i * n2:(i + 1) * n2]) for i in range(n1)]


# ------------------------------------------------------------------ DFT


def _is_pow2(n):
    return n > 0 and n & (n - 1) == 0


def _fft_pow2(x):
    """Iterative radix-2 FFT, unnormalized forward transform."""
    n = len(x)
    a = [complex(v) for v in x]
    j = 0
    for i in range(1, n):
        bit = n >> 1
        while j & bit:
            j ^= bit
            bit >>= 1
        j |= bit
        if i < j:
            a[i], a[j] = a[j], a[i]
    size = 2
    while size <= n:
        half = size // 2
        tw = [cmath.exp(-2j * math.pi * k / size) for k in range(half)]
        for start in range(0, n, size):
            for k in range(half):
                u = a[start + k]
                v = a[start + k + half] * tw[k]
                a[start + k] = u + v
                a[start + k + half] = u - v
        size *= 2
    return a


def dft(x):
    """X_k = sum_j x_j exp(-2 pi i j k / n). Radix-2 FFT when n is a power of 2."""
    n = len(x)
    if n == 0:
        return []
    if _is_pow2(n):
        return _fft_pow2(x)
    w = [cmath.exp(-2j * math.pi * t / n) for t in range(n)]
    return [sum(x[j] * w[(j * k) % n] for j in range(n)) for k in range(n)]


def idft(xf):
    """x_j = (1/n) sum_k X_k exp(2 pi i j k / n)."""
    n = len(xf)
    if n == 0:
        return []
    y = dft([complex(v).conjugate() for v in xf])
    return [v.conjugate() / n for v in y]


def _rows_then_cols(img, f):
    rows = [f(row) for row in img]
    cols = [f(list(col)) for col in zip(*rows)]
    return [list(r) for r in zip(*cols)]


def dft2(img):
    """2D DFT: X_kl = sum_jq x_jq exp(-2 pi i (j k / n1 + q l / n2))."""
    return _rows_then_cols(img, dft)


def idft2(img):
    """Inverse 2D DFT, with the factor 1 / (n1 n2)."""
    return _rows_then_cols(img, idft)


def _shift1(x, s):
    return list(x[s:]) + list(x[:s])


def fftshift(x):
    """Move the zero frequency to position n // 2 (1D, or both axes of an image)."""
    if x and isinstance(x[0], (list, tuple)):
        rows = [fftshift(r) for r in x]
        return _shift1(rows, (len(rows) + 1) // 2)
    return _shift1(x, (len(x) + 1) // 2)


def ifftshift(x):
    """The inverse of fftshift (1D, or both axes of an image)."""
    if x and isinstance(x[0], (list, tuple)):
        rows = [ifftshift(r) for r in x]
        return _shift1(rows, len(rows) // 2)
    return _shift1(x, len(x) // 2)


def circ_conv(x, h):
    """Periodic convolution y_i = sum_j h_j x_{(i - j) mod n}, kernel centered at index 0."""
    n = len(x)
    nz = [(j, hj) for j, hj in enumerate(h) if hj != 0]
    return [sum(hj * x[(i - j) % n] for j, hj in nz) for i in range(n)]


def circ_conv2(img, h):
    """Periodic 2D convolution with the kernel h centered at index (0, 0)."""
    n1, n2 = len(img), len(img[0])
    nz = [(p, q, h[p][q]) for p in range(len(h)) for q in range(len(h[0])) if h[p][q] != 0]
    out = new_image(n1, n2)
    for i in range(n1):
        for j in range(n2):
            out[i][j] = sum(v * img[(i - p) % n1][(j - q) % n2] for p, q, v in nz)
    return out


# ------------------------------------------------------------------ phantoms


def pixel_centers(n):
    """(xs, ys): xs[j] = -1 + (2 j + 1) / n and ys[i] = 1 - (2 i + 1) / n."""
    xs = [-1.0 + (2 * j + 1) / n for j in range(n)]
    ys = [1.0 - (2 * i + 1) / n for i in range(n)]
    return xs, ys


# Rows: rho, A, B, x0, y0, phi (degrees). A is the semi-axis along the
# direction phi (counterclockwise from the x axis), B the other semi-axis.
# Geometry and densities of Shepp and Logan (1974), as reproduced in Kak and
# Slaney, Principles of Computerized Tomographic Imaging, Table 3.1. The value
# at the center (0, 0) is 2 - 0.98 = 1.02.
SHEPP_LOGAN = [
    (2.0, 0.92, 0.69, 0.0, 0.0, 90.0),
    (-0.98, 0.874, 0.6624, 0.0, -0.0184, 90.0),
    (-0.02, 0.31, 0.11, 0.22, 0.0, 72.0),
    (-0.02, 0.41, 0.16, -0.22, 0.0, 108.0),
    (0.01, 0.25, 0.21, 0.0, 0.35, 90.0),
    (0.01, 0.046, 0.046, 0.0, 0.1, 0.0),
    (0.01, 0.046, 0.046, 0.0, -0.1, 0.0),
    (0.01, 0.046, 0.023, -0.08, -0.605, 0.0),
    (0.01, 0.023, 0.023, 0.0, -0.605, 0.0),
    (0.01, 0.046, 0.023, 0.06, -0.605, 90.0),
]

# The same ellipses with the gray levels of Toft (1996), which give more
# contrast. The value at the center is 1 - 0.8 = 0.2.
MODIFIED_SHEPP_LOGAN = [
    (rho, a, b, x0, y0, phi)
    for rho, (_, a, b, x0, y0, phi) in zip(
        (1.0, -0.8, -0.2, -0.2, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1), SHEPP_LOGAN
    )
]


def ellipse_value(x, y, table):
    """The phantom value at the point (x, y): the sum of rho over the ellipses that hold it."""
    total = 0.0
    for rho, a, b, x0, y0, phi in table:
        c, s = math.cos(math.radians(phi)), math.sin(math.radians(phi))
        dx, dy = x - x0, y - y0
        u = dx * c + dy * s
        v = -dx * s + dy * c
        if (u / a) ** 2 + (v / b) ** 2 <= 1.0:
            total += rho
    return total


def ellipse_phantom(n, table):
    """The n x n image of an ellipse table, sampled at the pixel centers."""
    xs, ys = pixel_centers(n)
    return [[ellipse_value(x, y, table) for x in xs] for y in ys]


def disk_phantom(n, radius):
    """1 at pixel centers with x^2 + y^2 <= radius^2, 0 elsewhere."""
    xs, ys = pixel_centers(n)
    r2 = radius * radius
    return [[1.0 if x * x + y * y <= r2 else 0.0 for x in xs] for y in ys]


def spikes_1d(n, positions, amplitudes):
    """A signal of length n with the given amplitudes at the given positions."""
    out = [0.0] * n
    for p, a in zip(positions, amplitudes):
        out[p] += a
    return out


# ------------------------------------------------------------------ projector


def parallel_beam_matrix(n, angles, nbins):
    """Pixel-driven discrete Radon transform of an n x n image on [-1, 1]^2.

    Each pixel center (x, y) projects to s = x cos(theta) + y sin(theta). Its
    value times the pixel area over the bin width is split linearly between
    the two nearest bin centers. The bins cover [-sqrt(2), sqrt(2)]. Row
    a * nbins + b holds angle a and bin b; column i * n + j holds pixel (i, j).
    Returns the sparse rows, each a list of (column, weight) pairs.
    Pixel-driven projection has a ripple: with a bin width close to the pixel
    size, a disk projection is off by up to about 10 percent in some bins. A
    bin of about twice the pixel size (nbins = 23 for n = 32) keeps it near
    1 percent.
    """
    xs, ys = pixel_centers(n)
    smax = math.sqrt(2.0)
    width = 2.0 * smax / nbins
    scale = (2.0 / n) ** 2 / width
    rows = []
    for theta in angles:
        c, s = math.cos(theta), math.sin(theta)
        acc = [dict() for _ in range(nbins)]
        for i, y in enumerate(ys):
            for j, x in enumerate(xs):
                t = (x * c + y * s + smax) / width - 0.5
                b0 = math.floor(t)
                frac = t - b0
                col = i * n + j
                for b, w in ((b0, 1.0 - frac), (b0 + 1, frac)):
                    if 0 <= b < nbins and w > 0.0:
                        acc[b][col] = acc[b].get(col, 0.0) + w * scale
        rows.extend(sorted(d.items()) for d in acc)
    return rows


def sp_matvec(rows, x):
    """y = A x for sparse rows of (column, weight) pairs."""
    return [sum(w * x[c] for c, w in row) for row in rows]


def sp_rmatvec(rows, y, ncols):
    """x = A^H y for sparse rows of (column, weight) pairs and ncols columns."""
    out = [0.0] * ncols
    for row, yi in zip(rows, y):
        if yi == 0:
            continue
        for c, w in row:
            out[c] += w.conjugate() * yi
    return out


# ------------------------------------------------------------------ noise


def gauss_noise(rng, shape, sigma):
    """Independent N(0, sigma^2) values: a list for an int shape, an image for (n1, n2)."""
    if isinstance(shape, int):
        return [rng.gauss(0.0, sigma) for _ in range(shape)]
    n1, n2 = shape
    return [[rng.gauss(0.0, sigma) for _ in range(n2)] for _ in range(n1)]


def _poisson_small(rng, lam):
    """Knuth's product method, exact for a mean lam <= 30."""
    limit = math.exp(-lam)
    k, p = 0, rng.random()
    while p > limit:
        k += 1
        p *= rng.random()
    return k


def poisson_sample(rng, lam):
    """An exact Poisson(lam) sample: a sum of Knuth samples with means at most 30."""
    if lam < 0:
        raise ValueError("negative mean")
    total = 0
    while lam > 30.0:
        total += _poisson_small(rng, 30.0)
        lam -= 30.0
    if lam > 0.0:
        total += _poisson_small(rng, lam)
    return total
phase_gradient_autofocus.py 86 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/phase-gradient-autofocus/. The authors are listed in prov/Y2C9T3.jsonl.
"""Phase gradient autofocus (PGA) for a complex SAR image.

Layout: img[m][j], row m a range bin, column j a cross-range (azimuth) pixel.
The azimuth phase history of row m is H_m = DFT(img[m]) (the Fourier sign is
exp(-i 2 pi f t), the sign of the DFT). An unknown phase error phi(k) of the
aperture, the same for every range bin, multiplies every H_m(k) by
exp(i phi(k)) and blurs the image in azimuth. PGA estimates phi from the
image itself and removes it. A constant and a linear part of phi only shift
the image, so PGA estimates phi up to a + b k and removes that part.
"""

import cmath
import math

from imgkit import dft, idft


def apply_phase(img, phi):
    """Multiply the azimuth phase history of every row by exp(i phi(k))."""
    rot = [cmath.exp(1j * p) for p in phi]
    return [idft([h * r for h, r in zip(dft(row), rot)]) for row in img]


def remove_linear(phi):
    """phi minus its least-squares line a + b k."""
    n = len(phi)
    km = (n - 1) / 2.0
    pm = sum(phi) / n
    skk = sum((k - km) ** 2 for k in range(n))
    b = sum((k - km) * (p - pm) for k, p in enumerate(phi)) / skk
    return [p - pm - b * (k - km) for k, p in enumerate(phi)]


def _window_width(rows, min_width):
    """Twice the distance from the center to the edge of the -10 dB region of the summed intensity."""
    n = len(rows[0])
    c = n // 2
    s = [sum(abs(r[j]) ** 2 for r in rows) for j in range(n)]
    top = s[c]
    half = 0
    while half < c and s[c - half - 1] >= 0.1 * top and s[(c + half + 1) % n] >= 0.1 * top:
        half += 1
    return max(min_width, int(1.5 * (2 * half + 1)))


def pga_once(img, width=None, min_width=16):
    """One PGA iteration. Returns (phase estimate, window width used).

    width=None picks the window from the -10 dB width of the summed
    intensity; width=n keeps whole rows.
    """
    n = len(img[0])
    c = n // 2
    shifted = []
    for row in img:
        jmax = max(range(n), key=lambda j: abs(row[j]))
        shifted.append([row[(j + jmax - c) % n] for j in range(n)])  # @line L1
    w = _window_width(shifted, min_width) if width is None else width
    lo, hi = c - w // 2, c - w // 2 + w
    windowed = [[v if lo <= j < hi else 0j for j, v in enumerate(row)] for row in shifted]  # @line L2
    hist = [dft(row) for row in windowed]  # @line L3
    grad = [cmath.phase(sum(h[k] * h[k - 1].conjugate() for h in hist)) for k in range(1, n)]  # @line L4
    # The mean gradient is a linear phase (a shift). Remove it on the circle
    # first, so that the integration does not pick up 2 pi jumps.
    mean = cmath.phase(sum(cmath.exp(1j * g) for g in grad))
    phi = [0.0]
    for g in grad:
        phi.append(phi[-1] + cmath.phase(cmath.exp(1j * (g - mean))))  # @line L5
    return remove_linear(phi), w  # @line L5


def pga(img, iterations=8, width=None, tol=0.01, min_width=16):
    """Iterate PGA: estimate, correct, repeat. Returns (focused image, total phase estimate)."""
    n = len(img[0])
    total = [0.0] * n
    cur = img
    for _ in range(iterations):
        est, _ = pga_once(cur, width, min_width)
        cur = apply_phase(cur, [-p for p in est])  # @line L6
        total = [t + p for t, p in zip(total, est)]
        rms = math.sqrt(sum(p * p for p in est) / n)
        if rms < tol:  # @line L7
            break
    return cur, remove_linear(total)
test_phase_gradient_autofocus.py 81 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/phase-gradient-autofocus/. The authors are listed in prov/Y2C9T3.jsonl.

import cmath
import math
import random

from phase_gradient_autofocus import apply_phase, pga, pga_once, remove_linear

N, M = 64, 24
Q = [((k - N / 2) / (N / 2)) ** 2 for k in range(N)]
SMOOTH = [8 * q + 3 * ((k - N / 2) / (N / 2)) ** 3 for k, q in enumerate(Q)]


def rms(v):
    return math.sqrt(sum(x * x for x in v) / len(v))


def points_only(seed):
    rng = random.Random(seed)
    img = [[0j] * N for _ in range(M)]
    for m in range(M):
        img[m][rng.randrange(N)] = complex(rng.gauss(0, 1), rng.gauss(0, 1))
    return img


def with_clutter(seed):
    rng = random.Random(seed)
    img = [[complex(rng.gauss(0, 0.3), rng.gauss(0, 0.3)) for _ in range(N)] for _ in range(M)]
    for m in range(M):
        img[m][rng.randrange(N)] += rng.choice([3, 4, 5]) * cmath.exp(2j * math.pi * rng.random())
    return img


def test_one_iteration_is_exact_for_isolated_points() -> None:
    """Theorem: one point per range bin, no clutter, full window: phi is found up to a + b k."""
    rng = random.Random(5)
    phi = [s + rng.gauss(0, 0.3) for s in SMOOTH]
    est, width = pga_once(apply_phase(points_only(5), phi), width=N)
    assert width == N
    assert max(abs(r) for r in remove_linear([p - e for p, e in zip(phi, est)])) < 1e-9


def test_reduces_a_smooth_phase_error_in_clutter() -> None:
    """Measurement: bright points in Gaussian clutter, default adaptive window."""
    start = rms(remove_linear(SMOOTH))
    assert start > 2.0
    for seed in (1, 2, 3, 4):
        _, est = pga(apply_phase(with_clutter(seed), SMOOTH))
        assert rms(remove_linear([p - e for p, e in zip(SMOOTH, est)])) < 0.25


def test_agrees_with_a_brute_force_search_on_a_quadratic_error() -> None:
    """Reference: try every quadratic coefficient on a grid and keep the sharpest image."""
    blurred = apply_phase(with_clutter(11), [6.0 * q for q in Q])

    def sharpness(c):
        img = apply_phase(blurred, [-c * q for q in Q])
        return sum(abs(v) ** 4 for row in img for v in row)

    brute = max((0.25 * i for i in range(41)), key=sharpness)
    _, est = pga(blurred)
    qc = remove_linear(Q)
    c_pga = sum(a * b for a, b in zip(qc, est)) / sum(a * a for a in qc)
    assert abs(brute - 6.0) <= 0.25
    assert abs(c_pga - brute) < 0.4


def test_apply_phase_round_trip() -> None:
    img = with_clutter(3)
    back = apply_phase(apply_phase(img, SMOOTH), [-p for p in SMOOTH])
    assert max(abs(a - b) for ra, rb in zip(img, back) for a, b in zip(ra, rb)) < 1e-9


def test_linear_phase_only_shifts_the_image() -> None:
    img = points_only(2)
    shifted = apply_phase(img, [2 * math.pi * 3 * k / N for k in range(N)])
    for row, srow in zip(img, shifted):
        for j in range(N):
            assert abs(srow[j] - row[(j + 3) % N]) < 1e-9
    assert max(abs(v) for v in remove_linear([1.5 + 0.2 * k for k in range(N)])) < 1e-12

History

Eichel, Ghiglia and Jakowatz (1989) proposed estimating the SAR phase error from the image itself, in a paper on speckle processing for phase correction. Wahl, Eichel, Ghiglia and Jakowatz (1994) described the full algorithm, with the four steps of center shift, windowing, phase gradient estimation and iterative correction, and presented it as a robust tool for phase errors of high order. The book of Jakowatz and colleagues (1996) treats it in its chapter on phase errors and autofocus, and PGA has since become a standard autofocus method for spotlight SAR.

References

  1. Daniel E. Wahl, Paul H. Eichel, Dennis C. Ghiglia and Charles V. Jakowatz Jr., Phase gradient autofocus: a robust tool for high resolution SAR phase correction, IEEE Transactions on Aerospace and Electronic Systems 30(3), 1994, 827 to 835, the four steps (center shift, windowing, phase gradient estimation, iterative correction) and the measured results (general locator)
  2. Paul H. Eichel, Dennis C. Ghiglia and Charles V. Jakowatz Jr., Speckle processing method for synthetic-aperture-radar phase correction, Optics Letters 14(1), 1989, the first description of the method (general locator)
  3. Charles V. Jakowatz Jr., Daniel E. Wahl, Paul H. Eichel, Dennis C. Ghiglia and Paul A. Thompson, Spotlight-Mode Synthetic Aperture Radar: A Signal Processing Approach, Kluwer, 1996, the chapter Phase Errors and Autofocus in SAR Imagery

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.data
  • 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