Algorithm Search⌘K

Algorithmadvanced

Fast factorized backprojection

Also called FFBP.

Speed up SAR backprojection of N pulses to an N x N image from O(N^3) to O(N^2 log N) by merging subaperture images on polar grids of growing angular resolution.

Time
O(N^2 log N) worst
Space
O(N^2) extra · data
Where
N = the number of pulses and the number of pixels along one side of the image
Properties
deterministicnot exactlinear in dataiterative
Origin
Lars M. H. Ulander, Hans Hellsten, Gunnar Stenstrom, 2003

Fast factorized backprojection (FFBP) computes nearly the same image as time-domain backprojection for synthetic aperture radar, at a much lower cost. Direct backprojection adds every pulse to every pixel, which for NN pulses and an N×NN \times N image costs O(N3)O(N^3). FFBP splits the aperture into short subapertures and first forms an image for each, on a polar grid centered on the subaperture. A short subaperture has a wide beam and so a coarse resolution in angle, and its image needs only a few angle samples. Pairs of neighboring subimages are then merged into the images of subapertures twice as long, which need twice as many angle samples, and so on. Each stage costs about N2N^2, there are about log⁡2N\log_2 N stages, and the total is O(N2log⁡N)O(N^2 \log N). The only approximation is the interpolation from one polar grid to the next.

In plain words

Adding every echo to every point of a large picture takes a long time. But a few echoes recorded close together cannot tell directions apart well, so their sum only changes slowly from one direction to the next. You can store that sum at a few directions only. Merge two such neighbor sums into one: the result can tell directions apart twice as well, so you store it at twice as many directions. Keep merging until one sum covers the whole flight. Each round of merging takes about as much work as one pass over the picture, and there are only a few rounds.

The problem

The input is as for backprojection: PP range compressed pulses dpd_p sampled at the delays t0+j/fst_0 + j/f_s, the antenna positions (xp,0)(x_p, 0) on a straight track with an even spacing Δx\Delta x, the carrier frequency f0f_0 with the wavelength λ=c/f0\lambda = c/f_0, and the pixels qq in the half plane y>0y > 0. The output is an approximation of the backprojection image

I(q)=∑pdp(2Rp(q)/c) e+i4πf0Rp(q)/c,Rp(q)=∣q−(xp,0)∣.I(q) = \sum_{p} d_p\big(2R_p(q)/c\big)\, e^{+i 4\pi f_0 R_p(q)/c}, \qquad R_p(q) = |q - (x_p, 0)|.

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.

The algorithm

A subaperture ss is a set of neighboring pulses with the center (xs,0)(x_s, 0) and the length lsl_s. Its subimage is stored in the polar coordinates (r,β)(r, \beta) about the center, with rr the range and β=(x−xs)/r\beta = (x - x_s)/r the direction cosine; the point (r,β)(r, \beta) is (xs+rβ, r1−β2)(x_s + r\beta,\ r\sqrt{1 - \beta^2}). The stored value is

Js(r,β)=∑p∈sdp(2Rp/c) e+i4πf0(Rp−r)/c,J_s(r, \beta) = \sum_{p \in s} d_p\big(2R_p/c\big)\, e^{+i 4\pi f_0 (R_p - r)/c},

where RpR_p is the range from pulse pp to that point. The factor e−i4πf0r/ce^{-i 4\pi f_0 r/c} removes the fast phase in rr and leaves a function that is smooth in β\beta, sampled with the step Δβs=λ/(O ls)\Delta\beta_s = \lambda/(O\, l_s) for an oversampling factor OO.

  1. FFBP(d, x, pixels, f_0, f_s, t_0, F, O) ▷ d[p]: range compressed pulses on an even straight track
  2. 1for every pulse p: e_p ← UPSAMPLE(d[p], F) ▷ zero padding of the DFT
  3. 2J_p(r) ← e_p read at the range r, on a range grid covering the scene ▷ one pulse: no β dependence
  4. 3while more than n_final subapertures remain: ▷ merge neighbors in pairs
  5. 4for each pair (a, b): polar grid of the merged s with Δβ_s = λ / (O l_s) covering the scene
  6. 5for each grid point q of s, at (r, β), and each child h in {a, b}: r_h ← |q - (x_h, 0)|
  7. 6v_h ← J_h(r_h, (q_x - x_h) / r_h) ▷ bilinear interpolation
  8. 7J_s(r, β) ← Σ_h v_h e^{+i 4π f_0 (r_h - r) / c}
  9. 8replace the subapertures by the merged ones
  10. 9I(q) ← Σ_s J_s(|q - (x_s, 0)|, β_s(q)) e^{+i 4π f_0 |q - (x_s, 0)| / c} for every pixel q

