SOPT
Sparse OPTimisation
conjugate_gradient.cc
Go to the documentation of this file.
1 #include <exception>
3 #include "sopt/types.h"
4 
5 int main(int, char const **) {
6  // Conjugate-gradient solves Ax=b, where A is positive definite.
7  // The input to our conjugate gradient can be a matrix or a function
8  // Lets try both approaches.
9 
10  // Creates the input.
13  t_Vector const b = t_Vector::Random(8);
14  t_Matrix const A = t_Matrix::Random(b.size(), b.size());
15 
16  // Transform to solvable problem A^hA x = A^hb, where A^h is the conjugate transpose
17  t_Matrix const AhA = A.conjugate().transpose() * A;
18  t_Vector const Ahb = A.conjugate().transpose() * b;
19  // The same transform can be realised using a function, where out = A^h * A * input.
20  // This will recompute AhA every time the function is applied by the conjugate gradient. It is not
21  // optmial for this case. But the function interface means A could be an FFT.
22  auto aha_function = [&A](t_Vector &out, t_Vector const &input) {
23  out = A.conjugate().transpose() * A * input;
24  };
25 
26  // Conjugate gradient with unlimited iterations and a convergence criteria of 1e-12
27  sopt::ConjugateGradient const cg(std::numeric_limits<sopt::t_uint>::max(), 1e-12);
28 
29  // Call conjugate gradient using both approaches
30  auto as_matrix = cg(AhA, Ahb);
31  auto as_function = cg(aha_function, Ahb);
32 
33  // Check result
34  if (not(as_matrix.good and as_function.good)) throw std::runtime_error("Expected convergence");
35  if (as_matrix.niters != as_function.niters)
36  throw std::runtime_error("Expected same number of iterations");
37  if (as_matrix.residual > cg.tolerance() or as_function.residual > cg.tolerance())
38  throw std::runtime_error("Expected better convergence");
39  if (not as_matrix.result.isApprox(as_function.result, 1e-6))
40  throw std::runtime_error("Expected same result");
41  if (not(A * as_matrix.result).isApprox(b, 1e-6))
42  throw std::runtime_error("Expected solution to Ax=b");
43 
44  return 0;
45 }
sopt::Vector< Scalar > t_Vector
constexpr Scalar b
sopt::Matrix< Scalar > t_Matrix
Solves $Ax = b$ for $x$, given $A$ and $b$.
t_real tolerance() const
Tolerance criteria.
int main(int, char const **)
Eigen::Matrix< T, Eigen::Dynamic, 1 > Vector
A vector of a given type.
Definition: types.h:24
Eigen::Matrix< T, Eigen::Dynamic, Eigen::Dynamic > Matrix
A matrix of a given type.
Definition: types.h:29