Skip to main content

lib_jsl_dsp/discrete/transformations/
channel_impairment.rs

1//! A channel model: FIR channel, Doppler shift, non-linearity and noise.
2//!
3//! See the book entry [Channels and equalisation](https://jwkunz.github.io/lib_jsl/book/comms/equalisation.html#a-channel-in-software).
4
5use num_complex::Complex;
6
7use crate::{
8    dsp::discrete::{
9        filters::overlap_and_add_fir::OverlapAddFir,
10        stream_operator::{StreamOperator, StreamOperatorManagement},
11        transformations::{
12            frequency_mixer::FrequencyMixer, non_linearity_transformers::NonLinearityTransformer,
13        },
14    },
15    prelude::ErrorsJSL,
16    random::{
17        distributions::gaussian_distribution_box_muller,
18        uniform_generator::UniformRNG,
19        xoshiro256plusplus::Xoshiro256PlusPlus,
20    },
21};
22
23/// Streaming channel impairment model for complex baseband samples.
24///
25/// Optional stages are applied in this order:
26/// 1) Channel convolution
27/// 2) Doppler shift
28/// 3) Non-linearity
29/// 4) Additive white Gaussian noise (AWGN)
30pub struct ChannelImpairment {
31    sample_rate_hz: Option<f64>,
32    channel_fir: Option<OverlapAddFir<Complex<f64>>>,
33    noise_power_db_watts_per_hz: Option<f64>,
34    doppler_mixer: Option<FrequencyMixer>,
35    non_linear_fn: Option<NonLinearityTransformer<Complex<f64>>>,
36    rng: UniformRNG,
37}
38
39impl ChannelImpairment {
40    #[allow(clippy::too_many_arguments)]
41    pub fn new(
42        // Sample rate in Hz, used for interpreting noise power and Doppler shift. Optional if those features are not used.
43        sample_rate_hz: Option<f64>,
44        // FIR taps for channel convolution. If None, no convolution is applied.
45        channel_model: Option<&[f64]>,
46        // Power spectral density of AWGN in dB Watts/Hz. If None, no noise is added.
47        noise_power_db_watts_per_hz: Option<f64>,
48        // Doppler shift in Hz. If None, no Doppler shift is applied.
49        doppler_shift_hz: Option<f64>,
50        // Optional non-linear function to apply to the signal after Doppler shift and before noise. If None, no non-linearity is applied.
51        non_linear_function: Option<NonLinearityTransformer<Complex<f64>>>,
52    ) -> Result<Self, ErrorsJSL> {
53        if let Some(fs) = sample_rate_hz
54            && (!fs.is_finite() || fs <= 0.0)
55        {
56            return Err(ErrorsJSL::InvalidInputRange(
57                "sample_rate must be finite and > 0",
58            ));
59        }
60        if let Some(db) = noise_power_db_watts_per_hz {
61            if !db.is_finite() {
62                return Err(ErrorsJSL::InvalidInputRange(
63                    "noise_power_db_watts_per_hz must be finite",
64                ));
65            }
66            if sample_rate_hz.is_none() {
67                return Err(ErrorsJSL::Misconfiguration(
68                    "sample_rate must be provided when noise_power_db_watts_per_hz is specified",
69                ));
70            }
71        }
72
73        let channel_fir = if let Some(h) = channel_model {
74            if h.is_empty() {
75                return Err(ErrorsJSL::InvalidInputRange(
76                    "channel_model must be non-empty when provided",
77                ));
78            }
79            let taps: Vec<Complex<f64>> = h.iter().map(|&x| Complex::new(x, 0.0)).collect();
80            // Modest default block size for streaming throughput.
81            Some(OverlapAddFir::new(&taps, 256)?)
82        } else {
83            None
84        };
85
86        let doppler_mixer = if let Some(fd) = doppler_shift_hz {
87            let fs = sample_rate_hz.ok_or(ErrorsJSL::Misconfiguration(
88                "sample_rate must be provided when doppler_shift_hz is specified",
89            ))?;
90            Some(FrequencyMixer::new(fd, fs, None))
91        } else {
92            None
93        };
94
95        Ok(Self {
96            sample_rate_hz,
97            channel_fir,
98            noise_power_db_watts_per_hz,
99            doppler_mixer,
100            non_linear_fn: non_linear_function,
101            rng: Xoshiro256PlusPlus::from_random_seed(),
102        })
103    }
104
105    #[inline]
106    fn apply_awgn(&mut self, data: &mut [Complex<f64>]) {
107        let Some(noise_db_psd) = self.noise_power_db_watts_per_hz else {
108            return;
109        };
110        // PSD in W/Hz -> linear.
111        let n0 = 10.0_f64.powf(noise_db_psd / 10.0);
112        let fs = self.sample_rate_hz.unwrap_or(1.0);
113        // Complex baseband: total noise power ~= N0*Fs, split equally across I/Q.
114        let sigma = (n0 * fs / 2.0).sqrt();
115
116        for x in data.iter_mut() {
117            let (n_i, n_q) = gaussian_distribution_box_muller(&mut self.rng, 0.0, sigma);
118            *x += Complex::new(n_i, n_q);
119        }
120    }
121}
122
123impl StreamOperatorManagement for ChannelImpairment {
124    fn reset(&mut self) -> Result<(), ErrorsJSL> {
125        if let Some(fir) = &mut self.channel_fir {
126            fir.reset()?;
127        }
128        if let Some(mix) = &mut self.doppler_mixer {
129            mix.reset()?;
130        }
131        if let Some(nl) = &mut self.non_linear_fn {
132            nl.reset()?;
133        }
134        self.rng = Xoshiro256PlusPlus::from_random_seed();
135        Ok(())
136    }
137
138    fn finalize(&mut self) -> Result<(), ErrorsJSL> {
139        if let Some(fir) = &mut self.channel_fir {
140            fir.finalize()?;
141        }
142        if let Some(mix) = &mut self.doppler_mixer {
143            mix.finalize()?;
144        }
145        if let Some(nl) = &mut self.non_linear_fn {
146            nl.finalize()?;
147        }
148        Ok(())
149    }
150}
151
152impl StreamOperator<Complex<f64>, Complex<f64>> for ChannelImpairment {
153    fn process(&mut self, data_in: &[Complex<f64>]) -> Result<Option<Vec<Complex<f64>>>, ErrorsJSL> {
154        if data_in.is_empty() {
155            return Ok(None);
156        }
157
158        let mut y = data_in.to_vec();
159
160        if let Some(fir) = &mut self.channel_fir {
161            y = match fir.process(&y)? {
162                Some(v) => v,
163                None => return Ok(None),
164            };
165        }
166        if let Some(mix) = &mut self.doppler_mixer {
167            y = match mix.process(&y)? {
168                Some(v) => v,
169                None => return Ok(None),
170            };
171        }
172        if let Some(nl) = &mut self.non_linear_fn {
173            y = match nl.process(&y)? {
174                Some(v) => v,
175                None => return Ok(None),
176            };
177        }
178
179        self.apply_awgn(&mut y);
180        Ok(Some(y))
181    }
182
183    fn flush(&mut self) -> Result<Option<Vec<Complex<f64>>>, ErrorsJSL> {
184        let Some(fir) = &mut self.channel_fir else {
185            return Ok(None);
186        };
187
188        let mut y = match fir.flush()? {
189            Some(v) => v,
190            None => return Ok(None),
191        };
192
193        if let Some(mix) = &mut self.doppler_mixer {
194            y = match mix.process(&y)? {
195                Some(v) => v,
196                None => return Ok(None),
197            };
198        }
199        if let Some(nl) = &mut self.non_linear_fn {
200            y = match nl.process(&y)? {
201                Some(v) => v,
202                None => return Ok(None),
203            };
204        }
205
206        self.apply_awgn(&mut y);
207        Ok(Some(y))
208    }
209}
210
211#[cfg(test)]
212mod tests {
213    use super::*;
214    use crate::discrete::{
215        convolve::{convolve, ConvolveMethod, ConvolveMode},
216        transformations::non_linearity_transformers::hard_clip_complex,
217    };
218
219    fn close(a: &[Complex<f64>], b: &[Complex<f64>], tol: f64) {
220        assert_eq!(a.len(), b.len());
221        for (x, y) in a.iter().zip(b.iter()) {
222            assert!((x.re - y.re).abs() < tol && (x.im - y.im).abs() < tol);
223        }
224    }
225
226    #[test]
227    fn test_channel_impairment_passthrough_when_all_none() {
228        let mut dut = ChannelImpairment::new(None, None, None, None, None).unwrap();
229        let x = vec![Complex::new(1.0, 0.5), Complex::new(-0.2, 0.3), Complex::new(0.0, -1.0)];
230        let y = dut.process(&x).unwrap().unwrap();
231        close(&x, &y, 1e-12);
232        assert!(dut.flush().unwrap().is_none());
233    }
234
235    #[test]
236    fn test_channel_impairment_convolution_matches_direct() {
237        let taps = [0.5, -0.2, 0.1];
238        let mut dut = ChannelImpairment::new(None, Some(&taps), None, None, None).unwrap();
239        let x = vec![
240            Complex::new(1.0, 0.0),
241            Complex::new(2.0, -1.0),
242            Complex::new(-0.5, 0.25),
243            Complex::new(0.1, 0.2),
244        ];
245        let mut y = dut.process(&x).unwrap().unwrap_or_default();
246        y.extend(dut.flush().unwrap().unwrap_or_default());
247
248        let h = taps.iter().map(|&v| Complex::new(v, 0.0)).collect::<Vec<_>>();
249        let golden = convolve(&x, &h, ConvolveMode::Full, ConvolveMethod::Direct).unwrap();
250        close(&y, &golden, 1e-9);
251    }
252
253    #[test]
254    fn test_channel_impairment_doppler_and_nonlinearity() {
255        fn clip1(x: Complex<f64>) -> Complex<f64> {
256            hard_clip_complex(x, 1.0)
257        }
258        let nl = NonLinearityTransformer::<Complex<f64>>::new(Some(clip1));
259        let mut dut =
260            ChannelImpairment::new(Some(8_000.0), None, None, Some(1_000.0), Some(nl)).unwrap();
261        let x = vec![Complex::new(2.0, 0.0); 8];
262        let y = dut.process(&x).unwrap().unwrap();
263        assert_eq!(y.len(), x.len());
264        for s in y {
265            assert!(s.norm() <= 1.0000001);
266        }
267    }
268
269    #[test]
270    fn test_channel_impairment_noise_changes_signal() {
271        let mut dut = ChannelImpairment::new(
272            Some(8_000.0),
273            None,
274            Some(-100.0),
275            None,
276            None,
277        )
278        .unwrap();
279        let x = vec![Complex::new(0.0, 0.0); 128];
280        let y = dut.process(&x).unwrap().unwrap();
281        assert_eq!(y.len(), x.len());
282        let energy: f64 = y.iter().map(|v| v.norm_sqr()).sum();
283        assert!(energy > 0.0);
284    }
285}