Algorithm Search⌘K

Algorithmadvanced

Polar format algorithm

Form spotlight SAR images by placing dechirped pulses on polar lines of 2D Fourier space, interpolating to a rectangular grid and taking an FFT.

Time
O(M N (log(M N) + K)) worst
Space
O(M N) extra · data
Where
K = the number of taps of the interpolator; M = the number of pulses; N = the number of fast-time samples per pulse
Properties
deterministicnot exactlinear in dataiterative
Origin
Jack L. Walker, 1980

The polar format algorithm (PFA) forms images from spotlight synthetic aperture radar data. In spotlight mode the radar keeps one patch of ground in its beam, and each echo is dechirped against the echo of the patch center. Under the plane-wave approximation, a dechirped pulse is then a band of one radial line of the 2D Fourier transform of the scene, the line at the look angle of that pulse; this is the Fourier slice theorem of tomography. All pulses together sample the transform on a polar raster, an annular sector. PFA interpolates these samples onto a rectangular grid, first along range and then along azimuth, and takes one 2D inverse FFT. It is the radar form of direct Fourier reconstruction in computed tomography, with band-pass data on a narrow sector of angles.

In plain words

When the radar watches one patch from slowly changing directions, each pulse, after a simple mixing step, tells you one line of the pattern of stripes that make up the picture of the patch. Each look direction gives the line at its own angle, so the data fill a fan-shaped piece of the stripe pattern. A fast inverse transform needs the pattern on a square grid, not on a fan. So you first estimate the values on the square grid from the nearby fan values, and then run the fast inverse transform. The picture of the patch appears in one step.

The problem

The input is the dechirped data d[m][n]d[m][n] of MM pulses and NN fast-time samples. Pulse mm looks at the scene center from the angle θm\theta_m, from the radar position −Rc(sin⁡θm,cos⁡θm)-R_c(\sin\theta_m, \cos\theta_m), and sample nn has the radial spatial frequency un=4πfn/cu_n = 4\pi f_n / c, where fnf_n runs over the band f0±B/2f_0 \pm B/2. A point (x,y)(x, y) of amplitude aa contributes a e−iunΔRma\, e^{-i u_n \Delta R_m} with ΔRm=∣am−(x,y)∣−Rc\Delta R_m = |a_m - (x, y)| - R_c, its range relative to the center. The Fourier sign is e−i2πfte^{-i 2\pi f t}, as for the DFT; radar books often use e+jωte^{+j\omega t} and so the opposite signs. Under the plane-wave approximation ΔRm=xsin⁡θm+ycos⁡θm\Delta R_m = x \sin\theta_m + y \cos\theta_m, so d[m][n]=σ^(unsin⁡θm,uncos⁡θm)d[m][n] = \hat\sigma(u_n \sin\theta_m, u_n \cos\theta_m) with σ^(kx,ky)=∑a e−i(kxx+kyy)\hat\sigma(k_x, k_y) = \sum a\, e^{-i (k_x x + k_y y)}. The output is the complex image σ\sigma on a pixel grid around the center.

The algorithm

The Cartesian grid has NN rows kyk_y evenly spaced from umin⁡u_{\min} to umax⁡cos⁡(Δθ/2)u_{\max} \cos(\Delta\theta/2) and MM columns kxk_x evenly spaced across ±umin⁡tan⁡(Δθ/2)\pm u_{\min} \tan(\Delta\theta/2), the largest rectangle inside the sector of total angle Δθ\Delta\theta.

  1. PFA(d, u_n, θ_m) ▷ d[m][n]: dechirped pulse m, sample n; returns the image
  2. 1for every pulse m and grid row k_y: R[m][k_y] ← d[m][·] read at u = k_y / cos θ_m ▷ range interpolation
  3. 2for every grid row k_y and column k_x: G[k_y][k_x] ← R[·][k_y] read at θ = atan2(k_x, k_y) ▷ azimuth interpolation
  4. 3I ← fftshift(2D IDFT of G)
  5. 4image[i][j] ← N M · I[i][j] · e^{i (k_{y,0} y_i + k_{x,0} x_j)} ▷ scale and the phase of the grid origin

