Algorithm Search⌘K

Algorithmadvanced

Chirp scaling algorithm

Focus SAR data with phase multiplies and FFTs only, using the chirp structure of the pulse to equalize range cell migration without interpolation.

Time
O(M N log(M N)) worst
Space
O(M N) extra · data
Where
M = the number of pulses; N = the number of range samples per pulse
Properties
deterministicnot exactlinear in dataiterative
Origin
R. Keith Raney, Hartmut Runge, Richard Bamler, Ian G. Cumming, Frank H. Wong, 1994

The chirp scaling algorithm (CSA) focuses stripmap synthetic aperture radar data with FFTs and multiplications by phase functions only. Like the range-Doppler algorithm, it works in the range-Doppler domain, where the range cell migration of a target depends only on its range. But it does not compress the range first. While the echoes are still linear FM chirps, it multiplies them by a weak chirp in range. That changes the slope of each echo a little and moves its center by an amount that grows with the distance from a reference range. The amount is chosen so that every target ends up with the migration of the reference range. That common migration is a shift, so a linear phase in the range frequency removes it, together with range compression and secondary range compression, without any interpolation.

In plain words

The echo of each point slides across range bins by an amount that depends on its distance, and correcting different slides at different distances needs interpolation. The chirp scaling trick uses the shape of the radar pulse. The pulse is a chirp, a tone that sweeps in pitch, and multiplying a chirp by another weak chirp moves it in time. A carefully chosen multiply moves the echoes of near and far points so that they all slide by the same amount. One equal slide is easy to undo for every point at once in the frequency domain, by multiplying with a phase. So the whole focus becomes Fourier transforms and multiplies.

The problem

The input is the raw data s[p][j]s[p][j] of MM pulses on a straight track at the speed VV, at the pulse rate PRF, with NN range samples at the rate fsf_s. Sample jj has the two-way time τj\tau_j and the slant range Rj=rstart+jc/(2fs)R_j = r_{\text{start}} + j c/(2 f_s). The pulse is a chirp eiπKrt2e^{i\pi K_r t^2} of length TT and bandwidth B=KrTB = K_r T, the carrier is f0f_0 (λ=c/f0\lambda = c/f_0), and the squint is zero. A target of amplitude aa at (x0,R0)(x_0, R_0) gives a chirp(τ−2R(η)/c) e−i4πf0R(η)/ca\, \text{chirp}(\tau - 2R(\eta)/c)\, e^{-i 4\pi f_0 R(\eta)/c} with R(η)=R02+(Vη−x0)2R(\eta) = \sqrt{R_0^2 + (V\eta - x_0)^2}. 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 the opposite signs. A reference range rrefr_{\text{ref}}, usually the middle of the swath, is a parameter. The output is the complex image on the M×NM \times N grid, as for SAR image formation.

The algorithm

Write D(f)=1−(λf/(2V))2D(f) = \sqrt{1 - (\lambda f/(2V))^2} and let Km(f,R)K_m(f, R) be the range FM rate in the range-Doppler domain,

Km=Kr1−KrcRf22V2f03D3.K_m = \frac{K_r}{1 - K_r \dfrac{c R f^2}{2 V^2 f_0^3 D^3}}.

In the pseudocode, τj\tau_j is measured from the center of the chirp.

  1. CSA(s, f_0, V, PRF, K_r, r_ref) ▷ s[p][j]: raw pulse p, range sample j
  2. 1for every range sample j: S[·][j] ← DFT over p of s[·][j] ▷ range-Doppler domain
  3. 2for every Doppler bin k with |f_k| ≤ f_max: D ← D(f_k); a ← 1/D - 1; K_m ← K_m(f_k, r_ref)
  4. 3S[k][j] ← S[k][j] · e^{iπ K_m a (τ_j - 2 r_ref / (c D))²} for every j ▷ chirp scaling
  5. 4Z ← DFT over j of S[k][·] ▷ 2D frequency domain
  6. 5Z[q] ← Z[q] · (f_s / sqrt(K_r)) e^{iπ D f_q² / K_m} e^{i 2π f_q · 2 r_ref a / c} for every q
  7. 6S[k][·] ← IDFT(Z) ▷ back to range-Doppler
  8. 7S[k][j] ← S[k][j] · (PRF / sqrt(K_a)) e^{i 4π f_0 R_j D / c} e^{-i Δφ_j} for every j
  9. 8for every range sample j: image[·][j] ← IDFT over k of S[·][j]

