#![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 {
fn filter(&mut self, input: &[Flt]) -> Vd;
fn reset(&mut self);
fn clone_dyn(&self) -> Box<dyn Filter>;
}
impl Clone for Box<dyn Filter> {
fn clone(&self) -> Self {
self.clone_dyn()
}
}
#[cfg_attr(feature = "extension-module", pyclass)]
#[derive(Clone, Copy, Debug)]
pub struct Biquad {
w1: Flt,
w2: Flt,
b0: Flt,
b1: Flt,
b2: Flt,
a1: Flt,
a2: Flt,
}
#[cfg(feature = "extension-module")]
#[cfg_attr(feature = "extension-module", pymethods)]
impl Biquad {
#[new]
pub fn new_py<'py>(coefs: PyReadonlyArrayDyn<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, cuton_Hz: Flt) -> PyResult<Biquad> {
Ok(Biquad::firstOrderHighPass(fs, cuton_Hz)?)
}
#[pyo3(name = "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 {
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 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);
let coefs = [
facnum, -facnum, 0., 1., facden, 0., ];
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;
}
}
}
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.clone())
}
}
#[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]
pub fn new_py<'py>(coefs: PyReadonlyArrayDyn<Flt>) -> PyResult<Self> {
Ok(SeriesBiquad::new(&coefs.as_slice()?)?)
}
#[pyo3(name = "unit")]
#[staticmethod]
pub fn unit_py() -> SeriesBiquad {
SeriesBiquad::unit()
}
#[pyo3(name = "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")]
pub fn reset_py(&mut self) {
self.reset();
}
}
impl SeriesBiquad {
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 })
}
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 {
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)]
pub struct BiquadBank {
biqs: Vec<Box<dyn Filter>>,
gains: Vec<Flt>,
}
#[cfg(feature = "extension-module")]
#[cfg_attr(feature = "extension-module", pymethods)]
impl 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")]
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")]
pub fn reset_py(&mut self) {
self.reset();
}
#[pyo3(name = "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")]
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")]
pub fn len_py(&self) -> usize {
self.len()
}
}
impl BiquadBank {
pub fn new(biqs: Vec<Box<dyn Filter>>) -> BiquadBank {
let gains = vec![1.0; biqs.len()];
BiquadBank { biqs, gains }
}
pub fn len(&self) -> usize {
self.biqs.len()
}
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.));
}
pub fn set_gains(&mut self, gains: &[Flt]) {
if gains.len() != self.gains.len() {
panic!("Invalid gains size!");
}
self.gains.clone_from(&gains.to_vec());
}
pub fn analysis(&mut self, input: &[Flt]) -> Vec<Vd> {
let filtered_out: Vec<Vd> = self
.biqs
.par_iter_mut()
.map(|biq| biq.filter(input))
.collect();
filtered_out
}
}
impl Filter for BiquadBank {
fn filter(&mut self, input: &[Flt]) -> Vd {
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) {
*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() {
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);
inp[0] = 0.5;
inp[1] = 0.5;
assert_eq!(&inp, &filtered);
}
#[test]
fn test_biquadbank1() {
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);
}
}