Line L1 interpolates each pulse along its radial line, so that its samples land on the rows of constant kyk_y: the point of the line at radius uu has ky=ucos⁡θmk_y = u \cos\theta_m. After L1 the samples lie on a raster shaped like a keystone, with rows of constant kyk_y and, in each row, points at kx=kytan⁡θmk_x = k_y \tan\theta_m that are not evenly spaced. Line L2 interpolates along each row to even kxk_x. Both steps use an 8-tap Hann-weighted sinc interpolation, which assumes the scene is small enough that its transform is smooth on the scale of the sample spacing. Line L3 is a 2D inverse FFT. Line L4 undoes the 1/(NM)1/(NM) of the inverse DFT and the phase from the grid not starting at k=0k = 0, so that a point target at a pixel center gives NMaN M a at that pixel. The pixel spacing is 2π/(NΔky)2\pi/(N \Delta k_y) in yy and 2π/(MΔkx)2\pi/(M \Delta k_x) in xx.

Example

The tests use f0=10f_0 = 10 GHz (λ=3\lambda = 3 cm), B=1B = 1 GHz, N=32N = 32 samples, M=32M = 32 pulses over a total angle Δθ=0.1\Delta\theta = 0.1 rad, and Rc=1000R_c = 1000 m. The range resolution c/(2B)c/(2B) is 0.15 m and the cross-range resolution λ/(2Δθ)\lambda / (2\Delta\theta) is also 0.15 m. The inscribed rectangle gives pixels of 0.158 m in xx and 0.147 m in yy. Three targets at pixel centers, with plane-wave data, give:

target (x,y)(x, y) in m amplitude ∣\lvertimage / 1024 −- amplitude∣\rvert
(0, 0) 1 0.0063
(0.631, -0.883) 0.5 0.0018
(-1.104, 1.178) 0.8i0.8i 0.0088

At these pixels the image agrees within 1% of 1024 with the brute-force polar sum ∑m,nd[m][n]e+iun(xsin⁡θm+ycos⁡θm)\sum_{m,n} d[m][n] e^{+i u_n (x \sin\theta_m + y \cos\theta_m)}. Away from the targets both are below 7% of 1024; they differ there because the sum uses the whole sector and PFA the inscribed rectangle, so their side lobes differ.

With exact spherical ranges instead of plane waves, the largest pixel of a target at (1.262,1.178)(1.262, 1.178) m is 1.009 of 1024 at Rc=1000R_c = 1000 m, 0.990 at Rc=100R_c = 100 m, and 0.816 at Rc=30R_c = 30 m, while a target at (0,1.178)(0, 1.178) m keeps 1.006 at every range. At Rc=30R_c = 30 m the brute-force sum of the same data peaks at 0.998 at a point 0.05 m in xx and 0.03 m in yy from the pixel. So at this range the loss is mostly a shift of a third of a pixel, a geometric distortion, not a blur. All values in this section are measurements on these simulations.

Correctness

The algorithm is linear. Under the plane-wave approximation, the data are exact samples of σ^\hat\sigma on the polar raster, by the definition of σ^\hat\sigma and the Fourier slice theorem. If the two interpolations are exact, GG holds σ^\hat\sigma on the Cartesian grid, and the inverse DFT of L3 with the phase of L4 gives the scene convolved with the 2D Dirichlet kernel of the rectangle; a target at a pixel center gives exactly NMaN M a there. Without the plane-wave approximation, ΔRm=xsin⁡θm+ycos⁡θm+(xcos⁡θm−ysin⁡θm)2/(2Rc)\Delta R_m = x \sin\theta_m + y \cos\theta_m + (x \cos\theta_m - y \sin\theta_m)^2/(2 R_c) plus smaller terms, and the second term shifts and blurs targets far from the center. The proofs are in proofs/correctness.md.