Line L1 upsamples each pulse, as in direct backprojection. In L2 a single pulse is its own subaperture and its subimage depends on the range only, because Rp=rR_p = r. Lines L3 to L8 are the merging stages: L4 sets up the polar grid of the merged subaperture, with a β\beta step half that of its children; L5 and L6 read each child at the point; and L7 moves each child value from the phase reference of its center to the new center. Line L9 reads the last few subimages at every pixel and adds them; the test uses nfinal=4n_{\text{final}} = 4. The implementation needs PP to be nfinaln_{\text{final}} times a power of 2, and merges in pairs; larger factors per stage, such as 4 or 8, are common too.

Example

The test uses the setup of the backprojection page: f0=300f_0 = 300 MHz (λ=1\lambda = 1 m), B=100B = 100 MHz, fs=120f_s = 120 MHz, P=64P = 64 pulses at 1.25 m spacing, targets of amplitude 1, 0.5 and 0.7 near the range of 400 m, and a 17×1717 \times 17 image of 0.625 m pixels, with the upsampling factor F=8F = 8.

oversampling OO 4 8 16 32
largest difference from direct backprojection, in units of its peak 0.183 0.065 0.025 0.015

With O=16O = 16, the three targets give 0.992, 0.506 and 0.693 of 64 at their pixels. The error falls by nearly 3 for each doubling of OO up to 16, as for the linear interpolation in β\beta, whose error falls with the square of the step.

The work of FFBP and of direct backprojection can be counted from the grid sizes alone. For PP pulses and an n×nn \times n image with n=P/4n = P/4, the ratio of the direct cost Pn2P n^2 to the number of interpolations of FFBP is 0.22, 0.79, 2.89, 10.55 and 38.78 for P=64P = 64, 256, 1024, 4096 and 16384. The ratio grows by a factor of about 3.7 for each factor of 4 in PP, a little faster than the ratio P/log⁡PP / \log P of the two cost bounds, because fixed overheads matter less at larger sizes. At small sizes FFBP is slower, and at large sizes it is much faster. All values in this section are measurements.

Correctness

Before interpolation the algorithm is exact. If JaJ_a and JbJ_b are read exactly at the point qq, then Jae+i4πf0ra/c+Jbe+i4πf0rb/cJ_a e^{+i 4\pi f_0 r_a/c} + J_b e^{+i 4\pi f_0 r_b/c} is the backprojection sum of the pulses of aa and bb at qq, so L7 gives JsJ_s at qq exactly, and L9 gives I(q)I(q) exactly. The approximation is the interpolation of L6 and L9. Under the far-field approximation, the phase of a term of JsJ_s varies in β\beta at a rate of at most 2πls/λ2\pi l_s/\lambda, so JsJ_s is band-limited in β\beta with a Nyquist step of λ/(2ls)\lambda/(2 l_s); a step of λ/(O ls)\lambda/(O\, l_s) with O>2O > 2 oversamples it. The proofs are in proofs/correctness.md.

Proof: Before interpolation, merging subaperture images is exact, so fast factorized backprojection differs from direct backprojection only by its interpolation errorfull

We prove three facts about FFBP as written on the main page (lines L1 to L9). Theorems 1 and 2 are exact. Theorem 3 is exact under the far-field approximation that it states; how small the interpolation error is for a given oversampling is a measurement, given on the main page.

Setting. The pulses dpd_p are range compressed and the antenna positions are (xp,0)(x_p, 0). For a point qq and a pulse pp write Rp(q)=∣q−(xp,0)∣R_p(q) = |q - (x_p, 0)| and Tp(q)=dp(2Rp(q)/c) e+i4πf0Rp(q)/cT_p(q) = d_p(2R_p(q)/c)\, e^{+i 4\pi f_0 R_p(q)/c}, so that direct backprojection is I(q)=∑pTp(q)I(q) = \sum_p T_p(q). A subaperture ss is a set of pulses with the center (xs,0)(x_s, 0); write rs(q)=∣q−(xs,0)∣r_s(q) = |q - (x_s, 0)| and βs(q)=(qx−xs)/rs(q)\beta_s(q) = (q_x - x_s)/r_s(q). The map q↦(rs(q),βs(q))q \mapsto (r_s(q), \beta_s(q)) is one-to-one on the half plane qy>0q_y > 0, with the inverse (r,β)↦(xs+rβ,r1−β2)(r, \beta) \mapsto (x_s + r\beta, r\sqrt{1 - \beta^2}). Define the exact subimage by Js(rs(q),βs(q))=e−i4πf0rs(q)/c∑p∈sTp(q)J_s(r_s(q), \beta_s(q)) = e^{-i 4\pi f_0 r_s(q)/c} \sum_{p \in s} T_p(q).

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

