refactor: move iir_filter to separate compilation unit

This commit is contained in:
2026-03-02 17:23:14 +01:00
parent 7de913f19c
commit 6ff7db4d93
9 changed files with 103 additions and 70 deletions

View File

@@ -2,6 +2,7 @@ project(Pasada_Lib)
SET(PASADA_SRC
library.cpp
iir_filter.cpp
)
if(PASADA_BUILD_TESTS)

51
pasada-lib/iir_filter.cpp Normal file
View File

@@ -0,0 +1,51 @@
//
// Created by david on 02.03.2026.
//
#include "iir_filter.h"
Buf::Buf(size_t N): size(N), n(0) {
data.resize(N);
data.assign(N, 0.0);
}
void Buf::push(double val) {
data[n] = val;
n = (n+1) % size;
}
Filt::Filt(size_t N, size_t shift, size_t offset, std::vector<double> taps): Buf(N), shift(shift), offset(offset), taps(taps) {
if (taps.size() != N) throw std::invalid_argument("taps.size() != N");
}
double Filt::filter(double val) {
this->push(val);
return this->peek();
}
double Filt::peek() {
double sum = 0;
for (size_t i = offset; i < this->size; i++) {
//size_t n = (this->n - i + shift - 1) % this->size; // unsigned % size ... bad if u is negative
size_t n = (this->size + this->n - i + shift - 1) % this->size;
//std::cout << " t[" << i << "] * v[" << n << "]" << std::endl;
sum += this->data[n] * this->taps[i];
}
return sum;
}
void Filt::push(double val) {
Buf::push(val);
}
IirFilter::IirFilter(std::vector<double> b, std::vector<double> a) : x(b.size(), 0, 0, b), y(a.size(), 1, 1, a) {
if (b.size() != a.size()) throw std::invalid_argument("b.size() != a.size()");
}
double IirFilter::filter(double val) {
//std::cout << "x.filter(" << val << ")" << std::endl;
double xv = x.filter(val);
//std::cout << "xv=" << xv << std::endl;
//std::cout << "y.peek()" << std::endl;
double yv = y.peek();
//std::cout << "yv=" << yv << std::endl;
//std::cout << "---" << std::endl;
double yo = xv - yv;
y.push(yo);
return yo;
}

View File

@@ -0,0 +1,46 @@
//
// Created by david on 02.03.2026.
//
#ifndef PASADASUPERPROJECT_IIR_FILTER_H
#define PASADASUPERPROJECT_IIR_FILTER_H
#include <utility>
#include <vector>
#include <stdexcept>
/** Shift register implemented as a circular buffer. */
class Buf {
protected:
std::vector<double> data;
size_t size;
size_t n;
public:
Buf(size_t N);
void push(double val);
};
/** Running filter base. */
class Filt : Buf {
protected:
std::vector<double> taps;
size_t shift;
size_t offset;
public:
Filt(size_t N, size_t shift, size_t offset, std::vector<double> taps);
double filter(double val);
double peek();
void push(double val);
};
/** Running IIR filter. */
class IirFilter {
protected:
Filt y;
Filt x;
public:
IirFilter(std::vector<double> b, std::vector<double> a);
double filter(double val);
};
#endif //PASADASUPERPROJECT_IIR_FILTER_H