Repository navigation
feat: add goertzel algorithm #176
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
94d82b3
add goertzel algorithm
gabrielfrasantos d3ba051
Merge branch 'main' into feature/add-goertzel-algo
gabrielfrasantos d6c71a2
Apply suggestions from code review
gabrielfrasantos 7c4a589
Merge branch 'main' into feature/add-goertzel-algo
gabrielfrasantos 1fbea76
split declaration from implementation
gabrielfrasantos 7150b33
Update TestGoertzelAlgorithm.cpp
gabrielfrasantos 80d3dc3
Merge branch 'main' into feature/add-goertzel-algo
gabrielfrasantos File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,111 @@ | ||
| # Goertzel Algorithm | ||
|
|
||
| ## Overview & Motivation | ||
|
|
||
| When a system needs to detect or measure a single known frequency — a DTMF touch-tone, a pilot sync tone, mains-hum, or a narrowband alarm — computing a full FFT wastes every cycle spent on bins that will never be read. The Goertzel algorithm computes exactly one DFT bin using a second-order recurrence that processes samples one at a time, requiring no input buffer and no twiddle-factor table. On the smallest microcontrollers with a few hundred bytes of RAM, this distinction is decisive. | ||
|
|
||
| ## Mathematical Theory | ||
|
|
||
| ### Core Definitions | ||
|
|
||
| Let $x[n]$, $n = 0, \ldots, N-1$, be a block of $N$ real samples. The DFT coefficient at bin $k$ is: | ||
|
|
||
| $$X[k] = \sum_{n=0}^{N-1} x[n]\, e^{-j2\pi kn/N}$$ | ||
|
|
||
| Define the resonator coefficient: | ||
|
|
||
| $$c = 2\cos\!\left(\frac{2\pi k}{N}\right)$$ | ||
|
|
||
| ### Derivation | ||
|
|
||
| The DFT sum can be reorganised as the output of a single-pole IIR filter evaluated at $n = N$. Introduce the auxiliary sequence: | ||
|
|
||
| $$s[n] = x[n] + c\,s[n-1] - s[n-2], \quad s[-1] = s[-2] = 0$$ | ||
|
|
||
| After $N$ steps the DFT bin follows from the final two state values: | ||
|
|
||
| $$X[k] = s[N-1] - s[N-2]\,e^{-j2\pi k/N}$$ | ||
|
|
||
| Separating real and imaginary parts: | ||
|
|
||
| $$\operatorname{Re}\{X[k]\} = s[N-1] - s[N-2]\cos\!\left(\tfrac{2\pi k}{N}\right)$$ | ||
|
|
||
| $$\operatorname{Im}\{X[k]\} = s[N-2]\sin\!\left(\tfrac{2\pi k}{N}\right)$$ | ||
|
|
||
| The magnitude can be obtained without the final trigonometric products using the identity: | ||
|
|
||
| $$|X[k]|^2 = s[N-1]^2 + s[N-2]^2 - c\,s[N-1]\,s[N-2]$$ | ||
|
|
||
| so $|X[k]| = \sqrt{s[N-1]^2 + s[N-2]^2 - c\,s[N-1]\,s[N-2]}$, saving two multiplies on the hot path. | ||
|
|
||
| ### Frequency-to-Bin Mapping | ||
|
|
||
| A physical frequency $f_t$ sampled at $f_s$ maps to bin: | ||
|
|
||
| $$k = \operatorname{round}\!\left(\frac{f_t}{f_s}\,N\right)$$ | ||
|
|
||
| Frequency resolution is $\Delta f = f_s / N$. | ||
|
|
||
| ## Complexity Analysis | ||
|
|
||
| | Case | Time | Space | Notes | | ||
| |------------|--------|--------|-----------------------------------------| | ||
| | Per sample | $O(1)$ | $O(1)$ | One multiply, two adds, no table lookup | | ||
| | Full block | $O(N)$ | $O(1)$ | Two state words; trig only at block end | | ||
|
|
||
| For $B$ bins of interest the total cost is $O(BN)$. An FFT computing all $N$ bins costs $O(N\log N)$, so the Goertzel approach is cheaper when $B \ll \log_2 N$ — typically $B \le 4$ for a 256-point transform. | ||
|
|
||
| ## Step-by-Step Walkthrough | ||
|
|
||
| Consider $N = 4$, $k = 1$, $x = [1, 0, -1, 0]$. | ||
|
|
||
| $c = 2\cos(\pi/2) = 0$ | ||
|
|
||
| | $n$ | $x[n]$ | $s[n] = x[n] + 0\cdot s[n-1] - s[n-2]$ | | ||
| |-----|--------|----------------------------------------| | ||
| | 0 | 1 | $1 + 0 - 0 = 1$ | | ||
| | 1 | 0 | $0 + 0 - 1 = -1$ | | ||
| | 2 | -1 | $-1 + 0 - 0 = -1$ (note: $s[-1]=0$) | | ||
| | 3 | 0 | $0 + 0 - (-1) = 1$ | | ||
|
|
||
| $\cos(2\pi/4) = 0$, $\sin(2\pi/4) = 1$ | ||
|
|
||
| $\operatorname{Re}\{X[1]\} = 1 - (-1)\cdot 0 = 1$ | ||
|
|
||
| $\operatorname{Im}\{X[1]\} = (-1)\cdot 1 = -1$ | ||
|
|
||
| Direct DFT check: $X[1] = 1 - j$. Matches. | ||
|
|
||
| ## Pitfalls & Edge Cases | ||
|
|
||
| The recurrence pole sits exactly on the unit circle, making the filter marginally stable. Error accumulates with each block if `Reset` is not called between blocks. The algorithm is designed for finite, bounded blocks of exactly $N$ samples. | ||
|
|
||
| Choosing $N$ such that the target tone lands near an integer bin minimises spectral leakage. A mismatch of half a bin can reduce the apparent magnitude by several decibels. Window functions do not apply here because the Goertzel filter already selects one bin; applying a window changes the effective DFT kernel. | ||
|
|
||
| The DC bin ($k = 0$) and the Nyquist bin ($k = N/2$) are purely real; their imaginary output is zero by symmetry. | ||
|
|
||
| ## Variants & Generalizations | ||
|
|
||
| The magnitude-squared form $s_1^2 + s_2^2 - c\,s_1 s_2$ avoids the square root when only power detection (threshold comparison) is needed, saving a transcendental call on platforms without hardware `sqrt`. | ||
|
|
||
| When several tones must be tracked simultaneously, one independent Goertzel instance per tone runs in $O(BN)$ total with $O(B)$ state — still far cheaper than an FFT for small $B$. | ||
|
|
||
| A sliding Goertzel variant updates one sample at a time by subtracting the oldest sample, giving a continuous output at the cost of maintaining an input ring buffer; this trades $O(1)$ memory for $O(N)$ memory and is outside the scope of the no-heap constraint here. | ||
|
|
||
| ## Applications | ||
|
|
||
| - DTMF decoding (telephony, industrial keypads) | ||
| - Sync-tone and pilot-tone detection in radio links | ||
| - Mains-frequency monitoring (50/60 Hz hum) | ||
| - Single-bin power spectral estimation in embedded monitors | ||
| - Lock-in detection for narrow-band sensor readout | ||
|
|
||
| ## Connections to Other Algorithms | ||
|
|
||
| The Goertzel algorithm computes exactly the same result as one bin of the DFT computed by the Cooley-Tukey FFT (`FastFourierTransform`), but limits the computation to that single bin. When all $N$ bins are required simultaneously, the FFT is always faster. `PowerDensitySpectrum` builds on the FFT for broadband spectral estimation. `SignalDetectors` provides simpler, non-frequency-selective detectors (peak hold, RMS) that cost even less per sample. | ||
|
|
||
| ## References & Further Reading | ||
|
|
||
| - G. Goertzel, "An Algorithm for the Evaluation of Finite Trigonometric Series," *American Mathematical Monthly*, 65(1), 34–35, 1958. | ||
| - A. V. Oppenheim and R. W. Schafer, *Discrete-Time Signal Processing*, 3rd ed., Prentice Hall, 2009, §8.1. | ||
| - P. Mock, "Add DTMF Generation and Decoding to DSP-µP Designs," *EDN*, March 1985 (practical embedded application of Goertzel). |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| #include "numerical/analysis/GoertzelAlgorithm.hpp" | ||
|
|
||
| namespace analysis | ||
| { | ||
| template class GoertzelAlgorithm<float>; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,110 @@ | ||
| #pragma once | ||
|
|
||
| #if defined(__GNUC__) || defined(__clang__) | ||
| #pragma GCC optimize("O3", "fast-math") | ||
| #endif | ||
|
|
||
| #include "numerical/math/CompilerOptimizations.hpp" | ||
| #include "numerical/math/ComplexNumber.hpp" | ||
| #include <cmath> | ||
| #include <cstddef> | ||
| #include <numbers> | ||
| #include <type_traits> | ||
|
|
||
| namespace analysis | ||
| { | ||
| template<typename T> | ||
| class GoertzelAlgorithm | ||
| { | ||
| static_assert(std::is_floating_point_v<T>, "GoertzelAlgorithm supports floating-point types only"); | ||
|
|
||
| public: | ||
| GoertzelAlgorithm(std::size_t k, std::size_t blockLength); | ||
| GoertzelAlgorithm(T targetHz, T sampleHz, std::size_t blockLength); | ||
|
|
||
| OPTIMIZE_FOR_SPEED void Push(T x); | ||
| bool Ready() const; | ||
| math::Complex<T> Result() const; | ||
| T Magnitude() const; | ||
| void Reset(); | ||
|
|
||
| static T Coefficient(std::size_t k, std::size_t blockLength); | ||
|
|
||
| private: | ||
| T coeff; | ||
| T cosine; | ||
| T sine; | ||
| std::size_t blockSize; | ||
| T s1; | ||
| T s2; | ||
| std::size_t sampleCount; | ||
| }; | ||
|
|
||
| template<typename T> | ||
| GoertzelAlgorithm<T>::GoertzelAlgorithm(std::size_t k, std::size_t blockLength) | ||
| : coeff{ T{ 2 } * std::cos(T{ 2 } * std::numbers::pi_v<T> * static_cast<T>(k) / static_cast<T>(blockLength)) } | ||
| , cosine{ std::cos(T{ 2 } * std::numbers::pi_v<T> * static_cast<T>(k) / static_cast<T>(blockLength)) } | ||
| , sine{ std::sin(T{ 2 } * std::numbers::pi_v<T> * static_cast<T>(k) / static_cast<T>(blockLength)) } | ||
| , blockSize{ blockLength } | ||
| , s1{ T{ 0 } } | ||
| , s2{ T{ 0 } } | ||
| , sampleCount{ 0 } | ||
| {} | ||
|
|
||
| template<typename T> | ||
| GoertzelAlgorithm<T>::GoertzelAlgorithm(T targetHz, T sampleHz, std::size_t blockLength) | ||
| : GoertzelAlgorithm( | ||
| static_cast<std::size_t>(targetHz / sampleHz * static_cast<T>(blockLength) + T{ 0.5 }), | ||
| blockLength) | ||
| {} | ||
|
|
||
| template<typename T> | ||
| OPTIMIZE_FOR_SPEED void GoertzelAlgorithm<T>::Push(T x) | ||
| { | ||
| T s0{ x + coeff * s1 - s2 }; | ||
| s2 = s1; | ||
| s1 = s0; | ||
| ++sampleCount; | ||
| } | ||
|
|
||
| template<typename T> | ||
| bool GoertzelAlgorithm<T>::Ready() const | ||
| { | ||
| return sampleCount >= blockSize; | ||
| } | ||
|
|
||
| template<typename T> | ||
| math::Complex<T> GoertzelAlgorithm<T>::Result() const | ||
| { | ||
| T real{ s1 - s2 * cosine }; | ||
| T imag{ s2 * sine }; | ||
| return math::Complex<T>{ real, imag }; | ||
| } | ||
|
|
||
| template<typename T> | ||
| T GoertzelAlgorithm<T>::Magnitude() const | ||
| { | ||
| return std::sqrt(s1 * s1 + s2 * s2 - coeff * s1 * s2); | ||
| } | ||
|
|
||
| template<typename T> | ||
| void GoertzelAlgorithm<T>::Reset() | ||
| { | ||
| s1 = T{ 0 }; | ||
| s2 = T{ 0 }; | ||
| sampleCount = 0; | ||
| } | ||
|
|
||
| template<typename T> | ||
| T GoertzelAlgorithm<T>::Coefficient(std::size_t k, std::size_t blockLength) | ||
| { | ||
| return T{ 2 } * std::cos(T{ 2 } * std::numbers::pi_v<T> * static_cast<T>(k) / static_cast<T>(blockLength)); | ||
| } | ||
| } | ||
|
|
||
| #ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD | ||
| namespace analysis | ||
| { | ||
| extern template class GoertzelAlgorithm<float>; | ||
| } | ||
| #endif |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.