diff --git a/README.md b/README.md index a0aba6ca..16082acc 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 | +| [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) | | [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 cd8631a1..6b487f58 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -28,7 +28,6 @@ Difficulty legend: | # | Component | Target module | Difficulty | |----|------------------------------------------------------|---------------------------|------------| | 13 | Goertzel algorithm | `analysis` | ★★☆☆☆ | -| 14 | CIC (Cascaded Integrator-Comb) filter | `filters/passive` | ★★☆☆☆ | | 15 | Biquad / Second-Order-Section cascade | `filters/passive` | ★★★☆☆ | | 16 | Notch / comb filter | `filters/passive` | ★★★☆☆ | | 17 | Lead-lag compensator | `controllers` | ★★★☆☆ | diff --git a/doc/filters/passive/CicFilter.md b/doc/filters/passive/CicFilter.md new file mode 100644 index 00000000..2805351d --- /dev/null +++ b/doc/filters/passive/CicFilter.md @@ -0,0 +1,120 @@ +# CIC (Cascaded Integrator-Comb) Filter + +## Overview & Motivation + +Decimation and interpolation in digital signal processing typically require a lowpass anti-aliasing filter before the rate change. Standard FIR filters require multiplications proportional to their order. The CIC filter achieves a highly efficient lowpass response using only additions and subtractions, making it ideal for resource-constrained embedded systems where multipliers are expensive or unavailable. + +CIC filters are used in sigma-delta ADC interfaces, software-defined radio front-ends, and any application that must drastically reduce the sample rate of a high-frequency signal stream before further processing. + +## Mathematical Theory + +### Core Definitions + +A CIC decimator of order $N$ with decimation ratio $R$ and differential delay $M$ is defined by its $z$-domain transfer function: + +$$H(z) = \left( \frac{1 - z^{-RM}}{1 - z^{-1}} \right)^N$$ + +The numerator factor $1 - z^{-RM}$ is the $z$-transform of the comb (differencing) stage. The denominator $\frac{1}{1 - z^{-1}}$ is the accumulator (integrator) stage. + +### Structure + +The filter consists of two cascaded sections: + +**Integrator section** (running at the high input rate $f_s$): $N$ stages of first-order IIR accumulators, + +$$y_k[n] = y_k[n-1] + y_{k-1}[n], \quad k = 1, \ldots, N$$ + +**Comb section** (running at the low output rate $f_s / R$): $N$ stages of differencing with delay $M$, + +$$y_k[m] = y_{k-1}[m] - y_{k-1}[m - M], \quad k = 1, \ldots, N$$ + +### DC Gain + +The unnormalized DC gain of the filter is: + +$$G = (R \cdot M)^N$$ + +All outputs are divided by $G$ to normalize the DC gain to unity for a constant input. + +### Frequency Response + +The magnitude response in the baseband is approximately: + +$$|H(f)| = \left| \frac{\sin(\pi f M R / f_s)}{R \sin(\pi f / f_s)} \right|^N$$ + +This is a sinc-like response that suppresses high-frequency content before the rate change. + +## Complexity Analysis + +| Case | Time per input sample | Space | Notes | +|---------|-----------------------|----------------|----------------------------------------------------| +| Best | $O(N)$ | $O(N \cdot M)$ | $N$ integrator ops; comb only at decimation points | +| Average | $O(N)$ | $O(N \cdot M)$ | Same | +| Worst | $O(N)$ | $O(N \cdot M)$ | Comb adds $N$ differencing ops at rate $f_s/R$ | + +The integrator section executes $N$ additions per input sample. The comb section executes $N$ subtractions once every $R$ input samples. There are no multiplications in the signal path. + +## Step-by-Step Walkthrough + +Consider $N=2$, $R=4$, $M=1$, input impulse $x[0]=1$, $x[n]=0$ for $n>0$. + +**Integrator section at $n=0,1,2,3$:** + +| $n$ | Input | Integrator 1 | Integrator 2 | +|-----|-------|--------------|--------------| +| 0 | 1 | 1 | 1 | +| 1 | 0 | 1 | 2 | +| 2 | 0 | 1 | 3 | +| 3 | 0 | 1 | 4 | + +**Comb section at decimated sample $m=0$ (triggered at $n=3$):** + +- Comb 1 input: 4; delay buffer held 0; output: $4 - 0 = 4$; buffer updated to 4 +- Comb 2 input: 4; delay buffer held 0; output: $4 - 0 = 4$; buffer updated to 4 +- Normalized output: $4 / 16 = 0.25$ + +**At $m=1$ (triggered at $n=7$):** + +- Integrator 2 output: 8 (accumulated four more 1s from integrator 1) +- Comb 1: $8 - 4 = 4$; Comb 2: $4 - 4 = 0$; Normalized output: $0.0$ + +## Pitfalls & Edge Cases + +**Integer overflow in fixed-point implementations**: in fixed-point arithmetic, the integrators accumulate without bound between comb operations. Registers must be wide enough to hold $(R \cdot M)^N$ times the maximum input value. This implementation uses floating-point, which avoids this issue. + +**Initial transient**: the filter takes several R-length blocks to settle to steady-state behavior for a constant input. DC normalization is exact only after the delay pipeline is fully flushed. + +**Passband droop**: the sinc-shaped response causes attenuation even near DC as the input frequency increases. Compensation filters or a larger $R$ reduce in-band droop. + +**Aliasing from high-order terms**: if the input signal has energy above $f_s / (2R)$, aliased components will appear at the output. A simple prefilter can reduce this. + +## Variants & Generalizations + +**Interpolating CIC**: the comb section runs at the low rate and the integrators at the high rate, acting as an upsampler. The architecture mirrors the decimator with sections swapped. + +**Pruned CIC**: removes multiplier-free adder stages that contribute negligibly to the response, reducing hardware at the cost of response shape. + +**Compensation filter**: a short linear-phase FIR appended at the low rate corrects passband droop without reintroducing multipliers in the high-rate path. + +**Variable-rate CIC**: by making $R$ a runtime parameter, one filter structure supports multiple decimation ratios, useful in SDR front-ends. + +## Applications + +- Sigma-delta ADC decimation: the high oversampling rate (e.g., 256x) is reduced to Nyquist rate by a CIC stage before a compensation FIR. +- Software-defined radio: narrowband channels are extracted from a wideband stream by decimating with a CIC before channelization. +- Audio sample-rate conversion: high-to-low rate conversion with anti-aliasing, followed by a polyphase FIR for droop correction. +- Sensor interfaces: smoothing and downsampling of high-rate MEMS sensor data with minimal compute budget. + +## Connections to Other Algorithms + +A CIC filter of order $N=1$, $M=1$ is equivalent to a boxcar (rectangular window) FIR of length $R$, identical to a Moving Average filter operating on non-overlapping blocks. The Moving Average filter in this library is the continuous-output counterpart. + +Higher-order CICs approximate a Gaussian response as $N \to \infty$, connecting them to the Gaussian filter family in theory. + +The CIC is a special case of the more general Hogenauer filter structure, which can be pruned to reduce word widths at each stage. + +## References & Further Reading + +- E. B. Hogenauer, "An economical class of digital filters for decimation and interpolation," IEEE Transactions on Acoustics, Speech, and Signal Processing, vol. 29, no. 2, pp. 155-162, April 1981. +- R. E. Crochiere and L. R. Rabiner, "Multirate Digital Signal Processing," Prentice-Hall, 1983. Chapter 3. +- F. J. Harris, "Multirate Signal Processing for Communication Systems," Prentice-Hall, 2004. diff --git a/numerical/filters/passive/CMakeLists.txt b/numerical/filters/passive/CMakeLists.txt index 7f2e3233..f729ec58 100644 --- a/numerical/filters/passive/CMakeLists.txt +++ b/numerical/filters/passive/CMakeLists.txt @@ -11,6 +11,7 @@ target_link_libraries(numerical.filters.passive ${NUMERICAL_VISIBILITY} ) target_sources(numerical.filters.passive PRIVATE + CicFilter.hpp ExponentialMovingAverage.hpp Fir.hpp Iir.hpp @@ -19,6 +20,7 @@ target_sources(numerical.filters.passive PRIVATE ) numerical_add_coverage_sources(numerical.filters.passive + CicFilter.cpp ExponentialMovingAverage.cpp Fir.cpp Iir.cpp diff --git a/numerical/filters/passive/CicFilter.cpp b/numerical/filters/passive/CicFilter.cpp new file mode 100644 index 00000000..08d3bf9c --- /dev/null +++ b/numerical/filters/passive/CicFilter.cpp @@ -0,0 +1,6 @@ +#include "numerical/filters/passive/CicFilter.hpp" + +namespace filters::passive +{ + template class CicDecimator; +} diff --git a/numerical/filters/passive/CicFilter.hpp b/numerical/filters/passive/CicFilter.hpp new file mode 100644 index 00000000..9ebcf7b6 --- /dev/null +++ b/numerical/filters/passive/CicFilter.hpp @@ -0,0 +1,122 @@ +#pragma once + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +#include "numerical/math/CompilerOptimizations.hpp" +#include +#include +#include + +namespace filters::passive +{ + template + struct CicSample + { + T value{}; + bool valid{ false }; + }; + + template + class Comb + { + static_assert(std::is_floating_point_v, "Comb supports floating-point types"); + + public: + OPTIMIZE_FOR_SPEED T PushPop(T input) noexcept; + void Reset() noexcept; + + private: + std::array delay{}; + std::size_t head{ 0 }; + }; + + template + class CicDecimator + { + static_assert(std::is_floating_point_v, "CicDecimator supports floating-point types"); + static_assert(Stages > 0, "Stages must be > 0"); + static_assert(R > 0, "R must be > 0"); + static_assert(M > 0, "M must be > 0"); + + public: + CicDecimator() noexcept = default; + + OPTIMIZE_FOR_SPEED CicSample Filter(T input) noexcept; + void Reset() noexcept; + static constexpr T Gain() noexcept; + + private: + std::array integrator{}; + std::array, Stages> comb{}; + std::size_t phase{ 0 }; + }; + + // --- Comb implementation --- + + template + OPTIMIZE_FOR_SPEED T Comb::PushPop(T input) noexcept + { + T oldest = delay[head]; + delay[head] = input; + head = (head + 1) % M; + return oldest; + } + + template + void Comb::Reset() noexcept + { + delay.fill(T{}); + head = 0; + } + + // --- CicDecimator implementation --- + + template + OPTIMIZE_FOR_SPEED CicSample CicDecimator::Filter(T input) noexcept + { + T acc{ input }; + for (std::size_t i = 0; i < Stages; ++i) + { + integrator[i] += acc; + acc = integrator[i]; + } + + ++phase; + if (phase < R) + return CicSample{}; + phase = 0; + + for (std::size_t i = 0; i < Stages; ++i) + { + T delayed = comb[i].PushPop(acc); + acc = acc - delayed; + } + + return CicSample{ acc / Gain(), true }; + } + + template + void CicDecimator::Reset() noexcept + { + integrator.fill(T{}); + for (std::size_t i = 0; i < Stages; ++i) + comb[i].Reset(); + phase = 0; + } + + template + constexpr T CicDecimator::Gain() noexcept + { + T g{ static_cast(R * M) }; + T result{ T{ 1 } }; + for (std::size_t i = 0; i < Stages; ++i) + result *= g; + return result; + } + +#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD + extern template class CicDecimator; +#endif +} diff --git a/numerical/filters/passive/test/CMakeLists.txt b/numerical/filters/passive/test/CMakeLists.txt index 9253deb2..0a30c5b7 100644 --- a/numerical/filters/passive/test/CMakeLists.txt +++ b/numerical/filters/passive/test/CMakeLists.txt @@ -10,6 +10,7 @@ target_link_libraries(numerical.filters.passive_test PUBLIC ) target_sources(numerical.filters.passive_test PRIVATE + TestCicFilter.cpp TestExponentialMovingAverage.cpp TestFir.cpp TestIir.cpp diff --git a/numerical/filters/passive/test/TestCicFilter.cpp b/numerical/filters/passive/test/TestCicFilter.cpp new file mode 100644 index 00000000..195815fb --- /dev/null +++ b/numerical/filters/passive/test/TestCicFilter.cpp @@ -0,0 +1,83 @@ +#include "numerical/filters/passive/CicFilter.hpp" +#include "numerical/math/Tolerance.hpp" +#include "gtest/gtest.h" + +namespace +{ + class TestCicDecimator + : public ::testing::Test + { + public: + filters::passive::CicDecimator cic{}; + }; +} + +TEST_F(TestCicDecimator, emits_one_per_R) +{ + int count{ 0 }; + for (int i = 0; i < 8; ++i) + { + auto result = cic.Filter(1.0f); + if (result.valid) + ++count; + } + EXPECT_EQ(count, 2); +} + +TEST_F(TestCicDecimator, dc_gain_normalized) +{ + constexpr float c{ 0.5f }; + constexpr float tol{ 1e-5f }; + filters::passive::CicSample result{}; + for (int i = 0; i < 16; ++i) + result = cic.Filter(c); + EXPECT_NEAR(result.value, c, tol); +} + +TEST_F(TestCicDecimator, impulse_response_is_triangular) +{ + constexpr float tol{ 1e-5f }; + filters::passive::CicSample first{}; + filters::passive::CicSample second{}; + for (int i = 0; i < 8; ++i) + { + float inp = (i == 0) ? 1.0f : 0.0f; + auto r = cic.Filter(inp); + if (r.valid) + { + if (!first.valid) + first = r; + else if (!second.valid) + second = r; + } + } + EXPECT_NEAR(first.value, 0.25f, tol); + EXPECT_NEAR(second.value, 0.0f, tol); +} + +TEST_F(TestCicDecimator, silence_gives_zero) +{ + constexpr float tol{ 1e-5f }; + for (int i = 0; i < 8; ++i) + { + auto result = cic.Filter(0.0f); + if (result.valid) + EXPECT_NEAR(result.value, 0.0f, tol); + } +} + +TEST_F(TestCicDecimator, reset_clears_all_state) +{ + constexpr float tol{ 1e-5f }; + for (int i = 0; i < 4; ++i) + cic.Filter(1.0f); + cic.Reset(); + filters::passive::CicSample first{}; + for (int i = 0; i < 4; ++i) + { + auto r = cic.Filter(1.0f); + if (r.valid) + first = r; + } + EXPECT_NEAR(first.value, 0.625f, tol); +} diff --git a/roadmap/filters/passive/CicFilter/explanation.md b/roadmap/filters/passive/CicFilter/explanation.md deleted file mode 100644 index 49adbc71..00000000 --- a/roadmap/filters/passive/CicFilter/explanation.md +++ /dev/null @@ -1,30 +0,0 @@ -# CIC (Cascaded Integrator-Comb) Filter — Overview - -## What it is -A multiplier-free decimation/interpolation filter built from `Stages` integrators running at the -high sample rate followed (after the rate change) by `Stages` comb (differencing) stages at the low -rate. - -## Why it matters (embedded) -It is the canonical front-end for sigma-delta ADCs/DACs and any large integer rate change: it uses -**only adds, subtracts, and delays — no multipliers and no coefficient storage**. That makes it -almost free in hardware and on multiplier-poor microcontrollers. - -## How it works (intuition) -An integrator is a running sum (a pole at DC); a comb with delay `M` subtracts a delayed copy (a -zero). Cascading `Stages` of each gives a `sinc^Stages` low-pass shape that suppresses the aliases -created by decimation. The trick is that integer integrator overflow wraps around and is exactly -undone by the comb subtraction, so the arithmetic stays lossless despite huge internal gain. - -## Key parameters -- **R (rate change)** — decimation/interpolation factor. -- **Stages (order)** — more stages ⇒ steeper roll-off and more alias rejection, but more droop. -- **M (differential delay)** — usually 1 or 2; sets the null spacing. - -## Reference -E. B. Hogenauer, "An Economical Class of Digital Filters for Decimation and Interpolation," -*IEEE Trans. Acoustics, Speech, and Signal Processing*, 29(2), 1981. - -## See also -`MovingAverage` (a 1-stage integrator-comb pair), `BiquadCascade` (droop compensation), -`IirFilterDesign` (sharper selective filtering). diff --git a/roadmap/filters/passive/CicFilter/implementation.md b/roadmap/filters/passive/CicFilter/implementation.md deleted file mode 100644 index d7fd8ca9..00000000 --- a/roadmap/filters/passive/CicFilter/implementation.md +++ /dev/null @@ -1,70 +0,0 @@ -# CIC (Cascaded Integrator-Comb) Filter — Implementation Pseudocode - -> Roadmap ref: #14 (Tier 2) · 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 CicDecimator: # R = decimation, M = differential delay - array integrator # integrator running sums - array, Stages> comb # each holds an M-sample delay line - counter phase = 0 # 0..R-1 decimation phase -``` - -## Interface - -``` -CicDecimator() -optional Filter(T input) # returns a sample once every R inputs -void Reset() -static constexpr T Gain() # (R*M)^Stages, for output scaling -``` - -## Algorithm (pseudocode) - -``` -function Filter(x): # OPTIMIZE_FOR_SPEED - # --- integrator section, runs at the INPUT rate --- - acc = x - for i in 0..Stages-1: - integrator[i] += acc # y = y + acc (pure accumulation) - acc = integrator[i] - - phase = phase + 1 - if phase < R: return none # decimate: emit 1 of every R inputs - - phase = 0 - # --- comb section, runs at the OUTPUT (decimated) rate --- - for i in 0..Stages-1: - delayed = comb[i].PushPop(acc) # value M output-samples ago - acc = acc - delayed # differencing - return acc / Gain() # normalize DC gain toward 1 -``` - -## Complexity & memory - -- Time: `O(Stages)` adds at input rate + `O(Stages)` subs per `R` inputs — **no multipliers**. -- Memory: `O(Stages · M)` accumulator/delay words. - -## Deployment - -- Header: `numerical/filters/passive/CicFilter.hpp` — `#pragma once` → - `#pragma GCC optimize("O3","fast-math")`, `OPTIMIZE_FOR_SPEED` on `Filter`, and - `extern template class CicDecimator;` under `#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD`. -- Coverage: `numerical/filters/passive/CicFilter.cpp` → - `template class CicDecimator;` -- Test: `numerical/filters/passive/test/TestCicFilter.cpp` -- Doc: `doc/filters/passive/CicFilter.md` (expand to follow `doc/TEMPLATE.md`) -- CMake: `.hpp` → `target_sources`; `.cpp` → `numerical_add_coverage_sources`; - `TestCicFilter.cpp` → the `_test` target. -- Generic pattern: see `roadmap/DEPLOYMENT.md`. - -## Numerical / embedded notes - -- DC gain is `(R·M)^Stages`; divide the comb output by this factor (`Gain()`) to normalize toward - unity. -- Passband droop (`sinc^Stages`) usually needs a small FIR compensator downstream. -- The interpolator is the dual: comb → zero-stuff (×R) → integrator, in that order. -- Float-only: `static_assert(std::is_floating_point_v)`; the generic `T` signature keeps a - `Q15`/`Q31` specialisation cheap to add later. diff --git a/roadmap/filters/passive/CicFilter/tests.md b/roadmap/filters/passive/CicFilter/tests.md deleted file mode 100644 index aaf16858..00000000 --- a/roadmap/filters/passive/CicFilter/tests.md +++ /dev/null @@ -1,45 +0,0 @@ -# CIC Filter — Unit Test Plan (Pseudocode) - -> GoogleTest · `TEST_F` (`float`) · `StrictMock` only · no heap. - -## Fixture - -``` -class TestCicDecimator : public ::testing::Test: - CicDecimator cic{} # Stages=2, R=4, M=1 -# each case below is a TEST_F(TestCicDecimator, ) -``` - -## Test cases (Arrange / Act / Assert) - -``` -emits_one_per_R: - Arrange: R = 4, feed 8 samples - Act: count non-empty outputs - Assert: exactly 2 outputs produced (decimation by 4) - -dc_gain_normalized: - Arrange: constant input c, Stages=2, R=4, M=1 - Assert: normalized output ≈ c (gain (R*M)^Stages divided out) - -impulse_response_is_triangular: - Arrange: single impulse, Stages=2, M=1 - Assert: decimated impulse response matches the sinc^2 / triangular shape - -silence_gives_zero: - Arrange: all-zero input - Assert: every emitted output == 0 - -reset_clears_all_state: - Arrange: run samples, Reset() - Assert: integrators, combs, and phase all zero -``` - -## Reference vectors - -- Stages=1, R=4, M=1, constant `1` ⇒ each output = `4` before normalization (gain `R·M`). -- Stages=2, R=2, M=1, impulse ⇒ decimated response `[1, 2, 1]` (triangular) pre-normalization. - -## Edge cases - -- `R = 1` ⇒ no decimation (integrator-comb pair only).