Line L1 takes the data to the range-Doppler domain without range compression. There a target at R0R_0 is a range chirp of the rate KmK_m, centered at 2R0/(cD)2R_0/(cD). Line L3 is the chirp scaling multiply. Completing the square in the exponent shows that the product is a chirp of the rate Km/DK_m/D centered at 2R0/c+2rref a/c2R_0/c + 2 r_{\text{ref}}\, a/c: the migration of every target is now that of the reference range, a shift that does not depend on R0R_0. Line L5 does three things at once in the range frequency fqf_q: range compression for the new rate Km/DK_m/D, which includes secondary range compression because KmK_m is used and not KrK_r; the bulk migration correction, the linear phase that undoes the common shift; and a gain. Line L7 is the azimuth matched filter at the range RjR_j, with the gain set by Ka=2V2f0D3/(c rref)K_a = 2 V^2 f_0 D^3/(c\, r_{\text{ref}}), and the removal of the residual phase Δφj=4πKm(1−D)(Rj−rref)2/(c2D2)\Delta\varphi_j = 4\pi K_m (1 - D)(R_j - r_{\text{ref}})^2 / (c^2 D^2) that the scaling leaves behind. Line L8 returns to the image.

Example

The tests use the geometry of the range-Doppler algorithm: f0=300f_0 = 300 MHz, B=100B = 100 MHz, T=0.2T = 0.2 us, fs=120f_s = 120 MHz (bins of 1.25 m), V=100V = 100 m/s, PRF =80= 80 Hz, M=128M = 128, N=64N = 64 from 380 m, a beam with the sine of the half angle 0.125, and rrefr_{\text{ref}} in the middle of the window. The measured peaks, divided by the brute-force matched filter value of each target, are:

target (x0,R0)(x_0, R_0), amplitude peak / matched filter phase of peak / amplitude
(0 m, 400 m), 1 0.998 −0.3-0.3 degrees
(10 m, 410 m), 0.7 0.986 −0.2-0.2 degrees
(-12.5 m, 395 m), 0.5 1.017 −0.3-0.3 degrees

Each peak is at its predicted pixel. The phase is close to zero because the phase-only range filter of L5 leaves a factor e+iπ/4e^{+i\pi/4} that cancels the e−iπ/4e^{-i\pi/4} of the azimuth stationary phase.

A wide beam shows what the scaling does. With the sine of the half angle 0.35, PRF =200= 200 Hz, M=256M = 256, a window from 80 m and rref=120r_{\text{ref}} = 120 m, a target at R0=96R_0 = 96 m migrates 6.48 m at the edge of the beam, against 8.10 m at the reference range. The full CSA gives 1.048 of the ideal peak at the right pixel. With L3 skipped (and Δφ=0\Delta\varphi = 0), only the bulk migration of 120 m is removed; the peak drops to 0.734 and moves by one range bin. The values in this section are measurements on these simulations.

Correctness

The algorithm is linear in the data. Its key step is an exact identity: for any R0R_0, the product of a chirp of rate KmK_m centered at τd=2R0/(cD)\tau_d = 2R_0/(cD) with the scaling chirp eiπKma(τ−τref)2e^{i\pi K_m a (\tau - \tau_{\text{ref}})^2} is a chirp of rate Km(1+a)=Km/DK_m(1 + a) = K_m/D centered at τref+D(τd−τref)=2R0/c+2rref a/c\tau_{\text{ref}} + D(\tau_d - \tau_{\text{ref}}) = 2R_0/c + 2 r_{\text{ref}}\, a/c, times the constant phase eiΔφe^{i\Delta\varphi}. So after L3 the migration is the same for every range, and L5 removes it exactly. The approximations are those of the range-Doppler signal model: the stationary phase in azimuth, and KmK_m evaluated at rrefr_{\text{ref}} instead of at each R0R_0. The proofs are in proofs/correctness.md.

Proof: Chirp scaling equalizes the range cell migration of every range exactly, so phase multiplies focus the range-Doppler signal modelfull

