IterativeSolverBase.h 11.3 KB
Newer Older
Don Gagne's avatar
Don Gagne committed
1 2 3
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
4
// Copyright (C) 2011-2014 Gael Guennebaud <gael.guennebaud@inria.fr>
Don Gagne's avatar
Don Gagne committed
5 6 7 8 9 10 11 12 13 14
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.

#ifndef EIGEN_ITERATIVE_SOLVER_BASE_H
#define EIGEN_ITERATIVE_SOLVER_BASE_H

namespace Eigen { 

15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
namespace internal {

template<typename MatrixType>
struct is_ref_compatible_impl
{
private:
  template <typename T0>
  struct any_conversion
  {
    template <typename T> any_conversion(const volatile T&);
    template <typename T> any_conversion(T&);
  };
  struct yes {int a[1];};
  struct no  {int a[2];};

  template<typename T>
  static yes test(const Ref<const T>&, int);
  template<typename T>
  static no  test(any_conversion<T>, ...);

public:
  static MatrixType ms_from;
  enum { value = sizeof(test<MatrixType>(ms_from, 0))==sizeof(yes) };
};

template<typename MatrixType>
struct is_ref_compatible
{
  enum { value = is_ref_compatible_impl<typename remove_all<MatrixType>::type>::value };
};

template<typename MatrixType, bool MatrixFree = !internal::is_ref_compatible<MatrixType>::value>
class generic_matrix_wrapper;

// We have an explicit matrix at hand, compatible with Ref<>
template<typename MatrixType>
class generic_matrix_wrapper<MatrixType,false>
{
public:
  typedef Ref<const MatrixType> ActualMatrixType;
  template<int UpLo> struct ConstSelfAdjointViewReturnType {
    typedef typename ActualMatrixType::template ConstSelfAdjointViewReturnType<UpLo>::Type Type;
  };

  enum {
    MatrixFree = false
  };

  generic_matrix_wrapper()
    : m_dummy(0,0), m_matrix(m_dummy)
  {}

  template<typename InputType>
  generic_matrix_wrapper(const InputType &mat)
    : m_matrix(mat)
  {}

  const ActualMatrixType& matrix() const
  {
    return m_matrix;
  }

  template<typename MatrixDerived>
  void grab(const EigenBase<MatrixDerived> &mat)
  {
    m_matrix.~Ref<const MatrixType>();
    ::new (&m_matrix) Ref<const MatrixType>(mat.derived());
  }

  void grab(const Ref<const MatrixType> &mat)
  {
    if(&(mat.derived()) != &m_matrix)
    {
      m_matrix.~Ref<const MatrixType>();
      ::new (&m_matrix) Ref<const MatrixType>(mat);
    }
  }

protected:
  MatrixType m_dummy; // used to default initialize the Ref<> object
  ActualMatrixType m_matrix;
};

// MatrixType is not compatible with Ref<> -> matrix-free wrapper
template<typename MatrixType>
class generic_matrix_wrapper<MatrixType,true>
{
public:
  typedef MatrixType ActualMatrixType;
  template<int UpLo> struct ConstSelfAdjointViewReturnType
  {
    typedef ActualMatrixType Type;
  };

  enum {
    MatrixFree = true
  };

  generic_matrix_wrapper()
    : mp_matrix(0)
  {}

  generic_matrix_wrapper(const MatrixType &mat)
    : mp_matrix(&mat)
  {}

  const ActualMatrixType& matrix() const
  {
    return *mp_matrix;
  }

