lasprs 0.2.1

Library for Acoustic Signal Processing (Rust edition, with optional Python bindings via pyo3)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
//! # Filter implemententations for biquads, series of biquads and banks of series of biquads.
//!
//! Contains [Biquad], [SeriesBiquad], and [BiquadBank]. These are all constructs that work on
//! blocks of input data, and apply filters on it. Todo: implement FIR filter.
#![allow(non_snake_case)]
use super::config::*;
use anyhow::{bail, Result};
use numpy::ndarray::{ArrayD, ArrayViewD, ArrayViewMutD};
use numpy::{IntoPyArray, PyArray1, PyArrayDyn, PyArrayLike1, PyReadonlyArrayDyn};
use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
use pyo3::{pymodule, types::PyModule, PyResult};
use rayon::prelude::*;

pub trait Filter: Send {
    //! The filter trait is implemented by Biquad, SeriesBiquad, and BiquadBank

    /// Filter input to generate output. A vector of output floats is generated with the same
    /// length as input.
    fn filter(&mut self, input: &[Flt]) -> Vd;
    /// Reset the filter state(s). In essence, this makes sure that all memory of the past is
    /// forgotten.
    fn reset(&mut self);

    /// Required method for cloning a BiquadBank, such that arbitrary filter types can be used as
    /// their 'channels'.
    fn clone_dyn(&self) -> Box<dyn Filter>;
}
impl Clone for Box<dyn Filter> {
    fn clone(&self) -> Self {
        self.clone_dyn()
    }
}

/// # A biquad is a second order recursive filter structure.
#[cfg_attr(feature = "extension-module", pyclass)]
#[derive(Clone, Copy, Debug)]
pub struct Biquad {
    // State parameters
    w1: Flt,
    w2: Flt,
    // Filter coefficients - forward
    b0: Flt,
    b1: Flt,
    b2: Flt,
    // Filter coefficients - recursive
    // a0: Flt, // a0 is assumed one, not used
    a1: Flt,
    a2: Flt,
}
#[cfg(feature = "extension-module")]
#[cfg_attr(feature = "extension-module", pymethods)]
impl Biquad {
    #[new]
    /// Create new biquad filter. See [Biquad::new()]
    ///
    pub fn new_py<'py>(coefs: PyReadonlyArrayDyn<Flt>) -> PyResult<Self> {
        Ok(Biquad::new(&coefs.as_slice()?)?)
    }
    #[pyo3(name = "unit")]
    #[staticmethod]
    /// See: [Biquad::unit()]
    pub fn unit_py() -> Biquad {
        Biquad::unit()
    }
    #[pyo3(name = "firstOrderHighPass")]
    #[staticmethod]
    /// See: [Biquad::firstOrderHighPass()]
    pub fn firstOrderHighPass_py(fs: Flt, cuton_Hz: Flt) -> PyResult<Biquad> {
        Ok(Biquad::firstOrderHighPass(fs, cuton_Hz)?)
    }
    #[pyo3(name = "filter")]
    /// See: [Biquad::filter()]
    pub fn filter_py<'py>(
        &mut self,
        py: Python<'py>,
        input: PyArrayLike1<Flt>,
    ) -> PyResult<&'py PyArray1<Flt>> {
        Ok(self.filter(input.as_slice()?).into_pyarray(py))
    }
}
impl Biquad {
    /// Create new biquad filter from given filter coeficients
    ///
    /// # Args
    ///
    /// - coefs: Filter coefficients.
    ///
    pub fn new(coefs: &[Flt]) -> Result<Self> {
        match coefs {
            [b0, b1, b2, a0, a1, a2] => {
                if *a0 != 1.0  {
                    bail!("Coefficient a0 should be equal to 1.0")
                }
                Ok(Biquad { w1: 0., w2: 0., b0: *b0, b1: *b1, b2: *b2, a1: *a1, a2: *a2})
            },
            _ => bail!("Could not initialize biquad. Please make sure that the coefficients contain 6 terms")
        }
    }

    /// Create unit impulse response biquad filter. Input = output
    fn unit() -> Biquad {
        let filter_coefs = &[1., 0., 0., 1., 0., 0.];
        Biquad::new(filter_coefs).unwrap()
    }

