lsst.afw  15.0-33-g5c41f601f+4
LeastSquares.cc
Go to the documentation of this file.
1 // -*- LSST-C++ -*-
2 
3 /*
4  * LSST Data Management System
5  * Copyright 2008, 2009, 2010, 2011 LSST Corporation.
6  *
7  * This product includes software developed by the
8  * LSST Project (http://www.lsst.org/).
9  *
10  * This program is free software: you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation, either version 3 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the LSST License Statement and
21  * the GNU General Public License along with this program. If not,
22  * see <http://www.lsstcorp.org/LegalNotices/>.
23  */
24 
25 #include "Eigen/Eigenvalues"
26 #include "Eigen/SVD"
27 #include "Eigen/Cholesky"
28 #include "boost/format.hpp"
29 #include <memory>
30 
32 #include "lsst/pex/exceptions.h"
33 #include "lsst/log/Log.h"
34 
35 namespace {
36 LOG_LOGGER _log = LOG_GET("afw.math.LeastSquares");
37 }
38 
39 namespace lsst {
40 namespace afw {
41 namespace math {
42 
44 public:
45  enum StateFlags {
48  RHS_VECTOR = 0x004,
49  SOLUTION_ARRAY = 0x008,
53  };
54 
55  int state;
56  int dimension;
57  int rank;
60  double threshold;
61 
62  Eigen::MatrixXd design;
63  Eigen::VectorXd data;
64  Eigen::MatrixXd fisher;
65  Eigen::VectorXd rhs;
66 
67  ndarray::Array<double, 1, 1> solution;
68  ndarray::Array<double, 2, 2> covariance;
69  ndarray::Array<double, 1, 1> diagnostic;
70 
71  template <typename D>
72  void setRank(Eigen::MatrixBase<D> const& values) {
73  double cond = threshold * values[0];
74  if (cond <= 0.0) {
75  rank = 0;
76  } else {
77  for (rank = dimension; (rank > 1) && (values[rank - 1] < cond); --rank)
78  ;
79  }
80  }
81 
82  void ensure(int desired) {
83  if (state & FULL_FISHER_MATRIX) state |= LOWER_FISHER_MATRIX;
84  if (desired & FULL_FISHER_MATRIX) desired |= LOWER_FISHER_MATRIX;
85  int toAdd = ~state & desired;
86  if (toAdd & LOWER_FISHER_MATRIX) {
87  assert(state & DESIGN_AND_DATA);
88  fisher = Eigen::MatrixXd::Zero(design.cols(), design.cols());
89  fisher.selfadjointView<Eigen::Lower>().rankUpdate(design.adjoint());
90  }
91  if (toAdd & FULL_FISHER_MATRIX) {
92  fisher.triangularView<Eigen::StrictlyUpper>() = fisher.adjoint();
93  }
94  if (toAdd & RHS_VECTOR) {
95  assert(state & DESIGN_AND_DATA);
96  rhs = design.adjoint() * data;
97  }
98  if (toAdd & SOLUTION_ARRAY) {
99  if (solution.isEmpty()) solution = ndarray::allocate(dimension);
100  updateSolution();
101  }
102  if (toAdd & COVARIANCE_ARRAY) {
103  if (covariance.isEmpty()) covariance = ndarray::allocate(dimension, dimension);
105  }
106  if (toAdd & DIAGNOSTIC_ARRAY) {
107  if (diagnostic.isEmpty()) diagnostic = ndarray::allocate(dimension);
109  }
110  state |= toAdd;
111  }
112 
113  virtual void factor() = 0;
114 
115  virtual void updateRank() = 0;
116 
117  virtual void updateSolution() = 0;
118  virtual void updateCovariance() = 0;
119 
120  virtual void updateDiagnostic() = 0;
121 
122  Impl(int dimension_, double threshold_ = std::numeric_limits<double>::epsilon())
123  : state(0), dimension(dimension_), rank(dimension_), threshold(threshold_) {}
124 
125  virtual ~Impl() {}
126 };
127 
128 namespace {
129 
130 class EigensystemSolver : public LeastSquares::Impl {
131 public:
132  explicit EigensystemSolver(int dimension) : Impl(dimension), _eig(dimension), _svd(), _tmp(dimension) {}
133 
134  virtual void factor() {
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);
140  } else {
141  // Note that the fallback is using SVD of the Fisher to compute the Eigensystem, because those
142  // are the same for a symmetric matrix; this is very different from doing a direct SVD of
143  // the design matrix.
145  _svd.compute(fisher, Eigen::ComputeFullU); // Matrix is symmetric, so V == U == eigenvectors
146  setRank(_svd.singularValues());
147  LOGL_DEBUG(_log,
148  "SelfAdjointEigenSolver failed; falling back to equivalent SVD: dimension=%d, rank=%d",
149  dimension, rank);
150  }
151  }
152 
153  virtual void updateRank() {
154  if (_eig.info() == Eigen::Success) {
155  setRank(_eig.eigenvalues().reverse());
156  } else {
157  setRank(_svd.singularValues());
158  }
159  }
160 
161  virtual void updateDiagnostic() {
162  if (whichDiagnostic == LeastSquares::NORMAL_CHOLESKY) {
163  throw LSST_EXCEPT(
165  "Cannot compute NORMAL_CHOLESKY diagnostic from NORMAL_EIGENSYSTEM factorization.");
166  }
167  if (_eig.info() == Eigen::Success) {
168  diagnostic.asEigen() = _eig.eigenvalues().reverse();
169  } else {
170  diagnostic.asEigen() = _svd.singularValues();
171  }
172  if (whichDiagnostic == LeastSquares::DIRECT_SVD) {
173  diagnostic.asEigen<Eigen::ArrayXpr>() = diagnostic.asEigen<Eigen::ArrayXpr>().sqrt();
174  }
175  }
176 
177  virtual void updateSolution() {
178  if (rank == 0) {
179  solution.asEigen().setZero();
180  return;
181  }
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);
186  } else {
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);
190  }
191  }
192 
193  virtual void updateCovariance() {
194  if (rank == 0) {
195  covariance.asEigen().setZero();
196  return;
197  }
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();
202  } else {
203  covariance.asEigen() = _svd.matrixU().leftCols(rank) *
204  _svd.singularValues().head(rank).array().inverse().matrix().asDiagonal() *
205  _svd.matrixU().leftCols(rank).adjoint();
206  }
207  }
208 
209 private:
210  Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> _eig;
211  Eigen::JacobiSVD<Eigen::MatrixXd> _svd; // only used if Eigendecomposition fails, should be very rare
212  Eigen::VectorXd _tmp;
213 };
214 
215 class CholeskySolver : public LeastSquares::Impl {
216 public:
217  explicit CholeskySolver(int dimension) : Impl(dimension, 0.0), _ldlt(dimension) {}
218 
219  virtual void factor() {
221  _ldlt.compute(fisher);
222  }
223 
224  virtual void updateRank() {}
225 
226  virtual void updateDiagnostic() {
227  if (whichDiagnostic != LeastSquares::NORMAL_CHOLESKY) {
228  throw LSST_EXCEPT(
230  "Can only compute NORMAL_CHOLESKY diagnostic from NORMAL_CHOLESKY factorization.");
231  }
232  diagnostic.asEigen() = _ldlt.vectorD();
233  }
234 
235  virtual void updateSolution() { solution.asEigen() = _ldlt.solve(rhs); }
236 
237  virtual void updateCovariance() {
238  auto cov = covariance.asEigen();
239  cov.setIdentity();
240  cov = _ldlt.solve(cov);
241  }
242 
243 private:
244  Eigen::LDLT<Eigen::MatrixXd> _ldlt;
245 };
246 
247 class SvdSolver : public LeastSquares::Impl {
248 public:
249  explicit SvdSolver(int dimension) : Impl(dimension), _svd(), _tmp(dimension) {}
250 
251  virtual void factor() {
252  if (!(state & DESIGN_AND_DATA)) {
254  "Cannot initialize DIRECT_SVD solver with normal equations.");
255  }
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);
259  }
260 
261  virtual void updateRank() { setRank(_svd.singularValues()); }
262 
263  virtual void updateDiagnostic() {
264  switch (whichDiagnostic) {
266  diagnostic.asEigen<Eigen::ArrayXpr>() = _svd.singularValues().array().square();
267  break;
269  throw LSST_EXCEPT(
271  "Can only compute NORMAL_CHOLESKY diagnostic from DIRECT_SVD factorization.");
273  diagnostic.asEigen() = _svd.singularValues();
274  break;
275  }
276  }
277 
278  virtual void updateSolution() {
279  if (rank == 0) {
280  solution.asEigen().setZero();
281  return;
282  }
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);
286  }
287 
288  virtual void updateCovariance() {
289  if (rank == 0) {
290  covariance.asEigen().setZero();
291  return;
292  }
293  covariance.asEigen() =
294  _svd.matrixV().leftCols(rank) *
295  _svd.singularValues().head(rank).array().inverse().square().matrix().asDiagonal() *
296  _svd.matrixV().leftCols(rank).adjoint();
297  }
298 
299 private:
300  Eigen::JacobiSVD<Eigen::MatrixXd> _svd;
301  Eigen::VectorXd _tmp;
302 };
303 
304 } // namespace
305 
306 void LeastSquares::setThreshold(double threshold) {
307  _impl->threshold = threshold;
308  _impl->state &= ~Impl::SOLUTION_ARRAY;
309  _impl->state &= ~Impl::COVARIANCE_ARRAY;
310  _impl->updateRank();
311 }
312 
313 double LeastSquares::getThreshold() const { return _impl->threshold; }
314 
315 ndarray::Array<double const, 1, 1> LeastSquares::getSolution() {
316  _impl->ensure(Impl::SOLUTION_ARRAY);
317  return _impl->solution;
318 }
319 
320 ndarray::Array<double const, 2, 2> LeastSquares::getCovariance() {
321  _impl->ensure(Impl::COVARIANCE_ARRAY);
322  return _impl->covariance;
323 }
324 
325 ndarray::Array<double const, 2, 2> LeastSquares::getFisherMatrix() {
326  _impl->ensure(Impl::FULL_FISHER_MATRIX);
327  // Wrap the Eigen::MatrixXd in an ndarray::Array, using _impl as the reference-counted owner.
328  // Doesn't matter if we swap strides, because it's symmetric.
329  return ndarray::external(_impl->fisher.data(), ndarray::makeVector(_impl->dimension, _impl->dimension),
330  ndarray::makeVector(_impl->dimension, 1), _impl);
331 }
332 
333 ndarray::Array<double const, 1, 1> LeastSquares::getDiagnostic(Factorization factorization) {
334  if (_impl->whichDiagnostic != factorization) {
335  _impl->state &= ~Impl::DIAGNOSTIC_ARRAY;
336  _impl->whichDiagnostic = factorization;
337  }
338  _impl->ensure(Impl::DIAGNOSTIC_ARRAY);
339  return _impl->diagnostic;
340 }
341 
342 int LeastSquares::getDimension() const { return _impl->dimension; }
343 
344 int LeastSquares::getRank() const { return _impl->rank; }
345 
346 LeastSquares::Factorization LeastSquares::getFactorization() const { return _impl->factorization; }
347 
348 LeastSquares::LeastSquares(Factorization factorization, int dimension) {
349  switch (factorization) {
350  case NORMAL_EIGENSYSTEM:
351  _impl = std::make_shared<EigensystemSolver>(dimension);
352  break;
353  case NORMAL_CHOLESKY:
354  _impl = std::make_shared<CholeskySolver>(dimension);
355  break;
356  case DIRECT_SVD:
357  _impl = std::make_shared<SvdSolver>(dimension);
358  break;
359  }
360  _impl->factorization = factorization;
361 }
362 
363 LeastSquares::LeastSquares(LeastSquares const&) = default;
367 
368 LeastSquares::~LeastSquares() = default;
369 
370 Eigen::MatrixXd& LeastSquares::_getDesignMatrix() { return _impl->design; }
371 Eigen::VectorXd& LeastSquares::_getDataVector() { return _impl->data; }
372 
373 Eigen::MatrixXd& LeastSquares::_getFisherMatrix() { return _impl->fisher; }
374 Eigen::VectorXd& LeastSquares::_getRhsVector() { return _impl->rhs; }
375 
376 void LeastSquares::_factor(bool haveNormalEquations) {
377  if (haveNormalEquations) {
378  if (_getFisherMatrix().rows() != _impl->dimension) {
380  (boost::format("Number of rows of Fisher matrix (%d) does not match"
381  " dimension of LeastSquares solver.") %
382  _getFisherMatrix().rows() % _impl->dimension)
383  .str());
384  }
385  if (_getFisherMatrix().cols() != _impl->dimension) {
387  (boost::format("Number of columns of Fisher matrix (%d) does not match"
388  " dimension of LeastSquares solver.") %
389  _getFisherMatrix().cols() % _impl->dimension)
390  .str());
391  }
392  if (_getRhsVector().size() != _impl->dimension) {
394  (boost::format("Number of elements in RHS vector (%d) does not match"
395  " dimension of LeastSquares solver.") %
396  _getRhsVector().size() % _impl->dimension)
397  .str());
398  }
400  } else {
401  if (_getDesignMatrix().cols() != _impl->dimension) {
402  throw LSST_EXCEPT(
404  "Number of columns of design matrix does not match dimension of LeastSquares solver.");
405  }
406  if (_getDesignMatrix().rows() != _getDataVector().size()) {
408  (boost::format("Number of rows of design matrix (%d) does not match number of "
409  "data points (%d)") %
410  _getDesignMatrix().rows() % _getDataVector().size())
411  .str());
412  }
413  if (_getDesignMatrix().cols() > _getDataVector().size()) {
414  throw LSST_EXCEPT(
416  (boost::format("Number of columns of design matrix (%d) must be smaller than number of "
417  "data points (%d)") %
418  _getDesignMatrix().cols() % _getDataVector().size())
419  .str());
420  }
421  _impl->state = Impl::DESIGN_AND_DATA;
422  }
423  _impl->factor();
424 }
425 } // namespace math
426 } // namespace afw
427 } // namespace lsst
Impl(int dimension_, double threshold_=std::numeric_limits< double >::epsilon())
void setThreshold(double threshold)
Set the threshold used to determine when to truncate Eigenvalues.
int getRank() const
Return the rank of the problem (number of nonzero Eigenvalues).
Solver for linear least-squares problems.
Definition: LeastSquares.h:67
LeastSquares(Factorization factorization, int dimension)
Construct a least-squares object for the given factorization and dimensionality.
Use a thin singular value decomposition of the design matrix.
Definition: LeastSquares.h:88
#define LOGL_DEBUG(logger, message...)
Use the normal equations with a Cholesky decomposition.
Definition: LeastSquares.h:80
ndarray::Array< double, 1, 1 > diagnostic
Definition: LeastSquares.cc:69
Use the normal equations with a symmetric Eigensystem decomposition.
Definition: LeastSquares.h:72
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...
A base class for image defects.
int getDimension() const
Return the number of parameters.
ndarray::Array< double, 1, 1 > solution
Definition: LeastSquares.cc:67
double getThreshold() const
Get the threshold used to determine when to truncate Eigenvalues.
Factorization getFactorization() const
Retun the type of factorization used by the solver.
ndarray::Array< double const, 2, 2 > getCovariance()
Return the covariance matrix of the least squares problem.
ndarray::Array< double, 2, 2 > covariance
Definition: LeastSquares.cc:68
#define LSST_EXCEPT(type,...)
Factorization
Private implementation; forward-declared publicly so we can inherit from it in .cc.
Definition: LeastSquares.h:71
ndarray::Array< double const, 1, 1 > getSolution()
Return the vector solution to the least squares problem.
void setRank(Eigen::MatrixBase< D > const &values)
Definition: LeastSquares.cc:72
#define LOG_GET(logger)
ndarray::Array< double const, 2, 2 > getFisherMatrix()
Return the Fisher matrix (inverse of the covariance) of the parameters.
LeastSquares & operator=(LeastSquares const &)