Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[MegaLinter] reported by reviewdog 🐶

| Category | Description |
|--------------------------------------------------------------------|----------------------------------------------------------------------|
| [Analysis](doc/analysis/README.md) | FFT, Power Spectral Density, DCT, Window Functions, Signal Detectors |
| [Control Analysis](doc/control_analysis/README.md) | Frequency Response, Root Locus |
| [Controllers](doc/controllers/README.md) | PID, LQR, MPC |
| [Dynamics](doc/dynamics/README.md) | Euler-Lagrange, Newton-Euler, Recursive Newton-Euler, ABA |
| [Estimators](doc/estimators/README.md) | Linear Regression, Yule-Walker (offline), Recursive Least Squares (online) |

Original file line number Diff line number Diff line change
Expand Up @@ -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 |
| [Analysis](doc/analysis/README.md) | FFT, Power Spectral Density, DCT, Window Functions, Signal Detectors |
| [Control Analysis](doc/control_analysis/README.md) | Frequency Response, Root Locus |
| [Controllers](doc/controllers/README.md) | PID, LQR, MPC |
| [Dynamics](doc/dynamics/README.md) | Euler-Lagrange, Newton-Euler, Recursive Newton-Euler, ABA |
Expand Down
1 change: 0 additions & 1 deletion ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ Difficulty legend:
| 1 | Exponential Moving Average (one-pole) | `filters/passive` | ★☆☆☆☆ |
| 3 | Saturation / rate-limiter / slew blocks | `controllers` | ★☆☆☆☆ |
| 4 | Bang-bang / hysteresis (relay) controller | `controllers` | ★☆☆☆☆ |
| 5 | Peak / zero-crossing / RMS-envelope detectors | `analysis` | ★☆☆☆☆ |
| 6 | Median filter | `filters/passive` | ★★☆☆☆ |
| 7 | Feedforward / 2-DOF controller | `controllers` | ★★☆☆☆ |
| 8 | Alpha-beta / alpha-beta-gamma filter | `filters/active` | ★★☆☆☆ |
Expand Down
1 change: 1 addition & 0 deletions doc/analysis/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ Signal analysis algorithms for frequency-domain decomposition and spectral estim
| [Fast Fourier Transform](FastFourierTransform.md) | Efficient computation of the Discrete Fourier Transform using the Cooley-Tukey radix-2 algorithm |
| [Power Spectral Density](PowerDensitySpectrum.md) | Estimation of signal power distribution across frequencies using Welch's method |
| [Discrete Cosine Transform](DiscreteCosineTransform.md) | Real-valued frequency decomposition via cosine basis functions, computed through FFT |
| [Signal Detectors](SignalDetectors.md) | Peak hold, zero-crossing counter, and RMS envelope detectors for real-time signal monitoring |

## Sub-domains

Expand Down
102 changes: 102 additions & 0 deletions doc/analysis/SignalDetectors.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
# Signal Detectors

## Overview & Motivation

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.

## Mathematical Theory

### Peak Hold

Let $m_n = |x_n|$. With a decay coefficient $d \in (0, 1]$, the held peak evolves as:

$$p_n = \max(m_n,\; d \cdot p_{n-1})$$

When $d = 1$ the peak is infinite-hold; when $d < 1$ it releases exponentially toward zero between new maxima.

### Zero-Crossing Detection

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$:

$$\text{crossed}_n = \bigl(\operatorname{sgn}(x_n) \neq \operatorname{sgn}(x_{n-1})\bigr) \land \bigl(|x_n| > h\bigr)$$

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$:

$$f_0 \approx \frac{C}{2 \, N \, T_s}$$

### RMS Envelope

A one-pole IIR filter is applied to $x^2$, yielding an exponentially weighted mean-square:

$$E_n = E_{n-1} + \alpha\,(x_n^2 - E_{n-1}), \quad \alpha \in (0, 1)$$

The RMS envelope is:

$$r_n = \sqrt{E_n}$$

This is structurally identical to an exponential moving average applied to the squared signal.

## Complexity Analysis

| Detector | Time per sample | State words |
|-----------------------|--------------------------------|---------------------|
| Peak Hold | O(1) — 1 mul, 1 compare, 1 abs | 1 scalar |
| Zero-Crossing Counter | O(1) — 1 compare, 1 abs | 1 scalar + 1 uint32 |
| RMS Envelope | O(1) — 1 MAC + 1 sqrt | 1 scalar |

No buffers, no windows, no dynamic allocation.

## Step-by-Step Walkthrough

### Peak Hold (decay = 0.5), input = [0.8, 0, 0, 0]

| n | $x_n$ | $m_n$ | $d \cdot p_{n-1}$ | $p_n$ |
|---|-------|-------|-------------------|-------|
| 0 | 0.8 | 0.8 | 0.0 | 0.8 |
| 1 | 0.0 | 0.0 | 0.4 | 0.4 |
| 2 | 0.0 | 0.0 | 0.2 | 0.2 |
| 3 | 0.0 | 0.0 | 0.1 | 0.1 |