We prove three facts about the CSA as written on the main page (lines L1 to L8) for the stripmap model with zero squint. Theorem 1 is exact. Theorem 2 is an exact identity about chirps. Theorem 3 applies it to the range-Doppler signal model, which itself rests on the principle of stationary phase in azimuth and on the rate KmK_m evaluated at the reference range; those are approximations, not theorems about the sampled data.

Setting. Write D=D(f)=1−(λf/(2V))2D = D(f) = \sqrt{1 - (\lambda f/(2V))^2} for a fixed Doppler frequency ff, a=1/D−1a = 1/D - 1, and τ\tau for the two-way time measured from the center of the chirp. The range-Doppler signal model (Cumming and Wong, Chapter 7) says that, after the azimuth DFT of L1, a target of amplitude α\alpha at the closest range R0R_0 and along-track time η0\eta_0 is

S(τ,f)=C(f) α eiπKm(τ−τd)2 e−i4πf0R0D/c e−i2πfη0,τd=2R0cD,S(\tau, f) = C(f)\, \alpha\, e^{i\pi K_m (\tau - \tau_d)^2}\, e^{-i 4\pi f_0 R_0 D/c}\, e^{-i 2\pi f \eta_0}, \qquad \tau_d = \frac{2 R_0}{c D},

for ∣τ−τd∣≤T/2|\tau - \tau_d| \le T/2, with a factor C(f)C(f) that does not depend on R0R_0 or τ\tau. The derivation of the delay τd\tau_d and of the azimuth phase is the stationary phase computation of the range-Doppler algorithm proof; the rate KmK_m comes from the same computation carried to second order in the range frequency, and the model takes it at R0=rrefR_0 = r_{\text{ref}}.

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

Proof. Every line is a DFT, an inverse DFT, or a product with a function that depends only on the indices and the geometry. □\square

Theorem 2 (chirp scaling identity). For real numbers KK, aa with 1+a≠01 + a \ne 0 and any τd\tau_d, τref\tau_{\text{ref}},

eiπK(τ−τd)2 eiπKa(τ−τref)2=eiπK(1+a)(τ−τc)2 eiπKa1+a(τd−τref)2,τc=τref+τd−τref1+a.e^{i\pi K (\tau - \tau_d)^2}\, e^{i\pi K a (\tau - \tau_{\text{ref}})^2} = e^{i\pi K (1 + a) (\tau - \tau_c)^2}\, e^{i\pi K \frac{a}{1 + a} (\tau_d - \tau_{\text{ref}})^2}, \qquad \tau_c = \tau_{\text{ref}} + \frac{\tau_d - \tau_{\text{ref}}}{1 + a}.

Proof. Put t=τ−τreft = \tau - \tau_{\text{ref}} and δ=τd−τref\delta = \tau_d - \tau_{\text{ref}}. The exponent divided by iπKi\pi K is (t−δ)2+at2=(1+a)t2−2δt+δ2=(1+a)(t−δ1+a)2+δ2−δ21+a(t - \delta)^2 + a t^2 = (1 + a) t^2 - 2\delta t + \delta^2 = (1 + a)\big(t - \frac{\delta}{1 + a}\big)^2 + \delta^2 - \frac{\delta^2}{1 + a}, and δ2−δ21+a=a1+aδ2\delta^2 - \frac{\delta^2}{1 + a} = \frac{a}{1 + a}\delta^2. □\square

Theorem 3 (equal migration and focus). In the signal model, take K=KmK = K_m, a=1/D−1a = 1/D - 1 and τref=2rref/(cD)\tau_{\text{ref}} = 2 r_{\text{ref}}/(c D) as in L2 and L3. Then:

  1. after L3, the target is a chirp of rate Km/DK_m / D centered at τc=2R0/c+2rref a/c\tau_c = 2R_0/c + 2 r_{\text{ref}}\, a / c;
  2. the extra constant phase is Δφ=4πKm(1−D)(R0−rref)2/(c2D2)\Delta\varphi = 4\pi K_m (1 - D)(R_0 - r_{\text{ref}})^2 / (c^2 D^2);
  3. after L4 to L6, the target is a compressed pulse centered at 2R0/c2R_0/c, the time of its own range bin, for every ff;
  4. after L7, the remaining phase is e−i2πfη0e^{-i 2\pi f \eta_0} times a constant that does not depend on ff, so L8 focuses the target at η0\eta_0.