Proof: Under the plane-wave model the dechirped data are the scene's 2D Fourier transform on a polar raster, so exact regridding and an inverse DFT recover the scenefull

We prove four facts about the polar format algorithm as written on the main page (lines L1 to L4). Theorems 1 to 3 are exact under the plane-wave approximation and with exact interpolation in L1 and L2. Theorem 4 is an exact expansion of the range without the plane-wave approximation and shows which term the algorithm ignores; its effect on a given image is a measurement, reported on the main page.

Setting. Pulse mm is sent from am=−Rc(sin⁡θm,cos⁡θm)a_m = -R_c(\sin\theta_m, \cos\theta_m). A point target of amplitude aa at p=(x,y)p = (x, y) has the relative range ΔRm=∣am−p∣−Rc\Delta R_m = |a_m - p| - R_c. After dechirp against the scene center, sample nn of pulse mm is a e−iunΔRma\, e^{-i u_n \Delta R_m} with un=4πfn/cu_n = 4\pi f_n / c, and the data of several targets add. The Fourier sign is e−i2πfte^{-i 2\pi f t}. Write σ^(kx,ky)=∑a e−i(kxx+kyy)\hat\sigma(k_x, k_y) = \sum a\, e^{-i (k_x x + k_y y)} over the targets. The Cartesian grid has the rows ky,i=ky,0+i Δkyk_{y,i} = k_{y,0} + i\, \Delta k_y for 0≤i<N0 \le i < N and the columns kx,j=kx,0+j Δkxk_{x,j} = k_{x,0} + j\, \Delta k_x for 0≤j<M0 \le j < M, all inside the polar sector, and the pixels are yq=(q−N/2) 2π/(NΔky)y_q = (q - N/2)\, 2\pi/(N \Delta k_y) and xr=(r−M/2) 2π/(MΔkx)x_r = (r - M/2)\, 2\pi/(M \Delta k_x).

Theorem 1 (linearity). The output of L1 to L4 is linear in the data.

Proof. L1 and L2 are weighted sums with weights fixed by the geometry, L3 is an inverse DFT and a fixed permutation, and L4 is a product with fixed numbers. □\square

Theorem 2 (polar samples of the Fourier transform). Under the plane-wave approximation ΔRm=xsin⁡θm+ycos⁡θm\Delta R_m = x \sin\theta_m + y \cos\theta_m, the data are d[m][n]=σ^(unsin⁡θm,uncos⁡θm)d[m][n] = \hat\sigma(u_n \sin\theta_m, u_n \cos\theta_m), the transform of the scene at radius unu_n and angle θm\theta_m from the kyk_y axis.

Proof. For one target, unΔRm=(unsin⁡θm)x+(uncos⁡θm)yu_n \Delta R_m = (u_n \sin\theta_m) x + (u_n \cos\theta_m) y, so a e−iunΔRm=a e−i(kxx+kyy)a\, e^{-i u_n \Delta R_m} = a\, e^{-i (k_x x + k_y y)} at (kx,ky)=un(sin⁡θm,cos⁡θm)(k_x, k_y) = u_n(\sin\theta_m, \cos\theta_m). Sum over the targets. □\square

This is the Fourier slice theorem for this geometry: each pulse is a band of the radial line of σ^\hat\sigma at its own angle.

Theorem 3 (regridding and focus). Assume Theorem 2 and that L1 and L2 return the exact values of the functions they interpolate. Then G[i][j]=σ^(kx,j,ky,i)G[i][j] = \hat\sigma(k_{x,j}, k_{y,i}), and the image of L4 at the pixel (xr,yq)(x_r, y_q) is

