lib_jsl_information/lfsr/
gold_codes.rs1use super::linear_feedback_shift_register::Lfsr;
12use super::maximum_length_polynomials::maximum_length_polynomial;
13use lib_jsl_core::ErrorsJSL;
14
15pub 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
25pub 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 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 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}