sablib
Loading...
Searching...
No Matches
moving_average.cpp
Go to the documentation of this file.
1
6#define _USE_MATH_DEFINES
7#include <cmath>
8#include "moving_average.h"
9
10namespace sablib {
11
12//
13// Implementation of MovingAverage() function, std::vector<double> version
14//
15const std::vector<double> MovingAverage(const std::vector<double> & y, const unsigned int n)
16{
17 Eigen::VectorXd yy = Eigen::VectorXd::Map(y.data(), y.size());
18
19 Eigen::VectorXd result = MovingAverage(yy, n);
20
21 std::vector<double> result_y(result.size());
22 Eigen::VectorXd::Map(result_y.data(), result_y.size()) = result;
23
24 return result_y;
25}
26
27//
28// Implementation of WeightedMovingAverage() function, std::vector<double> version
29//
30const std::vector<double> WeightedMovingAverage(const std::vector<double> & y, const std::vector<double> & w)
31{
32 Eigen::VectorXd yy = Eigen::VectorXd::Map(y.data(), y.size());
33 Eigen::VectorXd ww = Eigen::VectorXd::Map(w.data(), w.size());
34
35 Eigen::VectorXd result = WeightedMovingAverage(yy, ww);
36
37 std::vector<double> result_y(result.size());
38 Eigen::VectorXd::Map(result_y.data(), result_y.size()) = result;
39
40 return result_y;
41}
42
43//
44// Implementation of GaussianKernel() function
45//
46const std::vector<double> GaussianKernel(const unsigned int n, const double sigma)
47{
48 if(n == 0) {
49 throw std::invalid_argument("GaussianKernel(): n is zero.");
50 }
51
52 if(sigma <= 0) {
53 throw std::invalid_argument("GaussianKernel(): non-positive sigma value is given.");
54 }
55
56 int points = 2 * n + 1;
57 std::vector<double> result(points);
58
59 double coeff = 1.0 / (std::sqrt(2 * M_PI) * sigma);
60 auto gaussian = [&](const double xx) {
61 double t = xx / sigma;
62 return coeff * std::exp(-t * t / 2);
63 };
64
65 double sum = 0;
66 for(int i = -(int)n; i <= (int)n; i++) {
67 result[i + n] = gaussian(i);
68 sum += result[i + n];
69 }
70
71 for(int i = 0; i < points; i++) {
72 result[i] /= sum;
73 }
74
75 return result;
76}
77
78}; // namespace sablib
const std::vector< double > GaussianKernel(const unsigned int n, const double sigma)
Generates a Gaussian kernel.
const std::vector< double > WeightedMovingAverage(const std::vector< double > &y, const std::vector< double > &w)
Calculates the weighted moving average of the input signal (std::vector<double> version).
const std::vector< double > MovingAverage(const std::vector< double > &y, const unsigned int n)
Calculates the simple moving average of the input signal (std::vector<double> version).
Smoothing using simple/weighted moving average.