Proof. Here 1+a=1/D1 + a = 1/D. By Theorem 2 the rate is Km/DK_m/D and τc=τref+D(τd−τref)=2rrefcD+2(R0−rref)c=2R0c+2rrefc(1D−1)\tau_c = \tau_{\text{ref}} + D(\tau_d - \tau_{\text{ref}}) = \frac{2 r_{\text{ref}}}{c D} + \frac{2 (R_0 - r_{\text{ref}})}{c} = \frac{2R_0}{c} + \frac{2 r_{\text{ref}}}{c}\Big(\frac1D - 1\Big), which is part 1. The constant phase is πKma1+aδ2=πKm(1−D) 4(R0−rref)2c2D2\pi K_m \frac{a}{1 + a} \delta^2 = \pi K_m (1 - D)\, \frac{4 (R_0 - r_{\text{ref}})^2}{c^2 D^2} with δ=2(R0−rref)/(cD)\delta = 2(R_0 - r_{\text{ref}})/(c D), which is part 2. For part 3, a chirp eiπK(τ−τc)2e^{i\pi K (\tau - \tau_c)^2} has, by stationary phase, the spectrum K−1/2eiπ/4e−iπfq2/Ke−i2πfqτcK^{-1/2} e^{i\pi/4} e^{-i\pi f_q^2 / K} e^{-i 2\pi f_q \tau_c} over its band. With K=Km/DK = K_m/D, L5 multiplies by e+iπDfq2/Kme^{+i\pi D f_q^2 / K_m}, which removes the quadratic phase, and by e+i2πfq⋅2rrefa/ce^{+i 2\pi f_q \cdot 2 r_{\text{ref}} a / c}, which changes τc\tau_c into 2R0/c2R_0/c. The spectrum left is flat in phase except the delay 2R0/c2R_0/c, so the inverse DFT of L6 is a compressed pulse at that delay, the same for every ff. For part 4, the phase left is e−i4πf0R0D/c e−i2πfη0 eiΔφe^{-i 4\pi f_0 R_0 D/c}\, e^{-i 2\pi f \eta_0}\, e^{i\Delta\varphi} times a constant; at the bin of R0R_0, L7 multiplies by e+i4πf0R0D/c e−iΔφe^{+i 4\pi f_0 R_0 D / c}\, e^{-i\Delta\varphi}. What remains is linear in ff, and the inverse DFT of L8 turns it into a peak at η0\eta_0, as in the proof for the range-Doppler algorithm. □\square

The scaling factor aa depends on ff but not on R0R_0, so one multiply per Doppler line serves every range; this is why no interpolation is needed. The model error is the use of KmK_m at rrefr_{\text{ref}}: for a target at R0≠rrefR_0 \ne r_{\text{ref}} the true rate differs, which leaves a small range defocus that grows with ∣R0−rref∣|R_0 - r_{\text{ref}}| and with the Doppler frequency. The wide-beam example, with Km/KrK_m/K_r up to 1.25 at the edge of the band, still measures 1.05 of the ideal peak at the right pixel.

Cost. L1 and L8 cost O(MNlog⁡M)O(M N \log M), L4 and L6 cost O(MNlog⁡N)O(M N \log N) with an FFT, and the multiplies cost O(MN)O(M N). The total is O(MNlog⁡(MN))O(M N \log(M N)) in the real-RAM model, with O(MN)O(M N) extra space.

Complexity

Lines L1 and L8 do NN DFTs of length MM, and lines L4 and L6 do MM DFTs of length NN, so the FFTs cost O(MNlog⁡(MN))O(M N \log(M N)). Lines L2, L3, L5 and L7 cost O(1)O(1) per sample. The total is O(MNlog⁡(MN))O(M N \log(M N)) in the real-RAM model, and the extra space is the M×NM \times N array. There is no interpolation, so no factor KK as in the RDA.

Properties

  • Linear in the data; only FFTs and multiplications by phase functions that can be computed in advance.
  • No interpolation, so no interpolation error and no extra cost per sample.
  • Secondary range compression is built in through KmK_m.
  • Phase preserving after the residual phase of L7 is removed, which matters for SAR interferometry.
  • The accuracy falls as KmK_m varies across the swath, because L2 uses rrefr_{\text{ref}} for every range.