Proof. L1 is a DFT, a zero padding and an inverse DFT; L2, L6 and L9 are weighted sums of stored values with weights fixed by the geometry; L7 is a sum with fixed phase factors. A composition of linear maps is linear. □\square

Theorem 2 (exact factorization). Let ss be the union of the disjoint subapertures aa and bb. For every point qq with qy>0q_y > 0,

Js(rs(q),βs(q))=∑h∈{a,b}Jh(rh(q),βh(q)) e+i4πf0(rh(q)−rs(q))/c.J_s(r_s(q), \beta_s(q)) = \sum_{h \in \{a, b\}} J_h(r_h(q), \beta_h(q))\, e^{+i 4\pi f_0 (r_h(q) - r_s(q))/c}.

For a single pulse pp as its own subaperture, with the center xpx_p, Jp(r,β)=dp(2r/c)J_p(r, \beta) = d_p(2r/c) for every β\beta. For the final set SS of subapertures, which is a partition of all pulses, I(q)=∑s∈SJs(rs(q),βs(q)) e+i4πf0rs(q)/cI(q) = \sum_{s \in S} J_s(r_s(q), \beta_s(q))\, e^{+i 4\pi f_0 r_s(q)/c}.

Proof. By the definition, Jh(rh(q),βh(q)) e+i4πf0rh(q)/c=∑p∈hTp(q)J_h(r_h(q), \beta_h(q))\, e^{+i 4\pi f_0 r_h(q)/c} = \sum_{p \in h} T_p(q). Summing over h∈{a,b}h \in \{a, b\} gives ∑p∈sTp(q)\sum_{p \in s} T_p(q) because aa and bb are disjoint with the union ss, and multiplying by e−i4πf0rs(q)/ce^{-i 4\pi f_0 r_s(q)/c} gives JsJ_s. For one pulse the center is xpx_p, so rp(q)=Rp(q)r_p(q) = R_p(q) and Jp=dp(2Rp/c)J_p = d_p(2R_p/c), which depends on rr only. For the last statement, sum ∑p∈sTp(q)\sum_{p \in s} T_p(q) over the partition SS. □\square

So if L2, L6 and L9 read the subimages exactly, by induction over the stages every stored value equals the exact subimage at its grid point, and L9 returns I(q)I(q). The output differs from direct backprojection only through the interpolation of the stored grids.

Theorem 3 (the angle bandwidth). Let ss have the length lsl_s, so ∣xp−xs∣≤ls/2|x_p - x_s| \le l_s/2 for p∈sp \in s. Under the far-field approximation Rp(q)=rs(q)−(xp−xs)βs(q)R_p(q) = r_s(q) - (x_p - x_s)\beta_s(q), and for a fixed rr, the term of pulse pp in Js(r,β)J_s(r, \beta) is dp(2Rp/c) e−i2πνpβd_p(2R_p/c)\, e^{-i 2\pi \nu_p \beta} with the frequency νp=2(xp−xs)/λ\nu_p = 2(x_p - x_s)/\lambda, and ∣νp∣≤ls/λ|\nu_p| \le l_s/\lambda. So if the envelopes dp(2Rp/c)d_p(2R_p/c) vary slowly in β\beta, the spectrum of Js(r,⋅)J_s(r, \cdot) lies in [−ls/λ,ls/λ][-l_s/\lambda, l_s/\lambda] and the sampling theorem allows the step λ/(2ls)\lambda/(2 l_s).

