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)) {}
parameters for the conjugate gradient method
Definition: ConjugateGradientSolver.h:29
double dot(const V1 &a, const V2 &b)
Dot product.
Definition: Vector.h:162
void print(const Matrix &A, const string &s, ostream &stream)
print without optional string, must specify cout yourself
Definition: Matrix.cpp:141
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
Definition: iterative-inl.h:30
int k
iteration
Definition: iterative-inl.h:35
void axpy(double alpha, const V1 &x, V2 &y)
BLAS Level 1 axpy: y <- alpha*x + y.
Definition: Vector.h:185
Implementation of Conjugate Gradient solver for a linear system.
Iterative methods, implementation.
V d
gradient g and search direction d for CG
Definition: iterative-inl.h:37
Global functions in a separate testing namespace.
Definition: chartTesting.h:28
double threshold
gamma (squared L2 norm of g) and convergence threshold
Definition: iterative-inl.h:38
bool steepest
flag to indicate we are doing steepest descent
Definition: iterative-inl.h:36