### Zero-Crossing Counter (h = 0), input = [1, -1, 1, -1]

| n | $x_n$ | prev sign | curr sign | crossed | C |
|---|-------|-----------|-----------|---------|---|
| 0 | +1 | 0 | + | no | 0 |
| 1 | -1 | + | - | yes | 1 |
| 2 | +1 | - | + | yes | 2 |
| 3 | -1 | + | - | yes | 3 |

### RMS Envelope ($\alpha = 0.25$), DC input $x = 0.4$

$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$.

## Pitfalls & Edge Cases

- Decay = 0 collapses the peak hold to the instantaneous absolute value; decay must be in $(0, 1]$ for meaningful hold behavior.
- 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.
- RMS Envelope with very small $\alpha$ responds slowly to changes in signal level; with $\alpha$ near 1 it approaches the instantaneous absolute value squared.
- The RMS detector returns 0 at initialization ($E_0 = 0$) and converges to the true RMS from below for positive-power signals.

## Variants & Generalizations

- 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.
- A bilateral zero-crossing counter can distinguish positive-going from negative-going edges, enabling half-wave frequency estimation.
- 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.

## Applications

- VU meters and compressor side-chains use peak hold with a configurable release time.
- Zero-crossing rate is a low-cost voiced/unvoiced classifier in speech processing.
- RMS envelope tracks AC signal levels in power monitoring, audio dynamic processing, and vibration analysis.
- All three detectors compose naturally into a signal statistics block for real-time diagnostics.

## Connections to Other Algorithms

- RMS Envelope is structurally equivalent to the Exponential Moving Average (EMA) filter applied to $x^2$, sharing the same one-pole recurrence.
- Zero-crossing detection is a degenerate form of edge detection in discrete sequences, related to sign-change detection in root-finding algorithms.

## References & Further Reading

