MySQL 26.10.0
Source Code Documentation
fx_stats_util.h
Go to the documentation of this file.
1/* Copyright (c) 2025, 2026, Oracle and/or its affiliates.
2
3This program is free software; you can redistribute it and/or modify
4it under the terms of the GNU General Public License, version 2.0,
5as published by the Free Software Foundation.
6
7This program is designed to work with certain software (including
8but not limited to OpenSSL) that is licensed under separate terms,
9as designated in a particular file or component or in included license
10documentation. The authors of MySQL hereby grant you an additional
11permission to link the program and your derivative works with the
12separately licensed software that they have either included with
13the program or referenced in the documentation.
14
15This program is distributed in the hope that it will be useful,
16but WITHOUT ANY WARRANTY; without even the implied warranty of
17MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18GNU General Public License, version 2.0, for more details.
19
20You should have received a copy of the GNU General Public License
21along with this program; if not, write to the Free Software
22Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
23
24#pragma once
25
26#include <cmath> // std::sqrt
27#include <cstdint> // uint64_t
28#include <vector>
29
30#include "fx_sample.h" // Sample, Series
31
32/**
33 @brief Compute a modulo with a non-negative result ("positive modulo").
34
35 In C++, the % operator can yield negative remainders if the dividend is
36 negative, which is unsuitable for indexing arrays. This helper ensures the
37 result is always in the range [0, m-1].
38
39 @param a The integer value (can be negative).
40 @param m The modulus (must be positive).
41 @return int64_t The remainder of a divided by m, guaranteed non-negative.
42 @note Commonly used to wrap seasonal indices in Holt-Winters, ensuring
43 valid access into the seasonal component array.
44 @code
45 postmod(5, 4); // returns 1
46 postmod(-1, 4); // returns 3
47 postmod(-5, 4); // returns 3
48 @endcode
49*/
50int64_t postmod(int64_t a, int64_t m);
51
52#if 0
53// Variants for use with advanced forecasting features
54/**
55 @brief Compute the arithmetic mean of a subsequence of samples.
56 @param values Vector of double values
57 @param lo Inclusive start index within the series.
58 @param hi Inclusive end index within the series.
59 @return double The average value of y[lo..hi].
60
61 @warning No bounds checking: caller must ensure 0 <= lo <= hi < series.size().
62 @note Used for initializing Holt-Winters state (level and detrended season).
63*/
64double mean_average(const std::vector<double> &values, int lo, int hi);
65
66/**
67 @brief Compute the arithmetic mean of a subsequence of samples.
68 @param values Vector of double values
69 @return double The average value of y[lo..hi].
70
71 @warning No bounds checking: caller must ensure 0 <= lo <= hi < series.size().
72 @note Used for initializing Holt-Winters state (level and detrended season).
73*/
74double mean_average(const std::vector<double> &values);
75#endif
76
77/**
78 @brief Compute the arithmetic mean of a subsequence of samples.
79 @param series The full time series (vector of samples).
80 @param lo Inclusive start index within the series.
81 @param hi Inclusive end index within the series.
82 @return The mean for the inclusive range [lo, hi], or 0.0 if the range is
83 invalid.
84 @note Used for initializing Holt-Winters state (level and detrended season).
85*/
86double mean_average(const Series &series, int lo, int hi);
87
88/**
89 @struct Welford_Stats
90 @brief Maintains running statistics for a stream of values using Welford's
91 online algorithm.
92
93 This struct provides a way to calculate the mean and variance of a dataset
94 without storing the entire dataset in memory. It is suitable for large or
95 streaming datasets.
96 The statistics are updated incrementally as new values are added using the
97 @ref add method.
98
99*/
101 uint64_t count{0}; ///< Number of values processed so far
102 double mean{0.0}; ///< Current mean of the values
103 double m2{0.0}; ///< Sum of squared deviations from the mean
104
105 /**
106 @brief Adds a new value to the statistics.
107 @param x The new value to add.
108 @note add() updates running statistics online (count/mean/M2) one residual
109 at a time, and sigma() returns the stddev when needed. This avoids
110 having to store all residuals and then compute the stddev.
111 */
112 void add(double x) {
113 ++count;
114 double d = x - mean;
115 mean += d / count;
116 m2 += d * (x - mean);
117 }
118
119 /**
120 @brief Checks if the statistics are ready (i.e., more than one value has
121 been processed).
122 @return True if the statistics are ready, false otherwise.
123 */
124 [[nodiscard]] bool ready() const { return count > 1; }
125
126 /**
127 @brief Returns the sample standard deviation of the values.
128 @return The sample standard deviation.
129 */
130 [[nodiscard]] double sigma() const {
131 return ready() ? std::sqrt(m2 / (count - 1)) : 0.0;
132 }
133
134 /**
135 @brief Resets the statistics to their initial state.
136 */
137 void clear() {
138 count = 0;
139 mean = 0.0;
140 m2 = 0.0;
141 }
142};
143
144#if 0
145/**
146 @brief Compute the sample standard deviation using Welford's online algorithm.
147
148 Welford's algorithm is a method for calculating the variance and standard
149 deviation of a dataset. It avoids the need to store the entire dataset
150 in memory, and is suitable for large or streaming datasets.
151
152 @param values A vector of double values representing the dataset.
153 @return The sample standard deviation of the input values.
154
155 @note Returns 0.0 if the input vector contains fewer than two elements.
156 This is the batch/one-shot counterpart to Welford_Stats::add(), and will
157 be used in advanced forecasting features, e.g. aggregation, parameter
158 tuning, etc.
159 */
160double welford_stddev(const std::vector<double> &values);
161#endif
std::vector< Sample > Series
Definition: fx_sample.h:36
double mean_average(const Series &series, int lo, int hi)
Compute the arithmetic mean of a subsequence of samples.
Definition: fx_stats_util.cc:52
int64_t postmod(int64_t a, int64_t m)
Compute a modulo with a non-negative result ("positive modulo").
Definition: fx_stats_util.cc:63
Maintains running statistics for a stream of values using Welford's online algorithm.
Definition: fx_stats_util.h:100
uint64_t count
Number of values processed so far.
Definition: fx_stats_util.h:101
double mean
Current mean of the values.
Definition: fx_stats_util.h:102
bool ready() const
Checks if the statistics are ready (i.e., more than one value has been processed).
Definition: fx_stats_util.h:124
double sigma() const
Returns the sample standard deviation of the values.
Definition: fx_stats_util.h:130
double m2
Sum of squared deviations from the mean.
Definition: fx_stats_util.h:103
void add(double x)
Adds a new value to the statistics.
Definition: fx_stats_util.h:112
void clear()
Resets the statistics to their initial state.
Definition: fx_stats_util.h:137