∑a DN(Δky(yq−y)) DM(Δkx(xr−x)),DL(t)=∑leilt,\sum a\, D_N\big(\Delta k_y (y_q - y)\big)\, D_M\big(\Delta k_x (x_r - x)\big), \qquad D_L(t) = \sum_{l} e^{i l t},

where ll runs over the LL integers from −L/2-L/2 to L/2−1L/2 - 1, up to a phase factor of modulus one that is 1 when (x,y)(x, y) is a pixel. In particular a target at a pixel gives exactly NMaN M a there.

Proof. The point of the radial line at angle θm\theta_m with ky=ky,ik_y = k_{y,i} has radius ky,i/cos⁡θmk_{y,i}/\cos\theta_m, so L1 gives R[m][i]=σ^(ky,itan⁡θm,ky,i)R[m][i] = \hat\sigma(k_{y,i} \tan\theta_m, k_{y,i}). For a fixed row these are values of the smooth function kx↦σ^(kx,ky,i)k_x \mapsto \hat\sigma(k_x, k_{y,i}) at the points kx=ky,itan⁡θmk_x = k_{y,i}\tan\theta_m, the angle θ=atan2⁡(kx,ky,i)\theta = \operatorname{atan2}(k_x, k_{y,i}) is a one-to-one parameter of the row, and L2 reads the row at the angle of kx,jk_{x,j}, which gives σ^(kx,j,ky,i)\hat\sigma(k_{x,j}, k_{y,i}). For one target, G[i][j]=a e−i(kx,0x+ky,0y) e−i(jΔkxx+iΔkyy)G[i][j] = a\, e^{-i (k_{x,0} x + k_{y,0} y)}\, e^{-i (j \Delta k_x x + i \Delta k_y y)}. The inverse DFT of L3 divides by NMN M and multiplies by e+i2π(iq′/N+jr′/M)e^{+i 2\pi (i q' / N + j r' / M)}, and the fftshift sets q′=q−N/2q' = q - N/2 and r′=r−M/2r' = r - M/2, so 2πiq′/N=i Δky yq2\pi i q'/N = i\, \Delta k_y\, y_q and 2πjr′/M=j Δkx xr2\pi j r'/M = j\, \Delta k_x\, x_r. The sum over ii and jj is a product of two geometric sums, ∑iei iΔky(yq−y)\sum_i e^{i\, i \Delta k_y (y_q - y)} and ∑jei jΔkx(xr−x)\sum_j e^{i\, j \Delta k_x (x_r - x)}; shifting the index to center it gives DND_N and DMD_M times a phase of modulus one that is 1 when y=yqy = y_q and x=xrx = x_r. L4 multiplies by NMN M and by ei(ky,0yq+kx,0xr)e^{i (k_{y,0} y_q + k_{x,0} x_r)}; when (x,y)=(xr,yq)(x, y) = (x_r, y_q) this cancels e−i(kx,0x+ky,0y)e^{-i (k_{x,0} x + k_{y,0} y)}, and DN(0)DM(0)=NMD_N(0) D_M(0) = N M. By Theorem 1 the targets add. □\square

Theorem 4 (the term that the algorithm ignores). Without the plane-wave approximation, with s=xsin⁡θ+ycos⁡θs = x \sin\theta + y \cos\theta and t=xcos⁡θ−ysin⁡θt = x \cos\theta - y \sin\theta,

ΔR=(Rc+s)2+t2−Rc=s+t22Rc+O(∣p∣3Rc2).\Delta R = \sqrt{(R_c + s)^2 + t^2} - R_c = s + \frac{t^2}{2 R_c} + O\Big(\frac{|p|^3}{R_c^2}\Big).