Proof. For the point (xs+rβ,r1−β2)(x_s + r\beta, r\sqrt{1 - \beta^2}), Rp2=r2−2rβ(xp−xs)+(xp−xs)2R_p^2 = r^2 - 2r\beta(x_p - x_s) + (x_p - x_s)^2, and to first order in (xp−xs)/r(x_p - x_s)/r, Rp=r−(xp−xs)βR_p = r - (x_p - x_s)\beta. The phase of the term is then 4πf0(Rp−r)/c=−4π(xp−xs)β/λ=−2πνpβ4\pi f_0 (R_p - r)/c = -4\pi (x_p - x_s)\beta/\lambda = -2\pi \nu_p \beta. With ∣xp−xs∣≤ls/2|x_p - x_s| \le l_s/2, ∣νp∣≤ls/λ|\nu_p| \le l_s/\lambda, and a signal with this two-sided band is fixed by samples at a step of at most 1/(2ls/λ)1/(2 l_s/\lambda). □\square

When two subapertures merge, lsl_s doubles, so the step in β\beta halves: this is why L4 doubles the number of angle samples at each stage while the number of subimages halves, which keeps the work of a stage about constant. The implementation uses λ/(O ls)\lambda/(O\, l_s) with O=16O = 16, much finer than the Nyquist step, because it interpolates linearly.

Cost. For P=Θ(N)P = \Theta(N) pulses and an N×NN \times N scene, the subimages of one stage hold O(N2)O(N^2) samples together, by Theorem 3 and the fixed range step, and each costs O(1)O(1) with two bilinear interpolations. There are O(log⁡N)O(\log N) stages, so L3 to L8 cost O(N2log⁡N)O(N^2 \log N). L1 and L2 cost O(N⋅FNlog⁡(FN))O(N \cdot F N \log(F N)) and L9 costs O(N2)O(N^2) for a fixed number of final subimages. The total is O(N2log⁡N)O(N^2 \log N) in the real-RAM model for fixed FF and OO, with O(N2)O(N^2) extra space.

Complexity

Take P=Θ(N)P = \Theta(N) pulses and an N×NN \times N image. A subimage of length lsl_s needs O(N)O(N) range samples and O(ls/lfull⋅N)O(l_s / l_{\text{full}} \cdot N) angle samples to cover the scene, so all subimages of one stage hold O(N2)O(N^2) samples together, and each costs O(1)O(1) to compute. There are log⁡2(P/nfinal)\log_2(P/n_{\text{final}}) stages, and L9 costs O(nfinalN2)O(n_{\text{final}} N^2). With the upsampling of L1, O(N⋅FNlog⁡(FN))O(N \cdot F N \log(F N)), the total is O(N2log⁡N)O(N^2 \log N) for fixed FF, OO and nfinaln_{\text{final}}, in the real-RAM model. The extra space is O(N2)O(N^2) for the subimages of two stages.

Properties

  • Linear in the data.
  • Exact before interpolation; the error is set by the oversampling in β\beta and in range.
  • Not limited to a straight track in principle: the factorization holds for any path, and only the polar grids need care.
  • The trade between speed and accuracy is set by OO, the merge factor and the number of final subimages.

Variants and improvements

  • Larger merge factors. Merging 4 or 8 subapertures at a time lowers the number of stages; the cost is still O(N2log⁡N)O(N^2 \log N).
  • Better interpolators. A short sinc or spline kernel in β\beta allows a smaller OO for the same error.
  • Other paths. Versions for curved paths and for 3D scenes use local coordinates that follow the track.
  • Local backprojection. Simpler fast schemes split the aperture and the image only once, which lowers the cost below O(N3)O(N^3) but not to O(N2log⁡N)O(N^2 \log N).

When to use it

Use FFBP when backprojection is the right model, as for wide apertures, low frequencies or nonlinear paths, and the image is too large for direct backprojection. For small images the overhead of the polar grids makes direct backprojection faster, as the cost counts above show.

Pitfalls

  • Phase reference. The subimages must carry the factor e−i4πf0r/ce^{-i 4\pi f_0 r/c} about their own center, and L7 must use the child range rhr_h and the new range rr. Without this the subimages oscillate quickly in β\beta and interpolation fails.
  • Too few angle samples. A step near the Nyquist value λ/(2ls)\lambda/(2l_s) is not enough for linear interpolation; the test shows an error of 18% of the peak with O=4O = 4.
  • Grids that do not cover the scene. Each polar grid must cover the whole scene plus a margin of a few samples, or pixels near the edges read zeros.
  • Errors add over stages. Each stage interpolates again, so the error grows with the number of stages; use a better interpolator or a larger OO for long apertures.

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.

