Skip to main content

lib_jsl_information/lfsr/
gold_codes.rs

1//! Gold codes.
2//!
3//! A Gold family for register length `n` consists of the two m-sequences of a preferred pair
4//! together with the `2^n - 1` sequences obtained by adding the second sequence at every cyclic
5//! shift to the first. Their periodic cross-correlations take only three values,
6//! `-1`, `-t(n)` and `t(n) - 2`, where `t(n) = 1 + 2^((n+1)/2)` for odd `n` and
7//! `1 + 2^((n+2)/2)` for `n ≡ 2 (mod 4)`.
8//!
9//! See the book entry [LFSRs and Gold codes](https://jwkunz.github.io/lib_jsl/book/information/lfsr.html#gold-codes).
10
11use super::linear_feedback_shift_register::Lfsr;
12use super::maximum_length_polynomials::maximum_length_polynomial;
13use lib_jsl_core::ErrorsJSL;
14
15/// The magnitude bound `t(n)` on the Gold-code correlation values, or `None` if no Gold family
16/// exists for `n` (that is, when `n` is a multiple of 4).
17pub fn gold_correlation_bound(n: u32) -> Option<u64> {
18    match n % 4 {
19        0 => None,
20        2 => Some(1 + (1u64 << ((n + 2) / 2))),
21        _ => Some(1 + (1u64 << n.div_ceil(2))),
22    }
23}
24
25/// Generates the Gold family for register length `n` (`3..=20`, not a multiple of 4).
26///
27/// Returns `2^n + 1` sequences of `2^n - 1` chips each, as bits (0/1): index 0 is the first
28/// m-sequence `u`, index 1 is the second m-sequence `v` (a decimation of `u`), and index `2 + τ`
29/// is `u ⊕ (v cyclically shifted by τ)`. Map bits to ±1 chips with `1 - 2 * bit` for correlation.
30pub fn gold_codes(n: u32) -> Result<Vec<Vec<u8>>, ErrorsJSL> {
31    if !(3..=20).contains(&n) {
32        return Err(ErrorsJSL::InvalidInputRange("Gold code register length must be between 3 and 20."));
33    }
34    if gold_correlation_bound(n).is_none() {
35        return Err(ErrorsJSL::InvalidInputRange("Gold codes do not exist when the register length is a multiple of 4."));
36    }
37    let poly = maximum_length_polynomial(n).ok_or(ErrorsJSL::RuntimeError("No primitive polynomial available."))?;
38    let period = (1usize << n) - 1;
39    let u: Vec<u8> = Lfsr::from_polynomial(poly, 1).bits(period);
40    // Preferred decimation q = 2^k + 1 with k = 1 (odd n) or k = 2 (n ≡ 2 mod 4).
41    // ANCHOR: gold
42    let q = if n % 2 == 1 { 3 } else { 5 };
43    let v: Vec<u8> = (0..period).map(|t| u[(q * t) % period]).collect();
44    let mut family = Vec::with_capacity(period + 2);
45    family.push(u.clone());
46    family.push(v.clone());
47    for shift in 0..period {
48        family.push((0..period).map(|t| u[t] ^ v[(t + shift) % period]).collect());
49    }
50    // ANCHOR_END: gold
51    Ok(family)
52}
53
54#[cfg(test)]
55mod tests {
56    use super::*;
57
58    fn chips(bits: &[u8]) -> Vec<i32> {
59        bits.iter().map(|&b| 1 - 2 * b as i32).collect()
60    }
61
62    fn periodic_correlation(a: &[i32], b: &[i32], shift: usize) -> i32 {
63        let n = a.len();
64        (0..n).map(|t| a[t] * b[(t + shift) % n]).sum()
65    }
66
67    #[test]
68    fn family_size_and_length() {
69        let fam = gold_codes(5).unwrap();
70        assert_eq!(fam.len(), 33);
71        assert!(fam.iter().all(|s| s.len() == 31));
72    }
73
74    #[test]
75    fn three_valued_cross_correlation() {
76        for &n in &[5u32, 6] {
77            let fam: Vec<Vec<i32>> = gold_codes(n).unwrap().iter().map(|s| chips(s)).collect();
78            let t = gold_correlation_bound(n).unwrap() as i32;
79            let allowed = [-1, -t, t - 2];
80            let len = fam[0].len();
81            for i in 0..fam.len() {
82                for j in (i + 1)..fam.len() {
83                    for shift in 0..len {
84                        let c = periodic_correlation(&fam[i], &fam[j], shift);
85                        assert!(allowed.contains(&c), "n={n} i={i} j={j} shift={shift} c={c}");
86                    }
87                }
88            }
89        }
90    }
91
92    #[test]
93    fn m_sequences_have_two_valued_autocorrelation() {
94        let fam = gold_codes(7).unwrap();
95        let u = chips(&fam[0]);
96        assert_eq!(periodic_correlation(&u, &u, 0), 127);
97        for s in 1..127 {
98            assert_eq!(periodic_correlation(&u, &u, s), -1);
99        }
100    }
101
102    #[test]
103    fn invalid_lengths() {
104        assert!(gold_codes(4).is_err());
105        assert!(gold_codes(8).is_err());
106        assert!(gold_codes(2).is_err());
107        assert!(gold_codes(21).is_err());
108    }
109}