25 #include "Eigen/Eigenvalues"
27 #include "Eigen/Cholesky"
28 #include "boost/format.hpp"
32 #include "lsst/pex/exceptions.h"
33 #include "lsst/log/Log.h"
36 LOG_LOGGER _log = LOG_GET(
"afw.math.LeastSquares");
72 void setRank(Eigen::MatrixBase<D>
const& values) {
85 int toAdd = ~
state & desired;
89 fisher.selfadjointView<Eigen::Lower>().rankUpdate(
design.adjoint());
91 if (toAdd & FULL_FISHER_MATRIX) {
92 fisher.triangularView<Eigen::StrictlyUpper>() =
fisher.adjoint();
113 virtual void factor() = 0;
122 Impl(
int dimension_,
double threshold_ = std::numeric_limits<double>::epsilon())
132 explicit EigensystemSolver(
int dimension) : Impl(dimension),
_eig(dimension),
_svd(),
_tmp(dimension) {}
134 virtual void factor() {
135 ensure(LOWER_FISHER_MATRIX | RHS_VECTOR);
136 _eig.compute(fisher);
137 if (
_eig.info() == Eigen::Success) {
138 setRank(
_eig.eigenvalues().reverse());
139 LOGL_DEBUG(_log,
"SelfAdjointEigenSolver succeeded: dimension=%d, rank=%d", dimension, rank);
144 ensure(FULL_FISHER_MATRIX);
145 _svd.compute(fisher, Eigen::ComputeFullU);
146 setRank(
_svd.singularValues());
148 "SelfAdjointEigenSolver failed; falling back to equivalent SVD: dimension=%d, rank=%d",
153 virtual void updateRank() {
154 if (
_eig.info() == Eigen::Success) {
155 setRank(
_eig.eigenvalues().reverse());
157 setRank(
_svd.singularValues());
161 virtual void updateDiagnostic() {
164 pex::exceptions::LogicError,
165 "Cannot compute NORMAL_CHOLESKY diagnostic from NORMAL_EIGENSYSTEM factorization.");
167 if (
_eig.info() == Eigen::Success) {
168 diagnostic.asEigen() =
_eig.eigenvalues().reverse();
170 diagnostic.asEigen() =
_svd.singularValues();
173 diagnostic.asEigen<Eigen::ArrayXpr>() = diagnostic.asEigen<Eigen::ArrayXpr>().sqrt();
177 virtual void updateSolution() {
179 solution.asEigen().setZero();
182 if (
_eig.info() == Eigen::Success) {
183 _tmp.head(rank) =
_eig.eigenvectors().rightCols(rank).adjoint() * rhs;
184 _tmp.head(rank).array() /=
_eig.eigenvalues().tail(rank).array();
185 solution.asEigen() =
_eig.eigenvectors().rightCols(rank) *
_tmp.head(rank);
187 _tmp.head(rank) =
_svd.matrixU().leftCols(rank).adjoint() * rhs;
188 _tmp.head(rank).array() /=
_svd.singularValues().head(rank).array();
189 solution.asEigen() =
_svd.matrixU().leftCols(rank) *
_tmp.head(rank);
193 virtual void updateCovariance() {
195 covariance.asEigen().setZero();
198 if (
_eig.info() == Eigen::Success) {
199 covariance.asEigen() =
_eig.eigenvectors().rightCols(rank) *
200 _eig.eigenvalues().tail(rank).array().inverse().matrix().asDiagonal() *
201 _eig.eigenvectors().rightCols(rank).adjoint();
203 covariance.asEigen() =
_svd.matrixU().leftCols(rank) *
204 _svd.singularValues().head(rank).array().inverse().matrix().asDiagonal() *
205 _svd.matrixU().leftCols(rank).adjoint();
210 Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd>
_eig;
211 Eigen::JacobiSVD<Eigen::MatrixXd>
_svd;
215 class CholeskySolver :
public LeastSquares::Impl {
217 explicit CholeskySolver(
int dimension) : Impl(dimension, 0.0),
_ldlt(dimension) {}
219 virtual void factor() {
220 ensure(LOWER_FISHER_MATRIX | RHS_VECTOR);
221 _ldlt.compute(fisher);
224 virtual void updateRank() {}
226 virtual void updateDiagnostic() {
229 pex::exceptions::LogicError,
230 "Can only compute NORMAL_CHOLESKY diagnostic from NORMAL_CHOLESKY factorization.");
232 diagnostic.asEigen() =
_ldlt.vectorD();
235 virtual void updateSolution() { solution.asEigen() =
_ldlt.solve(rhs); }
237 virtual void updateCovariance() {
238 ndarray::EigenView<double, 2, 2> cov(covariance);
240 cov =
_ldlt.solve(cov);
247 class SvdSolver :
public LeastSquares::Impl {
249 explicit SvdSolver(
int dimension) : Impl(dimension),
_svd(),
_tmp(dimension) {}
251 virtual void factor() {
252 if (!(state & DESIGN_AND_DATA)) {
253 throw LSST_EXCEPT(pex::exceptions::InvalidParameterError,
254 "Cannot initialize DIRECT_SVD solver with normal equations.");
256 _svd.compute(design, Eigen::ComputeThinU | Eigen::ComputeThinV);
257 setRank(
_svd.singularValues());
258 LOGL_DEBUG(_log,
"Using direct SVD method; dimension=%d, rank=%d", dimension, rank);
261 virtual void updateRank() { setRank(
_svd.singularValues()); }
263 virtual void updateDiagnostic() {
264 switch (whichDiagnostic) {
266 diagnostic.asEigen<Eigen::ArrayXpr>() =
_svd.singularValues().array().square();
270 pex::exceptions::LogicError,
271 "Can only compute NORMAL_CHOLESKY diagnostic from DIRECT_SVD factorization.");
273 diagnostic.asEigen() =
_svd.singularValues();
278 virtual void updateSolution() {
280 solution.asEigen().setZero();
283 _tmp.head(rank) =
_svd.matrixU().leftCols(rank).adjoint() * data;
284 _tmp.head(rank).array() /=
_svd.singularValues().head(rank).array();
285 solution.asEigen() =
_svd.matrixV().leftCols(rank) *
_tmp.head(rank);
288 virtual void updateCovariance() {
290 covariance.asEigen().setZero();
293 covariance.asEigen() =
294 _svd.matrixV().leftCols(rank) *
295 _svd.singularValues().head(rank).array().inverse().square().matrix().asDiagonal() *
296 _svd.matrixV().leftCols(rank).adjoint();
300 Eigen::JacobiSVD<Eigen::MatrixXd>
_svd;
301 Eigen::VectorXd
_tmp;
307 _impl->threshold = threshold;
308 _impl->state &= ~
Impl::SOLUTION_ARRAY;
309 _impl->state &= ~
Impl::COVARIANCE_ARRAY;
317 return _impl->solution;
322 return _impl->covariance;
329 return ndarray::external(_impl->fisher.data(), ndarray::makeVector(_impl->dimension, _impl->dimension),
330 ndarray::makeVector(_impl->dimension, 1), _impl);
334 if (_impl->whichDiagnostic != factorization) {
335 _impl->state &= ~
Impl::DIAGNOSTIC_ARRAY;
336 _impl->whichDiagnostic = factorization;
339 return _impl->diagnostic;
349 switch (factorization) {
351 _impl = std::make_shared<EigensystemSolver>(dimension);
354 _impl = std::make_shared<CholeskySolver>(dimension);
357 _impl = std::make_shared<SvdSolver>(dimension);
360 _impl->factorization = factorization;
365 Eigen::MatrixXd& LeastSquares::_getDesignMatrix() {
return _impl->design; }
366 Eigen::VectorXd& LeastSquares::_getDataVector() {
return _impl->data; }
368 Eigen::MatrixXd& LeastSquares::_getFisherMatrix() {
return _impl->fisher; }
369 Eigen::VectorXd& LeastSquares::_getRhsVector() {
return _impl->rhs; }
371 void LeastSquares::_factor(
bool haveNormalEquations) {
372 if (haveNormalEquations) {
373 if (_getFisherMatrix().rows() != _impl->dimension) {
374 throw LSST_EXCEPT(pex::exceptions::InvalidParameterError,
375 (boost::format(
"Number of rows of Fisher matrix (%d) does not match"
376 " dimension of LeastSquares solver.") %
377 _getFisherMatrix().rows() % _impl->dimension)
380 if (_getFisherMatrix().cols() != _impl->dimension) {
381 throw LSST_EXCEPT(pex::exceptions::InvalidParameterError,
382 (boost::format(
"Number of columns of Fisher matrix (%d) does not match"
383 " dimension of LeastSquares solver.") %
384 _getFisherMatrix().cols() % _impl->dimension)
387 if (_getRhsVector().size() != _impl->dimension) {
388 throw LSST_EXCEPT(pex::exceptions::InvalidParameterError,
389 (boost::format(
"Number of elements in RHS vector (%d) does not match"
390 " dimension of LeastSquares solver.") %
391 _getRhsVector().size() % _impl->dimension)
396 if (_getDesignMatrix().cols() != _impl->dimension) {
398 pex::exceptions::InvalidParameterError,
399 "Number of columns of design matrix does not match dimension of LeastSquares solver.");
401 if (_getDesignMatrix().rows() != _getDataVector().size()) {
402 throw LSST_EXCEPT(pex::exceptions::InvalidParameterError,
403 (boost::format(
"Number of rows of design matrix (%d) does not match number of "
404 "data points (%d)") %
405 _getDesignMatrix().rows() % _getDataVector().size())
408 if (_getDesignMatrix().cols() > _getDataVector().size()) {
410 pex::exceptions::InvalidParameterError,
411 (boost::format(
"Number of columns of design matrix (%d) must be smaller than number of "
412 "data points (%d)") %
413 _getDesignMatrix().cols() % _getDataVector().size())
virtual void updateRank()=0
double getThreshold() const
Get the threshold used to determine when to truncate Eigenvalues.
void setThreshold(double threshold)
Set the threshold used to determine when to truncate Eigenvalues.
LeastSquares(Factorization factorization, int dimension)
Construct a least-squares object for the given factorization and dimensionality.
virtual void updateDiagnostic()=0
Use a thin singular value decomposition of the design matrix.
Use the normal equations with a Cholesky decomposition.
Eigen::SelfAdjointEigenSolver< Eigen::MatrixXd > _eig
ndarray::Array< double, 1, 1 > diagnostic
Factorization factorization
Eigen::JacobiSVD< Eigen::MatrixXd > _svd
Eigen::LDLT< Eigen::MatrixXd > _ldlt
int getRank() const
Return the rank of the problem (number of nonzero Eigenvalues).
Use the normal equations with a symmetric Eigensystem decomposition.
ndarray::Array< double const, 1, 1 > getDiagnostic(Factorization factorization)
Return a factorization-dependent vector that can be used to characterize the stability of the solutio...
ndarray::Array< double, 1, 1 > solution
ndarray::Array< double const, 2, 2 > getCovariance()
Return the covariance matrix of the least squares problem.
virtual void updateSolution()=0
virtual void updateCovariance()=0
ndarray::Array< double, 2, 2 > covariance
Factorization whichDiagnostic
Factorization
Private implementation; forward-declared publicly so we can inherit from it in .cc.
Factorization getFactorization() const
Retun the type of factorization used by the solver.
ndarray::Array< double const, 1, 1 > getSolution()
Return the vector solution to the least squares problem.
void setRank(Eigen::MatrixBase< D > const &values)
int getDimension() const
Return the number of parameters.
ndarray::Array< double const, 2, 2 > getFisherMatrix()
Return the Fisher matrix (inverse of the covariance) of the parameters.