fast_factorized_backprojection.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fast-factorized-backprojection/. The authors are listed in prov/NKKE4Y.jsonl.
"""Fast factorized backprojection (FFBP) for SAR on a straight track.

Geometry: the antenna moves along the x axis. Pulse p is sent from (xa[p], 0)
and the scene is in the half plane y > 0. Signals: complex baseband,
range-compressed. Sample j of a pulse is the two-way delay t0 + j / fs. A
point target of amplitude a gives a sinc(B (t - 2R/c)) exp(-i 4 pi f0 R / c).
The Fourier sign is exp(-i 2 pi f t), the sign of the DFT.

A subaperture with center (cx, 0) and length l stores a polar subimage
J(r, beta) on a grid of range r and direction cosine beta = (x - cx) / r.
The point with polar coordinates (r, beta) is (cx + r beta, r sqrt(1 - beta^2)).
J is the backprojection sum of the subaperture at that point times
exp(-i 4 pi f0 r / c), so J is smooth in beta: it needs a beta step of about
lambda / (4 l) only. Each stage merges pairs of subapertures, so the number of
beta samples doubles while the number of subimages halves.
"""

import cmath
import math

from imgkit import dft, idft

C = 3.0e8


def sinc(x):
    return 1.0 if x == 0 else math.sin(math.pi * x) / (math.pi * x)


def simulate_compressed(xa, targets, f0, bandwidth, fs, t0, n):
    """Range-compressed pulses data[p][j] of point targets (x, y, amplitude)."""
    data = []
    for ax in xa:
        row = [0j] * n
        for x, y, amp in targets:
            r = math.hypot(ax - x, y)
            ph = amp * cmath.exp(-4j * math.pi * f0 * r / C)
            for j in range(n):
                row[j] += ph * sinc(bandwidth * (t0 + j / fs - 2.0 * r / C))
        data.append(row)
    return data


def upsample(row, factor):
    """Band-limited interpolation by zero padding the DFT: factor times more samples."""
    n = len(row)
    spec = dft(row)
    half = n // 2
    padded = spec[:half] + [0j] * (n * factor - n) + spec[half:]
    return [v * factor for v in idft(padded)]


def direct_backprojection(data, xa, pixels, f0, fs, t0, factor=8):
    """Brute force: global backprojection, O(1) work per pulse and pixel."""
    step = C / (2.0 * fs * factor)
    out = [0j] * len(pixels)
    for row, ax in zip(data, xa):
        fine = upsample(row, factor)
        for i, (x, y) in enumerate(pixels):
            r = math.hypot(x - ax, y)
            out[i] += _lerp(fine, (r - C * t0 / 2.0) / step) * cmath.exp(4j * math.pi * f0 * r / C)
    return out


def _lerp(seq, u):
    k = math.floor(u)
    if k < 0 or k >= len(seq) - 1:
        return 0j
    w = u - k
    return (1.0 - w) * seq[k] + w * seq[k + 1]


class Polar:
    """A polar grid r_k = r_lo + k dr, beta_m = b_lo + m db, with values J[m][k]."""

    def __init__(self, cx, length, r_lo, dr, nr, b_lo, db, nb):
        self.cx, self.length = cx, length
        self.r_lo, self.dr, self.nr = r_lo, dr, nr
        self.b_lo, self.db, self.nb = b_lo, db, nb
        self.J = [[0j] * nr for _ in range(nb)]

    def point(self, m, k):
        r = self.r_lo + k * self.dr
        b = self.b_lo + m * self.db
        return self.cx + r * b, r * math.sqrt(1.0 - b * b), r

    def value(self, r, b):
        """Bilinear interpolation of J at (r, beta); zero outside the grid."""
        u = (r - self.r_lo) / self.dr
        k = math.floor(u)
        if k < 0 or k >= self.nr - 1:
            return 0j
        w = u - k
        if self.nb == 1:
            row = self.J[0]
            return (1.0 - w) * row[k] + w * row[k + 1]
        v = (b - self.b_lo) / self.db
        m = math.floor(v)
        if m < 0 or m >= self.nb - 1:
            return 0j
        z = v - m
        a0, a1 = self.J[m], self.J[m + 1]
        return ((1.0 - z) * ((1.0 - w) * a0[k] + w * a0[k + 1])
                + z * ((1.0 - w) * a1[k] + w * a1[k + 1]))


def _box(pixels):
    xs = [x for x, _ in pixels]
    ys = [y for _, y in pixels]
    return min(xs), max(xs), min(ys), max(ys)


