lib_jsl_dsp/discrete/digital_communications/
constellations.rs1use lib_jsl_core::ErrorsJSL;
15use num_complex::Complex;
16use std::f64::consts::TAU;
17
18#[derive(Clone, Debug, PartialEq)]
20pub struct Constellation {
21 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 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 pub fn qpsk() -> Constellation {
44 Constellation::qam(4).expect("4 is a valid QAM order")
45 }
46
47 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 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 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 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 pub fn points(&self) -> &[Complex<f64>] {
90 &self.points
91 }
92
93 pub fn average_power(&self) -> f64 {
95 self.points.iter().map(|p| p.norm_sqr()).sum::<f64>() / self.size() as f64
96 }
97
98 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 pub fn symbol(&self, label: usize) -> Option<Complex<f64>> {
111 self.points.get(label).copied()
112 }
113
114 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 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 pub fn slice(&self, sample: Complex<f64>) -> Complex<f64> {
136 self.points[self.nearest(sample)]
137 }
138
139 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 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 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 }
178}
179
180pub 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 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 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 let c = Constellation::qpsk();
284 let ebn0 = 10f64.powf(0.4);
285 let sigma2 = 1.0 / (2.0 * ebn0); 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 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}