Skip to main content

lib_jsl_dsp/discrete/radar/
pulse_compression.rs

1//! Radar pulse compression: linear FM chirps and matched filtering.
2//!
3//! A long pulse carries energy for detection range, a wide bandwidth gives range resolution;
4//! a frequency-modulated pulse has both. Correlating the echo with the transmitted pulse (the
5//! matched filter, which maximises the output SNR in white noise) compresses each target's echo
6//! into a peak about `1/B` wide, with a processing gain equal to the time-bandwidth product.
7//!
8//! See the book entry [Pulse compression, Barker codes and pulse tracking](https://jwkunz.github.io/lib_jsl/book/comms/radar.html#chirps).
9
10use crate::discrete::convolve::ConvolveMode;
11use crate::discrete::fft_convolution::fft_convolve;
12use lib_jsl_core::ErrorsJSL;
13use num_complex::Complex;
14use std::f64::consts::PI;
15
16type C64 = Complex<f64>;
17
18/// A complex baseband linear-FM chirp sweeping `−B/2 … +B/2` over `duration` seconds at sample
19/// rate `fs`: `s(t) = exp(jπ (B/T) (t − T/2)²)`.
20pub fn linear_chirp(bandwidth: f64, duration: f64, fs: f64) -> Result<Vec<C64>, ErrorsJSL> {
21    if !(bandwidth > 0.0 && duration > 0.0 && fs > 0.0) || bandwidth > fs {
22        return Err(ErrorsJSL::InvalidInputRange("Need positive bandwidth, duration and rate, with bandwidth <= fs."));
23    }
24    let n = (duration * fs).round() as usize;
25    if n == 0 {
26        return Err(ErrorsJSL::InvalidInputRange("The pulse is shorter than one sample."));
27    }
28    let rate = bandwidth / duration;
29    Ok((0..n).map(|i| { let t = i as f64 / fs - duration / 2.0; C64::from_polar(1.0, PI * rate * t * t) }).collect())
30}
31
32/// The matched filter of `pulse`, optionally amplitude-weighted (e.g. by a Hamming or Taylor
33/// window) to lower range sidelobes at a small cost in SNR and resolution: the time-reversed,
34/// conjugated pulse.
35pub fn matched_filter(pulse: &[C64], weights: Option<&[f64]>) -> Result<Vec<C64>, ErrorsJSL> {
36    if let Some(w) = weights
37        && w.len() != pulse.len()
38    {
39        return Err(ErrorsJSL::IncompatibleArraySizes((w.len(), pulse.len())));
40    }
41    Ok((0..pulse.len()).rev().map(|i| pulse[i].conj() * weights.map_or(1.0, |w| w[i])).collect())
42}
43
44/// Compresses `received` with the (optionally weighted) matched filter of `pulse`. Output index
45/// `k` is the correlation at delay `k` samples, `Σ_n r[n + k] w[n] conj(p[n])`, so a target whose
46/// echo starts at sample `k` peaks at index `k`. The output has `received.len()` samples.
47pub fn pulse_compress(received: &[C64], pulse: &[C64], weights: Option<&[f64]>) -> Result<Vec<C64>, ErrorsJSL> {
48    if pulse.is_empty() || received.is_empty() {
49        return Err(ErrorsJSL::InvalidInputRange("The pulse and the received signal must not be empty."));
50    }
51    // ANCHOR: pulse_compress
52    let filter = matched_filter(pulse, weights)?;
53    let full = fft_convolve(received, &filter, ConvolveMode::Full)?;
54    let offset = pulse.len() - 1;
55    Ok((0..received.len()).map(|k| full[k + offset]).collect())
56    // ANCHOR_END: pulse_compress
57}
58
59/// The peak sidelobe level (dB relative to the main peak) of a compressed pulse: the largest
60/// magnitude outside the main lobe, which extends from the peak to the first local minima.
61pub fn peak_sidelobe_level_db(compressed: &[C64]) -> f64 {
62    let magnitude: Vec<f64> = compressed.iter().map(|c| c.norm()).collect();
63    let Some(peak) = (0..magnitude.len()).max_by(|&i, &j| magnitude[i].total_cmp(&magnitude[j])) else { return f64::NEG_INFINITY };
64    let mut right = peak;
65    while right + 1 < magnitude.len() && magnitude[right + 1] < magnitude[right] {
66        right += 1;
67    }
68    let mut left = peak;
69    while left > 0 && magnitude[left - 1] < magnitude[left] {
70        left -= 1;
71    }
72    let sidelobe = magnitude[..left].iter().chain(&magnitude[right + 1..]).fold(0.0f64, |m, &v| m.max(v));
73    20.0 * (sidelobe / magnitude[peak]).log10()
74}
75
76#[cfg(test)]
77mod tests {
78    use super::*;
79    use crate::discrete::windows::{WindowType, generate_window};
80
81    fn echo_scene(pulse: &[C64], delays: &[(usize, f64)], length: usize) -> Vec<C64> {
82        let mut r = vec![C64::new(0.0, 0.0); length];
83        for &(d, a) in delays {
84            r[d..d + pulse.len()].iter_mut().zip(pulse).for_each(|(v, p)| *v += a * p);
85        }
86        r
87    }
88
89    #[test]
90    fn resolves_close_targets_with_the_expected_gain() {
91        // B = 10 MHz, T = 20 µs at 40 MHz: N = 800 samples, BT = 200.
92        let (b, t, fs) = (10e6, 20e-6, 40e6);
93        let pulse = linear_chirp(b, t, fs).unwrap();
94        assert_eq!(pulse.len(), 800);
95        // Targets 20 samples (half a microsecond, 5 resolution cells) apart overlap heavily in time.
96        // A single echo compresses to a peak equal to the pulse energy (N for unit amplitude).
97        let single = pulse_compress(&echo_scene(&pulse, &[(300, 1.0)], 2000), &pulse, None).unwrap();
98        assert!((single[300].norm() - 800.0).abs() < 1e-6);
99        let r = echo_scene(&pulse, &[(300, 1.0), (320, 0.5)], 2000);
100        let y = pulse_compress(&r, &pulse, None).unwrap();
101        let magnitude: Vec<f64> = y.iter().map(|v| v.norm()).collect();
102        // Both peaks stand out (each sits on the other's sidelobes) with a deep gap between.
103        assert!((magnitude[300] / 800.0 - 1.0).abs() < 0.03 && (magnitude[320] / 400.0 - 1.0).abs() < 0.06, "{} {}", magnitude[300], magnitude[320]);
104        let gap = magnitude[302..319].iter().fold(f64::INFINITY, |m, &v| m.min(v));
105        assert!(gap < 0.25 * magnitude[320], "{gap}");
106        // The −3 dB main-lobe width is about 0.886 fs / B = 3.5 samples.
107        let half_power = magnitude[300] / 2f64.sqrt();
108        let width = magnitude[290..311].iter().filter(|&&m| m >= half_power).count();
109        assert!((3..=5).contains(&width), "{width}");
110    }
111
112    #[test]
113    fn weighting_trades_sidelobes_for_resolution_and_validates() {
114        let pulse = linear_chirp(5e6, 40e-6, 20e6).unwrap();
115        let r = echo_scene(&pulse, &[(1000, 1.0)], 3000);
116        let plain = peak_sidelobe_level_db(&pulse_compress(&r, &pulse, None).unwrap());
117        // An unweighted LFM shows the −13.3 dB sinc sidelobe.
118        assert!((plain + 13.3).abs() < 0.8, "{plain}");
119        let window = generate_window(WindowType::Hamming, pulse.len(), true);
120        let weighted = peak_sidelobe_level_db(&pulse_compress(&r, &pulse, Some(&window)).unwrap());
121        assert!(weighted < -35.0, "{weighted}");
122        assert!(linear_chirp(5e6, 1e-6, 1e6).is_err() && matched_filter(&pulse, Some(&[1.0])).is_err());
123        assert!(pulse_compress(&r, &[], None).is_err());
124    }
125}