def _grid_for(cx, length, box, dr, lam, oversample, margin=2):
    """The polar grid of a subaperture that covers the scene box (with a margin of samples)."""
    x0, x1, y0, y1 = box
    corners = [(x, y) for x in (x0, x1) for y in (y0, y1)]
    rs = [math.hypot(x - cx, y) for x, y in corners]
    bs = [(x - cx) / r for (x, y), r in zip(corners, rs)]
    near = y0 if x0 <= cx <= x1 else min(rs)  # the closest point may be on an edge
    r_lo = near - margin * dr
    nr = int(math.ceil((max(rs) + margin * dr - r_lo) / dr)) + 1
    db = lam / (oversample * length)
    b_lo = min(bs) - margin * db
    nb = int(math.ceil((max(bs) + margin * db - b_lo) / db)) + 1
    return r_lo, nr, b_lo, db, nb


def ffbp_cost(xa, box, n_pixels, f0, fs, factor=8, oversample=16.0, n_final=4):
    """The number of interpolations ffbp does, from the grid sizes alone (no data needed)."""
    lam = C / f0
    dr = C / (2.0 * fs * factor)
    spacing = xa[1] - xa[0]
    centers = list(xa)
    ops = sum(_grid_for(cx, spacing, box, dr, lam, oversample)[1] for cx in centers)
    length = spacing
    while len(centers) > n_final:
        centers = [0.5 * (a + b) for a, b in zip(centers[0::2], centers[1::2])]
        length *= 2
        for cx in centers:
            _, nr, _, _, nb = _grid_for(cx, length, box, dr, lam, oversample)
            ops += 2 * nr * nb
    return ops + len(centers) * n_pixels


def ffbp(data, xa, pixels, f0, fs, t0, factor=8, oversample=16.0, n_final=4, count=None):
    """Factorized backprojection. len(xa) must be n_final times a power of 2 and xa evenly spaced.

    Returns the image values at the pixels. If count is a list, the number of
    interpolations done is appended to it.
    """
    lam = C / f0
    dr = C / (2.0 * fs * factor)
    spacing = xa[1] - xa[0]
    box = _box(pixels)
    ops = 0
    subs = []
    for row, ax in zip(data, xa):  # stage 0: one pulse per subaperture, J does not depend on beta
        fine = upsample(row, factor)  # @line L1
        r_lo, nr = _grid_for(ax, spacing, box, dr, lam, oversample)[:2]
        s = Polar(ax, spacing, r_lo, dr, nr, 0.0, 1.0, 1)
        r0 = C * t0 / 2.0
        s.J[0] = [_lerp(fine, (r_lo + k * dr - r0) / dr) for k in range(nr)]  # @line L2
        ops += nr
        subs.append(s)
    while len(subs) > n_final:  # @line L3
        merged = []
        for a, b in zip(subs[0::2], subs[1::2]):
            cx = 0.5 * (a.cx + b.cx)
            length = a.length + b.length
            r_lo, nr, b_lo, db, nb = _grid_for(cx, length, box, dr, lam, oversample)  # @line L4
            s = Polar(cx, length, r_lo, dr, nr, b_lo, db, nb)
            for m in range(nb):
                row = s.J[m]
                for k in range(nr):
                    px, py, r = s.point(m, k)
                    acc = 0j
                    for child in (a, b):
                        rc = math.hypot(px - child.cx, py)  # @line L5
                        val = child.value(rc, (px - child.cx) / rc)  # @line L6
                        acc += val * cmath.exp(4j * math.pi * f0 * (rc - r) / C)  # @line L7
                    row[k] = acc
            ops += 2 * nr * nb
            merged.append(s)
        subs = merged  # @line L8
    out = [0j] * len(pixels)
    for s in subs:  # @line L9
        for i, (x, y) in enumerate(pixels):
            r = math.hypot(x - s.cx, y)
            out[i] += s.value(r, (x - s.cx) / r) * cmath.exp(4j * math.pi * f0 * r / C)
        ops += len(pixels)
    if count is not None:
        count.append(ops)
    return out


def image_grid(xs, ys):
    """The pixel list of a grid: row-major, y outer."""
    return [(x, y) for y in ys for x in xs]