Variants and improvements

  • Extended chirp scaling. For squinted and spotlight data, an extra scaling in azimuth and a range-varying Doppler centroid.
  • Nonlinear chirp scaling. A cubic term in the scaling function for wide swaths and high squint, where the migration is not well matched by a quadratic phase.
  • Range blocks. Split a wide swath into blocks with their own rrefr_{\text{ref}} to keep KmK_m accurate.
  • Dechirped data. When the receiver removes the chirp in hardware, the scaling cannot act on a chirp; the omega-k algorithm or polar format algorithm are used instead.

When to use it

Use the CSA for stripmap data from a straight track when the RDA interpolation is too costly or too inexact, and when phase must be preserved. It is a common choice for spaceborne processors with moderate squint. For very wide apertures or long synthetic apertures in which KmK_m varies strongly, the omega-k algorithm is more exact. For curved tracks, use backprojection.

Pitfalls

  • Range compression first. L3 must act on the uncompressed chirps. If the data are range compressed before L1, there is no chirp to scale, and L3 only adds a phase.
  • Reference time. In L3 the time τj\tau_j is measured from the center of the chirp. If the chirp is stored from its start, as in the code, add T/2T/2 to the reference time in L3 and to the shift in L5, or every target moves by half a pulse.
  • Forgetting the residual phase. Without e−iΔφje^{-i\Delta\varphi_j} in L7 the modulus is fine, but the phase of a target varies with (R0−rref)2(R_0 - r_{\text{ref}})^2, which ruins interferometry.
  • The window. The scaling moves echoes by up to 2∣R0−rref∣ a/c2 |R_0 - r_{\text{ref}}|\, a / c in time, so the range record must have room for the moved chirps; otherwise the circular FFT of L4 wraps them.
  • Wrong rate in L5. Using KrK_r in place of Km/DK_m/D leaves range defocus at large Doppler frequencies.

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.

chirp_scaling_algorithm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/chirp-scaling-algorithm/. The authors are listed in prov/C270V5.jsonl.
"""Chirp scaling algorithm (CSA) for stripmap SAR with zero squint.

Geometry: the radar moves along a straight line at the speed V and sends one
pulse at each slow time eta_p = (p - n_az / 2) / PRF, at the position
x_p = V eta_p. A point target at the along-track position x and the closest
range R0 has the range history R(eta) = sqrt(R0^2 + (x_p - x)^2). The radar
sees it only inside the beam: |x_p - x| / R <= beam.

Signals: complex baseband. The pulse is a linear FM chirp
p(t) = exp(i pi Kr (t - T/2)^2) for 0 <= t < T. The echo of a target of
amplitude a is a p(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. Range sample j is the two-way delay
t_start + j / fs, that is the slant range r_start + j c / (2 fs).

The algorithm uses only DFTs and multiplications by phase functions: no
interpolation. Data layout: data[p][j], row p a pulse, column j a range bin.
"""

import cmath
import math

from imgkit import dft, idft

C = 3.0e8


