165 lines
4.6 KiB
Rust
165 lines
4.6 KiB
Rust
use super::*;
|
|
use ndarray::prelude::*;
|
|
use anyhow::{Result, bail};
|
|
use num::Complex;
|
|
|
|
#[cfg_attr(feature = "python-bindings", pyclass)]
|
|
#[derive(Clone, Copy, Debug)]
|
|
/// # A biquad is a second order recursive filter structure.
|
|
///
|
|
///
|
|
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 = "python-bindings")]
|
|
#[cfg_attr(feature = "python-bindings", 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())
|
|
}
|
|
pub fn filter_inout(&mut self, inout: &mut [Flt]) {
|
|
for sample in inout.iter_mut() {
|
|
let w0 = *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;
|
|
*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)
|
|
}
|
|
}
|
|
impl TransferFunction for Biquad {
|
|
fn tf(&self, fs: Flt, freq: VdView) -> Ccol {
|
|
let res = freq.mapv(|f| {
|
|
let z = Complex::exp(I * 2. * pi * f / fs);
|
|
let num = self.b0 + self.b1 / z + self.b2 / z / z;
|
|
let den = 1. + self.a1 / z + self.a2 / z / z;
|
|
num / den
|
|
});
|
|
res
|
|
// re
|
|
}
|
|
}
|
|
#[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);
|
|
}
|
|
}
|