Skip to main content

lib_jsl_dsp/discrete/sources/
pulse_train.rs

1//! Pulse train source.
2//!
3//! See the book entry [Signal sources: oscillators, CORDIC and waveforms](https://jwkunz.github.io/lib_jsl/book/comms/sources.html#waveforms-and-noise).
4
5use super::nco::{threshold_from_duty, threshold_from_ratio, Nco, NcoSource, Phase, Waveform};
6use lib_jsl_core::ErrorsJSL;
7
8/// A unipolar pulse train: `1` for the first part of every cycle (the duty fraction), `0` after.
9#[derive(Clone, Debug)]
10pub struct PulseTrainWave {
11    threshold: u128,
12}
13
14impl PulseTrainWave {
15    /// A pulse train with the given duty cycle in `[0, 1]`.
16    pub fn new(duty: f64) -> Result<PulseTrainWave, ErrorsJSL> {
17        Ok(PulseTrainWave { threshold: threshold_from_duty(duty)? })
18    }
19}
20
21impl Waveform for PulseTrainWave {
22    type Output = f64;
23
24    fn sample(&mut self, phase: Phase) -> f64 {
25        if (phase.0 as u128) < self.threshold { 1.0 } else { 0.0 }
26    }
27}
28
29impl NcoSource<PulseTrainWave> {
30    /// Pulses at `frequency_hz` with the given duty cycle.
31    pub fn pulse_train(frequency_hz: f64, sample_rate: f64, duty: f64) -> Result<Self, ErrorsJSL> {
32        Ok(NcoSource::from_parts(Nco::new(frequency_hz, sample_rate)?, PulseTrainWave::new(duty)?))
33    }
34
35    /// Pulses repeating every `period` samples, each `width` samples long (`width <= period`).
36    pub fn pulse_train_with_period(period: u64, width: u64) -> Result<Self, ErrorsJSL> {
37        let wave = PulseTrainWave { threshold: threshold_from_ratio(width, period)? };
38        Ok(NcoSource::from_parts(Nco::from_period(period)?, wave))
39    }
40}
41
42/// Convenience: `length` samples of a pulse train with an integer `period` (>= 2) and pulse
43/// `width` in samples (0 to `period`).
44pub fn pulse_train(period: usize, width: usize, length: usize) -> Result<Vec<f64>, ErrorsJSL> {
45    Ok(NcoSource::pulse_train_with_period(period as u64, width as u64)?.generate(length))
46}
47
48#[cfg(test)]
49mod tests {
50    use super::*;
51
52    #[test]
53    fn simple_patterns() {
54        assert_eq!(pulse_train(5, 2, 10).unwrap(), vec![1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0]);
55        assert_eq!(pulse_train(4, 0, 4).unwrap(), vec![0.0; 4]);
56        assert_eq!(pulse_train(4, 4, 4).unwrap(), vec![1.0; 4]);
57        assert!(pulse_train(4, 5, 4).is_err());
58        assert!(pulse_train(1, 1, 4).is_err());
59    }
60
61    #[test]
62    fn widths_are_exact_for_every_period() {
63        for period in 2..80usize {
64            for width in 0..=period {
65                let x = pulse_train(period, width, period * 12).unwrap();
66                for (n, v) in x.iter().enumerate() {
67                    assert_eq!(*v, if n % period < width { 1.0 } else { 0.0 }, "period {period} width {width} n {n}");
68                }
69            }
70        }
71    }
72
73    #[test]
74    fn frequency_form() {
75        let mut p = NcoSource::pulse_train(10.0, 100.0, 0.3).unwrap();
76        let x = p.generate(100);
77        assert_eq!(x.iter().sum::<f64>(), 30.0);
78        assert_eq!(&x[..10], &[1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]);
79        assert!(NcoSource::pulse_train(10.0, 100.0, -0.1).is_err());
80    }
81
82    #[test]
83    fn amplitude_scaling_makes_a_clock_or_trigger() {
84        let mut p = NcoSource::pulse_train_with_period(4, 1).unwrap().with_amplitude(3.3);
85        assert_eq!(p.generate(5), vec![3.3, 0.0, 0.0, 0.0, 3.3]);
86    }
87}