www.mooseframework.org
LeastSquaresFitBase.C
Go to the documentation of this file.
1 //* This file is part of the MOOSE framework
2 //* https://www.mooseframework.org
3 //*
4 //* All rights reserved, see COPYRIGHT for full restrictions
5 //* https://github.com/idaholab/moose/blob/master/COPYRIGHT
6 //*
7 //* Licensed under LGPL 2.1, please see LICENSE for details
8 //* https://www.gnu.org/licenses/lgpl-2.1.html
9 
10 #include "LeastSquaresFitBase.h"
11 #include "MooseError.h"
12 
13 #include "libmesh/int_range.h"
14 // Ignore warnings from Eigen related to deprecated declarations (C++17)
15 #include "libmesh/ignore_warnings.h"
16 #include <Eigen/Dense>
17 #include "libmesh/restore_warnings.h"
18 
20 
21 LeastSquaresFitBase::LeastSquaresFitBase(const std::vector<Real> & x, const std::vector<Real> & y)
22  : _x(x), _y(y)
23 {
24 }
25 
26 void
27 LeastSquaresFitBase::setVariables(const std::vector<Real> & x, const std::vector<Real> & y)
28 {
29  _x = x;
30  _y = y;
31 }
32 
33 void
35 {
36  if (_x.empty())
37  mooseError("Empty variables in LeastSquaresFitBase. x and y must be set in the constructor or "
38  "using setVariables(x, y)");
39 
40  fillMatrix();
42 }
43 
44 void
46 {
47  _coeffs.resize(_num_coeff);
48 
49  typedef Eigen::Matrix<Real, Eigen::Dynamic, 1> SolveVec;
50  auto b = Eigen::Map<SolveVec, Eigen::Unaligned>(_y.data(), _y.size());
51  auto x = Eigen::Map<SolveVec, Eigen::Unaligned>(_coeffs.data(), _num_coeff);
52  typedef Eigen::Matrix<Real, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> SolveMatrix;
53  auto A = Eigen::Map<SolveMatrix, Eigen::Unaligned>(_matrix.data(), _y.size(), _num_coeff);
54  x = A.colPivHouseholderQr().solve(b);
55 }
56 
57 unsigned int
59 {
60  return _x.size();
61 }
62 
63 const std::vector<Real> &
65 {
66  return _coeffs;
67 }
void doLeastSquares()
Wrapper for the LAPACK dgels function.
void mooseError(Args &&... args)
Emit an error message with the given stringified, concatenated args and terminate the application...
Definition: MooseError.h:284
virtual void fillMatrix()=0
Helper function that creates the matrix necessary for the least squares algorithm.
unsigned int getSampleSize()
Size of the array holding the points.
unsigned int _num_coeff
The number of coefficients.
std::vector< Real > _y
Dependent variable.
virtual void generate()
Generate the fit.
std::vector< Real > _x
Independent variable.
void setVariables(const std::vector< Real > &x, const std::vector< Real > &y)
const std::vector< Real > & getCoefficients()
Const reference to the vector of coefficients of the least squares fit.
std::vector< Real > _coeffs
Vector of coefficients of the least squares fit.
std::vector< Real > _matrix
Basis functions evaluated at each independent variable (note: actually a vector)