- Zolzer, U., "DAFX: Digital Audio Effects", 2nd ed., Wiley, 2011 — Chapter 2 (dynamics processing, envelope followers).
- Proakis, J. & Manolakis, D., "Digital Signal Processing", 4th ed., Prentice Hall, 2007 — Section 1.4 (zero-crossing rate).
- Smith, J.O., "Introduction to Digital Filters with Audio Applications", W3K Publishing, 2007 — [online](https://ccrma.stanford.edu/~jos/filters/).
2 changes: 2 additions & 0 deletions numerical/analysis/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,13 @@ target_sources(numerical.analysis PRIVATE
FastFourierTransform.hpp
FastFourierTransformRadix2Impl.hpp
PowerDensitySpectrum.hpp
SignalDetectors.hpp
)

numerical_add_coverage_sources(numerical.analysis
FastFourierTransformRadix2Impl.cpp
PowerDensitySpectrum.cpp
SignalDetectors.cpp
)

add_subdirectory(test)
Expand Down
8 changes: 8 additions & 0 deletions numerical/analysis/SignalDetectors.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#include "numerical/analysis/SignalDetectors.hpp"

namespace analysis
{
template class PeakHold<float>;
template class ZeroCrossingCounter<float>;
template class RmsEnvelope<float>;
}
108 changes: 108 additions & 0 deletions numerical/analysis/SignalDetectors.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
#pragma once

#if defined(__GNUC__) || defined(__clang__)
#pragma GCC optimize("O3", "fast-math")
#endif

#include "numerical/math/CompilerOptimizations.hpp"
#include <cmath>
#include <cstdint>
#include <type_traits>

namespace analysis
{
template<typename T>
class PeakHold
{
static_assert(std::is_floating_point_v<T>, "PeakHold supports floating-point types only");

public:
explicit PeakHold(T decay = T{ 1 })
: decay{ decay }
{}

OPTIMIZE_FOR_SPEED T Update(T x)
{
T m{ std::abs(x) };
peak = (m > peak * decay) ? m : peak * decay;
return peak;
}

void Reset()
{
peak = T{ 0 };
}

private:
T peak{ T{ 0 } };
T decay;
};

template<typename T>
class ZeroCrossingCounter
{
static_assert(std::is_floating_point_v<T>, "ZeroCrossingCounter supports floating-point types only");

public:
explicit ZeroCrossingCounter(T hysteresis = T{ 0 })
: hysteresis{ hysteresis }
{}

OPTIMIZE_FOR_SPEED bool Update(T x)
{
bool crossed{ (previous < T{ 0 } ? x > T{ 0 } : x < T{ 0 }) && (std::abs(x) > hysteresis) };
if (crossed)
++count;
previous = x;
return crossed;
}

uint32_t Count() const
{
return count;
}

void Reset()
{
previous = T{ 0 };
count = 0;
}

private:
T previous{ T{ 0 } };
uint32_t count{ 0 };
T hysteresis;
};

template<typename T>
class RmsEnvelope
{
static_assert(std::is_floating_point_v<T>, "RmsEnvelope supports floating-point types only");

public:
explicit RmsEnvelope(T alpha)
: alpha{ alpha }
{}

OPTIMIZE_FOR_SPEED T Update(T x)
{
meanSquare += alpha * (x * x - meanSquare);
return std::sqrt(meanSquare);
}

void Reset(T value = T{ 0 })
{
meanSquare = value;
}

private:
T alpha;
T meanSquare{ T{ 0 } };
};

#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD
extern template class PeakHold<float>;
extern template class ZeroCrossingCounter<float>;
extern template class RmsEnvelope<float>;
#endif
}
1 change: 1 addition & 0 deletions numerical/analysis/test/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@ target_sources(numerical.analysis_test PRIVATE
TestDiscreteCosineTransform.cpp
TestFastFourierTransformRadix2Impl.cpp
TestPowerDensitySpectrum.cpp
TestSignalDetectors.cpp
)
98 changes: 98 additions & 0 deletions numerical/analysis/test/TestSignalDetectors.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
#include "numerical/analysis/SignalDetectors.hpp"
#include "numerical/math/Tolerance.hpp"
#include "gmock/gmock.h"
#include <cmath>
#include <numbers>

namespace
{
class TestSignalDetectors : public ::testing::Test
{
public:
analysis::PeakHold<float> peak{ 1.0f };
analysis::ZeroCrossingCounter<float> zc{ 0.0f };
analysis::RmsEnvelope<float> rms{ 0.25f };
};
}

TEST_F(TestSignalDetectors, peak_hold_latches_maximum)
{
EXPECT_NEAR(peak.Update(0.2f), 0.2f, math::Tolerance<float>());
EXPECT_NEAR(peak.Update(0.5f), 0.5f, math::Tolerance<float>());
EXPECT_NEAR(peak.Update(0.3f), 0.5f, math::Tolerance<float>());
EXPECT_NEAR(peak.Update(0.1f), 0.5f, math::Tolerance<float>());
}

TEST_F(TestSignalDetectors, peak_hold_decays_when_leaky)
{
analysis::PeakHold<float> leaky{ 0.5f };
EXPECT_NEAR(leaky.Update(0.8f), 0.8f, math::Tolerance<float>());
EXPECT_NEAR(leaky.Update(0.0f), 0.4f, math::Tolerance<float>());
EXPECT_NEAR(leaky.Update(0.0f), 0.2f, math::Tolerance<float>());
EXPECT_NEAR(leaky.Update(0.0f), 0.1f, math::Tolerance<float>());
}

TEST_F(TestSignalDetectors, peak_hold_tracks_magnitude_not_sign)
{
EXPECT_NEAR(peak.Update(-0.9f), 0.9f, math::Tolerance<float>());
EXPECT_NEAR(peak.Update(0.1f), 0.9f, math::Tolerance<float>());
}

TEST_F(TestSignalDetectors, zero_crossing_counts_sign_changes)
{
zc.Update(1.0f);
zc.Update(-1.0f);
zc.Update(1.0f);
zc.Update(-1.0f);
EXPECT_EQ(zc.Count(), 3u);
}

TEST_F(TestSignalDetectors, zero_crossing_hysteresis_rejects_noise)
{
analysis::ZeroCrossingCounter<float> noisy{ 0.1f };
noisy.Update(0.02f);
noisy.Update(-0.02f);
noisy.Update(0.02f);
EXPECT_EQ(noisy.Count(), 0u);
}

TEST_F(TestSignalDetectors, rms_envelope_converges_to_true_rms)
{
analysis::RmsEnvelope<float> r{ 0.1f };
constexpr int fs{ 48000 };
constexpr int freq{ 1000 };
constexpr int period{ fs / freq };
constexpr int warmup{ 5000 };
constexpr float amplitude{ 0.5f * 1.41421356f };
for (int i = 0; i < warmup; ++i)
r.Update(amplitude * std::sin(std::numbers::pi_v<float> * 2.0f * static_cast<float>(freq) * static_cast<float>(i) / static_cast<float>(fs)));
float sum{ 0.0f };
for (int i = 0; i < period; ++i)
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)));
EXPECT_NEAR(sum / static_cast<float>(period), 0.5f, 1e-2f);
}

TEST_F(TestSignalDetectors, rms_dc_input_returns_magnitude)
{
analysis::RmsEnvelope<float> r{ 0.25f };
float result{ 0.0f };
for (int i = 0; i < 200; ++i)
result = r.Update(0.4f);
EXPECT_NEAR(result, 0.4f, 1e-2f);
}

TEST_F(TestSignalDetectors, reset_clears_all_state)
{
peak.Update(1.0f);
zc.Update(1.0f);
zc.Update(-1.0f);
rms.Update(1.0f);

peak.Reset();
zc.Reset();
rms.Reset();

EXPECT_NEAR(peak.Update(0.0f), 0.0f, math::Tolerance<float>());
EXPECT_EQ(zc.Count(), 0u);
EXPECT_NEAR(rms.Update(0.0f), 0.0f, math::Tolerance<float>());
}
31 changes: 0 additions & 31 deletions roadmap/analysis/SignalDetectors/explanation.md

This file was deleted.

Loading
Loading