diff --git a/README.md b/README.md index 7ae55c52..f2c88ffa 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Refer to the documentation to quickly integrate and utilize the library's signal | Category | Description | |--------------------------------------------------------------------|----------------------------------------------------------------------| -| [Analysis](doc/analysis/README.md) | FFT, Power Spectral Density, DCT, Window Functions, Signal Detectors | +| [Analysis](doc/analysis/README.md) | FFT, Power Spectral Density, DCT, Window Functions, Signal Detectors, Convolution & Correlation | | [Control Analysis](doc/control_analysis/README.md) | Frequency Response, Root Locus | | [Controllers](doc/controllers/README.md) | Bang-Bang/Hysteresis, PID, LQR, MPC, Saturation, Rate Limiter, Slew-Limited Saturation, Feedforward/2-DOF | | [Dynamics](doc/dynamics/README.md) | Euler-Lagrange, Newton-Euler, Recursive Newton-Euler, ABA | diff --git a/ROADMAP.md b/ROADMAP.md index 9c43e759..562b321f 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -29,7 +29,6 @@ Difficulty legend: |----|------------------------------------------------------|---------------------------|------------| | 8 | Alpha-beta / alpha-beta-gamma filter | `filters/active` | ★★☆☆☆ | | 10 | Gain-scheduled controller | `controllers` | ★★☆☆☆ | -| 11 | Convolution & correlation utilities | `analysis` | ★★☆☆☆ | | 12 | Polynomial least-squares curve fitting | `estimators/offline` | ★★☆☆☆ | | 13 | Goertzel algorithm | `analysis` | ★★☆☆☆ | | 14 | CIC (Cascaded Integrator-Comb) filter | `filters/passive` | ★★☆☆☆ | diff --git a/doc/analysis/ConvolutionCorrelation.md b/doc/analysis/ConvolutionCorrelation.md new file mode 100644 index 00000000..a0c9b12e --- /dev/null +++ b/doc/analysis/ConvolutionCorrelation.md @@ -0,0 +1,145 @@ +# Convolution & Correlation + +## Overview & Motivation + +Two signals interacting in time — one being filtered, delayed, or matched against another — are +described by convolution and correlation. Convolution is the time-domain action of any linear +time-invariant (LTI) filter: given an input signal and a system's impulse response, their +convolution is the output. Correlation measures the similarity between two signals as a function +of relative shift (lag), making it the foundation of matched filtering, pulse detection, and +time-delay estimation. + +Both operations are indispensable in embedded DSP: they underlie FIR filtering, pitch detection, +radar/sonar processing, and auto-regressive modeling. Bounded, no-heap implementations make +these algorithms practical on microcontrollers. + +## Mathematical Theory + +### Linear Convolution + +For finite sequences $x$ of length $M$ and $h$ of length $K$, the linear convolution $y = x * h$ +is a sequence of length $M + K - 1$ defined by: + +$$y[n] = \sum_{k=0}^{M-1} x[k] \cdot h[n - k], \quad n = 0, \ldots, M+K-2$$ + +where $h[j] = 0$ for $j < 0$ or $j \geq K$. + +### Circular Convolution + +For two sequences of equal length $N$, circular (periodic) convolution wraps indices modulo $N$: + +$$y[n] = \sum_{k=0}^{N-1} x[k] \cdot h[(n - k) \bmod N], \quad n = 0, \ldots, N-1$$ + +Circular convolution equals linear convolution only when both operands are zero-padded to at least +$M + K - 1$ samples. Without padding, time-aliasing occurs. + +### Cross-Correlation + +Cross-correlation of $x$ (length $M$) and $y$ (length $K$) is defined as: + +$$r_{xy}[\ell] = \sum_{n} x[n] \cdot y[n - \ell]$$ + +This equals linear convolution of $x$ with the time-reversed $y$: + +$$r_{xy} = x * \overline{y}$$ + +### Auto-Correlation + +Auto-correlation is cross-correlation of a signal with itself: + +$$r_{xx}[\ell] = \sum_{n} x[n] \cdot x[n - \ell]$$ + +It is always symmetric about the zero-lag index, and its maximum occurs at zero lag. +Dividing by $r_{xx}[0]$ yields a normalized coefficient in $[-1, 1]$. + +### Convolution Theorem (Fast Path) + +For long signals, the convolution theorem enables an $O(L \log L)$ computation: + +$$x * h = \mathcal{F}^{-1}\!\left(\mathcal{F}(x) \cdot \mathcal{F}(h)\right)$$ + +where $\mathcal{F}$ denotes the DFT and $L$ is the next power of two $\geq M + K - 1$. The +pointwise complex product replaces the $O(MK)$ direct sum. + +## Complexity Analysis + +| Operation | Time | Space (extra) | Notes | +|----------------------|---------------|---------------|---------------------------------------| +| Linear convolution | $O(MK)$ | $O(1)$ | Writes into caller-owned buffer | +| Circular convolution | $O(N^2)$ | $O(1)$ | Same as linear for equal-length input | +| Cross-correlation | $O(MK)$ | $O(K)$ | Reverses one operand on the stack | +| Auto-correlation | $O(M^2)$ | $O(1)$ | Alias of cross-correlation | +| Fast convolution | $O(L \log L)$ | $O(L)$ | $L = 2^{\lceil\log_2(M+K-1)\rceil}$ | + +The fast path is beneficial when $MK > L \log_2 L$, roughly when both operands exceed 32–64 +samples. + +## Step-by-Step Walkthrough + +Linear convolution of $x = [1, 2, 3]$ and $h = [1, 1]$ (output length $= 4$): + +| $n$ | Active $k$ range | Computation | $y[n]$ | +|-----|------------------|-------------------------|--------| +| 0 | $k=0$ | $1 \cdot 1$ | 1 | +| 1 | $k=0,1$ | $2 \cdot 1 + 1 \cdot 1$ | 3 | +| 2 | $k=1,2$ | $3 \cdot 1 + 2 \cdot 1$ | 5 | +| 3 | $k=2$ | $3 \cdot 1$ | 3 | + +Result: $[1, 3, 5, 3]$. + +Auto-correlation of $[1, 1, 1, 1]$ produces the triangular sequence $[1, 2, 3, 4, 3, 2, 1]$, +with the peak at the zero-lag center index (index 3 in 0-based notation). + +## Pitfalls & Edge Cases + +- **Time-aliasing**: Circular convolution of length $N$ equals linear convolution only when both + operands are zero-padded to $M + K - 1 \leq N$. Failing to pad causes energy from the tail to + wrap around and corrupt the beginning of the output. +- **Lag estimation**: `ArgMaxLag` returns the index of the maximum in the cross-correlation + output. For cross-correlation of two length-$M$ sequences the zero-lag corresponds to index + $M - 1$; a delay of $d$ samples appears at index $M - 1 + d$. +- **Normalization**: The raw auto-correlation at zero lag equals the signal energy. Dividing the + entire sequence by $r[0]$ gives a coefficient bounded in $[-1, 1]$. +- **Float precision**: Accumulating many products in single precision can lose significance for + very long sequences. The MAC loop uses the native float accumulator; for sequences longer than + a few hundred samples, extended precision may be warranted. + +## Variants & Generalizations + +- **Normalized cross-correlation**: Divide $r_{xy}[\ell]$ by $\sqrt{r_{xx}[0] \cdot r_{yy}[0]}$ + for an amplitude-invariant similarity measure. +- **Overlap-add / overlap-save**: Partition long signals into short blocks and convolve each + with $h$ via the FFT fast path, then reassemble. Reduces latency for streaming applications. +- **Partial correlation**: Compute cross-correlation over a sliding window rather than the full + signal length — useful for non-stationary signals. + +## Applications + +- **FIR filtering**: Direct-form FIR is linear convolution of the input with the filter's impulse + response. +- **Matched filtering**: Cross-correlate the received signal with a known template to detect it + in noise. +- **Time-delay estimation (TDOA)**: The lag of the cross-correlation peak between two sensors + gives the inter-sensor arrival time difference. +- **Pitch detection**: Auto-correlation of a speech frame reveals the fundamental period as the + first large secondary peak. +- **AR modeling**: Yule-Walker equations use auto-correlation values to fit auto-regressive + parameters. + +## Connections to Other Algorithms + +- **FastFourierTransform**: The fast convolution path is a direct application of the FFT-based + convolution theorem. +- **GoertzelAlgorithm**: A single-frequency DFT bin — cross-correlating with a complex + exponential at one frequency is equivalent. +- **YuleWalker**: Constructs the AR system matrix from auto-correlation lags computed by + `AutoCorrelation`. +- **PowerSpectralDensity**: The power spectrum is the DFT of the auto-correlation sequence + (Wiener–Khinchin theorem). + +## References & Further Reading + +- A. V. Oppenheim, R. W. Schafer, *Discrete-Time Signal Processing*, 3rd ed., Prentice Hall, + 2009, Chapters 2 & 8. +- A. V. Oppenheim, A. S. Willsky, *Signals and Systems*, 2nd ed., Prentice Hall, 1997, + Chapter 9. diff --git a/numerical/analysis/CMakeLists.txt b/numerical/analysis/CMakeLists.txt index b4f37df9..f2ff7856 100644 --- a/numerical/analysis/CMakeLists.txt +++ b/numerical/analysis/CMakeLists.txt @@ -12,6 +12,7 @@ target_link_libraries(numerical.analysis ${NUMERICAL_VISIBILITY} ) target_sources(numerical.analysis PRIVATE + ConvolutionCorrelation.hpp DiscreteCosineTransform.hpp FastFourierTransform.hpp FastFourierTransformRadix2Impl.hpp @@ -20,6 +21,7 @@ target_sources(numerical.analysis PRIVATE ) numerical_add_coverage_sources(numerical.analysis + ConvolutionCorrelation.cpp FastFourierTransformRadix2Impl.cpp PowerDensitySpectrum.cpp SignalDetectors.cpp diff --git a/numerical/analysis/ConvolutionCorrelation.cpp b/numerical/analysis/ConvolutionCorrelation.cpp new file mode 100644 index 00000000..a41f5e79 --- /dev/null +++ b/numerical/analysis/ConvolutionCorrelation.cpp @@ -0,0 +1,32 @@ +#include "numerical/analysis/ConvolutionCorrelation.hpp" + +namespace analysis +{ + template void LinearConvolution( + const infra::BoundedVector::WithMaxSize<3>&, + const infra::BoundedVector::WithMaxSize<3>&, + infra::BoundedVector::WithMaxSize<5>&); + + template void CircularConvolution( + const infra::BoundedVector::WithMaxSize<4>&, + const infra::BoundedVector::WithMaxSize<4>&, + infra::BoundedVector::WithMaxSize<4>&); + + template void CrossCorrelation( + const infra::BoundedVector::WithMaxSize<5>&, + const infra::BoundedVector::WithMaxSize<5>&, + infra::BoundedVector::WithMaxSize<9>&); + + template void AutoCorrelation( + const infra::BoundedVector::WithMaxSize<4>&, + infra::BoundedVector::WithMaxSize<7>&); + + template std::size_t ArgMaxLag( + const infra::BoundedVector::WithMaxSize<9>&); + + template void FastConvolution( + const infra::BoundedVector::WithMaxSize<3>&, + const infra::BoundedVector::WithMaxSize<3>&, + infra::BoundedVector::WithMaxSize<5>&, + FastFourierTransform&); +} diff --git a/numerical/analysis/ConvolutionCorrelation.hpp b/numerical/analysis/ConvolutionCorrelation.hpp new file mode 100644 index 00000000..550ac9b5 --- /dev/null +++ b/numerical/analysis/ConvolutionCorrelation.hpp @@ -0,0 +1,163 @@ +#pragma once + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +#include "numerical/analysis/FastFourierTransform.hpp" +#include "numerical/math/CompilerOptimizations.hpp" +#include "numerical/math/ComplexNumber.hpp" +#include +#include +#include + +namespace analysis +{ + template + OPTIMIZE_FOR_SPEED void LinearConvolution( + const typename infra::BoundedVector::template WithMaxSize& x, + const typename infra::BoundedVector::template WithMaxSize& h, + typename infra::BoundedVector::template WithMaxSize& y) + { + static_assert(std::is_floating_point_v, "ConvolutionCorrelation supports floating-point types only"); + y.clear(); + y.resize(M + K - 1, T{ 0 }); + for (std::size_t n = 0; n < M + K - 1; ++n) + { + T acc{ 0 }; + std::size_t kStart{ n >= K - 1 ? n - (K - 1) : 0 }; + std::size_t kEnd{ n < M - 1 ? n : M - 1 }; + for (std::size_t k = kStart; k <= kEnd; ++k) + acc += x[k] * h[n - k]; + y[n] = acc; + } + } + + template + OPTIMIZE_FOR_SPEED void CircularConvolution( + const typename infra::BoundedVector::template WithMaxSize& x, + const typename infra::BoundedVector::template WithMaxSize& h, + typename infra::BoundedVector::template WithMaxSize& y) + { + static_assert(std::is_floating_point_v, "ConvolutionCorrelation supports floating-point types only"); + y.clear(); + y.resize(N, T{ 0 }); + for (std::size_t n = 0; n < N; ++n) + { + T acc{ 0 }; + for (std::size_t k = 0; k < N; ++k) + acc += x[k] * h[(n + N - k) % N]; + y[n] = acc; + } + } + + template + OPTIMIZE_FOR_SPEED void CrossCorrelation( + const typename infra::BoundedVector::template WithMaxSize& x, + const typename infra::BoundedVector::template WithMaxSize& y, + typename infra::BoundedVector::template WithMaxSize& r) + { + static_assert(std::is_floating_point_v, "ConvolutionCorrelation supports floating-point types only"); + typename infra::BoundedVector::template WithMaxSize yRev; + yRev.resize(K, T{ 0 }); + for (std::size_t i = 0; i < K; ++i) + yRev[i] = y[K - 1 - i]; + LinearConvolution(x, yRev, r); + } + + template + void AutoCorrelation( + const typename infra::BoundedVector::template WithMaxSize& x, + typename infra::BoundedVector::template WithMaxSize<2 * M - 1>& r) + { + static_assert(std::is_floating_point_v, "ConvolutionCorrelation supports floating-point types only"); + CrossCorrelation(x, x, r); + } + + template + std::size_t ArgMaxLag(const typename infra::BoundedVector::template WithMaxSize& r) + { + static_assert(std::is_floating_point_v, "ConvolutionCorrelation supports floating-point types only"); + std::size_t best{ 0 }; + for (std::size_t i = 1; i < N; ++i) + if (r[i] > r[best]) + best = i; + return best; + } + + template + void FastConvolution( + const typename infra::BoundedVector::template WithMaxSize& x, + const typename infra::BoundedVector::template WithMaxSize& h, + typename infra::BoundedVector::template WithMaxSize& y, + FastFourierTransform& fft) + { + static_assert(std::is_floating_point_v, "ConvolutionCorrelation supports floating-point types only"); + static_assert((L & (L - 1)) == 0, "L must be a power of two"); + static_assert(L >= M + K - 1, "L must be at least M+K-1"); + + typename infra::BoundedVector::template WithMaxSize xPad; + typename infra::BoundedVector::template WithMaxSize hPad; + xPad.resize(L, T{ 0 }); + hPad.resize(L, T{ 0 }); + + for (std::size_t i = 0; i < M; ++i) + xPad[i] = x[i]; + for (std::size_t i = 0; i < K; ++i) + hPad[i] = h[i]; + + typename infra::BoundedVector>::template WithMaxSize X; + X.resize(L, math::Complex{ T{ 0 }, T{ 0 } }); + { + auto& rawX = fft.Forward(xPad); + for (std::size_t i = 0; i < L; ++i) + X[i] = rawX[i]; + } + auto& H = fft.Forward(hPad); + + typename infra::BoundedVector>::template WithMaxSize Y; + Y.resize(L, math::Complex{ T{ 0 }, T{ 0 } }); + for (std::size_t i = 0; i < L; ++i) + Y[i] = X[i] * H[i]; + + auto& yFull = fft.Inverse(Y); + + y.clear(); + y.resize(M + K - 1, T{ 0 }); + for (std::size_t i = 0; i < M + K - 1; ++i) + y[i] = yFull[i]; + } +} + +#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD +namespace analysis +{ + extern template void LinearConvolution( + const infra::BoundedVector::WithMaxSize<3>&, + const infra::BoundedVector::WithMaxSize<3>&, + infra::BoundedVector::WithMaxSize<5>&); + + extern template void CircularConvolution( + const infra::BoundedVector::WithMaxSize<4>&, + const infra::BoundedVector::WithMaxSize<4>&, + infra::BoundedVector::WithMaxSize<4>&); + + extern template void CrossCorrelation( + const infra::BoundedVector::WithMaxSize<5>&, + const infra::BoundedVector::WithMaxSize<5>&, + infra::BoundedVector::WithMaxSize<9>&); + + extern template void AutoCorrelation( + const infra::BoundedVector::WithMaxSize<4>&, + infra::BoundedVector::WithMaxSize<7>&); + + extern template std::size_t ArgMaxLag( + const infra::BoundedVector::WithMaxSize<9>&); + + extern template void FastConvolution( + const infra::BoundedVector::WithMaxSize<3>&, + const infra::BoundedVector::WithMaxSize<3>&, + infra::BoundedVector::WithMaxSize<5>&, + FastFourierTransform&); +} +#endif diff --git a/numerical/analysis/test/CMakeLists.txt b/numerical/analysis/test/CMakeLists.txt index 7ed99d0b..e8eeba46 100644 --- a/numerical/analysis/test/CMakeLists.txt +++ b/numerical/analysis/test/CMakeLists.txt @@ -9,6 +9,7 @@ target_link_libraries(numerical.analysis_test PUBLIC ) target_sources(numerical.analysis_test PRIVATE + TestConvolutionCorrelation.cpp TestDiscreteCosineTransform.cpp TestFastFourierTransformRadix2Impl.cpp TestPowerDensitySpectrum.cpp diff --git a/numerical/analysis/test/TestConvolutionCorrelation.cpp b/numerical/analysis/test/TestConvolutionCorrelation.cpp new file mode 100644 index 00000000..aafd2475 --- /dev/null +++ b/numerical/analysis/test/TestConvolutionCorrelation.cpp @@ -0,0 +1,219 @@ +#include "numerical/analysis/ConvolutionCorrelation.hpp" +#include "numerical/analysis/FastFourierTransformRadix2Impl.hpp" +#include "numerical/math/Tolerance.hpp" +#include "gmock/gmock.h" +#include +#include +#include + +namespace +{ + template + class ConcreteTwiddleFactors : public analysis::TwiddleFactors + { + public: + ConcreteTwiddleFactors() + { + for (std::size_t k = 0; k < HalfLen; ++k) + { + float angle{ -2.0f * std::numbers::pi_v * static_cast(k) / static_cast(2 * HalfLen) }; + factors[k] = math::Complex{ T(std::cos(angle)), T(std::sin(angle)) }; + } + } + + math::Complex& operator[](std::size_t n) override + { + return factors[n]; + } + + private: + std::array, HalfLen> factors; + }; + + class TestConvolutionCorrelation : public ::testing::Test + { + public: + using Vec3 = infra::BoundedVector::WithMaxSize<3>; + using Vec4 = infra::BoundedVector::WithMaxSize<4>; + using Vec5 = infra::BoundedVector::WithMaxSize<5>; + using Vec7 = infra::BoundedVector::WithMaxSize<7>; + using Vec8 = infra::BoundedVector::WithMaxSize<8>; + using Vec9 = infra::BoundedVector::WithMaxSize<9>; + }; +} + +TEST_F(TestConvolutionCorrelation, linear_convolution_matches_hand_calc) +{ + Vec3 x; + x.push_back(1.0f); + x.push_back(2.0f); + x.push_back(3.0f); + + Vec3 h; + h.push_back(0.0f); + h.push_back(1.0f); + h.push_back(0.5f); + + Vec5 y; + analysis::LinearConvolution(x, h, y); + + EXPECT_NEAR(y[0], 0.0f, math::Tolerance()); + EXPECT_NEAR(y[1], 1.0f, math::Tolerance()); + EXPECT_NEAR(y[2], 2.5f, math::Tolerance()); + EXPECT_NEAR(y[3], 4.0f, math::Tolerance()); + EXPECT_NEAR(y[4], 1.5f, math::Tolerance()); +} + +TEST_F(TestConvolutionCorrelation, convolution_with_unit_impulse_is_identity) +{ + Vec3 x; + x.push_back(1.0f); + x.push_back(2.0f); + x.push_back(3.0f); + + Vec3 h; + h.push_back(1.0f); + h.push_back(0.0f); + h.push_back(0.0f); + + Vec5 y; + analysis::LinearConvolution(x, h, y); + + EXPECT_NEAR(y[0], x[0], math::Tolerance()); + EXPECT_NEAR(y[1], x[1], math::Tolerance()); + EXPECT_NEAR(y[2], x[2], math::Tolerance()); +} + +TEST_F(TestConvolutionCorrelation, convolution_is_commutative) +{ + Vec3 x; + x.push_back(1.0f); + x.push_back(2.0f); + x.push_back(3.0f); + + Vec3 h; + h.push_back(0.0f); + h.push_back(1.0f); + h.push_back(0.5f); + + Vec5 y1; + Vec5 y2; + analysis::LinearConvolution(x, h, y1); + analysis::LinearConvolution(h, x, y2); + + for (std::size_t i = 0; i < 5; ++i) + EXPECT_NEAR(y1[i], y2[i], math::Tolerance()); +} + +TEST_F(TestConvolutionCorrelation, circular_convolution_wraps) +{ + Vec4 x; + x.push_back(1.0f); + x.push_back(2.0f); + x.push_back(3.0f); + x.push_back(4.0f); + + Vec4 h; + h.push_back(1.0f); + h.push_back(0.0f); + h.push_back(0.0f); + h.push_back(1.0f); + + Vec4 y; + analysis::CircularConvolution(x, h, y); + + EXPECT_NEAR(y[0], 3.0f, math::Tolerance()); + EXPECT_NEAR(y[1], 5.0f, math::Tolerance()); + EXPECT_NEAR(y[2], 7.0f, math::Tolerance()); + EXPECT_NEAR(y[3], 5.0f, math::Tolerance()); +} + +TEST_F(TestConvolutionCorrelation, autocorrelation_peaks_at_zero_lag) +{ + Vec4 x; + x.push_back(1.0f); + x.push_back(1.0f); + x.push_back(1.0f); + x.push_back(1.0f); + + Vec7 r; + analysis::AutoCorrelation(x, r); + + std::size_t peak{ analysis::ArgMaxLag(r) }; + EXPECT_EQ(peak, 3u); + + EXPECT_NEAR(r[0], r[6], math::Tolerance()); + EXPECT_NEAR(r[1], r[5], math::Tolerance()); + EXPECT_NEAR(r[2], r[4], math::Tolerance()); +} + +TEST_F(TestConvolutionCorrelation, cross_correlation_finds_known_delay) +{ + using Vec5 = infra::BoundedVector::WithMaxSize<5>; + using Vec9 = infra::BoundedVector::WithMaxSize<9>; + + Vec5 x; + x.push_back(1.0f); + x.push_back(0.0f); + x.push_back(0.0f); + x.push_back(0.0f); + x.push_back(0.0f); + + Vec5 yShifted; + yShifted.push_back(0.0f); + yShifted.push_back(0.0f); + yShifted.push_back(0.0f); + yShifted.push_back(1.0f); + yShifted.push_back(0.0f); + + Vec9 r; + analysis::CrossCorrelation(x, yShifted, r); + + std::size_t lag{ analysis::ArgMaxLag(r) }; + EXPECT_EQ(lag, 1u); +} + +TEST_F(TestConvolutionCorrelation, fast_convolution_matches_direct) +{ + Vec3 x; + x.push_back(1.0f); + x.push_back(2.0f); + x.push_back(3.0f); + + Vec3 h; + h.push_back(1.0f); + h.push_back(1.0f); + h.push_back(0.0f); + + Vec5 yDirect; + analysis::LinearConvolution(x, h, yDirect); + + ConcreteTwiddleFactors twiddle; + analysis::FastFourierTransformRadix2Impl fft{ twiddle }; + + Vec5 yFast; + analysis::FastConvolution(x, h, yFast, fft); + + for (std::size_t i = 0; i < 5; ++i) + EXPECT_NEAR(yFast[i], yDirect[i], 1e-3f); +} + +TEST_F(TestConvolutionCorrelation, single_tap_scales_signal) +{ + Vec3 x; + x.push_back(1.0f); + x.push_back(2.0f); + x.push_back(3.0f); + + Vec3 h; + h.push_back(2.5f); + h.push_back(0.0f); + h.push_back(0.0f); + + Vec5 y; + analysis::LinearConvolution(x, h, y); + + EXPECT_NEAR(y[0], 2.5f, math::Tolerance()); + EXPECT_NEAR(y[1], 5.0f, math::Tolerance()); + EXPECT_NEAR(y[2], 7.5f, math::Tolerance()); +} diff --git a/roadmap/analysis/ConvolutionCorrelation/explanation.md b/roadmap/analysis/ConvolutionCorrelation/explanation.md deleted file mode 100644 index a9385fd9..00000000 --- a/roadmap/analysis/ConvolutionCorrelation/explanation.md +++ /dev/null @@ -1,30 +0,0 @@ -# Convolution & Correlation — Overview - -## What it is -A small library of the two most fundamental DSP operations. **Convolution** slides one sequence over -another and sums the overlapping products (the time-domain action of any LTI filter). **Correlation** -does the same but without reversing one operand — it measures *similarity* as a function of lag. - -## Why it matters (embedded) -Matched filtering, template matching, pulse detection, and time-delay (lag) estimation all reduce to -these two kernels. Auto-correlation also underlies pitch detection and the Yule-Walker/AR estimators -already in the library. Bounded, no-heap versions let them run on-device instead of offline. - -## How it works (intuition) -Convolution output sample `n` is `Σ x[k]·h[n−k]` — flip `h`, shift it to position `n`, multiply -point-by-point, and add. Correlation is identical but with `h` *not* flipped, so a peak in the -cross-correlation marks the lag at which two signals line up best. For long signals the convolution -theorem lets you multiply spectra instead: `x∗h = IFFT(FFT(x)·FFT(h))`. - -## Key parameters -- **operand lengths** — set the compile-time output size `M+K−1` (linear) or `N` (circular). -- **circular vs linear** — circular wraps modulo `N`; equal to linear only with zero-padding. -- **normalization** — divide by `r[0]` for a correlation coefficient in `[−1, 1]`. - -## Reference -A. V. Oppenheim, R. W. Schafer, *Discrete-Time Signal Processing*, 3rd ed., Prentice Hall, 2009, -Chs. 2 & 8. - -## See also -`RealFft` / `FastFourierTransform` (fast convolution), `GoertzelAlgorithm`, `YuleWalker` -(auto-correlation-based AR estimation). diff --git a/roadmap/analysis/ConvolutionCorrelation/implementation.md b/roadmap/analysis/ConvolutionCorrelation/implementation.md deleted file mode 100644 index 4fb2ea65..00000000 --- a/roadmap/analysis/ConvolutionCorrelation/implementation.md +++ /dev/null @@ -1,92 +0,0 @@ -# Convolution & Correlation — Implementation Pseudocode - -> Roadmap ref: #11 (Tier 2) · Target: `numerical/analysis` · Namespace `analysis` · Type: `float` (templated on `T`, instantiated for `float` only) - -## Data structures - -Free functions over bounded vectors; no persistent state. Outputs are written into a caller-owned -`infra::BoundedVector` sized at compile time. - -``` -template # static_assert(std::is_floating_point_v); instantiated for float -using Vector = infra::BoundedVector::WithMaxSize - -# Output sizes (compile-time): -# linear conv/corr of (M, K) -> M + K - 1 -# circular conv of length N -> N -``` - -## Interface - -``` -# Every function: template # instantiated for float - -# Convolution -void LinearConvolution(Vector x, Vector h, Vector& y) # |y| = |x|+|h|-1 -void CircularConvolution(Vector x, Vector h, Vector& y) # equal length N - -# Correlation -void CrossCorrelation(Vector x, Vector y, Vector& r) # lag-indexed -void AutoCorrelation(Vector x, Vector& r) # r = CrossCorrelation(x, x) -size_t ArgMaxLag(Vector r) # delay / lag estimate - -# Optional fast path (power-of-two) -void FastConvolution(Vector x, Vector h, Vector& y, Fft& fft) -``` - -## Algorithm (pseudocode) - -``` -function LinearConvolution(x, h, y): # OPTIMIZE_FOR_SPEED - for n in 0 .. |x|+|h|-2: - acc = 0 - for k in max(0, n-|h|+1) .. min(n, |x|-1): - acc += x[k] * h[n-k] # MAC in wide accumulator - y[n] = acc - -function CircularConvolution(x, h, y): # length N, indices mod N - for n in 0 .. N-1: - acc = 0 - for k in 0 .. N-1: - acc += x[k] * h[(n-k) mod N] - y[n] = acc - -function CrossCorrelation(x, y, r): - # r[l] = sum_n x[n]·y[n-l] == convolution with a time-reversed y - LinearConvolution(x, reverse(y), r) - -function FastConvolution(x, h, y, fft): - L = next_pow2(|x| + |h| - 1) - X = fft.Forward(zeroPad(x, L)); H = fft.Forward(zeroPad(h, L)) - Y = X .* H # pointwise complex multiply - y = fft.Inverse(Y)[0 .. |x|+|h|-2] -``` - -## Complexity & memory - -- Direct linear/circular: `O(M·K)` time, `O(1)` extra memory (writes into caller buffer). -- FFT fast convolution: `O(L log L)` — worth it when both operands are long; needs three length-`L` - complex scratch buffers (compile-time sized). -- Correlation is convolution with one operand reversed — identical cost. - -## Numerical / embedded notes - -- Optionally divide auto-correlation by `r[0]` to get a normalized correlation in `[-1, 1]`. -- Circular convolution equals linear convolution only when both signals are zero-padded to - `|x|+|h|-1`; document this to avoid time-aliasing surprises. -- `ArgMaxLag` of the cross-correlation gives an integer sample delay — the basis of TDOA/lag estimation. -- 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/analysis/ConvolutionCorrelation.hpp` — `#pragma once` → - `#pragma GCC optimize("O3","fast-math")`, `OPTIMIZE_FOR_SPEED` on `LinearConvolution`/`CircularConvolution`, - and `extern template` declarations of the `float` instantiations under `#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD`. -- Coverage: `numerical/analysis/ConvolutionCorrelation.cpp` → explicit `float` function instantiations, - e.g. `template void LinearConvolution(...);` for each free function. -- Test: `numerical/analysis/test/TestConvolutionCorrelation.cpp` -- Doc: `doc/analysis/ConvolutionCorrelation.md` (expand to follow `doc/TEMPLATE.md`) -- CMake: `.hpp` → `target_sources`; `.cpp` → `numerical_add_coverage_sources`; - `TestConvolutionCorrelation.cpp` → the `_test` target. -- Generic pattern: see `roadmap/DEPLOYMENT.md`. diff --git a/roadmap/analysis/ConvolutionCorrelation/tests.md b/roadmap/analysis/ConvolutionCorrelation/tests.md deleted file mode 100644 index 615de59e..00000000 --- a/roadmap/analysis/ConvolutionCorrelation/tests.md +++ /dev/null @@ -1,59 +0,0 @@ -# Convolution & Correlation — Unit Test Plan (Pseudocode) - -> GoogleTest · `TEST_F` (`float`) · `StrictMock` only · no heap. - -## Fixture - -``` -class TestConvolutionCorrelation : public ::testing::Test: - Vector x, h, y, r # WithMaxSize buffers, filled per test -# each case below is a TEST_F(TestConvolutionCorrelation, ) -``` - -## Test cases (Arrange / Act / Assert) - -``` -linear_convolution_matches_hand_calc: - Arrange: x = [1, 2, 3], h = [0, 1, 0.5] - Act: LinearConvolution(x, h, y) - Assert: y ≈ [0, 1, 2.5, 4, 1.5] - -convolution_with_unit_impulse_is_identity: - Arrange: h = [1, 0, 0] - Assert: first |x| samples of y == x - -convolution_is_commutative: - Assert: conv(x, h) ≈ conv(h, x) - -circular_convolution_wraps: - Arrange: length-4 x and h - Assert: matches a DFT-multiply reference - -autocorrelation_peaks_at_zero_lag: - Arrange: r = AutoCorrelation(x) - Assert: argmax(r) is the zero-lag index, r symmetric - -cross_correlation_finds_known_delay: - Arrange: y = shift(x, +3) - Assert: ArgMaxLag(CrossCorrelation(x, y)) == 3 - -fast_convolution_matches_direct: - Arrange: StrictMock (or real radix-2 FFT), power-of-two length - Assert: FastConvolution ≈ LinearConvolution (±tol) - -single_tap_scales_signal: - Arrange: h = [k] - Assert: y == k · x -``` - -## Reference vectors - -- `[1,2,3] * [1,1]` (linear) ⇒ `[1, 3, 5, 3]`. -- Auto-correlation of `[1,1,1,1]` ⇒ triangular `[1,2,3,4,3,2,1]` (unnormalized). -- A delayed copy at lag `d` ⇒ cross-correlation peak at `d`. - -## Edge cases - -- Different-length operands (M ≠ K). -- Zero input vector ⇒ zero output. -- Circular vs linear mismatch when not zero-padded (documented behaviour).