4#ifndef GREM_CORE_STATISTICS_HPP
5#define GREM_CORE_STATISTICS_HPP
44 constexpr void reset(T newValue = {}) {
58 template <
typename Coefficient>
59 constexpr T
update(T newSignalValue, Coefficient alpha) {
60 return value = newSignalValue * alpha + value * (Coefficient{1} - alpha);
68 [[nodiscard]]
constexpr T
get()
const {
82template <
typename T, std::
size_t N>
99 sampleSumOfSquares = SquaredT{};
109 if (sampleBuffer.size() >= N) {
110 const T expiredSample = sampleBuffer.front();
111 sampleSum -= expiredSample;
112 sampleSumOfSquares -= expiredSample * expiredSample;
113 sampleBuffer.pop_front();
115 sampleBuffer.push_back(newSample);
116 sampleSum += newSample;
117 sampleSumOfSquares += newSample * newSample;
126 const std::size_t sampleCount = sampleBuffer.size();
127 const T mean = (sampleCount <= 1) ? sampleSum : sampleSum / sampleCount;
128 const SquaredT variance = (sampleCount <= 1) ? SquaredT{} : (sampleSumOfSquares - (sampleSum * sampleSum) / sampleCount) / (sampleCount - 1);
129 const T standardDeviation =
sqrt(variance);
130 return {.mean = mean, .standardDeviation = standardDeviation};
145 using SquaredT = std::remove_cvref_t<
decltype(T{} * T{})>;
147 InplaceDoubleEndedQueue<T, N> sampleBuffer{};
149 SquaredT sampleSumOfSquares{};
constexpr ExponentialMovingAverage(T value)
Construct an exponential moving average with a specific initial value.
Definition statistics.hpp:36
constexpr void reset(T newValue={})
Reset the exponential moving average to a specific value.
Definition statistics.hpp:44
constexpr T get() const
Get the current exponential moving average value.
Definition statistics.hpp:68
constexpr ExponentialMovingAverage()=default
Default-construct an exponential moving average.
constexpr T update(T newSignalValue, Coefficient alpha)
Update the exponential moving average given the next discrete input signal sample value.
Definition statistics.hpp:59
Sliding window of a discrete-time input signal.
Definition statistics.hpp:83
void clear() noexcept
Clear the sliding window of all samples.
Definition statistics.hpp:96
Statistics getStatistics() const noexcept
Calculate the statistics of the current samples in the sliding window.
Definition statistics.hpp:125
auto getSamples() const noexcept
Get the samples in the sliding window.
Definition statistics.hpp:140
void update(T newSample) noexcept
Push a new sample into the sliding window, popping the oldest sample first if the window is at its ma...
Definition statistics.hpp:108
Definition Subrange.hpp:88
@ T
't'
Definition keyboard.hpp:90
GREM_ALWAYS_INLINE constexpr T GREM_VECTORCALL sqrt(T a)
Get the square root of a value.
Definition math.hpp:1114
Statistics of the sliding window.
Definition statistics.hpp:88
T mean
Mean (average) of all samples in the window.
Definition statistics.hpp:89
T standardDeviation
Standard deviation of all samples in the window.
Definition statistics.hpp:90