lib_jsl_dsp/discrete/transformations/
non_linearity_transformers.rs1use num_complex::Complex;
8
9use crate::discrete::stream_operator::{StreamOperator, StreamOperatorManagement};
10use lib_jsl_core::{ErrorsJSL, IsAnalytic, IsLinearOperatable};
11
12pub fn sigmoid<T: IsAnalytic>(x: T) -> T {
17 T::one() / (T::one() + (-x).f_exp())
18}
19
20pub fn hard_clip_real(x: f64, threshold: f64) -> f64 {
22 if x > threshold {
23 threshold
24 } else if x < -threshold {
25 -threshold
26 } else {
27 x
28 }
29}
30pub fn hard_clip_complex(x: Complex<f64>, threshold: f64) -> Complex<f64> {
31 let mag = x.norm();
32 let phase = x.arg();
33 let clipped_mag = if mag > threshold { threshold } else { mag };
34 Complex::from_polar(clipped_mag, phase)
35}
36
37pub fn quantize_real(x: f64, levels: usize) -> f64 {
42 let step = 2.0 / (levels as f64 - 1.0);
43 let quantized = (x + 1.0) / step;
44 let quantized_rounded = quantized.round();
45 quantized_rounded * step - 1.0
46}
47pub fn quantize_complex(x: Complex<f64>, levels: usize) -> Complex<f64> {
48 let real_quantized = quantize_real(x.re, levels);
49 let imag_quantized = quantize_real(x.im, levels);
50 Complex::new(real_quantized, imag_quantized)
51}
52
53pub struct NonLinearityTransformer<T: IsLinearOperatable> {
56 non_linearity_fn: fn(T) -> T,
57}
58
59impl<T: IsAnalytic> NonLinearityTransformer<T> {
60 pub fn new(non_linearity_fn: Option<fn(T) -> T>) -> Self {
61 Self {
62 non_linearity_fn: non_linearity_fn.unwrap_or(sigmoid),
63 }
64 }
65 pub fn evaluate(&self, x: T) -> T {
66 (self.non_linearity_fn)(x)
67 }
68}
69
70
71impl StreamOperatorManagement for NonLinearityTransformer<f64> {
73 fn reset(&mut self) -> Result<(), ErrorsJSL> {
74 Ok(())
75 }
76 fn finalize(&mut self) -> Result<(), ErrorsJSL> {
77 Ok(())
78 }
79}
80
81impl StreamOperator<f64, f64> for NonLinearityTransformer<f64> {
82 fn process(&mut self, input: &[f64]) -> Result<Option<Vec<f64>>, ErrorsJSL> {
83 if input.is_empty() {
84 return Ok(None);
85 }
86 Ok(Some(input.iter().map(|&x| self.evaluate(x)).collect()))
87 }
88 fn flush(&mut self) -> Result<Option<Vec<f64>>, ErrorsJSL> {
89 Ok(None)
90 }
91}
92
93impl StreamOperatorManagement for NonLinearityTransformer<Complex<f64>> {
95 fn reset(&mut self) -> Result<(), ErrorsJSL> {
96 Ok(())
97 }
98 fn finalize(&mut self) -> Result<(), ErrorsJSL> {
99 Ok(())
100 }
101}
102
103impl StreamOperator<Complex<f64>, Complex<f64>> for NonLinearityTransformer<Complex<f64>> {
104 fn process(&mut self, input: &[Complex<f64>]) -> Result<Option<Vec<Complex<f64>>>, ErrorsJSL> {
105 if input.is_empty() {
106 return Ok(None);
107 }
108 Ok(Some(input.iter().map(|&x| self.evaluate(x)).collect()))
109 }
110 fn flush(&mut self) -> Result<Option<Vec<Complex<f64>>>, ErrorsJSL> {
111 Ok(None)
112 }
113}
114
115#[cfg(test)]
116mod tests {
117 use super::*;
118 use std::fs;
119
120 fn load_csv_real(path: &str) -> Vec<f64> {
121 let path = format!(
122 "{}/src/discrete/test_data/{path}",
123 env!("CARGO_MANIFEST_DIR")
124 );
125 fs::read_to_string(path)
126 .expect("read golden csv")
127 .lines()
128 .filter(|l| !l.trim().is_empty())
129 .map(|l| l.trim().parse::<f64>().expect("valid f64 csv value"))
130 .collect()
131 }
132
133 fn load_csv_complex(path: &str) -> Vec<Complex<f64>> {
134 let path = format!(
135 "{}/src/discrete/test_data/{path}",
136 env!("CARGO_MANIFEST_DIR")
137 );
138 fs::read_to_string(path)
139 .expect("read golden csv")
140 .lines()
141 .filter(|l| !l.trim().is_empty())
142 .map(|l| {
143 let mut parts = l.split(',').map(|s| s.trim().parse::<f64>().expect("valid f64"));
144 let re = parts.next().expect("real part");
145 let im = parts.next().expect("imag part");
146 Complex::new(re, im)
147 })
148 .collect()
149 }
150
151 fn assert_vec_close(a: &[f64], b: &[f64], tol: f64) {
152 assert_eq!(a.len(), b.len());
153 for (x, y) in a.iter().zip(b.iter()) {
154 assert!((x - y).abs() <= tol, "actual={x}, golden={y}");
155 }
156 }
157
158 fn assert_vec_complex_close(a: &[Complex<f64>], b: &[Complex<f64>], tol: f64) {
159 assert_eq!(a.len(), b.len());
160 for (x, y) in a.iter().zip(b.iter()) {
161 assert!(
162 (x.re - y.re).abs() <= tol && (x.im - y.im).abs() <= tol,
163 "actual={x}, golden={y}"
164 );
165 }
166 }
167
168 #[test]
169 fn test_sigmoid_real_golden_len7() {
170 let input = load_csv_real("nonlinearity_input_real_len7.csv");
171 let golden = load_csv_real("nonlinearity_sigmoid_real_len7.csv");
172 let output: Vec<f64> = input.into_iter().map(sigmoid).collect();
173 assert_vec_close(&output, &golden, 1e-12);
174 }
175
176 #[test]
177 fn test_hard_clip_real_golden_len7() {
178 let input = load_csv_real("nonlinearity_input_real_len7.csv");
179 let golden = load_csv_real("nonlinearity_hard_clip_real_thr0p8_len7.csv");
180 let output: Vec<f64> = input.into_iter().map(|x| hard_clip_real(x, 0.8)).collect();
181 assert_vec_close(&output, &golden, 1e-12);
182 }
183
184 #[test]
185 fn test_hard_clip_complex_golden_len7() {
186 let input = load_csv_complex("nonlinearity_input_complex_len7.csv");
187 let golden = load_csv_complex("nonlinearity_hard_clip_complex_thr1p0_len7.csv");
188 let output: Vec<Complex<f64>> = input
189 .into_iter()
190 .map(|x| hard_clip_complex(x, 1.0))
191 .collect();
192 assert_vec_complex_close(&output, &golden, 1e-12);
193 }
194
195 #[test]
196 fn test_quantize_real_golden_len7() {
197 let input = load_csv_real("nonlinearity_input_real_len7.csv");
198 let golden = load_csv_real("nonlinearity_quantize_real_levels8_len7.csv");
199 let output: Vec<f64> = input.into_iter().map(|x| quantize_real(x, 8)).collect();
200 assert_vec_close(&output, &golden, 1e-12);
201 }
202
203 #[test]
204 fn test_quantize_complex_golden_len7() {
205 let input = load_csv_complex("nonlinearity_input_complex_len7.csv");
206 let golden = load_csv_complex("nonlinearity_quantize_complex_levels8_len7.csv");
207 let output: Vec<Complex<f64>> = input
208 .into_iter()
209 .map(|x| quantize_complex(x, 8))
210 .collect();
211 assert_vec_complex_close(&output, &golden, 1e-12);
212 }
213
214 #[test]
215 fn test_non_linearity_transformer_sigmoid_real_golden_len7() {
216 let input = load_csv_real("nonlinearity_input_real_len7.csv");
217 let golden = load_csv_real("nonlinearity_sigmoid_real_len7.csv");
218 let mut dut = NonLinearityTransformer::<f64>::new(None);
219 let output = dut.process(&input).unwrap().unwrap();
220 assert_vec_close(&output, &golden, 1e-12);
221 }
222
223 #[test]
224 fn test_non_linearity_transformer_custom_complex_golden_len7() {
225 let input = load_csv_complex("nonlinearity_input_complex_len7.csv");
226 let golden = load_csv_complex("nonlinearity_hard_clip_complex_thr1p0_len7.csv");
227 fn clip1(x: Complex<f64>) -> Complex<f64> {
228 hard_clip_complex(x, 1.0)
229 }
230 let mut dut = NonLinearityTransformer::<Complex<f64>>::new(Some(clip1));
231 let output = dut.process(&input).unwrap().unwrap();
232 assert_vec_complex_close(&output, &golden, 1e-12);
233 }
234}