lib_jsl_dsp/discrete/transformations/frequency_mixer.rs
1//! A frequency mixer is used to frequency shift a signal by multiplying it with a complex exponential.
2//! This operation is commonly used in applications such as modulation, demodulation, and frequency translation in communication systems.
3//! The `FrequencyMixer` struct maintains the current phase of the complex exponential and the normalized frequency increment, which determines how much the phase is advanced for each sample processed.
4//! The `process` method takes an input signal (either real or complex) and multiplies each sample by the corresponding value of the complex exponential based on the current phase.
5//! The phase is then incremented for the next sample, ensuring that the frequency shift is applied consistently across the entire signal.
6//!
7//! See the book entry [Signal sources: oscillators, CORDIC and waveforms](https://jwkunz.github.io/lib_jsl/book/comms/sources.html#frequency-mixing).
8
9use std::f64::consts::PI;
10
11use num_complex::Complex;
12use lib_jsl_core::{ErrorsJSL};
13use crate::discrete::stream_operator::{StreamOperator, StreamOperatorManagement};
14
15pub struct FrequencyMixer {
16 phase: f64,
17 phase_increment : f64,
18}
19
20impl FrequencyMixer {
21 /// The `new` method initializes a `FrequencyMixer` instance with the specified frequency in Hz, sample rate in Hz, and initial phase in radians.
22 /// The `frequency_increment_normalized` is calculated as the ratio of the desired frequency shift to the sample rate, which determines how much the phase will be incremented for each sample processed.
23 /// The `initial_phase` parameter allows you to set the starting phase of the complex exponential, which can be useful for synchronizing the mixer with other components in a signal processing chain or for achieving specific phase relationships in modulation schemes.
24 pub fn new(frequency_hz: f64, sample_rate_hz: f64, initial_phase: Option<f64>) -> Self {
25 Self {
26 phase: initial_phase.unwrap_or(0.0),
27 phase_increment: 2.0*PI*frequency_hz / sample_rate_hz,
28 }
29 }
30
31 // Increment the phase with wrapping to keep it in the range [0, 2*PI) for positive frequencies or (-2*PI, 0] for negative frequencies. This ensures that the phase remains bounded and prevents numerical issues that can arise from unbounded phase growth.
32 pub fn increment_phase(&mut self) {
33 self.phase += self.phase_increment;
34 if self.phase_increment > 0.0 {
35 if self.phase > 2.0*PI {
36 self.phase -= 2.0*PI; // Wrap around to keep phase in [0, 2*PI)
37 }
38 } else if self.phase < 0.0 {
39 self.phase += 2.0*PI; // Wrap around to keep phase in [0, 2*PI)
40 }
41 }
42
43 /// Setters and getters for manual control
44 pub fn set_phase(&mut self, x : f64){
45 self.phase = x;
46 }
47 pub fn get_phase(&mut self) -> f64{
48 self.phase
49 }
50 pub fn set_phase_increment(&mut self, x : f64){
51 self.phase_increment = x;
52 }
53 pub fn get_phase_increment(&mut self) -> f64{
54 self.phase_increment
55 }
56}
57
58impl StreamOperatorManagement for FrequencyMixer {
59 fn reset(&mut self) -> Result<(), ErrorsJSL> {
60 self.phase = 0.0;
61 Ok(())
62 }
63
64 fn finalize(&mut self) -> Result<(), ErrorsJSL> {
65 Ok(())
66 }
67}
68
69/// This is a real-valued mixer that produces a real-valued output by multiplying the input signal with the cosine of the current phase.
70/// This type of mixer is commonly used for applications such as amplitude modulation (AM) or for down-converting a signal to baseband in a receiver.
71impl StreamOperator<f64, f64> for FrequencyMixer {
72 fn process(&mut self, input: &[f64]) -> Result<Option<Vec<f64>>, ErrorsJSL> {
73 if input.is_empty() {
74 return Ok(None);
75 }
76 input.iter().map(|&x| {
77 let mixer = self.phase.cos();
78 self.increment_phase();
79 Ok(x * mixer)
80 }).collect::<Result<Vec<f64>, ErrorsJSL>>().map(Some)
81 }
82
83 fn flush(&mut self) -> Result<Option<Vec<f64>>, ErrorsJSL> {
84 Ok(None)
85 }
86}
87
88/// This is a complex-valued mixer that produces a complex-valued output by multiplying the input signal with a complex exponential based on the current phase.
89/// This type of mixer is commonly used for applications such as quadrature amplitude modulation (QAM) or for up-converting a baseband signal to a higher frequency in a transmitter.
90impl StreamOperator<f64, Complex<f64>> for FrequencyMixer {
91 fn process(&mut self, input: &[f64]) -> Result<Option<Vec<Complex<f64>>>, ErrorsJSL> {
92 if input.is_empty() {
93 return Ok(None);
94 }
95 input.iter().map(|&x| {
96 let mixer = Complex::from_polar(1.0, self.phase);
97 self.increment_phase();
98 Ok(x * mixer)
99 }).collect::<Result<Vec<Complex<f64>>, ErrorsJSL>>().map(Some)
100 }
101
102 fn flush(&mut self) -> Result<Option<Vec<Complex<f64>>>, ErrorsJSL> {
103 Ok(None)
104 }
105}
106
107/// This is a complex-valued mixer that takes a complex-valued input signal and produces a complex-valued output by multiplying the input signal with a complex exponential based on the current phase.
108/// This type of mixer is commonly used for applications such as quadrature amplitude modulation (QAM) or for up-converting a baseband signal to a higher frequency in a transmitter, as well as for down-converting a signal to baseband in a receiver.
109/// It can also be used for frequency translation in spectral processing applications, such as shifting the frequency of a signal for analysis or filtering purposes
110impl StreamOperator<Complex<f64>, Complex<f64>> for FrequencyMixer {
111 fn process(&mut self, input: &[Complex<f64>]) -> Result<Option<Vec<Complex<f64>>>, ErrorsJSL> {
112 if input.is_empty() {
113 return Ok(None);
114 }
115 input.iter().map(|&x| {
116 let mixer = Complex::from_polar(1.0, self.phase);
117 self.increment_phase();
118 Ok(x * mixer)
119 }).collect::<Result<Vec<Complex<f64>>, ErrorsJSL>>().map(Some)
120 }
121
122 fn flush(&mut self) -> Result<Option<Vec<Complex<f64>>>, ErrorsJSL> {
123 Ok(None)
124 }
125}
126
127#[cfg(test)]
128mod tests {
129 use super::*;
130 fn approx_eq(a: Complex<f64>, b: Complex<f64>, tol: f64) -> bool {
131 (a - b).norm() < tol
132 }
133 #[test]
134 fn test_mixer(){
135 let mut dut = FrequencyMixer::new(1000.0, 8000.0, None);
136 let input = vec![1.0; 8];
137 let output = dut.process(&input).unwrap().unwrap();
138 let expected = input.iter().enumerate().map(|(n, &x)| {
139 let phase = dut.phase_increment * (n) as f64;
140 x * Complex::from_polar(1.0, phase)
141 }).collect::<Vec<Complex<f64>>>();
142 for (o, e) in output.iter().zip(expected.iter()) {
143 assert!(approx_eq(*o, *e, 1e-6), "Output {o} is not approximately equal to expected {e}");
144 }
145 }
146}