sablib
Loading...
Searching...
No Matches
polynomial.cpp
Go to the documentation of this file.
1
6
7#include <Eigen/Eigen>
8
9#include "polynomial.h"
10
11namespace sablib {
12
13//
14// Implementation of BaselineLinear() function
15//
16std::vector<double> BaselineLinear(std::vector<double> & y, const unsigned int index1, const unsigned int index2)
17{
18 if(y.size() == 0) {
19 throw std::invalid_argument("BaselineLinear(): the length of y is zero.");
20 }
21
22 if(index1 >= index2 || y.size() <= index1 || y.size() <= index2) {
23 throw std::invalid_argument("BaselineLinear(): illegal indices");
24 }
25
26 std::vector<double> result = y;
27 double m = (y[index2] - y[index1]) / (index2 - index1);
28
29 auto f = [&](const unsigned int x) {
30 return m * (x - index1) + y[index1];
31 };
32
33 for(unsigned int x = index1; x <= index2; x++) {
34 result[x] = f(x);
35 }
36
37 return result;
38}
39
40//
41// Implementation of BaselinePolynomial() function
42//
43std::vector<double> BaselinePolynomial(
44 std::vector<double> & y, const unsigned int polyorder, const std::vector<unsigned int> & indices
45)
46{
47 if(y.size() == 0 || indices.size() == 0) {
48 throw std::invalid_argument("BaselinePolynomial(): the length of y or indices is zero.");
49 }
50
51 if(y.size() < indices.size()) {
52 throw std::invalid_argument("BaselinePolynomial(); the length of indices is larger than y.");
53 }
54
55 if(polyorder >= indices.size()) {
56 throw std::invalid_argument("BaselinePolynomial(): Too few indices.");
57 }
58
59 double max_index = y.size() - 1;
60 std::vector<unsigned int> sorted_indices = indices;
61 Eigen::VectorXd xx(indices.size()), yy(indices.size());
62
63 std::sort(sorted_indices.begin(), sorted_indices.end());
64
65 for(unsigned int i = 0; i < indices.size(); i++) {
66 xx(i) = sorted_indices[i] / max_index;
67 yy(i) = y[sorted_indices[i]];
68 }
69
70 Eigen::VectorXd coefficients = PolyFit(xx, yy, polyorder);
71
72 std::vector<double> result = y;
73
74 for(unsigned int i = sorted_indices[0]; i < sorted_indices.back(); i++) {
75 double x = i / max_index;
76 double fx = 0;
77 double k = 1;
78
79 for(int j = 0; j < coefficients.size(); j++) {
80 fx += coefficients(j) * k;
81 k *= x;
82 }
83
84 result[i] = fx;
85 }
86
87 return result;
88}
89
90}; // namespace sablib
const Derived::PlainObject PolyFit(const Eigen::MatrixBase< Derived > &x, const Eigen::MatrixBase< Derived > &y, const unsigned int polyorder)
Fits a polynomial of a specified order to the given data points.
Definition polyfit.h:29
std::vector< double > BaselineLinear(std::vector< double > &y, const unsigned int index1, const unsigned int index2)
Performs baseline estimation with a linear line between two points.
std::vector< double > BaselinePolynomial(std::vector< double > &y, const unsigned int polyorder, const std::vector< unsigned int > &indices)
Performs baseline estimation by fitting a polynomial to specified points.
Baseline estimation with polynomial line.