Proof. ∣am−p∣2=Rc2+2Rcs+∣p∣2|a_m - p|^2 = R_c^2 + 2 R_c s + |p|^2, and ∣p∣2=s2+t2|p|^2 = s^2 + t^2 because (sin⁡θ,cos⁡θ)(\sin\theta, \cos\theta) and (cos⁡θ,−sin⁡θ)(\cos\theta, -\sin\theta) are orthonormal, so ∣am−p∣=(Rc+s)2+t2|a_m - p| = \sqrt{(R_c + s)^2 + t^2}. Expand (Rc+s)2+t2=(Rc+s)1+t2/(Rc+s)2=Rc+s+t2/(2(Rc+s))+O(t4/Rc3)\sqrt{(R_c + s)^2 + t^2} = (R_c + s)\sqrt{1 + t^2/(R_c + s)^2} = R_c + s + t^2/(2(R_c + s)) + O(t^4/R_c^3), and t2/(2(Rc+s))=t2/(2Rc)+O(∣p∣3/Rc2)t^2/(2(R_c + s)) = t^2/(2R_c) + O(|p|^3/R_c^2). □\square

The term t2/(2Rc)t^2/(2R_c) adds the phase −unt2/(2Rc)-u_n t^2/(2R_c), which Theorem 2 leaves out. At θ=0\theta = 0 it is x2/(2Rc)x^2/(2R_c), a range offset for every pulse; its change with θ\theta is to first order −xy θ/Rc-x y\, \theta / R_c, a cross-range offset of about xy/Rcx y / R_c. Both are shifts, so the first effect of a large scene at short range is a geometric distortion; the parts of the term that are quadratic in θ\theta or vary with unu_n blur the image, which matters only at still shorter range. Neither is corrected by L1 to L4.

Cost. L1 and L2 each do MNM N interpolations of KK taps, L3 is a 2D FFT of O(MNlog⁡(MN))O(M N \log(M N)) operations and L4 is O(MN)O(M N). The total is O(MN(log⁡(MN)+K))O(M N (\log(M N) + K)) in the real-RAM model, with O(MN)O(M N) extra space.

Complexity

Line L1 does NN interpolations of KK taps per pulse, O(MNK)O(M N K). Line L2 does MM per row, O(MNK)O(M N K). Line L3 is a 2D FFT, O(MNlog⁡(MN))O(M N \log(M N)), and L4 is O(MN)O(M N). The total is O(MN(log⁡(MN)+K))O(M N (\log(M N) + K)) in the real-RAM model, with O(MN)O(M N) extra space for the intermediate grid.

Properties

  • Linear in the data.
  • Exact under the plane-wave approximation, up to the interpolation.
  • The scene size is limited: the error of the plane-wave approximation grows with the square of the distance from the center divided by RcR_c, so large scenes at short range are split into patches.
  • The image is on a grid in the plane of the Fourier slices, the slant plane; a projection to the ground is a separate step.

Variants and improvements

  • Order of interpolation. Range first and then azimuth, as here, is the usual separable order; azimuth-first versions and the 2D nonuniform FFT avoid separate passes.
  • Chirp-Z in azimuth. The azimuth interpolation of L2 can be replaced by a resampling of each row with a chirp-Z transform, which avoids interpolation error along that axis.
  • Wavefront curvature correction. A space-variant post-filter, or a subdivision of the scene into small patches each with its own center, removes most of the distortion and blur of large scenes.
  • ISAR. The same algorithm forms images of turning targets in inverse SAR, where the angle comes from the motion of the target.
  • Autofocus. Phase gradient autofocus was developed for spotlight images formed this way.

When to use it

Use PFA for spotlight data that are dechirped in hardware, for scenes that are small compared to the range, and when the look angle changes by a small amount. It is fast and its errors are well understood. For large scenes at short range, wide angles or curved flight paths, use backprojection, which has no plane-wave approximation, or the omega-k algorithm for a straight track.