class Stripmap:
    """The parameters of a stripmap acquisition (SI units)."""

    def __init__(self, f0=300e6, bandwidth=100e6, pulse_len=0.2e-6, fs=120e6,
                 v=100.0, prf=80.0, n_range=64, n_az=128, r_start=380.0, beam=0.125):
        self.f0 = f0
        self.bandwidth = bandwidth
        self.pulse_len = pulse_len
        self.fs = fs
        self.v = v
        self.prf = prf
        self.n_range = n_range
        self.n_az = n_az
        self.r_start = r_start
        self.beam = beam
        self.kr = bandwidth / pulse_len
        self.dr = C / (2.0 * fs)

    def slant_range(self, j):
        return self.r_start + j * self.dr

    def x_pulse(self, p):
        return self.v * (p - self.n_az // 2) / self.prf

    def doppler(self, k):
        """The Doppler frequency of azimuth DFT bin k, wrapped to [-PRF/2, PRF/2)."""
        kk = k if k < self.n_az // 2 else k - self.n_az
        return kk * self.prf / self.n_az

    def range_freq(self, q):
        """The baseband range frequency of range DFT bin q, wrapped to [-fs/2, fs/2)."""
        qq = q if q < self.n_range // 2 else q - self.n_range
        return qq * self.fs / self.n_range

    def chirp(self, t):
        if 0.0 <= t < self.pulse_len:
            return cmath.exp(1j * math.pi * self.kr * (t - self.pulse_len / 2) ** 2)
        return 0j


def simulate_raw(g, targets):
    """Raw echo data of point targets (x, R0, amplitude), exact hyperbolic range."""
    t_start = 2.0 * g.r_start / C
    data = []
    for p in range(g.n_az):
        xp = g.x_pulse(p)
        row = [0j] * g.n_range
        for (x, r0, amp) in targets:
            r = math.hypot(r0, xp - x)
            if abs(xp - x) > g.beam * r:
                continue
            tau = 2.0 * r / C
            ph = amp * cmath.exp(-4j * math.pi * g.f0 * r / C)
            for j in range(g.n_range):
                row[j] += ph * g.chirp(t_start + j / g.fs - tau)
        data.append(row)
    return data


def migration_factor(g, f):
    """D(f) = sqrt(1 - (c f / (2 V f0))^2)."""
    return math.sqrt(1.0 - (C * f / (2.0 * g.v * g.f0)) ** 2)


def modified_fm_rate(g, f, r):
    """Km = Kr / (1 - Kr c r f^2 / (2 V^2 f0^3 D^3)), the range FM rate in the range-Doppler domain."""
    d = migration_factor(g, f)
    return g.kr / (1.0 - g.kr * C * r * f ** 2 / (2.0 * g.v ** 2 * g.f0 ** 3 * d ** 3))


def csa(g, data, r_ref=None, scaling=True):
    """Focus raw stripmap data. Returns the complex image img[p][j].

    With scaling=False the chirp scaling multiply is skipped, so only the
    bulk migration of r_ref is corrected (for the tests).
    """
    if r_ref is None:
        r_ref = g.slant_range(g.n_range / 2)
    t_start = 2.0 * g.r_start / C
    f_max = 2.0 * g.v * g.beam * g.f0 / C
    cols = [dft([data[p][j] for p in range(g.n_az)]) for j in range(g.n_range)]  # @line L1
    rd = [[cols[j][k] for j in range(g.n_range)] for k in range(g.n_az)]  # rd[k][j]
    gain_r = g.fs / math.sqrt(g.kr)
    for k in range(g.n_az):
        f = g.doppler(k)
        if abs(f) > f_max:
            rd[k] = [0j] * g.n_range
            continue
        d = migration_factor(g, f)
        km = modified_fm_rate(g, f, r_ref)
        a = 1.0 / d - 1.0  # @line L2
        tau_ref = 2.0 * r_ref / (C * d) + g.pulse_len / 2
        line = rd[k]
        if scaling:
            line = [v * cmath.exp(1j * math.pi * km * a * (t_start + j / g.fs - tau_ref) ** 2)
                    for j, v in enumerate(line)]  # @line L3
        spec = dft(line)  # @line L4
        shift = 2.0 * r_ref * a / C + g.pulse_len / 2
        for q in range(g.n_range):
            fr = g.range_freq(q)
            spec[q] *= gain_r * cmath.exp(1j * math.pi * d * fr ** 2 / km
                                          + 2j * math.pi * fr * shift)  # @line L5
        line = idft(spec)  # @line L6
        ka = 2.0 * g.v ** 2 * g.f0 * d ** 3 / (C * r_ref)
        for j in range(g.n_range):
            r0 = g.slant_range(j)
            resid = 4.0 * math.pi * km / C ** 2 * (1.0 - d) * (r0 - r_ref) ** 2 / d ** 2
            if not scaling:
                resid = 0.0
            line[j] *= (g.prf / math.sqrt(ka)) * cmath.exp(
                1j * (4.0 * math.pi * g.f0 * r0 * d / C - resid))  # @line L7
        rd[k] = line
    cols_img = [idft([rd[k][j] for k in range(g.n_az)]) for j in range(g.n_range)]  # @line L8
    return [[cols_img[j][p] for j in range(g.n_range)] for p in range(g.n_az)]


def target_pixel(g, x, r0):
    """The (fractional) image position (p, j) where a target at (x, R0) focuses."""
    return x * g.prf / g.v + g.n_az // 2, (r0 - g.r_start) / g.dr
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_chirp_scaling_algorithm.py 70 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/chirp-scaling-algorithm/. The authors are listed in prov/C270V5.jsonl.

from chirp_scaling_algorithm import Stripmap, csa, migration_factor, modified_fm_rate, simulate_raw, target_pixel

G = Stripmap()
TARGETS = [(0.0, 400.0, 1.0), (10.0, 410.0, 0.7), (-12.5, 395.0, 0.5)]  # on the 1.25 m pixel grid
RAW = simulate_raw(G, TARGETS)
IMG = csa(G, RAW)


def matched_filter(g, raw, x, r0):
    """Brute force: correlate the raw data with the exact echo of a unit target at (x, r0)."""
    ref = simulate_raw(g, [(x, r0, 1.0)])
    return sum(a.conjugate() * b for ra, rb in zip(ref, raw) for a, b in zip(ra, rb))


def ideal_gain(g, x, r0):
    ref = simulate_raw(g, [(x, r0, 1.0)])
    return sum(abs(a) ** 2 for row in ref for a in row)


def local_peak(img, p0, j0, w=3):
    return max((abs(img[p][j]), p, j) for p in range(p0 - w, p0 + w + 1) for j in range(j0 - w, j0 + w + 1))


def test_targets_focus_at_their_pixels() -> None:
    for x, r0, _ in TARGETS:
        p0, j0 = (round(v) for v in target_pixel(G, x, r0))
        _, p, j = local_peak(IMG, p0, j0)
        assert (p, j) == (p0, j0)


def test_peak_matches_the_brute_force_matched_filter() -> None:
    for x, r0, amp in TARGETS:
        p0, j0 = (round(v) for v in target_pixel(G, x, r0))
        brute = abs(matched_filter(G, RAW, x, r0))
        assert abs(brute - amp * ideal_gain(G, x, r0)) < 0.03 * brute
        assert abs(abs(IMG[p0][j0]) - brute) < 0.06 * brute


def test_scaling_corrects_range_varying_migration() -> None:
    """Wide beam and short range: the target is 24 m from r_ref, so its migration differs."""
    g = Stripmap(beam=0.35, prf=200.0, n_az=256, r_start=80.0)
    raw = simulate_raw(g, [(0.0, 96.0, 1.0)])
    ideal = ideal_gain(g, 0.0, 96.0)
    p0, j0 = (round(v) for v in target_pixel(g, 0.0, 96.0))
    with_scaling = local_peak(csa(g, raw, r_ref=120.0), p0, j0)
    without = local_peak(csa(g, raw, r_ref=120.0, scaling=False), p0, j0)
    assert with_scaling[1:] == (p0, j0)
    assert with_scaling[0] > 0.95 * ideal
    assert without[0] < 0.8 * ideal
    assert without[1:] != (p0, j0)


def test_linear_in_the_data() -> None:
    parts = [csa(G, simulate_raw(G, [t])) for t in TARGETS]
    for p in (58, 64, 72):
        for j in (12, 16, 20):
            total = sum(im[p][j] for im in parts)
            assert abs(total - IMG[p][j]) < 1e-6 * abs(IMG[64][16])


def test_modified_fm_rate_tends_to_kr_at_zero_doppler() -> None:
    assert migration_factor(G, 0.0) == 1.0
    assert modified_fm_rate(G, 0.0, 400.0) == G.kr
    f = 20.0
    d = migration_factor(G, f)
    assert abs(d - (1 - (3.0e8 * f / (2 * G.v * G.f0)) ** 2) ** 0.5) < 1e-15
    assert modified_fm_rate(G, f, 400.0) > G.kr

History

Raney, Runge, Bamler, Cumming and Wong (1994) published the chirp scaling algorithm. Their insight was that the range chirp of the transmitted pulse can be used to equalize the migration before range compression, so the range-varying interpolation of the range-Doppler algorithm is replaced by phase multiplies. Cumming and Wong (2005, Chapter 7) give a full derivation and its relation to the range-Doppler and omega-k algorithms.

References

  1. R. Keith Raney, Hartmut Runge, Richard Bamler, Ian G. Cumming and Frank H. Wong, Precision SAR processing using chirp scaling, IEEE Transactions on Geoscience and Remote Sensing 32(4), 1994, 786 to 799, the chirp scaling operation in the range-Doppler domain, the bulk migration correction and range compression in the 2D frequency domain, and the residual phase (general locator)
  2. Ian G. Cumming and Frank H. Wong, Digital Processing of Synthetic Aperture Radar Data, Artech House, 2005, Chapter 7, The Chirp Scaling Algorithm

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