Skip to content

Commit cbda3ab

Browse files
feat: add notch filter (#179)
* add notch filter * Apply suggestions from code review Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --------- Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
1 parent f5c0569 commit cbda3ab

11 files changed

Lines changed: 408 additions & 166 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ Refer to the documentation to quickly integrate and utilize the library's signal
2121
| [Controllers](doc/controllers/README.md) | Bang-Bang/Hysteresis, PID, LQR, MPC, Saturation, Rate Limiter, Slew-Limited Saturation, Feedforward/2-DOF, Gain-Scheduled Controller |
2222
| [Dynamics](doc/dynamics/README.md) | Euler-Lagrange, Newton-Euler, Recursive Newton-Euler, ABA |
2323
| [Estimators](doc/estimators/README.md) | Linear Regression, Polynomial Fitting, Yule-Walker (offline), Recursive Least Squares (online) |
24-
| [Filters](doc/filters/README.md) | Kalman, Extended Kalman, Unscented Kalman, Alpha-Beta/Alpha-Beta-Gamma, FIR, IIR, Exponential Moving Average, Moving Average, Complementary, Median Filter, CIC (Cascaded Integrator-Comb) |
24+
| [Filters](doc/filters/README.md) | Kalman, Extended Kalman, Unscented Kalman, Alpha-Beta/Alpha-Beta-Gamma, FIR, IIR, Exponential Moving Average, Moving Average, Complementary, Median Filter, CIC (Cascaded Integrator-Comb), Notch/Comb Filter |
2525
| [Kinematics](doc/kinematics/README.md) | Forward Kinematics |
2626
| [Neural Network](doc/neural_network/README.md) | Layers, activations, losses, model |
2727
| [Optimization](doc/optimization/README.md) | Gradient Descent |

‎ROADMAP.md‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@ Difficulty legend:
2828
| # | Component | Target module | Difficulty |
2929
|----|------------------------------------------------------|---------------------------|------------|
3030
| 15 | Biquad / Second-Order-Section cascade | `filters/passive` | ★★★☆☆ |
31-
| 16 | Notch / comb filter | `filters/passive` | ★★★☆☆ |
3231
| 17 | Lead-lag compensator | `controllers` | ★★★☆☆ |
3332
| 19 | Luenberger observer + pole placement (Ackermann) | `controllers` | ★★★☆☆ |
3433
| 20 | Integral / servo state feedback (LQI) | `controllers` | ★★★☆☆ |
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
# Notch / Comb Filter
2+
3+
## Overview & Motivation
4+
5+
Narrow-band interference — mains hum at 50/60 Hz and its harmonics — contaminates bio-signal
6+
acquisition (ECG, EEG, EMG) and precision instrumentation. A notch filter surgically eliminates
7+
a single frequency while leaving the rest of the spectrum intact. A comb filter extends this idea
8+
to an entire harmonic series using a single delay line, making it far more efficient than cascading
9+
individual notches when the interference is periodic.
10+
11+
## Mathematical Theory
12+
13+
### Notch Filter (RBJ Biquad)
14+
15+
The continuous-time transfer function for a band-reject filter with centre frequency $f_0$ and
16+
quality factor $Q$ is:
17+
18+
$$H(s) = \frac{s^2 + \omega_0^2}{s^2 + \frac{\omega_0}{Q}s + \omega_0^2}$$
19+
20+
Applying the bilinear transform with $\omega_0 = 2\pi f_0 / f_s$, the discrete-time biquad
21+
coefficients (Bristow-Johnson "Cookbook" notch) are:
22+
23+
$$\alpha = \frac{\sin(\omega_0)}{2Q}, \quad c_\omega = \cos(\omega_0)$$
24+
25+
$$b_0 = b_2 = \frac{1}{1+\alpha}, \quad b_1 = \frac{-2c_\omega}{1+\alpha}$$
26+
27+
$$a_1 = \frac{-2c_\omega}{1+\alpha}, \quad a_2 = \frac{1-\alpha}{1+\alpha}$$
28+
29+
The zeros lie exactly on the unit circle at $e^{\pm j\omega_0}$, guaranteeing infinite attenuation
30+
at $f_0$ in exact arithmetic.
31+
32+
Transposed Direct Form II (TDF-II) realises this with two state variables $z_1, z_2$:
33+
34+
$$y[n] = b_0 x[n] + z_1[n-1]$$
35+
$$z_1[n] = b_1 x[n] - a_1 y[n] + z_2[n-1]$$
36+
$$z_2[n] = b_2 x[n] - a_2 y[n]$$
37+
38+
### Comb Filter
39+
40+
A comb filter exploits the identity: subtracting (or adding) a signal delayed by $D$ samples
41+
creates periodic nulls (or peaks) spaced every $f_s / D$ Hz:
42+
43+
**Feedforward (FIR) comb:**
44+
45+
$$y[n] = x[n] - g \cdot x[n-D]$$
46+
47+
Zeros at $\omega = 2\pi k / D$ for $k = 0, 1, \ldots, D-1$. The system is always stable.
48+
49+
**Feedback (IIR) comb:**
50+
51+
$$y[n] = x[n] + g \cdot y[n-D]$$
52+
53+
Poles at the same locations. The system is stable if and only if $|g| < 1$.
54+
55+
## Complexity Analysis
56+
57+
| Case | Time | Space | Notes |
58+
|-------|--------|--------|-----------------------------------|
59+
| Notch | $O(1)$ | $O(1)$ | Fixed biquad; 2 multiplies/adds |
60+
| Comb | $O(1)$ | $O(D)$ | Single circular-buffer read/write |
61+
62+
## Step-by-Step Walkthrough
63+
64+
**Notch example** — $f_0 = 50$ Hz, $f_s = 1000$ Hz, $Q = 10$:
65+
66+
1. $\omega_0 = 2\pi \cdot 0.05 \approx 0.3142$
67+
2. $c_\omega = \cos(0.3142) \approx 0.9511$, $\alpha = \sin(0.3142)/(20) \approx 0.01564$
68+
3. $a_0 = 1.01564$; divide all coefficients by $a_0$
69+
4. $b_0 = b_2 \approx 0.9846$, $b_1 = a_1 \approx -1.8730$, $a_2 \approx 0.9693$
70+
5. At each sample: compute $y = b_0 x + z_1$, then update $z_1, z_2$.
71+
72+
**Comb example** — $D = 4$, $g = 1$ (FIR):
73+
74+
Impulse response: $[1, 0, 0, 0, -1, 0, 0, 0, 0, \ldots]$ — zeros at 0, fs/4, fs/2, 3fs/4.
75+
76+
## Pitfalls & Edge Cases
77+
78+
- **High Q instability**: a very narrow notch ($Q \gg 10$) places poles close to the unit circle.
79+
Finite-precision arithmetic can shift them outside, causing instability. Use double precision or
80+
second-order-section cascades when $Q > 30$.
81+
- **Detuned comb**: if $f_s$ is not an exact integer multiple of the harmonic spacing, the comb
82+
nulls misalign and leave residual hum. Prefer a sample rate that divides evenly, or cascade
83+
individual biquad notches.
84+
- **Feedback comb stability**: gain must satisfy $|g| < 1$ with margin. Values near 1 produce
85+
extremely long ring-down and amplify quantisation noise.
86+
- **DC gain**: the RBJ notch has unity gain at DC and Nyquist; FIR comb has gain $(1 - g)$ at DC.
87+
88+
## Variants & Generalizations
89+
90+
- **Notch with adjustable bandwidth**: replace the fixed $Q$ with an adaptive estimator tracking
91+
the instantaneous interference frequency (e.g., a phase-locked loop).
92+
- **All-pass + notch cascade**: derive a steep-skirt band-stop by cascading a notch with an
93+
all-pass tuned to the same frequency.
94+
- **Comb as reverberator**: adding (instead of subtracting) a delayed, attenuated copy produces
95+
artificial reverberation (Schroeder comb).
96+
- **Multi-rate comb**: operate the comb at a lower decimated rate, then interpolate — reduces
97+
delay-line length proportionally.
98+
99+
## Applications
100+
101+
- Bio-signal acquisition: removing 50/60 Hz mains hum and harmonics from ECG/EEG/EMG.
102+
- Power-line harmonic suppression in current/voltage sensors.
103+
- Audio effects: chorus, flange, reverberation.
104+
- Synchronous sampling: align comb nulls with switching-converter ripple harmonics.
105+
106+
## Connections to Other Algorithms
107+
108+
- **BiquadCascade** — the notch is a single biquad section; a cascade realizes higher-order
109+
band-stop designs with better numerical conditioning.
110+
- **IirFilterDesign** — a band-stop Butterworth/Chebyshev design from a bilinear transform
111+
produces a family of notches; the RBJ notch here is the minimal single-section special case.
112+
- **GoertzelAlgorithm** — detects the frequency that the notch removes; useful for adaptive
113+
centre-frequency tuning.
114+
115+
## References & Further Reading
116+
117+
- R. Bristow-Johnson, "Cookbook formulae for audio EQ biquad filter coefficients",
118+
<https://www.w3.org/TR/audio-eq-cookbook/>
119+
- R. G. Lyons, *Understanding Digital Signal Processing*, 3rd ed., Prentice Hall, 2011, Ch. 6.
120+
- A. V. Oppenheim & R. W. Schafer, *Discrete-Time Signal Processing*, 3rd ed., Ch. 5.

‎numerical/filters/passive/CMakeLists.txt‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ target_sources(numerical.filters.passive PRIVATE
1717
Iir.hpp
1818
MedianFilter.hpp
1919
MovingAverage.hpp
20+
NotchCombFilter.hpp
2021
)
2122

2223
numerical_add_coverage_sources(numerical.filters.passive
@@ -26,6 +27,7 @@ numerical_add_coverage_sources(numerical.filters.passive
2627
Iir.cpp
2728
MedianFilter.cpp
2829
MovingAverage.cpp
30+
NotchCombFilter.cpp
2931
)
3032

3133
add_subdirectory(test)
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
#include "numerical/filters/passive/NotchCombFilter.hpp"
2+
3+
namespace filters::passive
4+
{
5+
template class NotchFilter<float>;
6+
template class CombFilter<float, 20, false>;
7+
template class CombFilter<float, 20, true>;
8+
}
Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
#pragma once
2+
3+
#if defined(__GNUC__) || defined(__clang__)
4+
#pragma GCC optimize("O3", "fast-math")
5+
#endif
6+
7+
#include "numerical/math/CompilerOptimizations.hpp"
8+
#include <array>
9+
#include <cmath>
10+
#include <cstddef>
11+
#include <numbers>
12+
#include <type_traits>
13+
14+
namespace filters::passive
15+
{
16+
template<typename T>
17+
class NotchFilter
18+
{
19+
static_assert(std::is_floating_point_v<T>, "NotchFilter supports floating-point types");
20+
21+
public:
22+
NotchFilter(T f0, T fs, T Q) noexcept;
23+
24+
OPTIMIZE_FOR_SPEED T Filter(T x) noexcept;
25+
void Reset() noexcept;
26+
27+
private:
28+
T b0{};
29+
T b1{};
30+
T b2{};
31+
T a1{};
32+
T a2{};
33+
T z1{};
34+
T z2{};
35+
};
36+
37+
template<typename T, std::size_t D, bool Feedback = false>
38+
class CombFilter
39+
{
40+
static_assert(std::is_floating_point_v<T>, "CombFilter supports floating-point types");
41+
static_assert(D > 0, "CombFilter delay length must be greater than zero");
42+
43+
public:
44+
explicit CombFilter(T gain) noexcept;
45+
46+
OPTIMIZE_FOR_SPEED T Filter(T x) noexcept;
47+
void Reset() noexcept;
48+
49+
private:
50+
T gain{};
51+
std::array<T, D> delayLine{};
52+
std::size_t writeIndex{};
53+
};
54+
55+
//// NotchFilter Implementation ////
56+
57+
template<typename T>
58+
NotchFilter<T>::NotchFilter(T f0, T fs, T Q) noexcept
59+
{
60+
const T w0{ T{ 2 } * std::numbers::pi_v<T> * f0 / fs };
61+
const T cw{ std::cos(w0) };
62+
const T alpha{ std::sin(w0) / (T{ 2 } * Q) };
63+
const T a0{ T{ 1 } + alpha };
64+
b0 = T{ 1 } / a0;
65+
b1 = (T{ -2 } * cw) / a0;
66+
b2 = T{ 1 } / a0;
67+
a1 = (T{ -2 } * cw) / a0;
68+
a2 = (T{ 1 } - alpha) / a0;
69+
}
70+
71+
template<typename T>
72+
OPTIMIZE_FOR_SPEED T NotchFilter<T>::Filter(T x) noexcept
73+
{
74+
const T y{ b0 * x + z1 };
75+
z1 = b1 * x - a1 * y + z2;
76+
z2 = b2 * x - a2 * y;
77+
return y;
78+
}
79+
80+
template<typename T>
81+
void NotchFilter<T>::Reset() noexcept
82+
{
83+
z1 = T{};
84+
z2 = T{};
85+
}
86+
87+
//// CombFilter Implementation ////
88+
89+
template<typename T, std::size_t D, bool Feedback>
90+
CombFilter<T, D, Feedback>::CombFilter(T gain) noexcept
91+
: gain{ gain }
92+
, writeIndex{ 0 }
93+
{
94+
delayLine.fill(T{});
95+
}
96+
97+
template<typename T, std::size_t D, bool Feedback>
98+
OPTIMIZE_FOR_SPEED T CombFilter<T, D, Feedback>::Filter(T x) noexcept
99+
{
100+
const T d{ delayLine[writeIndex] };
101+
T y{};
102+
if constexpr (!Feedback)
103+
{
104+
y = x - gain * d;
105+
delayLine[writeIndex] = x;
106+
}
107+
else
108+
{
109+
y = x + gain * d;
110+
delayLine[writeIndex] = y;
111+
}
112+
writeIndex = (writeIndex + 1) % D;
113+
return y;
114+
}
115+
116+
template<typename T, std::size_t D, bool Feedback>
117+
void CombFilter<T, D, Feedback>::Reset() noexcept
118+
{
119+
delayLine.fill(T{});
120+
writeIndex = 0;
121+
}
122+
123+
#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD
124+
extern template class NotchFilter<float>;
125+
extern template class CombFilter<float, 20, false>;
126+
extern template class CombFilter<float, 20, true>;
127+
#endif
128+
}

‎numerical/filters/passive/test/CMakeLists.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,4 +16,5 @@ target_sources(numerical.filters.passive_test PRIVATE
1616
TestIir.cpp
1717
TestMedianFilter.cpp
1818
TestMovingAverage.cpp
19+
TestNotchCombFilter.cpp
1920
)

0 commit comments

Comments
 (0)