Pitfalls

  • Interpolating to the wrong radius. In L1 the range sample for row kyk_y is at u=ky/cos⁡θmu = k_y / \cos\theta_m, not at u=kyu = k_y; the second leaves a range error that grows with ∣θm∣|\theta_m|.
  • A grid outside the sector. If the Cartesian grid extends past the polar data, L1 or L2 reads outside the samples and the image gets edge artifacts. Use the inscribed rectangle, or set the outside values to zero on purpose.
  • Forgetting the grid origin. The grid starts at ky=umin⁡k_y = u_{\min}, not at 0. Without the phase of L4 the image has a phase that varies with position, which spoils interferometry and autofocus.
  • Scenes too large for the range. The plane-wave error grows as the square of the distance from the center; check it against the depth of focus of the system before trusting the corners.
  • Sign convention. With the data e−iuΔRe^{-i u \Delta R}, the image needs the inverse DFT, which has e+ie^{+i}; using the forward DFT flips the image.

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
polar_format_algorithm.py 133 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/polar-format-algorithm/. The authors are listed in prov/8JG48Y.jsonl.
"""Polar format algorithm (PFA) for spotlight SAR.

Geometry: the scene is a plane with points p = (x, y) and its center at the
origin. Pulse m looks at the center from the angle theta_m, from the radar
position a_m = -Rc (sin theta_m, cos theta_m). The radar dechirps each echo
against the echo of the center, so fast-time sample n of pulse m holds

    d[m][n] = sum over targets of amp exp(-i u_n dR_m(p)),

with u_n = 4 pi (f0 + Kr t_n) / c and dR_m(p) = |a_m - p| - Rc, the range
relative to the center. The Fourier sign is exp(-i 2 pi f t), the sign of the
DFT, so the image is a sum with exp(+i ...). In the far field,
dR_m(p) is close to x sin theta_m + y cos theta_m, so d samples the 2D Fourier
transform of the scene on a polar raster: radius u_n, angle theta_m. PFA
resamples this raster onto a Cartesian grid (range then azimuth, the keystone
order) and takes one 2D inverse DFT.
"""

import cmath
import math

from imgkit import fftshift, idft2

C = 3.0e8


class Spotlight:
    """The parameters of a spotlight collection (SI units)."""

    def __init__(self, f0=10e9, bandwidth=1e9, n_fast=32, n_pulses=32, span=0.1, rc=1000.0):
        self.f0 = f0
        self.bandwidth = bandwidth
        self.n_fast = n_fast
        self.n_pulses = n_pulses
        self.span = span  # the total change of look angle, in radians
        self.rc = rc

    def u(self, n):
        """The radial spatial frequency of fast-time sample n (rad/m)."""
        f = self.f0 - self.bandwidth / 2 + self.bandwidth * n / (self.n_fast - 1)
        return 4.0 * math.pi * f / C

    def theta(self, m):
        return -self.span / 2 + self.span * m / (self.n_pulses - 1)


def simulate_dechirped(g, targets, plane_wave=False):
    """Dechirped data d[m][n] of point targets (x, y, amp): exact ranges, or the plane-wave model."""
    data = []
    for m in range(g.n_pulses):
        th = g.theta(m)
        s, c = math.sin(th), math.cos(th)
        ax, ay = -g.rc * s, -g.rc * c
        row = [0j] * g.n_fast
        for x, y, amp in targets:
            dr = x * s + y * c if plane_wave else math.hypot(x - ax, y - ay) - g.rc
            for n in range(g.n_fast):
                row[n] += amp * cmath.exp(-1j * g.u(n) * dr)
        data.append(row)
    return data


def sinc_interp(seq, t, taps=8):
    """Value of a sampled band-limited sequence at the fractional index t (Hann-windowed sinc)."""
    half = taps // 2
    i0 = math.floor(t)
    acc = 0j
    for k in range(i0 - half + 1, i0 + half + 1):
        if 0 <= k < len(seq):
            x = t - k
            w = 1.0 if x == 0 else math.sin(math.pi * x) / (math.pi * x)
            acc += seq[k] * w * (0.5 + 0.5 * math.cos(math.pi * x / half))
    return acc


