use super::*;
use crate::config::*;
use anyhow::{bail, Result};
use num::Complex;
#[cfg_attr(feature = "python-bindings", pyclass)]
#[derive(Clone, Copy, Debug)]
pub struct Biquad {
w1: Flt,
w2: Flt,
b0: Flt,
b1: Flt,
b2: Flt,
a1: Flt,
a2: Flt,
}
#[cfg(feature = "python-bindings")]
#[cfg_attr(feature = "python-bindings", pymethods)]
impl Biquad {
#[new]
pub fn new_py<'py>(coefs: PyArrayLike1<Flt>) -> PyResult<Self> {
Ok(Biquad::new(coefs.as_slice()?)?)
}
#[pyo3(name = "unit")]
#[staticmethod]
pub fn unit_py() -> Biquad {
Biquad::unit()
}
#[pyo3(name = "firstOrderHighPass")]
#[staticmethod]
pub fn firstOrderHighPass_py(fs: Flt, fc: Flt) -> PyResult<Biquad> {
Ok(Biquad::firstOrderHighPass(fs, fc)?)
}
#[pyo3(name = "firstOrderLowPass")]
#[staticmethod]
pub fn firstOrderLowPass_py(fs: Flt, fc: Flt) -> PyResult<Biquad> {
Ok(Biquad::firstOrderLowPass(fs, fc)?)
}
#[pyo3(name = "tf")]
pub fn tf_py<'py>(
&self,
py: Python<'py>,
fs: Flt,
freq: PyArrayLike1<Flt>,
) -> PyResult<PyArr1Cflt<'py>> {
let freq = freq.as_array();
let res = PyArray1::from_array_bound(py, &self.tf(fs, freq));
Ok(res)
}
#[pyo3(name = "filter")]
pub fn filter_py<'py>(
&mut self,
py: Python<'py>,
input: PyArrayLike1<Flt>,
) -> PyResult<PyArr1Flt<'py>> {
Ok(PyArray1::from_vec_bound(py, self.filter(input.as_slice()?)))
}
}
impl Biquad {
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")
}
}
fn fromCoefs(b0: Flt, b1: Flt, b2: Flt, a1: Flt, a2: Flt) -> Biquad {
Biquad {
w1: 0.,
w2: 0.,
b0,
b1,
b2,
a1,
a2,
}
}
fn unit() -> Biquad {
let filter_coefs = &[1., 0., 0., 1., 0., 0.];
Biquad::new(filter_coefs).unwrap()
}
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);
Ok(Biquad::fromCoefs(
facnum, -facnum, 0., facden, 0., ))
}
pub fn firstOrderLowPass(fs: Flt, fc: Flt) -> Result<Biquad> {
if fc <= 0. {
bail!("Cuton frequency, given: should be > 0")
}
if fc >= fs / 2. {
bail!("Cuton frequency should be smaller than Nyquist frequency")
}
let b0 = pi*fc/(pi*fc+fs);
let b1 = b0;
let a1 = (pi*fc-fs)/(pi*fc+fs);
Ok(Biquad::fromCoefs(b0, b1, 0., a1, 0.))
}
#[inline]
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;
}
}
}
impl Default for Biquad {
fn default() -> Self {
Biquad::unit()
}
}
impl Filter for Biquad {
fn filter(&mut self, input: &[Flt]) -> Vec<Flt> {
let mut out = input.to_vec();
self.filter_inout(&mut out);
out
}
fn reset(&mut self) {
self.w1 = 0.;
self.w2 = 0.;
}
fn clone_dyn(&self) -> Box<dyn Filter> {
Box::new(*self)
}
}
impl<'a, T: AsArray<'a, Flt>> TransferFunction<'a, T> for Biquad {
fn tf(&self, fs: Flt, freq: T) -> Ccol {
let freq = freq.into();
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
}
}
#[cfg(test)]
mod test {
use approx::assert_abs_diff_eq;
use num::complex::ComplexFloat;
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]
fn test_firstOrderLowpass() {
let fs = 1e5;
let fc = 10.;
let b = Biquad::firstOrderLowPass(fs, fc).unwrap();
let mut freq = Dcol::from_elem(5, 0.);
freq[1] = fc;
freq[2] = fs / 2.;
let tf = b.tf(fs, freq.view());
assert_abs_diff_eq!(tf[0].re, 1., epsilon = 1e-6);
assert_abs_diff_eq!(tf[0].im, 0.);
assert_abs_diff_eq!(tf[1].abs(), 1. / Flt::sqrt(2.), epsilon = 1e-6);
}
}