imgkit.py 322 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/.
"""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
test_fast_factorized_backprojection.py 60 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fast-factorized-backprojection/. The authors are listed in prov/NKKE4Y.jsonl.

from fast_factorized_backprojection import (_box, direct_backprojection, ffbp, ffbp_cost, image_grid,
                                            simulate_compressed)

F0, B, FS, T0, N = 300e6, 100e6, 120e6, 2 * 370 / 3.0e8, 64
XA = [-40.0 + 1.25 * p for p in range(64)]
TARGETS = [(0.0, 400.0, 1.0), (3.75, 403.75, 0.5), (-4.375, 396.25, 0.7)]
PIX = image_grid([-5.0 + 0.625 * i for i in range(17)], [395.0 + 0.625 * i for i in range(17)])
DATA = simulate_compressed(XA, TARGETS, F0, B, FS, T0, N)
REF = direct_backprojection(DATA, XA, PIX, F0, FS, T0)
COUNT = []
FAST = ffbp(DATA, XA, PIX, F0, FS, T0, count=COUNT)
PEAK = max(abs(v) for v in REF)


def test_matches_direct_backprojection() -> None:
    assert max(abs(a - b) for a, b in zip(FAST, REF)) < 0.04 * PEAK


def test_targets_focus_at_their_positions() -> None:
    for x, y, amp in TARGETS:
        i = PIX.index((x, y))
        assert abs(abs(FAST[i]) - 64 * amp) < 0.05 * 64


def test_finer_beta_sampling_lowers_the_error() -> None:
    coarse = ffbp(DATA, XA, PIX, F0, FS, T0, oversample=4.0)
    e_coarse = max(abs(a - b) for a, b in zip(coarse, REF))
    e_fine = max(abs(a - b) for a, b in zip(FAST, REF))
    assert e_fine < 0.3 * e_coarse


def test_cost_formula_matches_the_count() -> None:
    assert COUNT[0] == ffbp_cost(XA, _box(PIX), len(PIX), F0, FS)


def test_speedup_grows_with_the_aperture() -> None:
    """P pulses and an n x n image with n = P / 4: direct costs P n^2, FFBP about n^2 log n."""
    ratios = []
    for p in (64, 256, 1024, 4096):
        n = p // 4
        xa = [1.25 * k for k in range(p)]
        r0, mid = 400.0 * p / 64, 1.25 * p / 2
        box = (mid - 0.3125 * n, mid + 0.3125 * n, r0, r0 + 0.625 * n)
        ratios.append(p * n * n / ffbp_cost(xa, box, n * n, F0, FS))
    assert all(b > 2.5 * a for a, b in zip(ratios, ratios[1:]))
    assert ratios[0] < 1 < ratios[2]


def test_linear_in_the_data() -> None:
    xa = XA[24:40]  # 16 pulses: two merging stages, enough to test linearity quickly
    d1 = simulate_compressed(xa, TARGETS[:1], F0, B, FS, T0, N)
    d2 = simulate_compressed(xa, TARGETS[1:], F0, B, FS, T0, N)
    small = PIX[::7]
    a = ffbp(d1, xa, small, F0, FS, T0)
    b = ffbp(d2, xa, small, F0, FS, T0)
    both = ffbp([[u + v for u, v in zip(r1, r2)] for r1, r2 in zip(d1, d2)], xa, small, F0, FS, T0)
    assert max(abs(u + v - w) for u, v, w in zip(a, b, both)) < 1e-9

History

Fast versions of SAR backprojection were developed in the 1990s for ultra-wideband, low-frequency airborne radar, where the aperture is wide and frequency-domain algorithms are not accurate. Ulander, Hellsten and Stenstrom (2003) described the fully factorized version, with polar subimages, the O(N2log⁡N)O(N^2 \log N) cost and an analysis of its errors, and it has since become a standard method for such systems.

References

  1. Lars M. H. Ulander, Hans Hellsten and Gunnar Stenstrom, Synthetic-aperture radar processing using fast factorized back-projection, IEEE Transactions on Aerospace and Electronic Systems 39(3), 2003, 760 to 776, the factorization of the backprojection sum over subapertures, the polar subimages and their sampling, and the O(N^2 log N) cost (general locator)
  2. Mita D. Desai and W. Kenneth Jenkins, Convolution backprojection image reconstruction for spotlight mode synthetic aperture radar, IEEE Transactions on Image Processing 1(4), 1992, 505 to 517, the direct backprojection of O(N^3) cost that the fast algorithm replaces (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
  • at least three sources
  • a scene preset for the example