Skip to main content

lib_jsl_dsp/discrete/digital_communications/
constellations.rs

1//! Symbol constellations: BPSK, PSK, and square QAM with Gray mapping.
2//!
3//! A [`Constellation`] maps groups of bits to complex symbols and back. All constellations are
4//! normalised to unit average symbol energy, and bits are mapped MSB first. PSK and QAM use Gray
5//! labelling, so symbols that are nearest neighbours differ in exactly one bit; a single symbol
6//! error from noise therefore usually costs one bit error.
7//!
8//! Demapping is available as hard decisions (nearest symbol) and as soft information: the
9//! max-log log-likelihood ratio `ln P(bit = 0) / P(bit = 1)` per bit (positive favours 0), the
10//! convention used by the LDPC and polar decoders in the `information` crate.
11//!
12//! See the book entry [Modulation: constellations, OFDM and FM](https://jwkunz.github.io/lib_jsl/book/comms/modulation.html#constellations-and-gray-labelling).
13
14use lib_jsl_core::ErrorsJSL;
15use num_complex::Complex;
16use std::f64::consts::TAU;
17
18/// A symbol constellation with a bit labelling.
19#[derive(Clone, Debug, PartialEq)]
20pub struct Constellation {
21    /// `points[label]` is the symbol sent for the bit pattern `label` (MSB first).
22    points: Vec<Complex<f64>>,
23    bits_per_symbol: usize,
24}
25
26fn gray(n: usize) -> usize {
27    n ^ (n >> 1)
28}
29
30fn normalised(points: Vec<Complex<f64>>) -> Vec<Complex<f64>> {
31    let power = points.iter().map(|p| p.norm_sqr()).sum::<f64>() / points.len() as f64;
32    let scale = 1.0 / power.sqrt();
33    points.into_iter().map(|p| p * scale).collect()
34}
35
36impl Constellation {
37    /// Binary phase-shift keying: bit 0 → +1, bit 1 → −1.
38    pub fn bpsk() -> Constellation {
39        Constellation { points: vec![Complex::new(1.0, 0.0), Complex::new(-1.0, 0.0)], bits_per_symbol: 1 }
40    }
41
42    /// Quadrature PSK with Gray labelling (the same constellation as 4-QAM).
43    pub fn qpsk() -> Constellation {
44        Constellation::qam(4).expect("4 is a valid QAM order")
45    }
46
47    /// `m`-ary PSK (`m` a power of two, at least 2) on the unit circle with Gray labelling:
48    /// symbol `k` sits at angle `2πk/m`.
49    pub fn psk(m: usize) -> Result<Constellation, ErrorsJSL> {
50        if m < 2 || !m.is_power_of_two() {
51            return Err(ErrorsJSL::InvalidInputRange("PSK order must be a power of two, at least 2"));
52        }
53        let mut points = vec![Complex::new(0.0, 0.0); m];
54        for k in 0..m {
55            points[gray(k)] = Complex::from_polar(1.0, TAU * k as f64 / m as f64);
56        }
57        Ok(Constellation { points, bits_per_symbol: m.trailing_zeros() as usize })
58    }
59
60    /// Square `m`-QAM (`m` = 4, 16, 64, 256 or 1024) with independent Gray-coded PAM on the I and Q
61    /// axes: the first half of the bits label I, the second half label Q.
62    pub fn qam(m: usize) -> Result<Constellation, ErrorsJSL> {
63        let side = (m as f64).sqrt().round() as usize;
64        if side * side != m || !side.is_power_of_two() || !(2..=32).contains(&side) {
65            return Err(ErrorsJSL::InvalidInputRange("QAM order must be 4, 16, 64, 256 or 1024"));
66        }
67        let half_bits = side.trailing_zeros() as usize;
68        let mut points = vec![Complex::new(0.0, 0.0); m];
69        for i in 0..side {
70            for q in 0..side {
71                // PAM level index i has the Gray label gray(i); levels are -(side-1), …, side-1.
72                let label = (gray(i) << half_bits) | gray(q);
73                points[label] = Complex::new(2.0 * i as f64 - (side - 1) as f64, 2.0 * q as f64 - (side - 1) as f64);
74            }
75        }
76        Ok(Constellation { points: normalised(points), bits_per_symbol: 2 * half_bits })
77    }
78
79    /// Number of symbols.
80    pub fn size(&self) -> usize {
81        self.points.len()
82    }
83
84    pub fn bits_per_symbol(&self) -> usize {
85        self.bits_per_symbol
86    }
87
88    /// The symbols, indexed by bit label.
89    pub fn points(&self) -> &[Complex<f64>] {
90        &self.points
91    }
92
93    /// Mean symbol energy (1 by construction).
94    pub fn average_power(&self) -> f64 {
95        self.points.iter().map(|p| p.norm_sqr()).sum::<f64>() / self.size() as f64
96    }
97
98    /// Smallest distance between two distinct symbols.
99    pub fn min_distance(&self) -> f64 {
100        let mut best = f64::INFINITY;
101        for (i, a) in self.points.iter().enumerate() {
102            for b in &self.points[i + 1..] {
103                best = best.min((a - b).norm());
104            }
105        }
106        best
107    }
108
109    /// The symbol for a bit label.
110    pub fn symbol(&self, label: usize) -> Option<Complex<f64>> {
111        self.points.get(label).copied()
112    }
113
114    /// Maps bits (each 0 or 1, MSB first within a symbol) to symbols; the bit count must be a
115    /// multiple of [`bits_per_symbol`](Self::bits_per_symbol).
116    pub fn map_bits(&self, bits: &[u8]) -> Result<Vec<Complex<f64>>, ErrorsJSL> {
117        let k = self.bits_per_symbol;
118        if !bits.len().is_multiple_of(k) {
119            return Err(ErrorsJSL::IncompatibleArraySizes((bits.len(), k)));
120        }
121        Ok(bits.chunks(k).map(|c| self.points[c.iter().fold(0usize, |acc, &b| (acc << 1) | (b & 1) as usize)]).collect())
122    }
123
124    /// The label of the symbol nearest to `sample`.
125    pub fn nearest(&self, sample: Complex<f64>) -> usize {
126        self.points
127            .iter()
128            .enumerate()
129            .min_by(|a, b| (a.1 - sample).norm_sqr().partial_cmp(&(b.1 - sample).norm_sqr()).unwrap())
130            .map(|(i, _)| i)
131            .unwrap()
132    }
133
134    /// The symbol nearest to `sample` (a slicer).
135    pub fn slice(&self, sample: Complex<f64>) -> Complex<f64> {
136        self.points[self.nearest(sample)]
137    }
138
139    /// Hard-decision demapping to bits (MSB first).
140    pub fn demap_hard(&self, samples: &[Complex<f64>]) -> Vec<u8> {
141        let k = self.bits_per_symbol;
142        samples
143            .iter()
144            .flat_map(|&s| {
145                let label = self.nearest(s);
146                (0..k).map(move |b| ((label >> (k - 1 - b)) & 1) as u8)
147            })
148            .collect()
149    }
150
151    /// Soft demapping: the max-log LLR `ln P(bit=0)/P(bit=1)` of every bit, for complex noise of
152    /// total variance `noise_variance` per sample (`E|n|²`).
153    pub fn demap_soft(&self, samples: &[Complex<f64>], noise_variance: f64) -> Result<Vec<f64>, ErrorsJSL> {
154        if !(noise_variance > 0.0) {
155            return Err(ErrorsJSL::InvalidInputRange("Noise variance must be positive"));
156        }
157        // ANCHOR: demap_soft
158        let k = self.bits_per_symbol;
159        let mut llr = Vec::with_capacity(samples.len() * k);
160        for &s in samples {
161            for b in 0..k {
162                let shift = k - 1 - b;
163                let (mut d0, mut d1) = (f64::INFINITY, f64::INFINITY);
164                for (label, p) in self.points.iter().enumerate() {
165                    let d = (s - p).norm_sqr();
166                    if (label >> shift) & 1 == 0 {
167                        d0 = d0.min(d);
168                    } else {
169                        d1 = d1.min(d);
170                    }
171                }
172                llr.push((d1 - d0) / noise_variance);
173            }
174        }
175        Ok(llr)
176        // ANCHOR_END: demap_soft
177    }
178}
179
180/// The 16-QAM constellation (4 bits per symbol, points `(±1, ±3)/√10`).
181pub fn qam16() -> Constellation {
182    Constellation::qam(16).expect("16 is a valid QAM order")
183}
184
185#[cfg(test)]
186mod tests {
187    use super::*;
188
189    fn lcg(seed: &mut u64) -> f64 {
190        *seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
191        ((*seed >> 33) as f64 / (1u64 << 31) as f64) - 0.5
192    }
193
194    fn gauss(seed: &mut u64) -> f64 {
195        (0..12).map(|_| lcg(seed)).sum::<f64>()
196    }
197
198    fn all_constellations() -> Vec<(&'static str, Constellation)> {
199        vec![
200            ("bpsk", Constellation::bpsk()),
201            ("qpsk", Constellation::qpsk()),
202            ("8psk", Constellation::psk(8).unwrap()),
203            ("16psk", Constellation::psk(16).unwrap()),
204            ("16qam", qam16()),
205            ("64qam", Constellation::qam(64).unwrap()),
206            ("256qam", Constellation::qam(256).unwrap()),
207        ]
208    }
209
210    #[test]
211    fn unit_power_and_sizes() {
212        for (name, c) in all_constellations() {
213            assert!((c.average_power() - 1.0).abs() < 1e-12, "{name}");
214            assert_eq!(c.size(), 1 << c.bits_per_symbol(), "{name}");
215        }
216        assert_eq!(qam16().bits_per_symbol(), 4);
217        assert!(Constellation::qam(8).is_err() && Constellation::qam(2048).is_err());
218        assert!(Constellation::psk(3).is_err() && Constellation::psk(1).is_err());
219    }
220
221    #[test]
222    fn sixteen_qam_has_the_expected_geometry() {
223        let c = qam16();
224        let s = 1.0 / 10f64.sqrt();
225        let mut levels: Vec<f64> = c.points().iter().map(|p| p.re / s).collect();
226        levels.sort_by(|a, b| a.partial_cmp(b).unwrap());
227        levels.dedup_by(|a, b| (*a - *b).abs() < 1e-9);
228        assert_eq!(levels.iter().map(|v| v.round() as i32).collect::<Vec<_>>(), vec![-3, -1, 1, 3]);
229        assert!((c.min_distance() - 2.0 * s).abs() < 1e-12);
230        // Label 0b0000 is the corner (I and Q both at the Gray label 00 = level index 0 = -3).
231        assert!((c.symbol(0).unwrap() - Complex::new(-3.0 * s, -3.0 * s)).norm() < 1e-12);
232    }
233
234    #[test]
235    fn gray_labelling_nearest_neighbours_differ_by_one_bit() {
236        for (name, c) in all_constellations() {
237            let d = c.min_distance();
238            for a in 0..c.size() {
239                for b in (a + 1)..c.size() {
240                    if (c.points()[a] - c.points()[b]).norm() < d * 1.0001 {
241                        assert_eq!((a ^ b).count_ones(), 1, "{name}: labels {a} and {b} are neighbours");
242                    }
243                }
244            }
245        }
246    }
247
248    #[test]
249    fn mapping_round_trips_through_hard_demapping() {
250        let mut seed = 5;
251        for (name, c) in all_constellations() {
252            let bits: Vec<u8> = (0..c.bits_per_symbol() * 200).map(|_| (lcg(&mut seed) > 0.0) as u8).collect();
253            let symbols = c.map_bits(&bits).unwrap();
254            assert_eq!(symbols.len(), 200);
255            assert_eq!(c.demap_hard(&symbols), bits, "{name}");
256        }
257        assert!(qam16().map_bits(&[0, 1, 0]).is_err());
258    }
259
260    #[test]
261    fn soft_demapping_agrees_with_hard_decisions_and_scales_with_noise() {
262        let mut seed = 9;
263        for (name, c) in all_constellations() {
264            let samples: Vec<Complex<f64>> = (0..100).map(|_| c.points()[(lcg(&mut seed) * 1e6).abs() as usize % c.size()] + Complex::new(gauss(&mut seed), gauss(&mut seed)) * 0.03).collect();
265            let hard = c.demap_hard(&samples);
266            let llr = c.demap_soft(&samples, 0.01).unwrap();
267            assert_eq!(llr.len(), hard.len());
268            for (l, h) in llr.iter().zip(&hard) {
269                assert_eq!(*l < 0.0, *h == 1, "{name}: LLR sign must match the hard decision");
270            }
271            let llr2 = c.demap_soft(&samples, 0.02).unwrap();
272            assert!(llr.iter().zip(&llr2).all(|(a, b)| (a / 2.0 - b).abs() < 1e-9), "LLRs scale as 1/variance");
273        }
274        assert!(Constellation::bpsk().demap_soft(&[Complex::new(1.0, 0.0)], 0.0).is_err());
275        // BPSK max-log LLR is exactly 4 Re(y) / σ² (for E|n|² = σ²).
276        let l = Constellation::bpsk().demap_soft(&[Complex::new(0.4, 0.2)], 0.5).unwrap()[0];
277        assert!((l - 4.0 * 0.4 / 0.5).abs() < 1e-12);
278    }
279
280    #[test]
281    fn qpsk_bit_error_rate_matches_theory() {
282        // BER = Q(sqrt(2 Eb/N0)); at Eb/N0 = 4 dB this is about 1.25e-2.
283        let c = Constellation::qpsk();
284        let ebn0 = 10f64.powf(0.4);
285        let sigma2 = 1.0 / (2.0 * ebn0); // Es = 1 = 2 Eb, N0 = sigma2 (total complex variance)
286        let mut seed = 77;
287        let n = 100_000;
288        let bits: Vec<u8> = (0..2 * n).map(|_| (lcg(&mut seed) > 0.0) as u8).collect();
289        let rx: Vec<Complex<f64>> = c.map_bits(&bits).unwrap().into_iter().map(|s| s + Complex::new(gauss(&mut seed), gauss(&mut seed)) * (sigma2 / 2.0).sqrt()).collect();
290        let errors = c.demap_hard(&rx).iter().zip(&bits).filter(|(a, b)| a != b).count();
291        let ber = errors as f64 / bits.len() as f64;
292        let q = 0.5 * erfc_approx((ebn0).sqrt());
293        assert!((ber / q - 1.0).abs() < 0.15, "measured {ber}, theory {q}");
294    }
295
296    /// Complementary error function (Abramowitz-Stegun 7.1.26, |error| < 1.5e-7).
297    fn erfc_approx(x: f64) -> f64 {
298        let t = 1.0 / (1.0 + 0.3275911 * x);
299        let poly = t * (0.254829592 + t * (-0.284496736 + t * (1.421413741 + t * (-1.453152027 + t * 1.061405429))));
300        poly * (-x * x).exp()
301    }
302}