    /// Initialize biquad as first order high pass filter.
    ///
    ///
    /// * fs: Sampling frequency in \[Hz\]
    /// * cuton_Hz: -3 dB cut-on frequency in \[Hz\]
    ///
    pub fn firstOrderHighPass(fs: Flt, cuton_Hz: Flt) -> Result<Biquad> {
        if fs <= 0. {
            bail!("Invalid sampling frequency: {} [Hz]", fs);
        }
        if cuton_Hz <= 0. {
            bail!("Invalid cuton frequency: {} [Hz]", cuton_Hz);
        }
        if cuton_Hz >= 0.98 * fs / 2. {
            bail!(
                "Invalid cuton frequency. We limit this to 0.98* fs / 2. Given value {} [Hz]",
                cuton_Hz
            );
        }

        let tau: Flt = 1. / (2. * pi * cuton_Hz);
        let facnum = 2. * fs * tau / (1. + 2. * fs * tau);
        let facden = (1. - 2. * fs * tau) / (1. + 2. * fs * tau);

        let coefs = [
            facnum,  // b0
            -facnum, // b1
            0.,      // b2
            1.,      // a0
            facden,  // a1
            0.,      // a2
        ];

        Ok(Biquad::new(&coefs).unwrap())
    }
    fn filter_inout(&mut self, inout: &mut [Flt]) {
        for sample in 0..inout.len() {
            let w0 = inout[sample] - self.a1 * self.w1 - self.a2 * self.w2;
            let yn = self.b0 * w0 + self.b1 * self.w1 + self.b2 * self.w2;
            self.w2 = self.w1;
            self.w1 = w0;
            inout[sample] = yn;
        }
        // println!("{:?}", inout);
    }
}
impl Filter for Biquad {
    fn filter(&mut self, input: &[Flt]) -> Vec<Flt> {
        let mut out = input.to_vec();
        self.filter_inout(&mut out);
        // println!("{:?}", out);
        out
    }
    fn reset(&mut self) {
        self.w1 = 0.;
        self.w2 = 0.;
    }
    fn clone_dyn(&self) -> Box<dyn Filter> {
        Box::new(self.clone())
    }
}

/// Series of biquads that filter sequentially on an input signal
///
/// # Examples
///
/// See [tests]
/// ```
#[derive(Clone, Debug)]
#[cfg_attr(feature = "extension-module", pyclass)]
pub struct SeriesBiquad {
    biqs: Vec<Biquad>,
}

#[cfg(feature = "extension-module")]
#[cfg_attr(feature = "extension-module", pymethods)]
impl SeriesBiquad {
    #[new]
    /// Create new series filter set. See [SeriesBiquad::new()]
    ///
    pub fn new_py<'py>(coefs: PyReadonlyArrayDyn<Flt>) -> PyResult<Self> {
        Ok(SeriesBiquad::new(&coefs.as_slice()?)?)
    }
    #[pyo3(name = "unit")]
    #[staticmethod]
    /// See: [Biquad::unit()]
    pub fn unit_py() -> SeriesBiquad {
        SeriesBiquad::unit()
    }
    #[pyo3(name = "filter")]
    /// See: [SeriesBiquad::filter()]
    pub fn filter_py<'py>(
        &mut self,
        py: Python<'py>,
        input: PyArrayLike1<Flt>,
    ) -> PyResult<&'py PyArray1<Flt>> {
        Ok(self.filter(input.as_slice()?).into_pyarray(py))
    }
    #[pyo3(name = "reset")]
    /// See: [SeriesBiquad::reset()]
    pub fn reset_py(&mut self) {
        self.reset();
    }
}
impl SeriesBiquad {
    /// Create a new series biquad, having an arbitrary number of biquads.
    ///
    /// # Arguments
    ///
    /// * `filter_coefs` - Vector of biquad coefficients, stored in a single array. The first six
    /// for the first biquad, and so on.
    ///
    ///
    pub fn new(filter_coefs: &[Flt]) -> Result<SeriesBiquad> {
        if filter_coefs.len() % 6 != 0 {
            bail!(
                "filter_coefs should be multiple of 6, given: {}.",
                filter_coefs.len()
            );
        }
        let nfilters = filter_coefs.len() / 6;

        let mut biqs: Vec<Biquad> = Vec::with_capacity(nfilters);
        for coefs in filter_coefs.chunks(6) {
            let biq = Biquad::new(coefs)?;
            biqs.push(biq);
        }

        if biqs.len() == 0 {
            bail!("No filter coefficients given!");
        }

        Ok(SeriesBiquad { biqs })
    }

