Skip to content

Commit ade498b

Browse files
feat: add signal detectors (#168)
* add signal detectors * Apply suggestions from code review Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * fix sonar findings --------- Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
1 parent 4db3f6f commit ade498b

12 files changed

Lines changed: 321 additions & 188 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ Refer to the documentation to quickly integrate and utilize the library's signal
1616

1717
| Category | Description |
1818
|--------------------------------------------------------------------|----------------------------------------------------------------------|
19-
| [Analysis](doc/analysis/README.md) | FFT, Power Spectral Density, DCT, Window Functions |
19+
| [Analysis](doc/analysis/README.md) | FFT, Power Spectral Density, DCT, Window Functions, Signal Detectors |
2020
| [Control Analysis](doc/control_analysis/README.md) | Frequency Response, Root Locus |
2121
| [Controllers](doc/controllers/README.md) | PID, LQR, MPC, Saturation, Rate Limiter, Slew-Limited Saturation |
2222
| [Dynamics](doc/dynamics/README.md) | Euler-Lagrange, Newton-Euler, Recursive Newton-Euler, ABA |

‎ROADMAP.md‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,6 @@ Difficulty legend:
7979
| 2 | Moving Average (running-sum boxcar) | `filters/passive` | ★☆☆☆☆ |
8080
| 3 | Saturation / rate-limiter / slew blocks | `controllers` | ★☆☆☆☆ |
8181
| 4 | Bang-bang / hysteresis (relay) controller | `controllers` | ★☆☆☆☆ |
82-
| 5 | Peak / zero-crossing / RMS-envelope detectors | `analysis` | ★☆☆☆☆ |
8382
| 6 | Median filter | `filters/passive` | ★★☆☆☆ |
8483
| 7 | Feedforward / 2-DOF controller | `controllers` | ★★☆☆☆ |
8584
| 8 | Alpha-beta / alpha-beta-gamma filter | `filters/active` | ★★☆☆☆ |

‎doc/analysis/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ Signal analysis algorithms for frequency-domain decomposition and spectral estim
99
| [Fast Fourier Transform](FastFourierTransform.md) | Efficient computation of the Discrete Fourier Transform using the Cooley-Tukey radix-2 algorithm |
1010
| [Power Spectral Density](PowerDensitySpectrum.md) | Estimation of signal power distribution across frequencies using Welch's method |
1111
| [Discrete Cosine Transform](DiscreteCosineTransform.md) | Real-valued frequency decomposition via cosine basis functions, computed through FFT |
12+
| [Signal Detectors](SignalDetectors.md) | Peak hold, zero-crossing counter, and RMS envelope detectors for real-time signal monitoring |
1213

1314
## Sub-domains
1415

‎doc/analysis/SignalDetectors.md‎

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
# Signal Detectors
2+
3+
## Overview & Motivation
4+
5+
Real-time signal monitoring requires lightweight, stateful primitives that track envelope, periodicity, and energy without buffering entire waveforms. Three composable detectors cover the most common needs: holding the peak magnitude for VU-style metering, counting sign reversals to estimate frequency, and smoothing instantaneous power to approximate RMS level. All three operate in O(1) time and O(1) memory per sample, making them suitable for tight interrupt service routines.
6+
7+
## Mathematical Theory
8+
9+
### Peak Hold
10+
11+
Let $m_n = |x_n|$. With a decay coefficient $d \in (0, 1]$, the held peak evolves as:
12+
13+
$$p_n = \max(m_n,\; d \cdot p_{n-1})$$
14+
15+
When $d = 1$ the peak is infinite-hold; when $d < 1$ it releases exponentially toward zero between new maxima.
16+
17+
### Zero-Crossing Detection
18+
19+
A zero crossing occurs at sample $n$ when the sign of $x_n$ differs from the sign of $x_{n-1}$ and $|x_n|$ exceeds a hysteresis threshold $h \geq 0$:
20+
21+
$$\text{crossed}_n = \bigl(\operatorname{sgn}(x_n) \neq \operatorname{sgn}(x_{n-1})\bigr) \land \bigl(|x_n| > h\bigr)$$
22+
23+
The instantaneous fundamental frequency of a periodic signal can be estimated from the cumulative count $C$ over a window of $N$ samples at sampling period $T_s$:
24+
25+
$$f_0 \approx \frac{C}{2 \, N \, T_s}$$
26+
27+
### RMS Envelope
28+
29+
A one-pole IIR filter is applied to $x^2$, yielding an exponentially weighted mean-square:
30+
31+
$$E_n = E_{n-1} + \alpha\,(x_n^2 - E_{n-1}), \quad \alpha \in (0, 1)$$
32+
33+
The RMS envelope is:
34+
35+
$$r_n = \sqrt{E_n}$$
36+
37+
This is structurally identical to an exponential moving average applied to the squared signal.
38+
39+
## Complexity Analysis
40+
41+
| Detector | Time per sample | State words |
42+
|-----------------------|--------------------------------|---------------------|
43+
| Peak Hold | O(1) — 1 mul, 1 compare, 1 abs | 1 scalar |
44+
| Zero-Crossing Counter | O(1) — 1 compare, 1 abs | 1 scalar + 1 uint32 |
45+
| RMS Envelope | O(1) — 1 MAC + 1 sqrt | 1 scalar |
46+
47+
No buffers, no windows, no dynamic allocation.
48+
49+
## Step-by-Step Walkthrough
50+
51+
### Peak Hold (decay = 0.5), input = [0.8, 0, 0, 0]
52+
53+
| n | $x_n$ | $m_n$ | $d \cdot p_{n-1}$ | $p_n$ |
54+
|---|-------|-------|-------------------|-------|
55+
| 0 | 0.8 | 0.8 | 0.0 | 0.8 |
56+
| 1 | 0.0 | 0.0 | 0.4 | 0.4 |
57+
| 2 | 0.0 | 0.0 | 0.2 | 0.2 |
58+
| 3 | 0.0 | 0.0 | 0.1 | 0.1 |
59+
60+
### Zero-Crossing Counter (h = 0), input = [1, -1, 1, -1]
61+
62+
| n | $x_n$ | prev sign | curr sign | crossed | C |
63+
|---|-------|-----------|-----------|---------|---|
64+
| 0 | +1 | 0 | + | no | 0 |
65+
| 1 | -1 | + | - | yes | 1 |
66+
| 2 | +1 | - | + | yes | 2 |
67+
| 3 | -1 | + | - | yes | 3 |
68+
69+
### RMS Envelope ($\alpha = 0.25$), DC input $x = 0.4$
70+
71+
$E_0 = 0$; after $n$ steps, $E_n = 0.16\,(1-(1-0.25)^n)$. At $n = 20$: $E_{20} \approx 0.1599$, $r_{20} \approx 0.3999$.
72+
73+
## Pitfalls & Edge Cases
74+
75+
- Decay = 0 collapses the peak hold to the instantaneous absolute value; decay must be in $(0, 1]$ for meaningful hold behavior.
76+
- Zero-crossing sign comparison must treat $x = 0$ consistently; a sample at exactly zero with $h = 0$ can cause spurious double-counts if not handled. The hysteresis guard mitigates this.
77+
- RMS Envelope with very small $\alpha$ responds slowly to changes in signal level; with $\alpha$ near 1 it approaches the instantaneous absolute value squared.
78+
- The RMS detector returns 0 at initialization ($E_0 = 0$) and converges to the true RMS from below for positive-power signals.
79+
80+
## Variants & Generalizations
81+
82+
- The peak hold decay parameter maps directly to a time constant: $\tau = -T_s / \ln(d)$, bridging the gap between digital and analog VU meter release times.
83+
- A bilateral zero-crossing counter can distinguish positive-going from negative-going edges, enabling half-wave frequency estimation.
84+
- The RMS envelope is the special case of an exponential moving average applied to $x^2$; replacing the squaring with $|x|$ yields a mean-absolute-value envelope.
85+
86+
## Applications
87+
88+
- VU meters and compressor side-chains use peak hold with a configurable release time.
89+
- Zero-crossing rate is a low-cost voiced/unvoiced classifier in speech processing.
90+
- RMS envelope tracks AC signal levels in power monitoring, audio dynamic processing, and vibration analysis.
91+
- All three detectors compose naturally into a signal statistics block for real-time diagnostics.
92+
93+
## Connections to Other Algorithms
94+
95+
- RMS Envelope is structurally equivalent to the Exponential Moving Average (EMA) filter applied to $x^2$, sharing the same one-pole recurrence.
96+
- Zero-crossing detection is a degenerate form of edge detection in discrete sequences, related to sign-change detection in root-finding algorithms.
97+
98+
## References & Further Reading
99+
100+
- Zolzer, U., "DAFX: Digital Audio Effects", 2nd ed., Wiley, 2011 — Chapter 2 (dynamics processing, envelope followers).
101+
- Proakis, J. & Manolakis, D., "Digital Signal Processing", 4th ed., Prentice Hall, 2007 — Section 1.4 (zero-crossing rate).
102+
- Smith, J.O., "Introduction to Digital Filters with Audio Applications", W3K Publishing, 2007 — [online](https://ccrma.stanford.edu/~jos/filters/).

‎numerical/analysis/CMakeLists.txt‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,13 @@ target_sources(numerical.analysis PRIVATE
1616
FastFourierTransform.hpp
1717
FastFourierTransformRadix2Impl.hpp
1818
PowerDensitySpectrum.hpp
19+
SignalDetectors.hpp
1920
)
2021

2122
numerical_add_coverage_sources(numerical.analysis
2223
FastFourierTransformRadix2Impl.cpp
2324
PowerDensitySpectrum.cpp
25+
SignalDetectors.cpp
2426
)
2527

2628
add_subdirectory(test)
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
#include "numerical/analysis/SignalDetectors.hpp"
2+
3+
namespace analysis
4+
{
5+
template class PeakHold<float>;
6+
template class ZeroCrossingCounter<float>;
7+
template class RmsEnvelope<float>;
8+
}
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
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 <cmath>
9+
#include <cstdint>
10+
#include <type_traits>
11+
12+
namespace analysis
13+
{
14+
template<typename T>
15+
class PeakHold
16+
{
17+
static_assert(std::is_floating_point_v<T>, "PeakHold supports floating-point types only");
18+
19+
public:
20+
explicit PeakHold(T decay = T{ 1 })
21+
: decay{ decay }
22+
{}
23+
24+
OPTIMIZE_FOR_SPEED T Update(T x)
25+
{
26+
T m{ std::abs(x) };
27+
peak = (m > peak * decay) ? m : peak * decay;
28+
return peak;
29+
}
30+
31+
void Reset()
32+
{
33+
peak = T{ 0 };
34+
}
35+
36+
private:
37+
T peak{ T{ 0 } };
38+
T decay;
39+
};
40+
41+
template<typename T>
42+
class ZeroCrossingCounter
43+
{
44+
static_assert(std::is_floating_point_v<T>, "ZeroCrossingCounter supports floating-point types only");
45+
46+
public:
47+
explicit ZeroCrossingCounter(T hysteresis = T{ 0 })
48+
: hysteresis{ hysteresis }
49+
{}
50+
51+
OPTIMIZE_FOR_SPEED bool Update(T x)
52+
{
53+
bool crossed{ (previous < T{ 0 } ? x > T{ 0 } : x < T{ 0 }) && (std::abs(x) > hysteresis) };
54+
if (crossed)
55+
++count;
56+
previous = x;
57+
return crossed;
58+
}
59+
60+
uint32_t Count() const
61+
{
62+
return count;
63+
}
64+
65+
void Reset()
66+
{
67+
previous = T{ 0 };
68+
count = 0;
69+
}
70+
71+
private:
72+
T previous{ T{ 0 } };
73+
uint32_t count{ 0 };
74+
T hysteresis;
75+
};
76+
77+
template<typename T>
78+
class RmsEnvelope
79+
{
80+
static_assert(std::is_floating_point_v<T>, "RmsEnvelope supports floating-point types only");
81+
82+
public:
83+
explicit RmsEnvelope(T alpha)
84+
: alpha{ alpha }
85+
{}
86+
87+
OPTIMIZE_FOR_SPEED T Update(T x)
88+
{
89+
meanSquare += alpha * (x * x - meanSquare);
90+
return std::sqrt(meanSquare);
91+
}
92+
93+
void Reset(T value = T{ 0 })
94+
{
95+
meanSquare = value;
96+
}
97+
98+
private:
99+
T alpha;
100+
T meanSquare{ T{ 0 } };
101+
};
102+
103+
#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD
104+
extern template class PeakHold<float>;
105+
extern template class ZeroCrossingCounter<float>;
106+
extern template class RmsEnvelope<float>;
107+
#endif
108+
}

‎numerical/analysis/test/CMakeLists.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,5 @@ target_sources(numerical.analysis_test PRIVATE
1212
TestDiscreteCosineTransform.cpp
1313
TestFastFourierTransformRadix2Impl.cpp
1414
TestPowerDensitySpectrum.cpp
15+
TestSignalDetectors.cpp
1516
)
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
#include "numerical/analysis/SignalDetectors.hpp"
2+
#include "numerical/math/Tolerance.hpp"
3+
#include "gmock/gmock.h"
4+
#include <cmath>
5+
#include <numbers>
6+
7+
namespace
8+
{
9+
class TestSignalDetectors : public ::testing::Test
10+
{
11+
public:
12+
analysis::PeakHold<float> peak{ 1.0f };
13+
analysis::ZeroCrossingCounter<float> zc{ 0.0f };
14+
analysis::RmsEnvelope<float> rms{ 0.25f };
15+
};
16+
}
17+
18+
TEST_F(TestSignalDetectors, peak_hold_latches_maximum)
19+
{
20+
EXPECT_NEAR(peak.Update(0.2f), 0.2f, math::Tolerance<float>());
21+
EXPECT_NEAR(peak.Update(0.5f), 0.5f, math::Tolerance<float>());
22+
EXPECT_NEAR(peak.Update(0.3f), 0.5f, math::Tolerance<float>());
23+
EXPECT_NEAR(peak.Update(0.1f), 0.5f, math::Tolerance<float>());
24+
}
25+
26+
TEST_F(TestSignalDetectors, peak_hold_decays_when_leaky)
27+
{
28+
analysis::PeakHold<float> leaky{ 0.5f };
29+
EXPECT_NEAR(leaky.Update(0.8f), 0.8f, math::Tolerance<float>());
30+
EXPECT_NEAR(leaky.Update(0.0f), 0.4f, math::Tolerance<float>());
31+
EXPECT_NEAR(leaky.Update(0.0f), 0.2f, math::Tolerance<float>());
32+
EXPECT_NEAR(leaky.Update(0.0f), 0.1f, math::Tolerance<float>());
33+
}
34+
35+
TEST_F(TestSignalDetectors, peak_hold_tracks_magnitude_not_sign)
36+
{
37+
EXPECT_NEAR(peak.Update(-0.9f), 0.9f, math::Tolerance<float>());
38+
EXPECT_NEAR(peak.Update(0.1f), 0.9f, math::Tolerance<float>());
39+
}
40+
41+
TEST_F(TestSignalDetectors, zero_crossing_counts_sign_changes)
42+
{
43+
zc.Update(1.0f);
44+
zc.Update(-1.0f);
45+
zc.Update(1.0f);
46+
zc.Update(-1.0f);
47+
EXPECT_EQ(zc.Count(), 3u);
48+
}
49+
50+
TEST_F(TestSignalDetectors, zero_crossing_hysteresis_rejects_noise)
51+
{
52+
analysis::ZeroCrossingCounter<float> noisy{ 0.1f };
53+
noisy.Update(0.02f);
54+
noisy.Update(-0.02f);
55+
noisy.Update(0.02f);
56+
EXPECT_EQ(noisy.Count(), 0u);
57+
}
58+
59+
TEST_F(TestSignalDetectors, rms_envelope_converges_to_true_rms)
60+
{
61+
analysis::RmsEnvelope<float> r{ 0.1f };
62+
constexpr int fs{ 48000 };
63+
constexpr int freq{ 1000 };
64+
constexpr int period{ fs / freq };
65+
constexpr int warmup{ 5000 };
66+
constexpr float amplitude{ 0.5f * 1.41421356f };
67+
for (int i = 0; i < warmup; ++i)
68+
r.Update(amplitude * std::sin(std::numbers::pi_v<float> * 2.0f * static_cast<float>(freq) * static_cast<float>(i) / static_cast<float>(fs)));
69+
float sum{ 0.0f };
70+
for (int i = 0; i < period; ++i)
71+
sum += r.Update(amplitude * std::sin(std::numbers::pi_v<float> * 2.0f * static_cast<float>(freq) * static_cast<float>(warmup + i) / static_cast<float>(fs)));
72+
EXPECT_NEAR(sum / static_cast<float>(period), 0.5f, 1e-2f);
73+
}
74+
75+
TEST_F(TestSignalDetectors, rms_dc_input_returns_magnitude)
76+
{
77+
analysis::RmsEnvelope<float> r{ 0.25f };
78+
float result{ 0.0f };
79+
for (int i = 0; i < 200; ++i)
80+
result = r.Update(0.4f);
81+
EXPECT_NEAR(result, 0.4f, 1e-2f);
82+
}
83+
84+
TEST_F(TestSignalDetectors, reset_clears_all_state)
85+
{
86+
peak.Update(1.0f);
87+
zc.Update(1.0f);
88+
zc.Update(-1.0f);
89+
rms.Update(1.0f);
90+
91+
peak.Reset();
92+
zc.Reset();
93+
rms.Reset();
94+
95+
EXPECT_NEAR(peak.Update(0.0f), 0.0f, math::Tolerance<float>());
96+
EXPECT_EQ(zc.Count(), 0u);
97+
EXPECT_NEAR(rms.Update(0.0f), 0.0f, math::Tolerance<float>());
98+
}

‎roadmap/analysis/SignalDetectors/explanation.md‎

Lines changed: 0 additions & 31 deletions
This file was deleted.

0 commit comments

Comments
 (0)