def cartesian_grid(g):
    """The keystone grid inside the polar annulus: ky values (rows) and kx values (columns)."""
    half = g.span / 2
    ky_lo, ky_hi = g.u(0), g.u(g.n_fast - 1) * math.cos(half)
    kys = [ky_lo + (ky_hi - ky_lo) * n / (g.n_fast - 1) for n in range(g.n_fast)]
    kx_hi = ky_lo * math.tan(half)
    kxs = [-kx_hi + 2 * kx_hi * m / g.n_pulses for m in range(g.n_pulses)]
    return kys, kxs


def pixel_coords(g):
    """The image coordinates: ys for rows, xs for columns, both centered on the scene center."""
    kys, kxs = cartesian_grid(g)
    dky = kys[1] - kys[0]
    dkx = kxs[1] - kxs[0]
    ny, nx = len(kys), len(kxs)
    ys = [2 * math.pi * (i - ny // 2) / (ny * dky) for i in range(ny)]
    xs = [2 * math.pi * (j - nx // 2) / (nx * dkx) for j in range(nx)]
    return ys, xs


def pfa(g, data):
    """Focus dechirped spotlight data. Returns img[i][j] at (xs[j], ys[i]) of pixel_coords."""
    kys, kxs = cartesian_grid(g)
    u0 = g.u(0)
    du = g.u(1) - g.u(0)
    dth = g.span / (g.n_pulses - 1)
    # range interpolation: on pulse m, the sample with u cos(theta_m) = ky
    stage = []
    for m in range(g.n_pulses):
        c = math.cos(g.theta(m))
        stage.append([sinc_interp(data[m], (ky / c - u0) / du) for ky in kys])  # @line L1
    # azimuth interpolation: on row ky, the pulse with ky tan(theta) = kx
    grid = []
    for n, ky in enumerate(kys):
        col = [stage[m][n] for m in range(g.n_pulses)]
        grid.append([sinc_interp(col, (math.atan2(kx, ky) + g.span / 2) / dth) for kx in kxs])  # @line L2
    img = fftshift(idft2(grid))  # @line L3
    ys, xs = pixel_coords(g)
    ny, nx = len(kys), len(kxs)
    return [[img[i][j] * ny * nx * cmath.exp(1j * (kys[0] * ys[i] + kxs[0] * xs[j]))
             for j in range(nx)] for i in range(ny)]  # @line L4


def polar_sum(g, data, pixels):
    """Brute force: the direct polar Fourier sum at each pixel (x, y), O(N^2) per pixel."""
    out = []
    for x, y in pixels:
        acc = 0j
        for m in range(g.n_pulses):
            th = g.theta(m)
            proj = x * math.sin(th) + y * math.cos(th)
            for n in range(g.n_fast):
                acc += data[m][n] * cmath.exp(1j * g.u(n) * proj)
        out.append(acc)
    return out
test_polar_format_algorithm.py 70 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/polar-format-algorithm/. The authors are listed in prov/8JG48Y.jsonl.

import math

from polar_format_algorithm import Spotlight, cartesian_grid, pfa, pixel_coords, polar_sum, simulate_dechirped

G = Spotlight()
YS, XS = pixel_coords(G)
TARGETS = [(XS[16], YS[16], 1.0), (XS[20], YS[10], 0.5), (XS[9], YS[24], 0.8j)]
GAIN = G.n_fast * G.n_pulses
PLANE = simulate_dechirped(G, TARGETS, plane_wave=True)
IMG = pfa(G, PLANE)


def peak(img):
    return max((abs(v), i, j) for i, row in enumerate(img) for j, v in enumerate(row))


def test_targets_focus_at_their_pixels_with_their_amplitudes() -> None:
    for x, y, amp in TARGETS:
        i, j = YS.index(y), XS.index(x)
        assert abs(IMG[i][j] / GAIN - amp) < 0.02


def test_matches_the_direct_polar_fourier_sum() -> None:
    on = [(16, 16), (10, 20), (24, 9)]
    off = [(i, j) for i in range(8, 25, 4) for j in range(8, 25, 4) if (i, j) not in on]
    ref = polar_sum(G, PLANE, [(XS[j], YS[i]) for i, j in on + off])
    for (i, j), r in zip(on, ref):
        assert abs(IMG[i][j] - r) < 0.01 * GAIN
    # Away from the targets: the direct sum uses the whole annular sector and
    # PFA the inscribed rectangle, so their sidelobes differ, but both are low.
    for (i, j), r in zip(off, ref[len(on):]):
        assert abs(IMG[i][j]) < 0.07 * GAIN and abs(r) < 0.07 * GAIN


def test_keystone_grid_lies_inside_the_polar_annulus() -> None:
    kys, kxs = cartesian_grid(G)
    u_lo, u_hi = G.u(0), G.u(G.n_fast - 1)
    for ky in (kys[0], kys[-1]):
        for kx in (kxs[0], kxs[-1]):
            assert u_lo - 1e-9 <= math.hypot(kx, ky) <= u_hi + 1e-9
            assert abs(math.atan2(kx, ky)) <= G.span / 2 + 1e-12


def test_wavefront_curvature_lowers_off_center_peaks() -> None:
    """Measurement: exact spherical ranges at a short range break the plane-wave model.

    At rc = 30 m the corner target moves by about a third of a pixel (geometric
    distortion), so the largest pixel value drops; the down-range target does not move.
    """
    far = Spotlight(rc=1000.0)
    near = Spotlight(rc=30.0)
    corner, down_range = (24, 24), (24, 16)
    for g, low in ((far, 0.98), (near, None)):
        ys, xs = pixel_coords(g)
        for i, j in (corner, down_range):
            img = pfa(g, simulate_dechirped(g, [(xs[j], ys[i], 1.0)]))
            value = peak(img)[0] / GAIN
            if low is not None or (i, j) == down_range:
                assert value > 0.98
            else:
                assert value < 0.9


def test_linear_in_the_data() -> None:
    a = pfa(G, simulate_dechirped(G, TARGETS[:1], plane_wave=True))
    b = pfa(G, simulate_dechirped(G, TARGETS[1:], plane_wave=True))
    assert max(abs(a[i][j] + b[i][j] - IMG[i][j]) for i in range(32) for j in range(32)) < 1e-9 * GAIN

History

Walker (1980) described range-Doppler imaging of rotating objects and the storage of the data in polar format, which allows a resolution beyond the limit of a rectangular format. Munson, O'Brien and Jenkins (1983) showed that spotlight SAR is a tomography problem, in which each dechirped pulse is a slice of the 2D Fourier transform of the scene, and so placed PFA beside direct Fourier reconstruction. Jakowatz and colleagues (1996) and Carrara, Goodman and Majewski (1995) gave full accounts of the algorithm, its interpolations and its limits from wavefront curvature.

References

  1. Jack L. Walker, Range-Doppler imaging of rotating objects, IEEE Transactions on Aerospace and Electronic Systems 16(1), 1980, 23 to 52, the polar format storage of the data and its resolution limits for a rotating object (general locator)
  2. David C. Munson Jr., James D. O'Brien and W. Kenneth Jenkins, A tomographic formulation of spotlight-mode synthetic aperture radar, Proceedings of the IEEE 71(8), 1983, 917 to 925, the dechirped spotlight pulse as a slice of the 2D Fourier transform of the scene, and polar format reconstruction (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 chapters A Tomographic Foundation for Spotlight-Mode SAR Imaging and Aspects of Spotlight-Mode Image Formation
  4. Walter G. Carrara, Ron S. Goodman and Ronald M. Majewski, Spotlight Synthetic Aperture Radar: Signal Processing Algorithms, Artech House, 1995, the polar format algorithm and its limits from wavefront curvature (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.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