22 #include <Eigen/Dense>
29 #include <boost/random/mersenne_twister.hpp>
31 #if BOOST_VERSION >= 104700
32 #include <boost/random/uniform_int_distribution.hpp>
34 #include <boost/random/uniform_int.hpp>
62 #if BOOST_VERSION >= 104700
64 boost::random::mt19937
gen;
73 typedef Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>
MatType;
76 typedef Eigen::Matrix<T, Eigen::Dynamic, 1>
VecType;
111 if(!
x.size() || !
y.size() || (
x.size() !=
y.size())) {
112 throw std::exception();
116 throw std::exception();
122 std::vector<T>
evalPoly(
const std::vector<T>& at) {
129 for(
int i = 0; i < at.size(); ++i)
134 y.setConstant(
pCoef(0, 0));
136 int nc =
pCoef.rows();
137 for(
int i = 1; i < nc; ++i)
138 y = (
x.cwiseProduct(
y)).array() +
pCoef(i, 0);
141 std::vector<T> out(
y.rows());
142 for(
int i = 0; i <
y.rows(); ++i)
151 throw std::exception();
163 throw std::exception();
176 if(
xM.rows() !=
yM.rows()) {
177 throw std::exception();
184 pCoef =
V.colPivHouseholderQr().solve(
yM.col(0));
187 pCoef =
V.fullPivHouseholderQr().solve(
yM.col(0));
190 pCoef =
V.jacobiSvd(Eigen::ComputeThinU |
200 if(
V.cols() !=
pCoef.rows() &&
yM.rows() !=
V.rows()) {
201 throw std::logic_error(
"Assert Polyfit l220");
205 Eigen::VectorXd diff = ((
V *
pCoef).array() -
yM.col(0).array());
206 for(
int i = 0; i < diff.rows(); ++i)
207 mse += pow(diff(i), 2);
213 if(N < 0 && s < 0 && (N <= s)) {
214 throw std::logic_error(
"Assert Polyfit l230");
218 while(
static_cast<int>(ind.size()) < s) {
219 ind.insert(dist(
gen));
225 std::vector<int> bestSubset;
226 Eigen::Matrix<T, Eigen::Dynamic, 1> bestCoef;
235 while(N > trialCount) {
237 std::set<int> indexSet;
242 throw std::logic_error(
"Assert Polyfit l265");
253 std::vector<int> inliers;
256 if(inliers.size() > bestSubset.size()) {
258 bestSubset = inliers;
262 double fracInliers =
static_cast<double>(inliers.size()) /
double(
yM.rows());
264 pNoOutliers = std::max(1e-9, pNoOutliers);
265 pNoOutliers = std::min(1 - 1e-9, pNoOutliers);
266 N =
log(1 - p) /
log(pNoOutliers);
279 int nVal =
static_cast<int>(indexSet.size());
284 std::set<int>::iterator it = indexSet.begin();
285 while(it != indexSet.end()) {
300 Eigen::VectorXd diff = ((
V *
pCoef).array() -
yM.col(0).array());
301 for(
int i = 0; i < diff.rows(); ++i) {
303 inliers.push_back(i);
305 return static_cast<int>(inliers.size());
310 xM.resize(
static_cast<int>(
x.size()), 1);
311 yM.resize(
static_cast<int>(
y.size()), 1);
313 for(
int i = 0; i < static_cast<int>(
x.size()); ++i)
316 for(
int i = 0; i < static_cast<int>(
y.size()); ++i)
324 for(
int i = 0; i <
xM.rows(); ++i)
328 for(
int i = 0; i <
xM.rows(); ++i)
334 template <
typename T>
336 out <<
"Polynomial coefficients for " << f.
getDegree() <<
"-nd order:" << std::endl;