23#include <boost/shared_ptr.hpp>
29 template<
class S,
class V,
class E>
44 parameters_(parameters),
k(0),
steepest(steep) {
53 threshold = std::max(parameters_.epsilon_abs(), parameters_.epsilon() * parameters_.epsilon() * gamma);
56 if (gamma > parameters_.epsilon_abs()) Ad = Ab *
d;
61 void print(
const V& x) {
62 std::cout <<
"iteration = " <<
k << std::endl;
65 std::cout <<
"dotg = " << gamma << std::endl;
72 double takeOptimalStep(V& x) {
74 double alpha = -
dot(
d, g) /
dot(Ad, Ad);
81 bool step(
const S& Ab, V& x) {
83 if ((++
k) >= ((
int)parameters_.maxIterations()))
return true;
86 double alpha = takeOptimalStep(x);
89 if (
k % parameters_.reset() == 0) g = Ab.gradient(x);
91 else Ab.transposeMultiplyAdd(alpha, Ad, g);
94 double new_gamma =
dot(g, g);
96 if (parameters_.verbosity() != ConjugateGradientParameters::SILENT)
97 std::cout <<
"iteration " <<
k <<
": alpha = " << alpha
98 <<
", dotg = " << new_gamma
106 double beta = new_gamma / gamma;
115 Ab.multiplyInPlace(
d, Ad);
124 template<
class S,
class V,
class E>
129 if (parameters.verbosity() != ConjugateGradientParameters::SILENT)
130 std::cout <<
"CG: epsilon = " << parameters.epsilon()
131 <<
", maxIterations = " << parameters.maxIterations()
132 <<
", ||g0||^2 = " << state.gamma
137 if (parameters.verbosity() != ConjugateGradientParameters::SILENT)
138 std::cout <<
"||g0||^2 < threshold, exiting immediately !" << std::endl;
144 while (!state.step(Ab, x)) {}
Iterative methods, implementation.
Implementation of Conjugate Gradient solver for a linear system.
Global functions in a separate testing namespace.
Definition: chartTesting.h:28
void print(const Matrix &A, const string &s, ostream &stream)
print without optional string, must specify cout yourself
Definition: Matrix.cpp:155
V conjugateGradients(const S &Ab, V x, const ConjugateGradientParameters ¶meters, bool steepest)
Method of conjugate gradients (CG) template "System" class S needs gradient(S,v), e=S*v,...
Definition: iterative-inl.h:125
double dot(const V1 &a, const V2 &b)
Dot product.
Definition: Vector.h:194
parameters for the conjugate gradient method
Definition: ConjugateGradientSolver.h:29
Definition: iterative-inl.h:30
bool steepest
flag to indicate we are doing steepest descent
Definition: iterative-inl.h:36
double threshold
gamma (squared L2 norm of g) and convergence threshold
Definition: iterative-inl.h:38
int k
iteration
Definition: iterative-inl.h:35
V d
gradient g and search direction d for CG
Definition: iterative-inl.h:37