    /// Unit impulse response series biquad. Input = output
    pub fn unit() -> SeriesBiquad {
        let filter_coefs = &[1., 0., 0., 1., 0., 0.];
        SeriesBiquad::new(filter_coefs).unwrap()
    }
    fn clone_dyn(&self) -> Box<dyn Filter> {
        Box::new(self.clone())
    }
}

impl Filter for SeriesBiquad {
    //! Filter input by applying all biquad filters in series on each input sample, to obtain the
    //! output samples.
    //!
    fn filter(&mut self, input: &[Flt]) -> Vd {
        let mut inout = input.to_vec();
        for biq in self.biqs.iter_mut() {
            biq.filter_inout(&mut inout);
        }
        inout
    }
    fn reset(&mut self) {
        self.biqs.iter_mut().for_each(|f| f.reset());
    }
    fn clone_dyn(&self) -> Box<dyn Filter> {
        Box::new(self.clone())
    }
}

#[cfg_attr(feature = "extension-module", pyclass)]
#[derive(Clone)]
/// Multiple biquad filter that operate in parallel on a signal, and can apply a gain value to each
/// of the returned values. The BiquadBank can be used to decompose a signal by running it through
/// parallel filters, or it can directly be used to eq a signal. For the latter process, also a
/// gain can be applied when the output is made as the sum of the filtered inputs for each biquad.
///
/// # Detailed description
///
/// Below is an example of the signal flow is for the case of three SeriesBiquad filters, `h1`,
/// `h2` and `h3`:
///
/// ```markdown
///
///            analysis()       gain application             sum()              
///                                                               
///                  +------+   +-----+                    +------------+
///            +-----+ h1   |---+ g1  +-------------+      |            |
///            |     +------+   +-----+             ++     |   +------  |
///            |                                     +-----|   ++       |
///  Input     |     +------+   +-----+                    |    ++      |   Output of filter()
///--------|>--+-----+ h2   |---+ g2  |--------------------|     +-+    +----------------|>
///            |     ---+---+   +-----+                    |     +-+    |
///            |                                     +-----|    ++      |
///            |     +------+   +-----+             ++     |   ++       |
///            +-----+ h3   |---+ g3  |-------------+      |   +------  |
///                  +------+   +-----+                    |            |
///                           |                            +------------+
///                           |                  
///                           | Output of analysis() method (optional)
///                           +-------------|>
/// ```
pub struct BiquadBank {
    biqs: Vec<Box<dyn Filter>>,
    gains: Vec<Flt>,
}

#[cfg(feature = "extension-module")]
#[cfg_attr(feature = "extension-module", pymethods)]
/// Methods to wrap it in Python
impl BiquadBank {
    #[new]
    /// Create new biquadbank filter set. See [BiquadBank::new()]
    ///
    pub fn new_py<'py>(coefs: PyReadonlyArrayDyn<Flt>) -> PyResult<Self> {
        let mut filts = vec![];
        for col in coefs.as_array().columns() {
            match col.as_slice() {
                Some(colslice) => {
                    let new_ser = SeriesBiquad::new(colslice)?;
                    filts.push(new_ser.clone_dyn());
                }
                None => {
                    return Err(PyValueError::new_err("Error generating column"));
                }
            }
        }
        Ok(BiquadBank::new(filts))
    }
    #[pyo3(name = "filter")]
    /// See: [BiquadBank::filter()]
    pub fn filter_py<'py>(
        &mut self,
        py: Python<'py>,
        input: PyArrayLike1<Flt>,
    ) -> PyResult<&'py PyArray1<Flt>> {
        Ok(self.filter(input.as_slice()?).into_pyarray(py))
    }
    #[pyo3(name = "reset")]
    /// See: [BiquadBank::reset()]
    pub fn reset_py(&mut self) {
        self.reset();
    }

    #[pyo3(name = "set_gains")]
    /// See: [BiquadBank::set_gains()]
    pub fn set_gains_py<'py>(&mut self, py: Python<'py>, gains: PyArrayLike1<Flt>) -> PyResult<()> {
        if gains.len() != self.len() {
            return Err(PyValueError::new_err("Invalid number of provided gains"));
        }
        self.set_gains(gains.as_slice()?);
        Ok(())
    }
    #[pyo3(name = "set_gains_dB")]
    /// See: [BiquadBank::set_gains_dB()]
    pub fn set_gains_dB_py<'py>(&mut self, py: Python<'py>, gains_dB: PyArrayLike1<Flt>) -> PyResult<()> {
        if gains_dB.len() != self.len() {
            return Err(PyValueError::new_err("Invalid number of provided gains"));
        }
        self.set_gains_dB(gains_dB.as_slice()?);
        Ok(())

    }
    #[pyo3(name = "len")]
    /// See: [BiquadBank::len()]
    pub fn len_py(&self) -> usize {
        self.len()
    }
}

