Allium  0.1.0
cg.impl.hpp
1 // Copyright 2020 Hannah Rittich
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "cg.hpp"
16 
17 #include <complex>
18 
19 namespace allium {
20 
21  template <typename N>
22  CgSolverBase<N>::~CgSolverBase()
23  {}
24 
25  template <typename N>
26  void CgSolverBase<N>::solve(VectorStorage<N>& solution,
27  const VectorStorage<N>& rhs,
28  InitialGuess initial_guess)
29  {
30  auto residual = allocate_like(rhs);
31  auto new_residual = allocate_like(rhs);
32  auto x = allocate_like(rhs);
33  auto tmp1 = allocate_like(rhs);
34 
35  switch (initial_guess) {
37  set_zero(*x);
38  break;
40  x->assign(solution);
41  break;
42  }
43 
44  //residual = rhs - m_mat * x;
45  matvec(*tmp1, *x);
46  residual->assign(rhs);
47  residual->add_scaled(-1, *tmp1);
48 
49  Real residual_norm_sq = std::real(residual->dot(*residual));
50  auto p = allocate_like(rhs);
51  p->assign(*residual);
52 
53  Real abs_tol = rhs.l2_norm() * m_tol;
54 
55  m_iteration_count = 0;
56  if (sqrt(residual_norm_sq) > abs_tol)
57  {
58  auto Ap = allocate_like(rhs);
59  while (true) {
60  m_iteration_count++;
61 
62  matvec(*Ap, *p);
63 
64  Real alpha = std::real(residual->dot(*residual)) / std::real(p->dot(*Ap));
65 
66  // x = x + alpha * p;
67  x->add_scaled(alpha, *p);
68 
69  // new_residual = residual - alpha * Ap;
70  new_residual->assign(*residual);
71  new_residual->add_scaled(-alpha, *Ap);
72 
73  Real new_residual_norm_sq
74  = std::real(new_residual->dot(*new_residual));
75 
76  if (sqrt(new_residual_norm_sq) <= abs_tol) break;
77 
78  Real beta = new_residual_norm_sq / residual_norm_sq;
79  // p = beta * p + new_residual
80  *p *= beta;
81  *p += *new_residual;
82 
83  // @todo Remove unecessary copying
84  residual->assign(*new_residual);
85  residual_norm_sq = new_residual_norm_sq;
86  }
87  }
88 
89  solution.assign(*x);
90  }
91 
92 }
InitialGuess
Behavior for the initial guess.
Definition: linear_solver.hpp:32
@ NOT_PROVIDED
Initialize with zero.
@ PROVIDED
Use the value from the solution vector.