diff --git a/README.md b/README.md index 5fa99af6..d13546af 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 | +| [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 | diff --git a/ROADMAP.md b/ROADMAP.md index 500d6847..c3663df4 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -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` | ★★☆☆☆ | diff --git a/doc/analysis/README.md b/doc/analysis/README.md index ecc005b7..dde16fbb 100644 --- a/doc/analysis/README.md +++ b/doc/analysis/README.md @@ -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 diff --git a/doc/analysis/SignalDetectors.md b/doc/analysis/SignalDetectors.md new file mode 100644 index 00000000..6695d9ea --- /dev/null +++ b/doc/analysis/SignalDetectors.md @@ -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/). diff --git a/numerical/analysis/CMakeLists.txt b/numerical/analysis/CMakeLists.txt index 8194db45..b4f37df9 100644 --- a/numerical/analysis/CMakeLists.txt +++ b/numerical/analysis/CMakeLists.txt @@ -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) diff --git a/numerical/analysis/SignalDetectors.cpp b/numerical/analysis/SignalDetectors.cpp new file mode 100644 index 00000000..b56289bf --- /dev/null +++ b/numerical/analysis/SignalDetectors.cpp @@ -0,0 +1,8 @@ +#include "numerical/analysis/SignalDetectors.hpp" + +namespace analysis +{ + template class PeakHold; + template class ZeroCrossingCounter; + template class RmsEnvelope; +} diff --git a/numerical/analysis/SignalDetectors.hpp b/numerical/analysis/SignalDetectors.hpp new file mode 100644 index 00000000..0f82ddae --- /dev/null +++ b/numerical/analysis/SignalDetectors.hpp @@ -0,0 +1,108 @@ +#pragma once + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC optimize("O3", "fast-math") +#endif + +#include "numerical/math/CompilerOptimizations.hpp" +#include +#include +#include + +namespace analysis +{ + template + class PeakHold + { + static_assert(std::is_floating_point_v, "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 + class ZeroCrossingCounter + { + static_assert(std::is_floating_point_v, "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 + class RmsEnvelope + { + static_assert(std::is_floating_point_v, "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; + extern template class ZeroCrossingCounter; + extern template class RmsEnvelope; +#endif +} diff --git a/numerical/analysis/test/CMakeLists.txt b/numerical/analysis/test/CMakeLists.txt index 43dee991..7ed99d0b 100644 --- a/numerical/analysis/test/CMakeLists.txt +++ b/numerical/analysis/test/CMakeLists.txt @@ -12,4 +12,5 @@ target_sources(numerical.analysis_test PRIVATE TestDiscreteCosineTransform.cpp TestFastFourierTransformRadix2Impl.cpp TestPowerDensitySpectrum.cpp + TestSignalDetectors.cpp ) diff --git a/numerical/analysis/test/TestSignalDetectors.cpp b/numerical/analysis/test/TestSignalDetectors.cpp new file mode 100644 index 00000000..5a4565ed --- /dev/null +++ b/numerical/analysis/test/TestSignalDetectors.cpp @@ -0,0 +1,98 @@ +#include "numerical/analysis/SignalDetectors.hpp" +#include "numerical/math/Tolerance.hpp" +#include "gmock/gmock.h" +#include +#include + +namespace +{ + class TestSignalDetectors : public ::testing::Test + { + public: + analysis::PeakHold peak{ 1.0f }; + analysis::ZeroCrossingCounter zc{ 0.0f }; + analysis::RmsEnvelope rms{ 0.25f }; + }; +} + +TEST_F(TestSignalDetectors, peak_hold_latches_maximum) +{ + EXPECT_NEAR(peak.Update(0.2f), 0.2f, math::Tolerance()); + EXPECT_NEAR(peak.Update(0.5f), 0.5f, math::Tolerance()); + EXPECT_NEAR(peak.Update(0.3f), 0.5f, math::Tolerance()); + EXPECT_NEAR(peak.Update(0.1f), 0.5f, math::Tolerance()); +} + +TEST_F(TestSignalDetectors, peak_hold_decays_when_leaky) +{ + analysis::PeakHold leaky{ 0.5f }; + EXPECT_NEAR(leaky.Update(0.8f), 0.8f, math::Tolerance()); + EXPECT_NEAR(leaky.Update(0.0f), 0.4f, math::Tolerance()); + EXPECT_NEAR(leaky.Update(0.0f), 0.2f, math::Tolerance()); + EXPECT_NEAR(leaky.Update(0.0f), 0.1f, math::Tolerance()); +} + +TEST_F(TestSignalDetectors, peak_hold_tracks_magnitude_not_sign) +{ + EXPECT_NEAR(peak.Update(-0.9f), 0.9f, math::Tolerance()); + EXPECT_NEAR(peak.Update(0.1f), 0.9f, math::Tolerance()); +} + +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 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 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 * 2.0f * static_cast(freq) * static_cast(i) / static_cast(fs))); + float sum{ 0.0f }; + for (int i = 0; i < period; ++i) + sum += r.Update(amplitude * std::sin(std::numbers::pi_v * 2.0f * static_cast(freq) * static_cast(warmup + i) / static_cast(fs))); + EXPECT_NEAR(sum / static_cast(period), 0.5f, 1e-2f); +} + +TEST_F(TestSignalDetectors, rms_dc_input_returns_magnitude) +{ + analysis::RmsEnvelope 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()); + EXPECT_EQ(zc.Count(), 0u); + EXPECT_NEAR(rms.Update(0.0f), 0.0f, math::Tolerance()); +} diff --git a/roadmap/analysis/SignalDetectors/explanation.md b/roadmap/analysis/SignalDetectors/explanation.md deleted file mode 100644 index 9f3397aa..00000000 --- a/roadmap/analysis/SignalDetectors/explanation.md +++ /dev/null @@ -1,31 +0,0 @@ -# Signal Detectors — Overview - -## What it is -A trio of tiny feature extractors that summarise a stream without storing it: a **peak-hold** -(running maximum with optional decay), a **zero-crossing counter** (sign-change events), and an -**RMS envelope** (a one-pole smoother running on `x²`). - -## Why it matters (embedded) -These are the cheapest possible front-ends for higher-level logic — each is O(1) time and O(1) -memory. They power VU meters, activity/onset detection, crude pitch/frequency estimation, clipping -alarms, and wake-on-event triggers on parts with no room for an FFT. - -## How it works (intuition) -- **Peak-hold** latches the largest magnitude seen; a `decay < 1` slowly releases it so a meter - falls back after transients. -- **Zero-crossing** counting approximates fundamental frequency — a sinusoid crosses zero twice per - period, so `f ≈ crossings / (2·T)`. A hysteresis band stops noise near zero from over-counting. -- **RMS envelope** passes `x²` through the item-1 one-pole low-pass and takes the square root, - yielding a smooth estimate of signal power/loudness. - -## Key parameters -- **decay** (peak-hold) ∈ (0, 1] — 1 latches forever, smaller releases faster. -- **hysteresis** (zero-crossing) — dead-band amplitude a crossing must exceed. -- **alpha** (RMS) — one-pole smoothing factor; smaller = smoother, slower envelope. - -## Reference -R. G. Lyons, *Understanding Digital Signal Processing*, 3rd ed., Pearson, 2011. - -## See also -`ExponentialMovingAverage` (the one-pole the RMS envelope reuses), `math::Statistics`, -`GoertzelAlgorithm` (precise single-tone detection). diff --git a/roadmap/analysis/SignalDetectors/implementation.md b/roadmap/analysis/SignalDetectors/implementation.md deleted file mode 100644 index 3abb9ce6..00000000 --- a/roadmap/analysis/SignalDetectors/implementation.md +++ /dev/null @@ -1,93 +0,0 @@ -# Signal Detectors — Implementation Pseudocode - -> Roadmap ref: #5 (Tier 1) · Target: `numerical/analysis` · Namespace `analysis` · Type: `float` (templated on `T`, instantiated for `float` only) - -## Data structures - -Three small, independent, composable detectors sharing a scalar-state style. - -``` -template # static_assert(std::is_floating_point_v); instantiated for float -class PeakHold: - T peak # running max magnitude - T decay # per-sample leak toward 0 in (0, 1] - -template # static_assert(std::is_floating_point_v); instantiated for float -class ZeroCrossingCounter: - T previous # last sample, for sign compare - uint32_t count # crossings since Reset - T hysteresis # dead-band to reject noise flips - -template # static_assert(std::is_floating_point_v); instantiated for float -class RmsEnvelope: - T alpha # one-pole smoothing factor on x^2 - T meanSquare # state = E[x^2] -``` - -## Interface - -``` -# PeakHold -PeakHold(T decay = 1) -T Update(T x) # hot path, returns held peak -void Reset() - -# ZeroCrossingCounter -ZeroCrossingCounter(T hysteresis = 0) -bool Update(T x) # hot path, true when a crossing occurs -uint32_t Count() const -void Reset() - -# RmsEnvelope -RmsEnvelope(T alpha) -T Update(T x) # hot path, returns sqrt(meanSquare) -void Reset(T value = 0) -``` - -## Algorithm (pseudocode) - -``` -function PeakHold.Update(x): # OPTIMIZE_FOR_SPEED - m = abs(x) - peak = max(m, peak * decay) # leak first, then admit new peak - return peak - -function ZeroCrossingCounter.Update(x): # OPTIMIZE_FOR_SPEED - crossed = (sign(x) != sign(previous)) and (abs(x) > hysteresis) - if crossed: count += 1 - previous = x - return crossed - -function RmsEnvelope.Update(x): # OPTIMIZE_FOR_SPEED - meanSquare += alpha * (x*x - meanSquare) # one-pole on x^2 (reuses item 1) - return sqrt(meanSquare) -``` - -## Complexity & memory - -- Time: `O(1)` per sample per detector (peak: 1 mul + max; ZC: 1 compare; RMS: 1 MAC + 1 sqrt). -- Memory: `O(1)` — one to two state words each; no buffers, no window. - -## Numerical / embedded notes - -- `decay = 1` is a true infinite peak-hold; `decay < 1` gives an exponential release (VU-meter feel). -- Zero-crossing `sign()` must treat `0` consistently; the `hysteresis` dead-band stops a signal - hovering near zero from inflating the count. Fundamental frequency ≈ `count / (2·window·Ts)`. -- `RmsEnvelope` feeds the item-1 one-pole with `x²` and returns the square root of the smoothed - mean-square (reuses `ExponentialMovingAverage`). -- 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/SignalDetectors.hpp` — `#pragma once` → - `#pragma GCC optimize("O3","fast-math")`, `OPTIMIZE_FOR_SPEED` on each `Update`, and - `extern template class PeakHold; ZeroCrossingCounter; RmsEnvelope;` - under `#ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD`. -- Coverage: `numerical/analysis/SignalDetectors.cpp` → - `template class PeakHold; template class ZeroCrossingCounter; template class RmsEnvelope;` -- Test: `numerical/analysis/test/TestSignalDetectors.cpp` -- Doc: `doc/analysis/SignalDetectors.md` (expand to follow `doc/TEMPLATE.md`) -- CMake: `.hpp` → `target_sources`; `.cpp` → `numerical_add_coverage_sources`; - `TestSignalDetectors.cpp` → the `_test` target. -- Generic pattern: see `roadmap/README.md` → "Deployment shape". diff --git a/roadmap/analysis/SignalDetectors/tests.md b/roadmap/analysis/SignalDetectors/tests.md deleted file mode 100644 index 3bf69ecd..00000000 --- a/roadmap/analysis/SignalDetectors/tests.md +++ /dev/null @@ -1,62 +0,0 @@ -# Signal Detectors — Unit Test Plan (Pseudocode) - -> GoogleTest · `TEST_F` (`float`) · `StrictMock` only · no heap. - -## Fixture - -``` -class TestSignalDetectors : public ::testing::Test: - PeakHold peak{ 1.0f } # no decay by default - ZeroCrossingCounter zc{ 0.0f } - RmsEnvelope rms{ 0.25f } -# each case below is a TEST_F(TestSignalDetectors, ) -``` - -## Test cases (Arrange / Act / Assert) - -``` -peak_hold_latches_maximum: - Arrange: feed [0.2, 0.5, 0.3, 0.1] - Act: collect outputs - Assert: output stays at 0.5 after the peak (decay = 1) - -peak_hold_decays_when_leaky: - Arrange: decay = 0.5, feed [0.8, 0, 0, 0] - Assert: peak ≈ [0.8, 0.4, 0.2, 0.1] - -peak_hold_tracks_magnitude_not_sign: - Arrange: feed [-0.9, 0.1] - Assert: first output == 0.9 - -zero_crossing_counts_sign_changes: - Arrange: feed [1, -1, 1, -1] - Assert: Count() == 3 - -zero_crossing_hysteresis_rejects_noise: - Arrange: hysteresis = 0.1, feed dither [0.02, -0.02, 0.02] - Assert: Count() == 0 - -rms_envelope_converges_to_true_rms: - Arrange: alpha = 0.1, feed a sine of RMS 0.5 for many samples - Assert: steady-state output ≈ 0.5 (±tol) - -rms_dc_input_returns_magnitude: - Arrange: feed constant 0.4 - Assert: output → 0.4 - -reset_clears_all_state: - Arrange: run samples, Reset() - Assert: peak == 0, Count() == 0, rms == 0 -``` - -## Reference vectors - -- Peak-hold, `decay = 0.5`, impulse `0.8` ⇒ `0.8·0.5^n`. -- Full-scale sine of amplitude `A` ⇒ RMS envelope → `A/√2`. -- Square wave of period `P` samples ⇒ 2 crossings per period. - -## Edge cases - -- All-zero input: no crossings, RMS stays 0, peak stays 0. -- Constant-sign ramp: `ZeroCrossingCounter` reports 0. -- Single-sample and alternating ±full-scale sequences.