Skip to main content

lib_jsl_dsp/discrete/digital_communications/
ofdm.rs

1//! Orthogonal frequency-division multiplexing (OFDM).
2//!
3//! OFDM sends data on many narrow, orthogonal subcarriers at once. The transmitter places one
4//! constellation symbol on each active subcarrier of an `N`-point frequency grid, takes an inverse
5//! FFT to get `N` time samples, and prepends a **cyclic prefix** (a copy of the last `cp_len`
6//! samples). Because the prefix makes the channel's linear convolution look *circular* over the
7//! symbol body, a multipath channel whose delay spread is shorter than the prefix turns into a
8//! simple complex gain `H[k]` on each subcarrier: the receiver drops the prefix, takes an FFT, and
9//! equalizes every subcarrier with one complex division.
10//!
11//! The channel gains come either from a known **training symbol** ([`Ofdm::estimate_channel`]),
12//! which gives an exact per-subcarrier estimate, or from the **pilot** subcarriers carried in every
13//! symbol, interpolated in frequency across the data subcarriers ([`Ofdm::demodulate`]). Pilot
14//! interpolation needs the pilots dense enough that the channel is smooth between them: roughly
15//! `pilot spacing < N / delay spread`.
16//!
17//! Scaling is chosen so the time-domain samples have unit average power when the subcarrier
18//! symbols have unit power.
19//!
20//! See the book entry [Modulation: constellations, OFDM and FM](https://jwkunz.github.io/lib_jsl/book/comms/modulation.html#ofdm).
21
22use crate::{
23    ffts::{
24        Fft,
25        fft_engine_trait::{FftEngine1D, FftDirection, FftOrdering, FftScaleFactor},
26    },
27    prelude::ErrorsJSL,
28};
29use num_complex::Complex;
30
31/// The subcarrier layout of an OFDM system. Subcarriers are numbered by signed index `k` in
32/// `-N/2 .. N/2` (index 0 is DC and is never used); negative indices are the upper half of the FFT.
33#[derive(Clone, Debug, PartialEq)]
34pub struct OfdmParams {
35    fft_size: usize,
36    cp_len: usize,
37    data: Vec<isize>,
38    pilots: Vec<isize>,
39    pilot_values: Vec<Complex<f64>>,
40}
41
42impl OfdmParams {
43    /// A layout with `fft_size` (a power of two, at least 8), a cyclic prefix of `cp_len` samples
44    /// (`< fft_size`), the signed indices of the data and pilot subcarriers, and the known value
45    /// sent on each pilot every symbol. Indices must be distinct, nonzero, and within `±fft_size/2`.
46    pub fn new(fft_size: usize, cp_len: usize, data: Vec<isize>, pilots: Vec<isize>, pilot_values: Vec<Complex<f64>>) -> Result<Self, ErrorsJSL> {
47        if fft_size < 8 || !fft_size.is_power_of_two() {
48            return Err(ErrorsJSL::InvalidInputRange("OFDM FFT size must be a power of two, at least 8"));
49        }
50        if cp_len >= fft_size {
51            return Err(ErrorsJSL::InvalidInputRange("The cyclic prefix must be shorter than the FFT size"));
52        }
53        if data.is_empty() {
54            return Err(ErrorsJSL::InvalidInputRange("At least one data subcarrier is required"));
55        }
56        if pilots.len() != pilot_values.len() {
57            return Err(ErrorsJSL::IncompatibleArraySizes((pilots.len(), pilot_values.len())));
58        }
59        let half = (fft_size / 2) as isize;
60        let mut all: Vec<isize> = data.iter().chain(&pilots).copied().collect();
61        if all.iter().any(|&k| k == 0 || k < -half || k >= half) {
62            return Err(ErrorsJSL::InvalidInputRange("Subcarrier indices must be nonzero and within -N/2 .. N/2"));
63        }
64        all.sort_unstable();
65        if all.windows(2).any(|w| w[0] == w[1]) {
66            return Err(ErrorsJSL::InvalidInputRange("Subcarrier indices must be distinct across data and pilots"));
67        }
68        // Keep the pilots sorted by index (carrying their values) for interpolation.
69        let mut pv: Vec<(isize, Complex<f64>)> = pilots.into_iter().zip(pilot_values).collect();
70        pv.sort_by_key(|p| p.0);
71        Ok(OfdmParams { fft_size, cp_len, data, pilots: pv.iter().map(|p| p.0).collect(), pilot_values: pv.iter().map(|p| p.1).collect() })
72    }
73
74    /// A 64-point layout in the style of IEEE 802.11a/g: 48 data subcarriers `±1..±26`, pilots at
75    /// `±7` and `±21` (BPSK `+1, +1, +1, −1`), and a 16-sample prefix.
76    pub fn wifi_like() -> Self {
77        let pilots = vec![-21isize, -7, 7, 21];
78        let data: Vec<isize> = (-26..=26).filter(|k| *k != 0 && !pilots.contains(k)).collect();
79        let values = [1.0, 1.0, 1.0, -1.0].iter().map(|&v| Complex::new(v, 0.0)).collect();
80        OfdmParams::new(64, 16, data, pilots, values).expect("valid layout")
81    }
82
83    pub fn fft_size(&self) -> usize {
84        self.fft_size
85    }
86
87    pub fn cp_len(&self) -> usize {
88        self.cp_len
89    }
90
91    /// Number of data symbols carried by each OFDM symbol.
92    pub fn num_data(&self) -> usize {
93        self.data.len()
94    }
95
96    /// Samples per OFDM symbol including the prefix.
97    pub fn symbol_len(&self) -> usize {
98        self.fft_size + self.cp_len
99    }
100
101    fn bin(&self, k: isize) -> usize {
102        k.rem_euclid(self.fft_size as isize) as usize
103    }
104
105    fn active_count(&self) -> usize {
106        self.data.len() + self.pilots.len()
107    }
108}
109
110/// The result of demodulating a stream of OFDM symbols.
111#[derive(Clone, Debug, PartialEq)]
112pub struct OfdmDemodulated {
113    /// Equalized data symbols, `num_data` per OFDM symbol, in subcarrier-list order.
114    pub data: Vec<Complex<f64>>,
115    /// The channel estimate used for each data subcarrier of each OFDM symbol (same layout).
116    pub channel: Vec<Complex<f64>>,
117}
118
119/// An OFDM modulator/demodulator for a fixed layout.
120pub struct Ofdm {
121    params: OfdmParams,
122    fwd: Fft,
123    inv: Fft,
124}
125
126impl Ofdm {
127    pub fn new(params: OfdmParams) -> Result<Self, ErrorsJSL> {
128        let mut fwd = Fft::new();
129        fwd.plan(params.fft_size, FftScaleFactor::None, FftDirection::Forward, FftOrdering::Standard)?;
130        let mut inv = Fft::new();
131        inv.plan(params.fft_size, FftScaleFactor::N, FftDirection::Inverse, FftOrdering::Standard)?;
132        Ok(Ofdm { params, fwd, inv })
133    }
134
135    pub fn params(&self) -> &OfdmParams {
136        &self.params
137    }
138
139    /// Time samples (with prefix) for one OFDM symbol from its data symbols.
140    // ANCHOR: ofdm_modulate
141    fn modulate_symbol(&mut self, data: &[Complex<f64>]) -> Result<Vec<Complex<f64>>, ErrorsJSL> {
142        let p = &self.params;
143        let mut x = vec![Complex::new(0.0, 0.0); p.fft_size];
144        for (&k, &v) in p.data.iter().zip(data) {
145            x[p.bin(k)] = v;
146        }
147        for (&k, &v) in p.pilots.iter().zip(&p.pilot_values) {
148            x[p.bin(k)] = v;
149        }
150        let scale = p.fft_size as f64 / (p.active_count() as f64).sqrt();
151        let body: Vec<Complex<f64>> = self.inv.execute(&x)?.into_iter().map(|v| v * scale).collect();
152        let mut out = Vec::with_capacity(p.symbol_len());
153        out.extend_from_slice(&body[p.fft_size - p.cp_len..]);
154        out.extend_from_slice(&body);
155        Ok(out)
156    }
157    // ANCHOR_END: ofdm_modulate
158
159    /// Modulates data symbols into a time-domain signal. The number of symbols must be a multiple
160    /// of [`num_data`](OfdmParams::num_data).
161    pub fn modulate(&mut self, symbols: &[Complex<f64>]) -> Result<Vec<Complex<f64>>, ErrorsJSL> {
162        let nd = self.params.num_data();
163        if symbols.is_empty() || !symbols.len().is_multiple_of(nd) {
164            return Err(ErrorsJSL::IncompatibleArraySizes((symbols.len(), nd)));
165        }
166        let mut out = Vec::with_capacity(symbols.len() / nd * self.params.symbol_len());
167        for chunk in symbols.chunks(nd) {
168            out.extend(self.modulate_symbol(chunk)?);
169        }
170        Ok(out)
171    }
172
173    #[allow(clippy::wrong_self_convention)]
174    /// Frequency-domain values on every subcarrier index of one received OFDM symbol (with prefix).
175    fn to_frequency(&mut self, symbol: &[Complex<f64>]) -> Result<Vec<Complex<f64>>, ErrorsJSL> {
176        let p = &self.params;
177        let y = self.fwd.execute(&symbol[p.cp_len..])?;
178        let scale = (p.active_count() as f64).sqrt() / p.fft_size as f64;
179        Ok(y.into_iter().map(|v| v * scale).collect())
180    }
181
182    fn check_stream(&self, rx: &[Complex<f64>]) -> Result<usize, ErrorsJSL> {
183        let len = self.params.symbol_len();
184        if rx.is_empty() || !rx.len().is_multiple_of(len) {
185            return Err(ErrorsJSL::IncompatibleArraySizes((rx.len(), len)));
186        }
187        Ok(rx.len() / len)
188    }
189
190    /// Per-data-subcarrier channel estimate for one symbol, interpolated linearly in frequency
191    /// from the pilots (holding the outermost pilot's value beyond them).
192    fn pilot_channel(&self, freq: &[Complex<f64>]) -> Vec<Complex<f64>> {
193        let p = &self.params;
194        let h_pilot: Vec<Complex<f64>> = p.pilots.iter().zip(&p.pilot_values).map(|(&k, &v)| freq[p.bin(k)] / v).collect();
195        p.data
196            .iter()
197            .map(|&k| {
198                let idx = p.pilots.partition_point(|&q| q < k);
199                if idx == 0 {
200                    h_pilot[0]
201                } else if idx == p.pilots.len() {
202                    h_pilot[idx - 1]
203                } else {
204                    let (k0, k1) = (p.pilots[idx - 1] as f64, p.pilots[idx] as f64);
205                    let t = (k as f64 - k0) / (k1 - k0);
206                    h_pilot[idx - 1] * (1.0 - t) + h_pilot[idx] * t
207                }
208            })
209            .collect()
210    }
211
212    /// Demodulates a stream of OFDM symbols (each `symbol_len` samples, prefix included),
213    /// equalizing with a pilot-derived channel estimate per symbol. Without pilots there is
214    /// nothing to estimate from and the channel is taken to be 1.
215    pub fn demodulate(&mut self, rx: &[Complex<f64>]) -> Result<OfdmDemodulated, ErrorsJSL> {
216        let count = self.check_stream(rx)?;
217        let len = self.params.symbol_len();
218        let mut data = Vec::with_capacity(count * self.params.num_data());
219        let mut channel = Vec::with_capacity(data.capacity());
220        for s in 0..count {
221            let freq = self.to_frequency(&rx[s * len..(s + 1) * len])?;
222            let h = if self.params.pilots.is_empty() { vec![Complex::new(1.0, 0.0); self.params.num_data()] } else { self.pilot_channel(&freq) };
223            for (&k, &hk) in self.params.data.iter().zip(&h) {
224                data.push(freq[self.params.bin(k)] / hk);
225            }
226            channel.extend(h);
227        }
228        Ok(OfdmDemodulated { data, channel })
229    }
230
231    /// Estimates the channel on every data subcarrier from one received training OFDM symbol (with
232    /// prefix) and the `num_data` known symbols it carried: `H[k] = Y[k] / X[k]`.
233    pub fn estimate_channel(&mut self, training_rx: &[Complex<f64>], known: &[Complex<f64>]) -> Result<Vec<Complex<f64>>, ErrorsJSL> {
234        if training_rx.len() != self.params.symbol_len() || known.len() != self.params.num_data() {
235            return Err(ErrorsJSL::IncompatibleArraySizes((training_rx.len(), self.params.symbol_len())));
236        }
237        if known.iter().any(|v| v.norm() < 1e-12) {
238            return Err(ErrorsJSL::InvalidInputRange("Training symbols must be nonzero"));
239        }
240        let freq = self.to_frequency(training_rx)?;
241        Ok(self.params.data.iter().zip(known).map(|(&k, &x)| freq[self.params.bin(k)] / x).collect())
242    }
243
244    /// Demodulates using a fixed per-data-subcarrier channel estimate (e.g. from a training symbol).
245    pub fn demodulate_with_channel(&mut self, rx: &[Complex<f64>], channel: &[Complex<f64>]) -> Result<Vec<Complex<f64>>, ErrorsJSL> {
246        let count = self.check_stream(rx)?;
247        let len = self.params.symbol_len();
248        if channel.len() != self.params.num_data() {
249            return Err(ErrorsJSL::IncompatibleArraySizes((channel.len(), self.params.num_data())));
250        }
251        let mut data = Vec::with_capacity(count * channel.len());
252        for s in 0..count {
253            let freq = self.to_frequency(&rx[s * len..(s + 1) * len])?;
254            for (&k, &hk) in self.params.data.iter().zip(channel) {
255                data.push(freq[self.params.bin(k)] / hk);
256            }
257        }
258        Ok(data)
259    }
260}
261
262/// Modulates `symbols` (a multiple of the layout's data-subcarrier count) into an OFDM signal.
263pub fn ofdm_modulate(symbols: &[Complex<f64>], params: &OfdmParams) -> Result<Vec<Complex<f64>>, ErrorsJSL> {
264    Ofdm::new(params.clone())?.modulate(symbols)
265}
266
267/// Demodulates an OFDM signal, equalizing with the pilots, and returns the data symbols.
268pub fn ofdm_demodulate(rx: &[Complex<f64>], params: &OfdmParams) -> Result<Vec<Complex<f64>>, ErrorsJSL> {
269    Ok(Ofdm::new(params.clone())?.demodulate(rx)?.data)
270}
271
272#[cfg(test)]
273mod tests {
274    use super::*;
275    use crate::discrete::digital_communications::constellations::Constellation;
276
277    fn lcg(seed: &mut u64) -> f64 {
278        *seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
279        ((*seed >> 33) as f64 / (1u64 << 31) as f64) - 0.5
280    }
281
282    fn gauss(seed: &mut u64) -> f64 {
283        (0..12).map(|_| lcg(seed)).sum::<f64>()
284    }
285
286    fn data_symbols(c: &Constellation, n: usize, seed: &mut u64) -> Vec<Complex<f64>> {
287        (0..n).map(|_| c.points()[((lcg(seed) + 0.5) * c.size() as f64) as usize % c.size()]).collect()
288    }
289
290    /// Linear convolution with a channel impulse response, truncated to the input length.
291    fn apply_channel(x: &[Complex<f64>], h: &[Complex<f64>]) -> Vec<Complex<f64>> {
292        (0..x.len()).map(|n| h.iter().enumerate().filter(|(k, _)| *k <= n).map(|(k, c)| c * x[n - k]).sum()).collect()
293    }
294
295    /// 64-point layout with a pilot on every 4th subcarrier: dense enough to interpolate a mild channel.
296    fn dense_pilot_params() -> OfdmParams {
297        let pilots: Vec<isize> = (-24..=24).step_by(4).filter(|k| *k != 0).collect();
298        let data: Vec<isize> = (-26..=26).filter(|k| *k != 0 && !pilots.contains(k)).collect();
299        let values = vec![Complex::new(1.0, 0.0); pilots.len()];
300        OfdmParams::new(64, 16, data, pilots, values).unwrap()
301    }
302
303    #[test]
304    fn layout_of_the_wifi_like_configuration() {
305        let p = OfdmParams::wifi_like();
306        assert_eq!((p.fft_size(), p.cp_len(), p.num_data(), p.symbol_len()), (64, 16, 48, 80));
307    }
308
309    #[test]
310    fn noiseless_round_trip_and_unit_power() {
311        let c = Constellation::qam(16).unwrap();
312        let mut seed = 3;
313        let params = OfdmParams::wifi_like();
314        let syms = data_symbols(&c, 48 * 50, &mut seed);
315        let tx = ofdm_modulate(&syms, &params).unwrap();
316        assert_eq!(tx.len(), 50 * 80);
317        let power = tx.iter().map(|v| v.norm_sqr()).sum::<f64>() / tx.len() as f64;
318        assert!((power - 1.0).abs() < 0.1, "average sample power {power}");
319        let back = ofdm_demodulate(&tx, &params).unwrap();
320        assert_eq!(back.len(), syms.len());
321        assert!(back.iter().zip(&syms).all(|(a, b)| (a - b).norm() < 1e-10));
322    }
323
324    #[test]
325    fn the_cyclic_prefix_copies_the_symbol_tail() {
326        let mut seed = 5;
327        let params = OfdmParams::wifi_like();
328        let c = Constellation::qpsk();
329        let tx = ofdm_modulate(&data_symbols(&c, 48, &mut seed), &params).unwrap();
330        for i in 0..16 {
331            assert!((tx[i] - tx[64 + i]).norm() < 1e-12, "prefix sample {i}");
332        }
333    }
334
335    #[test]
336    fn a_single_subcarrier_is_a_pure_tone() {
337        // One data symbol on one subcarrier (plus the pilots, which we zero by using none).
338        let params = OfdmParams::new(32, 4, vec![3], vec![], vec![]).unwrap();
339        let tx = ofdm_modulate(&[Complex::new(1.0, 0.0)], &params).unwrap();
340        for n in 0..32 {
341            let want = Complex::from_polar(1.0, std::f64::consts::TAU * 3.0 * n as f64 / 32.0);
342            assert!((tx[4 + n] - want).norm() < 1e-12, "sample {n}");
343        }
344    }
345
346    #[test]
347    fn multipath_within_the_prefix_is_removed_by_per_subcarrier_equalization() {
348        let c = Constellation::qam(16).unwrap();
349        let mut seed = 7;
350        let params = OfdmParams::wifi_like();
351        let mut ofdm = Ofdm::new(params.clone()).unwrap();
352        let h = [Complex::new(1.0, 0.0), Complex::new(0.0, 0.0), Complex::new(0.35, 0.2), Complex::new(0.0, 0.0), Complex::new(-0.15, 0.1)];
353        // Training symbol then payload; the channel is applied to the whole stream.
354        let training = data_symbols(&c, 48, &mut seed);
355        let payload = data_symbols(&c, 48 * 30, &mut seed);
356        let mut all = training.clone();
357        all.extend(&payload);
358        let rx = apply_channel(&ofdm.modulate(&all).unwrap(), &h);
359        let est = ofdm.estimate_channel(&rx[..80], &training).unwrap();
360        let eq = ofdm.demodulate_with_channel(&rx[80..], &est).unwrap();
361        assert!(eq.iter().zip(&payload).all(|(a, b)| (a - b).norm() < 1e-9), "exact equalization with a training-symbol estimate");
362        // Without equalization the channel wrecks the symbols.
363        let raw = ofdm.demodulate_with_channel(&rx[80..], &vec![Complex::new(1.0, 0.0); 48]).unwrap();
364        let wrong = raw.iter().zip(&payload).filter(|(a, b)| c.slice(**a) != **b).count();
365        assert!(wrong > payload.len() / 4);
366    }
367
368    #[test]
369    fn pilot_interpolation_equalizes_a_mild_channel_and_tolerates_noise() {
370        let c = Constellation::qpsk();
371        let mut seed = 11;
372        let params = dense_pilot_params();
373        let mut ofdm = Ofdm::new(params.clone()).unwrap();
374        let nd = params.num_data();
375        let syms = data_symbols(&c, nd * 60, &mut seed);
376        let h = [Complex::new(0.9, 0.2), Complex::new(0.25, -0.1)];
377        let mut rx = apply_channel(&ofdm.modulate(&syms).unwrap(), &h);
378        for v in rx.iter_mut() {
379            *v += Complex::new(gauss(&mut seed), gauss(&mut seed)) * 0.02;
380        }
381        let out = ofdm.demodulate(&rx).unwrap();
382        let errors = out.data.iter().zip(&syms).filter(|(a, b)| c.slice(**a) != **b).count();
383        assert_eq!(errors, 0);
384        assert_eq!(out.channel.len(), out.data.len());
385        // The estimated channel has the shape of the true frequency response at a data subcarrier.
386        let k = params.data[10] as f64;
387        let truth: Complex<f64> = h.iter().enumerate().map(|(n, c)| c * Complex::from_polar(1.0, -std::f64::consts::TAU * k * n as f64 / 64.0)).sum();
388        assert!((out.channel[10] - truth).norm() < 0.05, "{} vs {truth}", out.channel[10]);
389    }
390
391    #[test]
392    fn a_channel_longer_than_the_prefix_breaks_orthogonality() {
393        let c = Constellation::qpsk();
394        let mut seed = 13;
395        let params = OfdmParams::new(64, 4, (-26..=26).filter(|k| *k != 0 && k % 4 != 0).collect(), (-24..=24).step_by(4).filter(|k| *k != 0).collect(), vec![Complex::new(1.0, 0.0); 12]).unwrap();
396        let mut ofdm = Ofdm::new(params.clone()).unwrap();
397        let syms = data_symbols(&c, params.num_data() * 40, &mut seed);
398        // 12-sample delay spread against a 4-sample prefix: heavy inter-symbol interference.
399        let mut h = vec![Complex::new(0.0, 0.0); 13];
400        h[0] = Complex::new(1.0, 0.0);
401        h[12] = Complex::new(0.8, 0.0);
402        let rx = apply_channel(&ofdm.modulate(&syms).unwrap(), &h);
403        let out = ofdm.demodulate(&rx).unwrap();
404        let errors = out.data.iter().zip(&syms).filter(|(a, b)| c.slice(**a) != **b).count();
405        assert!(errors > syms.len() / 20, "only {errors} errors out of {}", syms.len());
406    }
407
408    #[test]
409    fn invalid_layouts_and_inputs() {
410        let one = Complex::new(1.0, 0.0);
411        assert!(OfdmParams::new(60, 4, vec![1], vec![], vec![]).is_err(), "FFT size must be a power of two");
412        assert!(OfdmParams::new(64, 64, vec![1], vec![], vec![]).is_err(), "prefix must be shorter than the FFT");
413        assert!(OfdmParams::new(64, 8, vec![], vec![], vec![]).is_err(), "no data subcarriers");
414        assert!(OfdmParams::new(64, 8, vec![0], vec![], vec![]).is_err(), "DC is not allowed");
415        assert!(OfdmParams::new(64, 8, vec![40], vec![], vec![]).is_err(), "out of range");
416        assert!(OfdmParams::new(64, 8, vec![1, 2], vec![2], vec![one]).is_err(), "pilot overlaps data");
417        assert!(OfdmParams::new(64, 8, vec![1], vec![5], vec![]).is_err(), "pilot value count mismatch");
418        assert!(OfdmParams::new(64, 8, vec![1, 1], vec![], vec![]).is_err(), "duplicate indices");
419        let params = OfdmParams::wifi_like();
420        assert!(ofdm_modulate(&[one; 47], &params).is_err(), "not a multiple of the data count");
421        assert!(ofdm_modulate(&[], &params).is_err());
422        assert!(ofdm_demodulate(&[one; 79], &params).is_err(), "not a multiple of the symbol length");
423        let mut ofdm = Ofdm::new(params).unwrap();
424        assert!(ofdm.estimate_channel(&[one; 80], &[Complex::new(0.0, 0.0); 48]).is_err(), "zero training symbols");
425        assert!(ofdm.demodulate_with_channel(&[one; 80], &[one; 3]).is_err());
426    }
427}