  void grab(const MatrixType &mat)
  {
    mp_matrix = &mat;
  }

protected:
  const ActualMatrixType *mp_matrix;
};

}

Don Gagne's avatar
Don Gagne committed
137 138 139 140 141 142
/** \ingroup IterativeLinearSolvers_Module
  * \brief Base class for linear iterative solvers
  *
  * \sa class SimplicialCholesky, DiagonalPreconditioner, IdentityPreconditioner
  */
template< typename Derived>
143
class IterativeSolverBase : public SparseSolverBase<Derived>
Don Gagne's avatar
Don Gagne committed
144
{
145 146 147 148
protected:
  typedef SparseSolverBase<Derived> Base;
  using Base::m_isInitialized;
  
Don Gagne's avatar
Don Gagne committed
149 150 151 152
public:
  typedef typename internal::traits<Derived>::MatrixType MatrixType;
  typedef typename internal::traits<Derived>::Preconditioner Preconditioner;
  typedef typename MatrixType::Scalar Scalar;
153
  typedef typename MatrixType::StorageIndex StorageIndex;
Don Gagne's avatar
Don Gagne committed
154 155
  typedef typename MatrixType::RealScalar RealScalar;

156 157 158 159 160
  enum {
    ColsAtCompileTime = MatrixType::ColsAtCompileTime,
    MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime
  };

Don Gagne's avatar
Don Gagne committed
161 162
public:

163
  using Base::derived;
Don Gagne's avatar
Don Gagne committed
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180

  /** Default constructor. */
  IterativeSolverBase()
  {
    init();
  }

  /** Initialize the solver with matrix \a A for further \c Ax=b solving.
    * 
    * This constructor is a shortcut for the default constructor followed
    * by a call to compute().
    * 
    * \warning this class stores a reference to the matrix A as well as some
    * precomputed values that depend on it. Therefore, if \a A is changed
    * this class becomes invalid. Call compute() to update it with the new
    * matrix A, or modify a copy of A.
    */
181 182 183
  template<typename MatrixDerived>
  explicit IterativeSolverBase(const EigenBase<MatrixDerived>& A)
    : m_matrixWrapper(A.derived())
Don Gagne's avatar
Don Gagne committed
184 185
  {
    init();
186
    compute(matrix());
Don Gagne's avatar
Don Gagne committed
187 188 189 190
  }

  ~IterativeSolverBase() {}
  
191
  /** Initializes the iterative solver for the sparsity pattern of the matrix \a A for further solving \c Ax=b problems.
Don Gagne's avatar
Don Gagne committed
192
    *
193 194
    * Currently, this function mostly calls analyzePattern on the preconditioner. In the future
    * we might, for instance, implement column reordering for faster matrix vector products.
Don Gagne's avatar
Don Gagne committed
195
    */
196 197
  template<typename MatrixDerived>
  Derived& analyzePattern(const EigenBase<MatrixDerived>& A)
Don Gagne's avatar
Don Gagne committed
198
  {
199 200
    grab(A.derived());
    m_preconditioner.analyzePattern(matrix());
Don Gagne's avatar
Don Gagne committed
201 202
    m_isInitialized = true;
    m_analysisIsOk = true;
203
    m_info = m_preconditioner.info();
Don Gagne's avatar
Don Gagne committed
204 205 206 207 208
    return derived();
  }
  
  /** Initializes the iterative solver with the numerical values of the matrix \a A for further solving \c Ax=b problems.
    *
209
    * Currently, this function mostly calls factorize on the preconditioner.
Don Gagne's avatar
Don Gagne committed
210 211 212 213 214 215
    *
    * \warning this class stores a reference to the matrix A as well as some
    * precomputed values that depend on it. Therefore, if \a A is changed
    * this class becomes invalid. Call compute() to update it with the new
    * matrix A, or modify a copy of A.
    */
216 217
  template<typename MatrixDerived>
  Derived& factorize(const EigenBase<MatrixDerived>& A)
Don Gagne's avatar
Don Gagne committed
218 219
  {
    eigen_assert(m_analysisIsOk && "You must first call analyzePattern()"); 
220 221
    grab(A.derived());
    m_preconditioner.factorize(matrix());
Don Gagne's avatar
Don Gagne committed
222
    m_factorizationIsOk = true;
223
    m_info = m_preconditioner.info();
Don Gagne's avatar
Don Gagne committed
224 225 226 227 228
    return derived();
  }

  /** Initializes the iterative solver with the matrix \a A for further solving \c Ax=b problems.
    *
229 230
    * Currently, this function mostly initializes/computes the preconditioner. In the future
    * we might, for instance, implement column reordering for faster matrix vector products.
Don Gagne's avatar
Don Gagne committed
231 232 233 234 235 236
    *
    * \warning this class stores a reference to the matrix A as well as some
    * precomputed values that depend on it. Therefore, if \a A is changed
    * this class becomes invalid. Call compute() to update it with the new
    * matrix A, or modify a copy of A.
    */
237 238
  template<typename MatrixDerived>
  Derived& compute(const EigenBase<MatrixDerived>& A)
Don Gagne's avatar
Don Gagne committed
239
  {
240 241
    grab(A.derived());
    m_preconditioner.compute(matrix());
Don Gagne's avatar
Don Gagne committed
242 243 244
    m_isInitialized = true;
    m_analysisIsOk = true;
    m_factorizationIsOk = true;
245
    m_info = m_preconditioner.info();
Don Gagne's avatar
Don Gagne committed
246 247 248 249
    return derived();
  }

  /** \internal */
250 251
  Index rows() const { return matrix().rows(); }

Don Gagne's avatar
Don Gagne committed
252
  /** \internal */
253
  Index cols() const { return matrix().cols(); }
Don Gagne's avatar
Don Gagne committed
254

255 256 257
  /** \returns the tolerance threshold used by the stopping criteria.
    * \sa setTolerance()
    */
Don Gagne's avatar
Don Gagne committed
258 259
  RealScalar tolerance() const { return m_tolerance; }
  
260 261 262 263 264
  /** Sets the tolerance threshold used by the stopping criteria.
    *
    * This value is used as an upper bound to the relative residual error: |Ax-b|/|b|.
    * The default value is the machine precision given by NumTraits<Scalar>::epsilon()
    */
Don Gagne's avatar
Don Gagne committed
265 266 267 268 269 270 271 272 273 274 275 276
  Derived& setTolerance(const RealScalar& tolerance)
  {
    m_tolerance = tolerance;
    return derived();
  }

  /** \returns a read-write reference to the preconditioner for custom configuration. */
  Preconditioner& preconditioner() { return m_preconditioner; }
  
  /** \returns a read-only reference to the preconditioner. */
  const Preconditioner& preconditioner() const { return m_preconditioner; }

277 278 279 280 281
  /** \returns the max number of iterations.
    * It is either the value setted by setMaxIterations or, by default,
    * twice the number of columns of the matrix.
    */
  Index maxIterations() const
Don Gagne's avatar
Don Gagne committed
282
  {
283
    return (m_maxIterations<0) ? 2*matrix().cols() : m_maxIterations;
Don Gagne's avatar
Don Gagne committed
284 285
  }
  
286 287 288 289
  /** Sets the max number of iterations.
    * Default is twice the number of columns of the matrix.
    */
  Derived& setMaxIterations(Index maxIters)
Don Gagne's avatar
Don Gagne committed
290 291 292 293 294 295
  {
    m_maxIterations = maxIters;
    return derived();
  }

  /** \returns the number of iterations performed during the last solve */
296
  Index iterations() const
Don Gagne's avatar
Don Gagne committed
297 298 299 300 301
  {
    eigen_assert(m_isInitialized && "ConjugateGradient is not initialized.");
    return m_iterations;
  }

302 303 304
  /** \returns the tolerance error reached during the last solve.
    * It is a close approximation of the true relative residual error |Ax-b|/|b|.
    */
Don Gagne's avatar
Don Gagne committed
305 306 307 308 309 310
  RealScalar error() const
  {
    eigen_assert(m_isInitialized && "ConjugateGradient is not initialized.");
    return m_error;
  }

311 312
  /** \returns the solution x of \f$ A x = b \f$ using the current decomposition of A
    * and \a x0 as an initial solution.
Don Gagne's avatar
Don Gagne committed
313
    *
314
    * \sa solve(), compute()
Don Gagne's avatar
Don Gagne committed
315
    */
316 317 318
  template<typename Rhs,typename Guess>
  inline const SolveWithGuess<Derived, Rhs, Guess>
  solveWithGuess(const MatrixBase<Rhs>& b, const Guess& x0) const
Don Gagne's avatar
Don Gagne committed
319
  {
320 321 322
    eigen_assert(m_isInitialized && "Solver is not initialized.");
    eigen_assert(derived().rows()==b.rows() && "solve(): invalid number of rows of the right hand side matrix b");
    return SolveWithGuess<Derived, Rhs, Guess>(derived(), b.derived(), x0);
Don Gagne's avatar
Don Gagne committed
323 324 325 326 327 328 329 330 331 332
  }

  /** \returns Success if the iterations converged, and NoConvergence otherwise. */
  ComputationInfo info() const
  {
    eigen_assert(m_isInitialized && "IterativeSolverBase is not initialized.");
    return m_info;
  }
  
  /** \internal */
333 334
  template<typename Rhs, typename DestDerived>
  void _solve_impl(const Rhs& b, SparseMatrixBase<DestDerived> &aDest) const
Don Gagne's avatar
Don Gagne committed
335 336 337
  {
    eigen_assert(rows()==b.rows());
    
338 339 340 341
    Index rhsCols = b.cols();
    Index size = b.rows();
    DestDerived& dest(aDest.derived());
    typedef typename DestDerived::Scalar DestScalar;
Don Gagne's avatar
Don Gagne committed
342
    Eigen::Matrix<DestScalar,Dynamic,1> tb(size);
343 344 345 346 347
    Eigen::Matrix<DestScalar,Dynamic,1> tx(cols());
    // We do not directly fill dest because sparse expressions have to be free of aliasing issue.
    // For non square least-square problems, b and dest might not have the same size whereas they might alias each-other.
    typename DestDerived::PlainObject tmp(cols(),rhsCols);
    for(Index k=0; k<rhsCols; ++k)
Don Gagne's avatar
Don Gagne committed
348 349 350
    {
      tb = b.col(k);
      tx = derived().solve(tb);
351
      tmp.col(k) = tx.sparseView(0);
Don Gagne's avatar
Don Gagne committed
352
    }
353
    dest.swap(tmp);
Don Gagne's avatar
Don Gagne committed
354 355 356 357 358 359 360 361 362 363 364
  }

protected:
  void init()
  {
    m_isInitialized = false;
    m_analysisIsOk = false;
    m_factorizationIsOk = false;
    m_maxIterations = -1;
    m_tolerance = NumTraits<Scalar>::epsilon();
  }
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380

  typedef internal::generic_matrix_wrapper<MatrixType> MatrixWrapper;
  typedef typename MatrixWrapper::ActualMatrixType ActualMatrixType;

  const ActualMatrixType& matrix() const
  {
    return m_matrixWrapper.matrix();
  }
  
  template<typename InputType>
  void grab(const InputType &A)
  {
    m_matrixWrapper.grab(A);
  }
  
  MatrixWrapper m_matrixWrapper;
Don Gagne's avatar
Don Gagne committed
381 382
  Preconditioner m_preconditioner;

383
  Index m_maxIterations;
Don Gagne's avatar
Don Gagne committed
384 385 386
  RealScalar m_tolerance;
  
  mutable RealScalar m_error;
387
  mutable Index m_iterations;
Don Gagne's avatar
Don Gagne committed
388
  mutable ComputationInfo m_info;
389
  mutable bool m_analysisIsOk, m_factorizationIsOk;
Don Gagne's avatar
Don Gagne committed
390 391 392 393 394
};

} // end namespace Eigen

#endif // EIGEN_ITERATIVE_SOLVER_BASE_H