irox_stats/
filter.rs

1// SPDX-License-Identifier: MIT
2// Copyright 2023 IROX Contributors
3
4//!
5//! This module provides Discrete Convolution Filters for Digital Signals Processing.
6//!
7//! Many algorithms sourced from the wonderful [DSPGuide](https://www.dspguide.com)
8//!
9
10extern crate alloc;
11
12use alloc::collections::vec_deque::Drain;
13use alloc::collections::VecDeque;
14use alloc::vec;
15use alloc::vec::Vec;
16
17///
18/// Represents a convolving operation with streaming input data against the provided kernel.
19#[derive(Clone)]
20pub struct StreamingFilter {
21    kernel: Vec<f64>,
22    buffer: VecDeque<f64>,
23}
24
25impl StreamingFilter {
26    ///
27    /// Creates a new streaming filter with the provided input kernel
28    pub fn new(kernel: Vec<f64>) -> StreamingFilter {
29        let len = kernel.len() - 2;
30        let buffer = VecDeque::from(vec![0.0; len]);
31        StreamingFilter { kernel, buffer }
32    }
33
34    ///
35    /// Adds the sample to the internal data buffer.  If there are enough samples in the buffer,
36    /// the convolve operation is run, and the output returned.  Otherwise returns None.
37    pub fn add_and_convolve(&mut self, sample: f64) -> Option<f64> {
38        self.buffer.push_back(0.0_f64);
39
40        self.kernel.iter().enumerate().for_each(|(idx, k)| {
41            if let Some(val) = self.buffer.get_mut(idx) {
42                *val += sample * *k;
43            }
44        });
45
46        self.buffer.pop_front()
47    }
48
49    ///
50    /// Drains the residual data in the buffer to the caller.
51    pub fn drain(&mut self) -> Drain<f64> {
52        self.buffer.drain(..)
53    }
54}
55
56///
57/// Performs the [discrete convolution](https://en.wikipedia.org/wiki/Convolution#Discrete_convolution)
58/// function.  Convolves the provided kernel against the provided data.
59pub fn convolve<K: AsRef<[f64]>, D: AsRef<[f64]>>(kernel: K, data: D) -> Vec<f64> {
60    let kernel = kernel.as_ref();
61    let data = data.as_ref();
62    let length = kernel.len() + data.len();
63    let mut out: Vec<f64> = Vec::with_capacity(length);
64    out.resize(length, 0.0_f64);
65
66    data.iter().enumerate().for_each(|(d_idx, d)| {
67        kernel.iter().enumerate().for_each(|(k_idx, k)| {
68            let idx = d_idx + k_idx;
69            if let Some(val) = out.get_mut(idx) {
70                *val += *d * *k;
71            }
72        });
73    });
74
75    out
76}