impl BiquadBank {
    /// Create new biquad bank. Initialized from given vector of series biquads.
    pub fn new(biqs: Vec<Box<dyn Filter>>) -> BiquadBank {
        let gains = vec![1.0; biqs.len()];
        BiquadBank { biqs, gains }
    }
    /// Return the number of parallel filters installed.
    pub fn len(&self) -> usize {
        self.biqs.len()
    }

    /// Set the gains for each of the biquad. The gains are not used in the analyisis phase, but in
    /// the reconstruction phase, so when BiquadBank::filter() is run on an input signal.
    ///
    /// # Panics
    ///
    /// When gains_dB.len() != to the number of filters.
    pub fn set_gains_dB(&mut self, gains_dB: &[Flt]) {
        if gains_dB.len() != self.gains.len() {
            panic!("Invalid gains size!");
        }
        self.gains
            .iter_mut()
            .zip(gains_dB)
            .for_each(|(g, gdB)| *g = Flt::powf(10., gdB / 20.));
    }
    /// Set linear gain values for each biquad. Same comments hold as for
    /// [BiquadBank::set_gains_dB()].
    pub fn set_gains(&mut self, gains: &[Flt]) {
        if gains.len() != self.gains.len() {
            panic!("Invalid gains size!");
        }
        // This could be done more efficient, but it does not matter. How often would you change
        // the gain values?
        self.gains.clone_from(&gains.to_vec());
    }
    /// Analysis step. Runs input signal through all filters. Outputs a vector of output results,
    /// one for each filter in the bank.

    pub fn analysis(&mut self, input: &[Flt]) -> Vec<Vd> {
        // Filtered output for each filter in biquad bank
        let filtered_out: Vec<Vd> = self
            .biqs
            .par_iter_mut()
            // .iter_mut()
            .map(|biq| biq.filter(input))
            .collect();
        filtered_out
    }
}

impl Filter for BiquadBank {
    fn filter(&mut self, input: &[Flt]) -> Vd {
        // Sum of filter output times gains
        let filtered_out = self.analysis(input);

        let mut out: Vd = vec![0.; input.len()];

        for (f, g) in filtered_out.iter().zip(&self.gains) {
            for (outi, fi) in out.iter_mut().zip(f) {
                // Sum and multiply by gain value
                *outi += g * fi;
            }
        }
        out
    }
    fn reset(&mut self) {
        self.biqs.iter_mut().for_each(|b| b.reset());
    }
    fn clone_dyn(&self) -> Box<dyn Filter> {
        Box::new(self.clone())
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_biquad1() {
        let mut ser = Biquad::unit();
        let inp = vec![1., 0., 0., 0., 0., 0.];
        let filtered = ser.filter(&inp);
        assert_eq!(&filtered, &inp);
    }
    #[test]
    #[should_panic]
    fn test_biquad2() {
        // A a0 coefficient not in the right place, meaning we panic on unwrap
        let filter_coefs = vec![1., 0., 0., 0., 0., 0.];
        let mut ser = SeriesBiquad::new(&filter_coefs).unwrap();
        let inp = vec![1., 0., 0., 0., 0., 0.];
        let filtered = ser.filter(&inp);
        assert_eq!(&filtered, &inp);
    }
    #[test]
    fn test_biquad3() {
        let filter_coefs = vec![0.5, 0.5, 0., 1., 0., 0.];
        let mut ser = SeriesBiquad::new(&filter_coefs).unwrap();

        let mut inp = vec![1., 0., 0., 0., 0., 0.];
        let filtered = ser.filter(&inp);

        // Change input to see match what should come out of output
        inp[0] = 0.5;
        inp[1] = 0.5;
        assert_eq!(&inp, &filtered);
    }
    #[test]
    fn test_biquadbank1() {
        //! Creates two unit filters with gains of 0.5. Runs the input signal through these filters
        //! in parallel and check if input == output.
        let ser = Biquad::unit();
        let mut biq = BiquadBank::new(vec![ser.clone_dyn(), ser.clone_dyn()]);
        biq.set_gains(&[0.5, 0.5]);
        let inp = vec![1., 0., 0., 0., 0., 0.];
        let out = biq.filter(&inp);
        assert_eq!(&out, &inp);
    }
}