From 412a9e96a6acacf49ca7717d57259ce4868a85cb Mon Sep 17 00:00:00 2001 From: Gabriel Santos Date: Mon, 27 Jul 2026 06:11:23 +0000 Subject: [PATCH 1/2] add notch filter --- README.md | 2 +- ROADMAP.md | 1 - doc/filters/passive/NotchCombFilter.md | 120 ++++++++++++++ numerical/filters/passive/CMakeLists.txt | 2 + numerical/filters/passive/NotchCombFilter.cpp | 8 + numerical/filters/passive/NotchCombFilter.hpp | 128 +++++++++++++++ numerical/filters/passive/test/CMakeLists.txt | 1 + .../passive/test/TestNotchCombFilter.cpp | 148 ++++++++++++++++++ .../passive/NotchCombFilter/explanation.md | 31 ---- .../passive/NotchCombFilter/implementation.md | 83 ---------- .../filters/passive/NotchCombFilter/tests.md | 50 ------ 11 files changed, 408 insertions(+), 166 deletions(-) create mode 100644 doc/filters/passive/NotchCombFilter.md create mode 100644 numerical/filters/passive/NotchCombFilter.cpp create mode 100644 numerical/filters/passive/NotchCombFilter.hpp create mode 100644 numerical/filters/passive/test/TestNotchCombFilter.cpp delete mode 100644 roadmap/filters/passive/NotchCombFilter/explanation.md delete mode 100644 roadmap/filters/passive/NotchCombFilter/implementation.md delete mode 100644 roadmap/filters/passive/NotchCombFilter/tests.md diff --git a/README.md b/README.md index 4bb2ea2f..f661b1b6 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ Refer to the documentation to quickly integrate and utilize the library's signal | [Controllers](doc/controllers/README.md) | Bang-Bang/Hysteresis, PID, LQR, MPC, Saturation, Rate Limiter, Slew-Limited Saturation, Feedforward/2-DOF, Gain-Scheduled Controller | | [Dynamics](doc/dynamics/README.md) | Euler-Lagrange, Newton-Euler, Recursive Newton-Euler, ABA | | [Estimators](doc/estimators/README.md) | Linear Regression, Polynomial Fitting, Yule-Walker (offline), Recursive Least Squares (online) | -| [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) | +| [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 | | [Kinematics](doc/kinematics/README.md) | Forward Kinematics | | [Neural Network](doc/neural_network/README.md) | Layers, activations, losses, model | | [Optimization](doc/optimization/README.md) | Gradient Descent | diff --git a/ROADMAP.md b/ROADMAP.md index a5d7eeba..7660f63a 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -28,7 +28,6 @@ Difficulty legend: | # | Component | Target module | Difficulty | |----|------------------------------------------------------|---------------------------|------------| | 15 | Biquad / Second-Order-Section cascade | `filters/passive` | ★★★☆☆ | -| 16 | Notch / comb filter | `filters/passive` | ★★★☆☆ | | 17 | Lead-lag compensator | `controllers` | ★★★☆☆ | | 18 | Quaternion type | `math` | ★★★☆☆ | | 19 | Luenberger observer + pole placement (Ackermann) | `controllers` | ★★★☆☆ | diff --git a/doc/filters/passive/NotchCombFilter.md b/doc/filters/passive/NotchCombFilter.md new file mode 100644 index 00000000..b45b6b71 --- /dev/null +++ b/doc/filters/passive/NotchCombFilter.md @@ -0,0 +1,120 @@ +# Notch / Comb Filter + +## Overview & Motivation + +Narrow-band interference — mains hum at 50/60 Hz and its harmonics — contaminates bio-signal +acquisition (ECG, EEG, EMG) and precision instrumentation. A notch filter surgically eliminates +a single frequency while leaving the rest of the spectrum intact. A comb filter extends this idea +to an entire harmonic series using a single delay line, making it far more efficient than cascading +individual notches when the interference is periodic. + +## Mathematical Theory + +### Notch Filter (RBJ Biquad) + +The continuous-time transfer function for a band-reject filter with centre frequency $f_0$ and +quality factor $Q$ is: + +$$H(s) = \frac{s^2 + \omega_0^2}{s^2 + \frac{\omega_0}{Q}s + \omega_0^2}$$ + +Applying the bilinear transform with $\omega_0 = 2\pi f_0 / f_s$, the discrete-time biquad +coefficients (Bristow-Johnson "Cookbook" notch) are: + +$$\alpha = \frac{\sin(\omega_0)}{2Q}, \quad c_\omega = \cos(\omega_0)$$ + +$$b_0 = b_2 = \frac{1}{1+\alpha}, \quad b_1 = \frac{-2c_\omega}{1+\alpha}$$ + +$$a_1 = \frac{-2c_\omega}{1+\alpha}, \quad a_2 = \frac{1-\alpha}{1+\alpha}$$ + +The zeros lie exactly on the unit circle at $e^{\pm j\omega_0}$, guaranteeing infinite attenuation +at $f_0$ in exact arithmetic. + +Transposed Direct Form II (TDF-II) realises this with two state variables $z_1, z_2$: + +$$y[n] = b_0 x[n] + z_1[n-1]$$ +$$z_1[n] = b_1 x[n] - a_1 y[n] + z_2[n-1]$$ +$$z_2[n] = b_2 x[n] - a_2 y[n]$$ + +### Comb Filter + +A comb filter exploits the identity: subtracting (or adding) a signal delayed by $D$ samples +creates periodic nulls (or peaks) spaced every $f_s / D$ Hz: + +**Feedforward (FIR) comb:** + +$$y[n] = x[n] - g \cdot x[n-D]$$ + +Zeros at $\omega = 2\pi k / D$ for $k = 0, 1, \ldots, D-1$. The system is always stable. + +**Feedback (IIR) comb:** + +$$y[n] = x[n] + g \cdot y[n-D]$$ + +Poles at the same locations. The system is stable if and only if $|g| < 1$. + +## Complexity Analysis + +| Case | Time | Space | Notes | +|---------|---------|---------|----------------------------------| +| Notch | $O(1)$ | $O(1)$ | Fixed biquad; 2 multiplies/adds | +| Comb | $O(1)$ | $O(D)$ | Single circular-buffer read/write| + +## Step-by-Step Walkthrough + +**Notch example** — $f_0 = 50$ Hz, $f_s = 1000$ Hz, $Q = 10$: + +1. $\omega_0 = 2\pi \cdot 0.05 \approx 0.3142$ +2. $c_\omega = \cos(0.3142) \approx 0.9511$, $\alpha = \sin(0.3142)/(20) \approx 0.01564$ +3. $a_0 = 1.01564$; divide all coefficients by $a_0$ +4. $b_0 = b_2 \approx 0.9846$, $b_1 = a_1 \approx -1.8730$, $a_2 \approx 0.9693$ +5. At each sample: compute $y = b_0 x + z_1$, then update $z_1, z_2$. + +**Comb example** — $D = 4$, $g = 1$ (FIR): + +Impulse response: $[1, 0, 0, 0, -1, 0, 0, 0, 0, \ldots]$ — zeros at 0, fs/4, fs/2, 3fs/4. + +## Pitfalls & Edge Cases + +- **High Q instability**: a very narrow notch ($Q \gg 10$) places poles close to the unit circle. + Finite-precision arithmetic can shift them outside, causing instability. Use double precision or + second-order-section cascades when $Q > 30$. +- **Detuned comb**: if $f_s$ is not an exact integer multiple of the harmonic spacing, the comb + nulls misalign and leave residual hum. Prefer a sample rate that divides evenly, or cascade + individual biquad notches. +- **Feedback comb stability**: gain must satisfy $|g| < 1$ with margin. Values near 1 produce + extremely long ring-down and amplify quantisation noise. +- **DC gain**: the RBJ notch has unity gain at DC and Nyquist; FIR comb has gain $(1 - g)$ at DC. + +## Variants & Generalizations + +- **Notch with adjustable bandwidth**: replace the fixed $Q$ with an adaptive estimator tracking + the instantaneous interference frequency (e.g., a phase-locked loop). +- **All-pass + notch cascade**: derive a steep-skirt band-stop by cascading a notch with an + all-pass tuned to the same frequency. +- **Comb as reverberator**: adding (instead of subtracting) a delayed, attenuated copy produces + artificial reverberation (Schroeder comb). +- **Multi-rate comb**: operate the comb at a lower decimated rate, then interpolate — reduces + delay-line length proportionally. + +## Applications + +- Bio-signal acquisition: removing 50/60 Hz mains hum and harmonics from ECG/EEG/EMG. +- Power-line harmonic suppression in current/voltage sensors. +- Audio effects: chorus, flange, reverberation. +- Synchronous sampling: align comb nulls with switching-converter ripple harmonics. + +## Connections to Other Algorithms + +- **BiquadCascade** — the notch is a single biquad section; a cascade realizes higher-order + band-stop designs with better numerical conditioning. +- **IirFilterDesign** — a band-stop Butterworth/Chebyshev design from a bilinear transform + produces a family of notches; the RBJ notch here is the minimal single-section special case. +- **GoertzelAlgorithm** — detects the frequency that the notch removes; useful for adaptive + centre-frequency tuning. + +## References & Further Reading + +- R. Bristow-Johnson, "Cookbook formulae for audio EQ biquad filter coefficients", + https://www.w3.org/TR/audio-eq-cookbook/ +- R. G. Lyons, *Understanding Digital Signal Processing*, 3rd ed., Prentice Hall, 2011, Ch. 6. +- A. V. Oppenheim & R. W. Schafer, *Discrete-Time Signal Processing*, 3rd ed., Ch. 5. diff --git a/numerical/filters/passive/CMakeLists.txt b/numerical/filters/passive/CMakeLists.txt index f729ec58..fa3e37b6 100644 --- a/numerical/filters/passive/CMakeLists.txt +++ b/numerical/filters/passive/CMakeLists.txt @@ -17,6 +17,7 @@ target_sources(numerical.filters.passive PRIVATE Iir.hpp MedianFilter.hpp MovingAverage.hpp + NotchCombFilter.hpp ) numerical_add_coverage_sources(numerical.filters.passive @@ -26,6 +27,7 @@ numerical_add_coverage_sources(numerical.filters.passive Iir.cpp MedianFilter.cpp MovingAverage.cpp + NotchCombFilter.cpp ) add_subdirectory(test) diff --git a/numerical/filters/passive/NotchCombFilter.cpp b/numerical/filters/passive/NotchCombFilter.cpp new file mode 100644 index 00000000..c305daa8 --- /dev/null +++ b/numerical/filters/passive/NotchCombFilter.cpp @@ -0,0 +1,8 @@ +#include "numerical/filters/passive/NotchCombFilter.hpp" + +namespace filters::passive +{ + template class NotchFilter; + template class CombFilter; + template class CombFilter; +} diff --git a/numerical/filters/passive/NotchCombFilter.hpp b/numerical/filters/passive/NotchCombFilter.hpp new file mode 100644 index 00000000..9edb7f43 --- /dev/null +++ b/numerical/filters/passive/NotchCombFilter.hpp @@ -0,0 +1,128 @@ +#pragma once + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +#include "numerical/math/CompilerOptimizations.hpp" +#include +#include +#include +#include +#include + +namespace filters::passive +{ + template + class NotchFilter + { + static_assert(std::is_floating_point_v, "NotchFilter supports floating-point types"); + + public: + NotchFilter(T f0, T fs, T Q) noexcept; + + OPTIMIZE_FOR_SPEED T Filter(T x) noexcept; + void Reset() noexcept; + + private: + T b0{}; + T b1{}; + T b2{}; + T a1{}; + T a2{}; + T z1{}; + T z2{}; + }; + + template + class CombFilter + { + static_assert(std::is_floating_point_v, "CombFilter supports floating-point types"); + static_assert(D > 0, "CombFilter delay length must be greater than zero"); + + public: + explicit CombFilter(T gain) noexcept; + + OPTIMIZE_FOR_SPEED T Filter(T x) noexcept; + void Reset() noexcept; + + private: + T gain{}; + std::array delayLine{}; + std::size_t writeIndex{}; + }; + + //// NotchFilter Implementation //// + + template + NotchFilter::NotchFilter(T f0, T fs, T Q) noexcept + { + const T w0{ T{ 2 } * std::numbers::pi_v * f0 / fs }; + const T cw{ std::cos(w0) }; + const T alpha{ std::sin(w0) / (T{ 2 } * Q) }; + const T a0{ T{ 1 } + alpha }; + b0 = T{ 1 } / a0; + b1 = (T{ -2 } * cw) / a0; + b2 = T{ 1 } / a0; + a1 = (T{ -2 } * cw) / a0; + a2 = (T{ 1 } - alpha) / a0; + } + + template + OPTIMIZE_FOR_SPEED T NotchFilter::Filter(T x) noexcept + { + const T y{ b0 * x + z1 }; + z1 = b1 * x - a1 * y + z2; + z2 = b2 * x - a2 * y; + return y; + } + + template + void NotchFilter::Reset() noexcept + { + z1 = T{}; + z2 = T{}; + } + + //// CombFilter Implementation //// + + template + CombFilter::CombFilter(T gain) noexcept + : gain{ gain } + , writeIndex{ 0 } + { + delayLine.fill(T{}); + } + + template + OPTIMIZE_FOR_SPEED T CombFilter::Filter(T x) noexcept + { + const T d{ delayLine[writeIndex] }; + T y{}; + if constexpr (!Feedback) + { + y = x - gain * d; + delayLine[writeIndex] = x; + } + else + { + y = x + gain * d; + delayLine[writeIndex] = y; + } + writeIndex = (writeIndex + 1) % D; + return y; + } + + template + void CombFilter::Reset() noexcept + { + delayLine.fill(T{}); + writeIndex = 0; + } + +#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD + extern template class NotchFilter; + extern template class CombFilter; + extern template class CombFilter; +#endif +} diff --git a/numerical/filters/passive/test/CMakeLists.txt b/numerical/filters/passive/test/CMakeLists.txt index 0a30c5b7..504fcc67 100644 --- a/numerical/filters/passive/test/CMakeLists.txt +++ b/numerical/filters/passive/test/CMakeLists.txt @@ -16,4 +16,5 @@ target_sources(numerical.filters.passive_test PRIVATE TestIir.cpp TestMedianFilter.cpp TestMovingAverage.cpp + TestNotchCombFilter.cpp ) diff --git a/numerical/filters/passive/test/TestNotchCombFilter.cpp b/numerical/filters/passive/test/TestNotchCombFilter.cpp new file mode 100644 index 00000000..1c2d4e24 --- /dev/null +++ b/numerical/filters/passive/test/TestNotchCombFilter.cpp @@ -0,0 +1,148 @@ +// Copyright (c) 2025 Gabriel Santos. All rights reserved. +#include "numerical/filters/passive/NotchCombFilter.hpp" +#include "numerical/math/Tolerance.hpp" +#include "gtest/gtest.h" +#include +#include +#include + +namespace +{ + class TestNotchComb + : public ::testing::Test + { + public: + filters::passive::NotchFilter notch{ 50.0f, 1000.0f, 10.0f }; + filters::passive::CombFilter comb{ 0.9f }; + }; +} + +TEST_F(TestNotchComb, notch_rejects_target_frequency) +{ + constexpr int settleSamples{ 500 }; + constexpr int measureSamples{ 100 }; + constexpr float fs{ 1000.0f }; + constexpr float f0{ 50.0f }; + const float w0{ 2.0f * std::numbers::pi_v * f0 / fs }; + + for (int i = 0; i < settleSamples; ++i) + notch.Filter(std::sin(static_cast(i) * w0)); + + float maxAmp{ 0.0f }; + for (int i = settleSamples; i < settleSamples + measureSamples; ++i) + { + const float y{ notch.Filter(std::sin(static_cast(i) * w0)) }; + const float abs_y{ y < 0.0f ? -y : y }; + if (abs_y > maxAmp) + maxAmp = abs_y; + } + + EXPECT_NEAR(maxAmp, 0.0f, 0.05f); +} + +TEST_F(TestNotchComb, notch_passes_off_frequency) +{ + constexpr int settleSamples{ 200 }; + constexpr int measureSamples{ 100 }; + constexpr float fs{ 1000.0f }; + constexpr float f{ 200.0f }; + const float w{ 2.0f * std::numbers::pi_v * f / fs }; + + for (int i = 0; i < settleSamples; ++i) + notch.Filter(std::sin(static_cast(i) * w)); + + float maxAmp{ 0.0f }; + for (int i = settleSamples; i < settleSamples + measureSamples; ++i) + { + const float y{ notch.Filter(std::sin(static_cast(i) * w)) }; + const float abs_y{ y < 0.0f ? -y : y }; + if (abs_y > maxAmp) + maxAmp = abs_y; + } + + EXPECT_NEAR(maxAmp, 1.0f, 0.05f); +} + +TEST_F(TestNotchComb, notch_dc_gain_unity) +{ + constexpr float tol{ 1e-3f }; + constexpr float dc{ 0.7f }; + constexpr int samples{ 200 }; + + float last{ 0.0f }; + for (int i = 0; i < samples; ++i) + last = notch.Filter(dc); + + EXPECT_NEAR(last, dc, tol); +} + +TEST_F(TestNotchComb, comb_rejects_harmonics) +{ + constexpr int settleSamples{ 200 }; + constexpr int measureSamples{ 40 }; + constexpr float fs{ 1000.0f }; + constexpr float fundamental{ fs / 20.0f }; + const float w1{ 2.0f * std::numbers::pi_v * fundamental / fs }; + const float w2{ 2.0f * std::numbers::pi_v * 2.0f * fundamental / fs }; + const float w3{ 2.0f * std::numbers::pi_v * 3.0f * fundamental / fs }; + + for (int i = 0; i < settleSamples; ++i) + { + const float x{ std::sin(static_cast(i) * w1) + + std::sin(static_cast(i) * w2) + + std::sin(static_cast(i) * w3) }; + comb.Filter(x); + } + + float maxAmp{ 0.0f }; + for (int i = settleSamples; i < settleSamples + measureSamples; ++i) + { + const float x{ std::sin(static_cast(i) * w1) + + std::sin(static_cast(i) * w2) + + std::sin(static_cast(i) * w3) }; + const float y{ comb.Filter(x) }; + const float abs_y{ y < 0.0f ? -y : y }; + if (abs_y > maxAmp) + maxAmp = abs_y; + } + + EXPECT_LT(maxAmp, 0.5f); +} + +TEST_F(TestNotchComb, feedback_comb_is_stable) +{ + filters::passive::CombFilter fbComb{ 0.95f }; + + float previous{ fbComb.Filter(1.0f) }; + bool decaying{ true }; + float peakAfterInitial{ 0.0f }; + + for (int i = 1; i < 400; ++i) + { + const float y{ fbComb.Filter(0.0f) }; + const float abs_y{ y < 0.0f ? -y : y }; + if (abs_y > peakAfterInitial) + peakAfterInitial = abs_y; + (void)previous; + previous = y; + } + + EXPECT_LT(peakAfterInitial, 100.0f); +} + +TEST_F(TestNotchComb, reset_clears_state) +{ + constexpr float tol{ 1e-6f }; + + for (int i = 0; i < 50; ++i) + { + notch.Filter(1.0f); + comb.Filter(1.0f); + } + + notch.Reset(); + comb.Reset(); + + EXPECT_NEAR(notch.Filter(0.0f), 0.0f, tol); + EXPECT_NEAR(comb.Filter(0.0f), 0.0f, tol); +} diff --git a/roadmap/filters/passive/NotchCombFilter/explanation.md b/roadmap/filters/passive/NotchCombFilter/explanation.md deleted file mode 100644 index 0d150f35..00000000 --- a/roadmap/filters/passive/NotchCombFilter/explanation.md +++ /dev/null @@ -1,31 +0,0 @@ -# Notch / Comb Filter — Overview - -## What it is -Two related narrow-band rejecters: a **notch** removes a single frequency (a biquad with its zeros -on the unit circle), and a **comb** removes a fundamental *and all its harmonics* using a single -delayed feedforward/feedback path. - -## Why it matters (embedded) -The dominant interference in bio-signals (ECG/EEG/EMG) and precision instrumentation is `50/60 Hz` -mains hum and its harmonics. A notch surgically deletes the fundamental while leaving the rest of -the spectrum intact; a comb cleans up the whole harmonic series at once for the price of one delay -line. - -## How it works (intuition) -A notch places a pair of zeros exactly on the unit circle at the offending frequency and nearby -poles just inside to keep the rest of the response flat — `Q` controls how tight the notch is. A -comb delays the signal by `D` samples and subtracts (or adds) it; the delay creates evenly spaced -nulls at every multiple of `fs/D`, which lines up perfectly with a harmonic series. - -## Key parameters -- **f0, Q (notch)** — centre frequency and width; higher `Q` = narrower, sharper notch. -- **D, gain, feedback (comb)** — delay length sets null spacing (`fs/D`), gain sets depth, feedback - mode trades sharper nulls for a stability constraint (`gain < 1`). - -## Reference -R. Bristow-Johnson, "Cookbook formulae for audio EQ biquad filter coefficients" (notch); -R. G. Lyons, *Understanding Digital Signal Processing* (comb filters). - -## See also -`BiquadCascade` (general biquad realization), `IirFilterDesign` (band-stop design), -`GoertzelAlgorithm` (detect the tone a notch removes). diff --git a/roadmap/filters/passive/NotchCombFilter/implementation.md b/roadmap/filters/passive/NotchCombFilter/implementation.md deleted file mode 100644 index 0b2097c5..00000000 --- a/roadmap/filters/passive/NotchCombFilter/implementation.md +++ /dev/null @@ -1,83 +0,0 @@ -# Notch / Comb Filter — Implementation Pseudocode - -> Roadmap ref: #16 (Tier 3) · Target: `numerical/filters/passive` · Namespace `filters::passive` · Type: `float` (templated on `T`, instantiated for `float` only) - -## Data structures - -``` -template # static_assert(std::is_floating_point_v); instantiated for float -class NotchFilter: # single-frequency biquad notch - BiquadCoeffs c - T z1 = 0, z2 = 0 # TDF-II state - -template -class CombFilter: # periodic notches at k·fs/D - RecursiveBuffer delay # D-sample delay line - T gain # 0 ≤ gain < 1 - bool feedback = false # false = FIR comb, true = IIR comb -``` - -## Interface - -``` -NotchFilter(T f0, T fs, T Q) # RBJ notch coefficients -T Filter(T x) -CombFilter(T gain, bool feedback = false) -T Filter(T x) -void Reset() -``` - -## Algorithm (pseudocode) - -``` -# RBJ notch biquad coefficients (zeros ON the unit circle at ±w0): -w0 = 2*pi*f0/fs ; cw = cos(w0) ; alpha = sin(w0)/(2*Q) -b0=1 ; b1=-2*cw ; b2=1 ; a0=1+alpha ; a1=-2*cw ; a2=1-alpha -divide b0,b1,b2,a1,a2 by a0 - -function Notch.Filter(x): # OPTIMIZE_FOR_SPEED (TDF-II) - y = b0*x + z1 - z1 = b1*x - a1*y + z2 - z2 = b2*x - a2*y - return y - -function Comb.Filter(x): # OPTIMIZE_FOR_SPEED - d = delay.Oldest() # sample D steps ago - if not feedback: # feedforward (FIR) comb - y = x - gain * d ; delay.Push(x) - else: # feedback (IIR) comb - y = x + gain * d ; delay.Push(y) - return y -``` - -## Complexity & memory - -- Notch: `O(1)` per sample (one biquad); memory `O(1)`. -- Comb: `O(1)` per sample; memory `O(D)` for the delay line. - -## Numerical / embedded notes - -- Notch width is set by `Q`: higher `Q` ⇒ narrower notch, but poles sit closer to the unit circle - ⇒ more coefficient sensitivity and a longer ring-down. -- Feedback comb with `gain → 1` places poles near the unit circle → conditionally stable; keep - `gain < 1` with margin to avoid limit cycles / sustained oscillation. -- `D = round(fs / f0)`; if `fs` is not an integer multiple of the line frequency the comb is - detuned and leaves residual hum — prefer a sample rate that divides evenly, or cascade single - notches. -- Cascade a `50/60 Hz` notch with a comb to also kill the harmonics; notch DC gain is 1. -- Float-only: `static_assert(std::is_floating_point_v)`; the generic `T` signature keeps a - `Q15`/`Q31` specialisation cheap to add later. - -## Deployment - -- Header: `numerical/filters/passive/NotchCombFilter.hpp` — `#pragma once` → - `#pragma GCC optimize("O3","fast-math")`, `OPTIMIZE_FOR_SPEED` on `Filter`, and - `extern template class NotchFilter;` / `extern template class CombFilter;` - under `#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD`. -- Coverage: `numerical/filters/passive/NotchCombFilter.cpp` → - `template class NotchFilter; template class CombFilter;` -- Test: `numerical/filters/passive/test/TestNotchCombFilter.cpp` -- Doc: `doc/filters/passive/NotchCombFilter.md` (expand to follow `doc/TEMPLATE.md`) -- CMake: `.hpp` → `target_sources`; `.cpp` → `numerical_add_coverage_sources`; - `TestNotchCombFilter.cpp` → the `_test` target. -- Generic pattern: see `roadmap/DEPLOYMENT.md`. diff --git a/roadmap/filters/passive/NotchCombFilter/tests.md b/roadmap/filters/passive/NotchCombFilter/tests.md deleted file mode 100644 index de155231..00000000 --- a/roadmap/filters/passive/NotchCombFilter/tests.md +++ /dev/null @@ -1,50 +0,0 @@ -# Notch / Comb Filter — Unit Test Plan (Pseudocode) - -> GoogleTest · `TEST_F` (`float`) · `StrictMock` only · no heap. - -## Fixture - -``` -class TestNotchComb : public ::testing::Test: - NotchFilter notch{ 50.0f, 1000.0f, 10.0f } # 50 Hz, fs=1 kHz, Q=10 - CombFilter comb{ 0.9f } # D=20 (fs/f0 = 1000/50) -# each case below is a TEST_F(TestNotchComb, ) -``` - -## Test cases (Arrange / Act / Assert) - -``` -notch_rejects_target_frequency: - Arrange: feed a 50 Hz sine (fs = 1 kHz) - Assert: steady-state output amplitude ≈ 0 - -notch_passes_off_frequency: - Arrange: feed a 200 Hz sine - Assert: output amplitude ≈ input amplitude (≈ 0 dB) - -notch_dc_gain_unity: - Arrange: constant input - Assert: output ≈ input (DC untouched) - -comb_rejects_harmonics: - Arrange: feedforward comb D=20, feed fundamental + 2nd/3rd harmonic of fs/D - Assert: all harmonics of fs/D attenuated - -feedback_comb_is_stable: - Arrange: gain = 0.95, feed impulse - Assert: output decays (bounded), no growth - -reset_clears_state: - Arrange: run samples, Reset() - Assert: biquad state and delay line all zero -``` - -## Reference vectors - -- Notch `f0/fs = 0.05, Q = 10` ⇒ magnitude at `0.05·fs` ≈ `0`, at DC and Nyquist ≈ `1`. -- FIR comb `gain = 1, D = 4` ⇒ zeros at `k·fs/4`; impulse response `[1,0,0,0,−1]`. - -## Edge cases - -- Feedback `gain` approaching 1 — assert bounded output (stability margin). -- `D` not integer-dividing `fs/f0` — documents residual-hum detuning. From e854029aff6ae7a94eb00334e0decb637256f617 Mon Sep 17 00:00:00 2001 From: gfs Date: Mon, 27 Jul 2026 17:55:21 +0200 Subject: [PATCH 2/2] Apply suggestions from code review Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- doc/filters/passive/NotchCombFilter.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/doc/filters/passive/NotchCombFilter.md b/doc/filters/passive/NotchCombFilter.md index b45b6b71..2ea0ffa1 100644 --- a/doc/filters/passive/NotchCombFilter.md +++ b/doc/filters/passive/NotchCombFilter.md @@ -54,10 +54,10 @@ Poles at the same locations. The system is stable if and only if $|g| < 1$. ## Complexity Analysis -| Case | Time | Space | Notes | -|---------|---------|---------|----------------------------------| -| Notch | $O(1)$ | $O(1)$ | Fixed biquad; 2 multiplies/adds | -| Comb | $O(1)$ | $O(D)$ | Single circular-buffer read/write| +| Case | Time | Space | Notes | +|-------|--------|--------|-----------------------------------| +| Notch | $O(1)$ | $O(1)$ | Fixed biquad; 2 multiplies/adds | +| Comb | $O(1)$ | $O(D)$ | Single circular-buffer read/write | ## Step-by-Step Walkthrough @@ -115,6 +115,6 @@ Impulse response: $[1, 0, 0, 0, -1, 0, 0, 0, 0, \ldots]$ — zeros at 0, fs/4, f ## References & Further Reading - R. Bristow-Johnson, "Cookbook formulae for audio EQ biquad filter coefficients", - https://www.w3.org/TR/audio-eq-cookbook/ + - R. G. Lyons, *Understanding Digital Signal Processing*, 3rd ed., Prentice Hall, 2011, Ch. 6. - A. V. Oppenheim & R. W. Schafer, *Discrete-Time Signal Processing*, 3rd ed., Ch. 5.